text
stringlengths
184
4.48M
<!doctype html> <html class="no-js" lang="en"> <head> <style> body { margin: 0; padding: 0; background-color: white; } body .controls { display: none; } @media (min-width: 600px) { body.preview { background-color: #ccc; } body.preview .controls { display: block; margin: 30px; } body.preview .controls input[type=text] { width: 300px; margin: 0; } body.preview .controls .button { display: inline-block; padding: 10px; background-color: #eee; border-radius: 5px; box-shadow: 2px 3px 1px rgba(40, 40, 40, 0.5); text-decoration: none; color: black; margin-left: 10px; } body.preview .controls .button:hover { background-color: #ddd; } body.preview .paper { background-color: white; width: 440px; padding-top: 25px; padding-bottom: 50px; margin: 30px auto; box-shadow: 10px 10px 5px rgba(40, 40, 40, 0.5); } body.preview .content { -webkit-font-smoothing: antialiased; } } body .content { -webkit-font-smoothing: none; width: 384px; overflow: hidden; margin: 0 auto; background-color: white; } </style> <script type="text/javascript" charset="utf-8"> const Printer = { backendURL: "http://printer.exciting.io", printerURL: function() { return document.getElementById('printerURL').value; }, isRelative: function(path) { return !path.match(/^((https?|file):\/\/)|data:/); }, makeAbsolute: function(path) { return (this.isRelative(path) ? (window.location.protocol + "//" + window.location.host) : "") + path; }, updateSrc: function(tagName) { Array.prototype.forEach.call(document.getElementsByTagName(tagName), function(element) { if (element.src) { element.src = this.makeAbsolute(element.src) } }.bind(this)); }, updateHref: function() { Array.prototype.forEach.call(document.querySelectorAll('link[rel=stylesheet]'), function(stylesheet) { if (stylesheet.href) { stylesheet.href = this.makeAbsolute(stylesheet.href) } }.bind(this)); }, serializePage: function(callback) { this.updateSrc('img'); this.updateSrc('script'); this.updateHref(); }, withSerializedPage: function(callback) { this.serializePage(); const page_content = document.documentElement.innerHTML; callback(page_content); }, previewPage: function() { this.withSerializedPage((page_content) => { let width = document.querySelector('.content').offsetWidth; console.log("posting width", width); let formData = new FormData(); formData.append('content', page_content); formData.append('width', width); fetch(Printer.backendURL + "/preview", { method: 'POST', body: formData }) .then(response => response.json()) .then(json => window.location = json.location); }); return false; }, printPage: function(callback) { this.withSerializedPage((page_content) => { let formData = new FormData(); formData.append('content', page_content); fetch(Printer.printerURL(), { method: 'POST', body: formData }) .then(response => response.json()) .then(data => callback(data)) }); return false; } } document.addEventListener('DOMContentLoaded', function() { const printerURLInput = document.getElementById('printerURL'); printerURLInput.addEventListener('change', function() { document.cookie = "printerURL=" + document.getElementById('printerURL').value; }); printerURLInput.value = document.cookie.replace(/(?:(?:^|.*;\s*)printerURL\s*\=\s*([^;]*).*$)|^.*$/, "$1"); document.getElementById('previewPage').addEventListener('click', Printer.previewPage.bind(Printer)); document.getElementById('serialize').addEventListener('click', Printer.serializePage.bind(Printer)); document.getElementById('printPage').addEventListener('click', function() { Printer.printPage(function(result) { if (result.response == "ok") { alert("Page successfully sent for printing"); } else { alert("There was a problem sending this content"); console.log("Error response", result); } }); }); }) </script> </head> <body class="preview"> <div class="controls"> <p>Printer URL: <input type="text" id="printerURL"/> <a id="serialize" class="button" href="#">Serialize</a> <a id="previewPage" class="button" href="#">Preview</a> <a id="printPage" class="button" href="#">Print</a> </p> </div> <div class="paper"> <div class="content"> <h1>OK, folks</h1> <img src="https://images.unsplash.com/photo-1606115915090-be18fea23ec7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=465&q=80"> </div> </div> </body> </html>
/* * Copyright (C)2005-2017 Haxe Foundation * * 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. */ /** A linked-list of elements. The list is composed of element container objects that are chained together. It is optimized so that adding or removing an element does not imply copying the whole list content every time. @see https://haxe.org/manual/std-List.html **/ class List<T> { private var h : ListNode<T>; private var q : ListNode<T>; /** The length of `this` List. **/ public var length(default,null) : Int; /** Creates a new empty list. **/ public function new() { length = 0; } /** Adds element `item` at the end of `this` List. `this.length` increases by 1. **/ public function add( item : T ) { var x = ListNode.create(item, null); if( h == null ) h = x; else q.next = x; q = x; length++; } /** Adds element `item` at the beginning of `this` List. `this.length` increases by 1. **/ public function push( item : T ) { var x = ListNode.create(item, h); h = x; if( q == null ) q = x; length++; } /** Returns the first element of `this` List, or null if no elements exist. This function does not modify `this` List. **/ public function first() : Null<T> { return if( h == null ) null else h.item; } /** Returns the last element of `this` List, or null if no elements exist. This function does not modify `this` List. **/ public function last() : Null<T> { return if( q == null ) null else q.item; } /** Returns the first element of `this` List, or null if no elements exist. The element is removed from `this` List. **/ public function pop() : Null<T> { if( h == null ) return null; var x = h.item; h = h.next; if( h == null ) q = null; length--; return x; } /** Tells if `this` List is empty. **/ public function isEmpty() : Bool { return (h == null); } /** Empties `this` List. This function does not traverse the elements, but simply sets the internal references to null and `this.length` to 0. **/ public function clear() : Void { h = null; q = null; length = 0; } /** Removes the first occurrence of `v` in `this` List. If `v` is found by checking standard equality, it is removed from `this` List and the function returns true. Otherwise, false is returned. **/ public function remove( v : T ) : Bool { var prev:ListNode<T> = null; var l = h; while( l != null ) { if( l.item == v ) { if( prev == null ) h = l.next; else prev.next = l.next; if( q == l ) q = prev; length--; return true; } prev = l; l = l.next; } return false; } /** Returns an iterator on the elements of the list. **/ public inline function iterator() : ListIterator<T> { return new ListIterator<T>(h); } /** Returns a string representation of `this` List. The result is enclosed in { } with the individual elements being separated by a comma. **/ public function toString() { var s = new StringBuf(); var first = true; var l = h; s.add("{"); while( l != null ) { if( first ) first = false; else s.add(", "); s.add(Std.string(l.item)); l = l.next; } s.add("}"); return s.toString(); } /** Returns a string representation of `this` List, with `sep` separating each element. **/ public function join(sep : String) { var s = new StringBuf(); var first = true; var l = h; while( l != null ) { if( first ) first = false; else s.add(sep); s.add(l.item); l = l.next; } return s.toString(); } /** Returns a list filtered with `f`. The returned list will contain all elements for which `f(x) == true`. **/ public function filter( f : T -> Bool ) { var l2 = new List(); var l = h; while( l != null ) { var v = l.item; l = l.next; if( f(v) ) l2.add(v); } return l2; } /** Returns a new list where all elements have been converted by the function `f`. **/ public function map<X>(f : T -> X) : List<X> { var b = new List(); var l = h; while( l != null ) { var v = l.item; l = l.next; b.add(f(v)); } return b; } } #if neko private extern class ListNode<T> extends neko.NativeArray<Dynamic> { var item(get,set):T; var next(get,set):ListNode<T>; private inline function get_item():T return this[0]; private inline function set_item(v:T):T return this[0] = v; private inline function get_next():ListNode<T> return this[1]; private inline function set_next(v:ListNode<T>):ListNode<T> return this[1] = v; inline static function create<T>(item:T, next:ListNode<T>):ListNode<T> { return untyped __dollar__array(item, next); } } #else private class ListNode<T> { public var item:T; public var next:ListNode<T>; public function new(item:T, next:ListNode<T>) { this.item = item; this.next = next; } @:extern public inline static function create<T>(item:T, next:ListNode<T>):ListNode<T> { return new ListNode(item, next); } } #end private class ListIterator<T> { var head:ListNode<T>; public inline function new(head:ListNode<T>) { this.head = head; } public inline function hasNext():Bool { return head != null; } public inline function next():T { var val = head.item; head = head.next; return val; } }
# Mecanismos de gestión de la memoria real # Asignaciones ## Asignación contigua La asignación contigua de memoria carga los procesos completos y contiguos, sin dividirlos y en orden. La MMU de suma simple es solo válida en este sistema. ## Asignación no contigua La asignación no contigua de memoria carga los procesos divididos y sin orden, de manera "desorganizada". # Tipos de memoria ## Memoria real * Los procesos se cargan completos en memoria principal → menor grado de multiprogramación. * Medianamiente complejo de implementar. ## Memoria virtual * Los procesos se cargan PARCIALMENTE en memoria principal → mayor grado de multiprogramación. * La mínima parte de un proceso que debe de estar en memoria es la instrucción máquina en curso, aunque normalmente se carga más que eso. * Muy complejo de implementar. # Introducción De cada esquema hay que saber: * **Organización física de la memoria RAM** * Cómo trocea el sistema operativo la memoria. * **Estructuras de datos que necesita el operativo para poder decir cómo está dividida la memoria RAM..** * Las necesita para poder determinar qué zonas de la memoria principal está en uso. * **Traducción de direcciones lógicas a direcciones físicas** * **Estrategias de asignación** * Cómo se asigna memoria principal a los procesos. * **Ventajas e inconvenientes**
import React, { useState, useEffect } from 'react' // GRAPHQL CLIENT import { useLazyQuery } from '@apollo/client' import { GET_MY_PETS_POPULATION } from '../../../graphql/queries' // COMPONENTS import CardsListTemplate from '../../templates/CardsListTemplate' import TagList from '../../molecules/TagList' import ProgressBar from '../../atoms/ProgressBar' // FUNCTIONS import { getLoggedUser } from '../../../functions/local-storage' // MOCKS import config from './config.json' const { cardListTitle, petPopulationWidget } = config const Home = () => { const [user] = useState(getLoggedUser()) const [cardListData, setCardListData] = useState([ { ...petPopulationWidget, cardContent: [ petPopulationWidget.cardContent[0], { ...petPopulationWidget.cardContent[1], content: <ProgressBar isInfiniteLoading={true} /> } ] } ]) const [getData, { data }] = useLazyQuery(GET_MY_PETS_POPULATION) useEffect(() => { const asyncGetData = async () => await getData() asyncGetData() }, [getData]) useEffect(() => { if (data) { const [all, ...pets] = data.getMyPetsPopulation setCardListData([ { ...petPopulationWidget, cardContent: [ { ...petPopulationWidget.cardContent[0], content: { ...petPopulationWidget.cardContent[0].content, titleText: `${ all.quantity === 0 ? `No created Pets yet` : `Created Pets: ${all.quantity}` }` } }, { ...petPopulationWidget.cardContent[1], content: ( <TagList {...{ dataList: pets.map(({ name, quantity }, i) => ({ text: `${name}s: ${quantity}`, color: i % 2 ? 'success' : 'danger' })) }} /> ) } ] } ]) } }, [data]) const cardsListTitle = { ...cardListTitle, titleText: `HELLO ${user?.name?.toUpperCase()}` } return <CardsListTemplate {...{ cardsListTitle, cardListData }} /> } export default Home
{{-- MODAL DE CARNET QR --}} <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-4">Generar Carnets QR</h1> </div> <div class="modal-body"> <form id="pdf-form" action="{{ route('alumno.pdf') }}" method="GET" target="_blank"> <div class="form-group"> <label for="gradoSeccion">Escribe un Grado y Sección:</label> <input type="text" name="gradoSeccion" id="gradoSeccion" class="form-control" style="background-color: #F8FCFC; color: black; border-radius: 10px;" required> <span id="error-message" style="color: red;"></span> </div> <div class="d-flex justify-content-between mt-3"> <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancelar</button> <button type="submit" class="btn btn-outline-warning" data-placement="left"> <i class="fas fa-qrcode"></i> {{ __('Generar Carnets QR') }} </button> </div> </form> </div> </div> </div> </div> {{-- script de seleccion de secciones --}} <script> const gradoSelect = document.getElementById('grado'); const seccionSelect = document.getElementById('seccion'); // Obtener todas las secciones de la base de datos const secciones = Seccione::all(); // Llenar el select de secciones con todas las secciones secciones.forEach(seccion => { const option = document.createElement('option'); option.value = seccion.nombre; option.textContent = seccion.nombre; seccionSelect.appendChild(option); }); gradoSelect.addEventListener('change', () => {}); // Detecta cuando se envía el formulario y restablece el valor del select de grado document.getElementById('pdf-form').addEventListener('submit', () => { setTimeout(() => { gradoSelect.value = ''; seccionSelect.value = ''; }, 0); }); </script> <script> const gradoSeccionInput = document.getElementById('gradoSeccion'); const errorMessage = document.getElementById('error-message'); document.getElementById('pdf-form').addEventListener('submit', (event) => { // Obtén el valor del campo "Grado y Sección" const gradoSeccionValue = gradoSeccionInput.value.trim(); // Divide el valor en palabras const words = gradoSeccionValue.split(' '); // Verifica si se han ingresado al menos dos palabras if (words.length < 2) { // Muestra un mensaje de error y evita que se envíe el formulario errorMessage.textContent = "Te falto poner la Sección"; event.preventDefault(); } else { // Limpia el mensaje de error si los dos campos están presentes errorMessage.textContent = ""; } }); </script> {{-- MODAL PARA REGISTRAR ALUMNOS --}} <div class="modal fade" id="alumno" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-4">Registrar Alumno</h1> </div> <div class="modal-body"> <form id="registroForm" action="{{ route('alumnos.store') }}" method="POST"> @csrf <div class="form-group"> {{ Form::label('DNI') }} {{ Form::text('DNI', '', ['id' => 'dni-input', 'class' => 'form-control', 'placeholder' => 'Ingrese DNI', 'required']) }} <span id="dni-error" class="invalid-feedback" style="display: none;"></span> </div> <div class="form-group"> {{ Form::label('nombre') }} {{ Form::text('nombre', '', ['class' => 'form-control', 'placeholder' => 'Ingrese Nombre', 'required']) }} </div> <div class="form-group"> {{ Form::label('apellidos') }} {{ Form::text('apellidos', '', ['class' => 'form-control' . ($errors->has('apellidos') ? ' is-invalid' : ''), 'placeholder' => 'Ingrese Apellidos', 'required']) }} {!! $errors->first('apellidos', '<div class="invalid-feedback">:message</div>') !!} </div> <div class="form-group"> {{ Form::label('grado') }} {{ Form::select('grado_id', $grados, null, ['class' => 'form-control' . ($errors->has('grado_id') ? ' is-invalid' : ''), 'placeholder' => 'Seleccione un Grado', 'required' => 'required']) }} {!! $errors->first('grado_id', '<div class="invalid-feedback">:message</div>') !!} </div> <div class="form-group"> {{ Form::label('seccion') }} {{ Form::select('seccion_id', $secciones, null, ['class' => 'form-control' . ($errors->has('seccion_id') ? ' is-invalid' : ''), 'placeholder' => 'Selecciona una Sección', 'required' => 'required']) }} {!! $errors->first('seccion_id', '<div class="invalid-feedback">:message</div>') !!} </div> <div class="d-flex justify-content-between mt-3"> <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancelar</button> <button type="button" id="registroButton" class="btn btn-primary">{{ __('Registrar') }}</button> </div> </form> </div> </div> </div> </div> {{-- VALIDACION DE NUMEROS DEL DNI --}} <script> $(document).ready(function() { $('#dni-input').on('input', function() { var dniValue = $(this).val(); var isValid = dniValue.length === 8; if (dniValue.length < 8) { // Mensaje de error para menos de 8 dígitos $('#dni-error').text('Te faltan números.').show(); } else if (dniValue.length > 8) { // Mensaje de error para más de 8 dígitos $('#dni-error').text('Te pasaste de números.').show(); } else { // Oculta el mensaje de error si es válido $('#dni-error').hide(); } }); }); </script> <script> $(document).ready(function() { // Obtener todos los campos de entrada y select del formulario var $formInputs = $('#registroForm :input'); // Obtener el botón de "Registrar" var $registroButton = $('#registroButton'); // Función para verificar si todos los campos están llenos function checkFields() { var allFieldsFilled = true; $formInputs.each(function() { if ($(this).prop('required') && $(this).val() === '') { allFieldsFilled = false; return false; // Salir del bucle si encontramos un campo vacío } }); return allFieldsFilled; } // Deshabilitar el botón de "Registrar" al cargar la página $registroButton.prop('disabled', true); // Habilitar o deshabilitar el botón de "Registrar" según los campos $formInputs.on('input change', function() { if (checkFields()) { $registroButton.prop('disabled', false); } else { $registroButton.prop('disabled', true); } }); }); </script> <div class="modal fade" id="confirmacionModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Confirmación de Registro</h4> </div> <div class="modal-body"> ¿Estás seguro de registrar a este alumno? </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancelar</button> <button type="button" class="btn btn-primary" id="confirmarRegistro">Confirmar</button> </div> </div> </div> </div> {{-- MANEJO DE MODAL DE CONFIRMACION --}} <script> $(document).ready(function() { let formData; // Almacenar temporalmente los datos del formulario $("#registroButton").click(function(event) { // Prevenir el envío del formulario por defecto event.preventDefault(); // Almacenar los datos del formulario formData = $("#registroForm").serializeArray(); // Mostrar el modal de confirmación $("#confirmacionModal").modal("show"); }); // Manejar la confirmación de registro $("#confirmarRegistro").click(function() { // Ocultar el modal $("#confirmacionModal").modal("hide"); // Recuperar los datos del formulario y enviar el formulario if (formData) { formData.forEach(function(field) { $(`[name="${field.name}"]`).val(field.value); }); $("#registroForm").submit(); } }); }); </script>
import { Router } from 'express'; import { celebrate, Segments, Joi } from 'celebrate'; import ensureAuthenticated from '@modules/users/infra/http/middlewares/ensureAuthenticated'; import BusinessPostController from '../controllers/BusinessPostController'; const postRouter = Router(); const businessPostController = new BusinessPostController(); // List postRouter.get('/', ensureAuthenticated, businessPostController.findAll); postRouter.get('/business/:id', businessPostController.findAllInBusiness); // Find postRouter.get('/:id', ensureAuthenticated, businessPostController.find); // Create postRouter.post( '/', ensureAuthenticated, celebrate({ [Segments.BODY]: { title: Joi.string().required(), short_desc: Joi.string().required(), desc: Joi.string().required(), business_id: Joi.string().guid().required(), image_url: Joi.string().required(), }, }), businessPostController.create, ); // Delete postRouter.delete('/:id', ensureAuthenticated, businessPostController.delete); export default postRouter;
--- title: arouter使用阶段性认知 date: 2018-09-13 10:41:22 tags: [工程,arouter] categories: android技能 --- * arouter 问题总结 * values 两种系统识别文件夹,细分三种 * 有没有改造之法? <!-- more --> ![image](arouter-thinking/city.jpg) ## arouter 问题总结: ## ``` 作为一个阿里系的框架,arouter在根本上是实现了,介绍里面所说的,解耦,传参,拦截器,注解,基本的方案实现。在单module中运行也还是可以的,可 能初学者写个把demo之后发现,哎,这阿里系的还是厉害啊。满足要求啊,不过别着急各位,早晚得报到身上的,来自于三方不可控框架造成的问题,或早或晚会给个教训。说好的太多了,我们可以来探讨一下阿里的这个框架的不足; 不足一: 对于多个module的完全解耦是带了认知负担的,完全靠直接的信任度来进行保证; arouter最基本的一点是实现字符串作为路由来完成页面-包含activity,fragment页面的跳转,但是也带来了对于其他的模块完全的黑盒问题,不过要是维护者说,这本就是不多的一些妥协,那确实也没什么好说得了,毕竟这是一个在已有框架中总结弊端的文章。这算是其中一个问题,arouter利用编译时注解来生成了,string与class的对应map,每次在router到相应的地址的时候,直接在map中找key,由此拿出对于的类引用,跳转或者是fragmentmanager跳转,确实也是把一些简单代码逻辑重复工作给封装起来。map处理这种的key-value形式的操作,速度也快,确是带来了完全解耦的无管理状态,这会带来什么呢? 带来问题挺多的,其中下文就会列举一个方面的影响; 不足二: 组件化的支持,后期拆分会带来很大问题; 组件化拆分之前,无法知道一个业务会发展出多大的代码库,开始认为不用拆分的库,之后也会走入一个拆分的巷道,那么前期跟后台跟前段约定的路由就会变成一个巨大的负担。解决方案可以用intercepter来进行拦截和转发,当前的工程已经进入了这个怪圈; 不足三: 为了拆分,工程做了妥协,在原有的基础上,保留原始的分组;而新分出去的module就需要在interceptor中定义一些转发,同时要插桩,本身也不是不可接受,但是还有一个问题违背了我们拆分组件的初衷。组件之所以拆分就是因为需要划分职责,增加重用的概率,而且就算组建不重用,那么底层的很多公共的页面例如分享,选择照片,选择视频,之内的公共的一些页面可能由于没有上下级依赖需要arouter跳转的时候,都会遇到同一个问题: 作为转发的app层不在了,那么没有中间层进行转发,开始的分组件就变成了,离开中央集权之后就不可通讯的问题; ``` ## 有没有改造之法? ## ``` 改造的方法分为基础上改动和彻底重建两种,各有利弊吧; A.一般成熟的大公司,或者说人力比较充沛的大公司,一般都选择了自己自建一个路由转发系统来绕开对于三方框架的依赖,后期的改动和定制都会成为瓶颈;那么市面上已经使用比较多的几个路由框架分别是,美团+饿了么+阿里都有自己的一套路由框架; B.改造arouter的aop和加载核心: arouter之所以有这个问题,根本原因在于,arouter通过aop生成类来做map映射的时候,是在同一个path中生成了诸多的以group为类名的类,那么肯定就有不同的module不能有相同的分组,问题的关键在于生成的逻辑是依赖group来进行的,同路径的自然不能同类名的; 针对这个限制,我们可以进行修改 ``` ## 改造之后的注意点? ## ``` 改动比较大一些的框架,基础的框架,随之而来的肯定是要经过大量的验证和测试的,一个大意可能会影响面非常的大;验证自己的逻辑对于老逻辑有没有影响,开发之中一定要遵循开闭原则,对于修改关闭对于扩展开放; ``` [传送门之大传送之术]()
import { Avatar, Box, Container, Grid, Tab, Tabs, Typography, } from "@mui/material"; import React, { useState } from "react"; import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import NoImage from "../../assets/images/noImage.jpg"; import { CustomTabPanel, a11yProps } from "../../components/CustomTabPanel"; import PostActive from "./components/PostActive"; import PostExpired from "./components/PostExpired"; import PostHidden from "./components/PostHidden"; import { useTranslation } from "react-i18next"; const ManagePost: React.FC = () => { const { t } = useTranslation(); const { user } = useSelector((state: RootState) => state.user); const [value, setValue] = useState<number>(0); const handleChange = (event: React.SyntheticEvent, newValue: number) => { setValue(newValue); }; return ( <Container maxWidth="md"> <Typography variant="h5" align="center" marginBottom={4} fontSize={30}> {t("managePost")} </Typography> <Grid container spacing={2}> <Grid item md={12}> <Box display={"flex"} alignItems={"center"}> <Avatar alt="Avatar" sx={{ marginRight: "10px" }} src={user?.avatar ?? NoImage} /> <Typography sx={{ fontSize: "16px", fontWeight: 700, color: "#000" }} > {user?.name} </Typography> </Box> </Grid> <Grid item md={12}> <Box sx={{ borderBottom: 1, borderColor: "divider", }} > <Tabs value={value} onChange={handleChange} textColor="inherit"> <Tab label={t("tab.active")} {...a11yProps(0)} sx={{ textTransform: "none", }} /> <Tab label={t("tab.expired")} {...a11yProps(1)} sx={{ textTransform: "none", }} /> <Tab label={t("tab.hidden")} {...a11yProps(2)} sx={{ textTransform: "none", }} /> </Tabs> </Box> </Grid> <CustomTabPanel value={value} index={0}> <PostActive /> </CustomTabPanel> <CustomTabPanel value={value} index={1}> <PostExpired /> </CustomTabPanel> <CustomTabPanel value={value} index={2}> <PostHidden /> </CustomTabPanel> </Grid> </Container> ); }; export default ManagePost;
""" This file contains a minimal set of tests for compliance with the extension array interface test suite, and should contain no other tests. The test suite for the full functionality of the array is located in `pandas/tests/arrays/`. The tests in this file are inherited from the BaseExtensionTests, and only minimal tweaks should be applied to get the tests passing (by overwriting a parent method). Additional tests should either be added to one of the BaseExtensionTests classes (if they are relevant for the extension interface for all dtypes), or be added to the array-specific tests in `pandas/tests/arrays/`. """ import numpy as np import pytest from pandas._libs import iNaT from pandas.core.dtypes.dtypes import PeriodDtype import pandas as pd from pandas.core.arrays import PeriodArray from pandas.tests.extension import base @pytest.fixture def dtype(): return PeriodDtype(freq="D") @pytest.fixture def data(dtype): return PeriodArray(np.arange(1970, 2070), freq=dtype.freq) @pytest.fixture def data_for_twos(dtype): return PeriodArray(np.ones(100) * 2, freq=dtype.freq) @pytest.fixture def data_for_sorting(dtype): return PeriodArray([2018, 2019, 2017], freq=dtype.freq) @pytest.fixture def data_missing(dtype): return PeriodArray([iNaT, 2017], freq=dtype.freq) @pytest.fixture def data_missing_for_sorting(dtype): return PeriodArray([2018, iNaT, 2017], freq=dtype.freq) @pytest.fixture def data_for_grouping(dtype): B = 2018 NA = iNaT A = 2017 C = 2019 return PeriodArray([B, B, NA, NA, A, A, B, C], freq=dtype.freq) @pytest.fixture def na_value(): return pd.NaT class BasePeriodTests: pass class TestPeriodDtype(BasePeriodTests, base.BaseDtypeTests): pass class TestConstructors(BasePeriodTests, base.BaseConstructorsTests): pass class TestGetitem(BasePeriodTests, base.BaseGetitemTests): pass class TestIndex(base.BaseIndexTests): pass class TestMethods(BasePeriodTests, base.BaseMethodsTests): def test_combine_add(self, data_repeated): # Period + Period is not defined. pass class TestInterface(BasePeriodTests, base.BaseInterfaceTests): pass class TestArithmeticOps(BasePeriodTests, base.BaseArithmeticOpsTests): implements = {"__sub__", "__rsub__"} def test_arith_frame_with_scalar(self, data, all_arithmetic_operators): # frame & scalar if all_arithmetic_operators in self.implements: df = pd.DataFrame({"A": data}) self.check_opname(df, all_arithmetic_operators, data[0], exc=None) else: # ... but not the rest. super().test_arith_frame_with_scalar(data, all_arithmetic_operators) def test_arith_series_with_scalar(self, data, all_arithmetic_operators): # we implement substitution... if all_arithmetic_operators in self.implements: s = pd.Series(data) self.check_opname(s, all_arithmetic_operators, s.iloc[0], exc=None) else: # ... but not the rest. super().test_arith_series_with_scalar(data, all_arithmetic_operators) def test_arith_series_with_array(self, data, all_arithmetic_operators): if all_arithmetic_operators in self.implements: s = pd.Series(data) self.check_opname(s, all_arithmetic_operators, s.iloc[0], exc=None) else: # ... but not the rest. super().test_arith_series_with_scalar(data, all_arithmetic_operators) def _check_divmod_op(self, s, op, other, exc=NotImplementedError): super()._check_divmod_op(s, op, other, exc=TypeError) def test_add_series_with_extension_array(self, data): # we don't implement + for Period s = pd.Series(data) msg = ( r"unsupported operand type\(s\) for \+: " r"\'PeriodArray\' and \'PeriodArray\'" ) with pytest.raises(TypeError, match=msg): s + data @pytest.mark.parametrize("box", [pd.Series, pd.DataFrame]) def test_direct_arith_with_ndframe_returns_not_implemented(self, data, box): # Override to use __sub__ instead of __add__ other = pd.Series(data) if box is pd.DataFrame: other = other.to_frame() result = data.__sub__(other) assert result is NotImplemented class TestCasting(BasePeriodTests, base.BaseCastingTests): pass class TestComparisonOps(BasePeriodTests, base.BaseComparisonOpsTests): pass class TestMissing(BasePeriodTests, base.BaseMissingTests): pass class TestReshaping(BasePeriodTests, base.BaseReshapingTests): pass class TestSetitem(BasePeriodTests, base.BaseSetitemTests): pass class TestGroupby(BasePeriodTests, base.BaseGroupbyTests): pass class TestPrinting(BasePeriodTests, base.BasePrintingTests): pass class TestParsing(BasePeriodTests, base.BaseParsingTests): @pytest.mark.parametrize("engine", ["c", "python"]) def test_EA_types(self, engine, data): super().test_EA_types(engine, data) class Test2DCompat(BasePeriodTests, base.NDArrayBacked2DTests): pass
import { IStandardHeader } from './set/standard_header' import { IOrdAllocGrp } from './set/ord_alloc_grp' import { IExecAllocGrp } from './set/exec_alloc_grp' import { IInstrument } from './set/instrument' import { IInstrumentExtension } from './set/instrument_extension' import { IFinancingDetails } from './set/financing_details' import { IUndInstrmtGrp } from './set/und_instrmt_grp' import { IInstrmtLegGrp } from './set/instrmt_leg_grp' import { ISpreadOrBenchmarkCurveData } from './set/spread_or_benchmark_curve_data' import { IParties } from './set/parties' import { IStipulations } from './set/stipulations' import { IYieldData } from './set/yield_data' import { IPositionAmountData } from './set/position_amount_data' import { IAllocGrp } from './set/alloc_grp' import { IStandardTrailer } from './set/standard_trailer' import { IRateSource } from './set/rate_source' /* *************************************************************** * The Allocation Instruction message provides the ability to * * specify how an order or set of orders should be subdivided * * amongst one or more accounts. In versions of FIX prior to * * version 4.4, this same message was known as the Allocation * * message. Note in versions of FIX prior to version 4.4, the * * allocation message was also used to communicate fee and * * expense details from the Sellside to the Buyside. This role * * has now been removed from the Allocation Instruction and is * * now performed by the new (to version 4.4) Allocation Report * * and Confirmation messages.,The Allocation Report message * * should be used for the Sell-side Initiated Allocation role * * as defined in previous versions of the protocol. * *************************************************************** */ export interface IAllocationInstruction { StandardHeader: IStandardHeader AllocID: string// 70 AllocTransType: string// 71 AllocType: number// 626 SecondaryAllocID?: string// 793 RefAllocID?: string// 72 AllocCancReplaceReason?: number// 796 AllocIntermedReqType?: number// 808 AllocLinkID?: string// 196 AllocLinkType?: number// 197 BookingRefID?: string// 466 AllocNoOrdersType?: number// 857 OrdAllocGrp?: IOrdAllocGrp[] ExecAllocGrp?: IExecAllocGrp[] PreviouslyReported?: boolean// 570 ReversalIndicator?: boolean// 700 MatchType?: string// 574 Side: string// 54 Instrument: IInstrument InstrumentExtension?: IInstrumentExtension FinancingDetails?: IFinancingDetails UndInstrmtGrp?: IUndInstrmtGrp InstrmtLegGrp?: IInstrmtLegGrp Quantity: number// 53 QtyType?: number// 854 LastMkt?: string// 30 TradeOriginationDate?: Date// 229 TradingSessionID?: string// 336 TradingSessionSubID?: string// 625 PriceType?: number// 423 AvgPx?: number// 6 AvgParPx?: number// 860 SpreadOrBenchmarkCurveData?: ISpreadOrBenchmarkCurveData Currency?: string// 15 AvgPxPrecision?: number// 74 Parties?: IParties[] TradeDate: Date// 75 TransactTime?: Date// 60 SettlType?: string// 63 SettlDate?: Date// 64 BookingType?: number// 775 GrossTradeAmt?: number// 381 Concession?: number// 238 TotalTakedown?: number// 237 NetMoney?: number// 118 PositionEffect?: string// 77 AutoAcceptIndicator?: boolean// 754 Text?: string// 58 EncodedTextLen?: number// 354 EncodedText?: Buffer// 355 NumDaysInterest?: number// 157 AccruedInterestRate?: number// 158 AccruedInterestAmt?: number// 159 TotalAccruedInterestAmt?: number// 540 InterestAtMaturity?: number// 738 EndAccruedInterestAmt?: number// 920 StartCash?: number// 921 EndCash?: number// 922 LegalConfirm?: boolean// 650 Stipulations?: IStipulations[] YieldData?: IYieldData PositionAmountData?: IPositionAmountData[] TotNoAllocs?: number// 892 LastFragment?: boolean// 893 AllocGrp?: IAllocGrp[] AvgPxIndicator?: number// 819 ClearingBusinessDate?: Date// 715 TrdType?: number// 828 TrdSubType?: number// 829 CustOrderCapacity?: number// 582 TradeInputSource?: string// 578 MultiLegReportingType?: string// 442 MessageEventSource?: string// 1011 RndPx?: number// 991 StandardTrailer: IStandardTrailer RateSource?: IRateSource[] }
# Import the pandas library to handle data manipulation and CSV file reading. import pandas as pd class DeletionModel: """ A simple model that deletes bad words from sentences. This model works by maintaining a list of words considered 'bad' or inappropriate. It processes text by removing these words. No machine learning training is involved since the operation is based solely on word deletion. Attributes: bad_words (list of str): A list of words that are to be filtered out of texts. """ def __init__(self, bad_words_path): """ The constructor for DeletionModel class. Parameters: bad_words_path (str): The file path to a CSV file containing a list of bad words. """ # Read the bad words from a CSV file into a pandas DataFrame, then convert them into a list. self.bad_words = pd.read_csv(bad_words_path, header=None)[0].tolist() def train(self): """ The training method for the DeletionModel. In this context, training is not required because the model's behavior is predefined by the bad words list and involves no statistical or machine learning methods. """ # Since there is no training involved, we output a message stating that. print("No need to train this model") def detoxify(self, X_test): """ Detoxify a list of sentences by removing bad words. Parameters: X_test (list of str): A list of sentences to be detoxified. Returns: result (list of str): The list of detoxified sentences. """ # Initialize an empty list to store the results. result = [] # Loop through each sentence in the input list. for sentence in X_test: # Initialize an empty list to store words that are not bad. result_sentence = [] # Split the sentence into individual words and check each one. for word in sentence.split(): # If the word is not in the list of bad words, add it to the results. if word not in self.bad_words: result_sentence.append(word) # Join the words back into a sentence and add it to the list of results. result.append(" ".join(result_sentence)) # Return the list of detoxified sentences. return result
import Vue from 'vue' import VueRouter, { RouteConfig } from 'vue-router' import Layout from '@/layout/index.vue' import store from '@/store' Vue.use(VueRouter) const routes: Array<RouteConfig> = [ { path: '/login', name: 'login', component: () => import(/* webpackChunkName: 'login' */ '@/views/login/index.vue') }, { path: '*', name: '404', component: () => import(/* webpackChunkName: '404' */ '@/views/error-page/404.vue') }, { path: '/', component: Layout, meta: { requiresAuth: true }, children: [ { path: '', name: 'home', component: () => import(/* webpackChunkName: 'home' */ '@/views/home/index.vue') }, { path: '/advert', name: 'advert', component: () => import(/* webpackChunkName: 'advert' */ '@/views/advert/index.vue') }, { path: '/advert-space', name: 'advert-space', component: () => import(/* webpackChunkName: 'home' */ '@/views/advert-space/index.vue') }, { path: '/menu', name: 'menu', component: () => import(/* webpackChunkName: 'menu' */ '@/views/menu/index.vue') }, { path: '/menu/create', name: 'menu-create', component: () => import(/* webpackChunkName: 'menu-modify' */ '@/views/menu/create.vue') }, { path: '/menu/:id/edit', name: 'menu-edit', component: () => import(/* webpackChunkName: 'menu-modify' */ '@/views/menu/edit.vue') }, { path: '/resource', name: 'resource', component: () => import(/* webpackChunkName: 'resource' */ '@/views/resource/index.vue') }, { path: '/role', name: 'role', component: () => import(/* webpackChunkName: 'role' */ '@/views/role/index.vue') }, { path: '/course', name: 'course', component: () => import(/* webpackChunkName: 'course' */ '@/views/course/index.vue') }, { path: '/user', name: 'user', component: () => import(/* webpackChunkName: 'user' */ '@/views/user/index.vue') } ] } ] const router = new VueRouter({ routes }) // 全局前置守卫 router.beforeEach((to, from, next) => { // 匹配到的路由集合中有需要进行验证登录的 if (to.matched.some(record => record.meta.requiresAuth)) { if (!store.state.user) { next({ name: 'login', query: { // 记录当前的页面地址,用于返回此页面用 redirect: to.fullPath } }) } else { next() } } else { next() } }) export default router
# Analysis Report ## Approach taken in evaluating the codebase ### Time spent on this audit: 21 days (Full duration of the contest) Day 1 - Consuming resources provide in the README - Understanding and noting down the logical scope Day 2-7 - Reviewing base contracts (least inherited) - Adding inline bookmarks for notes - Understanding RLP encoding, EIP-4844, Day 8-12 - Reviewing core libs such as LibDepositing, Proposing, Verifying, Proving - Adding inline bookmarks for problems in libs - Gas optimizations for libs Day 13-14 - Other L1, L2 contracts for taiko Day 15-19 - Reviewing bridge contracts, timelocktokenpool, airdrop contracts Day 19-21 - Writing reports ## Architecture recommendations ### What's unique? 1. Allowing custom processing - Allowing users to take over the processing aspect gives them control over how and when they want to process their messages. 2. On L2s and L2s that have no invocation delays, the team has created an MEV market from the bridge itself since the processing fees are rewarded to the fastest processor. 3. Use to transient storage - The team has used TSTORE and TLOAD in two places. One is to enable cheaper reentrancy locks and the second is to provide external applications with context. Having context is important since it allows anyone e.g. the vaults to verify whether the source sending the transactions is valid. ### What's using existing patterns and how this codebase compare to others I'm familiar with - Comparing Taiko to Starknet, the taiko model is much superior since it takes Ethereum's security and uses it to provide cheaper fees to user. The risk associated with Taiko is lesser as well even though it is a type-1 zkevm. This is because Taiko uses guardians while Starknet implements escape hatches, which are more centralized. ## Centralization risks ### Actors Involved and their roles 1. The biggest trust assumption in the contract is the owner role handling all the Address manager contracts. This role can pause the contracts at anytime. 2. The second trust assumption is the guardians multisig. Currently, the guardians are trusted and will be removed over time. But since they are the highest tier, the centralization risk in the proving system exists. 3. ANother role is the bridge watchdog. This role can ban and suspend any messages at will. It is the most important risk of the bridge contracts. 4. The snapshooter role has some risks associated since it takes snapshots on the TaikoToken. There are more roles in the codebase but these are the foremost and most central to the protocol. ## Resources used to gain deeper context on the codebase 1. Based Rollups and decentralized sequencing - [Understanding the Concept of Based Rollups](https://ethresear.ch/t/based-rollups-superpowers-from-l1-sequencing/15016) - [Based Rollup FAQ](https://taiko.mirror.xyz/7dfMydX1FqEx9_sOvhRt3V8hJksKSIWjzhCVu7FyMZU) - [X space - Part 1](https://www.youtube.com/watch?v=eS5s08sgjuo) - [X space - Part 2](https://www.youtube.com/watch?v=RqgIEkAfpks) 2. Based Contestable Rollup (BCR) - [Understanding the concept of Based Contestable Rollup](https://taiko.mirror.xyz/Z4I5ZhreGkyfdaL5I9P0Rj0DNX4zaWFmcws-0CVMJ2A) - [Based Contestable Rollup 101](https://www.youtube.com/watch?v=A6ncZirXPfc) 3. Protocol Documentation - [Website Docs](https://docs.taiko.xyz/core-concepts/what-is-taiko/) - [Markdown concept-specific docs](https://github.com/code-423n4/2024-03-taiko/blob/main/packages/protocol/docs) ## Mechanism Review ### Protocol Goals ![Imgur](https://i.imgur.com/eWUK7d5.png) ### High Level System Overview ![Imgur](https://i.imgur.com/C2NE56L.png) ### Understanding Taiko BCR 1. Taiko has no sequencer - block builders/sequencing is decided by Ethereum validators. Permissionless block proposing, building and proving of taiko blocks. Since it uses what Ethereum has to provide (the market of proposers/builders) to its advantage and is not reinventing the wheel, Taiko is "based". 2. Why do we need contestable rollups? Although ZK is the future, it does introduce complexity in the implementation of the system and thus the chances of bugs. There might be a small % of proofs that are invalid but can still be verified onchain. As a protocol designer, Taiko has to handle these small odds. No validity proof can be trusted without battle testing in short. A malicious block proposer (since proposing blocks is permissionless) can bundle a lot of transactions in a block and create an invalid proof, which would not be handleable by the MerkleTrie verification system. This is why contestable rollups are introduced to prevent these kind of situations/attacks. Due to this since not all blocks are ZK-provable (block gas limit <> ZK constraint limit), Taiko introduced the guardian role to override invalid proofs. Another reason why this tier-based contestable rollup design is used is in case, app chains, other layer 2s and layer3s want to use different proof systems other than ZK (so opt out of ZK proofs and maybe opt into SGX proof a.k.a Optimistic proofs). 3. How the guardian will be chosen DAO => Security Council (owner of all smart contracts) => security council is a multisig with a lot of actors not only from taiko but also the community (like token holders) => security council will decide who will be the guardians => guardian is the multisig smart contract onchain => each guardian will have to run their own full node => each guardian works independently and they do not need to reach consensus offchain => they independently correct the wrong onchain => if the aggregated approval onchain is greater than let's say 2/3rd of the guardians, then the previous proof is overwritten by the guardian to make sure the network is on the right path and has the right state. This guardian proving should be really rare since there is this taiko token-based bond design i.e. validity bond which will be burnt if the proof is re-proven to be incorrect or they have the contestation bond i.e. if you contest a proof and it ends up that the original proof is correct and you are wrong, then your contestation bond is burnt. This prevents people from spamming the network (unless they want to burn bonds, which is dumb). Eventually, after the best tier i.e. highest tier proof (ZK proof) is solid and battle-tested and is really bug free, then the guardian provers should be gone since it's really just for the training wheel. 4. Benefits of Based Contestable Rollup - Abstraction of special if-else code into a tier-based proof system makes the developers aware that the team cannot just shut down the chain uasing guardian prover and does not have control over it. - Taiko has 3 types of bonds - validity bonds, contestation bonds and liveness bonds. We've spoken about the first two. Liveness bonds are basically, le's say, I have a prover off-chain and this prover is supposed to submit the proof within 15 minutes, then if the prover does not submit the proof in that time, then the prover's liveness bond is burnt. - As an app dev, you can always change your config a long way. You can just use one layer-1 transaction to go from 100% optimistic to 100% ZK rollup. - As ZK becomes more trustworthy, the team will slowly increase the % to ZK unitl they become fully ZK and remove the guardian prover. 5. Cooldown window for validity proofs Since we know ZK is not fully trustworthy, let's give it 2-3 hours, so that if nobody challenges this ZK proof, it is final. So from that perspective, Taiko always allows validity proofs to be challenged and overwritten with a higher-tier proof. This adds security. 6. Another Benefit of Based Contestable Rollup If someone says "I don't like the contestable feature", they can always configure their rollup with only one (top) tier. Then all proofs are not contestable and final. No validity bond nor contestable bond applies. 7. Taiko Mainnet Proofs Initially: Optimistic => SGX => PSE zkEVM => Guardians Later: Optimistic => SGX => PSE zkEVM => zkVM (risc0) => Guardians End game: multiple zkVMs (Guardians removed) ### Chains supported - Ethereum - Taiko L2s/L3s ### Grouping of Core Contracts ![Imgur](https://i.imgur.com/HMD27NM.png) ### Recall specific scenario ![Imgur](https://i.imgur.com/cHzS1vH.png) ## Systemic Risks/Architecture-level weak spots and how they can be mitigated There are a few risks associated with the protocol: - The protocol does not have a robust on-chain fee estimation mechanism. On calling the on-chain functions, the relayers should provide the contracts with upto date prices for users or atleast maintain a default amount of gas to send across. - The protocol would not work perfectly with swapping protocols. This is because the bridge includes invocation delays which can cause swaps to go outdated. - There is an issue related to custom coinbase transfers which can create a risk among block proposers. ### Time spent: 200 hours
Tasks = new Mongo.Collection("tasks"); if (Meteor.isClient) { Template.body.helpers({ tasks: function () { /* Uses hideCompleted Session variable to control appearance of list items */ if (Session.get("hideCompleted")) { // $ne: MongoDB flag, not equals return Tasks.find({checked: {$ne: true}},{sort:{createdAt: -1}}); } else { return Tasks.find({},{sort:{createdAt: -1}}); } }, // This method is called in the template, and sets the value of "checked" in the hideCompleted // checkbox hideCompleted: function () { return Session.get("hideCompleted"); }, // keep track of incompletes incompleteCount: function () { return Tasks.find({checked: {$ne: true}}).count(); } }); Template.body.events({ "submit .new-task": function (event) { // Prevent default browser form submit event.preventDefault(); // Get value from form element var text = event.target.text.value; // Insert a task into the collection Meteor.call("addTask", text); // Clear form event.target.text.value = ""; }, "change .hide-completed input": function (event) { Session.set("hideCompleted", event.target.checked); } }); // Task template events Template.task.events({ "click .toggle-checked": function () { // Set the checked property to the opposite of its current value Meteor.call("setChecked", this._id, ! this.checked); }, "click .delete": function () { Meteor.call("deleteTask", this._id); } }); Accounts.ui.config({ passwordSignupFields: "USERNAME_ONLY" }); } // End of client only code if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); } Meteor.methods({ addTask: function (text) { // Make sure the user is logged in before inserting a task if (! Meteor.userId()) { throw new Meteor.Error("not-authorized"); } Tasks.insert({ text: text, createdAt: new Date(), owner: Meteor.userId(), username: Meteor.user().username }); }, deleteTask: function (taskId) { Tasks.remove(taskId); }, setChecked: function (taskId, setChecked) { Tasks.update(taskId, { $set: { checked: setChecked} }); } }); // End of server code
import React , {useState } from 'react' import "./style.css" import Menu from "./menuApi" import MenuCard from './MenuCard'; import Navbar from './Navbar'; const uniqueList = [ ... new Set( Menu.map((curElem) => { return curElem.cat; })), "All", ]; console.log(uniqueList); const Res = () => { const [menuData, setMenuData] = useState(Menu); console.log(menuData); const [menuList, setMenuList] =useState(uniqueList); const filterItem = (category) => { if(category === "All"){ setMenuData(Menu); return; } const updatedlist = Menu.filter((curElem) => { return curElem.cat === category; } ) setMenuData(updatedlist); }; return ( <div> <Navbar filterItem = {filterItem} menuList = {menuList} /> <MenuCard menuData = {menuData} /> </div> ) } export default Res; // import React, { useState } from 'react' // import "./style.css"; // import Menu from "./menuApi" // const res = () => { // const myStyle = {color : "metallic black"}; // const [menuData, setMenuData]= useState(Menu); // return ( // <> // {/* <p>Hello resturant</p> */} // <div className='card-container' > // <div className='card'> // <div className='card-body'> // <span className='card-number card-circle subtle'>1</span> // <span className='card-author subtle' style ={myStyle} > Breakfast </span> // <h2 className='card-title'> Maggi </h2> // <span className=' card-description subtle'> // Lorem ipsum dolor sit amet consectetur, adipisicing elit. Voluptatibus consequatur quis cum, sit natus tempora harum deleniti a? Quia tempora nostrum cupiditate, harum dolores aut rerum voluptate nesciunt nisi voluptatum. // </span> // <div className='card-read'>Read</div> // </div> // <img src = "https://cdn.pixabay.com/photo/2015/06/19/21/24/avenue-815297_1280.jpg" alt = 'image' className='card-media' /> // </div> // </div> // </> // ) // } // export default res
# The elves now need to get ribbon for each present # The length of each ribbon needed is the shortest perimeter of any one face e.g. 2x3x4 has the shortest perimeter of 2+2+3+3 = 10 # The bow fo the ribbon is equal in length to the volume of th present e.g. 2x3x4 needs ribbon of 2*3*4 length # Read the order_list.txt file and store the contents in a string named ribbon_to_order # split the contents into a list so that each line of the file (each present) is an item within the list # initialize an integer named total_ribbon_needed at 0 which represents the total amount of ribbon needed # loop through the list and for each item in the list find the specific dimensions and store them in their respective integer variables # e.g. if an item in the list is 2x3x4 then store 2 in an integer variable name length, store 3 in one called width and store 4 in one called height # when i have all the dimensions of a given item I find the smallest 2 items and add them together before doubling it to find the smallest perimeter, I store this in an integer called smallest_perimeter # i then multiply each of the dimensions with each other and store the value in a variable called bow length # i then add smallest_permiter and bow_length and that value to total_ribbon_needed # once the list has been completely looped through i output total_ribbon_needed import re order_list_file = open("../order_list.txt", "r") ribbon_to_order = order_list_file.read() dimensions_list = ribbon_to_order.split("\n") total_ribbon_needed = 0 for dimensions in dimensions_list: length = int((re.findall("(\d+)x\d+x\d+", dimensions))[0]) smallest = length second_smallest = length width = int((re.findall("\d+x(\d+)x\d+", dimensions))[0]) if width < smallest: smallest = width else: second_smallest = width height = int((re.findall("\d+x\d+x(\d+)", dimensions))[0]) if height < smallest: second_smallest = smallest smallest = height elif height < second_smallest: second_smallest = height smallest_perimeter = 2 * (smallest + second_smallest) bow_length = length * width * height total_ribbon_needed = total_ribbon_needed + smallest_perimeter + bow_length print(total_ribbon_needed)
<div class="mt-10"> <div class="grid gap-6 grid-cols-4"> <div *ngFor="let cliente of clientes"> <mat-card class="w-96 h-96 shadow-xl"> <mat-card-header class="h-72 mb-5"> <mat-card-title class="w-full">{{ cliente.nome }}</mat-card-title> <mat-card-subtitle class="w-full">{{ cliente.cargo }}</mat-card-subtitle> <mat-card-content> <div *ngIf="cliente.minFaturamento || cliente.maxFaturamento"> <p> Faturamento: {{ cliente.minFaturamento }} - {{ cliente.maxFaturamento }} </p> </div> <div *ngIf="cliente.empresa"> <br /> <p>Empresa:</p> </div> <div *ngIf="cliente.endereco?.cidade && cliente.endereco?.estado"> <br /> <p> Cidade: {{ cliente?.endereco?.cidade }} - {{ cliente?.endereco?.estado }} </p> </div> <div *ngIf="cliente.contato?.telefone"> <br /> <p>Telefone: {{ cliente?.contato?.telefone }}</p> </div> <div *ngIf="cliente?.contato?.telefone2"> <br /> <p>Telefone: {{ cliente?.contato?.telefone }}</p> </div> </mat-card-content> </mat-card-header> <mat-card-actions> <button class="bg-blue-300 rounded text-white px-4 py-2" (click)="openDialogEditar(cliente.uuid!)" > Editar </button> <button (click)="openDialog(cliente.uuid!)" class="bg-green-400 rounded text-white px-4 py-2 mx-3" > Ações </button> <button class="bg-red-400 rounded text-white px-4 py-2"> Excluir </button> </mat-card-actions> </mat-card> </div> </div> </div>
<template> <div class="auth-reg auth-reg--auth"> <div class="auth-reg__header"> <h2 class="auth-reg__header__title">Авторизация</h2> <svg @click="togglePopupAuth" class="icon-close icon-close--auth-reg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"> <path d="M310.6 361.4c12.5 12.5 12.5 32.75 0 45.25C304.4 412.9 296.2 416 288 416s-16.38-3.125-22.62-9.375L160 301.3L54.63 406.6C48.38 412.9 40.19 416 32 416S15.63 412.9 9.375 406.6c-12.5-12.5-12.5-32.75 0-45.25l105.4-105.4L9.375 150.6c-12.5-12.5-12.5-32.75 0-45.25s32.75-12.5 45.25 0L160 210.8l105.4-105.4c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25l-105.4 105.4L310.6 361.4z"/> </svg> </div> <form @submit.prevent="submitForm"> <div class="auth-reg__input-section"> <div class="auth-reg__input-block"> <img class="auth-reg__image" src="../../../../../public/assets/files/images/user-solid.svg" alt=""> <div class="auth-reg__input-container"> <input v-model="fieldEmail" class="input" type="text" name="email" placeholder="Электронная почта"> <p class="error-p"> {{ emailExist }} </p> </div> </div> <div class="auth-reg__input-block"> <img class="auth-reg__image" src="../../../../../public/assets/files/images/key-solid.svg" alt=""> <div class="auth-reg__input-container"> <input v-model="fieldPassword" class="input" type="password" name="password" placeholder="Пароль"> <p class="error-p"> {{ passwordExist }} </p> </div> </div> <div class="auth-reg__input-block"> <button type="button" class="button auth-reg__forgot-password" href="">Забыли пароль?</button> </div> </div> <div class="auth-reg__button-section"> <button class="button button--auth auth-reg__button" href="">Войти в систему</button> </div> </form> </div> </template> <script> export default { name: "PopupAuth", data() { return { fieldEmail: "", fieldPassword: "", } }, watch: { fieldEmail() { this.$store.commit("setEmailField", this.fieldEmail) }, fieldPassword() { this.$store.commit("setPasswordField", this.fieldPassword) }, }, computed: { emailExist() { return this.$store.getters.getEmailExist }, passwordExist() { return this.$store.getters.getPasswordExist }, }, methods: { togglePopupAuth() { this.$store.commit("togglePopupAuth", false) this.$store.commit("changeErrors", {}) }, submitForm() { this.$store.dispatch("validateFieldsAuthReg", 0) }, }, } </script> <style scoped> </style>
import { getErrorMessageByPropertyName } from "@/utils/schemaValidator"; import React from "react"; import { Controller, useFormContext } from "react-hook-form"; import PublicInfo from "../Formatting/PublicInfo"; import Text from "../Formatting/Text"; interface IProps { name: string; value?: string | string[] | undefined; placeholder?: string; label?: string; size?: "md" | "lg" | "sm"; defaultValue?: string; className?: string; } const FormTextArea = ({ name, value, placeholder, label, size = "md", defaultValue, className, }: IProps) => { const { control, formState: { errors }, } = useFormContext(); const errorMessage = getErrorMessageByPropertyName(name, errors); return ( <div className="mb-5"> {label && size === "lg" && <PublicInfo>{label ? label : ""}</PublicInfo>} {label && size === "md" && <PublicInfo>{label ? label : ""}</PublicInfo>} {label && size === "sm" && <Text>{label ? label : ""}</Text>} <Controller control={control} name={name} render={({ field }) => ( <textarea placeholder={placeholder} {...field} value={value ? value : field?.value} defaultValue={defaultValue} className={`mt-1 px-1 md:px-2 py-1 lg:px-3 focus:outline-none md:text-lg w-full bg-transparent box-border text-white rounded border-2 border-solid border-gray-300 focus:border-[#0099ff]${ size === "lg" && "text-base md:text-lg lg:text-xl" } ${size === "md" && "text-sm md:text-base lg:text-lg"} ${ size === "sm" && "text-xs md:text-sm lg:text-base" } ${className}`} /> )} /> {errorMessage && ( <div className="text-red-500 mt-1 text-sm">{errorMessage}</div> )} </div> ); }; export default FormTextArea;
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. library fuchsia.component.decl; using fuchsia.io; /// Declares a capability defined by this component. type Capability = flexible union { 1: service Service; 2: protocol Protocol; 3: directory Directory; 4: storage Storage; 5: runner Runner; 6: resolver Resolver; @available(removed=14) 7: event Event; @available(added=8) 8: event_stream EventStream; @available(added=HEAD) 9: dictionary Dictionary; @available(added=20) 10: config Configuration; }; /// Declares a service capability backed by this component. /// /// To learn more about services, see: /// https://fuchsia.dev/fuchsia-src/glossary#service type Service = table { /// (Required) The name of this service. 1: name name; /// (Optional) The path to the service in the component's outgoing /// directory. /// /// Not set for built-in capabilities. 2: source_path string:MAX_PATH_LENGTH; }; /// Declares a protocol capability backed by this component. /// /// To learn more about protocols, see: /// https://fuchsia.dev/fuchsia-src/glossary#protocol type Protocol = table { /// (Required) The name of this protocol. 1: name name; /// (Optional) The path to the protocol in the component's outgoing /// directory. /// /// Not set for built-in capabilities. 2: source_path string:MAX_PATH_LENGTH; /// (Optional, defaults to `EAGER`) specifies when the framework will open /// the protocol from this component's outgoing directory when someone /// requests the capability. See details on `DeliveryType`. @available(added=HEAD) 3: delivery DeliveryType; }; /// Declares a directory capability backed by this component. /// /// To learn more about directories, see: /// https://fuchsia.dev/fuchsia-src/glossary#directory type Directory = table { /// (Required) The name of this directory. 1: name name; /// (Optional) The path to the directory in the component's outgoing /// directory. /// /// Not set for built-in capabilities. 2: source_path string:MAX_PATH_LENGTH; /// (Required) The maximum rights that can be set by a component using this /// directory. 3: rights fuchsia.io.Rights; }; /// Declares a storage capability backed by a directory from which data, cache, /// or meta storage can be offered. type Storage = table { /// (Required) The name of this storage 1: name name; /// (Required) The provider of the backing directory capability relative to /// the component itself. Must be `parent`, `self`, or `child`. 2: source Ref; /// (Required) The name of the directory capability from `source` that backs /// the storage. 3: backing_dir name; /// (Optional) The subdirectory of the source directory that will back the /// storage 4: subdir string:MAX_PATH_LENGTH; /// (Required) This enum determines how to key a component's isolated /// storage directory. Each option corresponds to a different key'ing /// strategy. 5: storage_id StorageId; }; /// Declares which identifier to use to key a component's isolated storage /// directory. type StorageId = strict enum { /// Isolated storage directories are keyed using a component's instance ID /// specified in the component ID index. Components which are not listed in /// the index cannot use or open this storage capability. STATIC_INSTANCE_ID = 1; /// Isolated storage directories are keyed using a component's instance ID /// if one is specified in the component ID index. Otherwise, a component's /// moniker from the storage capability is used to key its isolated /// storage directory. STATIC_INSTANCE_ID_OR_MONIKER = 2; }; /// Declares a runner capability backed by a service. type Runner = table { /// (Required) The name of this runner. /// /// Must unique among runners declared in the same `ComponentDecl`. 1: name name; /// (Optional) The path to the runner protocol in the component's outgoing /// directory. /// /// Not set for built-in capabilities. 2: source_path string:MAX_PATH_LENGTH; }; /// Declares a resolver which is responsible for resolving component URLs to /// actual components. See `fuchsia.component.resolution.Resolver` for the /// protocol resolvers are expected to implement. type Resolver = table { /// (Required) The name of this resolver. /// /// Must be unique among resolvers declared in the same `ComponentDecl`. 1: name name; /// (Optional) The path to the resolver protocol in the component's outgoing /// directory /// /// Not set for built-in capabilities. 2: source_path string:MAX_PATH_LENGTH; }; /// Declares an event capability which component instances may subscribe to. /// This type cannot be used in `fuchsia.component.decl.Component`. It is only /// used for the framework's built-in capabilities declared in /// `internal.Config`. @available(removed=14) type Event = table { /// (Required) The name of this event. /// /// Must be unique among built-in capabilities. 1: name name; }; /// Declares an event_stream capability /// /// This type cannot be used in `fuchsia.component.decl.Component`. It is only /// used for the framework's built-in capabilities declared in /// `internal.Config`. @available(added=8) type EventStream = table { /// (Required) The name of this event stream. /// /// Must be unique among built-in capabilities. 1: name name; }; /// Declares a dictionary capability. // TODO(https://fxbug.dev/300503731): Add doc link @available(added=HEAD) type Dictionary = table { /// (Required) The name of this dictionary. /// /// Must be unique among built-in capabilities. 1: name name; /// (Optional) Source of the contents used to initialize the dictionary. /// Must be `parent`, `self`, or `child`. 2: source Ref; /// (Optional) Path in a dictionary provided by `ref` which contains the contents /// that will be used to initialize the dictionary. /// /// This must be set iff `source` is set. 3: source_dictionary dictionary_path; }; /// Declares a configuration capability. /// /// To learn more about configuration capabilities, see: /// https://fuchsia.dev/fuchsia-src/glossary#configuration-capability /// or: /// https://fuchsia.dev/fuchsia-src/docs/concepts/components/v2/capabilities/configuration @available(added=20) type Configuration = table { /// (Required) The name of this configuration 1: name name; /// (Required) The value of this Configuration. 2: value ConfigValue; };
\chapter{\IfLanguageName{dutch}{Vereisten}{Requirements}}% \label{ch:vereisten} \section{Vereisten uit literatuurstudie}% \label{sec:vereisten-literatuurstudie} In de literatuurstudie kwamen er enkele criteria naar boven die invloed kunnen hebben op de keuze van een Low-Code en/of No-Code platform. Voor een duidelijk overzicht is hieronder een tabel opgesteld met de volgende velden; Criteria, Reden/Relevantie, Bron. Ter info; de criteria die in de tabel zijn opgenomen staan niet vast en zijn bedoeld als een leidraad voor de requirements analyse. \begin{longtable}{p{4.25cm}p{7cm}p{3.5cm}} \caption{Criteria lijst a.d.h.v. voorgaande literatuurstudie} \label{criteriums} \\ \toprule \textbf{Criteria} & \textbf{Reden/Relevantie} & \textbf{Bron} \\ \midrule \endfirsthead % Repeat the headers on the next page \multicolumn{3}{c}{{\bfseries \tablename\ \thetable{} -- vervolg van de vorige pagina}} \\ \toprule \textbf{Criteria} & \textbf{Reden/Relevantie} & \textbf{Bron} \\ \midrule \endhead % Footer at the end of each page, except the last page \midrule \multicolumn{3}{r}{{Vervolg op volgende pagina}} \\ \endfoot % Footer at the end of the table \bottomrule \endlastfoot % Table content Snelheid van het platform & Om snel en eenvoudig ingewikkelde applicaties te ontwikkelen. & \hyperref[subsec:snelheid]{Voordelen: snelheid} \\ Snelheid van applicatieontwikkeling & Zorgt dat er meerdere applicaties in een korte tijd ontwikkeld kunnen worden. Vervolgens moeten bedrijven ook steeds snel en flexibel kunnen inspelen op de veranderende markt. & \hyperref[subsec:snelheid]{Voordelen: snelheid} \& \hyperref[sec:reden-tot-gebruik]{Reden tot gebruik: Tijdrovend} \\ Leercurve & Heel wat mensen laten zich afschrikken om te programmeren, door de complexiteit van de programmeertalen. Hierdoor is het belangrijk dat het snel en eenvoudig is om te leren. & \hyperref[sec:reden-tot-gebruik]{Reden tot gebruik: Beperkt aantal programmeurs} \\ Updatebeleid \& Moderniteit & Omdat technologie vaak verandert, is de impact van een updatebeleid en moderniteit van het platform belangrijk op lange termijn. & \hyperref[sec:reden-tot-gebruik]{Reden tot gebruik: Technologische turbulentie} \\ Kostprijs & Omdat Quivvy Solutions BV een start-up is, zijn er beperkte financiële middelen. Daardoor is het belangrijk dat de kostprijs niet over het budget gaat. & \hyperref[sec:reden-tot-gebruik]{Reden tot gebruik: Hoge kosten} \& \hyperref[sec:lcnc-bedrijven]{LCNC binnen bedrijven} \\ Klantentevredenheid & Als klein bedrijf is het belangrijk dat de klanten tevreden zijn over de applicaties die worden ontwikkeld. & \hyperref[sec:reden-tot-gebruik]{Reden tot gebruik: Klantentevredenheid} \\ Veiligheid & Om ervoor te zorgen dat zowel het bedrijf Quivvy Solutions BV als hun eindklant zo weinig mogelijk schade kunnen ondervinden door het gebruikte platform. & \hyperref[subsec:veiligheid]{Voordelen: Veiligheid} \\ Herstelbeheer \& Back-up & Wanneer er zich een ramp afspeelt moeten de gegevens zo snel mogelijk kunnen hersteld worden. Hierdoor is regelmatig back-ups nemen relevant. & \hyperref[subsec:cloud-based-lcnc]{Cloud-based LCNC : Dataherstel} \\ Integratie mogelijkheden & Hoe meer Integratie mogelijkheden dat het LCNC platform heeft, hoe beter. & \hyperref[subsec:beperkte-flexibiliteit]{Nadelen: Beperkte Flexibiliteit} \\ Platformflexibiliteit \& Aanpasbaarheid & Mogelijkheid om high-code en de mogelijke functionaliteiten te implementeren wanneer nodig. & \hyperref[subsec:beperkte-flexibiliteit]{Nadelen: Beperkte Flexibiliteit} \\ Schaalbaarheid & Een applicatie in LCNC platformen zou gemakkelijk uitbreidbaar moeten zijn en de mogelijkheid moeten hebben om meer gelijktijdig gebruikers toe te laten. & \hyperref[subsec:gelimiteerde-schaalbaarheid]{Nadelen: Gelimiteerde schaalbaarheid} \\ Documentatiekwaliteit & Documentatie kan leiden tot een oplossing voor het beter begrijpen van bijvoorbeeld het opslaan van data. & \hyperref[subsec:lcnc-binnen-agile]{LCNC in Software Development Life Cycle: Application Design} \\ Test- en debugmogelijkheden & LCNC platformen verwaarlozen vaak testen, maar dit blijft nog steeds een belangrijke fase in de Software Development Life Cycle. & \hyperref[subsec:lcnc-binnen-agile]{LCNC in Software Development Life Cycle: Testing} \\\endline \end{longtable} \section{Bepaling van belangrijke vereisten\\ voor LCNC platformen}% \label{sec:bepaling-van-belangrijke-vereisten} Bij het antwoord van de copromotor op de vraag: Welke vereisten zijn volgens u belangrijk bij het kiezen van een LCNC platform en rangschik deze vereisten van belangrijk naar minder belangrijk; kwamen er ook andere criteria naar voren. Deze bestaan uit; gebruiksvriendelijkheid, integratie met AirTable, en integratie met MAKE.com. Vervolgens heb ik samen met mijn copromotor overlegd welke criteria de belangrijkste zijn en welke minder belangrijk zijn. Hieruit volgt een lijst van requirements met een score op 10, waarbij 10 het belangrijkste is en 1 het minst belangrijk. \begin{table}[H] \centering \caption{Requirements score} \begin{tabular}{llc} \toprule Criteria & Score \\ \midrule Snelheid van het platform & 10 \\ Herstelbeheer & 10 \\ Veiligheid & 9 \\ Snelheid van applicatieontwikkeling & 8 \\ Integratie mogelijkheden & 8 \\ Platformflexibiliteit (bv. high-code kunnen implementeren) & 8 \\ Schaalbaarheid & 8 \\ Gebruiksvriendelijkheid & 8 \\ Integratie met AirTable en/of MAKE.com & 8 \\ Kostprijs & 7.5 \\ Updatebeleid & 7.5 \\ Klantentevredenheid & 7.5 \\ Test- en debugmogelijkheden & 7.5 \\ Leercurve & 6 \\ Documentatiekwaliteit & 6 \\ \bottomrule \end{tabular} \end{table} \section{Officiële Vereisten}% \label{sec:officiële-vereisten} De officiële requirements worden de criteria die een score hebben van 8 of hoger, met uitzondering van kostprijs en updatebeleid. De reden hiervoor is dat de kostprijs toch wel belangrijk is voor een start-up en het updatebeleid voor de lange termijn. Hieruit volgt dat de klantentevredenheid, test- en debug mogelijkheden, documentatiekwaliteit en leercurve niet in de officiële requirements zullen opgenomen worden. Een reden waarom leercurve en documentatiekwaliteit niet belangrijk is, is omdat er tegenwoordig bronnen zijn die kunnen helpen bij het leren van een platform. Daarnaast beschikt een platform vaak over goede documentatiekwaliteit. Zo niet, dan zijn er tutorials die kunnen helpen bij een bepaald probleem.
import type { GetServerSideProps, GetServerSidePropsContext, NextPage, } from "next"; import Head from "next/head"; import { useState } from "react"; import { useSetUrl } from "../utils/trpc"; import { formatDistanceToNow } from 'date-fns' import {parse} from 'superjson' import { ShortLink } from "@prisma/client"; type Props = { host: string | null }; export const getServerSideProps = async ( ctx: GetServerSidePropsContext ) => { return { props: { host: ctx.req.headers.host } }; }; const Home: NextPage<Props> = ({ host }) => { const [form, setForm] = useState({ url: "", ttl: 60, }); const [newUrl, setNewUrl] = useState<ShortLink>({ id: "", url: "", createdAt: new Date(), expiresAt: new Date(), slug: "", }); const { setUrl, loading, success, error } = useSetUrl(); const createUrl = async (value: typeof form) => { const { url, ttl } = value; const result = parse<ShortLink>(await setUrl(url, ttl)); console.log('client side date and type', result.expiresAt, typeof result.expiresAt) setNewUrl(result); }; return ( <div> <Head> <title>lnk</title> <meta name="description" content="Create a shorter link" /> <link rel="icon" href="/favicon.ico" /> </Head> <main className="flex flex-col items-center justify-center h-screen"> <form className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4 flex flex-col items-center content-center" onSubmit={(e) => { e.preventDefault(); createUrl(form); }} > <div className="mb-4"> <label className="block text-gray-700 font-bold mb-2" htmlFor="url" > Paste in your URL </label> <input className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="url" type="text" placeholder="http://example.com" value={form.url} onChange={(e) => setForm({...form, url: e.currentTarget.value})} /> </div> <div className="mb-4"> <label className="block text-gray-700 font-bold mb-2" htmlFor="ttl" > Time to live (minutes) </label> <input className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="ttl" type="number" value={form.ttl} onChange={(e) => setForm({...form, ttl: parseInt(e.currentTarget.value)})} /> </div> <div className="mb-6"> <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="submit" > Submit </button> </div> </form> {loading && <div>Loading...</div>} {error && <div>Something went wrong...</div>} <div className="flex flex-col gap-4 items-center"> {success && ( <> <p>Link expires in {formatDistanceToNow(newUrl.expiresAt)}</p> <a href={`${host}/lnk/${newUrl.slug}`} target="_blank" rel="noreferrer"> {host}/lnk/{newUrl.slug} </a> <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" onClick={() => { navigator.clipboard.writeText(`${host}/lnk/${newUrl.slug}`); }} > Copy link to clipboard </button> </> )} </div> </main> </div> ); }; export default Home;
#ifndef QSIMPLEUPDATER_H #define QSIMPLEUPDATER_H // Copyright (c) 2014-2016 Alex Spataru <alex_spataru@outlook.com> #include <QUrl> #include <QList> #include <QObject> class Updater; /** * \brief Manages the updater instances * * The \c QSimpleUpdater class manages the updater system and allows for * parallel application modules to check for updates and download them. * * The behavior of each updater can be regulated by specifying the update * definitions URL (from where we download the individual update definitions) * and defining the desired options by calling the individual "setter" * functions (e.g. \c setNotifyOnUpdate()). * * The \c QSimpleUpdater also implements an integrated downloader. * If you need to use a custom install procedure/code, just create a function * that is called when the \c downloadFinished() signal is emitted to * implement your own install procedures. * * By default, the downloader will try to open the file as if you opened it * from a file manager or a web browser (with the "file:*" url). */ class QSimpleUpdater : public QObject { Q_OBJECT signals: void checkingFinished (const QString& url); void appcastDownloaded (const QString& url, const QByteArray& data); void downloadFinished (const QString& url, const QString& filepath); public: static QSimpleUpdater* getInstance(); bool usesCustomAppcast (const QString& url) const; bool getNotifyOnUpdate (const QString& url) const; bool getNotifyOnFinish (const QString& url) const; bool getUpdateAvailable (const QString& url) const; bool getDownloaderEnabled (const QString& url) const; bool usesCustomInstallProcedures (const QString& url) const; QString getOpenUrl (const QString& url) const; QString getChangelog (const QString& url) const; QString getModuleName (const QString& url) const; QString getDownloadUrl (const QString& url) const; QString getPlatformKey (const QString& url) const; QString getLatestVersion (const QString& url) const; QString getModuleVersion (const QString& url) const; QString getUserAgentString (const QString& url) const; public slots: void checkForUpdates (const QString& url); void setModuleName (const QString& url, const QString& name); void setNotifyOnUpdate (const QString& url, const bool notify); void setNotifyOnFinish (const QString& url, const bool notify); void setPlatformKey (const QString& url, const QString& platform); void setModuleVersion (const QString& url, const QString& version); void setDownloaderEnabled (const QString& url, const bool enabled); void setUserAgentString (const QString& url, const QString& agent); void setUseCustomAppcast (const QString& url, const bool customAppcast); void setUseCustomInstallProcedures (const QString& url, const bool custom); protected: ~QSimpleUpdater(); private: Updater* getUpdater (const QString& url) const; }; #endif // QSIMPLEUPDATER_H
extern crate tokio; use simplelog::*; use std::fs::OpenOptions; use tokio::sync::{broadcast, mpsc, Barrier, RwLock}; use std::sync::Arc; use crate::ControlSignal; #[derive(Debug, Clone)] pub struct LogMessage { pub message: String, pub level: log::Level, } fn create_log_message(log_level: log::Level, msg: &str) -> LogMessage { LogMessage { message: String::from(msg), level: log_level, } } #[derive(Clone)] #[allow(unused)] pub struct Logging { initialized: bool, logtx: Option<mpsc::Sender<LogMessage>>, level: Level, logfile: Option<String>, } use lazy_static::lazy_static; lazy_static! { static ref LOGGER: Arc<RwLock<Logging>> = Arc::new(RwLock::new(Logging { initialized: false, logtx: None, level: Level::Info, logfile: None, })); } impl Logging { pub async fn set_logqueue(logtx: &mpsc::Sender<LogMessage>) { let mut logger = LOGGER.write().await; logger.logtx = Some(logtx.clone()); } pub async fn set_debug(debug: bool) { let mut logger = LOGGER.write().await; if debug { logger.level = Level::Debug; } else { logger.level = Level::Info; } } pub async fn set_logfile(logfile: String) { let mut logger = LOGGER.write().await; logger.logfile = Some(logfile.clone()); logger.initialize(); } fn initialize(&mut self) { self.level = Level::Info; if self.initialized { return; } let console_logger = TermLogger::new( LevelFilter::Debug, ConfigBuilder::new() .set_time_format_custom(format_description!("[hour]:[minute]:[second].[subsecond]")) .set_thread_level(LevelFilter::Trace) .set_target_level(LevelFilter::Trace) .set_location_level(LevelFilter::Trace) .set_thread_mode(ThreadLogMode::Both) .build(), TerminalMode::Mixed, ColorChoice::Auto, ); let file_logger = WriteLogger::new( LevelFilter::Debug, ConfigBuilder::new() .set_time_format_custom(format_description!("[hour]:[minute]:[second].[subsecond]")) .set_thread_level(LevelFilter::Debug) .set_target_level(LevelFilter::Debug) .set_location_level(LevelFilter::Debug) .set_thread_mode(ThreadLogMode::Both) .build(), OpenOptions::new() .create(true) .append(true) .open(self.logfile.as_ref().unwrap().clone()) .unwrap(), ); CombinedLogger::init(vec![ console_logger, file_logger, ]).unwrap_or_else(|_| {}); self.initialized = true; } pub async fn log_thread(& self, barrier: Arc<Barrier>, shutdown_barrier: Arc<Barrier>, ctltx: broadcast::Sender<ControlSignal>, mut logrx: mpsc::Receiver<LogMessage>) { let mut shutdown = false; let mut draining = false; let mut drained = false; let mut ctlqueue = ctltx.subscribe(); self.log_info("Starting logging thread".to_string()); let _ = barrier.wait().await; while (!shutdown || draining) && !drained { let mut a = None; let mut b = None; while a.is_none() && b.is_none() && !drained { tokio::select! { v = logrx.recv() => { if v.is_none() { draining = false; drained = true; info!("Logs drained."); } else { a = Some(v.unwrap()); } }, v = ctlqueue.recv() => b = Some(v.unwrap()), } } if !a.is_none() { let log_message = a.unwrap(); let message = log_message.message.to_owned(); if log_enabled!(log_message.level) && log_message.level <= self.level { log!(log_message.level, "{}", message); } } if !b.is_none() { match b.unwrap() { ControlSignal::Shutdown => { shutdown = true; draining = true; drained = false; // Allow all other tasks to log dying gasps. shutdown_barrier.wait().await; info!("Draining logs"); logrx.close(); }, ControlSignal::Reconfigure(_) => {}, } } } drop(logrx); drop(ctlqueue); info!("Shutting down Logging thread"); } #[allow(unused)] pub fn log_trace(& self, message: String) { if !self.logtx.is_none() { let logtx = self.logtx.as_ref().unwrap().clone(); logtx.try_send(create_log_message(Level::Trace, &message)).unwrap(); } } #[allow(unused)] pub fn log_debug(& self, message: String) { if !self.logtx.is_none() { let logtx = self.logtx.as_ref().unwrap().clone(); logtx.try_send(create_log_message(Level::Debug, &message)).unwrap(); } } #[allow(unused)] pub fn log_info(& self, message: String) { if !self.logtx.is_none() { let logtx = self.logtx.as_ref().unwrap().clone(); logtx.try_send(create_log_message(Level::Info, &message)).unwrap(); } } #[allow(unused)] pub fn log_warn(& self, message: String) { if !self.logtx.is_none() { let logtx = self.logtx.as_ref().unwrap().clone(); logtx.try_send(create_log_message(Level::Warn, &message)).unwrap(); } } #[allow(unused)] pub fn log_error(& self, message: String) { if !self.logtx.is_none() { let logtx = self.logtx.as_ref().clone().unwrap(); logtx.try_send(create_log_message(Level::Error, &message)).unwrap(); } } } pub async fn do_log_thread(barrier: Arc<Barrier>, shutdown_barrier: Arc<Barrier>, ctlqueue: broadcast::Sender<ControlSignal>, logrx: mpsc::Receiver<LogMessage>) { let _ = tokio::spawn(async move { let logger = LOGGER.read().await; logger.log_thread(barrier, shutdown_barrier, ctlqueue, logrx).await; }); } #[allow(unused)] pub fn log_trace(message: &str) { let msg = String::from(message); let _ = tokio::spawn(async move { let mut logger = LOGGER.read().await; logger.log_trace(msg); }); } #[allow(unused)] pub fn log_debug(message: &str) { let msg = String::from(message); let _ = tokio::spawn(async move { let mut logger = LOGGER.read().await; logger.log_debug(msg); }); } #[allow(unused)] pub fn log_info(message: &str) { let msg = String::from(message); let _ = tokio::spawn(async move { let mut logger = LOGGER.read().await; logger.log_info(msg); }); } #[allow(unused)] pub fn log_warn(message: &str) { let msg = String::from(message); let _ = tokio::spawn(async move { let mut logger = LOGGER.read().await; logger.log_warn(msg); }); } #[allow(unused)] pub fn log_error(message: &str) { let msg = String::from(message); let _ = tokio::spawn(async move { let mut logger = LOGGER.read().await; logger.log_error(msg); }); }
/* * This file is a part of Bluecherry Client (https://github.com/bluecherrydvr/unity). * * Copyright 2022 Bluecherry, LLC * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import 'package:bluecherry_client/api/api.dart'; import 'package:bluecherry_client/models/server.dart'; import 'package:bluecherry_client/providers/server_provider.dart'; import 'package:bluecherry_client/utils/constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; Future<void> showEditServer(BuildContext context, Server server) { return showDialog( context: context, builder: (context) { final loc = AppLocalizations.of(context); return AlertDialog( title: Text(loc.editServer(server.name)), content: ConstrainedBox( constraints: BoxConstraints( minWidth: MediaQuery.sizeOf(context).width * 0.75, ), child: EditServer( serverIp: server.ip, serverPort: server.port, ), ), ); }, ); } Future<void> updateServer(BuildContext context, Server serverCopy) async { final (code, updatedServer) = await API.instance.checkServerCredentials( serverCopy, ); if (updatedServer.serverUUID != null && updatedServer.hasCookies && code == ServerAdditionResponse.validated) { await ServersProvider.instance.update(updatedServer); if (context.mounted) Navigator.of(context).pop(); } else if (context.mounted) { showDialog( context: context, builder: (context) { final theme = Theme.of(context); final loc = AppLocalizations.of(context); return AlertDialog( title: Text(loc.error), content: Text( loc.serverNotAddedError(serverCopy.name), style: theme.textTheme.headlineMedium, ), actions: [ MaterialButton( onPressed: Navigator.of(context).maybePop, textColor: theme.colorScheme.secondary, child: Padding( padding: const EdgeInsetsDirectional.all(8.0), child: Text( loc.ok, ), ), ), ], ); }, ); } } class EditServer extends StatefulWidget { final String serverIp; final int serverPort; const EditServer({ super.key, required this.serverIp, required this.serverPort, }); @override State<EditServer> createState() => _EditServerState(); } class _EditServerState extends State<EditServer> { final formKey = GlobalKey<FormState>(); bool nameTextFieldEverFocused = false; bool disableFinishButton = false; bool showPassword = false; Server get server { return ServersProvider.instance.servers.firstWhere( (s) => s.ip == widget.serverIp && s.port == widget.serverPort, orElse: () => Server.dump( ip: widget.serverIp, port: widget.serverPort, ), ); } late final hostnameController = TextEditingController(text: server.ip); late final portController = TextEditingController(text: '${server.port}'); late final rtspPortController = TextEditingController(text: '${server.rtspPort}'); late final nameController = TextEditingController(text: server.name); late final usernameController = TextEditingController(text: server.login); late final passwordController = TextEditingController(text: server.password); @override void dispose() { hostnameController.dispose(); portController.dispose(); rtspPortController.dispose(); nameController.dispose(); usernameController.dispose(); passwordController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final theme = Theme.of(context); final loc = AppLocalizations.of(context); return PopScope( canPop: !disableFinishButton, child: Form( key: formKey, child: Column(mainAxisSize: MainAxisSize.min, children: [ Row(children: [ Expanded( flex: 5, child: TextFormField( enabled: !disableFinishButton, validator: (value) { if (value == null || value.isEmpty) { return loc.errorTextField(loc.hostname); } return null; }, controller: hostnameController, autofocus: true, autocorrect: false, enableSuggestions: false, keyboardType: TextInputType.url, textInputAction: TextInputAction.next, style: theme.textTheme.headlineMedium, decoration: InputDecoration( label: Text(loc.hostname), hintText: loc.hostnameExample, border: const OutlineInputBorder(), ), ), ), const SizedBox(width: 16.0), Expanded( flex: 2, child: TextFormField( enabled: !disableFinishButton, validator: (value) { if (value == null || value.isEmpty) { return loc.errorTextField(loc.port); } return null; }, controller: portController, autofocus: true, keyboardType: TextInputType.number, textInputAction: TextInputAction.next, style: theme.textTheme.headlineMedium, decoration: InputDecoration( label: Text(loc.port), hintText: '$kDefaultPort', border: const OutlineInputBorder(), ), ), ), const SizedBox(width: 16.0), Expanded( flex: 2, child: TextFormField( enabled: !disableFinishButton, // https://github.com/bluecherrydvr/unity/issues/182 // validator: (value) { // if (value == null || value.isEmpty) { // return loc.errorTextField(loc.rtspPort); // } // return null; // }, controller: rtspPortController, autofocus: true, keyboardType: TextInputType.number, textInputAction: TextInputAction.next, style: theme.textTheme.headlineMedium, decoration: InputDecoration( label: Text(loc.rtspPort), hintText: '$kDefaultRTSPPort', border: const OutlineInputBorder(), ), ), ), ]), const SizedBox(height: 16.0), TextFormField( enabled: !disableFinishButton, validator: (value) { if (value == null || value.isEmpty) { return loc.errorTextField(loc.serverName); } return null; }, onTap: () => nameTextFieldEverFocused = true, controller: nameController, textCapitalization: TextCapitalization.words, keyboardType: TextInputType.name, textInputAction: TextInputAction.next, style: theme.textTheme.headlineMedium, decoration: InputDecoration( label: Text(loc.serverName), border: const OutlineInputBorder(), ), ), const SizedBox(height: 16.0), Row(children: [ Expanded( child: TextFormField( enabled: !disableFinishButton, validator: (value) { if (value == null || value.isEmpty) { return loc.errorTextField(loc.username); } return null; }, textInputAction: TextInputAction.next, controller: usernameController, style: theme.textTheme.headlineMedium, decoration: InputDecoration( label: Text(loc.username), hintText: loc.usernameHint, border: const OutlineInputBorder(), ), ), ), ]), const SizedBox(height: 16.0), Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: TextFormField( enabled: !disableFinishButton, validator: (value) { if (value == null || value.isEmpty) { return loc.errorTextField(loc.password); } return null; }, controller: passwordController, obscureText: !showPassword, style: theme.textTheme.headlineMedium, textInputAction: TextInputAction.done, decoration: InputDecoration( label: Text(loc.password), border: const OutlineInputBorder(), suffixIcon: Padding( padding: const EdgeInsetsDirectional.only(end: 8.0), child: Tooltip( message: showPassword ? loc.hidePassword : loc.showPassword, child: InkWell( borderRadius: BorderRadius.circular(8.0), child: Icon( showPassword ? Icons.visibility : Icons.visibility_off, size: 22.0, ), onTap: () => setState( () => showPassword = !showPassword, ), ), ), ), ), onFieldSubmitted: (_) => update(), ), ), ]), const SizedBox(height: 16.0), Align( alignment: AlignmentDirectional.bottomEnd, child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [ MaterialButton( onPressed: !disableFinishButton ? () => Navigator.of(context).pop(context) : null, child: Padding( padding: const EdgeInsetsDirectional.all(8.0), child: Text(loc.cancel), ), ), const SizedBox(width: 8.0), FilledButton( onPressed: disableFinishButton ? null : update, child: Padding( padding: const EdgeInsetsDirectional.all(8.0), child: Text(loc.finish.toUpperCase()), ), ), ]), ), ]), ), ); } Future<void> update() async { if (formKey.currentState?.validate() ?? false) { if (mounted) setState(() => disableFinishButton = true); final serverCopy = server.copyWith( ip: hostnameController.text, port: int.parse(portController.text), rtspPort: int.parse(rtspPortController.text), name: nameController.text, login: usernameController.text, password: passwordController.text, ); await updateServer(context, serverCopy); if (mounted) setState(() => disableFinishButton = false); } } }
import { z } from "zod"; const amenitySchema = z.object({ id: z.number(), name: z.string(), description: z.string(), category: z.string(), }); export type Amenity = z.infer<typeof amenitySchema>; export const amenitiesData: Amenity[] = [ { id: 1, name: "Acid-resistant coatings", description: "Protects spacecraft surfaces from harsh chemical environments.", category: "standard", }, { id: 2, name: "Solar energy propulsion", description: "Provides efficient and sustainable propulsion using solar energy.", category: "standard", }, { id: 3, name: "Cosmic radiation shielding", description: "Shields occupants from harmful cosmic rays and solar radiation.", category: "standard", }, { id: 4, name: "All-terrain capability", description: "Enables navigation across diverse planetary surfaces and terrains.", category: "standard", }, { id: 5, name: "Controlled environment agriculture modules", description: "Supports sustainable growth of crops in controlled conditions.", category: "standard", }, { id: 6, name: "High-definition navigation cameras", description: "Offers precise and high-resolution imaging for navigation and exploration.", category: "standard", }, { id: 7, name: "Storm navigation system", description: "Advanced systems for navigating through severe planetary storms.", category: "standard", }, { id: 8, name: "Emergency shelters", description: "Provides safe havens in case of environmental hazards or failures.", category: "standard", }, { id: 9, name: "Warp drive", description: "Facilitates faster-than-light travel between star systems.", category: "standard", }, { id: 10, name: "Quantum entanglement communication", description: "Enables instant communication across infinite distances without delay.", category: "standard", }, { id: 11, name: "Geothermal energy harnessing", description: "Utilizes planetary heat sources for energy production.", category: "standard", }, { id: 12, name: "Zero-gravity art studios", description: "Creative spaces designed for art creation in zero-gravity environments.", category: "premium", }, { id: 13, name: "Gourmet space cuisine", description: "Offers a high-end dining experience with dishes prepared by renowned space chefs.", category: "premium", }, { id: 14, name: "Floating gardens", description: "Beautifully designed aerial gardens that use minimal gravity to float.", category: "premium", }, { id: 15, name: "Panoramic observatory for sky viewing", description: "Provides expansive views of the cosmos through large-scale observatories.", category: "premium", }, { id: 16, name: "Luxury passenger cabin with viewing windows", description: "Spacious and luxurious cabins equipped with large windows for spectacular views.", category: "premium", }, { id: 17, name: "Observatory dome", description: "A dome-shaped observatory offering 360-degree views of the surrounding space.", category: "premium", }, { id: 18, name: "AI-guided educational tours", description: "Interactive tours led by advanced AI, offering educational content about the surroundings.", category: "premium", }, { id: 19, name: "Zero-gravity gym", description: "A gym equipped to handle physical fitness routines in a zero-gravity environment.", category: "premium", }, { id: 20, name: "Luxury survival suits", description: "High-tech suits designed for comfort and survival in harsh space conditions.", category: "premium", }, { id: 21, name: "Multi-species habitation modules", description: "Living modules designed to accommodate various alien species comfortably.", category: "premium", }, { id: 22, name: "Holodeck", description: "An advanced virtual reality space where users can simulate virtually any experience.", category: "premium", }, ];
import React, { useEffect } from "react"; import { useSelector } from "react-redux"; import clsx from "clsx"; import moment from "moment"; import "moment/locale/ko"; import { ko } from "date-fns/esm/locale"; // Material UI Components import TextField from "@material-ui/core/TextField"; import Grid from "@material-ui/core/Grid"; import Checkbox from "@material-ui/core/Checkbox"; import FormGroup from "@material-ui/core/FormGroup"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import FormControl from "@material-ui/core/FormControl"; import Button from "@material-ui/core/Button"; import Box from "@material-ui/core/Box"; import IconButton from "@material-ui/core/IconButton"; import HighlightOffIcon from "@material-ui/icons/HighlightOff"; import CircularProgress from "@material-ui/core/CircularProgress"; import Snackbar from "@material-ui/core/Snackbar"; import Alert from "@material-ui/core/Alert"; import Modal from "@material-ui/core/Modal"; import Backdrop from "@material-ui/core/Backdrop"; import Fade from "@material-ui/core/Fade"; import ButtonGroup from "@material-ui/core/ButtonGroup"; import { Divider, Typography } from "@material-ui/core"; import AdapterDateFns from "@material-ui/lab/AdapterDateFns"; import LocalizationProvider from "@material-ui/lab/LocalizationProvider"; import DesktopTimePicker from "@material-ui/lab/DesktopTimePicker"; // Local Component import Api from "../Api"; import { theme, baseStyles, ModalCancelButton, ModalConfirmButton, } from "../styles/base"; import { StoreTimeStyles } from "../styles/custom"; import { DayArr } from "../assets/datas"; interface IList { [key: string]: string; } export default function SetStoreTime01() { const { mt_id, mt_jumju_code } = useSelector((state: any) => state.login); const base = baseStyles(); const classes = StoreTimeStyles(); const [isLoading, setLoading] = React.useState(false); const [lists, setLists] = React.useState<IList[]>([]); const [id, setId] = React.useState(""); const [open, setOpen] = React.useState(false); // 영업시간 삭제 모달 on/off const [openQuestion, setOpenQuestion] = React.useState(false); // 영업시간 적용 범위 질의 모달 on/off const [selectDay, setSelectDay] = React.useState<Array<string>>([]); // 선택 요일 const [startTime, setStartTime] = React.useState<Date | null>(new Date()); // 시작 시간 const [endTime, setEndTime] = React.useState<Date | null>(new Date()); // 마감 시간 const [getDays, setGetDays] = React.useState<Array<string>>([]); // 등록된 요일 const [strValue, setStringValue] = React.useState(""); // getDays의 stringify const checkArr = `["0","1","2","3","4","5","6"]`; // 등록된 값과 비교하기 위한 스트링 데이터 (저장하기 버튼 on/off 유무) // 요일 선택 핸들러 const selectDayHandler = (payload: string) => { const filtered = selectDay.find((day) => day === payload); if (filtered) { const removeObj = selectDay.filter((day) => day !== payload); setSelectDay(removeObj); } else { let result = selectDay.concat(payload); setSelectDay(result); } }; // Toast(Alert) 관리 const [toastState, setToastState] = React.useState({ msg: "", severity: "", }); const [openAlert, setOpenAlert] = React.useState(false); const handleOpenAlert = () => { setOpenAlert(true); }; const handleCloseAlert = () => { setOpenAlert(false); }; // 영업시간 불러오기 const getStoreTime = () => { setLoading(true); const param = { jumju_id: mt_id, jumju_code: mt_jumju_code, mode: "list", }; Api.send("store_service_hour", param, (args: any) => { setLoading(true); let resultItem = args.resultItem; let arrItems = args.arrItems; if (resultItem.result === "Y") { setLists(arrItems); if (arrItems) { let result = arrItems.reduce((acc: any, curr: any, i: number) => { let toArr = curr.st_yoil.split(","); acc.push(toArr); return acc; }, []); let flatArr = result.flat(Infinity); let flatArrSort = flatArr.sort(); // console.log("flatArrSort", flatArrSort); setGetDays(flatArrSort); let stringifyValue = JSON.stringify(flatArrSort); setStringValue(stringifyValue); } else { setGetDays([]); setLists([]); } setLoading(false); } else { setLists([]); setLoading(false); } }); }; // 삭제 전 모달 const handleOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const deleteStoreTimeHandler = (st_idx: string) => { setId(st_idx); handleOpen(); }; // 삭제 처리 const deleteStoreTime = () => { setLoading(true); const param = { jumju_id: mt_id, jumju_code: mt_jumju_code, mode: "delete", st_idx: id, }; Api.send("store_service_hour", param, (args: any) => { setLoading(true); let resultItem = args.resultItem; // let arrItems = args.arrItems; if (resultItem.result === "Y") { handleClose(); setToastState({ msg: "해당 영업시간을 삭제하였습니다.", severity: "success", }); handleOpenAlert(); getStoreTime(); setLoading(false); } else { handleClose(); setToastState({ msg: "해당 영업시간 삭제시 오류가 발생하였습니다.", severity: "error", }); handleOpenAlert(); setLoading(false); } }); }; // 적용 범위 전 체크 핸들러 const checkHandler = () => { if (selectDay.length < 1) { setToastState({ msg: "영업 날짜를 지정해주세요.", severity: "error" }); handleOpenAlert(); } else { setOpenQuestion(true); } }; // 추가 처리 const addStoreTime = (type: string) => { let sortSelectDay = selectDay.sort(); let selectDayFormat = sortSelectDay.join(); let startTimeFormat = moment(startTime, "HH:mm").format("HH:mm"); let endTimeFormat = moment(endTime, "HH:mm").format("HH:mm"); setLoading(true); const param = { jumju_id: mt_id, jumju_code: mt_jumju_code, mode: "update", // mode2: 'all', // '' st_yoil: selectDayFormat, st_stime: startTimeFormat, st_etime: endTimeFormat, RangeType: type, }; Api.send("store_service_hour", param, (args: any) => { setLoading(true); let resultItem = args.resultItem; // let arrItems = args.arrItems; if (resultItem.result === "Y") { handleClose(); setSelectDay([]); setToastState({ msg: "영업시간을 추가하였습니다.", severity: "success", }); handleOpenAlert(); setOpenQuestion(false); getStoreTime(); setLoading(false); } else { handleClose(); setSelectDay([]); setToastState({ msg: "영업시간 추가시 오류가 발생하였습니다.", severity: "error", }); handleOpenAlert(); setOpenQuestion(false); setLoading(false); } }); }; useEffect(() => { getStoreTime(); return () => getStoreTime(); }, [mt_id, mt_jumju_code]); console.log("strValue === ", strValue); console.log("checkArr === ", checkArr); return isLoading ? ( <Box className={base.loadingWrap}> <CircularProgress disableShrink color="primary" style={{ width: 50, height: 50 }} /> </Box> ) : ( <Box component="section"> <Box className={base.alertStyle}> <Snackbar anchorOrigin={{ vertical: "top", horizontal: "center", }} open={openAlert} autoHideDuration={5000} onClose={handleCloseAlert} > <Alert onClose={handleCloseAlert} severity={toastState.severity === "error" ? "error" : "success"} > {toastState.msg} </Alert> </Snackbar> </Box> {/* 영업시간 삭제 모달 */} <Modal aria-labelledby="transition-modal-title" aria-describedby="transition-modal-description" className={base.modal} open={open} // onClose={handleClose} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500, }} > <Fade in={open}> <Box className={clsx(base.modalInner, base.colCenter)}> <h2 id="transition-modal-title" className={base.modalTitle}> 영업시간 삭제 </h2> <p id="transition-modal-description" className={base.modalDescription} > 해당 영업시간을 삭제하시겠습니까? </p> <ButtonGroup variant="text" color="primary" aria-label="text primary button group" > <ModalConfirmButton variant="contained" style={{ boxShadow: "none" }} onClick={deleteStoreTime} > 삭제하기 </ModalConfirmButton> <ModalCancelButton fullWidth variant="outlined" onClick={handleClose} > 취소 </ModalCancelButton> </ButtonGroup> </Box> </Fade> </Modal> {/* // 영업시간 삭제 모달 */} {/* 영업시간 적용 범위 질의 모달 */} <Modal aria-labelledby="transition-modal-title" aria-describedby="transition-modal-description" className={base.modal} open={openQuestion} // onClose={handleClose} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500, }} > <Fade in={openQuestion}> <Box className={clsx(base.modalInner, base.colCenter)}> <h2 id="transition-modal-title" className={base.modalTitle}> 영업시간 적용 범위 </h2> <p id="transition-modal-description" className={base.modalDescription} > 해당 영업시간을 전체 매장에 적용하시겠습니까? </p> <ButtonGroup variant="text" color="inherit" aria-label="text primary button group" > <ModalConfirmButton variant="contained" style={{ boxShadow: "none", backgroundColor: theme.palette.primary.main, color: theme.palette.primary.contrastText, }} onClick={() => addStoreTime("all")} > 전체 매장에 적용 </ModalConfirmButton> <ModalConfirmButton variant="contained" style={{ boxShadow: "none", backgroundColor: theme.palette.info.main, color: theme.palette.info.contrastText, }} onClick={() => addStoreTime("curr")} > 해당 매장만 </ModalConfirmButton> <ModalCancelButton variant="outlined" onClick={() => setOpenQuestion(false)} > 닫기 </ModalCancelButton> </ButtonGroup> </Box> </Fade> </Modal> {/* // 영업시간 적용 범위 질의 모달 */} {lists !== null && lists.length > 0 ? ( <Box component="article" style={{ margin: "30px 0" }}> {lists.map((list, index) => ( <Box key={index}> <Box className={clsx(base.flexRowBetweenCenter)} style={{ margin: "10px 0" }} > <Box className={base.flexRowStartCenter}> <Box className={clsx(base.flexRow, base.mr10)} style={{ minWidth: 200 }} > <p className={base.mr20} style={{ fontSize: 14, padding: "2px 10px", backgroundColor: theme.palette.primary.main, color: theme.palette.primary.contrastText, borderRadius: 5, }} > 매주 </p> <p className={base.mr20}> {list.st_yoil_txt.replaceAll(",", ", ")} </p> </Box> <Typography className={base.mr20} style={{ minWidth: 100 }} >{`시작: ${list.st_stime}`}</Typography> <Typography>{`마감: ${list.st_etime}`}</Typography> </Box> <IconButton color="primary" aria-label="delete" component="span" style={{ alignItems: "flex-end" }} onClick={() => deleteStoreTimeHandler(list.st_idx)} > <HighlightOffIcon color="primary" /> </IconButton> </Box> <Divider /> </Box> ))} </Box> ) : null} <Typography className={clsx(classes.pointTxt, base.mb10)} style={{ margin: "25px 0 10px", color: strValue === checkArr ? "rgba(0, 0, 0, 0.26)" : theme.palette.primary.main, }} > {strValue === checkArr ? "영업 날짜와 시간이 모두 설정되어 있습니다." : "영업 날짜와 시간을 설정하실 수 있습니다."} </Typography> <FormControl component="fieldset" style={{ marginBottom: 20 }}> <FormGroup aria-label="position" row> {DayArr && DayArr.map((day, index) => ( <FormControlLabel key={index} value={day.idx} control={ getDays.find((getDay) => getDay === day.idx) ? ( <Checkbox checked style={{ color: "#e5e5e5" }} /> ) : ( <Checkbox color="primary" /> ) } label={day.ko} labelPlacement="end" onClick={() => { let result = getDays.find((getDay) => getDay === day.idx); if (result) { return false; } else { selectDayHandler(day.idx); } }} disabled={ getDays.find((getDay) => getDay === day.idx) ? true : false } checked={selectDay.includes(day.idx) ? true : false} /> ))} </FormGroup> </FormControl> <Typography className={clsx(classes.pointTxt, base.mb10)} style={{ color: strValue === checkArr ? "rgba(0, 0, 0, 0.26)" : theme.palette.primary.main, }} > 영업 시작시간과 마감시간을 설정해주세요. </Typography> <Grid container spacing={3} className={base.mb20}> <Grid item xs={6}> <LocalizationProvider dateAdapter={AdapterDateFns} locale={ko}> <Box display="flex" flexDirection="row" className={classes.paper}> <Grid container spacing={2}> <Grid item xs={12} md={6}> <DesktopTimePicker label="시작시간" value={startTime} inputFormat="a hh:mm" onChange={(newValue) => { setStartTime(newValue); }} renderInput={(params) => <TextField {...params} />} disabled={strValue === checkArr ? true : false} /> </Grid> <Grid item xs={12} md={6}> <DesktopTimePicker label="마감시간" value={endTime} inputFormat="a hh:mm" onChange={(newValue) => { setEndTime(newValue); }} renderInput={(params) => <TextField {...params} />} disabled={strValue === checkArr ? true : false} /> </Grid> </Grid> </Box> </LocalizationProvider> </Grid> </Grid> {/* <p>영업시간은 사용자앱에서 주문할 수 있는 시간과 연동됩니다.</p> */} {strValue === checkArr ? ( <Button className={classes.button} variant="contained" style={{ height: 50 }} disableElevation disabled > 저장하기 </Button> ) : ( <Button className={classes.button} variant="contained" style={{ backgroundColor: theme.palette.primary.main, color: "#fff", height: 50, }} disableElevation onClick={checkHandler} > 저장하기 </Button> )} </Box> ); }
package com.example.newsapp.presentation.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.newsapp.R import com.example.newsapp.models.Article class NewsAdapter : RecyclerView.Adapter<NewsAdapter.NewsViewHolder>() { inner class NewsViewHolder(view: View) : RecyclerView.ViewHolder(view) { val articleImage = view.findViewById<ImageView>(R.id.article_image) val articleTitle = view.findViewById<TextView>(R.id.article_title) val articleDate = view.findViewById<TextView>(R.id.article_date) } private val callback = object : DiffUtil.ItemCallback<Article>() { override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean { return oldItem.url == newItem.url } override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean { return oldItem == newItem } } val differ = AsyncListDiffer(this, callback) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder { return NewsViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.item_article, parent, false) ) } override fun getItemCount(): Int { return differ.currentList.size } override fun onBindViewHolder(holder: NewsViewHolder, position: Int) { val article = differ.currentList[position] holder.itemView.apply { Glide.with(this).load(article.urlToImage).into(holder.articleImage) holder.articleImage.clipToOutline = true holder.articleTitle.text = article.title holder.articleDate.text = article.publishedAt } } private var onItemClickListener: ((Article) -> Unit)? = null fun setOnItemClickListener(listener: (Article) -> Unit) { onItemClickListener = listener } }
import { Loading, LocalStorage, Notify } from 'quasar' import { errorHandler } from '../handlers/error' import { useRouter } from 'vue-router' import { api } from 'boot/axios' import { useAppStore } from '../stores/app.store' import { useProfileStore } from '../stores/profile.store' export class AuthController { // private router = useRouter() private appStore = useAppStore() private profileStore = useProfileStore() async register(form: {}) { Loading.show() api.post('auth/register', form) .then(({ data }) => { this.setData(data) }) .catch(e => errorHandler(e)) } async login(form: {}) { Loading.show() api.post('auth/login', form) .then(({ data }) => { this.setData(data) Loading.hide() }) .catch(e => { Loading.hide() if (e.response.status == 401) { Notify.create({ type: 'negative', message: 'The email or password your entered is incorrect.' }) } else if (e.response.status == 403) { Notify.create({ type: 'negative', message: 'No account found associated with this email.' }) } else { Notify.create({ type: 'negative', message: 'Oops, something went wrong. Please try again later.' }) } }) } async setData(data: any) { const { profile, token, user, company } = data user.isSignedIn = true this.profileStore.setProfile(profile) this.appStore.user = user company ? (this.appStore.company = company) : null LocalStorage.set('access_token', token) api.defaults.headers.common['Authorization'] = `Bearer ${token}` await this.router.push({ name: 'dashboard' }) Loading.hide() } async logOut() { Loading.show() try { await api.get('auth/logout') this.appStore.clear() localStorage.clear() await this.router.push({ name: 'login' }) Loading.hide() } catch (error) { Loading.hide() errorHandler(error) } Loading.hide() } // async getSession(){ // } }
# This file was last updated April 19 # This code does not need any input to run. # The output of this code is used in compare_pMSE_utility.R # This code creates synthetic versions of simulated data using # KNG methods, pMSE mechanism, and non-private quantile regression. # The simulated data consists of 3 variables (x1, x2, and x3) # and 5000 observations. # The code for pMSE mechanism is adapted from "pMSE Mechanism: # Differentially Private Synthetic Data with Maximal Distributional # Similarity" (Snoke and Slavković, 2018). rm(list = ls()) ## pMSE mechanism # Note: Based on the current set up synParam[1, 4, 8] are rates # and need to be positive, hence the abs(). densitySamp = function(synParam, ep, origData, nSyn, nVar, nObs, lambda){ synParam[c(1, 4, 8)] = abs(synParam[c(1, 4, 8)]) util = getPMSE_multivar(origData, synParam, nSyn, nVar, nObs) return(- (sum(synParam ^ 2 / (2 * lambda))) - (nObs * ep * util[1] / 2)) ## multivariate normal prior, diag. sigma, fixed var. } getPMSE_multivar = function(origData, synParam, nSyn, nVar, nObs){ synX = vector("list", nSyn) pmse = rep(NA, nSyn) for(a in 1:nSyn){ synX[[a]] = syn_data(synParam, nVar, nObs) combData = data.frame(cbind(rbind(origData, synX[[a]]), rep(0:1, each = nrow(origData)))) combData[, nVar + 1] = as.factor(combData[, nVar + 1]) colnames(combData) = c(paste("var", 1:nVar, sep = ""), "Y") # nonsubsampling testUtil = rpart(Y ~ ., data = combData, method = "class", control = rpart.control(maxdepth = 5, cp = 0.01, minsplit = 2, minbucket = 1, maxsurrogate = 0)) testProp = predict(testUtil)[, 2] pmse[a] = sum((testProp - 0.5) ^ 2) / nrow(combData) } output = c(mean(pmse), var(pmse)) return(output) } # Note: this function may not be generalizable beyond 3 variables, depending on # the simulated data setup. Double check param set up before making changes. syn_data = function(param, nVar, nObs){ x = matrix(NA, nrow = nObs, ncol = nVar) paramCount = 0 for(a in 1:nVar){ if(a == 1){ x[, 1] = rexp(nObs, param[1]) } else{ x[, a] = syn_exp(param[(1 + paramCount):(paramCount + a + 1)], x[, 1:(a - 1), drop = F], nObs) } if (a == 1){ paramCount = paramCount + a } else { paramCount = paramCount + a + 1 } } return(x) } syn_exp = function(param, pred_mat, nObs){ output = cbind(1, pred_mat) %*% param[-length(param)] + rexp(nObs, param[length(param)]) return(output) } ## implementation of KNG (Reimherr and Awan, 2019) originalKNG = function(data, total_eps, tau, nbatch = 10000, scale = 1e-4, lower_accept = 0, upper_accept = 1, Cx, formula = NULL, update_after = 10, adjust_scale_by = 2){ ep = total_eps/length(tau) i = ncol(data) Y = data[,i] R = max(abs(Y)) Y = Y/R X = as.matrix(cbind(rep(1, nrow(data)), data)) X = as.matrix(X[, -ncol(X)]) X[X > Cx] = Cx sumX = apply(X = X, 2, FUN = sum) m = ncol(X) - 1 accept_rate = rep(NA, length(tau)) scale_output = rep(NA, length(tau)) ans = NA for (i in 1:length(tau)){ curr_scale = scale[i] temp = KNG(init = rep(0, ncol(X)), ep = ep, tau = tau[i], sumX = sumX, X = X, Y = Y, Cx = Cx, nbatch = nbatch, scale = scale/R, lower_accept = lower_accept, upper_accept = upper_accept, update_after = update_after, adjust_scale_by = adjust_scale_by) ans = cbind(ans, t(tail(temp[[1]], 1)*R)) scale_output[i] = tail(temp[[3]], 1) accept_rate[i] = temp[[2]] } ans = ans[, -1] return(list(ans, scale_output, accept_rate)) } # this function is used to get synthetic values from a vector of randomly # selected quantiles syndata = function(beta_result, x, select_quantile){ allsyn = x%*%beta_result coord = cbind(c(1:nrow(x)), select_quantile) ans = allsyn[coord] return(ans) } compare_methods = function(data1, holdout_dat = holdout_dat, tau = c(seq(0.01, 0.47, 0.02), 0.5, seq(0.53, 0.99, 0.02)), main_tau = c(0.01, 0.05, 0.25, 0.5, 0.75, 0.95, 0.99), n = 5000, toteps = 1, runs = 1000){ vars = c("x1", "x2", "x3") ## find synthetic data using pMSE mechnism # check is the mcmc acceptance rate and is used to ensure it moves around check = 0 while(check == 0){ pmse = mcmc::metrop(densitySamp, initial = c(1e-4, 4, 3, 1e-4, 3, 2, 1, 1e-4), nbatch = 100, scale = 0.4, ep = toteps, origData = data1, nSyn = 25, nVar = length(vars), nObs = n, lambda = 100000) check = pmse$accept } # generate data from the last iteration of the mcmc pmse_res = tail(pmse$batch, 1) pmse_res[, c(1, 4, 8)] = abs(pmse_res[, c(1, 4, 8)]) syn_pmse = syn_data(pmse_res, length(vars), n) ## generate synthetic data using KNG methods and non-private quantile regression # we will generate synthetic x1 first, then x2, and finally x3 for (k in 1:length(vars)){ syn_var = vars[k] print(syn_var) if (syn_var == "x1"){ # we allocate more eps to x1 as it can be more bumpy (due to having on 49 # possible values) and it is used to generate x2 and x3 ep = 0.5 # set formula fml = "x1 ~ 1" # subset data data = as.data.frame(data1[, 1]) colnames(data) = "x1" all_beta = list() # generate private quantiles using KNG mechanism temp = originalKNG(data = data, total_eps = ep, tau = tau, nbatch = runs, scale = 0.01, Cx = 1, formula = fml) all_beta[[1]] = temp[[1]] # generate private quantiles using stepwise fixed slope KNG temp = stepwiseKNG(data = data, total_eps = ep, median_eps = 0.25, Cx = 1, tau = tau, scale = 0.025, nbatch = runs, method = "fixed", lb = 0, ub = 1000, formula = fml) all_beta[[2]] = temp[[1]] # generate private quantiles using stepwise varying slope KNG temp = stepwiseKNG(data = data, total_eps = ep, median_eps = 0.25, Cx = 1, tau = tau, scale = 0.025, nbatch = runs, method = "varying", lb = 0, ub = 1000, formula = fml) all_beta[[3]] = temp[[1]] # generate private quantiles using sandwich fixed slope KNG temp = sandwichKNG(data = data, total_eps = ep, median_eps = 0.25, Cx = 1, main_tau_eps = 0.6, tau = tau, main_tau = main_tau, scale = 0.1, sw_scale = 0.03, nbatch = runs, method = "fixed", lb = 0, ub = 1000, formula = fml) all_beta[[4]] = temp[[1]] # generate private quantiles using sandwich varying slope KNG temp = sandwichKNG(data = data, total_eps = ep, median_eps = 0.25, Cx = 1, main_tau_eps = 0.6, tau = tau, main_tau = main_tau, scale = 0.1, sw_scale = 0.03, nbatch = runs, method = "varying", lb = 0, ub = 1000, formula = fml) all_beta[[5]] = temp[[1]] all_beta[[6]] = coef(rq(x1 ~ 1, tau, data = data)) # generate non-private quantiles using quantile regression all_beta[[6]] = coef(rq(x1 ~ 1, tau, data = data)) # generate synthetic data using randomly selected quantiles # we sample quantiles using different probabilities because # the quantiles are not evenly spaced out X = rep(list(matrix(1, nrow = n)), 6) synx1 = mapply(syndata, beta_result = all_beta, x = X, MoreArgs = list(sample(1:length(tau), n, replace = TRUE, prob = c(0.01, rep(0.02, 23), 0.03, 0.03, rep(0.02, 22), 0.03))), SIMPLIFY = FALSE) # synall is the final output synall = synx1 # plotting synthetic data out can help with tuning the scales # synx1[[7]] = c(data[,1]) # synx1[[8]] = syn_pmse[,1] # names(synx1) = c("KNG", "Stepwise-Fixed Slope", "Stepwise-Varying Slope", # "Sandwich-Fixed Slope", "Sandwich-Varying Slope", "Non-Private", # "Raw Data", "pMSE Mechanism") # for (i in 1:5){ # plotdata = melt(synx1[c(i, 6, 7)]) # print(ggplot(plotdata,aes(x=value, fill= L1)) + geom_density(alpha=0.51, bw = 2)) # # } } else { # for x2 and x3, the eps used is 0.25 ep = 0.25 # subset data and specify model depending on whether the synthesizing variable # is x2 or x3 if (syn_var == "x2"){ data = data = as.data.frame(data1[, c(1, 2)]) colnames(data) = c("x1", "x2") mod = "x2 ~ x1" Cx = 46 ub = 1000 } else { data = as.data.frame(data1) mod = "x3 ~ x1 + x2" Cx = 106 ub = 2000 } all_beta = list() # generate private coef (beta) using the KNG mechanism (Reimherr and Awan, 2019) temp = originalKNG(data = data, total_eps = ep, tau = tau, nbatch = runs, scale = 1e-5, Cx = Cx, formula = mod) all_beta[[1]] = temp[[1]] temp = stepwiseKNG(data = data, total_eps = ep, median_eps = 0.6, #0.003 tau = tau, scale = 0.01, nbatch = runs, method = "fixed", lb = 0, ub = ub, Cx = Cx, formula = mod, check_data = synall[[2]]) all_beta[[2]] = temp[[1]] temp = stepwiseKNG(data = data, total_eps = ep, median_eps = 0.8, #0.003 tau = tau, scale = 6e-6, nbatch = runs, method = "varying", lb = 0, ub = ub, Cx = Cx, formula = mod, check_data = synall[[3]]) all_beta[[3]] = temp[[1]] temp = sandwichKNG(data = data, total_eps = ep, median_eps = 0.6, main_tau_eps = 0.7, tau = tau, main_tau = main_tau, scale = 0.05, sw_scale = 0.01, nbatch = runs, method = "fixed", lb = 0, check_data = synall[[4]], ub = ub, Cx = Cx, formula = mod) all_beta[[4]] = temp[[1]] temp = sandwichKNG(data = data, total_eps = ep, median_eps = 0.8, main_tau_eps = 0.8, tau = tau, main_tau = main_tau, scale = 3e-5, sw_scale = 9e-6, nbatch = runs, method = "varying", lb = 0, ub = ub, Cx = Cx, formula = mod, check_data = synall[[5]]) all_beta[[5]] = temp[[1]] # generate private coef (beta) using quantile regression all_beta[[6]] = coef(rq(mod, tau, data = data)) # generate synthetic data using randomly selected quantiles # we sample the quantiles with different probability due to them not # being evenly spaced X = mapply(cbind, rep(list(matrix(1, nrow = n)), 6), synall, SIMPLIFY = FALSE) syn = mapply(syndata, beta_result = all_beta, x = X, MoreArgs = list(sample(1:length(tau), n, replace = TRUE, prob = c(0.01, rep(0.02, 23), 0.03, 0.03, rep(0.02, 22), 0.03))), SIMPLIFY = FALSE) # bind the data to the final output synall = mapply(cbind, synall, syn, SIMPLIFY = FALSE) # ploting the synthetic data can help tune the scales. # syn[[7]] = data[, k] # syn[[8]] = syn_pmse[, k] # names(syn) = c("KNG", "Stepwise-Fixed Slope", "Stepwise-Varying Slope", # "Sandwich-Fixed Slope", "Sandwich-Varying Slope", "Non-Private", # "Raw Data", "pMSE Mechanism") # # for (i in 1:5){ # plotdata = melt(syn[c(i, 6, 7)]) # print(ggplot(plotdata,aes(x=value, fill= L1)) + geom_density(alpha=0.51)) # } } } # synall, the final output, is a list of 9. The order of synall is KNG, stepwise # fixed slope KNG, stepwise varying slope KNG, sandwich fixed slope KNG, sandwich # varying slope kNG, non-private, pMSE mechanism, training data (data used to generate # synthetic data), and finally testing (holdout) data synall[[7]] = syn_pmse synall[[8]] = data1 synall[[9]] = holdout_dat synall_name = lapply(synall, `colnames<-`, vars) return(synall_name) } # parallel code to speed up the run time library(doParallel) num_cores=detectCores()-1 # use all available core but 1 workers=makeCluster(num_cores,type="SOCK",outfile="log.txt") registerDoParallel(workers) # run 100 reps, the ith rep is run with seed i oper <- foreach(i=1:100, .combine=rbind, .multicombine=TRUE, .init=list()) %dopar% { source("functions_final.R") library(rmutil) library(rpart) library(mcmc) library(quantreg) library(reshape2) library(ggplot2) set.seed(i) # create training and testing data with 5000 obs each # x1 = rexp(0.1) # x2 = 4 + 3x1 + rexp(0.1) # x3 = 3 + 2x1 + x2 + rexp(0.1) n = 5000 data1 = syn_data(param = c(0.1, 4, 3, 0.1, 3, 2, 1, 0.1), nVar = 3, nObs = n*2) vars = c("x1", "x2", "x3") colnames(data1) = vars # randomly sample training and hold out data holdout = sample(1:nrow(data1), n) holdout_dat = data1[holdout, ] data1 = data1[-holdout, ] # get synthetic data for all methods out = compare_methods(data1 = data1, holdout_dat = holdout_dat, toteps = 1) } stopCluster(workers) save(oper, file = "../output/simulation_data_eps1.Rdata")
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireCommonComponents final class EmojiDataSource: NSObject, UICollectionViewDataSource { // MARK: - Properties let cellProvider: CellProvider private let initialSections: [Section] private var sections: [Section] private let recentlyUsed: RecentlyUsedEmojiSection private let emojiRepository: EmojiRepositoryInterface var sectionTypes: [EmojiSectionType] { return sections.map(\.id) } // MARK: - Life cycle init( provider: @escaping CellProvider, emojiRepository: EmojiRepositoryInterface = EmojiRepository() ) { cellProvider = provider self.emojiRepository = emojiRepository let smileysAndEmotion = emojiRepository.emojis(for: .smileysAndEmotion) let peopleAndBody = emojiRepository.emojis(for: .peopleAndBody) let animalsAndNature = emojiRepository.emojis(for: .animalsAndNature) let foodAndDrink = emojiRepository.emojis(for: .foodAndDrink) let activities = emojiRepository.emojis(for: .activities) let travelAndPlaces = emojiRepository.emojis(for: .travelAndPlaces) let objects = emojiRepository.emojis(for: .objects) let symbols = emojiRepository.emojis(for: .symbols) let flags = emojiRepository.emojis(for: .flags) initialSections = [ Section(id: .people, items: smileysAndEmotion + peopleAndBody), Section(id: .nature, items: animalsAndNature), Section(id: .food, items: foodAndDrink), Section(id: .activities, items: activities), Section(id: .travel, items: travelAndPlaces), Section(id: .objects, items: objects), Section(id: .symbols, items: symbols), Section(id: .flags, items: flags) ] recentlyUsed = RecentlyUsedEmojiSection( capacity: 15, items: emojiRepository.fetchRecentlyUsedEmojis() ) sections = initialSections super.init() insertRecentlyUsedSectionIfNeeded() } // MARK: - Helpers subscript (index: Int) -> Section { return sections[index] } subscript (indexPath: IndexPath) -> Emoji { return sections[indexPath.section].items[indexPath.item] } func sectionIndex(for id: EmojiSectionType) -> Int? { return sections.firstIndex { $0.id == id } } // MARK: - Data source func numberOfSections(in collectionView: UICollectionView) -> Int { return sections.count } func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int ) -> Int { return sections[section].items.count } func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { return cellProvider(self[indexPath], indexPath) } // MARK: - Filter func filterEmojis(withQuery query: String) { guard !query.isEmpty else { sections = initialSections insertRecentlyUsedSectionIfNeeded() return } let lowercasedQuery = query.lowercased() sections = initialSections.compactMap { $0.filteredBySearchQuery(lowercasedQuery) } } // MARK: - Recents @discardableResult func register(used emoji: Emoji) -> Update? { let shouldReload = recentlyUsed.register(emoji) let shouldInsert = insertRecentlyUsedSectionIfNeeded() defer { emojiRepository.registerRecentlyUsedEmojis(recentlyUsed.items.map(\.value)) } switch (shouldInsert, shouldReload) { case (true, _): return .insert(0) case (false, true): return .reload(0) default: return nil } } @discardableResult func insertRecentlyUsedSectionIfNeeded() -> Bool { guard let first = sections.first, !(first is RecentlyUsedEmojiSection), !recentlyUsed.items.isEmpty else { return false } sections.insert(recentlyUsed, at: 0) return true } } extension EmojiDataSource { typealias CellProvider = (Emoji, IndexPath) -> UICollectionViewCell enum Update { case insert(Int) case reload(Int) } class Section { let id: EmojiSectionType var items: [Emoji] init( id: EmojiSectionType, items: [Emoji] ) { self.id = id self.items = items } func filteredBySearchQuery(_ query: String) -> Section? { guard !query.isEmpty else { return self } let filteredItems = items.filter { $0.matchesSearchQuery(query) } guard !filteredItems.isEmpty else { return nil } return Section( id: id, items: filteredItems ) } } } enum EmojiSectionType: Int, CaseIterable { case recent case people case nature case food case travel case activities case objects case symbols case flags var icon: StyleKitIcon { switch self { case .recent: return .clock case .people: return .emoji case .nature: return .flower case .food: return .cake case .travel: return .car case .activities: return .ball case .objects: return .crown case .symbols: return .asterisk case .flags: return .flag } } var imageAsset: ImageAsset { switch self { case .recent: return Asset.Images.recents case .people: return Asset.Images.smileysPeople case .nature: return Asset.Images.animalsNature case .food: return Asset.Images.foodDrink case .travel: return Asset.Images.travelPlaces case .activities: return Asset.Images.activity case .objects: return Asset.Images.objects case .symbols: return Asset.Images.symbols case .flags: return Asset.Images.flags } } }
#!/usr/bin/env python # coding: utf-8 # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') from pylab import * from sci378 import * from sci378.stats import * # http://doingbayesiandataanalysis.blogspot.com/2013/06/bayesian-robust-regression-for-anscombe.html # # https://en.wikipedia.org/wiki/Anscombe%27s_quartet # In[2]: xy1=""" X Y 10 8.04 8 6.95 13 7.58 9 8.81 11 8.33 14 9.96 6 7.24 4 4.26 12 10.84 7 4.82 5 5.68 """ # In[3]: xy2=""" X Y 10 9.14 8 8.14 13 8.74 9 8.77 11 9.26 14 8.1 6 6.13 4 3.1 12 9.13 7 7.26 5 4.74 """ # In[4]: xy3=""" X Y 10 7.46 8 6.77 13 12.74 9 7.11 11 7.81 14 8.84 6 6.08 4 5.39 12 8.15 7 6.42 5 5.73 """ # In[5]: xy4=""" X Y 8 6.58 8 5.76 8 7.71 8 8.84 8 8.47 8 7.04 8 5.25 19 12.5 8 5.56 8 7.91 8 6.89 """ # In[6]: for i,xy in enumerate([xy1,xy2,xy3,xy4]): subplot(2,2,i+1) x,y=array([_.split() for _ in xy.strip().split('\n')[1:]],dtype=float).T plot(x,y,'o') # ## Linear Regression # In[7]: def lnlike(data,m,b,sigma): x,y=data model = m * x + b return lognormalpdf(model-y,0,sigma) # In[8]: xy=xy1 x,y=array([_.split() for _ in xy.strip().split('\n')[1:]],dtype=float).T data=x,y model=MCMCModel(data,lnlike, m=Normal(0,10), b=Normal(0,10), sigma=Jeffreys(), ) # In[9]: model.run_mcmc(400,repeat=3,verbose=True) model.plot_chains() # In[10]: model.plot_distributions() # In[11]: figure(figsize=(12,12)) for i,xy in enumerate([xy1,xy2,xy3,xy4]): subplot(2,2,i+1) x,y=array([_.split() for _ in xy.strip().split('\n')[1:]],dtype=float).T data=x,y model=MCMCModel(data,lnlike, m=Normal(0,10), b=Normal(0,10), sigma=Jeffreys(), ) model.run_mcmc(400,repeat=3) plot(x,y,'o') xl=gca().get_xlim() xx=linspace(xl[0],xl[1],100) for m,b in model.sample_iterator('m','b'): yy=m*xx+b plot(xx,yy,'g-',alpha=0.002) m,b=model.best_estimates()['m'][1],model.best_estimates()['b'][1] yy=m*xx+b plot(xx,yy,'g-') S=[] for key,label in zip(['m','b'],['m','b']): i=model.index[key] v=np.percentile(model.samples[:,i], [2.5, 50, 97.5],axis=0) S.append(r'$\hat{%s}^{97.5}_{2.5}=%.3f^{%.3f}_{%.3f}$' % (label,v[1],v[2],v[0])) title(",".join(S),fontsize=12) # ## Robust Linear Regression # # In[7]: def logtpdf(x,df,mu,sd): try: N=len(x) except TypeError: N=1 t=(x-mu)/float(sd) return N*(gammaln((df+1)/2.0)-0.5*log(df*np.pi)-gammaln(df/2.0)-np.log(sd))+(-(df+1)/2.0)*sum(np.log(1+t**2/df)) def lnlike(data,m,b,sigma,nu): x,y=data model = m * x + b return sum(logtpdf(y,nu,model,sigma)) # In[8]: models=[] figure(figsize=(12,12)) for i,xy in enumerate([xy1,xy2,xy3,xy4]): subplot(2,2,i+1) x,y=array([_.split() for _ in xy.strip().split('\n')[1:]],dtype=float).T data=x,y model=MCMCModel(data,lnlike, m=Normal(0,10), b=Normal(0,10), sigma=Jeffreys(), nu=Exponential(1/29), ) model.run_mcmc(400,repeat=3) models.append(model) plot(x,y,'o') xl=gca().get_xlim() xx=linspace(xl[0],xl[1],100) for m,b in model.sample_iterator('m','b'): yy=m*xx+b plot(xx,yy,'g-',alpha=0.002) m,b=model.best_estimates()['m'][1],model.best_estimates()['b'][1] yy=m*xx+b plot(xx,yy,'g-') S=[] for key,label in zip(['m','b','nu'],['m','b','ν']): i=model.index[key] v=np.percentile(model.samples[:,i], [2.5, 50, 97.5],axis=0) S.append(r'$\hat{%s}^{97.5}_{2.5}=%.3f^{%.3f}_{%.3f}$' % (label,v[1],v[2],v[0])) title(",".join(S),fontsize=12) # ## Add a 2nd order term with robust regression # In[9]: def logtpdf(x,df,mu,sd): try: N=len(x) except TypeError: N=1 t=(x-mu)/float(sd) return N*(gammaln((df+1)/2.0)-0.5*log(df*np.pi)-gammaln(df/2.0)-np.log(sd))+(-(df+1)/2.0)*sum(np.log(1+t**2/df)) def lnlike(data,a,b,c,sigma,nu): x,y=data model = a*x**2+b*x+c return sum(logtpdf(y,nu,model,sigma)) # In[10]: models=[] figure(figsize=(12,12)) for i,xy in enumerate([xy1,xy2,xy3,xy4]): subplot(2,2,i+1) x,y=array([_.split() for _ in xy.strip().split('\n')[1:]],dtype=float).T data=x,y model=MCMCModel(data,lnlike, a=Normal(0,10), b=Normal(0,10), c=Normal(0,10), sigma=Jeffreys(), nu=Exponential(1/29), ) model.run_mcmc(400,repeat=3) models.append(model) plot(x,y,'o') xl=gca().get_xlim() xx=linspace(xl[0],xl[1],100) for a,b,c in model.sample_iterator('a','b','c'): yy=a*xx**2+b*xx+c plot(xx,yy,'g-',alpha=0.002) S=[] for key,label in zip(['a','b','c','nu'],['a','b','c','ν']): i=model.index[key] v=np.percentile(model.samples[:,i], [2.5, 50, 97.5],axis=0) S.append(r'$\hat{%s}^{97.5}_{2.5}=%.3f^{%.3f}_{%.3f}$' % (label,v[1],v[2],v[0])) title(",".join(S),fontsize=12) # In[13]: models[2].plot_distributions() # In[ ]:
/* * MIT License * * Copyright (c) 2021 CSCS, ETH Zurich * 2021 University of Basel * * 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. */ /*! @file * @brief implements a bounding bounding box for floating point coordinates and integer indices * * @author Sebastian Keller <sebastian.f.keller@gmail.com> */ #pragma once #include <cassert> #include <cmath> #include "../util/annotation.hpp" #include "../util/array.hpp" #include "../util/tuple.hpp" #include "bitops.hpp" namespace cstone { template<class T> using Vec3 = util::array<T, 3>; template<class T> using Vec4 = util::array<T, 4>; enum class BoundaryType : char { open = 0, periodic = 1, fixed = 2 }; //! @brief stores the coordinate bounds template<class T> class Box { public: HOST_DEVICE_FUN constexpr Box(T xyzMin, T xyzMax, BoundaryType b = BoundaryType::open) : limits{xyzMin, xyzMax, xyzMin, xyzMax, xyzMin, xyzMax} , lengths_{xyzMax - xyzMin, xyzMax - xyzMin, xyzMax - xyzMin} , inverseLengths_{T(1.) / (xyzMax - xyzMin), T(1.) / (xyzMax - xyzMin), T(1.) / (xyzMax - xyzMin)} , boundaries{b, b, b} { } HOST_DEVICE_FUN constexpr Box(T xmin, T xmax, T ymin, T ymax, T zmin, T zmax, BoundaryType bx = BoundaryType::open, BoundaryType by = BoundaryType::open, BoundaryType bz = BoundaryType::open) : limits{xmin, xmax, ymin, ymax, zmin, zmax} , lengths_{xmax - xmin, ymax - ymin, zmax - zmin} , inverseLengths_{T(1.) / (xmax - xmin), T(1.) / (ymax - ymin), T(1.) / (zmax - zmin)} , boundaries{bx, by, bz} { } HOST_DEVICE_FUN constexpr T xmin() const { return limits[0]; } HOST_DEVICE_FUN constexpr T xmax() const { return limits[1]; } HOST_DEVICE_FUN constexpr T ymin() const { return limits[2]; } HOST_DEVICE_FUN constexpr T ymax() const { return limits[3]; } HOST_DEVICE_FUN constexpr T zmin() const { return limits[4]; } HOST_DEVICE_FUN constexpr T zmax() const { return limits[5]; } //! @brief return edge lengths HOST_DEVICE_FUN constexpr T lx() const { return lengths_[0]; } HOST_DEVICE_FUN constexpr T ly() const { return lengths_[1]; } HOST_DEVICE_FUN constexpr T lz() const { return lengths_[2]; } //! @brief return inverse edge lengths HOST_DEVICE_FUN constexpr T ilx() const { return inverseLengths_[0]; } HOST_DEVICE_FUN constexpr T ily() const { return inverseLengths_[1]; } HOST_DEVICE_FUN constexpr T ilz() const { return inverseLengths_[2]; } HOST_DEVICE_FUN constexpr BoundaryType boundaryX() const { return boundaries[0]; } // NOLINT HOST_DEVICE_FUN constexpr BoundaryType boundaryY() const { return boundaries[1]; } // NOLINT HOST_DEVICE_FUN constexpr BoundaryType boundaryZ() const { return boundaries[2]; } // NOLINT private: HOST_DEVICE_FUN friend constexpr bool operator==(const Box<T>& a, const Box<T>& b) { return a.limits[0] == b.limits[0] && a.limits[1] == b.limits[1] && a.limits[2] == b.limits[2] && a.limits[3] == b.limits[3] && a.limits[4] == b.limits[4] && a.limits[5] == b.limits[5] && a.boundaries[0] == b.boundaries[0] && a.boundaries[1] == b.boundaries[1] && a.boundaries[2] == b.boundaries[2]; } T limits[6]; T lengths_[3]; T inverseLengths_[3]; BoundaryType boundaries[3]; }; //! @brief Compute the shortest periodic distance dX = A - B between two points, template<class T> HOST_DEVICE_FUN inline Vec3<T> applyPbc(Vec3<T> dX, const Box<T>& box) { bool pbcX = (box.boundaryX() == BoundaryType::periodic); bool pbcY = (box.boundaryY() == BoundaryType::periodic); bool pbcZ = (box.boundaryZ() == BoundaryType::periodic); dX[0] -= pbcX * box.lx() * std::rint(dX[0] * box.ilx()); dX[1] -= pbcY * box.ly() * std::rint(dX[1] * box.ily()); dX[2] -= pbcZ * box.lz() * std::rint(dX[2] * box.ilz()); return dX; } /*! @brief stores octree index integer bounds */ template<class T> class SimpleBox { public: HOST_DEVICE_FUN constexpr SimpleBox() : limits{0, 0, 0, 0, 0, 0} { } HOST_DEVICE_FUN constexpr SimpleBox(T xyzMin, T xyzMax) : limits{xyzMin, xyzMax, xyzMin, xyzMax, xyzMin, xyzMax} { } HOST_DEVICE_FUN constexpr SimpleBox(T xmin, T xmax, T ymin, T ymax, T zmin, T zmax) : limits{xmin, xmax, ymin, ymax, zmin, zmax} { } HOST_DEVICE_FUN constexpr T xmin() const { return limits[0]; } // NOLINT HOST_DEVICE_FUN constexpr T xmax() const { return limits[1]; } // NOLINT HOST_DEVICE_FUN constexpr T ymin() const { return limits[2]; } // NOLINT HOST_DEVICE_FUN constexpr T ymax() const { return limits[3]; } // NOLINT HOST_DEVICE_FUN constexpr T zmin() const { return limits[4]; } // NOLINT HOST_DEVICE_FUN constexpr T zmax() const { return limits[5]; } // NOLINT //! @brief return the shortest coordinate range in any dimension HOST_DEVICE_FUN constexpr T minExtent() const // NOLINT { return stl::min(stl::min(xmax() - xmin(), ymax() - ymin()), zmax() - zmin()); } private: HOST_DEVICE_FUN friend constexpr bool operator==(const SimpleBox& a, const SimpleBox& b) { return a.limits[0] == b.limits[0] && a.limits[1] == b.limits[1] && a.limits[2] == b.limits[2] && a.limits[3] == b.limits[3] && a.limits[4] == b.limits[4] && a.limits[5] == b.limits[5]; } HOST_DEVICE_FUN friend bool operator<(const SimpleBox& a, const SimpleBox& b) { return util::tie(a.limits[0], a.limits[1], a.limits[2], a.limits[3], a.limits[4], a.limits[5]) < util::tie(b.limits[0], b.limits[1], b.limits[2], b.limits[3], b.limits[4], b.limits[5]); } T limits[6]; }; using IBox = SimpleBox<int>; /*! @brief calculate floating point 3D center and radius of a and integer box and bounding box pair * * @tparam T float or double * @tparam KeyType 32- or 64-bit unsigned integer * @param ibox integer coordinate box * @param box floating point bounding box * @return the geometrical center and the vector from the center to the box corner farthest from the origin */ template<class KeyType, class T> constexpr HOST_DEVICE_FUN util::tuple<Vec3<T>, Vec3<T>> centerAndSize(const IBox& ibox, const Box<T>& box) { constexpr int maxCoord = 1u << maxTreeLevel<KeyType>{}; // smallest octree cell edge length in unit cube constexpr T uL = T(1.) / maxCoord; T halfUnitLengthX = T(0.5) * uL * box.lx(); T halfUnitLengthY = T(0.5) * uL * box.ly(); T halfUnitLengthZ = T(0.5) * uL * box.lz(); Vec3<T> boxCenter = {box.xmin() + (ibox.xmax() + ibox.xmin()) * halfUnitLengthX, box.ymin() + (ibox.ymax() + ibox.ymin()) * halfUnitLengthY, box.zmin() + (ibox.zmax() + ibox.zmin()) * halfUnitLengthZ}; Vec3<T> boxSize = {(ibox.xmax() - ibox.xmin()) * halfUnitLengthX, (ibox.ymax() - ibox.ymin()) * halfUnitLengthY, (ibox.zmax() - ibox.zmin()) * halfUnitLengthZ}; return {boxCenter, boxSize}; } //! @brief returns the smallest distance vector of point X to box b, 0 if X is in b template<class T> HOST_DEVICE_FUN Vec3<T> minDistance(const Vec3<T>& X, const Vec3<T>& bCenter, const Vec3<T>& bSize) { Vec3<T> dX = abs(bCenter - X) - bSize; dX += abs(dX); dX *= T(0.5); return dX; } //! @brief returns the smallest periodic distance vector of point X to box b, 0 if X is in b template<class T> HOST_DEVICE_FUN Vec3<T> minDistance(const Vec3<T>& X, const Vec3<T>& bCenter, const Vec3<T>& bSize, const Box<T>& box) { Vec3<T> dX = bCenter - X; dX = abs(applyPbc(dX, box)); dX -= bSize; dX += abs(dX); dX *= T(0.5); return dX; } //! @brief returns the smallest distance vector between two boxes, 0 if they overlap template<class T> HOST_DEVICE_FUN Vec3<T> minDistance(const Vec3<T>& aCenter, const Vec3<T>& aSize, const Vec3<T>& bCenter, const Vec3<T>& bSize) { Vec3<T> dX = abs(bCenter - aCenter) - aSize - bSize; dX += abs(dX); dX *= T(0.5); return dX; } //! @brief returns the smallest periodic distance vector between two boxes, 0 if they overlap template<class T> HOST_DEVICE_FUN Vec3<T> minDistance( const Vec3<T>& aCenter, const Vec3<T>& aSize, const Vec3<T>& bCenter, const Vec3<T>& bSize, const Box<T>& box) { Vec3<T> dX = bCenter - aCenter; dX = abs(applyPbc(dX, box)); dX -= aSize; dX -= bSize; dX += abs(dX); dX *= T(0.5); return dX; } } // namespace cstone
extends CharacterBody2D # Initial parameters for ship movement (connected with sliders) var weight = 1 var max_speed = 150.0 / weight var acceleration = 400.0 / weight var deceleration = 100.0 * weight var rotation_speed = 0.1 / weight # REMOVE ROTATION SPEED!! ADD ROTATION_ACCELERATION AND ROTATION_DECELERATION PARAMETERS var friction = 150.0 * weight var max_rotational_velocity = 0.8 / weight const WIND_DIRECTION_DEG = 0 # -90 up, 90 down, 0 right, 180 left const WIND_POWER = 100 var crash_coeff = 0.25 var wind_vector = Vector2.ZERO var config = ConfigFile.new() var calculated_velocity = Vector2.ZERO var movement_direction = Vector2.ZERO # Initial direction where ship is positioned var crash = false const ROTATION_STOP = 0.1 var rotation_velocity = 0 var last_rotation_direction = 0 var rotation_direction_change = false var rotation_before_stop = 0 const MAX_SAVE_SIZE = 3e+7 var input_file : FileAccess var is_recording = false var is_playback = false func _ready(): rotation_degrees = -90 set_scale(Vector2(weight, weight)) # Changes size and parameters of the ship movement_direction = Vector2.from_angle(rotation) create_cfg() ship_parameter_init() var emitter = get_parent() # Main node emitter.record_input.connect(_on_record_pressed) emitter.playback_input.connect(_on_playback_pressed) func _physics_process(delta): ship_movement(delta) ship_rotation(delta) move_and_slide() func ship_movement(delta): # Save which input is pressed, can't allow to press both inputs at the same time var propel_forward = Input.get_axis("move_back", "move_forward") record_input(propel_forward, "UP", "DOWN") if is_playback: if input_file.eof_reached(): emit_signal("end_of_file") else: propel_forward = playback_input("UP", "DOWN") # Move towards where facing if propel_forward: # We move in the last direction that we looked at, either in positive (forward) or negative (backwards) calculated_velocity += movement_direction * propel_forward * acceleration * delta if !crash: calculated_velocity = calculated_velocity.limit_length(max_speed) else: calculated_velocity = calculated_velocity.limit_length(max_speed * crash_coeff) else: # Over time if no input slow down the ship if velocity.length() > (friction * delta): calculated_velocity -= calculated_velocity.normalized() * (deceleration * delta) else: # Stop the ship when fully slowed down calculated_velocity = Vector2.ZERO velocity = calculated_velocity + wind_vector func ship_rotation(delta): var rotation_direction = Input.get_axis("turn_left", "turn_right") # Rotate in the pressed direction record_input(rotation_direction, "RIGHT", "LEFT") if is_playback: if input_file.eof_reached(): end_of_file_reached() else: rotation_direction = playback_input("RIGHT", "LEFT") if rotation_direction: # If you press other direction of rotation, start slowing down, before back to maximum speed if rotation_direction != last_rotation_direction and rotation_direction_change == false: rotation_direction_change = true rotation_before_stop = last_rotation_direction last_rotation_direction = rotation_direction # save last rotation to remember turn if rotation_direction_change == false: if !crash: rotation += rotation_direction * rotational_acceleration(rotation_velocity, max_rotational_velocity, delta) * delta else: rotation += rotation_direction * rotational_acceleration(rotation_velocity, max_rotational_velocity * crash_coeff, delta) * delta else: # start slowing down until back to basic speed if rotation_velocity > ROTATION_STOP: rotation += rotation_before_stop * rotational_deceleration(rotation_velocity, delta) * delta else: rotation_direction_change = false else: # continue movement of rotation when no input if rotation_velocity > 0.0: rotation += last_rotation_direction * rotational_deceleration(rotation_velocity, delta) * delta movement_direction = Vector2.from_angle(rotation) #print(rotation_velocity) # debug func rotational_acceleration(curr_vel, max_velocity, delta): if curr_vel > max_velocity: return max_velocity else: rotation_velocity = curr_vel + (acceleration / 200) * delta return curr_vel func rotational_deceleration(curr_vel, delta): rotation_velocity = curr_vel - (deceleration / 200) * delta return curr_vel func create_cfg(): if FileAccess.file_exists("user://ship.cfg"): return else: config.set_value("Ship_Parameters", "weight", weight) config.set_value("Ship_Parameters", "max_speed", max_speed) config.set_value("Ship_Parameters", "acceleration", acceleration) config.set_value("Ship_Parameters", "deceleration", deceleration) config.set_value("Ship_Parameters", "rotation_speed", rotation_speed) config.set_value("Ship_Parameters", "friction", friction) config.set_value("Ship_Parameters", "max_rotational_velocity", max_rotational_velocity) config.save("user://ship.cfg") func ship_parameter_init(): var err = config.load("user://ship.cfg") if err != OK: return weight = config.get_value("Ship_Parameters", "weight") recalculate_parameters() func record_input(input_matching, input1, input2): if is_recording: var string match input_matching: 1.0: string = input1 -1.0: string = input2 0.0: string = "NONE" input_file.store_line(string) if input_file.get_length() > MAX_SAVE_SIZE: var main = get_parent() main.record_pressed = false var recording = main.get_node("Recording") recording.visible = false is_recording = false input_file.close() func playback_input(input1, input2): var input = input_file.get_line() match input: input1: input = 1.0 input2: input = -1.0 "NONE": input = 0.0 return input func _on_record_pressed(): if is_recording: # Create/open file and start saving input input_file = FileAccess.open("user://recorded_input.save", FileAccess.WRITE) if FileAccess.get_open_error() != OK: return else: # Close file input_file.close() func _on_playback_pressed(): if is_playback: # Read file for input input_file = FileAccess.open("user://recorded_input.save", FileAccess.READ) if FileAccess.get_open_error() != OK: return else: # Close file input_file.close() func end_of_file_reached(): input_file.close() is_playback = false var label = get_node("../GUI/Playback") label.visible = false var main = get_parent() main.playback_pressed = false func recalculate_parameters(): max_speed = config.get_value("Ship_Parameters", "max_speed") / weight acceleration = config.get_value("Ship_Parameters", "acceleration") / weight deceleration = config.get_value("Ship_Parameters", "deceleration") / weight rotation_speed = config.get_value("Ship_Parameters", "rotation_speed") / weight friction = config.get_value("Ship_Parameters", "friction") * weight max_rotational_velocity = config.get_value("Ship_Parameters", "max_rotational_velocity") / weight func _on_area_2d_body_entered(_body): crash = true func _on_area_2d_body_exited(_body): crash = false func _on_max_speed_slider_value_changed(value): max_speed = value func _on_acceleration_slider_value_changed(value): acceleration = value func _on_deceleration_slider_value_changed(value): deceleration = value func _on_rotation_speed_slider_value_changed(value): rotation_speed = value func _on_friction_slider_value_changed(value): friction = value func _on_max_rotational_velocity_slider_value_changed(value): max_rotational_velocity = value func _on_weight_slider_value_changed(value): weight = value set_scale(Vector2(weight, weight)) recalculate_parameters()
import { APP_INITIALIZER, NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HomeModule } from './features/home/pages/home.module'; import { SubjectModule } from './features/subjects/subject.module'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { HttpClientModule } from '@angular/common/http'; import {MatDialogModule} from '@angular/material/dialog'; import { KeycloakAngularModule, KeycloakService } from 'keycloak-angular'; import { initializer } from './shared/utils/app-init'; // import { SharedModule } from './shared/shared.module'; import {MatSidenavModule} from '@angular/material/sidenav'; import {MatListModule} from '@angular/material/list'; import {MatToolbarModule} from '@angular/material/toolbar'; import {MatIconModule} from '@angular/material/icon'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MatNativeDateModule } from '@angular/material/core'; import {MatButtonModule} from '@angular/material/button'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, HomeModule, BrowserAnimationsModule, SubjectModule, HttpClientModule, MatDialogModule, // SharedModule, KeycloakAngularModule, MatSidenavModule, MatListModule, MatToolbarModule, MatIconModule, MatButtonModule, FormsModule, MatNativeDateModule, ReactiveFormsModule, ], providers: [ { provide: APP_INITIALIZER, useFactory: initializer, deps: [KeycloakService], multi: true, }, ], bootstrap: [AppComponent] }) export class AppModule { }
[![CMake and CTest on ubuntu-latest](https://github.com/314rs/lpkf91s/actions/workflows/cmake-ubuntu-latest.yml/badge.svg)](https://github.com/314rs/lpkf91s/actions/workflows/cmake-ubuntu-latest.yml) # LPKF91s tooling - gcode to hpgl converter This project features some helper programs to revive the LPKF91s PCB mill. The individual components are: - __gcode2hpgl__: a converter from gcode to hpgl. (cli, gui) - __hpgl2serial__: send a hpgl file to the PCB mill via a serial port. (cli, gui) - a manual hpgl sender (gui) ## Download Download the program for your platform from the releases ## Build yourself ### Dependencies - CMake - conan package manager - WxWidgets - boost (asio, program_options) ### Build ```bash conan install conanfile.txt --build=missing ``` ```bash cmake ``` ## Commands gcode -> hpgl absolute (hpgl relative) ### G00 & G01 #### Parameters Not all parameters need to be used, but at least one has to be used ```text Xnnn The position to move to on the X axis Ynnn The position to move to on the Y axis Znnn The position to move to on the Z axis Ennn The amount to extrude between the starting point and ending point Fnnn The feedrate per minute of the move between the starting point and ending poin (if supplied) Hnnn (RepRapFirmware) Flag to check if an endstop was hit (H1 to check, H0 to ignore, other Hnnn see note, default is H0)1 Rnnn (RepRapFirmware) Restore point number 4 Snnn Laser cutter/engraver power. In RepRapFirmware, when not in laser mode S in interpreted the same as H. ``` absolute -> `PA (x1,y1{,...xn,yn}){;}` (plot absolute) relative -> `PR (x1,y1{,...xn,yn}){;}` (plot relative) -> `PD {;}` (pen down) iff Z position is low _parameter z_ -> `PU {;}` (pen up) iff Z position is high _parameter z_ -> `VS (v{,n}){;}` Velocity select Defines the track speed in the XY level v=[mm/s] with the tool lowered and allocates this speed to the tool with number n. _parameter F ?!?!?_ ### G21 Set units to mm ### G90 set to absolute positioning ### G91 set to relative positioning ### G92 set position > i.e. Give the current position a new name #### Parameters This command can be used without any additional parameters. `Xnnn` new X axis position `Ynnn` new Y axis position `Znnn` new Z axis position `Ennn` new extruder position ### M0 Stop or unconditional stop #### Parameters This command can be used without any additional parameters. `Pnnn` Time to wait, in milliseconds1 `Snnn` Time to wait, in seconds2 #### Example `M0` ### M3 Spindle On, Clockwise #### Parameters ```Snnn Spindle RPM``` #### Example ```M3 S4000``` ### M5 Spindle off ### M6 Tool change ### T1 select tool
package com.mr_turtle.hadoop.mr.wordcount; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.util.StringUtils; import java.io.IOException; /* * map和reduce的输入输出数据都是以key-value的形式封装的。 * 前两个是输入数据的泛型,后两个是输出数据的泛型 Long, String, String, Long * 前两个一般不需要修改。key是要处理文本中的起始偏移量;value是这一行的内容 * hadoop实现了一套自己的序列化机制,效率更高,网络传输更精简 */ public class WCMapper extends Mapper<LongWritable, Text, Text, LongWritable>{ // 读一行调用一次 @Override protected void map(LongWritable key, Text value, Context context)throws IOException, InterruptedException { // key是要处理文本中的起始偏移量;value是这一行的内容 // 输出的工具放到了context里 String line = value.toString(); String[] words = StringUtils.split(line, ' '); for(String word:words){ context.write(new Text(word), new LongWritable(1)); } } }
import React from 'react'; import { Container, Header, Buttons } from './styles'; interface Props { label: String; description: String; } const DefaultOverLayContent: React.FC<Props> = ({ label, description }) => { return ( <Container> <Header> <h1>{label}</h1> <h2>{description}</h2> </Header> <Buttons> <button>Custom Order</button> <button className='white'>Existing Inventory</button> </Buttons> </Container> ); }; export default DefaultOverLayContent;
import { colors } from "@/constants/colors"; import { JumbotromProps } from "./types"; import { Typography } from "@/constants/typography"; import Button from "../button"; const Jumbotron = ({ title = "", description = "", btnText = "", className, classNameContent, onClick, }: JumbotromProps) => { return ( <div className={`${className} relative z-0`}> <div className="absolute inset-0 bg-[#000] opacity-60 z-10"></div> <div className={`${classNameContent} z-20`}> <h1 className={`${Typography.latoBold} text-4xl leading-[50px] mb-4`}> {title} </h1> <p className={`${Typography.latoLight} text-base mt-6 mb-8 `}> {description} </p> <Button onClick={onClick} variant="primary" className="max-w-[320px]" text={btnText} /> </div> </div> ); }; export default Jumbotron;
/* SINGLE-HEADER LIBRARY */ /* VARIATION TUI (LIBRARY) */ #ifndef _VN_H #define _VN_H /* -------------------------------- * * ASCII ESCAPE SEQUENCE RESET CODE * * -------------------------------- */ #define esc_reset "\033[0m" /* -------------------------------- * * MUST BE USED AFTER COLOR CODES */ /* --------------------------------- * * ASCII ESCAPE SEQUENCE TEXT STYLES * * --------------------------------- */ #define text_bold "\033[1m" #define text_italic "\033[3m" #define text_underline "\033[4m" #define text_blink "\033[5m" #define text_strikethrough "\033[9m" /* --------------------------------- */ /* ----------------------------------- * * ASCII ESCAPE SEQUENCE UTILITY CODES * * ----------------------------------- */ #define clear_screen "\033[2J\033[H" #define cursor_visible "\033[?25h" #define cursor_invisible "\033[?25l" /* ----------------------------------- */ struct vnc_color { /* VARIATION CUSTOM COLOR */ int is_fore; /* IS FOR FOREGROUND OR BACKGROUND */ char* color; /* COLOR BUFFER NEED USE WITH 'vn_color()' FUNCTION */ }; /* ONLY NEED HEX CODE */ void vn_cursor_visibility(int boolean); /* SET CURSOR VISIBILITY */ void vn_clrscr(void); /* CLEAR SCREEN */ void vn_gotoxy(int pos_x, int pos_y); /* SET CURSOR TO X AND Y POSITIONS */ void vn_cprint(char *str, char *fg_color, char *bg_color, char *str_style); /* PRINT WITH COLORS */ void vn_goto_cprint(char *str, char *fg_color, char *bg_color, char *str_style, int pos_x, int pos_y); /* PRINT WITH COLORS TO CERTAIN POSITIONS*/ void vn_bg(int pos_x, int pos_y, int width, int height, char *bg_color); /* SET BACKGROUND COLOR */ void vn_frame(int pos_x, int pos_y, int width, int height, char *fg_color, char *bg_color, char vertical_symbol, char horizontal_symbol); /* SET FRAME */ void vn_label(int pos_x, int pos_y, int width, int height, char *fg_color, char *bg_color, char* text_style, char *str); /* SET LABEL */ void vn_warn(int pos_x, int pos_y, int width, int height, char *fg_color, char *bg_color, char *frame_fg_color, char *frame_bg_color, char frame_vertical_symbol, char frame_horizontal_symbol, char *text_style, char *str, char *title); /* WARNING SCREEN */ char *vn_color(char *hex_color, int is_fore); /* FOR CUSTOM COLORS */ #endif /* MADE BY @hanilr */ #ifdef VN_IMPLEMENTATION #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> void vn_cursor_visibility(int boolean) { if(boolean == 1) { printf("%s", cursor_visible); } else { printf("%s", cursor_invisible); } } void vn_clrscr(void) { printf("%s", clear_screen); } void vn_gotoxy(int pos_x, int pos_y) { printf("\033[%d;%dH", pos_y, pos_x); } void vn_cprint(char *str, char *fg_color, char *bg_color, char *str_style) { /* IF YOU DON'T WANT TO USE ARGUMENTS THEN ENTER IN DOUBLE QUOTATION MARKS WITH GAP */ printf("%s%s%s%s%s", fg_color, bg_color, str_style, str, esc_reset); } /* EXAMPLE: print_c("temp", "", "", ""); */ void vn_goto_cprint(char *str, char *fg_color, char *bg_color, char *str_style, int pos_x, int pos_y) { vn_gotoxy(pos_x, pos_y); vn_cprint(str, fg_color, bg_color, str_style); } int hex_number(int number, int left_side) { if(left_side == 0) { return number; } else if(left_side == 1) { if(number == 1) { return 16; } else if(number == 2) { return 32; } else if(number == 3) { return 48; } else if(number == 4) { return 64; } else if(number == 5) { return 80; } else if(number == 6) { return 96; } else if(number == 7) { return 112; } else if(number == 8) { return 128; } else if(number == 9) { return 144; } } return 0; } /* 'left_side' MEAN IS IF AT LEFT SIDE THEN RETURN ORIGINAL NUMBER IF NOT THEN MULTIPLY WITH 16 */ int hex_letter(char letter, int left_side) { if(left_side == 0) { if(letter == 'a') { return 10; } else if(letter == 'b') { return 11; } else if(letter == 'c') { return 12; } else if(letter == 'd') { return 13; } else if(letter == 'e') { return 14; } else if(letter == 'f') { return 15; } } else if(left_side == 1) { if(letter == 'a') { return 160; } else if(letter == 'b') { return 176; } else if(letter == 'c') { return 192; } else if(letter == 'd') { return 208; } else if(letter == 'e') { return 224; } else if(letter == 'f') { return 240; } } return 0; } /* 'left_side' MEAN IS IF AT LEFT SIDE THEN RETURN 2 DIGIT NUMBER WHO START WITH 10 IF NOT THEN MULTIPLY WITH 16 */ char *vn_color(char *hex_color, int is_fore) { if(strlen(hex_color) != 6) { fprintf(stderr, "[ERROR] 'vn_color()' function argument not equal to 6 digit!"); exit(1); } /* IF 'hex_color' ARGUMENT LENGTH NOT EQUAL TO 6 DIGIT THEN PRINT ERROR AND EXIT */ if(strcmp(hex_color, "#") == 0) { fprintf(stderr, "[ERROR] 'vn_color()' function argument has '#' symbol!"); exit(1); } /* IF 'hex_color' ARGUMENT HAS '#' SYMBOL THEN PRINT ERROR AND EXIT */ int red, green, blue, red_x, red_y, green_x, green_y, blue_x, blue_y; char *rgb = (char*) malloc(32); if(isalpha(hex_color[0]) != 0) { red_x = hex_letter(hex_color[0], 1); } else { red_x = hex_number(hex_color[0] - '0', 1); } if(isalpha(hex_color[1]) != 0) { red_y = hex_letter(hex_color[1], 0); } else { red_y = hex_number(hex_color[1] - '0', 0); } if(isalpha(hex_color[2]) != 0) { green_x = hex_letter(hex_color[2], 1); } else { green_x = hex_number(hex_color[2] - '0', 1); } if(isalpha(hex_color[3]) != 0) { green_y = hex_letter(hex_color[3], 0); } else { green_y = hex_number(hex_color[3] - '0', 0); } if(isalpha(hex_color[4]) != 0) { blue_x = hex_letter(hex_color[4], 1); } else { blue_x = hex_number(hex_color[4] - '0', 1); } if(isalpha(hex_color[5]) != 0) { blue_y = hex_letter(hex_color[5], 0); } else { blue_y = hex_number(hex_color[5] - '0', 0); } red = red_x + red_y; green = green_x + green_y; blue = blue_x + blue_y; if(is_fore == 1) { sprintf(rgb, "\033[38;2;%d;%d;%dm", red, green, blue); } if(is_fore == 0) { sprintf(rgb, "\033[48;2;%d;%d;%dm", red, green, blue); } return rgb; } void vn_bg(int pos_x, int pos_y, int width, int height, char *bg_color) { int x = 0, y = 0; printf("%s", bg_color); while(height > y) { vn_gotoxy(pos_x, pos_y+y); while(width > x) { printf(" "); x+=1; } x=0; y+=1; } printf("%s", esc_reset); } void vn_frame(int pos_x, int pos_y, int width, int height, char *fg_color, char *bg_color, char vertical_symbol, char horizontal_symbol) { int x = 0, y = 0; printf("%s%s", fg_color, bg_color); vn_gotoxy(pos_x, pos_y); while(width > x) { printf("%c", horizontal_symbol); x+=1; } x=0; while(height > y+2) { vn_gotoxy(pos_x, pos_y+y+1); printf("%c", vertical_symbol); vn_gotoxy(pos_x+width-1, pos_y+y+1); printf("%c", vertical_symbol); y+=1; } vn_gotoxy(pos_x, pos_y+height-1); while(width > x) { printf("%c", horizontal_symbol); x+=1; } printf("%s", esc_reset); } void vn_label(int pos_x, int pos_y, int width, int height, char *fg_color, char *bg_color, char *text_style, char *str) { vn_bg(pos_x, pos_y, width, height, bg_color); vn_gotoxy(pos_x, pos_y); if(strlen(str) > width) { int x = 0, y = 0, z = 0, i = 0; printf("%s%s%s", fg_color, bg_color, text_style); while(strlen(str) > x) { if(z == width) { i+=1; y+=1; int space_pos = 0; if(str[x+1] != ' ' || str[x] != ' ') { z=x; while(1) { if(str[z] != ' ') { space_pos+=1; z-=1; vn_gotoxy(pos_x+width-space_pos, pos_y+y-1); printf(" "); } else { x-=space_pos-1; break; } } } vn_gotoxy(pos_x, pos_y+y); z=0; } if(i == height) { vn_gotoxy(pos_x+width-3, pos_y+height-1); printf("..."); break; } printf("%c", str[x]); x+=1; z+=1; } printf("%s", esc_reset); } else { vn_cprint(str, fg_color, bg_color, text_style); } } void vn_warn(int pos_x, int pos_y, int width, int height, char *fg_color, char *bg_color, char *frame_fg_color, char *frame_bg_color, char frame_vertical_symbol, char frame_horizontal_symbol, char *text_style, char *str, char *title) { vn_bg(pos_x, pos_y, width, height, bg_color); vn_frame(pos_x, pos_y, width, height, frame_fg_color, frame_bg_color, frame_vertical_symbol, frame_horizontal_symbol); vn_gotoxy(pos_x+((width/2)-strlen(str)/2), pos_y); vn_cprint(title, fg_color, frame_bg_color, text_bold); vn_gotoxy(pos_x+((width/2)-strlen(str)/2), pos_y+((height-1)/2)); vn_cprint(str, fg_color, bg_color, text_style); } #endif
public class Wait_Notify_Methods { public static void main(String[] args) { Message message = new Message("Hello, World!"); Thread senderThread = new Thread(new Sender(message)); Thread receiverThread1 = new Thread(new Receiver(message)); Thread receiverThread2 = new Thread(new Receiver(message)); senderThread.start(); receiverThread1.start(); receiverThread2.start(); } } class Message { private String message; public Message(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } class Sender implements Runnable { private Message message; public Sender(Message message) { this.message = message; } public void run() { String[] messages = {"Message 1", "Message 2", "Message 3", "Message 4"}; for (String msg : messages) { message.setMessage(msg); synchronized (message) { message.notify(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Receiver implements Runnable { private Message message; public Receiver(Message message) { this.message = message; } public void run() { synchronized (message) { try { message.wait(); System.out.println(Thread.currentThread().getName() + " received message: " + message.getMessage()); message.notify(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
import { Component, ViewChild, OnInit } from '@angular/core'; import { UserserviceService } from 'src/app/services/userservice.service'; import { MatSnackBar } from '@angular/material/snack-bar'; import Swal from 'sweetalert2'; import { HttpClient } from '@angular/common/http'; import { ActivatedRoute } from '@angular/router'; import { Router } from '@angular/router'; @Component({ selector: 'app-password-reset', templateUrl: './password-reset.component.html', styleUrls: ['./password-reset.component.css'] }) export class PasswordResetComponent implements OnInit { step: number = 1; newPassword: string = ''; confirmPassword: string = ''; hidePassword: boolean = true; passwordMismatchError: boolean = false; otp: string = ''; timer: number = 60; resendButtonVisible: boolean = false; timerInterval: any; user: any = null; userEmail: string = ''; otpValidation: string = ''; userEnteredOTP: string = ''; disabled: boolean = false; successMessage: string | null = null; resetDisabled: boolean = false; constructor( private userservice: UserserviceService, private snack: MatSnackBar, private http: HttpClient, private route: ActivatedRoute, private _router: Router ) { // Capture the user data from the ActivatedRoute snapshot this.route.params.subscribe((params) => { if (params && params['user']) { this.user = JSON.parse(params['user']); } }); } sendOTP(newStep: number): void { if (this.userEmail === this.user.email) { console.log(this.userEmail); console.log("this.user", this.user); this.disabled = true; this.step = newStep; this.userservice.sendOTP(this.user.username).subscribe((data: any) => { console.log(data); this.otpValidation = data.message; console.log(this.otpValidation); }, (error) => { console.log('error', error); }); } else { // Email does not match, display an error message to the user console.log('Email does not match'); // You can display an error message to the user using MatSnackBar or another method // Example with MatSnackBar: this.snack.open('Email does not match. Please enter the correct email address.', '', { duration: 3000, verticalPosition: 'bottom', horizontalPosition: 'center', }); } this.timer = 60; // Set the initial timer value this.timerInterval = setInterval(() => { this.timer--; if (this.timer === 0) { clearInterval(this.timerInterval); // Clear the timer interval when it reaches 0 this.resendButtonVisible = true; // Show the Resend OTP button } }, 1000); } resendOTP() { this.resendButtonVisible = false; this.userservice.sendOTP(this.user.username).subscribe((data: any) => { console.log(data); this.otpValidation = data.message; console.log(this.otpValidation); }, (error) => { console.log('error', error); }); this.timer = 60; // Set the initial timer value this.timerInterval = setInterval(() => { this.timer--; if (this.timer === 0) { clearInterval(this.timerInterval); // Clear the timer interval when it reaches 0 this.resendButtonVisible = true; // Show the Resend OTP button } }, 1000); } verifyOTP(newStep: number): void { if (this.userEnteredOTP.length == 0) { this.snack.open('Enter the OTP to continue.', '', { duration: 3000, verticalPosition: 'top', horizontalPosition: 'right', }); } else { if (this.otpValidation == this.userEnteredOTP) { this.step = newStep; console.log(this.userEnteredOTP); } else { console.log('OTP did not match'); this.snack.open('OTP did not match. Please enter the correct OTP.', '', { duration: 3000, verticalPosition: 'bottom', horizontalPosition: 'center', }); } } } ngOnInit(): void { } formSubmit() { // alert('submit'); if (this.user.username == '' || this.user.username == null) { this.snack.open('UserName is Required', '', { duration: 3000, verticalPosition: 'bottom', horizontalPosition: 'center', }); return; } //validate //addUser : userservice this.userservice.addUser(this.user).subscribe( (data: any) => { console.log("entered signup"); //Success Swal.fire( 'Successfully Done', this.user.username + ' is Registered as User', 'success' ); }, (error) => { //Error console.log('error'); this.snack.open('User with this Username is already there please try with new one', '', { duration: 3000, verticalPosition: 'bottom', horizontalPosition: 'center', }); } ); } resetPassword() { // Define a regular expression pattern for password complexity const passwordPattern = /^(?=.*[A-Z])(?=.*[!@#$%^&*])(?=.*[0-9]).{8,}$/; if (this.newPassword.length != 0) { // Check if the new password and confirm password match if (this.newPassword === this.confirmPassword) { // Check if the new password meets the complexity criteria console.log("pass validate :: ", !passwordPattern.test(this.confirmPassword)); if (passwordPattern.test(this.confirmPassword)) { // Password complexity is met, proceed with the password reset this.user.password = this.confirmPassword; console.log("HI password is ok"); this.resetDisabled = true; this.userservice.resetPassword(this.user).subscribe( (data: any) => { console.log(data); // Add any additional logic for handling the password reset success // Display a success message to the user this.successMessage = 'Password reset successfully done'; if (data.message === 'Success') { //Success Swal.fire( data.message, 'Password Reset Successful', 'success' ).then((result) => { this._router.navigate(['/admin/profile']); }); this.newPassword = ''; this.confirmPassword = ''; } else if (data.message == 'Error in mail Service') { Swal.fire( data.message, 'Password Reset Successful, But Mail could not be sent.', 'warning' ).then((result) => { this._router.navigate(['/admin/profile']); }); } else { Swal.fire( data.message, 'Password Reset Failed', 'error' ); this.resetDisabled = false; } }, (error) => { console.log(error); // Handle password reset error } ); } else { // Password complexity is not met, display an error message this.snack.open('Password did not met the requirement, Try another one.', '', { duration: 3000, verticalPosition: 'top', horizontalPosition: 'center', panelClass: 'warning-snackbar' }); } } else { // Passwords don't match, display an error message this.snack.open('Passwords do not match.', '', { duration: 3000, verticalPosition: 'top', horizontalPosition: 'center', }); } } else { // Passwords don't match, display an error message this.snack.open('Enter the Password.', '', { duration: 3000, verticalPosition: 'top', horizontalPosition: 'center', }); } } togglePasswordVisibility() { this.hidePassword = !this.hidePassword; } isPasswordComplex(): boolean { // Define a regular expression pattern for password complexity const passwordPattern = /^(?=.*[A-Z])(?=.*[!@#$%^&*])(?=.*[0-9]).{8,}$/; return !passwordPattern.test(this.newPassword); } }
from PIL import Image import pytesseract from discord.ext import commands import re import util.JsonHandler import os import discord imageReadEmbed = discord.Embed(title="Automatic Image Reading:", description="", color=0x5D3FD3) class imageStuff(commands.Cog): def __init__(self, bot :commands.Bot) -> None: self.bot = bot @commands.Cog.listener() async def on_message(self, message): channels = util.JsonHandler.load_channels() users = util.JsonHandler.load_users() if str(message.author.id) in users: return if str(message.channel.id) in channels: if message.attachments: await message.attachments[0].save("image.png") image = Image.open('image.png') text = pytesseract.image_to_string(image) if re.search("windows.protected.your.pc", text.lower()): imageReadEmbed.add_field(name="", value="Mod managers sometimes get auto flagged by Windows Defender because they don't have a digital signature, which Windows automatically (falsely) assumes is dangerous. These files, however, are not dangerous. They're all open source (so you can see all the code that make them up) if you want to confirm for yourself.\n\nYou can simply press `More Info` and `Run Anyway` to use the application. Please only do this when I respond if you're getting this message specifically for a Northstar mod manager, and nothing else.") if re.search("items.nut", text.lower()) and re.search("INVALID_REF", text.lower()): imageReadEmbed.add_field(name="", value="If you're encountering the \"INVALID_REF\" issue, please double check if you've removed any mods that do things like add skins to the game. A big cause of this is removing MoreSkins while a skin is equipped on a gun, making the game try to load something that doesn't exist. If you aren't sure or this didn't work, you'll have to reset multiplayer data, which should fix the issue. You can do this by opening the console on the main menu by hitting `~`, typing `ns_resetpersistence` , and then hitting enter.") if re.search("Encountered.CLIENT.script.compilation.error", text.lower()) and re.search("error|help", message.content.lower()): imageReadEmbed.add_field(name="", value="From this image alone, we can't see what's causing the issue. Please send a screenshot of the console (open it by hitting the `~` key), or send the newest log. You can find logs in `Titanfall2/R2Northstar/logs`, with the newest being on the bottom by default.") if re.search("Invalid.or.expired.masterserver.token", text.lower()) or re.search("Couldn't.find.player.account", text.lower()): imageReadEmbed.add_field(name="", value="Try following the guide on solving the \"Couldn't find player account\" and \"Invalid master server token\" errors [here](https://r2northstar.gitbook.io/r2northstar-wiki/installing-northstar/troubleshooting#playeraccount)") if re.search("MSVCP120.dll", text.lower()): imageReadEmbed.add_field(name="", value="The \"MSVCP120.dll\" error comes up when you're missing a dependency Titanfall 2 uses to run. Follow the [wiki section for this issue](https://r2northstar.gitbook.io/r2northstar-wiki/installing-northstar/troubleshooting#msvcr) to solve it.") # FlightCore specific errors if re.search("Mod.failed.sanity.check", text.lower()): imageReadEmbed.add_field(name="", value="The \"Mod failed sanity check\" error is specific to FlightCore, and means that the mod isn't properly formatted and FlightCore can't automatically install it. However, you can still follow the [manual mod install guide](https://r2northstar.gitbook.io/r2northstar-wiki/installing-northstar/manual-installation#installing-northstar-mods-manually) to install the mod you wanted.") # Viper specific errors if re.search("Unknown.error*an.unknown.error.occurred", text.lower()): imageReadEmbed.add_field(name="", value="If you're using Viper, please click on the error message shown in this image and send a screenshot of the actual error message that pops up afterwards.") if re.search("operation.not.permitted", text.lower()) and re.search("EA.Games", text.lower()): imageReadEmbed.add_field(name="", value="EA's default install directory has some issues associated with it, which can be solved by following the [wiki section about this error](https://r2northstar.gitbook.io/r2northstar-wiki/installing-northstar/troubleshooting#cannot-write-log-file-when-using-northstar-on-ea-app)") if len(imageReadEmbed.fields) > 0: if len(imageReadEmbed) > 1: return else: imageReadEmbed.add_field(name="", value="\nPlease note that I'm a bot automatically reading your image. There is a chance this information is wrong, in which case please ping @Cyn") await message.channel.send(embed=imageReadEmbed, reference=message) imageReadEmbed.clear_fields() os.remove("image.png") # is this bad? probably # does it work? also probably async def setup(bot: commands.Bot) -> None: await bot.add_cog(imageStuff(bot))
import React from "react"; import Logo from "../assets/homeLogo.svg"; import { useFormik } from "formik"; import * as Yup from "yup"; import { Link, useNavigate } from "react-router-dom"; import toast from "react-hot-toast"; import axios from "axios"; import Measurements from "./components/measurements"; import MeasurementsDisplay from "./components/measurementsDisplay"; import AddImages from "./components/addImages"; const AddProduct = () => { const navigate = useNavigate(); const [category, setCategory] = React.useState([ "clothes", "footwear", "accessories", "others", ]); const [gender, setGender] = React.useState(["male", "female", "unisex"]); const [fileList, setFileLIst] = React.useState([]); const [comingSoon, setComingSoon] = React.useState(false); const lorem = "lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet tempus libero. Morbi a bibendum lacus. Mauris blandit, ipsum id elementum pellentesque, augue augue aliquam risus, non egestas quam dui vitae ipsum. Ut sodales tempus tortor, eget sagittis mauris molestie et. Aliquam placerat augue at ipsum ornare, id egestas elit pulvinar. Morbi a massa aliquet, pellentesque dolor vitae, dignissim felis."; const [selectedCategory, setSelectedCategory] = React.useState("clothes"); const [selectedGender, setSelectedGender] = React.useState("unisex"); const [measurements, setMeasurements] = React.useState([]); const formik = useFormik({ initialValues: { name: "", price: 0, description: "", brief: "", urlForSizeChart: "", }, onSubmit: (values, { setSubmitting }) => { setSubmitting(true); if (measurements.length === 0) { toast.error("Please add atleast one name"); setSubmitting(false); return; } if (fileList.length === 0) { toast.error("Please Upload atleast one image"); setSubmitting(false); return; } const data = new FormData(); data.append("name", values.name); data.append("price", values.price); data.append("description", values.description); data.append("brief", values.brief); data.append("urlForSizeChart", values.urlForSizeChart); data.append("category", selectedCategory); data.append("gender", selectedGender); data.append("comingSoon", comingSoon); measurements.forEach((item, index) => { data.append(`measurements[${index}][name]`, item.name); data.append(`measurements[${index}][unit]`, item.unit); }); fileList.forEach((file) => { data.append("images", file); }); axios .post(`${import.meta.env.VITE_BACKEND_URL}products/`, data) .then((res) => { toast.success("Product Added Successfully"); navigate("/products"); }) .catch((err) => { toast.error(err.response.data.msg || "Something went wrong"); setSubmitting(false); }); }, validationSchema: Yup.object({ name: Yup.string().required("name is Required"), price: Yup.number().min(1).positive().required("price is Required"), description: Yup.string().required("description is Required"), brief: Yup.string().required("brief is Required"), // add yup validator for a url making sure it is a url urlForSizeChart: Yup.string() .required("url For SizeChart is Required") .matches( /^(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]$/i, "Invalid url", ), }), }); return ( <main className="py-12 font-medium"> <form className="flex flex-col gap-y-8" onSubmit={formik.handleSubmit}> <section className="flex flex-col gap-x-12 gap-y-2 md:flex-row "> <label className="basis-[20%] capitalize" htmlFor="name"> product Name </label> <div className="flex w-full flex-col text-asisDark "> <input type="text" id="name" name="name" {...formik.getFieldProps("name")} className=" w-full border-2 border-asisDark/30 bg-transparent px-3 py-3 text-sm text-asisDark md:w-2/3 lg:w-2/5" /> <div className="h-2"> {formik.touched.name && formik.errors.name ? ( <p className="text-xs capitalize text-red-500"> {formik.errors.name} </p> ) : null} </div> </div> </section> <section className="flex flex-col gap-x-12 gap-y-2 md:flex-row "> <label className="basis-[20%] capitalize" htmlFor="brief"> product Brief </label> <div className="flex w-full flex-col text-asisDark "> <input type="text" id="brief" name="brief" {...formik.getFieldProps("brief")} className=" w-full border-2 border-asisDark/30 bg-transparent px-3 py-3 text-sm text-asisDark md:w-2/3 lg:w-2/5" /> <div className="h-2"> {formik.touched.brief && formik.errors.brief ? ( <p className="text-xs capitalize text-red-500"> {formik.errors.brief} </p> ) : null} </div> </div> </section> <section className="flex flex-col gap-x-12 gap-y-2 md:flex-row"> <label className="basis-[20%] capitalize" htmlFor="description"> product details </label> <div className="flex w-full flex-col text-asisDark "> <textarea type="text" id="description" name="description" {...formik.getFieldProps("description")} className="min-h-[8rem] w-full border-2 border-asisDark/30 bg-transparent px-3 py-3 text-sm text-asisDark md:w-2/3 lg:w-3/4" /> <div className="h-2"> {formik.touched.description && formik.errors.description ? ( <p className="text-xs capitalize text-red-500"> {formik.errors.description} </p> ) : null} </div> </div> </section> <section className="flex flex-col gap-x-12 gap-y-2 md:flex-row "> <label className="basis-[20%] capitalize" htmlFor="brief"> Product coming soon </label> <div className="flex w-full flex-col text-asisDark "> <input type="checkbox" id="comingSoon" name="comingSoon" checked={comingSoon} onChange={() => setComingSoon(!comingSoon)} className=" w-full cursor-pointer border-2 border-asisDark/30 bg-transparent px-3 py-3 text-sm text-asisDark md:w-2/3 lg:w-2/5" /> </div> </section> <section className="flex flex-col gap-x-12 gap-y-2 md:flex-row "> <label className="basis-[20%] capitalize" htmlFor="brief"> product Price [$] </label> <div className="flex w-full flex-col text-asisDark "> <input type="number" id="price" name="price" min={0} {...formik.getFieldProps("price")} className=" w-full border-2 border-asisDark/30 bg-transparent px-3 py-3 text-sm text-asisDark md:w-2/3 lg:w-2/5" /> <div className="h-2"> {formik.touched.price && formik.errors.price ? ( <p className="text-xs capitalize text-red-500"> {formik.errors.price} </p> ) : null} </div> </div> </section> <section className="flex flex-col gap-x-12 gap-y-2 md:flex-row "> <label className="basis-[20%] capitalize" htmlFor="brief"> Gender </label> <div className="flex w-full flex-wrap gap-4 text-asisDark "> {gender.map((item, index) => ( <button type="button" key={index} className={`${ selectedGender == item ? "bg-asisDark text-white" : "border border-asisDark bg-transparent text-asisDark" } rounded px-4 py-2 font-normal capitalize`} onClick={() => setSelectedGender(item)} > {item} </button> ))} </div> </section> <section className="flex flex-col gap-x-12 gap-y-2 md:flex-row "> <label className="basis-[20%] capitalize" htmlFor="brief"> Category </label> <div className="flex w-full flex-wrap gap-4 text-asisDark "> {category.map((item, index) => ( <button type="button" key={index} className={`${ selectedCategory == item ? "bg-asisDark text-white" : "border border-asisDark bg-transparent text-asisDark" } rounded px-4 py-2 font-normal capitalize`} onClick={() => setSelectedCategory(item)} > {item} </button> ))} </div> </section> <section className="flex flex-col gap-x-12 gap-y-2 md:flex-row "> <label className="basis-[20%] capitalize" htmlFor="brief"> Measurements </label> <section className="flex w-full flex-col gap-y-4 text-asisDark"> <Measurements measurements={measurements} setMeasurements={setMeasurements} /> <MeasurementsDisplay measurements={measurements} setMeasurements={setMeasurements} /> </section> </section> <section className="flex flex-col gap-x-12 gap-y-2 md:flex-row "> <label className="basis-[20%] capitalize" htmlFor="brief"> Size Chart Link </label> <div className="flex w-full flex-col text-asisDark "> <input type="text" id="urlForSizeChart" name="urlForSizeChart" {...formik.getFieldProps("urlForSizeChart")} className=" w-full border-2 border-asisDark/30 bg-transparent px-3 py-3 text-sm text-asisDark md:w-2/3 lg:w-2/5" /> <div className="h-2"> {formik.touched.urlForSizeChart && formik.errors.urlForSizeChart ? ( <p className="text-xs capitalize text-red-500"> {formik.errors.urlForSizeChart} </p> ) : null} </div> </div> </section> <section className="flex flex-col gap-x-12 gap-y-2 md:flex-row "> <label className="basis-[20%] capitalize" htmlFor="brief"> Image Upload & Preview </label> <section className="flex w-full flex-col gap-y-4 text-asisDark"> <AddImages fileList={fileList} setFileLIst={setFileLIst} /> </section> </section> <section className="flex w-full items-end justify-end gap-4"> <button type="button" disabled={formik.isSubmitting} onClick={() => navigate("/products")} className={`rounded bg-red-500 px-8 py-1.5 text-white ${ formik.isSubmitting && "cursor-not-allowed opacity-50" }`} > cancel </button> <button disabled={formik.isSubmitting} type="submit" className={`rounded bg-green-500 px-8 py-1.5 text-white ${ formik.isSubmitting && "cursor-not-allowed opacity-50" }`} > Add Product </button> </section> </form> </main> ); }; export default AddProduct; // name: 'Genevive Sweater Swagger lee', // price: '300', // description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet tempus libero. Morbi a bibendum lacus. Mauris blandit, ipsum id elementum pellentesque, augue augue aliquam risus, non egestas quam dui vitae ipsum. Ut sodales tempus tortor, eget sagittis mauris molestie et. Aliquam placerat augue at ipsum ornare, id egestas elit pulvinar. Morbi a massa aliquet, pellentesque dolor vitae, dignissim felis.', // brief: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', // category: 'Shirts', // measurements: [ // [Object: null prototype] { name: 'xl', unit: '5' }, // [Object: null prototype] { name: 'lg', unit: '5' }, // [Object: null prototype] { name: 'md', unit: '5' }, // [Object: null prototype] { name: 'sm', unit: '5' } // ],
<!DOCTYPE html> <!-- Copyright 2022 Murilo Rocha Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- Código para a demonstração do desenvolvimento de um layout de duas colunas com o uso de HTML e CSS. --> <html lang="pt-BR"> <head> <title>Layout de duas colunas com CSS</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> html, body { height: 100%; margin: 0; padding: 0; } body { font-family: arial, helvetica, sans-serif; } div#corpo_pagina { width: 100%; min-height: 100%; display: flex; flex-direction: column; background: #fff; } div#corpo_pagina header { background: #0d5ea1; } div#corpo_pagina header h1 { margin: 0; padding: 1em; font-size: 2em; color: #fff; } div#corpo_pagina main { min-height: 0; display: flex; flex: auto; flex-wrap: wrap; overflow:auto; background: #ceecfa; } div#corpo_pagina aside { max-height:100%; padding: 1em; float: left; overflow: auto; background: #93c3e6; } div#corpo_pagina aside nav#menu_lateral ul { margin: 0; padding: 0; } div#corpo_pagina aside nav#menu_lateral ul li { list-style-type: none; margin: 1em; } div#corpo_pagina aside nav#menu_lateral ul li a { padding: 0.5em 1.5em; display: inline-block; text-align: left; text-decoration: none; font-size: 1em; background: #077bba; color: #fff; } div#corpo_pagina aside nav#menu_lateral ul li a:hover { background: #1191d7; } div#corpo_pagina section { flex: auto; max-height:100%; overflow: auto; float: left; padding: 1em; background: #b4ddfa; } div#corpo_pagina section h2 { padding: 0; margin: 0; font-size: 1.5em; color: #12516b; } div#corpo_pagina footer { bottom: 0; width: 100%; clear: both; text-align: center; background: #0d5ea1; } div#corpo_pagina footer p { font-size: 1em; color: #fff; } </style> </head> <body> <div id="corpo_pagina"> <header> <h1>T&iacute;tulo da p&aacute;gina.</h1> </header> <main> <aside> <nav id="menu_lateral"> <ul> <li> <a href="#link1">Texto do Link 1</a> </li> <li> <a href="#link2">Texto do Link 2</a> </li> <li> <a href="#link3">Texto do Link 3</a> </li> <li> <a href="#link4">Texto do Link 4</a> </li> <li> <a href="#link5">Texto do Link 5</a> </li> </ul> </nav> </aside> <section> <h2>Conte&uacute;do da p&aacute;gina.</h2> </section> </main> <footer> <p>&copy; 2022 &ndash; Murilo Rocha</p> </footer> </div> </body> </html>
<nav class="navbar navbar-dark bg-black text-light navbar-expand-lg"> <div class="container-fluid"> <a class="navbar-brand" href="#">Kekflix</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse d-flex justify-content-between" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item" *ngIf="utente"> <a class="nav-link" [routerLink]="['/movies']" routerLinkActive="active">Film</a> </li> <li class="nav-item" *ngIf="utente"> <a class="nav-link" [routerLink]="['/utenti']" routerLinkActive="active">Utenti</a> </li> <li class="dropdown" *ngIf="utente"> <a class="nav-link dropdown-toggle" [routerLink]="['/profile']" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Profilo </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" [routerLink]="['/profile/details']">Dettagli</a></li> <li><a class="dropdown-item" [routerLink]="['/profile/favorites']">Preferiti</a></li> </ul> </li> <li class="nav-item" *ngIf="!utente"> <a class="nav-link" [routerLink]="['/login']" routerLinkActive="active">Accedi</a> </li> <li class="nav-item" *ngIf="!utente"> <a class="nav-link" [routerLink]="['/register']" routerLinkActive="active">Registrati</a> </li> </ul> <div class="text-end" *ngIf="utente"> <h6>Benvenuto {{utente.user.name }} </h6> <button type="button" id="logout" name="logout" class="btn btn-danger" (click)="logout()">Esci</button> </div> </div> </div> </nav>
import { Component, h, State, Prop, Event, EventEmitter } from '@stencil/core'; import { RouterHistory } from '@stencil/router'; import { UtilService } from '../../services/util-service'; import { CrudService } from '../../services/crud-service'; import { cfg } from '../../config/config'; @Component({ tag: 'app-login', styleUrl: 'login.css', }) export class Login { @State() colorEye = 'primary'; @State() nameIcon = 'eye'; @State() eyePwd: boolean = false; @Prop() history?: RouterHistory; @Event() loginCompleted?: EventEmitter; @State() userName:any=''; @State() userPass:any=''; loginCompletedHandler(todo: any) { CrudService.getInfo(cfg.account.account).then((res)=>{ localStorage.setItem('userData',JSON.stringify(res)); }) this.loginCompleted?.emit(todo); } constructor() { document.title = `Login - iCare`; } handleSubmit(e:any) { e.preventDefault(); // send data to our backend this.login(this.userName, this.userPass); } componentWillRender(){ let token = localStorage.getItem('userToken'); if(token==null||token.length!=191){ } else{ this.loginCompletedHandler('login'); this.history?.replace('/'); } } changeValue(ev:any) { const value = ev.target.value; switch (ev.target.name) { case 'userName': { this.userName = value; break; } case 'userPass': { this.userPass = value; break; } } } async login(user:any, pwd:any){ const loading = document.createElement('ion-loading'); loading.message = 'Loading...', // loading.duration = 2000; document.body.appendChild(loading); await loading.present(); // const { role, data } = await loading.onDidDismiss(); setTimeout(()=>{ // if(username==''||thi.length<1){ // UtilService.presentToastWithOptions('Harap masukkan nomor telepon'); // } // else if(this.userPass==''||this.userPass.length<1){ // UtilService.presentToastWithOptions('Harap masukkan kata sandi'); // } // else{ let data={ username:user, password:pwd, rememberMe:true } CrudService.postData(cfg.jwt.authenticate,data).then((rs)=>{ let strg = localStorage.getItem('pos'+cfg.jwt.authenticate); if(strg == '201' || strg == '200'){ UtilService.presentToastWithOptions('Berhasil Login'); setTimeout(() => { localStorage.removeItem('pos'+cfg.jwt.authenticate); localStorage.setItem('userToken',JSON.stringify(rs.id_token)); this.history?.replace('/'); this.loginCompletedHandler('login'); },1000); } else{ UtilService.presentToastWithOptions('Nomor telepon/password salah!'); localStorage.removeItem('pos'+cfg.jwt.authenticate); } }) //} //this.loginCompletedHandler('login'); loading.dismiss(); //this.history?.replace('/'); }, 1000); } lookPwd(){ if(this.eyePwd == false){ this.colorEye = 'danger'; this.nameIcon = 'eye-off'; this.eyePwd = true; }else { this.colorEye = 'primary'; this.nameIcon = 'eye'; this.eyePwd = false; } } render() { return ( <div class="container" id="app-login"> <div class="div-login"> <p class="p-login">LOGIN</p> <form onSubmit={(e) => this.handleSubmit(e)} class=""> <ion-input placeholder="Nomor Telepon Anda" required minlength={2} name="userName" class="input" onInput={(event) => this.changeValue(event)}></ion-input> {this.eyePwd == false ? <ion-input type="password" required minlength={3} placeholder="Password" class="input" name="userPass" onInput={(event) => this.changeValue(event)}> <ion-buttons slot="end" class="btns-eye" onClick={() => this.lookPwd()}> <ion-button fill="clear" color={this.colorEye} type="button"> <ion-icon name={this.nameIcon} slot="icon-only" class="eye-pwd"></ion-icon> </ion-button> </ion-buttons> </ion-input> : <ion-input type="text" placeholder="Password" class="input" name="userPass" onInput={(event) => this.changeValue(event)}> <ion-buttons slot="end" class="btns-eye" onClick={() => this.lookPwd()}> <ion-button fill="clear" color={this.colorEye} type="button"> <ion-icon name={this.nameIcon} slot="icon-only" class="eye-pwd"></ion-icon> </ion-button> </ion-buttons> </ion-input> } <div class="div-regis"> {/* <stencil-route-link class="label-2" url="/register"> Daftar Akun? </stencil-route-link> */} <p class="label-2"> <a href="/register">Daftar Akun?</a> </p> <p class="p-forgot"> <a href="/forgot-password">Lupa Password?</a> </p> </div> <button type="submit" class="btn-login"> LOGIN </button> </form> </div> </div> ); } }
from fastapi import APIRouter, HTTPException, Depends from database import SessionLocal, engine from schemas import SignUpModel, LoginModel from models import User from werkzeug.security import generate_password_hash, check_password_hash from fastapi_jwt_auth import AuthJWT from fastapi.encoders import jsonable_encoder auth_router = APIRouter( prefix='/auth', tags=['auth'] ) session = SessionLocal(bind=engine) @auth_router.get('/') async def hello(Authorize: AuthJWT = Depends()): try: Authorize.jwt_required() except Exception as e: raise HTTPException(status_code=401, detail="Invalid token") return {"message": "Hello World"} @auth_router.post('/signup', status_code=201) async def sign_up(user: SignUpModel): db_email = session.query(User).filter(User.email == user.email).first() if db_email is not None: raise HTTPException(status_code=404, detail='Email already exist') db_username = session.query(User).filter(User.username == user.username).first() if db_username is not None: raise HTTPException(status_code=404, detail='User already exist') new_user = User( username=user.username, email=user.email, password=generate_password_hash(user.password), is_active=user.is_active, is_staff=user.is_staff ) session.add(new_user) session.commit() session.refresh(new_user) return new_user # login route @auth_router.post('/login', status_code=200) async def login(user: LoginModel, Authorize: AuthJWT = Depends()): db_user = session.query(User).filter(User.username == user.username).first() if db_user and check_password_hash(db_user.password, user.password): access_token = Authorize.create_access_token(subject=db_user.username) refresh_token = Authorize.create_refresh_token(subject=db_user.username) response = { "access": access_token, "refresh": refresh_token } return jsonable_encoder(response) raise HTTPException(status_code=400, detail="Invalid username or password") # refreshing tokens @auth_router.get('/refresh') async def refresh_token(Authorize: AuthJWT = Depends()): try: Authorize.jwt_refresh_token_required() except Exception as e: raise HTTPException(status_code=401, detail="Invalid refresh token") current_user = Authorize.get_jwt_subject() access_token = Authorize.create_access_token(subject=current_user) return jsonable_encoder({"access": access_token})
import 'dart:async'; import 'dart:io'; import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; Future<void> main() async{ WidgetsFlutterBinding.ensureInitialized(); final cameras = await availableCameras(); final firstCamera = cameras.first; runApp( MaterialApp( theme: ThemeData.light(), home: TakePictureScreen( camera: firstCamera, ), ), ); } class TakePictureScreen extends StatefulWidget{ final CameraDescription camera; const TakePictureScreen({ //Key key, @required this.camera}); //}) : super(key: key); @override TakePictureScreenState createState() => TakePictureScreenState(); } class TakePictureScreenState extends State<TakePictureScreen>{ CameraController _controller; Future<void> _initialzeControllerFuture; @override void initState(){ super.initState(); _controller = CameraController( widget.camera, ResolutionPreset.medium, ); _initialzeControllerFuture = _controller.initialize(); } @override void dispose(){ _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context){ return Scaffold( appBar: AppBar( title: Text('Take A Picture'), backgroundColor: Theme.of(context).primaryColor ), body: FutureBuilder<void>( future: _initialzeControllerFuture, builder: (context, snapshot){ //if(snapshot.connectionState == ConnectionState.done){ return CameraPreview(_controller); //} else { // return Center(child: CircularProgressIndicator()); }, ), floatingActionButton: FloatingActionButton( child: Icon(Icons.camera_alt), onPressed: () async{ try{ await _initialzeControllerFuture; final path = join( (await getTemporaryDirectory()).path, '${DateTime.now()}.png', ); await _controller.takePicture(path); Navigator.push( context, MaterialPageRoute( builder: (context) => DisplayPictureScreen(imagePath: path), ), ); } catch(e){ print(e); } }, ), ); } } class DisplayPictureScreen extends StatelessWidget{ final String imagePath; const DisplayPictureScreen({Key key, this.imagePath}): super(key:key); @override Widget build(BuildContext context){ return Scaffold( appBar: AppBar(title: Text('Display the picture')), body: Image.file(File(imagePath)), ); } }
// // ApiCalls.swift // CarMaintenanceReminder // // Created by YASSINE on 24/7/2023. // import Foundation import Combine class Token : ObservableObject { static let userToken = Token() @Published var currentToken : String = "" func setToken(token : String){ currentToken = token } } class LoginViewModel: ObservableObject { @Published var isLoggedIn = false @Published var showError = false @Published var errorMessage = "" func loginUser(email: String, password: String) async { DispatchQueue.main.async{ self.showError = false self.isLoggedIn = false self.errorMessage = "" } guard let url = URL(string: "http://localhost:9000/user/login") else { DispatchQueue.main.async{ self.showError = true self.errorMessage = "Invalid URL" } return } let body: [String: String] = ["email": email, "password": password] var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") do { request.httpBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) } catch _ { DispatchQueue.main.async{ self.showError = true self.errorMessage = "Veuillez réessayer" } } do { let (data, _) = try await URLSession.shared.data(for: request) let response = try JSONDecoder().decode(tokenModel.self, from: data) Token.userToken.setToken(token: response.token) DispatchQueue.main.async{ self.isLoggedIn = true } } catch { do{ let (data, _) = try await URLSession.shared.data(for: request) let errorJSON = try? JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ self.showError = true self.errorMessage = errorJSON?.message ?? "" } }catch{ DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } } } class RegisterViewModel: ObservableObject { @Published var isLoggedIn = false @Published var showError = false @Published var errorMessage = "" func registerUser(username: String, email: String, password: String, confirmPassword: String) async { DispatchQueue.main.async{ self.showError = false self.isLoggedIn = false self.errorMessage = "" } guard let url = URL(string: "http://localhost:9000/user/register") else { self.showError = true self.errorMessage = "Invalid URL" return } let body: [String: String] = ["username" : username, "email" : email, "password" : password, "confirmPassword" : confirmPassword] var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") do { request.httpBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) } catch _ { self.showError = true self.errorMessage = "Veuillez réessayer" } do { let (data, _) = try await URLSession.shared.data(for: request) let response = try JSONDecoder().decode(tokenModel.self, from: data) Token.userToken.setToken(token: response.token) DispatchQueue.main.async{ self.isLoggedIn = true } } catch { do{ let (data, _) = try await URLSession.shared.data(for: request) let errorJSON = try? JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ self.showError = true self.errorMessage = errorJSON?.message ?? "" } }catch{ DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } } } class CloseRemindersModel: ObservableObject { @Published var dataFound : SortedRemindersStruct? = nil @Published var showError = false @Published var errorMessage = "" func getAll() async { DispatchQueue.main.async{ self.showError = false self.errorMessage = "" } guard let url = URL(string: "http://localhost:9000/reminders/sortedall") else { DispatchQueue.main.async{ self.showError = true self.errorMessage = "Invalid URL" } return } var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue("Bearer \(Token.userToken.currentToken)", forHTTPHeaderField: "Authorization") do { let (data, _) = try await URLSession.shared.data(for: request) let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let response = try decoder.decode(SortedRemindersStruct.self, from: data) DispatchQueue.main.async{ self.dataFound = response } } catch { do{ let (data, _) = try await URLSession.shared.data(for: request) let errorJSON = try? JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ self.showError = true self.errorMessage = errorJSON?.message ?? "" } }catch{ DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } } } class UserNameModel: ObservableObject { @Published var isAuthenticated = false @Published var dataFound : String = "" @Published var showError = false @Published var errorMessage = "" func get() async { DispatchQueue.main.async{ self.showError = false self.errorMessage = "" } guard let url = URL(string: "http://localhost:9000/user/name") else { DispatchQueue.main.async{ self.showError = true self.errorMessage = "Invalid URL" } return } var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue("Bearer \(Token.userToken.currentToken)", forHTTPHeaderField: "Authorization") do { let (data, _) = try await URLSession.shared.data(for: request) let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let response = try decoder.decode(errorModel.self, from: data) DispatchQueue.main.async{ self.dataFound = response.message } } catch { do{ let (data, _) = try await URLSession.shared.data(for: request) let errorJSON = try? JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ self.showError = true self.errorMessage = errorJSON?.message ?? "" } }catch{ DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } } func verify() async { DispatchQueue.main.async{ self.showError = false self.errorMessage = "" } guard let url = URL(string: "http://localhost:9000/user/verify") else { DispatchQueue.main.async{ self.isAuthenticated = false self.showError = true self.errorMessage = "Invalid URL" } return } var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue("Bearer \(Token.userToken.currentToken)", forHTTPHeaderField: "Authorization") do { let (data, _) = try await URLSession.shared.data(for: request) let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let response = try decoder.decode(authenticationModel.self, from: data) DispatchQueue.main.async{ self.isAuthenticated = response.authenticated } } catch { do{ let (data, _) = try await URLSession.shared.data(for: request) let errorJSON = try? JSONDecoder().decode(authenticationModel.self, from: data) DispatchQueue.main.async{ self.isAuthenticated = errorJSON?.authenticated ?? false self.showError = true } }catch{ DispatchQueue.main.async{ self.isAuthenticated = false self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } DispatchQueue.main.async{ self.isAuthenticated = false self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } } } class CarDataModel: ObservableObject { @Published var dataFound : [CarModelWithReminders] = [] @Published var showError = false @Published var sucess = false @Published var errorMessage = "" func addCar(brand: String, model: String, libelle: String) async { DispatchQueue.main.async{ self.showError = false self.sucess = false self.errorMessage = "" } guard let url = URL(string: "http://localhost:9000/cars/add") else { self.showError = true self.errorMessage = "Invalid URL" return } let body: [String: String] = ["brand" : brand, "model" : model, "libelle" : libelle] var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("Bearer \(Token.userToken.currentToken)", forHTTPHeaderField: "Authorization") do { request.httpBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) } catch _ { self.showError = true self.errorMessage = "Veuillez réessayer" } do { let (data, _) = try await URLSession.shared.data(for: request) let response = try JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ if response.status == "sucess" { self.sucess = true self.showError = false }else{ self.sucess = false self.showError = true self.errorMessage = response.message } } } catch { do{ let (data, _) = try await URLSession.shared.data(for: request) let errorJSON = try? JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ self.showError = true self.errorMessage = errorJSON?.message ?? "" } }catch{ DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } } func getAll() async { DispatchQueue.main.async{ self.showError = false self.errorMessage = "" } guard let url = URL(string: "http://localhost:9000/cars") else { DispatchQueue.main.async{ self.showError = true self.errorMessage = "Invalid URL" } return } var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue("Bearer \(Token.userToken.currentToken)", forHTTPHeaderField: "Authorization") do { let (data, _) = try await URLSession.shared.data(for: request) let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let response = try decoder.decode(CarModelData.self, from: data) DispatchQueue.main.async{ self.dataFound = response.data } } catch { do{ let (data, _) = try await URLSession.shared.data(for: request) let errorJSON = try? JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ self.showError = true self.errorMessage = errorJSON?.message ?? "" } }catch{ DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } } func deleteCar(carID : Int) async { DispatchQueue.main.async{ self.showError = false self.errorMessage = "" } guard let url = URL(string: "http://localhost:9000/cars/\(carID)") else { DispatchQueue.main.async{ self.showError = true self.errorMessage = "Invalid URL" } return } var request = URLRequest(url: url) request.httpMethod = "DELETE" request.setValue("Bearer \(Token.userToken.currentToken)", forHTTPHeaderField: "Authorization") do { let (data, _) = try await URLSession.shared.data(for: request) let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let response = try decoder.decode(errorModel.self, from: data) DispatchQueue.main.async{ if response.status == "sucess" { self.sucess = true }else{ self.showError = true self.errorMessage = response.message } } } catch { do{ let (data, _) = try await URLSession.shared.data(for: request) let errorJSON = try? JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ self.showError = true self.errorMessage = errorJSON?.message ?? "" } }catch{ DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } } } class RemindersDataModel: ObservableObject { @Published var sucess = false @Published var showError = false @Published var errorMessage = "" func formatDateToString(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" dateFormatter.timeZone = TimeZone(identifier: "UTC") return dateFormatter.string(from: date) } func addReminder(carID: Int, name: String, beginDate: Date, distance: Int, timePeriodicity: Int, distancePeriodicity: Int, price: Double ) async { DispatchQueue.main.async{ self.showError = false self.sucess = false self.errorMessage = "" } guard let url = URL(string: "http://localhost:9000/reminders/add/\(carID)") else { self.showError = true self.errorMessage = "Invalid URL" return } let dateFormated = formatDateToString(date: beginDate) var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("Bearer \(Token.userToken.currentToken)", forHTTPHeaderField: "Authorization") let jsonEncoder = JSONEncoder() jsonEncoder.keyEncodingStrategy = .convertToSnakeCase do { let body = ReminderToAdd(name: name, beginDate: dateFormated, price: price, distance: distance, timePeriodicty: timePeriodicity, distancePeriodicty: distancePeriodicity) let jsonData = try jsonEncoder.encode(body) request.httpBody = jsonData } catch { self.showError = true self.errorMessage = "Veuillez réessayer" return } do { let (data, _) = try await URLSession.shared.data(for: request) let response = try JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ if response.status == "sucess" { self.sucess = true self.showError = false }else{ self.sucess = false self.showError = true self.errorMessage = response.message } } } catch { do{ let (data, _) = try await URLSession.shared.data(for: request) let errorJSON = try? JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ self.showError = true self.errorMessage = errorJSON?.message ?? "" } }catch{ DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } } func delete(reminderId : Int) async { DispatchQueue.main.async{ self.showError = false self.errorMessage = "" } guard let url = URL(string: "http://localhost:9000/reminders/\(reminderId)") else { DispatchQueue.main.async{ self.showError = true self.errorMessage = "Invalid URL" } return } var request = URLRequest(url: url) request.httpMethod = "DELETE" request.setValue("Bearer \(Token.userToken.currentToken)", forHTTPHeaderField: "Authorization") do { let (data, _) = try await URLSession.shared.data(for: request) let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let response = try decoder.decode(errorModel.self, from: data) DispatchQueue.main.async{ if response.status == "sucess"{ self.sucess = true }else{ self.showError = true self.errorMessage = response.message } } } catch { do{ let (data, _) = try await URLSession.shared.data(for: request) let errorJSON = try? JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ self.showError = true self.errorMessage = errorJSON?.message ?? "" } }catch{ DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } } func reset(reminderId : Int) async { DispatchQueue.main.async{ self.showError = false self.errorMessage = "" } guard let url = URL(string: "http://localhost:9000/reminders/reset/\(reminderId)") else { DispatchQueue.main.async{ self.showError = true self.errorMessage = "Invalid URL" } return } var request = URLRequest(url: url) request.httpMethod = "PATCH" request.setValue("Bearer \(Token.userToken.currentToken)", forHTTPHeaderField: "Authorization") do { let (data, _) = try await URLSession.shared.data(for: request) let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let response = try decoder.decode(errorModel.self, from: data) DispatchQueue.main.async{ if response.status == "sucess"{ self.sucess = true }else{ self.showError = true self.errorMessage = response.message } } } catch { do{ let (data, _) = try await URLSession.shared.data(for: request) let errorJSON = try? JSONDecoder().decode(errorModel.self, from: data) DispatchQueue.main.async{ self.showError = true self.errorMessage = errorJSON?.message ?? "" } }catch{ DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } DispatchQueue.main.async{ self.showError = true self.errorMessage = self.errorMessage != "" ? self.errorMessage : "Veuillez réessayer" } } } }
// // PointsView.swift // Bulls Eye // // Created by Celil Çağatay Gedik on 12.09.2022. //aa import SwiftUI struct PointsView: View { @Binding var alertIsVisible : Bool @Binding var sliderValue : Double @Binding var game : Game var body: some View { let roundedValue = Int(sliderValue.rounded()) let points = game.points(sliderValue: roundedValue) VStack(spacing: 10) { InstructionText(text: "The slider's value is") BigNumberText(text: String(roundedValue)) BodyText(text: "You Scored \(points) Points\n🎉🎉🎉") Button(action: { withAnimation { alertIsVisible = false } game.startNewRound(points: points) } ) { ButtonText(text: "Start New Round") } } .padding() .frame(maxWidth: 300) .background(Color("BackgroundColor")) .cornerRadius(Constants.General.roundedRectCornerRadius) .shadow(radius: 10, x: 5 , y:5) .transition(.scale) } struct PointsView_Previews: PreviewProvider { static private var alertIsVisible = Binding.constant(false) static private var sliderValue = Binding.constant(50.0) static private var game = Binding.constant(Game()) static var previews: some View { PointsView(alertIsVisible: alertIsVisible, sliderValue: sliderValue, game: game) PointsView(alertIsVisible: alertIsVisible, sliderValue: sliderValue, game: game) .previewLayout(.fixed(width: 568, height: 320)) PointsView(alertIsVisible: alertIsVisible, sliderValue: sliderValue, game: game) .preferredColorScheme(.dark) PointsView(alertIsVisible: alertIsVisible, sliderValue: sliderValue, game: game) .previewLayout(.fixed(width: 568, height: 320)) .preferredColorScheme(.dark) } } }
package com.lcaohoanq; import com.lcaohoanq.mode.WindowsShutdown; import com.lcaohoanq.mode.WindowsSleep; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.InputStream; import java.net.URL; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.SwingWorker; import javax.swing.border.Border; public class GUI extends JFrame implements ActionListener { private JPanel jPanel = new JPanel(new GridLayout(3, 1)); private JLabel jLabel = new JLabel("Enter the time schedule to...", JLabel.CENTER); private JTextField jTextField = new JTextField(); private JPanel jPanelBottom = new JPanel(new GridLayout(1, 4)); private JButton jButtonShutdown = new JButton("Shutdown"); private JButton jButtonRestart = new JButton("Restart"); private JButton jButtonSleep = new JButton("Sleep"); private JButton jButtonHibernate = new JButton("Hibernate"); public URL iconURL = GUI.class.getResource("/logo.png"); public Image icon = Toolkit.getDefaultToolkit().createImage(iconURL); private JFrame jFrameProgressBar = new JFrame(); private JPanel jPanelProgressBar = new JPanel(new GridLayout(2, 1)); private JLabel jLabelProgress = new JLabel("", JLabel.CENTER); private JProgressBar jProgressBar = new JProgressBar(0, 100); AudioHandler audioHandler = new AudioHandler(); private int result; private String userChoice; private String timeSchedule; public GUI() { this.setTitle("Power Management"); this.setSize(500, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setIconImage(icon); this.setResizable(false); initPanelButton(); initPanelProgressBar(); } private void initPanelProgressBar() { Border border = BorderFactory.createEmptyBorder(10, 20, 10, 20); jFrameProgressBar.setTitle("Loading..."); jFrameProgressBar.setIconImage(icon); jFrameProgressBar.setSize(250, 100); jFrameProgressBar.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); jFrameProgressBar.setResizable(false); jFrameProgressBar.setLocationRelativeTo(null); jFrameProgressBar.setVisible(false); jFrameProgressBar.add(jPanelProgressBar); jPanelProgressBar.add(jLabelProgress); jPanelProgressBar.add(jProgressBar); jPanel.setBorder(border); } private void initPanelButton() { Border border = BorderFactory.createEmptyBorder(10, 20, 10, 20); jLabel.setFont(new Font("Roboto", Font.BOLD, 15)); jTextField.setFont(new Font("Roboto", Font.PLAIN, 20)); jTextField.setHorizontalAlignment(JTextField.CENTER); jPanel.add(jLabel); jPanel.add(jTextField); jButtonShutdown.setBackground(Color.RED); jButtonShutdown.setForeground(Color.WHITE); jButtonShutdown.setFont(new Font("Roboto", Font.BOLD, 15)); jButtonRestart.setBackground(Color.YELLOW); jButtonRestart.setForeground(Color.BLACK); jButtonRestart.setFont(new Font("Roboto", Font.BOLD, 15)); jButtonSleep.setBackground(Color.BLUE); jButtonSleep.setForeground(Color.WHITE); jButtonSleep.setFont(new Font("Roboto", Font.BOLD, 15)); jButtonHibernate.setBackground(Color.GREEN); jButtonHibernate.setForeground(Color.WHITE); jButtonHibernate.setFont(new Font("Roboto", Font.BOLD, 15)); jPanelBottom.add(jButtonShutdown); jPanelBottom.add(jButtonRestart); jPanelBottom.add(jButtonSleep); jPanelBottom.add(jButtonHibernate); List<JButton> buttons = List.of(jButtonShutdown, jButtonRestart, jButtonSleep, jButtonHibernate); buttons.stream().forEach(button -> button.addActionListener(this::actionPerformed)); jPanel.add(jPanelBottom); jPanel.setBorder(border); this.add(jPanel); } @Override public void actionPerformed(ActionEvent e) { userChoice = e.getActionCommand(); timeSchedule = this.jTextField.getText(); if (timeSchedule.isEmpty() || timeSchedule.equals("0")) { //show the progress bar result = JOptionPane.showConfirmDialog(null, "Are you sure to continue to " + e.getActionCommand() + " immediately ?", "Power Management", JOptionPane.YES_NO_OPTION); if(result == JOptionPane.YES_OPTION){ jFrameProgressBar.setVisible(true); audioHandler.playAudio(); SwingWorker<Void, Void> worker = new SwingWorker<>() { @Override protected Void doInBackground() throws Exception { for (int i = 0; i <= 100; i++) { jProgressBar.setValue(i); if (i == 25) { jLabelProgress.setText("Loading."); } else if (i == 50) { jLabelProgress.setText("Loading.."); } else if (i == 75) { jLabelProgress.setText("Loading..."); } else if (i == 100) { jLabelProgress.setText("Loading.... Done!"); } Thread.sleep(50); // Simulate loading time } return null; } @Override protected void done() { //do action immediately switch (userChoice) { case "Shutdown": WindowsShutdown.shutdown(); break; case "Restart": System.out.println("Restart 0s"); break; case "Sleep": WindowsSleep.sleep(); break; case "Hibernate": System.out.println("Hibernate 0s"); break; } } }; worker.execute(); } } else if (Integer.parseInt(timeSchedule) > 0) { result = JOptionPane.showConfirmDialog(null, "Are you sure to continue to " + e.getActionCommand() + " in " + timeSchedule + " seconds?", "Power Management", JOptionPane.YES_NO_OPTION); if(result == JOptionPane.YES_OPTION){ //do action with the time specify switch (userChoice) { case "Shutdown": System.out.println("Shutdown xs"); break; case "Restart": System.out.println("Restart xs"); break; case "Sleep": System.out.println("Sleep xs"); break; case "Hibernate": System.out.println("Hibernate xs"); break; } } } else { JOptionPane.showMessageDialog(null, "Please enter a number greater or equals than 0", "Power Management", JOptionPane.ERROR_MESSAGE); } } }
/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.accessibility.braille.brltty; import android.os.Parcel; import android.os.Parcelable; /** * An input event, originating from a braille display. * * <p>An event contains a command that is a high-level representation of the key or key combination * that was pressed on the display such as a navigation key or braille keyboard combination. For * some commands, there is also an integer argument that contains additional information. * * <p>Members of this class are accessed by native brltty code. */ public class BrailleInputEvent implements Parcelable { // Movement commands. /** Keyboard command: Used when there is no actual command. */ public static final int CMD_NONE = -1; /** Keyboard command: Navigate upwards. */ public static final int CMD_NAV_LINE_PREVIOUS = 1; /** Keyboard command: Navigate downwards. */ public static final int CMD_NAV_LINE_NEXT = 2; /** Keyboard command: Navigate left one item. */ public static final int CMD_NAV_ITEM_PREVIOUS = 3; /** Keyboard command: Navigate right one item. */ public static final int CMD_NAV_ITEM_NEXT = 4; /** Keyboard command: Navigate one display window to the up. */ public static final int CMD_NAV_PAN_UP = 5; /** Keyboard command: Navigate one display window to the down. */ public static final int CMD_NAV_PAN_DOWN = 6; /** Keyboard command: Navigate to the top or beginning. */ public static final int CMD_NAV_TOP = 7; /** Keyboard command: Navigate to the bottom or end. */ public static final int CMD_NAV_BOTTOM = 8; /** Keyboard command: Navigate previous character. */ public static final int CMD_CHARACTER_PREVIOUS = 9; /** Keyboard command: Navigate next character. */ public static final int CMD_CHARACTER_NEXT = 10; /** Keyboard command: Navigate previous word. */ public static final int CMD_WORD_PREVIOUS = 11; /** Keyboard command: Navigate next word. */ public static final int CMD_WORD_NEXT = 12; /** Keyboard command: Navigate next window. */ public static final int CMD_WINDOW_PREVIOUS = 13; /** Keyboard command: Navigate previous window. */ public static final int CMD_WINDOW_NEXT = 14; /** Keyboard command: Navigate backward by reading granularity or adjust reading control down. */ public static final int CMD_NAVIGATE_BY_READING_GRANULARITY_OR_ADJUST_READING_CONTROL_BACKWARD = 15; /** Keyboard command: Navigate forward by reading granularity or adjust reading control up. */ public static final int CMD_NAVIGATE_BY_READING_GRANULARITY_OR_ADJUST_READING_CONTROL_FORWARD = 16; // Activation commands. /** Keyboard command: Activate the currently selected/focused item. */ public static final int CMD_ACTIVATE_CURRENT = 20; /** Keyboard command: Long press the currently selected/focused item. */ public static final int CMD_LONG_PRESS_CURRENT = 21; // Scrolling. /** Keyboard command: Scroll backward. */ public static final int CMD_SCROLL_BACKWARD = 30; /** Keyboard command: Scroll forward. */ public static final int CMD_SCROLL_FORWARD = 31; // Selection commands. /** Keyboard command: Set the start ot the selection. */ public static final int CMD_SELECTION_START = 40; /** Keyboard command: Set the end of the selection. */ public static final int CMD_SELECTION_END = 41; /** Keyboard command: Select all content of the current field. */ public static final int CMD_SELECTION_SELECT_ALL = 42; /** Keyboard command: Cut the content of the selection. */ public static final int CMD_SELECTION_CUT = 43; /** Keyboard command: Copy the current selection. */ public static final int CMD_SELECTION_COPY = 44; /** Keyboard command: Paste the content of the clipboard at the current insertion point. */ public static final int CMD_SELECTION_PASTE = 45; /** * Keyboard command: Primary routing key pressed, typically used to move the insertion point or * click/tap on the item under the key. The argument is the zero-based position, relative to the * first cell on the display, of the cell that is closed to the key that was pressed. */ public static final int CMD_ROUTE = 50; /** * Keyboard command: Primary routing key long pressed, typically used to long press the item under * the key. The argument is the zero-based position, relative to the first cell on the display, of * the cell that is closed to the key that was pressed. */ public static final int CMD_LONG_PRESS_ROUTE = 51; // Braille keyboard input. /** * Keyboard command: A key combination was pressed on the braille keyboard. The argument contains * the dots that were pressed as a bitmask. */ public static final int CMD_BRAILLE_KEY = 60; // Editing keys. /** Keyboard command: Enter key. */ public static final int CMD_KEY_ENTER = 70; /** Keyboard command: Delete backward. */ public static final int CMD_KEY_DEL = 71; /** Keyboard command: Delete a word backward. */ public static final int CMD_DEL_WORD = 72; /** Keyboard command: Select previous character. */ public static final int CMD_SELECT_PREVIOUS_CHARACTER = 77; /** Keyboard command: Select next character. */ public static final int CMD_SELECT_NEXT_CHARACTER = 78; /** Keyboard command: Select previous word. */ public static final int CMD_SELECT_PREVIOUS_WORD = 79; /** Keyboard command: Select next word. */ public static final int CMD_SELECT_NEXT_WORD = 80; /** Keyboard command: Select previous line. */ public static final int CMD_SELECT_PREVIOUS_LINE = 81; /** Keyboard command: Select next line. */ public static final int CMD_SELECT_NEXT_LINE = 82; // Global navigation keys. /** Keyboard command: Back button. */ public static final int CMD_GLOBAL_BACK = 90; /** Keyboard command: Home button. */ public static final int CMD_GLOBAL_HOME = 91; /** Keyboard command: Recent apps button. */ public static final int CMD_GLOBAL_RECENTS = 92; /** Keyboard command: Show notifications. */ public static final int CMD_GLOBAL_NOTIFICATIONS = 93; /** Keyboard command: Quick Settings. */ public static final int CMD_QUICK_SETTINGS = 94; /** Keyboard command: All apps. */ public static final int CMD_ALL_APPS = 95; /** Keyboard command: Play or pause media. */ public static final int CMD_PLAY_PAUSE_MEDIA = 134; // Miscellaneous commands. /** Keyboard command: Invoke keyboard help. */ public static final int CMD_HELP = 100; /** Keyboard command: Edit custom label. */ public static final int CMD_EDIT_CUSTOM_LABEL = 117; /** Keyboard command: Open TalkBack menu. */ public static final int CMD_OPEN_TALKBACK_MENU = 118; /** Keyboard command: Switch to next input language. */ public static final int CMD_SWITCH_TO_NEXT_INPUT_LANGUAGE = 119; /** Keyboard command: Switch to next output language. */ public static final int CMD_SWITCH_TO_NEXT_OUTPUT_LANGUAGE = 120; /** Keyboard command: Navigate Braille display settings. */ public static final int CMD_BRAILLE_DISPLAY_SETTINGS = 121; /** Keyboard command: Navigate TalkBack settings. */ public static final int CMD_TALKBACK_SETTINGS = 122; /** Keyboard command: Turn off braille display. */ public static final int CMD_TURN_OFF_BRAILLE_DISPLAY = 123; /** Keyboard command: Mute/Unmute voice feedback. */ public static final int CMD_TOGGLE_VOICE_FEEDBACK = 124; /** Keyboard command: Switch to previous reading control. */ public static final int CMD_PREVIOUS_READING_CONTROL = 125; /** Keyboard command: Switch to next reading control. */ public static final int CMD_NEXT_READING_CONTROL = 126; /** Keyboard command: Toggle braille grade. */ public static final int CMD_TOGGLE_BRAILLE_GRADE = 127; /** Keyboard command: In editing text, navigate to the top. In common state, activate key. */ public static final int CMD_NAV_TOP_OR_KEY_ACTIVATE = 128; /** Keyboard command: In editing text, navigate to the bottom. In common state, activate key. */ public static final int CMD_NAV_BOTTOM_OR_KEY_ACTIVATE = 129; /** Keyboard command: Stop reading. */ public static final int CMD_STOP_READING = 130; /** Keyboard command: Start or stop auto scroll. */ public static final int CMD_TOGGLE_AUTO_SCROLL = 131; /** Keyboard command: Increase auto scroll duration. */ public static final int CMD_INCREASE_AUTO_SCROLL_DURATION = 132; /** Keyboard command: Decrease auto scroll duration. */ public static final int CMD_DECREASE_AUTO_SCROLL_DURATION = 133; // Web content commands. /** Keyboard command: Next heading in page. */ public static final int CMD_HEADING_NEXT = 110; /** Keyboard command: Previous heading in page. */ public static final int CMD_HEADING_PREVIOUS = 111; /** Keyboard command: Next control in page. */ public static final int CMD_CONTROL_NEXT = 112; /** Keyboard command: Previous control in page. */ public static final int CMD_CONTROL_PREVIOUS = 113; /** Keyboard command: Next link in page. */ public static final int CMD_LINK_NEXT = 114; /** Keyboard command: Previous link in page. */ public static final int CMD_LINK_PREVIOUS = 115; /** Keyboard command: Toggle Screen search. */ public static final int CMD_TOGGLE_SCREEN_SEARCH = 116; // Meanings of the argument to a command. /** This command doesn't have an argument. */ public static final int ARGUMENT_NONE = 0; /** * The lower order bits of the arguemnt to this command represent braille dots. Dot 1 is * represented by the rightmost bit and so on until dot 8, which is represented by bit 7, counted * from the right. */ public static final int ARGUMENT_DOTS = 1; /** The argument represents a 0-based position on the display counted from the leftmost cell. */ public static final int ARGUMENT_POSITION = 2; private final int command; private final int argument; private final long eventTime; public BrailleInputEvent(int command, int argument, long eventTime) { this.command = command; this.argument = argument; this.eventTime = eventTime; } /** Returns the keyboard command that this event represents. */ public int getCommand() { return command; } /** * Returns the command-specific argument of the event, or zero if the command doesn't have an * argument. See the individual command constants for more details. */ public int getArgument() { return argument; } /** * Returns the approximate time when this event happened as returned by {@link * android.os.SystemClock#uptimeMillis}. */ public long getEventTime() { return eventTime; } /** Returns the type of argument for the given {@code command}. */ public static int argumentType(int command) { switch (command) { case CMD_SELECTION_START: case CMD_SELECTION_END: case CMD_ROUTE: case CMD_LONG_PRESS_ROUTE: return ARGUMENT_POSITION; case CMD_BRAILLE_KEY: return ARGUMENT_DOTS; default: return ARGUMENT_NONE; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("BrailleInputEvent {"); sb.append("cmd="); sb.append(command); sb.append(", arg="); sb.append(argument); sb.append("}"); return sb.toString(); } // For Parcelable support. public static final Creator<BrailleInputEvent> CREATOR = new Creator<BrailleInputEvent>() { @Override public BrailleInputEvent createFromParcel(Parcel in) { return new BrailleInputEvent(in); } @Override public BrailleInputEvent[] newArray(int size) { return new BrailleInputEvent[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeInt(command); out.writeInt(argument); out.writeLong(eventTime); } private BrailleInputEvent(Parcel in) { command = in.readInt(); argument = in.readInt(); eventTime = in.readLong(); } }
-- author 테이블에 post_count 라는 컬럼(int) 추가 alter table author ADD column post_count int; alter table author modify colum post_count int DEFAULT 0; -- post에 글 쓴 후, author 테이블에 post_count 값 +1 => 트랜잭션 start transaction; update author set post_count = post_count + 1 where id = 10; insert into post(title, author_id) value('hello word!', 5); -- 위 쿼리들이 정상실행이라면 x , 실패 y -> 분기처리 procedure commit; -- 또는 rollback; -- stored 프로시저를 활용한 트랜잭션 테스트 DELIMITER // CREATE PROCEDURE InsertPostAndUpdateAuthor() BEGIN DECLARE exit handler for SQLEXCEPTION BEGIN ROLLBACK; END; -- 트랜잭션 시작 START TRANSACTION; -- UPDATE 구문 UPDATE author SET post_count = post_count + 1 where id = 1; -- INSERT 구문 insert into post(title, author_id) values('hello world java', 5); -- 모든 작업이 성공했을 때 커밋 COMMIT; END // DELIMITER ; CALL InsertPostAndUpdateAuthor();
import pdfplumber import os class ReadFiles: folder: list def __init__(self, folder): self.folder = folder print(self.folder) return def filename(self): """ Reading files names which are only of PDF file formats. """ fullname: list for folder, sub_folder, files in os.walk(self.folder): fullname = [os.path.join( folder, names) for names in files if names.endswith(".pdf")] return fullname class InfoExtract: """ Reading the PDF files provided in the ReadFiles """ def __init__(self, all_names): self.all_names = all_names return def name_split(self): """ Return the full_path of the file and filename of the file. """ path_name: str name: str name_called = [] for fullname in self.all_names: path_name, name = fullname, str(os.path.split(fullname)[-1]).split(".")[0] name_called.append([path_name, name]) return name_called def extract(self): single_name: list single_name = self.name_split() for path_name, name in single_name: with open(os.path.join(os.path.split(path_name)[0], name+".txt"), "w") as fyle: with pdfplumber.open(path_name) as pdf: for number, page in enumerate(pdf.pages, 1): print('--- page', number, '---') text = page.extract_text() fyle.write(text) rd = ReadFiles(os.getcwd()) info = InfoExtract(rd.filename()) info.extract()
import React, { useState, useEffect } from "react"; import axios from "axios"; function App() { const [message, setMessage] = useState(""); const [inputText, setInputText] = useState(""); const [generatedImage, setGeneratedImage] = useState(null); useEffect(() => { axios .get("http://localhost:3001") .then((response) => { setMessage(response.data); }) .catch((error) => { console.error(error); }); }, []); const handleTextareaChange = (event) => { setInputText(event.target.value); }; const generateImage = async () => { try { const response = await axios.post( "http://localhost:3001/generate-image", { htmlContent: `<html><body><h1>${inputText}</h1></body></html>`, }, { responseType: "blob" } ); const imageUrl = URL.createObjectURL(new Blob([response.data])); setGeneratedImage(imageUrl); } catch (error) { console.error(error); } }; const downloadImage = () => { // Créez un lien pour le téléchargement const downloadLink = document.createElement("a"); downloadLink.href = generatedImage; downloadLink.download = "generated_image.png"; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); }; return ( <div className="App"> <h1>Application React</h1> <p>Message du serveur Node.js : {message}</p> <textarea rows="4" cols="50" value={inputText} onChange={handleTextareaChange} placeholder="Entrez du texte ici..." /> <br /> <br /> {generatedImage && ( <div> <h2>Image générée :</h2> <img src={generatedImage} alt="Image générée" /> <button onClick={downloadImage} style={{ backgroundColor: "#007bff", color: "#fff", border: "none", padding: "10px 20px", fontSize: "16px", cursor: "pointer", borderRadius: "5px", marginTop: "10px", boxShadow: "0px 4px 6px rgba(0, 0, 0, 0.1)", }} > Télécharger l'image </button> </div> )} <button onClick={generateImage} style={{ backgroundColor: "#007bff", color: "#fff", border: "none", padding: "10px 20px", fontSize: "16px", cursor: "pointer", borderRadius: "5px", marginTop: "20px", boxShadow: "0px 4px 6px rgba(0, 0, 0, 0.1)", }} > Générer une image </button> </div> ); } export default App;
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ import { Observable } from 'rxjs'; import type { SavedObjectUnsanitizedDoc } from '@kbn/core-saved-objects-server'; import type { IndexMapping } from '../mappings'; /** @internal */ export interface IKibanaMigrator { readonly kibanaVersion: string; /** * Migrates the mappings and documents in the Kibana index. By default, this will run only * once and subsequent calls will return the result of the original call. * * @param options.rerun - If true, method will run a new migration when called again instead of * returning the result of the initial migration. This should only be used when factors external * to Kibana itself alter the kibana index causing the saved objects mappings or data to change * after the Kibana server performed the initial migration. * * @remarks When the `rerun` parameter is set to true, no checks are performed to ensure that no migration * is currently running. Chained or concurrent calls to `runMigrations({ rerun: true })` can lead to * multiple migrations running at the same time. When calling with this parameter, it's expected that the calling * code should ensure that the initial call resolves before calling the function again. * * @returns - A promise which resolves once all migrations have been applied. * The promise resolves with an array of migration statuses, one for each * elasticsearch index which was migrated. */ runMigrations(options?: { rerun?: boolean }): Promise<MigrationResult[]>; prepareMigrations(): void; getStatus$(): Observable<KibanaMigratorStatus>; /** * Gets all the index mappings defined by Kibana's enabled plugins. */ getActiveMappings(): IndexMapping; /** * Migrates an individual doc to the latest version, as defined by the plugin migrations. * * @param doc - The saved object to migrate * @returns `doc` with all registered migrations applied. */ migrateDocument(doc: SavedObjectUnsanitizedDoc): SavedObjectUnsanitizedDoc; } /** @internal */ export interface KibanaMigratorStatus { status: MigrationStatus; result?: MigrationResult[]; waitingIndex?: string; } /** @internal */ export type MigrationStatus = | 'waiting_to_start' | 'waiting_for_other_nodes' | 'running' | 'completed'; /** @internal */ export type MigrationResult = | { status: 'skipped' } | { status: 'patched'; destIndex: string; elapsedMs: number; } | { status: 'migrated'; destIndex: string; sourceIndex: string; elapsedMs: number; };
package com.codreal.product.controller; import com.codreal.product.exceptions.NoProductExistInRepository; import com.codreal.product.models.Product; import com.codreal.product.services.ProductService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.List; @RestController @CrossOrigin(origins = "*") @RequiredArgsConstructor public class ProductController { @Autowired private ProductService productService; @GetMapping("/check") public String check(){ return "Working...!"; } @DeleteMapping("/product/{pid}") public Long deleteProduct(@PathVariable Long pid) { return productService.deleteProduct(pid); } @GetMapping("/all") public ResponseEntity<List<Product>> getAll(){ try{ return new ResponseEntity<List<Product>>(productService.getAll(), HttpStatus.OK); }catch (NoProductExistInRepository e){ return new ResponseEntity("List Not Found", HttpStatus.NOT_FOUND); } } @PostMapping("/add") public ResponseEntity<Product> add1(@RequestBody Product product) throws IOException { Product user=productService.add1(product); return new ResponseEntity<Product>(user,HttpStatus.OK); } @GetMapping("/get/by/pid/{pid}") public ResponseEntity<Product> getById(@PathVariable Long pid){ try { return new ResponseEntity<Product>(productService.getById(pid), HttpStatus.OK); }catch (NoProductExistInRepository e) { return new ResponseEntity("Product not found", HttpStatus.NOT_FOUND); } } }
type TechType = "Frontend" | "Backend" | "Tool"; export type Tech = { name: string; type: TechType; }; export type JobNote = { note: string; }; export type Job = { company: string; jobTitle: string; jobNotes: JobNote[]; tech: Record<string, string[]>; fromDate: Date; toDate: Date | "present"; }; export const myJobsBeLike: Job[] = [ { company: "Auro Digital", jobTitle: "Frontend Engineer", fromDate: new Date(2023, 5), toDate: "present", jobNotes: [ { note: "Developed a React application for an Order Management System (OMS) in the crypto trading domain", }, { note: "Implemented various components, including order placement forms, trade history, and real-time market data displays.", }, { note: "Integrated Redux into the application to manage and synchronize the global state across different components, Utilized Redux actions, reducers, and selectors to handle complex data flows and ensure data consistency throughout the application.", }, { note: "Addressed performance bottlenecks by identifying and resolving issues related to rendering, data fetching, and state management.", }, { note: "Integrated WebSockets into the application to establish real-time communication between the frontend and backend servers.", } ], tech: { Frontend: [ "React", "Next.js", "Typescript", "TailwindCSS", "BlueprintJS", "HTML", "CSS", "Javascript", ], Backend: ["Python", "Django", "Flask", "SQL"], Tools: ["Snowflake DB", "AWS Lambda", "AWS S3"], }, }, ];
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var chalk = require("chalk"); var path = require("path"); var ast_tools_1 = require("../../lib/ast-tools"); var config_1 = require("../../models/config"); var dynamic_path_parser_1 = require("../../utilities/dynamic-path-parser"); var app_utils_1 = require("../../utilities/app-utils"); var resolve_module_file_1 = require("../../utilities/resolve-module-file"); var stringUtils = require('ember-cli-string-utils'); var astUtils = require('../../utilities/ast-utils'); var findParentModule = require('../../utilities/find-parent-module').default; var Blueprint = require('../../ember-cli/lib/models/blueprint'); var getFiles = Blueprint.prototype.files; exports.default = Blueprint.extend({ name: 'pipe', description: '', aliases: ['p'], availableOptions: [ { name: 'flat', type: Boolean, description: 'Flag to indicate if a dir is created.' }, { name: 'spec', type: Boolean, description: 'Specifies if a spec file is generated.' }, { name: 'skip-import', type: Boolean, default: false, description: 'Allows for skipping the module import.' }, { name: 'module', type: String, aliases: ['m'], description: 'Allows specification of the declaring module.' }, { name: 'export', type: Boolean, default: false, description: 'Specifies if declaring module exports the pipe.' }, { name: 'app', type: String, aliases: ['a'], description: 'Specifies app name to use.' } ], beforeInstall: function (options) { var appConfig = app_utils_1.getAppFromConfig(this.options.app); if (options.module) { this.pathToModule = resolve_module_file_1.resolveModulePath(options.module, this.project, this.project.root, appConfig); } else { try { this.pathToModule = findParentModule(this.project.root, appConfig.root, this.generatePath); } catch (e) { if (!options.skipImport) { throw "Error locating module for declaration\n\t" + e; } } } }, normalizeEntityName: function (entityName) { var appConfig = app_utils_1.getAppFromConfig(this.options.app); var dynamicPathOptions = { project: this.project, entityName: entityName, appConfig: appConfig, dryRun: this.options.dryRun }; var parsedPath = dynamic_path_parser_1.dynamicPathParser(dynamicPathOptions); this.dynamicPath = parsedPath; return parsedPath.name; }, locals: function (options) { options.flat = options.flat !== undefined ? options.flat : config_1.CliConfig.getValue('defaults.pipe.flat'); options.spec = options.spec !== undefined ? options.spec : config_1.CliConfig.getValue('defaults.pipe.spec'); return { dynamicPath: this.dynamicPath.dir, flat: options.flat }; }, files: function () { var fileList = getFiles.call(this); if (this.options && !this.options.spec) { fileList = fileList.filter(function (p) { return p.indexOf('__name__.pipe.spec.ts') < 0; }); } return fileList; }, fileMapTokens: function (options) { var _this = this; // Return custom template variables here. return { __path__: function () { var dir = _this.dynamicPath.dir; if (!options.locals.flat) { dir += path.sep + options.dasherizedModuleName; } _this.generatePath = dir; return dir; } }; }, afterInstall: function (options) { var _this = this; var returns = []; var className = stringUtils.classify(options.entity.name + "Pipe"); var fileName = stringUtils.dasherize(options.entity.name + ".pipe"); var fullGeneratePath = path.join(this.project.root, this.generatePath); var moduleDir = path.parse(this.pathToModule).dir; var relativeDir = path.relative(moduleDir, fullGeneratePath); var normalizeRelativeDir = relativeDir.startsWith('.') ? relativeDir : "./" + relativeDir; var importPath = relativeDir ? normalizeRelativeDir + "/" + fileName : "./" + fileName; if (!options.skipImport) { if (options.dryRun) { this._writeStatusToUI(chalk.yellow, 'update', path.relative(this.project.root, this.pathToModule)); return; } returns.push(astUtils.addDeclarationToModule(this.pathToModule, className, importPath) .then(function (change) { return change.apply(ast_tools_1.NodeHost); }) .then(function (result) { if (options.export) { return astUtils.addExportToModule(_this.pathToModule, className, importPath) .then(function (change) { return change.apply(ast_tools_1.NodeHost); }); } return result; })); this._writeStatusToUI(chalk.yellow, 'update', path.relative(this.project.root, this.pathToModule)); this.addModifiedFile(this.pathToModule); } return Promise.all(returns); } }); //# sourceMappingURL=index.js.map
import { Component, OnInit } from '@angular/core'; import { trigger,style,transition,animate,keyframes,query,stagger } from '@angular/animations'; import { GoalDataService } from '../goal-data.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], animations: [ trigger('goals', [ transition('* => *', [ query(':enter', style({ opacity: 0 }), {optional: true}), query(':enter', stagger('300ms', [ animate('.6s ease-in', keyframes([ style({opacity: 0, transform: 'translateY(-75%)', offset: 0}), style({opacity: .5, transform: 'translateY(35px)', offset: .3}), style({opacity: 1, transform: 'translateY(0)', offset: 1}), ]))]), {optional: true}), query(':leave', stagger('300ms', [ animate('.6s ease-in', keyframes([ style({opacity: 1, transform: 'translateY(0)', offset: 0}), style({opacity: .5, transform: 'translateY(35px)', offset: .3}), style({opacity: 0, transform: 'translateY(-75%)', offset: 1}), ]))]), {optional: true}) ]) ]) ] }) export class HomeComponent implements OnInit { btnText:string='Add an item'; goalCount:number; goalText:string='add a goal'; goals=[]; constructor(private goalService : GoalDataService) { } ngOnInit(){ this.goalService.goal.subscribe(res => this.goals = res); this.goalCount = this.goals.length; this.goalService.changeGoal(this.goals); } addItem(){ this.goals.push(this.goalText); this.goalCount = this.goals.length; this.goalText = ''; this.goalService.changeGoal(this.goals); } removeItem(i){ this.goals.splice(i,1); this.goalService.changeGoal(this.goals); } }
<div class="mainDiv animated fadeIn"> <div fxLayout="row wrap" fxLayout.lt-sm="column" fxLayoutGap="32px" fxLayoutAlign="flex-start"> <h1 class="mat-display-1 animated fadeIn" fxFlex="0 1 calc(35% - 32px)" fxFlex.lt-md="0 1 calc(50% - 32px)" fxFlex.lt-sm="100%">{{ titulo | uppercase }}</h1> </div> <br> <mat-spinner *ngIf="spinner"></mat-spinner> <div fxLayoutGap="30px" fxLayout="row" fxLayout.xs="column" *ngIf="!spinner" class="animated fadeIn"> <div fxFlex="20%" fxFlex.lt-md="40%" fxFlex.lt-sm="50%" fxFlex.lt-xs="80%" fxLayoutGap="20px"> <img src="assets/images/test-perfil/profile.png"> </div> <div fxFlex="100%" fxFlex.lt-md="100%" fxFlex.lt-sm="100%" fxFlex.lt-xs="100%" fxLayoutGap="30px"> <mat-card> <form autocomplete="off" [formGroup]="forma" (ngSubmit)="guardarDatos()"> <div fxLayoutGap="30px" fxLayout="row" fxLayout.xs="column" fxLayout.sm="column"> <mat-form-field class="example-full-width"> <mat-label>Rut</mat-label> <input matInput placeholder="Rut" [disabled]="true" [value]="ID"> </mat-form-field> <mat-form-field class="example-full-width"> <mat-label>Email</mat-label> <input matInput placeholder="Email" formControlName="email"> <mat-hint align="start" color="red" *ngIf="emailNoValido"><strong>Campo no válido</strong></mat-hint> </mat-form-field> </div> <div fxLayoutGap="30px" fxLayout="row" fxLayout.xs="column" fxLayout.sm="column"> <mat-form-field class="example-full-width"> <mat-label>Nombre</mat-label> <input matInput placeholder="Nombre" formControlName="nombre"> <mat-hint align="start" color="red" *ngIf="nombreNoValido"><strong>Campo no válido</strong></mat-hint> </mat-form-field> <mat-form-field class="example-full-width"> <mat-label>Apellido Paterno</mat-label> <input matInput placeholder="Apellido Paterno" formControlName="apaterno"> <mat-hint align="start" *ngIf="apaternoNoValido"><strong>Campo no válido</strong></mat-hint> </mat-form-field> </div> <div fxLayoutGap="30px" fxLayout="row" fxLayout.xs="column" fxLayout.sm="column"> <mat-form-field class="example-full-width"> <mat-label>Apellido Materno</mat-label> <input matInput placeholder="Apellido Materno" formControlName="amaterno"> <mat-hint align="start" *ngIf="amaternoNoValido"><strong>Campo no válido</strong></mat-hint> </mat-form-field> <mat-form-field class="example-full-width"> <mat-label>Teléfono</mat-label> <span matPrefix>+56 &nbsp;</span> <input type="tel" matInput placeholder="123-456-7890" formControlName="telefono"> </mat-form-field> </div> <div class="foto" fxLayoutGap="30px" fxLayout="row" fxLayout.xs="column" fxLayout.sm="column"> <button type="button" mat-raised-button (click)="fileInput.click()">Seleccione Imagen de perfil</button> <input hidden #fileInput type="file" id="file" formControlName="foto"> </div> <div fxLayoutGap="30px" fxLayout="row" fxLayout.xs="column" fxLayout.sm="column"> <mat-form-field class="example-full-width"> <mat-label>Clave</mat-label> <input matInput type="password" placeholder="Debe contener mínimo 8 carácteres" formControlName="pass1" [class.is-invalid]="pass1NoValido"> </mat-form-field> <mat-form-field class="example-full-width"> <mat-label>Repita Clave</mat-label> <input matInput type="password" placeholder="Debe contener mínimo 8 carácteres" formControlName="pass2" [class.is-invalid]="pass2NoValido"> </mat-form-field> </div> <div fxLayout="column" fxLayoutAlign="end end" class="animated fadeIn"> <button id="add-button" type="submit" mat-fab color="primary" matTooltip="Guardar datos" matTooltipPosition="above"> <mat-icon>save</mat-icon> </button> </div> </form> </mat-card> </div> </div> </div>
/* * Created by Angot Rémi and Lhote Jean-Claude on 15/02/2022. * * MathALEA 2D : Software for animating online dynamic mathematics figures * https://coopmaths.fr * @Author Angot Rémi and Lhote Jean-Claude (contact@coopmaths.fr) * @License: GNU AGPLv3 https://www.gnu.org/licenses/agpl-3.0.html */ import { Element2D } from '../Element2D' import { Angle } from '../measures/Angle' import { Const } from '../measures/Const' import { Measure } from '../measures/Measure' import { Coords } from '../others/Coords' import { Point } from '../points/Point' import { OptionsGraphiques } from './Line' /** * Crée un arc de cercle d'extrémité A, de centre O et d'angle donné. * angle peut être un nombre (constante) ou une instance des classes dérivées de Measure */ export class Arc extends Element2D { center: Point point: Point point2: Coords angle: Measure horiz: Coords private _label: string constructor (O: Point, A: Point, angle: number | Measure, { color = 'black', thickness = 1, dashed = false, fill = 'none' }: OptionsGraphiques = {}) { super(O.parentFigure) this.center = O this.point = A if (typeof angle === 'number') this.angle = new Const(O.parentFigure, angle) else { this.angle = angle angle.addChild(this) } this.parentFigure.set.add(this) const B = Coords.rotationCoord(A, O, this.angle.value) this.point2 = B this._label = (O.label ?? '') + (A.label ?? '') + ' ' + this.angle.value.toString() + '°' this.horiz = { x: this.center.x + 1, y: this.center.y } const radius = this.parentFigure.xToSx(Point.distance(O, A)) const [large, sweep] = getLargeSweep(this.angle.value) this.g = document.createElementNS('http://www.w3.org/2000/svg', 'path') this.g.setAttribute('d', `M${this.parentFigure.xToSx(A.x)} ${this.parentFigure.yToSy(A.y)} A ${radius} ${radius} 0 ${large} ${sweep} ${this.parentFigure.xToSx(B.x)} ${this.parentFigure.yToSy(B.y)}`) // Ajout des segments ? // this.g.setAttribute('d', this.g.getAttribute('d') + `L ${this.parentFigure.xToSx(O.x)} ${this.parentFigure.yToSy(O.y)} Z`) this.color = color this.fill = fill this.thickness = thickness this.dashed = dashed this.parentFigure.svg.appendChild(this.g) A.addChild(this) O.addChild(this) } update (): void { try { const [large, sweep] = getLargeSweep(this.angle.value) this.point2 = Coords.rotationCoord(this.point, this.center, this.angle.value) const d = this.parentFigure.xToSx(Point.distance(this.center, this.point)) this.g.setAttribute('d', `M${this.parentFigure.xToSx(this.point.x)} ${this.parentFigure.yToSy(this.point.y)} A ${d} ${d} 0 ${large} ${sweep} ${this.parentFigure.xToSx(this.point2.x)} ${this.parentFigure.yToSy(this.point2.y)}`) } catch (error) { console.log('Erreur dans Arc.update()', error) this.exist = false } // Ajout des segments ? // this.g.setAttribute('d', this.g.getAttribute('d') + `L ${this.parentFigure.xToSx(this.center.x)} ${this.parentFigure.yToSy(this.center.y)} Z`) } // ToFix !!! Pas le même qu'en SVG get latex (): string { if (!this.isVisible || !this.exist) return '' try { const radius = Point.distance(this.center, this.point) const azimut = Angle.angleOriented(this.horiz, this.center, this.point) const anglefin = azimut + this.angle.value let latex = `\n\n\t% Arc ${this._label}` latex += `\n\t\\draw${this.tikzOptions} (${this.point.x},${this.point.y}) arc (${azimut}:${anglefin}:${radius}) ;` return latex } catch (error) { return '' } } } function getLargeSweep (angle: number) { try { let large: 0 | 1 let sweep: 0 | 1 if (angle > 180) { angle = angle - 360 large = 1 sweep = 0 } else if (angle < -180) { angle = 360 + angle large = 1 sweep = 1 } else { large = 0 sweep = (angle > 0) ? 0 : 1 } return [large, sweep] } catch (error) { return [NaN, NaN] } }
<?php /** * This file is part of the Lasalle Software Nova back-end package * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * * LARAVEL's NOVA IS A COMMERCIAL PACKAGE! * -------------------------------------------------------------------------- * NOVA is a *first*-party commercial package for the Laravel Framework, made * by the Laravel Project. You have to pay for it. * * So, yes, my LaSalle Software, as FOSS as it may be, depends on a commercial * OSS package. * * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * @copyright (c) 2019-2022 The South LaSalle Trading Corporation * @license http://opensource.org/licenses/MIT * @author Bob Bloom * @email bob.bloom@lasallesoftware.ca * @link https://lasallesoftware.ca * @link https://packagist.org/packages/lasallesoftware/ls-novabackend-pkg * @link https://github.com/LaSalleSoftware/ls-novabackend-pkg * */ namespace Lasallesoftware\Novabackend\Nova\Fields; // Laravel Nova classes use Laravel\Nova\Fields\Expandable; use Laravel\Nova\Fields\Textarea; use Illuminate\Support\Facades\Crypt; /** * Class Comments * * @package Lasallesoftware\Novabackend\Nova\Fields */ class CommentsEncrypted extends BaseTextField { use Expandable; /** * The field's component. * * @var string */ public $component = 'textarea-field'; /** * Indicates if the element should be shown on the index view. * * @var bool */ public $showOnIndex = false; /** * The number of rows used for the textarea. * * @var int */ public $rows = 5; /** * Create a new custom text field for title. * * @param string $name * @param string|null $attribute * @param mixed|null $resolveCallback * @return void */ public function __construct($name, $attribute = null, $resolveCallback = null) { parent::__construct($name, $attribute, $resolveCallback); $this->name = __('lasallesoftwarelibrarybackend::general.field_name_comments'); $this->help('<ul> <li>'. __('lasallesoftwarelibrarybackend::general.field_help_optional') .'</li> </ul>' ); $this->sanitize(); $this->formatTheValueForTheFormWeAreOn($this->identifyForm()); $this->specifyShowOnForms(); } /** * This field will display, or not display, on these forms. * * @return $this */ private function specifyShowOnForms() { $this->showOnIndex = false; $this->showOnDetail = true; $this->showOnCreation = true; $this->showOnUpdate = true; return $this; } /** * Format this field for the individual forms, * * @param string $formType The form being displayed. * From Lasallesoftware\Novabackend\Nova\Fields->identifyForm() * @return \Closure */ private function formatTheValueForTheFormWeAreOn($formType) { // if we are on the index form if ($formType == "index") { return $this->resolveCallback = function ($value) { // Nova 2.9+ wants this if statement. if (! isset($value)) { return ""; } $value = Crypt::decrypt($value); return substr($value, 0, 50) . "..."; }; } // if we are creating a new record if ($formType == "creation") { // not applicable } // if we are on the detail (show) form if ($formType == "detail") { return $this->resolveCallback = function ($value) { return Crypt::decrypt($value); }; } // if we are on the update (edit) form if ($formType == "update") { return $this->resolveCallback = function ($value) { return Crypt::decrypt($value); }; } } /** * Sanitize data * * @return closure */ private function sanitize() { return $this->resolveCallback = function ($value) { return trim($value); }; } /** * Set the number of rows used for the textarea. * * @param int $rows * @return $this */ public function rows($rows) { $this->rows = $rows; return $this; } }
package org.jiajie.coffeecode.concurrent.future; public class Host { public Data request(final int count, final char c){ System.out.println(" request(" + count + "," + c + ") BEGIN"); // (1)创建FutureData的实例 final FutureData future = new FutureData(); // (2)启动一个新线程,用于创建RealData的实例 new Thread(){ @Override public void run() { RealData realData = new RealData(count, c); future.setRealData(realData); } }.start(); System.out.println(" request(" + count + "," + c + ") END"); // (3)返回FutureData的实例 return future; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>动画</title> <link rel="stylesheet" href="../node_modules/animate.css/animate.css"> <style> div>div{ width: 200px; height: 200px; background-color: #1e7e34; } /*.v-enter, .v-leave-to{opacity: 0}*/ /*.v-enter-active, .v-leave-active{transition:opacity 1s linear}*/ </style> </head> <body> <div id="app"> <button @click="flag=!flag">切换</button> <input type="text" v-model="query"> <transition-group enter-active-class="animated bounceInUp" leave-active-class="animated bounceOutDown"> <div v-for="a in newarr" :key="Math.random()">{{a}}</div> </transition-group> </div> <script src="../node_modules/vue/dist/vue.js"></script> <script> let vm = new Vue({ el:'#app', computed:{ newarr(){ return this.arr.filter(x=>x==this.query) } }, data:{ flag:true, arr:[1,2,3,4,5,6], query:'', } }) </script> </body> </html>
import React from "react"; import { Card, Avatar, Grid } from "@mui/material"; import { Box, styled, useTheme } from "@mui/system"; import { MonetizationOn } from "@mui/icons-material"; import { numToCurrency } from "./../../utils/helpers"; import { Small, Paragraph } from "app/components/Typography"; import { themeShadows } from "app/components/MatxTheme/themeColors"; const FlexBox = styled(Box)(() => ({ display: "flex", alignItems: "center", })); const ListCard = styled(Card)(({ theme }) => ({ padding: "8px", position: "relative", transition: "all 0.3s ease", boxShadow: themeShadows[12], "& .card__button-group": { display: "none", position: "absolute", top: 0, bottom: 0, right: 0, zIndex: 1, background: theme.palette.background.paper, }, "&:hover": { "& .card__button-group": { display: "flex", alignItems: "center", }, }, })); function statusImage(paid) { if (paid) { return <MonetizationOn color="success" />; } else { return <MonetizationOn color="error" />; } } const InvoicesListView = ({ list = [] }) => { const { palette } = useTheme(); const textMuted = palette.text.secondary; return ( <div> {list.map((item, index) => ( <ListCard key={item.id} elevation={3} sx={{ mb: index < list.length && 2 }} > <Grid container justify="space-between" alignItems="center"> <Grid item md={7}> <FlexBox> {statusImage(item.paid)} <Box ml={2}> <Paragraph sx={{ mb: 1 }}>{item.statement}</Paragraph> <Box display="flex"> <Small sx={{ color: textMuted }}> {new Date(item.date).toLocaleString()} </Small> <Small sx={{ ml: 3, color: textMuted }}>{item.email}</Small> </Box> </Box> </FlexBox> </Grid> <Grid item md={4}> <Paragraph sx={{ fontWeight: "bold" }}> {item.paid ? "Paid" : "Unpaid"} commission of{" "} {numToCurrency(item.commission)}. </Paragraph> </Grid> <Grid item md={0}> <FlexBox> <Avatar src={item.avatarUrl}></Avatar> </FlexBox> </Grid> </Grid> </ListCard> ))} </div> ); }; export default InvoicesListView;
package com.dluvian.voyage.ui.components.indicator import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import com.dluvian.voyage.ui.theme.SearchIcon import com.dluvian.voyage.ui.theme.light import com.dluvian.voyage.ui.theme.sizing import com.dluvian.voyage.ui.theme.spacing @Composable fun BaseHint(text: String) { val color = MaterialTheme.colorScheme.onBackground.light() Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize() ) { Icon( modifier = Modifier .size(sizing.baseHint) .aspectRatio(1f), imageVector = SearchIcon, contentDescription = text, tint = color ) Spacer(modifier = Modifier.height(spacing.small)) Text( text = text, textAlign = TextAlign.Center, color = color ) } }
package com.tutorat.exception; import com.tutorat.dto.BusinessResourceExceptionDTO; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.transaction.TransactionSystemException; import org.springframework.ui.Model; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import javax.persistence.RollbackException; import javax.servlet.http.HttpServletRequest; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.util.List; import java.util.stream.Collectors; @ControllerAdvice(basePackages = {"com.tutorat"} ) public class GlobalHandlerControllerException extends ResponseEntityExceptionHandler{ @InitBinder public void dataBinding(WebDataBinder binder) { //Vous pouvez intialiser n'importe quelle donnée ici } @ExceptionHandler(TransactionSystemException.class) protected ResponseEntity<List<String>> handleTransactionException(TransactionSystemException ex) throws Throwable { Throwable cause = ex.getCause(); if (!(cause instanceof RollbackException)) throw cause; if (!(cause.getCause() instanceof ConstraintViolationException)) throw cause.getCause(); ConstraintViolationException validationException = (ConstraintViolationException) cause.getCause(); List<String> messages = validationException.getConstraintViolations().stream() .map(ConstraintViolation::getMessage).collect(Collectors.toList()); return new ResponseEntity<>(messages, HttpStatus.BAD_REQUEST); } @ModelAttribute public void globalAttributes(Model model) { model.addAttribute("technicalError", "Une erreur technique est survenue !"); } @ExceptionHandler(BusinessResourceException.class) public ResponseEntity<BusinessResourceExceptionDTO> businessResourceError(HttpServletRequest req, BusinessResourceException ex) { BusinessResourceExceptionDTO businessResourceExceptionDTO = new BusinessResourceExceptionDTO(); businessResourceExceptionDTO.setStatus(ex.getStatus()); businessResourceExceptionDTO.setErrorCode(ex.getErrorCode()); businessResourceExceptionDTO.setErrorMessage(ex.getMessage()); businessResourceExceptionDTO.setRequestURL(req.getRequestURL().toString()); return new ResponseEntity<BusinessResourceExceptionDTO>(businessResourceExceptionDTO, ex.getStatus()); } @ExceptionHandler(Exception.class)//toutes les autres erreurs non gérées par le service sont interceptées ici public ResponseEntity<BusinessResourceExceptionDTO> unknowError(HttpServletRequest req, Exception ex) { BusinessResourceExceptionDTO response = new BusinessResourceExceptionDTO(); response.setErrorCode("Technical Error"); response.setErrorMessage(ex.getMessage()); response.setRequestURL(req.getRequestURL().toString()); return new ResponseEntity<BusinessResourceExceptionDTO>(response, HttpStatus.INTERNAL_SERVER_ERROR); } }
package com.example.pokedexapp.pokemonListView; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; import com.example.pokedexapp.R; import com.example.pokedexapp.pokemon.Pokemon; import com.example.pokedexapp.pokemonapi.PokeAPIBean; import java.util.ArrayList; public class PokemonListAdaptor extends RecyclerView.Adapter<PokemonListAdaptor.MyViewHolder>{ private final Context mContext; private ArrayList<Pokemon> pokemonList = new ArrayList<>(); private OnPokemonClickListener onPokemonClickListener; // Constructor public PokemonListAdaptor(Context c, ArrayList<Pokemon> pokemonList, OnPokemonClickListener onPokemonClickListener) { mContext = c; this.pokemonList = pokemonList; this.onPokemonClickListener = onPokemonClickListener; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.linearlayout_pokemon, null); MyViewHolder viewHolder = new MyViewHolder(view, onPokemonClickListener); return viewHolder; } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { final Pokemon pokemon = pokemonList.get(position); if (pokemon != null) { holder.nameTextView.setText(pokemon.getName()); holder.numberTextView.setText("#" + pokemon.getId()); if (pokemon.getSprites() == null) { holder.pokemonSpriteImageView.setVisibility(View.GONE); } else { holder.pokemonSpriteImageView.setVisibility(View.VISIBLE); Glide.with(holder.pokemonSpriteImageView.getContext()).load(pokemon.getSprites().get(0)).into(holder.pokemonSpriteImageView); } } } @Override public long getItemId(int i) { return 0; } @Override public int getItemCount() { if (pokemonList != null) { return pokemonList.size(); } else { return 0; } } public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView nameTextView, numberTextView; ImageView pokemonSpriteImageView; OnPokemonClickListener onPokemonClickListener; public MyViewHolder(@NonNull View itemView, OnPokemonClickListener onPokemonClickListener) { super(itemView); pokemonSpriteImageView = (ImageView) itemView.findViewById(R.id.imageview_pokemon_sprite); nameTextView = (TextView) itemView.findViewById(R.id.textview_pokemon_name); numberTextView = (TextView) itemView.findViewById(R.id.textview_pokemon_number); this.onPokemonClickListener = onPokemonClickListener; itemView.setOnClickListener(this); } @Override public void onClick(View view) { onPokemonClickListener.onPokemonClick(getAdapterPosition()); } } public interface OnPokemonClickListener { void onPokemonClick(int position); } }
import React, { useContext } from 'react' import Container from 'react-bootstrap/Container'; import Nav from 'react-bootstrap/Nav'; import Navbar from 'react-bootstrap/Navbar'; import { useTranslation } from 'react-i18next'; import { Link, useNavigate } from 'react-router-dom'; import { CartSumContext } from '../store/CartSumContext'; import { AuthContext } from '../store/AuthContext'; function NavigationBar() { const { t, i18n } = useTranslation(); const { cartSum } = useContext(CartSumContext); const { loggedIn, setLoggedIn } = useContext(AuthContext); const navigate = useNavigate(); // const languageToEn = () => { // i18n.changeLanguage("en"); // localStorage.setItem("language","en"); // } // const languageToEe = () => { // i18n.changeLanguage("ee"); // localStorage.setItem("language","ee"); // } const languageChange = (languageClicked) => { i18n.changeLanguage(languageClicked); localStorage.setItem("language",languageClicked); } // const login = () => { // setLoggedIn(true); // } const logout = () => { setLoggedIn(false); sessionStorage.removeItem("token"); navigate("/"); } return ( <Navbar collapseOnSelect expand="lg" bg="light" variant="light"> <Container> <Navbar.Brand as={Link} to="/">Mihkel's shop</Navbar.Brand> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav"> <Nav className="me-auto"> {loggedIn === true && <Nav.Link as={Link} to="/admin">{t("admin")}</Nav.Link>} <Nav.Link as={Link} to="/contact">{t("contact")}</Nav.Link> <Nav.Link as={Link} to="/shops">{t("shops")}</Nav.Link> </Nav> <Nav> {loggedIn === false && <> <Nav.Link as={Link} to="/login">Logi sisse</Nav.Link> <Nav.Link as={Link} to="/signup">Registreeru</Nav.Link> </>} {loggedIn === true && <button onClick={logout}>Logi välja</button>} <div>{cartSum} €</div> <img className="lang" src="/english.png" onClick={() => languageChange("en")} alt="" /> <img className="lang" src="/estonian.png" onClick={() => languageChange("ee")} alt="" /> <Nav.Link as={Link} to="/cart">{t("cart")}</Nav.Link> </Nav> </Navbar.Collapse> </Container> </Navbar> ) } export default NavigationBar
import React, { FunctionComponent } from 'react' import { StyleSheet, Text, View } from 'react-native' import { useUser } from '../../store' import { colors, layout, typography } from '../../styles' import { CommentType } from '../../types' import { Avatar, Timestamp } from '../common' interface Props { item: CommentType } export const Comment: FunctionComponent<Props> = ({ item }) => { const [{ user }] = useUser() return ( <View style={styles.main}> <Avatar seed={item.user.id} /> <View style={styles.details}> <View style={styles.body}> <Text style={styles.bodyText}>{item.body}</Text> </View> <View style={styles.meta}> <Text style={[styles.metaLabel, styles.name]}> {user?.id === item.user.id ? 'YOU' : item.user.name} </Text> <Timestamp style={styles.metaLabel} time={item.createdAt} /> </View> </View> </View> ) } const styles = StyleSheet.create({ body: { alignSelf: 'flex-start', backgroundColor: colors.backgroundLight, borderRadius: layout.radius * 5, paddingHorizontal: layout.padding * layout.lineHeight, paddingVertical: layout.padding }, bodyText: { ...typography.footnote, color: colors.foreground }, details: { flex: 1, marginLeft: layout.margin }, main: { alignItems: 'center', flexDirection: 'row', paddingHorizontal: layout.margin, paddingVertical: layout.padding }, meta: { flexDirection: 'row', marginLeft: -layout.padding, marginTop: layout.padding }, metaLabel: { ...typography.small, color: colors.foregroundDark, marginLeft: layout.padding }, name: { ...typography.medium, color: colors.accent } })
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Animal.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: otaraki <otaraki@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/11/23 16:59:10 by otaraki #+# #+# */ /* Updated: 2023/11/23 17:06:10 by otaraki ### ########.fr */ /* */ /* ************************************************************************** */ #include "Animal.hpp" Animal::Animal() { std::cout << "Animal default constructor called" << std::endl; _type = "Animal"; } Animal::Animal(std::string type) { std::cout << "Animal type constructor called" << std::endl; _type = type; } Animal::Animal(const Animal &copy) { std::cout << "Animal copy constructor called" << std::endl; *this = copy; } Animal::~Animal() { std::cout << "Animal destructor called" << std::endl; } Animal &Animal::operator=(const Animal &copy) { std::cout << "Animal assignation operator called" << std::endl; _type = copy._type; return (*this); } std::string Animal::getType() const { return (_type); } void Animal::makeSound() const { std::cout << "weeeeee weeeee weeeee" << std::endl; } /* ************************************************************************** */
<!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>Project-1</title> <link rel="stylesheet" href="day9Style.css"> <link rel="stylesheet" media="screen and (max-width: 600px)" href="resposive.css"> </head> <body> <div class="cont"> <div class="header"> <div class="logo"> <img src="./images/cropped-iist-logo-2.png" alt=""> <h3>IIST</h3> </div> <div class="menu"> <ul> <li><a href="">Home</a></li> <li><a href="">About</a></li> <li><a href="">Gallery</a></li> <li><a href="">Contact</a></li> </ul> </div> </div> </div> <!-- Header Part End --> <!-- Slider Part Start --> <div class="slider"> <h1>Ideal Institute of Science & Technology</h1> <p>Lorem ipsum dolor sit amet consectetur<br> adipisicing elit. Enim, eius.</p> <a href="">Read More</a> </div> <!-- Slider Part End --> <!-- Hero Part Start --> <section class="hero"> <div class="services-title"> <h1>Our <span>Services</span></h1> <p>Lorem ipsum dolor sit, amet<br> consectetur adipisicing elit.<br> Molestiae, fugit.</p> </div> <div class="services-box"> <div class="card"> <img src="./images/bg1.png" alt=""> <h2>Diploma Courses</h2> <p>Lorem ipsum dolor<br> sit amet consectetur adipisicing elit.<br> Tenetur iure totam recusandae!</p> <a href="">Read More</a> </div> <div class="card"> <img src="./images/bg1.png" alt=""> <h2>Diploma Courses</h2> <p>Lorem ipsum dolor<br> sit amet consectetur adipisicing elit.<br> Tenetur iure totam recusandae!</p> <a href="">Read More</a> </div> <div class="card"> <img src="./images/bg1.png" alt=""> <h2>Diploma Courses</h2> <p>Lorem ipsum dolor<br> sit amet consectetur adipisicing elit.<br> Tenetur iure totam recusandae!</p> <a href="">Read More</a> </div> <div class="card"> <img src="./images/bg1.png" alt=""> <h2>Diploma Courses</h2> <p>Lorem ipsum dolor<br> sit amet consectetur adipisicing elit.<br> Tenetur iure totam recusandae!</p> <a href="">Read More</a> </div> </div> </section> <!-- Hero Part End --> </body> </html>
package com.bassure.ims.productservice.serviceImpl; import com.bassure.ims.productservice.collection.Asset; import com.bassure.ims.productservice.collection.Warranty; import com.bassure.ims.productservice.config.HttpStatusCode; import com.bassure.ims.productservice.config.HttpStatusMessage; import com.bassure.ims.productservice.config.UtilsConfig; import com.bassure.ims.productservice.config.UtilsResponse; import com.bassure.ims.productservice.repository.AssetRepository; import com.bassure.ims.productservice.repository.BrandRepository; import com.bassure.ims.productservice.repository.ModelRepository; import com.bassure.ims.productservice.repository.OrderRepository; import com.bassure.ims.productservice.request.AssetRequest; import com.bassure.ims.productservice.response.ResponseEntity; import com.bassure.ims.productservice.service.AssetService; import java.time.LocalDateTime; import java.util.*; import com.mongodb.client.result.UpdateResult; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationOperation; import org.springframework.data.mongodb.core.aggregation.LookupOperation; import org.springframework.data.mongodb.core.aggregation.UnwindOperation; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; @Service public class AssetServiceImpl implements AssetService { @Autowired private AssetRepository assetRepository; @Autowired private SequenceGeneratorService sequenceGeneratorService; @Autowired private HttpStatusCode httpStatusCode; @Autowired private HttpStatusMessage httpStatusMessage; @Autowired private BrandRepository brandRepository; @Autowired private ModelRepository modelRepository; @Autowired private OrderRepository orderRepository; @Autowired MongoTemplate mongoTemplate; @Override public ResponseEntity addAsset(AssetRequest assetsRequest) { Asset anAsset = new Asset(); BeanUtils.copyProperties(assetsRequest, anAsset); anAsset.setAssetId(sequenceGeneratorService.generateSequence(UtilsConfig.getASSET_SEQUENCE_NAME())); Warranty warranty = new Warranty(); warranty.setStartDate(assetsRequest.getWarranty().getStartDate()); warranty.setEndDate(assetsRequest.getWarranty().getEndDate()); warranty.setStatus(assetsRequest.getWarranty().getStatus()); anAsset.setWarranty(warranty); anAsset.setCreatedAt(LocalDateTime.now()); anAsset.setStatus("ACTIVE"); if (brandRepository.findById(anAsset.getBrandId()).isPresent() && modelRepository.findById(anAsset.getModelId()).isPresent() && orderRepository.findById(anAsset.getOrderId()).isPresent()) { assetRepository.save(anAsset); return UtilsResponse.responsesEntity(httpStatusCode.getSuccess(), httpStatusMessage.getAddMessage()); } else { return UtilsResponse.responsesEntity(httpStatusCode.getError(), Map.of(httpStatusMessage.getErrorKey(), "")); } } @Override public ResponseEntity getAsset() { List<Asset> all = assetRepository.findAll(); if (!all.isEmpty()) { return UtilsResponse.responsesEntity(httpStatusCode.getSuccess(), all); } else { return UtilsResponse.responsesEntity(httpStatusCode.getNoData(), Map.of()); } } @Override public ResponseEntity getAssetById(String assetId) { Optional<Asset> asset = assetRepository.findById(assetId); if (asset.isPresent()) { return UtilsResponse.responsesEntity(httpStatusCode.getSuccess(), asset); } else { return UtilsResponse.responsesEntity(httpStatusCode.getNoData(), Map.of()); } } @Override public ResponseEntity getAggregatedAssets() { List<Asset> assets = assetRepository.retrieveAggregatedAssets(); if (!assets.isEmpty()) { return UtilsResponse.responsesEntity(httpStatusCode.getSuccess(), assets); } else { return UtilsResponse.responsesEntity(httpStatusCode.getNoData(), Map.of()); } } @Override public ResponseEntity retrieveAggregatedAsset() { LookupOperation lookupBrand = LookupOperation.newLookup() .from("brand") .localField("brand_id") .foreignField("_id") .as("brandData"); LookupOperation lookupOrder = LookupOperation.newLookup() .from("Order") .localField("order_id") .foreignField("_id") .as("orderData"); UnwindOperation unwindOrder = Aggregation.unwind("orderData"); List<AggregationOperation> supplierPipeline = new ArrayList<>(); supplierPipeline.add(Aggregation.replaceRoot("orderData")); LookupOperation lookupSupplier = LookupOperation.newLookup() .from("supplier") .localField("supplier_id") .foreignField("_id") .as("supplierData"); // AggregationOperation lookupSupplierOperation = Aggregation.lookup("Order") // .applyAggregationOperations(supplierPipeline) // .applyAggregationOperation(lookupSupplier) // .as("supplierData"); // Aggregation aggregation = Aggregation.newAggregation( // lookupBrand, // lookupOrder, // unwindOrder, // lookupSupplierOperation // ); Aggregation aggregation = null; List<Asset> product = mongoTemplate.aggregate(aggregation, "product", Asset.class).getMappedResults(); if (!product.isEmpty()) { return UtilsResponse.responsesEntity(httpStatusCode.getSuccess(), product); } else { return UtilsResponse.responsesEntity(httpStatusCode.getNoData(), Map.of()); } } @Override public ResponseEntity updateAsset(String assetId, AssetRequest anAssetRequest) { Optional<Asset> optionalAsset = assetRepository.findById(assetId); if (optionalAsset.isPresent()) { Asset anAsset = new Asset(); anAsset.setAssetId(optionalAsset.get().getAssetId()); BeanUtils.copyProperties(anAssetRequest, anAsset); assetRepository.save(anAsset); return UtilsResponse.responsesEntity(httpStatusCode.getSuccess(), "updated success"); } else { return UtilsResponse.responsesEntity(httpStatusCode.getNoData(), Map.of()); } } @Override public ResponseEntity deleteAsset(String assetId) { if (getAssetById(assetId).getCode() == httpStatusCode.getSuccess()) { Query query = new Query(Criteria.where("id").is(assetId)); Update update = new Update().set("status", "INACTIVE"); UpdateResult result = mongoTemplate.updateFirst(query, update, Asset.class); if (result.getModifiedCount() > 0) { return UtilsResponse.responsesEntity(httpStatusCode.getSuccess(), "Asset deleted successfully"); } } return UtilsResponse.responsesEntity(httpStatusCode.getFailed(), Map.of("", "Asset failed to delete id - " + assetId)); } }
setwd("../Desktop/git_repos/bat-CoVs/") require(tidyverse) require(data.table) require(foreach) require(Biostrings) data("BLOSUM62") spike_AA <- readAAStringSet("data/proteins/extracted_proteins/all_spikes.faa") names(spike_AA)[names(spike_AA) == "NC_045512"] <- "SARS-CoV-2" names(spike_AA)[names(spike_AA) == "NC_004718"] <- "SARS-CoV-1" names(spike_AA)[names(spike_AA) == "MZ937003"] <- "BANAL-236" names(spike_AA)[names(spike_AA) == "NC_019843"] <- "MERS" morsels <- foreach(i = seq(length(spike_AA))) %do% { crumbs <- foreach (j = seq(length(spike_AA))) %do% { aln <- pairwiseAlignment(spike_AA[[i]], spike_AA[[j]], substitutionMatrix = BLOSUM62, gapOpening = 0, gapExtension = -5) spike_aa_ident <- pid(aln, type = "PID1") accession1 <- names(spike_AA)[i] accession2 <- names(spike_AA)[j] tibble(accession1 = accession1, accession2 = accession2, pident = spike_aa_ident) } bind_rows(crumbs) } final <- bind_rows(morsels) all_viruses <- rev(c("RFGB01", "RFGB02", "RHGB02", "RHGB03", "RHGB04", "BANAL-236", "SARS-CoV-1", "SARS-CoV-2", "PAGB01", "MERS")) hm_df <- final %>% filter(accession1 %in% all_viruses, accession2 %in% all_viruses) hm_df %>% mutate(accession1 = factor(accession1, all_viruses), accession2 = factor(accession2, rev(all_viruses))) %>% ggplot(aes(x = accession1, y = accession2, fill = pident)) + geom_tile() + geom_text(aes(label = round(pident, 1))) + scale_fill_gradient(low = "dodgerblue4", high = "paleturquoise2") + theme_bw() + theme(legend.position = "top", axis.title = element_blank(), axis.text.x = element_text(angle = 45, hjust = 1)) + labs(fill = "Amino acid similarity (%; incl. gaps)") ggsave("results/pident_hm.png", dpi = 600, height = 6, width = 6) spike_AA[all_viruses]
package com.example.packmanbarcodesgenerator.uiElements.CustomListView import android.annotation.SuppressLint import android.content.Context import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.AlertDialog import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import barcodeGenerator.BoxQRcode import barcodeGenerator.PartQRcode import com.example.packmanbarcodesgenerator.screens.BottomItems import com.example.packmanbarcodesgenerator.screens.makeToast @SuppressLint("RememberReturnType") @Composable fun CustomAlertDialog( state: MutableState<Boolean>, activeBottomItem: String, fieldsForPart: Map<String, MutableState<String>>, fieldsForPartHWandSW: Map<String, MutableState<Boolean>>, fieldsForBox: Map<String, MutableState<String>>, listOfRecords: List<Any>, listOfCheckedItems: SnapshotStateList<Int>, context: Context ) { if (state.value) { AlertDialog( onDismissRequest = { state.value = false }, title = { Text(text = "Попередньо збережені...") }, text = { Column() { var neededList: List<Any> = listOfRecords.filterIsInstance<BoxQRcode>() if (activeBottomItem == BottomItems.Box.name) { neededList = listOfRecords.filterIsInstance<BoxQRcode>() } else if (activeBottomItem == BottomItems.Part.name) { neededList = listOfRecords.filterIsInstance<PartQRcode>() } CustomListView( context = LocalContext.current, neededList, listOfCheckedItems ) } }, buttons = { Row( modifier = Modifier .padding(all = 8.dp) .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { Button( onClick = { if (listOfCheckedItems.count() != 1) { listOfCheckedItems.clear() makeToast(context, "Оберіть ОДИН елемент") } else { val neededList: Any if (activeBottomItem == BottomItems.Box.name) { neededList = listOfRecords.filterIsInstance<BoxQRcode>() val chosenRecord = neededList[listOfCheckedItems[0]] fieldsForBox["article"]?.value = chosenRecord.article fieldsForBox["index"]?.value = chosenRecord.index fieldsForBox["packaging"]?.value = chosenRecord.packaging fieldsForBox["quantityInBox"]?.value = chosenRecord.quantityInBox fieldsForBox["batchNumber"]?.value = chosenRecord.batchNumber fieldsForBox["customerArticle"]?.value = chosenRecord.customerArticle } else if (activeBottomItem == BottomItems.Part.name) { val neededList: List<PartQRcode> = listOfRecords.filterIsInstance<PartQRcode>() val chosenRecord = neededList[listOfCheckedItems[0]] fieldsForPart["article"]?.value = chosenRecord.article fieldsForPart["index"]?.value = chosenRecord.index fieldsForPart["customerArticle"]?.value = chosenRecord.customerArticle fieldsForPart["HWversion"]?.value = chosenRecord.HWversion fieldsForPart["SWversion"]?.value = chosenRecord.SWversion fieldsForPart["serialNumber"]?.value = chosenRecord.serialNumber fieldsForPartHWandSW["isHWpresent"]?.value = chosenRecord.isHWpresent fieldsForPartHWandSW["isSWpresent"]?.value = chosenRecord.isSWpresent } state.value = false } } ) { Text("Обрати") } Button( onClick = { state.value = false } ) { Text("Видалити") } } } ) } }
require('babel/register')(); /** * Module dependencies. */ const app = require('../server'); const http = require('http'); /** * Get port from environment and store in Express. */ if(!process.env.PORT){ throw Error('PORT variable must exist to continue.')} const port = normalizePort(process.env.PORT); app.set('port', port); /** * Create HTTP server. */ const server = http.createServer(app); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on('error', onError); server.on('listening', onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.log(bind + ' requires elevated privileges'); break; case 'EADDRINUSE': console.log(bind + ' is already in use'); break; default: throw error; process.exit(1); } } /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'PIPE ' + addr : 'PORT ' + addr.port; console.log('----STARTING----'); console.log('Listening on ' + bind); console.log('NODE_ENV: "' + process.env.NODE_ENV + '"'); console.log('---------------'); } // process.on('SIGINT', ()=>{ //clean up and release pool connections and etc... // });
#Importing the libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #Importing the dataset dataset = pd.read_csv('Iris.csv') from sklearn.preprocessing import LabelEncoder le = LabelEncoder() dataset['Species'] = le.fit_transform(dataset.Species.values) x = dataset.iloc[:, 1:].values print(x) #Using the elbow method to find the optimal number of clusters from sklearn.cluster import KMeans wcss = [] for i in range(1, 11): kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42) kmeans.fit(x) wcss.append(kmeans.inertia_) plt.plot(range(1, 11), wcss) plt.title('The Elbow Method') plt.xlabel('Number of clusters') plt.ylabel('WCSS') plt.show() #Training the K-Means Model from sklearn.cluster import KMeans kmeans = KMeans(n_clusters = 3, init='k-means++', random_state=42) y_kmeans = kmeans.fit_predict(x) #Visualizing the clusters plt.scatter(x[y_kmeans == 0, 0], x[y_kmeans == 0, 4], s = 25, c = 'red', label = 'Iris-setosa') plt.scatter(x[y_kmeans == 1, 0], x[y_kmeans == 1, 4], s = 25, c = 'blue', label = 'Iris-versicolor') plt.scatter(x[y_kmeans == 2, 0], x[y_kmeans == 2, 4], s = 25, c = 'green', label = 'Iris-virginica') plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 4], s = 50, c = 'black', label = 'Centroids') plt.title('Clusters of species') plt.xlabel('SepalLength (cm)') plt.ylabel('Species') plt.legend() plt.show()
import { useDispatch, useSelector } from "react-redux" import { addItem, removeItem } from "../redux/handleWishlist" import { imagesIcons } from "../App" import { Link } from "react-router-dom" const ShoppingPageProducts = ({data, categoryName}) => { const dispatch = useDispatch() const wishlist = useSelector((state) => state.handleWishlist.wishlistContents) function changeHeart(e, product) { if (wishlist[product.name]) { e.target.style.backgroundImage = `url(${imagesIcons.heartOutline})` dispatch(removeItem(product)) } else { e.target.style.backgroundImage = `url(${imagesIcons.solidHeart})` dispatch(addItem(product)) } } function entered(e, product) { if (wishlist[product.name]) return e.target.style.backgroundImage = `url(${imagesIcons.solidHeart})` } function left(e, product) { if (!wishlist[product.name]) { e.target.style.backgroundImage = `url(${imagesIcons.heartOutline})` } } return ( <section> { data.map((product, index) => { return ( <div className="showcase-product-div" key={product.id}> <img className="showcase-img" src={product.images[0]} alt="bike name"/> <div onMouseLeave={(e) => left(e, product)} onMouseEnter={(e) => entered(e, product)} onClick={(e) => changeHeart(e, product)} className="heart-img" style={wishlist[product.name] && {backgroundImage: `url(${imagesIcons.solidHeart})`}}/> <div className="product-info"> <p className="product-name">{product.name}</p> <p className="price-type">{product.make} &#124; ${product.price}</p> <Link to={"/productPage"} state={{product: product, categoryName: categoryName, index: index}} className="shop-item-link"><button className="view-product">View Bike</button></Link> </div> </div> ) }) } </section> ) } export default ShoppingPageProducts
package softuni.exam.service.impl; import com.google.gson.Gson; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import softuni.exam.models.dto.mechanic.MechanicImportDTO; import softuni.exam.models.entity.Mechanic; import softuni.exam.repository.MechanicsRepository; import softuni.exam.service.MechanicsService; import softuni.exam.util.ValidationUtils; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static softuni.exam.constant.Message.*; @Service public class MechanicsServiceImpl implements MechanicsService { private static final String MECHANICS_FILE_PATH = "src/main/resources/files/json/mechanics.json"; private final StringBuilder sb; private final Gson gson; private final ModelMapper mapper; private final ValidationUtils validationUtils; private final MechanicsRepository mechanicsRepository; @Autowired public MechanicsServiceImpl(Gson gson, ModelMapper mapper, ValidationUtils validationUtils, MechanicsRepository mechanicsRepository) { this.sb = new StringBuilder(); this.gson = gson; this.mapper = mapper; this.validationUtils = validationUtils; this.mechanicsRepository = mechanicsRepository; } @Override public boolean areImported() { return this.mechanicsRepository.count() > 0; } @Override public String readMechanicsFromFile() throws IOException { return Files.readString(Path.of(MECHANICS_FILE_PATH)); } @Override public String importMechanics() throws IOException { final List<MechanicImportDTO> mechanicsImportDTO = Arrays.stream(this.gson.fromJson(this.readMechanicsFromFile(), MechanicImportDTO[].class)) .collect(Collectors.toList()); mechanicsImportDTO .forEach(mechanicDTO -> { if (this.mechanicsRepository.findFirstByEmail(mechanicDTO.getEmail()).isPresent() || this.mechanicsRepository.findFirstByPhone(mechanicDTO.getPhone()).isPresent() || !this.validationUtils.isValid(mechanicDTO)) { this.sb.append(String.format(INVALID_ENTITY, MECHANIC)) .append(System.lineSeparator()); } else { final Mechanic mechanic = this.mapper.map(mechanicDTO, Mechanic.class); this.mechanicsRepository.saveAndFlush(mechanic); this.sb.append(String.format(SUCCESSFUL_MECHANIC_IMPORT, MECHANIC, mechanic.getFullName())) .append(System.lineSeparator()); } }); return this.sb.toString().trim(); } }
package middleware import ( "crypto/x509" "encoding/pem" "io/ioutil" "log" "net/http" "strings" "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt/v4" ) func AuthMiddleware() gin.HandlerFunc { buffer, err := ioutil.ReadFile("public.pem") if err != nil { log.Fatal("Cannot read publickey") } block, _ := pem.Decode(buffer) if err != nil { log.Fatal("Cannot parse public.pem file") } rsaPublicKey, err := x509.ParsePKCS1PublicKey(block.Bytes) if err != nil { log.Fatal("Cannot parse public key") } return func(c *gin.Context) { authHeader := c.GetHeader("Authorization") if len(authHeader) == 0 { c.AbortWithStatus(http.StatusUnauthorized) return } fields := strings.Fields(authHeader) if strings.ToLower(fields[0]) != "bearer" { c.AbortWithStatus(http.StatusUnauthorized) return } jwtString := fields[1] claims := &jwt.RegisteredClaims{} parsedToken, err := jwt.ParseWithClaims(jwtString, claims, func(t *jwt.Token) (interface{}, error) { return rsaPublicKey, nil }) if !parsedToken.Valid || err != nil { c.AbortWithStatus(http.StatusUnauthorized) return } c.Next() } }
import { createRouter, createWebHistory } from 'vue-router' import LoginView from '../views/LoginView.vue' import DashboardView from '../views/DashboardView.vue' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: 'home', component: LoginView, }, { path: '/dashboard', name: 'dashboard', component: DashboardView }, { path: '/profile', name: 'profile', component: () => import('../components/UserComp.vue') }, { path: '/loading', name: 'loading', component: () => import('../views/LoadingView.vue') }, // Ruta de redirección automática { path: '/autoredirect', beforeEnter: (to, from, next) => { if (localStorage.getItem('isAuthenticated')) { to('/dashboard') } else { to('/') } }, }, ] }) export default router
'use server' import { sendMail } from '@/services/mailService' import * as z from 'zod' import { ZodIssue } from 'zod' type FormData = { honey_pot?: any name: string email: string subject: string message: string } export async function sendEmail(formData: FormData) { const { honey_pot, name, email, subject, message } = formData if (honey_pot !== '') { throw new Error('Spam submission') } const schema = z.object({ name: z.string().min(1).max(50), email: z.string().min(1).max(50), subject: z.string().min(1).max(50), message: z.string().min(15).max(255), }) const parse = schema.safeParse({ name, email, subject, message, }) if (!parse.success) { const res = parse.error.flatten((issue: ZodIssue) => ({ message: issue.message, errorCode: issue.code, })) console.error('form errors', res.formErrors) console.error('field errors', res.fieldErrors) throw new Error() } const data = parse.data const body = ` name: ${data.name}, email: ${data.email}, body: ${data.message} ` try { await sendMail(data.subject, body) } catch (err) { if (err instanceof Error) { throw new Error(err.message) } } }
/* * Copyright (C) 2004 * Swiss Federal Institute of Technology, Lausanne. All rights reserved. * * Developed at the Autonomous Systems Lab. * Visit our homepage at http://asl.epfl.ch/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ #include "Lookup.hpp" #include <sfl/util/numeric.hpp> #include <iostream> #include <limits> using std::ostream; using std::numeric_limits; namespace sfl { Lookup:: Lookup(const array2d<double> & buffer, double _minValue, double _maxValue, double _invalidValue) : minValue(_minValue), maxValue(_maxValue), invalidValue(_invalidValue), m_key(buffer.xsize, buffer.ysize), m_no_valid(true) { // initialize histogram, but only with valid values histogram_t histogram; for(size_t ix(0); ix < buffer.xsize; ++ix) for(size_t iy(0); iy < buffer.ysize; ++iy) if((buffer[ix][iy] >= minValue) && (buffer[ix][iy] <= maxValue)) histogram.insert(buffer[ix][iy]); if(histogram.empty()) return; // empty buffer, no valid entry m_actualVmin = * histogram.begin(); m_actualVmax = * histogram.rbegin(); // initialize binlist... yes, there are maxNbins + 1 bins, // because the last is "only" there to keep the upper (inclusive) // bound for the last interval const double scale((m_actualVmax - m_actualVmin) / maxNbins); binlist_t binlist; binlist.push_back(bin_s(m_actualVmin, invalidValue)); for(size_t ii(1); ii < maxNbins; ++ii) binlist.push_back(bin_s(m_actualVmin + ii * scale, invalidValue)); binlist.push_back(bin_s(m_actualVmax, invalidValue)); if( ! LloydMax(histogram, binlist)) return; // oops, probably a bug... abort()? if( ! Quantize(buffer, histogram, binlist)) return; // oops, probably a bug... abort()? m_no_valid = false; } double Lookup:: Get(size_t iqdl, size_t iqdr) const { if(m_no_valid || (iqdl >= m_key.xsize) || (iqdr >= m_key.ysize)) return invalidValue; const key_t key(m_key[iqdl][iqdr]); if(key >= m_quantizer.size()) return invalidValue; return m_quantizer[key]; } bool Lookup:: LloydMax(const histogram_t & histogram, binlist_t & binlist) const { bool finished(false); while( ! finished){ finished = true; // calculate levels const binlist_t::iterator ilast(--binlist_t::iterator(binlist.end())); binlist_t::iterator inext(binlist.begin()); if((inext == ilast) || (inext == binlist.end())) return false; // oops: empty or single-element binlist binlist_t::iterator icurr(inext); ++inext; while(inext != binlist.end()){ double val; if(inext == ilast) val = PMeanInc(histogram, icurr->bound, inext->bound); else val = PMean(histogram, icurr->bound, inext->bound); if((icurr->val == invalidValue) || (absval(icurr->val - val) > epsilon)){ finished = false; icurr->val = val; } icurr = inext; ++inext; } // remove empty bins, beware the last bin always contains // invalidValue but it has to stay in place for the upper bound // of the last interval, so we test against ilast, but also // check binlist.end() because std::list::erase() can return // std::list::end() if the last element is removed (which should // never happen here, but well... at least we don't go // currupting RAM elsewhere) for(icurr = binlist.begin(); (icurr != ilast) && (icurr != binlist.end()); ++icurr) if(icurr->val == invalidValue) icurr = binlist.erase(icurr); // adjust boundaries, keeping the first last at the actual range // of the histogram icurr = binlist.begin(); if((icurr == ilast) || (icurr == binlist.end())) return false; // oops: removed too many bins icurr->bound = m_actualVmin; binlist_t::iterator iprev(icurr); ++icurr; while(icurr != ilast){ icurr->bound = 0.5 * (iprev->val + icurr->val); iprev = icurr; ++icurr; } icurr->bound = m_actualVmax; // should be redundant... } // while(!finished) return true; } bool Lookup:: Quantize(const array2d<double> & buffer, const histogram_t & histogram, const binlist_t & binlist) { if(binlist.empty()) return false; // initialize quantizer lookup m_quantizer.clear(); const binlist_t::const_iterator ilast(--binlist_t::const_iterator(binlist.end())); binlist_t::const_iterator inext(binlist.begin()); if((inext == ilast) || (inext == binlist.end())) return false; // oops: empty or single-element binlist binlist_t::const_iterator icurr(inext); ++inext; while(inext != binlist.end()){ if(inext == ilast) m_quantizer.push_back(PMinInc(histogram, icurr->bound, inext->bound)); else m_quantizer.push_back(PMin(histogram, icurr->bound, inext->bound)); icurr = inext; ++inext; } // quantize buffer and store it in m_key for(size_t ix(0); ix < buffer.xsize; ++ix) for(size_t iy(0); iy < buffer.ysize; ++iy){ if((buffer[ix][iy] < minValue) || (buffer[ix][iy] > maxValue)) m_key[ix][iy] = m_quantizer.size(); // flag as invalidValue else{ m_key[ix][iy] = 0; inext = binlist.begin(); ++inext; while(inext != ilast){ // no need to test for ilast->bound if(buffer[ix][iy] < inext->bound) break; ++m_key[ix][iy]; ++inext; } } } return true; } double Lookup:: PMean(const histogram_t & histogram, double from, double to) const { double sum(0); size_t count(0); for(histogram_t::const_iterator ih(histogram.begin()); ih != histogram.end(); ++ih) if( * ih >= from){ if( * ih < to){ sum += * ih; ++count; } else break; } if(count < 1) return invalidValue; return sum / count; } double Lookup:: PMeanInc(const histogram_t & histogram, double from, double to) const { double sum(0); size_t count(0); for(histogram_t::const_iterator ih(histogram.begin()); ih != histogram.end(); ++ih) if( * ih >= from){ if( * ih <= to){ sum += * ih; ++count; } else break; } if(count < 1) return invalidValue; return sum / count; } double Lookup:: PMin(const histogram_t & histogram, double from, double to) const { for(histogram_t::const_iterator ih(histogram.begin()); ih != histogram.end(); ++ih) if(( * ih >= from) && ( * ih < to)) return * ih; return invalidValue; } double Lookup:: PMinInc(const histogram_t & histogram, double from, double to) const { for(histogram_t::const_iterator ih(histogram.begin()); ih != histogram.end(); ++ih) if(( * ih >= from) && ( * ih <= to)) return * ih; return invalidValue; } void Lookup:: DumpStats(const array2d<double> & buffer, ostream & os) const { os << "Lookup::DumpStats():\n"; if((buffer.xsize != m_key.xsize) || (buffer.ysize != m_key.ysize)) os << " dimension mismatch\n"; else{ double diffmin(numeric_limits<double>::max()); double diffmax(numeric_limits<double>::min()); double diffsum(0); size_t diffcount(0); size_t invalid_mismatch(0); for(size_t ix(0); ix < buffer.xsize; ++ix) for(size_t iy(0); iy < buffer.ysize; ++iy){ if((Get(ix, iy) == invalidValue) && (buffer[ix][iy] >= minValue) && (buffer[ix][iy] <= maxValue)) ++invalid_mismatch; else{ const double diff(Get(ix, iy) - buffer[ix][iy]); if(diff < diffmin) diffmin = diff; if(diff > diffmax) diffmax = diff; diffsum += diff; ++diffcount; } } os << " diffmin = " << diffmin << "\n" << " diffmax = " << diffmax << "\n" << " diffcount = " << diffcount << "\n"; if(diffcount > 0) os << " diffmean = " << diffsum / diffcount << "\n"; os << " invalid_mismatch = " << invalid_mismatch << "\n"; } } }
import React, { Component } from "react"; import "./ChatComponent.css"; export default class ChatComponent extends Component { constructor(props) { super(props); this.state = { messageList: [], message: "", chatStatus: true, nameColor: null, }; this.chatScroll = React.createRef(); this.handleChange = this.handleChange.bind(this); this.handlePressKey = this.handlePressKey.bind(this); this.close = this.close.bind(this); this.sendMessage = this.sendMessage.bind(this); this.handleChatStatus = this.handleChatStatus.bind(this); this.sendQuestionSignal = this.sendQuestionSignal.bind(this); this.sendFastSignal = this.sendFastSignal.bind(this); this.sendHardSignal = this.sendHardSignal.bind(this); } componentDidMount() { // Delay the execution of the component initialization this.setState({ nameColor: this.getRandomBrightColor() }); // console.log(this.nameColor); setTimeout(() => { this.initializeChat(); }, 5000); // Adjust the delay time as needed } initializeChat() { // console.log( // "채팅의 getStreamManager()임!!!!!", // this.props.user.getStreamManager() // ); this.props.user .getStreamManager() .stream.session.on("signal:chat", (event) => { const data = JSON.parse(event.data); let messageList = this.state.messageList; messageList.push({ userProfileUrl: data.userProfileUrl, connectionId: event.from.connectionId, nickname: data.nickname, message: data.message, nameColor: data.nameColor, nowTime: data.nowTime, }); const document = window.document; this.setState({ messageList: messageList }); this.scrollToBottom(); }); } handleChange(event) { this.setState({ message: event.target.value }); } handlePressKey(event) { if (event.key === "Enter") { this.sendMessage(); } } handleChatStatus() { this.setState({ chatStatus: !this.state.chatStatus }); } sendMessage() { // console.log(this.state.message); if (this.props.user && this.state.message) { let message = this.state.message.replace(/ +(?= )/g, ""); let dt = new Date(); const hour = dt.getHours(); const min = dt.getMinutes(); const formattedHour = hour < 10 ? '0' + hour : hour; const formattedMin = min < 10 ? '0' + min : min; const nowTime = formattedHour + ":" + formattedMin; if (message !== "" && message !== " ") { const data = { userProfileUrl: this.props.userProfileUrl, message: message, nickname: this.props.user.getNickname(), streamId: this.props.user.getStreamManager().stream.streamId, nameColor: this.state.nameColor, nowTime: nowTime, }; this.props.user.getStreamManager().stream.session.signal({ data: JSON.stringify(data), type: "chat", }); } } this.setState({ message: "" }); } scrollToBottom() { setTimeout(() => { try { this.chatScroll.current.scrollTop = this.chatScroll.current.scrollHeight; } catch (err) {} }, 0); // Increase the delay to 200ms or more } close() { this.props.close(undefined); } getRandomBrightColor() { const hue = Math.floor(Math.random() * 360); const saturation = "100%"; const lightness = `${Math.floor(Math.random() * 21) + 70}%`; return `hsl(${hue}, ${saturation}, ${lightness})`; } // '질문이 있어요' signal 보내기 sendQuestionSignal() { // console.log('props다!!!!!!!!!',this.props.user) this.props.user.getStreamManager().stream.session.signal({ type:'questionSignal' }) } // '너무 빨라요' signal 보내기 sendFastSignal() { this.props.user.getStreamManager().stream.session.signal({ type: "tooFastSignal", }); } // 너무 어려워요 sendHardSignal() { this.props.user.getStreamManager().stream.session.signal({ type: "tooHardSignal", }); } render() { const { user } = this.props; return ( <div className="totalChatContainer"> {/* 제목 */} <div className="titleContainer"> <p className="chatTitleDetail"> <span style={{ cursor: "pointer", color: !this.state.chatStatus ? "#ffaa00" : "black", }} onClick={this.handleChatStatus} > 레시피 보기 </span> <span>|</span> <span style={{ cursor: "pointer", color: this.state.chatStatus ? "#ffaa00" : "black", }} onClick={this.handleChatStatus} > 채팅 </span> </p> </div> {this.state.chatStatus ? ( <div id="chatContainer" ref={this.chatScroll}> {/* 채팅 목록 */} <div id="chatComponent"> <div className="message-wrap"> {this.state.messageList.map((data, i) => ( <div key={i} id="remoteUsers" className={ "message" + (data.connectionId !== this.props.user.getConnectionId() ? " left" : " right") } > <div className="msg-container"> <img className="chatProfileImg" src={data.userProfileUrl} /> <div className="msg-info"> {/* {console.log(data.userProfileUrl)} */} <div style={{ display: "flex", flexDirection: "row", justifyContent: "space-between", }} > <span style={{ fontSize: "smaller", color: data.nameColor, }} > {data.nickname}{" "} </span> <span style={{ fontSize: "smaller" }}> {data.nowTime} </span> </div> <span>{data.message}</span> </div> </div> </div> ))} </div> </div> {/* 제출하기 input */} <div id="messageInput"> <input className="messageSendInput" placeholder=" 내용을 입력해주세요." id="chatInput" value={this.state.message} onChange={this.handleChange} onKeyPress={this.handlePressKey} /> <ion-icon name="arrow-redo-circle" style={{ color: "#ffaa00", width: "50px" }} onClick={this.sendMessage} size="large" ></ion-icon> </div> </div> ) : ( <div className="recipeContainer"> <div className="recipe-info"> <div className="recipe-title">재료</div> {this.props.recipeData.recipeIngredients.map( (ingredient, index) => ( <div key={index}> {this.props.recipeData.ingredients[index].name} :{" "} {ingredient.amount} </div> ) )} {/* {this.props.recipeData.recipeIngredients.map((ing)=>{ return <div>{ing.ingredientName} {ing.amount}</div> })} */} </div> <div className="recipe-info-list"> <div className="recipe-title">레시피</div> {this.props.recipeData.steps.map((step) => { return ( <div> <div style={{ fontWeight: "bold" }}> Step{step.orderingNumber} </div> <span>{step.description}</span> </div> ); })} </div> </div> )} <button className="reactionBtn" onClick={this.sendQuestionSignal}> 질문이 있어요 </button> <button className="reactionBtn" onClick={this.sendFastSignal}> 너무 빨라요 </button> <button className="reactionBtn" onClick={this.sendHardSignal}> 너무 어려워요 </button> </div> ); } }
--- title: Istio 1.21 Upgrade Notes description: Important changes to consider when upgrading to Istio 1.21.x. weight: 20 publishdate: 2024-03-13 --- When you upgrade from Istio 1.20.x to Istio 1.21.0, you need to consider the changes on this page. These notes detail the changes which purposefully break backwards compatibility with Istio 1.20.x. The notes also mention changes which preserve backwards compatibility while introducing new behavior. Changes are only included if the new behavior would be unexpected to a user of Istio 1.20.x. ## Default value of the feature flag `ENABLE_AUTO_SNI` to true [auto-sni](https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/core/v3/protocol.proto#envoy-v3-api-field-config-core-v3-upstreamhttpprotocoloptions-auto-sni) is enabled by default. This means SNI will be set automatically based on the downstream HTTP host/authority header if `DestinationRule` does not explicitly set the same. If this is not desired, use the new `compatibilityVersion` feature to fallback to old behavior. ## Default value of the feature flag `VERIFY_CERT_AT_CLIENT` is set to true This means server certificates will be automatically verified using the OS CA certificates when not using a DestinationRule `caCertificates` field. If this is not desired, use the new `compatibilityVersion` feature to fallback to old behavior, or use the `insecureSkipVerify` field in DestinationRule to skip the verification. ## `ExternalName` support changes Kubernetes `ExternalName` `Service`s allow users to create new DNS entries. For example, you can create an `example` service that points to `example.com`. This is implemented by a DNS `CNAME` redirect. In Istio, the implementation of `ExternalName`, historically, was substantially different. Each `ExternalName` represented its own service, and traffic matching the service was sent to the configured DNS name. This caused a few issues: * Ports are required in Istio, but not in Kubernetes. This can result in broken traffic if ports are not configured as Istio expects, despite them working without Istio. * Ports not declared as `HTTP` would match *all* traffic on that port, making it easy to accidentally send all traffic on a port to the wrong place. * Because the destination DNS name is treated as opaque, we cannot apply Istio policies to it as expected. For example, if I point an external name at another in-cluster Service (for example, `example.default.svc.cluster.local`), mTLS would not be used. `ExternalName` support has been revamped to fix these problems. `ExternalName`s are now simply treated as aliases. Wherever we would match `Host: <concrete service>` we additionally will match `Host: <external name service>`. Note that the primary implementation of `ExternalName` -- DNS -- is handled outside of Istio in the Kubernetes DNS implementation, and remains unchanged. If you are using `ExternalName` with Istio, please be advised of the following behavioral changes: * The `ports` field is no longer needed, matching Kubernetes behavior. If it is set, it will have no impact. * `VirtualServices` that route to an `ExternalName` service will no longer work unless the referenced service exists (as a Service or ServiceEntry). * `DestinationRule` can no longer apply to `ExternalName` services. Instead, create rules where the `host` references service. To opt-out, the `ENABLE_EXTERNAL_NAME_ALIAS=false` environment variable can be set. Note: the same change was introduced in the previous release, but off by default. This release turns the flag on by default. ## Gateway Name label modified If you are using the [Kubernetes Gateway](https://gateway-api.sigs.k8s.io/references/spec/#gateway.networking.k8s.io%2fv1.Gateway) to manage your Istio gateways, the label key used to identify the gateway name is changing from `istio.io/gateway-name` to `gateway.networking.k8s.io/gateway-name`. The old label will continue to be appended to the relevant label sets for backwards compatibility, but it will be removed in a future release. Furthermore, istiod's gateway controller will automatically detect and continue to use the old label for label selectors belonging to existing `Deployment` and `Service` resources. Therefore, once you've completed your Istio upgrade, you can change the label selector in `Deployment` and `Service` resources whenever you are ready to use the new label. Additionally, please upgrade any other policies, resources, or scripts that rely on the old label.
package com.example.naziacakes; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; public class LoginActivity extends AppCompatActivity { EditText e1,e2; Button b1; FirebaseAuth mAuth; SignInButton gbtn; GoogleApiClient mGoogleApiClient; private static final String TAG ="Cake Gallery"; private static final int RC_SIGN_IN = 2; public void register(View view){ startActivity(new Intent(LoginActivity.this,RegisterActivity.class)); } public void forget(View view){ startActivity(new Intent(LoginActivity.this,ForgetActivity.class)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); gbtn = findViewById(R.id.SignInbtn); mAuth = FirebaseAuth.getInstance(); e1 = findViewById(R.id.EmailID); e2 = findViewById(R.id.Password); b1 = findViewById(R.id.Login); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Toast.makeText(LoginActivity.this, "Something went wrong!!", Toast.LENGTH_SHORT).show(); } }) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); gbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signIn(); } }); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String email = e1.getText().toString().trim(); final String password = e2.getText().toString().trim(); mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (!task.isSuccessful()) { if (password.length() < 6) { e2.setError("Minimum password length is 6!!"); } else { Toast.makeText(LoginActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show(); } } else { Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); } } }); } }); } @Override protected void onStart() { super.onStart(); //if the user is already signed in //we will close this activity //and take the user to profile activity if (mAuth.getCurrentUser() != null) { finish(); String nn=mAuth.getCurrentUser().getEmail(); Toast.makeText(LoginActivity.this,nn,Toast.LENGTH_SHORT).show(); startActivity(new Intent(this, MainActivity.class)); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //if the requestCode is the Google Sign In code that we defined at starting if (requestCode == RC_SIGN_IN) { //Getting the GoogleSignIn Task Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { //Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); //authenticating with firebase firebaseAuthWithGoogle(account); } catch (ApiException e) { Toast.makeText(LoginActivity.this, "NOT SUCCESS", Toast.LENGTH_SHORT).show(); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); //getting the auth credential AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); //Now using firebase we are signing in the user here mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(LoginActivity.this, "User Signed In", Toast.LENGTH_SHORT).show(); Intent intent=new Intent(LoginActivity.this,MainActivity.class); startActivity(intent); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.getException()); Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } // ... } }); } private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent,RC_SIGN_IN); } }
import { makeCollidable } from "./collidable.js"; import { drawTile, getFramesPos } from "../utils.js"; export function makeTiledMap(p, x, y) { return { tileWidth: 32, tileHeight: 32, x, y, async load(tilesetURL, tiledMapURL) { this.mapImage = p.loadImage(tilesetURL); const response = await fetch(tiledMapURL); this.tiledData = await response.json(); }, prepareTiles() { this.tilesPos = getFramesPos(8, 55, this.tileWidth, this.tileHeight); }, getSpawnPoints() { for (const layer of this.tiledData.layers) { if (layer.name === "SpawnPoints") { return layer.objects; } } }, draw(camera, player) { for (const layer of this.tiledData.layers) { if (layer.type === "tilelayer") { const currentTilePos = { x: this.x, y: this.y, }; let nbOfTilesDrawn = 0; for (const tileNumber of layer.data) { if (nbOfTilesDrawn % layer.width === 0) { currentTilePos.x = this.x; currentTilePos.y += this.tileHeight; } else { currentTilePos.x += this.tileWidth; } nbOfTilesDrawn++; if (tileNumber === 0) continue; drawTile( p, this.mapImage, Math.round(currentTilePos.x + camera.x), Math.round(currentTilePos.y + camera.y), this.tilesPos[tileNumber - 1].x, this.tilesPos[tileNumber - 1].y, this.tileWidth, this.tileHeight ); } } if (layer.type === "objectgroup" && layer.name === "Boundaries") { for (const boundary of layer.objects) { const collidable = makeCollidable( p, this.x + boundary.x, this.y + boundary.y + this.tileHeight, boundary.width, boundary.height ); collidable.preventPassthroughFrom(player); collidable.update(camera); collidable.draw(); } } } }, }; }
Java String trim() The java string trim() method eliminates leading and trailing spaces. The unicode value of space character is '\u0020'. The trim() method in java string checks this unicode value before and after the string, if it exists then removes the spaces and returns the omitted string. The string trim() method doesn't omits middle spaces. Internal implementation public String trim() { int len = value.length; int st = 0; char[] val = value; /* avoid getfield opcode */ while ((st < len) && (val[st] <= ' ')) { st++; } while ((st < len) && (val[len - 1] <= ' ')) { len--; } return ((st > 0) || (len < value.length)) ? substring(st, len) : this; } Signature The signature or syntax of string trim method is given below: public String trim() Returns string with omitted leading and trailing spaces Java String trim() method example public class StringTrimExample{ public static void main(String args[]){ String s1=" hello string "; System.out.println(s1+"javatpoint");//without trim() System.out.println(s1.trim()+"javatpoint");//with trim() }} Test it Now hello string javatpoint hello stringjavatpoint Java String trim() Method Example 2 This example demonstrate the use of trim method. This method removes all the trailing spaces so the length of string also reduces. Let's see an example. public class StringTrimExample { public static void main(String[] args) { String s1 =" hello java string "; System.out.println(s1.length()); System.out.println(s1); //Without trim() String tr = s1.trim(); System.out.println(tr.length()); System.out.println(tr); //With trim() } } 22 hello java string 17 hello java string
# frozen_string_literal: true module EE module Gitlab module Ci module Config module Entry module Job extend ActiveSupport::Concern extend ::Gitlab::Utils::Override EE_ALLOWED_KEYS = %i[dast_configuration secrets pages_path_prefix].freeze prepended do attributes :dast_configuration, :secrets, :pages_path_prefix entry :dast_configuration, ::Gitlab::Ci::Config::Entry::DastConfiguration, description: 'DAST configuration for this job', inherit: false entry :secrets, ::Gitlab::Config::Entry::ComposableHash, description: 'Configured secrets for this job', inherit: false, metadata: { composable_class: ::Gitlab::Ci::Config::Entry::Secret } entry :pages_path_prefix, ::Gitlab::Ci::Config::Entry::PagesPathPrefix, inherit: false, description: \ 'Pages path prefix identifier. ' \ 'This allows to create multiple versions of the same site with different path prefixes' validations do validates :pages_path_prefix, absence: { message: "can only be used within a `pages` job" }, unless: -> { pages_job? } end end class_methods do extend ::Gitlab::Utils::Override override :allowed_keys def allowed_keys super + EE_ALLOWED_KEYS end end override :value def value super.merge({ dast_configuration: dast_configuration_value, secrets: secrets_value, pages_path_prefix: pages_path_prefix }.compact) end end end end end end end
const express = require('express'); const { Todo } = require('../mongo') const { getAsync, setAsync } = require('../redis'); const router = express.Router(); /* GET todos listing. */ router.get('/', async (_, res) => { const todos = await Todo.find({}) res.send(todos); }); /* POST todo to listing. */ router.post('/', async (req, res) => { const currentCount = parseInt(await getAsync('todoCount')); let updatedCount; if (isNaN(currentCount)) { updatedCount = 1; } else { updatedCount = currentCount + 1; } const todo = await Todo.create({ text: req.body.text, done: false }) await setAsync('todoCount', updatedCount); res.send(todo); }); const singleRouter = express.Router(); const findByIdMiddleware = async (req, res, next) => { const { id } = req.params req.todo = await Todo.findById(id) if (!req.todo) return res.sendStatus(404) next() } /* DELETE todo. */ singleRouter.delete('/', async (req, res) => { await req.todo.delete(); res.sendStatus(200); }); /* GET todo. */ singleRouter.get('/', async (req, res) => { const foundTodo = req.todo; res.status(200).send(foundTodo); }); /* PUT todo. */ singleRouter.put('/', async (req, res) => { const { text, done } = req.body; const foundTodo = req.todo; foundTodo.text = text || foundTodo.text; foundTodo.done = done || foundTodo.done; await foundTodo.save(); res.send(foundTodo); }); router.use('/:id', findByIdMiddleware, singleRouter) module.exports = router;
import requests import json import config from datetime import datetime from yahoo_fin import stock_info as si class TDAmeritrade: """ Pulls stock data from TD Ameritrade API stock_ticker: str -> stock ticker you are looking for data for api_key: str -> in the config file, this is the API key to TD Ameritrade period_type: str -> day, month, year, or ytd, default is year period: str -> The number of periods to show, default is 1 frequency_type: str -> minute, daily, weekly or monthly. Default is daily frequency: str -> if minute (put 1, 5, 10, 15, 30), if daily (put 1), if weekly (put 1), if monthly (put 1) need_extended: str -> get extended hours data with true projection: str -> type of information you are looking for from fundamentals. Default is fundamental TO BE ADDED FOR OPTIONS contract_type: str -> CALL, PUT or ALL. Default is ALL strike_count: str -> The number of strikes to return above and below the at the money price. Default is 10 include_quotes: str -> Include quotes for options in the option chain. Can be TRUE or FALSE. Default is TRUE strategy: str -> SINGLE, ANALYTICAL (Allows use of volatility, underlyingPrice, InterestRate, and daysToExpire params to calculate theoretical values), COVERED, VERTICAL, CALENDAR, STRANGLE, STRADDLE, BUTTERFLY, CONDOR, DIAGONAL, COLLAR, or ROLL. Default is SINGLE strike: str -> strike price, Default 10 -> MUST PUT A VALUE IN FOR THIS option_range -> ITM (In The Money), NTM (Near the Money), OTM (Out of the money), SAK (Strikes Above Market), SBK (Strikes Below Market), SNK (Strikes Near Market), ALL (All Strikes) Default ALL from_date to_date volatility underlying_price interest_rate days_to_expire exp_month option_type """ def __init__(self, api_key=config.tda_api_key, period_type='year', frequency_type='daily', frequency='1', projection='fundamental', direction='up', change='percent', start_date='2020-01-01', end_date=datetime.today()): self.api_key = api_key self.period_type = period_type self.frequency_type = frequency_type self.frequency = frequency self.projection = projection self.direction = direction self.change = change self.start_date = str(int(datetime.strptime(start_date, "%Y-%m-%d").timestamp() * 1000)) self.end_date = str(int(end_date.timestamp() * 1000)) # self.end_date = str(int(datetime.strptime(end_date, "%Y-%m-%d").timestamp() * 1000)) @staticmethod def get_all_tickers(): df1 = si.tickers_dow(include_company_data=True) df1 = df1[['Symbol', 'Company']] df2 = si.tickers_sp500(include_company_data=True) df2 = df2[['Symbol', 'Security']] df2.rename(columns={'Security': 'Company'}, inplace=True) df3 = si.tickers_nasdaq(include_company_data=True) df3 = df3[['Symbol', 'Security Name']] df3.rename(columns={'Security Name': 'Company'}, inplace=True) df4 = si.tickers_other(include_company_data=True) df4 = df4[['ACT Symbol', 'Security Name']] df4.rename(columns={'ACT Symbol': 'Symbol', 'Security Name': 'Company'}, inplace=True) df = df1.append(df2).append(df3).append(df4) df.sort_values(by='Symbol', inplace=True) df.drop_duplicates(subset="Symbol", keep="first", inplace=True) df = df[~df['Symbol'].str.contains('.', regex=False)] df = df[~df['Symbol'].str.contains('$', regex=False)] df = df[df['Symbol'] != 'ZVV'] df = df[df['Symbol'] != 'ZVZZC'] df = df[df['Symbol'] != 'ZVZZT'] df = df[df['Symbol'] != 'ZWZZT'] df = df[df['Symbol'] != 'ZXZZT'] df = df[df['Symbol'] != 'ZJZZT'] df = df[~df["Symbol"].str.contains("File Creation")] return df.set_index('Symbol')['Company'].to_dict() def get_prices(self, ticker): price_endpoint = config.prices_url.format(stock_ticker=ticker, periodType=self.period_type, frequencyType=self.frequency_type, frequency=self.frequency, end_date=self.end_date, start_date=self.start_date) return self.get_content(price_endpoint) def get_fundamentals(self, ticker): fundamental_endpoint = config.fundamentals_url.format(stock_ticker=ticker, projection=self.projection) return self.get_content(fundamental_endpoint) def get_options(self, ticker): options_endpoint = config.options_url.format(stock_ticker=ticker) return self.get_content(options_endpoint) def get_movers(self, index): movers_endpoint = config.movers_url.format(index=index, direction=self.direction, change=self.change) return self.get_content(movers_endpoint) def get_content(self, url): page = requests.get(url=url, params={'apikey': self.api_key}) return json.loads(page.content) class TDDataPull: @staticmethod def pull_one_minute(ticker): tda = TDAmeritrade(period_type='day', frequency_type='minute') return tda.get_prices(ticker) @staticmethod def pull_five_minute(ticker): tda = TDAmeritrade(period_type='day', frequency_type='minute', frequency='5') return tda.get_prices(ticker) @staticmethod def pull_ten_minute(ticker): tda = TDAmeritrade(period_type='day', frequency_type='minute', frequency='10') return tda.get_prices(ticker) @staticmethod def pull_fifteen_minute(ticker): tda = TDAmeritrade(period_type='day', frequency_type='minute', frequency='15') return tda.get_prices(ticker) @staticmethod def pull_thirty_minute(ticker): tda = TDAmeritrade(period_type='day', frequency_type='minute', frequency='30') return tda.get_prices(ticker) @staticmethod def pull_hour(ticker): tda = TDAmeritrade(period_type='day', frequency_type='minute', frequency='60') return tda.get_prices(ticker) @staticmethod def pull_daily(ticker): tda = TDAmeritrade(period_type='year', frequency_type='daily', frequency='1') return tda.get_prices(ticker) @staticmethod def pull_weekly(ticker): tda = TDAmeritrade(period_type='year', frequency_type='weekly', frequency='1') return tda.get_prices(ticker) if __name__ == "__main__": # tda = TDAmeritrade() # prices = tda.get_prices("TSLA") # options = tda.get_options("TSLA") # fund = tda.get_fundamentals("TSLA") # list_tickers = tda.get_all_tickers() tddp = TDDataPull() prices = tddp.pull_one_minute('TSLA') pass
import os import random import torch import torchaudio from pytorch_lightning import LightningDataModule def _batch_by_token_count(idx_target_lengths, max_tokens, batch_size=None): batches = [] current_batch = [] current_token_count = 0 for idx, target_length in idx_target_lengths: if current_token_count + target_length > max_tokens or (batch_size and len(current_batch) == batch_size): batches.append(current_batch) current_batch = [idx] current_token_count = target_length else: current_batch.append(idx) current_token_count += target_length if current_batch: batches.append(current_batch) return batches def get_sample_lengths(commom_voice_dataset): fileid_to_target_length = {} def _target_length(item_file): file_id = item_file[0] transcript = item_file[2] if file_id not in fileid_to_target_length: fileid_to_target_length[file_id] = len(transcript) # speaker_id, chapter_id, _ = fileid.split("-") # file_text = speaker_id + "-" + chapter_id + commom_voice_dataset._ext_txt # file_text = os.path.join(commom_voice_dataset._path, speaker_id, chapter_id, file_text) # with open(file_text) as ft: # for line in ft: # fileid_text, transcript = line.strip().split(" ", 1) # fileid_to_target_length[fileid_text] = len(transcript) return fileid_to_target_length[file_id] return [_target_length(fitem_file) for fitem_file in commom_voice_dataset._walker] class CustomBucketDataset(torch.utils.data.Dataset): def __init__( self, dataset, lengths, max_tokens, num_buckets, shuffle=False, batch_size=None, ): super().__init__() assert len(dataset) == len(lengths) self.dataset = dataset max_length = max(lengths) min_length = min(lengths) assert max_tokens >= max_length buckets = torch.linspace(min_length, max_length, num_buckets) lengths = torch.tensor(lengths) bucket_assignments = torch.bucketize(lengths, buckets) idx_length_buckets = [(idx, length, bucket_assignments[idx]) for idx, length in enumerate(lengths)] if shuffle: idx_length_buckets = random.sample(idx_length_buckets, len(idx_length_buckets)) else: idx_length_buckets = sorted(idx_length_buckets, key=lambda x: x[1], reverse=True) sorted_idx_length_buckets = sorted(idx_length_buckets, key=lambda x: x[2]) self.batches = _batch_by_token_count( [(idx, length) for idx, length, _ in sorted_idx_length_buckets], max_tokens, batch_size=batch_size, ) def __getitem__(self, idx): return [self.dataset[subidx] for subidx in self.batches[idx]] def __len__(self): return len(self.batches) class TransformDataset(torch.utils.data.Dataset): def __init__(self, dataset, transform_fn): self.dataset = dataset self.transform_fn = transform_fn def __getitem__(self, idx): return self.transform_fn(self.dataset[idx]) def __len__(self): return len(self.dataset) class CommomVoiceDataModule(LightningDataModule): common_voice_cls = torchaudio.datasets.COMMONVOICE def __init__( self, *, dataset_path, train_transform, val_transform, test_transform, max_tokens=700, batch_size=2, train_num_buckets=50, train_shuffle=True, num_workers=10, ): super().__init__() self.dataset_path = dataset_path self.train_dataset_lengths = None self.val_dataset_lengths = None self.train_transform = train_transform self.val_transform = val_transform self.test_transform = test_transform self.max_tokens = max_tokens self.batch_size = batch_size self.train_num_buckets = train_num_buckets self.train_shuffle = train_shuffle self.num_workers = num_workers def train_dataloader(self): datasets = [ self.common_voice_cls(self.dataset_path, tsv="validated.tsv"), ] if not self.train_dataset_lengths: self.train_dataset_lengths = [get_sample_lengths(dataset) for dataset in datasets] dataset = torch.utils.data.ConcatDataset( [ CustomBucketDataset( dataset, lengths, self.max_tokens, self.train_num_buckets, batch_size=self.batch_size, ) for dataset, lengths in zip(datasets, self.train_dataset_lengths) ] ) # dataset = CustomBucketDataset(dataset, None, self.max_tokens, self.train_num_buckets, batch_size=self.batch_size) dataset = TransformDataset(dataset, self.train_transform) dataloader = torch.utils.data.DataLoader( dataset, num_workers=self.num_workers, batch_size=None, shuffle=self.train_shuffle, ) return dataloader def val_dataloader(self): datasets = [ self.common_voice_cls(self.dataset_path, tsv="dev.tsv"), ] if not self.val_dataset_lengths: self.val_dataset_lengths = [get_sample_lengths(dataset) for dataset in datasets] dataset = torch.utils.data.ConcatDataset( [ CustomBucketDataset( dataset, lengths, self.max_tokens, 1, batch_size=self.batch_size, ) for dataset, lengths in zip(datasets, self.val_dataset_lengths) ] ) dataset = TransformDataset(dataset, self.val_transform) datalot = TransformDataset(dataset, self.val_transform) dataloader = torch.utils.data.DataLoader(dataset, batch_size=None, num_workers=self.num_workers) return dataloader def test_dataloader(self): dataset = self.common_voice_cls(self.dataset_path, url="test.tsv") dataset = TransformDataset(dataset, self.test_transform) dataloader = torch.utils.data.DataLoader(dataset, batch_size=None) return dataloader
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.samza.table; import junit.framework.Assert; import org.apache.samza.SamzaException; import org.apache.samza.config.JavaTableConfig; import org.apache.samza.config.MapConfig; import org.apache.samza.config.SerializerConfig; import org.apache.samza.context.MockContext; import org.apache.samza.serializers.IntegerSerde; import org.apache.samza.serializers.Serde; import org.apache.samza.serializers.SerializableSerde; import org.apache.samza.serializers.StringSerde; import org.apache.samza.storage.StorageEngine; import org.junit.Test; import java.lang.reflect.Field; import java.util.Base64; import java.util.HashMap; import java.util.Map; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class TestTableManager { private static final String TABLE_ID = "t1"; public static class DummyTableProviderFactory implements TableProviderFactory { static ReadWriteUpdateTable table; static TableProvider tableProvider; @Override public TableProvider getTableProvider(String tableId) { table = mock(ReadWriteUpdateTable.class); tableProvider = mock(TableProvider.class); when(tableProvider.getTable()).thenReturn(table); return tableProvider; } } @Test public void testInitByConfig() { Map<String, String> map = new HashMap<>(); map.put(String.format(JavaTableConfig.TABLE_PROVIDER_FACTORY, TABLE_ID), DummyTableProviderFactory.class.getName()); map.put(String.format("tables.%s.some.config", TABLE_ID), "xyz"); addKeySerde(map); addValueSerde(map); doTestInit(map); } @Test(expected = Exception.class) public void testInitFailsWithoutProviderFactory() { Map<String, String> map = new HashMap<>(); addKeySerde(map); addValueSerde(map); doTestInit(map); } @Test(expected = IllegalStateException.class) public void testInitFailsWithoutInitializingLocalStores() { TableManager tableManager = new TableManager(new MapConfig(new HashMap<>())); tableManager.getTable("dummy"); } private void doTestInit(Map<String, String> map) { Map<String, StorageEngine> storageEngines = new HashMap<>(); storageEngines.put(TABLE_ID, mock(StorageEngine.class)); TableManager tableManager = new TableManager(new MapConfig(map)); tableManager.init(new MockContext()); for (int i = 0; i < 2; i++) { Table table = tableManager.getTable(TABLE_ID); verify(DummyTableProviderFactory.tableProvider, times(1)).init(anyObject()); verify(DummyTableProviderFactory.tableProvider, times(1)).getTable(); Assert.assertEquals(DummyTableProviderFactory.table, table); } Map<String, TableManager.TableCtx> ctxMap = getFieldValue(tableManager, "tableContexts"); TableManager.TableCtx ctx = ctxMap.get(TABLE_ID); Assert.assertEquals(TABLE_ID, ctxMap.keySet().iterator().next()); TableProvider tableProvider = getFieldValue(ctx, "tableProvider"); Assert.assertNotNull(tableProvider); } private void addKeySerde(Map<String, String> map) { String serdeId = "key-serde"; map.put(String.format(SerializerConfig.SERDE_SERIALIZED_INSTANCE, serdeId), serializeSerde(new IntegerSerde())); map.put(String.format(JavaTableConfig.STORE_KEY_SERDE, TABLE_ID), serdeId); } private void addValueSerde(Map<String, String> map) { String serdeId = "value-serde"; map.put(String.format(SerializerConfig.SERDE_SERIALIZED_INSTANCE, serdeId), serializeSerde(new StringSerde("UTF-8"))); map.put(String.format(JavaTableConfig.STORE_MSG_SERDE, TABLE_ID), serdeId); } private String serializeSerde(Serde serde) { return Base64.getEncoder().encodeToString(new SerializableSerde().toBytes(serde)); } private <T> T getFieldValue(Object object, String fieldName) { Field field = null; try { field = object.getClass().getDeclaredField(fieldName); field.setAccessible(true); return (T) field.get(object); } catch (NoSuchFieldException | IllegalAccessException ex) { throw new SamzaException(ex); } finally { if (field != null) { field.setAccessible(false); } } } }
import 'package:flutter/material.dart'; import 'package:projeto3_refeicoes/components/category_item.dart'; import '../data//dummy_data.dart'; class CategoriesScreen extends StatelessWidget { const CategoriesScreen({super.key}); @override Widget build(BuildContext context) { return GridView( padding: const EdgeInsets.all(25), //sliver quer dizer q tem scroll, grid delegate delegando quem vai extender no caso max cross axis gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 200, // proporcao de cada elemento na grid childAspectRatio: 3 / 2, crossAxisSpacing: 20, mainAxisSpacing: 20, ), children: DUMMY_CATEGORIES.map((cat) { return CategoryItem(category: cat); }).toList(), ); } }
/* tslint:disable */ /* eslint-disable */ import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { BaseService } from '../base-service'; import { ApiConfiguration } from '../api-configuration'; import { StrictHttpResponse } from '../strict-http-response'; import { RequestBuilder } from '../request-builder'; import { Observable } from 'rxjs'; import { map, filter } from 'rxjs/operators'; @Injectable({ providedIn: 'root', }) export class ApiService extends BaseService { constructor( config: ApiConfiguration, http: HttpClient ) { super(config, http); } /** * Path part for operation appControllerGetData */ static readonly AppControllerGetDataPath = '/api/hello'; /** * This method provides access to the full `HttpResponse`, allowing access to response headers. * To access only the response body, use `appControllerGetData()` instead. * * This method doesn't expect any request body. */ appControllerGetData$Response(params?: { }): Observable<StrictHttpResponse<void>> { const rb = new RequestBuilder(this.rootUrl, ApiService.AppControllerGetDataPath, 'get'); if (params) { } return this.http.request(rb.build({ responseType: 'text', accept: '*/*' })).pipe( filter((r: any) => r instanceof HttpResponse), map((r: HttpResponse<any>) => { return (r as HttpResponse<any>).clone({ body: undefined }) as StrictHttpResponse<void>; }) ); } /** * This method provides access to only to the response body. * To access the full response (for headers, for example), `appControllerGetData$Response()` instead. * * This method doesn't expect any request body. */ appControllerGetData(params?: { }): Observable<void> { return this.appControllerGetData$Response(params).pipe( map((r: StrictHttpResponse<void>) => r.body as void) ); } }
// ----------------------------------------------------------------------------- // This file contains all application-wide Sass mixins. // ----------------------------------------------------------------------------- /// Event wrapper /// @author Harry Roberts /// @param {Bool} $self [false] - Whether or not to include current selector /// @link https://twitter.com/csswizardry/status/478938530342006784 Original tweet from Harry Roberts @mixin on-event($self: false) { @if $self { &, &:hover, &:active, &:focus, &:focus-within { @content; } } @else { &:hover, &:active, &:focus, &:focus-within { @content; } } } /// Make a context based selector a little more friendly /// @author Kitty Giraudel /// @param {String} $context @mixin when-inside($context) { #{$context} & { @content; } } @mixin cards-gradient { background: linear-gradient(45deg, rgba(248,219,229,1) 0%, rgba(255,252,247,1) 94%); } @mixin main-gradient { background: radial-gradient(circle, rgba(249,220,211,1) 16%, rgba(206,171,209,1) 100%); } @mixin media-tablet { @media (max-width: $tablet-width) { @content; } } @mixin media-mobile { @media (max-width: $mobile-width) { @content; } }
// This file is part of www.nand2tetris.org // and the book "The Elements of Computing Systems" // by Nisan and Schocken, MIT Press. // File name: projects/03/b/RAM4K.hdl /** * Memory of 4K registers, each 16 bit-wide. Out holds the value * stored at the memory location specified by address. If load==1, then * the in value is loaded into the memory location specified by address * (the loaded value will be emitted to out from the next time step onward). */ CHIP RAM4K { IN in[16], load, address[12]; OUT out[16]; PARTS: DMux8Way(in=true, sel=address[0..2], a=addr1, b=addr2, c=addr3, d=addr4, e=addr5, f=addr6, g=addr7, h=addr8); And(a=load, b=addr1, out=load1); And(a=load, b=addr2, out=load2); And(a=load, b=addr3, out=load3); And(a=load, b=addr4, out=load4); And(a=load, b=addr5, out=load5); And(a=load, b=addr6, out=load6); And(a=load, b=addr7, out=load7); And(a=load, b=addr8, out=load8); RAM512(in=in, load=load1, address=address[3..11], out=out1); RAM512(in=in, load=load2, address=address[3..11], out=out2); RAM512(in=in, load=load3, address=address[3..11], out=out3); RAM512(in=in, load=load4, address=address[3..11], out=out4); RAM512(in=in, load=load5, address=address[3..11], out=out5); RAM512(in=in, load=load6, address=address[3..11], out=out6); RAM512(in=in, load=load7, address=address[3..11], out=out7); RAM512(in=in, load=load8, address=address[3..11], out=out8); Mux8Way16(a=out1, b=out2, c=out3, d=out4, e=out5, f=out6, g=out7, h=out8, sel=address[0..2], out=out); }
<script> import Button from '$lib/components/common/Button.svelte'; import FlexContainer from '$lib/components/common/FlexContainer.svelte'; import GridContainer from '$lib/components/common/GridContainer.svelte'; import Tag from '$lib/components/common/Tag.svelte'; import CloseIcon from '$lib/components/materialIcons/CloseIcon.svelte'; import Logo from '$lib/components/svg/Logo.svelte'; import { displayError } from '$lib/modules/errors'; import { deleteOAuthAccount, terminateOAuthAccountSessions } from '$lib/modules/requests'; import { formatDuration } from '$lib/modules/utils'; import { showSnackbar } from '$lib/stores/snackbar'; import { minuteTimer } from '$lib/stores/timers'; export let handleClose; export let account; let deleting = false; let terminating = false; async function terminateActiveSessions() { terminating = true; try { await terminateOAuthAccountSessions({ id: account.id }); showSnackbar({ text: 'Active sessions terminated.' }); } catch (err) { console.error(err); displayError(err); } finally { terminating = false; } } async function revokeAccess() { deleting = true; try { await deleteOAuthAccount({ id: account.id }); handleClose(account.id); } catch (err) { console.error(err); displayError(err); } finally { deleting = false; } } </script> <FlexContainer column gap="1rem"> <FlexContainer align_items="center" justify_content="space-between"> <h3 class="no-margin">Account Info</h3> <Button height="auto" on:click={handleClose} blendin rounded> <CloseIcon dimension="25px" /> </Button> </FlexContainer> <FlexContainer column margin="0px" justify_items="center" align_items="stretch" gap="1rem"> <GridContainer template_columns="50px 1fr" align_items="top" padding="0.5rem" gap="0.7rem" border rounded> <FlexContainer height="50px" bgColor="var(--new-layer-color)" width="auto" roundedIcon> {#if account.client_icon} <img alt="icon" src={`data:image/png;base64,${account.client_icon}`} /> {:else} <Logo dimension="100%" color="linear-gradient(#e66465, #9198e5)" opacity="1" blueprint /> {/if} </FlexContainer> <FlexContainer column align_items="start" gap="0.2rem"> <h5 class="no-margin">{account.client_name}</h5> <span class="xs">{new URL(account.client_url).host}</span> <div> <Tag><span class="xs oneline">Created {formatDuration(account.created_at - $minuteTimer)}</span></Tag> <Tag><span class="xs oneline">Last login {formatDuration(account.last_auth - $minuteTimer)}</span></Tag> </div> </FlexContainer> </GridContainer> <FlexContainer column align_items="center" bgColor="var(--new-layer-color)" padding="0.5rem" gap="0.5rem" rounded> <h6 class="no-margin">Account Data</h6> {#if !account?.name && !account?.email} <FlexContainer column align_items="center"> <span class="xs">No data has been shared with <strong>{account.client_name}</strong>.</span> </FlexContainer> {:else} <GridContainer template_columns="auto 1fr" align_items="center" gap="0.5rem"> <div class="gridline"></div> {#if !!account?.name} <h6 class="no-margin">Name</h6> <span class="xs">{account.name}</span> {/if} {#if !!account?.email} <h6 class="no-margin">Email</h6> <span class="xs">{account.email}</span> {/if} </GridContainer> {/if} </FlexContainer> </FlexContainer> <FlexContainer column gap="0.5rem"> <Button on:click={terminateActiveSessions} basic rounded disabled={terminating || deleting}> {#if terminating} Terminating active sessions... {:else} Terminate active sessions {/if} </Button> <Button on:click={revokeAccess} danger rounded disabled={deleting}> {#if deleting} Revoking Access... {:else} Revoke Access {/if} </Button> </FlexContainer> </FlexContainer>