text stringlengths 184 4.48M |
|---|
import { ChangeEvent, useState } from 'react';
type InputProps = {
type: 'text' | 'number' | 'email' | 'password';
initialValue: string | number;
label: string;
name?: string;
placeholder?: string;
disabled?: boolean;
autoComplete?: 'on' | 'off';
onChangeValue?: (value: string) => void;
onBlur?: () => void;
};
export default function Input(props: InputProps) {
const {
type = 'text',
initialValue = '',
label = '',
placeholder = '',
disabled = false,
name = '',
autoComplete = 'on',
onChangeValue,
onBlur,
} = props;
const handleOnChange = (e: ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
if (onChangeValue && e) onChangeValue(e.target.value);
};
const [value, setValue] = useState(initialValue);
return (
<div>
{label && (
<label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
{label}
</label>
)}
<input
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
type={type}
value={value}
placeholder={placeholder}
name={name}
disabled={disabled}
autoComplete={autoComplete}
onChange={handleOnChange}
onBlur={onBlur}
/>
</div>
);
} |
import cv2
import numpy as np
import os
from PIL import Image, ImageDraw, ImageFont, ImageEnhance
import sys
import tensorflow as tf
import time
np.set_printoptions(threshold=sys.maxsize)
FONT_BOX_SIZE = 20
IMAGE_HEIGHT = 3672
IMAGE_WIDTH = 6500
USED_CHARCTERS = ([*"^*()_+=-=qwertyuiopasdfghjklzxcvbnm[]\;',./{}|:<>? "])
NUMBER_OF_USED_CHARACTERS = len(USED_CHARCTERS)
FONT_PATH = os.path.join(os.getcwd(), "ANDALEMO.ttf")
FONT = ImageFont.truetype(FONT_PATH, 24)
VIDEO_MATRIX_CHARACTERS = []
def upload_file():
file_path = input("drag the jpeg file to the terminal: ")
return file_path
def get_image_from_file_path(file_path):
return Image.open(file_path)
def get_final_image_dimensions(image_original_width, image_original_height):
if image_original_height > image_original_width:
padding_height_needed = IMAGE_HEIGHT - image_original_height
padding_width_needed = padding_height_needed * (image_original_height/image_original_width)
final_width = int((image_original_width + padding_width_needed) * 1.83)
print(final_width)
assert(final_width <= IMAGE_WIDTH)
return final_width, IMAGE_HEIGHT
#unicode character is 1.83 times wider than it is tall
padding_width_needed = IMAGE_WIDTH - image_original_width
padding_height_needed = padding_width_needed * (image_original_height/image_original_width)
#unicode character is 1.83 times wider than it is tall
final_height = int((image_original_height + padding_height_needed)/1.83)
assert(final_height <= IMAGE_HEIGHT)
return IMAGE_WIDTH, int((image_original_height + padding_height_needed)/1.83)
def process_image(image, brightness_modifier = 1, contrast_modifier = 2, sharpness_modifier = 3):
image = image.convert("L")
#print(f"MEAN OF IMAGE BEFORE PROCESSING {np.mean(image)}")
enhancer = ImageEnhance.Contrast(image)
image = enhancer.enhance(contrast_modifier)
enhancer = ImageEnhance.Sharpness(image)
image = enhancer.enhance(sharpness_modifier)
width, height = image.size
#print(f"IMAGE HAS WIDTH OF {width} AND HEIGHT OF {height}")
#unicode character is 1.83 times wider than it is tall
final_width, final_height = get_final_image_dimensions(width, height)
#print(f"IMAGE RESIZED TO {final_width} BY {final_height}")
image = image.resize((final_width, final_height))
image = tf.keras.utils.normalize(image, axis=0) * 255
#subtract the mean to evenly space values between positive and negative
#An average pixel value of -1.85 seems to work best
image = image - (np.mean(image) * 1/brightness_modifier)
#print(f"MEAN OF IMAGE AFTER PROCESSING {np.mean(image)}")
return image
def get_numpy_array_for_letter(char):
image = Image.new(mode = "L", size = (FONT_BOX_SIZE, FONT_BOX_SIZE))
draw = ImageDraw.Draw(image)
draw.text((3,-4), char, fill=255, font=FONT)
arr = np.array(image)
binary_arr = (arr > 0).astype(int)
binary_arr[np.where(binary_arr == 0)] = -1
if char == "_":
binary_arr[-1] = np.array([1] * FONT_BOX_SIZE)
return binary_arr
def get_character_matrix_filter():
character_matrix_filter = np.zeros((FONT_BOX_SIZE, FONT_BOX_SIZE, 1, NUMBER_OF_USED_CHARACTERS))
index = 0
for char in USED_CHARCTERS:
character_matrix_filter[:, :, :, index] = np.reshape(get_numpy_array_for_letter(char), (20, 20, 1))
index += 1
return character_matrix_filter
def get_convolution_scores(image_arr, filters):
image_arr = np.reshape(image_arr, (1, np.shape(image_arr)[0], np.shape(image_arr)[1], 1)).astype(np.intc)
filters = np.reshape(filters, (np.shape(filters)[0], np.shape(filters)[1], 1, NUMBER_OF_USED_CHARACTERS)).astype(np.intc)
convolution = tf.nn.convolution(image_arr, filters, strides=20).numpy()
strongest_filter_indices = np.argmax(convolution, axis=-1)
return strongest_filter_indices
def gen_image(best_letters_indices):
best_letters_indices = best_letters_indices.astype(int)
text_picture = ""
for row in best_letters_indices[0]:
result_array = [USED_CHARCTERS[i] for i in row]
text_picture = text_picture + ''.join(result_array) + "\n"
return text_picture
def get_number_of_frames_from_video(file_path):
cap = cv2.VideoCapture(file_path)
if not cap.isOpened():
print("Error: Could not open video.")
exit()
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
cap.release()
return frame_count
def get_video_dimensions(file_path):
cap = cv2.VideoCapture(file_path)
if not cap.isOpened():
print("Error: Could not open video.")
exit()
ret, frame = cap.read()
cap.release()
image = Image.fromarray(frame)
width, height = image.size
return width, height
def fill_video_matrix(file_path, filters, num_frames):
print("FILLING VIDEO MATRIX")
cap = cv2.VideoCapture(file_path)
if not cap.isOpened():
print("Error: Could not open video.")
exit()
frame_number = 0
p = tf.keras.utils.Progbar(num_frames)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
image = Image.fromarray(frame)
image = process_image(image)
best_letters_indices = get_convolution_scores(image, filters)
VIDEO_MATRIX_CHARACTERS.append(gen_image(best_letters_indices))
frame_number += 1
p.add(1)
def current_milli_time():
return round(time.time() * 1000)
def clear_stdout():
print("\033c")
def play_video():
#assuming 30 fps
milliseconds_per_frame = 1000/30
num_frames = len(VIDEO_MATRIX_CHARACTERS)
timings = [milliseconds_per_frame * (i + 10) for i in range(num_frames)]
start_time = current_milli_time()
frame_num = 0
clear_stdout()
for frame in VIDEO_MATRIX_CHARACTERS:
while current_milli_time() - start_time <= timings[frame_num]:
time.sleep(0.015)
clear_stdout()
print(frame)
frame_num +=1
if __name__ == "__main__":
picture = False
file = sys.argv[1]
brightness_modifier = float(sys.argv[2])
contrast_modifier = float(sys.argv[3])
sharpness_modifier = float(sys.argv[4])
filters = get_character_matrix_filter()
file_path = os.getcwd() + "/" + file
if picture:
image = get_image_from_file_path(file_path)
t1 = time.time()
image = process_image(image, brightness_modifier=brightness_modifier, contrast_modifier=contrast_modifier,
sharpness_modifier=sharpness_modifier)
best_letters_indices = get_convolution_scores(image, filters)
text_picture = gen_image(best_letters_indices)
print(text_picture)
print(f"Algorithm took {time.time() - t1} to run")
quit()
num_frames = get_number_of_frames_from_video(file_path)
width, height = get_video_dimensions(file_path)
final_width, final_height = get_final_image_dimensions(width, height)
fill_video_matrix(file_path, filters, num_frames)
play_video() |
import { useLoaderData, Link } from 'react-router-dom'
import axios from 'axios'
import styled from 'styled-components'
import H1 from '../H1'
import IssueCard from '../IssueCard'
import AddButton from '../AddButton'
import { useContext } from 'react'
import { TokenContext } from '../Root'
export async function loader ({ params: { username, project_name } }) {
const res = await axios.get(`http://localhost:3000/api/users/${username}/projects/${project_name}/`)
const project = res.data
console.log(res.data)
return { ...project, username }
}
const StyledH1 = styled(H1)`
color: #1F83DE;
margin-bottom: 20px;
`
const StyledDiv = styled.div`
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 20px;
`
const StyledAddButton = styled(AddButton)`
text-decoration: none;
`
const IssuesList = ({ issues }) =>
<StyledDiv>{issues.map((issue, index) => <IssueCard key={index} issue={issue} linkToComments />)}</StyledDiv>
export default function ProjectPage () {
const { name, issues, username } = useLoaderData()
const { username: userLoggedIn } = useContext(TokenContext)
return (
<article>
<StyledH1>{username}/{name}</StyledH1>
{userLoggedIn && <StyledAddButton as={Link} to='issues/new'>Create Issue</StyledAddButton>}
{issues ? <IssuesList issues={issues} /> : <p>This project has no issues.</p>}
</article>
)
} |
import React, { useState, useEffect } from 'react';
const CountdownTimer = ({ duration, results, category_count, time }) => {
const targetTime = new Date().getTime() + duration * 60 * 1000;
const [timeRemaining, setTimeRemaining] = useState(calculateTimeRemaining());
const [isRunning, setIsRunning] = useState(true);
const [isTimeUp, setIsTimeUp] = useState(false);
useEffect(() => {
let interval = null;
if (isRunning) {
interval = setInterval(() => {
const remaining = calculateTimeRemaining();
setTimeRemaining(remaining);
if (remaining.minutes === 0 && remaining.seconds === 0) {
setIsTimeUp(true);
clearInterval(interval);
}
}, 1000);
}
return () => {
clearInterval(interval);
};
}, [isRunning]);
const calculatePercentage = (value, total) => {
return ((value / total) * 100).toFixed(2); // Adjust the decimal places as needed
};
const categories = Object.keys(category_count);
function calculateTotalCorrectAnswers(results) {
let totalCorrectAnswers = 0;
Object.values(results).forEach((value) => {
totalCorrectAnswers += value;
});
return totalCorrectAnswers;
}
function calculateTotalPercentage(results, category_count) {
const totalCorrectAnswers = calculateTotalCorrectAnswers(results);
const totalQuestions = time * 0.6;
return ((totalCorrectAnswers / totalQuestions) * 100).toFixed(2);
}
function calculateTimeRemaining() {
const currentTime = new Date().getTime();
const difference = targetTime - currentTime;
if (difference <= 0) {
// Countdown is finished
return {
minutes: 0,
seconds: 0
};
}
// Calculate remaining minutes and seconds
const minutes = Math.floor(difference / (1000 * 60));
const seconds = Math.floor((difference % (1000 * 60)) / 1000);
return {
minutes,
seconds
};
}
const handleStop = () => {
setIsRunning(false);
};
const handleResume = () => {
setIsRunning(true);
};
return (
<div>
<div>
{isTimeUp ? (
<h4>
<div>Time is Up! Here is your results:</div>
<div>
<div className='complete-result'>
Total Number of Correct Answers: {calculateTotalCorrectAnswers(results)}
<br />
Percentage: {calculateTotalPercentage(results, category_count)}%
</div>
<div>{calculateTotalPercentage(results, category_count) > 70 ? <div>Pass! You beat 70%.</div> : <div>Fail! You need to achieve at least 70%.</div>}</div>
<div className='result-table'>
<table style={{ borderCollapse: "collapse", border: "1px solid black" }}>
<thead>
<tr>
<th style={{ border: "1px solid black", padding: "5px" }}>Category</th>
<th style={{ border: "1px solid black", padding: "5px" }}>Number of Correct Answers/Total number</th>
<th style={{ border: "1px solid black", padding: "5px" }}>Percentage</th>
</tr>
</thead>
<tbody>
{categories.map((category) => (
<tr key={category}>
<td style={{ border: "1px solid black", padding: "5px" }}>{category}</td>
<td style={{ border: "1px solid black", padding: "5px", 'text-align': 'center' }}>{results[category]} / {category_count[category]}</td>
<td style={{ border: "1px solid black", padding: "5px" }}>
{calculatePercentage(results[category], category_count[category])}%
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</h4>
) : (
<>
<div className='timer-display'>
<div>Remaining Time:</div>
<div>{timeRemaining.minutes} minutes</div>
<div>{timeRemaining.seconds} seconds</div>
{isRunning ? (
<div className="stop-button" onClick={handleStop}>Stop</div>
) : (
<div className="stop-button" onClick={handleResume}>Resume</div>
)}
</div>
</>
)}
</div>
{isTimeUp && <style>{'.question-card { display: none; }'}</style>}
{isTimeUp && <style>{'.stop-button { display: none; }'}</style>}
</div>
);
};
export default CountdownTimer; |
#pragma once
#include <unordered_map>
#include <optional>
#include <random>
#include <limits>
#include <account.hpp>
namespace banking {
class Bank {
public:
using account_id_t = std::size_t;
using pin_code_t = std::size_t;
class Card {
private:
friend class Bank;
Card(account_id_t account_id, pin_code_t pin);
bool set_password(pin_code_t old_pin, pin_code_t new_pin);
[[nodiscard]] std::optional<account_id_t> get_account(pin_code_t pin) const;
std::size_t account_id_;
std::size_t pin_code_;
};
struct AccountInfo {
Card card;
account_id_t account_id;
pin_code_t pin_code;
};
enum class operation_status {
success,
wrong_pin,
invalid_source_account,
invalid_destination_account,
not_enough_money,
operation_declined
};
struct account_clonning_result {
std::optional<AccountInfo> account_info;
operation_status status;
};
struct balance_result {
std::optional<IAccount::balance_t> balance;
operation_status status;
};
AccountInfo open_new_account(std::shared_ptr<IAccount> new_account);
account_clonning_result open_same_account(const Card& card, pin_code_t pin);
operation_status close_account(const Card& card, pin_code_t pin);
static operation_status change_password(Card& card, pin_code_t old_pin, pin_code_t new_pin);
operation_status get_cash(IAccount::transaction_t amount, const Card& card, pin_code_t pin);
operation_status transfer_to_account (account_id_t other_account, IAccount::transaction_t amount,
const Card& card, pin_code_t pin);
[[nodiscard]] balance_result get_balance(const Card& card, pin_code_t pin) const;
private:
static constexpr pin_code_t MIN_PIN = std::numeric_limits<pin_code_t>::min();
static constexpr pin_code_t MAX_PIN = std::numeric_limits<pin_code_t>::max();
pin_code_t generate_random_pin();
struct data_base {
account_id_t id_counter {0};
std::unordered_map<account_id_t, std::shared_ptr<IAccount>> accounts {};
std::mt19937_64 randomDevice {0};
std::uniform_int_distribution<pin_code_t> distribution {MIN_PIN, MAX_PIN};
};
std::shared_ptr<data_base> data_ = std::make_shared<data_base>();
};
} |
VARIABLES
La forma de definir las variables es con la palabra reservada Let o con la palabra reservada var
let f=90;
No se puede definir 2 veces la misma variable, eso da error
let nombre='Matias'
let nombre='Jaime'
Esto genera error
NO puede iniciarse el nombre de una variable con un NUMERO
NO puede contener caracteres especiales( salvo _ y $)
Usar CamelCase: NombreCompleto
LowerCamelCasas: nombreCompleto
Hay una diferencia entre la palabra reservada Let y var:
Var tiene un alcance global(actualizar una vez el valor de la variable genera un impacto en toda la aplicacion)
Let tiene un alcance local(actualizar el valor de la variable va a generar un impacto dependiendo del alcance de la misma)
Se recomienda evitar el uso de Var, en vez de eso, se recomienda Let
CONSTANTES
La forma de definir las constantes es con la palabra reservada const
const nombre='Matias'
TIPOS
Number:
Let salario=1500;
Para incrementar en 1 unidad una variable o disminuir en una unidad 1 variable se utiliza la sintaxis= ++ o --
var++; incrementa en 1
Strings:
Let nombre= "Fernando Herrera",
Para concatenar Strings se utiliza el signo +
Booleans:
Let activo=true; (Que las variables boleanas sean definidas en positivo)
Operacion con String
Para concatenerar strings se utiliza el singo +
Nombre1='Matias' Apellido='Jaime'
Salida= Nombre1+Apellido
Si se suma un string y un booleano, el booleano cambia su valor por un string
let activo='false';falso=false;
salida= activo+falso='falsefalse'
Operacion con Booleanos
Cuan se realiza la suma de variables booleanas, si hay qu tenga valor true, el resultado es 1(independiente de cuantos true existan), si no hay ninguno devuelve 0
var1=true var2=false var3=true
salida=var1+var2+var3=1
Operacion con Areglos
Let arreglo=[var1,var2,var3]
Comienza en el indice 0
Operaciones con Conjuntos
Dado el arreglo de conjunto de datos como el siguiente:
Datos=[
{
id:1,
nombre:'Matias'
},
{
id:2,
},
]
Datos[1].nombre me va a dar Matias
Datos[2].nombre me va a dar ERROR
Salvo que lo escriba de la siguiente manera:
Datos[2]?.nombre el ? hace que Javascript intente realizar la operación, y se detiene si da error, Esto sirve para que el programa no se rompa cuando falta algun dato
-----------------------------------------------------------------------------------------------
Estructura de Control:
Formato de estructura del condicional
if (condition) {
accion1
} else {
accion2
}
Tambien existe un operador ternario, siguiendo con el ejemplo anterior:
(condicion)
?(accion1)
:(accion2)
Solo funciona cuando acción1 y accion2 son 1 sola acción
Existe el elif:
else if
Condicional Switch
switch (key) {
case value:
break; El break es fundamental para, ya que le indica al flujo que deje de analizar lo que está abajo y termine el condicional
default: El default se utiliza para cualquier valor fuera de los aceptados
break;
}
Ciclos de Control
while (condition) {
}
FOR
for (let i = 0;i<= 10;i++) {
}
----------------------------------------------
FUNCIONES
function saludar(arg1,arg2,){ Los argumentos se separan por coma
return algo Se utiliza la palabra reservada return para devolver los valores
}
Las funciones no pueden modificar el valor de los argumentos que reciben,
Si el arg1=4, dentro del scope de la función puedo modificar el valor, pero afuera continuará teniendo el mismo valor
-----------------------------------------------------------------
OBJETOS
lo que define a un objeto son los corchetes {}
si se define una variable con corchetes, significa que es un objeto
let carro={
atributos
carro:'blanco', No utiliza el = para realizar la asignación, sino los 2 puntos:
}
CLASES
La sintaxis para crear clases es con la palabra reservada class
class Galleta{
Constructor(variables){
this.var1=variable1;
this.var2=variable2;
}
}
get Parametros(){}
La forma de instanciar una clase es con la palabra resrvada
let galleta1= new Galleta()
Los metodos getter, no utilizan parentesis cuando se los instancia, para la clase anterior sería:
Galleta.Paramentros;
COMILLA INVERTIDA
La comilla invertida me permite en la cadena añadir variables
${variable}no es transformado a una cadena, sino que nos devuelve el valor de la varialbe
`Esta es una cadela ${variable}`
Función de Flecha:
Es lo mismos que la función normal pero descripta de otra manera:
Funtion Saludar(argumentos){
acciones función
}
lo mismo a esto sería:
const Saludar=(argumentos) =>{
return `Saludo`
}
Ambas son lo mismo
Cuando la función de flecha tiene en el cuerpo 1 solo renglon, y ese renglo tiene un return, se puede cambar la sintaxis de la función, quedando de la siguiente manera:
const Saludar =(argumentos)=> `Saludo`
Se eliminan los {} y la palabra return
---------------------------------------------------------------------------------------------
PROMESAS
Dada cualquier función con callback, se puede utilizar las promesas en su lugar,
La sintaxis inicial sería:
const Función=(id,callback)=>{
const Salida= BaseDatos.find(id)
callback(Salida)
}
Esta función recibe 2 parametros de entrada, y cuando se ejecute la función, va a ser necesario que se defina el callback
Para evitar cambiar esto, se usan las promesas.
Quedando de la siguiente manera:
La sintaxis inicial sería:
const Función=(id)=>{
const Salida= BaseDatos.find(id)
const Promesa=new Promise((resolve,rejects)=>{
if(Salida){
resolve(Salida);
}else{
reject(`No se encontró el dato`)
}
})
return Promesa
La promesas utilizan por lo general 2 valores, un Resolve(cuando todo sale segun lo planeado) y un Reject(Cuando segenera una excepción) y finalmente se devuelve la promesa
Cuando se llama a la función, hay que escribirlo de la siguiente manera, con las palabras reservadas .then(flujo normal de ejecución) y .catch( Flujo de ejecucioncon excepción)
Función(id)
.then(var=>argumentos)
.catch(var=>argumentos)
Se pueden anidar las promesas
Función1(id)
.then(varFun1=>Función2(id))
.then(varFun2=>argumentos)
.catch(var=>argumentos)
Pero solo es necesario 1 Catch, ya que ese catch va a tomar el error que se genere de cualquiera de las funciones
Agregar el termino async a una función, hace que se transforme en una promesa, por lo tanto cuando instanciemos la función, debemos llamar a los metodos then y catch
const funcion=async()=>{
codigo
try{(condicion)
}
catch(error){}
}
funcion()
.then()
.catch()
Las palabras Reservadas await y Throw tienen mucha utilidad en este tipo de funciones,
El await, permite que asignemos a una variable el resultado de la ejecución de una función que tiene callback
El Thrown es lo mismo que el reject pero para funciones asincronas, ya que el reject no funciona en funciones asincronas
const getInfoUsuario2=async(id)=>{
try {
const empleado= await getEmpleado(id)
return `El salario del empleado: ${empleado} es ${salario}`
} catch (error) {
throw error
}
}
----------------------------------------------------------------------------------------------
Desestructuración
Sirve para convertir en variables, los valores de los atributos de un objeto
const {atributo1,atributo2,atributon, met1,net2}=objeto
De esa manera podemos sacar del objeto los atributos/metodos que querramos,
Los metodos no simpre funcionarian como queremos
-------------------------------------------------------------------
Exportar OBJETOS
Para poder exportar objeto entre distintos archivos se utilizan las palabras reservadas Export y Requiere
Dada la funcion
const funcion =()=>{
}
Luego de haberla definido, se utiliza la palabra:
module.exports ={
funcion
}
Y en el programa en el que queremos utilizar la función la llamamos de la siguiente manera:
const {funcion}=require('.././')
Lo recomendable es que primer o vayan las exportaciones de terceros y luegos las importaciones creadas por uno mismo
----------------------------------------------------------------------------------------------
RUTAS DIRECTORIOS
La barra que se utiliza para indicar la ruta en la que se va a escribir un archivo, es el parentesis simple / , no el parentesis Invertido \
`./salida/Tabla4.txt`
-----------------------------------------------------------------------------------------------------
SALIDA POR PANTALLA
la impresión por pantalla se realiza mediante el comando console.log, pero lo que va a salir en la pantalla va a depender de los caracteres especiales que utilicemos adentro
Si no se utilizan los caracteres especiales {}, lo que se muestra por pantalla es el valor de uno de los atributos de un objeto
Si se utilizan los caracteres especaiels {}, entonces lo que se muestra por pantalla es el objeto
Dado el arreglo:
let Direcciones={ 1:'Norte', 2:'Sur', 3:'Este', 5:'oeste'}
console.log(Direcciones[1])===== Norte
console.log({Direcciones}====Direcciones={ 1:'Norte', 2:'Sur', 3:'Este', 5:'oeste'}
Su uso va a depender de que es lo que queramos mostrar
-----------------------------------------------------------------------------------------------------------
LEVANTAR WEB SERVER NODE
const express = require('express');
const app = express();
const port=8081
app.get('/', (req, res) =>{
res.write('Hola Mundo');
res.end();
})
app.listen(port, ()=>{
console.log(`Ejemplo corrienendo en: http://localhost: ${port}`)
}
) |
/* Consider a file that contains a number of integers. Create two threads.
* Call them ‘producer’ and ‘consumer’ threads.
* Producer thread will be reading the integers from the file continuously while consumer thread will add them up.
* Use a proper synchronization mechanism if needed.
*/
package com.java;
class PC {
public void produce() throws InterruptedException {
synchronized(this) {
System.out.println("Producer thread running");
wait();
System.out.println("Producer thread resume");
}
}
public void consume() throws InterruptedException {
Thread.sleep(1000);
synchronized(this) {
System.out.println("Consumer Thread running");
notify();
Thread.sleep(2000);
}
}
}
public class InterThreadComm{
public static void main(String[] args) throws InterruptedException {
final PC pc = new PC();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
pc.produce();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
pc.consume();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
} |
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.source.formatter.check.util;
import com.liferay.petra.string.CharPool;
import com.liferay.petra.string.StringBundler;
import com.liferay.petra.string.StringPool;
import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ArrayUtil;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.tools.ToolsUtil;
import com.liferay.portal.xml.SAXReaderFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
/**
* @author Hugo Huijser
*/
public class SourceUtil {
public static boolean containsUnquoted(String s, String text) {
int x = -1;
while (true) {
x = s.indexOf(text, x + 1);
if (x == -1) {
return false;
}
if (!ToolsUtil.isInsideQuotes(s, x)) {
return true;
}
}
}
public static String getAbsolutePath(File file) {
return getAbsolutePath(file.toPath());
}
public static String getAbsolutePath(Path filePath) {
filePath = filePath.toAbsolutePath();
filePath = filePath.normalize();
return StringUtil.replace(
filePath.toString(), CharPool.BACK_SLASH, CharPool.SLASH);
}
public static String getAbsolutePath(String fileName) {
return getAbsolutePath(Paths.get(fileName));
}
public static Map<String, String> getAnnotationMemberValuePair(
String annotation) {
Map<String, String> annotationMemberValuePair = new HashMap<>();
Matcher matcher = _annotationMemberValuePairPattern.matcher(annotation);
while (matcher.find()) {
annotationMemberValuePair.put(matcher.group(1), matcher.group(2));
}
return annotationMemberValuePair;
}
public static List<String> getAnnotationsBlocks(String content) {
List<String> annotationsBlocks = new ArrayList<>();
Matcher matcher = _modifierPattern.matcher(content);
while (matcher.find()) {
int lineNumber = getLineNumber(content, matcher.end());
String annotationsBlock = StringPool.BLANK;
for (int i = lineNumber - 1;; i--) {
String line = getLine(content, i);
if (Validator.isNull(line) ||
line.matches("\t*(private|public|protected| \\*/).*")) {
if (Validator.isNotNull(annotationsBlock)) {
annotationsBlocks.add(annotationsBlock);
}
break;
}
annotationsBlock = line + "\n" + annotationsBlock;
}
}
return annotationsBlocks;
}
public static String getIndent(String s) {
StringBundler sb = new StringBundler(s.length());
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != CharPool.TAB) {
break;
}
sb.append(CharPool.TAB);
}
return sb.toString();
}
public static String getLine(String content, int lineNumber) {
int nextLineStartPos = getLineStartPos(content, lineNumber);
if (nextLineStartPos == -1) {
return null;
}
int nextLineEndPos = content.indexOf(
CharPool.NEW_LINE, nextLineStartPos);
if (nextLineEndPos == -1) {
return content.substring(nextLineStartPos);
}
return content.substring(nextLineStartPos, nextLineEndPos);
}
public static int getLineNumber(String content, int pos) {
return StringUtil.count(content, 0, pos, CharPool.NEW_LINE) + 1;
}
public static int getLineStartPos(String content, int lineNumber) {
if (lineNumber <= 0) {
return -1;
}
if (lineNumber == 1) {
return 0;
}
int x = -1;
for (int i = 1; i < lineNumber; i++) {
x = content.indexOf(CharPool.NEW_LINE, x + 1);
if (x == -1) {
return x;
}
}
return x + 1;
}
public static int[] getMultiLinePositions(
String content, Pattern multiLinePattern) {
List<Integer> multiLinePositions = new ArrayList<>();
Matcher matcher = multiLinePattern.matcher(content);
while (matcher.find()) {
multiLinePositions.add(getLineNumber(content, matcher.start()));
multiLinePositions.add(getLineNumber(content, matcher.end() - 1));
}
return ArrayUtil.toIntArray(multiLinePositions);
}
public static String getRootDirName(String absolutePath) {
while (true) {
int x = absolutePath.lastIndexOf(CharPool.SLASH);
if (x == -1) {
return StringPool.BLANK;
}
absolutePath = absolutePath.substring(0, x);
File file = new File(absolutePath + "/portal-impl");
if (file.exists()) {
return absolutePath;
}
}
}
public static String getTitleCase(
String s, boolean allowDash, String... exceptions) {
if (!allowDash) {
s = StringUtil.replace(s, CharPool.DASH, CharPool.SPACE);
}
String[] words = s.split("\\s+");
if (ArrayUtil.isEmpty(words)) {
return s;
}
StringBundler sb = new StringBundler(words.length * 2);
outerLoop:
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (Validator.isNull(word)) {
continue;
}
for (String exception : exceptions) {
if (StringUtil.equalsIgnoreCase(exception, word)) {
sb.append(exception);
sb.append(CharPool.SPACE);
continue outerLoop;
}
}
if ((i != 0) && (i != words.length)) {
String lowerCaseWord = StringUtil.toLowerCase(word);
if (ArrayUtil.contains(_ARTICLES, lowerCaseWord) ||
ArrayUtil.contains(_CONJUNCTIONS, lowerCaseWord) ||
ArrayUtil.contains(_PREPOSITIONS, lowerCaseWord)) {
sb.append(lowerCaseWord);
sb.append(CharPool.SPACE);
continue;
}
}
if (Character.isUpperCase(word.charAt(0))) {
sb.append(word);
}
else {
sb.append(StringUtil.upperCaseFirstLetter(word));
}
sb.append(CharPool.SPACE);
}
sb.setIndex(sb.index() - 1);
return sb.toString();
}
public static boolean hasTypo(String s1, String s2) {
if (Validator.isNull(s1) || Validator.isNull(s2) || s1.equals(s2) ||
(s1.charAt(0) != s2.charAt(0)) ||
(s1.charAt(s1.length() - 1) != s2.charAt(s2.length() - 1))) {
return false;
}
int min = Math.min(s1.length(), s2.length());
int diff = Math.abs(s1.length() - s2.length());
if ((min < 5) || (diff > 1)) {
return false;
}
int i = StringUtil.startsWithWeight(s1, s2);
s1 = s1.substring(i);
if (s1.startsWith(StringPool.UNDERLINE)) {
return false;
}
s2 = s2.substring(i);
if (s2.startsWith(StringPool.UNDERLINE)) {
return false;
}
for (int j = 1;; j++) {
if ((j > s1.length()) || (j > s2.length())) {
return true;
}
if (s1.charAt(s1.length() - j) != s2.charAt(s2.length() - j)) {
char[] chars1 = s1.toCharArray();
char[] chars2 = s2.toCharArray();
Arrays.sort(chars1);
Arrays.sort(chars2);
if (!Arrays.equals(chars1, chars2)) {
return false;
}
return true;
}
}
}
public static boolean isInsideMultiLines(
int lineNumber, int[] multiLinePositions) {
for (int i = 0; i < (multiLinePositions.length - 1); i += 2) {
if (lineNumber < multiLinePositions[i]) {
return false;
}
if (lineNumber <= multiLinePositions[i + 1]) {
return true;
}
}
return false;
}
public static boolean isXML(String content) {
try {
readXML(content);
return true;
}
catch (DocumentException documentException) {
if (_log.isDebugEnabled()) {
_log.debug(documentException);
}
return false;
}
}
public static Document readXML(File file) throws DocumentException {
SAXReader saxReader = SAXReaderFactory.getSAXReader(null, false, false);
return saxReader.read(file);
}
public static Document readXML(String content) throws DocumentException {
SAXReader saxReader = SAXReaderFactory.getSAXReader(null, false, false);
return saxReader.read(new UnsyncStringReader(content));
}
public static List<String> splitAnnotations(
String annotationsBlock, String indent)
throws IOException {
List<String> annotations = new ArrayList<>();
try (UnsyncBufferedReader unsyncBufferedReader =
new UnsyncBufferedReader(
new UnsyncStringReader(annotationsBlock))) {
String annotation = null;
String line = null;
while ((line = unsyncBufferedReader.readLine()) != null) {
if (annotation == null) {
if (line.startsWith(indent + StringPool.AT)) {
annotation = line + "\n";
}
continue;
}
String lineIndent = getIndent(line);
if (lineIndent.length() < indent.length()) {
annotations.add(annotation);
annotation = null;
}
else if (line.startsWith(indent + StringPool.AT)) {
annotations.add(annotation);
annotation = line + "\n";
}
else {
annotation += line + "\n";
}
}
if (Validator.isNotNull(annotation)) {
annotations.add(annotation);
}
}
return annotations;
}
private static final String[] _ARTICLES = {"a", "an", "the"};
private static final String[] _CONJUNCTIONS = {
"and", "but", "for", "nor", "or", "yet"
};
private static final String[] _PREPOSITIONS = {
"a", "abaft", "aboard", "about", "above", "absent", "across", "afore",
"after", "against", "along", "alongside", "amid", "amidst", "among",
"amongst", "an", "apropos", "apud", "around", "as", "aside", "astride",
"at", "athwart", "atop", "barring", "before", "behind", "below",
"beneath", "beside", "besides", "between", "beyond", "but", "by",
"circa", "concerning", "despite", "down", "during", "except",
"excluding", "failing", "for", "from", "given", "in", "including",
"inside", "into", "lest", "mid", "midst", "modulo", "near", "next",
"notwithstanding", "of", "off", "on", "onto", "opposite", "out",
"outside", "over", "pace", "past", "per", "plus", "pro", "qua",
"regarding", "sans", "since", "through", "throughout", "thru",
"thruout", "till", "to", "toward", "towards", "under", "underneath",
"unlike", "until", "unto", "up", "upon", "v", "versus", "via", "vice",
"vs", "with", "within", "without", "worth"
};
private static final Log _log = LogFactoryUtil.getLog(SourceUtil.class);
private static final Pattern _annotationMemberValuePairPattern =
Pattern.compile("(\\w+) = \"(.*?)\"");
private static final Pattern _modifierPattern = Pattern.compile(
"[^\n]\n(\t*)(public|protected|private)");
} |
package java_standard.new_time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
class DayAfterTomorrow implements TemporalAdjuster {
@Override
public Temporal adjustInto (Temporal temporal) {
return temporal.plus(2, ChronoUnit.DAYS);
}
}
public class NewTimeEx3 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate date = today.with(new DayAfterTomorrow());
p(today); // System.out.println(today);
p(date);
p(today.with(firstDayOfNextMonth())); // 다음 달의 첫 날
p(today.with(firstDayOfMonth())); // 이 달의 첫날
p(today.with(lastDayOfMonth())); // 이 달의 마지막 날
p(today.with(firstInMonth(TUESDAY))); // 이 달의 첫번째 화요일
p(today.with(lastInMonth(TUESDAY))); // 이 달의 마지막 화요일
p(today.with(previous(TUESDAY))); // 지난 주 화요일
p(today.with(previousOrSame(TUESDAY))); // 지난 주 화요일(오늘 포함)
p(today.with(next(TUESDAY))); // 다음 주 화요일
p(today.with(nextOrSame(TUESDAY))); // 다음 주 화요일(오늘 포함)
p(today.with(dayOfWeekInMonth(4, TUESDAY))); // 이 달의 4번째 화요일
}
static void p(Object obj) {
System.out.println(obj);
}
} |
package com.wxhl.tools.jdbc;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* 使用本类的方法,必须提供c3p0-copnfig.xml文件
*/
public class JdbcUtils {
// 饿汉式
private static final DataSource ds = new ComboPooledDataSource();
/**
* 它为null表示没有事务
* 它不为null表示有事务
* 当开启事务时,需要给它赋值
* 当结束事务时,需要给它赋值为null
* 并且在开启事务时,让dao的多个方法共享这个Connection
*/
private static final ThreadLocal<Connection> THREAD_LOCAL_CONNECTION = new ThreadLocal<>();
public static DataSource getDataSource() {
return ds;
}
/**
* dao使用本方法来获取连接
*
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
/*
* 如果有事务,返回当前事务的con
* 如果没有事务,通过连接池返回新的con
*/
Connection con = THREAD_LOCAL_CONNECTION.get();//获取当前线程的事务连接
if (con != null) return con;
return ds.getConnection();
}
/**
* 开启事务
*
* @throws SQLException
*/
public static void beginTransaction() throws SQLException {
Connection con = THREAD_LOCAL_CONNECTION.get();//获取当前线程的事务连接
if (con != null) throw new SQLException("已经开启了事务,不能重复开启!");
con = ds.getConnection();//给con赋值,表示开启了事务
con.setAutoCommit(false);//设置为手动提交
THREAD_LOCAL_CONNECTION.set(con);//把当前事务连接放到tl中
}
/**
* 提交事务
*
* @throws SQLException
*/
public static void commitTransaction() throws SQLException {
Connection con = THREAD_LOCAL_CONNECTION.get();//获取当前线程的事务连接
if (con == null) throw new SQLException("没有事务不能提交!");
con.commit();//提交事务
con.close();//关闭连接
//con = null;//表示事务结束!
THREAD_LOCAL_CONNECTION.remove();
}
/**
* 回滚事务
*
* @throws SQLException
*/
public static void rollbackTransaction() throws SQLException {
Connection con = THREAD_LOCAL_CONNECTION.get();//获取当前线程的事务连接
if (con == null) throw new SQLException("没有事务不能回滚!");
con.rollback();
con.close();
//con = null;
THREAD_LOCAL_CONNECTION.remove();
}
/**
* 释放Connection
*
* @param con
* @throws SQLException
*/
public static void releaseConnection(Connection connection) throws SQLException {
Connection con = THREAD_LOCAL_CONNECTION.get();//获取当前线程的事务连接
if (connection != con) {//如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭!
if (connection != null && !connection.isClosed()) {//如果参数连接没有关闭,关闭之!
connection.close();
}
}
}
} |
import { Component, OnDestroy } from '@angular/core';
import { NavigationStart, Router } from '@angular/router';
import { filter, map, Subscription } from 'rxjs';
import { LoginServiceService } from 'src/app/services/login-service.service';
@Component({
selector: 'app-nav-bar',
templateUrl: './nav-bar.component.html',
styleUrls: ['./nav-bar.component.scss']
})
export class NavBarComponent implements OnDestroy{
titulo_cabecalho: string
nome_usuario: string
routeSubscription: Subscription;
constructor(private router: Router, private login_service: LoginServiceService){
this.titulo_cabecalho = this.retornarTitutloCabeçalho(router.url.split("/")[1])
this.routeSubscription = this.router.events
.pipe(
filter(event => event instanceof NavigationStart),
map(event => event as NavigationStart), // appease typescript
).subscribe(
event => {
this.titulo_cabecalho = this.retornarTitutloCabeçalho(event.url.split("/")[1])
}
);
const token_object = JSON.parse(this.login_service.getToken()!)
this.nome_usuario = token_object['nome']
}
ngOnDestroy(): void {
this.routeSubscription.unsubscribe()
}
retornarTitutloCabeçalho(rota: string): string {
const urls_to_titulos: any = {
'home': "ESTATÍSTICAS E INFORMAÇÕES",
'registration': "CADASTRO DE PACIENTE",
'list_medical_record': "LISTAGEM DE PRONTUÁRIOS",
'medical_record': "PRONTUÁRIO DE PACIENTE",
'registration_medical_appointment': "CADASTRO DE CONSULTA",
'registration_medical_exam': "CADASTRO DE EXAME",
'': "ESTATÍSTICAS E INFORMAÇÕES"
}
if(urls_to_titulos.hasOwnProperty(rota)){
return urls_to_titulos[rota]
} else {
return "ESTATÍSTICAS E INFORMAÇÕES"
}
}
} |
package web.id.ramads.firebasesample
import android.app.ProgressDialog
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.QuerySnapshot
class DataActivity : AppCompatActivity() {
private lateinit var progressDialog: ProgressDialog
private val adapter = DataAdapter()
private val data = ArrayList<String>()
var db = FirebaseFirestore.getInstance()
private companion object {
private const val TAG = "___TEST___"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_data)
progressDialog = ProgressDialog(this@DataActivity)
data.add("Data Masih Kosong")
adapter.setData(data);
val list = findViewById<RecyclerView>(R.id.rv_data)
list.layoutManager = LinearLayoutManager(this)
list.adapter = adapter
// get data from firebase firestore
this.getDataFromFirestore()
}
private fun getDataFromFirestore() {
showProgressDialog()
db.collection("mahasiswa")
.get()
.addOnCompleteListener(OnCompleteListener<QuerySnapshot> { task ->
if (task.isSuccessful) {
data.clear()
for (document in task.result!!) {
var temp : String = document.data["nim"] as String
temp = temp + " - " + document.data["nama"] as String
Log.d(TAG, document.id + " => " + document.data)
data.add(temp)
}
adapter.setData(data)
hideProgressDialog()
} else {
Log.w(TAG, "Error getting documents.", task.exception)
hideProgressDialog()
}
})
}
private fun showProgressDialog() {
progressDialog.setTitle("Fetching Data")
progressDialog.setMessage("Please wait..")
progressDialog.show()
}
private fun hideProgressDialog() {
progressDialog.hide()
}
} |
package com.aditya.project.recursion.combination;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Combination {
public static void main(String[] args) {
int n = 3;
int[] a = new int[]{3, 1, 2};
System.out.print("Array : ");
Arrays.stream(a).forEach(value -> System.out.print(value + "\t"));
System.out.println();
List<List<Integer>> res = new ArrayList<>();
System.out.println("Power Set :");
func(0, n, a, new ArrayList<>(), res);
System.out.println(res);
res = new ArrayList<>();
System.out.println("Power Set In Reverse:");
funcReverse(0, n, a, new ArrayList<>(), res);
System.out.println(res);
}
// Power Set
// TC : O(2^N)
// SC : O(N)
private static void func(int i, int n, int[] a, List<Integer> curr, List<List<Integer>> res) {
if (i == n) {
res.add(new ArrayList<>(curr));
return;
}
curr.add(a[i]);
func(i + 1, n, a, curr, res);
curr.remove(curr.size() - 1);
func(i + 1, n, a, curr, res);
}
// Power Set Reverse
// TC : O(2^N)
// SC : O(N)
private static void funcReverse(int i, int n, int[] a, List<Integer> curr, List<List<Integer>> res) {
if (i == n) {
res.add(new ArrayList<>(curr));
return;
}
funcReverse(i + 1, n, a, curr, res);
curr.add(a[i]);
funcReverse(i + 1, n, a, curr, res);
curr.remove(curr.size() - 1);
}
} |
# 1) Design model (input, output size, forward pass)
# 2) Construct loss and optimizer
# 3) Training loop
# - forward pass: compute prediction
# - backward pass: gradients
# - update weights
import torch
import torchvision
import numpy as np
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
import pandas as pd
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder
from sklearn.model_selection import train_test_split
import math
# ------PYTORCH CLASSES------#
# creating class dataset
class CustomDataset(Dataset):
def __init__(self, dataset) -> None:
# data loading
# loading in dataset
xy = dataset
# splitting the values into the dependent and independent variables
# NOTE: look up the notation for SPLICING arrays
self.x = torch.from_numpy(xy[:, 1:])
self.y = torch.from_numpy(xy[:, [0]]).view(xy.shape[0], 1)
self.n_samples = xy.shape[0]
def __getitem__(self, index):
# dataset[0]
return self.x[index], self.y[index]
def __len__(self):
# len(dataset)
return self.n_samples
# creating the network
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size):
super(NeuralNet, self).__init__()
self.l1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.l2 = nn.Linear(hidden_size, 1)
def forward(self, x):
out = self.l1(x)
out = self.relu(out)
out = self.l2(out)
return out
# -----MODEL SETUP-----#
# setup GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# hyper parameters
input_size = 71
hidden_size = 64
num_classes = 1
num_epochs = 50
batch_size = 20
learning_rate = 0.0001
train_data = np.loadtxt(
"/Users/calebfernandes/Desktop/CaliHousingPredictions_PyTorch/data/tf_train_df.csv",
delimiter=",",
dtype=np.float32,
skiprows=1,
)
test_data = np.loadtxt(
"/Users/calebfernandes/Desktop/CaliHousingPredictions_PyTorch/data/tf_test_df.csv",
delimiter=",",
dtype=np.float32,
skiprows=1,
)
# turning dataset into a dataloader to be iterated over
# NOTE: SHAPE OF DATA: [20640, 73]
train = CustomDataset(train_data)
test = CustomDataset(test_data)
train = DataLoader(dataset=train, batch_size=batch_size, shuffle=True)
test = DataLoader(dataset=test, batch_size=batch_size, shuffle=True)
# setting up model, loss, and optimizer
model = NeuralNet(input_size, hidden_size)
MSE = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=1e-6)
# -----TRAINING LOOP-----
# NOTE: ASK JUSTIN ABOUT ITERATIONS AND BATCH_SIZE!!!
iterations = math.ceil(train.__len__() / batch_size)
print(train.__len__())
print()
for epoch in range(num_epochs):
model.train()
for i, (inputs, labels) in enumerate(train):
inputs.reshape(-1, 71).to(device)
labels = labels.to(device)
# loss function and optimizer
outputs = model(inputs)
loss = MSE(outputs, labels)
# backwards
loss.backward()
optimizer.step()
optimizer.zero_grad()
if (i + 1) % 100 == 0:
print(
f"epoch {epoch+1}/{num_epochs}, step {i+1}/{iterations}, loss = {loss.item():.4f}"
)
# -----TESTING AND ACCURACY-----
with torch.no_grad():
model.eval()
n_correct = 0
n_samples = 0
for images, labels in test:
# reshaping again
images = images.reshape(-1, 71).to(device)
labels = labels.to(device)
# getting predicted values
outputs = model(images)
# predictions
predictions = outputs
n_samples += labels.shape[0]
n_correct += abs(predictions - labels).sum().item()
print(predictions, labels)
acc = n_correct / n_samples
print(f"Accuracy: {acc}") |
package stockhw7.resources;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* The Index is meant to hold a string of the index
* of a stock, for ease of calling the index.
*/
public class IndexImpl implements Index {
private final String name;
private final String[][] separated;
Calendar lastUpdated;
private String index;
/**
* Constructor that initializes the given name
* and calls the api. for the index.
*
* @param name the name of the stock index.
*/
public IndexImpl(String name) {
this.name = name;
this.index = AlphaVantageDemo.getStockValues(name);
this.lastUpdated = new GregorianCalendar();
this.separated = setSeparated(this.index);
}
/**
* creates the index with a given name and a given
* index already grabbed.
*
* @param name the name of the index.
* @param index the values of the index.
*/
public IndexImpl(String name, String index) {
this.name = name;
this.index = index;
this.separated = setSeparated(this.index);
}
@Override
public String toString() {
return name;
}
@Override
public String getIndex() {
return index;
}
@Override
public void update() {
this.index = AlphaVantageDemo.getStockValues(name);
this.lastUpdated = new GregorianCalendar();
}
@Override
public Calendar getLastUpdate() {
return lastUpdated;
}
@Override
public double getValue(int year, int month, int day) throws IllegalArgumentException {
String[] firstDate = separated[1][0].split("-");
Calendar given;
int iVal = -1;
for (int i = 1; i < separated.length; i++) {
String[] date = separated[i][0].split("-");
try {
int test = Integer.valueOf(date[2]);
} catch (ArrayIndexOutOfBoundsException e) {
int stop = 0;
}
if (year == Integer.valueOf(date[0]) && month == Integer.valueOf(date[1])
&& day == Integer.valueOf(date[2])) {
iVal = i;
break;
}
}
//must adjust values so that it starts with 0 can possibly change so inputs have to be correct
given = new GregorianCalendar(year, month - 1, day - 1,
0, 0, 0);
//set the date as the first date in the list.
Calendar startDate = new GregorianCalendar(Integer.valueOf(firstDate[0]),
Integer.valueOf(firstDate[1]) - 1, Integer.valueOf(firstDate[2]) - 1,
0, 0, 0);
if (given.get(Calendar.YEAR) < 1792 || given.compareTo(startDate) > 0
|| given.get(Calendar.DAY_OF_WEEK) > 5) {
throw new IllegalArgumentException("invalid date input: the year given is either "
+ "too large or too small");
}
if (iVal == -1) {
throw new IllegalArgumentException("invalid date input");
}
double output = (Math.round((Double.parseDouble(separated[iVal][2])
+ Double.parseDouble(separated[iVal][3])) / 2) * 100);
return output / 100;
}
@Override
public boolean equals(Object o) {
return false;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
@Override
public int compareTo(Index o) {
return this.toString().compareTo(index);
}
private String[][] setSeparated(String index) {
String[] newline = index.split("\n");
String[][] result = new String[newline.length][6];
if (index.length() > 0) {
for (int i = 0; i < newline.length; i++) {
System.arraycopy(newline[i].split(","), 0, result[i], 0, 6);
}
}
return result;
}
} |
package br.oficial.savestudents.debug_mode.view.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import br.oficial.savestudents.databinding.ActivityEditTimelineBinding
import br.oficial.savestudents.debug_mode.controller.CreateTimelineController
import br.oficial.savestudents.debug_mode.model.contract.CreateTimelineContract
import br.oficial.savestudents.debug_mode.model.contract.CreateTimelineItemDialogContract
import br.oficial.savestudents.debug_mode.model.contract.EditTimelineItemDialogContract
import br.oficial.savestudents.debug_mode.view.fragment.CreateTimelineItemDialog
import br.oficial.savestudents.debug_mode.view.fragment.EditTimelineItemDialog
import br.oficial.savestudents.debug_mode.viewModel.EditTimelineViewModel
import com.example.data_transfer.model.CreateTimelineItem
import com.example.data_transfer.model.TimelineItem
import com.example.data_transfer.model.asDomainModel
import com.example.data_transfer.model.entity.CreateTimelineItemEntity
class EditTimelineActivity : AppCompatActivity() {
private lateinit var binding: ActivityEditTimelineBinding
private lateinit var timelineItem: TimelineItem
private val controller by lazy { CreateTimelineController(contract) }
private val viewModel by lazy { EditTimelineViewModel() }
private var timelineItemsList: MutableList<CreateTimelineItem> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEditTimelineBinding.inflate(layoutInflater)
setContentView(binding.root)
controller()
fetchTimelineItem()
observers()
handleAddNewTimeline()
handleBackButton()
handleSubmitButton()
}
private fun controller() {
binding.timelineListRv.apply {
setController(controller)
layoutManager = LinearLayoutManager(applicationContext)
requestModelBuild()
}
}
private fun observers() {
viewModel.timelineItem.observe(this) { timelineItem ->
controller.setTimelineItemsList(timelineItem.timelineList!!)
timelineItemsList = timelineItem.timelineList!!
this.timelineItem = timelineItem
}
viewModel.updateTimelineItem.observe(this) {
Toast.makeText(
applicationContext,
"Cronograma atualizado com sucesso.",
Toast.LENGTH_SHORT
).show()
finish()
}
}
private fun fetchTimelineItem() {
val id = intent?.getStringExtra(ID)
id?.let { viewModel.getSubjectItemPerId(it) }
}
private fun handleAddNewTimeline() {
binding.addTimelineButton.setOnClickListener {
CreateTimelineItemDialog(contractDialog).show(
supportFragmentManager,
CreateTimelineItemDialog.TAG
)
}
}
private fun handleBackButton() {
binding.backContainer.setOnClickListener {
finish()
}
}
private fun handleSubmitButton() {
binding.buttonSubmit.setOnClickListener {
if (validateTimelineItems()) {
updateTimelineListItem(timelineItem)
} else {
Toast.makeText(applicationContext, "Crie pelomenos uma matéria", Toast.LENGTH_SHORT)
.show()
}
}
}
private fun updateTimelineListItem(timelineItem: TimelineItem) {
viewModel.updateTimelineItem(timelineItem)
}
private fun validateTimelineItems(): Boolean {
if (timelineItemsList.isNotEmpty()) {
return true
}
return false
}
private fun createTimelineItem(timelineItem: CreateTimelineItem) {
timelineItemsList.add(timelineItem)
controller.setTimelineItemsList(timelineItemsList)
}
private fun deleteTimelineItem(id: String) {
val filterElementDelete = timelineItemsList.find { item -> item.id.toString() == id }
timelineItemsList.remove(filterElementDelete)
controller.setTimelineItemsList(timelineItemsList)
}
private fun updateTimelineItem(timeline: CreateTimelineItem) {
val item = timelineItemsList.find { it.id == timeline.id }
val index = timelineItemsList.indexOf(item)
timelineItemsList[index] = timeline
controller.setTimelineItemsList(timelineItemsList)
timelineItem.copy(timelineList = timelineItemsList)
}
val contract = object : CreateTimelineContract {
override fun clickEditButtonListener(timelineItem: CreateTimelineItem) {
EditTimelineItemDialog(editContractDialog, timelineItem).show(
supportFragmentManager,
EditTimelineItemDialog.TAG
)
}
override fun clickDeleteButtonListener(id: Int) {
deleteTimelineItem(id.toString())
}
}
private val contractDialog = object : CreateTimelineItemDialogContract {
override fun createTimelineItemListener(timelineItem: CreateTimelineItemEntity) {
createTimelineItem(timelineItem.asDomainModel())
}
}
private val editContractDialog = object : EditTimelineItemDialogContract {
override fun editTimelineItemListener(timelineItem: CreateTimelineItemEntity) {
updateTimelineItem(timelineItem.asDomainModel())
}
}
companion object {
private const val ID = "id"
fun newInstance(context: Context, id: String?): Intent {
val intent = Intent(context, EditTimelineActivity::class.java)
saveBundle(intent, id)
return intent
}
private fun saveBundle(intent: Intent, id: String?) {
val bundle = Bundle().apply {
this.putString(ID, id)
}
intent.putExtras(bundle)
}
}
} |
//
// GridPhotoUploader.swift
// SwiftCamera
//
// Created by Kiarra Villaraza on 7/1/22.
//
/*
File to upload images to Firestore
*/
import Firebase
import UIKit
import FirebaseStorage
struct GridPhotoUploader {
//upload an image and return location of image with url
/*
method used to upload user's captured images to firebase and returns the location of the images with urls
*/
static func uploadGridPhotos(images: [UIImage], completion: @escaping([String]) -> Void) {
//returned array of image urls
var postImagesUrl: [String] = []
images.forEach { image in
//lowers quality of image but reduces image size to make the downloaded file smaller to make app faster and limit data usage
guard let imageData = image.jpegData(compressionQuality: 0.5) else { return }
let filename = NSUUID().uuidString
//creates a path for the images in storage
let ref = Storage.storage().reference(withPath: "/grids_picture/\(filename)")
//uploading data
ref.putData(imageData, metadata: nil) { metadata, error in
if let error = error {
print("DEBUG: Failed to upload post image \(error.localizedDescription)")
return
}
//urls for images
ref.downloadURL { url, error in
guard let imageUrl = url?.absoluteString else { return }
postImagesUrl.append(imageUrl)
completion(postImagesUrl)
}
}
}
print("DEBUG: Images were stored successfully!")
}
} |
import { injectable, inject } from 'tsyringe'
import Product from '../infra/typeorm/entities/Product'
import IProductsRepository from '../repositories/IProductsRepository'
import IPaginationOptionsDTO from '../../dtos/IPaginationOptionsDTO'
import IWishRepository from '../repositories/IWishRepository'
import ICategoriesRepository from '../repositories/ICategoriesRepository'
import Categories from '../infra/typeorm/entities/ProductCategory'
import {
IFilterOrderProduct,
IFilterProduct,
} from '../infra/typeorm/repositories/ProductsRepository'
import TimeDiscountRepository from '../infra/typeorm/repositories/TimeDiscountRepository'
import TimeDiscount from '../infra/typeorm/entities/TimeDiscount'
import dayjs from 'dayjs'
import ITimeDiscountRepository from '../repositories/ITimeDiscountRepository'
@injectable()
class IndexProductsService {
constructor(
@inject('ProductsRepository')
private readonly productsRepository: IProductsRepository,
@inject('WishRepository')
private readonly wishRepository: IWishRepository,
@inject('TimeDiscountRepository')
private readonly timeDiscountRepository: ITimeDiscountRepository,
@inject('CategoriesRepository')
private readonly categoriesRepository: ICategoriesRepository,
) {}
public async execute(
options: IPaginationOptionsDTO,
filter: IFilterProduct,
order: IFilterOrderProduct,
): Promise<[Product[], number]> {
const products = await this.productsRepository.findAndCount(
options,
filter,
order,
)
for (const product of products[0]) {
const wish = await this.wishRepository.findByProductAndUser(
product.id,
filter.userId,
)
if (product.categories) {
const categories: Categories[] = []
for (const categoryId of JSON.parse(product.categories)) {
const category = await this.categoriesRepository.findById(categoryId)
if (category) {
categories.push(category)
}
}
product.categories_items = categories
}
product.wish = wish ?? null
if (product.time_discount && product.time_discount_id) {
const start = dayjs(product.time_discount.startDate)
const end = dayjs(product.time_discount.endDate)
await this.timeDiscountExpired(end.isBefore(start), product)
}
}
return products
}
async timeDiscountExpired(
isExpired: boolean,
product: Product,
): Promise<void> {
if (isExpired) {
product.time_discount = null
if (product.time_discount_id) {
const timeDiscount = await this.timeDiscountRepository.findById(
product.time_discount_id,
)
if (timeDiscount) {
timeDiscount.status = 'expired'
await this.timeDiscountRepository.save(timeDiscount)
}
}
}
}
}
export default IndexProductsService |
<?php
declare (strict_types=1);
namespace Rector\Renaming\Rector\MethodCall;
use PhpParser\BuilderHelpers;
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Identifier;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\ClassMethod;
use Rector\Core\Contract\Rector\ConfigurableRectorInterface;
use Rector\Core\NodeManipulator\ClassManipulator;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Renaming\Collector\MethodCallRenameCollector;
use Rector\Renaming\Contract\MethodCallRenameInterface;
use Rector\Renaming\ValueObject\MethodCallRename;
use Rector\Renaming\ValueObject\MethodCallRenameWithArrayKey;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use RectorPrefix20211020\Webmozart\Assert\Assert;
/**
* @see \Rector\Tests\Renaming\Rector\MethodCall\RenameMethodRector\RenameMethodRectorTest
*/
final class RenameMethodRector extends \Rector\Core\Rector\AbstractRector implements \Rector\Core\Contract\Rector\ConfigurableRectorInterface
{
/**
* @var string
*/
public const METHOD_CALL_RENAMES = 'method_call_renames';
/**
* @var MethodCallRenameInterface[]
*/
private $methodCallRenames = [];
/**
* @var \Rector\Core\NodeManipulator\ClassManipulator
*/
private $classManipulator;
/**
* @var \Rector\Renaming\Collector\MethodCallRenameCollector
*/
private $methodCallRenameCollector;
public function __construct(\Rector\Core\NodeManipulator\ClassManipulator $classManipulator, \Rector\Renaming\Collector\MethodCallRenameCollector $methodCallRenameCollector)
{
$this->classManipulator = $classManipulator;
$this->methodCallRenameCollector = $methodCallRenameCollector;
}
public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
{
return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns method names to new ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE'
$someObject = new SomeExampleClass;
$someObject->oldMethod();
CODE_SAMPLE
, <<<'CODE_SAMPLE'
$someObject = new SomeExampleClass;
$someObject->newMethod();
CODE_SAMPLE
, [self::METHOD_CALL_RENAMES => [new \Rector\Renaming\ValueObject\MethodCallRename('SomeExampleClass', 'oldMethod', 'newMethod')]])]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes() : array
{
return [\PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\StaticCall::class, \PhpParser\Node\Stmt\ClassMethod::class];
}
/**
* @param MethodCall|StaticCall|ClassMethod $node
*/
public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node
{
foreach ($this->methodCallRenames as $methodCallRename) {
$implementsInterface = $this->classManipulator->hasParentMethodOrInterface($methodCallRename->getOldObjectType(), $methodCallRename->getOldMethod());
if ($implementsInterface) {
continue;
}
if (!$this->nodeTypeResolver->isMethodStaticCallOrClassMethodObjectType($node, $methodCallRename->getOldObjectType())) {
continue;
}
if (!$this->isName($node->name, $methodCallRename->getOldMethod())) {
continue;
}
if ($this->shouldSkipClassMethod($node, $methodCallRename)) {
continue;
}
$node->name = new \PhpParser\Node\Identifier($methodCallRename->getNewMethod());
if ($methodCallRename instanceof \Rector\Renaming\ValueObject\MethodCallRenameWithArrayKey && !$node instanceof \PhpParser\Node\Stmt\ClassMethod) {
return new \PhpParser\Node\Expr\ArrayDimFetch($node, \PhpParser\BuilderHelpers::normalizeValue($methodCallRename->getArrayKey()));
}
return $node;
}
return null;
}
/**
* @param array<string, MethodCallRenameInterface[]> $configuration
*/
public function configure(array $configuration) : void
{
$methodCallRenames = $configuration[self::METHOD_CALL_RENAMES] ?? [];
\RectorPrefix20211020\Webmozart\Assert\Assert::allIsInstanceOf($methodCallRenames, \Rector\Renaming\Contract\MethodCallRenameInterface::class);
$this->methodCallRenames = $methodCallRenames;
$this->methodCallRenameCollector->addMethodCallRenames($methodCallRenames);
}
/**
* @param \PhpParser\Node\Expr\MethodCall|\PhpParser\Node\Expr\StaticCall|\PhpParser\Node\Stmt\ClassMethod $node
*/
private function shouldSkipClassMethod($node, \Rector\Renaming\Contract\MethodCallRenameInterface $methodCallRename) : bool
{
if (!$node instanceof \PhpParser\Node\Stmt\ClassMethod) {
return \false;
}
return $this->shouldSkipForAlreadyExistingClassMethod($node, $methodCallRename);
}
private function shouldSkipForAlreadyExistingClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \Rector\Renaming\Contract\MethodCallRenameInterface $methodCallRename) : bool
{
$classLike = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE);
if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) {
return \false;
}
return (bool) $classLike->getMethod($methodCallRename->getNewMethod());
}
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Answer to the quetions</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body class="container">
<!-- navbar start -->
<nav class="navbar navbar-expand-lg bg-light p-4">
<div class="container-fluid">
<a class="navbar-brand bg-primary text-white px-2 rounded-2" href="#">Global</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<a class="navbar-brand text-primary" href="#">News</a>
</ul>
<form class="d-flex" role="search">
<a class="navbar-brand text-primary" href="index.html">Home</a>
<a class="navbar-brand" href="#">Blog</a>
<img src="image/Avatar.png" alt="">
</form>
</div>
</div>
</nav>
<!-- navbar end -->
<!-- between var let and const -->
<section>
<table class="table caption-top border border-1">
<h2 class="mb-4 text-success">Differences between var, let, and const</h2>
<thead>
<tr>
<th scope="col">No</th>
<th scope="col">var</th>
<th scope="col">let</th>
<th scope="col">const</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>The scope of a var variable is functional scope.</td>
<td>The scope of a let variable is block scope.</td>
<td>The scope of a const variable is block scope.</td>
</tr>
<tr>
<th scope="row">2</th>
<td>It can be declared without initialization.</td>
<td>It can be declared without initialization.</td>
<td>It cannot be declared without initialization.</td>
</tr>
<tr>
<th scope="row">3</th>
<td>It can be accessed without initialization as its default value is “undefined”.</td>
<td>It cannot be accessed without initialization otherwise it will give ‘referenceError’.</td>
<td>It cannot be accessed without initialization, as it cannot be declared without initialization.</td>
</tr>
<tr>
<th scope="row">4</th>
<td>It can be updated and re-declared into the scope.</td>
<td>It can be updated but cannot be re-declared into the scope.</td>
<td>It cannot be updated or re-declared into the scope.</td>
</tr>
</tbody>
</table>
</section>
<!-- between regular function and arrow funtion -->
<section>
<table class="table caption-top border border-1">
<h2 class="mb-4 text-success">between regular function and arrow funtion</h2>
<thead>
<tr>
<th scope="col">NO</th>
<th scope="col">regular function</th>
<th scope="col">arrow function</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Inside of a regular JavaScript function, this value (aka the execution context) is dynamic. <br> const myObject = {
method() {
console.log(this);
}
};
myObject.method(); </td>
<td>The behavior of this inside of an arrow function differs considerably from the regular function's this behavior. The arrow function doesn't define its own execution context. <br>
const myObject = {
myMethod(items) {
console.log(this);
const callback = () => {
console.log(this);
};
items.forEach(callback);
}
};
myObject.myMethod([1, 2, 3]); </td>
</tr>
<tr>
<th scope="row">2</th>
<td>As seen in the previous section, the regular function can easily construct objects.
For example, the new Car() function creates instances of a car: <br>
function Car(color) {
this.color = color;
}
const redCar = new Car('red');</td>
<td>A consequence of this resolved lexically is that an arrow function cannot be used as a constructor.
If you try to invoke an arrow function prefixed with new keyword, JavaScrip throws an error:
<br>
const Car = (color) => {
this.color = color;
};
const redCar = new Car('red'); // TypeError: Car is not a constructor</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Inside the body of a regular function, arguments is a special array-like object containing the list of arguments with which the function has been invoked.</td>
<td>On the other side, no arguments special keyword is defined inside an arrow function.
Again (same as with this value), the arguments object is resolved lexically: the arrow function accesses arguments from the outer function.</td>
</tr>
</tbody>
</table>
</section>
<!-- why we can use template string -->
<section>
<h2 class="text-success">why we can use template strings?</h2>
<p class="mt-4">
Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, for string interpolation with embedded expressions, and for special constructs called tagged templates.
Template literals are sometimes informally called template strings, because they are used most commonly for string interpolation (to create strings by doing substitution of placeholders). However, a tagged template literal may not result in a string; it can be used with a custom tag function to perform whatever operations you want on the different parts of the template literal.
</p>
</section>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
</body>
</html> |
import React from "react";
const Css = () => {
return (
<div>
<h1> Css </h1>
<h3>Use of fontAwesome</h3>
<div>
{`<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/brands.min.css"
integrity="sha512-L+sMmtHht2t5phORf0xXFdTC0rSlML1XcraLTrABli/0MMMylsJi3XA23ReVQkZ7jLkOEIMicWGItyK4CAt2Xw=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/fontawesome.min.css"
integrity="sha512-cHxvm20nkjOUySu7jdwiUxgGy11vuVPE9YeK89geLMLMMEOcKFyS2i+8wo0FOwyQO/bL8Bvq1KMsqK4bbOsPnA=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
`}
</div>
<h1>CSS (cascading style sheet)</h1>
<p> use to decorate a html page </p>
<p>Three way to write css </p>
<ul className="ul_list">
<li>inline css</li>
<li>Internal css</li>
<li>external css</li>
</ul>
<p>
<mark>Externsal css : -</mark> use a seperate file to write css. <br />{" "}
importing file in html using link tag, import should we inside a{" "}
{`<head>`} tag
{`<link ref="styleSheet" href="filename >`}
</p>
<p>
<mark>Internal css :- </mark>
internal css write inside then head tag using the styel tag like{" "}
<pre>
{` <head>
<style>
h1{
color:red;
}
</style>
</head>`}
</pre>
<mark>disADV of internal css ;-</mark>
use only in sigle page we can not use it in other file
</p>
<p>
<mark>Inline css : -</mark>
<pre>
{` inline css is used inside the tag
EXAMPLE :-
<h1 style="color> hello </h1>
OutPut : -`}
<h1 style={{ color: "red" }}> Hello</h1>
</pre>
</p>
<p>
{" "}
<mark>disADV of inline css</mark> only use for a perticular tag
</p>
<div>
<h3> CSS selector</h3>
<ul className="ul_list">
<li>tag selector : - use tag name to give css</li>
<li>Id selector : - use id name to give css </li>
<li>Class selector :- use class name to give css </li>
<li>
universal selector(*) :- using this we can aplly css to all the tags{" "}
</li>
</ul>
</div>
</div>
);
};
export default Css; |
import React, { PropTypes } from 'react';
import { cummulativeSeperation } from '../helpers';
import TimelineDot from './TimelineDot';
/**
* The markup Information for all the events on the horizontal timeline.
*
* @param {object} props The props from parent mainly styles
* @return {StatelessFunctionalReactComponent} Markup Information for the fader
*/
const EventsBar = ({ events, selectedIndex, styles, handleDateClick, labelWidth }) => (
<ol
className='events-bar'
style={{
listStyle: 'none'
}}
>
{events.map((event, index) =>
<TimelineDot
distanceFromOrigin={event.distance}
label={event.label}
date={event.date}
index={index}
key={index}
onClick={handleDateClick}
selected={selectedIndex}
styles={styles}
labelWidth={labelWidth}
/>
)}
</ol>
);
/**
* The styles that parent will provide
* @type {Object}
*/
export default EventsBar; |
.Dd $Mdocdate$
.Dt SNAC 8
.Os
.Sh NAME
.Nm snac
.Nd snac administration
.Sh DESCRIPTION
The
.Nm
daemon processes messages from other servers in the Fediverse
using the ActivityPub protocol.
.Pp
This is the admin manual. For user operation, see
.Xr snac 1 .
For file and data formats, see
.Xr snac 5 .
.Ss Installation
Install the OpenSSL and urllib3 Python3 external packages, and run as root
.Bd -literal -offset indent
make install
.Ed
.Ss Database Initialization
Once
.Nm
is properly installed on the system, designate a directory where
the server and user data are to be stored. This directory
must not exist yet.
.Nm
must always be run as a regular user; you can create one for
it or use your own. To initialize the database, execute
.Bd -literal -offset indent
snac init $HOME/snac-data
.Ed
.Pp
A small set of questions will be asked regarding the installation,
specially the host name it will run under, the local network address
and port
.Nm
will listen to, the optional path prefix and possibly other things.
.Pp
You can launch the
.Nm
process by running
.Bd -literal -offset indent
snac httpd $HOME/snac-data
.Ed
.Pp
Use a web browser to connect to the specified address and port. You
should see a greeting page.
.Pp
Log messages are sent to the standard error stream. By default, only
relevant information is written there. You can increase the debugging
level by editing the 'dbglevel' field in the
.Pa server.json
file or by setting a numeric value between 0 and 3 to the DEBUG
environment variable, see below.
.Pp
If you run
.Nm
in an OS controlled by
.Xr systemd 1 ,
you can prepare a user service to start/stop the daemon. Following the
previous example, create the file
.Pa ~/.config/systemd/user/snac.service
with the following content:
.Bd -literal -offset indent
[Unit]
Description=snac daemon
[Service]
Type=simple
Restart=always
RestartSec=5
ExecStart=/usr/local/bin/snac httpd /path/to/snac-data
[Install]
WantedBy=default.target
.Ed
.Pp
And activate it by running
.Bd -literal -offset indent
systemctl --user enable snac.service
systemctl --user start snac.service
.Ed
.Pp
For other operating systems, please read the appropriate documentation
on how to install a daemon as a non-root service.
.Ss Server Setup
.Pp
An http server with TLS and proxying support must already be
installed and configured.
.Nm
runs as a daemon and listens on a TCP/IP socket, preferrably
on a local interface. It can serve the full domain or only
a directory. The http server must be configured to route to the
.Nm
socket all related traffic and also the webfinger standard
address. The Host header must be propagated.
See the examples below.
.Ss Adding Users
.Pp
Users must be created from the command line.
You can do it by running
.Bd -literal -offset indent
snac adduser $HOME/snac-data
.Ed
.Pp
All needed data will be prompted for. There is no artificial limit
on the number of users that can be created.
.Ss Customization
The
.Pa server.json
configuration file allows some behaviour tuning:
.Bl -tag -width tenletters
.It Ic host
The host name.
.It Ic prefix
The URL path prefix.
.It Ic address
The listen network address.
.It Ic port
The list network port.
.It Ic dbglevel
The debug level. An integer value, being 0 the less verbose (the default).
.It Ic layout
The disk storage layout version. Never touch this.
.It Ic queue_retry_max
Messages sent out are stored in a queue. If the posting of a messages fails,
it's re-enqueued for later. This integer configures the maximum count of
times the sending will be retried.
.It Ic queue_retry_minutes
The number of minutes to wait before the failed posting of a message is
retried. This is not linear, but multipled by the number of retries
already done.
.It Ic max_timeline_entries
This is the maximum timeline entries shown in the web interface.
.It Ic timeline_purge_days
Entries in the timeline older that this number of days are purged.
.It Ic css_urls
This is a list of URLs to CSS files that will be inserted, in this order,
in the HTML before the user CSS. Use these files to configure the global
site layout.
.El
.Pp
You must restart the server to make effective these changes.
.Pp
If a file named
.Pa greeting.html
is present in the server base directory, it will be returned whenever
the base URL of the server is requested. Fill it with whatever
information about the instance you want to supply to people
visiting the server, like sign up requirements, site policies
and such. The special %userlist% mark in the file will cause
the list of users in this instance to be inserted.
.Pp
Users can change a bit of information about themselves from the
web interface. See
.Xr snac 1
for details. Further, every user has a private CSS file in their
.Pa static/style.css
that can be modified to suit their needs. This file contains
a copy of the
.Pa style.css
file in the server root and it's inserted into the HTML output.
It's not easily accesible from the web interface to avoid users
shooting themselves in the foot by destroying everything.
.Ss Old Data Purging
The Fediverse generates big loads of data that get old and
stale very quickly. By default,
.Nm
does not delete anything; you must do it explicitly by issuing a
.Ar purge
command periodically. A cron entry will suffice. You can add the
following to the
.Nm
user's crontab:
.Bd -literal -offset indent
# execute a data purge on Sundays at 4 am
0 4 * * 0 /usr/local/bin/snac purge /path/to/snac-data
.Ed
.Pp
Other directories, like
.Pa archive/ ,
can grow very quickly if the debug level is greater than 0. These
files must be deleted manually.
.Pp
The user-generated data (the local timeline) is never deleted.
.Ss ActivityPub Support
These are the following activities and objects that
.Nm
supports:
.Bl -tag -width tenletters
.It Vt Follow
Complete support, on input and output.
.It Vt Undo
For
.Vt Follow ,
.Vt Like
and
.Vt Announce
objects, on input and output.
.It Vt Create
For
.Vt Note
objects, on input and output.
.It Vt Accept
For
.Vt Follow
objects, on input and output.
.It Vt Like
For
.Vt Note
objects, on input and output.
.It Vt Announce
For
.Vt Note
objects, on input and output.
.It Vt Update
For
.Vt Person
objects, on input and output. Support for updating
.Vt Note
objects will probably be added in the future.
.It Vt Delete
Supported for
.Vt Note
and
.Vt Tomsbtone
objects on input, and for
.Vt Note
objects on output.
.El
.Pp
The rest of activities and objects are dropped on input.
.Pp
There is partial support for
.Vt OrderedCollection
objects in the
.Pa /outbox
(with the last 20 entries of the local timeline shown). No pagination
is supported. Intentionally, the
.Pa /followers
and
.Pa /following
paths return empty lists.
.Ss Other Considerations
.Nm
stores all the messages it receives as JSON files, which are usually
bloated and filled with redundant information. Using a filesystem with
file compression enabled (like btrfs or zfs) will probably be a good
choice to store the
.Nm
database into.
.Sh ENVIRONMENT
.Bl -tag -width Ds
.It Ev DEBUG
Overrides the debugging level from the server 'dbglevel' configuration
variable. Set it to an integer value. The higher, the deeper in meaningless
verbiage you'll find yourself into.
.El
.Sh EXAMPLES
You want to install the
.Nm
Fediverse daemon in the host example.com, that is correctly configured
with a valid TLS certificate and running the nginx httpd server.
The service will be installed under the
.Pa fedi
location. Two users, walter and jessie, will be hosted in the system.
Their Fediverse presence addresses will be https://example.com/fedi/walter
and https://example.com/fedi/jesse, respectively. They will be known
in the Fediverse as @walter@example.com and @jesse@example.com. The
.Nm
daemon will run as the user snacusr in the system and listen to the
localhost:8001 network socket. All data will be stored in the
.Pa /home/snacusr/fedidata
directory.
.Pp
Log into the system as snacusr and execute:
.Bd -literal -offset indent
snac init /home/snacusr/fedidata
.Ed
.Pp
Answer "example.com" to the host name question, "/fedi" to the path
prefix question, "localhost" to the address and "8001" to the port.
.Pp
Create the users
.Bd -literal -offset indent
snac adduser /home/snacusr/fedidata walter
snac adduser /home/snacusr/fedidata jesse
.Ed
.Pp
Answer the questions with reasonable values.
.Pp
Execute the server:
.Bd -literal -offset indent
snac httpd /home/snacusr/fedidata
.Ed
.Pp
Edit the nginx configuration and add the following snippet to the
example.com server section:
.Bd -literal -offset indent
location /.well-known/webfinger {
proxy_pass http://localhost:8001;
proxy_set_header Host $http_host;
}
location /fedi {
proxy_pass http://localhost:8001;
proxy_set_header Host $http_host;
}
.Ed
.Pp
Restart the nginx daemon and connect to https://example.com/fedi/walter.
The empty, default screen will be shown. Enter the admin section with the
credentials defined for this user. Search people, start following
them, engage in arid discussions and generally enjoy the frustrating
experience of Social Media.
.Sh SEE ALSO
.Xr snac 1 ,
.Xr snac 5
.Sh AUTHORS
.An grunfink
.Sh LICENSE
See the LICENSE file for details.
.Sh CAVEATS
JSON files are fragile when modified by hand. Take care. |
//
// EditCards.swift
// Flashzilla
//
// Created by Yi An Chen on 2022/3/22.
//
import SwiftUI
struct EditCards: View {
@Environment(\.dismiss) var dismiss
@State private var cards = [Card]()
@State private var newPrompt = ""
@State private var newAnswer = ""
let savedPath = FileManager.documentsDirectory.appendingPathComponent("Cards")
var body: some View {
NavigationView {
List {
Section("Add new card") {
TextField("Prompt", text: $newPrompt)
TextField("Answer", text: $newAnswer)
Button("Add card", action: addCard)
}
Section {
ForEach(cards) { card in
VStack(alignment: .leading) {
Text(card.prompt)
.font(.headline)
Text(card.answer)
.foregroundColor(.secondary)
}
}
.onDelete(perform: removeCards)
}
}
.navigationBarTitle("Edit Cards")
.toolbar {
Button("Done", action: done)
}
.listStyle(.grouped)
.onAppear {
cards = Card.load()
}
}
}
func done() {
dismiss()
}
func addCard() {
let trimmedPrompt = newPrompt.trimmingCharacters(in: .whitespaces)
let trimmedAnswer = newAnswer.trimmingCharacters(in: .whitespaces)
guard trimmedPrompt.isEmpty == false && trimmedAnswer.isEmpty == false else { return }
let card = Card(id: UUID(), prompt: trimmedPrompt, answer: trimmedAnswer)
cards.insert(card, at: 0)
Card.save(cards)
newPrompt = ""
newAnswer = ""
}
func removeCards(at offsets: IndexSet) {
cards.remove(atOffsets: offsets)
Card.save(cards)
}
}
struct EditCards_Previews: PreviewProvider {
static var previews: some View {
EditCards()
}
} |
from django.forms import TimeInput
from clients.models import Client, Newsletter, Message
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, AuthenticationForm
from clients.models import User
class StyleFormMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name, field in self.fields.items():
if isinstance(field.widget, forms.widgets.CheckboxInput):
field.widget.attrs['class'] = 'form-check-input'
else:
field.widget.attrs['class'] = 'form-control'
class ClientForm(StyleFormMixin, forms.ModelForm):
class Meta:
model = Client
fields = '__all__'
class NewsletterForm(StyleFormMixin, forms.ModelForm):
class Meta:
model = Newsletter
exclude = ("status",)
widgets = {
'time': TimeInput(attrs={'type': 'time'}),
}
def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
if user:
self.fields['client'].queryset = Client.objects.filter(user=user)
class MessageForm(StyleFormMixin, forms.ModelForm):
class Meta:
model = Message
fields = '__all__'
class LoginUserForm(StyleFormMixin, AuthenticationForm):
username = forms.EmailField(widget=forms.TextInput(attrs={'autofocus': True}))
password = forms.CharField(
label="Password",
strip=False,
widget=forms.PasswordInput(attrs={'autocomplete': 'current-password'}),
)
class UserRegisterForm(StyleFormMixin, UserCreationForm):
class Meta:
model = User
fields = ('email', 'password1', 'password2')
class UserProfileForm(StyleFormMixin, UserChangeForm):
class Meta:
model = User
fields = ('email', 'first_name', 'last_name')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['password'].widget = forms.HiddenInput() |
package main
import (
"fmt"
"sync"
"time"
)
// Job represents the task to be executed by a worker
type Job struct {
ID int
}
// WorkerPool represents a pool of worker goroutines
type WorkerPool struct {
numWorkers int
jobQueue chan Job
results chan int
wg sync.WaitGroup
}
// NewWorkerPool creates a new worker pool with the specified number of workers
func NewWorkerPool(numWorkers, jobQueueSize int) *WorkerPool {
return &WorkerPool{
numWorkers: numWorkers,
jobQueue: make(chan Job, jobQueueSize),
results: make(chan int, jobQueueSize),
}
}
// worker function to process jobs from the queue
func (wp *WorkerPool) worker(id int) {
defer wp.wg.Done()
for job := range wp.jobQueue {
// Do the actual work here
fmt.Printf("Worker %d started job %d\n", id, job.ID)
time.Sleep(time.Second) // Simulating work
fmt.Printf("Worker %d finished job %d\n", id, job.ID)
wp.results <- job.ID
}
}
// Start starts the worker pool and dispatches jobs to workers
func (wp *WorkerPool) Start() {
for i := 1; i <= wp.numWorkers; i++ {
wp.wg.Add(1)
go wp.worker(i)
}
}
// Wait waits for all workers to finish and closes the results channel
func (wp *WorkerPool) Wait() {
wp.wg.Wait()
close(wp.results)
}
// AddJob adds a job to the job queue
func (wp *WorkerPool) AddJob(job Job) {
wp.jobQueue <- job
}
// CollectResults collects and prints results from the results channel
func (wp *WorkerPool) CollectResults() {
for result := range wp.results {
fmt.Printf("Result received for job %d\n", result)
}
}
func main() {
numWorkers := 3
numJobs := 10
workerPool := NewWorkerPool(numWorkers, numJobs)
// Adding jobs to the Job Queue
for i := 1; i <= numJobs; i++ {
workerPool.AddJob(Job{ID: i})
}
close(workerPool.jobQueue)
workerPool.Start()
workerPool.Wait()
workerPool.CollectResults()
} |
const socketio = require('socket.io');
const http = require('http');
const log = require('../utils/logUtil.js');
const ipUtil = require('../utils/ipUtil');
const cookieUtil = require('../utils/cookieUtil');
const config = require('./config');
const store = require('../store');//session容器
module.exports = function (app) {
let server = http.createServer(app.callback());
let io = socketio(server);
server.listen(666);
log.success('消息服务连接成功...');
/**
* 监听客户端连接
*/
io.on('connection', function (socket) {
let cookie = socket.request.headers.cookie;
let sessionId = cookieUtil.getCookie(cookie, config.sessionIdKey);
console.log(store.get(sessionId));
let ip = socket.handshake.address.substring(7);
// 获取当前客户端地址位置信息
ipUtil.getIpInfo(ip, function (err, result) {
if (err) {
log.error(err);
} else {
let position = result.data;
broadcast(position.city + '进入房间!');
}
});
/**
* 监听客户端发送的消息
*/
socket.on('sendMsg', function (msg) {
console.log(msg);
});
});
/**
* 广播消息
*/
function broadcast(msg) {
io.sockets.emit("broadcast", msg);
}
/**
* 定向消息
*/
function directional(sid, msg) {
io.sockets.socket(sid).emit("directional", msg);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->
<link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
<link rel="stylesheet" href="styles.css">
<script src="https://kit.fontawesome.com/46ed42cf35.js" crossorigin="anonymous"></script>
<!-- <link rel="stylesheet" href="fontawesome-free-6.4.0-web/css/all.css"> -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
<title>Huddle landing page </title>
<!-- Feel free to remove these styles or customise in your own stylesheet 👍 -->
<style>
.attribution { font-size: 11px; text-align: center; }
.attribution a { color: hsl(228, 45%, 44%); }
</style>
</head>
<body>
<!-- BG -->
<section class="bg-hero">
<div class="header">
<a href=""><img src="images/logo.svg" alt="" class="logo"></a>
<nav class="header-link">
<ul class="link-items">
<li><a href="">Try It Free</a></li>
</ul>
</nav>
</div>
<div class="hero-text">
<h1 class="hero-text-h1">Build The Community <br> Your Fans Will Love</h1>
<p class="hero-text-p"> Huddle re-imagines the way we build communities. You have <br> a voice, but so does your audience.
Create connections with <br> your users as you engage in genuine discussion</p>
<button><a href="">Get Started For Free</a></button>
</div>
<div class="hero-img">
<img src="images/illustration-mockups.svg" alt="" class="hero-mockup">
</div>
</section>
<!-- COL-1 -->
<section class="col-1">
<div class="rectangle-col">
<div class="rectangle-col-content-1">
<div class="rectangle-col-content-1-text">
<h2 style="margin-bottom: 20px;">Grow Together</h2>
<p> Generate meaningful discussions with your audience and <br> build a strong, loyal community. Think of the insightful <br> conversations you miss out on with a feedback form. </p>
</div>
<img src="images/illustration-grow-together.svg" alt="" class="image-illustration">
</div>
</div>
<div class="rectangle-col">
<div class="rectangle-col-content-1">
<img src="images/illustration-flowing-conversation.svg" alt="" class="image-flowing">
<div class="rectangle-col-content-2-text" >
<h2 style="margin-bottom: 20px;">Flowing Conversations</h2>
<p>You wouldn't paginate a conversation in real life, so why do <br> it online? Our threads have just-in-time loading for a more <br> natural flow.</p>
</div>
</div>
</div>
<div class="rectangle-col">
<div class="rectangle-col-content-1">
<div class="rectangle-col-content-1-text">
<h2 style="margin-bottom: 20px;">Your Users</h2>
<p> It takes no time at all to integrate Huddle with your app's authentication solution.This means, once signed in to your app, your users can start chatting immediately.</p>
</div>
<img src="images/illustration-your-users.svg" alt="" class="image-users">
</div>
</div>
</section>
<!-- FOOTER -->
<footer>
<div id="footer-col">
<div class="footer-rectangle">
<h1 class="footer-h1">Ready To Build Your Community?</h1>
</div>
<div class="footer-btn">
<button class="hero-btn1" style="margin-left: 40px;"><a href="" class="nav-a">Get Started For Free</a></button>
</div>
</div>
<div class="footer-items">
<div class="link-1">
<img src="images/logo.svg" alt="" class="footer-logo" style="margin-bottom: 20px;">
<p style="color: #ffffff;margin-bottom: 10px;"><img src="images/icon-location.svg" alt=""><span style="margin-left: 10px;">Lorem ipsum dolor sit amet, consectetur <br> adipiscing elit, sed do eiusmod tempor <br> incididunt ut labore et dolore magna aliqua</span></p>
<p style="color: #ffffff;margin-bottom: 10px;"><img src="images/icon-phone.svg" alt=""><span style="margin-left: 10px;">+1-543-123-4567</span></p>
<p style="color: #ffffff;"><img src="images/icon-email.svg" alt=""><span style="margin-left: 10px;"> example@huddle.com</span></p>
</div>
<div class="link-2">
<li><a href="" class="txt">About Us</a></li>
<li><a href="" class="txt">What We Do</a></li>
<li><a href="" class="txt">FAQ</a></li>
</div>
<div class="link-3">
<li><a href="" class="txt"> Career</a></li>
<li><a href="" class="txt">Blog</a></li>
<li><a href="" class="txt">Contact Us</a></li>
</div>
<div class="circle-container">
<div class="circle">
<div id="social"><i class="fa-brands fa-facebook" style="color: #ffffff;"></i></div>
</div>
<div class="circle">
<div id="social"><i class="fa-brands fa-twitter" style="color: #ffffff;"></i></div>
</div>
<div class="circle">
<div id="social"><i class="fa-brands fa-instagram" style="color: #ffffff;"></i></div>
</div>
</div>
</div>
<div class="copyright">
<p style="color: #ffffff;">©Copyright 2018 Huddle.All rights reserved.</p>
</div>
</footer>
</body>
</html> |
You just setup the perfect directory structure for your new project and now you
want to save it so you can use it again, but you don’t want to deal with all the
fuss of traditional methods. PowPow is here for you.
PowPow is a CLI written in JavaScript that makes managing tarballs dead simple.
To use PowPow you need [Node and NPM so get those][node] and then to install it
globally with npm like so.
```
$ npm install -g powpow
```
PowPow starts off empty so choose your best starting point folder and feed it to
PowPow by using the `add` command.
```
$ powpow add path/to/my/template_folder
```
You can see what templates PowPow knows about by using the `ls` command.
```
$ powpow ls
```
When you’re ready to start a project using your newly PowPow’d template use the
`new` command
```
$ powpow new template_folder my_project
```
This will create a folder in the current directory called `my_project` based on
the `template_folder` template.
If you no longer want powpow to know about a template use the `rm` command.
```
$ powpow rm template_folder
```
[node]: https://gist.github.com/isaacs/579814 |
import 'package:firebase_auth/firebase_auth.dart';
import 'package:b_finder/models/authUser.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
AuthUser _userFromFirebaseUser(User user){
return user != null ? AuthUser(uid: user.uid): null;
}
Stream<AuthUser> get user{
return _auth.authStateChanges()
.map((User user) => _userFromFirebaseUser(user));
}
//anon sign in
Future signInAnon() async{
try {
UserCredential result = await _auth.signInAnonymously();
User user = result.user;
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
Future registerWithEmailAndPassword(String email, String password) async{
try {
UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
User user = result.user;
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
Future signInWithEmailAndPassword(String email, String password) async{
try {
UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
User user = result.user;
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
Future signOut() async{
try {
return await _auth.signOut();
} catch (e) {
print(e.toString());
}
}
} |
//-------------------------------------------------------------------------------//
// Author: Stefan Lörwald, Universität Heidelberg //
// License: CC BY-NC 4.0 http://creativecommons.org/licenses/by-nc/4.0/legalcode //
//-------------------------------------------------------------------------------//
#pragma once
#include <iosfwd>
#include <type_traits>
#include "matrix.h"
#include "names.h"
#include "row.h"
/// Unnamed output of a row.
template <typename Integer>
std::ostream& operator<<(std::ostream&, const panda::Row<Integer>&);
template <>
std::ostream& operator<<(std::ostream&, const panda::Row<int>&);
/// Addition of a row onto another.
template <typename Integer>
panda::Row<Integer>& operator+=(panda::Row<Integer>&, const panda::Row<Integer>&) noexcept;
/// Addition of two rows.
template <typename Integer>
panda::Row<Integer> operator+(panda::Row<Integer>, const panda::Row<Integer>&);
/// Scaling of a row.
template <typename Integer>
panda::Row<Integer>& operator*=(panda::Row<Integer>&, const Integer) noexcept;
/// Returns a scaled row.
template <typename Integer>
panda::Row<Integer> operator*(panda::Row<Integer>, const Integer);
/// Returns a scaled row.
template <typename Integer>
panda::Row<Integer> operator*(const Integer, panda::Row<Integer>);
/// Subtraction of a row from another.
template <typename Integer>
panda::Row<Integer>& operator-=(panda::Row<Integer>&, const panda::Row<Integer>&) noexcept;
/// Subtraction of two rows.
template <typename Integer>
panda::Row<Integer> operator-(panda::Row<Integer>, const panda::Row<Integer>&);
/// Scaling of a row (division).
template <typename Integer>
panda::Row<Integer>& operator/=(panda::Row<Integer>&, const Integer);
/// Returns a scaled row (division).
template <typename Integer>
panda::Row<Integer> operator/(panda::Row<Integer>, const Integer);
/// Returns the scalar product of two rows.
template <typename Integer>
Integer operator*(const panda::Row<Integer>&, const panda::Row<Integer>&) noexcept;
namespace panda
{
namespace algorithm
{
/// Normalizes a row according to a set of equations.
template <typename Integer>
Row<Integer> normalize(Row<Integer>, const Equations<Integer>&);
/// Calculates the greatest common divisor of all entries of a row.
template <typename Integer>
Integer gcd(const Row<Integer>&) noexcept;
/// Calculates the least common multiple of all entries of a row.
template <typename Integer>
Integer lcm(const Row<Integer>&) noexcept;
/// Named output of a row (last entry is delimited by a sequence of characters (last argument)).
template <typename Integer>
void prettyPrint(std::ostream&, const Row<Integer>&, const Names&, const char*);
/// Named output of a row with trailing newline.
template <typename Integer>
void prettyPrintln(std::ostream&, const Row<Integer>&, const Names&, const char*);
/// Unnamed output of a vertex that may have fractional values.
template <typename Integer>
void printFractional(std::ostream&, const Vertex<Integer>&);
// explicit instantiations for type int:
template <>
void prettyPrint(std::ostream&, const Row<int>&, const Names&, const char*);
template <>
void prettyPrintln(std::ostream&, const Row<int>&, const Names&, const char*);
template <>
void printFractional(std::ostream&, const Vertex<int>&);
}
}
#include "algorithm_row_operations.eti" |
public static void main(String[] args) {
Log.printLine("Starting NetworkExample3...");
try {
// First step: Initialize the CloudSim package. It should be called
// before creating any entities.
// number of cloud users
int num_user = 2;
Calendar calendar = Calendar.getInstance();
// mean trace events
boolean trace_flag = false;
// Initialize the CloudSim library
CloudSim.init(num_user, calendar, trace_flag);
// Second step: Create Datacenters
// Datacenters are the resource providers in CloudSim. We need at list one of them to run a CloudSim simulation
Datacenter datacenter0 = createDatacenter("Datacenter_0");
Datacenter datacenter1 = createDatacenter("Datacenter_1");
// Third step: Create Brokers
DatacenterBroker broker1 = createBroker(1);
int brokerId1 = broker1.getId();
DatacenterBroker broker2 = createBroker(2);
int brokerId2 = broker2.getId();
// Fourth step: Create one virtual machine for each broker/user
vmlist1 = new ArrayList<Vm>();
vmlist2 = new ArrayList<Vm>();
// VM description
int vmid = 0;
// image size (MB)
long size = 10000;
int mips = 250;
// vm memory (MB)
int ram = 512;
long bw = 1000;
// number of cpus
int pesNumber = 1;
// VMM name
String vmm = "Xen";
// create two VMs: the first one belongs to user1
Vm vm1 = new Vm(vmid, brokerId1, mips, pesNumber, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
// the second VM: this one belongs to user2
Vm vm2 = new Vm(vmid, brokerId2, mips, pesNumber, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
// add the VMs to the vmlists
vmlist1.add(vm1);
vmlist2.add(vm2);
// submit vm list to the broker
broker1.submitVmList(vmlist1);
broker2.submitVmList(vmlist2);
// Fifth step: Create two Cloudlets
cloudletList1 = new ArrayList<Cloudlet>();
cloudletList2 = new ArrayList<Cloudlet>();
// Cloudlet properties
int id = 0;
long length = 40000;
long fileSize = 300;
long outputSize = 300;
UtilizationModel utilizationModel = new UtilizationModelFull();
Cloudlet cloudlet1 = new Cloudlet(id, length, pesNumber, fileSize, outputSize, utilizationModel, utilizationModel, utilizationModel);
cloudlet1.setUserId(brokerId1);
Cloudlet cloudlet2 = new Cloudlet(id, length, pesNumber, fileSize, outputSize, utilizationModel, utilizationModel, utilizationModel);
cloudlet2.setUserId(brokerId2);
// add the cloudlets to the lists: each cloudlet belongs to one user
cloudletList1.add(cloudlet1);
cloudletList2.add(cloudlet2);
// submit cloudlet list to the brokers
broker1.submitCloudletList(cloudletList1);
broker2.submitCloudletList(cloudletList2);
// Sixth step: configure network
// load the network topology file
NetworkTopology.buildNetworkTopology("topology.brite");
// maps CloudSim entities to BRITE entities
// Datacenter0 will correspond to BRITE node 0
int briteNode = 0;
NetworkTopology.mapNode(datacenter0.getId(), briteNode);
// Datacenter1 will correspond to BRITE node 2
briteNode = 2;
NetworkTopology.mapNode(datacenter1.getId(), briteNode);
// Broker1 will correspond to BRITE node 3
briteNode = 3;
NetworkTopology.mapNode(broker1.getId(), briteNode);
// Broker2 will correspond to BRITE node 4
briteNode = 4;
NetworkTopology.mapNode(broker2.getId(), briteNode);
// Sixth step: Starts the simulation
CloudSim.startSimulation();
// Final step: Print results when simulation is over
List<Cloudlet> newList1 = broker1.getCloudletReceivedList();
List<Cloudlet> newList2 = broker2.getCloudletReceivedList();
CloudSim.stopSimulation();
printCloudletList(newList1);
printCloudletList(newList2);
// Print the debt of each user to each datacenter
datacenter0.printDebts();
datacenter1.printDebts();
Log.printLine("NetworkExample3 finished!");
} catch (Exception e) {
e.printStackTrace();
Log.printLine("Unwanted errors happen");
}
} |
// @ts-ignore
// @ts-nocheck
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
import '../../styles/App.scss'
import shoppingCart from '../../assets/Image/shopping_Cart.png';
import todoList from '../../assets/Image/Todo_List.png';
import Personnel from '../../assets/Image/Personnel_Info.png';
import { useEffect, useRef, useState } from "react";
import { gsap, Power2 } from "gsap";
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
import { Button, Card, Modal } from 'react-bootstrap';
import { FiExternalLink } from 'react-icons/fi'
import { BsFillInfoSquareFill, BsFillBootstrapFill } from 'react-icons/bs'
import { FaGithub, FaReact, FaAws } from 'react-icons/fa6'
import { SiSpringboot, SiMysql } from 'react-icons/si'
export const Portfolio = () => {
let triggerRef = useRef(null);
const tl = useRef();
// reveal effect
useEffect(() => {
tl.current = gsap
.timeline({
scrollTrigger: {
trigger: triggerRef,
start: "top 50%"
}
})
.to('.container', { duration: 0.2, css: { visibility: "visible" } })
.to('.after', { duration: 2, width: "0%", ease: Power2.easeInOut }, "reveal")
.fromTo('.bg-img', { scale: 1.8 }, { duration: 2, scale: 1 }, "reveal")
return () => tl.current.kill();
}, []);
// Modal
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const [show2, setShow2] = useState(false);
const handleClose2 = () => setShow2(false);
const handleShow2 = () => setShow2(true);
const [show3, setShow3] = useState(false);
const handleClose3 = () => setShow3(false);
const handleShow3 = () => setShow3(true);
return (
<div id='portfolio' className="portfolio-container p-3 ">
<div className="row row-cols-1 row-cols-xxl-2 ">
<h1 className='mx-auto' ref={(el: any) => triggerRef = el} >{`</> `}Portfolio</h1>
<div className="col">
<Card className='mx-auto bg-body-secondary'>
<Card.Header as="h2">人員資料網站</Card.Header>
<div className="container">
<a href="https://github.com/alankowabunga/React/tree/master/Portfolio_Projects/Registration_React" target='_blank'>
<FaGithub className="github-link text-black bg-light rounded" fontSize="1.6rem" />
</a>
<BsFillInfoSquareFill className='web-info text-success border-3 bg-white' fontSize="1.6rem" onClick={handleShow} />
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>
<FaReact className="text-info ms-4" fontSize="2.2rem" />
<SiSpringboot className="text-success ms-4" fontSize="2.2rem" />
<SiMysql className="text-primary ms-4" fontSize="2.2rem" />
<FaAws className="text-dark ms-4" fontSize="2.2rem" />
</Modal.Title>
</Modal.Header>
<Modal.Body>
此專案中後端我使用 Spring Boot框架、關聯式資料庫 MySQL。主頁的背景使用 Particles.js 的動畫特效增加生動感覺,組件樣式由 React-Bootstrap 去做微調,使用 Java 語言開發簡單的 Spring Boot 後端程式實現業務邏輯處理、並連接 MySQL 資料庫。最後將整個全端應用程式部屬到 AWS 雲端的虛擬伺服器。
</Modal.Body>
<Modal.Footer>
<a href='http://register-project-bucket.s3-website-us-east-1.amazonaws.com/' target='_blank'>
<Button variant="dark" onClick={handleClose}>
Visit Site
<FiExternalLink className="ms-2" fontSize="1.3rem" />
</Button>
</a>
</Modal.Footer>
</Modal>
<a href='http://register-project-bucket.s3-website-us-east-1.amazonaws.com/' target='_blank'>
<FiExternalLink className='ex-link bg-primary text-white rounded p-1' fontSize="1.6rem" />
</a>
<div className="img-container mx-auto ">
<Card.Img src={Personnel} className="bg-img" />
<div className="after"></div>
</div>
</div>
</Card>
</div> {/* Registration System*/}
<div className="col">
<Card className='mx-auto bg-body-secondary'>
<Card.Header as="h2">購物網站</Card.Header>
<div className="container">
<a href="https://github.com/alankowabunga/React/tree/master/Portfolio_Projects/Shopping_Cart_React" target='_blank'>
<FaGithub className="github-link text-black bg-light rounded" fontSize="1.6rem" />
</a>
<BsFillInfoSquareFill className='web-info text-success border-3 bg-white' fontSize="1.6rem" onClick={handleShow2} />
<Modal show={show2} onHide={handleClose2}>
<Modal.Header closeButton>
<Modal.Title>
<FaReact className="text-info ms-4" fontSize="2.2rem" />
<BsFillBootstrapFill className="text-primary ms-4" fontSize="2.2rem" />
</Modal.Title>
</Modal.Header>
<Modal.Body>
此專案我前端使用 React.js 框架,將 Bootstrap 工具快速製成的元件像拼圖一樣組成一幅畫面,並運用能處理複雜狀態的 useReducer Hook 和能在整個專案中傳遞狀態的 useContext Hook ,使我發現其他作品的程式碼能更優化、精簡。最後將網站部屬到 Netlify 為靜態網站。
</Modal.Body>
<Modal.Footer>
<a href='https://64e63368b36fbf076d152764--jolly-begonia-7a7e37.netlify.app/' target='_blank'>
<Button variant="dark" onClick={handleClose2}>
Visit Site
<FiExternalLink className="ms-2" fontSize="1.3rem" />
</Button>
</a>
</Modal.Footer>
</Modal>
<a href='https://64e63368b36fbf076d152764--jolly-begonia-7a7e37.netlify.app/' target='_blank'>
<FiExternalLink className='ex-link bg-primary text-white rounded p-1' fontSize="1.6rem" />
</a>
<div className="img-container mx-auto ">
<Card.Img src={shoppingCart} className="bg-img" />
<div className="after"></div>
</div>
</div>
</Card>
</div> {/*shopping cart*/}
<div className="col">
<Card className='mx-auto bg-body-secondary'>
<Card.Header as="h2">備忘錄</Card.Header>
<div className="container">
<a href="https://github.com/alankowabunga/React/tree/master/Portfolio_Projects/Todo_List_React" target='_blank'>
<FaGithub className="github-link text-black bg-light rounded" fontSize="1.6rem" />
</a>
<BsFillInfoSquareFill className='web-info text-success border-3 bg-white' fontSize="1.6rem" onClick={handleShow3} />
<Modal show={show3} onHide={handleClose3}>
<Modal.Header closeButton>
<Modal.Title>
<FaReact className="text-info ms-4" fontSize="2.2rem" />
{/* <SiSpringboot className="text-success ms-4" fontSize="2.2rem" />
<SiMysql className="text-primary ms-4" fontSize="2.2rem" /> */}
</Modal.Title>
</Modal.Header>
<Modal.Body>
這是我第一個使用 React.js 元件式開發的專案,理解 React 的邏輯和各項 Hooks 使用方式,運用 props 跟 state 完成的待辦事項應用程式。
</Modal.Body>
<Modal.Footer>
<a href='https://64e6d66715a4493879746195--moonlit-lamington-2c8cfd.netlify.app/' target='_blank'>
<Button variant="dark" onClick={handleClose3}>
Visit Site
<FiExternalLink className="ms-2" fontSize="1.3rem" />
</Button>
</a>
</Modal.Footer>
</Modal>
<a href='https://64e6d66715a4493879746195--moonlit-lamington-2c8cfd.netlify.app/' target='_blank'>
<FiExternalLink className='ex-link bg-primary text-white rounded p-1' fontSize="1.6rem" />
</a>
<div className="img-container mx-auto ">
<Card.Img src={todoList} className="bg-img" />
<div className="after"></div>
</div>
</div>
</Card>
</div> {/*To-Do List*/}
</div>
</div>
)
} |
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="CNIT 133a Homework" />
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
<title>CNIT 133a Homework</title>
</head>
<body>
<h1 class="display-1" id="hw1_heading">CNIT 133a Homework</h1>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-sm">
<a
class="navbar-brand"
href="https://ccsf.instructure.com/courses/50293"
>Home</a
>
<button
class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a
class="nav-link active"
aria-current="page"
href="https://ccsf.instructure.com/courses/50293/announcements"
>Announcements</a
>
</li>
<li class="nav-item">
<a
class="nav-link active"
href="https://ccsf.instructure.com/courses/50293/assignments/syllabus"
>Syllabus</a
>
</li>
<li class="nav-item">
<a
class="nav-link active"
href="https://ccsf.instructure.com/courses/50293/modules"
>Modules</a
>
</li>
<li class="nav-item">
<a
class="nav-link active"
href="https://codebeautify.org/html-pretty-print"
>HTML pretty print</a
>
</li>
<li class="nav-item">
<a
class="nav-link active"
href="https://validator.w3.org/nu/?doc=https%3A%2F%2Fcnit133a.com"
>validate</a
>
</li>
</ul>
</div>
</div>
</nav>
<div class="container-sm">
<div class="row">
<div class="btn-group-vertical col-4">
<a
href="hw2/index.html"
class="btn btn-outline-secondary btn-md active"
role="button"
id="homework_jquery"
>Homework Jquery</a
>
<a
href="hw3/index.html"
class="btn btn-outline-secondary btn-md active"
role="button"
id="homework_d3"
>Homework D3</a
>
<a
href="#"
class="btn btn-outline-secondary btn-md disabled"
role="button"
id="homework_node"
>Homework Node</a
>
<a
href="#"
class="btn btn-outline-secondary btn-md disabled"
role="button"
id="homework_angular"
>Homework Angular</a
>
<a
href="#"
class="btn btn-outline-secondary btn-md disabled"
role="button"
id="homework_react"
>Homework React</a
>
<a
href="#"
class="btn btn-outline-secondary btn-md disabled"
role="button"
id="homework_vue"
>Homework Vue</a
>
</div>
<div class="col">
Hello World<br />
</div>
</div>
</div>
<footer class="text-lg-start bg-light text-muted">
<div class="container p-3 text-center">
Made with 🚀 and a 🚲 from
<a
class="text-decoration-none text-reset"
href="https://getbootstrap.com/"
>Bootstrap</a
>
in SF
<br />
<span id="footer_links"></span>
<script>
let link_status = null;
let link_build = null;
if ( window.location.hostname != "cnit133a.com") {
link_status = `
<a href="https://status.cnit133a.com/">
<img alt="Uptime Robot ratio (7 days)" src="https://img.shields.io/uptimerobot/ratio/7/m790429750-fd07748c612e99432fb76452">
</a>`;
link_build = `
<a href="https://circleci.com/gh/geburke/s.cnit133a.com/tree/dev"><img src="https://circleci.com/gh/geburke/s.cnit133a.com/tree/dev.svg?style=svg"></a>
`;
link_status = `
<a href="https://status.cnit133a.com/">
<img alt="Uptime Robot ratio (7 days)" src="https://img.shields.io/uptimerobot/ratio/7/m790429748-2d49b000bffeff0054dd0c09">
</a>`;
} else {
link_status = `
<a href="https://status.cnit133a.com/">
<img alt="Uptime Robot ratio (7 days)" src="https://img.shields.io/uptimerobot/ratio/7/m790429748-2d49b000bffeff0054dd0c09">
</a>`;
link_build = `
<a href="https://circleci.com/gh/geburke/cnit133a.com/tree/master"><img src="https://circleci.com/gh/geburke/cnit133a.com/tree/master.svg?style=svg"></a>
`;
}
links = link_build + link_status
document.getElementById("footer_links").innerHTML = links
</script>
</div>
</footer>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"
></script>
</body>
</html> |
import 'package:flutter/material.dart';
import 'package:weather/model/weather_model.dart';
import 'package:weather/services/weather_client_api.dart';
import 'package:weather/views/current_weather.dart';
import 'views/additional_information.dart';
void main() {
runApp(const MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
));
}
class HomePage extends StatefulWidget {
const HomePage({Key key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
WeatherApiClient client = WeatherApiClient();
Weather data;
String textInput = 'Bishkek';
Future<void> getData() async {
data = await client.getCurrentWeather(textInput);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFf9f9f9),
appBar: AppBar(
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.menu),
color: Colors.black,
),
elevation: 0.0,
backgroundColor: const Color(0xFFf9f9f9),
centerTitle: true,
title: const Text(
'Weather App',
style: TextStyle(
color: Colors.black,
),
),
),
body: Column(
children: [
FutureBuilder(
future: getData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
currentWeather(Icons.wb_sunny_rounded, '${data.temp}',
data.cityName),
const SizedBox(
height: 60.0,
),
const Text(
'Additional Information',
style: TextStyle(
fontSize: 24.0,
color: Color(0xdd212121),
fontWeight: FontWeight.bold,
),
),
const Divider(),
const SizedBox(
height: 20.0,
),
additionalInformation('${data.wind}', '${data.humidity}',
'${data.pressure}', '${data.feels_like}'),
],
);
} else if (snapshot.connectionState ==
ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return Container();
},
),
SizedBox(
width: 300.0,
child: TextField(
onSubmitted: (text) {
setState(() {
textInput = text;
});
text = '';
('Число: $text');
},
textAlign: TextAlign.center,
decoration: const InputDecoration(
hintText: 'Город',
),
),
)
],
));
}
} |
import React from "react";
import Card from "./Card";
import Pokeinfo from "./PokeInfo";
import axios from "axios";
import { useState, useEffect } from "react";
const Main = () => {
const [pokeData, setPokeData] = useState([]); // Estado para almacenar los datos de los Pokémon
const [loading, setLoading] = useState(true); // Estado para controlar la carga de datos
const [url] = useState("https://pokeapi.co/api/v2/pokemon?limit=150&offset=0"); // URL de la API de Pokémon con límite de 150 Pokémon
const [pokeDex, setPokeDex] = useState(); // Estado para almacenar los detalles de un Pokémon seleccionado
// Función para obtener los datos de los primeros 150 Pokémon
const pokeFun = async () => {
setLoading(true);
const res = await axios.get(url); // Realizar petición a la API
getPokemon(res.data.results); // Llamar a la función para obtener detalles de cada Pokémon
setLoading(false);
};
// Función para obtener los detalles de los Pokémon
const getPokemon = async (res) => {
const pokemonPromises = res.map(async (item) => {
const result = await axios.get(item.url); // Obtener detalles individuales de un Pokémon
return result.data;
});
// Esperar a que todas las promesas se resuelvan
const pokemonData = await Promise.all(pokemonPromises);
// Actualizar el estado con los detalles de los Pokémon ordenados por su ID
setPokeData(pokemonData.sort((a, b) => a.id - b.id));
};
// Efecto para cargar los datos de los Pokémon al montar el componente
useEffect(() => {
pokeFun();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [url]);
return (
<div className="container">
<div className="left-content">
{/* Pasar datos y funciones a componente Card */}
<Card pokemon={pokeData} loading={loading} infoPokemon={poke => setPokeDex(poke)} />
</div>
<div className="right-content">
{/* Pasar datos del Pokémon seleccionado a componente Pokeinfo */}
<Pokeinfo data={pokeDex} />
</div>
</div>
);
};
export default Main; |
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Trademark>
*/
class TrademarkFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
return [
'application_no' => $this->faker->unique()->numberBetween(1, 1000000),
'application_date' => $this->faker->dateTimeBetween('-1 years', '-1 days'),
'register_no' => $this->faker->unique()->numberBetween(1, 1000000),
'register_date' => $this->faker->dateTimeBetween('-1 years', '-1 days'),
'intreg_no' => $this->faker->unique()->numberBetween(1, 1000000),
'name' => $this->faker->unique()->name,
'slug' => $this->faker->unique()->slug,
'nice_classes' => $this->faker->unique()->name,
'vienna_classes' => $this->faker->unique()->name,
'type' => $this->faker->unique()->name,
'pub_type' => $this->faker->unique()->name,
'image_path' => $this->faker->unique()->name,
];
}
} |
import { useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import { PebblePlayer, VideoCard } from "Components";
import { useAxiosCalls, useModal } from "Context";
import "./SingleVideo.css";
import { useDispatch, useSelector } from "react-redux";
import { modalActions, videoActions } from "Store/store";
import { VideoDescription } from "./VideoDescription/VideoDescription";
export const SingleVideo = () => {
const { videoId } = useParams();
const {
fetchVideoFromServer,
likeVideoOnServer,
unLikeVideoOnServer,
addToWatchlaterOnServer,
removeFromWatchlaterOnServer,
} = useAxiosCalls();
const {
auth: { token },
} = useSelector((authState) => authState);
const dispatch = useDispatch();
const {
videoState: { videos, singleVideo, watchlater, likes },
} = useSelector((videoState) => videoState);
const [played, setPlayed] = useState(false);
const { snippet, statistics } = singleVideo;
const [watchlaterButton, setWatchlaterButton] = useState(
"far fa-clock icon-inactive"
);
const [likeButton, setLikeButton] = useState(
"far fa-thumbs-up icon-inactive"
);
const videoConfig = {
url: `/api/video`,
videoId: videoId,
};
const watchlaterConfig = {
url: "/api/user/watchlater",
body: { video: { ...singleVideo } },
headers: { headers: { authorization: token } },
};
const likeConfig = {
url: "/api/user/likes",
body: { video: { ...singleVideo } },
headers: { headers: { authorization: token } },
};
const addToLikeVideoHandler = () => {
if (token) {
likeVideoOnServer(likeConfig);
setLikeButton("fas fa-thumbs-up");
} else {
dispatch(modalActions.showLogin(true));
}
};
const removeLikeVideoHandler = () => {
unLikeVideoOnServer(likeConfig);
setLikeButton("far fa-thumbs-up icon-inactive");
};
const likeButtonStatus = () => {
if (likeButton === "far fa-thumbs-up icon-inactive") {
addToLikeVideoHandler();
} else {
removeLikeVideoHandler();
}
};
const addToWatchlaterClickHandler = () => {
if (token) {
addToWatchlaterOnServer(watchlaterConfig);
setWatchlaterButton("fas fa-clock icon-inactive");
} else {
dispatch(modalActions.showLogin(true));
}
};
const removeFromWatchlaterClickHandler = () => {
removeFromWatchlaterOnServer(watchlaterConfig);
setWatchlaterButton("far fa-clock icon-inactive");
};
const watchlaterButtonStatus = () => {
if (watchlaterButton === "far fa-clock icon-inactive") {
addToWatchlaterClickHandler();
} else {
removeFromWatchlaterClickHandler();
}
};
// playlist
const addToPlaylistClickHandler = () => {
if (token) {
dispatch(videoActions.tempCacheVideo(singleVideo));
dispatch(modalActions.showPlaylistModal(true));
} else {
dispatch(modalActions.showLogin(true));
}
};
useEffect(() => {
if (watchlater?.findIndex((el) => el?._id === singleVideo?._id) !== -1) {
setWatchlaterButton("fas fa-clock");
} else {
setWatchlaterButton("far fa-clock icon-inactive");
}
if (likes?.findIndex((el) => el?._id === singleVideo?._id) !== -1) {
setLikeButton("fas fa-thumbs-up");
} else {
setLikeButton("far fa-thumbs-up icon-inactive");
}
}, [likes, watchlater, singleVideo._id, setWatchlaterButton, setLikeButton]);
const likedStatus =
likes?.findIndex((el) => el?._id === singleVideo?._id) !== -1;
const likeCount = likedStatus
? Number(singleVideo.statistics?.likeCount) + 1
: Number(singleVideo.statistics?.likeCount);
const mapMustWatched = videos?.map((video) => {
return (
video?.mustWatch && <VideoCard key={video?._id} videoDetail={video} />
);
});
useEffect(() => {
fetchVideoFromServer(videoConfig);
}, [videoId]);
return (
<div className="video-page-body">
{singleVideo && (
<div className="video-player-container">
<PebblePlayer
videoId={videoId}
videoDetails={singleVideo}
played={played}
setPlayed={setPlayed}
/>
<VideoDescription
snippet={snippet}
statistics={statistics}
likeButtonStatus={likeButtonStatus}
likeButton={likeButton}
likeCount={likeCount}
watchlaterButtonStatus={watchlaterButtonStatus}
watchlaterButton={watchlaterButton}
addToPlaylistClickHandler={addToPlaylistClickHandler}
/>
</div>
)}
<div className="must-watch-container">
<h1 className="video-title text-center">Must Watch</h1>
<div className="must-watch-videos">{mapMustWatched}</div>
</div>
</div>
);
}; |
import React from "react";
import styled from "styled-components";
import { getCookie } from "../../shared/cookie";
import { useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { createComment } from "../../redux/modules/comments";
import { __getDetailPosts, __getPosts } from "../../redux/modules/posts";
import Ment from "../ment/Ment";
const Comment = () => {
let token = getCookie("ACCESS_TOKEN");
let fresh = getCookie("REFRESH_TOKEN");
let dispatch = useDispatch();
const initialState = {
postId: 0,
content: "",
};
let [ment, setMent] = useState("");
let [review, setReview] = useState(initialState);
let { id } = useParams();
let postId = id;
let payload = {
token: token,
fresh: fresh,
review: review,
id,
};
const { isLoading, error, detail } = useSelector((state) => state?.posts);
useEffect(() => {
dispatch(__getDetailPosts(id));
}, []);
if (isLoading) {
return <div>...로딩중</div>;
}
if (error) {
return <div>{error.message}</div>;
}
return (
<div>
<Divin>
<div>
<Input
type="text"
value={ment}
onChange={(e) => {
setMent(e.target.value);
setReview({
...review,
postId: Number(id),
content: e.target.value,
});
}}
/>
<Button
onClick={() => {
dispatch(createComment(payload));
setReview(initialState);
setMent("");
}}
>
작성
</Button>
</div>
<div>
{detail?.commentResponseDtoList?.map((comment) => {
return <Ment ment={comment} key={comment.id} postId={postId} />;
})}
</div>
</Divin>
</div>
);
};
export default Comment;
const Divin = styled.div`
margin-top: 80px;
margin-left: 310px;
`;
const Button = styled.button`
margin-left: 16px;
width: 60px;
height: 25px;
border: none;
border-radius: 5px;
margin-right: 10px;
background: #118ba3;
color: #ffffff;
&:hover {
color: #ffffff;
background: #cc3723;
transition: all 0.2s linear;
overflow: hidden;
box-shadow: 0 2px 5px 1px rgb(64 60 67 / 16%);
}
`;
const Input = styled.input`
border: #e6e6fa;
border-radius: 5px;
width: 500px;
height: 30px;
`; |
import argparse
import socket
import shlex
import subprocess
import sys
import textwrap
import threading
# here we set up the functionality for the -e or --execute command
def execute(cmd):
cmd = cmd.strip()
if not cmd:
return
output = subprocess.check_output(shlex.split(cmd),
stderr=subprocess.STDOUT)
return output.decode()
# here we create the NetCat class that takes arguments from the command line and
# creates a socket object
class NetCat:
def __init__(self, args, buffer=None):
self.args = args
self.buffer = buffer
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# this function delegates execution to either the listen function or the send function
def run(self):
if self.args.listen:
self.listen()
else:
self.send()
# this function provides functionality for the send method
def send(self):
self.socket.connect((self.args.target, self.args.port))
if self.buffer:
self.socket.send(self.buffer)
try:
while True:
recv_len = 1
response = ''
while recv_len:
data = self.socket.recv(4096)
recv_len = len(data)
response += data.decode()
if recv_len < 4096:
break
if response:
print(response)
buffer = input('> ')
buffer += '\n'
self.socket.send(buffer.encode())
except KeyboardInterrupt:
print('User terminated.')
self.socket.close()
sys.exit()
# this function provides functionality for the listen method
def listen(self):
self.socket.bind((self.args.target, self.args.port))
self.socket.listen(5)
while True:
client_socket, _ = self.socket.accept()
client_thread = threading.Thread(
target=self.handle, args=(client_socket,)
)
client_thread.start()
# this function create a handler for when a connection is established
def handle(self, client_socket):
if self.args.execute:
output = execute(self.args.execute)
client_socket.send(output.encode())
elif self.args.upload:
file_buffer = b''
while True:
data = client_socket.recv(4096)
if data:
file_buffer += data
else:
break
with open(self.args.upload, 'wb') as f:
f.write(file_buffer)
message = f'Saved file {self.args.upload}'
client_socket.send(message.encode())
elif self.args.command:
cmd_buffer = b''
while True:
try:
client_socket.send(b'BHP: #> ')
while '\n' not in cmd_buffer.decode():
cmd_buffer += client_socket.recv(64)
response = execute(cmd_buffer.decode())
if response:
client_socket.send(response.encode())
cmd_buffer = b''
except Exception as e:
print(f'server killed {e}')
self.socket.close()
sys.exit()
# this if statement provides the infomation in the --help menu
if __name__ == '__main__':
parser = argparse.ArgumentParser(description = 'BHP Net Tool',
formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''
Example:
netcat.py -t 192.168.1.108 -p 5555 -1 -c #command shell
netcat.py -t 192.168.1.108 -p 5555 -1 -u=mytest.txt #upload a file
netcat.py -t 192.168.1.108 -p 5555 -1 -e=\"cat /etc/passwd\" #execute command
echo "ABC" | ./necat.py -t 192.168.1.108 -p 555 #echo text to port
netcat.py -t 192.168.1.108 -p 5555 #connect to a server'''))
parser.add_argument('-c', '--command', action='store_true', help='command shell')
parser.add_argument('-e', '--execute', help='execute a command')
parser.add_argument('-l', '--listen', action='store_true',help='listen to a port')
parser.add_argument('-p', '--port', type=int, default=5555, help='specify port number')
parser.add_argument('-t', '--target', default='192.168.1.108', help='specified target IP')
parser.add_argument('-u', '--upload', help='upload file')
args = parser.parse_args()
if args.listen:
buffer = ''
else:
buffer = sys.stdin.read()
nc = NetCat(args, buffer.encode())
nc.run() |
//
// ProfileNameViewController.swift
// SeSACShopping
//
// Created by 민지은 on 2024/01/19.
//
import UIKit
enum ProfileSettingType {
case new
case edit
}
class ProfileNameViewController: UIViewController {
@IBOutlet var profileButton: UIButton!
@IBOutlet var cameraImage: UIImageView!
@IBOutlet var profileView: UIView!
@IBOutlet var inputTextField: UITextField!
@IBOutlet var underLine: UIView!
@IBOutlet var checkLabel: UILabel!
@IBOutlet var completeButton: UIButton!
let symbolList = ["@","#","$","%"]
let numberList = ["0","1","2","3","4","5","6","7","8","9"]
var symbol = false
var number = false
var count = false
var isPossible = false
var type: ProfileSettingType = .new
let originProfile = UserDefaultManager.shared.profileIndex
override func viewDidLoad() {
super.viewDidLoad()
setBackgroundColor()
configureView()
}
@objc func completeButtonTapped() {
print(#function)
if isPossible {
if type == .new {
let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
let sceneDelegate = windowScene?.delegate as? SceneDelegate
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "mainSearchEmptyTabController") as! UITabBarController
sceneDelegate?.window?.rootViewController = vc
sceneDelegate?.window?.makeKeyAndVisible()
UserDefaultManager.shared.nickName = inputTextField.text!
print(UserDefaultManager.shared.nickName)
UserDefaultManager.shared.newMember = false
} else {
let alert = UIAlertController(title: "프로필 변경 완료!", message: nil, preferredStyle: .alert)
let oneButton = UIAlertAction(title: "확인", style: .cancel) { action in
UserDefaultManager.shared.nickName = self.inputTextField.text!
self.navigationController?.popViewController(animated: true)
}
alert.addAction(oneButton)
present(alert, animated: true)
}
} else {
let alert = UIAlertController(title: "프로필 등록 실패", message: "닉네임을 다시 확인해주세요!", preferredStyle: .alert)
let button = UIAlertAction(title: "확인", style: .cancel)
alert.addAction(button)
present(alert, animated: true)
}
}
@objc func leftBarButtonItemClicked() {
print(#function)
if type == .edit {
UserDefaultManager.shared.profileIndex = originProfile
}
navigationController?.popViewController(animated: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print(#function)
let image = "profile\(UserDefaultManager.shared.profileIndex + 1)"
profileButton.profileButtonStyle(image: image, isSelected: true)
}
@IBAction func profileImageTapped(_ sender: UIButton) {
print(#function)
let sb = UIStoryboard(name: "ProfileImage", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: ProfileImageViewController.identifier) as! ProfileImageViewController
vc.selectIndex = UserDefaultManager.shared.profileIndex
vc.type = type
navigationController?.pushViewController(vc, animated: true)
}
@IBAction func inputFinish(_ sender: UITextField) {
print(#function)
view.endEditing(true)
UserDefaultManager.shared.nickName = inputTextField.text!
}
@IBAction func isEditing(_ sender: UITextField) {
print(#function)
checkName()
}
func checkName() {
for index in 0...symbolList.count - 1 {
if inputTextField.text!.contains(symbolList[index]) {
checkLabel.text = "닉네임에 @,#,$,% 는 포함할 수 없어요"
symbol = true
break
}
symbol = false
}
for index in 0...numberList.count - 1 {
if inputTextField.text!.contains(numberList[index]) {
checkLabel.text = "닉네임에 숫자는 포함할 수 없어요"
number = true
break
}
number = false
}
// 2가지 조건에 모두 다 해당될 경우 마지막 input값에 따라 불가능한 조건 표시
var lastInput = ""
if !(inputTextField.text!.isEmpty) {
lastInput = String(inputTextField.text!.last!)
}
if symbolList.contains(lastInput){
checkLabel.text = "닉네임에 @,#,$,% 는 포함할 수 없어요"
}
if numberList.contains(lastInput){
checkLabel.text = "닉네임에 숫자는 포함할 수 없어요"
}
if inputTextField.text!.count > 10 || inputTextField.text!.count < 2{
checkLabel.text = "닉네임은 2글자 이상 10글자 미만으로 설정해주세요"
count = true
} else {
count = false
}
if !symbol && !number && !count{
checkLabel.text = "사용 가능한 닉네임입니다"
isPossible = true
} else {
isPossible = false
}
}
}
extension ProfileNameViewController: ViewProtocol {
func configureView() {
let image = "profile\(UserDefaultManager.shared.profileIndex + 1)"
profileView.backgroundColor = .clear
navigationItem.title = type == .new ? "프로필 설정" : "프로필 수정"
self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
profileButton.profileButtonStyle(image: image, isSelected: true)
cameraImage.image = UIImage(named: "camera")
inputTextField.nickNameInputTF()
underLine.backgroundColor = .white
checkName()
checkLabel.textColor = .pointColor
checkLabel.font = .systemFont(ofSize: 12)
completeButton.pointButtonStyle(title: "완료")
completeButton.addTarget(self, action: #selector(completeButtonTapped), for: .touchUpInside)
let button = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain, target: self, action: #selector(leftBarButtonItemClicked))
button.tintColor = .white
navigationItem.leftBarButtonItem = button
}
} |
import argparse
from pathlib import Path
import sys
import pytest
this_file = Path(__file__)
INPUT_TXT = this_file.parent / (this_file.stem + ".txt")
def solve_aoc(s: str) -> int:
d = {"L": 0, "R": 1}
pattern, rest = s.split("\n\n")
network = {l[:3]: (l[7:10], l[12:15]) for l in rest.splitlines()}
current = "AAA"
total = 0
while current != "ZZZ":
idx = d[pattern[total % len(pattern)]]
total += 1
current = network[current][idx]
return total
SAMPLE1 = """\
RL
AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)
"""
EXPECTED1 = 2
SAMPLE2 = """\
LLR
AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)
"""
EXPECTED2 = 6
@pytest.mark.parametrize(
("sample", "expected"), ((SAMPLE1, EXPECTED1), (SAMPLE2, EXPECTED2))
)
def test_solve(sample: str, expected: int) -> None:
assert solve_aoc(sample) == expected
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("input_file", nargs="?", default=INPUT_TXT)
args = parser.parse_args()
input_s = Path(args.input_file).read_text(encoding="utf-8")
print(solve_aoc(input_s))
return 0
if __name__ == "__main__":
raise sys.exit(main()) |
package study_abstract;
/*
abstract关键字的使用
1.abstract抽象的
2.abstract可以用来修饰的结构;类,方法
3.abstract修饰类;抽象类
此类不能实例化
抽象类中一定有构造器,便于子类实例化时候调用(涉及子类对象实例化全过程)
开发中都会提供抽象类的子类,让子类完成实例化,完成相关操作
4.abstract修饰方法;抽象方法
抽象方法只有方法声明,没有方法体
包含抽象方法的类一定是一个抽象类,反之,抽象类中可以没有抽象方法
若子类重写了父类中的抽象方法后,此子类方可实例化,
若子类没有重写父类中的抽象方法,此子类也是一个抽象类,需要使用abstract修饰
*/
public class AbstractTest {
public static void main(String[] args) {
//一旦person类抽象,就不可实例化
// Person1 p1 = new Person1();
// p1.eat();
}
}
abstract class Creature{
public abstract void breath();
}
abstract class Person1 extends Creature {
String name;
int age;
public Person1(){
}
public Person1(String name, int age){
this.name = name;
this.age = age;
}
//不是抽象方法
// public void eat(){
//
// }
//抽象方法
public abstract void eat();
public void walk(){
System.out.println(" walk");
}
}
class Student extends Person1 {
public Student(int age,String name){
super(name,age);
}
public Student() {
}
public void eat(){
System.out.println("学生应该多吃有营养的食物");
}
@Override
public void breath() {
System.out.println("学生应该呼吸新鲜的空气");
}
} |
// ignore_for_file: prefer_const_constructors
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:e_commerce/consts/consts.dart';
import 'package:e_commerce/controller/chats_controller.dart';
import 'package:e_commerce/services/firestore_services.dart';
import 'package:e_commerce/views/chat_screen/components/sender_bubble.dart';
import 'package:e_commerce/views/widgets_common/loading.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class ChatScreen extends StatelessWidget {
const ChatScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
var controller = Get.put(ChatsController());
return Scaffold(
backgroundColor: whiteColor,
appBar: AppBar(
title: "${controller.friendName}"
.text
.color(darkFontGrey)
.fontFamily(semibold)
.make(),
),
body: Padding(
padding: EdgeInsets.all(8.0),
child: Column(
children: [
Obx(
() => controller.isLoading.value
? Center(
child: loadingIndicator(),
)
: Expanded(
child: StreamBuilder(
stream: FirestoreServices.getChatMessages(
controller.chatDocId.toString()),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: loadingIndicator(),
);
} else if (snapshot.data!.docs.isEmpty) {
return Center(
child: "Send a Message..."
.text
.color(darkFontGrey)
.make(),
);
} else {
return ListView(
children: snapshot.data!.docs
.mapIndexed((currentValue, index) {
var data = snapshot.data!.docs[index];
return Align(
alignment: data['uid'] == currentUser!.uid
? Alignment.centerRight
: Alignment.centerLeft,
child: senderBubble(data));
}).toList(),
);
}
},
),
),
),
10.heightBox,
Row(
children: [
Expanded(
child: TextFormField(
controller: controller.msgController,
decoration: InputDecoration(hintText: "Type a message..."),
)),
IconButton(
onPressed: () {
controller.sendMsg(controller.msgController.text);
controller.msgController.clear();
},
icon: Icon(Icons.send),
color: redColor,
)
],
)
.box
.height(80)
.padding(EdgeInsets.all(12))
.margin(EdgeInsets.only(bottom: 8))
.make(),
],
),
),
);
}
} |
import React, { useEffect, useState } from 'react';
import Skeleton from 'react-loading-skeleton';
import './TvShow.css';
import { useParams } from 'react-router-dom';
const TvShow = () => {
const [shows, setShows] = useState([]);
const [loading, setLoading] = useState(true);
const { id } = useParams();
useEffect(() => {
setLoading(true);
fetch(`https://api.tvmaze.com/shows/${id}`)
.then((response) => response.json())
.then((data) => {
setShows(data);
setLoading(false);
})
.catch((error) => {
console.log(error);
setLoading(false);
});
}, [id]);
return (
<div className="TvShow">
<div className="TvShow__intro">
{loading ? (
<Skeleton height={500} />
) : (
<img className="backdrop__img" src={shows.image?.original} alt={shows.name} />
)}
</div>
<div className="TvShow__details">
<div className="TvShow__detailLeft">
{loading ? (
<Skeleton height={400} width={280} />
) : (
<div className="TvShow__poster">
<img className="poster__img" src={shows.image?.medium} alt={shows.name} />
</div>
)}
</div>
<div className="TvShow__detailRight">
<div className="TvShow__detailRightTop">
{loading ? (
<Skeleton height={40} width={500} />
) : (
<div className="TvShow__name">{shows?.name}</div>
)}
{loading ? (
<Skeleton height={20} width={200} />
) : (
<div className="TvShow__lang">{shows?.language}</div>
)}
{loading ? (
<Skeleton height={20} width={100} />
) : (
<div className="TvShow__rating">
{shows.rating?.average}
<i class="fas fa-star" />
</div>
)}
{loading ? (
<Skeleton height={20} width={100} />
) : (
<div className="TvShow__runtime">
{shows ? shows?.runtime + ' mins' : ''}
</div>
)}
{loading ? (
<Skeleton height={20} width={200} />
) : (
<div className="TvShow__releaseDate">
{shows ? 'Release date: ' + shows?.premiered : ''}
</div>
)}
<div className="TvShow__genres">
{loading
? Array.from({ length: 5 }, (_, i) => (
<Skeleton key={i} height={20} width={80} style={{ marginRight: 10 }} />
))
: shows?.genres?.map((genre, i) => (
<span className="TvShow__genre" key={i}>
{genre}
</span>
))}
</div>
</div>
<div className="TvShow__detailRightBottom">
<div className="summary">Summary</div>
{loading ? (
<Skeleton height={100} count={3} />
) : (
<div>{shows?.summary?.replace(/<[^>]+>/g, '')}</div>
)}
</div>
</div>
</div>
</div>
)
}
export default TvShow |
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//Route::get('/','PagesController@root')->name('root');
// 把秒杀接口放在路由的最开头,是因为 Laravel 匹配路由是从上往下匹配的,遇到第一个满足条件的路由就返回,所以放在最开头可以节省掉很多匹配路由的资源消耗。
Route::post('seckill_orders', 'OrdersController@seckill')->name('seckill_orders.store');
// 在之前的路由里加上一个 verify 参数
Auth::routes(['verify' => true]);
// auth 中间件代表需要登录,verified中间件代表需要经过邮箱验证
Route::group(['middleware' => ['auth', 'verified']], function() {
Route::get('user_addresses', 'UserAddressesController@index')->name('user_addresses.index');
Route::get('user_addresses/create', 'UserAddressesController@create')->name('user_addresses.create');
Route::post('user_addresses', 'UserAddressesController@store')->name('user_addresses.store');
Route::get('user_addresses/{address}','UserAddressesController@edit')->name('user_addresses.edit');
Route::put('user_addresses/{address}', 'UserAddressesController@update')->name('user_addresses.update');
Route::delete('user_addresses/{address}','UserAddressesController@destroy')->name('user_addresses.destroy');
Route::post('products/{product}/favorite', 'ProductsController@favor')->name('products.favor');
Route::delete('products/{product}/favorite', 'ProductsController@disfavor')->name('products.disfavor');
Route::get('products/favorites', 'ProductsController@favorites')->name('products.favorites');
Route::post('cart','CartController@add')->name('cart.add');
Route::get('cart', 'CartController@index')->name('cart.index');
Route::delete('cart/{productSku}', 'CartController@remove')->name('cart.remove');
Route::get('orders', 'OrdersController@index')->name('orders.index');
Route::post('orders','OrdersController@store')->name('orders.store');
Route::get('orders/{order}', 'OrdersController@show')->name('orders.show');
Route::post('orders/{order}/received', 'OrdersController@received')->name('orders.received');
Route::get('payment/{order}/alipay','PaymentController@payByAlipay')->name('payment.alipay');
Route::get('payment/alipay/return', 'PaymentController@alipayReturn')->name('payment.alipay.return');
Route::get('payment/{order}/wechat', 'PaymentController@payByWechat')->name('payment.wechat');
Route::get('orders/{order}/review', 'OrdersController@review')->name('orders.review.show');
Route::post('orders/{order}/review','OrdersController@sendReview')->name('orders.review.store');
Route::post('orders/{order}/apply_refund','OrdersController@applyRefund')->name('orders.apply_refund');
Route::get('coupon_codes/{code}', 'CouponCodesController@show')->name('coupon_codes.show');
Route::post('crowdfunding_orders', 'OrdersController@crowdfunding')->name('crowdfunding_orders.store');
Route::post('payment/{order}/installment', 'PaymentController@payByInstallment')->name('payment.installment');
Route::get('installments','InstallmentsController@index')->name('installments.index');
Route::get('installments/{installment}','InstallmentsController@show')->name('installments.show');
Route::get('installments/{installment}/alipay', 'InstallmentsController@payByAlipay')->name('installments.alipay');
Route::get('installments/alipay/return', 'InstallmentsController@alipayReturn')->name('installments.alipay.return');
});
Route::post('payment/alipay/notify','PaymentController@alipayNotify')->name('payment.alipay.notify');
Route::post('payment/wechat/notify', 'PaymentController@wechatNotify')->name('payment.wechat.notify');
Route::post('payment/wechat/refund_notify', 'PaymentController@wechatRefundNotify')->name('payment.wechat.refund_notify');
Route::post('installments/alipay/notify', 'InstallmentsController@alipayNotify')->name('installments.alipay.notify');
Route::post('installments/wechat/refund_notify', 'InstallmentsController@wechatRefundNotify')->name('installments.wechat.refund_notify');
Route::redirect('/', '/products')->name('root');
Route::get('products', 'ProductsController@index')->name('products.index');
Route::get('products/{product}', 'ProductsController@show')->name('products.show'); |
import CreateUserModal from '../../../../src/components/Users/CreateUserModal.vue'
import {
defaultComponentMocks,
defaultPlugins,
mockAxiosReject,
mockAxiosResolve,
shallowMount
} from 'web-test-helpers'
import { mock } from 'jest-mock-extended'
import { AxiosResponse } from 'axios'
import { Modal, eventBus, useMessages } from '@ownclouders/web-pkg'
describe('CreateUserModal', () => {
describe('computed method "isFormInvalid"', () => {
it('should be true if any data set is invalid', () => {
const { wrapper } = getWrapper()
wrapper.vm.formData.userName.valid = false
expect(wrapper.vm.isFormInvalid).toBeTruthy()
})
})
it('should be false if no data set is invalid', () => {
const { wrapper } = getWrapper()
Object.keys(wrapper.vm.formData).forEach((key) => {
wrapper.vm.formData[key].valid = true
})
expect(wrapper.vm.isFormInvalid).toBeFalsy()
})
describe('method "validateUserName"', () => {
it('should be false when userName is empty', async () => {
const { wrapper } = getWrapper()
wrapper.vm.user.onPremisesSamAccountName = ''
expect(await wrapper.vm.validateUserName()).toBeFalsy()
})
it('should be false when userName is longer than 255 characters', async () => {
const { wrapper } = getWrapper()
wrapper.vm.user.onPremisesSamAccountName = 'n'.repeat(256)
expect(await wrapper.vm.validateUserName()).toBeFalsy()
})
it('should be false when userName contains white spaces', async () => {
const { wrapper } = getWrapper()
wrapper.vm.user.onPremisesSamAccountName = 'jan owncCloud'
expect(await wrapper.vm.validateUserName()).toBeFalsy()
})
it('should be false when userName starts with a numeric value', async () => {
const { wrapper } = getWrapper()
wrapper.vm.user.onPremisesSamAccountName = '1moretry'
expect(await wrapper.vm.validateUserName()).toBeFalsy()
})
it('should be false when userName is already existing', async () => {
const { wrapper, mocks } = getWrapper()
const graphMock = mocks.$clientService.graphAuthenticated
const getUserStub = graphMock.users.getUser.mockResolvedValue(
mock<AxiosResponse>({ data: { onPremisesSamAccountName: 'jan' } })
)
wrapper.vm.user.onPremisesSamAccountName = 'jan'
expect(await wrapper.vm.validateUserName()).toBeFalsy()
expect(getUserStub).toHaveBeenCalled()
})
it('should be true when userName is valid', async () => {
const { wrapper, mocks } = getWrapper()
const graphMock = mocks.$clientService.graphAuthenticated
const getUserStub = graphMock.users.getUser.mockRejectedValue(() => mockAxiosReject())
wrapper.vm.user.onPremisesSamAccountName = 'jana'
expect(await wrapper.vm.validateUserName()).toBeTruthy()
expect(getUserStub).toHaveBeenCalled()
})
})
describe('method "validateDisplayName"', () => {
it('should be false when displayName is empty', () => {
const { wrapper } = getWrapper()
wrapper.vm.user.displayName = ''
expect(wrapper.vm.validateDisplayName()).toBeFalsy()
})
it('should be false when displayName is longer than 255 characters', async () => {
const { wrapper } = getWrapper()
wrapper.vm.user.displayName = 'n'.repeat(256)
expect(await wrapper.vm.validateDisplayName()).toBeFalsy()
})
it('should be true when displayName is valid', () => {
const { wrapper } = getWrapper()
wrapper.vm.user.displayName = 'jana'
expect(wrapper.vm.validateDisplayName()).toBeTruthy()
})
})
describe('method "validateEmail"', () => {
it('should be false when email is invalid', () => {
const { wrapper } = getWrapper()
wrapper.vm.user.mail = 'jana@'
expect(wrapper.vm.validateEmail()).toBeFalsy()
})
it('should be true when email is valid', () => {
const { wrapper } = getWrapper()
wrapper.vm.user.mail = 'jana@owncloud.com'
expect(wrapper.vm.validateEmail()).toBeTruthy()
})
})
describe('method "validatePassword"', () => {
it('should be false when password is empty', () => {
const { wrapper } = getWrapper()
wrapper.vm.user.passwordProfile.password = ''
expect(wrapper.vm.validatePassword()).toBeFalsy()
})
it('should be true when password is valid', () => {
const { wrapper } = getWrapper()
wrapper.vm.user.passwordProfile.password = 'asecret'
expect(wrapper.vm.validatePassword()).toBeTruthy()
})
})
describe('method "onConfirm"', () => {
it('should not create user if form is invalid', async () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined)
const { wrapper } = getWrapper()
const eventSpy = jest.spyOn(eventBus, 'publish')
try {
await wrapper.vm.onConfirm()
} catch (error) {}
const { showMessage } = useMessages()
expect(showMessage).not.toHaveBeenCalled()
expect(eventSpy).not.toHaveBeenCalled()
})
it('should create user on success', async () => {
const { wrapper, mocks } = getWrapper()
mocks.$clientService.graphAuthenticated.users.getUser.mockRejectedValueOnce(new Error(''))
wrapper.vm.user.onPremisesSamAccountName = 'foo'
wrapper.vm.validateUserName()
wrapper.vm.user.displayName = 'foo bar'
await wrapper.vm.validateDisplayName()
wrapper.vm.user.mail = 'foo@bar.com'
wrapper.vm.validateEmail()
wrapper.vm.user.passwordProfile.password = 'asecret'
wrapper.vm.validatePassword()
mocks.$clientService.graphAuthenticated.users.createUser.mockImplementation(() =>
mockAxiosResolve({ id: 'e3515ffb-d264-4dfc-8506-6c239f6673b5' })
)
mocks.$clientService.graphAuthenticated.users.getUser.mockResolvedValueOnce(
mockAxiosResolve({ id: 'e3515ffb-d264-4dfc-8506-6c239f6673b5' })
)
const eventSpy = jest.spyOn(eventBus, 'publish')
await wrapper.vm.onConfirm()
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalled()
expect(eventSpy).toHaveBeenCalled()
})
it('should show message on error', async () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined)
const { wrapper, mocks } = getWrapper()
mocks.$clientService.graphAuthenticated.users.getUser.mockRejectedValue(new Error(''))
wrapper.vm.user.onPremisesSamAccountName = 'foo'
wrapper.vm.validateUserName()
wrapper.vm.user.displayName = 'foo bar'
await wrapper.vm.validateDisplayName()
wrapper.vm.user.mail = 'foo@bar.com'
wrapper.vm.validateEmail()
wrapper.vm.user.passwordProfile.password = 'asecret'
wrapper.vm.validatePassword()
mocks.$clientService.graphAuthenticated.users.createUser.mockImplementation(() =>
mockAxiosResolve({ id: 'e3515ffb-d264-4dfc-8506-6c239f6673b5' })
)
const eventSpy = jest.spyOn(eventBus, 'publish')
await wrapper.vm.onConfirm()
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalled()
expect(eventSpy).not.toHaveBeenCalled()
})
})
})
function getWrapper() {
const mocks = defaultComponentMocks()
return {
mocks,
wrapper: shallowMount(CreateUserModal, {
props: {
modal: mock<Modal>()
},
global: {
mocks,
provide: mocks,
plugins: [...defaultPlugins()]
}
})
}
} |
//
// LinkyAPI.swift
// LinkyAPI
//
// Created by Karim Angama on 13/06/2023.
//
import Foundation
import WebKit
import UIKit
/// Launch the authorization request
/// To access customer metering data APIs, the application must first obtain permission from the customer.
/// It requires the authentication of the end customer with Enedis and their free, explicit and informed consent.
///
/// - Parameter configuration: Information to access API data
///
public class LinkyAuthorization {
/// Submits a block for synchronous execution
///
///- Parameter error: An error object that indicates why the request failed, or nil if the request was successful.
///
public typealias AuthorizationCompletion = (_ error: Error?) -> Void
/// Indicates whether access has already been authorized
///
public var isAccess: Bool {
get {
if configuration.mode != .production
&& account.getUsagePointsId() != nil
&& configuration.mode.prm != account.getUsagePointsId() {
account.deleteUsagePointsId()
}
return account.isAccess
}
}
private(set) var configuration: LinkyConfiguration
private(set) var account: LinkyAccount
private(set) var serviceAPI: LinkyAPI
private(set) var authorizationBlok: AuthorizationCompletion?
/// Launch the authorization request
///
/// - Parameter configuration: Information to access API data
///
public convenience init(configuration: LinkyConfiguration) {
let account = LinkyAccountImpl()
self.init(
configuration: configuration,
account: LinkyAccountImpl(),
serviceAPI: LinkyServiceAPI(
configuration: configuration,
account: account
)
)
}
// MARK: - Public methode
/// Display a view for the user to accepts the sharing of this consumptions data
///
/// - Parameter completionHandler : The completion handler to call when the authorization is complete.
///
public func authorization(completionHandler: @escaping AuthorizationCompletion) {
if !isAccess {
self.authorizationBlok = completionHandler
displayWebViewScreen()
}else{
completionHandler(nil)
}
}
/// Reset account
///
public func logout() {
account.deleteAcceesToken()
account.deleteUsagePointsId()
account.setExpireAccessToken(0)
}
// MARK: - Internal methode
internal init(configuration: LinkyConfiguration, account: LinkyAccount, serviceAPI: LinkyAPI) {
self.configuration = configuration
self.account = account
self.serviceAPI = serviceAPI
LinkyConsumption.shared.linkyAPI = serviceAPI
}
internal func handleResponse(usagePointsId: String?, state: String?, error: Error?) {
if (state != configuration.state || error != nil) && usagePointsId == nil {
if error != nil {
self.authorizationBlok?(error)
}else {
self.authorizationBlok?(LinkyAuthorizationError.stateAuthorization)
}
dismissScreen()
} else if let usagePointsId = usagePointsId {
if account.getUsagePointsId() == nil {
account.setUsagePointsId(usagePointsId)
}
handleAccessToken()
}else{
self.authorizationBlok?(LinkyAuthorizationError.authorization)
dismissScreen()
}
}
internal func displayWebViewScreen() {
let nc = UINavigationController(
rootViewController: WebViewController(
configuration: configuration,
account: account,
block: handleResponse)
)
getLastViewControler()?.present(nc, animated: true)
}
internal func dismissScreen() {
DispatchQueue.main.async {
let viewController = self.getLastViewControler()
viewController?.dismiss(animated: true)
}
}
internal func handleAccessToken() {
self.serviceAPI.accessToken { [weak self] accessToken, error in
if (accessToken != nil) {
self?.account.setAcceesToken(accessToken?.access_token ?? "")
self?.account.setExpireAccessToken(accessToken?.expires_in ?? 0)
self?.dismissScreen()
self?.authorizationBlok?(nil)
} else if error != nil {
self?.logout()
self?.dismissScreen()
self?.authorizationBlok?(error)
}
}
}
// MARK: - Private methode
private func getLastViewControler() -> UIViewController? {
guard let scene = UIApplication.shared.connectedScenes.first,
let windowSceneDelegate = scene.delegate as? UIWindowSceneDelegate,
let window = windowSceneDelegate.window,
let rootViewController = window?.rootViewController else { return nil }
if let navigationController = rootViewController as? UINavigationController {
return navigationController.topViewController?.presentedViewController ?? navigationController.topViewController
}
return rootViewController
}
} |
import Button from "@/Components/Button";
import { CartContext } from "@/Components/CartContext";
import Center from "@/Components/Center";
import Header from "@/Components/Header";
import ProductImages from "@/Components/ProductImages";
import StyledTitle, { Title } from "@/Components/Title";
import WhiteBox from "@/Components/WhiteBox";
import CartIcon from "@/Components/icons/Cart";
import { mongooseConnect } from "@/lib/mongoose";
import { Product } from "@/models/Products";
import { useContext } from "react";
import styled from "styled-components";
const ColWrapper = styled.div`
display: grid;
grid-template-columns: 1fr;
gap: 30px;
margin-top: 20px;
@media screen and (min-width: 768px) {
grid-template-columns: 1fr 1fr;
}
`;
const PriceRow = styled.div`
display: flex;
align-items: center;
gap: 4rem;
margin: 30px 0;
`
const Price = styled.span`
font-size: 2rem;
font-weight: 700;
`
export default function ProductPage({ product }) {
const {addProduct} = useContext(CartContext)
return (
<>
<Header />
<Center>
<StyledTitle>Product Details</StyledTitle>
<ColWrapper>
<WhiteBox>
<ProductImages images={product.images} />
</WhiteBox>
<div>
<Title>{product.title}</Title>
{product.description}
<PriceRow>
<Price>${product.price}</Price>
<Button size={"large"} outline black onClick={() => addProduct(product._id)}>
<CartIcon />
Add to Cart
</Button>
</PriceRow>
</div>
</ColWrapper>
</Center>
</>
);
}
export async function getServerSideProps(context) {
await mongooseConnect();
const { id } = context.query;
const product = await Product.findById(id);
return {
props: {
product: JSON.parse(JSON.stringify(product)),
},
};
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
<link rel="stylesheet" href="styles.css">
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
}
.container {
display: flex;
height: 100vh;
}
.left-layout {
flex: 70%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: rgba(255, 255, 255, 0.7); /* White background color */
background-image: url('https://img.freepik.com/premium-photo/set-four-illustrations-landscape_875337-154.jpg?w=900');
border-radius: 0 20px 20px 0; /* Curved corner on the right side */
overflow: hidden; /* Hide overflowing parts of the image */
position: relative; /* Add relative positioning for the search box */
background-size: cover; /* Scale the image as large as possible without stretching */
background-position: center; /* Center the background image */
background-repeat: no-repeat; /* Prevent the image from repeating */
}
.left-layout img {
min-width: 100%; /* Make the image fill the entire left layout */
height: 100%; /* Maintain the aspect ratio of the image */
}
.search-box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(255, 255, 255, 0.7); /* Transparent background */
border-radius: 20px;
display: flex;
align-items: center;
padding: 5px;
}
.search-box input {
flex: 1;
padding: 10px 40px; /* Adjust the input box size */
border: none;
outline: none;
background-color: transparent; /* Set the input box to transparent */
font-size: 16px; /* Adjust font size if needed */
}
.search-box button {
background: transparent;
border: none;
padding: 5px;
cursor: pointer;
}
/* Make sure the search icon is visible */
.search-box img {
max-width: 30px;
max-height: 30px;
}
.right-layout {
flex: 30%;
padding: 20px;
background-color: #e2e0e0;
border-radius: 20px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center; /* Align content to the center */
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* Add a subtle box shadow */
}
.app-title {
font-size: 24px;
margin-bottom: 10px;
color: #000000; /* Black color for the title */
}
#weatherResult {
margin-top: 10px; /* Adjust margin for spacing */
text-align: center; /* Center the weather description */
}
/* Weather details styles */
#weatherResult p {
font-size: 18px;
margin: 5px 0;
}
.weather-icon {
width: 50px;
height: 50px;
}
/* Additional styles */
.temperature-container {
background-color: #ffffff;
border-radius: 20px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
}
.temperature-text {
font-size: 40px;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.container {
flex-direction: column;
align-items: center;
justify-content: center;
}
.left-layout {
flex: 100%;
border-radius: 20px; /* Remove the curved corner on smaller screens */
}
}
</style>
</head>
<body>
<div class="container">
<div class="left-layout" id="leftLayout">
<!-- Weather icon will be dynamically inserted here -->
<div class="search-box">
<input type="text" id="cityInput" placeholder="Enter Location">
<button onclick="getWeather()">
<img src="https://img.icons8.com/?size=512&id=132&format=png" alt="Search Icon">
</button>
</div>
</div>
<div class="right-layout">
<h1 class="app-title">Weather App</h1>
<div class="temperature-container">
<p class="temperature-text" id="temperatureText"></p>
<div id="weatherResult"></div>
</div>
</div>
</div>
<script>
function getWeather() {
const apiKey = '815d9c869e1ec958ac264b881609c488';
const city = document.getElementById('cityInput').value;
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;
fetch(apiUrl)
.then(response => response.json())
.then(data => {
const weatherResult = document.getElementById('weatherResult');
const temperatureText = document.getElementById('temperatureText');
const leftLayout = document.getElementById('leftLayout');
if (data.cod === '404') {
weatherResult.innerHTML = `<p>Error: City not found</p>`;
} else {
const { name, main, weather } = data;
const temperature = main.temp;
const description = weather[0].description;
const iconCode = weather[0].icon;
// Update temperature and weather description
temperatureText.textContent = `${temperature} °C`;
weatherResult.innerHTML = `<p>${description}</p>
<p>City: ${name}</p>`;
// Change left layout image based on weather condition
const backgroundImageUrl = getBackgroundImageUrl(iconCode);
leftLayout.style.backgroundImage = `url(${backgroundImageUrl})`;
// Set weather icon
const weatherIcon = document.createElement('img');
weatherIcon.classList.add('weather-icon');
weatherIcon.src = `https://openweathermap.org/img/w/${iconCode}.png`;
weatherResult.prepend(weatherIcon);
}
})
.catch(error => {
const weatherResult = document.getElementById('weatherResult');
weatherResult.innerHTML = `<p>Error: ${error.message}</p>`;
});
}
// Function to get background image URL based on weather condition
function getBackgroundImageUrl(weatherIcon) {
const weatherConditions = {
'01': 'https://img.freepik.com/premium-photo/colorful-autumn-landscape-mountains-sunrise_230497-3003.jpg?w=900', //clear sky
'02': 'https://img.freepik.com/free-vector/skye-wallpaper-with-fluffy-clouds_1017-30895.jpg?w=996&t=st=1690373537~exp=1690374137~hmac=bef4c6f33b381af94e4e8337c0ff3873fb879c6eff300498b12ca3ab19434030', //few clouds
'03': 'https://img.freepik.com/free-vector/cloud-background-pastel-paper-cut-style-vector_53876-135914.jpg?w=900&t=st=1690383500~exp=1690384100~hmac=7e1e6caba19262a715a39062bf57117b79346ad1f6749dbb88be5543df7667c5', //scattered cloud
'04': 'https://img.freepik.com/free-photo/dramatic-sky-tranquil-scene-dusk-generated-by-ai_188544-43238.jpg?t=st=1690384376~exp=1690387976~hmac=e2f877a344898a3b09beb57d67dddf775b30a03b56316b09e90d110c64d987a0&w=996', //broken cloudd
'09': 'https://img.freepik.com/free-vector/monsoon-rainfall-with-clouds-background_1017-32365.jpg?w=996&t=st=1690373450~exp=1690374050~hmac=c0482e3d6a3beb1fa2f5397d2e7152957371c16dae8a2cdbd97299cd2667d9d7', //shower rain
'10': 'https://img.freepik.com/premium-photo/rainy-day-swiss-countryside_702665-302.jpg?w=996', // rain
'11': 'https://img.freepik.com/free-photo/majestic-mountain-range-tranquil-meadow-spooky-forest-generated-by-ai_188544-38542.jpg?t=st=1690383727~exp=1690387327~hmac=42964351afeae76a3c49df8a0491e09661e628e2250945606d96c70668a0e4e7&w=996', //thunderstrom
'13': 'https://example.com/snow.jpg', //snow
'50': 'https://example.com/mist.jpg', //mist
};
const weatherCondition = weatherIcon.slice(0, -1); // Remove last character (d or n)
return weatherConditions[weatherCondition] || 'https://example.com/default.jpg';
}
</script>
</body>
</html> |
import React from "react";
import PropTypes from "prop-types";
import Panel from "muicss/lib/react/panel";
import RainbowTableDetailTable from "./rainbow-table-detail-table";
import RainbowTableEfficiencyTable from "./rainbow-table-efficiency-table";
import RainbowTableSearchResultsTable from "./rainbow-table-search-results-table";
import RainbowTableSearchForm from "./rainbow-table-search-form";
import RainbowTableSearchTable from "./rainbow-table-search-table";
import ErrorElement from "./error-element";
import DefaultRainbowTablePage from "./default-rainbow-table-page";
import { JobStatus } from "../constants";
export default class SearchRainbowTablePage extends DefaultRainbowTablePage {
constructor() {
super();
Object.assign(this.state, {
rainbowTable: null,
searchResults: { totalSearches: 0, foundSearches: 0 }
});
}
retrieveData() {
this.state.rainbowTableService
.getRainbowTableById(this.props.rainbowTableId)
.then((rainbowTable) => {
this.setState({ rainbowTable: rainbowTable });
if (
rainbowTable.status === JobStatus.STARTED ||
rainbowTable.status === JobStatus.QUEUED
) {
setTimeout(this.retrieveData.bind(this), 5000);
} else {
this.state.rainbowTableService
.getRainbowTableSearchResultsById(
this.props.rainbowTableId
)
.then((searchResults) => {
this.setState({ searchResults: searchResults });
});
}
});
}
renderWithRainbowTableService() {
if (this.state.rainbowTable === null) {
return (
<Panel>
<ErrorElement error={this.state.error} />
</Panel>
);
}
return (
<Panel>
<ErrorElement error={this.state.error} />
<h2>
Rainbow Table '{this.state.rainbowTable.name}'
</h2>
<div className="mui-divider" />
<div className="content-block">
<h4>Table Details</h4>
<RainbowTableDetailTable
entities={[this.state.rainbowTable]}
/>
</div>
<div className="content-block">
<h4>Table Efficiency Stats</h4>
<RainbowTableEfficiencyTable
entities={[this.state.rainbowTable]}
/>
</div>
<div className="content-block">
<h4>Search Result Stats</h4>
<RainbowTableSearchResultsTable
entities={[this.state.searchResults]}
/>
</div>
<div className="content-block">
<h4>Past Rainbow Table Searches</h4>
<RainbowTableSearchTable
rainbowTableService={this.state.rainbowTableService}
rainbowTableId={this.props.rainbowTableId}
refreshRateSeconds={5}
/>
</div>
<div className="content-block">
<h4>New Rainbow Table Search</h4>
<RainbowTableSearchForm
rainbowTable={this.state.rainbowTable}
rainbowTableService={this.state.rainbowTableService}
/>
</div>
</Panel>
);
}
}
SearchRainbowTablePage.propTypes = {
rainbowTableId: PropTypes.string.isRequired,
httpService: PropTypes.func.isRequired,
error: PropTypes.string
}; |
import useAuthContext from "../../hook/useAuthContext";
import { useState } from "react";
import { Link } from "react-router-dom";
import { REGISTER } from "../../config/routes/paths";
import { validatePassword, validateEmail } from "../../helpers/Helpers";
import Layout from "../../components/Layouts/Layout";
import styles from "./Login.module.css";
const Login = () => {
const { login } = useAuthContext();
const [message, setMessage] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
let classMessage = "alert alert-fw alert-error";
let message = "Error login";
const data = new FormData(e.currentTarget);
let email = data.get("email");
let password = data.get("password");
if (!validateEmail(email)) return setMessage({ classMessage, message });
if (validatePassword(password))
return setMessage({ classMessage, message });
let userLogin = await login({
email: email,
password: password,
});
if (userLogin) {
classMessage = "alert alert-fw alert-ok";
message = "Success";
}
setMessage({ classMessage, message });
};
return (
<Layout>
<section className="section-title section-center">
<h1>Login</h1>
<p>Example login. Dont have validation.</p>
</section>
<section className={`${styles.form_login_container}`}>
<form
className={`${styles.form_login} form-default form-vertical`}
onSubmit={handleSubmit}
>
<label>
<input
type="text"
className="inpt-primary"
placeholder="Email"
name="email"
/>
</label>
<label>
<input
type="password"
className="inpt-primary"
placeholder="Password"
name="password"
/>
</label>
<button type="submit" className="btn btn-primary">
Sign in
</button>
{message ? (
<span className={message.classMessage}>{message.message}</span>
) : (
""
)}
</form>
<p className={styles.link_user}>
New to APP?
<Link to={REGISTER}> Create new account</Link>.
</p>
</section>
</Layout>
);
};
export default Login; |
import {
PICK_INGREDIENT,
RESET_INGREDIENT,
SET_INGREDIENTS,
DELETE_INGREDIENT,
SET_INFO_INGREDIENT,
MAKE_ORDER,
DECREMENT_MAP,
INCREMENT_MAP,
SET_BUN,
SWITCH_INGREDIENT,
RESET_MAP,
ERROR_SET_INGREDIENTS,
ERROR_MAKE_ORDER,
UPDATE_USER,
NETWORK_CONNECTION,
DECREASE_BUN_MAP,
INCREASE_BUN_MAP
} from '../actions/constructor';
import {Reducer} from 'redux'
import { IBareBurgerIngredient, IReduxState,IOrder, IUser, IState } from '../../components/Interfaces';
import {IAction, IBareAction, IDecreaseBntMap, IIncreaseBunMap} from 'services/actions/Interfaces';
import {RootState} from 'services/store'
import {Actions,INetworkConnection ,
IPickIngredient,
IDeleteIngredient,
IErrorSetIngredients,
ISwitchIngredient,
IResetIngredients,
IErrorMakeOrder,
IMakeOrder,
IUpdateUser,
ISetInfoIngredient,
ISetBun,
ISetIngredients,
IIncrementMap,
IDecrementMap,
IResetMap} from 'services/actions/Interfaces'
//Here I treat a bun ingredient separately.
export const initialIngredients: IBareBurgerIngredient[] =[];
export const initialBun: IBareBurgerIngredient | null = null;
//this is an aux object to make it easier to account for the number of ingredients of the same _id.
export const initialIngredientMap: Object={};
const initialAllIngredients: IBareBurgerIngredient[] | string =[];
export const initalIngredientDetails: IBareBurgerIngredient | null = null;
export const initalOrderDetails: IOrder | null = null;
export const initialUser: IUser | null = null;
const initialVisited : Object = {};
export const initialNetworkError : boolean=false;
//:Reducer< boolean,IAction<boolean>>
export const noConnectionReducer = (state:boolean = initialNetworkError, action:INetworkConnection):boolean=>{
switch(action.type){
case NETWORK_CONNECTION:{
if(action.payload) return true;
else return false;
}
default:
return state;
}
}
export const securityUserReducer = (state: IUser | null= initalOrderDetails, action:IUpdateUser): IUser | null=>{
switch(action.type){
case UPDATE_USER:
return action.payload ? {...action.payload}: initialUser;
default:
return state;
}
}
export const orderDetailsReducer= (state: IOrder | null = initalOrderDetails, action:IErrorMakeOrder| IMakeOrder):IOrder | null=>{
switch(action.type){
case MAKE_ORDER:
return action.payload ? {...action.payload}: null;
case ERROR_MAKE_ORDER:
return initalOrderDetails
default:
return state;
}
}
export const ingredientDetailsReducer = (state: IBareBurgerIngredient | null = initalIngredientDetails, action:ISetInfoIngredient): IBareBurgerIngredient | null=>{
switch(action.type){
case SET_INFO_INGREDIENT:{
if(action.payload) return {...action.payload};
else return initalIngredientDetails;
}
default:
return state;
}
}
export const allIngredientsReducer = (state=initialAllIngredients, action:IErrorSetIngredients |ISetIngredients): IBareBurgerIngredient[] | string=>{
switch(action.type){
case SET_INGREDIENTS:
return Array.isArray(action.payload)? [...action.payload]:action.payload;
case ERROR_SET_INGREDIENTS:
return 'error';
default:
return state;
}
}
export const bunReducer = (state:IBareBurgerIngredient | null =initialBun, action:ISetBun):IBareBurgerIngredient | null=>{
switch(action.type){
case SET_BUN :{
return action.payload? {...action.payload} : null;
}
default:
return state;
}
}
export const mapReducer = (state: Object=initialIngredientMap, action:IIncrementMap|IDecrementMap| IResetMap|IIncreaseBunMap|
IDecreaseBntMap): Object=>{
switch(action.type){
case RESET_MAP :
return initialIngredientMap
case DECREMENT_MAP: {
const _id = action.payload._id;
const tempContext = JSON.parse(JSON.stringify(state));
if(state&& state.hasOwnProperty(_id) && state[_id]>1){
tempContext[_id]=state[_id]-1
}
else if(state && state.hasOwnProperty(_id) && state[_id]===1){
delete tempContext[_id];
}
else{
}
return tempContext
}
case INCREMENT_MAP:{
const _id = action.payload._id;
const tempContext = JSON.parse(JSON.stringify(state));
if(state&& state.hasOwnProperty(_id)){
tempContext[_id]=state[_id]+1;
}
else{
tempContext[_id]=1;
}
return tempContext
}
case DECREASE_BUN_MAP:{
const tempContext = {...state};
const _id = action.payload._id
if(state.hasOwnProperty(_id)) {
tempContext[_id]=0;
}
return tempContext;
}
case INCREASE_BUN_MAP:{
const tempContext = {...state};
const _id = action.payload._id;
tempContext[_id]=1;
return tempContext;
}
default:
return state;
}
}
export const ingredientReducer = (state: IBareBurgerIngredient[]=initialIngredients, action:IPickIngredient| IDeleteIngredient| ISwitchIngredient| IResetIngredients)=>{
switch(action.type){
case PICK_INGREDIENT :
return [...state.concat(action.payload)]
case RESET_INGREDIENT:
return initialIngredients
case DELETE_INGREDIENT :{
const tempContext = JSON.parse(JSON.stringify(state));
const index = state.findIndex(el=>{return (el._id===action.payload._id)})
tempContext.splice(index,1);
return tempContext;
}
case SWITCH_INGREDIENT:{
const tempContext = JSON.parse(JSON.stringify(state));
tempContext[action.to] = state[action.from];
tempContext[action.from] = state[action.to];
return tempContext;
}
default:
return state;
}
}
// export const updateIngredientReducer = (state: IReduxState=initialState, action:{type:string,to:number, from:number})=>{
// switch(action.type){
// case SWITCH_INGREDIENT:{
// const tempContext = JSON.parse(JSON.stringify(state));
// tempContext.ingredients[action.to] = state.ingredients[action.from];
// tempContext.ingredients[action.from] = state.ingredients[action.to];
// return tempContext;
// }
// }
// }
// export const constructorIngredientArrayReducer = (state: IReduxState=initialState, action :IAction<IBareBurgerIngredient[] | string>)=>{
// switch(action.type){
// case SET_INGREDIENTS:
// return {...state, allIngredients: Array.isArray(action.payload)? [...action.payload]:action.payload};
// default:
// return state;
// }
// } |
# $browserV
<ContainerBox title="介绍">
<template #desc>
判断用户浏览器到没达到要求的版本,没达到让他升级
</template>
</ContainerBox>
<ContainerBox title="基础用法">
```js
console.log($browserV); //{browser:"",version:0}
```
<ShowCode>
<template #codes>
```js
export const $browserV = (() => {
const ua = navigator.userAgent;
let browser = 0;
let version = 0;
if (ua.indexOf("Chrome") > -1) {
browser = "chrome";
version = Number(
ua
.match(/Chrome\/[\d.]+/)[0]
.split("/")[1]
.split(".")[0]
);
} else if (ua.indexOf("Safari") > -1) {
browser = "safari";
version = Number(
ua
.match(/Version\/[\d.]+/)[0]
.split("/")[1]
.split(".")[0]
);
}
return { browser, version };
})();
```
</template>
</ShowCode>
</ContainerBox> |
<?php
namespace App\Http\Requests\Admin\User;
use App\Rules\Phone;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UserStoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'username'=>'bail|required|string|unique:users',
'password'=>'required|string',
'phone'=>['bail','required',new Phone(),'unique:users'],
'role'=>['required','integer',Rule::in(1,2)],
];
}
public function attributes()
{
return [
'username'=>'用户账号',
'password'=>'密码',
'phone'=>'手机号码',
'role'=>'角色',
];
}
} |
# C#/Rust Connection Prototype
I wrote a small prototype, which shows how Rust code can be called from C#.
It consists of a small Rust library and a C# console application.
## Basic structure and compilation
The root folder contains the C# project, the subfolder "rusttest" contains the
rust cargo crate. This crate has the following Definition in its Cargo.toml file,
which tells the compiler to create a DLL:
```toml
[lib]
name = "rust_test"
crate-type = ["dylib"]
```
Compile it by running
```bash
cd rusttest
cargo build
```
You can then run the C# App normally through VS/Rider. The project has a
post-build build event which copies the compiled rust DLL into the C# build
directory.
## Basic function syntax
Every exposed Rust function has to have the following signature:
```rust
#[no_mangle]
pub extern fn hello_world() {
println!("Hello from Rust 😎");
}
```
- The ```#[no_mangle]``` ensures that the rust compiler doesn't change the
function name, so that it can be called externally
- The function has to be labeled ```pub``` and ```extern``` to be fully exposed
in the DLL
The corresponding C# function has to have the following signature:
```c#
[DllImport("rust_test.dll")]
public static extern void hello_world();
```
> **Note**: The C# function name can differ (and conform to the C# conventions) by
using the ```EndPoint``` property in the ```DllImport``` Attribute. The above
snippet is equivalent to this one:
>
> ```c#
> [DllImport("rust_test.dll", EntryPoint = "hello_world")]
> public static extern void HelloWorld();
> ```
## Type conversion
### Scalar types
The basic scalar types can be (with the exception of chars) easily converted to
C# types. A conversion table can be found [here](https://microsoft.github.io/rust-for-dotnet-devs/latest/language/scalar-types.html)
> **Note**: For integer types it is recommended to use the .NET classes
> (e.g. Int32) instead of the primitive types (e.g. int) to specify the bit width
> explicitly.
```rust
pub extern fn square(val: i32) -> i32 {}
pub extern fn invert(val: bool) -> bool {}
pub extern fn isOdd(val: i64) -> bool {}
pub extern fn sqrt(val: f32) -> f32 {}
```
```c#
public static extern Int32 square(Int32 val);
public static extern bool invert(bool val);
public static extern bool isOdd(Int64 val);
public static extern float sqrt(float val);
```
### Structs
Structs can be used to easily transfer multiple values at once. In Rust, they
have to have the following syntax:
```rust
#[repr(C)]
pub struct PolarCoordinates {
length: f32,
angle: f32
}
```
- The #[repr(C)] saves the struct in a c-like structure (i.e the entries are
saved sequentially in the given order)
The corresponding C# struct looks like this:
```c#
[StructLayout(LayoutKind.Sequential)]
public struct PolarCoordinates
{
public float Length;
public float Angle;
}
```
- The ```[StructLayout(LayoutKind.Sequential)]``` ensures, like in Rust, that the
structure is identical
> **Note**: The variable names can differ, but the types and order have to match.
### Arrays
Methods with array parameters can be called in the c-style: a (mutable) pointer
to the array and the length. The best tactic is, for our purpose, to let C#
allocate the array and give it to Rust. Therefore, there are two approaches
(given an input array):
1. Allocate a second array (with compile-time known size). Pass a constant
pointer to the input array and a mutable pointer to the output array, along with
their sizes
```rust
pub extern fn inverse_with_second_array(data_in: *const u8, data_out: *mut u8, len: usize)
```
```c#
private static extern void inverse_with_second_array(byte[] dataIn, byte[] dataOut, UIntPtr len);
```
2. Let Rust modify the input array in-place, i.e. pass a mutable pointer to the
input array, along with its size
```rust
pub extern fn inverse_in_place(data: *mut u8, len: usize)
```
```c#
public static extern void inverse_in_place(byte[] data, UIntPtr len);
```
You can then convert the raw pointer into a (mutable) rust array slice and work
with it normally:
```rust
let input: &[u8] = unsafe { std::slice::from_raw_parts(data_in, len)};
let output: &mut[u8] = unsafe { std::slice::from_raw_parts_mut(data_out, len) };
```
### Strings
Strings are just char arrays:

But they are a bit complicated over language barriers, especially if the one uses
UTF-16 with 2-Byte chars and the other uses UTF-32 with 4-byte chars. But both
support UTF-8 and 1-byte chars (aka c-chars). Therefore the strategy for sending
Strings to Rust is:
1. Encode the C# String as a null-terminated UTF-8 byte array and send it to Rust
```c#
RustInterface.printc(Encoding.UTF8.GetBytes(str));
```
2. Let Rust decode the C-String and convert it to a normal Rust String
```rust
let c_str = unsafe { CStr::from_ptr(buf) };
let str = c_str.to_str().unwrap();
```
The reverse way is not so simple: You could let C# provide a predefined buffer
and copy the formatted bytes into it, but there is a more elegant way: Rust has
a way to transfer the ownership to the C caller (aka trust that there is no
memory leak). This opens up the following way:
1. Decode the Rust String into a C-String
2. Pass the ownership to C and save the pointer in a static variable
```rust
let ptr = CString::new(str).unwrap().into_raw();
unsafe { STRING_POINTER = ptr; }
```
3. In C#: Copy the data into a managed String and notify Rust to free the String
```c#
var ptr = format_string(number);
var str = Marshal.PtrToStringUTF8(ptr) ?? "null";
free_string();
```
4. In Rust: Take back ownership of the string, clear the static variable and
deallocate the data
```rust
unsafe {
let _ = CString::from_raw(STRING_POINTER);
STRING_POINTER = 0 as *mut c_char;
}
```
## Example Output
The C# console app tests every function type I’ve listed here (and some more).
The output should look something like this:
```text
Hello from C#!
Hello from Rust 😎
20^2 is 400
The inverse of True is False
Is 1099511627777 odd? True
The square root of 6,25 is 2,5
The length of euler vector (3, 4) is 5
The polar vector (5, 0,7853982) is equivalent to the euler vector (3,535534, 3,535534)
The reverse of [1, 2, 3, 4, 5] is [5, 4, 3, 2, 1]
After in-place reverse, data is [5, 4, 3, 2, 1]
C# String: "This is a test äöü 😎"
Rust decoded string: "This is a test äöü 😎"
Created Rust string: "The number is 42 äöü 😎"
```
## Useful links and tutorials
I mainly used [this](https://dev.to/living_syn/calling-rust-from-c-6hk) guide
from the DEV Community and the [Rust for C#/.NET developers](https://microsoft.github.io/rust-for-dotnet-devs/latest/)
reference by .NET. |
import CardProductList from "../components/CardProductList";
import styles from "../styles/productList.module.css";
import React, { useState, useEffect } from "react";
import { useRouter } from "next/router";
import { trpc } from "../utils/trpc";
import {
Box,
Flex,
Highlight,
Button,
Menu,
MenuButton,
MenuList,
MenuItem,
MenuDivider,
useColorModeValue,
} from "@chakra-ui/react";
export default function Productlist() {
const router = useRouter();
const category: any = router.query.category;
const q: any = router.query.q;
const colorBg = useColorModeValue("gray.100", "gray.900");
//trae del back
const utils = trpc.useContext();
let products: any;
const [page, setPage] = useState(1);
const [limit, setLimit] = useState(10);
const [order, setOrder] = useState("");
if (products === undefined) {
if (category || q) {
if (!!category && !q) {
products = trpc.product.getProductByCategory.useQuery({
categoryName: category,
order,
limit,
page,
}).data;
} else if (!!q && !category) {
products = trpc.product.getProductByTitle.useQuery({
title: q,
order,
limit,
page,
}).data;
} else {
products = trpc.product.getProductByTitleAndCategory.useQuery({
title: q,
categoryName: category,
limit,
page,
order,
}).data;
}
} else {
products = trpc.product.getProducts.useQuery({
limit,
page,
order,
}).data;
}
}
const [data, setData] = useState<any>(undefined);
function handleOrder(e: string) {
if (e === "relevantes") {
setOrder("Más relevantes");
} else if (e === "menor") {
setOrder("Menor precio");
} else if (e === "mayor") {
setOrder("Mayor precio");
}
}
//para que refresque los datos
useEffect(() => {
setData(products);
}, [products]);
if (!data) return <p>No profile data</p>;
const handleNext = (e: any) => {
setPage(page + 1);
e.preventDefault();
utils.product.getProducts.invalidate();
};
const handlePrevious = (e: any) => {
if (page > 1) setPage(page - 1);
e.preventDefault();
utils.product.getProducts.invalidate();
};
return (
<div>
<Box bg={colorBg} px={4}>
<Flex h={8} alignItems={"center"} justifyContent={"space-between"}>
<Flex alignItems={"center"}>
<Highlight
query={`${q}`}
styles={{ px: "1", py: "0", rounded: "full", bg: "orange.100" }}
>
{`1 a ${data?.length} de ${data?.length} resultados ${
q ? `para: ${q}` : ""
}`}
</Highlight>
</Flex>
<Flex alignItems={"center"}>
<Menu>
<MenuButton
as={Button}
rounded={"full"}
variant={"link"}
cursor={"pointer"}
minW={0}
>
Ordenar por: {order}
</MenuButton>
<MenuList zIndex={2}>
<MenuItem onClick={() => handleOrder("relevantes")}>
Más relevantes
</MenuItem>
<MenuDivider />
<MenuItem onClick={() => handleOrder("menor")}>
Menor precio
</MenuItem>
<MenuDivider />
<MenuItem onClick={() => handleOrder("mayor")}>
Mayor precio
</MenuItem>
</MenuList>
</Menu>
</Flex>
</Flex>
</Box>
<div className={styles.cardsDivProdHome}>
{data?.map((p: any) => (
<CardProductList
productName={p.title}
photo={p.pictures[0]}
productPrice={p.price}
rating={p.rating}
id={p.id}
key={p.id}
/>
))}
</div>
<Box
display="flex"
justifyContent="center"
alignContent="center"
margin="5"
>
{page > 1 ? (
<Button onClick={(e) => handlePrevious(e)}>Anterior</Button>
) : null}
<Button>{page}</Button>
{data?.length >= limit ? (
<Button onClick={(e) => handleNext(e)}>Proximo</Button>
) : null}
</Box>
</div>
);
} |
import React from 'react';
import {
usePockestContext,
} from '../../contexts/PockestContext';
import TargetMonsterSelect from '../TargetMonsterSelect';
import useEggs from '../../hooks/useEggs';
import getMonsterPlan from '../../utils/getTargetMonsterPlan';
import './index.css';
function EggControls() {
const {
pockestState,
} = usePockestContext();
const allEggs = useEggs();
const targetPlan = React.useMemo(() => getMonsterPlan(pockestState), [pockestState]);
const planEgg = React.useMemo(
() => allEggs.find((egg) => egg?.name_en?.slice(0, 1) === targetPlan?.planEgg),
[allEggs, targetPlan],
);
return (
<div className="EggControls">
<div className="PockestLine">
<span className="PockestText">Target</span>
<TargetMonsterSelect />
</div>
<div className="PockestLine">
<span className="PockestText">Plan</span>
<span className="PockestText PockestLine-value">{targetPlan?.planId ?? '--'}</span>
</div>
<div className="PockestLine">
<span className="PockestText">Egg</span>
<span className="PockestText PockestLine-value">{planEgg?.name_en ?? '--'}</span>
</div>
<div className="PockestLine">
<span className="PockestText">Cost</span>
<span className="PockestText PockestLine-value">
{planEgg?.unlock ? 0 : planEgg?.buckler_point ?? '--'}
</span>
</div>
</div>
);
}
export default EggControls; |
'''
Given an array arr of size n, the task is to check if the given array can be a level order representation of a Max Heap.
Example 1:
Input:
n = 6
arr[] = {90, 15, 10, 7, 12, 2}
Output:
1
Explanation:
The given array represents below tree
90
/ \
15 10
/ \ /
7 12 2
The tree follows max-heap property as every
node is greater than all of its descendants.
Example 2:
Input:
n = 6
arr[] = {9, 15, 10, 7, 12, 11}
Output:
0
Explanation:
The given array represents below tree
9
/ \
15 10
/ \ /
7 12 11
The tree doesn't follows max-heap property 9 is
smaller than 15 and 10, and 10 is smaller than 11.
Your Task:
You don't need to read input or print anything. Your task is to complete the function isMaxHeap() which takes the array arr[] and its size n as inputs and returns True if the given array could represent a valid level order representation of a Max Heap, or else, it will return False.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)
'''
class Solution:
def isMaxHeap(self, arr, n):
# Traverse through all internal nodes starting from last non-leaf node
for i in range((n // 2) - 1, -1, -1):
# Check if the current node is smaller than any of its children
if arr[i] < arr[2 * i + 1] or (2 * i + 2 < n and arr[i] < arr[2 * i + 2]):
return False
return True
#{
# Driver Code Starts
if __name__ =='__main__':
t= int(input())
for tcs in range(t):
n=int(input())
arr=[int(x) for x in input().split()]
ob=Solution()
print(int(ob.isMaxHeap(arr,n)))
# } Driver Code Ends |
## Data Wrangling R - Prof. Wilson Tarantin Junior
## MBA DSA USP ESALQ
# Atividade de Análise nº 1 - Introdução ao pacote dplyr
# https://dplyr.tidyverse.org/
# O pacote dplyr está contido no tidyverse
# dplyr: contém muitas funções comuns na manipulação de dados
#--------------------Carregar os Pacotes----------------------------------------
library(tidyverse)
library(readxl)
#--------------------Importar os datasets---------------------------------------
# "dataset_inicial" - Fonte: Fávero & Belfiore (2017, Cap. 12)
caminho <- file.path('.')
nova_base <- read_excel(file.path(caminho, "data", "(1.2) Dataset Aula Data Wrangling.xls")) %>%
rename(observacoes = 1,
tempo = 2,
distancia = 3,
semaforos = 4,
periodo = 5,
perfil = 6)
#--------------------Transmute--------------------------------------------------
# Função "transmute": inclui variáveis no dataset, excluindo as existentes
# Depois de informar o dataset, informe as variáveis mantidas e adicionadas
base_exclui_1 <- transmute(nova_base,
observacoes, tempo,
variavel_nova_1, variavel_nova_2)
# Podemos praticar um pouco mais com o pipe
base_exclui_rename <- nova_base %>%
transmute(observacoes, tempo, variavel_nova_1) %>%
mutate(tempo_novo = recode(tempo,
`10` = "dez",
`15` = "quinze",
`20` = "vinte",
`25` = "vinte e cinco",
`30` = "trinta",
`35` = "trinta e cinco",
`40` = "quarenta",
`50` = "cinquenta",
`55` = "cinquenta e cinco")) %>%
mutate(posicao = cut(tempo,
breaks = c(0, median(tempo), Inf),
labels = c("menores", "maiores")))
# Para referência do cálculo, a mediana da amostra
median(nova_base$tempo)
# Utilizamos a função "cut", que converte uma variável de valores em intervalos
# No exemplo acima, pedimos 2 intervalos tendo a mediana como referência
# Em seguida, já adicionamos novos nomes aos intervalos (labels)
# Note que a variável resultante é uma "factor"
# Ao aplicar a função "summary" à variável factor, o resultado é uma contagem
# summary: gera estatísticas descritivas para variáveis
summary(base_exclui_rename$posicao) |
#ifndef _DICT_H_
#define _DICT_H_
#include <string>
#include <iostream>
#include <cassert>
#include <fstream>
#include <vector>
#include <set>
#include <unordered_map>
#include <functional>
class Dict {
typedef std::unordered_map<std::string, unsigned, std::hash<std::string> > Map;
public:
Dict() : b0_("<bad0>") {
words_.reserve(1000);
}
inline unsigned max() const { return words_.size(); }
inline unsigned size() const { return words_.size(); }
inline unsigned count(const std::string& word) const { return d_.count(word); }
static bool is_ws(char x) {
return (x == ' ' || x == '\t');
}
inline void ConvertWhitespaceDelimitedLine(const std::string& line, std::vector<unsigned>* out) {
size_t cur = 0;
size_t last = 0;
int state = 0;
out->clear();
while(cur < line.size()) {
if (is_ws(line[cur++])) {
if (state == 0) continue;
out->push_back(Convert(line.substr(last, cur - last - 1)));
state = 0;
} else {
if (state == 1) continue;
last = cur - 1;
state = 1;
}
}
if (state == 1)
out->push_back(Convert(line.substr(last, cur - last)));
}
inline unsigned Convert(const std::string& word, bool frozen = false) {
Map::iterator i = d_.find(word);
if (i == d_.end()) {
if (frozen)
return 0;
words_.push_back(word);
d_[word] = words_.size();
return words_.size();
} else {
return i->second;
}
}
inline const std::string& Convert(const unsigned id) const {
if (id == 0) return b0_;
return words_[id-1];
}
template<class Archive> void serialize(Archive& ar, const unsigned int version) {
ar & b0_;
ar & words_;
ar & d_;
}
private:
std::string b0_;
std::vector<std::string> words_;
Map d_;
};
inline void ReadFromFile(const std::string& filename,
Dict* d,
std::vector<std::vector<unsigned> >* src,
std::set<unsigned>* src_vocab) {
src->clear();
std::cerr << "Reading from " << filename << std::endl;
std::ifstream in(filename);
assert(in);
std::string line;
int lc = 0;
while(getline(in, line)) {
++lc;
src->push_back(std::vector<unsigned>());
d->ConvertWhitespaceDelimitedLine(line, &src->back());
for (unsigned i = 0; i < src->back().size(); ++i) src_vocab->insert(src->back()[i]);
}
}
inline void ReadParallelCorpusFromFile(const std::string& filename,
Dict* d,
std::vector<std::vector<unsigned> >* src,
std::vector<std::vector<unsigned> >* trg,
std::set<unsigned>* src_vocab,
std::set<unsigned>* trg_vocab) {
src->clear();
trg->clear();
std::cerr << "Reading from " << filename << std::endl;
std::ifstream in(filename);
assert(in);
std::string line;
int lc = 0;
std::vector<unsigned> v;
const unsigned kDELIM = d->Convert("|||");
while(getline(in, line)) {
++lc;
src->push_back(std::vector<unsigned>());
trg->push_back(std::vector<unsigned>());
d->ConvertWhitespaceDelimitedLine(line, &v);
unsigned j = 0;
while(j < v.size() && v[j] != kDELIM) {
src->back().push_back(v[j]);
src_vocab->insert(v[j]);
++j;
}
if (j >= v.size()) {
std::cerr << "Malformed input in parallel corpus: " << filename << ":" << lc << std::endl;
abort();
}
++j;
while(j < v.size()) {
trg->back().push_back(v[j]);
trg_vocab->insert(v[j]);
++j;
}
}
}
#endif |
export default class CodeEditorModal {
__html = `
<div class="modal-dialog modal-xl modal-fullscreen-sm-down modal-dialog-centered">
<div class="modal-content">
<div class="modal-header border-0">
<h1 class="modal-title fs-6">EDITOR DE CODIGO</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body p-0 d-flex w-100" style="height: 768px">
<div class="spinner bg-dark d-flex w-100 h-100 justify-content-center align-items-center position-absolute">
<div class="spinner-border p-5" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
<div class="rounded-bottom h-100 code-editor"></div>
<iframe class="bg-dark d-none d-md-block w-100 code-preview"></iframe>
</div>
<div class="modal-footer d-md-none p-1 border-0">
<div class="d-flex w-100 justify-content-between">
<button type="button" class="btn-responsive w-100 me-2" data-bs-dismiss="modal">Sair</button>
<button type="button" class="btn-responsive w-100 view">Resultado</button>
</div>
</div>
</div>
</div>`
constructor(config) {
this._element = document.createElement('div');
this._element.classList.add('modal', 'fade');
this._element.setAttribute('tabindex', '-1');
this._element.innerHTML = this.__html;
this._root = this._element.querySelector('.modal-body');
this.modal = new bootstrap.Modal(this._element);
this.editorInitialized = false;
const iframe = this._element.querySelector('.code-preview')
const setContentPreview = code => {
const blob = new Blob([code], { type: 'text/html' });
const url = window.URL.createObjectURL(blob);
iframe.src = url;
}
this._element.addEventListener('shown.bs.modal', () => {
if (!this.editorInitialized) {
createEditor({
element: this._element.querySelector('.code-editor'),
value: config.value ?? '',
onchange: code => {
setContentPreview(code)
config.value = code
},
onload: () => {
this._element.querySelector('.spinner').remove();
this.editorInitialized = true
}
});
setContentPreview(config.value ?? '')
}
})
const btnView = this._element.querySelector('.view');
btnView.onclick = () => {
iframe.classList.toggle('position-absolute');
iframe.classList.toggle('h-100');
iframe.classList.toggle('d-none');
};
}
show() {
this.modal.show();
}
hide() {
this.modal.hide();
}
static create(config) {
return config != null ? new CodeEditorModal(config) : null;
}
} |
package Arrays.ArrayAlgorithms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// MAJORITY ELEMENT (N/2, N/3)
public class MooreVoting_Algorithm {
public static int better(int arr[])
{
Map<Integer,Integer> map = new HashMap<>();
for(int i:arr){
map.put(i,map.getOrDefault(i,0)+1);
}
for(int i:map.keySet()){
if(map.get(i)> (arr.length/2))
return i;
}
return -1;
}
/*
Moore Voting Algorithm
1. first traverse the array ;
2. at every iteration , first check if the cnt ==0 , then increase the count by 1 and make
and make current majority element as arr[i] ;
3. At every iteration if arr[i] == current majority element , increase the count by 1 ;
4. else decrease the counter by 1 ;
5.At last make single traversal and check if the count of current majority element is >n/2 times or not.
*/
//(>n/2)
public static int best(int arr[]){
int cnt=0,element = -1;
for(int i:arr){
if(cnt==0){
cnt=1;
element = i;
}
else if(i==element){
cnt++;
}
else
cnt--;
}
cnt=0;
for(int i:arr){
if(i==element)cnt++;
}
if(cnt>(arr.length/2))
return cnt;
return -1;
}
//(>n/3)
/*
1. In here, At max , the array can have only 2 elements which can be appeared more than
N/3 times.
2.
*/
public static List<Integer> best_1(int arr[]){
int cnt1=0,element1 = -1;
int cnt2=0,element2 = -1;
List<Integer>list = new ArrayList<>();
for(int i:arr){
if(cnt1==0 && i!=element2){
cnt1=1;
element1 = i;
}
if(cnt2==0 && i!=element1){
cnt2=1;
element2 = i;
}
else if(i==element1){
cnt1++;
}
else if(i==element2)
cnt2--;
}
cnt1=0;
for(int i:arr){
if(i==element1)cnt1++;
}
if(cnt1>(arr.length/2))
list.add(element1);
if(cnt2>(arr.length/2))
list.add(element2);
return list;
}
public static void main(String args[]){
int arr[] = {1,2,3,3,4,5,5,6,5,4,5,5,2,1};
System.out.println(best(arr));
System.out.print(best_1(arr));
}
} |
<?php declare(strict_types=1);
namespace Shopware\Storefront\Pagelet\Country;
use Shopware\Core\Framework\Log\Package;
use Shopware\Core\Framework\Script\Execution\Awareness\SalesChannelContextAwareTrait;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Storefront\Page\PageLoadedHook;
/**
* Triggered when the CountryStateDataPagelet is loaded
*
* @hook-use-case data_loading
*
* @since 6.4.8.0
*
* @final
*/
#[Package('storefront')]
class CountryStateDataPageletLoadedHook extends PageLoadedHook
{
use SalesChannelContextAwareTrait;
final public const HOOK_NAME = 'country-state-data-pagelet-loaded';
public function __construct(
private readonly CountryStateDataPagelet $pagelet,
SalesChannelContext $context
) {
parent::__construct($context->getContext());
$this->salesChannelContext = $context;
}
public function getName(): string
{
return self::HOOK_NAME;
}
public function getPage(): CountryStateDataPagelet
{
return $this->pagelet;
}
} |
package com.example.aprendendospring.models;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.UUID;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "TB_PRODUCTS")
public class ProductModel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO) //Gera id automaticamente
private UUID idProduct; //Muito usado em sistemas que trabalham com micro serviços e arquitetura distribuida e não corre o risco de possuir IDs iguais
private String name;
private BigDecimal value;
public UUID getIdProduct() {
return idProduct;
}
public void setIdProduct(UUID idProduct) {
this.idProduct = idProduct;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getValue() {
return value;
}
public void setValue(BigDecimal value) {
this.value = value;
}
} |
using ContactsConsoleAPI.Business.Contracts;
using ContactsConsoleAPI.Data.Models;
namespace ContactsConsoleAPI.Business
{
public class Engine : IEngine
{
public async Task Run(IContactManager contactManager)
{
bool exitRequested = false;
while (!exitRequested)
{
Console.WriteLine($"{Environment.NewLine}Choose an option:");
Console.WriteLine("1: Add Contact");
Console.WriteLine("2: Delete Contact");
Console.WriteLine("3: List All Contacts");
Console.WriteLine("4: Update Contact");
Console.WriteLine("5: Find Contact by First name");
Console.WriteLine("6: Find Contact by Last name");
Console.WriteLine("X: Exit");
Console.Write("Enter your choice: ");
string choice = Console.ReadLine();
switch (choice)
{
case "1":
await AddContact(contactManager);
break;
case "2":
await DeleteBook(contactManager);
break;
case "3":
await ListAllBooks(contactManager);
break;
case "4":
await UpdateContact(contactManager);
break;
case "5":
await FindBookByFirstName(contactManager);
break;
case "6":
await FindBookByLastName(contactManager);
break;
case "X":
case "x":
exitRequested = true;
break;
default:
Console.WriteLine("Invalid choice, please try again.");
break;
}
static async Task AddContact(IContactManager contactManager)
{
Console.WriteLine("Adding a new contact:");
Console.Write("Enter FirstName: ");
var firstName = Console.ReadLine();
Console.Write("Enter LastName: ");
var lastName = Console.ReadLine();
Console.Write("Enter Address: ");
var address = Console.ReadLine();
Console.Write("Enter Phone number: ");
var phone = Console.ReadLine();
Console.Write("Enter Email: ");
var email = Console.ReadLine();
Console.Write("Choice Gender: ");
var gender = Console.ReadLine();
Console.Write("Enter ULID: ");
var ulid = Console.ReadLine();
var newContact = new Contact
{
Address = address,
Contact_ULID = ulid,
Email = email,
FirstName = firstName,
LastName = lastName,
Gender = gender,
Phone = phone
};
await contactManager.AddAsync(newContact);
Console.WriteLine("Contact added successfully.");
}
static async Task DeleteBook(IContactManager contactManager)
{
Console.Write("Enter ULID of the contact to delete it: ");
string ulid = Console.ReadLine();
await contactManager.DeleteAsync(ulid);
Console.WriteLine("Contact deleted successfully.");
}
static async Task ListAllBooks(IContactManager contactManager)
{
var contacts = await contactManager.GetAllAsync();
if (contacts.Any())
{
foreach (var contact in contacts)
{
Console.WriteLine($"ULID: {contact.Contact_ULID}, Name: {contact.FirstName} {contact.LastName}, Phone: {contact.Phone}, Email: {contact.Email}");
}
}
else
{
Console.WriteLine("No contacts available.");
}
}
static async Task UpdateContact(IContactManager contactManager)
{
Console.Write("Enter ULID of the contact to update: ");
string ulid = Console.ReadLine();
var contactToUpdate = await contactManager.GetSpecificAsync(ulid);
if (contactToUpdate == null)
{
Console.WriteLine("Contact not found.");
return;
}
// HERE AM I
Console.Write("Enter new First name (leave blank to keep current): ");
var firstName = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(firstName))
{
contactToUpdate.FirstName = firstName;
}
Console.Write("Enter new Last name (leave blank to keep current): ");
var lastName = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(lastName))
{
contactToUpdate.LastName = lastName;
}
Console.Write("Enter new Email (leave blank to keep current): ");
var email = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(email))
{
contactToUpdate.Email = email;
}
Console.Write("Enter new Phone number (leave blank to keep current): ");
var phone = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(phone))
{
contactToUpdate.Phone = phone;
}
Console.Write("Enter new Address (leave blank to keep current): ");
var address = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(address))
{
contactToUpdate.Address = address;
}
Console.Write("Change the gender of the contact (leave blank to keep current): ");
var gender = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(gender))
{
contactToUpdate.Gender = gender;
}
await contactManager.UpdateAsync(contactToUpdate);
Console.WriteLine("Contact updated successfully.");
}
static async Task FindBookByFirstName(IContactManager contactManager)
{
Console.Write("Enter the first name of contact: ");
string firstName = Console.ReadLine();
var contacts = await contactManager.SearchByFirstNameAsync(firstName);
if (contacts.Any())
{
foreach (var contact in contacts)
{
Console.WriteLine();
Console.WriteLine($"First name: {contact.FirstName}, Last name: {contact.LastName}, Gender: {contact.Gender}");
Console.WriteLine($"--Phone: {contact.Phone}, Email: {contact.Email}");
Console.WriteLine($"---Address: {contact.Address}");
}
}
else
{
Console.WriteLine("No contact found with the given first name fragment.");
}
}
static async Task FindBookByLastName(IContactManager contactManager)
{
Console.Write("Enter the last name of contact: ");
string lastName = Console.ReadLine();
var contacts = await contactManager.SearchByLastNameAsync(lastName);
if (contacts.Any())
{
foreach (var contact in contacts)
{
Console.WriteLine();
Console.WriteLine($"First name: {contact.FirstName}, Last name: {contact.LastName}, Gender: {contact.Gender}");
Console.WriteLine($"--Phone: {contact.Phone}, Email: {contact.Email}");
Console.WriteLine($"---Address: {contact.Address}");
}
}
else
{
Console.WriteLine("No contact found with the given last name fragment.");
}
}
}
}
}
} |
// Definition of the antenna-related geometry functions
#include "geometryfunc.h"
#include <isce3/core/Projections.h>
#include <isce3/core/Quaternion.h>
#include <isce3/core/Vector.h>
#include <isce3/except/Error.h>
#include <isce3/geometry/geometry.h>
#include <isce3/math/RootFind1dBracket.h>
// Aliases
using namespace isce3::core;
namespace geom = isce3::geometry;
namespace ant = isce3::antenna;
using VecXd = Eigen::VectorXd;
// Helper local functions
/**
* @internal
* Helper function to get slant range and LLH and convergence flag
* @param[in] el_theta : either elevation or theta angle in radians
* depending on the "frame" object.
* @param[in] az_phi : either azimuth or phi angle in radians depending
* on the "frame" object.
* @param[in] pos_ecef : antenna/spacecraft position in ECEF (m,m,m)
* @param[in] vel_ecef : spacecraft velocity scaled by 2/wavalength in
* ECEF (m/s,m/s,m/s)
* @param[in] quat : isce3 quaternion object for transformation from antenna
* body-fixed to ECEF
* @param[in] dem_interp (optional): isce3 DEMInterpolator object
* w.r.t ellipsoid. Default is zero height.
* @param[in] abs_tol (optional): Abs error/tolerance in height estimation (m)
* between desired input height and final output height. Default is 0.5.
* @param[in] max_iter (optional): Max number of iterations in height
* estimation. Default is 10.
* @param[in] frame (optional): isce3 Frame object to define antenna spherical
* coordinate system. Default is based on "EL_AND_AZ" spherical grid.
* @param[in] ellips (optional): isce3 Ellipsoid object defining the
* ellipsoidal planet. Default is WGS84 ellipsoid.
* @return a tuple of three values : slantrange (m), Doppler (Hz), a bool
* which is true if height tolerance is met, false otherwise.
* @exception InvalidArgument, RuntimeError
*/
static std::tuple<double, double, bool> _get_sr_dop_conv(double el_theta,
double az_phi, const Vec3& pos_ecef, const Vec3& vel_ecef,
const Quaternion& quat, const geom::DEMInterpolator& dem_interp,
double abs_tol, int max_iter, const ant::Frame& frame,
const Ellipsoid& ellips)
{
// pointing sphercial to cartesian in Antenna frame
auto pnt_xyz = frame.sphToCart(el_theta, az_phi);
// pointing from Ant XYZ to global ECEF
auto pnt_ecef = quat.rotate(pnt_xyz);
// get slant range and target position on/above the ellipsoid
Vec3 tg_ecef, tg_llh;
double sr;
auto iter_info = geom::srPosFromLookVecDem(sr, tg_ecef, tg_llh, pos_ecef,
pnt_ecef, dem_interp, abs_tol, max_iter, ellips);
bool convergence {true};
if (iter_info.second > abs_tol)
convergence = false;
double doppler = vel_ecef.dot(pnt_ecef);
return {sr, doppler, convergence};
}
// Antenna to Radar functions
std::tuple<double, double, bool> ant::ant2rgdop(double el_theta, double az_phi,
const Vec3& pos_ecef, const Vec3& vel_ecef, const Quaternion& quat,
double wavelength, const geom::DEMInterpolator& dem_interp,
double abs_tol, int max_iter, const ant::Frame& frame,
const Ellipsoid& ellips)
{
if (!(wavelength > 0.0))
throw isce3::except::InvalidArgument(
ISCE_SRCINFO(), "Bad value for wavelength!");
const auto vel_ecef_cst = (2. / wavelength) * vel_ecef;
return _get_sr_dop_conv(el_theta, az_phi, pos_ecef, vel_ecef_cst, quat,
dem_interp, abs_tol, max_iter, frame, ellips);
}
std::tuple<VecXd, VecXd, bool> ant::ant2rgdop(
const Eigen::Ref<const VecXd>& el_theta, double az_phi,
const Vec3& pos_ecef, const Vec3& vel_ecef, const Quaternion& quat,
double wavelength, const geom::DEMInterpolator& dem_interp,
double abs_tol, int max_iter, const ant::Frame& frame,
const Ellipsoid& ellips)
{
if (wavelength <= 0.0)
throw isce3::except::InvalidArgument(
ISCE_SRCINFO(), "Bad value for wavelength!");
// initialization and vector allocations
const auto vel_ecef_cst = (2. / wavelength) * vel_ecef;
auto ang_size = el_theta.size();
VecXd slantrange(ang_size);
VecXd doppler(ang_size);
bool converge {true};
// FIXME OpenMP work sharing on this loop causes slowdown
// for unknown reasons in conda environment
for (decltype(ang_size) idx = 0; idx < ang_size; ++idx) {
auto [sr, dop, flag] =
_get_sr_dop_conv(el_theta[idx], az_phi, pos_ecef, vel_ecef_cst,
quat, dem_interp, abs_tol, max_iter, frame, ellips);
slantrange(idx) = sr;
doppler(idx) = dop;
if (!flag)
converge = false;
}
return {slantrange, doppler, converge};
}
// Antenna to Geometry
std::tuple<Vec3, bool> ant::ant2geo(double el_theta, double az_phi,
const Vec3& pos_ecef, const Quaternion& quat,
const geom::DEMInterpolator& dem_interp, double abs_tol, int max_iter,
const ant::Frame& frame, const Ellipsoid& ellips)
{
// pointing sphercial to cartesian in Antenna frame
auto pnt_xyz = frame.sphToCart(el_theta, az_phi);
// pointing from Ant XYZ to global ECEF
auto pnt_ecef = quat.rotate(pnt_xyz);
// get slant range and target position on/above the ellipsoid
Vec3 tg_ecef, tg_llh;
double sr;
auto iter_info = geom::srPosFromLookVecDem(sr, tg_ecef, tg_llh, pos_ecef,
pnt_ecef, dem_interp, abs_tol, max_iter, ellips);
bool convergence {true};
if (iter_info.second > abs_tol)
convergence = false;
return {tg_llh, convergence};
}
std::tuple<std::vector<Vec3>, bool> ant::ant2geo(
const Eigen::Ref<const VecXd>& el_theta, double az_phi,
const Vec3& pos_ecef, const Quaternion& quat,
const geom::DEMInterpolator& dem_interp, double abs_tol, int max_iter,
const ant::Frame& frame, const Ellipsoid& ellips)
{
// initialize and allocate vectors
auto ang_size {el_theta.size()};
std::vector<Vec3> tg_llh_vec(ang_size);
bool converge {true};
// FIXME OpenMP work sharing on this loop causes slowdown
// for unknown reasons in conda environment
for (decltype(ang_size) idx = 0; idx < ang_size; ++idx) {
auto [tg_llh, flag] = ant::ant2geo(el_theta(idx), az_phi, pos_ecef,
quat, dem_interp, abs_tol, max_iter, frame, ellips);
if (!flag)
converge = false;
tg_llh_vec[idx] = tg_llh;
}
return {tg_llh_vec, converge};
}
Vec3 ant::rangeAzToXyz(double slant_range, double az, const Vec3& pos_ecef,
const Quaternion& quat, const geom::DEMInterpolator& dem_interp,
double el_min, double el_max, double el_tol, const ant::Frame& frame)
{
// Get ellipsoid associated with DEM.
const auto ellipsoid = makeProjection(dem_interp.epsgCode())->ellipsoid();
// EL defines a 3D position.
const auto el2xyz =
[&](double el) {
const auto line_of_sight_rcs = frame.sphToCart(el, az);
const auto line_of_sight_ecef = quat.rotate(line_of_sight_rcs);
// As of writing, newer compilers (GCC 12.2 and clang 15.0)
// seem to mess this up if Vec3 ctor is omitted (the return
// value is always equal to pos_ecef).
return Vec3(pos_ecef + slant_range * line_of_sight_ecef);
};
// Given a 3D position we can convert to LLH and compare to DEM.
const auto height_error =
[&](double el) {
const auto target = el2xyz(el);
const auto llh = ellipsoid.xyzToLonLat(target);
return llh[2] - dem_interp.interpolateLonLat(llh[0], llh[1]);
};
double el_solution = 0.0;
auto errcode = isce3::math::find_zero_brent(
el_min, el_max, height_error, el_tol, &el_solution);
if (errcode != isce3::error::ErrorCode::Success) {
throw isce3::except::RuntimeError(ISCE_SRCINFO(),
std::string("rangeAzToXyz failed with error (") +
isce3::error::getErrorString(errcode) +
std::string("). Current solution = ") +
std::to_string(el_solution));
}
return el2xyz(el_solution);
} |
"use client";
import { MicroGrantsStrategy, Registry } from "@allo-team/allo-v2-sdk/";
import React, { useState } from "react";
import { MicroGrantsABI } from "@/abi/Microgrants";
import {
EProgressStatus,
ETarget,
TNewApplication,
TProgressStep,
} from "@/app/types";
import { getIPFSClient } from "@/services/ipfs";
import { getChain, wagmiConfigData } from "@/services/wagmi";
import {
ethereumHashRegExp,
extractLogByEventName,
getEventValues,
pollUntilDataIsIndexed,
pollUntilMetadataIsAvailable,
} from "@/utils/common";
import { checkIfRecipientIsIndexedQuery } from "@/utils/query";
import { getProfileById } from "@/utils/request";
import {
TransactionData,
ZERO_ADDRESS,
} from "@allo-team/allo-v2-sdk/dist/Common/types";
import { sendTransaction } from "@wagmi/core";
import { decodeEventLog } from "viem";
import { useAccount } from "wagmi";
import { RegistryABI } from "@/abi/Registry";
export interface IApplicationContextProps {
steps: TProgressStep[];
createApplication: (
data: TNewApplication,
chain: number,
poolId: number
) => Promise<string>;
}
const initialSteps: TProgressStep[] = [
{
id: 'application-0',
content: "Using profile ",
target: "",
href: "",
status: EProgressStatus.IN_PROGRESS,
},
{
id: "application-1",
content: "Saving your application to ",
target: ETarget.IPFS,
href: "",
status: EProgressStatus.NOT_STARTED,
},
{
id: "application-2",
content: "Registering your application on ",
target: ETarget.POOL,
href: "#",
status: EProgressStatus.NOT_STARTED,
},
{
id: "application-3",
content: "Indexing your application on ",
target: ETarget.SPEC,
href: "",
status: EProgressStatus.NOT_STARTED,
},
{
id: "application-4",
content: "Indexing application metadata on ",
target: ETarget.IPFS,
href: "",
status: EProgressStatus.NOT_STARTED,
},
];
export const ApplicationContext = React.createContext<IApplicationContextProps>(
{
steps: [],
createApplication: async () => {
return "";
},
}
);
export const ApplicationContextProvider = (props: {
children: JSX.Element | JSX.Element[];
}) => {
const [steps, setSteps] = useState<TProgressStep[]>(initialSteps);
const { address } = useAccount();
const updateStepTarget = (index: number, target: string) => {
const newSteps = [...steps];
newSteps[index].target = target;
setSteps(newSteps);
};
const updateStepStatus = (index: number, flag: boolean) => {
const newSteps = [...steps];
if (flag) {
newSteps[index].status = EProgressStatus.IS_SUCCESS;
} else {
newSteps[index].status = EProgressStatus.IS_ERROR;
}
if (flag && steps.length > index + 1)
newSteps[index + 1].status = EProgressStatus.IN_PROGRESS;
setSteps(newSteps);
return newSteps;
};
const updateStepHref = (index: number, href: string) => {
const newSteps = [...steps];
newSteps[index].href = href;
setSteps(newSteps);
};
const updateStepContent = (index: number, content: string) => {
const newSteps = [...steps];
newSteps[index].content = content;
setSteps(newSteps);
};
const createApplication = async (
data: TNewApplication,
chain: number,
poolId: number
): Promise<string> => {
// reset steps
steps.map((step, index) => {
if (index == 0) step.status = EProgressStatus.IN_PROGRESS;
else step.status = EProgressStatus.NOT_STARTED;
})
setSteps(steps);
// todo: check for supported chain. Update steps if not supported.
if (chain !== 5) {
// todo: update steps
updateStepStatus(steps.length, false);
updateStepContent(steps.length, "Unsupported chain");
return "0x";
}
const chainInfo: any | unknown = getChain(chain);
const newSteps = [...steps];
newSteps.map((step, index) => {
if (step.target === ETarget.CHAIN) {
updateStepTarget(index, chainInfo.name);
}
});
let stepIndex = 0;
let profileContent = steps[0].content;
let profileTarget = steps[0].target;
// if data.profileName set a new step at index 0 of steps
if (data.profileName) {
profileContent = "Creating new profile ";
profileTarget = data.profileName;
} else {
const profile = await getProfileById({
chainId: chain.toString(),
profileId: data.profileId!.toLowerCase(),
});
profileTarget = profile.name;
}
updateStepContent(stepIndex, profileContent);
updateStepTarget(stepIndex, profileTarget);
updateStepHref(stepIndex, "");
let profileId = data.profileId;
const registry = new Registry({ chain: chain });
// 1. if profileName is set, create profile
if (data.profileName && address) {
const randomNumber = Math.floor(Math.random() * 10000000000);
const txCreateProfile: TransactionData = await registry.createProfile({
nonce: randomNumber,
name: data.profileName,
metadata: {
protocol: BigInt(0),
pointer: "",
},
owner: address,
members: [],
});
try {
const tx = await sendTransaction({
to: txCreateProfile.to as string,
data: txCreateProfile.data,
value: BigInt(txCreateProfile.value),
});
const receipt =
await wagmiConfigData.publicClient.waitForTransactionReceipt({
hash: tx.hash,
});
profileId =
getEventValues(receipt, RegistryABI, "ProfileCreated").profileId ||
"0x";
if (profileId === "0x") {
throw new Error("Profile creation failed");
}
updateStepHref(
stepIndex,
`${chainInfo.blockExplorers.default.url}/tx/` + tx.hash,
);
} catch (e) {
updateStepStatus(stepIndex, false);
console.log("Creating Profile", e);
}
await new Promise((resolve) => setTimeout(resolve, 10000));
}
updateStepStatus(stepIndex, true);
stepIndex++;
// 2. Save metadata to IPFS
const ipfsClient = getIPFSClient();
const metadata = {
name: data.name,
website: data.website,
description: data.description,
email: data.email,
base64Image: data.base64Image,
};
let imagePointer;
let pointer;
try {
if (metadata.base64Image.includes("base64")) {
imagePointer = await ipfsClient.pinJSON({
data: metadata.base64Image,
});
metadata.base64Image = imagePointer.IpfsHash;
}
pointer = await ipfsClient.pinJSON(metadata);
updateStepHref(stepIndex, "https://ipfs.io/ipfs/" + pointer.IpfsHash);
updateStepStatus(stepIndex, true);
} catch (e) {
console.log("IPFS", e);
updateStepStatus(stepIndex, false);
}
stepIndex++;
// 3. Register application to pool
let recipientId;
const strategy = new MicroGrantsStrategy({ chain, poolId });
let anchorAddress: string = ZERO_ADDRESS;
if (ethereumHashRegExp.test(profileId || "")) {
anchorAddress = (
await getProfileById({
chainId: chain.toString(),
profileId: profileId!.toLowerCase(),
})
).anchor;
}
const registerRecipientData = strategy.getRegisterRecipientData({
registryAnchor: anchorAddress as `0x${string}`,
recipientAddress: data.recipientAddress as `0x${string}`,
requestedAmount: data.requestedAmount,
metadata: {
protocol: BigInt(1),
pointer: pointer.IpfsHash,
},
});
try {
const tx = await sendTransaction({
to: registerRecipientData.to as string,
data: registerRecipientData.data,
value: BigInt(registerRecipientData.value),
});
const reciept =
await wagmiConfigData.publicClient.waitForTransactionReceipt({
hash: tx.hash,
});
const { logs } = reciept;
const decodedLogs = logs.map((log) =>
decodeEventLog({ ...log, abi: MicroGrantsABI }),
);
let log = extractLogByEventName(decodedLogs, "Registered");
if (!log) {
log = extractLogByEventName(decodedLogs, "UpdatedRegistration");
}
recipientId = log.args["recipientId"].toLowerCase();
updateStepTarget(
stepIndex,
`${chainInfo.name} at ${tx.hash.slice(0, 6)}`,
);
updateStepHref(
stepIndex,
`${chainInfo.blockExplorers.default.url}/tx/` + tx.hash,
);
updateStepStatus(stepIndex, true);
} catch (e) {
console.log("Registering Application", e);
updateStepStatus(stepIndex, false);
}
stepIndex++;
// 4. Poll indexer for recipientId
const pollingData: any = {
chainId: chain,
poolId: poolId,
recipientId: recipientId.toLowerCase(),
};
const pollingResult: boolean = await pollUntilDataIsIndexed(
checkIfRecipientIsIndexedQuery,
pollingData,
"microGrantRecipient",
);
if (pollingResult) {
updateStepStatus(stepIndex, true);
} else {
console.log("Polling ERROR");
updateStepStatus(stepIndex, false);
}
stepIndex++;
// 5. Index Metadata
const pollingMetadataResult = await pollUntilMetadataIsAvailable(
pointer.IpfsHash,
);
if (pollingMetadataResult) {
updateStepStatus(stepIndex, true);
} else {
console.log("Polling ERROR");
updateStepStatus(stepIndex, false);
}
await new Promise((resolve) => setTimeout(resolve, 3000));
return recipientId;
};
return (
<ApplicationContext.Provider
value={{
steps: steps,
createApplication: createApplication,
}}
>
{props.children}
</ApplicationContext.Provider>
);
}; |
import cv2
import pyautogui
import numpy as np
import keyboard
import os
import time
import torch
import PIL
from torchvision import transforms
class ImageMatcher:
def __init__(self):
self.image_folder = 'C:/Users/Jordan/Desktop/Programming/GIT/PESBot/DATA_/images/templates_folder'
self.templates = []
# Load all images in the folder
for filename in os.listdir(self.image_folder):
if filename.endswith('.PNG') or filename.endswith('.png'):
template = cv2.imread(os.path.join(self.image_folder, filename), cv2.IMREAD_GRAYSCALE)
self.templates.append(template)
def take_screenshot(self, counter, mineral):
# Create the "images" folder if it doesn't exist
image_folder = 'C:/Users/Jordan/Desktop/Programming/GIT/PESBot/DATA_/images/screenshots'
# Get the mouse position
mouse_x, mouse_y = pyautogui.position()
# Calculate the coordinates for the image region around the mouse position
image_x = max(0, mouse_x - 25)
image_y = max(0, mouse_y - 25)
image_width = 50
image_height = 50
# Capture the image region
screenshot = pyautogui.screenshot(region=(image_x, image_y, image_width, image_height))
screenshot.save(os.path.join(image_folder, f'{mineral}{counter}.png'))
@staticmethod
def take_screenshot_at_position(coordinates):
# Get the mouse position
mouse_x, mouse_y = coordinates[0], coordinates[1]
# Calculate the coordinates for the image region around the mouse position
image_x = max(0, int(mouse_x) - 40)
image_y = max(0, int(mouse_y) - 40)
image_width = 80
image_height = 80
temp_image_folder = 'C:/Users/Jordan/Desktop/Programming/GIT/PESBot/DATA_/images/temp_check'
# Capture the image region
screenshot = pyautogui.screenshot(region=(image_x, image_y, image_width, image_height))
screenshot.save(os.path.join(temp_image_folder, 'temp_img.png'))
def match_image(self, coordinates):
# Calculate the coordinates for the image region around the mouse position
ImageMatcher.take_screenshot_at_position(coordinates)
temp_image_folder = 'C:/Users/Jordan/Desktop/Programming/GIT/PESBot/DATA_/images/temp_check'
screenshot = cv2.imread(os.path.join(temp_image_folder, 'temp_img.png'), cv2.IMREAD_GRAYSCALE)
# Perform template matching for each template
try:
for template in self.templates:
result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.80
matches = np.where(result >= threshold)
# Check if there is a match
if len(matches[0]) > 0:
return True
else:
return False
except Exception as e:
print(e)
def match_image_nn_captcha(self, image):
model = torch.load('C:\\Users\\Jordan\\Desktop\\Programming\\GIT\\PESBot\\Python_\\Scripts\\nn\\model.pt')
if torch.cuda.is_available():
model.cuda()
model.eval()
labels = ['1', '2', '3', '4', '5', '6', '7', '8', 'x']
# Perform template matching for each template
try:
transform = transforms.ToTensor()
x = transform(image)
x = x.cuda()
with torch.inference_mode():
output = model(x.unsqueeze(0))
_, index = torch.max(output, 1)
percentage = torch.nn.functional.softmax(output, dim=1)[0] * 100
return (labels[index], percentage[index[0]].item())
except Exception as e:
print(e)
def match_image_nn_mineral(self, image):
model = torch.load('C:\\Users\\Jordan\\Desktop\\Programming\\GIT\\PESBot\\Python_\\Scripts\\nn\\mineral_model.pt')
if torch.cuda.is_available():
model.cuda()
model.eval()
labels = ['mineral', 'not_mineral']
# Perform template matching for each template
try:
transform = transforms.ToTensor()
x = transform(image)
x = x.cuda()
with torch.inference_mode():
output = model(x.unsqueeze(0))
_, index = torch.max(output, 1)
percentage = torch.nn.functional.softmax(output, dim=1)[0] * 100
return (labels[index], percentage[index[0]].item())
except Exception as e:
print(e)
def check_for_captcha(self):
# Calculate the coordinates for the image region around the mouse position
ImageMatcher.take_screenshot_at_position((600, 460))
temp_image_folder = 'C:/Users/Jordan/Desktop/Programming/GIT/PESBot/DATA_/images/temp_check'
screenshot = cv2.imread(os.path.join(temp_image_folder, 'temp_img.png'), cv2.IMREAD_GRAYSCALE)
# Perform template matching for each template
try:
for template in self.templates:
result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.80
matches = np.where(result >= threshold)
# Check if there is a match
if len(matches[0]) > 0:
return True
else:
return False
except Exception as e:
print(e)
# Usage example
"""
matcher = ImageMatcher()
counter=1
mineral = 'coal'
while True:
if keyboard.is_pressed(('a')):
matcher.match_image()
time.sleep(0.25)
elif keyboard.is_pressed('b'):
matcher.take_screenshot(counter, mineral)
counter+=1
time.sleep(0.25)
continue
elif(keyboard.is_pressed('q')):
break
""" |
import React, {useEffect} from 'react'
import {AiOutlineMenu} from 'react-icons/ai'
import {FiShoppingCart} from 'react-icons/fi'
import {BsChatLeft} from 'react-icons/bs'
import {RiNotification3Line} from 'react-icons/ri'
import {MdKeyboardArrowDown} from 'react-icons/md'
import {TooltipComponent} from '@syncfusion/ej2-react-popups'
import avatar from '../data/avatar.jpg'
import { NavButton } from './NavButton'
import {Cart} from './Cart'
import {Chat} from './Chat'
import {Notification} from './Notification'
import {UserProfile} from './UserProfile'
import { useStateContext } from '../contexts/ContextProvider'
export const Navbar = () => {
const { currentColor, activeMenu, setActiveMenu, handleClick, isClicked, setScreenSize, screenSize } = useStateContext()
useEffect(() => {
const handleResize = () => setScreenSize(window.innerWidth)
window.addEventListener('resize', handleResize)
handleResize()
return () => window.removeEventListener('resize', handleResize)
},[])
useEffect(() => {
screenSize <= 900 ? setActiveMenu(false) : setActiveMenu(true)
},[screenSize])
const handleActiveMenu = () => setActiveMenu(!activeMenu)
return (
<div className='flex justify-between p-2 md:ml-6 md:mr-6 relative'>
<NavButton
title='Menu'
customFunc={handleActiveMenu}
color={currentColor}
icon={<AiOutlineMenu />}
/>
<div className="flex">
<NavButton
title='Cart'
customFunc={() => handleClick('cart')}
color={currentColor}
icon={<FiShoppingCart />}
/>
<NavButton
title='Chat'
customFunc={() => handleClick('chat')}
dotColor='#03c9d7'
icon={<BsChatLeft />}
/>
<NavButton
title='Notifications'
customFunc={() => handleClick('notification')}
dotColor='rgb(254, 201, 15)'
icon={<RiNotification3Line />}
/>
<TooltipComponent
content="Profile"
position="BottomCenter"
>
<div
className='flex item-center gap-2 cursor-pointer p-1 hover:bg-light-gray rounded-lg'
onClick={() => handleClick('userProfile')}
>
<img
className='rounded-full w-8 h-8'
src={avatar}
alt='user=profile'
/>
<p>
<span className='text-gray-400 text-14'>Hi,</span>{' '}
<span className='text-gray-400 font-bold ml-1 text-14'>
Zhangsan
</span>
</p>
<MdKeyboardArrowDown className='text-gray-400 text-14' />
</div>
</TooltipComponent>
{isClicked.cart && (<Cart />)}
{isClicked.chat && (<Chat />)}
{isClicked.notification && (<Notification />)}
{isClicked.userProfile && (<UserProfile />)}
</div>
</div>
)
} |
package com.example.tourmanagement.filtration.impl;
import com.example.tourmanagement.exception.LogicException;
import com.example.tourmanagement.filtration.TourFilter;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Optional;
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TourFilterBetweenRequest implements TourFilter {
private String field;
private Object value;
private Object value2;
private Object operation;
@Override
public String getOperation() {
return "between";
}
@Override
public Predicate addPredicate(CriteriaBuilder builder, Path<?> path) {
Method method = ReflectionUtils.findMethod(builder.getClass(), getOperation(), Expression.class, Comparable.class, Comparable.class);
return (Predicate) Optional.ofNullable(method)
.map(m -> ReflectionUtils.invokeMethod(method, builder, path,
value,
value2))
.orElseThrow(() -> new LogicException("Не существует такой операции!"));
}
@Getter
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
private static class TourFilterBetweenRequestHelper {
private String field;
private Object value;
private Object value2;
private String operation;
}
@JsonCreator
private static TourFilterBetweenRequest create(@NonNull TourFilterBetweenRequestHelper helper) {
var request = new TourFilterBetweenRequest();
request.setField(helper.getField());
request.setOperation(helper.getOperation());
request.setValue(request.getField().equals("startDateTime") ? LocalDateTime.parse(helper.getValue().toString()) : helper.getValue());
request.setValue2(request.getField().equals("startDateTime") ? LocalDateTime.parse(helper.getValue2().toString()) : helper.getValue2());
return request;
}
} |
package part02.Exercise3;
public class MovableCircle implements Movable{
private int radius;
private MovablePoint center;
public MovableCircle(int x, int y, int xSpeed, int ySpeed, int radius){
this.radius = radius;
this.center = new MovablePoint(x,y,xSpeed,ySpeed);
}
public int getRadius(){
return radius;
}
public MovablePoint getCenter(){
return center;
}
@Override
public String toString() {
return "Radius: " + getRadius() + ", " + center.toString();
}
@Override
public void moveUp() {
center.moveUp();
}
@Override
public void moveDown() {
center.moveDown();
}
@Override
public void moveRight() {
center.moveRight();
}
@Override
public void moveLeft() {
center.moveLeft();
}
} |
## Refinanciamientos y pago sostenidos
Aplicación para recibir webhooks desde Mambu en los eventos de refinanciamientos y pagos a cuentas de préstamos que permite lo siguiente:
1. Para el evento de refinanciamiento (diagrama https://swimlanes.io/u/MWAfpHJFs):
- Validar la información del préstamo original y del refinanciado usando la API de Loans (https://api.mambu.com/#loan-accounts-getbyid)
- Calcular la cantidad de días de atraso que tenía el préstamo original para asignarlo a un CF del préstamo nuevo.
- Actualizar el préstamo nuevo con la nueva sucursal, días de atraso del préstamo original e inicializar el contador de pagos sostenidos como un CF a través de la API de Loans (https://api.mambu.com/#loan-accounts-patch).
- Realiza el desembolso del nuevo préstamo refinanciado mediante la API de Loans Transactions (https://api.mambu.com/#loan-transactions-makedisbursement).
2. Para el evento de pago (diagrama https://app.diagrams.net/#G1hrLrEzkmLd7K1A42WVpSOzoJ0Dq7KsQH):
- Determina si es un pago al día, mediante la validación del atributo arrears position/situación de pagos atrasados del pago.
- Actualizar el CF contador de pagos sostenidos y cambiar la sucursal del préstamo si se alcanzó la cantidad de pagos sostenidos, a a través de la API de Loans (https://api.mambu.com/#loan-accounts-patch).
## Requisitos mínimos
1. Se deben tener configurados los campos personalizados a nivel de Branch y Loan Accounts descritos en el documento https://docs.google.com/document/d/1ms_1qk897VkY2nv4rVuYLQpCnW0OKtCjaXR-t28dd0Q/edit.
2. Se deben tener configuradas las plantillas de webhook en el tenant de Mambu descritos en el documento https://docs.google.com/document/d/1ms_1qk897VkY2nv4rVuYLQpCnW0OKtCjaXR-t28dd0Q/edit.
## Limitaciones conocidas
1. No se tiene implementado un esquema completo para el manejo de errores.
2. No se tiene implementado el uso de idempotencia.
3. No se tiene implementado un esquema de reintentos en caso de errores.
4. No se tiene implementado ningún esquema de seguridad para validar peticiones entrantes.
5. No se implementó el uso de autenticación básica para las llamadas API de Mambu, solo trabaja con apikeys.
**Nota**: El código no está listo para producción, por lo que antes de intentar usarlo en un entorno productivo, pruébelo minuciosamente.
## Como ejecutar el programa:
1. Descargar el código.
2. Instalar nodejs.
>https://nodejs.org/
3. Instalar los paquetes y modulos requeridos por la aplicación.
>npm -install
4. Modificar el archivo .env con las configuraciones del ambiente requeridas.
- MAMBU_URL= https://demo.sandbox.mambu.com/api
>Instancia de Mambu
- MAMBU_APIKEY=abcdefghjk12345546
>API Key valida de la instancia de un consumer con los permisos necesarios para consultar y editar loans y CFs.
- MAX_PAYMENTS=3
>Parámetro para controlar el valor maximo de pagos sostenidos antes de realizar el cambio de etapa del préstamo.
- PORT=3000
>Puerto en el que se levanta el servidor de nodejs para recibir los webhooks desde Mambu
5. Ejecutar el programa.
>npm run start
6. Generar los eventos de refinanciamiento y pagos desde Mambu para disparar los procesos. Es importante que los campos personalizados necesarios esten configurados en el tenant.
- Ejemplo para disparar el proceso de refinanciamiento a través de curl:
>curl -X POST -H "Content-Type: application/json" -d '{"datetime": "2023-11-16 01:01:53","accountid": "SNSN314","nextbranchkey": "8a44a7748952f662018954f864257c07"}' http://localhost:3000/refinance
- Ejemplo para disparar el proceso de pago sostenido a través de curl:
>curl -X POST -H "Content-Type: application/json" -d '{"datetime": "2023-11-16 01:18:28","accountid": "IWTT427","paycounter": "3","initialbranchkey": "8a444935853413e00185354701e43f79"}' http://localhost:3000/payment
############################################################################################################################################################################################################################
## Refinancing and sustained payments
Application to receive webhooks from Mambu in refinancing events and payments to loan accounts that allows the following:
1. For the refinancing event (sequence diagram https://swimlanes.io/u/MWAfpHJFs):
- Validate original and refinanced loan information using the Loans API (https://api.mambu.com/#loan-accounts-getbyid)
- Calculate the number of days late that the original loan was, to assign it to a CF of the new loan.
- Update the new loan with the new branch, days late of the original loan and initialize the sustained payment counter as a CF through the Loans API (https://api.mambu.com/#loan-accounts-patch).
- Disburse the new refinanced loan using the Loans Transactions API (https://api.mambu.com/#loan-transactions-makedisbursement).
2. For the payment event (sequence diagram https://app.diagrams.net/#G1hrLrEzkmLd7K1A42WVpSOzoJ0Dq7KsQH):
- Determines if it is an up-to-date payment, by validating the arrears position attribute of the payment itself.
- Update the CF sustained payment counter and change the loan branch if the amount of sustained payments was reached, through the Loans API (https://api.mambu.com/#loan-accounts-patch).
## Minimum requirements
1. The custom fields must be configured at the Branch and Loan Accounts level described in the document https://docs.google.com/document/d/1ms_1qk897VkY2nv4rVuYLQpCnW0OKtCjaXR-t28dd0Q/edit.
2. The webhook templates described in the document must be configured in the Mambu tenant https://docs.google.com/document/d/1ms_1qk897VkY2nv4rVuYLQpCnW0OKtCjaXR-t28dd0Q/edit.
## Known limitations
1. There is no complete error handling scheme implemented.
2. The use of idempotency has not been implemented.
3. There is no retry scheme implemented in case of errors.
4. There is no security scheme implemented to validate incoming requests.
5. Using basic authentication for Mambu API calls has not been implemented, it only works with apikeys.
**Note**: The code isn't Production Ready, so before trying to use it in a production environment, please test it thoroughly
## How to run the program:
1. Download the code.
2. Install nodejs.
>https://nodejs.org/
3. Install the packages and modules required by the application.
>npm -install
4. Modify the .env file with the required environment configurations.
- MAMBU_URL= https://demo.sandbox.mambu.com/api
>Mambu tenant
- MAMBU_APIKEY=abcdefghjk12345546
>Valid API Key linked to consumer of the tenant with the necessary permissions to query and edit loans and CFs.
- MAX_PAYMENTS=3
>Parameter to control the maximum value of sustained payments before changing the loan stage.
- PORT=3000
>Using basic authentication for Mambu API calls has not been implemented, it only works with apikeys.
5. Ejecutar el programa.
>npm run start
6. Generate refinancing and payment events from Mambu to trigger the processes. It is important that the necessary custom fields are configured in the tenant.
- Example to trigger the refinancing process through curl:
>curl -X POST -H "Content-Type: application/json" -d '{"datetime": "2023-11-16 01:01:53","accountid": "SNSN314","nextbranchkey": "8a44a7748952f662018954f864257c07"}' http://localhost:3000/refinance
- Example to trigger the sustained payment process through curl:
>curl -X POST -H "Content-Type: application/json" -d '{"datetime": "2023-11-16 01:18:28","accountid": "IWTT427","paycounter": "0","initialbranchkey": "8a444935853413e00185354701e43f79"}' http://localhost:3000/payment |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class HierarchyOfException {
public static void main(String[] args) {
//int result = 7 / 0; //this throws an arithematic exception which is an unchecked exception
// System.out.println(result);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
try{
str=br.readLine();
}
catch(IOException e){ //this throws an ioexceptions which is checked
e.printStackTrace();
}
System.out.println(str);
}
}
//Checked Exceptions are those exceptions that compiler will force you to handle
//Unchecked exceptions are those that compiler will force you to handle weather we want to handle it or not
//to know which exception is checked and which exception is unchecked we have to understand Hierarchy of Exceptions
//whenever there is -able at the end then in java these are interfaces
//Throwable is the only class that runs with able , so throwable extends objects
//Throwable has two class: Exception and Error
//when we check any class where superclass is runtime , so it is unchecked exception
//overall exceptions are checked |
import 'package:flutter/material.dart';
import 'package:movies_app/providers/movies_provider.dart';
import 'package:movies_app/screens/screens.dart';
import 'package:movies_app/theme/app_theme.dart';
import 'package:provider/provider.dart';
void main() => runApp(const AppState());
class AppState extends StatelessWidget {
const AppState({super.key});
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => MoviesProvider(), lazy: false),
// ChangeNotifierProvider(create: (_) => MoviesProvider()),
],
child: const MyApp(),
);
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Movies App',
debugShowCheckedModeBanner: false,
initialRoute: 'home',
routes: {
'home': (_) => const HomeScreen(),
'details': (_) => const DetailsScreen(),
},
theme: AppTheme.lightTheme,
);
}
} |
wd <- Sys.getenv("RWD")
if (!file.exists(wd)) {
stop(paste("O diretorio definido na variavel de ambiente RWD nao foi encontrado",wd, sep="="))
}
setwd(wd)
getwd()
rm(list = ls())
options(scipen=999)
options(width = 1024)
library(utils)
library(tseries)
#install.packages("tseries")
library(tseries)
serie <- read.ts("dados/serie3.txt", header = FALSE, sep = "", skip = 0)
#Análise Exploratória da Série
summary(serie)
# Gráfico da serie
par(mfrow=c(1,1))
ts.plot(serie)
# Teste de Estacionariedade
adf.test(serie)
#Identificação
#Gráfico de Autocorrelação e Autocorrelação Parcial da série
par(mfrow=c(1,2))
acf(serie, main="ACF")
pacf(serie,main="PACF")
#Modelo AR(1)
modelo <- arima(serie, order = c(1,0,0), fixed = c(NA,NA), method = c("ML"))
#Teste de hipótese dos parâmetros
library(lmtest)
coeftest(modelo) #apresenta o modelo e os p-valores
#Retira o intercepto
modelo <- arima(serie, order = c(1,0,0), fixed = c(NA,0), method = c("ML"))
coeftest(modelo) #apresenta o modelo e os p-valores
#Análise de Resíduos
par(mfrow=c(1,2))
acf(residuals(modelo), main="ACF dos Resíduos")
pacf(residuals(modelo), main="PACF dos Resíduos")
# AR(22)
modelo<- arima(serie, order = c(22,0,0),
fixed =
c(NA,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,NA,0), method = c("ML"))
coeftest(modelo)
#Análise de Resíduos
par(mfrow=c(1,2))
acf(residuals(modelo), main="ACF dos Resíduos")
pacf(residuals(modelo), main="PACF dos Resíduos")
# ma(12)
modelo <- arima(serie, order = c(22,0,12),
fixed = c(NA,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,NA,0,0,0,0,0,0,0,0,0,0,0,NA,0), method = c("ML"))
coeftest(modelo) #apresenta o modelo e os p-valores
#Análise de Resíduos
par(mfrow=c(1,2))
acf(residuals(modelo), main="ACF dos Resíduos")
pacf(residuals(modelo), main="PACF dos Resíduos")
#Modelo ARMA(1,22)
modelo<- arima(serie, order = c(1,0,22), fixed = c(NA,0,0,0,0,0,0,0,0,0,0,0,NA,0,0,0,0,0,0,0,0,0,NA,0), method = c("ML")) |
import * as z from "zod";
export const RegisterFormSchema = z.object({
name: z.string().min(2, {
message: "Full name must be at least 3 characters.",
}),
email: z.string().email({
message: "Please enter a valid email address.",
}),
phoneNumber: z.string().min(10, {
message: "Phone number must be at least 10 characters.",
}),
password: z
.string()
.min(8, {
message: "Password must be at least 8 characters.",
})
.regex(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$#!%*.?&])[A-Za-z\d@$.#!%*?&]{8,}$/,
{
message:
"Password must include uppercase and lowercase letters, numbers, and special characters.",
}
),
});
export const LoginFormSchema = z.object({
email: z.string().email({
message: "Please enter a valid email.",
}),
password: z.string().min(8, {
message: "Password must be at least 8 characters.",
}),
});
export const UpdateProfileFormSchema = z.object({
name: z.string().min(2, {
message: "Full name must be at least 3 characters.",
}),
jobTitle: z.string().min(2, {
message: "Job title must be at least 3 characters.",
}),
username: z.string().min(2, {
message: "Username must be at least 3 characters.",
}),
phoneNumber: z.string().min(10, {
message: "Phone number must be at least 10 characters.",
}),
about: z.string().min(10, {
message: "About must be at least 10 characters.",
}),
});
export const CreateCourseFormSchema = z.object({
title: z.string({
required_error: "Course title is required",
}),
description: z
.string({
required_error: "Course description is required",
})
.max(150, { message: "Course description is too long" }),
category: z.string(),
topics: z.array(z.string()),
madeFor: z.array(z.string()),
faqs: z.array(
z.object({
question: z.string(),
answer: z.string(),
})
),
}); |
# L21-04
Let’s first create a node running Nginx by using the imperative way.
## Create the pod
kubectl run mynginx --image=nginx
## Get a list of running pods
kubectl get pods
## Get more info
kubectl get pods -o wide
kubectl describe pod mynginx
## Delete the pod
kubectl delete pod mynginx
## Create a pod running BusyBox
Let’s now create a node running BusyBox, this time attaching bash to our terminal.
kubectl run mybox --image=busybox -it -- /bin/sh
## List the folders and use command
ls
echo -n 'A Secret' | base64
exit
## Cleanup
kubectl delete pod mybox
## Create a pod using the declarative way
Let’s now create a node using a YAML file.
kubectl create -f myapp.yaml
## Get some info
kubectl get pods -o wide
kubectl describe pod myapp-pod
## Attach our terminal
kubectl exec -it myapp-pod -- bash
Print the DBCON environment variable that was set in the YAML file.
echo $DBCON
## Detach from the instance
exit
## Cleanup
kubectl delete -f myapp.yaml |
import { NextApiRequest, NextApiResponse } from "next";
import { initFirebaseAdmin, initFirebase } from "../initFirebase";
import { getUser } from "../userUtils";
const admin = require("firebase-admin");
let db = admin.firestore();
const firebase = require("firebase/app");
initFirebaseAdmin();
initFirebase();
const { Storage } = require('@google-cloud/storage');
// Create envVariables.json to store files in Firebase storage
const envVar = require("../../createEnvVariablesJson");
envVar.createEnvVariablesJson();
var fs = require("fs");
var shortId = require("shortid");
const storage = new Storage({
keyFilename: "/tmp/" + "envVariables.json",
});
let bucketName = process.env.STORAGE_BUCKET;
const uploadImage = async(imageName: string) => {
await storage.bucket(bucketName).upload(imageName, {
public: true,
metadata: {
cacheControl: 'public, max-age=31536000',
},
})
}
const generateImageURL = async(imageName: string) => {
let imageURL = `https://storage.googleapis.com/${bucketName}/${imageName}`
return imageURL;
}
const saveImageToProfile = async(uid: string, imageURL: string) => {
await db
.collection("users")
.doc(uid)
.update({ profileImage: imageURL });
}
export default async function handleSaveProfileImage(req: NextApiRequest, res: NextApiResponse) {
let { uid } = await getUser(req, res);
if (uid === "") {
res.statusCode = 403;
res.end();
return;
}
// get img data
let image = req.body.imageFile;
let b64 = image.split(",")[1];
let mimeType = image.match(/^data:([^;]+);base64,(.*)$/);
let imageType = mimeType[1].split("/")[1];
let imageName = shortId.generate().toString() + "." + imageType;
// create img file locally temporarily
await fs.writeFile("/tmp/" + imageName, b64, {encoding: 'base64'}, function(err: any) {
if (err) {
console.log(err);
} else {
}
});
// upload img file to firebase storage
await uploadImage("/tmp/" + imageName);
// generate public URL for img file to save to firestore
let imageURL = await generateImageURL(imageName);
// save img URL to firestore under relevant profile
await saveImageToProfile(uid, imageURL);
// delete local img
fs.unlinkSync("/tmp/" + imageName);
res.statusCode = 200;
res.send({url: imageURL});
return;
} |
package db
import (
"context"
"order-status-log-service/core/models"
"os"
"github.com/google/uuid"
"github.com/uptrace/bun"
)
type IOrderStatusRepository interface {
Insert(os *models.OrderStatus) (err error)
Update(os *models.OrderStatus) (err error)
Get(orderId uuid.UUID) (orderStatus models.OrderStatus, err error)
}
type OrderStatusRepository struct {
context *bun.DB
}
func NewOrderRepository() IOrderStatusRepository {
return &OrderStatusRepository{
context: NewDB(os.Getenv("DB_URL")),
}
}
func (o *OrderStatusRepository) Insert(os *models.OrderStatus) (err error) {
_, err = o.context.
NewInsert().
Model(os).
Exec(context.Background())
return
}
func (o *OrderStatusRepository) Update(os *models.OrderStatus) (err error) {
_, err = o.context.
NewUpdate().
Model(&os).
Column("Status").
Where("id = ?", os.OrderId).
Exec(context.Background())
return
}
func (o *OrderStatusRepository) Get(order uuid.UUID) (orderStatus models.OrderStatus, err error) {
err = o.context.
NewSelect().
Model(&orderStatus).
Where("id = ? ", order).
Scan(context.Background())
return
} |
package com.knits.assetcare.dto.data.inventory;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.knits.assetcare.dto.data.business.VendorDto;
import com.knits.assetcare.dto.data.common.AbstractAuditableDto;
import com.knits.assetcare.dto.data.location.LocationDto;
import com.knits.assetcare.dto.validation.OnCreate;
import com.knits.assetcare.dto.validation.OnUpdate;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.PositiveOrZero;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
@Data
@NoArgsConstructor
@SuperBuilder(toBuilder = true)
public class AbstractInventoryItemDto extends AbstractAuditableDto {
@NotNull(groups = {OnCreate.class})
@Size(min = 4, max = 50, groups = {OnCreate.class, OnUpdate.class})
private String name;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Size(max = 255, groups = {OnCreate.class, OnUpdate.class})
private String description;
@JsonInclude(JsonInclude.Include.NON_NULL)
@PositiveOrZero(groups = {OnUpdate.class, OnUpdate.class})
private Integer quantity;
@JsonInclude(JsonInclude.Include.NON_NULL)
@PositiveOrZero(groups = {OnUpdate.class, OnUpdate.class})
private BigDecimal price;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Size(min = 6, max = 14, groups = {OnCreate.class, OnUpdate.class})
private String barCode;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Valid
private VendorDto vendor;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Valid
private LocationDto location;
} |
//
// Copyright 2022 The GUAC Authors.
//
// 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 guesser
import (
"testing"
"github.com/guacsec/guac/internal/testing/testdata"
"github.com/guacsec/guac/pkg/handler/processor"
)
func Test_Ite6TypeGuesser(t *testing.T) {
testCases := []struct {
name string
blob []byte
expected processor.DocumentType
}{{
name: "invalid ITE6 Document",
blob: []byte(`{ "abc": "def"}`),
expected: processor.DocumentUnknown,
}, {
name: "valid ITE6 Document",
blob: []byte(`{"_type": "https://in-toto.io/Statement/v0.1"}`),
expected: processor.DocumentITE6Generic,
}, {
name: "valid SLSA ITE6 Document",
blob: []byte(`{"_type": "https://in-toto.io/Statement/v0.1", "predicateType": "https://slsa.dev/provenance/v0.2"}`),
expected: processor.DocumentITE6SLSA,
}, {
name: "valid SLSA ITE6 Document with different versions",
blob: []byte(`{"_type": "https://in-toto.io/Statement/v1.1", "predicateType": "https://slsa.dev/provenance/v1.0"}`),
expected: processor.DocumentITE6SLSA,
}, {
name: "valid CREV ITE6 Document",
blob: testdata.ITE6CREVExample,
expected: processor.DocumentITE6Generic,
}, {
name: "valid Runtime ITE6 Document",
blob: testdata.ITE6ReviewExample,
expected: processor.DocumentITE6Generic,
}, {
name: "valid Vuln ITE6 Document",
blob: testdata.ITE6VulnExample,
expected: processor.DocumentITE6Vul,
}}
for _, tt := range testCases {
t.Run(tt.name, func(t *testing.T) {
guesser := &ite6TypeGuesser{}
f := guesser.GuessDocumentType(tt.blob, processor.FormatJSON)
if f != tt.expected {
t.Errorf("got the wrong format, got %v, expected %v", f, tt.expected)
}
})
}
} |
# Project 3
Nitu Girish Mohan
In this project, I will be looking at the Gradient Boosting Algorithm, testing the Boosted Locally Weighted Regressor on different datasets/kernels, and using complete KFold cross validations to compare with other regressors.
## Gradient Boosting
Let's start by discussing Gradient Boosting, a boosting technique in machine learning that operates on the principle of minimizing the total prediction error by combining the best possible subsequent model with the previous models. The crucial aspect is to establish target outcomes for the next model to minimize the error. This approach generates a predictive model composed of a collection of weak prediction models, usually decision trees. When a decision tree functions as the weak learner, the resulting algorithm is known as gradient-boosted trees, and it frequently outperforms random forest (which we'll demonstrate later in the code).
Assume you have an regressor F and, for the observation x_i we make the prediction F(x_i). To improve the predictions, we can regard F as a 'weak learner' and therefore train a decision tree (we can call it h) where the new output is y_i-F(x_i). So, the new predictor is trained on the residuals of the previous one. Thus, there are increased chances that the new regressor
<img src="largeF.png" class="LR" alt="">
is better than the old one, F.
Main task: implement this idea in an algorithm and test it on real data sets.
The algorithm follows the order of the structure below:
<img src="GBDiagram.png" class="LR" alt="">
Importing necessary libraries
```python
# computational libraries
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.preprocessing import StandardScaler, QuantileTransformer, MinMaxScaler, PolynomialFeatures
from sklearn.decomposition import PCA
from scipy.spatial import Delaunay
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
import scipy.stats as stats
from sklearn.model_selection import train_test_split as tts, KFold, GridSearchCV
from sklearn.metrics import mean_squared_error as mse
from scipy.interpolate import interp1d, RegularGridInterpolator, griddata, LinearNDInterpolator, NearestNDInterpolator
from math import ceil
from scipy import linalg
from scipy.linalg import lstsq
# the following line(s) are necessary if you want to make SKlearn compliant functions
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
import xgboost as xgb
scale = StandardScaler()
```
To implement the Gradient Boosting algorithm with user defined choices for Regressor_1 and Regressor_2 we will do the following. First we'll start with the boosted regressor implementation from class.
```python
def boosted_lwr(x, y, xnew, f=1/3,iter=2,intercept=True):
# we need decision trees
# for training the boosted method we use x and y
model1 = Lowess_AG_MD(f=f,iter=iter,intercept=intercept) # we need this for training the Decision Tree
model1.fit(x,y)
residuals1 = y - model1.predict(x)
model2 = Lowess_AG_MD(f=f,iter=iter,intercept=intercept)
#model2 = RandomForestRegressor(n_estimators=200,max_depth=9)
model2.fit(x,residuals1)
output = model1.predict(xnew) + model2.predict(xnew)
return output
```
We will now change it slightly to take user-defined choices for each of the regressors for model1 and model2.
```python
def user_boosted_lwr(x, y, xnew, f=1/3, iter=2, intercept=True, model1_type="Lowess_AG_MD", model2_type="Lowess_AG_MD"):
# Define the first model
if model1_type == "Lowess_AG_MD":
model1 = Lowess_AG_MD(f=f, iter=iter, intercept=intercept)
elif model1_type == "RandomForestRegressor":
model1 = RandomForestRegressor(n_estimators=200,max_depth=5)
else:
raise ValueError("please choose 'Lowess_AG_MD' or 'RandomForestRegressor'.")
model1.fit(x, y)
residuals1 = y - model1.predict(x)
# Define the second model
if model2_type == "Lowess_AG_MD":
model2 = Lowess_AG_MD(f=f, iter=iter, intercept=intercept)
elif model2_type == "RandomForestRegressor":
model2 = RandomForestRegressor(n_estimators=200,max_depth=5)
else:
raise ValueError("please choose 'Lowess_AG_MD' or 'RandomForestRegressor'.")
model2.fit(x, residuals1)
output = model1.predict(xnew) + model2.predict(xnew)
return output
```
To demonstrate, we will look at it using the concrete dataset (using the distance function, kernels, and Lowess_AG_MD defined in class) :
```python
data = pd.read_csv('/content/drive/MyDrive/22 23 - Junior Yr/Adv Applied Machine Learning/1. Preliminaries, Intro to Locally Weighted Regression/concrete.csv')
data
x = data.loc[:,'cement':'age'].values
y = data['strength'].values
xtrain, xtest, ytrain, ytest = tts(x,y,test_size=0.3,shuffle=True,random_state=123)
yhat = user_boosted_lwr(xtrain, ytrain, xtest,f=25/len(xtrain),iter=1,intercept=True, model1_type="Lowess_AG_MD", model2_type="Lowess_AG_MD")
mse(ytest,yhat)
```
57.73151261936397
I will now try it with the RandomForestRegressor.
```python
yhat = user_boosted_lwr(xtrain, ytrain, xtest,f=25/len(xtrain),iter=1,intercept=True, model1_type="Lowess_AG_MD", model2_type="RandomForestRegressor")
mse(ytest,yhat)
```
42.90724190818058
## Boosted Locally Weighted Regressor Testing with K-Fold Crossvalidations
I will now test the Boosted Locally Weighted Regressor with different choices of data (such as "cars.csv", "concrete.csv" and "housing.csv") and different choice of kernels, such as Gaussian, Tricubic, Epanechnikov and Quartic.
These are the datasets I will use:
```python
# load in the datasets
housing = pd.read_csv('/content/drive/MyDrive/22 23 - Junior Yr/Adv Applied Machine Learning/4. Variable Selection, Feature Engineering and Neural Networks/housing.csv')
concrete = pd.read_csv('/content/drive/MyDrive/22 23 - Junior Yr/Adv Applied Machine Learning/1. Preliminaries, Intro to Locally Weighted Regression/concrete.csv')
```
For this project, I will be looking at kernel options of tricubic, quartic, and Epanechnikov.
```python
# Tricubic Kernel
def Tricubic(x):
if len(x.shape) == 1:
x = x.reshape(-1,1)
d = np.sqrt(np.sum(x**2,axis=1))
return np.where(d>1,0,70/81*(1-d**3)**3)
# Quartic Kernel
def Quartic(x):
if len(x.shape) == 1:
x = x.reshape(-1,1)
d = np.sqrt(np.sum(x**2,axis=1))
return np.where(d>1,0,15/16*(1-d**2)**2)
# Epanechnikov Kernel
def Epanechnikov(x):
if len(x.shape) == 1:
x = x.reshape(-1,1)
d = np.sqrt(np.sum(x**2,axis=1))
return np.where(d>1,0,3/4*(1-d**2))
```
This is the regressor and boosted regressor I will be comparing (adapted from class notebooks):
```python
#Defining the kernel local regression model
def lw_reg(X, y, xnew, kern, tau, intercept):
# tau is called bandwidth K((x-x[i])/(2*tau))
n = len(X) # the number of observations
yest = np.zeros(n)
if len(y.shape)==1: # here we make column vectors
y = y.reshape(-1,1)
if len(X.shape)==1:
X = X.reshape(-1,1)
if intercept:
X1 = np.column_stack([np.ones((len(X),1)),X])
else:
X1 = X
w = np.array([kern((X - X[i])/(2*tau)) for i in range(n)]) # here we compute n vectors of weights
#Looping through all X-points
for i in range(n):
W = np.diag(w[:,i])
b = np.transpose(X1).dot(W).dot(y)
A = np.transpose(X1).dot(W).dot(X1)
#A = A + 0.001*np.eye(X1.shape[1]) # if we want L2 regularization
#theta = linalg.solve(A, b) # A*theta = b
beta, res, rnk, s = lstsq(A, b)
yest[i] = np.dot(X1[i],beta)
if X.shape[1]==1:
f = interp1d(X.flatten(),yest,fill_value='extrapolate')
else:
f = LinearNDInterpolator(X, yest)
output = f(xnew) # the output may have NaN's where the data points from xnew are outside the convex hull of X
if sum(np.isnan(output))>0:
g = NearestNDInterpolator(X,y.ravel())
# output[np.isnan(output)] = g(X[np.isnan(output)])
output[np.isnan(output)] = g(xnew[np.isnan(output)])
return output
```
```python
def boosted_lwr(X, y, xnew, kern, tau, intercept):
model1 = lw_reg(X,y,X,kern,tau,intercept) # we need this for training the Decision Tree
residuals = y - model1
model2 = RandomForestRegressor(n_estimators=100,max_depth=2)
model2.fit(X,residuals)
output = model2.predict(xnew) + lw_reg(X,y,xnew,kern,tau,intercept)
return output
```
Let's first try it with the concrete data with the Epanechnikov kernel.
```python
x = concrete.loc[:,'cement':'age'].values
y = concrete['strength'].values
```
```python
mse_lwr = []
mse_boosted_lwr = []
kf = KFold(n_splits=10,shuffle=True,random_state = 310)
for idxtrain, idxtest in kf.split(X):
xtrain = X[idxtrain]
ytrain = y[idxtrain]
ytest = y[idxtest]
xtest = X[idxtest]
xtrain = scale.fit_transform(xtrain)
xtest = scale.transform(xtest)
yhat_lwr = lw_reg(xtrain,ytrain, xtest,Epanechnikov,tau=0.9,intercept=True)
yhat_blwr = boosted_lwr(xtrain,ytrain, xtest,Epanechnikov,tau=0.9,intercept=True)
mse_lwr.append(mse(ytest,yhat_lwr))
mse_boosted_lwr.append(mse(ytest,yhat_blwr))
print('The Cross-validated MSE for lw_reg is : '+str(np.mean(mse_lwr)))
print('The Cross-validated MSE for boosted_lw_reg is : '+str(np.mean(mse_boosted_lwr)))
```
The Cross-validated MSE for lw_reg is : 261.9172057655939
The Cross-validated MSE for boosted_lw_reg is : 254.10545711938212
Now lets try it with a Tricubic kernel.
```python
mse_lwr = []
mse_boosted_lwr = []
kf = KFold(n_splits=10,shuffle=True,random_state = 310)
scale = StandardScaler()
for idxtrain, idxtest in kf.split(X):
xtrain = X[idxtrain]
ytrain = y[idxtrain]
ytest = y[idxtest]
xtest = X[idxtest]
xtrain = scale.fit_transform(xtrain)
xtest = scale.transform(xtest)
yhat_lwr = lw_reg(xtrain,ytrain, xtest,Tricubic,tau=0.9,intercept=True)
yhat_blwr = boosted_lwr(xtrain,ytrain, xtest,Tricubic,tau=0.9,intercept=True)
mse_lwr.append(mse(ytest,yhat_lwr))
mse_boosted_lwr.append(mse(ytest,yhat_blwr))
print('The Cross-validated MSE for lw_reg is : '+str(np.mean(mse_lwr)))
print('The Cross-validated MSE for boosted_lw_reg is : '+str(np.mean(mse_boosted_lwr)))
```
The Cross-validated MSE for lw_reg is : 261.6978107579365
The Cross-validated MSE for boosted_lw_reg is : 255.78521768269502
Next, let's try it with the housing data with the Epanechnikov kernel.
```python
X = housing[['lstat', 'rooms', 'distance']].values
y = housing['cmedv'].values
```
```python
mse_lwr = []
mse_boosted_lwr = []
kf = KFold(n_splits=10,shuffle=True,random_state = 310)
for idxtrain, idxtest in kf.split(X):
xtrain = X[idxtrain]
ytrain = y[idxtrain]
ytest = y[idxtest]
xtest = X[idxtest]
xtrain = scale.fit_transform(xtrain)
xtest = scale.transform(xtest)
yhat_lwr = lw_reg(xtrain,ytrain, xtest,Epanechnikov,tau=0.9,intercept=True)
yhat_blwr = boosted_lwr(xtrain,ytrain, xtest,Epanechnikov,tau=0.9,intercept=True)
mse_lwr.append(mse(ytest,yhat_lwr))
mse_boosted_lwr.append(mse(ytest,yhat_blwr))
print('The Cross-validated MSE for lw_reg is : '+str(np.mean(mse_lwr)))
print('The Cross-validated MSE for boosted_lw_reg is : '+str(np.mean(mse_boosted_lwr)))
```
The Cross-validated MSE for lw_reg is : 23.03885019369726
The Cross-validated MSE for boosted_lw_reg is : 21.79843470960379
Now lets try it with a Quartic kernel.
```python
mse_lwr = []
mse_boosted_lwr = []
kf = KFold(n_splits=10,shuffle=True,random_state = 310)
scale = StandardScaler()
for idxtrain, idxtest in kf.split(X):
xtrain = X[idxtrain]
ytrain = y[idxtrain]
ytest = y[idxtest]
xtest = X[idxtest]
xtrain = scale.fit_transform(xtrain)
xtest = scale.transform(xtest)
yhat_lwr = lw_reg(xtrain,ytrain, xtest,Quartic,tau=0.9,intercept=True)
yhat_blwr = boosted_lwr(xtrain,ytrain, xtest,Quartic,tau=0.9,intercept=True)
mse_lwr.append(mse(ytest,yhat_lwr))
mse_boosted_lwr.append(mse(ytest,yhat_blwr))
print('The Cross-validated MSE for lw_reg is : '+str(np.mean(mse_lwr)))
print('The Cross-validated MSE for boosted_lw_reg is : '+str(np.mean(mse_boosted_lwr)))
```
The Cross-validated MSEfor lw_reg is : 22.723935874668843
The Cross-validated MSE for boosted_lw_reg is : 21.254084109129884
Let's also compare this one with RandomForest.
```python
mse_lwr = []
mse_boosted_lwr = []
mse_rf = []
kf = KFold(n_splits=10,shuffle=True,random_state = 310)
scale = StandardScaler()
for idxtrain, idxtest in kf.split(X):
xtrain = X[idxtrain]
ytrain = y[idxtrain]
ytest = y[idxtest]
xtest = X[idxtest]
xtrain = scale.fit_transform(xtrain)
xtest = scale.transform(xtest)
yhat_lwr = lw_reg(xtrain,ytrain, xtest,Quartic,tau=0.9,intercept=True)
yhat_blwr = boosted_lwr(xtrain,ytrain, xtest,Quartic,tau=0.9,intercept=True)
model_rf = RandomForestRegressor(n_estimators=100,max_depth=3)
model_rf.fit(xtrain,ytrain)
yhat_rf = model_rf.predict(xtest)
mse_lwr.append(mse(ytest,yhat_lwr))
mse_boosted_lwr.append(mse(ytest,yhat_blwr))
print('The Cross-validated MSE for lw_reg is : '+str(np.mean(mse_lwr)))
print('The Cross-validated MSE for boosted_lw_reg is : '+str(np.mean(mse_boosted_lwr)))
print('The Cross-validated MSE for RandomForest is : '+str(np.mean(mse_rf)))
```
The Cross-validated MSE for lw_reg is : 22.723935874668843
The Cross-validated MSE for boosted_lw_reg is : 20.938354282358254
The Cross-validated MSE for RandomForest is :16.376944002440666
# References:
1. https://www.displayr.com/gradient-boosting-the-coolest-kid-on-the-machine-learning-block/
2. https://en.wikipedia.org/wiki/Gradient_boosting
3. Class Notebooks |
import 'package:contacts_hive/models/contact_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../cubit/contact_cubit.dart';
class EditContactScreen extends StatefulWidget {
const EditContactScreen({
super.key,
required this.contact,
required this.index,
});
final ContactModel contact;
final int index;
@override
State<EditContactScreen> createState() => _EditContactScreenState();
}
class _EditContactScreenState extends State<EditContactScreen> {
String? name, phone;
@override
Widget build(BuildContext context) {
var cubit = BlocProvider.of<ContactCubit>(context);
return Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: const Icon(
Icons.check,
size: 36,
),
onPressed: () {
ContactModel contact = ContactModel(
name: cubit.nameController.text,
phone: cubit.phoneController.text,
);
cubit.editContact(
contact: contact,
index: widget.index,
);
cubit.getContacts();
Navigator.pop(context);
},
),
],
),
body: Padding(
padding: const EdgeInsets.all(35.0),
child: Column(
children: [
TextFormField(
controller: cubit.nameController..text = widget.contact.name,
//initialValue: widget.contact.name,
onChanged: (value) {
if (value.isEmpty) {
name = value;
// cubit.nameController.text = value;
} else {
name = widget.contact.name;
}
},
decoration: const InputDecoration(
label: Text(
'Name',
),
hintText: 'Enter Name',
),
),
TextFormField(
controller: cubit.phoneController..text = widget.contact.phone,
decoration: const InputDecoration(
label: Text(
'phone',
),
hintText: 'Enter phone',
),
),
const SizedBox(
height: 20.0,
),
],
),
),
);
}
} |
/**
* @jest-environment jsdom
*/
import { verify } from 'approvals/lib/Providers/Jest/JestApprovals';
import moment from 'moment';
import { Options } from 'approvals/lib/Core/Options';
import { Query } from '../../../src/Query/Query';
window.moment = moment;
/**
* Save an instructions block to disc, so that it can be embedded in
* to documentation, using a 'snippet' line.
* @todo Figure out how to include the '```tasks' and '```' lines:
* see discussion in https://github.com/SimonCropp/MarkdownSnippets/issues/537
* @param instructions
* @param options
*/
function verifyQuery(instructions: string, options?: Options): void {
options = options || new Options();
options = options.forFile().withFileExtention('query.text');
verify(instructions, options);
}
/**
* Save an explanation of the instructions block to disk, so that it can be
* embedded in to documentation, using a 'snippet' line.
* @param instructions
* @param options
*/
function verifyExplanation(instructions: string, options?: Options): void {
const query = new Query({ source: instructions });
const explanation = query.explainQuery();
expect(query.error).toBeUndefined();
options = options || new Options();
options = options.forFile().withFileExtention('explanation.text');
verify(explanation, options);
}
describe('explain', () => {
beforeAll(() => {
jest.useFakeTimers();
jest.setSystemTime(new Date(2022, 9, 21)); // 2022-10-21
});
afterAll(() => {
jest.useRealTimers();
});
it('expands dates', () => {
// Arrange
const instructions: string = `
starts after 2 years ago
scheduled after 1 week ago
due before tomorrow
explain`;
// Act, Assert
verifyQuery(instructions);
verifyExplanation(instructions);
});
it('boolean combinations', () => {
// Arrange
const instructions: string = `
explain
not done
(due before tomorrow) AND (is recurring)`;
// Act, Assert
verifyQuery(instructions);
verifyExplanation(instructions);
});
it('nested boolean combinations', () => {
// Arrange
const instructions: string = `
explain
( (description includes 1) AND (description includes 2) AND (description includes 3) ) OR ( (description includes 5) AND (description includes 6) AND (description includes 7) ) AND NOT (description includes 7)`;
// Act, Assert
verifyQuery(instructions);
verifyExplanation(instructions);
});
}); |
import React from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import App from "./App";
import { TodoListProps } from "./components/TodoList";
jest.mock("./components/TodoList", () => ({
TodoList: ({
deleteItemFromList,
updateItemFromList,
item,
}: TodoListProps) => {
return (
<div>
<div>{item.name}</div>
<button
data-testid="editItem"
onClick={() => updateItemFromList({ ...item, name: "lorem ipsum" })}
>
EditTodoList
</button>
<button
data-testid="deleteItem"
onClick={() => deleteItemFromList(item.id)}
>
DeleteTodoList
</button>
</div>
);
},
}));
describe("render App component", () => {
it("Should render input and button", () => {
render(<App />);
const headingElement = screen.getByTestId("heading");
const inputText = screen.getByTestId("input-text");
const btnAdd = screen.getByTestId("btn-add");
expect(headingElement).toBeInTheDocument();
expect(inputText).toBeInTheDocument();
expect(btnAdd).toBeInTheDocument();
expect(btnAdd).toBeDisabled();
});
it("Should add an item to the list", async () => {
render(<App />);
const inputText = screen.getByTestId("input-text");
const btnAdd = screen.getByTestId("btn-add");
expect(inputText).toBeInTheDocument();
expect(btnAdd).toBeInTheDocument();
expect(btnAdd).toBeDisabled();
fireEvent.change(inputText, { target: { value: "New" } });
expect(btnAdd).not.toBeDisabled();
fireEvent.click(btnAdd);
expect(screen.getByText("New")).toBeInTheDocument();
});
it("Should edit an item from the list", async () => {
render(<App />);
const editItem = screen.getByTestId("editItem");
fireEvent.click(editItem);
expect(screen.getByText("lorem ipsum")).toBeInTheDocument();
});
it("Should delete an item from the list", async () => {
render(<App />);
const deleteItem = screen.getByTestId("deleteItem");
fireEvent.click(deleteItem);
expect(screen.queryByText("lorem ipsum")).not.toBeInTheDocument();
});
it("Should delete entire list", async () => {
render(<App />);
const inputText = screen.getByTestId("input-text");
const btnAdd = screen.getByTestId("btn-add");
expect(inputText).toBeInTheDocument();
expect(btnAdd).toBeInTheDocument();
expect(btnAdd).toBeDisabled();
fireEvent.change(inputText, { target: { value: "New" } });
expect(btnAdd).not.toBeDisabled();
fireEvent.click(btnAdd);
const btnDeleteAll = screen.getByTestId("btn-deleteAll");
fireEvent.click(btnDeleteAll);
expect(screen.getByTestId("initial-msg")).toBeInTheDocument();
});
}); |
<template>
<div class="main-container">
<div class="form-title">
<md-icon class="form-title-icon">assessment</md-icon>
<span class="form-title-text">财务中心</span>
</div>
<div class="sub-container">
<div class="balance-container">
<div class="balance-main-container">
<span class="balance-label">可用余额</span>
<span class="balance-symbol">¥</span>
<span class="balance-text">{{balance}}</span>
</div>
<md-button class="deposit-button" @click="active = true">提现</md-button>
</div>
<div class="table-container">
<div class="table-selector">
<el-date-picker
v-model="time"
type="daterange"
align="right"
unlink-panels
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
:picker-options="pickerOptions"
class="date-picker">
</el-date-picker>
<md-radio class="md-primary type-radio" v-model="radio" value="out">支出</md-radio>
<md-radio class="md-primary type-radio" v-model="radio" value="in">收入</md-radio>
<md-radio class="md-primary type-radio" v-model="radio" value="all">全部</md-radio>
</div>
<div class="table-main">
<el-table
:data="tableData"
stripe
style="width: 100%">
<el-table-column
prop="date"
label="日期"
width="180">
</el-table-column>
<el-table-column
prop="type"
label="类型"
width="180">
</el-table-column>
<el-table-column
prop="amount"
label="金额">
</el-table-column>
<el-table-column
prop="sum"
label="余额">
</el-table-column>
</el-table>
</div>
</div>
</div>
<md-dialog :md-active="active">
<md-dialog-title>提现</md-dialog-title>
<md-dialog-content>
<md-field :class="{'md-invalid':inputWrong}">
<label>提现金额</label>
<md-input v-model="depositNum" type="number" min="0" :max="balance" @blur="checkDeposit"></md-input>
<span class="md-error">提现金额不可大于余额</span>
</md-field>
</md-dialog-content>
<md-dialog-actions>
<md-button @click="cancelDeposit">取消</md-button>
<md-button @click="confirmDeposit">确认</md-button>
</md-dialog-actions>
</md-dialog>
</div>
</template>
<script>
export default {
name: "shop-data",
data() {
return {
pickerOptions: {
shortcuts: [{
text: '最近一周',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近一个月',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近三个月',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
picker.$emit('pick', [start, end]);
}
}]
},
time: '',
radio: 'all',
tableData: [],
balance: 0.0,
active: false,
depositNum: '',
inputWrong: false
}
},
methods: {
initAccount: function () {
this.$ajax.get('/shop/'+this.$store.getters.identifyCode).then((response) => {
let data = response.data;
if(data.code === 0){
this.balance = data.data.balance;
}
})
},
initFinance: function () {
this.$ajax.get('/shop/finance/list', {
params: {
identifyCode: this.$store.getters.identifyCode
}
}).then((response) => {
let data = response.data;
if (data.code === 0){
this.tableData = data.data;
}
})
},
confirmDeposit: function () {
if (this.balance >= this.depositNum*1.0){
this.active = false;
this.$ajax.post('/shop/deposit', this.qs.stringify({
identifyCode: this.$store.getters.identifyCode,
amount: this.depositNum*1.0
})).then((response) => {
let data = response.data;
if (data.code === 0){
this.balance = this.balance - this.depositNum*1.0;
this.depositNum = '';
}
})
}
},
cancelDeposit: function () {
this.active = false;
this.depositNum = '';
},
checkDeposit: function () {
if (this.balance < this.depositNum*1.0){
this.inputWrong = true;
} else {
this.inputWrong = false;
}
}
},
created() {
this.initAccount();
this.initFinance();
}
}
</script>
<style lang="stylus" scoped>
.main-container
width 70%
height 100%
margin 0 auto
background-color white
padding 36px
text-align left
.form-title-text
font-weight bold
font-size 20px
text-align left
margin-left 15px
.form-title-icon
font-size 34px !important
.sub-container
width 70%
margin 0 auto
padding-top 50px
.balance-container
width 100%
height 100px
display flex
align-items center
box-shadow 0 3px 1px -2px rgba(0,0,0,.2), 0 2px 2px 0 rgba(0,0,0,.14), 0 1px 5px 0 rgba(0,0,0,.12)
.balance-main-container
width 70%
height 60%
text-align right
float left
line-height 60px
vertical-align center
padding-right 40px
border-right solid 1px #e6e6e6
margin-right 40px
.balance-label
font-size 13px
.balance-symbol
color darkorange
font-size 18px
.balance-text
font-size 35px
color darkorange
.deposit-button
background-color #C9A990
color white !important
.table-container
margin-top 30px
.time-picker
float left
.type-radio
float right
.table-main
padding-top 40px
</style> |
**Crafting the Perfect Pitch: The Art of Persuasion in Sales**
Dive into the intricate world of sales pitches with this detailed guide. Crafting an impactful and persuasive pitch is more than just presenting a product; it's about connecting with your audience and addressing their unique needs. This lesson will take you through the steps of creating a compelling pitch, adapting to various client scenarios, and ensuring your message resonates.
**Table of Contents:**
1. **Introduction to Crafting a Pitch:**
- What is a Sales Pitch?
- The Significance of a Well-Crafted Pitch
2. **Components of a Winning Sales Pitch:**
- Starting with a Strong Hook
- Addressing Pain Points and Offering Solutions
- Demonstrating Value and Benefits
- Including Testimonials and Case Studies
3. **Adapting Your Pitch to Different Scenarios:**
- **In-Person Pitches:** Engaging a Live Audience
- **Cold Calls:** Making an Impact in a Short Time
- **Email Pitches:** Crafting Concise and Catchy Content
- **Webinars and Online Demos:** Using Technology to Your Advantage
4. **The Psychology Behind a Successful Pitch:**
- Building Trust and Credibility
- Emotional Triggers and Storytelling in Sales
- Addressing Objections Proactively
5. **Practice Makes Perfect: Roleplaying and Feedback:**
- Conducting Mock Pitches for Feedback
- Iterating and Improving Your Pitch
6. **Using Technology to Enhance Your Pitch:**
- Presentation Tools and Software
- Analytics: Understanding Audience Engagement
7. **Conclusion and Further Development:**
- Recap of Crafting the Perfect Pitch
- Resources and Courses for Continued Growth |
/**
* $Id: writeabletoxml.h 680 2014-09-10 12:15:43Z klugeflo $
* @file writeabletoxml.h
* @brief Abstract class for serialising objects to XML
* @author Florian Kluge <kluge@informatik.uni-augsburg.de>
*/
#ifndef CORE_WRITEABLETOXML_H
#define CORE_WRITEABLETOXML_H 1
#include <string>
#include <libxml/xmlwriter.h>
#include <xmlio/xmlutils.h> // include for convenience - needed only in cpp
namespace tmssim {
/**
* @brief Generic abstract class for serialising objects to XML.
*
* This class defines an interface that you should implement if you
* want your classes to be serialisable to XML.
*/
class WriteableToXML {
public:
/**
* D'tor
*/
virtual ~WriteableToXML();
/**
* @brief This method manages writing an object to XML.
*
* Call this method to write your object to an XML file.
* @param writer Pointer to the xmlTextWriter that sould be used
* for serialisation
* @return
*/
int writeToXML(xmlTextWriterPtr writer);
/**
* @brief Get the class's XML element name.
*
* Overwrite this method in any subclass you want to be able to
* serialise to XML.
* @return The class's XML element name.
*/
virtual const std::string& getClassElement() = 0;
/**
* @brief Write the element's data to XML.
*
* Implement this function in any subclass you want to serialise.
* The implementation must only write the subclass' data to XML,
* superclass data is written by additionally calling the
* the superclass's writeData method. Do this before you write any other
* data to XML! Make sure you do this in any
* class not directly derived from WritableToXML.
* @param writer Pointer to the xmlTextWriter that sould be used
* for serialisation
* @return
*/
virtual int writeData(xmlTextWriterPtr writer) = 0;
};
} // NS tmssim
#endif // !CORE_WRITEABLETOXML_H |
import { Item } from "../models/item.model";
import { useItemStore } from "../store/useStore";
interface Props {
data: Item[];
}
const Card: React.FC<Props> = ({ data: items }) => {
const addItem = useItemStore(state => state.addItem);
const addItemToCart = (item: Item) => {
addItem(item);
};
return (
<div className="overflow-auto relative my-5 ml-5">
<div className="h-[80vh] grid grid-cols-cards justify-around gap-y-4">
{items && items.map((item, i) => (
<div
key={item.id}
className="relative p-5 m-1 cursor-pointer border border-[#F5F5F5] w-[14rem] h-[22rem] text-gray-600 flex flex-col justify-between shadow-lg "
>
<div className="h-full">
<div className="flex justify-center py-4 ">
<img
src={item.imageUrl}
alt="item"
className="h-24"
/>
</div>
<div className="text-sm whitespace-nowrap mb-2">
<div className=" font-semibold text-ellipsis overflow-hidden" >{item?.productName}</div>
</div>
<div className="text-xs mb-2 ">
<span className="font-semibold">Category:</span> <span>{item.category}</span>
</div>
<div className="text-sm">
<p className="text-ellipsis3 text-xs">{item.description}</p>
</div>
<div className="mt-2 text-red-500 font-semibold">₱ {item.unitPrice.toLocaleString(
undefined,
{ minimumFractionDigits: 2 }
)}</div>
</div>
<button
className="bg-secondary hover:bg-primary w-full py-2 text-white text-sm"
onClick={() => addItemToCart(item)}
>
Add to Cart
</button>
</div>
))}
</div>
</div >
);
};
export default Card;;;; |
//
// Copyright © 2023 Zhiwei Sun. All rights reserved.
//
// File name: NumberofOrdersintheBacklog.swift
// Author: Zhiwei Sun @szwathub
// E-mail: szwathub@gmail.com
//
// Description:
// https://github.com/szwathub/LeetCode.swift/issues/486
// https://leetcode.cn/problems/number-of-orders-in-the-backlog
// History:
// 2023/1/2: Created by szwathub on 2023/1/2
//
import Structure
class NumberofOrdersintheBacklog {
fileprivate let MOD: Int = 1000000007
fileprivate typealias Order = (price: Int, amount: Int)
func getNumberOfBacklogOrders(_ orders: [[Int]]) -> Int {
var buy = PriorityQueue<Order> { $0.price > $1.price }
var sell = PriorityQueue<Order> { $0.price < $1.price }
for order in orders {
let price = order[0]
var amount = order[1]
if order[2] == 0 {
while amount > 0, let top = sell.peek(), top.price <= price {
sell.dequeue()
if top.amount > amount {
sell.enqueue((top.price, top.amount - amount))
amount = 0
} else {
amount -= top.amount
}
}
if amount > 0 {
buy.enqueue((price, amount))
}
} else {
while amount > 0, let top = buy.peek(), top.price >= price {
buy.dequeue()
if top.amount > amount {
buy.enqueue((top.price, top.amount - amount))
amount = 0
} else {
amount -= top.amount
}
}
if amount > 0 {
sell.enqueue((price, amount))
}
}
}
var ans = 0
while let top = sell.dequeue() {
ans += top.amount % MOD
}
while let top = buy.dequeue() {
ans += top.amount % MOD
}
return ans % MOD
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous" />
<script src="script.js"></script>
<title>Collage Form</title>
</head>
<body>
<div class="row">
<div class="container ">
<div class="text-center">
<div class="progress fixed-top">
<div class="progress-bar progress-bar-striped" role="progressbar" style="width: 33.33%"
aria-valuenow="15" aria-valuemin="0" aria-valuemax="100">Stage 1</div>
<div class="progress-bar progress-bar-striped bg-info" role="progressbar" style="width: 33.33%"
aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">Stage 2</div>
<!-- <div class="progress-bar bg-success" role="progressbar" style="width: 33.33%" aria-valuenow="30"
aria-valuemin="0" aria-valuemax="100"></div> -->
</div>
<div class="py-4">
<h2>Submit your Collage Form</h2>
</div>
<div class="col-md-3 justify-content-start position-fixed">
<button class="btn btn-info" onclick="history.back()">Go Back</button>
</div>
</div>
<div class="d-flex justify-content-center">
<!-- action="company.html" -->
<form class="border border-info rounded p-5" name="myForm" action="company.html" method="post">
<div class="bg-info p-1">
<b>Enter Your Collage Name</b>
</div>
<br />
<label> Firstname </label>
<input type="text" name="firstname" onchange="resetColor();" size="15" />
<br />
<br />
<label> Lastname: </label>
<input type="text" name="lastname" onchange="resetColor();" size="15" />
<br />
<br />
<b>Select Your Course</b>
<br />
<label> Course : </label>
<select id="mySelect" onchange="resetColor();">
<option value="">Select an Option</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="B.Tech">B.Tech</option>
<option value="MBA">MBA</option>
<option value="MCA">MCA</option>
<option value="M.Tech">M.Tech</option>
</select>
<br />
<br />
<label><b>Choose your Gender:</b></label><br />
<div class="display d-flex">
<input type="radio" name="radioname" /> Male <br />
<input type="radio" name="radioname" /> Female <br />
<input type="radio" name="radioname" /> Other
</div>
<br />
<div class="checkValidate" id="checking">
<label>
<h5>Choose Your Faivorait Hobbies</h5>
</label>
<br />
<tr>
<td>
Reading:
<input type="checkbox" id="check1" class="pl" value="Reading" />
</td>
<td>
Writing:
<input type="checkbox" id="check2" class="pl" value="Writing" />
</td>
</tr>
<tr>
<td>
Playing:
<input type="checkbox" id="check3" class="pl" value="Playing" />
</td>
<td>
Listening
<input type="checkbox" id="check4" class="pl" value="Listening" />
</td>
</tr>
<tr>
<td>
Coding:
<input type="checkbox" id="check5" class="pl" value="Coding" />
</td>
<td>
Gaming
<input type="checkbox" id="check6" class="pl" value="Gaming" />
</td>
<span style="margin-left: 10px;">
<button class="btn btn-sm btn-outline-primary" type="button" onclick="checkAll();">Check all</button>
</span>
<br />
<br />
<h4 id="result"></h4>
</tr>
</div>
<br />
<label> <b>Mobile Number:</b> </label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{3}[0-9]{3}[0-9]{4}" required />
<br />
<br />
<b>Address</b>
<br />
<textarea cols="80" rows="5" value="address"> </textarea>
<br />
<br />
<b>Email:</b>
<input type="email" id="email" name="email" required />
<br />
<br />
<br />
<b>Password:</b>
<input type="Password" id="pass" name="pass" required />
<br />
<br />
<br />
<input class="btn btn-success" type="submit" onclick="return validateForm();" value="Submit" />
<input class="btn btn-warning" type="reset" value="Reset" />
</form>
</div>
</div>
</div>
</body>
</html> |
import React, { useEffect, useRef, useState } from 'react'
import style from './gymplans.module.css'
import axios from 'axios';
import ReactCardFlip from 'react-card-flip';
export default function Gymplans() {
const [todos, setTodos] = useState([]);
const inputRef = useRef();
const [isFlipped, setIsFlipped] = useState(false);
const handleClick = () => {
setIsFlipped(!isFlipped);
};
const handler = () => {
const text = inputRef.current.value;
const newItem = { Completed: false, text }
setTodos([...todos, newItem]);
inputRef.current.value = ""
}
const handelItemDone = (index) => {
const newToDos = [...todos];
newToDos[index].Completed = !newToDos[index].Completed;
setTodos(newToDos)
console.log(newToDos)
}
const handelDeleteItem = (index) => {
const newToDos = [...todos];
newToDos.splice(index, 1);
setTodos(newToDos)
}
const [filp, setFlip] = useState(false)
const [gif, getGifExercises] = useState([])
useEffect(() => {
const fetchData = async () => {
const options = {
method: 'GET',
url: 'https://exercisedb.p.rapidapi.com/exercises',
params: { limit: '10' },
headers: {
'X-RapidAPI-Key': 'f9dd725c93msh0bc7a1528d1187bp17edf3jsn0a9d65571d92',
'X-RapidAPI-Host': 'exercisedb.p.rapidapi.com',
},
};
try {
const response = await axios.request(options);
console.log(response.data);
getGifExercises(response.data);
} catch (error) {
console.error(error);
}
};
fetchData();
}, []);
return (
<>
<div className={style.maincontainer} style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', backgroundImage: `url('https://t4.ftcdn.net/jpg/04/61/47/03/360_F_461470323_6TMQSkCCs9XQoTtyer8VCsFypxwRiDGU.jpg')`, backgroundPosition: 'center', minHeight: '100vh'}}>
{/*<div className='d-flex flex-wrap'>
{biceps.slice(0, 2).map((item)=>(
<div key={item.id} className="card" style={{width: '18rem'}}>
<img src="..." className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title">{item.muscle}</h5>
<p className="card-text">{item.equipment}</p>
<a href="#" className="btn btn-primary">Go somewhere</a>
</div>
</div>
))}
</div>*/}
<ReactCardFlip isFlipped={isFlipped} flipDirection="vertical">
{/* Front of the card */}
<div className="card-front" onClick={handleClick}>
<div className="chestcontainer d-flex">
<div className="card mb-3" style={{ maxWidth: 540, height: 203 }}>
<div className="row g-0">
<div className="col-md-4">
<img
src="https://media.istockphoto.com/id/1126903494/photo/a-young-handsome-man-doing-strength-workout-exercise-in-gym.webp?b=1&s=170667a&w=0&k=20&c=jivkCkjjORHPwjbtV9C2FljZau3BG7RE78nHRZOy0Tg="
className="img-fluid rounded-start h-100 rounded-circle"
alt="..."
style={{ width: '100%', height: 'auto' }}
/>
</div>
<div className="col-md-8">
<div className="card-body">
<h5 className="card-title text-primary">Chest in the gym</h5>
<ol>
<li>Bench press builds chest strength</li>
<li>Incline press targets upper chest.</li>
<li>Chest flyes isolate chest muscles.</li>
<li>Cable crossovers shape chest nicely.</li> </ol>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Back of the card */}
<div className="card-back" onClick={handleClick}>
<div className="card mb-3" style={{ maxWidth: 540, height: 203 }}>
<div className="row g-0">
<div className="col-md-4">
<img
src="https://www.muscleandfitness.com/wp-content/uploads/2018/07/1109-home-workout0.jpg?quality=86&strip=all"
className="img-fluid rounded-start h-100 rounded-circle"
alt="..."
style={{ width: '100%', height: 'auto' }}
/>
</div>
<div className="col-md-8">
<div className="card-body " >
<h5 className="card-title text-primary">Chest in the gym</h5>
<ol>
<li>Push-ups for chest at home.</li>
<li>Decline push-ups target upper chest.</li>
<li>Dumbbell chest press, floor-based.</li>
<li>Wide-arm push-ups engage chest.</li>
</ol>
</div>
</div>
</div>
</div>
</div>
</ReactCardFlip>
<ReactCardFlip isFlipped={isFlipped} flipDirection="vertical">
{/* Front of the card */}
<div className="card-front" onClick={handleClick}>
<div className="chestcontainer d-flex">
<div className="card mb-3" style={{ maxWidth: 540, height: 225 }}>
<div className="row g-0">
<div className="col-md-4" style={{}}>
<img
src="https://steelsupplements.com/cdn/shop/articles/shutterstock_657941434_376ae0c9-1a39-42d3-bc39-3eaf18d5038f_600x.jpg?v=1641548776"
className="img-fluid rounded-start h-100 rounded-circle"
alt="..."
style={{ width: '100%', height: 'auto' }}
/> </div>
<div className="col-md-8">
<div className="card-body">
<h5 className="card-title text-primary">Biceps in the gym</h5>
<ol>
<li>Barbell curls build bicep strength.</li>
<li>Hammer curls work biceps nicely.</li>
<li>Preacher curls target bicep muscles.</li>
<li>Concentration curls isolate biceps effectively</li>
</ol>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Back of the card */}
<div className="card-back" onClick={handleClick}>
<div className="card mb-3" style={{ maxWidth: 540, height: 203 }}>
<div className="row g-0">
<div className="col-md-4">
<img
src="https://cdn.muscleandstrength.com/sites/default/files/images/articles/chinups_for_arm_muscles.jpg"
className="img-fluid rounded-start h-100 rounded-circle"
alt="..."
style={{ width: '100%', height: 'auto' }}
/> </div>
<div className="col-md-8">
<div className="card-body">
<h5 className="card-title text-primary">Biceps in the home</h5>
<ol>
<li>Push-ups engage biceps at home</li>
<li>Dumbbell curls, home bicep workout</li>
<li>Chin-ups, great for bicep development.</li>
<li>Resistance band curls, home option</li>
<li>Towel curls, creative bicep exercise.</li>
</ol>
</div>
</div>
</div>
</div>
</div>
</ReactCardFlip>
<ReactCardFlip isFlipped={isFlipped} flipDirection="vertical">
{/* Front of the card */}
<div className="card-front" onClick={handleClick}>
<div className="chestcontainer d-flex">
<div className="card mb-3" style={{ maxWidth: 540, height: 225 }}>
<div className="row g-0">
<div className="col-md-4">
<img
src="https://blogscdn.thehut.net/wp-content/uploads/sites/478/2018/05/11115302/triceps-dip-min.jpg"
className="img-fluid rounded-start h-100 rounded-circle"
alt="..."
style={{ width: '100%', height: 'auto' }}
/> </div>
<div className="col-md-8">
<div className="card-body">
<h5 className="card-title text-primary">Tricep in the gym</h5>
<ol>
<li>Tricep dips build arm strength</li>
<li>Close-grip bench press targets triceps</li>
<li>Tricep pushdowns work arm muscles</li>
<li>Skull crushers isolate triceps effectively</li>
<li>Overhead extensions strengthen triceps nicely</li>
</ol>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Back of the card */}
<div className="card-back" onClick={handleClick}>
<div className="card mb-3" style={{ maxWidth: 540, height: 225 }}>
<div className="row g-0">
<div className="col-md-4">
<img
src="https://img.livestrong.com/-/clsd/getty/95715babdffa4e769ada80f2c759327a.jpg"
className="img-fluid rounded-start h-100 rounded-circle"
alt="..."
style={{ width: '100%', height: 'auto' }}
/>
</div>
<div className="col-md-8">
<div className="card-body">
<h5 className="card-title text-primary">Tricep in the home</h5>
<ol>
<li>Chair dips engage triceps well</li>
<li>Diamond push-ups isolate triceps</li>
<li>Resistance bands for tricep workouts</li>
<li>Tricep kickbacks with dumbbells</li>
<li>Tricep overhead extensions with household items</li>
</ol>
</div>
</div>
</div>
</div>
</div>
</ReactCardFlip>
<ReactCardFlip isFlipped={isFlipped} flipDirection="vertical">
{/* Front of the card */}
<div className="card-front" onClick={handleClick}>
<div className="chestcontainer d-flex">
<div className="card mb-3" style={{ maxWidth: 540, height: 260 }}>
<div className="row g-0">
<div className="col-md-4" style={{ height: 260 }}>
<img
src="https://myxperiencefitness.com/wp-content/uploads/2020/07/back-main-image.jpg"
className="img-fluid rounded-start h-100 rounded-circle"
alt="..."
style={{ width: '100%', height: '100%', }}
/>
</div>
<div className="col-md-8">
<div className="card-body">
<h5 className="card-title text-primary">Back in the gym</h5>
<ol>
<li>Deadlifts strengthen the entire back effectively.</li>
<li>Pull-ups work upper back muscles intensely</li>
<li>Rows target mid-back and lats.</li>
<li>Lat pulldowns for broad back development.</li>
<li>Face pulls improve upper back posture</li>
</ol>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Back of the card */}
<div className="card-back" onClick={handleClick}>
<div className="card mb-3" style={{ maxWidth: 540, height: 225 }}>
<div className="row g-0">
<div className="col-md-4" style={{ height: 225 }}>
<img
src="https://cdn-images.cure.fit/www-curefit-com/image/upload/c_fill,w_375,q_auto:eco,dpr_2,f_auto,fl_progressive/image/diy/f5332b0b-253a-416c-9266-2d19ddd4224e.jpg"
className="img-fluid rounded-start h-100 rounded-circle"
alt="..."
style={{ width: '100%', height: 'auto' }}
/>
</div>
<div className="col-md-8">
<div className="card-body">
<h5 className="card-title text-primary">Back in the home</h5>
<ol>
<li>Superman exercise for lower back activation.</li>
<li>Bodyweight rows using a sturdy bar</li>
<li>Doorway pull-ups engage back muscles</li>
<li>Plank with row to work back</li>
<li>Resistance band rows for a home back workout effectively </li>
</ol>
</div>
</div>
</div>
</div>
</div>
</ReactCardFlip>
<ReactCardFlip isFlipped={isFlipped} flipDirection="vertical">
{/* Front of the card */}
<div className="card-front" onClick={handleClick}>
<div className="chestcontainer d-flex">
<div className="card mb-3" style={{ maxWidth: 540, height: 225 }}>
<div className="row g-0">
<div className="col-md-4" style={{ height: 225 }}>
<img
src="https://global-uploads.webflow.com/5f517d45532327f0210280dc/60d6002ddc91a45f41743e7c_Untitled%20design%20(10).png"
className="img-fluid rounded-start h-100 rounded-circle"
alt="..."
style={{ width: '100%', height: 'auto' }}
/>
</div>
<div className="col-md-8">
<div className="card-body">
<h5 className="card-title text-primary">Shoulder in the gym</h5>
<ol>
<li>Military press builds shoulder strength</li>
<li>Dumbbell lateral raises for broad shoulders</li>
<li>Upright rows target shoulder muscles</li>
<li>Face pulls improve shoulder posture</li>
<li>Arnold presses enhance overall shoulder development</li>
</ol>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Back of the card */}
<div className="card-back" onClick={handleClick}>
<div className="card mb-3" style={{ maxWidth: 540, height: 220 }}>
<div className="row g-0">
<div className="col-md-4" style={{ height: 220 }}>
<img
src="https://www.mensjournal.com/.image/t_share/MTk2MTM2NDUyMzIwNTM1Njk3/1280-shoulder-raise.jpg"
className="img-fluid rounded-start h-100 rounded-circle"
alt="..."
style={{ width: '100%', height: 'auto' }}
/>
</div>
<div className="col-md-8">
<div className="card-body">
<h5 className="card-title text-primary">Shoulder in the home</h5>
<ol>
<li>Bodyweight shoulder presses for home workout.</li>
<li>Bodyweight rows using a sturdy bar</li>
<li>Lateral raises using household items</li>
<li>Resistance band exercises for shoulder strength</li>
</ol>
</div>
</div>
</div>
</div>
</div>
</ReactCardFlip>
</div>
{/*to do list */}
<div className={style.todoContainer} style={{ backgroundImage: `url('https://t4.ftcdn.net/jpg/04/61/47/03/360_F_461470323_6TMQSkCCs9XQoTtyer8VCsFypxwRiDGU.jpg')` }}> <h2 className='text-light'>To Do List</h2>
<ol className={style.liToDoList}>
{todos.map(({ text, Completed }, index,) => {
return (<div className={style.listContainer}><li onClick={() => handelItemDone(index)} className={Completed ? "text-decoration-line-through " : ""} key={index}>{text}</li>
<span onClick={() => handelDeleteItem(index)} >❌</span></div>)
})}
</ol>
<input className={style.inputTask} type="text" ref={inputRef} placeholder='Enter the exercise' />
<button onClick={handler} className='btn btn-primary'>Add</button>
</div>
<div>
<span className='text-capitalize fs-3 text-primary position-relative top-0 ps-3 translate-middle'>warm-up exercises</span>
</div>
<div style={{
flexWrap: 'wrap', height: "auto",
display: 'flex',
}} className="showExercises">
{gif.map((data) => (
<div key={data.id}>
<div className="card" style={{ width: '18rem' }}>
<img src={data.gifUrl} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title text-primary">{data.bodyPart}</h5>
<p className="card-text">{data.equipment}</p>
</div>
</div>
</div>
))}
</div>
</>
)
} |
import pygame
import sys
from pygame.locals import *
class QuizGame:
def __init__(self):
# Initialize Pygame
pygame.init()
# Set up the display
self.WIDTH, self.HEIGHT = 800, 600
self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
pygame.display.set_caption('Pygame Quiz')
# Define colors
self.WHITE = (255, 255, 255)
self.BLACK = (0, 0, 0)
self.GRAY = (200, 200, 200)
self.GREEN = (0, 255, 0)
self.RED = (255, 0, 0)
# Define fonts
self.font = pygame.font.Font(None, 36)
self.image = pygame.image.load("img/CIA_Text.png")
self.meme_img = pygame.image.load("img/ProcrastinatorMeme.jpg")
self.youKnowIt_img = pygame.image.load("img/YouKnowIt.jpg")
self.dress_meme_img = pygame.image.load("img/dress_meme.png")
self.cr_meme_img = pygame.image.load("img/cr_meme.png")
self.questions = [
{"question": "Who is the best Advanced Python Teacher?", "options": ["Gunavathi Ma'am", "Berlin", "John Doe", "23"], "correct": 0},
{"question": "When is the correct time to begin a CIA?", "options": ["A night before submission", "Sandwich", "Jupiter", "Saturn"], "correct": 0},
{"question": "What color is your blazer supposed to be on a thursday?", "options": ["Rainbow", "Black", "Hot Pink", "Bling Bling"], "correct": 1},
{"question": "Who is the best CR that BscDs ever had?", "options": ["Gulafshan", "Gulafshan", "Gulafshan", "All of the Above"], "correct": 3}]
# Button class
class Button:
def __init__(self, screen, text, x, y, width, height, color, action, font, quiz_game_instance):
self.screen = screen
self.rect = pygame.Rect(x, y, width, height)
self.text = text
self.color = color
self.action = action
self.font = font
self.quiz_game_instance = quiz_game_instance
def draw_text(self, text, font, color, x, y):
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.topleft = (x, y)
self.screen.blit(text_surface, text_rect)
def draw(self):
pygame.draw.rect(self.screen, self.color, self.rect)
self.draw_text(self.text, self.font, self.quiz_game_instance.BLACK, self.rect.x + 10, self.rect.y + 10)
def is_clicked(self, pos):
return self.rect.collidepoint(pos)
self.Button = Button
self.current_question = 0
self.score = 0
def draw_text(self, text, font, color, x, y):
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.topleft = (x, y)
self.screen.blit(text_surface, text_rect)
def draw_options(self, options, buttons):
option_y = 300
button_spacing = 60 # Adjust as needed
for i, option in enumerate(options):
buttons[i].rect.topleft = (self.WIDTH // 2 - 150, option_y)
buttons[i].draw()
self.draw_text(option, self.font, self.BLACK, self.WIDTH // 2 - 120, option_y + 10)
option_y += button_spacing
def display_feedback(self, is_correct, correct_answer, y_position):
feedback_text = "Correct!" if is_correct else f"Oops! The correct answer was {correct_answer}"
self.draw_text(feedback_text, self.font, self.GREEN if is_correct else self.RED, self.WIDTH // 2 - 150, y_position)
def check_answer(self, selected_option):
correct_option = self.questions[self.current_question]["correct"]
is_correct = selected_option == correct_option
self.display_feedback(is_correct, self.questions[self.current_question]["options"][correct_option], 100)
if is_correct:
self.score += 1
self.current_question += 1
if self.current_question == len(self.questions):
# Display final score
self.screen.fill(self.WHITE)
self.draw_text("Quiz Completed!", self.font, self.BLACK, self.WIDTH // 2 - 150, 100)
self.draw_text(f"Your Score: {self.score}/{len(self.questions)}", self.font, self.BLACK, self.WIDTH // 2 - 150, 200)
pygame.display.flip()
return True
return False
# pygame.time.wait(3000) # Display final screen for 3 seconds
# pygame.quit()
# sys.exit()
def main(self):
global current_question, score
# Create buttons
button_width, button_height = 400, 40
option_buttons = [
self.Button(self.screen, "", 0, 0, button_width, button_height, self.GRAY, self.check_answer, self.font, self),
self.Button(self.screen, "", 0, 0, button_width, button_height, self.GRAY, self.check_answer, self.font, self),
self.Button(self.screen, "", 0, 0, button_width, button_height, self.GRAY, self.check_answer, self.font, self),
self.Button(self.screen, "", 0, 0, button_width, button_height, self.GRAY, self.check_answer, self.font, self),
]
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
for i, button in enumerate(option_buttons):
if button.is_clicked(event.pos):
if self.check_answer(i):
return True
self.screen.fill(self.WHITE)
self.screen.blit(self.image, (self.WIDTH // 2 - self.image.get_width() // 2, 50))
question_text = self.questions[self.current_question]["question"]
self.draw_text(question_text, self.font, self.BLACK, self.WIDTH // 2 - 300, 100)
if self.current_question == 0:
self.screen.blit(self.youKnowIt_img, (self.WIDTH // 2 - self.youKnowIt_img.get_width() // 2, 130))
if self.current_question == 1:
self.screen.blit(self.meme_img, (self.WIDTH // 2 - self.meme_img.get_width() // 2, 130))
if self.current_question == 2:
self.screen.blit(self.dress_meme_img, (self.WIDTH // 2 - self.meme_img.get_width() // 2, 130))
if self.current_question == 3:
self.screen.blit(self.cr_meme_img, (self.WIDTH // 2 - self.cr_meme_img.get_width() // 2, 130))
options = self.questions[self.current_question]["options"]
self.draw_options(options, option_buttons)
pygame.display.flip()
if __name__ == '__main__':
quiz_game = QuizGame()
quiz_game.main() |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>
int main()
{
int i, j;
int R1, C1;
int R2, C2;
printf("Ingresar el numero de R1: ");
scanf("%d", &R1);
printf("Ingresar el numero de C1: ");
scanf("%d", &C1);
printf("Ingresar el numero de R2: ");
scanf("%d", &R2);
printf("Ingresar el numero de C2: ");
scanf("%d", &C2);
printf("\n");
int m1[R1][C1];
int m2[R2][C2];
// int m2[R2][C2];
// if coloumn of m1 not equal to rows of m2
if (C1 != R2)
{
printf("The number of columns in Matrix-1 must be "
"equal to the number of rows in "
"Matrix-2\n");
printf("Please update MACROs value according to "
"your array dimension in "
"#define section\n");
exit(EXIT_FAILURE);
}
// Fill with random number between 1 to 8 the m1
for (i = 0; i < R1; i++)
{
for (j = 0; j < C1; j++)
{
m1[i][j] = (rand() % 8) + 1;
m1[i][j] = (rand() % 8) + 1;
}
}
// Fill with random number between 1 to 8 the m2
for (i = 0; i < R2; i++)
{
for (j = 0; j < C2; j++)
{
m2[i][j] = (rand() % 8) + 1;
m2[i][j] = (rand() % 8) + 1;
}
}
// Show Matriz 1
for (i = 0; i < R1; i++)
{
for (j = 0; j < C1; j++)
{
printf("%d ", m1[i][j]);
}
printf("\n");
}
printf("\n");
// Show Matriz 2
for (i = 0; i < R2; i++)
{
for (j = 0; j < C2; j++)
{
printf("%d ", m2[i][j]);
}
printf("\n");
}
clock_t end = clock();
void multiplyMatrix(int m1[][C1], int m2[][C2])
{
double time_spent = 0.0;
clock_t begin = clock();
int result[R1][C2];
printf("\n");
printf("El resultado de la multiplicación es:");
printf("\n");
for (int i = 0; i < R1; i++)
{
for (int j = 0; j < C2; j++)
{
result[i][j] = 0;
for (int k = 0; k < R2; k++)
{
result[i][j] += m1[i][k] * m2[k][j];
}
printf("%d ", result[i][j]);
}
printf("\n");
}
printf("\n");
clock_t end = clock();
time_spent += (double)(end - begin) / CLOCKS_PER_SEC;
printf("El tiempo que se demoro sin usar programación paralela en multiplicar dos matrices es de: %f seconds", time_spent);
printf("\n");
}
void multiplyMatrixP(int m1[][C1], int m2[][C2])
{
printf("\n");
double time_spent = 0.0;
int result[R1][C2];
clock_t begin = clock();
#pragma omp parallel
{
#pragma omp for
for (int i = 0; i < R1; i++)
{
for (int j = 0; j < C2; j++)
{
result[i][j] = 0;
for (int k = 0; k < R2; k++)
{
result[i][j] += m1[i][k] * m2[k][j];
}
printf("%d ", result[i][j]);
}
printf("\n");
}
}
clock_t end = clock();
time_spent += (double)(end - begin) / CLOCKS_PER_SEC;
printf("El tiempo que se demoro sin usando paralela en multiplicar dos matrices es de: %f seconds", time_spent);
}
multiplyMatrix(m1, m2);
multiplyMatrixP(m1, m2);
return 0;
} |
import { Button, Tabs } from 'antd'
import styles from '@/styles/landing.module.css'
import TabPane from 'antd/es/tabs/TabPane'
import CourseCard from './CourseCard'
interface Course {
id: number
title: string
description: string
rating: number
price: number
imageUrl: string
category: string
}
const courseCategories = [
'Python',
'Excel',
'Web Development',
'JavaScript'
]
const coursesData: Course[] = [
{
id: 1,
title: 'The Complete Python Bootcamp From Zero to Hero',
description: 'Become an Python pro',
rating: 4.6,
price: 1399,
imageUrl: 'https://img-b.udemycdn.com/course/240x135/567828_67d0.jpg',
category: 'Python'
},
{
id: 1,
title: 'The Complete Python Bootcamp From Zero to Hero',
description: 'Become an Python pro',
rating: 4.6,
price: 1399,
imageUrl: 'https://img-b.udemycdn.com/course/240x135/567828_67d0.jpg',
category: 'Python'
},
{
id: 1,
title: 'The Complete Python Bootcamp From Zero to Hero',
description: 'Become an Python pro',
rating: 4.6,
price: 1399,
imageUrl: 'https://img-b.udemycdn.com/course/240x135/567828_67d0.jpg',
category: 'Python'
},
{
id: 1,
title: 'The Complete Python Bootcamp From Zero to Hero',
description: 'Become an Python pro',
rating: 4.6,
price: 1399,
imageUrl: 'https://img-b.udemycdn.com/course/240x135/567828_67d0.jpg',
category: 'Python'
},
{
id: 1,
title: 'The Complete Python Bootcamp From Zero to Hero',
description: 'Become an Python pro',
rating: 4.6,
price: 1399,
imageUrl: 'https://img-b.udemycdn.com/course/240x135/567828_67d0.jpg',
category: 'Python'
},
{
id: 1,
title: 'The Complete Python Bootcamp From Zero to Hero',
description: 'Become an Python pro',
rating: 4.6,
price: 1.399,
imageUrl: 'https://img-b.udemycdn.com/course/240x135/567828_67d0.jpg',
category: 'Python'
},
{
id: 2,
title: 'Excel Mastery for Data Analysis',
description: 'Become an Excel pro',
rating: 4.8,
price: 999,
imageUrl: 'https://img-b.udemycdn.com/course/240x135/543600_64d1_4.jpg',
category: 'Excel'
},
{
id: 2,
title: 'The Complete 2024 Web Development Bootcamp',
description: 'Become an Web Developer pro',
rating: 4.8,
price: 999,
imageUrl: 'https://img-b.udemycdn.com/course/240x135/543600_64d1_4.jpg',
category: 'Web Development'
},
{
id: 3,
title: 'The Complete JavaScript Course 2024: From Zero to Expert!',
description: 'Become an Javascript pro',
rating: 4.8,
price: 999,
imageUrl: 'https://img-b.udemycdn.com/course/240x135/543600_64d1_4.jpg',
category: 'JavaScript'
},
{
id: 4,
title: 'Complete JAVASCRIPT with HTML5,CSS3 from zero to Expert-2024',
description: 'Become an JavaScript pro',
rating: 4.8,
price: 999,
imageUrl: 'https://img-b.udemycdn.com/course/240x135/543600_64d1_4.jpg',
category: 'JavaScript'
}
]
const CourseTab = () => {
const coursesByCategory = coursesData.reduce((acc, course: Course) => {
if (
course.category.length > 0) {
acc[course.category] = (Boolean(acc[course.category])) || []
acc[course.category].push(course)
}
return acc
}, {})
return (
<div className={styles.coursetabcontainer}>
<h2>A broad selection of courses</h2>
<Tabs defaultActiveKey="1" className={styles.coursetab}>
{courseCategories.map(category => (
<TabPane tab={category} key={category} className={styles.category}>
<p>{category} description</p>
<Button href="#">Explore {category}</Button>
<div className={styles.cardscontainer}>
{(Boolean(coursesByCategory[category])) &&
coursesByCategory[category].map(course => (
<CourseCard key={course.id} {...course} />
))}
</div>
</TabPane>
))}
</Tabs>
</div>
)
}
export default CourseTab |
import { PartialType } from '@nestjs/mapped-types';
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsBoolean, IsDate, IsNumber } from 'class-validator';
import { CreateOrderStatusDto } from './create-order-status.dto';
export class UpdateOrderStatusDto extends PartialType(CreateOrderStatusDto) {
@ApiProperty()
@IsNotEmpty()
@IsString()
orderStatus: string
@ApiProperty()
@IsNotEmpty()
@IsBoolean()
status: boolean
@ApiProperty()
@IsNotEmpty()
@IsNumber()
updatedBy:number
} |
import React from 'react';
import JumboCardQuick from "@jumbo/components/JumboCardQuick";
import { Button, Grid, List, MenuItem} from "@mui/material";
import { useState } from 'react';
import { GetUsersListApi, UpdateUserPasswordApi } from 'backendServices/ApiCalls';
import SweetAlert from 'app/pages/components/mui/Alerts/SweetAlert';
import * as yup from "yup";
import { Form, Formik } from "formik";
import Div from '@jumbo/shared/Div/Div';
import JumboTextField from '@jumbo/components/JumboFormik/JumboTextField';
import { LoadingButton } from '@mui/lab';
import { useEffect } from 'react';
const validationSchema = yup.object({
user_name: yup
.string()
.required('User name is Required'),
password: yup
.string()
.required('Old transaction password is required'),
confirm_password: yup
.string()
.required('New transaction password is required')
.min(4, 'Password must be at least 8 characters long'),
admin_transaction_password: yup
.string()
.required('Admin transaction password is required')
.min(4, 'Password must be at least 8 characters long'),
});
const Updateuserpassword = () => {
const [userdata, setUserData] =useState([]);
const [alertData, setalertData] = useState({
show: false,
message: "",
variant: ""
})
const style = {
"& .MuiOutlinedInput-root": {
"&.Mui-focused fieldset": {
borderColor: "#fff"
}
}
}
const usernamelist = () => {
GetUsersListApi(response =>{
console.log("response22", response)
// userdata.filter(data =>(
// console.log("data", data.username)
// ))
setUserData(response?.data?.userdata)
})
}
// let data = userdata?.filter(data => data.username);
// console.log("44444444444",data)
useEffect(() => {
usernamelist();
}, [])
const handleSubmit = (data, setSubmitting, resetForm) => {
let params = {
userid: data.user_name,
password: data.password,
confirmpassword: data.confirm_password,
admintransactionpassword: data.admin_transaction_password
}
UpdateUserPasswordApi(params, (response) => {
if (response?.data?.status === "error") {
setalertData({
show: true,
message: response?.data?.message,
variant: "error"
})
setSubmitting(false)
}
else if (response?.data?.status === "success") {
setalertData({
show: true,
message: response?.data?.message,
variant: "success"
})
setSubmitting(false);
resetForm();
}
else {
setalertData({
show: true,
message: 'Something went wrong please try again later',
variant: "error"
})
setSubmitting(false)
}
}, (error) => {
console.log(error?.response?.data);
});
}
// const test = () => {
// console.log('aaaaaaaaaaaaaaaaaaaaaa')
// console.log(userdata[0])
// }
return (
<Grid container fullWidth sm={12} xs={12} p={2} alignItems="center" justifyContent="center">
<Grid item sm={6} xs={12}>
<JumboCardQuick title={"Update User Password"} noWrapper>
{
alertData.show && (<SweetAlert alertData={alertData} setalertData={setalertData} />)
}
<List disablePadding sx={{ mb: 2 }}>
<Formik
validateOnChange={true}
initialValues={{
user_name: '',
password: '',
confirm_password: '',
admin_transaction_password: '',
}}
validationSchema={validationSchema}
onSubmit={(data, { setSubmitting, resetForm }) => {
setSubmitting(true);
handleSubmit(data, setSubmitting, resetForm);
console.log("formikdata", data)
}}
>
{({ isSubmitting }) => (
<Form style={{ textAlign: 'left' }} noValidate autoComplete='off'>
<Div sx={{ mt: 1, mb: 3, pl: 2, pr: 2 }}>
<JumboTextField
select
fullWidth
name="user_name"
label="Select a User"
>
{userdata && userdata.map(value => (
<MenuItem value={value.id} key={value.id}>{value.username}</MenuItem>
))}
</JumboTextField>
</Div>
<Div sx={{ mt: 1, mb: 3, pl: 2, pr: 2 }}>
<JumboTextField
fullWidth
name="password"
label="Password"
type="password"
/>
</Div>
<Div sx={{ mt: 1, mb: 3, pl: 2, pr: 2 }}>
<JumboTextField
fullWidth
name="confirm_password"
label="Confirm Password"
type="password"
/>
</Div>
<Div sx={{ mt: 1, mb: 3, pl: 2, pr: 2 }}>
<JumboTextField
fullWidth
name="admin_transaction_password"
label="Admin transaction Password"
type="password"
/>
</Div>
<Div sx={{ mt: 1, pl: 2, pr: 2 }}>
<LoadingButton
fullWidth
type="submit"
variant="contained"
size="large"
sx={{ mb: 3 }}
loading={isSubmitting}
>Submit</LoadingButton>
{/* <Button type="button" onClick={test}>click me</Button> */}
</Div>
</Form>
)}
</Formik>
</List>
</JumboCardQuick>
</Grid>
</Grid>
);
};
export default Updateuserpassword; |
import { test, expect } from '@playwright/test';
test('homepage has title and links to intro page', async ({ page }, testInfo) => {
await page.goto('https://playwright.dev/');
// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/);
// create a locator
const getStarted = page.getByRole('link', { name: 'Get started' });
await page.screenshot();
// await expect(true).toBeFalsy();
// Expect an attribute "to be strictly equal" to the value.
await expect(getStarted).toHaveAttribute('href', '/docs/intro');
// Click the get started link.
await getStarted.click();
// Expects the URL to contain intro.
await expect(page).toHaveURL(/.*intro/);
});
test('should fail', async ({ page }, testInfo) => {
await page.goto('https://playwright.dev/');
// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/);
// create a locator
const getStarted = page.getByRole('link', { name: 'Get started' });
await page.screenshot();
await expect(true).toBeFalsy();
// Expect an attribute "to be strictly equal" to the value.
await expect(getStarted).toHaveAttribute('href', '/docs/intro');
// Click the get started link.
await getStarted.click();
// Expects the URL to contain intro.
await expect(page).toHaveURL(/.*intro/);
}); |
---
tags:
- Note_done
- Biologie
source: Biologie - Peter H. Raven - 4e édition
---
Link :
_Biologie : Introduction_
1. [[1.0.0 - Zoologie]]
2. [[1.0.13 - Phylogénie]]
3. [[1.0.13.1 - Arbre phylogénétique]]
# Définition
Un cladogramme est une représentation graphique qui montre les relations évolutives entre différents groupes d'organismes.
**Illustration** : ![[Pasted image 20240404233629.png]]
### Utilité ?
Il est utilisé en biologie pour illustrer les liens de parenté entre les espèces en se basant sur leurs caractéristiques communes.
\
Les organismes qui partagent des caractéristiques similaires sont regroupés dans des branches, appelées clades, sur le cladogramme. Les clades qui partagent un ancêtre commun plus récent sont regroupés plus étroitement sur le cladogramme. En résumé, un cladogramme est un outil visuel pour représenter les liens évolutifs entre les organismes.
### Différence entre arbre phylogénétique & cladogramme
Un cladogramme et un arbre phylogénétique sont deux représentations graphiques des relations évolutives entre les organismes, mais ils diffèrent dans leur niveau de détail et dans leur interprétation. Voici les principales différences entre un cladogramme et un arbre phylogénétique :
1. **Cladogramme** :
- Un cladogramme est une représentation schématique simplifiée des relations évolutives entre les organismes.
- Il montre les regroupements des organismes en clades, des groupes monophylétiques, mais ne représente pas nécessairement les distances évolutives entre eux.
- Les branches du cladogramme ne sont pas proportionnelles aux différences évolutives entre les organismes.
- Les nœuds du cladogramme indiquent les points de divergence où des caractères partagés dérivés (synapomorphies) sont apparus.
- Les cladogrammes sont souvent utilisés pour représenter des hypothèses sur les relations phylogénétiques entre les organismes, mais ils ne fournissent pas d'informations sur la chronologie des événements évolutifs.
2. **Arbre phylogénétique** :
- Un arbre phylogénétique est une représentation plus détaillée et plus informatique des relations évolutives entre les organismes.
- Il montre les regroupements des organismes en clades, mais également les distances évolutives entre eux.
- Les branches de l'arbre phylogénétique sont proportionnelles aux différences évolutives entre les organismes, ce qui permet d'estimer le temps écoulé depuis les divergences.
- Les nœuds de l'arbre phylogénétique représentent également les points de divergence, mais ils peuvent être étiquetés avec des estimations de temps ou d'autres informations supplémentaires.
- Les arbres phylogénétiques sont utilisés pour représenter des hypothèses sur les relations phylogénétiques, mais ils peuvent également être utilisés pour estimer les dates de divergence, étudier l'évolution moléculaire et d'autres analyses évolutives. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.