text
stringlengths
184
4.48M
import 'package:news/core/data/model/news_recsource.dart'; import 'package:news/core/database/dao/news_resource_dao.dart'; import 'package:news/core/database/dao/topic_dao.dart'; import 'package:news/core/database/model/news_resource_topic_corss_ref.dart'; import 'package:news/core/database/model/topic_entity.dart'; import 'package:news/core/database/nia_database.dart'; import 'package:news/core/network/network_data_source.dart'; import 'package:news/core/shared_preference/user_data.dart'; import '../../database/model/news_resource_entity.dart'; import '../sync_utils.dart'; /// singleton of news repository. NewsRepository newsRepository = OfflineFirstNewsRepository( newsResourceDao: niaDatabase.getNewsResourceDao(), topicDao: niaDatabase.getTopicDao(), networkDataSource: networkDataSource, niaPreferencesDataSource: niaUserDataSource); abstract class NewsRepository implements Syncable { Stream<List<NewsResource>> getNewsResources( {Set<String> filterTopicIds = const {}, Set<String> filterNewsIds = const {}}); } class OfflineFirstNewsRepository extends NewsRepository { final NewsResourceDao newsResourceDao; final TopicDao topicDao; final NetworkDataSource networkDataSource; final NiaPreferencesDataSource niaPreferencesDataSource; OfflineFirstNewsRepository( {required this.newsResourceDao, required this.topicDao, required this.networkDataSource, required this.niaPreferencesDataSource}); @override Stream<List<NewsResource>> getNewsResources( {Set<String> filterTopicIds = const {}, Set<String> filterNewsIds = const {}}) { final newsEntitiesStream = newsResourceDao.getPopulatedNewsResourceStream( useFilterNewsIds: filterNewsIds.isNotEmpty, filterNewsIds: filterNewsIds, useFilterTopicIds: filterTopicIds.isNotEmpty, filterTopicIds: filterTopicIds); return newsEntitiesStream.map((list) { return list.map((e) => NewsResource.fromEntity(e)).toList(); }); } @override Future<bool> syncWith(Synchronizer synchronizer) { var isFirstSync = false; return synchronizer.changeListSync( versionReader: (ChangeListVersions currentChangeListVersion) => currentChangeListVersion.newsResourceVersion, changeListFetcher: (int version) async { isFirstSync = version <= 0; return networkDataSource.getNewsResourceChangeList(after: version); }, versionUpdater: (ChangeListVersions lastVersion, int newVersion) { return ChangeListVersions( newsResourceVersion: newVersion, topicVersion: lastVersion.topicVersion); }, modelDeleter: (List<String> ids) async { await newsResourceDao.deleteNewsResources(ids); }, modelUpdater: (List<String> ids) async { // bool hasOnboarded = niaPreferencesDataSource.shouldHideOnboarding; // Set<String> followedTopicIds = // niaPreferencesDataSource.followedTopics; // if (isFirstSync) { // // When we first retrieve news, mark everything viewed, so that we aren't // // overwhelmed with all historical news. // niaPreferencesDataSource.setNewsResourcesViewed(changedIds, true) // } final networkNewsResources = await networkDataSource.getNewsResources(ids: ids); await topicDao.insertOrIgnoreTopics(networkNewsResources .map((e) => TopicEntity.fromNewsDto(e)) .expand((list) => list) .toSet() .toList()); await newsResourceDao.upsertNewsResources( networkNewsResources .map((res) => NewsResourceEntity.fromDto(res)) .toSet() .toList(), ); await newsResourceDao.insertOrIgnoreTopicCrossRefEntities( networkNewsResources .map((res) => NewsResourceTopicCrossRef.fromDto(res)) .expand((list) => list) .toSet() .toList(), ); } // if (hasOnboarded) {} ); } }
// Este es un comentario para el scss // Partials @import "partials/reset"; @import "partials/mixins"; @import "partials/extend"; $colorbody: #c8d8e4; $colorheader: #52ab98; $colorfooter: #2b6777; /* Grid areas del body */ header { grid-area: cabecera; } main { grid-area: principal; } footer { grid-area: pie; } /* Grid areas del Nav */ .homeNav { grid-area: casa; } .enlacesNav { grid-area: enlaces; } .search { grid-area: busqueda; } /* Grid areas del Footer */ .info { grid-area: info; } .contacto { grid-area: contacto; } .copyright { grid-area: derechos; } /* Display del body */ body { display: grid; grid-template-areas: "cabecera" "principal" "pie"; grid-template-rows: auto auto auto; background-color: $colorbody; } /* Display del header */ header { background-color: $colorheader; z-index: 1; } /* Display del footer */ footer { background-color: $colorfooter; } /* Anulo el padding y el margin de Bootstrap para que no rompa el nav */ ul { padding-left: 0px; margin: 0px; } /* Alinea el contenido del main en el medio */ main { text-align: center; } /* Se acomoda el icono de home */ .homeNav { text-align: center; vertical-align: auto; /* Tamaño de la imagen del home */ img { width: 100px; } } /* Se acomoda los enlaces a las paginas */ .enlacesNav { list-style-type: none; display: flex; flex-direction: row; justify-content: space-evenly; align-items: center; /* Estilo del nav para que se vea como un boton de enlace */ a { font-weight: bold; padding: 20px; text-decoration: none; display: block; background-color: $colorheader; color: #ffffff; /* Animacion de los botones cuando se pasa el mouse */ &:hover { background-color: $colorfooter; color: #f2f2f2; } } } /* Estilo de las listas dentro del nav */ .navegacion { ul { list-style-type: none; display: flex; flex-direction: row; /* Para que el submenu tome como referencia el menu */ li { position: relative; /* Para ocultar los sub-menus */ ul { display: none; min-width: 90px; /* Acomoda el sub menu a la derecha */ li ul { left: 119px; top: 0px; } } /* Aparecen los submenus al pasar el mouse para un item de la lista */ &:hover > ul { display: block; position: absolute; } } } } /* Se acomodan los elementos del footer */ .info { display: flex; flex-direction: column; justify-content: flex-start; align-items: center; ul { list-style-type: none; li { h4 { margin-top: 5px; margin-bottom: 30px; } a { text-decoration: none; color: #ffffff; &:hover { text-decoration: underline; } } } } .iconosFoot { img { @include acomodoIconosFoot; } } } /* Transformacion que agranda las imagens de los productos */ .animacion img:hover { transform: scale(1.1, 1.1); } /*------------------------------- PRODUCTOS -------------------------------*/ /* Disposicion de los productos */ .filtrosProductos { display: flex; flex-direction: row; } /* Hover para la navegacion de los productos */ .imgProductos .card:hover { transform: scale(1.05, 1.05); img { opacity: .8; } } /*------------------------------- CONTACTO -------------------------------*/ /* Distribucion de espacios entre el texto, mapa y el formulario */ .paginaContacto { display: grid; grid-template-columns: 50% 50%; justify-items: center; div { p { text-align: start; } .mapa { position: relative; width: 100%; overflow: hidden; padding-top: 75%; .mapa_responsive { position: absolute; top: 0; left: 0; bottom: 0; right: 0; width: 100%; height: 100%; border: none; } } } form { width: 80%; } } /* DESKTOP */ @media (min-width: 1024px) { /* Display del nav */ .navegacion { display: grid; grid-template-areas: "casa none busqueda" "casa enlaces enlaces"; grid-template-rows: auto auto; grid-template-columns: 15% 60% 25%; } /* Disposicion del Footer con Grids */ footer { display: grid; grid-template-areas: "info contacto" "derechos derechos"; grid-template-rows: auto auto; grid-template-columns: 1fr 1fr; .copyright { text-align: center; } } } /* TABLET */ @media (min-width: 481px) and (max-width: 1023px){ /* Grid del Nav en Tablet */ .navegacion { display: grid; grid-template-areas: "casa enlaces enlaces"; grid-template-rows: auto; grid-template-columns: 15% 60% 25%; /* Acomoda el icono del home */ .homeNav { display: flex; flex-direction: column; justify-content: center; } /* Disposicion del Nav */ .enlacesNav { background-color: $colorheader; list-style-type: none; display: flex; flex-direction: row; justify-content: space-evenly; align-items: center; } /* Oculta la barra de busqueda */ .search { display: none; } } /* Disposicion del Footer con Grids */ footer { display: grid; grid-template-areas: "info contacto" "derechos derechos"; grid-template-rows: auto auto; grid-template-columns: repeat(2, 1fr); .copyright { text-align: center; } } /* Acomoda los filtros de los productos en columna */ .filtrosProductos { display: flex; flex-direction: column; } /* Acomoda la pagina de contacto en una columna */ .paginaContacto { display: grid; grid-template-columns: 1fr; } } /* SMARTPHONE */ @media (max-width: 480px){ /* Grid del Nav en Phone */ .navegacion { display: grid; grid-template-areas: "casa" "enlaces"; grid-template-rows: auto auto; grid-template-columns: 100%; /* Oculta la barra de busqueda */ .search { display: none; } } /* Disposicion del Footer con Grids */ footer { display: grid; grid-template-areas: "info" "contacto" "derechos"; grid-template-rows: auto auto; grid-template-columns: 1fr; .copyright { text-align: center; } } /* Acomoda los filtros de los productos en columna */ .filtrosProductos { display: flex; flex-direction: column; } /* Acomoda la pagina de contacto en una columna */ .paginaContacto { display: grid; grid-template-columns: 1fr; } }
interface Array<T> { asyncForEach<U>( callback: (e: T, i: number, arr: T[]) => Promise<U>, ): Promise<void> asyncMap<U>( callback: (e: T, i: number, arr: T[]) => Promise<U>, ): Promise<U[]> isEmpty(): boolean isNotEmpty(): boolean } Array.prototype.asyncForEach = async function (callback) { await Promise.all(this.map(callback)) } Array.prototype.asyncMap = async function (callback) { return await Promise.all(this.map(callback)) } Array.prototype.isNotEmpty = function (): boolean { return this.length !== 0 } Array.prototype.isEmpty = function (): boolean { return this.length === 0 }
import React, { useEffect } from 'react'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import { ProtectedRoute } from '../protected-route'; import { LoginPage } from '../../pages/login/login'; import { HomePage } from '../../pages/home/home'; import { getContacts } from '../../services/actions/app'; import { useAppDispatch } from '../../services/types/types'; import 'normalize.css'; import './app.scss'; export const App = () => { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const dispatch = useAppDispatch(); useEffect(() => { dispatch(getContacts()); }, [dispatch]); return ( <Router basename={process.env.PUBLIC_URL}> <React.StrictMode> <Switch> <ProtectedRoute path="/" exact> <HomePage /> </ProtectedRoute> <Route path="/login" exact> <LoginPage /> </Route> <Route> <LoginPage /> </Route> </Switch> </React.StrictMode> </Router> ); };
/* This sketch multiplexes two RTCM serial sources into one. * On ESP32,the sources are Radio (Serial2) and Bluetooth SPP. * * The ESP32 vesion defaults to passing Radio (Serial2) through * to GPS (Serial1) unless data is received on Bluetooth Serial. * In that case, only bluetooth data is passed to GPS (Serial1). * After a timeout of no data received, it switches back to * Radio (Serial2). * * Speed is usually set to 57600 because that's what I'm using * on the Trimble receivers and the radio network. * * Using pins 16 & 17 for the GPS uart (F9P uart2 or Trimble Port * C). Pins 21 & 22 connect to the radio modem's uart. * Pin 5 is a button/switch to enable pass-through mode for * connecting XCTU to the Digi receiver via the RS232 port. */ #include <BluetoothSerial.h> BluetoothSerial SerialBT; HardwareSerial GPS(1); HardwareSerial Radio(2); unsigned long last_bt_time; bool use_bluetooth; #define BT_TIMEOUT 3000 //3 seconds #define RADIO_RX 21 #define RADIO_TX 22 #define GPS_RX 16 #define GPS_TX 17 #define PASSTHRU_PIN 5 #define TRAFFIC_LED 4 #define RADIO_SPEED 57600 #define GPS_SPEED 57600 #define BLUETOOTH_NAME "Tractor RTK" /* Set serial_wait create a delay (in milliseconds) before data is passed through to the serial port, in order to wait for the monitor to boot up. Set to 0 if not needed. */ unsigned long serial_wait=0; //ms delay before relaying data void setup() { unsigned long start_time; Serial.begin(115200); Radio.begin(RADIO_SPEED,SERIAL_8N1,RADIO_RX,RADIO_TX); //radio GPS.begin(GPS_SPEED,SERIAL_8N1,GPS_RX,GPS_TX); //F9P or Trimble SerialBT.begin(BLUETOOTH_NAME); //hard code name Serial.println(); Serial.println("RTCM switcher."); use_bluetooth = false; last_bt_time = millis(); pinMode(TRAFFIC_LED, OUTPUT); pinMode(PASSTHRU_PIN, INPUT_PULLUP); if (serial_wait > 0) { start_time = millis(); while ( (millis() - start_time) < serial_wait) { //consume the bytes so buffers don't overflow if (Radio.available()) Radio.read(); if (SerialBT.available()) SerialBT.read(); } } } void loop() { uint8_t c; bool pass_through = false; while(1) { if (!digitalRead(PASSTHRU_PIN)) { if (!pass_through) { Serial.println("switching to pass through"); } pass_through = true; use_bluetooth = false; } else { if (pass_through) { Serial.println("back to normal mode."); } pass_through = false; } if (Radio.available()) { c = Radio.read(); if (pass_through || !use_bluetooth) { digitalWrite(TRAFFIC_LED,HIGH); GPS.write(c); } } else if (!use_bluetooth) { digitalWrite(TRAFFIC_LED,LOW); } if (GPS.available()) { //pass GGA data onto bluetooth for VRS NTRIP c = GPS.read(); if (pass_through) { Radio.write(c); } else { SerialBT.write(c); } } if (SerialBT.available()) { //Bluetooth data available, switch to bluetooth c = SerialBT.read(); //if (!use_bluetooth) { // Serial.println ("Switching to Bluetooth."); //} if (!pass_through) { use_bluetooth = true; last_bt_time = millis(); GPS.write(c); digitalWrite(TRAFFIC_LED,HIGH); } } else { if ((millis() - last_bt_time) > BT_TIMEOUT) { //haven't seen any bt data in a while //switch back to radio. //if (use_bluetooth) { // Serial.println("Switching back to radio."); //} use_bluetooth = false; } if (use_bluetooth) { digitalWrite(TRAFFIC_LED,LOW); } } } }
## Docker Containers: ### Básicos: - **docker container –help**: Muestra ayuda para comandos relacionados con contenedores. - **docker container ls -a**: Lista todos los contenedores, incluidos los detenidos. - **docker ps**: Muestra contenedores en ejecución. Similar a `docker container ls` pero solo para los que están corriendo. - **docker container start**: Inicia un contenedor detenido. ### Ejecución y Configuración: - **docker container run -d**: Ejecuta un contenedor en modo 'detached' (en segundo plano). - **docker container run -dp 1080:80 docker/getting-started**: Ejecuta en segundo plano, mapea puerto 1080 del host al 80 del contenedor y utiliza la imagen `docker/getting-started`. - **docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres**: Ejecuta contenedor con nombre "some-postgres", establece variable de entorno para contraseña y utiliza imagen "postgres". ### Gestión: - **docker container rm ID o shortcutID o nombre**: Elimina un contenedor específico. - **docker container prune**: Elimina todos los contenedores detenidos. ## Docker Imágenes: - **docker image ls**: Lista todas las imágenes disponibles localmente. - **docker image rm 92034fe9a41f**: Elimina la imagen con ID `92034fe9a41f`. ### Repositorios: - **Imágenes de docker → docker hub**: Referencia al Docker Hub, repositorio en línea para encontrar, compartir y gestionar imágenes. ### Comandos específicos: ```bash docker container run \ --name world-db \ --env MARIADB_USER=psych \ --env MARIADB_PASSWORD=mypassword \ --env MARIADB_ROOT_PASSWORD=mypassword \ --env MARIADB_DATABASE=world-db \ --volume world-db:/var/lib/mysql \ -dp 4306:3306 \ --network world-app \ mariadb:jammy ``` ```bash docker container run \ --name phpmyadmin \ -d \ -e PMA_ARBITRARY=1 \ -p 8090:80 \ --network world-app \ phpmyadmin:5.2.0 ``` ```bash docker container run \ --name nest-app \ -w /app \ -dp 90:3000 \ -v "$(pwd)":/app \ node:16-alpine3.16 \ sh -c "yarn install && yarn start:dev" ``` - **docker logs -f fa1**: Sigue los logs en tiempo real del contenedor con ID `fa1`. ##Docker Compose ```bash version: '3' services: db: container_name: pokemon_db image: mongo:6.0 volumes: - poke-vol:/data/db ports: - 27017:27017 retart: always volumes: poke-vol: external: true ``` ```bash version: '3' services: db: container_name: ${MONGO_DB_NAME} image: mongo:6.0 volumes: - poke-vol:/data/db #ports: #- 27017:27017 restart: always environment: MONGO_INITDB_ROOT_USERNAME: ${MONGO_USERNAME} MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD} command: ['--auth'] mongo-express: depends_on: - db image: mongo-express:1.0.0-alpha.4 environment: ME_CONFIG_MONGODB_ADMINUSERNAME: ${MONGO_USERNAME} ME_CONFIG_MONGODB_ADMINPASSWORD: ${MONGO_PASSWORD} ME_CONFIG_MONGODB_SERVER: ${MONGO_DB_NAME} ports: - 9090:8081 restart: always volumes: poke-vol: external: false ``` ``` bash docker buildx create --name mybuilder --driver docker-container --bootstrap docker buildx use mybuilder docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7,linux/arm64/v8 \ -t psych30/cron-ticker:latest --push . docker buildx imagetools inspect psych30/cron-ticker:latest```
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title>Title</title> <style> canvas{ background-color: #ccc; } </style> <script> class ClockDrawer{ constructor(ctx,radius,x,y){ this.ctx = ctx; this.radius = radius; this.x = x; this.y = y; } drawClockwise(cx,cy,l,w,pos,fillColor,strokeColor){ this.ctx.save(); this.ctx.fillStyle = fillColor; this.ctx.strokeStyle = strokeColor; let angle = pos/30*Math.PI;//pos*6/180*PI angle-=Math.PI/2; let startAngle = angle-Math.PI/2; let endAngle = angle+Math.PI/2; this.ctx.beginPath(); this.ctx.arc(cx,cy,w/2,startAngle,endAngle,true); let y0 = cy + l*Math.cos(Math.PI/2-angle); let x0 = cx + l*Math.sin(Math.PI/2-angle); this.ctx.lineTo(x0,y0); this.ctx.closePath(); this.ctx.stroke(); this.ctx.fill(); this.ctx.restore(); } drawSeconds(sec){ sec = sec===0 ? 60 : sec; let radius = 0.9*this.radius; let start = -Math.PI/2; let end = -Math.PI/2 + sec/30*Math.PI; this.ctx.save(); this.ctx.lineWidth = 0.05*this.radius; this.ctx.beginPath(); this.ctx.arc(this.x,this.y,radius,start,end); this.ctx.stroke(); this.ctx.restore(); } drawCircle(){ this.ctx.save(); this.ctx.strokeStyle="red"; this.ctx.beginPath(); this.ctx.arc(this.x,this.y,this.radius*0.4,0,2*Math.PI); this.ctx.stroke(); this.ctx.restore(); } drawTime(){ let date = new Date(); let second = date.getSeconds(); let minute = date.getMinutes(); let hour = date.getHours(); this.drawClockwise(this.x,this.y,this.radius/2,this.radius/20,(hour%12)*5,"red","black"); this.drawClockwise(this.x,this.y,this.radius*0.8,this.radius/20,minute,"black","black"); this.drawSeconds(second); } draw(){ this.drawCircle(); this.drawTime() } } window.addEventListener("load",function () { let canvas = document.getElementById("cvs"); let ctx = canvas.getContext("2d"); let clockDriver = new ClockDrawer(ctx,150,160,160); setInterval(function () { ctx.clearRect(0,0,canvas.width,canvas.height); clockDriver.draw() },500); }) </script> </head> <body> <canvas width="820" height="320" id="cvs" style="border: 1px solid black">Your browser is old</canvas> </body> </html>
import React from 'react'; import { render } from '@testing-library/react'; import Pagination from '@/components/Pagination'; describe('Pagination component', () => { it('check if correct page is selected', () => { const props = { totalPages: 10, currentPage: 1, disabled: false, handleChange: jest.fn() } const { getAllByTestId } = render(<Pagination {...props} />); const options = getAllByTestId('page-option') const selectedOption = options.find(option => option.selected); expect(selectedOption.innerHTML).toBe('1'); }); it('check if all pages are listed', () => { const props = { totalPages: 10, currentPage: 1, disabled: false, handleChange: jest.fn() } const { getByText } = render(<Pagination {...props} />); for (let i = 1; i <= props.totalPages; i++) { expect(getByText(i).innerHTML).toBe(`${i}`); } }); it('check if select is disabled', () => { const props = { totalPages: 10, currentPage: 1, disabled: true, handleChange: jest.fn() } const { getByTestId } = render(<Pagination {...props} />); const select = getByTestId('page-selector'); expect(select.disabled).toBe(true); }); });
width = 720 height = 720 outerRadius = Math.min(width, height) / 2 - 10 innerRadius = outerRadius - 24 formatPercent = d3.format(".1%") arc = d3.svg.arc() .innerRadius(innerRadius) .outerRadius(outerRadius) layout = d3.layout.chord() .padding(.10) .sortSubgroups(d3.descending) .sortChords(d3.ascending) path = d3.svg.chord() .radius(innerRadius) svg = d3.select("#content").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("id", "circle") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")") svg.append("circle") .attr("r", outerRadius) colors = d3.scale.category20() d3.json "/api/tag/#{window.hashtag}", (data) -> data.data = data.data.map (obj) -> newObj = obj newObj.color = colors(newObj.name) newObj console.log data window.spinner.stop() document.getElementById("spin").style.display = "none" document.getElementById("content").style.display = "block" layout.matrix(data.matrix) mouseover = (d, i) -> chord.classed "fade", (p) -> p.source.index != i && p.target.index != i group = svg.selectAll(".group") .data(layout.groups) .enter().append("g") .attr("class", "group") .on("mouseover", mouseover) group.append("title").text (d, i) -> data.data[i].name groupPath = group.append("path") .attr("id", (d, i) -> "group" + i) .attr("d", arc) .style("fill", (d,i) -> data.data[i].color) groupText = group.append("text") .attr("x", 4) .attr("dy", 15) .attr("fill", "white") .attr("stroke-width", 10) groupText.append("textPath") .attr("xlink:href", (d,i) -> "#group" + i) .text((d, i) -> data.data[i].name) groupText.filter((d, i) -> groupPath[0][i].getTotalLength() / 2 - 25 < this.getComputedTextLength() ) .remove() chord = svg.selectAll(".chord") .data(layout.chords) .enter().append("path") .attr("class", "chord") .style("fill", (d) -> data.data[d.source.index].color) .attr("d", path)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ssm.mybatis.mapper.StuddMapper"> <!--开启二级缓存--> <!-- 在mapper配置文件中添加的cache标签可以设置一些属性: ①eviction属性:缓存回收策略,默认的是 LRU。 LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。 FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。 SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。 WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。 ②flushInterval属性:刷新间隔,单位毫秒 默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新 ③size属性:引用数目,正整数 代表缓存最多可以存储多少个对象,太大容易导致内存溢出 ④readOnly属性:只读, true/false true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了 很重 要的性能优势。 false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是 false。 --> <cache type="org.mybatis.caches.ehcache.EhcacheCache"/> <resultMap id="getStudd" type="Studd"> <id column="s_id" property="sId"/> <result column="s_name" property="sName"/> <result column="s_age" property="sAge"/> </resultMap> <!-- collection 集合名称 item 变量名称 separator 分隔符 --> <insert id="addBatch"> insert into studd values <foreach collection="studd" item="item" separator="," > (null,#{item.sName},#{item.sAge}) </foreach> </insert> <!-- collection 集合名称 item 变量名称 separator 分隔符 open 左边包含 close 右边包含 --> <delete id="delBatch"> delete from studd where s_id in <foreach collection="ids" item="item" separator="," open="(" close=")"> #{item} </foreach> </delete> <!-- if标签可通过test属性的表达式进行判断, 若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行 sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入 --> <sql id="StuddColumn"> s_id,s_name,s_age </sql> <select id="getStudd" resultType="com.ssm.mybatis.entity.Studd"> select <include refid="StuddColumn"/> from Studd where 1=1 <if test="sName != null and sName != ''"> and s_name = #{sName} </if> <if test="sAge != null and sAge !='' "> and s_age = #{sAge} </if> </select> <!-- where和if一般结合使用: a>若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字 b>若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的 and去掉 注意:where标签不能去掉条件最后多余的and --> <select id="getStuddTwo" resultType="com.ssm.mybatis.entity.Studd"> select * from Studd <where> <if test="sName != null and sName != ''"> and s_name = #{sName} </if> <if test="sAge != null and sAge !='' "> and s_age = #{sAge} </if> </where> </select> <!-- prefix:在trim标签中的内容的前面添加某些内容 prefixOverrides:在trim标签中的内容的前面去掉某些内容 suffix:在trim标签中的内容的后面添加某些内容 suffixOverrides:在trim标签中的内容的后面去掉某些内容 --> <select id="getStuddThree" resultType="com.ssm.mybatis.entity.Studd"> select * from Studd <trim prefix="where" suffixOverrides="and"> <if test="sName != null and sName != ''"> s_name = #{sName} and </if> <if test="sAge != null and sAge !='' "> s_age = #{sAge} </if> </trim> </select> <!-- choose、when、 otherwise相当于if...else if..else --> <select id="getStuddFour" resultType="com.ssm.mybatis.entity.Studd"> select * from Studd <where> <choose> <when test="sName != null and sName != ''"> and s_name = #{sName} </when> <when test="sAge != null and sAge !='' "> and s_age = #{sAge} </when> </choose> </where> </select> </mapper>
//https://app.pluralsight.com/course-player?clipId=f3a37c01-7a23-4d70-b569-746e31445183 import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, of, throwError } from 'rxjs'; import { catchError, tap, map, shareReplay } from 'rxjs/operators'; import { Product } from '@model/product'; import { ProductCategoryService } from '../product-categories/product-category.service'; import { ProductCategory } from '../product-categories/product-category'; @Injectable({ providedIn: 'root', }) export class ProductService { private productsUrl = 'api/products'; constructor(private http: HttpClient) {} getProducts(): Observable<Product[]> { return this.http.get<Product[]>(this.productsUrl).pipe( shareReplay(1), tap((products) => console.log(JSON.stringify(products))), catchError(this.handleError) ); } getProduct(id: number): Observable<Product> { if (id === 0) { return of(this.initializeProduct()); } const url = `${this.productsUrl}/${id}`; return this.http.get<Product>(url).pipe( tap((data) => console.log('getProduct: ' + JSON.stringify(data))), catchError(this.handleError) ); } createProduct(product: Product): Observable<Product> { const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); product.id = null; return this.http.post<Product>(this.productsUrl, product, { headers }).pipe( tap((data) => console.log('createProduct: ' + JSON.stringify(data))), catchError(this.handleError) ); } deleteProduct(id: number): Observable<{}> { const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); const url = `${this.productsUrl}/${id}`; return this.http.delete<Product>(url, { headers }).pipe( tap((data) => console.log('deleteProduct: ' + id)), catchError(this.handleError) ); } updateProduct(product: Product): Observable<Product> { const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); const url = `${this.productsUrl}/${product.id}`; return this.http.put<Product>(url, product, { headers }).pipe( tap(() => console.log('updateProduct: ' + product.id)), // Return the product on an update map(() => product), catchError(this.handleError) ); } private handleError(err: any): Observable<never> { // in a real world app, we may send the server to some remote logging infrastructure // instead of just logging it to the console let errorMessage: string; if (err.error instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. errorMessage = `An error occurred: ${err.error.message}`; } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, errorMessage = `Backend returned code ${err.status}: ${err.message}`; } console.error(errorMessage); return throwError(errorMessage); } private initializeProduct(): Product { // Return an initialized object return { id: 0, productName: null, productCode: null, category: null, tags: [], releaseDate: null, price: null, description: null, starRating: null, imageUrl: null, }; } }
--- title: "\"[Updated] Step-by-Step Looping iPhones Videos Effortlessly\"" date: 2024-06-05T10:57:44.417Z updated: 2024-06-06T10:57:44.417Z tags: - ai video - ai youtube categories: - ai - youtube description: "\"This Article Describes [Updated] Step-by-Step: Looping iPhones Videos Effortlessly\"" excerpt: "\"This Article Describes [Updated] Step-by-Step: Looping iPhones Videos Effortlessly\"" keywords: "IPhone Video Looping,IOS Loop Tricks,Smooth iPhone Video Playback,IPhone Loop Guide,Quick iPhone Video Loop,Easy Phone Video Loop,Seamless iPhone Video Repeat" thumbnail: https://thmb.techidaily.com/0d94a1daa7c27cd73a9d8298e21e0d777d1adaffd7b41de949895538a87e46dd.jpg --- ## Step-by-Step: Looping iPhones Videos Effortlessly # How to Loop A Video on iPhone? ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) ##### Shanoon Cox Mar 27, 2024• Proven solutions [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) ![Filmora secure download](https://images.wondershare.com/filmora/images/store/secure.png) Secure Download [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later ![Filmora secure download](https://images.wondershare.com/filmora/images/store/secure.png) Secure Download [Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/) or Try Filmora App for mobile >>> [download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) Nowadays, we can see a trend of people posting looping videos on their social media. These looping videos are fascinating and fun to watch. A loop is a popular element in photography and especially music videos, the idea being that the camera appears to magically repeat itself as many times as there are photos or frames showing the action. They can also simply recur a sequence a certain number of times, then stop. Now some people don’t know how to make looping videos, so in this article, we are going to discuss **how to loop a video on iPhone videos** and also how to loop YouTube videos on iPhone. Let's get started. * [Part 1: Convert iPhone Live Photos to a Loop Video](#part1) * [Part 2: Repeat Slideshow Video to Loop on iPhone](#part2) * [Part 3: Loop YouTube Videos On iPhone](#part3) * [Part 4: Best Apps to Loop Videos on iPhone and iPad](#part4) * [Part 5: Better Way to Loop and Create Boomerang Videos in Filmora Video Editor](#part5) * [Part 6: Frequently Asked Questions About Choosing Best Free Video Editor for Windows](#part7) ## Part 1: How to Convert iPhone Live Photos to a Loop Video A loop video is a short video that plays in repeat/ indefinitely. Loop videos can be created with features on social media apps and third-party apps. iPhone has a setting that allows you to edit the photos to loop or bounce videos, and it only works with a photo feature called 'live photo'. The live photo feature records 1.5 seconds moving picture when you click on the shutter button. The live photo feature can be edited to create a loop video, and you can do that by following these steps: 1. Before creating the video, you need to have the live picture saved on your phone. To do this, capture a live photo by opening your camera app. Then click on the live photo icon, which is located in the upper right corner. And tap on the shutter button. 1. Afterward, you locate the live photo you want to convert to a loop video by going to the Photos apps. Then click on _Albums > Media Types> Live photos._ ![iPhone Media types](https://images.wondershare.com/filmora/article-images/iphone-live-photos-media-types.jpg) 1. After locating and clicking on the live picture, you will see the _Live_ tab in the upper left corner. Click on the arrow down to view other options, including Loop, Bounce, and long exposure. ![iPhone live photos options](https://images.wondershare.com/filmora/article-images/iphone-live-photos-options.jpg) 1. Select the effect you want to create (loop) and save the file. The loop feature plays the video in a one-way order. So, to make it more interesting, you can select the bounce effect, which makes it play back and forth. 2. You can share the created loop video with the share icon at the lower-left corner. ![iPhone save live photos to loop](https://images.wondershare.com/filmora/article-images/iphone-live-photos-save-video.jpg) ## Part 2: Repeat Slideshow to Loop Video on iPhone for Free Slideshow videos are a very fun way to see your content. People gather around a screen to enjoy these beautiful memories of their life. Here is a step-by-step guide on how to loop a slideshow video on iPhone. 1. First, go to your gallery and select a video that you want to make a slideshow of. 2. Add that video to an album in your gallery under any name. 3. Pause the slideshow video, and you will see Options button at the bottom. Click it and then enable the Repeat option. ![iphone loop slideshow video](https://images.wondershare.com/filmora/article-images/iphone-slideshow-repeat-loop-effects.jpg) Now open that video from the album and start playing the video. That video will start playing in a loop until you make it stop. --- ## Part 3: How to Loop YouTube Videos On iPhone? Now coming to the part that we discussed in the intro, how to loop YouTube videos on iPhone. So here, we will show you a step-by-step guide on how to loop the videos on your iPhone. 1. Launch YouTube on your iPhone and log in to your account if you are not already logged in. 2. Now go to the "Search" option and lookup for the desired video that you want to loop, and add it to the playlist. There are two ways you can do that. Click and hold on to the video; a small menu will appear, then click on “Add to” to make a playlist. Start the video and then scroll down a bit and on the extreme right side, click on the "Add to" option, and then name the playlist. 3. After that, go back to the main menu and on the lower bottom right side of the screen, click on "Library," and then select the new playlist. 4. Start playing the video, and under the video, click on the drop-down button, and on the left side of the drop-down screen, there is a loop button, click on that, and it will start to play the loop infinitely. Check this ultimate guide to [looping YouTube videos](https://tools.techidaily.com/wondershare/filmora/download/) to get more ways. ## Part 4: Best Apps to Loop Videos on iPhone and iPad ### 1. [Loopideo - Loop Videos](https://apps.apple.com/us/app/loopideo-loop-videos/id798990531) ![Loopideo - Loop Videos](https://images.wondershare.com/filmora/article-images/loopideo-loop-videos-iphone.jpg) Loopideo is the app on our list that is an answer to **how to loop a video on iPhone**. It lets you import any video from your play that you want to play in a loop. This is a great tool when it comes to individual and organizational presentations. This powerful app can be very useful for you in many cases. ### 2. [Loop Video – GIF Maker](https://apps.apple.com/us/app/loop-videos-gif-maker/id1515299503) ![Loop Video – GIF Maker](https://images.wondershare.com/filmora/article-images/loop-videos-gif-maker.jpg) The second app on our list is Loop Video GIF Maker. It is very fun and easy to use the tool. It allows you to make the videos loop by turning them into GIFs. Loop Video GIF Maker allows you to import any video from your gallery into your app. You can then convert into a looping GIF. You can also choose the playback speed of the GIF after you can export it to the gallery or upload it to your social media directly from the app. ### 3. [Loopideo Pro](https://apps.apple.com/us/app/loopideo-pro-loop-videos/id1343372109) ![Loopideo Pro](https://images.wondershare.com/filmora/article-images/loopideo-pro-loop-videos.jpg) Loopideo Pro is a more feature-filled app on the App Store. Loopideo allows you to make the videos loop an unlimited amount of times. You can also choose the formats that you want to convert the looping video into. This app also gives you the option to choose the playback speed and then can also convert it into GIF speed so that you can save it in your gallery. ### 4. [iMovie](https://apps.apple.com/us/app/imovie/id377298193) iMovie is a more professional app that is available on the list. This app allows you to loop not only the video but also edit the video. This allows you to play the video in a loop for an unlimited amount of time in the built-in player, but when it comes to saving the looping video, it is not possible because you would need an unlimited amount of space to save that video. ### 5. [Looper](https://apps.apple.com/us/app/looper/id936806191) ![Looper video iphone](https://images.wondershare.com/filmora/article-images/looper-app-iphone.jpg) The last app on our list is a looper, and it is a very fun and easy-to-use app available on this list. Choose a video from your gallery, Local Videos, or iCloud Drive. Select the times you want the video to repeat and play. You can also export your video in reverse or in GIF format. **Bonus: Record a Looping Video with Boomerang app on iPhone** To make a looping video on your iPhone, you can either download the boomerang app or use the boomerang video on Instagram. If you are using the Boomerang app, take these steps to make a looping video: * Launch the Boomerang from Instagram app on your iPhone, if you haven’t installed it already, click on the search bar and type in _Boomerang_ in the App Store. * The welcome screen will appear, swipe left and tap on _Get started._ Allow it to access to your camera, location, and photos. After you are done setting up, you can make the videos. * To make a boomerang video, click and hold the shutter button. Hold the shutter for a few seconds and move the phone across the image or scene. * A preview of the looping video will appear; tap on Done to save the video. Or click on the X symbol to make a new video. * You can change the settings to record a selfie video by clicking on the curved arrows symbol. And you can also tap the lightning sign to put the flash on and off. To make the video with the Instagram Boomerang feature: * Open the Instagram app, and then swipe left as if to add a story. * Click on the boomerang icon (infinity symbol). Press and hold the shutter to make the video. * Preview the video, and you can add texts, songs, markups, and stickers to the video. * And then click on the arrow-down symbol to save/ download the video. You can share the video to close friends or your story. --- ## Part 5: What If You'd Like to Loop Videos on Computer? [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is one of the most popular video editors among video creators. It gives you high-quality end product, smooth slowing down & speeding up movements, voiceovers on top of music tracks and transitions between audio & video clips. But another amazing benefit of this [computer video editor](https://tools.techidaily.com/wondershare/filmora/download/) is that you can produce a loop video. ![Filmora logo](https://images.wondershare.com/filmora/logo_icon/wondershare-filmora-logo-horizontal.png) ![filmora product interface](https://images.wondershare.com/filmora/images/common/filmora-product-banner.png) ### The Best Video Looper on Windows and Mac * Loop and repeat videos multiple times * Copy and paste clips easily * Built-in plentiful templates and effects * Export to MP4, MOV, MKV, GIF and multiple formats [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) ![Filmora secure download](https://images.wondershare.com/filmora/images/store/secure.png) Secure Download [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later ![Filmora secure download](https://images.wondershare.com/filmora/images/store/secure.png) Secure Download [Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/) or Try Filmora App for mobile >>> [download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) In this part, I'm going to show you how to create looping video in Filmora video editor with the reverse effect. It's actually really easy and doesn't require any complicated steps. You'll be able to create a cool, looping video in no time! So, let's get started! **Step 1: Import Videos to Filmora video editor** Launch Filmora video editor on your Windows or Mac computer and then make a new project. Import videos as you can see it has been already imported all the media in the media library from your which you want to loop effect, and then drag the video clip to the timeline. ![import video to filmora](https://images.wondershare.com/filmora/article-images/import-video-to-loop-filmora.jpg) **Step 2: Copy and Paste the Video** After drag and drop the video to the timeline, make a copy of it (Ctrl+C). Go to the last frame and paste this video again. ![copy and paste the video](https://images.wondershare.com/filmora/article-images/copy-paste-clips-filmora.jpg) **Step 3: Enable Reverse Speed effect** Right click on the pasted video and go to Speed and Duration option in which custom speed dialog box where you can adjust the speed. In the Custom Speed dialog box you will find the speed, duration, reverse and ripple options. To make a video with loop effects, click the Reverse option to reverse the video play back from end to start frames automatically. Click OK to save the settings. ![reverse speed in Filmora](https://images.wondershare.com/filmora/article-images/reverse-speed-filmora.jpg) Now you have got a video with one looping count, if you want the video to loop several times, you can select these 2 clips and paste it based on your needs to get a continuous looping effect. ![again paste the similar video for continuous effect](<https://images.wondershare.com/filmora/article-images/again-paste-the> similar-video-for-continuous-effect.jpg) We hope you found this post helpful in learning how to create looping video with Filmora video editor. This makes them perfect for use as GIFs because they are never ending! What’s more, you can create a looping video in Filmora video editor by adding a sound that plays continuously. If you're looking to make an endlessly repeating animated image or video clip using just one still image, look no further than Filmora video editor. It's easy and fun to use. [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) ![Filmora secure download](https://images.wondershare.com/filmora/images/store/secure.png) Secure Download [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later ![Filmora secure download](https://images.wondershare.com/filmora/images/store/secure.png) Secure Download [Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/) or Try Filmora App for mobile >>> [download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) ## Part 6: Frequently Asked Question About Looping Videos on iPhone 1. **What is a looping video?** It means a video that repeats for a specific number of times or maybe an unlimited amount of times automatically. For example, a GIF. 1. **Can I loop videos an unlimited number of times?** Yes, it is possible to loop a video an unlimited amount of times. You can learn **how to loop a video on iPhone** by using the methods that we discussed above in the whole article. It is not possible to save the infinitely looping because it will take an infinite amount of memory. 1. **Does the view count if I play a YouTube video in a loop?** No, YouTube will not count repeated views if they all come over and over again from the same sources. This is to maintain the overall quality of YouTube and make it scam-free. [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) ![Filmora secure download](https://images.wondershare.com/filmora/images/store/secure.png) Secure Download [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later ![Filmora secure download](https://images.wondershare.com/filmora/images/store/secure.png) Secure Download [Click here to get Filmora for PC by email](https://tools.techidaily.com/wondershare/filmora/download/) or Try Filmora App for mobile >>> [download filmora app for ios](https://images.wondershare.com/filmorago/article-common/app_store.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) [download filmora app for android](https://images.wondershare.com/filmorago/article-common/google_play.svg) ](https://app.adjust.com/b0k9hf2%5F4bsu85t) ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://facebook-video-footage.techidaily.com/the-hidden-economics-of-youtube-content-production-for-2024/"><u>The Hidden Economics of YouTube Content Production for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-in-2024-ace-your-videos-essential-editors-for-youtube/"><u>[New] In 2024, Ace Your Videos Essential Editors for YouTube</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-captivate-and-enchant-explore-the-best-creative-reactions-on-yt-for-2024/"><u>[Updated] Captivate and Enchant Explore the Best Creative Reactions on YT for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-2024-approved-becoming-a-confident-content-creator-youtubes-top-tips/"><u>[Updated] 2024 Approved Becoming a Confident Content Creator YouTube's Top Tips</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-8-tips-on-how-to-vlog-confidently-like-popular-youtubers-for-2024/"><u>[Updated] 8 Tips on How to Vlog Confidently Like Popular YouTubers for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-in-2024-10-best-mobile-edits-youtube-shorts-clips-on-iosandroid/"><u>[Updated] In 2024, 10 Best Mobile Edits YouTube Shorts Clips on iOS/Android</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-in-2024-constructing-an-inviting-subscribe-link-for-youtube-enthusiasts/"><u>[New] In 2024, Constructing an Inviting Subscribe Link for YouTube Enthusiasts</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-laughter-labyr-writes-making-memorable-parodies/"><u>[New] Laughter Labyr Writes Making Memorable Parodies</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-2024-approved-budget-friendly-tactics-to-increase-your-youtube-video-impact/"><u>[Updated] 2024 Approved Budget-Friendly Tactics to Increase Your YouTube Video Impact</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-2024-approved-channel-boosting-strategies-effortless-sponsorship-securing-tips/"><u>[New] 2024 Approved Channel Boosting Strategies Effortless Sponsorship Securing Tips</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-tailoring-trending-topics-to-endings/"><u>[Updated] Tailoring Trending Topics to Endings</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/2024-approved-windows-movie-maker-tips-for-youtube-editing-excellence/"><u>2024 Approved Windows Movie Maker Tips for YouTube Editing Excellence</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-the-power-of-persuasion-hire-success-stories-1-10/"><u>[Updated] The Power of Persuasion Hire Success Stories #1-10</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-diving-deep-into-lyric-video-designs-powered-by-lyric-video-maker-for-2024/"><u>[Updated] Diving Deep Into Lyric Video Designs, Powered by Lyric Video Maker for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-crafting-engaging-content-with-google-trends-analytics-for-2024/"><u>[New] Crafting Engaging Content with Google Trends Analytics for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-in-2024-discover-8-youtube-thumbnail-generators-online/"><u>[Updated] In 2024, Discover 8 YouTube Thumbnail Generators Online</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/in-2024-youtube-dimensions-demystified-a-complete-aspect-ratio-handbook/"><u>In 2024, YouTube Dimensions Demystified A Complete Aspect Ratio Handbook</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-iconic-video-titles-youtubes-most-watched-lore/"><u>[Updated] Iconic Video Titles YouTube's Most-Watched Lore</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-a-step-by-step-manual-on-repetitive-watch-experiences-in-yt-for-2024/"><u>[New] A Step-by-Step Manual on Repetitive Watch Experiences in YT for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-in-2024-expert-advice-incorporating-narrative-elements-into-youtube-videos/"><u>[New] In 2024, Expert Advice Incorporating Narrative Elements Into YouTube Videos</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-2024-approved-elevate-your-content-top-rated-cameras-for-youtubers/"><u>[Updated] 2024 Approved Elevate Your Content Top-Rated Cameras for YouTubers</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-banner-brilliance-elevating-your-game-channel-image-for-2024/"><u>[Updated] Banner Brilliance Elevating Your Game Channel Image for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-a-comprehensive-guide-to-use-youtube-movie-maker/"><u>[New] A Comprehensive Guide to Use YouTube Movie Maker</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-final-thoughts-in-journalistic-styling/"><u>[Updated] Final Thoughts in Journalistic Styling</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-2024-approved-eye-catching-vlog-talk-points/"><u>[New] 2024 Approved Eye-Catching Vlog Talk Points</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/precision-in-sound-10-tips-for-professional-audio-quality-for-2024/"><u>Precision in Sound 10 Tips for Professional Audio Quality for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/say-goodbye-to-vertical-and-horizontal-bars-in-youtube-movies-for-2024/"><u>Say Goodbye to Vertical and Horizontal Bars in YouTube Movies for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-2024-approved-7-star-rated-apps-for-effortless-youtube-live-broadcast-from-iphone-and-android/"><u>[New] 2024 Approved 7 Star-Rated Apps for Effortless YouTube LIVE Broadcast From iPhone and Android</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-in-2024-engage-and-inspire-audiences-professional-level-tips-for-youtube-edits/"><u>[Updated] In 2024, Engage and Inspire Audiences Professional-Level Tips for YouTube Edits</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-compile-of-the-most-beautiful-wedding-videos-youtube-and-vimeo-edition-for-2024/"><u>[Updated] Compile of the Most Beautiful Wedding Videos - Youtube & Vimeo Edition for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/weaving-narrative-threads-into-trailers-for-2024/"><u>Weaving Narrative Threads Into Trailers for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-in-2024-11-free-youtube-playlist-downloaders-onlinepcandroidios/"><u>[Updated] In 2024, 11 FREE YouTube Playlist Downloaders [Online/PC/Android/iOS]</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-youtube-storytelling-made-simple-with-premiere-pro-tips/"><u>[New] YouTube Storytelling Made Simple - With Premiere Pro Tips</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-insiders-look-at-top-9-free-platforms-for-designing-youtube-logos/"><u>[New] Insider's Look at Top 9 FREE Platforms for Designing YouTube Logos</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-2024-approved-examining-how-youtube-curates-its-highlighted-discussion-threads/"><u>[Updated] 2024 Approved Examining How YouTube Curates Its Highlighted Discussion Threads</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-in-2024-expose-your-guide-to-finding-censored-youtube-clips/"><u>[Updated] In 2024, Exposé Your Guide to Finding Censored YouTube Clips</u></a></li> <li><a href="https://youtube-video-recordings.techidaily.com/in-2024-dive-into-digital-green-magic-top-4-youtube-sources-for-no-cost-background-workshops/"><u>In 2024, Dive Into Digital Green Magic Top 4 YouTube Sources for No-Cost Background Workshops</u></a></li> <li><a href="https://screen-recording.techidaily.com/new-securing-your-discord-sessions-with-ease/"><u>[New] Securing Your Discord Sessions with Ease</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/in-2024-additional-tips-about-sinnoh-stone-for-oppo-a1x-5g-drfone-by-drfone-virtual-android/"><u>In 2024, Additional Tips About Sinnoh Stone For Oppo A1x 5G | Dr.fone</u></a></li> <li><a href="https://some-approaches.techidaily.com/2024-approved-unveiling-the-secrets-to-making-spectacular-haul-videos/"><u>2024 Approved Unveiling the Secrets to Making Spectacular Haul Videos</u></a></li> <li><a href="https://some-skills.techidaily.com/in-2024-ultimate-strategy-for-professional-srt-production/"><u>In 2024, Ultimate Strategy for Professional SRT Production</u></a></li> <li><a href="https://tiktok-clips.techidaily.com/tiktok-masterclass-how-to-leverage-top-50-hashtags/"><u>TikTok Masterclass How to Leverage Top 50 Hashtags</u></a></li> <li><a href="https://sim-unlock.techidaily.com/in-2024-android-unlock-code-sim-unlock-your-honor-play-8t-phone-and-remove-locked-screen-by-drfone-android/"><u>In 2024, Android Unlock Code Sim Unlock Your Honor Play 8T Phone and Remove Locked Screen</u></a></li> <li><a href="https://bypass-frp.techidaily.com/is-gsm-flasher-adb-legit-full-review-to-bypass-your-samsung-galaxy-a05sfrp-lock-by-drfone-android/"><u>Is GSM Flasher ADB Legit? Full Review To Bypass Your Samsung Galaxy A05sFRP Lock</u></a></li> <li><a href="https://extra-approaches.techidaily.com/updated-perfect-whatsapp-ringtones-for-iphone-and-android-users/"><u>[Updated] Perfect WhatsApp Ringtones for iPhone & Android Users</u></a></li> <li><a href="https://youtube-clips.techidaily.com/does-quick-subscribe-strategy-boost-audience-growth-in-2024/"><u>Does Quick-Subscribe Strategy Boost Audience Growth, In 2024</u></a></li> <li><a href="https://extra-skills.techidaily.com/updated-masterclass-in-meme-template-selection/"><u>[Updated] Masterclass in Meme Template Selection</u></a></li> <li><a href="https://facebook-videos.techidaily.com/ultimate-fb-downloading-kit-best-for-ff-browser-users/"><u>Ultimate FB Downloading Kit - Best for FF Browser Users</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-2024-approved-create-engaging-videos-with-these-10-free-whiteboard-animation-tools/"><u>New 2024 Approved Create Engaging Videos with These 10 Free Whiteboard Animation Tools</u></a></li> <li><a href="https://screen-sharing-recording.techidaily.com/updated-converting-your-cellphone-to-a-diy-video-recorder-for-2024/"><u>[Updated] Converting Your Cellphone to a DIY Video Recorder for 2024</u></a></li> <li><a href="https://facebook-videos.techidaily.com/from-concept-to-completion-producing-a-viral-facebook-reel/"><u>From Concept to Completion Producing a Viral Facebook Reel</u></a></li> <li><a href="https://youtube-clips.techidaily.com/in-2024-efficient-tactics-for-viewing-subscribers-on-yt/"><u>In 2024, Efficient Tactics for Viewing Subscribers on YT</u></a></li> <li><a href="https://youtube-videos.techidaily.com/in-2024-a-comprehenensive-guide-to-youtube-studios-editing-features/"><u>In 2024, A Comprehenensive Guide to YouTube Studio's Editing Features</u></a></li> <li><a href="https://youtube-video-recordings.techidaily.com/in-2024-best-audio-modification-methods-for-youtube-stars/"><u>In 2024, Best Audio Modification Methods for YouTube Stars</u></a></li> <li><a href="https://phone-solutions.techidaily.com/does-xiaomi-redmi-note-13-pro-5g-has-native-hevc-support-by-aiseesoft-video-converter-play-hevc-video-on-android/"><u>Does Xiaomi Redmi Note 13 Pro 5G has native HEVC support?</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/new-easy-ways-to-translate-tiktok-videos-for-2024/"><u>New Easy Ways to Translate TikTok Videos for 2024</u></a></li> <li><a href="https://facebook-video-recording.techidaily.com/in-2024-can-your-tv-play-facebook-content-like-youtube-now/"><u>In 2024, Can Your TV Play Facebook Content Like YouTube Now?</u></a></li> <li><a href="https://smart-video-editing.techidaily.com/new-2024-approved-from-audio-to-video-what-you-need-to-know-about-mp3-to-mp4-conversion/"><u>New 2024 Approved From Audio to Video What You Need to Know About MP3 to MP4 Conversion</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-low-cost-superior-circular-lenses-for-photos-and-videos/"><u>[Updated] Low-Cost, Superior Circular Lenses for Photos & Videos</u></a></li> <li><a href="https://android-unlock.techidaily.com/6-proven-ways-to-unlock-oppo-a79-5g-phone-when-you-forget-the-password-by-drfone-android/"><u>6 Proven Ways to Unlock Oppo A79 5G Phone When You Forget the Password</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/2024-approved-unleash-the-chaos-10-essential-glitch-art-video-editing-apps-for-ios-and-android/"><u>2024 Approved Unleash the Chaos 10 Essential Glitch Art Video Editing Apps for iOS and Android</u></a></li> <li><a href="https://video-capture.techidaily.com/2024-approved-10-must-have-tech-gadgets-for-seamless-video-meetings/"><u>2024 Approved 10 Must-Have Tech Gadgets for Seamless Video Meetings</u></a></li> <li><a href="https://youtube-clips.techidaily.com/convert-youtube-music-seamlessly-for-mac-users-2023-edition-for-2024/"><u>Convert YouTube Music Seamlessly for Mac Users, 2023 Edition for 2024</u></a></li> <li><a href="https://instagram-clips.techidaily.com/in-2024-sail-through-social-media-instagrams-reel-mastery-secrets/"><u>In 2024, Sail Through Social Media Instagram's Reel Mastery Secrets</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-unlocking-iphone-6-plus-passcode-without-a-computer-drfone-by-drfone-ios/"><u>In 2024, Unlocking iPhone 6 Plus Passcode without a Computer | Dr.fone</u></a></li> <li><a href="https://facebook-clips.techidaily.com/new-in-2024-facebook-photosvideos-the-role-of-watermarks/"><u>[New] In 2024, Facebook Photos/Videos The Role of Watermarks</u></a></li> <li><a href="https://instagram-video-recordings.techidaily.com/in-2024-elevate-engagement-the-list-of-todays-hot-instagram-hashtags/"><u>In 2024, Elevate Engagement The List of Today's Hot Instagram Hashtags</u></a></li> <li><a href="https://location-fake.techidaily.com/a-detailed-vpna-fake-gps-location-free-review-on-oppo-a1-5g-drfone-by-drfone-virtual-android/"><u>A Detailed VPNa Fake GPS Location Free Review On Oppo A1 5G | Dr.fone</u></a></li> <li><a href="https://fake-location.techidaily.com/how-to-fake-gps-on-oppo-f23-5g-for-mobile-legends-drfone-by-drfone-virtual-android/"><u>How To Fake GPS On Oppo F23 5G For Mobile Legends? | Dr.fone</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-how-to-mirror-apple-iphone-15-pro-max-to-roku-drfone-by-drfone-ios/"><u>In 2024, How to Mirror Apple iPhone 15 Pro Max to Roku? | Dr.fone</u></a></li> <li><a href="https://ios-unlock.techidaily.com/in-2024-7-ways-to-lock-apps-on-iphone-8-plus-and-ipad-securely-by-drfone-ios/"><u>In 2024, 7 Ways to Lock Apps on iPhone 8 Plus and iPad Securely</u></a></li> </ul></div> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="generator" content="pandoc"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> <title>Recurrent Additive Network (RAN)</title> <style type="text/css">code{white-space: pre;}</style> <link rel="stylesheet" href="../resources/css/c.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript"></script> <!--[if lt IE 9]> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script> <![endif]--> </head> <body> <header class="page-header"> <a href='index.html'><img src="../resources/img/identicon.png" style="position:relative; top:0.4em; width:1.3em;border-radius:0.8em;" /> paper/</a> </header> <header> <h1 class="title">Recurrent Additive Network (RAN)</h1> </header> <ul> <li> original paper: <a href=http://www.kentonl.com/pub/llz.2017.pdf>http://www.kentonl.com/pub/llz.2017.pdf</a> </li> </ul> <div class="is-pulled-right"> <p><a class='tag is-blue' href=index.html#深層学習>深層学習</a></p> </div> <h2 id="概要">概要</h2> <p>LSTMよりもさらに単純化した再帰型ネットワークのための構造の提案. LSTM よりパラメータ数は 3/5 程度でありながら、タスクに依っては性能が上回る.</p> <h2 id="提案手法">提案手法</h2> <p>セルは状態 <span class="math inline">\(c_{t-1} \in \mathbb{R}^m\)</span> 一つを持つ. 入力 <span class="math inline">\(x_t\)</span> に対して次の手続きによって状態を <span class="math inline">\(c_t\)</span> に遷移し、<span class="math inline">\(h_t\)</span> を出力する.</p> <ul> <li><span class="math inline">\(\tilde{c} = W_0 x\)</span></li> <li><span class="math inline">\(i = \sigma(W_1 c_{t-1} + W_2 x_t)\)</span> (input)</li> <li><span class="math inline">\(f = \sigma(W_3 c_{t-1} + W_4 x_t)\)</span> (forget)</li> <li><span class="math inline">\(c_t = i \circ \tilde{c} + f \circ c_{t-1}\)</span> (要素ごとの積)</li> <li><span class="math inline">\(h_t = \tanh(c_t)\)</span> (output)</li> </ul> <p><span class="math inline">\(\tilde{c}\)</span> は content layer と呼ばれ主に入力の次元を内部状態の次元に揃えるためにあるが、 気にせず次元を揃えるならば <span class="math inline">\(\tilde{c} = x\)</span> としてしまっても良いそう.</p> <!-- HTML として pandoc -B で include する. <H2> を列挙してそれらにリンクを貼った toc を id='toc' に埋め込む. markdown で書いてるだろうから例として次のような段落を書けばよい. ``` ## INDEX <div id=toc></div> ``` used in - /memo/gnuplot - /memo/linux - /memo/imagemagick --> <script> (function() { var sections = document.getElementsByTagName('h2'); var i; var OL = document.createElement('ol'); for (i=0; i < sections.length; ++i) { var LI = document.createElement('li'); var A = document.createElement('a'); A.innerHTML = sections[i].innerHTML; if (A.innerHTML.toUpperCase() == 'INDEX') continue; A.href = '#' + i; LI.appendChild(A); OL.appendChild(LI); var PREF = document.createElement('a'); PREF.name = i; sections[i].appendChild(PREF); } var done = false; function work() { if (done) return; if ( document.getElementById('toc') === null) return; // no toc element document.getElementById('toc').appendChild(OL); done = true; }; window.onload = work; setTimeout(work,800); }()); </script> </body> </html>
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AdminLayoutComponent } from './layouts/admin-layout/admin-layout.component'; import { FrontLayoutComponent } from './layouts/front-layout/front-layout.component'; import { LayoutsModule } from './layouts/layouts.module'; import { UserLayoutComponent } from './layouts/user-layout/user-layout.component'; const routes: Routes = [ {path:"",component:FrontLayoutComponent}, {path:'admin',component:AdminLayoutComponent, children:[ {path:'dashboard',loadChildren:()=>import('./views/admin/dashbord/dashbord.module').then(m=>m.DashbordModule)}, {path:'reclamation',loadChildren:()=>import('./views/admin/reclamation/reclamation.module').then(m=>m.ReclamationModule)} ]}, {path:"user",component:UserLayoutComponent} ]; @NgModule({ imports: [ RouterModule.forRoot(routes), LayoutsModule ], exports: [RouterModule] }) export class AppRoutingModule { }
using System.Diagnostics; using FluentAssertions; namespace FootballWorldCupScoreboard.Tests; public class ScoreboardTests { public static IEnumerable<object[]> GetData(int count) { var dataset = new[] { ("Dinamo", "Arsenal"), ("Barcelona", "Madrid"), ("NYT", "CaliforniaBikers"), ("Juventus", "Real Madrid"), ("AJAX", "Portu") }; yield return new object[] { dataset }; } public static IEnumerable<object[]> GetData2(int count) { var dataset = new[] { ("Mexico", "Canada", 0, 5), ("Spain", "Brazil", 10, 2), ("Germany", "France", 2, 2), ("Uruguay", "Italy", 6, 6), ("Argentine", "Australia", 3, 1) }; yield return new object[] { dataset }; } [Fact] public void Finish_RemovesMatchFromMatchesProperty() { // Arrange var scoreboard = new Scoreboard(); var match = scoreboard.Start("TeamA", "TeamB"); // Act var matchFinished = scoreboard.Finish(match); // Assert Assert.True(matchFinished); Assert.DoesNotContain(match, scoreboard.Matches); } [Fact] public void Finish_Throw_WhenArgumentIsNull() { // Arrange var scoreboard = new Scoreboard(); // Act & Assert Assert.Throws<ArgumentNullException>(() => scoreboard.Finish(null)); } [Theory] [MemberData(nameof(GetData2), 5)] public void Get_ReturnsMatchesOrderedByTheirScore(IEnumerable<(string, string, int, int)> enumerable) { // Arrange var scoreboard = new Scoreboard(); var i = 0; var count = enumerable.Count(); foreach (var item in enumerable) { scoreboard.Start(item.Item1, item.Item2).UpdateScore((byte)(count - i), (byte)(count - i)); i++; } // Act var sorted = scoreboard.Get().ToList(); // Assert for (var j = 0; j < sorted.Count - 1; j++) Assert.True(sorted[j].TotalScore >= sorted[j + 1].TotalScore, "Matches are not ordered by their score in descending order."); } [Theory] [MemberData(nameof(GetData2), 5)] public void Get_ReturnsMatchesOrderedByTheirScore_ThanByTheirStartTime( IEnumerable<(string, string, int, int)> enumerable) { // Arrange var scoreboard = new Scoreboard(); var list = enumerable.ToList(); for (var i = 0; i < list.Count; i++) scoreboard.Start(list[i].Item1, list[i].Item2).UpdateScore((byte)list[i].Item3, (byte)list[i].Item4); // Act var sorted = scoreboard.Get().ToList(); // Assert var matches = scoreboard.Matches.ToArray(); Assert.Equal(list.Count, sorted.Count); for (var i = 0; i < sorted.Count - 1; i++) { Assert.True(sorted[i].TotalScore >= sorted[i + 1].TotalScore); if (sorted[i].TotalScore == sorted[i + 1].TotalScore) Assert.True(Array.IndexOf(matches, sorted[i]) > Array.IndexOf(matches, sorted[i + 1])); } } [Theory] [MemberData(nameof(GetData2), 5)] public void Get_ReturnsMatchesOrderedByTheirStartTimeDesc(IEnumerable<(string, string, int, int)> enumerable) { // Arrange var scoreboard = new Scoreboard(); foreach (var item in enumerable) scoreboard.Start(item.Item1, item.Item2); // Act var sorted = scoreboard.Get().ToList(); // Assert for (var i = 0; i < sorted.Count - 1; i++) Assert.True(Array.IndexOf(scoreboard.Matches.ToArray(), sorted[i]) > Array.IndexOf(scoreboard.Matches.ToArray(), sorted[i + 1])); } [Theory] [MemberData(nameof(GetData), 5)] public void Matches_PropertyShouldReturnAllStartedMatches(IEnumerable<(string, string)> enumerable) { // Arrange var scoreboard = new Scoreboard(); // Act foreach (var item in enumerable) scoreboard.Start(item.Item1, item.Item2); // Assert Assert.Equal(enumerable.Count(), scoreboard.Matches.Count); foreach (var valueTuple in enumerable) { var matchExists = scoreboard.Matches.Any(match => match.HomeTeam == valueTuple.Item1 && match.AwayTeam == valueTuple.Item2); Assert.True(matchExists, $"Match not found for teams: {valueTuple.Item1} vs {valueTuple.Item2}"); } } [Fact] public void Start_OnSuccess_ReturnsNewMatchWithInitScores() { // Arrange var scoreboard = new Scoreboard(); var match = new Match("Barcelona", "Madrid"); // Act var result = scoreboard.Start("Barcelona", "Madrid"); // Assert Assert.Equal(match.HomeTeam, result.HomeTeam); Assert.Equal(match.AwayTeam, result.AwayTeam); Assert.Equal(0, result.HomeTeamScore); Assert.Equal(0, result.AwayTeamScore); } [Fact] public void Start_OnSuccess_ReturnsNotNull() { // Arrange var scoreboard = new Scoreboard(); // Act var result = scoreboard.Start("Barcelona", "Madrid"); // Assert result.Should().NotBeNull(); } [Fact] public void Start_Throw_WhenTeamNamesIsNullOrEmpty() { // Arrange var scoreboard = new Scoreboard(); // Act & Assert Assert.Throws<ArgumentException>(() => scoreboard.Start(string.Empty, null)); Assert.Throws<ArgumentException>(() => scoreboard.Start("Barcelona", null)); Assert.Throws<ArgumentException>(() => scoreboard.Start(string.Empty, "Manchester")); } }
<?php //security check if (!defined('ABSPATH')) { exit('You must not access this file directly'); } /** * BiggiDroid Payment Gateway * * @author Adeleye Ayodeji * @since 1.0.0 */ class Biggi_Droid_Payment_Gateway extends WC_Payment_Gateway_CC { /** * Public key * * @var string */ public $public_key; /** * Secret key * * @var string */ public $secret_key; /** * Test mode * */ public $test_mode; /** * Title * */ public $title; /** * Description * */ public $description; /** * test_public_key * */ public $test_public_key; /** * test_secret_key * */ public $test_secret_key; /** * live_public_key * */ public $live_public_key; /** * live_secret_key * */ public $live_secret_key; /** * saved_cards * */ public $saved_cards; /** * Constructor * * @since 1.0.0 */ public function __construct() { //id $this->id = 'biggidroid_payment'; //has fields $this->has_fields = true; //method title $this->method_title = __('BiggiDroid Payment Gateway', BIGGIDROID_TEXT_DOMAIN); //description $this->method_description = __('This plugin allows you to accept payment on your website using BiggiDroid Payment Gateway.', BIGGIDROID_TEXT_DOMAIN); //supports $this->supports = array( 'products' // 'tokenization', // 'subscriptions', // 'subscription_cancellation', // 'subscription_suspension', // 'subscription_reactivation', // 'subscription_amount_changes', // 'subscription_date_changes', // 'subscription_payment_method_change', // 'subscription_payment_method_change_customer', // 'subscription_payment_method_change_admin', // 'multiple_subscriptions', ); //Add form fields $this->init_form_fields(); $this->title = $this->get_option('title'); $this->description = $this->get_option('description'); $this->enabled = $this->get_option('enabled'); //saved_cards $this->saved_cards = false; $this->test_mode = 'yes' === $this->get_option('test_mode') ? true : false; $this->test_public_key = $this->get_option('test_public_key'); $this->test_secret_key = $this->get_option('test_secret_key'); $this->live_public_key = $this->get_option('live_public_key'); $this->live_secret_key = $this->get_option('live_secret_key'); $this->public_key = $this->test_mode ? $this->test_public_key : $this->live_public_key; $this->secret_key = $this->test_mode ? $this->test_secret_key : $this->live_secret_key; //process admin options add_action('woocommerce_update_options_payment_gateways_' . $this->id, [$this, 'process_admin_options']); //admin script add_action('admin_enqueue_scripts', [$this, 'admin_scripts']); //woocommerce available payment gateways add_action('woocommerce_available_payment_gateways', [$this, 'available_payment_gateways']); } /** * Get Paystack payment icon URL. */ public function get_logo_url() { $url = WC_HTTPS::force_https_url(BIGGI_DROID_PAYMENT_PLUGIN_URL . '/assets/images/biggidroid_payment.png'); return apply_filters('woocommerce_biggidroid_payment_icon', $url, $this->id); } /** * available_payment_gateways * */ public function available_payment_gateways($available_gateways) { if (!$this->is_available()) { //unset the gateway unset($available_gateways[$this->id]); } return $available_gateways; } /** * is available * */ public function is_available() { return $this->enabled === 'yes'; } /** * Admin scripts * * @since 1.0.0 */ public function admin_scripts() { wp_enqueue_script('biggidroid-admin-script', BIGGI_DROID_PAYMENT_PLUGIN_URL . 'assets/js/admin.js', ['jquery'], BIGGI_DROID_PAYMENT_VERSION, true); } /** * Initialize form fields * * @since 1.0.0 */ public function init_form_fields() { $form_fields = apply_filters('woo_biggidroid_payment', [ 'enabled' => [ 'title' => __('Enable/Disable', BIGGIDROID_TEXT_DOMAIN), 'type' => 'checkbox', 'label' => __('Enable BiggiDroid Payment Gateway', BIGGIDROID_TEXT_DOMAIN), 'default' => 'no' ], //test mode select 'test_mode' => [ 'title' => __('Payment Mode', BIGGIDROID_TEXT_DOMAIN), 'type' => 'select', 'description' => __('Select the test mode', BIGGIDROID_TEXT_DOMAIN), 'options' => [ 'yes' => __('Test', BIGGIDROID_TEXT_DOMAIN), 'no' => __('Live', BIGGIDROID_TEXT_DOMAIN) ], 'default' => 'yes' ], 'title' => [ 'title' => __('Title', BIGGIDROID_TEXT_DOMAIN), 'type' => 'text', 'description' => __('This controls the title which the user sees during checkout.', BIGGIDROID_TEXT_DOMAIN), 'default' => __('BiggiDroid Payment Gateway', BIGGIDROID_TEXT_DOMAIN), 'desc_tip' => true ], 'description' => [ 'title' => __('Description', BIGGIDROID_TEXT_DOMAIN), 'type' => 'textarea', 'description' => __('This controls the description which the user sees during checkout.', BIGGIDROID_TEXT_DOMAIN), 'default' => __('Pay with your credit card via BiggiDroid Payment Gateway.', BIGGIDROID_TEXT_DOMAIN), 'desc_tip' => true ], 'live_public_key' => [ 'title' => __('Live Public Key', BIGGIDROID_TEXT_DOMAIN), 'type' => 'text', 'description' => __('This is the live public key provided by BiggiDroid Payment Gateway.', BIGGIDROID_TEXT_DOMAIN), 'default' => '', 'desc_tip' => true ], 'live_secret_key' => [ 'title' => __('Live Secret Key', BIGGIDROID_TEXT_DOMAIN), 'type' => 'text', 'description' => __('This is the live secret key provided by BiggiDroid Payment Gateway.', BIGGIDROID_TEXT_DOMAIN), 'default' => '', 'desc_tip' => true ], //test pk key 'test_public_key' => [ 'title' => __('Test Public Key', BIGGIDROID_TEXT_DOMAIN), 'type' => 'text', 'description' => __('This is the test public key provided by BiggiDroid Payment Gateway.', BIGGIDROID_TEXT_DOMAIN), 'default' => '', 'desc_tip' => true ], //test secret key 'test_secret_key' => [ 'title' => __('Test Secret Key', BIGGIDROID_TEXT_DOMAIN), 'type' => 'text', 'description' => __('This is the test secret key provided by BiggiDroid Payment Gateway.', BIGGIDROID_TEXT_DOMAIN), 'default' => '', 'desc_tip' => true ] ]); //return form fields to woocommerce $this->form_fields = $form_fields; } }
Now lets get back to processing the wikipedia dataset. In this part you will write your own mappers and reducers to perform the following tasks on the entire 1-month input dataset. Create an EMR Job Flow to: Filter out elements based on the rules discussed in the previous page Aggregate the pageviews from hourly views to daily views Calculate the total pageviews for each article For every article that has page-views over 100,000, print the following line as output: <total month views>\t<article name>\t <date1:page views for date1>\t <date2:page views for date2> ... Note: Print out the page views for all dates in a single line Getting the input filename from within a Mapper: As the date/time information is encoded in the filename, Hadoop streaming makes the filename available to every map task through the environment variables map_input_file or map.input.file. For example, the filename can be accessed in python using the statement os.environ["map_input_file"], or in Java using the statement System.getenv("map_input_file"). Note: If you are having trouble getting the filename, check the Hadoop version in EMR. If you are using the latest version, the environment variable will be mapreduce_map_input_file
package com.dflorez.assignment3.ViewModels; import android.app.Activity; import android.content.Context; import android.util.Log; import android.widget.ImageView; import android.widget.TextView; import androidx.core.content.ContextCompat; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.dflorez.assignment3.Models.GameClass; import com.dflorez.assignment3.R; import com.dflorez.assignment3.Views.Game; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import android.os.Handler; import android.os.Looper; public class GameViewModel extends ViewModel { //========== // Global //========== final Integer SCORE = 10; //========== // LiveData //========== private GameClass gameClass = new GameClass(); // GameClass instance private MutableLiveData<GameClass> GameData = new MutableLiveData<>(); // Holds the GameClass instance private MutableLiveData<String> PlayerNameData = new MutableLiveData<>(); private MutableLiveData<Integer> ScoreData = new MutableLiveData<>(); private MutableLiveData<Integer> RoundData = new MutableLiveData<>(); private MutableLiveData<Integer> SquaresToRememberData = new MutableLiveData<>(); //========== // Getter/Setters //========== public MutableLiveData<GameClass> getGameData() { return GameData; } public MutableLiveData<String> getPlayerName() { return PlayerNameData; } public void setPlayerName(String name) { PlayerNameData.setValue(name); gameClass.setPlayerName(name); // Update the GameClass instance attribute } public MutableLiveData<Integer> getScore() { return ScoreData; } public void setScore(Integer score) { ScoreData.setValue(score); gameClass.setScore(score); // Update the GameClass instance attribute } public MutableLiveData<Integer> getRound() { return RoundData; } public void setRound(Integer round) { RoundData.setValue(round); gameClass.setRound(round); // Update the GameClass instance attribute } public MutableLiveData<Integer> getSquaresToRemember() { return SquaresToRememberData; } public void setSquaresToRemember(Integer squares) { SquaresToRememberData.setValue(squares); gameClass.setSquaresToRemember(squares); // Update the GameClass instance attribute } //========== // Constructor //========== public GameViewModel() { setPlayerName(""); GameData.setValue(gameClass); // GameData.setValue(game); // Initialize GameData with a Game instance (empty game board) } // Methods public void playGame(Context context, ImageView[] imageViews, TextView countDownTV) { // Choose random tiles (ImageViews) int squaresToRemember = gameClass.getSquaresToRemember(); Random random = new Random(); List<String> activeTileIds = new ArrayList<>(); // Will hold the activeTiles. Used to check if the user clicked the correct ones Log.i("tag", "Play Game: After List"); // Pick X number of tiles (set by the difficulty) that need to be remember by the user. That means that they will change bg color (light up) while (activeTileIds.size() < squaresToRemember) { int randomIndex = random.nextInt(imageViews.length); String tileId = context.getResources().getResourceEntryName(imageViews[randomIndex].getId()); activeTileIds.add(tileId); } Log.i("tag", "Play Game: After While"); // Add the randomly selected tileIds to the GameClass instance gameClass.setActiveTiles(activeTileIds); Log.i("tag", "-----------------"); for (String t : activeTileIds) { Log.i("tag", "activeTileIds " + t); } Log.i("tag", "-----------------"); Log.i("tag", "Play Game: Add to instance ActiveTiles"); // Trying New Code - Ran out of time - Ran into issues trying to get the ImageView Id to change the BG // Change Tile bg color /* for (String tileId : activeTileIds) { Log.i("tag", "Play Game: For change BG Color - Start"); ImageView imageView = null; for (ImageView iv : imageViews) { if (iv.getTag() != null && iv.getTag().equals(tileId)) { imageView = iv; break; } } if (imageView != null) { imageView.setBackgroundColor(ContextCompat.getColor(context, R.color.tileOn)); Log.i("tag", "Play Game: For change BG Color - set BG"); Log.i("tag", "Stored randomly generated tiles"); Log.i("tag", tileId); } else { Log.e("tag", "ImageView not found for tile ID: " + tileId); } /* int resourceId = context.getResources().getIdentifier(tileId, "id", context.getPackageName()); Log.i("tag", "Play Game: For change BG Color - resourceId " + resourceId); Log.i("tag", "-----------------"); ImageView imageView = ((Activity) context).findViewById(resourceId); Log.i("tag", "Play Game: For change BG Color - imageView"); imageView.setBackgroundColor(ContextCompat.getColor(context, R.color.tileOn)); Log.i("tag", "Play Game: For change BG Color - set BG"); Log.i("tag", "Stored randomly generated tiles"); Log.i("tag", tileId); } */ // Old Code, working Set<Integer> chosenArrayIndices = new HashSet<>(); while (chosenArrayIndices.size() < squaresToRemember) { chosenArrayIndices.add(random.nextInt(imageViews.length)); } // Change tile color (Light up) // Old Code working for (int index : chosenArrayIndices) { imageViews[index].setBackgroundColor(ContextCompat.getColor(context, R.color.tileOn)); } // Runnable to show the tiles light up for 5 seconds and the countdown timer going down to from 5 to 0 seconds // Once its over, reset tiles back to the original color final int[] counter = {5}; // 5 seconds to play final Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(new Runnable() { @Override public void run() { // Checks if count has reached 0 "seconds" if (counter[0] >= 0) { countDownTV.setText(String.valueOf(counter[0])); counter[0]--; // Repeat every second handler.postDelayed(this, 1000); } else { // Go back to the original tile color after 5 seconds for (int index : chosenArrayIndices) { imageViews[index].setBackgroundColor(ContextCompat.getColor(context, R.color.tileOff)); // Part of the new code I was trying - Ran out of Time // for (String tileId : activeTileIds) { // int resourceId = context.getResources().getIdentifier(tileId, "id", context.getPackageName()); // ImageView imageView = ((Activity) context).findViewById(resourceId); // imageView.setBackgroundColor(ContextCompat.getColor(context, R.color.tileOff)); } // Reset countdown timer countDownTV.setText("5"); } } }, 1000); } }
// // FooterPoweredByDojo.swift // dojo-ios-sdk-drop-in-ui // // Created by Deniss Kaibagarovs on 18/08/2022. // import UIKit enum FooterPoweredByDojoStyle { static let `default`: [FooterPoweredByDojoItems] = [.poweredBy] static let checkoutPage: [FooterPoweredByDojoItems] = [.poweredBy, .terms, .privacy] } enum FooterPoweredByDojoItems { case poweredBy case privacy case terms } class FooterPoweredByDojo: UIView { @IBOutlet private var contentView: UIView! @IBOutlet weak var imageLogo: UIImageView! @IBOutlet weak var labelPoweredBy: UILabel! @IBOutlet weak var buttonPrivacy: UIButton! @IBOutlet weak var buttonTerms: UIButton! @IBOutlet weak var viewSeparator: UIView! @IBOutlet weak var stackViewRight: UIStackView! @IBOutlet weak var stackViewLeft: UIStackView! @IBOutlet weak var constraintPoweredByCenter: NSLayoutConstraint! @IBOutlet weak var constraintPoweredByTailing: NSLayoutConstraint! @IBOutlet weak var constraintButtonByCenter: NSLayoutConstraint! @IBOutlet weak var constraintButtonByLeft: NSLayoutConstraint! let viewModel = FooterPoweredByViewModel() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initSubviews() } override init(frame: CGRect) { super.init(frame: frame) initSubviews() } func setTheme(theme: ThemeSettings) { labelPoweredBy.textColor = theme.colorPoweredByDojo labelPoweredBy.font = theme.fontPoweredByDojo labelPoweredBy.setTextSpacingBy(value: 0.5) imageLogo.tintColor = theme.colorPoweredByDojo viewSeparator.backgroundColor = theme.colorPoweredBySeparator buttonTerms.tintColor = theme.colorPoweredByButtons buttonPrivacy.tintColor = theme.colorPoweredByButtons buttonTerms.titleLabel?.font = theme.fontSubtitle2 buttonPrivacy.titleLabel?.font = theme.fontSubtitle2 viewModel.showBranding = theme.showBranding } func setStyle(_ styleItems: [FooterPoweredByDojoItems] = FooterPoweredByDojoStyle.default) { labelPoweredBy.isHidden = true buttonTerms.isHidden = true buttonPrivacy.isHidden = true viewSeparator.isHidden = true stackViewRight.isHidden = true if styleItems.contains(where: {$0 == .poweredBy}) { labelPoweredBy.isHidden = false } if styleItems.contains(where: {$0 == .terms}) { buttonTerms.isHidden = false } if styleItems.contains(where: {$0 == .privacy}) { buttonPrivacy.isHidden = false } // if any of the text is visible - show separator let termsOrPrivacyIsVisible = (!buttonTerms.isHidden || !buttonPrivacy.isHidden) viewSeparator.isHidden = !termsOrPrivacyIsVisible stackViewRight.isHidden = !termsOrPrivacyIsVisible if termsOrPrivacyIsVisible { constraintPoweredByTailing.isActive = true constraintPoweredByCenter.isActive = false } else { constraintPoweredByTailing.isActive = false constraintPoweredByCenter.isActive = true } if !viewModel.showBranding { stackViewLeft.isHidden = true viewSeparator.isHidden = true constraintButtonByCenter.isActive = true constraintButtonByLeft.isActive = false } } func initSubviews() { let nib = UINib(nibName: String(describing: type(of: self)), bundle: Bundle.libResourceBundle) nib.instantiate(withOwner: self, options: nil) contentView.frame = bounds addSubview(contentView) // Additional setup setupTranslations() setStyle() } func setupTranslations() { labelPoweredBy.text = LocalizedText.PoweredBy.title buttonTerms.setTitle(LocalizedText.PoweredBy.terms, for: .normal) buttonPrivacy.setTitle(LocalizedText.PoweredBy.privacy, for: .normal) } @IBAction func onPrivacyButtonPress(_ sender: Any) { openURL(viewModel.privacyURL) } @IBAction func onTermsButtonPress(_ sender: Any) { openURL(viewModel.termsURL) } } extension FooterPoweredByDojo { func openURL(_ url: URL?) { if let url = url { UIApplication.shared.open(url) } } }
import React from "react"; import { Route, Routes } from "react-router-dom"; import { Home } from "./structure-examples/home"; import { RenderBased } from "./structure-examples/render-based"; import { PropsBased } from "./structure-examples/props-based"; import { HookBased } from "./structure-examples/hook-based"; import { HybridBased } from "./structure-examples/hybrid-based"; export default function App() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/render-based" element={<RenderBased />} /> <Route path="/props-based" element={<PropsBased />} /> <Route path="/hook-based" element={<HookBased />} /> <Route path="/hybrid-based" element={<HybridBased />} /> </Routes> ); }
function KanbasNavigation(location) { const links = [ { name: "Account", url: "/Kanbas/Account/Profile/screen.html", icon: "fa fa-user-circle", }, { name: "Dashboard", url: "/Kanbas/Dashboard/screen.html", icon: "fa fa-tachometer", }, { name: "Courses", url: "/Kanbas/Courses/Home/screen.html", icon: "fa fa-fax", }, { name: "Calendar", url: "#", icon: "fa fa-calendar", }, { name: "Inbox", url: "#", icon: "fa fa-inbox", }, { name: "History", url: "#", icon: "fa fa-history", }, { name: "Studio", url: "#", icon: "fa fa-toggle-right", }, { name: "Commons", url: "#", icon: "fa fa-share-square-o", }, { name: "Help", url: "#", icon: "fa fa-question-circle", }, ]; return ` <ul class="wd-kanbas-navigation"> <li> <a href="http://northeastern.edu"> <img src="https://imgur.com/TFsDSJy.jpg" alt="Northeastern University Logo"> </a> </li> ${links .map((link) => { return ` <li class="${link.name === location ? "wd-active" : ""}"> <a href="${link.url}"> ${ link.icon ? `<i class="${link.icon}" style=${ link.name === "Account" ? "color:white" : "" }></i><br/>` : "" } ${link.name}</a></li> `; }) .join("")} </ul> `; }
<template> <div class="container"> <div class="signup-content"> <form @submit.prevent="updateCategory" method='post' class="signup-form"> <h2 class="form-title" style="margin-bottom: 60px; margin-top: 20px">Update Category</h2> <div class="form-group position-relative"> <label for="nom">Category Name<span style="color: red;">*</span></label> <input autocomplete="off" ref="nameInput" :class="{ 'is-invalid': isNameInvalid && touched }" v-model="category.nom" type="text" class="form-control" name="nom" id="name" placeholder="Category Name"/> <div class="invalid-feedback" v-if="formErrors[0] !== null"> {{ formErrors[0] }} </div> </div> <div class="form-group position-relative"> <label for="description">Category Description<span style="color: red;">*</span></label> <textarea autocomplete="off" ref="descriptionInput" :class="{ 'is-invalid': isDescriptionInvalid && touched }" v-model="category.description" type="text" class="form-control" name="description" id="description" placeholder="Category Description"/> <div class="invalid-feedback" v-if="formErrors[1] !== null"> {{ formErrors[1] }} </div> </div> <div class="form-group"> <input type="submit" name="submit" id="submit" class="btn btn-warning send-button" value="Update Category"/> </div> </form> </div> </div> </template> <script> import CategoryService from "@/services/CategoryService"; export default { name: "UpdateCategory", data(){ return{ formErrors: [], touched: false, category: { nom: "", description: "" } } }, methods: { getCategory(){ CategoryService.getCategory(this.$route.params.id).then((res) => { console.log(res.data) this.category = res.data; }).catch(function (error){ console.log(error) }) }, updateCategory(){ const nameInput = this.$refs.nameInput; const descriptionInput = this.$refs.descriptionInput; this.formErrors = []; if (!this.category.nom) { this.formErrors.push("Category name can't be empty"); nameInput.classList.add('is-invalid'); } else { this.formErrors.push(""); nameInput.classList.remove('is-invalid'); } if (!this.category.description) { this.formErrors.push("Category description can't be empty"); descriptionInput.classList.add('is-invalid'); } else { this.formErrors.push(""); descriptionInput.classList.remove('is-invalid'); } this.touched = true; if (this.formErrors[0] === "" && this.formErrors[1] === "") { CategoryService.updateCategory(this.$route.params.id,{ nom: this.category.nom, description: this.category.description }) } else { console.log("Fill in all fields") } } }, computed: { isNameInvalid() { return !this.category.nom; }, isDescriptionInvalid() { return !this.category.description; } }, mounted() { this.getCategory() } } </script> <style scoped> .container { width: 660px; text-align: center; padding: 20px; } form { width: 500px; margin: 20px auto; } .form-group { margin-bottom: 20px; } input[type="text"]{ padding: 10px 15px; background-color: #efefef; border: 1px solid #ccc; width: 93%; border-radius: 5px; } input[type="text"].is-invalid, textarea.is-invalid{ background-color: #fdeeee; border-color: #ff4343; } .form-control { padding: 10px 15px; background-color: #efefef; border: 1px solid #ccc; border-radius: 5px; width: 100%; } label { display: block; margin-bottom: 15px; font-size: 18px; } textarea { height: 120px; resize: none; } .btn.send-button { display: block; height: 50px; border-color: transparent; padding: 5px 20px; width: 100%; font-size: 24px; } </style>
### 解题思路 1、使用hashmap 2、复制节点并插入当前节点后面,再设定好random指针,最后分离出原链表与副本链表 ### 代码 ```cpp class Solution { public: //方法1 Node* copyRandomList(Node* head) { if (head == nullptr) return head; //遍历原链表 创建新链表节点并建立映射关系 unordered_map<Node*, Node*> map; //key: 原链表节点 value: 新创建节点 Node* cur = head; while (cur) { map[cur] = new Node(cur->val); cur = cur->next; } //遍历原链表 根据map找新链表的random cur = head; while (cur) { map[cur]->next = map[cur->next]; map[cur]->random = map[cur->random]; cur = cur->next; } return map[head]; } //方法2 Node* copyRandomList(Node* head) { if (head == nullptr) return head; //遍历原链表 遍历过程中插入新副本节点 Node* cur = head; while (cur) { Node* node = new Node(cur->val); Node* next = cur->next; node->next = next; cur->next = node; cur = next; } //遍历原链表 对新副本节点设置random指针 cur = head; while (cur) { cur->next->random = cur->random ? cur->random->next : nullptr; cur = cur->next->next; } //分离出原链表与新副本链表 cur = head; Node* new_cur = head->next; Node* res = new_cur; while (cur) { cur->next = cur->next->next; cur = cur->next; new_cur->next = cur ? cur->next : nullptr; new_cur = new_cur->next; } return res; //注意:不能再返回head->next了,head已经是分离后的原链表 } }; ```
<div class="row my-3"> <div class="col-md-12"> <h5 class="mb-0">App Sec Testing</h5> </div> </div> <div class="row my-3 custom-gutters"> <div class="col-md-2"> <div class="epts"> <div class="input-group"> <select [(ngModel)]="searchApplication" class="form-control" name="searchApplication"> <option value="All">All</option> <option [value]="item" *ngFor="let item of applications">{{item}}</option> </select> </div> </div> </div> <div class="col-md-8"> <div class="epts"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search specific data like hostname, operating system, ip address, admin user, softwares, etc." aria-label="Recipient's username" aria-describedby="button-addon2" [(ngModel)]="searchCriteria"> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="button" id="button-addon2" style="padding: 0 8px; border-color: #ced4da;"> <mat-icon aria-hidden="false" aria-label="Example home icon" style="vertical-align: middle;"> search</mat-icon> </button> </div> </div> </div> </div> <div class="col-md-1"> <div class="epts"> <button mat-stroked-button [matMenuTriggerFor]="menu" aria-label="Example icon-button with a menu" matTooltip="Download" class="btn btn-dark btn-action"> <mat-icon style="margin-top: -1px;">cloud_download</mat-icon> </button> <mat-menu #menu="matMenu"> <button mat-menu-item (click)="download('PDF')"> <mat-icon class="pdf-icon">picture_as_pdf</mat-icon> <span>PDF</span> </button> <button mat-menu-item (click)="download('Excel')"> <mat-icon class="excel-icon">table_chart</mat-icon> <span>Excel</span> </button> <button mat-menu-item (click)="download('HTML')"> <mat-icon class="html-icon">code</mat-icon> <span>HTML</span> </button> </mat-menu> </div> </div> <div class="col-md-1"> <div class="epts"> <button mat-stroked-button [matMenuTriggerFor]="menuShare" aria-label="Example icon-button with a menu" matTooltip="Share" class="btn btn-dark btn-action"> <mat-icon style="margin-top: -1px;">share</mat-icon> </button> <mat-menu #menuShare="matMenu"> <button mat-menu-item (click)="openEmailDialog()"> <mat-icon class="pdf-icon" style="margin-top: -1px;">mail_outline</mat-icon> <span>Email</span> </button> </mat-menu> </div> </div> </div> <div class="row custom-gutters my-3 table-grid"> <div class="col-md-12"> <mat-card class="pb-0"> <mat-card-content> <table class="table table-hover table-bordered mb-0"> <thead class="thead-light"> <tr> <th scope="col" style="width: 6%;">Sr. No.</th> <th scope="col">Application</th> <th scope="col">Vulnerability</th> <th scope="col">Severity</th> <th scope="col">Severity1</th> <th scope="col">Status</th> </tr> </thead> <tbody> <tr *ngFor="let item of getAppSecuritySearch(); let i= index"> <th scope="row">{{ (pageEvent.pageIndex * pageEvent.pageSize) + i + 1}}</th> <td>{{item.application}}</td> <td>{{item.vulnerability}}</td> <td>{{item.severity}}</td> <td>{{item.severity1}}</td> <td>{{item.status}}</td> </tr> </tbody> </table> <mat-paginator [length]="length" [pageSize]="pageEvent.pageSize" [pageSizeOptions]="pageSizeOptions" (page)="pageChanged($event)"> </mat-paginator> </mat-card-content> </mat-card> </div> </div> <table class="table table-hover table-bordered mb-0" style="display: none;" id="excel-table"> <thead class="thead-light"> <tr> <th scope="col" style="width: 13%;">Sr. No.</th> <th scope="col" *ngIf="isPrintArrayHas('application')">Application</th> <th scope="col" *ngIf="isPrintArrayHas('vulnerability')">Vulnerability</th> <th scope="col" *ngIf="isPrintArrayHas('severity')">Severity</th> <th scope="col" *ngIf="isPrintArrayHas('severity1')">Severity1</th> <th scope="col" *ngIf="isPrintArrayHas('status')">Status</th> </tr> </thead> <tbody> <tr *ngFor="let item of getAppSecurityPrint(); let i= index"> <th scope="row"> {{ i + 1}}</th> <td *ngIf="isPrintArrayHas('application')">{{item.application}}</td> <td *ngIf="isPrintArrayHas('vulnerability')">{{item.vulnerability}}</td> <td *ngIf="isPrintArrayHas('severity')">{{item.severity}}</td> <td *ngIf="isPrintArrayHas('severity1')">{{item.severity1}}</td> <td *ngIf="isPrintArrayHas('status')">{{item.status}}</td> </tr> </tbody> </table>
<?php use App\Http\Controllers\AuthController; use App\Http\Controllers\DrugSearchController; use App\Http\Controllers\MedicationController; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "api" middleware group. Make something great! | */ Route::middleware(['auth:sanctum'])->group(function () { Route::post('/logout', [AuthController::class, 'logout']); Route::prefix('medication')->controller(MedicationController::class)->group(function () { Route::post('/add', 'addDrug'); Route::delete('/delete/{medicationId}', [MedicationController::class, 'deleteDrug']); Route::get('/', 'getUserDrugs'); }); }); Route::get('/search/{name}', [DrugSearchController::class, 'search'])->middleware('throttle:20,1');; Route::post('/register', [AuthController::class, 'register']); Route::post('/login', [AuthController::class, 'login']);
import React, { useContext } from "react"; import moment from "moment"; import { Context } from "./../Context"; import { Box, List, ListSubheader, ListItemButton, Stack, Chip, Typography, Divider, } from "@mui/material"; export const UploadedPDFList = React.forwardRef( ({ handleModalOpen, dates, rows }, ref) => { const { actions, program, areaNum, parameter, file } = useContext(Context); return ( <Box ref={ref}> {dates.length ? ( dates.map((date, index) => { return ( <List dense={true} key={`list${index}`}> <ListSubheader sx={{ textAlign: "right" }}> {moment(date, "YYYY-MM-DD").format("MMM DD, YYYY")} </ListSubheader> {rows.map((row, index) => { const { program, areaNum, parameter, fileName, dateUpload } = row; if (dateUpload === date) { return ( <> <ListItemButton onClick={() => { actions.setFile(fileName); actions.setDirectory( `${program}/${areaNum}/${parameter}` ); handleModalOpen(); }} sx={{ display: "flex", justifyContent: "space-between", }} key={index} > {row.fileName} <Stack direction="row" spacing={2}> <Chip label={row.program} color="warning" size="small" /> <Chip label={`Area ${row.areaNum.slice(-1)}`} color="warning" size="small" /> <Chip label={`Parameter ${row.parameter.slice(-1)}`} color="warning" size="small" /> </Stack> </ListItemButton> <Divider /> </> ); } })} </List> ); }) ) : ( <Typography sx={{ textAlign: "center", p: 1 }} variant="h5"> No Files Uploaded </Typography> )} </Box> ); } );
const ADD_POST = 'ADD-POST'; const UPDATE_NEW_POST_TEXT = 'UPDATE-NEW-POST-TEXT'; //начальные значения let initialState = { posts: [ {id: 1, message: "Hey what's upp", likesCount: 1}, {id: 2, message: "Nice, thnx", likesCount: 21}, {id: 1, message: "Hey what's upp", likesCount: 1} ], newPostText: 'Hola' } const profileReducer = (state = initialState, action) => { switch (action.type) { case ADD_POST: { let newPost = { id: 5, message: state.newPostText, //приходит из пропсов, из инпута textarea.value likesCount: 0 }; return { ...state, posts: [...state.posts, newPost], newPostText: '' } } case UPDATE_NEW_POST_TEXT: { return { ...state, newPostText: action.newText } } default: return state } } // Actions это объекты (Вызываются из компонентов и передаются через dispatch(props): export const addPostActionCreator = () => ({type: ADD_POST}); export const updateNewPostTextActionCreator = (text) => ({type: UPDATE_NEW_POST_TEXT, newText: text}); export default profileReducer
import 'package:crosstrack_italia/features/weather/domain/models/forecast.dart'; import 'package:crosstrack_italia/features/weather/domain/providers/forecast_info_provider.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class WeatherView extends ConsumerWidget { const WeatherView({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { return Column( children: [ Text( 'Meteo:', style: TextStyle( fontSize: 12.sp, color: Theme.of(context).colorScheme.tertiary, fontWeight: FontWeight.bold, ), ), Consumer( builder: (context, ref, child) { final AsyncValue<Forecast> forecastInfo = ref.watch(forecastInfoProvider); return SafeArea( child: Center( child: switch (forecastInfo) { AsyncData(:final value) => WeatherWidget(forecast: value), AsyncError() => const Icon(Icons.error), _ => const CircularProgressIndicator(), }, ), ); }, ), ], ); } } class WeatherWidget extends ConsumerWidget { final Forecast forecast; const WeatherWidget({ super.key, required this.forecast, }); @override Widget build(BuildContext context, WidgetRef ref) { return Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisSize: MainAxisSize.max, children: [ ...forecast.list.map( (weather) => Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Text( weather.date, style: TextStyle( fontSize: 12.sp, fontWeight: FontWeight.bold, ), ), //hour Image.network( 'https://openweathermap.org/img/wn/${weather.iconUrl}.png', height: 37.5.h, width: 37.5.w, ), Text( weather.temperature, style: TextStyle( fontSize: 12.sp, fontWeight: FontWeight.bold, ), ), ], ), ), ), ], ); } }
package com.ling5821.javabase.juc; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @author lsj * @date 2021/7/7 10:06 */ public class JucCondition { private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); public void before() { lock.lock(); try { System.out.println("before"); condition.signalAll(); } finally { lock.unlock(); } } public void after() { lock.lock(); try { condition.await(); System.out.println("after"); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); JucCondition jucCondition = new JucCondition(); executorService.execute(() -> jucCondition.after()); executorService.execute(() -> jucCondition.before()); } }
import React, { useState, useEffect } from "react" import ArticleList from "../common/ArticleList" import { getTagArticles, getTagWithLabel } from "../services/tagsAPI" const TagArticles = (props) => { const [articles, setArticles] = useState([]) const [tag, setTag] = useState({}) const [loaded, setLoaded] = useState(false) const { user } = props useEffect(() => { fetchTag() }, [props.match.params.label]) useEffect(() => { fetchArticles(1) console.log(articles) }, [tag]) useEffect(() => {}, [articles]) const fetchTag = async () => { try { setTag(await getTagWithLabel(props.match.params.label)) setLoaded(true) } catch (error) { console.log(error) } } const fetchArticles = async (pageNumber) => { try { let formatArray = [] if (pageNumber === 1) { formatArray = await getTagArticles(tag.id, pageNumber) } else { formatArray = [...articles].concat( await getTagArticles(tag.id, pageNumber) ) } if (formatArray.length === articles.length) { setScrolled(true) } setArticles(formatArray) setLoaded(true) } catch (error) { console.log(error) } } return ( <React.Fragment> <div id="articles"> <h1 className="text-center"> <i className="fa fa-fw fa-tags" aria-hidden="true"></i> Catégorie {props.match.params.label} </h1> {tag.label && ( <ArticleList articles={articles} setArticles={setArticles} user={user} fetchArticles={fetchArticles} loaded={loaded} /> )} </div> </React.Fragment> ) } export default TagArticles
import { jest } from '@jest/globals'; import { bodyUserComplete, confirmButNoPassword, passWordButNoConfirm, returnFoundedUser, returnUserExist, returnUserInfo } from '../factories'; import authenticantionRepository from '@/repositories/authentication-repository'; import usersRepository from '@/repositories/users-repository'; import usersService from '@/services/users-services'; import bcrypt from 'bcrypt'; import { faker } from '@faker-js/faker'; import { badRequestError, duplicatedEmailError, notFoundUserError } from '@/errors'; jest.mock('@/repositories/authentication-repository'); jest.mock('@/repositories/users-repository'); describe('usersService function', () => { describe('getUserInfoService function', () => { it('should return user information', async () => { const user = returnUserExist(); const userInfo = returnUserInfo(); jest.spyOn(authenticantionRepository, 'findUserById').mockResolvedValue(user); jest.spyOn(usersRepository, 'getUserInfo').mockResolvedValue(userInfo); const response = await usersService.getUserInfoService(user.id); expect(authenticantionRepository.findUserById).toHaveBeenCalledWith(user.id); expect(usersRepository.getUserInfo).toHaveBeenCalledWith(user.id); expect(response).toEqual(userInfo); }) it('should not return info if user does not exit', async () => { const user = returnUserExist(); const userInfo = returnUserInfo(); jest.spyOn(authenticantionRepository, 'findUserById').mockResolvedValue(undefined); await expect(usersService.getUserInfoService(user.id)).rejects.toEqual(notFoundUserError()) expect(authenticantionRepository.findUserById).toHaveBeenCalledWith(user.id); }) }) describe('editUserService function', () => { it('should edit user information', async () => { const user = returnUserExist(); const body = bodyUserComplete(); const hashedPassword = faker.internet.password(); const newBody = { name: body.name, email: body.email, password: hashedPassword, image: body.image, birthday: body.birthday } jest.spyOn(authenticantionRepository, 'findUserById').mockResolvedValue(user); jest.spyOn(authenticantionRepository, 'findUserEmail').mockResolvedValue(user); jest.spyOn(bcrypt, 'compare').mockImplementationOnce((): boolean => { return true }); jest.spyOn(bcrypt, 'hash').mockImplementationOnce((): string => { return hashedPassword }); jest.spyOn(usersRepository, 'editUserInfo').mockResolvedValue(undefined); const response = await usersService.editUserService(user.id, body); expect(response).toEqual(undefined); expect(authenticantionRepository.findUserById).toHaveBeenCalledWith(user.id); expect(authenticantionRepository.findUserEmail).toHaveBeenCalledWith(body.email); expect(bcrypt.compare).toHaveBeenCalled(), expect(bcrypt.hash).toHaveBeenCalled(), expect(usersRepository.editUserInfo).toHaveBeenCalledWith(user.id, newBody); }) it('should not edit user info if email already exist', async () => { const user = returnUserExist(); const otherUser = { id: 0, name: user.name, email: user.email, password: user.password, birthday: user.birthday, image: user.image } const body = bodyUserComplete(); jest.spyOn(authenticantionRepository, 'findUserById').mockResolvedValue(user); jest.spyOn(authenticantionRepository, 'findUserEmail').mockResolvedValue(otherUser); await expect(usersService.editUserService(user.id, body)).rejects.toEqual(duplicatedEmailError()); expect(authenticantionRepository.findUserById).toHaveBeenCalledWith(user.id); expect(authenticantionRepository.findUserEmail).toHaveBeenCalledWith(body.email); }) it('should not edit user info if password exist but no confirm password', async () => { const user = returnUserExist(); const body = passWordButNoConfirm(); jest.spyOn(authenticantionRepository, 'findUserById').mockResolvedValue(user); await expect(usersService.editUserService(user.id, body)).rejects.toEqual(badRequestError()); expect(authenticantionRepository.findUserById).toHaveBeenCalledWith(user.id); }) it('should not edit user info if confirm password exist but no password', async () => { const user = returnUserExist(); const body = confirmButNoPassword(); jest.spyOn(authenticantionRepository, 'findUserById').mockResolvedValue(user); await expect(usersService.editUserService(user.id, body)).rejects.toEqual(badRequestError()); expect(authenticantionRepository.findUserById).toHaveBeenCalledWith(user.id); }) it('should not edit user info if password is wrong', async () => { const user = returnUserExist(); const body = bodyUserComplete(); jest.spyOn(authenticantionRepository, 'findUserById').mockResolvedValue(user); jest.spyOn(authenticantionRepository, 'findUserEmail').mockResolvedValue(user); jest.spyOn(bcrypt, 'compare').mockImplementationOnce((): boolean => { return false }); await expect(usersService.editUserService(user.id, body)).rejects.toEqual(notFoundUserError()); expect(authenticantionRepository.findUserById).toHaveBeenCalledWith(user.id); expect(authenticantionRepository.findUserEmail).toHaveBeenCalledWith(body.email); expect(bcrypt.compare).toHaveBeenCalled() }) }) describe('findUser', () => { it('should find user by its name', async () => { const users = returnFoundedUser(); jest.spyOn(usersRepository, 'findUserByName').mockResolvedValue([users]); const response = await usersService.findUser(users.name); expect(response).toEqual([users]); expect(usersRepository.findUserByName).toHaveBeenCalledWith(users.name); }) }) })
use crate::data::{ models::todo_model::Todo, queries::sql_queries::{ DELETE_QUERY, INSERT_QUERY, SELECT_BY_ID_QUERY, SELECT_QUERY, UPDATE_QUERY, }, }; use postgres::{Client, NoTls}; /// /// Get a database connection /// pub fn client() -> Client { let connection_string = "postgresql://postgres:postgres@127.0.0.1:5432/postgres"; Client::connect(connection_string, NoTls).unwrap() } /// /// Find all the todo items from the database /// pub fn find_all() -> Vec<Todo> { std::thread::spawn(move || { let mut todos = Vec::new(); for row in client().query(SELECT_QUERY, &[]).unwrap() { let todo = Todo { id: row.get(0), title: row.get(1), completed: row.get(2), }; todos.push(todo); } todos }) .join() .unwrap() } /// /// Find a todo item from the database by id /// pub fn find_by_id(id: i32) -> Todo { std::thread::spawn(move || { let row = client().query_one(SELECT_BY_ID_QUERY, &[&id]).unwrap(); Todo { id: row.get(0), title: row.get(1), completed: row.get(2), } }) .join() .unwrap() } /// /// Insert a todo item into the database /// pub fn insert_into(title: String, completed: bool) -> Todo { std::thread::spawn(move || { let row = client() .query_one(INSERT_QUERY, &[&title, &completed]) .unwrap(); Todo { id: row.get(0), title: row.get(1), completed: row.get(2), } }) .join() .unwrap() } /// /// Update a todo item in the database /// pub fn update_where(id: i32, title: String, completed: bool) -> Todo { std::thread::spawn(move || { let row = client() .query_one(UPDATE_QUERY, &[&title, &completed, &id]) .unwrap(); Todo { id: row.get(0), title: row.get(1), completed: row.get(2), } }) .join() .unwrap() } /// /// Delete a todo item from the database /// pub fn delete_from(id: i32) { std::thread::spawn(move || { client().execute(DELETE_QUERY, &[&id]).unwrap(); }) .join() .unwrap() }
import React, { useState } from 'react' import EmployeeForm from './EmployeeForm' import PeopleOutlineOutlinedIcon from '@mui/icons-material/PeopleOutlineOutlined'; import PageHeader from '../../Components/PageHeader'; import { InputAdornment, makeStyles, Paper, TableBody, TableCell, TableRow, Toolbar } from '@material-ui/core'; import useTable from '../../Components/useTable'; import * as EmployeeService from '../../services/EmployeeService' import Controls from '../../Components/Controls/Controls' import { Search } from '@mui/icons-material'; const useStyles = makeStyles(theme => ({ pageContent: { margin: theme.spacing(5), padding: theme.spacing(3) }, searchInput:{ width:'75%' } })) const headCells = [ { id:'fullName',label :'Employee Name' }, { id:'email',label :'Email Address' }, { id:'mobile',label :'Mobile Number' }, { id:'department',label :'Department',disableSorting : true } ] const Employees = () => { const classes = useStyles(); const [records,setRecords] = useState(EmployeeService.getAllEmployees()); const [filterFn, setFilterFn] = useState({ fn: items => { return items; } }) const {TblContainer,TblHead,TblPagination,recordsAfterPagingAndSorting}=useTable(records,headCells,filterFn); const handleSearch = e => { let target = e.target; setFilterFn({ fn: items => { if (target.value === "") return items; else return items.filter(x => x.fullName.toLowerCase().includes(target.value)) } }) } return ( <> <PageHeader title="New Employees" subtitle="Form Design with Validation" icon={<PeopleOutlineOutlinedIcon />} /> <Paper className={classes.pageContent}> <EmployeeForm /> <Toolbar> <Controls.Input label="Search Employees" className={classes.searchInput} InputProps={{ startAdornment: (<InputAdornment position="start"> <Search /> </InputAdornment>) }} onChange={handleSearch} /> </Toolbar> <TblContainer> <TblHead/> <TableBody> {recordsAfterPagingAndSorting().map(item => ( <TableRow key={item.id}> <TableCell>{item.fullName}</TableCell> <TableCell>{item.email}</TableCell> <TableCell>{item.mobile}</TableCell> <TableCell>{item.department}</TableCell> </TableRow> ))} </TableBody> </TblContainer> <TblPagination/> </Paper> </> ) } export default Employees
import { Component } from 'react'; import './app.css'; import Habits from './components/habits'; import Navbar from './components/navbar'; class App extends Component { state = { habits : [ {id : 1, name : 'Reading',count : 0}, {id : 2, name : 'Running',count : 0}, {id : 3, name : 'Coding',count : 0}, ] } handleIncrement = (habit) =>{ // const habits = [...this.state.habits]; // const index = habits.indexOf(habit); // console.log(index); // habits[index].count++; // this.setState({ habits : habits}); const habits = this.state.habits.map(item =>{ if(item.id === habit.id){ return {...habit, count : habit.count + 1} } return item; }) this.setState({habits}) }; handleDecrement = (habit) =>{ // const habits = [...this.state.habits]; // const index = habits.indexOf(habit); // const count = habits[index].count -1; // habits[index].count = count < 0 ? 0 : count; // this.setState({ habits : habits}); const habits = this.state.habits.map(item =>{ if(item.id === habit.id){ const count = habit.count -1; return {...habit, count : count<0 ? 0 : count} } return item; }) this.setState({habits}) } handleDelete = (habit) =>{ const habits = this.state.habits.filter(itme => itme.id !== habit.id) this.setState({ habits : habits}); } handleAdd = (name) => { const habits = [...this.state.habits, {id:Date.now(),name,count:0}]; this.setState({habits}); } handleReset = () => { const habits = this.state.habits.map(habit => { if(habit.count !== 0){ return {...habit, count : 0} } return habit }) this.setState({habits}) } render() { return ( <> <Navbar totalCount={this.state.habits.filter(item=>item.count>0).length}/> <Habits habits={this.state.habits} onIncrement={this.handleIncrement} onDecrement={this.handleDecrement} onDelete={this.handleDelete} onAdd={this.handleAdd} onReset={this.handleReset} /> </> ) }; } export default App;
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateShippingDetailsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('shipping_details', function (Blueprint $table) { $table->id(); $table->bigInteger('order_id')->unsigned(); $table->string('firstname')->nullable(); $table->string('lastname')->nullable(); $table->string('email')->nullable(); $table->string('phone')->nullable(); $table->string('address')->nullable(); $table->string('country')->nullable(); $table->string('state')->nullable(); $table->string('city')->nullable(); $table->timestamps(); $table->foreign('order_id') ->on('orders') ->references('id') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('shipping_details'); } }
/* * Copyright 2022-2023 Sweden Connect * * 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 se.swedenconnect.signservice.audit; /** * Runtime exception class that is thrown if audit logging fails. There are basically two types of failures: * <ul> * <li>The underlying logging system reports an error, or,</li> * <li>An audit event is incorrect, for example missing some of its mandatory data.</li> * </ul> */ public class AuditLoggerException extends RuntimeException { /** For serializing. */ private static final long serialVersionUID = -4136899216063988045L; /** * Constructor setting the error message. * * @param message the error message */ public AuditLoggerException(final String message) { super(message); } /** * Constructor setting the error message and the cause of the error. * * @param message the error message * @param cause the cause of the error */ public AuditLoggerException(final String message, final Throwable cause) { super(message, cause); } }
import torch # torch help us to derivation, x0.data store the value, x0.grad store the gradient value # print(torch.__version__) x0 = torch.randint(low=-1000, high=1001, size=(1,), dtype=torch.float32, requires_grad=True) y0 = torch.randint(low=-1000, high=1001, size=(1,), dtype=torch.float32, requires_grad=True) z0 = torch.randint(low=-1000, high=1001, size=(1,), dtype=torch.float32, requires_grad=True) def fn(x, y, z): return x ** 2 + y ** 2 + z ** 2 epochs = 10000 learning_rate = 1e-2 # Ensure gradients are zero before starting x0.grad = torch.zeros_like(x0) y0.grad = torch.zeros_like(y0) z0.grad = torch.zeros_like(z0) for _ in range(epochs): # Forward Propagation target = fn(x0, y0, z0) # Backward Propagation, taking the partial derivative target.backward() # Gradient descent update with torch.no_grad(): x0 -= learning_rate * x0.grad y0 -= learning_rate * y0.grad z0 -= learning_rate * z0.grad # Zero the gradients after updating x0.grad.zero_() y0.grad.zero_() z0.grad.zero_() print(x0.item(), y0.item(), z0.item())
import { Server } from "socket.io"; import { ClientToServerEvents, ServerToClientEvents } from "./src/types"; import { GameState } from "./src/gameState"; import { Task } from "./src/task"; import { Card } from "./src/card"; import { Communication } from "./src/communication"; import { Color, Direction, GameError, TaskToken } from "./src/header"; import { StrippedGameState } from "./src/strippedData"; import { CardData, TaskData, CommunicationData, dataToCard, dataToTask, dataToCommunication } from "./src/data"; import { TEST_MISSION_TASKS, MISSION_35 } from "./src/mission"; const PORT = 3000; const io = new Server<ClientToServerEvents, ServerToClientEvents>(PORT, { serveClient: false, cors: { origin: "http://127.0.0.1:5173", }, }); console.log('ƒNƒ%。ƒVƒbƒNƒRƒ"ƒgƒ [ƒ%。,ª▪️ K—v,Å,· B'); console.log("You will need the classic controller."); let game = MISSION_35.game; let uuidToDir: Record<string, Direction> = {}; let socketToDir: Record<string, Direction> = {}; io.on("connection", (socket) => { socket.on("ping", () => { console.log(uuidToDir); console.log("ping"); socket.emit("pong"); }); socket.on("joinGame", (uuid: string) => { console.log("joinGame", uuid); if (uuid in uuidToDir) { socket.emit("error", "YOU'RE ALREADY IN BUDDY"); return; } let num_players_joined = Object.keys(uuidToDir).length; if (num_players_joined >= 4) { socket.emit("error", "We are full."); return; } uuidToDir[uuid] = num_players_joined; socketToDir[socket.id] = num_players_joined; emitUpdateToAll(); }); socket.on("playCard", (uuid: string, data: CardData) => { console.log("playCard", uuid, data); if (!(uuid in uuidToDir)) { socket.emit("error", "who are you?"); } let dir = uuidToDir[uuid]; let card = dataToCard(data); if (game.update_playCard(dir, card) == GameError.SUCCESS) { emitUpdateToAll(); } else { socket.emit("error", "gamestate error"); } }); socket.on("pickTask", (uuid: string, data: TaskData) => { console.log("pickTask", uuid, data); if (!(uuid in uuidToDir)) { socket.emit("error", "who are you?"); } let dir = uuidToDir[uuid]; let task = dataToTask(data); if (game.update_pickTask(dir, task) == GameError.SUCCESS) { emitUpdateToAll(); } else { socket.emit("error", "gamestate error"); } }); socket.on("communicate", (uuid: string, data: CommunicationData) => { console.log("pickTask", uuid, data); if (!(uuid in uuidToDir)) { socket.emit("error", "who are you?"); } let dir = uuidToDir[uuid]; let communication = dataToCommunication(data); if (game.update_communicate(dir, communication) == GameError.SUCCESS) { emitUpdateToAll(); } else { socket.emit("error", "gamestate error"); } }); socket.on("requestGameState", (uuid) => { console.log("requestGameState", uuid); if (!(uuid in uuidToDir)) { return; } console.log(socketToDir); let dir = uuidToDir[uuid]; let strippedGame = new StrippedGameState(game, dir); if (!(socket.id in socketToDir)) { socketToDir[socket.id] = dir; } socket.emit("update", strippedGame); }); }); async function emitUpdateToAll() { const sockets = await io.fetchSockets(); const socketIDs = sockets.map((socket) => socket.id); for (const socketID of socketIDs) { let strippedGame = new StrippedGameState(game, socketToDir[socketID]); io.to(socketID).emit("update", strippedGame); } }
class Validadores { static String? nome(String? nome) { if (nome == null || nome.isEmpty) { return 'Preencha um nome'; } if (nome.length < 2) { return 'Digite um nome válido'; } return null; } static String? vendedor(String? nome) { if (nome == null || nome.isEmpty) { return 'Vendedor vazio'; } if (nome.length < 2) { return 'Digite um vendedor válido'; } return null; } static String? cpf(String? cpf) { if (cpf == null || cpf.isEmpty) { return 'Preencha o seu CPF'; } if (cpf.length < 11 || cpf.length > 14) { return 'Preencha o CPF corretamente'; } return null; } static String? rg(String? rg) { if (rg == null || rg.isEmpty) { return 'Preencha o seu RG corretamente'; } if (rg.length < 8 || rg.length > 8) { return 'Preencha o CPF corretamente'; } return null; } static String? data(String? data) { if (data == null || data.isEmpty) { return 'Preencha a data corretamente'; } if (data.length < 10) { return 'Digite uma data válida'; } return null; } static String? valor(String? valor) { if (valor == null || valor.isEmpty) { return 'Digite o valor'; } if (valor.length < 2 || valor.length >= 100) { return 'Digite um valor válidor'; } return null; } static String? produto(String? produto) { if (produto == null || produto.isEmpty) { return 'Preencha o produto'; } if (produto.length < 2) { return 'Digite um produto válido'; } return null; } static String? numeroVenda(String? numeroVenda) { if (numeroVenda == null || numeroVenda.isEmpty) { return 'Preencha o numero de venda'; } if (numeroVenda.isEmpty) { return 'Digite um numero de venda válido'; } return null; } }
pragma solidity 0.4.25; interface ISGAAuthorizationManager { function isAuthorizedToBuy(address _sender) external view returns (bool); function isAuthorizedToSell(address _sender) external view returns (bool); function isAuthorizedToTransfer(address _sender, address _target) external view returns (bool); function isAuthorizedToTransferFrom(address _sender, address _source, address _target) external view returns (bool); function isAuthorizedForPublicOperation(address _sender) external view returns (bool); } interface IContractAddressLocator { function getContractAddress(bytes32 _identifier) external view returns (address); function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); } contract ContractAddressLocatorHolder { bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource"; bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ; bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ; bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ; bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ; bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ; bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ; bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ; bytes32 internal constant _IMintHandler_ = "IMintHandler" ; bytes32 internal constant _IMintListener_ = "IMintListener" ; bytes32 internal constant _IMintManager_ = "IMintManager" ; bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ; bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ; bytes32 internal constant _IRedButton_ = "IRedButton" ; bytes32 internal constant _IReserveManager_ = "IReserveManager" ; bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ; bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ; bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ; bytes32 internal constant _ISGAAuthorizationManager_ = "ISGAAuthorizationManager"; bytes32 internal constant _ISGAToken_ = "ISGAToken" ; bytes32 internal constant _ISGATokenManager_ = "ISGATokenManager" ; bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager"; bytes32 internal constant _ISGNToken_ = "ISGNToken" ; bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ; bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ; bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ; bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ; bytes32 internal constant _IWalletsTradingDataSource_ = "IWalletsTradingDataSource" ; bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ; bytes32 internal constant _WalletsTradingLimiter_SGATokenManager_ = "WalletsTLSGATokenManager" ; bytes32 internal constant _IETHConverter_ = "IETHConverter" ; bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ; bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ; bytes32 internal constant _IRateApprover_ = "IRateApprover" ; IContractAddressLocator private contractAddressLocator; constructor(IContractAddressLocator _contractAddressLocator) internal { require(_contractAddressLocator != address(0), "locator is illegal"); contractAddressLocator = _contractAddressLocator; } function getContractAddressLocator() external view returns (IContractAddressLocator) { return contractAddressLocator; } function getContractAddress(bytes32 _identifier) internal view returns (address) { return contractAddressLocator.getContractAddress(_identifier); } function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) { return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers); } modifier only(bytes32 _identifier) { require(msg.sender == getContractAddress(_identifier), "caller is illegal"); _; } } library AuthorizationActionRoles { string public constant VERSION = "1.0.0"; enum Flag { BuySga , SellSga , SellSgn , ReceiveSga , ReceiveSgn , TransferSga , TransferSgn , TransferFromSga, TransferFromSgn } function isAuthorizedToBuySga (uint256 _flags) internal pure returns (bool) {return isAuthorized(_flags, Flag.BuySga );} function isAuthorizedToSellSga (uint256 _flags) internal pure returns (bool) {return isAuthorized(_flags, Flag.SellSga );} function isAuthorizedToSellSgn (uint256 _flags) internal pure returns (bool) {return isAuthorized(_flags, Flag.SellSgn );} function isAuthorizedToReceiveSga (uint256 _flags) internal pure returns (bool) {return isAuthorized(_flags, Flag.ReceiveSga );} function isAuthorizedToReceiveSgn (uint256 _flags) internal pure returns (bool) {return isAuthorized(_flags, Flag.ReceiveSgn );} function isAuthorizedToTransferSga (uint256 _flags) internal pure returns (bool) {return isAuthorized(_flags, Flag.TransferSga );} function isAuthorizedToTransferSgn (uint256 _flags) internal pure returns (bool) {return isAuthorized(_flags, Flag.TransferSgn );} function isAuthorizedToTransferFromSga(uint256 _flags) internal pure returns (bool) {return isAuthorized(_flags, Flag.TransferFromSga);} function isAuthorizedToTransferFromSgn(uint256 _flags) internal pure returns (bool) {return isAuthorized(_flags, Flag.TransferFromSgn);} function isAuthorized(uint256 _flags, Flag _flag) private pure returns (bool) {return ((_flags >> uint256(_flag)) & 1) == 1;} } interface IAuthorizationDataSource { function getAuthorizedActionRole(address _wallet) external view returns (bool, uint256); function getTradeLimitAndClass(address _wallet) external view returns (uint256, uint256); } contract SGAAuthorizationManager is ISGAAuthorizationManager, ContractAddressLocatorHolder { string public constant VERSION = "1.0.0"; using AuthorizationActionRoles for uint256; constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} function getAuthorizationDataSource() public view returns (IAuthorizationDataSource) { return IAuthorizationDataSource(getContractAddress(_IAuthorizationDataSource_)); } function isAuthorizedToBuy(address _sender) external view returns (bool) { IAuthorizationDataSource authorizationDataSource = getAuthorizationDataSource(); (bool senderIsWhitelisted, uint256 senderActionRole) = authorizationDataSource.getAuthorizedActionRole(_sender); return senderIsWhitelisted && senderActionRole.isAuthorizedToBuySga(); } function isAuthorizedToSell(address _sender) external view returns (bool) { IAuthorizationDataSource authorizationDataSource = getAuthorizationDataSource(); (bool senderIsWhitelisted, uint256 senderActionRole) = authorizationDataSource.getAuthorizedActionRole(_sender); return senderIsWhitelisted && senderActionRole.isAuthorizedToSellSga(); } function isAuthorizedToTransfer(address _sender, address _target) external view returns (bool) { IAuthorizationDataSource authorizationDataSource = getAuthorizationDataSource(); (bool senderIsWhitelisted, uint256 senderActionRole) = authorizationDataSource.getAuthorizedActionRole(_sender); (bool targetIsWhitelisted, uint256 targetActionRole) = authorizationDataSource.getAuthorizedActionRole(_target); return senderIsWhitelisted && senderActionRole.isAuthorizedToTransferSga() && targetIsWhitelisted && targetActionRole.isAuthorizedToReceiveSga(); } function isAuthorizedToTransferFrom(address _sender, address _source, address _target) external view returns (bool) { IAuthorizationDataSource authorizationDataSource = getAuthorizationDataSource(); (bool senderIsWhitelisted, uint256 senderActionRole) = authorizationDataSource.getAuthorizedActionRole(_sender); (bool sourceIsWhitelisted, uint256 sourceActionRole) = authorizationDataSource.getAuthorizedActionRole(_source); (bool targetIsWhitelisted, uint256 targetActionRole) = authorizationDataSource.getAuthorizedActionRole(_target); return senderIsWhitelisted && senderActionRole.isAuthorizedToTransferFromSga() && sourceIsWhitelisted && sourceActionRole.isAuthorizedToTransferSga() && targetIsWhitelisted && targetActionRole.isAuthorizedToReceiveSga(); } function isAuthorizedForPublicOperation(address _sender) external view returns (bool) { IAuthorizationDataSource authorizationDataSource = getAuthorizationDataSource(); (bool senderIsWhitelisted,) = authorizationDataSource.getAuthorizedActionRole(_sender); return senderIsWhitelisted; } }
import * as Sequelize from 'sequelize'; import { DataTypes, Model, Optional } from 'sequelize'; import type { comuneros, comunerosId } from './comuneros'; import type { comuneros_tipos_doc, comuneros_tipos_docId } from './comuneros_tipos_doc'; export interface tipo_documentosAttributes { id_tipo_doc: string; tipo_doc: string; estado_doc?: number; alias?: string; } export type tipo_documentosPk = "id_tipo_doc"; export type tipo_documentosId = tipo_documentos[tipo_documentosPk]; export type tipo_documentosOptionalAttributes = "estado_doc" | "alias"; export type tipo_documentosCreationAttributes = Optional<tipo_documentosAttributes, tipo_documentosOptionalAttributes>; export class tipo_documentos extends Model<tipo_documentosAttributes, tipo_documentosCreationAttributes> implements tipo_documentosAttributes { id_tipo_doc!: string; tipo_doc!: string; estado_doc?: number; alias?: string; // tipo_documentos belongsToMany comuneros via id_tipo_doc and id_comunero id_comunero_comuneros!: comuneros[]; getId_comunero_comuneros!: Sequelize.BelongsToManyGetAssociationsMixin<comuneros>; setId_comunero_comuneros!: Sequelize.BelongsToManySetAssociationsMixin<comuneros, comunerosId>; addId_comunero_comunero!: Sequelize.BelongsToManyAddAssociationMixin<comuneros, comunerosId>; addId_comunero_comuneros!: Sequelize.BelongsToManyAddAssociationsMixin<comuneros, comunerosId>; createId_comunero_comunero!: Sequelize.BelongsToManyCreateAssociationMixin<comuneros>; removeId_comunero_comunero!: Sequelize.BelongsToManyRemoveAssociationMixin<comuneros, comunerosId>; removeId_comunero_comuneros!: Sequelize.BelongsToManyRemoveAssociationsMixin<comuneros, comunerosId>; hasId_comunero_comunero!: Sequelize.BelongsToManyHasAssociationMixin<comuneros, comunerosId>; hasId_comunero_comuneros!: Sequelize.BelongsToManyHasAssociationsMixin<comuneros, comunerosId>; countId_comunero_comuneros!: Sequelize.BelongsToManyCountAssociationsMixin; // tipo_documentos hasMany comuneros_tipos_doc via id_tipo_doc comuneros_tipos_docs!: comuneros_tipos_doc[]; getComuneros_tipos_docs!: Sequelize.HasManyGetAssociationsMixin<comuneros_tipos_doc>; setComuneros_tipos_docs!: Sequelize.HasManySetAssociationsMixin<comuneros_tipos_doc, comuneros_tipos_docId>; addComuneros_tipos_doc!: Sequelize.HasManyAddAssociationMixin<comuneros_tipos_doc, comuneros_tipos_docId>; addComuneros_tipos_docs!: Sequelize.HasManyAddAssociationsMixin<comuneros_tipos_doc, comuneros_tipos_docId>; createComuneros_tipos_doc!: Sequelize.HasManyCreateAssociationMixin<comuneros_tipos_doc>; removeComuneros_tipos_doc!: Sequelize.HasManyRemoveAssociationMixin<comuneros_tipos_doc, comuneros_tipos_docId>; removeComuneros_tipos_docs!: Sequelize.HasManyRemoveAssociationsMixin<comuneros_tipos_doc, comuneros_tipos_docId>; hasComuneros_tipos_doc!: Sequelize.HasManyHasAssociationMixin<comuneros_tipos_doc, comuneros_tipos_docId>; hasComuneros_tipos_docs!: Sequelize.HasManyHasAssociationsMixin<comuneros_tipos_doc, comuneros_tipos_docId>; countComuneros_tipos_docs!: Sequelize.HasManyCountAssociationsMixin; static initModel(sequelize: Sequelize.Sequelize): typeof tipo_documentos { return tipo_documentos.init({ id_tipo_doc: { type: DataTypes.STRING(50), allowNull: false, primaryKey: true }, tipo_doc: { type: DataTypes.TEXT, allowNull: false }, estado_doc: { type: DataTypes.BOOLEAN, allowNull: true, defaultValue: 1 }, alias: { type: DataTypes.STRING(60), allowNull: true } }, { sequelize, tableName: 'tipo_documentos', timestamps: false, indexes: [ { name: "PRIMARY", unique: true, using: "BTREE", fields: [ { name: "id_tipo_doc" }, ] }, ] }); } }
/* * Copyright 2024 C Thing Software * SPDX-License-Identifier: Apache-2.0 */ package org.cthing.filevisitor; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.cthing.annotations.AccessForTesting; /** * Represents a glob matching pattern. Though they may look similar, a glob pattern differs from an ignore pattern. * An ignore pattern has additional syntax for directory matching and negation. */ final class Glob { /** * Lexical type for parsed glob patterns. */ enum TokenType { /** A character literal (e.g. "a"). */ Literal, /** Any single character (i.e. "?"). */ Any, /** Zero or more characters (i.e. "*"). */ ZeroOrMore, /** Any directory path prefix (i.e. "{@literal **}/"). */ RecursivePrefix, /** Any directory path suffix (i.e. "/{@literal **}"). */ RecursiveSuffix, /** Any directory path within a pattern (e.g. "a/{@literal **}/b"). */ RecursiveZeroOrMore, /** A character class (e.g. [f-h]). */ CharClass } /** * Interface implemented by glob pattern matchers. */ @AccessForTesting @FunctionalInterface interface Matcher { /** * Indicates whether the specified path matches the pattern represented by this matcher. * * @param path Path to test * @return {@code true} if the specified path matches. */ boolean matches(Path path); } /** * Matches literal strings (e.g. "abc"). */ @AccessForTesting static class LiteralMatcher implements Matcher { private final String literal; LiteralMatcher(final String literal) { this.literal = literal; } @Override public boolean matches(final Path path) { return this.literal.equals(path.toString()); } String getLiteral() { return this.literal; } } /** * Matches regular expressions. */ @AccessForTesting static class RegexMatcher implements Matcher { private final Pattern pattern; RegexMatcher(final Pattern pattern) { this.pattern = pattern; } @Override public boolean matches(final Path path) { return this.pattern.matcher(path.toString()).matches(); } Pattern getPattern() { return this.pattern; } } /** * Represents a range of characters with an inclusive start and end character (e.g. [a-z]). */ @AccessForTesting static class CharRange { char start; char end; CharRange(final char start, final char end) { this.start = start; this.end = end; } @Override public String toString() { return "(" + this.start + ',' + this.end + ')'; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final CharRange charRange = (CharRange)obj; return this.start == charRange.start && this.end == charRange.end; } @Override public int hashCode() { return Objects.hash(this.start, this.end); } } /** * A token generated by parsing a glob pattern. */ @AccessForTesting static class Token { final TokenType type; final char ch; final boolean negated; final List<CharRange> ranges; /** * Constructs a token with the specified type. * * @param type Type for the token */ Token(final TokenType type) { this.type = type; this.ch = 0; this.negated = false; this.ranges = List.of(); } /** * Constructs a literal token representing the specified character. * * @param ch Literal character */ Token(final char ch) { this.type = TokenType.Literal; this.ch = ch; this.negated = false; this.ranges = List.of(); } /** * Constructs a token representing a character class. * * @param negated {@code true} if the token excludes rather than includes the characters in the class * @param ranges Characters in the character class */ Token(final boolean negated, final Collection<CharRange> ranges) { this.type = TokenType.CharClass; this.ch = 0; this.negated = negated; this.ranges = List.copyOf(ranges); } @Override public String toString() { if (this.type == TokenType.Literal) { return String.valueOf(this.ch); } if (this.type == TokenType.CharClass) { return "[" + (this.negated ? '!' : "") + this.ranges.stream() .map(CharRange::toString) .collect(Collectors.joining(",")) + "]"; } return this.type.toString(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final Token token = (Token)obj; return this.ch == token.ch && this.negated == token.negated && this.type == token.type && Objects.equals(this.ranges, token.ranges); } @Override public int hashCode() { return Objects.hash(this.type, this.ch, this.negated, this.ranges); } } /** * Parses a glob pattern. */ @AccessForTesting static class Parser { private final StringIterator iterator; private final LinkedList<Token> tokens; Parser(final String pattern) { this.iterator = new StringIterator(pattern); this.tokens = new LinkedList<>(); } /** * Parses the glob pattern into a list of tokens. * * @return Tokens parsed from the glob pattern. * @throws MatchingException if there is a problem parsing the glob pattern. */ List<Token> parse() throws MatchingException { for (int ch = this.iterator.next(); ch != -1; ch = this.iterator.next()) { switch (ch) { case '?': this.tokens.addLast(new Token(TokenType.Any)); break; case '*': parseStar(); break; case '[': parseCharClass(); break; case '\\': parseBackslash(); break; default: this.tokens.addLast(new Token((char)ch)); break; } } return Collections.unmodifiableList(this.tokens); } private void parseStar() { final int prev = this.iterator.peekPrev(); if (this.iterator.peekNext() != '*') { this.tokens.addLast(new Token(TokenType.ZeroOrMore)); return; } final int star = this.iterator.next(); assert star == '*'; if (this.tokens.isEmpty()) { if (this.iterator.peekNext() == '/' || this.iterator.peekNext() < 0) { this.tokens.addLast(new Token(TokenType.RecursivePrefix)); this.iterator.next(); } else { this.tokens.addLast(new Token(TokenType.ZeroOrMore)); this.tokens.addLast(new Token(TokenType.ZeroOrMore)); } return; } if (prev != '/') { this.tokens.addLast(new Token(TokenType.ZeroOrMore)); this.tokens.addLast(new Token(TokenType.ZeroOrMore)); return; } final boolean suffix; final int nextCh = this.iterator.peekNext(); if (nextCh < 0) { this.iterator.next(); suffix = true; } else if (nextCh == '/') { this.iterator.next(); suffix = false; } else { this.tokens.addLast(new Token(TokenType.ZeroOrMore)); this.tokens.addLast(new Token(TokenType.ZeroOrMore)); return; } final Token removedToken = this.tokens.removeLast(); if (removedToken.type == TokenType.RecursivePrefix) { this.tokens.addLast(removedToken); } else if (removedToken.type == TokenType.RecursiveSuffix) { this.tokens.addLast(removedToken); } else { if (suffix) { this.tokens.addLast(new Token(TokenType.RecursiveSuffix)); } else { this.tokens.addLast(new Token(TokenType.RecursiveZeroOrMore)); } } } private void parseCharClass() throws MatchingException { final List<CharRange> ranges = new ArrayList<>(); final int nextCh = this.iterator.peekNext(); final boolean negated; if (nextCh == '!' || nextCh == '^') { final int ch = this.iterator.next(); assert ch == '!' || ch == '^'; negated = true; } else { negated = false; } boolean first = true; boolean inRange = false; loop: while (true) { final int ch = this.iterator.next(); if (ch < 0) { throw new MatchingException("Character class not closed"); } switch (ch) { case ']': if (first) { ranges.add(new CharRange(']', ']')); } else { break loop; } break; case '-': if (first) { ranges.add(new CharRange('-', '-')); } else if (inRange) { final CharRange r = ranges.get(ranges.size() - 1); r.end = '-'; if (r.end < r.start) { throw new MatchingException("Invalid character range: " + r); } inRange = false; } else { assert !ranges.isEmpty(); inRange = true; } break; default: if (inRange) { final CharRange r = ranges.get(ranges.size() - 1); r.end = (char)ch; if (r.end < r.start) { throw new MatchingException("Invalid character range: " + r); } } else { ranges.add(new CharRange((char)ch, (char)ch)); } inRange = false; break; } first = false; } if (inRange) { ranges.add(new CharRange('-', '-')); } this.tokens.addLast(new Token(negated, ranges)); } private void parseBackslash() throws MatchingException { final int ch = this.iterator.next(); if (ch < 0) { throw new MatchingException("Incomplete escape"); } this.tokens.addLast(new Token((char)ch)); } } private final String pattern; private final Matcher matcher; private final boolean caseInsensitive; /** * Constructs a glob matcher based on the specified pattern. * * @param pattern Glob pattern for matching * @throws MatchingException if there was a problem parsing the pattern */ Glob(final String pattern) throws MatchingException { this(pattern, false); } /** * Constructs a glob matcher based on the specified pattern. * * @param pattern Glob pattern for matching * @param caseInsensitive {@code true} if matches should be case-insensitive * @throws MatchingException if there was a problem parsing the pattern */ Glob(final String pattern, final boolean caseInsensitive) throws MatchingException { this.pattern = pattern; this.caseInsensitive = caseInsensitive; final Parser parser = new Parser(this.pattern); final List<Token> tokens = parser.parse(); Matcher m = literalMatcher(tokens); if (m == null) { m = regexMatcher(tokens); } this.matcher = m; } /** * Obtains the original glob pattern. * * @return Original glob pattern. */ String getPattern() { return this.pattern; } @AccessForTesting Matcher getMatcher() { return this.matcher; } /** * Indicates whether the specified path matches this glob pattern. * * @param path Path to be matched * @return {@code true} if the specified path matches this glob pattern. */ boolean matches(final Path path) { return this.matcher.matches(path); } /** * Creates a matcher based on the literal string generated from the specified tokens. * * @param tokens Parser tokens on which to base the matcher * @return Matcher based on the literal string generated from the specified tokens. If * any token does not represent a literal or if case-insensitive matching is specified, * this method will return {@code null}. */ @Nullable private Matcher literalMatcher(final List<Token> tokens) { if (this.caseInsensitive) { return null; } final StringBuilder buffer = new StringBuilder(); for (final Token token : tokens) { if (token.type != TokenType.Literal) { return null; } buffer.append(token.ch); } return buffer.isEmpty() ? null : new LiteralMatcher(buffer.toString()); } /** * Creates a matcher based on a regular expression generated from the specified tokens. * * @param tokens Parser tokens on which to base the matcher * @return Matcher based on the regular expression generated by the specified tokens * @throws MatchingException if there is a problem creating the matcher. */ private Matcher regexMatcher(final List<Token> tokens) throws MatchingException { final Pattern regex = tokensToRegex(tokens); return new RegexMatcher(regex); } /** * Generates a regular expression from the specified parser tokens. * * @param tokens Parser tokens from which to generate a regular expression * @return Regular expression based on the specified tokens * @throws MatchingException if there is a problem generating the regular expression */ private Pattern tokensToRegex(final List<Token> tokens) throws MatchingException { final StringBuilder buffer = new StringBuilder(); // Disable Unicode-aware case folding buffer.append("(?-u)"); if (this.caseInsensitive) { buffer.append("(?i)"); } buffer.append('^'); // If the entire glob is "**", match everything. if (tokens.size() == 1 && tokens.get(0).type == TokenType.RecursivePrefix) { buffer.append(".*$"); return Pattern.compile(buffer.toString()); } for (final Token token : tokens) { switch (token.type) { case Literal -> buffer.append(RegexUtils.escape(token.ch)); case Any -> buffer.append("[^/]"); case ZeroOrMore -> buffer.append("[^/]*"); case RecursivePrefix -> buffer.append("(?:/?|.*/)"); case RecursiveSuffix -> buffer.append("/.*"); case RecursiveZeroOrMore -> buffer.append("(?:/|/.*/)"); case CharClass -> { buffer.append('['); if (token.negated) { buffer.append('^'); } for (final CharRange range : token.ranges) { if (range.start == range.end) { buffer.append(RegexUtils.escapeCharClass(range.start)); } else { buffer.append(RegexUtils.escapeCharClass(range.start)) .append('-') .append(RegexUtils.escapeCharClass(range.end)); } } buffer.append(']'); } default -> { } } } buffer.append('$'); try { return Pattern.compile(buffer.toString()); } catch (final PatternSyntaxException ex) { throw new MatchingException("Could not create regular expression for pattern: " + this.pattern, ex); } } @Override public String toString() { return this.pattern; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return Objects.equals(this.pattern, ((Glob)obj).pattern); } @Override public int hashCode() { return Objects.hash(this.pattern); } }
from ..define import * from skyfield.api import load from astropy.time import Time from astropy.coordinates import SkyCoord, EarthLocation, AltAz, ICRS from astropy import units as u TS = load.timescale() # Loads skyfield timescale def RaDec2AzAlt(ra, dec): """ Utilitary method that transforms the input Right Ascension (RA) and Declination (Dec) coordinates to Azimuth (Az) and elevation (Alt) coordinates. AzAlt is computed taking into account the geolocation of VEGA, stored in global variables OBS_LAT, OBS_LON and OBS_HEIGHT. :param ra: Input RA coordinate in decimal hours :type ra: float :param dec: Input Dec coordinate in decimal degrees :type dec: float :return: Converted AzAlt coordinates :rtype: (float,float) """ obs_loc = EarthLocation( # lat=46.52457*u.deg, lon=6.61650*u.deg, height=500*u.m) lat=OBS_LAT*u.deg, lon=OBS_LON * u.deg, height=OBS_HEIGHT*u.m) time_now = Time.now() # + 2*u.hour Don't need to add the time difference coords = SkyCoord(ra*u.deg, dec*u.deg) altaz = coords.transform_to(AltAz(obstime=time_now, location=obs_loc)) az, alt = [float(x) for x in altaz.to_string( 'decimal', precision=4).split(' ')] return az, alt def AzAlt2RaDec(az, alt): """ Utilitary method that transforms the input Azimuth (Az) and Elevation (Alt) coordinates to Right Ascension (RA) and Declination (Dec) coordinates. AzAlt is computed taking into account the geolocation of VEGA, stored in global variables OBS_LAT, OBS_LON and OBS_HEIGHT. :param az: Input Az coordinate in decimal degrees :type az: float :param alt: Input Alt coordinate in decimal degrees :type alt: float :return: Converted RaDec coordinates :rtype: (float,float) """ obs_loc = EarthLocation( # lat=46.52457*u.deg, lon=6.61650*u.deg, height=500*u.m) lat=OBS_LAT*u.deg, lon=OBS_LON * u.deg, height=OBS_HEIGHT*u.m) time_now = Time.now() # + 2*u.hour Don't need to add the time difference altaz = AltAz(az=az*u.deg, alt=alt*u.deg, obstime=time_now, location=obs_loc) coords = SkyCoord(altaz.transform_to(ICRS())) ra, dec = [float(x) for x in coords.to_string( decimal=True, precision=4).split(' ')] return ra, dec def Gal2AzAlt(long, b): """ Utilitary method that transforms the input galactic longitude (long) and latitude (b) coordinates to Azimuth (Az) and elevation (Alt) coordinates. AzAlt is computed taking into account the geolocation of VEGA, stored in global variables OBS_LAT, OBS_LON and OBS_HEIGHT. :param long: Input long coordinate in decimal hours :type long: float :param b: Input b coordinate in decimal degrees :type b: float :return: Converted AzAlt coordinates :rtype: (float,float) """ obs_loc = EarthLocation( # lat=46.52457*u.deg, lon=6.61650*u.deg, height=500*u.m) lat=OBS_LAT*u.deg, lon=OBS_LON * u.deg, height=OBS_HEIGHT*u.m) time_now = Time.now() coords = SkyCoord(long*u.deg, b*u.deg) altazFrame = coords.transform_to(AltAz(obstime=time_now, location=obs_loc)) galactic_coords = SkyCoord( l=long*u.deg, b=b*u.deg, frame='galactic') azalt_coords = galactic_coords.transform_to(altazFrame) az, alt = [float(x) for x in azalt_coords.to_string( 'decimal', precision=4).split(' ')] return az, alt def AzAlt2Gal(az, alt): """ Utilitary method that transforms the input Azimuth (Az) and Elevation (Alt) coordinates to galactic longitude (long) and latitude (b) coordinates. AzAlt is computed taking into account the geolocation of VEGA, stored in global variables OBS_LAT, OBS_LON and OBS_HEIGHT. :param az: Input Az coordinate in decimal degrees :type az: float :param alt: Input Alt coordinate in decimal degrees :type alt: float :return: Converted galactic coordinates :rtype: (float,float) """ obs_loc = EarthLocation( # lat=46.52457*u.deg, lon=6.61650*u.deg, height=500*u.m) lat=OBS_LAT*u.deg, lon=OBS_LON * u.deg, height=OBS_HEIGHT*u.m) time_now = Time.now() altaz = AltAz(az=az*u.deg, alt=alt*u.deg, obstime=time_now, location=obs_loc) g = SkyCoord(0, 0, unit='rad', frame='galactic') coords = SkyCoord(altaz.transform_to(g)) long, b = [float(x) for x in coords.to_string( decimal=True, precision=4).split(' ')] return long, b def TLE2AzAlt(tle, delay=0): """Returns az and alt position of sat at current time given TLE :param tle: The target satellite TLE :type tle: ? TODO: find this :param delay: Delay in seconds to introduce in the TLE propagation in order to cope with the slew duration to the tracking path :type delay: float :return: The converted AzAlt coordinates :rtype: (float, float) """ t = TS.now() if delay != 0: t = t.utc t = TS.utc(t.year, t.month, t.day, t.hour, t.minute, t.second+delay) pos = (tle - TOPOS_LOC).at(t).altaz() return pos[1].degrees, pos[0].degrees
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApartmentService { apartments: Apartment[] = [ { id: 1, name: 'Luxury Beachfront Villa', address: '123 Ocean Drive', city: 'Miami', country: 'USA', description: 'A stunning villa with direct beach access and breathtaking ocean views.', reviews: 15, stars: 4.8, pricePerNight: 500, bookedDates: ['2024-05-10', '2024-05-15', '2024-05-20'], features: ['Pool', 'Free WiFi', 'Parking', 'Business Services'], photo: 'assets/Apartments/1.jpeg' }, { id: 2, name: 'Modern Downtown Loft', address: '456 Main Street', city: 'New York City', country: 'USA', description: 'Chic loft apartment in the heart of NYC with skyline views.', reviews: 10, stars: 4.5, pricePerNight: 300, bookedDates: ['2024-05-12', '2024-05-17', '2024-05-22'], features: ['Free WiFi', 'Parking'], photo: 'assets/Apartments/2.jpeg' }, { id: 3, name: 'Cozy Mountain Cabin', address: '789 Forest Avenue', city: 'Denver', country: 'USA', description: 'Escape to this charming cabin nestled in the Rocky Mountains.', reviews: 20, stars: 4.9, pricePerNight: 200, bookedDates: ['2024-05-11', '2024-05-16', '2024-05-21'], features: ['Mountain View', 'Fireplace', 'Pet Friendly'], photo: 'assets/Apartments/3.jpeg' }, { id: 4, name: 'Seaside Cottage Retreat', address: '321 Beach Road', city: 'Sydney', country: 'Australia', description: 'Tranquil cottage just steps away from the beach with panoramic ocean views.', reviews: 12, stars: 4.7, pricePerNight: 450, bookedDates: ['2024-05-13', '2024-05-18', '2024-05-23'], features: ['Beachfront', 'Balcony', 'Garden'], photo: 'assets/Apartments/4.jpeg' }, { id: 5, name: 'Urban Studio Apartment', address: '10 Elm Street', city: 'London', country: 'UK', description: 'Sleek and modern studio apartment in the heart of London.', reviews: 8, stars: 4.3, pricePerNight: 150, bookedDates: ['2024-05-14', '2024-05-19', '2024-05-24'], features: ['Central Location', 'Kitchenette'], photo: 'assets/Apartments/5.jpeg' }, { id: 6, name: 'Rustic Farmhouse Retreat', address: '567 Meadow Lane', city: 'Tuscany', country: 'Italy', description: 'Experience the charm of rural Tuscany in this cozy farmhouse.', reviews: 18, stars: 4.6, pricePerNight: 250, bookedDates: ['2024-05-15', '2024-05-20', '2024-05-25'], features: ['Countryside', 'Garden', 'Wine Tasting'], photo: 'assets/Apartments/6.jpeg' }, { id: 7, name: 'City View Penthouse', address: '789 Skyline Avenue', city: 'Tokyo', country: 'Japan', description: 'Luxurious penthouse with stunning views of Tokyo skyline.', reviews: 25, stars: 4.9, pricePerNight: 700, bookedDates: ['2024-05-16', '2024-05-21', '2024-05-26'], features: ['City View', 'Spa', 'Fitness Center'], photo: 'assets/Apartments/7.jpeg' }, { id: 8, name: 'Historic Mansion Stay', address: '101 Heritage Drive', city: 'Paris', country: 'France', description: 'Live like royalty in this elegant mansion located in the heart of Paris.', reviews: 30, stars: 5.0, pricePerNight: 1000, bookedDates: ['2024-05-17', '2024-05-22', '2024-05-27'], features: ['Historic', 'Gourmet Dining', 'Concierge Service'], photo: 'assets/Apartments/8.jpeg' }, { id: 9, name: 'Lakeside Retreat', address: '456 Lakefront Drive', city: 'Vancouver', country: 'Canada', description: 'Tranquil retreat overlooking a pristine lake surrounded by nature.', reviews: 15, stars: 4.8, pricePerNight: 400, bookedDates: ['2024-05-18', '2024-05-23', '2024-05-28'], features: ['Lake View', 'Hiking Trails', 'Kayaking'], photo: 'assets/Apartments/9.jpeg' }, { id: 10, name: 'Mountain Chalet Getaway', address: '789 Summit Avenue', city: 'Aspen', country: 'USA', description: 'Cozy chalet nestled in the Colorado Rockies, perfect for a ski getaway.', reviews: 22, stars: 4.7, pricePerNight: 350, bookedDates: ['2024-05-19', '2024-05-24', '2024-05-29'], features: ['Ski-in/Ski-out', 'Hot Tub', 'Fireplace'], photo: 'assets/Apartments/10.jpeg' } ]; private apiUrl = 'https://ketiketelauri123-001-site1.jtempurl.com/api/bookingRoomDetails/get/1'; constructor(private http: HttpClient) { } getApartments(): Apartment[] { return this.apartments } getRoomDetails(): Observable<any> { return this.http.get(this.apiUrl); } getApartmentsById(id: string | number | null | undefined): Apartment | undefined { let found = this.apartments.find((element) => element.id == id); // console.log('found apartmentebiii: ', found); return found; } getApartmentsByCountry(): { country: string, count: number }[] { const countryCountMap: { [key: string]: number } = {}; this.apartments.forEach(apartment => { countryCountMap[apartment.country] = (countryCountMap[apartment.country] || 0) + 1; }); const countryCountArray = Object.keys(countryCountMap).map(country => ({ country, count: countryCountMap[country] })); return countryCountArray.sort((a, b) => b.count - a.count).slice(0, 4); } } export interface Apartment { id: number; name: string; address: string; city: string; country: string; description: string; reviews: number; stars: number; pricePerNight: number; bookedDates: string[]; features: string[]; photo: string; }
import React, {useEffect} from 'react'; import {Route, Routes} from 'react-router-dom'; import {doc, getDoc, updateDoc, setDoc} from 'firebase/firestore'; import Main from "./Display/Main"; import Header from "./Header/Header"; import Posts from "./Posts/Posts"; import {useTelegram} from "./Hooks/useTelegram"; import {db} from "./firebase"; import './App.css'; import dayjs from "dayjs"; const App = () => { const {tg, user} = useTelegram(); useEffect(() => { tg.ready(); tg.expand(); }, [tg]); useEffect(() => { async function setUser() { if (user) { console.log('User object:', user); const userDocId = `user_${user.id}`; console.log('User document ID:', userDocId); try { const userDocRef = doc(db, "users", userDocId); console.log('User document reference:', userDocRef); const docSnap = await getDoc(userDocRef); console.log('Document snapshot:', docSnap); if (docSnap.exists()) { await updateDoc(userDocRef, { lastSignIn: dayjs().format("dddd, MMMM DD, YYYY [at] HH:mm"), }); console.log('User document updated'); } else { await setDoc(userDocRef, { applicationId: Date.now(), ...user }); console.log('New user document set'); } } catch (error) { console.error("Error updating/setting user document:", error); } } } setUser(); }, [user]); return ( <div className="container"> <Header/> {user ? ( <h5 style={{textAlign: "center", padding: 14}}> Hello {user.first_name} {user.last_name} - {user.username} </h5> ) : (<h5 style={{textAlign: "center", padding: 14}}> nookon </h5>) } <Routes> <Route index element={<Main/>}/> <Route path="/posts" element={<Posts/>}/> </Routes> </div> ); }; export default App;
<template> <div> <div class="modal-backdrop fade show"></div> <div class="modal fade show" id="chapterModal" tabindex="-1" aria-labelledby="chapterModalLabel"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <div class="modal-header"> <h3 class="modal-title h5" id="chapterModalConfigLabel">Chapitre</h3> <button type="button" class="btn-close" aria-label="fermeture" @click.prevent="closeModal"></button> </div> <div class="modal-body"> <div class="d-flex gap-2"> <div class="mb-3 flex-fill"> <label for="title" class="form-label required">Titre</label> <input type="text" class="form-control" id="title" v-model="title" :class="{ 'is-invalid': v$.title.$errors.length }"> <div class="invalid-feedback"> Ce champ est obligatoire et doit faire entre 2 et 255 caractères. </div> </div> <div class="mb-3"> <div for="color" class="form-label">Couleur</div> <color-picker format="hex" v-model:pureColor="color" disable-alpha lang="En"/> </div> </div> <div class="mb-3"> <label for="description" class="form-label">Description</label> <textarea class="form-control" id="description" rows="3" v-model="description" :class="{ 'is-invalid': v$.description.$errors.length }"></textarea> <div class="form-text">Donnez une courte description de moins de 1500 caractères.</div> <div class="invalid-feedback"> Ce champ doit faire entre 3 et 1500 caractères. </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary btn-sm" @click.prevent="closeModal"> <i class="fa-solid fa-xmark"></i> Annuler </button> <button type="button" class="btn btn-success btn-sm" @click.prevent="save"> <i class="fa-solid fa-spinner fa-spin" v-if="loading"></i> <i class="fa-solid fa-floppy-disk" v-else></i> Sauvegarder </button> </div> </div> </div> </div> </div> </template> <script> import { mapStores } from "pinia"; import { useSynopsisStore } from '&synopsis/stores/synopsis.js'; import { createToastify } from '&utils/toastify.js'; import { required, maxLength, minLength } from '@vuelidate/validators'; import { useVuelidate } from '@vuelidate/core' import { ColorPicker } from "vue3-colorpicker"; import "vue3-colorpicker/style.css"; export default { name: 'ChapterModal', components: { ColorPicker, }, props: { chapter: Object, }, data() { return { title: null, description: null, color: null, v$: useVuelidate(), loading: false, } }, computed: { ...mapStores(useSynopsisStore), }, validations () { return { title: { required, maxLength: maxLength(255), minLength: minLength(2) }, description: { maxLength: maxLength(1500), minLength: minLength(3) }, } }, mounted () { this.title = this.chapter.title; this.description = this.chapter.description; this.color = this.chapter.color; }, methods: { closeModal() { this.$emit('on-close'); }, async save() { this.loading = true; const result = await this.v$.$validate(); if (!result) { createToastify('Le formulaire comporte des erreurs.', 'error'); this.loading = false; return; } const data = { title: this.title, description: this.description, color: this.color }; let status; if (this.chapter.id === null) { status = await this.synopsisStore.postChapter(data); } else { status = await this.synopsisStore.putChapter(data, this.chapter.id); } if (!status) { createToastify('Le formulaire comporte des erreurs.', 'error'); this.loading = false; } else { this.closeModal(); } } }, } </script> <style scoped> #chapterModal { display: block; z-index: 3000; } </style>
import pandas as pd # Create a pandas series of the grocery items given in the list 'my_groceries' groceries = pd.Series(data=[30, 6, 'Yes', 'No'], index=['eggs', 'apples', 'milk', 'bread']) print (groceries) # We access elements in a Series in similar ways as we would in NumPy ndarrays. groceries['eggs'] print (groceries['eggs']) # We can also access multiple elements in a Series in similar ways as we would in NumPy ndarrays. groceries[['milk', 'bread']] print (groceries[['milk', 'bread']]) # We can use loc attribute to access elements in a Series. #groceries[0] #print (groceries[0]) # We can access multiple elements in a Series using loc attribute. groceries.loc[['eggs', 'apples']] print (groceries.loc[['eggs', 'apples']]) # We can also access elements in a Series using numerical indices. groceries.iloc[[2, 3]] print (groceries.iloc[[2, 3]]) # We can modify an existing element in a Series. groceries['eggs'] = 2 print (groceries['eggs']) # We can also delete items from a Series inplace without having to reassign the Series to a new variable. groceries.drop('apples') print (groceries.drop('apples'))
import axios from "axios"; class OscarRemoteData { constructor() { this.state = { loading: false, debug: false, error: "", datas: null, errorMessage: "", pendingMessage: "Chargement des données" } } /** * * @param pendingMessage * @returns {OscarRemoteData} */ setPendingMessage(pendingMessage) { this.state.pendingMessage = pendingMessage; return this; } setErrorMessage(errorMessage) { this.state.errorMessage = errorMessage; return this; } getAxiosInstance() { let instance = axios.create({}); instance.defaults.headers.common['X_REQUESTED_WITH'] = 'XMLHttpRequest'; return instance; } /** * Permet d'activer/désactiver le mode debug * @param bool */ setDebug(b) { this.state.debug = b; return this; } debug() { if (this.state.debug) { console.log.apply(this, arguments); } } performGet(url, handlerResponse = null, handlerError = null) { this.debug("[ORD] GET " + url); this.state.loading = true; this.getAxiosInstance().get(url) .then( response => { this.debug(" > response ", response); this.state.datas = response.data; if (handlerResponse) { handlerResponse(response); } else { this.debug(' > NO handerResponse given'); } }) .catch( error => { this.debug(" > error ", error); this.debug(error); this.state.error = error; if (handlerError) { handlerError(error); } else { this.debug(' > NO handlerError given'); } }) .finally(() => { this.state.loading = false; }) } performPost(url, datas, handlerResponse = null, handlerError = null) { this.state.loading = true; this.getAxiosInstance().post(url, datas) .then(response => { if (handlerResponse) { handlerResponse(response); } }) .catch(error => { this.debug("[ERROR] " + error); if (handlerError) { handlerError(error); } else { this.state.error = error; } }) .finally(() => { this.state.loading = false; }) } delete(url) { console.log("delete()", url) } update(url, datas) { console.log("update()", url, datas) } push(url, datas) { console.log("push()", url, datas) } } export default OscarRemoteData;
import flatpickr from 'flatpickr'; import 'flatpickr/dist/flatpickr.min.css'; import Notiflix from 'notiflix'; let date = null; let intervalId = null; const options = { enableTime: true, time_24hr: true, defaultDate: new Date(), minuteIncrement: 1, onClose: selectedDates => { date = selectedDates[0].getTime(); }, }; flatpickr('input#datetime-picker', options); const inputRef = document.querySelector('input#datetime-picker'); const startButtonRef = document.querySelector('button[data-start]'); const timerRefs = { days: document.querySelector('[data-days]'), hours: document.querySelector('[data-hours]'), minutes: document.querySelector('[data-minutes]'), seconds: document.querySelector('[data-seconds]'), }; const onTimerStart = function () { let startTime = Date.now(); if (date <= startTime) { Notiflix.Notify.failure('Please choose a date in the future'); return; } startButtonRef.disabled = true; inputRef.disabled = true; startButtonRef.removeEventListener('click', onTimerStart); const initialTime = convertMs(date - startTime); updateClock(initialTime); intervalId = setInterval(() => { let currentTime = Date.now(); let remainingTime = date - currentTime; if (remainingTime < 0) { clearInterval(intervalId); return; } const timeComponents = convertMs(remainingTime); updateClock(timeComponents); }, 1000); }; const addLeadingZero = function (value) { return String(value).padStart(2, '0'); }; const updateClock = function ({ days, hours, minutes, seconds }) { timerRefs.days.textContent = addLeadingZero(days); timerRefs.hours.textContent = addLeadingZero(hours); timerRefs.minutes.textContent = addLeadingZero(minutes); timerRefs.seconds.textContent = addLeadingZero(seconds); }; function convertMs(ms) { // Number of milliseconds per unit of time const second = 1000; const minute = second * 60; const hour = minute * 60; const day = hour * 24; // Remaining days const days = Math.floor(ms / day); // Remaining hours const hours = Math.floor((ms % day) / hour); // Remaining minutes const minutes = Math.floor(((ms % day) % hour) / minute); // Remaining seconds const seconds = Math.floor((((ms % day) % hour) % minute) / second); return { days, hours, minutes, seconds }; } startButtonRef.addEventListener('click', onTimerStart);
const API_KEY = process.env.EXPO_PUBLIC_API_KEY; import { MediaType, TrendingResult } from '@/interfaces/apiresults'; export const getTrending = async (): Promise<TrendingResult> => { const options = { method: 'GET', headers: { accept: 'application/json', Authorization: `Bearer ${API_KEY}` } }; console.log("🚀 ~ getTrending ~ API_KEY:", API_KEY) const response = await fetch( `https://api.themoviedb.org/3/trending/all/day?language=en-US&page=1`, options ); const json = await response.json(); return json; }; export const getSearchResults = async (query: string): Promise<TrendingResult> => { console.log('SEARCH: ', query); const options = { method: 'GET', headers: { accept: 'application/json', Authorization: `Bearer ${API_KEY}` } }; const response = await fetch( `https://api.themoviedb.org/3/search/multi?language=en-US&api_key=${API_KEY}&query=${encodeURIComponent( query )}`, options ); const data = await response.json(); return data; }; export const getMovieDetails = async (id: number, type: MediaType): Promise<any> => { const options = { method: 'GET', headers: { accept: 'application/json', Authorization: `Bearer ${API_KEY}` } } const response = await fetch( `https://api.themoviedb.org/3/${type}/${id}?language=en-US&api_key=${API_KEY}`, options ); const data = await response.json(); return data; };
from marshmallow import Schema, fields, base """ This module aims at providing the request and response format for the various api calls. This also helpful for creating swagger docs for apis testing. """ class UserMasterSchema(Schema): name = fields.String(required=True, default='name') username = fields.String(required=True, default='username') password = fields.String(required=True, default='password') is_admin = fields.Integer(required=True, default=0) class CreateQuizSchema(Schema): quiz_name = fields.String(required=True, default='quiz_name') question_ids = fields.List(fields.String()) class ViewQuizSchema(Schema): quiz_id = fields.String(required=True) class QuestionMasterSchema(Schema): question = fields.String(required=True) choice1 = fields.String(required=True) choice2 = fields.String(required=True) choice3 = fields.String(required=True) choice4 = fields.String(required=True) answer = fields.Integer(required=True) marks = fields.Integer(required=True) remarks = fields.String(required=True) class AssignQuizSchema(Schema): instance = fields.Dict(keys=fields.String(), values=fields.List(fields.String())) class UserResponseSchema(Schema): quiz_id = fields.String(required=True) responses = fields.List(fields.Dict(keys=fields.String(), values=fields.String())) class LoginSchema(Schema): username = fields.String(required=True) password = fields.String(required=True) class UnifiedAPIResponseSchema(Schema): message = fields.String(default="default responce message") class UnifiedViewResponseSchema(Schema): response = fields.List(fields.Dict(keys=fields.String(), values=fields.String()))
<style type='text/scss'> @mixin border-radius($radius){ -webkit-border-radius:$radius; -moz-border-radius:$radius; -ms-border-radius:$radius; border-radius:$radius; } #awesome { width: 150px; height: 150px; background-color: green; @include border-radius(15px); } </style> <div id="awesome"></div> ***************************************************************************************************** <style type='text/scss'> @mixin border-stroke($val){ @if $val==light{ border:1px solid black; } @else if $val==medium{ border:3px solid black; } @else if $val==heavy{ border:6px solid black; } @else{ border:none; } } #box { width: 150px; height: 150px; background-color: red; @include border-stroke(medium); } </style> <div id="box"></div> ****************************************************************************************** <style type='text/scss'> @for $j from 1 through 6{ .text-#{$j}{font-size:15px*$j; } } </style> <p class="text-1">Hello</p> <p class="text-2">Hello</p> <p class="text-3">Hello</p> <p class="text-4">Hello</p> <p class="text-5">Hello</p> ****************************************************************************************** <style type='text/scss'> @each $color in blue,black,red{ .#{$color}-bg {background-color:$color}; } div { height: 200px; width: 200px; } </style> <div class="blue-bg"></div> <div class="black-bg"></div> <div class="red-bg"></div> ********************************************************************************************* <style type='text/scss'> $x:1; @while $x<6{ .text-#{$x} {font-size:15px * $x;} $x:$x+1; } </style> <p class="text-1">Hello</p> <p class="text-2">Hello</p> <p class="text-3">Hello</p> <p class="text-4">Hello</p> <p class="text-5">Hello</p> ******************************************************************************************* <style type='text/scss'> h3{ text-align: center; } .info{ width: 200px; border: 1px solid black; margin: 0 auto; } .info-important{ @extend .info; background-color:magenta; } </style> <h3>Posts</h3> <div class="info-important"> <p>This is an important post. It should extend the class ".info" and have its own CSS styles.</p> </div> <div class="info"> <p>This is a simple post. It has basic styling and can be extended for other uses.</p> </div>
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <cuda.h> #define pi 3.14159265359 void load_image(char *fname, int Nx, int Ny, float *img) { FILE *fp; fp = fopen(fname, "r"); for (int i = 0; i < Ny; i++) { for (int j = 0; j < Nx; j++) fscanf(fp, "%f ", &img[i * Nx + j]); fscanf(fp, "\n"); } fclose(fp); } void save_image(char *fname, int Nx, int Ny, float *img) { FILE *fp; fp = fopen(fname, "w"); for (int i = 0; i < Ny; i++) { for (int j = 0; j < Nx; j++) fprintf(fp, "%10.3f ", img[i * Nx + j]); fprintf(fp, "\n"); } fclose(fp); } void calculate_kernel(int kernel_size, float sigma, float *kernel) { int Nk2 = kernel_size * kernel_size; float x, y, center; center = (kernel_size - 1) / 2.0; for (int i = 0; i < Nk2; i++) { x = (float)(i % kernel_size) - center; y = (float)(i / kernel_size) - center; kernel[i] = -(1.0 / pi * pow(sigma, 4)) * (1.0 - 0.5 * (x * x + y * y) / (sigma * sigma)) * exp(-0.5 * (x * x + y * y) / (sigma * sigma)); } } void conv_img_cpu(float *img, float *kernel, float *imgf, int Nx, int Ny, int kernel_size) { float sum = 0; int center = (kernel_size - 1) / 2; ; int ii, jj; for (int i = center; i < (Ny - center); i++) for (int j = center; j < (Nx - center); j++) { sum = 0; for (int ki = 0; ki < kernel_size; ki++) for (int kj = 0; kj < kernel_size; kj++) { ii = kj + j - center; jj = ki + i - center; sum += img[jj * Nx + ii] * kernel[ki * kernel_size + kj]; } imgf[i * Nx + j] = sum; } } __global__ void conv_img_gpu(float *img, float *kernel, float *imgf, int Nx, int Ny, int kernel_size,int offset) { int tid = threadIdx.x; int iy = blockIdx.x + (kernel_size - 1) / 2; int ix = threadIdx.x + (kernel_size - 1) / 2+offset; int idx = iy * Nx + ix; int K2 = kernel_size * kernel_size; int center = (kernel_size - 1) / 2; int ii, jj; float sum = 0.0; extern __shared__ float sdata[]; if (tid < K2) sdata[tid] = kernel[tid]; __syncthreads(); if (idx < Nx * Ny && ix<Nx) { for (int ki = 0; ki < kernel_size; ki++) for (int kj = 0; kj < kernel_size; kj++) { ii = kj + ix - center; jj = ki + iy - center; if(jj * Nx + ii < Nx*Ny) sum += img[jj * Nx + ii] * sdata[ki * kernel_size + kj]; } imgf[idx] = sum; } } __global__ void conv_img_gpu_f2(float *img, float *kernel, float *imgf, int Nx, int Ny, int kernel_size,int offset) { int iy = blockIdx.x + (kernel_size - 1) / 2; int ix = threadIdx.x + (kernel_size - 1) / 2+offset; int idx = iy * Nx + ix; int center = (kernel_size - 1) / 2; int ii, jj; float sum = 0.0; if (idx < Nx * Ny && ix < Nx) { for (int ki = 0; ki < kernel_size; ki++) for (int kj = 0; kj < kernel_size; kj++) { ii = kj + ix - center; jj = ki + iy - center; if(jj * Nx + ii < Nx*Ny) sum += img[jj * Nx + ii] * kernel[ki * kernel_size + kj]; } imgf[idx] = sum; } } int main(int argc, char *argv[]) { cudaEvent_t start, stop; clock_t t1, t2; double ms; float milliseconds = 0; int Nx, Ny; int kernel_size; float sigma; char finput[256], foutput[256], foutput_cpu[256]; int Nblocks, Nthreads; sprintf(finput, "2k.dat"); sprintf(foutput, "gpu_output.dat"); sprintf(foutput_cpu, "cpu_output.dat"); Nx = 2560; Ny = 1440; kernel_size = 3; sigma = 0.55; float *img, *imgf, *imgf_cpu, *kernel; img = (float *)malloc(Nx * Ny * sizeof(float)); imgf = (float *)malloc(Nx * Ny * sizeof(float)); imgf_cpu = (float *)malloc(Nx * Ny * sizeof(float)); kernel = (float *)malloc(kernel_size * kernel_size * sizeof(float)); //Cargamos la imagen y calculamos los valores del kennel segun el kernel_size load_image(finput, Nx, Ny, img); calculate_kernel(kernel_size, sigma, kernel); t1 = clock(); conv_img_cpu(img, kernel, imgf_cpu, Nx, Ny, kernel_size); t2 = clock(); ms = 1000.0 * (double)(t2 - t1) / CLOCKS_PER_SEC; printf("Tiempo (CPU): %f[ms]\n", ms); float *d_img, *d_imgf, *d_kernel; cudaMalloc(&d_img, Nx * Ny * sizeof(float)); cudaMalloc(&d_imgf, Nx * Ny * sizeof(float)); cudaMalloc(&d_kernel, kernel_size * kernel_size * sizeof(float)); cudaMemcpy(d_img, img, Nx * Ny * sizeof(float), cudaMemcpyHostToDevice); cudaMemcpy(d_kernel, kernel, kernel_size * kernel_size * sizeof(float), cudaMemcpyHostToDevice); cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start); int block_size = 256; int grid_size = (Ny - (kernel_size - 1)); for (int i = 0; i < (int)ceil((float)Nx / block_size); i++) { conv_img_gpu<<<grid_size, block_size, kernel_size * kernel_size * sizeof(float)>>>(d_img, d_kernel, d_imgf, Nx, Ny, kernel_size, i * block_size); } cudaDeviceSynchronize(); cudaEventRecord(stop); cudaEventSynchronize(stop); cudaEventElapsedTime(&milliseconds, start, stop); printf("Tiempo (GPU): %f ms\n", milliseconds); cudaMemcpy(imgf, d_imgf, Nx * Ny * sizeof(float), cudaMemcpyDeviceToHost); cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start); for (int i = 0; i < (int)ceil((float)Nx / block_size); i++) { conv_img_gpu_f2<<<grid_size, block_size, kernel_size * kernel_size * sizeof(float)>>>(d_img, d_kernel, d_imgf, Nx, Ny, kernel_size, i * block_size); } cudaDeviceSynchronize(); cudaEventRecord(stop); cudaEventSynchronize(stop); cudaEventElapsedTime(&milliseconds, start, stop); printf("Tiempo (GPU): %f ms\n", milliseconds); save_image(foutput, Nx, Ny, imgf); save_image(foutput_cpu, Nx, Ny, imgf_cpu); free(img); free(imgf); free(kernel); cudaFree(d_img); cudaFree(d_imgf); cudaFree(d_kernel); }
class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :posts, dependent: :destroy has_many :comments, dependent: :destroy def self.guest find_or_create_by!(email: 'guest@example.com') do |user| user.password = SecureRandom.urlsafe_base64 # user.confirmed_at = Time.now # Confirmable を使用している場合は必要 end end end
import { ClusterFlavorResp } from './ClusterFlavorResp'; import { CompatibleConfigurationResp } from './CompatibleConfigurationResp'; import { CompatibleDataStoreResp } from './CompatibleDataStoreResp'; import { CompatibleFaultResp } from './CompatibleFaultResp'; import { CompatibleInstanceVolumeResp } from './CompatibleInstanceVolumeResp'; import { CompatibleReplicasResp } from './CompatibleReplicasResp'; import { LinkResp } from './LinkResp'; import { SdkResponse } from "@huaweicloud/huaweicloud-sdk-core/SdkResponse"; export class ShowInstanceResponse extends SdkResponse { private 'configuration_status'?: string; private 'params_group_id'?: string; public type?: string; private 'subnet_id'?: string; public role?: string; private 'internal_subnet_id'?: string; public group?: string; private 'secure_group'?: string; public vpc?: string; public azcode?: string; public region?: string; private 'cluster_id'?: string; public created?: string; public updated?: string; public status?: string; public name?: string; public links?: Array<LinkResp>; public id?: string; public flavor?: ClusterFlavorResp; public volume?: CompatibleInstanceVolumeResp; public datastore?: CompatibleDataStoreResp; public fault?: CompatibleFaultResp; public configuration?: CompatibleConfigurationResp; public locality?: string; public replicas?: Array<CompatibleReplicasResp>; private 'db_user'?: string; private 'storage_engine'?: string; private 'pay_model'?: number; private 'public_ip'?: string; private 'traffic_ip'?: string; public constructor() { super(); } public withConfigurationStatus(configurationStatus: string): ShowInstanceResponse { this['configuration_status'] = configurationStatus; return this; } public set configurationStatus(configurationStatus: string | undefined) { this['configuration_status'] = configurationStatus; } public get configurationStatus(): string | undefined { return this['configuration_status']; } public withParamsGroupId(paramsGroupId: string): ShowInstanceResponse { this['params_group_id'] = paramsGroupId; return this; } public set paramsGroupId(paramsGroupId: string | undefined) { this['params_group_id'] = paramsGroupId; } public get paramsGroupId(): string | undefined { return this['params_group_id']; } public withType(type: string): ShowInstanceResponse { this['type'] = type; return this; } public withSubnetId(subnetId: string): ShowInstanceResponse { this['subnet_id'] = subnetId; return this; } public set subnetId(subnetId: string | undefined) { this['subnet_id'] = subnetId; } public get subnetId(): string | undefined { return this['subnet_id']; } public withRole(role: string): ShowInstanceResponse { this['role'] = role; return this; } public withInternalSubnetId(internalSubnetId: string): ShowInstanceResponse { this['internal_subnet_id'] = internalSubnetId; return this; } public set internalSubnetId(internalSubnetId: string | undefined) { this['internal_subnet_id'] = internalSubnetId; } public get internalSubnetId(): string | undefined { return this['internal_subnet_id']; } public withGroup(group: string): ShowInstanceResponse { this['group'] = group; return this; } public withSecureGroup(secureGroup: string): ShowInstanceResponse { this['secure_group'] = secureGroup; return this; } public set secureGroup(secureGroup: string | undefined) { this['secure_group'] = secureGroup; } public get secureGroup(): string | undefined { return this['secure_group']; } public withVpc(vpc: string): ShowInstanceResponse { this['vpc'] = vpc; return this; } public withAzcode(azcode: string): ShowInstanceResponse { this['azcode'] = azcode; return this; } public withRegion(region: string): ShowInstanceResponse { this['region'] = region; return this; } public withClusterId(clusterId: string): ShowInstanceResponse { this['cluster_id'] = clusterId; return this; } public set clusterId(clusterId: string | undefined) { this['cluster_id'] = clusterId; } public get clusterId(): string | undefined { return this['cluster_id']; } public withCreated(created: string): ShowInstanceResponse { this['created'] = created; return this; } public withUpdated(updated: string): ShowInstanceResponse { this['updated'] = updated; return this; } public withStatus(status: string): ShowInstanceResponse { this['status'] = status; return this; } public withName(name: string): ShowInstanceResponse { this['name'] = name; return this; } public withLinks(links: Array<LinkResp>): ShowInstanceResponse { this['links'] = links; return this; } public withId(id: string): ShowInstanceResponse { this['id'] = id; return this; } public withFlavor(flavor: ClusterFlavorResp): ShowInstanceResponse { this['flavor'] = flavor; return this; } public withVolume(volume: CompatibleInstanceVolumeResp): ShowInstanceResponse { this['volume'] = volume; return this; } public withDatastore(datastore: CompatibleDataStoreResp): ShowInstanceResponse { this['datastore'] = datastore; return this; } public withFault(fault: CompatibleFaultResp): ShowInstanceResponse { this['fault'] = fault; return this; } public withConfiguration(configuration: CompatibleConfigurationResp): ShowInstanceResponse { this['configuration'] = configuration; return this; } public withLocality(locality: string): ShowInstanceResponse { this['locality'] = locality; return this; } public withReplicas(replicas: Array<CompatibleReplicasResp>): ShowInstanceResponse { this['replicas'] = replicas; return this; } public withDbUser(dbUser: string): ShowInstanceResponse { this['db_user'] = dbUser; return this; } public set dbUser(dbUser: string | undefined) { this['db_user'] = dbUser; } public get dbUser(): string | undefined { return this['db_user']; } public withStorageEngine(storageEngine: string): ShowInstanceResponse { this['storage_engine'] = storageEngine; return this; } public set storageEngine(storageEngine: string | undefined) { this['storage_engine'] = storageEngine; } public get storageEngine(): string | undefined { return this['storage_engine']; } public withPayModel(payModel: number): ShowInstanceResponse { this['pay_model'] = payModel; return this; } public set payModel(payModel: number | undefined) { this['pay_model'] = payModel; } public get payModel(): number | undefined { return this['pay_model']; } public withPublicIp(publicIp: string): ShowInstanceResponse { this['public_ip'] = publicIp; return this; } public set publicIp(publicIp: string | undefined) { this['public_ip'] = publicIp; } public get publicIp(): string | undefined { return this['public_ip']; } public withTrafficIp(trafficIp: string): ShowInstanceResponse { this['traffic_ip'] = trafficIp; return this; } public set trafficIp(trafficIp: string | undefined) { this['traffic_ip'] = trafficIp; } public get trafficIp(): string | undefined { return this['traffic_ip']; } }
package com.example.democompose.utils.network /** * state for processing api response Loading, Success and Error */ sealed class DataState<out R> { class Success<out T>(val data: T) : DataState<T>() class Error(val exception: Exception) : DataState<Nothing>() object Loading : DataState<Nothing>() }
package token type TokenType string type Token struct { Type TokenType Literal string } const ( ILLEGAL = "ILLEGAL" EOF = "EOF" // Identifiers + literals IDENT = "IDENT" // add, foobar, x, y, ... INT = "INT" // 1343456 // Delimiters COMMA = "," SEMICOLON = ";" LPAREN = "(" RPAREN = ")" LBRACE = "{" RBRACE = "}" // Keywords FUNCTION = "FUNCTION" LET = "LET" IF = "if" ELSE = "else" RETURN = "return" TRUE = "true" FALSE = "false" // Operators ASSIGN = "=" PLUS = "+" MINUS = "-" BANG = "!" ASTERISK = "*" SLASH = "/" LT = "<" GT = ">" EQ = "==" NOT_EQ = "!=" ) var keywords = map[string]TokenType{ "fn": FUNCTION, "let": LET, "if": IF, "else": ELSE, "return": RETURN, "true": TRUE, "false": FALSE, } func LookupIdent(ident string) TokenType { if tt, ok := keywords[ident]; ok { return tt } return IDENT }
/******************************************************************************* * Copyright 2014 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * 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 de.tudarmstadt.ukp.dkpro.tc.features.length; import java.util.ArrayList; import java.util.List; import org.apache.uima.fit.descriptor.TypeCapability; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import de.tudarmstadt.ukp.dkpro.tc.api.exception.TextClassificationException; import de.tudarmstadt.ukp.dkpro.tc.api.features.DocumentFeatureExtractor; import de.tudarmstadt.ukp.dkpro.tc.api.features.Feature; import de.tudarmstadt.ukp.dkpro.tc.api.features.FeatureExtractorResource_ImplBase; /** * Extracts the number of tokens */ @TypeCapability(inputs = { "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token" }) public class NrOfTokensDFE extends FeatureExtractorResource_ImplBase implements DocumentFeatureExtractor { /** * Public name of the feature "number of tokens" */ public static final String FN_NR_OF_TOKENS = "NrofTokens"; @Override public List<Feature> extract(JCas jcas) throws TextClassificationException { List<Feature> featList = new ArrayList<Feature>(); double numTokens = JCasUtil.select(jcas, Token.class).size(); featList.add(new Feature(FN_NR_OF_TOKENS, numTokens)); return featList; } }
import { useEffect, useState } from "react"; import "./css/cart.css"; import Button from "@mui/material/Button"; import { useDispatch, useSelector } from "react-redux"; import { cart_get, cart_total, cart_update } from "../Redux/Cart/action"; import Box from "@mui/material/Box"; import { Navigate, useNavigate } from "react-router-dom"; import { ToastContainer, toast } from "react-toastify"; export const Cart = () => { const [cart, setCart] = useState([]); let sum = 0, cnt = 0; const navigate = useNavigate(); const dispatch = useDispatch(); const getData = () => { fetch(`https://ecom-app-herok.herokuapp.com/cart`) .then((res) => res.json()) .then((res) => setCart(res)) .catch((err) => console.log(err)); }; cart.forEach((E) => { sum = sum + E.price; cnt++; }); useEffect(() => { getData(); dispatch(cart_update(cnt, Math.floor(sum))); }, [sum, cnt]); const state = useSelector((state) => state.cart); console.log("The state is", state); const handleremove = (e) => { let id = e.target.id; fetch(`https://ecom-app-herok.herokuapp.com/cart/${id}`, { method: "DELETE", }) .then((res) => { toast.success("Delete Item Succesfully"); window.location.reload(); }) .catch((err) => { console.log(err); }); }; const checkOut = () => { // alert("Welcome to the checkout page"); navigate("/payment"); }; return ( <div id="cart_container"> <div id="cart_info"> {cart.map((e) => ( <> <div className="prod_info" key={e.id}> <div> <img src={e.image} alt="" /> </div> <div> <h4>Title:{e.title}</h4> <p>Description:{e.description}</p> <p>Price:{e.price}₹</p> <Button variant="contained" color="secondary" id={e._id} onClick={handleremove} > DELETE </Button> </div> </div> </> ))} </div> <div id="cart_total"> <div> {cart.map((e) => ( <> <div className="cart_div"> <div> <img width={"15%"} height={"50%"} src={e.image} alt="" /> </div> <div> <h5>Title : {e.title}</h5> <h3>Price :{e.price}</h3> </div> <hr /> </div> </> ))} <hr /> <div className="value"> <h5>Item:{cnt}</h5> <h5>Total Price:{Math.ceil(sum)}</h5> </div> <Box sx={{ margin: 2, borderRadius: 450, width: 250, height: 100, }} > <Button variant="contained" color="secondary" onClick={checkOut}> Proceed To Payment </Button> </Box> </div> </div> </div> ); };
import { PrismaAdapter } from "@next-auth/prisma-adapter"; import { User as PrismaUser } from "@prisma/client"; import NextAuth, { type NextAuthOptions, DefaultSession } from "next-auth"; import DiscordProvider from "next-auth/providers/discord"; import { env } from "../../../env/server.mjs"; import { prisma } from "../../../server/db"; export const authOptions: NextAuthOptions = { // Include user.id on session callbacks: { session({ session, user }) { if (session.user) { session.user.id = user.id; session.user.discordId = user.discordId; } return session; }, jwt({ token, user, account, profile, isNewUser }) { console.log(token, user, account, profile, isNewUser, " In jwt"); return token; }, redirect({ url, baseUrl }) { return baseUrl; }, }, // Configure one or more authentication providers adapter: PrismaAdapter(prisma), providers: [ DiscordProvider({ clientId: env.DISCORD_CLIENT_ID, clientSecret: env.DISCORD_CLIENT_SECRET, profile(profile) { if (profile.avatar === null) { const defaultAvatarNumber = parseInt(profile.discriminator) % 5; profile.image_url = `https://cdn.discordapp.com/embed/avatars/${defaultAvatarNumber}.png`; } else { const format = profile.avatar.startsWith("a_") ? "gif" : "png"; profile.image_url = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`; } return { id: profile.id, discordId: profile.id, name: profile.username, email: profile.email, image: profile.image_url, verified: profile.verified, }; }, }), ], events: { createUser: async (message) => { const existingUser = await prisma.internalUser.findUnique({ where: { discordId: message.user.discordId, }, }); if (!existingUser) await prisma.internalUser.create({ data: { discordId: message.user.discordId, name: message.user.name, collections: { create: { name: "All Saved", }, }, }, }); }, }, }; export default NextAuth(authOptions); declare module "next-auth" { interface User extends Partial<PrismaUser> { discordId: string; } interface Session extends DefaultSession { user?: { id: string; name?: string | null; email?: string | null; image?: string | null; discordId: string; }; } }
<?php namespace App\Controller; use App\Controller\AppController; /** * Repeats Controller * * @property \App\Model\Table\RepeatsTable $Repeats * * @method \App\Model\Entity\Repeat[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = []) */ class RepeatsController extends AppController { /** * Index method * * @return \Cake\Http\Response|null */ public function index() { $repeats = $this->paginate($this->Repeats); $this->set(compact('repeats')); } /** * View method * * @param string|null $id Repeat id. * @return \Cake\Http\Response|null * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function view($id = null) { $repeat = $this->Repeats->get($id, [ 'contain' => [] ]); $this->set('repeat', $repeat); } /** * Add method * * @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise. */ public function add() { $repeat = $this->Repeats->newEntity(); if ($this->request->is('post')) { $repeat = $this->Repeats->patchEntity($repeat, $this->request->getData()); if ($this->Repeats->save($repeat)) { $this->Flash->success(__('The repeat has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The repeat could not be saved. Please, try again.')); } $this->set(compact('repeat')); } /** * Edit method * * @param string|null $id Repeat id. * @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function edit($id = null) { $repeat = $this->Repeats->get($id, [ 'contain' => [] ]); if ($this->request->is(['patch', 'post', 'put'])) { $repeat = $this->Repeats->patchEntity($repeat, $this->request->getData()); if ($this->Repeats->save($repeat)) { $this->Flash->success(__('The repeat has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The repeat could not be saved. Please, try again.')); } $this->set(compact('repeat')); } /** * Delete method * * @param string|null $id Repeat id. * @return \Cake\Http\Response|null Redirects to index. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $repeat = $this->Repeats->get($id); if ($this->Repeats->delete($repeat)) { $this->Flash->success(__('The repeat has been deleted.')); } else { $this->Flash->error(__('The repeat could not be deleted. Please, try again.')); } return $this->redirect(['action' => 'index']); } }
package org.djunits.value; import org.djunits.unit.AbsoluteLinearUnit; import org.djunits.unit.Unit; /** * Absolute values are quantities that are measured from some agreed upon reference point. Absolute types always have an * associated Relative type, indicated by the interface AbsWithRel. Values are Absolute when the sum of two values makes no * sense, but the difference does (but results in a Relative). * <p> * Copyright (c) 2015-2023 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br> * BSD-style license. See <a href="https://djunits.org/docs/license.html">DJUNITS License</a>. * <p> * @author <a href="https://www.tudelft.nl/averbraeck">Alexander Verbraeck</a> * @author <a href="https://www.tudelft.nl/staff/p.knoppers/">Peter Knoppers</a> * @param <AU> the absolute unit type * @param <A> the absolute value type * @param <RU> the relative unit type * @param <R> the relative value type */ public interface Absolute<AU extends AbsoluteLinearUnit<AU, RU>, A extends Absolute<AU, A, RU, R>, RU extends Unit<RU>, R extends RelWithAbs<AU, A, RU, R>> { /** * Add a Relative value to this Absolute value. A new value is returned due to immutability. * @param rel R; R the right operand * @return A; the sum of this value and the operand */ A plus(R rel); /** * Subtract a Relative value from this Absolute value. A new value is returned due to immutability. * @param rel R; R the right operand * @return A; the subtraction of this value and the operand */ A minus(R rel); /** * Subtract an Absolute value from this Absolute value, resulting in a Relative value. A new value is returned due to * immutability. * @param abs A; A the right operand * @return R; the subtraction of this value and the operand */ R minus(A abs); }
using System; using System.Linq; using Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace FastTests.Issues { public class RavenDB_10583 : RavenTestBase { public RavenDB_10583(ITestOutputHelper output) : base(output) { } private class Article { public ArticleEnum Value { get; set; } } private enum ArticleEnum { Value1, Value2, Value3 } [RavenTheory(RavenTestCategory.Querying)] [RavenData(SearchEngineMode = RavenSearchEngineMode.All, DatabaseMode = RavenDatabaseMode.All)] public void TranslateEnumAsString(Options options) { options.ModifyDocumentStore = a => a.Conventions.SaveEnumsAsIntegers = false; using (var store = GetDocumentStore(options)) { using (var session = store.OpenSession()) { session.Store(new Article { Value = ArticleEnum.Value1 }); session.SaveChanges(); } using (var session = store.OpenSession()) { var query = from x in session.Query<Article>() let test = x.Value == ArticleEnum.Value1 select new { ShouldBeTrue = test }; var expectedQuery = $"declare function output(x) {{{Environment.NewLine}\tvar test = x.Value===\"Value1\";{Environment.NewLine}\treturn {{ ShouldBeTrue : test }};{Environment.NewLine}}}{Environment.NewLine}from 'Articles' as x select output(x)"; Assert.Equal(expectedQuery, query.ToString()); var result = query.ToList(); Assert.Equal(true, result[0].ShouldBeTrue); } } } [RavenTheory(RavenTestCategory.Querying)] [RavenData(SearchEngineMode = RavenSearchEngineMode.All, DatabaseMode = RavenDatabaseMode.All)] public void TranslateEnumAsInteger(Options options) { options.ModifyDocumentStore = a => a.Conventions.SaveEnumsAsIntegers = true; using (var store = GetDocumentStore(options)) { using (var session = store.OpenSession()) { session.Store(new Article { Value = ArticleEnum.Value1 }); session.SaveChanges(); } using (var session = store.OpenSession()) { var query = from x in session.Query<Article>() let test = x.Value == ArticleEnum.Value1 select new { ShouldBeTrue = test }; var expectedQuery = $"declare function output(x) {{{Environment.NewLine}\tvar test = x.Value===0;{Environment.NewLine}\treturn {{ ShouldBeTrue : test }};{Environment.NewLine}}}{Environment.NewLine}from 'Articles' as x select output(x)"; Assert.Equal(expectedQuery, query.ToString()); var result = query.ToList(); Assert.Equal(true, result[0].ShouldBeTrue); } } } } }
import { Button, TextField } from '@mui/material' import { Modal } from 'react-bootstrap' import React, { useState } from 'react' function Passwordchange(props) { const[input,setInput]=useState(""); function handlechange(e) { setInput(e.target.value) } async function changePassword() { try { let resp=await fetch('/changePasswordByAdmin',{ method:"POST", headers:{ "Content-Type":"application/json" }, body:JSON.stringify({ user:props.id, newpassword:input }) }) if(resp.status==200) { alert("New password updated.") } if(resp.status==400) { alert("Unable to update new password") } } catch (error) { alert('Unable to update New password') } } return ( <div> <Modal show={props.show} handleClose={props.handleClose}> <Modal.Header > <Modal.Title>Update password</Modal.Title> </Modal.Header> <Modal.Body> <div> <h5>User ID: {props.id}</h5> <h5>Name: {props.name}</h5> </div> <div> <TextField value={input} onChange={handlechange} fullWidth size='small' helperText="New password"/> </div> <Button variant='contained' className='mt-3' onClick={changePassword}>SUBMIT</Button> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={props.handleClose}> Close </Button> </Modal.Footer> </Modal> </div> ) } export default Passwordchange
package aws_sdk.budgets; typedef TimePeriod = { /** The start date for a budget. If you created your budget and didn't specify a start date, AWS defaults to the start of your chosen time period (DAILY, MONTHLY, QUARTERLY, or ANNUALLY). For example, if you created your budget on January 24, 2018, chose DAILY, and didn't set a start date, AWS set your start date to 01/24/18 00:00 UTC. If you chose MONTHLY, AWS set your start date to 01/01/18 00:00 UTC. The defaults are the same for the AWS Billing and Cost Management console and the API. You can change your start date with the UpdateBudget operation. **/ @:optional var Start : js.lib.Date; /** The end date for a budget. If you didn't specify an end date, AWS set your end date to 06/15/87 00:00 UTC. The defaults are the same for the AWS Billing and Cost Management console and the API. After the end date, AWS deletes the budget and all associated notifications and subscribers. You can change your end date with the UpdateBudget operation. **/ @:optional var End : js.lib.Date; };
import 'package:delivery_agent_white_label/app/shared/utilities.dart'; import 'package:flutter/material.dart'; import 'package:flutter_modular/flutter_modular.dart'; import 'package:google_fonts/google_fonts.dart'; import '../payment_store.dart'; class CreditCard extends StatelessWidget { final PaymentStore store = Modular.get(); final double? width; CreditCard({Key? key, this.width}) : super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: () => Modular.to.pushNamed('/payment/card-details'), child: Container( height: wXD(144, context), width: width ?? wXD(212, context), margin: EdgeInsets.symmetric(horizontal: wXD(6, context)), padding: EdgeInsets.fromLTRB( wXD(18, context), wXD(14, context), wXD(19, context), wXD(20, context), ), decoration: const BoxDecoration( // border: Border.all(color: getColors(context).onBackground.withOpacity(.7)), gradient: LinearGradient( colors: [Color(0xffFAB1A0), Color(0xffE27A62)], begin: Alignment.centerLeft, end: Alignment.centerRight, ), borderRadius: BorderRadius.all(Radius.circular(3)), boxShadow: [ BoxShadow( offset: Offset(0, 4), color: Color(0x15000000), blurRadius: 4) ], ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Row( children: [ Stack( children: [ SizedBox(width: wXD(40, context), height: wXD(25, context)), Positioned( left: 0, child: Container( height: wXD(25, context), width: wXD(25, context), decoration: const BoxDecoration( shape: BoxShape.circle, color: Color(0xffEA1D25), ), ), ), Positioned( right: 0, child: Container( height: wXD(25, context), width: wXD(25, context), decoration: const BoxDecoration( shape: BoxShape.circle, color: Color(0xffF69E1E), ), ), ), ], ), const Spacer(), Text( '00/00', style: GoogleFonts.rubik( fontSize: 11, color: const Color(0xffE27A62)), ), ], ), const Spacer(), Row( children: [ Text( 'Lorem ipsum', style: GoogleFonts.inter( fontSize: 13, color: getColors(context).onSurface), ), const Spacer(), Text( '• • • • 0000', style: GoogleFonts.rubik( fontSize: 11, color: getColors(context).onSurface), ), ], ) ], ), ), ); } }
import React from 'react' import s from './RadioInput.module.css' type Props = { name: string value: string checked: boolean isLoading: boolean onChange: any label: string } class RadioInput extends React.PureComponent<Props> { render() { return ( <label className={ this.props.isLoading ? `${s.container} ${s.loadingState}` : s.container } > <input type="radio" name={this.props.name} value={this.props.value} checked={this.props.checked} disabled={this.props.isLoading} onChange={this.props.onChange} required className={s.input} /> {this.props.label} </label> ) } } export default RadioInput
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class DeskStoreRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> */ public function rules(): array { return [ 'name' => 'required|max:255|unique:desks,name,'//. $this->desk->id ]; } public function messages(): array { return [ 'name.unique' => 'Это название доски уже занято', ]; } }
import React from 'react'; import { Link, useNavigate } from 'react-router-dom'; import { useDispatch } from 'react-redux'; import { RegisterInput } from '../components/Input'; import Logo from '../assets/images/Logo.svg'; import IllustrationFlip from '../assets/images/Illustration-flip.svg'; import { asyncRegisterUser } from '../states/users/action'; export default function RegisterPage() { const navigate = useNavigate(); const dispatch = useDispatch(); const onRegister = ({ name, email, password }) => { // Regular expression to validate email format const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (name === '') { alert('Name cannot be empty'); return; } if (!emailRegex.test(email)) { alert('Please enter a valid email address.'); return; } if (password.length < 6) { alert('Password must be at least 6 characters long.'); return; } dispatch(asyncRegisterUser({ name, email, password })); navigate('/'); }; return ( <div className="flex items-center h-screen"> <div className="flex flex-col items-center flex-1"> <div> <div className="flex flex-col gap-2"> <h1 className="text-4xl font-bold tracking-wider text-yankeesBlue">Create an Account</h1> <p className="text-sonicSilver">Please register for an account first</p> </div> <RegisterInput register={onRegister} /> <p className="text-sonicSilver"> Have an account? {' '} <Link to="/" className="font-semibold cursor-pointer text-outerSpace hover:underline">Login</Link> </p> </div> </div> <div className="flex-1 hidden h-screen p-5 lg:block bg-yankeesBlue"> <div className="flex justify-end"> <img src={Logo} className="p-3 " alt="Logo" /> </div> <div className="flex justify-center"> <img src={IllustrationFlip} alt="Illustration" /> </div> </div> </div> ); }
interface Component { operation(): string; } class ConcreteComponent implements Component { operation() { return "ConcreteComponent"; } } interface Decorator extends Component { setComponent(component: Component): void; } class ConcreteDecoratorA implements Decorator { private component: Component; setComponent(component: Component) { this.component = component; } operation() { return `ConcreteDecoratorA(${this.component.operation()})`; } } class ConcreteDecoratorB implements Decorator { private component: Component; setComponent(component: Component) { this.component = component; } operation() { return `ConcreteDecoratorB(${this.component.operation()})`; } } const component: Component = new ConcreteComponent(); const decoratorA: Decorator = new ConcreteDecoratorA(); const decoratorB: Decorator = new ConcreteDecoratorB(); decoratorA.setComponent(component); decoratorB.setComponent(decoratorA); const result: string = decoratorB.operation(); console.log(result);
import React, { Fragment, useEffect, useState } from "react" import ChangePasswordModal from "./ChangePasswordModal" import ChooseAvatarForm from "./ChooseAvatarForm" import SettingForm from "./SettingForm" interface SettingAccountModalProps { isOpen: boolean onClose: () => void } export const AccountModal = ({ isOpen, onClose }: SettingAccountModalProps) => { const [isChoosingAvatar, setIsChoosingAvatar] = useState(false) const [isChangingPassword, setIsChangingPassword] = useState(false) const [tempAvatar, setTempAvatar] = useState<Record<"id" | "imageUrl", string> | null>(null) useEffect(() => { if (isOpen) { setTempAvatar(null) } }, [isOpen]) useEffect(() => { if (!isOpen) { setIsChoosingAvatar(false) setIsChangingPassword(false) } }, [isOpen]) return ( <Fragment> <SettingForm isOpen={isOpen && !isChoosingAvatar && !isChangingPassword} onClose={onClose} onSetAvatar={() => setIsChoosingAvatar(true)} onChangePassword={() => setIsChangingPassword(true)} tempAvatar={tempAvatar} /> <ChooseAvatarForm isOpen={isChoosingAvatar} onClose={onClose} onBack={() => setIsChoosingAvatar(false)} onChangeAvatar={setTempAvatar} /> <ChangePasswordModal isOpen={isChangingPassword} onClose={onClose} onBack={() => setIsChangingPassword(false)} /> </Fragment> ) }
package com.algaworks.algafood.api.openapi.controller; import com.algaworks.algafood.api.exceptionhandler.Problem; import com.algaworks.algafood.api.model.ProdutoModel; import com.algaworks.algafood.api.model.input.ProdutoInput; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import java.util.List; @Api(tags = "Produtos") public interface RestauranteProdutoControllerOpenApi { @ApiOperation("Lista os produtos de um restaurante") @ApiResponses({ @ApiResponse(responseCode = "400", description = "Associação realizada com sucesso"), @ApiResponse(responseCode = "404", description = "Restaurante não encontrado", content = @Content(schema = @Schema(implementation = Problem.class))) }) List<ProdutoModel> listar(@ApiParam(value = "ID do restaurante", example = "1", required = true) Long restauranteId, @ApiParam(value = "Indica se deve ou não incluir produtos inativos no resultado da listagem", example = "false", defaultValue = "false") boolean incluirInativos); @ApiOperation("Busca um produto de um restaurante") @ApiResponses({ @ApiResponse(responseCode = "400", description = "ID do restaurante inváldio", content = @Content(schema = @Schema(implementation = Problem.class))), @ApiResponse(responseCode = "404", description = "Produto de restaurante não encontrado", content = @Content(schema = @Schema(implementation = Problem.class))) }) ProdutoModel buscar(@ApiParam(value = "ID do restaurante", example = "1", required = true) Long restauranteId, @ApiParam(value = "ID do produto", example = "1", required = true) Long produtoId); @ApiOperation("Cadastra um produto de um restaurante") @ApiResponses({ @ApiResponse(responseCode = "201", description = "Produto cadastrado"), @ApiResponse(responseCode = "404", description = "Produto de restaurante não encontrado", content = @Content(schema = @Schema(implementation = Problem.class))) }) ProdutoModel adicionar(@ApiParam(value = "ID do restaurante", example = "1", required = true) Long restauranteId, @ApiParam(name = "Corpo", value = "Representação do novo produto", required = true) ProdutoInput produtoInput); @ApiOperation("Atualiza um produto de um restaurante") @ApiResponses({ @ApiResponse(responseCode = "200", description = "Produto atualizado", content = @Content(schema = @Schema(implementation = Problem.class))), @ApiResponse(responseCode = "404", description = "Produto de restaurante não encontrado", content = @Content(schema = @Schema(implementation = Problem.class))) }) ProdutoModel atualizar(@ApiParam(value = "ID do restaurante", example = "1", required = true) Long restauranteId, @ApiParam(value = "ID do produto", example = "1", required = true) Long produtoId, @ApiParam(name = "Corpo", value = "Representação de um produto com novos dados", required = true) ProdutoInput produtoInput); }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSeoproperties extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('seoproperties', function (Blueprint $table) { $table->id(); $table->enum('pageName',['home', 'resume', 'projects','contact']); $table->string('title',50); $table->string('keywords',500); $table->string('description',500); $table->string('ogSiteName',100); $table->string('ogUrl',100); $table->string('ogTitle',100); $table->string('ogDescription',500); $table->string('ogImage',100); $table->timestamp('created_at')->useCurrent(); $table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('seoproperties'); } }
# Traffic meter demo **NB**: The demo optionally uses **YOLOV8** model which takes up to **10-15 minutes** to compile to TensorRT engine. The first launch may take a decent time. The pipeline detects when people cross a user-configured line and the direction of the crossing. The crossing events are attached to individual tracks, counted for each source separately and the counters are displayed on the frame. The crossing events are also stored with Graphite and displayed on a Grafana dashboard. Pedestrians preview: ![](assets/traffic-meter-loop.webp) Vehicles preview: ![](assets/road-traffic-loop.webp) Article on Medium: [Link](https://blog.savant-ai.io/efficient-city-traffic-metering-with-peoplenet-yolov8-savant-and-grafana-at-scale-d6f162afe883?source=friends_link&sk=ab96c5ef3c173902559f213849dede9b) Tested on platforms: - Xavier NX, Xavier AGX; - Nvidia Turing, Ampere. Demonstrated operational modes: - real-time processing: RTSP streams (multiple sources at once); Demonstrated adapters: - Video loop adapter; - Always-ON RTSP sink adapter; **Note**: Ubuntu 22.04 runtime configuration [guide](../../docs/runtime-configuration.md) helps to configure the runtime to run Savant pipelines. Run the demo: ```bash git clone https://github.com/insight-platform/Savant.git cd Savant/samples/traffic_meter git lfs pull # if x86 ../../utils/check-environment-compatible && docker compose -f docker-compose.x86.yml up # if Jetson ../../utils/check-environment-compatible && docker compose -f docker-compose.l4t.yml up # open 'rtsp://127.0.0.1:554/stream' in your player # or visit 'http://127.0.0.1:888/stream/' (LL-HLS) # for pre-configured Grafana dashboard visit # http://127.0.0.1:3000/d/WM6WimE4z/entries-exits?orgId=1&refresh=5s # Ctrl+C to stop running the compose bundle # to get back to project root cd ../.. ``` To create a custom Grafana dashboard, sign in with `admin\admin` credentials. ## Switch detector model The sample includes an option to choose the model used for object detection. Choose between NVIDIA [peoplenet](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/tao/models/peoplenet) and YOLOv8 by changing the env variable in `.env` file: - `DETECTOR=peoplenet` for peoplnet - `DETECTOR=yolov8m` for yolov8m - `DETECTOR=yolov8s` for yolov8s ## Performance Measurement Download the video file to your local folder. For example, create a data folder and download the video into it (all commands must be executed from the root directory of the project Savant) ```bash # you are expected to be in Savant/ directory mkdir -p data && curl -o data/AVG-TownCentre.mp4 \ https://eu-central-1.linodeobjects.com/savant-data/demo/AVG-TownCentre.mp4 ``` Next, if you haven't run the sample in the default mode yet (following the instructions above), run ```bash docker compose -f samples/traffic_meter/docker-compose.x86.yml build module ``` or ```bash docker compose -f samples/traffic_meter/docker-compose.l4t.yml build module ``` to build the module docker image. Now you are ready to run the performance benchmark with the following command: Peoplenet: ```bash docker run --rm -it --runtime=nvidia \ -e DETECTOR=peoplenet \ -v `pwd`/samples:/opt/savant/samples \ -v `pwd`/data:/data:ro \ -v `pwd`/models/traffic_meter:/models \ -v `pwd`/downloads/traffic_meter:/downloads \ traffic_meter-module \ samples/traffic_meter/module-performance.yml ``` Yolov8m: ```bash docker run --rm -it --runtime=nvidia \ -e DETECTOR=yolov8m \ -v `pwd`/samples:/opt/savant/samples \ -v `pwd`/data:/data:ro \ -v `pwd`/models/traffic_meter:/models \ -v `pwd`/downloads/traffic_meter:/downloads \ traffic_meter-module \ samples/traffic_meter/module-performance.yml ``` Yolov8s: ```bash docker run --rm -it --runtime=nvidia \ -e DETECTOR=yolov8s \ -v `pwd`/samples:/opt/savant/samples \ -v `pwd`/data:/data:ro \ -v `pwd`/models/traffic_meter:/models \ -v `pwd`/downloads/traffic_meter:/downloads \ traffic_meter-module \ samples/traffic_meter/module-performance.yml ```
const catchAsync = require("../utils/catchAsync"); const clinicDB = require("../config/DB/index"); const httpStatus = require("http-status"); const validator = require("validator"); const { QueryTypes } = require("sequelize"); exports.getPrescription = catchAsync(async (req, res, next) => { try { // const prescriptions = await clinicDB.prescription.findAll(); // let query = `select Prescriptions.id,patientId,drugs,tests,firstName,lastName, Prescriptions.createdAt,Prescriptions.updatedAt, period, familyHistory, diseases, birthday, email,gender,mobileNo,bloodGroup,weight,height,address from Prescriptions join Patients on Prescriptions.patientId = Patients.id`; let {userId} = req.params if (!userId) { return res.status(404).json({ data: { error: `Please enter userId`, }, }); } let query = `SELECT Prescriptions.id, Prescriptions.patientId, Prescriptions.drugs, Prescriptions.tests, Prescriptions.createdAt AS prescriptionCreatedAt, Prescriptions.updatedAt AS prescriptionUpdatedAt, JSON_OBJECT( 'firstName', Patients.firstName, 'lastName', Patients.lastName, 'birthday', Patients.birthday, 'email', Patients.email, 'gender', Patients.gender, 'mobileNo', Patients.mobileNo, 'bloodGroup', Patients.bloodGroup, 'weight', Patients.weight, 'height', Patients.height, 'address', Patients.address, 'period', Patients.period, 'familyHistory', Patients.familyHistory, 'diseases', Patients.diseases ) AS patient FROM Prescriptions JOIN Patients ON Prescriptions.patientId = Patients.id where Prescriptions.userId = ${userId} ;` const prescriptions = await clinicDB.sequelize.query(query, { type: QueryTypes.SELECT, attributes: { exclude: ["password"] }, }); return res.status(200).json({ data: { prescriptions } }); } catch (error) { next(error); } }); exports.addPrescription = catchAsync(async (req, res, next) => { const { userId } = req.params; const { patientId, drugs, tests } = req.body; if (!userId || !patientId) { return res.status(404).json({ data: { message: "User Id or patient Id not found", }, }); } const [user, patient] = await Promise.all([ clinicDB.users.findByPk(userId), clinicDB.patient.findByPk(patientId), ]); if (!user || !patient) { return res.status(404).json({ data: { message: "User or patient not found", }, }); } const prescription = await clinicDB.prescription.create({ patientId, drugs, tests, userId, }); return res.status(201).json({ data: { message: "Prescription added successfully", data: prescription, }, }); }); exports.deletePrescription = catchAsync(async (req, res, next) => { try { const { id } = req.params; const prescription = await clinicDB.prescription.findOne({ where: { id } }); if (!prescription) { return res.status(404).json({ message: "Prescription not found" }); } await prescription.destroy(); // Respond with success message return res.status(200).json({ message: "prescription deleted successfully", }); } catch (error) { next(error); } });
# -*- coding: utf-8 -*- # vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4 ############################################################################### # OpenLP - Open Source Lyrics Projection # # --------------------------------------------------------------------------- # # Copyright (c) 2008-2013 Raoul Snyman # # Portions copyright (c) 2008-2013 Tim Bentley, Gerald Britton, Jonathan # # Corwin, Samuel Findlay, Michael Gorven, Scott Guerrieri, Matthias Hub, # # Meinert Jordan, Armin Köhler, Erik Lundin, Edwin Lunando, Brian T. Meyer. # # Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias Põldaru, # # Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, # # Maikel Stuivenberg, Martin Thompson, Jon Tibble, Dave Warnock, # # Frode Woldsund, Martin Zibricky, Patrick Zimmermann # # --------------------------------------------------------------------------- # # 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; version 2 of the License. # # # # 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 # ############################################################################### import logging from PyQt4 import QtCore from openlp.core.lib import Plugin, Registry, StringContent, Settings, build_icon, translate from openlp.plugins.media.lib import MediaMediaItem, MediaTab log = logging.getLogger(__name__) # Some settings starting with "media" are in core, because they are needed for core functionality. __default_settings__ = { u'media/media auto start': QtCore.Qt.Unchecked, u'media/media files': [] } class MediaPlugin(Plugin): log.info(u'%s MediaPlugin loaded', __name__) def __init__(self): Plugin.__init__(self, u'media', __default_settings__, MediaMediaItem) self.weight = -6 self.iconPath = u':/plugins/plugin_media.png' self.icon = build_icon(self.iconPath) # passed with drag and drop messages self.dnd_id = u'Media' def createSettingsTab(self, parent): """ Create the settings Tab """ visible_name = self.getString(StringContent.VisibleName) self.settingsTab = MediaTab(parent, self.name, visible_name[u'title'], self.iconPath) def about(self): about_text = translate('MediaPlugin', '<strong>Media Plugin</strong>' '<br />The media plugin provides playback of audio and video.') return about_text def setPluginTextStrings(self): """ Called to define all translatable texts of the plugin """ ## Name PluginList ## self.textStrings[StringContent.Name] = { u'singular': translate('MediaPlugin', 'Media', 'name singular'), u'plural': translate('MediaPlugin', 'Media', 'name plural') } ## Name for MediaDockManager, SettingsManager ## self.textStrings[StringContent.VisibleName] = { u'title': translate('MediaPlugin', 'Media', 'container title') } # Middle Header Bar tooltips = { u'load': translate('MediaPlugin', 'Load new media.'), u'import': u'', u'new': translate('MediaPlugin', 'Add new media.'), u'edit': translate('MediaPlugin', 'Edit the selected media.'), u'delete': translate('MediaPlugin', 'Delete the selected media.'), u'preview': translate('MediaPlugin', 'Preview the selected media.'), u'live': translate('MediaPlugin', 'Send the selected media live.'), u'service': translate('MediaPlugin', 'Add the selected media to the service.') } self.setPluginUiTextStrings(tooltips) def finalise(self): """ Time to tidy up on exit """ log.info(u'Media Finalising') self.media_controller.finalise() Plugin.finalise(self) def getDisplayCss(self): """ Add css style sheets to htmlbuilder """ return self.media_controller.get_media_display_css() def getDisplayJavaScript(self): """ Add javascript functions to htmlbuilder """ return self.media_controller.get_media_display_javascript() def getDisplayHtml(self): """ Add html code to htmlbuilder """ return self.media_controller.get_media_display_html() def app_startup(self): """ Do a couple of things when the app starts up. In this particular case we want to check if we have the old "Use Phonon" setting, and convert it to "enable Phonon" and "make it the first one in the list". """ Plugin.app_startup(self) settings = Settings() settings.beginGroup(self.settingsSection) if settings.contains(u'use phonon'): log.info(u'Found old Phonon setting') players = self.media_controller.mediaPlayers.keys() has_phonon = u'phonon' in players if settings.value(u'use phonon') and has_phonon: log.debug(u'Converting old setting to new setting') new_players = [] if players: new_players = [player for player in players if player != u'phonon'] new_players.insert(0, u'phonon') self.media_controller.mediaPlayers[u'phonon'].isActive = True settings.setValue(u'players', u','.join(new_players)) self.settingsTab.load() settings.remove(u'use phonon') settings.endGroup() def _get_media_controller(self): """ Adds the media controller to the class dynamically """ if not hasattr(self, u'_media_controller'): self._media_controller = Registry().get(u'media_controller') return self._media_controller media_controller = property(_get_media_controller)
// // Color+Extension.swift // Glassmorphism-SwiftUI // // Created on 2021/04/19. // import SwiftUI extension Color { init(hex: String) { let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int: UInt64 = 0 Scanner(string: hex).scanHexInt64(&int) let a, r, g, b: UInt64 switch hex.count { case 3: (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: (a, r, g, b) = (1, 1, 1, 0) } self.init( .sRGB, red: Double(r) / 255, green: Double(g) / 255, blue: Double(b) / 255, opacity: Double(a) / 255 ) } static let softRed = Color(hex: "f64f59") static let softViolet = Color(hex: "c471ed") static let vividCyan = Color(hex: "12c2e9") static let whiteSmoke = Color(hex: "f5f5f5") }
<?php namespace App\Http\Controllers; use App\Http\Resources\EventResource; use App\Models\Event; use App\Http\Requests\StoreEventRequest; use App\Http\Requests\UpdateEventRequest; use Illuminate\Http\Request; use phpDocumentor\Reflection\Types\Resource_; use Illuminate\Support\Arr; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; use Illuminate\Validation\Rule; class EventController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { return EventResource::collection(Event::where('status', 'Published')->paginate(10)); } /** * Store a newly created resource in storage. * * @param \App\Http\Requests\StoreEventRequest $request * @return \Illuminate\Http\Response */ public function store(StoreEventRequest $request) { $data = $request->validated(); if (isset($data['image'])) { $relativePath = $this->saveImage($data['image']); $data['image'] = $relativePath; } $event = Event::create($data); return new EventResource($event); } /** * Display the specified resource. * * @param \App\Models\Event $event * @return \Illuminate\Http\Response */ public function show(Event $event, Request $request) { $user = $request->user(); if ($user->id !== $event->user_id) { return abort(403, 'Unauthorized action.'); } return new EventResource($event); } /** * Display the specified resource. * * @param \App\Models\Event $event * @return \Illuminate\Http\Response */ public function showForGuest(Event $event) { return new EventResource($event); } /** * Update the specified resource in storage. * * @param \App\Http\Requests\UpdateEventRequest $request * @param \App\Models\Event $event * @return \Illuminate\Http\Response */ public function update(UpdateEventRequest $request, Event $event) { $data = $request->validated(); if (isset($data['image'])) { $relativePath = $this->saveImage($data['image']); $data['image'] = $relativePath; if ($event->image) { $absolutePath = public_path($event->image); File::delete($absolutePath); } } $event->update($data); return new EventResource($event); } /** * Remove the specified resource from storage. * * @param \App\Models\Event $event * @return \Illuminate\Http\Response */ public function destroy(Event $event, Request $request) { $user = $request->user(); if ($user->id !== $event->user_id) { return abort(403, 'Unauthorized action.'); } if ($event->image) { $absolutePath = public_path($event->image); File::delete($absolutePath); } $event->delete(); return response('', 204); } private function saveImage($image) { //check if image is valid base64 string if (preg_match('/^data:image\/(\w+);base64,/', $image, $type)) { $image = substr($image, strpos($image, ',') + 1); //file extension $type = strtolower($type[1]); //jpg, png, gif if (!in_array($type, ['jpg', 'jpeg', 'gif', 'png', 'webp'])) { throw new \Exception('invalid image type'); } $image = str_replace(' ', '+', $image); $image = base64_decode($image); if ($image === false) { throw new \Exception('base64_decode failed'); } } else { throw new \Exception('did not match data URL with image data'); } $dir = 'images/'; $file = Str::random() . '.' . $type; $absolutePath = public_path($dir); $relativePath = $dir . $file; if (!File::exists($absolutePath)) { File::makeDirectory($absolutePath, 0755, true); } file_put_contents($relativePath, $image); return $relativePath; } }
<%@page import="org.joonzis.ex.GreenDao"%> <%@page import="org.joonzis.ex.GreenVO"%> <%@page import="java.util.List"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>녹색 회원 목록보기</title> </head> <body> <jsp:include page="index.jsp"/> <br/><hr/><br/> <% // 전체 목록 가져오기 GreenDao dao = GreenDao.getInstance(); List<GreenVO> list = dao.getAllList(); // == List<GreenVO> list = GreenDao.getInstance().getAllList(); --> 위처럼 두개로 나누는게 오류 날 확률이 훨씬 적다!! // EL은 4가지 영역(객체)에 저장된 데이터를 사용한다. list를 PageContext에 담았다!! pageContext.setAttribute("list", list ); %> <div> <h1>전체 녹색 회원 목록</h1> <table> <thead> <tr> <th>순번</th> <th>아이디</th> <th>비밀번호</th> <th>성명</th> <th>나이</th> <th>주소</th> <th>가입일</th> </tr> </thead> <tbody> <c:if test="${not empty list }"> <%-- ${not empty list }: 리스트가 비어있지 않다. (== if(list.size() > 0) --%> <c:forEach var="vo" items="${list}" > <%-- == for(GreenVO dto : list) --%> <tr> <td>${vo.idx }</td> <td>${vo.id }</td> <td>${vo.pw }</td> <td>${vo.name }</td> <td>${vo.age }</td> <td>${vo.addr }</td> <td>${vo.reg_date }</td> </tr> </c:forEach> </c:if> <c:if test="${empty list }"> <%-- ${empty list } : list가 비어있다. (== if(list.size() == 0) --%> <tr> <td colspan="7">녹색 회원이 없습니다.</td> </tr> </c:if> </tbody> </table> </div> </body> </html>
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head th:replace="admin/_fragments :: head(~{::title})"> <meta charset="UTF-8"> <!--移动端更好的适应--> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../../static/dist/semantic/semantic.min.css"> <link rel="stylesheet" href="../../static/css/my.css"> <title>Types Manage</title> </head> <body> <!--导航开始---------------------------------------------> <nav th:replace="admin/_fragments :: menu(2)" class="ui inverted attached segment m-padded-mini m-shadow-small" > <div class="ui container"> <div class="ui inverted secondary stackable menu"> <h2 class="ui teal header item">Manage</h2> <a href="#" class="active m-item item m-mobile-hide"><i class="home icon"></i>Blogs</a> <a href="#" class="m-item item m-mobile-hide"><i class="idea icon"></i>Classification</a> <div class="right m-item m-mobile-hide menu"> <div class="ui dropdown item"> <img class="ui avatar image" src="../../static/images/me.jpg">Pan <i class="dropdown icon"></i> <div class="menu"> <a href="#" class="item">Change Password</a> <a href="#" class="item">My Information</a> <a href="#" class="item">Exit</a> </div> </div> </div> </div> </div> <a href="#" class="ui m-menu m-toggle black icon button m-right-top m-mobile-show"> <i class="sidebar icon"></i> </a> </nav> <!-- 二级导航 --> <div class="ui attached pointing menu"> <div class="ui container"> <div class="right menu"> <a href="#" th:href="@{/admin/types/input}" class=" item">New</a> <a href="#" th:href="@{/admin/types}" class="active teal item">List</a> </div> </div> </div> <!--导航结束----------------------------------------------> <br><br><br><br> <!--中间内容开始------------------------------------------> <div class="m-container-small m-padded-large"> <div class="ui container"> <div class="ui success message" th:unless="${#strings.isEmpty(message)}"> <i class="close icon"></i> <div class="header">Tips:</div> <p th:text="${message}">Success!</p> </div> <!-- 中间内容搜索结果开始 --> <table class="ui celled table"> <thead> <tr> <th></th> <th>名称</th> <th>操作</th> </tr> </thead> <tbody> <tr th:each="type,iterStat : ${page.content}"> <td th:text="${iterStat.count}">1</td> <td th:text="${type.name}">springboot开发指南</td> <td> <a href="#" th:href="@{/admin/types/{id}/input(id=${type.id})}" class="ui mini teal basic button">Edit</a> <a href="#" th:href="@{/admin/types/{id}/delete(id=${type.id})}" class="ui mini red basic button">Delete</a> </td> </tr> </tbody> <!-- 中间内容分页开始 --> <tfoot> <tr> <th colspan="6"> <div class="ui mini pagination menu" th:if="${page.totalPages}>1"> <a th:href="@{/admin/types(page=${page.number}-1)}" class="item" th:unless="${page.first}">Last Page</a> <a th:href="@{/admin/types(page=${page.number}+1)}" class="item" th:unless="${page.last}">Next Page</a> </div> <a th:href="@{/admin/types/input}" class="ui mini right floated teal basic button">Add</a> </th> </tr> </tfoot> <!-- 中间内容分页结束 --> </table> <!-- 中间内容搜索结果结束 --> </div> </div> <!--中间内容结束------------------------------------------> <br><br><br><br><br><br> <!--底部内容开始--> <footer th:replace="admin/_fragments :: footer" class="ui inverted vertical segment m-padded-massive"> <div class="ui center aligned container"> <div class="ui inverted divided stackable grid"> <div class="three wide column"> <div class="ui inverted link list"> <div class="item"> <img src="../../static/images/wechat.png" class="ui rounded image" alt="" style="width: 110px"/> </div> </div> </div> <div class="three wide column"> <h4 class="ui inverted header m-text-thin m-text-spaced">Lasted Blogs</h4> <div class="ui inverted link list"> <a class="item" href="#">testXXXXXXXXX</a> <a class="item" href="#">testXXXXXXXXX</a> <a class="item" href="#">testXXXXXXXXX</a> <a class="item" href="#">testXXXXXXXXX</a> </div> </div> <div class="three wide column"> <h4 class="ui inverted header m-text-thin m-text-spaced">Contact me</h4> <div class="ui inverted link list"> <a class="item m-text-lined" href="#">Email: yuweipan53@gmail.com</a> <a class="item m-text-lined" href="#">QQ: 1441944792</a> </div> </div> <div class="seven wide column"> <h4 class="ui inverted header m-text-thin m-text-spaced">Introduction</h4> <p class="m-text-thin m-text-spaced m-opacity-mini">XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX</p> </div> </div> <div class="ui inverted section divider"></div> <p class="m-text-thin m-text-spaced m-opacity-tiny">Copyright 2021 Pan Yuwei</p> </div> </footer> <!--底部内容结束------------------------------------------> <script src="../../static/dist/jquery/jquery-3.4.1.min.js" th:src="@{/dist/jquery/jquery-3.4.1.min.js}"></script> <script src="../../static/dist/semantic/semantic.min.js" th:src="@{/dist/semantic/semantic.min.js}"></script> <script> $('.m-menu.m-toggle').click(function () { $('.m-item').toggleClass('m-mobile-hide'); }); $('.ui.dropdown').dropdown({ on : 'hover' }); $('.message .close') .on('click',function (){ $(this) .closest('.message') .transition('fade'); }) $('#newblog-container').load(/*[[@{/footer/newblog}]]*/"/footer/newblog") </script> </body> </html>
import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../common_widgets/alert_dialog.dart'; import '../../common_widgets/basic_form_field.dart'; import '../../config/providers.dart'; import '../../config/router.gr.dart'; import '../../model/entity/page_state.dart'; import '../../utils/validator.dart'; import 'login_controller.dart'; @RoutePage() class LoginPage extends ConsumerWidget { const LoginPage({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final formKey = ref.watch(loginFormKeyProvider); final controller = ref.watch(loginControllerProvider.notifier); final pageState = ref.watch(loginControllerProvider.select((value) => value.pageState)); return Stack( children: [ Form( key: formKey, child: Scaffold( appBar: AppBar( title: const Text( 'ログイン画面', style: TextStyle(color: Colors.white), ), backgroundColor: Colors.blueAccent, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.all(8), child: BasicFormField( onChanged: (value) => controller.updateEmailAndPassword( email: value, ), validator: v.email, hintText: 'メールアドレス', ), ), Padding( padding: const EdgeInsets.all(8), child: BasicFormField( onChanged: (value) => controller.updateEmailAndPassword( password: value, ), validator: v.password, hintText: 'パスワード', ), ), const SizedBox(height: 60), ElevatedButton( onPressed: () { if (formKey.currentState!.validate()) { controller.login().then( (value) => value ? context.router .replace(const TodoListRoute()) : null, ); } }, child: pageState is PageStateLoading ? const Text('確認中') : const Text('ログインする'), ), const SizedBox(height: 20), ElevatedButton( onPressed: () => context.router.push(const SignupRoute()), child: const Text('新規登録'), ), ], ), ), ), ), if (pageState is PageStateLoading) const Positioned.fill( child: ColoredBox( color: Colors.black38, child: Center(child: CircularProgressIndicator()), ), ), if (pageState is PageStateDialog) Positioned.fill( child: ColoredBox( color: Colors.black38, child: CostomAlertDialog( onTap: () => controller.updatePageState( pageState: const PageState.none(), ), title: pageState.title!, description: pageState.description!, ), ), ), ], ); } }
# https://medium.com/@tentotheminus9/python-oop-a-simple-diagnostic-test-example-b58b026951bd class Patient(): """ Description: A parent class for the disease classess Attributes: first_name: First name last_name: Last name nhs_number: Unique NHS number age: Age sex: Sex region: Region most relevant to the patient Methods: NA """ def __init__ (self, nhs_number, first_name, last_name, age, sex, region): self.nhs_number = nhs_number self.first_name = first_name self.last_name = last_name self.age = age self.sex = sex self.region = region from abc import ABC, abstractmethod class Condition(object): """ Description: An abstract parent class for the condition class Attributes: id: string name:string heart_rate_bpm: Heart rate in beats per minute pretest: float Methods: get_pretest: Get a probability from a database (hardcoded for now) generate_pretest: Calculate a probability from a set of symptoms enter_pretest: Allow the user to enter a probability """ def __init__(self, id, name, heart_rate_bpm, pretest = 0): self.id = id self.name = name self.heart_rate_bpm = heart_rate_bpm self.pretest = pretest def get_pretest(self, disease): #SQL code here to access the medical database, using the #'disease' key. #Imagine that we send and recieve back a value relevant to; #id = covid19, Patient.region = Leeds, #Patient.age = 55, Patient.sex = M pretest = 0.12 return(pretest) @abstractmethod def generate_pretest(self): pass def enter_pretest(self, pretest_entered): self.pretest = pretest_entered class Respiratory(Condition): """ Description: An abstract class for the respiratory class Attributes: blood_oxygen_level: float temperature: float smoker: boolean sneezing: boolean runny_nose: boolean sore_throat: boolean headaches: boolean muscle_aches: boolean breathlessness: boolean Methods: NA """ def __init__(self, blood_oxygen_level, temperature, smoker, sneezing, runny_nose, sore_throat, headaches, muscle_aches, breathlessness): #Condition.__init__(self, id, name, heart_rate_bpm, pretest) self.blood_oxygen_level = blood_oxygen_level self.temperature = temperature self.smoker = smoker self.sneezing = sneezing self.runny_nose = runny_nose self.sore_throat = sore_throat self.headaches = headaches self.muscle_aches = muscle_aches self.breathlessness = breathlessness class Covid19(Respiratory): """ Description: A class for the Covid19 class Attributes: continuous_cough: Does the patient have a continuous cough? covid_proximity: Has the patient been near to someone else with confirmed Covid19? taste_change: Has the patient's taste changed recently? vaccinated: Has the patient been vaccinated in the last 12 months? Methods: get_pretest: Get the pretest based upon suspected condition ID, region, age, and sex generate_pretest: Get the pretest based upon symptoms enter_pretest: Enter the pretest based upon experience """ def __init__(self, continuous_cough=None, covid_proximity=None, taste_change=None, vaccinated=None): #Respiratory.__init__(self, name, heart_rate_bpm, blood_oxygen_level, temperature, smoker, sneezing, runny_nose, # sore_throat, headaches, muscle_aches, breathlessness) self.continuous_cough = continuous_cough self.covid_proximity = covid_proximity self.taste_change = taste_change self.vaccinated = vaccinated def generate_pretest(self): score = 0 if self.heart_rate_bpm > 100: score += 1 if self.blood_oxygen_level <0.92: score += 1 if self.temperature > 39: score += 1 if self.smoker: score += 1 if self.sneezing: score += 1 if self.runny_nose: score += 1 if self.sore_throat: score += 1 if self.headaches: score += 1 if self.muscle_aches: score += 1 if self.breathlessness: score += 1 if self.continuous_cough: score += 1 if self.covid_proximity: score += 1 if self.taste_change: score += 1 if self.vaccinated: score -= 5 pretest = score / 14 if pretest < 0: pretest = 0 pretest = round(pretest, 2) return(pretest) class Test(): """ Description: Attributes: sensitivty: The test sensitivity, 0.0 - 1.0 (float) specificity: The test specificity, 0.0 - 1.0 (float) sensitivity_ci_upper: The upper 95% sensitvity confidence interval value sensitivity_ci_lower: The lower 95% sensitvity confidence interval value specificity_ci_upper: The upper 95% specificity confidence interval value specificity_ci_lower: The lower 95% specificity confidence interval value pretest: The pre-test (or 'prior') probability of disease (float) result: The result of the diagnostic test. Either positive or negative (string) Methods: __generate_posttest_general: Calculate post-test values (private) generate_posttest: Calculate post-test values using the above method, for the quoted, upper and lower values """ def __init__(self, sensitivity, specificity, sensitivity_ci_upper, sensitivity_ci_lower, specificity_ci_upper, specificity_ci_lower, pretest, result): """Initialise attributes""" self.sensitivity = sensitivity self.specificity = specificity self.sensitivity_ci_upper = sensitivity_ci_upper self.sensitivity_ci_lower = sensitivity_ci_lower self.specificity_ci_upper = specificity_ci_upper self.specificity_ci_lower = specificity_ci_lower self.pretest = pretest self.result = result def __generate_posttest_general(self, sensitivity_option, specificity_option, pretest, result): """Generate a post-test probability""" lr_pos = sensitivity_option / (1 - specificity_option) lr_neg = (1 - sensitivity_option) / specificity_option pre_odds = pretest / (1-pretest) post_odds_pos = pre_odds * lr_pos post_odds_neg = pre_odds * lr_neg post_pos = post_odds_pos / (1+post_odds_pos) post_neg = post_odds_neg / (1+post_odds_neg) if result == 'pos': return(round(post_pos, 3)) if result == 'neg': return(round(post_neg, 3)) def generate_posttest(self): #Generate results for each sens/spec level, given a pos or neg result, posttest_quoted = self.__generate_posttest_general(self.sensitivity, self.specificity, self.pretest, self.result) posttest_lower = self.__generate_posttest_general(self.sensitivity_ci_lower, self.specificity_ci_lower, self.pretest, self.result) posttest_upper = self.__generate_posttest_general(self.sensitivity_ci_upper, self.specificity_ci_upper, self.pretest, self.result) posttest_all = [posttest_quoted, posttest_lower, posttest_upper] return(posttest_all) # patient1 = Covid19() # pretest = patient1.get_pretest('covid19') # test_for_covid19 = Test(sensitivity = 0.92, # specificity = 0.90, # sensitivity_ci_upper = 0.94, # sensitivity_ci_lower = 0.90, # specificity_ci_upper = 0.91, # specificity_ci_lower = 0.89, # pretest = pretest, # result = 'pos') # posttest = test_for_covid19.generate_posttest() # print("Based upon the test result, with a pre-test probability of " + # str(pretest) + ', the post-test probability is ' + str(posttest[0]) + ' (' + # str(posttest[1]) + '-' + str(posttest[2]) + ' 95% CI)') # patient2 = Covid19() # patient2.continuous_cough = False # patient2.covid_proximity = False # patient2.taste_change = False # patient2.vaccinated = False # patient2.heart_rate_bpm = 80 # patient2.blood_oxygen_level = 0.85 # patient2.temperature = 40 # patient2.smoker = True # patient2.sneezing = False # patient2.runny_nose = False # patient2.sore_throat = False # patient2.headaches = False # patient2.muscle_aches = False # patient2.breathlessness = True # pretest = patient2.generate_pretest() # test_for_covid19 = Test(sensitivity = 0.95, # specificity = 0.95, # sensitivity_ci_upper = 0.97, # sensitivity_ci_lower = 0.94, # specificity_ci_upper = 0.96, # specificity_ci_lower = 0.94, # pretest = pretest, # result = 'neg') # posttest = test_for_covid19.generate_posttest() # print("Based upon the test result, with a pre-test probability of " + str(pretest) + ', the post-test probability is ' + str(posttest[0]) + ' (' + str(posttest[2]) + '-' + str(posttest[1]) + ' 95% CI)') # patient3 = Covid19() # patient3.continuous_cough = True # patient3.covid_proximity = True # patient3.taste_change = True # patient3.vaccinated = False # patient3.heart_rate_bpm = 105 # patient3.blood_oxygen_level = 0.85 # patient3.temperature = 40 # patient3.smoker = True # patient3.sneezing = False # patient3.runny_nose = False # patient3.sore_throat = False # patient3.headaches = True # patient3.muscle_aches = True # patient3.breathlessness = True # pretest = patient3.generate_pretest() # test_for_covid19 = Test(sensitivity = 0.95, # specificity = 0.95, # sensitivity_ci_upper = 0.97, # sensitivity_ci_lower = 0.94, # specificity_ci_upper = 0.96, # specificity_ci_lower = 0.94, # pretest = pretest, # result = 'pos') # posttest = test_for_covid19.generate_posttest() # print("Based upon the test result, with a pre-test probability of " + str(pretest) + ', the post-test probability is ' + str(posttest[0]) + ' (' + str(posttest[1]) + '-' + str(posttest[2]) + ' 95% CI)')
# TP557 - Tópicos avançados em IoT e Machine Learning Repositório contendo o material da disciplina "Tópicos avançados em IoT e Machine Learning". ## Material das aulas O material das aulas pode ser acessado através dos links abaixo. 1. [Introdução ao curso](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_1_Introdu%C3%A7ao_ao_curso.pdf) 2. [Desafios do TinyML: Sistemas Embarcados](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_2_Desafios_do_TinyML_sistemas_embarcados.pdf) 3. [Desafios do TinyML: Machine Learning](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_3_Desafios_do_TinyML_machine_learning.pdf) 4. [O Paradigma do Machine Learning](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_4_O_Paradigma_do_Machine_Learning.pdf) 5. [Medindo a precisão de um modelo de ML](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_5_Medindo_a_precisão_de_um_modelo_de_ML.pdf) 6. [Minimizando o erro](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_6_Minimizando_o_erro.pdf) 7. [Regressão com DNNs (Parte I)](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_7_Regressão_com_DNNs_parte_I.pdf) 8. [Regressão com DNNs (Parte II)](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_8_Regressão_com_DNNs_parte_II.pdf) 9. [Classificação com DNNs](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_9_Classificação_com_DNNs.pdf) 10. [Datasets](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_10_Datasets.pdf) 11. [Métricas de classificação](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_11_Métricas_de_Classificação.pdf) 12. [Introduzindo convoluções](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_12_Introduzindo_convolu%C3%A7%C3%B5es.pdf) 13. [Prevenindo o sobreajuste](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_13_Prevenindo_o_sobreajuste.pdf) 14. [Introdução ao TensorFlow Lite e Edge impulse](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_14_introducao_tensorflowlite.pdf) 15. [Introdução ao Arduino BLE](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_14b_introducao_arduinoble.pdf) 16. [Detecção de movimentos](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_15_classifica%C3%A7%C3%A3o%20de%20movimentos.pdf) 17. [Detecção de anomalias](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_16_detec%C3%A7%C3%A3o_de_anomalias.pdf) 18. [Identificação de palavras chave](https://github.com/zz4fap/tp557-iot-ml/blob/main/slides/TP557_17_identifica%C3%A7%C3%A3o_palavras_chave.pdf) <img src="/figures/iot_lab.jpg" width="100px"> <img src="/figures/ml_logo1.png" width="100px"> <img src="/figures/inatel_logo.png" width="200px"> #### Professores Felipe Augusto Pereira de Figueiredo (felipe.figueiredo@inatel.br) Samuel Baraldi Mafra (samuelbmafra@inatel.br)
from core.constants import ( EMAIL_MAX_LENGTH, NAME_MAX_LENGTH, QUERY_SET_LENGTH, ROLE_ADMIN, ROLE_AGENT, ROLE_MODERATOR, ROLES_CHOICES, ) from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.core.mail import send_mail from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField from phonenumber_field.validators import validate_international_phonenumber from users.managers import CustomUserManager class User(AbstractBaseUser, PermissionsMixin): """ Кастомная модель пользователя, поле 'username' исключено, идентификатором является поле с адресом электронной почты. """ first_name = models.CharField( max_length=NAME_MAX_LENGTH, verbose_name=_('Имя'), help_text=_('Имя'), ) last_name = models.CharField( max_length=NAME_MAX_LENGTH, verbose_name=_('Фамилия'), help_text=_('Фамилия'), ) patronymic = models.CharField( blank=True, max_length=NAME_MAX_LENGTH, verbose_name=_('Отчество'), help_text=_('Отчество'), ) role = models.CharField( choices=ROLES_CHOICES, default=ROLE_AGENT, max_length=max(len(role) for role, _ in ROLES_CHOICES), verbose_name=_('Роль'), help_text=_('Уровень прав доступа'), ) email = models.EmailField( max_length=EMAIL_MAX_LENGTH, unique=True, verbose_name=_('Электронная почта'), help_text=_('Электронная почта'), ) phone = PhoneNumberField( blank=True, validators=[validate_international_phonenumber], verbose_name=_('Актуальный номер телефона'), help_text=_('Номер телефона, допустимый формат - +7 ХХХ ХХХ ХХ ХХ'), ) date_joined = models.DateTimeField( default=timezone.now, verbose_name=_('Дата регистрации.'), ) is_staff = models.BooleanField( default=False, verbose_name=_('Статус администратора.'), ) is_active = models.BooleanField( default=True, verbose_name=_('Показывает статус он-лайн.'), ) objects = CustomUserManager() EMAIL_FIELD = "email" USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'role'] class Meta: verbose_name = _('Пользователь') verbose_name_plural = _('Пользователи') ordering = ('last_name',) def clean(self): super().clean() self.email = self.__class__.objects.normalize_email(self.email) def __str__(self): return self.email[:QUERY_SET_LENGTH].capitalize() def get_username(self): return ( f'{self.first_name[:QUERY_SET_LENGTH]} ' f'{self.last_name[:QUERY_SET_LENGTH]}' ) def get_full_name(self): return ( f'{self.first_name[:QUERY_SET_LENGTH]} ' f'{self.patronymic[:QUERY_SET_LENGTH]} ' f'{self.last_name[:QUERY_SET_LENGTH]}' ) def email_user(self, subject, message, from_email=None, **kwargs): send_mail(subject, message, from_email, [self.email], **kwargs) @property def is_agent(self): """ Представитель команды - имеет возможность редактировать данные детей в своей команде. Просматривать некоторые данные по игрокам в других командах (ФИО, возраст, спортивный класс, тип заболевания). Выгружать формы по своей команде. Загружать сканы справок. """ return self.role == ROLE_AGENT @property def is_moderator(self): """ Модератор - имеет возможности вносить данные по определенному ребенку, не может добавлять новых пользователей и удалять детей, команды. """ return self.role == ROLE_MODERATOR @property def is_admin(self): """ Администратор - имеет неограниченные права управления на проекте. """ return (self.role == ROLE_ADMIN) or self.is_staff
import React, { useState } from "react"; import "./Navbar.css"; import logo_branca from "../assets/images/logo_branca.svg"; import menu from "../assets/images/menu.svg"; import closeIcon from "../assets/images/close.svg"; import ModalSupport from "./modals/ModalSupport"; const Navbar = () => { const [modalOpen, setModalOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false); const [menuClosing, setMenuClosing] = useState(false); // Função para abrir a modal const openModal = () => { setModalOpen(true); }; // Função para fechar a modal const closeModal = () => { setModalOpen(false); }; // Função para alternar a exibição do menu const toggleMenu = () => { if (menuOpen) { setMenuClosing(true); setTimeout(() => { setMenuOpen(false); setMenuClosing(false); }, 300); } else { setMenuOpen(true); } }; return ( <> <nav className="flex items-center lg:justify-center bg-gradient-to-l from-gray-800 to-gray-900 flex-wrap maindiv md:justify-between justify-between"> <div className="lg:w-2/6 relative"> <a href="/"> <img className="h-logo w-logo" src={logo_branca} alt="Logo" /> </a> </div> <div className="lg:flex items-center lg:w-4/6 justify-around hidden md:hidden text-xl"> <a href="/" className="block mt-4 lg:inline-block lg:mt-0 text-white hover:text-gray-500 mr-10" > Home </a> <a href="/#about" className="block mt-4 lg:inline-block lg:mt-0 text-white hover:text-gray-500 mr-10" > About us </a> <a className="block mt-4 lg:inline-block lg:mt-0 text-white hover:text-gray-500 mr-10 cursor-pointer" onClick={openModal} // Adicione o evento onClick para abrir a modal > Support </a> <a href="/" className="block mt-4 lg:inline-block lg:mt-0 text-white hover:text-gray-500 mr-10 pr-20" > Contact Professional </a> </div> {/* Ícone do menu */} <div className="sm:block md:block lg:hidden relative"> <button className="flex items-center text-white" onClick={toggleMenu}> {menuOpen ? ( <img className="h-menu w-menu mx-10 sm:block md:block lg:hidden" src={closeIcon} alt="Close" /> ) : ( <img className="h-menu w-menu mx-10 sm:block md:block lg:hidden" src={menu} alt="Menu" /> )} </button> </div> </nav> {/* Conteúdo do menu expansível */} {menuOpen && ( <div className={`bg-gradient-to-l from-gray-800 to-gray-900 text-white text-center`}> <div className={`text-white text-center pb-5 ${ menuClosing ? "animate-slide-up" : "animate-slide-down" }`} > <a href="/" className="block py-2 px-4 hover:text-gray-500"> Home </a> <a href="#about" className="block py-2 px-4 hover:text-gray-500"> About us </a> <a className="block py-2 px-4 hover:text-gray-500 cursor-pointer" onClick={openModal} > Support </a> <a href="https://api.whatsapp.com/send?phone=5531980160125&text=Ol%C3%A1,%20tenho%20uma%20d%C3%BAvida." className="block py-2 px-4 hover:text-gray-500" target="_blank" rel="noopener noreferrer" > Contact Professional </a> </div> </div> )} <ModalSupport isOpen={modalOpen} onClose={closeModal} /> </> ); }; export default Navbar;
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LoginComponent } from './components/auth/login/login.component'; import { MatchingComponent } from './components/home/matching/matching.component'; import { HomeTemplateComponent } from './components/home/home-template/home-template.component'; import { RegisterComponent } from './components/auth/register/register.component'; import { NZ_I18N } from 'ng-zorro-antd/i18n'; import { ru_RU } from 'ng-zorro-antd/i18n'; import { registerLocaleData } from '@angular/common'; import ru from '@angular/common/locales/ru'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NzFormModule } from 'ng-zorro-antd/form'; import { NzInputModule } from 'ng-zorro-antd/input'; import { NzButtonModule } from 'ng-zorro-antd/button'; import { ProfileCreateComponent } from './components/auth/profile-create/profile-create.component'; import { AuthInterceptor } from './utils/auth.interceptor'; import { BASE_API_URL } from './services/api/api-config'; import { environment } from '../environments/environment'; import { NzNotificationModule, NzNotificationService, } from 'ng-zorro-antd/notification'; import { NzSelectModule } from 'ng-zorro-antd/select'; import { NzMenuModule } from 'ng-zorro-antd/menu'; import { NzSpinModule } from 'ng-zorro-antd/spin'; import { NzIconModule } from 'ng-zorro-antd/icon'; import { PairsComponent } from './components/home/pairs/pairs.component'; import { PairComponent } from './components/home/pair/pair.component'; import { ChatComponent } from './components/home/chat/chat.component'; registerLocaleData(ru); @NgModule({ declarations: [ AppComponent, LoginComponent, MatchingComponent, HomeTemplateComponent, RegisterComponent, ProfileCreateComponent, PairsComponent, PairComponent, ChatComponent, ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule, BrowserAnimationsModule, NzFormModule, NzInputModule, NzButtonModule, ReactiveFormsModule, NzNotificationModule, NzSelectModule, NzMenuModule, NzSpinModule, NzIconModule, ], providers: [ { provide: NZ_I18N, useValue: ru_RU, }, { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, }, { provide: BASE_API_URL, useValue: environment.baseUrl, }, ], bootstrap: [AppComponent], }) export class AppModule {}
/* Network.h Copyright 2011 Remous-Aris Koutsiamanis This file is part of HL-Hitters. HL-Hitters 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. HL-Hitters 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 HL-Hitters. If not, see <http://www.gnu.org/licenses/>. */ #ifndef NETWORK_H_ #define NETWORK_H_ #include "Common.h" class Flow; // Forward declaration typedef Flow* FlowP; // A pointer to a Flow, used extensively // A Packet, generated by a Flow, moves through the queue class Packet{ public: FlowP flowp; // The Flow that generated it uint seq_num; // Its sequence number Packet(FlowP flowp, uint seq_num) :flowp(flowp), seq_num(seq_num){} }; // A Flow, generates Packets class Flow { public: uint id; // The Id of the Flow uint seq_num; // The sequence number of the last packet sent Flow(uint id) :id(id) { seq_num = 1; } // Generate a new packet Packet NewPacket() { Packet p(this, seq_num); seq_num++; return p; } friend std::ostream& operator<< (std::ostream &, Flow &); }; // Helper function for printing std::ostream& operator<< (std::ostream &out, Flow &f){ out << "F" << f.id; return out; } // Helper function for printing std::ostream& operator<< (std::ostream &out, Packet &p){ out << "P" << p.flowp->id; return out; } // A Queue based on std::deque but which has an upper bound on the items it can contain template <class T> class MaxQueue : public std::deque<T>{ public: uint max_queue_size; MaxQueue(uint max_queue_size) :max_queue_size(max_queue_size) {} // Modified method to limit the number of items in it. // In this implementation exceeding the limit is an error, i.e. dropped packet are not allowed. void push_back ( const T& x ){ if(std::deque<T>::size()>=max_queue_size){ std::cout << "Error: Queue size exceeded. This queue cannot handle more than " << max_queue_size << " items" << std::endl; ::exit(-1); } std::deque<T>::push_back(x); } }; // Flow-Count and Count-Flow pairs and maps typedef std::pair< FlowP, uint> FlowCountPair; // A pair of a Flow (pointer) and an integer count typedef std::pair< uint, FlowP> CountFlowPair; // A pair of an integer count and a Flow (pointer) typedef boost::unordered_map<FlowP, uint> FlowCountMap; // A map from a FlowP to an integer count typedef std::vector<FlowCountPair> HittersQueryResult; // A vector of FlowP-Count Pairs // Helper overloaded operator for output std::ostream& operator<< (std::ostream &out, const FlowCountPair & fcp){ out << "FC[" << *(fcp.first) << ", " << fcp.second << "]"; return out; } #endif /* NETWORK_H_ */
import { AbstractControl, FormBuilder, FormGroup, Validators, NgForm } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { PoNotificationService, PoSelectOption, PoLookupColumn, PoDynamicFormField, PoDatepickerIsoFormat } from '@po-ui/ng-components'; import { Visitante } from '../visitante.interface'; import { VisitanteService } from '../visitante.service'; @Component({ selector: 'app-visitante-form', templateUrl: './visitante-form.component.html', styleUrls: ['./visitante-form.component.css'] }) export class VisitanteFormComponent implements OnInit { title = 'INCLUIR - Visitantes'; visitanteForm: FormGroup; isTableLoading = false; filial: string = ''; visitante: string = ''; nome: string = ''; apelido: string = ''; dataImplant: string | Date = new Date(); cpf: string = ''; rgVisitante: string = ''; orgaoExped: string = ''; funcionario: string = '2 - Não'; endereco: string = ''; bairro: string = ''; cep: string = ''; nrCidade: string = ''; fone: string = ''; observacao: string = ''; nmCidade: string = ''; uf: string = ''; private id; readonly funcionarioOpt: Array<PoSelectOption> = [ { label: '1 - Sim', value: '1 - Sim' }, { label: '2 - Não', value: '2 - Não' } ]; constructor( private activatedRoute: ActivatedRoute, private fb: FormBuilder, private notification: PoNotificationService, private router: Router, private visitanteService: VisitanteService) { const { id } = this.activatedRoute.snapshot.params; this.id = id; } ngOnInit() { this.visitanteForm = this.fb.group({filial: [''], visitante: [''], nome: ['', Validators.required], cpf: ['', Validators.required], funcionario: ['', Validators.required], dataImplant: [''], rgVisitante: [''], orgaoExped: [''], endereco: [''], bairro: [''], cep: [''], nrCidade: [''], fone: [''], observacao: [''], nmCidade: [''], uf: [''] }); this.loadData(this.id); } private loadData(id: number) { if (id) { this.visitanteService.get(id).subscribe((visitante: Visitante) => { this.visitanteForm.patchValue(visitante); this.title = "ALTERAR - Visitantes"; }); } } cancel() { window.history.back(); } save() { if (this.visitanteForm.invalid) { this.markAsDirtyInvalidControls(this.visitanteForm.controls); this.notification.warning('Formulário precisa ser preenchido corretamente.'); return; } const visitante = this.visitanteForm.value; const operation = !!this.id ? this.visitanteService.update(this.id, visitante) : this.visitanteService.save(visitante); const successMessage = !!this.id ? 'Visitante atualizado com sucesso' : 'Visitante salvo com sucesso'; operation.subscribe(() => { this.notification.success(successMessage); this.router.navigate(['app/visitante']); }); } private markAsDirtyInvalidControls(controls: { [key: string]: AbstractControl }) { for (const key in controls) { if (controls.hasOwnProperty(key)) { const control = controls[key]; if (control.invalid) { control.markAsDirty(); } } } } // Funções de controle do lookup public readonly columns: Array<PoLookupColumn> = [ { property: 'nickname', label: 'Código' }, { property: 'name', label: 'Descrição' } ]; advancedFilters: Array<PoDynamicFormField> = [ { property: 'nickname', divider: 'Selection Informations', optional: true, gridColumns: 6, label: 'Código' }, { property: 'name', optional: true, gridColumns: 6 } ]; fieldFormat(value) { return `${value.label}`; // `${value.nickname} - ${value.label}`; } }
import React from 'react'; import { OptionContext } from './option-context'; /** * Props for the OptionGroup component. */ interface OptionGroupProps { /** * The name of the option group. */ name: string; /** * The currently selected value in the option group. */ value?: string; /** * The default value for the option group. */ defaultValue?: string; /** * A callback function that is triggered when the selected value in the option group changes. * It receives the new selected value as a parameter. */ onChange?: (value: string) => void; /** * The child components to be wrapped by the OptionGroup. */ children: React.ReactNode; } /** * A context provider component for managing a group of options. * * This component allows you to create a context for a group of options and provides * the selected value, default value, and an onChange callback to its children via context. * * @example Creating an option group * * ```tsx * <OptionGroup name="fruit" defaultValue="apple"> * // Add Option components here * </OptionGroup> * ``` * * @remarks * - The `name` prop is required and represents the name of the option group. * - You can specify the `value` prop to control the selected value in the group. * - The `defaultValue` prop sets the default selected value when no value is specified. * - The `onChange` prop can be used to handle value changes within the group. */ export const OptionGroup = (props: OptionGroupProps) => { return ( <OptionContext.Provider value={props}> {props.children} </OptionContext.Provider> ); };
import { html } from "../../node_modules/lit-html/lit-html.js"; import { editItemById, getItemById } from "../api/data.js"; import { notify } from "../notify.js"; //import { getUserData } from "../utility.js";//logged or not info //edit //add in </form> @submit=${onSubmit} //add in </input> .value="${item.name}" //replace text with variables: ${item.name} ////copy shape here: // edit: // title, // description, // imageUrl const editTemplate = (item, onSubmit) => html` <!--TO DO --> <!-- Edit Meme Page ( Only for logged user and creator to this meme )--> <section id="edit-meme"> <form id="edit-form" @submit=${onSubmit}> <h1>Edit Meme</h1> <div class="container"> <label for="title">Title</label> <input id="title" type="text" placeholder="Enter Title" name="title" .value="${item.title}"> <label for="description">Description</label> <textarea id="description" placeholder="Enter Description" name="description">${item.description}</textarea> <label for="imageUrl">Image Url</label> <input id="imageUrl" type="text" placeholder="Enter Meme ImageUrl" name="imageUrl" .value="${item.imageUrl}"> <input type="submit" class="registerbtn button" value="Edit Meme" value="Edit Meme"> </div> </form> </section> `; //example const editTemplate2 = (item, onSubmit) => html` <section id="edit"> <h2>Edit Motorcycle</h2> <div class="form"> <h2>Edit Motorcycle</h2> <form class="edit-form" @submit=${onSubmit}> <input type="text" name="model" id="model" placeholder="Model" .value=${item.model} /> <input type="text" name="imageUrl" id="moto-image" placeholder="Moto Image" .value=${item.imageUrl} /> <input type="number" name="year" id="year" placeholder="Year" .value=${item.year} /> <input type="number" name="mileage" id="mileage" placeholder="mileage" .value=${item.mileage} /> <input type="number" name="contact" id="contact" placeholder="contact" .value=${item.contact} /> <textarea id="about" name="about" placeholder="about" rows="10" cols="50" .value=${item.about} ></textarea> <button type="submit">Edit Motorcycle</button> </form> </div> </section> `; export async function editPage(ctx) { const itemId = ctx.params.id; const item = await getItemById(itemId); ctx.render(editTemplate(item, onSubmit)); //ctx.render(editTemplate({ submit: onSubmit, data: offer })); //render(editTemplate(shoe, ctx), document.querySelector('main'));} //async function onSubmit(event, ctx) { //event.preventDefault(); //const id = ctx.params.id; //const formData = new FormData(event.target); async function onSubmit(item) { item.preventDefault(); const formData = new FormData(item.target); const editItem = { //fix properties //copy shape here: //copy shape from create.js // title, // description, // imageUrl title: formData.get("title").trim(), description: formData.get("description").trim(), imageUrl: formData.get("imageUrl").trim(), }; if (Object.values(editItem).some((x) => !x)) { return notify("All fields are required!"); } await editItemById(itemId, editItem); item.target.reset(); ctx.page.redirect(`/details/${itemId}`); } }
import { User } from "@prisma/client"; import {createContext} from "react"; type Method = "get" | "post" | "put" | "delete"; export class Api { public setToken:React.Dispatch<React.SetStateAction<string>>; public constructor (setToken:React.Dispatch<React.SetStateAction<string>>) { this.setToken = setToken } private makeRequest = async (url: string, method: Method, body: Record<string, any> = {}) => { const options: RequestInit= { method, headers : { "Content-Type": "application/json", "Authorization": `Bearer ${window.localStorage.getItem("token")}` } } if (method === 'post' || method === 'put') { options.body = JSON.stringify(body); } const result = await fetch(import.meta.env.VITE_SERVER_URL+url, options) if (result.status === 401) { this.setToken("") window.localStorage.removeItem("token") } return result.json(); } get(url:string) { return this.makeRequest(url, 'get'); } post(url:string, body: Record<string,any>) { return this.makeRequest(url, 'post', body); } put(url:string, body: Record<string,any>) { return this.makeRequest(url, 'put', body); } del(url: string) { return this.makeRequest(url, 'delete'); } } // type ApiContext = {api: Api, user?:User, setUser:Function} export const ApiContext = createContext<Api>(new Api(() => {}));
%{ title: "Let your GenServer Breathe!", author: "Tósìn Soremekun", tags: ~w(elixir genserver otp), description: "Small tips for better performance, or how to not crash your GenServer" } --- GenServers in Elixir (or Erlang) provides nice abstractions for working with processes with good guarantees. Despite these, one should be careful not to misuse them as it can become a major bottleneck or even DoS the entire application. In this article, I'll assume you're comfortable working with Elixir, and are familiar with GenServers. We'll also mention Protobuf, and RabbitMQ although no previous experience of any is required to follow along. Imagine the following scenario; ```elixir defmodule NotificationServer do use AMQPBroadcaster @exchange "notifications" @routing_key "notifications.sms" def broadcast(%Notification{} = notification) do GenServer.cast(__MODULE__, {:broadcast, notification}) end @impl true def handle_cast({:broadcast, notification}, state = %{chan: chan}) do AMQP.Basic.publish(chan, @exchange, @routing_key, Jason.encode(notification)) end end ``` For the sake of brevity, we have not included boilerplate code required for setting up RabbitMQ connections. We'd assume it's already been taken care of in the `AMQPBroadcaster` macro. In the above example, we have a `NotificationServer` module responsible for broadcasting notifications to a RabbitMQ exchange using a routing key. If you're an experienced elixir developer, you probably might have spotted an issue with the implementation. We are encoding the notification by calling `Jason.encode!(notification)` in the server callback of the process and since it can only perform one operation at a time, subsequent messages will be queued and only processed after the encoding is complete. This might not be an issue for smaller work loads since `Jason.encode!` is reasonably fast but delays will become obvious as more data needs to be processed. Now, let's imagine we change the data transport format from `json` to `protobuf`, we might have even bigger problems with the implementation. Protobuf unlike `json` is strongly typed, and exceptions are raised when there is a type mismatch with any field. If we start our processes properly under a supervision tree, then it should be restarted if it crashes but supervisors in Elixir have a `max_restarts` and `max_seconds` option that specifies how many restarts can be made in `x` seconds. What happens when the `max_restarts` is reached? The supervisor itself [restarts](https://hexdocs.pm/elixir/Supervisor.html#module-exit-reasons-and-restarts). This might cause the entire application to be restarted or lead to a cascade of failures and even take the entire node down. Having established some of the downsides, how do we fix this? We could `try..catch` our way to prevent it from crashing, but we still have a potential bottleneck since encoding data can sometimes be time consuming. One suitable way would be to push the serialization onto the client. ```elixir defmodule NotificationServer do use AMQPBroadcaster @exchange "notifications" @routing_key "notifications.sms" def broadcast(%Notification{} = notification) do GenServer.cast(__MODULE__, {:broadcast, Jason.encode!(notification)}) end @impl true def handle_cast({:broadcast, notification}, state = %{chan: chan}) do AMQP.Basic.publish(chan, @exchange, @routing_key, notification) end end ``` The encoding is now done in the `broadcast/1` function which is called in the client process, relieving the notification server of too much work. Encoding errors would be raised in the client process which can be handled appropriately. This change might seem very little, but it could make a huge difference even with a fairly high workload. GenServer in Elixir and Erlang is an awesome tool, but one must understand its limitations in order to fully maximize its capabilities.
<template> <v-dropdown :name="'sidebar-project-menu-' + id" close-outside> <template #trigger> <span class="text-gray-400 hover:text-gray-200 cursor-pointer"> <DotsHorizontalIcon class="w-4 h-4"/> </span> </template> <div class="bottom-6 ltr:origin-bottom-right rtl:origin-bottom-left absolute ltr:right-0 rtl:left-0 mt-2 w-48 rounded-md shadow-lg py-1 bg-white ring-1 ring-black ring-opacity-5 focus:outline-none z-40" role="menu" aria-orientation="vertical" aria-labelledby="user-menu"> <div class="py-1" role="none"> <button class="w-full text-left px-4 py-1.5 text-xs leading-5 font-normal text-gray-600 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 transition duration-150 ease-in-out" @click="restore">{{ __('Restore') }}</button> <button class="w-full text-left px-4 py-1.5 text-xs leading-5 font-normal text-gray-600 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 transition duration-150 ease-in-out" @click="onDelete">{{ __('Delete') }}</button> </div> </div> </v-dropdown> </template> <script setup> import VDropdown from 'Component/Dropdown.vue' import { useProjectStore } from 'Store/project' import { useProjectArchiveStore } from 'Store/project-archive' import { PlusIcon, DotsHorizontalIcon } from '@heroicons/vue/outline' const props = defineProps({ id: Number, index: Number, }) const project = useProjectStore() const archive = useProjectArchiveStore() function restore() { axios.patch(`projects/${props.id}/restore`) .then(data => { console.log('data') console.log(data) project.items.push(data) archive.items.splice(props.index, 1) }) } function onDelete() { axios.delete(`projects/${props.id}`) .then(data => { archive.items.splice(props.index, 1) }) } </script>
import User from "../models/User.js"; import Role from "../models/Role.js"; export const createUser = async (req, res) => { try { const { username, email, password, roles } = req.body; const rolesFound = await Role.find({ name: { $in: roles } }); // creating a new User const user = new User({ username, email, password, roles: rolesFound.map((role) => role._id), }); // encrypting password user.password = await User.encryptPassword(user.password); // saving the new user const savedUser = await user.save(); return res.status(200).json({ _id: savedUser._id, username: savedUser.username, email: savedUser.email, roles: savedUser.roles, }); } catch (error) { console.error(error); return res.status(500).json({ message: "Error creating user" }); } }; export const getUsers = async (req, res) => { try { const users = await User.find(); return res.json(users); } catch (error) { console.error(error); return res.status(500).json({ message: "Error fetching users" }); } }; export const getUser = async (req, res) => { try { const user = await User.findById(req.params.userId); return res.json(user); } catch (error) { console.error(error); return res.status(500).json({ message: "Error fetching user" }); } }; export const updateUserRole = async (req, res) => { try { const { userId, roles } = req.body; const rolesFound = await Role.find({ name: { $in: roles } }); if (!rolesFound || rolesFound.length === 0) { return res.status(400).json({ message: "Invalid roles provided" }); } const user = await User.findById(userId); if (!user) { return res.status(404).json({ message: "User not found" }); } user.roles = rolesFound.map((role) => role._id); await user.save(); return res.status(200).json({ _id: user._id, username: user.username, email: user.email, roles: user.roles, }); } catch (error) { console.error(error); return res.status(500).json({ message: "Error updating user role" }); } };
'use client' import { useEffect, useState } from 'react' import MoreIcon from '@/components/icons/MoreIcon' import BlankUser from '../BlankUser' import { UPDATE_CURRENT_CONTACT, useContacts, useCurrentContactDispatch } from '../CurrentContactContext' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' import { Button } from '@/components/ui/button' import { Toaster, toast } from 'react-hot-toast' import { createClient } from "@/utils/supabase-browser" import { useRouter } from 'next/navigation' import { AddTagDialog } from './addTagDialog' export default function ChatHeader({ waId , contact }: { waId: string , contact : any }) { const [ loading , setLoading ] = useState<any>(0); const router = useRouter(); const currentContact = useContacts() const dispatch = useCurrentContactDispatch(); const [ chechTagging , setChechTagging ] = useState(true); useEffect(() => { const supabaseClient = createClient() if (!currentContact?.current && dispatch) { dispatch({type: UPDATE_CURRENT_CONTACT, waId: Number.parseInt(waId)}) } // const checkIsTaged = async () => { // const { data: contactsWithTags, error } = await supabaseClient // .from('contact_tag') // .select(`contact`) // .eq('contact' , waId) // setChechTagging(contactsWithTags?.length > 0 ? 0 : 1); // // console.log("🚀 ~ checkIsTaged ~ checkIsTaged:", contactsWithTags) // } // checkIsTaged(); },[]); const [ isDialogOpen, setDialogOpen] = useState(false); const MoveToTrash = async (contactId: any) => { if(loading) return; setLoading(true); const supabaseClient = createClient() const refreshingToast = toast.loading( "Moving contact to trash..."); const { error } = await supabaseClient .from('contacts') .update({ in_chat: false }) .eq('wa_id', contactId); if (error) { setLoading(false); toast.error('Please try again', { id : refreshingToast }); throw error; } router.push('/chats'); toast.success('Contact moved to trash successfully.' , { id : refreshingToast }); console.log('Contact moved to trash successfully.'); location.reload(); } const CopyNumberPhone = (phoneNumber: any) => { navigator.clipboard.writeText(phoneNumber); toast.success('Phone Number copied successfully') }; return ( <div className="bg-panel-header-background"> <Toaster position='top-center' /> <header className="px-4 py-2 flex flex-row gap-4 items-center"> <BlankUser className="w-10 h-10" /> <div className='text-primary-strong flex-grow'> {contact[0].profile_name} </div> { contact[0].tag_id == null ? <AddTagDialog waId = {waId} setDialogOpen = {setDialogOpen} isDialogOpen={isDialogOpen} onSuccessfulAdd={() => {}}> <Button className="ml-auto">Add tag</Button> </AddTagDialog> : <></> } <DropdownMenu> <DropdownMenuTrigger asChild> <Button disabled = {loading} variant="ghost" className="h-8 w-8 p-0"> <MoreIcon className='text-panel-header-icon' /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuLabel>Actions</DropdownMenuLabel> <DropdownMenuSeparator /> <DropdownMenuItem className="cursor-pointer" onClick={() => MoveToTrash(contact[0]?.wa_id)}>Move to trash</DropdownMenuItem> <DropdownMenuItem className="cursor-pointer" onClick={() => CopyNumberPhone(contact[0]?.wa_id)}>Copy Phone Number</DropdownMenuItem> {/* <DropdownMenuItem className="cursor-pointer" onClick={() => MoveToTrash()}>Move to Trash</DropdownMenuItem> */} </DropdownMenuContent> </DropdownMenu> </header> </div> ) }
package bead1; import java.util.*; /** * * @author Czeglédy Péter */ public abstract class Jatekos { protected String name; protected int money; protected Vector<Ingatlan> property; protected int position; public Jatekos(String name){ this.name = name; this.money = 10000; this.position = 0; this.property = new Vector<>(); } public void move(int amount){ this.position += amount; } public Boolean isBankrupt(){ if(money < 0){ for(Ingatlan p : property){ p.resetOwner(); } this.property.clear(); return true; } return false; } public String getName(){ return name; } public int getPosition(){ return position; } public int getMoney(){ return money; } public void setMoney(int amount){ this.money += amount; } public void setPosition(int position){ this.position = position; } /** * Jelzi a mezőnek, hogy ráléptek,a többit pedig a mező saját trespass * függvénye bonyolítja le * @param mezo az a mező amire a játékos rálép */ public abstract void trespassProperty(Mezo mezo); public abstract Boolean willingToBuy(); }
import { render, fireEvent } from "@testing-library/react"; import { Input } from "./Input"; describe("Input component", () => { let handleChangeValue = ""; const handleChange = (value: string) => { handleChangeValue = value; }; it("renders input element", () => { const { getByRole } = render(<Input value="" onChange={handleChange} />); const input = getByRole("textbox"); expect(input).toBeInTheDocument(); }); it("handles change event", () => { const { getByRole } = render(<Input value="" onChange={handleChange} />); const input = getByRole("textbox"); fireEvent.change(input, { target: { value: "new value" } }); expect(handleChangeValue).toEqual("new value"); }); it("handles focus and blur events", () => { const { getByRole, rerender } = render( <Input value="" onChange={() => {}} /> ); const input = getByRole("textbox"); fireEvent.focus(input); rerender(<Input value="" onChange={() => {}} />); expect(input.className).toContain("focus"); fireEvent.blur(input); // This is a hack need, because in component Input, I use similar delay method // remove it, after will change Imput to correct way setTimeout(() => { rerender(<Input value="" onChange={() => {}} />); expect(input.className).not.toContain("focus"); }, 3000); }); });
;■함수 디자인 회전 ;◆RGB 칼라를 색의 이름 단어로 지정하는 함수(사용 빈도의 높은 것 같은 색만) ; 사용법: SETCOLOR COLOR("레드") ; tohoK 참고로 했습니다. 감사. @COLOR(ARGS:0) #FUNCTION ;기본 디자인 칼라 ; 선택중 메뉴의 착색등 IF ARGS:0 == "메인칼라" RETURNF 0x47B0A0 ; 카테고리 타이틀색등 ELSEIF ARGS:0 == "서브칼라" RETURNF 0x888E7E ; 선택 불가색등, 사용 불가인 것을 나타낸다 ELSEIF ARGS:0 == "다크그레이" RETURNF 0x303030 ; 시간이나 무드의 Default색등, 불가는 아니지만 오프를 나타낸다 ELSEIF ARGS:0 == "회색" RETURNF 0x505050 ; 주석등, 주목해 주었으면 한 부분이 그 밖에 있을 때의 뺄셈색 ELSEIF ARGS:0 == "실버" RETURNF 0x808992 ; 기본적인 강조색 ELSEIF ARGS:0 == "오렌지" RETURNF 0xCE7A19 ; 기본적인 강조색과 대립하는 색(현재의 메인 칼라에 가깝기 때문에 주의) ELSEIF ARGS:0 == "시안" RETURNF 0x47B3A5 ; 주의 환기·가장 눈에 띄는 색 ELSEIF ARGS:0 == "옐로" RETURNF 0xCFBF30 ; 강조색이 부족할 시용 ELSEIF ARGS:0 == "올리브" RETURNF 0x8B9E53 ;보좌색 ELSEIF ARGS:0 == "다크 오렌지" RETURNF 0xC66630 ELSEIF ARGS:0 == "다크 옐로" RETURNF 0x999939 ELSEIF ARGS:0 == "다크 레드" RETURNF 0x942C2C ;심함락 칼라 ELSEIF ARGS:0 == "레드" RETURNF 0xD04040 ELSEIF ARGS:0 == "그린" RETURNF 0x609040 ELSEIF ARGS:0 == "퍼플" RETURNF 0x8970DF ;천함락 칼라 ELSEIF ARGS:0 == "핑크" RETURNF 0xD97980 ELSEIF ARGS:0 == "옐로그린" RETURNF 0x809940 ELSEIF ARGS:0 == "블루" RETURNF 0x6070DC ;기성 사실 Lv2 맹세 칼라 ELSEIF ARGS:0 == "라이트 핑크" RETURNF 0xF09CA3 ELSEIF ARGS:0 == "라이트 그린" RETURNF 0x90A060 ELSEIF ARGS:0 == "라이트 블루" RETURNF 0x7090D0 ;기성 사실 Lv3 관계 칼라 ELSEIF ARGS:0 == "파스텔 핑크" RETURNF 0xE5ABBE ELSEIF ARGS:0 == "파스텔 그린" RETURNF 0xA0A966 ELSEIF ARGS:0 == "파스텔 블루" RETURNF 0x87A8DB ;폭군에게 복종(복종 루트는 블루~퍼플, 조금 비켜 놓아 시안계) ELSEIF ARGS:0 == "폭군 칼라" RETURNF 0x50A0A0 ;호적수에 연모(연모 루트는 핑크~레드, 조금 비켜 놓아 오렌지계) ELSEIF ARGS:0 == "호적수 칼라" RETURNF 0xCC9930 ;코마치를 애완(애완 루트는 그린~옐로그린, 조금 비켜 놓아 민트 그린계) ELSEIF ARGS:0 == "코마치 칼라" RETURNF 0x70BB90 ;실버의 바리에이션 ELSEIF ARGS:0 == "실버 블루" RETURNF 0x90A9BF ;계절 ELSEIF ARGS:0 == "봄" RETURNF 0xE597B2 ELSEIF ARGS:0 == "여름" RETURNF 0x72AE66 ELSEIF ARGS:0 == "가을" RETURNF 0xC53D43 ELSEIF ARGS:0 == "동" RETURNF 0x99B3DB ;기후 ELSEIF ARGS:0 == "강설" RETURNF 0x98AAAB ELSEIF ARGS:0 == "구름" RETURNF 0x708E94 ELSEIF ARGS:0 == "강우" RETURNF 0x5383C3 ELSEIF ARGS:0 == "맑음" RETURNF 0xD9D09F ;맵용 ELSEIF ARGS:0 == "흙" RETURNF 0x302010 ELSEIF ARGS:0 == "수" RETURNF 0x555555 ELSEIF ARGS:0 == "다다미 마루" RETURNF 0x363910 ELSEIF ARGS:0 == "판자 벽" RETURNF 0x736950 ELSEIF ARGS:0 == "널판지를 깐 일본식 방" RETURNF 0x332C16 ELSEIF ARGS:0 == "석 벽" RETURNF 0x606066 ELSEIF ARGS:0 == "돌바닥" RETURNF 0x202029 ELSEIF ARGS:0 == "물 마시는 장소" RETURNF 0x105060 ELSEIF ARGS:0 == "봄의 수" RETURNF 0xB38699 ELSEIF ARGS:0 == "여름의 수" RETURNF 0x0e6953 ELSEIF ARGS:0 == "가을의 수" RETURNF 0x652D30 ELSEIF ARGS:0 == "동의수" RETURNF 0x39435B ELSEIF ARGS:0 == "봄의 흙" RETURNF 0x283020 ELSEIF ARGS:0 == "여름의 흙" RETURNF 0x0e3129 ELSEIF ARGS:0 == "가을의 흙" RETURNF 0x403029 ELSEIF ARGS:0 == "동의흙" RETURNF 0x262C39 ELSEIF ARGS:0 == "봄의 밤의 수" RETURNF 0x3f212d ELSEIF ARGS:0 == "여름의 밤의 수" RETURNF 0x031611 ELSEIF ARGS:0 == "가을의 밤의 수" RETURNF 0x2b0508 ELSEIF ARGS:0 == "동의밤의 수" RETURNF 0x1e2330 ELSEIF ARGS:0 == "봄의 밤의 흙" RETURNF 0x101c0a ELSEIF ARGS:0 == "여름의 밤의 흙" RETURNF 0x051c1a ELSEIF ARGS:0 == "가을의 밤의 흙" RETURNF 0x0f0b09 ELSEIF ARGS:0 == "동의밤의 흙" RETURNF 0x0d0f14 ;Default 칼라 ELSEIF ARGS:0 == "Default" RETURNF GETDEFCOLOR() ;에러 회피 ELSE RETURNF GETDEFCOLOR() ENDIF ;◆다색 사용의 텍스트를 일행으로 쓰는 함수 ; Default 칼라는 지정 불요 ; CALL COLOR_PRINTFORML("오렌지로 표시", COLOR("오렌지")) ; CALL COLOR_PRINTFORML("여기는 언제나 대로", , "여기는 오렌지색", COLOR("오렌지"), "여기도 언제나 대로", , "여기는 블루", COLOR("블루")) @COLOR_PRINT(텍스트1, 칼라1, 텍스트2, 칼라2, 텍스트3, 칼라3, 텍스트4, 칼라4, 텍스트5, 칼라5, 텍스트6, 칼라6, 텍스트7, 칼라7, 텍스트8, 칼라8, 텍스트9, 칼라9, 텍스트10, 칼라10) #DIMS 텍스트1 #DIM 칼라1 #DIMS 텍스트2 #DIM 칼라2 #DIMS 텍스트3 #DIM 칼라3 #DIMS 텍스트4 #DIM 칼라4 #DIMS 텍스트5 #DIM 칼라5 #DIMS 텍스트6 #DIM 칼라6 #DIMS 텍스트7 #DIM 칼라7 #DIMS 텍스트8 #DIM 칼라8 #DIMS 텍스트9 #DIM 칼라9 #DIMS 텍스트10 #DIM 칼라10 IF 텍스트1 != "" IF 칼라1 SETCOLOR 칼라1 ELSE SETCOLOR GETDEFCOLOR() ENDIF PRINTFORM %텍스트1% ENDIF IF 텍스트2 != "" IF 칼라2 SETCOLOR 칼라2 ELSE SETCOLOR GETDEFCOLOR() ENDIF PRINTFORM %텍스트2% ENDIF IF 텍스트3 != "" IF 칼라3 SETCOLOR 칼라3 ELSE SETCOLOR GETDEFCOLOR() ENDIF PRINTFORM %텍스트3% ENDIF IF 텍스트4 != "" IF 칼라4 SETCOLOR 칼라4 ELSE SETCOLOR GETDEFCOLOR() ENDIF PRINTFORM %텍스트4% ENDIF IF 텍스트5 != "" IF 칼라5 SETCOLOR 칼라5 ELSE SETCOLOR GETDEFCOLOR() ENDIF PRINTFORM %텍스트5% ENDIF IF 텍스트6 != "" IF 칼라6 SETCOLOR 칼라6 ELSE SETCOLOR GETDEFCOLOR() ENDIF PRINTFORM %텍스트6% ENDIF IF 텍스트7 != "" IF 칼라7 SETCOLOR 칼라7 ELSE SETCOLOR GETDEFCOLOR() ENDIF PRINTFORM %텍스트7% ENDIF IF 텍스트8 != "" IF 칼라8 SETCOLOR 칼라8 ELSE SETCOLOR GETDEFCOLOR() ENDIF PRINTFORM %텍스트8% ENDIF IF 텍스트9 != "" IF 칼라9 SETCOLOR 칼라9 ELSE SETCOLOR GETDEFCOLOR() ENDIF PRINTFORM %텍스트9% ENDIF IF 텍스트10 != "" IF 칼라10 SETCOLOR 칼라10 ELSE SETCOLOR GETDEFCOLOR() ENDIF PRINTFORM %텍스트10% ENDIF SETCOLOR GETDEFCOLOR() ;◆다색 사용의 텍스트를 일행으로 쓰는 함수 ; Default 칼라는 지정 불요 ; CALL COLOR_PRINTFORML("오렌지로 표시", COLOR("오렌지")) ; CALL COLOR_PRINTFORML("여기는 언제나 대로", , "여기는 오렌지색", COLOR("오렌지"), "여기도 언제나 대로", , "여기는 블루", COLOR("블루")) @COLOR_PRINTL(텍스트1, 칼라1, 텍스트2, 칼라2, 텍스트3, 칼라3, 텍스트4, 칼라4, 텍스트5, 칼라5, 텍스트6, 칼라6, 텍스트7, 칼라7, 텍스트8, 칼라8, 텍스트9, 칼라9, 텍스트10, 칼라10) #DIMS 텍스트1 #DIM 칼라1 #DIMS 텍스트2 #DIM 칼라2 #DIMS 텍스트3 #DIM 칼라3 #DIMS 텍스트4 #DIM 칼라4 #DIMS 텍스트5 #DIM 칼라5 #DIMS 텍스트6 #DIM 칼라6 #DIMS 텍스트7 #DIM 칼라7 #DIMS 텍스트8 #DIM 칼라8 #DIMS 텍스트9 #DIM 칼라9 #DIMS 텍스트10 #DIM 칼라10 CALL COLOR_PRINT(텍스트1, 칼라1, 텍스트2, 칼라2, 텍스트3, 칼라3, 텍스트4, 칼라4, 텍스트5, 칼라5, 텍스트6, 칼라6, 텍스트7, 칼라7, 텍스트8, 칼라8, 텍스트9, 칼라9, 텍스트10, 칼라10) PRINTL @COLOR_PRINTW(텍스트1, 칼라1, 텍스트2, 칼라2, 텍스트3, 칼라3, 텍스트4, 칼라4, 텍스트5, 칼라5, 텍스트6, 칼라6, 텍스트7, 칼라7, 텍스트8, 칼라8, 텍스트9, 칼라9, 텍스트10, 칼라10) #DIMS 텍스트1 #DIM 칼라1 #DIMS 텍스트2 #DIM 칼라2 #DIMS 텍스트3 #DIM 칼라3 #DIMS 텍스트4 #DIM 칼라4 #DIMS 텍스트5 #DIM 칼라5 #DIMS 텍스트6 #DIM 칼라6 #DIMS 텍스트7 #DIM 칼라7 #DIMS 텍스트8 #DIM 칼라8 #DIMS 텍스트9 #DIM 칼라9 #DIMS 텍스트10 #DIM 칼라10 CALL COLOR_PRINT(텍스트1, 칼라1, 텍스트2, 칼라2, 텍스트3, 칼라3, 텍스트4, 칼라4, 텍스트5, 칼라5, 텍스트6, 칼라6, 텍스트7, 칼라7, 텍스트8, 칼라8, 텍스트9, 칼라9, 텍스트10, 칼라10) PRINTW ;◆바로서 수치를 표시하는 함수(Kh) ;최소치는 0으로 한다 ;ARG:0=최소치 ARG:1=바의 표시상의 최대치, ARG:2=바의 값, ARG:3=바의 폭, ARG:4=바의 색(온), ARG:5=바의 색(오프) @PRINT_KANNRAKU_BAR(ARG:0 = 0, ARG:1, ARG:2, ARG:3, ARG:4, ARG:5) #DIM H = 0 #DIM S = 0 #DIM V = 0 #DIM 하나의매스 = 0 #DIM 바의폭 = 0 #DIM 바의값 = 0 #DIM 치매스 = 0 #DIM 최대치 = 0 ;칼라 초기치 조정 H = RGB_TO_H(ARG:4) - 15 S = RGB_TO_S(ARG:4) - 5 V = RGB_TO_V(ARG:4) - 20 IF H <= 0 H = 359 + H ENDIF IF S <= 0 S = 0 ENDIF IF V <= 0 V = 0 ENDIF ;바의 초기치 조정 최대치 = ARG:1 바의값 = ARG:2 바의폭 = ARG:3 하나의매스 = 0 치매스 = 0 ;만약 바의 표시상의 최대치가 바폭보다 작으면 IF 최대치 < 바의폭 최대치 = 바의폭 ENDIF ;바의 값이 하나의 매스보다 작으면 IF 바의값 < 하나의매스 바의값 = 하나의매스 ENDIF ;바 하나의 매스의 값을 요구하는 최대치 ÷ 바의 폭 하나의매스 = 최대치 / 바의폭 ;치는 무엇 매스분인지를 요구한다 ;(치-최소치)÷ 바 하나의 매스의 값 치매스 = 바의값 / 하나의매스 ;0매스 이하라면 0 매스에 IF 치매스 < 0 치매스 = 0 ENDIF ;색상 변화의 리듬 카운트용 LOCAL:3 = 0 ;바의 폭까지 반복해 FOR LOCAL:0, 0, 바의폭 ;치 매스의 수이하라면 물이 들어라 IF LOCAL:0 <= 치매스 SETCOLOR HSV_TO_RGB(H, S, V) PRINT_RECT 0, 30, 30, 45 LOCAL:3 += 4 ;3회에 1 색상 변화 IF LOCAL:3 % 2 == 0 H += 1 IF H >= 360 H = 1 ENDIF V += 1 IF V >= 100 V = 100 ENDIF ENDIF ;지정된 매스의 수이상이라면 회색 ELSE SETCOLOR ARG:5 PRINT_RECT 0, 40, 30, 20 ENDIF NEXT RESETCOLOR RETURN 0 ;◆색포함의 라인을 지정하는 CALL COLOR_LINE(0, "회색") ;ARG:1은 선의굵기, 0살, 1 안팎, 2태 @COLOR_LINE(ARG:0, 지정칼라 = 칼라_다크그레이) #DIM 지정칼라 = GETDEFCOLOR() #DIM H = 0 #DIM S = 0 #DIM V = 0 #DIM 그라데이션개시 = 0 #DIM 선의굵기 = 0 ;폰트의 리셋트 ; CALL SETFONT_MEYRYOKE ;카운터 LOCAL:0 = 0 ;색의 밝음을 최대치로서 지정하는 용 LOCAL:1 = 0 ;카운터 2 LOCAL:3 = 0 IF ARG:0 == 2 선의굵기 = 30 ELSEIF ARG:0 == 1 선의굵기 = 20 ELSE 선의굵기 = 10 ENDIF ;칼라 조정 H = RGB_TO_H(지정칼라) S = RGB_TO_S(지정칼라) V = RGB_TO_V(지정칼라) ;일행에 들어가는 아야 자수는 49문자분 rect는 전각 1문자가 100 그라데이션개시 = 4800 - V / 5 * 100 IF 그라데이션개시 <= 0 그라데이션개시 = 100 ENDIF ;그라데이션개시하는 위치까지 같은 색 SETCOLOR HSV_TO_RGB(H, S, V) PRINT_RECT 0, 50-(선의굵기/2), 그라데이션개시, 선의굵기 ;최대치 LOCAL:1 = V / 5 FOR LOCAL:0, 0, LOCAL:1 SETCOLOR HSV_TO_RGB(H, S, V) PRINT_RECT 0, 50-(선의굵기/2), 100, 선의굵기 LOCAL:3 += 1 ;3회에 1 색상 변화 IF LOCAL:3 % 3 == 0 H += 1 IF H >= 360 H = 1 ENDIF ENDIF V -= 5 NEXT PRINTL RESETCOLOR RETURN 0 ;◆폰트·emuera.config의 지정이 MS Gothic(Default의 지정)의 경우 ; MeiryoKe_Console가 인스톨 되고 있으면 세트 하는 CALL SETFONT_MEYRYOKE ;@SETFONT_MEYRYOKE ; ;Default 지정의 폰트를 체크 ; GETFONT ; ;플레이어에 의해 변경되어 있지 않으면 ; IF RESULTS == "MS Gothic" ; ;인스톨 확인 ; CHKFONT "MeiryoKe_Console" ; ;존재하면 ; IF RESULT ; SETFONT "MeiryoKe_Console" ; ENDIF ; ENDIF ; ; RETURN 0 ;◆타이틀 라벨 CALL TITLE_LABEL_START("타이틀", 1, "화상명", "설명문 간이 표시") ;ARGS:0 타이틀 ; ARG:1 개행&말미의 라인 표시하고 싶지 않을 때는 ARG:1을 1으로 해 ; 개행과 라인은 따로 표시한다(타이틀의 옆에 버튼을 둘 때나 폰트의 색 바꾸고 싶을 때의 지정) ; ARG:2 화상 패턴(생략 하면 Default·화상을 바꾸고 싶은 경우로 지정하는·현상 없음) @TITLE_LABEL_START(ARGS:0, ARG:1, ARGS:2, ARGS:3) CALL COLOR_LINE(0, GETDEFCOLOR()) PRINT_SPACE 20 IF ARG:1 PRINTFORM %ARGS:0% ELSE PRINTFORM %ARGS:0% IF ARGS:3 != "" SETCOLOR COLOR("실버") PRINTFORML %ARGS:3% RESETCOLOR ENDIF CALL COLOR_LINE ENDIF RETURN 0 ;◆타이틀 라벨·범용 카테고리 타이틀 표시 CALL TITLE_CATEGORY_GENERAL("친교", 4) @TITLE_CATEGORY_GENERAL(ARGS:0, ARG:1) PRINT_SPACE 20 SETCOLOR COLOR("서브칼라") LOCALS:0 = ◇%ARGS:0%◇ PRINTFORM %LOCALS:0, ARG:1, LEFT% RESETCOLOR PRINT_SPACE 80 ;◆타이틀 라벨·지정된 텍스트(ARGS:0)가 지정된 아야 자수(ARG:1)가 될 때까지 스페이스에서 묻어-를 붙인다 ; 콘피그라든지 헬프의 디자인 정리용 ; %FILL_SPACE("텍스트", 24)% @FILL_SPACE(ARGS:0, ARG:1) #FUNCTIONS ;지정된 텍스트의 아야 자수를 체크 LOCALS:0 = %ARGS:0% STRLENFORM %LOCALS:0% LOCAL:1 = RESULT:0 FOR LOCAL:0, 0, ARG:1 - LOCAL:1 LOCALS:0 += " " NEXT LOCALS:0 = %LOCALS:0%- RETURNF LOCALS:0
<?php namespace App\Http\Controllers; use App\Models\Bus; use App\Models\Jadwal; use App\Models\Kota; use App\Models\Route; use App\Models\Terminal; use App\Models\User; use App\Models\Transaksi; use App\Models\Pembayaran; use Illuminate\Http\Request; use Carbon\Carbon; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; class SesiController extends Controller { function index() { return view('/home'); } function index2() { return view('/sesi/login'); } function login(Request $request) { $request->validate([ 'email' => 'required|email', 'password' => 'required', ], [ 'email.required' => 'Email Wajib Diisi', 'password.required' => 'Password Wajib Diisi', ]); $infologin = [ 'email' => $request->email, 'password' => $request->password, ]; if (Auth::attempt($infologin)) { if (Auth::user()->role == 'user') { return redirect('/user/homepage'); } elseif (Auth::user()->role == 'admin') { return redirect('/admin'); } } else { return redirect('')->withErrors('Username dan Password Tidak Sesuai')->withInput(); } } function logout() { auth::logout(); return redirect(''); } function register() { return view('sesi/register'); } function create(Request $request) { $request->validate([ 'name' => 'required', 'email' => 'required|email|unique:users', 'password' => 'required|min:6', ], [ 'name.required' => 'Nama Wajib Diisi', 'email.required' => 'Email Wajib Diisi', 'email.email' => 'Silahkan masukkan email yang valid', 'email.unique' => 'Email Sudah Terdaftar', 'password.required' => 'Password Wajib Diisi', 'password.min' => 'Password harus lebih dari 6 karakter' ]); $data = [ 'name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password) ]; // Simpan pengguna baru $user = User::create($data); // Cek apakah pengguna berhasil terautentikasi setelah mendaftar if ($user) { // Redirect pengguna ke halaman login return redirect('sesi/login')->with('success', 'Registrasi berhasil! Silakan masuk dengan email dan password Anda.'); } else { // Redirect pengguna kembali ke halaman registrasi dengan pesan kesalahan return redirect('/register')->withErrors('Registrasi gagal. Silakan coba lagi.')->withInput(); } } function createadmi(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|email|unique:users', 'nama' => 'required', 'password' => 'required|min:6', 'role' => 'required' ]); if ($validator->fails()) return redirect()->back()->withInput()->withErrors($validator); $data['email'] = $request->email; $data['nama'] = $request->name; $data['password'] = bcrypt($request->password); User::create($data); return redirect()->route('admin'); } function createadmin(Request $request) { $request->validate([ 'name' => 'required', 'email' => 'required|email|unique:users', 'password' => 'required|min:6', 'role' => 'required' ], [ 'name.required' => 'Nama Wajib Diisi', 'email.required' => 'Email Wajib Diisi', 'email.email' => 'Silahkan masukkan email yang valid', 'email.unique' => 'Email Sudah Terdaftar', 'password.required' => 'Password Wajib Diisi', 'password.min' => 'Password harus lebih dari 6 karakter' ]); $data = [ 'name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password), 'role' => $request->role, ]; // Simpan pengguna baru $user = User::create($data); // Cek apakah pengguna berhasil terautentikasi setelah mendaftar if ($user) { // Redirect pengguna ke halaman login return redirect('admin')->with('success', 'Registrasi berhasil! Silakan masuk dengan email dan password Anda.'); } else { // Redirect pengguna kembali ke halaman registrasi dengan pesan kesalahan return redirect('admin.halcreate')->withErrors('Registrasi gagal. Silakan coba lagi.')->withInput(); } } public function update(Request $request, $id) { // Validasi data yang diterima dari formulir $request->validate([ 'email' => 'required|email|unique:users,email,' . $id, 'name' => 'required', 'password' => 'nullable|min:6', 'role' => 'required', ], [ 'email.unique' => 'Email telah digunakan oleh pengguna lain.', ]); // Temukan user yang akan diperbarui $user = User::findOrFail($id); if ($request->email !== $user->email && User::where('email', $request->email)->exists()) { return redirect()->back()->withErrors(['email' => 'Email telah digunakan oleh pengguna lain.'])->withInput(); } // Tetapkan nilai baru untuk atribut yang diperlukan $user->email = $request->email; $user->name = $request->name; if ($request->filled('password')) { $user->password = bcrypt($request->password); } $user->role = $request->role; // Simpan perubahan ke database $user->save(); // Redirect kembali ke halaman yang diinginkan setelah berhasil diperbarui return redirect()->route('admin')->with('success', 'User berhasil diperbarui.'); } public function delete(Request $request, $id) { $data = User::find($id); if ($data) { $data->delete(); } return redirect()->route('admin'); } public function createkota(Request $request) { $request->validate([ 'nama' => 'required|string|max:255|unique:kota,nama,', ], [ 'nama.required' => 'Nama kota harus diisi.', 'nama.unique' => 'Nama kota Sudah Terdata.', ]); Kota::create([ 'nama' => $request->nama, ]); return redirect()->route('admin')->with('success', 'Data kota berhasil ditambahkan!'); } public function updatekota(Request $request, $id) { // Validasi data yang diterima dari formulir $request->validate([ 'nama' => 'required|string|max:255|unique:kota,nama,' . $id, ], [ 'nama.unique' => 'Nama kota Sudah Terdata.', ]); // Temukan kota yang akan diperbarui $kota = Kota::findOrFail($id); // Tetapkan nilai baru untuk atribut yang diperlukan $kota->nama = $request->nama; // Simpan perubahan ke database $kota->save(); // Redirect kembali ke halaman yang diinginkan setelah berhasil diperbarui return redirect()->route('admin')->with('success', 'Kota berhasil diperbarui.'); } public function deletekota(Request $request, $id) { $data = Kota::find($id); if ($data) { $data->delete(); } return redirect()->route('admin'); } public function createterminal(Request $request) { // Validasi data yang diterima dari formulir $validatedData = $request->validate([ 'nama' => 'required|string|max:255', 'kota_id' => 'required|exists:kota,id', 'address' => 'nullable|string|max:255', 'maps_link' => 'nullable|string|max:255', ]); // Periksa apakah nama terminal sudah ada sebelumnya $existingTerminal = Terminal::where('nama', $validatedData['nama'])->first(); if ($existingTerminal) { return redirect()->back()->withInput()->withErrors(['nama' => 'Nama terminal sudah ada']); } // Buat objek terminal baru berdasarkan data yang diterima $terminal = new Terminal(); $terminal->nama = $validatedData['nama']; $terminal->kota_id = $validatedData['kota_id']; $terminal->address = $validatedData['address']; $terminal->maps_link = $validatedData['maps_link']; $terminal->save(); // Redirect pengguna ke halaman dengan konfirmasi sukses return redirect()->route('admin')->with('success', 'Data terminal berhasil ditambahkan'); } public function updateterminal(Request $request, $id) { // Validasi data yang diterima dari formulir $request->validate([ 'nama' => 'required|string|max:255|unique:terminal,nama,' . $id, 'kota_id' => 'required|exists:kota,id', 'address' => 'nullable|string|max:255', 'maps_link' => 'nullable|string|max:255', ], [ 'nama.required' => 'Nama terminal harus diisi.', 'nama.unique' => 'Nama terminal sudah terdaftar.', 'kota_id.required' => 'Kota harus dipilih.', 'kota_id.exists' => 'Kota yang dipilih tidak valid.', ]); // Temukan terminal yang akan diperbarui $terminal = Terminal::findOrFail($id); // Tetapkan nilai baru untuk atribut yang diperlukan $terminal->nama = $request->nama; $terminal->kota_id = $request->kota_id; $terminal->address = $request->address; $terminal->maps_link = $request->maps_link; // Simpan perubahan ke database $terminal->save(); // Redirect kembali ke halaman yang diinginkan setelah berhasil diperbarui return redirect()->route('admin')->with('success', 'Data terminal berhasil diperbarui.'); } public function deleteterminal(Request $request, $id) { $data = Terminal::find($id); if ($data) { $data->delete(); } return redirect()->route('admin'); } public function createBus(Request $request) { $validatedData = $request->validate([ 'image' => 'nullable|mimes:png,jpg,jpeg|max:5048', 'nomor_plat' => 'required|string|max:255|unique:bus,nomor_plat', 'nama' => 'required|string|max:255', 'jenis' => 'required|string|max:255', 'jumlah_kursi' => 'required|integer|min:1', 'format_kursi' => 'required|string|max:255', 'fasilitas' => 'nullable|array', 'keterangan' => 'nullable|string', ], [ 'nomor_plat.required' => 'Nomor plat wajib diisi.', 'nomor_plat.unique' => 'Nomor plat sudah ada.', 'nama.required' => 'Nama wajib diisi.', 'jenis.required' => 'Jenis wajib diisi.', 'jumlah_kursi.required' => 'Jumlah kursi wajib diisi.', 'jumlah_kursi.min' => 'Jumlah kursi harus lebih dari 0.', 'format_kursi.required' => 'Format kursi wajib diisi.', ]); if ($request->hasFile('image')) { $image = $request->file('image'); $filename = date('Y-m-d') . $image->getClientOriginalName(); $path = $request->file('image')->storeAs('public/photo-bus', $filename); $validatedData['image'] = $filename; } $validatedData['fasilitas'] = implode(', ', $request->fasilitas); $existingBus = Bus::where('nomor_plat', $validatedData['nomor_plat'])->first(); if ($existingBus) { return redirect()->back()->withInput()->withErrors(['nomor_plat' => 'Nomor plat sudah ada']); } $bus = new Bus(); $bus->fill($validatedData); $bus->save(); return redirect()->route('admin')->with('success', 'Bus berhasil ditambahkan.'); } public function updatebus(Request $request, $id) { // Validasi data yang diterima dari formulir $validatedData = $request->validate([ 'image' => 'nullable|mimes:png,jpg,jpeg|max:5048', 'nomor_plat' => 'required|string|max:255|unique:bus,nomor_plat,' . $id, 'nama' => 'required|string|max:255', 'jenis' => 'required|string|max:255', 'jumlah_kursi' => 'required|integer|min:1', 'format_kursi' => 'required|string|max:255', 'fasilitas' => 'nullable|array', 'keterangan' => 'nullable|string', ], [ 'nomor_plat.required' => 'Nomor plat wajib diisi.', 'nomor_plat.unique' => 'Nomor plat sudah digunakan.', 'nama.required' => 'Nama wajib diisi.', 'jenis.required' => 'Jenis wajib diisi.', 'jumlah_kursi.required' => 'Jumlah kursi wajib diisi.', 'jumlah_kursi.min' => 'Jumlah kursi minimal 1.', 'format_kursi.required' => 'Format kursi wajib diisi.', ]); $bus = Bus::findOrFail($id); if ($request->hasFile('image')) { // Validasi dan simpan gambar baru $image = $request->file('image'); $filename = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension(); $path = $request->file('image')->storeAs('public/photo-bus', $filename); $validatedData['image'] = $filename; // Hapus gambar lama jika ada if ($bus->image) { Storage::delete('public/photo-bus/' . $bus->image); } // Perbarui nama file gambar di model Bus $bus->image = $filename; } // Konversi array fasilitas menjadi string $validatedData['fasilitas'] = implode(', ', $request->fasilitas); // Cari data bus berdasarkan ID // Update data bus dengan data yang divalidasi $bus->update($validatedData); // Redirect pengguna ke halaman dengan konfirmasi sukses return redirect()->route('admin')->with('success', 'Data bus berhasil diperbarui'); } public function deletebus(Request $request, $id) { $data = Bus::find($id); if ($data) { $data->delete(); } return redirect()->route('admin'); } public function createroute(Request $request) { // Validasi data yang diterima dari formulir $validatedData = $request->validate([ 'terminal_asal_id' => 'required', 'terminal_tujuan_id' => 'required', 'waktu_destinasi' => 'required', ], [ 'terminal_asal_id.required' => 'Bidang terminal asal harus diisi.', 'terminal_tujuan_id.required' => 'Bidang terminal tujuan harus diisi.', 'waktu_destinasi.required' => 'Bidang waktu destinasi harus diisi.', ]); // Pastikan terminal asal dan tujuan benar-benar ada $terminalAsal = Terminal::find($validatedData['terminal_asal_id']); $terminalTujuan = Terminal::find($validatedData['terminal_tujuan_id']); if (!$terminalAsal || !$terminalTujuan) { return back()->with('error', 'Terminal asal atau tujuan tidak valid.'); } // Buat data rute baru Route::create($validatedData); return redirect()->route('admin')->with('success', 'Data rute berhasil disimpan'); } public function updateroute(Request $request, $id) { $validatedData = $request->validate([ 'terminal_asal_id' => 'required', 'terminal_tujuan_id' => 'required', 'waktu_destinasi' => 'required', ], [ 'terminal_asal_id.required' => 'Bidang terminal asal harus diisi.', 'terminal_tujuan_id.required' => 'Bidang terminal tujuan harus diisi.', 'waktu_destinasi.required' => 'Bidang waktu destinasi harus diisi.', ]); // Update data route $route = Route::findOrFail($id); $route->update($validatedData); return redirect()->route('admin')->with('success', 'Route updated successfully'); } public function createjadwal(Request $request) { // Validasi request jika diperlukan $request->validate([ 'kota_asal_id' => 'required', 'kota_tujuan_id' => 'required', 'terminal_asal_id' => 'required', 'terminal_tujuan_id' => 'required', 'tanggal_keberangkatan' => 'required', 'tanggal_sampai' => 'required', 'jam_keberangkatan' => 'required', 'jam_sampai' => 'required', 'destinasi_waktu' => 'required', 'bus_id' => 'required', 'jumlah_tiket_tersedia' => 'required', 'harga_tiket' => 'required', // Tambahkan validasi lainnya sesuai kebutuhan ]); // Simpan data ke database $jadwal = new Jadwal(); $jadwal->kota_asal_id = $request->kota_asal_id; $jadwal->kota_tujuan_id = $request->kota_tujuan_id; $jadwal->terminal_asal_id = $request->terminal_asal_id; $jadwal->terminal_tujuan_id = $request->terminal_tujuan_id; $jadwal->tanggal_keberangkatan = $request->tanggal_keberangkatan; $jadwal->tanggal_sampai = $request->tanggal_sampai; $jadwal->jam_keberangkatan = $request->jam_keberangkatan; $jadwal->jam_sampai = $request->jam_sampai; $jadwal->destinasi_waktu = $request->destinasi_waktu; $jadwal->bus_id = $request->bus_id; $jadwal->jumlah_tiket_tersedia = $request->jumlah_tiket_tersedia; $jadwal->harga_tiket = $request->harga_tiket; $jadwal->save(); // Redirect ke halaman atau tindakan yang sesuai setelah penyimpanan berhasil return redirect()->route('admin'); } public function updatejadwal(Request $request, $id) { // Validasi input $request->validate([ 'kota_asal_id' => 'required', 'kota_tujuan_id' => 'required', 'terminal_asal_id' => 'required', 'terminal_tujuan_id' => 'required', 'tanggal_keberangkatan' => 'required', 'tanggal_sampai' => 'required', 'jam_keberangkatan' => 'required', 'jam_sampai' => 'required', 'destinasi_waktu' => 'required', 'bus_id' => 'required', 'jumlah_tiket_tersedia' => 'required', 'harga_tiket' => 'required', 'status' => 'required' // Tambahkan aturan validasi lainnya sesuai kebutuhan ]); // Ambil jadwal yang akan diupdate $jadwal = Jadwal::find($id); // Perbarui nilai atribut jadwal berdasarkan data yang diterima dari formulir $jadwal->kota_asal_id = $request->kota_asal_id; $jadwal->kota_tujuan_id = $request->kota_tujuan_id; $jadwal->terminal_asal_id = $request->terminal_asal_id; $jadwal->terminal_tujuan_id = $request->terminal_tujuan_id; $jadwal->tanggal_keberangkatan = $request->tanggal_keberangkatan; $jadwal->tanggal_sampai = $request->tanggal_sampai; $jadwal->jam_keberangkatan = $request->jam_keberangkatan; $jadwal->jam_sampai = $request->jam_sampai; $jadwal->destinasi_waktu = $request->destinasi_waktu; $jadwal->bus_id = $request->bus_id; $jadwal->jumlah_tiket_tersedia = $request->jumlah_tiket_tersedia; $jadwal->harga_tiket = $request->harga_tiket; // Perbarui nilai atribut jadwal berdasarkan data yang diterima dari formulir $jadwal->status = $request->status; // Simpan perubahan $jadwal->save(); // Redirect pengguna ke halaman yang sesuai, misalnya halaman detail jadwal return redirect()->route('admin', ['id' => $jadwal->id])->with('success', 'Jadwal berhasil diperbarui.'); } public function deletejadwal(Request $request, $id) { $data = Jadwal::find($id); if ($data) { $data->delete(); } return redirect()->route('admin'); } public function getKota() { $kota = Kota::pluck('nama')->toArray(); return response()->json($kota); } public function createpesan(Request $request) { // Validasi data $validatedData = $request->validate([ 'jadwal_id' => 'required|exists:jadwal,id', 'title.*' => 'required', 'nama.*' => 'required', // Tambahkan aturan validasi lainnya sesuai kebutuhan ]); // Periksa apakah jumlah penumpang sesuai dengan jumlah opsi dan nama yang dimasukkan $seats = $request->seats; $num_titles = count($request->title); $num_namas = count($request->nama); if ($seats != $num_titles || $seats != $num_namas) { return redirect()->back()->withInput()->withErrors(['msg' => 'Jumlah penumpang dan jumlah data tidak sesuai']); } // Ambil jadwal berdasarkan ID $jadwal = Jadwal::findOrFail($request->jadwal_id); // Cek apakah masih tersedia kursi if ($seats > $jadwal->jumlah_tiket_tersedia) { return redirect()->back()->withInput()->withErrors(['msg' => 'Jumlah tiket yang dipilih melebihi jumlah tiket yang tersedia']); } // Ambil nomor kursi yang sudah digunakan pada jadwal tertentu $used_seat_numbers = Transaksi::where('jadwal_id', $jadwal->id) ->pluck('no_kursi') ->toArray(); // Membuat nomor kursi secara berurutan dimulai dari 1 hingga jumlah tiket tersedia $available_seat_numbers = range(1, $jadwal->jumlah_tiket_tersedia); // Cari nomor kursi yang masih tersedia (tidak digunakan) $available_seat_numbers = array_diff($available_seat_numbers, $used_seat_numbers); $available_seat_numbers = array_values($available_seat_numbers); // Cek apakah ada nomor kursi yang tersedia if (empty($available_seat_numbers)) { return redirect()->back()->withInput()->withErrors(['msg' => 'Semua tiket untuk jadwal ini telah terjual']); } // Ambil nomor kursi berikutnya yang tersedia $next_seat_numbers = array_slice($available_seat_numbers, 0, $seats); // Simpan transaksi ke database $lastTransaksi = null; foreach ($next_seat_numbers as $index => $seat_number) { $transaksi = new Transaksi(); $transaksi->user_id = auth()->id(); // atau cara Anda untuk mendapatkan ID pengguna yang memesan $transaksi->jadwal_id = $jadwal->id; $transaksi->titel = $request->title[$index]; $transaksi->nama = $request->nama[$index]; $transaksi->harga_tiket = $jadwal->harga_tiket; $transaksi->tanggal_transaksi = now()->toDateString(); $transaksi->no_kursi = $seat_number; $transaksi->save(); $lastTransaksi = $transaksi; } // Arahkan pengguna ke halaman pembayaran dengan ID transaksi return redirect()->route('pembayaran5', ['id_transaksi' => $transaksi->id_transaksi]); } // Fungsi di SesiController public function batalkanPemesanan(Request $request) { // Validasi data $request->validate([ 'id' => 'required|exists:transaksis,id', ]); // Temukan transaksi berdasarkan ID $transaksi = Transaksi::findOrFail($request->id); // Hapus transaksi dengan user_id yang sama dengan user yang sedang login // dan jadwal_id yang sama dengan jadwal_id pada transaksi yang akan dihapus Transaksi::where('user_id', Auth::id()) ->where('jadwal_id', $transaksi->jadwal_id) ->delete(); // Redirect ke halaman lain atau tampilkan pesan sukses return view('user.homepage')->with('success', 'Pemesanan berhasil dibatalkan.'); } public function pembayaran(Request $request) { // Validasi request $request->validate([ 'screenshot' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', ]); // Simpan gambar ke dalam direktori storage/app/public/bukti_transfer $gambar = $request->file('screenshot'); $namaFile = $gambar->getClientOriginalName(); $gambar->storeAs('public/bukti_transfer', $namaFile); // Ambil nilai dari input hidden $user_id = $request->input('user_id'); $jadwal_id = $request->input('jadwal_id'); $totalHargaTiket = session('total_harga_tiket'); // Simpan pembayaran ke dalam database dan dapatkan ID yang baru dibuat $id_pembayaran = Pembayaran::insertGetId([ 'user_id' => $user_id, 'jadwal_id' => $jadwal_id, 'metode_pembayaran' => 'Transfer Bank', 'jumlah' => $totalHargaTiket, 'bukti_transfer' => $namaFile, 'status' => 'pending', ]); // Generate ID e-ticket berdasarkan ID pembayaran yang baru dibuat $eticketID = $this->generateEticketID($jadwal_id, $id_pembayaran); // Update kolom e_ticket_id dengan ID e-ticket yang baru dibuat Pembayaran::where('id', $id_pembayaran)->update(['e_ticket_id' => $eticketID]); // Kurangi jumlah tiket tersedia berdasarkan jumlah transaksi pada jadwal tersebut $transaksiJadwal = Transaksi::where('jadwal_id', $request->jadwal_id)->count(); $jadwal = Jadwal::findOrFail($request->jadwal_id); $jadwal->jumlah_tiket_tersedia -= $transaksiJadwal; $jadwal->save(); // Redirect ke halaman e-ticket return redirect()->route('e-ticket.show', ['user_id' => $user_id, 'jadwal_id' => $jadwal_id]) ->with('success', 'Bukti transfer berhasil dikirim. Menunggu konfirmasi dari admin.'); } // Fungsi untuk generate ID e-ticket unik // Fungsi untuk generate ID e-ticket unik public function generateEticketID($jadwal_id, $id_pembayaran) { // Generate nomor acak dengan panjang 4 digit $randomNumber = mt_rand(1000, 9999); // Gabungkan ID jadwal dengan nomor acak dan ID pembayaran $eticketID = 'ET' . $jadwal_id . $randomNumber . $id_pembayaran; return $eticketID; } public function backhome() { // Redirect ke halaman lain atau tampilkan pesan sukses return view('user.homepage')->with('success', 'Pemesanan berhasil dibatalkan.'); } public function terima($id) { // Temukan pembayaran berdasarkan ID $pembayaran = Pembayaran::findOrFail($id); // Lakukan pengecekan apakah pembayaran memiliki status 'pending' if ($pembayaran->status === 'pending') { // Ubah status pembayaran menjadi 'accepted' $pembayaran->status = 'accepted'; $pembayaran->save(); // Redirect kembali ke halaman detail pembayaran dengan pesan sukses return redirect()->back()->with('success', 'Pembayaran telah diterima.'); } else { // Redirect kembali ke halaman detail pembayaran dengan pesan error jika status bukan 'pending' return redirect()->back()->with('error', 'Status pembayaran tidak valid.'); } } public function hapusPembayaran($id) { $pembayaran = Pembayaran::find($id); if (!$pembayaran) { return redirect()->back()->with('error', 'Data pembayaran tidak ditemukan.'); } if ($pembayaran->status !== 'pending') { return redirect()->back()->with('error', 'Hanya pembayaran yang masih dalam status pending yang dapat dihapus.'); } $pembayaran->delete(); return redirect()->back()->with('success', 'Data pembayaran berhasil dihapus.'); } }
<template> <div class="header"> <div flex-box="0" class="header-logo cs-pl-10"> <a href="/"><img src="~@/assets/image/logo@2x.png" height="60" alt="logo"></a> <span class="cs-pl">Restful API {{$t('_title')}} <span style="font-size: 12px;">v{{$version}}</span></span> </div> <el-menu flex-box="1" class="header-menu" :default-active="$route.fullPath" mode="horizontal" background-color="#2C3643" text-color="#CCCCCC" active-text-color="#FFD04B" :router="true"> <el-menu-item index="/index">{{$t('home')}}</el-menu-item> <el-submenu index="favorites"> <template slot="title">{{$t('favorites')}}</template> <el-menu-item index="/favorites">{{$t('manage favorites')}}</el-menu-item> <el-menu-item @click="importFav">{{$t('import favorites')}}</el-menu-item> <el-menu-item @click="exportFav">{{$t('export favorites')}}</el-menu-item> </el-submenu> <el-menu-item index="/history">{{$t('history')}}</el-menu-item> <el-menu-item index="/help">{{$t('help')}}</el-menu-item> <el-menu-item @click="openSetting">{{$t('setting')}}</el-menu-item> <el-submenu index="languages"> <template slot="title">{{$t('languages')}}</template> <el-menu-item v-for="language in $languages" :key="language.value" @click="setLanguage(language.value)">{{language.label}}</el-menu-item> </el-submenu> </el-menu> <cs-setting ref="setting"></cs-setting> <input type="file" ref="refFile" style="display: none" v-on:change="fileLoad" accept=".json"> </div> </template> <script> import { mapActions } from 'vuex' export default { name: 'cs-navbar', methods: { ...mapActions('careyshop/favorites', [ 'importFavorites', 'exportFavorites' ]), openSetting() { this.$nextTick(() => { this.$refs.setting.dialog = true }) }, setLanguage(value) { this.$i18n.locale = value }, fileLoad() { const selectedFile = this.$refs.refFile.files[0] if (!selectedFile) { return } let reader = new FileReader() reader.readAsText(selectedFile) reader.onload = async({ target }) => { await this.importFavorites(target.result) this.$refs.refFile.value = '' this.$message.success(this.$t('favorite success')) } }, importFav() { this.$refs.refFile.dispatchEvent(new MouseEvent('click')) }, exportFav() { this.exportFavorites() .then(res => { const element = document.createElement('a') element.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(res)) element.setAttribute('download', 'favorites') element.style.display = 'none' element.click() }) } } } </script> <style scoped> .header { border-radius: 0 0 4px 4px; overflow: hidden; } .header-logo { float: left; height: 60px; display: flex; justify-content: center; align-items: center; color: #FFF; background: #2C3643; } .header-menu { display: flex; justify-content: flex-end; } </style>