text stringlengths 184 4.48M |
|---|
const { Model, DataTypes } = require("sequelize");
const { sequelize } = require("../util/db");
class User extends Model {}
User.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
username: {
type: DataTypes.TEXT,
unique: true,
allowNull: false,
validate: {
isEmail: true,
},
},
name: {
type: DataTypes.TEXT,
allowNull: false,
},
passwordHash: {
type: DataTypes.TEXT,
allowNull: false,
},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE,
},
{
sequelize,
underscored: true,
timestamps: true, //enable timestamps(createdAt and updatedAt)
modelName: "user",
}
);
module.exports = User; |
import 'package:betano/components/table_handall_body.dart';
import 'package:flutter/material.dart';
import '../constants/app_colors.dart';
import 'custom_button.dart';
import 'matches_handball_body.dart';
class TableMatchesHandballButton extends StatefulWidget {
const TableMatchesHandballButton({super.key});
@override
State<TableMatchesHandballButton> createState() =>
_TableMatchesHandballButtonState();
}
class _TableMatchesHandballButtonState
extends State<TableMatchesHandballButton> {
Color button1Color = AppColors.white;
Color button2Color = AppColors.white;
bool showTable = true;
void changeButton() {
if (button1Color == AppColors.white) {
setState(() {
button1Color = AppColors.tabColor;
button2Color = AppColors.white;
});
} else {
setState(() {
button1Color = AppColors.white;
button2Color = AppColors.tabColor;
});
}
}
void toggleView() {
setState(() {
showTable = !showTable;
});
}
@override
void initState() {
super.initState();
setState(() {
button1Color = AppColors.tabColor;
});
}
@override
Widget build(BuildContext context) {
return Expanded(
flex: 4,
child: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/bg_handball.png'),
fit: BoxFit.cover,
),
),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CustomButton(
backgroundColor: button1Color,
onPressed: () {
changeButton();
toggleView();
},
text: 'Table',
),
CustomButton(
backgroundColor: button2Color,
onPressed: () {
changeButton();
toggleView();
},
text: 'Matches',
),
],
),
if (showTable) const TableHandballBody(),
if (!showTable) const MatchesHandballBody(),
],
),
),
);
}
} |
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import inv
# Constants given in the problem
beta = 0.0075
lambda_ = 0.08
Lambda_ = 6e-5
N0 = 1
C0 = beta * N0 / (Lambda_ * lambda_)
alpha = 2.0 * beta
Nref = 1.0
rho0 = -6.67 * beta + alpha * N0 / Nref
# Reactivity function with negative feedback
def reactivity(t, N):
return rho0 - alpha * N / Nref
# Define the system of equations
def point_kinetics(N, C, rho):
dN_dt = (rho - beta) / Lambda_ * N + lambda_ * C
dC_dt = beta / Lambda_ * N - lambda_ * C
return np.array([dN_dt, dC_dt])
# The A matrix function as in A(t, f)
def A_matrix(t, f):
rho = reactivity(t, f[0])
return np.array([[(rho - beta) / Lambda_, lambda_], [beta / Lambda_, -lambda_]])
# The norm function as defined in the problem
def norm(f):
return np.sqrt(f[0] ** 2 + f[1] ** 2)
# Lagged Trapezoidal/BDF-2 scheme
def lagged_TBDF2(t, dt):
# Initial conditions
f = np.array([N0, C0])
# Storing the solution
f_values = [f]
for i in range(1, len(t)):
A_n = A_matrix(t[i - 1], f)
A_half = A_matrix(t[i] - dt / 2, f)
# Inverse calculation for intermediate step
inv_matrix = inv(np.identity(2) - A_half * dt / 4)
f_half = inv_matrix @ ((np.identity(2) + A_n * dt / 4) @ f)
A_next = A_matrix(t[i], f_half)
# Inverse calculation for final step
inv_matrix = inv(3 * np.identity(2) - A_next * dt)
f_next = inv_matrix @ (4 * f_half - f)
f = f_next
f_values.append(f)
return np.array(f_values)
# Fully-iterated Picard TBDF-2 scheme
def picard_TBDF2(t, dt, tol=1e-8, max_iter=100):
# Initial conditions
f = np.array([N0, C0])
# Storing the solution
f_values = [f]
for i in range(1, len(t)):
f_prev = f_values[-1]
f_half = f_prev
for _ in range(max(2, max_iter)):
f_half_prev = f_half
A_half = A_matrix(t[i] - dt / 2, f_half_prev)
inv_matrix = inv(np.identity(2) - A_half * dt / 4)
f_half = inv_matrix @ ((np.identity(2) + A_half * dt / 4) @ f_prev)
if norm(f_half - f_half_prev) / norm(f_half) < tol:
break
A_next = A_matrix(t[i], f_half)
inv_matrix = inv(3 * np.identity(2) - A_next * dt)
f_next = inv_matrix @ (4 * f_half - f_prev)
f = f_next
f_values.append(f)
return np.array(f_values)
# Time range for t0 = 0.001 s with different time steps
timesteps = [5e-5, 2.5e-5, 1.25e-5]
solutions_lagged = {}
solutions_picard = {}
for dt in timesteps:
t = np.arange(0, 0.001 + dt, dt)
solutions_lagged[dt] = lagged_TBDF2(t, dt)
solutions_picard[dt] = picard_TBDF2(t, dt)
# Assuming that we are interested in the solution at t = 0.001 s, we extract these
N_at_t0_lagged = {dt: sol[-1, 0] for dt, sol in solutions_lagged.items()}
N_at_t0_picard = {dt: sol[-1, 0] for dt, sol in solutions_picard.items()}
# Print the solutions for N at t = 0.001 s for both methods and all time steps
print("Lagged Trapezoidal/BDF-2 Scheme:")
for dt, N in N_at_t0_lagged.items():
print(f"Delta t = {dt:.1e}, N = {N:.6f}")
print("\nFully-Iterated Picard Trapezoidal/BDF-2 Scheme:")
for dt, N in N_at_t0_picard.items():
print(f"Delta t = {dt:.1e}, N = {N:.6f}")
# Calculate the convergence ratio and the estimated order of accuracy
def convergence_order(N_values):
ratios = []
orders = []
dt_keys = sorted(N_values.keys())
for i in range(len(dt_keys)-2):
N1, N2, N3 = N_values[dt_keys[i]], N_values[dt_keys[i+1]], N_values[dt_keys[i+2]]
ratio = (N1 - N2) / (N2 - N3)
order = np.log(ratio) / np.log(2)
ratios.append(ratio)
orders.append(order)
return ratios, orders
ratios_lagged, orders_lagged = convergence_order(N_at_t0_lagged)
ratios_picard, orders_picard = convergence_order(N_at_t0_picard)
print("\nConvergence Ratios and Orders of Accuracy for Lagged Scheme:")
for dt, ratio, order in zip(timesteps[:-2], ratios_lagged, orders_lagged):
print(f"For Delta t = {dt:.1e}, Ratio: {ratio:.2f}, Order: {order:.2f}")
print("\nConvergence Ratios and Orders of Accuracy for Picard Scheme:")
for dt, ratio, order in zip(timesteps[:-2], ratios_picard, orders_picard):
print(f"For Delta t = {dt:.1e}, Ratio: {ratio:.2f}, Order: {order:.2f}")
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import inv
# Constants given in the problem
beta = 0.0075
lambda_ = 0.08
Lambda_ = 6e-5
N0 = 1
C0 = beta * N0 / (Lambda_ * lambda_)
alpha_with_feedback = 2.0 * beta
alpha_no_feedback = 0.0
Nref = 1.0
rho0_with_feedback = -6.67 * beta + alpha_with_feedback * N0 / Nref
rho0_no_feedback = -6.67 * beta
# Reactivity function with and without feedback
def reactivity_with_feedback(t, N):
return rho0_with_feedback - alpha_with_feedback * N / Nref
def reactivity_no_feedback(t, N):
return rho0_no_feedback
# Define the system of equations
def point_kinetics(N, C, rho):
dN_dt = (rho - beta) / Lambda_ * N + lambda_ * C
dC_dt = beta / Lambda_ * N - lambda_ * C
return np.array([dN_dt, dC_dt])
# Fully-iterated Picard TBDF-2 scheme
def picard_TBDF2(t, dt, reactivity_func, tol=1e-8, max_iter=100):
# Initial conditions
f = np.array([N0, C0])
# Storing the solution
f_values = [f]
for i in range(1, len(t)):
f_prev = f_values[-1]
f_half = f_prev
for _ in range(max(2, max_iter)):
f_half_prev = f_half
rho = reactivity_func(t[i] - dt / 2, f_half_prev[0])
A_half = A_matrix(t[i] - dt / 2, f_half_prev, rho)
inv_matrix = inv(np.identity(2) - A_half * dt / 4)
f_half = inv_matrix @ ((np.identity(2) + A_half * dt / 4) @ f_prev)
if norm(f_half - f_half_prev) / norm(f_half) < tol:
break
rho = reactivity_func(t[i], f_half[0])
A_next = A_matrix(t[i], f_half, rho)
inv_matrix = inv(3 * np.identity(2) - A_next * dt)
f_next = inv_matrix @ (4 * f_half - f_prev)
f = f_next
f_values.append(f)
return np.array(f_values)
# A matrix function updated to include reactivity
def A_matrix(t, f, rho):
return np.array([[(rho - beta) / Lambda_, lambda_], [beta / Lambda_, -lambda_]])
# The norm function as defined in the problem
def norm(f):
return np.sqrt(f[0] ** 2 + f[1] ** 2)
# Time step and range for the solution
dt = 5e-5
t = np.arange(0, 0.001 + dt, dt)
# Solve the problem with and without feedback
solution_no_feedback = picard_TBDF2(t, dt, reactivity_no_feedback)
solution_with_feedback = picard_TBDF2(t, dt, reactivity_with_feedback)
# Plot comparison
plt.figure(figsize=(12, 6))
plt.plot(t, solution_no_feedback[:, 0], label='No Feedback', marker='o')
plt.plot(t, solution_with_feedback[:, 0], label='With Feedback', marker='x')
plt.xlabel('Time (s)')
plt.ylabel('Neutron Density')
plt.title('Comparison of Neutron Density with and without Feedback')
plt.legend()
plt.grid(True)
plt.show()
# Function to calculate the relative error between two solutions
def relative_error(solution1, solution2):
return np.abs((solution1 - solution2) / solution1)
# Perform a convergence check for the fully-iterated scheme
# We will check if the solution is converging as we decrease the time step
convergence_errors = []
for i in range(len(timesteps) - 1):
dt1, dt2 = timesteps[i], timesteps[i+1]
# Compare the solution at t=0.001s for two consecutive time steps
N1, N2 = solutions_picard[dt1][-1, 0], solutions_picard[dt2][-1, 0]
error = relative_error(N1, N2)
convergence_errors.append(error)
print(f'Convergence error between dt={dt1:.1e} and dt={dt2:.1e}: {error:.2e}')
# Check for the expected order of accuracy
# We expect the error to reduce by a factor of 4 (2^2) if the method is second order accurate
expected_reduction = 4
for i in range(len(convergence_errors) - 1):
reduction_factor = convergence_errors[i] / convergence_errors[i+1]
print(f'Reduction factor between dt={timesteps[i]:.1e} and dt={timesteps[i+1]:.1e}: '
f'{reduction_factor:.2f} (expected: {expected_reduction})') |
import coffeImage from "../assets/coffe.png";
import { AdvantagePoints, AdvantagePointsProps } from "./AdvantagePoints";
import { Coffes } from "./Coffes";
import { Header } from "./Header";
const advantages: AdvantagePointsProps[] = [
{
text: "Compra simples e segura",
icon: "shopping",
background: "bg-yellow-dark",
},
{
text: "Embalagem mantém café intacto",
icon: "package",
background: "bg-base-text",
},
{
text: "Entrega rápida e rastreada",
icon: "timer",
background: "bg-yellow",
},
{
text: "O café chega fresquinho até você",
icon: "coffee",
background: "bg-purple-dark",
},
];
export function Home() {
return (
<div className="bg-background">
<Header />
<div className="flex items-center justify-center gap-14 px-40 py-24 bg-backroundHome bg-no-repeat bg-cover w-full max-lg:flex-col max-sm:px-0">
<div className="flex flex-col w-[588px] gap-16 max-sm:w-4/5 max-sm:px-5">
<div className="flex flex-col gap-4">
<h1 className="text-5xl font-header ">
Encontre o café perfeito para qualquer hora do dia
</h1>
<p className="font-text text-xl">
Com o coffe delivery você recebe seu café onde estiver, a qualquer
hora
</p>
</div>
<div className="grid grid-cols-2 gap-5 max-sm:grid-cols-1 ">
{advantages.map((advantage) => {
return (
<AdvantagePoints
key={advantage.icon}
text={advantage.text}
background={advantage.background}
icon={advantage.icon}
/>
);
})}
</div>
</div>
<div className="max-sm:hidden">
<img src={coffeImage} alt="" />
</div>
</div>
<h1 className="px-40 text-3xl font-header max-sm:text-center max-sm:px-0">
Nossos cafés
</h1>
<Coffes />
</div>
);
} |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible_collections.manala.roles.tests.unit.compat import unittest
from ansible.plugins.loader import lookup_loader
from ansible.errors import AnsibleError
class Test(unittest.TestCase):
def setUp(self):
self.maxDiff = None
self.lookup = lookup_loader.get('manala.roles.deploy_writable_dirs')
def test_not_dict(self):
with self.assertRaises(AnsibleError) as error:
self.lookup.run([[NotImplemented], {}])
self.assertEqual("Expected a dict but was a <class 'NotImplementedType'>", str(error.exception))
def test_missing_index(self):
with self.assertRaises(AnsibleError) as error:
self.lookup.run([[{'foo': 'bar'}], {}])
self.assertEqual('Missing "dir" key', str(error.exception))
def test_merge(self):
self.assertListEqual([
{'dir': 'foo', '_discriminator': 'bar'},
], self.lookup.run([
[
{'dir': 'foo', '_discriminator': 'foo'},
{'dir': 'foo', '_discriminator': 'bar'},
],
{}
]))
def test_flatten(self):
self.assertListEqual([
{'dir': 'foo'},
{'dir': 'bar'},
], self.lookup.run([
[
{'dir': 'foo'},
[
{'dir': 'bar'},
],
],
{}
]))
def test_short_syntax(self):
self.assertListEqual([
{'dir': 'foo'},
], self.lookup.run([
[
'foo',
],
{}
]))
def test_default(self):
self.assertListEqual([
{'dir': 'foo', 'bar': 'bar'},
], self.lookup.run([
[
{'dir': 'foo'},
],
{
'bar': 'bar'
}
])) |
import './ToDo.css';
import { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
//MUI
import List from '@mui/material/List';
import Tooltip from '@mui/material/Tooltip';
//components
import ToDoItem from "./ToDoItem";
function ToDo () {
const dispatch = useDispatch();
const user_id = useSelector(store => store.user.id);
//hides or shows input
const [toggleInput, setToggleInput] = useState(false);
const [toDoInput, setToDoInput] = useState('');
const taskList = useSelector(store => store.tasks);
//adds task item to DB
const addItem = (e) => {
e.preventDefault();
console.log(toDoInput);
dispatch({ type: 'ADD_TASK', payload: {user: user_id, task: toDoInput} });
setToDoInput('');
setToggleInput(!toggleInput);
}
return(
<div className="widget_container todo_container">
<div className="todo_header">
<h4 className="todo_text">Tasks:</h4>
<Tooltip title="Add Task" placement="bottom-end">
<button className="widget_button" onClick={() => setToggleInput(true)}>+</button>
</Tooltip>
</div>
<List className="todo_list">
{toggleInput === true && //if "+" button is pressed, show input
<form onSubmit={(e) => addItem(e)} className="todo_input_section">
<input type="text"
className="todo_input"
value={toDoInput}
onChange={(e) => setToDoInput(e.target.value)}>
</input>
</form>}
{taskList ? taskList.map((item, i) =>
<ToDoItem key={i} task={item} userID={user_id}/>) : ''}
</List>
</div>
)
}
export default ToDo; |
#include <Arduino.h>
#include <PubSubClient.h>
#include <Dps310.h>
#include <Wire.h>
#include "WiFiClientSecure.h"
#include "certificates.h"
const char* ssid = "-"; // your network SSID (name of wifi network)
const char* password = "-"; // your network password
//const char* mqtt_server = "clusterunifiednamespace.sytes.net";
const char* mqtt_server = "unifiednamespace.sytes.net"; //Adress for your Mosquitto broker server, it must be the same adress that you set in Mosquitto.csr CN field
int port = 8883; //Port to your Mosquitto broker server. Dont forget to forward it in your router for remote access
char msg[256];
WiFiClientSecure client;
PubSubClient mqtt_client(client);
#define SDA_PIN 14
#define SCL_PIN 13
Dps310 Dps310PressureSensor = Dps310();
unsigned long lastMsg = 0;
int16_t ret;
byte tempConfig = 49;
void reconnect() {
// Loop until we're reconnected
while (!mqtt_client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (mqtt_client.connect("ESP32 UNS IOTT")) {
Serial.println("connected");
// ... and resubscribe
mqtt_client.subscribe("UNS/Hvl/IIoT/Commands/TemperatureUnits");
} else {
mqtt_client.print("failed, rc=");
mqtt_client.print(mqtt_client.state());
mqtt_client.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void initializeDPS310(){
Wire.begin(static_cast<int>(SDA_PIN),static_cast<int>(SCL_PIN), static_cast<uint32_t>(4000)); //sda scl config, static cast dude to bug.
Dps310PressureSensor.begin(Wire);
//temperature measure rate (value from 0 to 7)
//2^temp_mr temperature measurement results per second
int16_t temp_mr = 2;
//temperature oversampling rate (value from 0 to 7)
//2^temp_osr internal temperature measurements per result
//A higher value increases precision
int16_t temp_osr = 2;
//pressure measure rate (value from 0 to 7)
//2^prs_mr pressure measurement results per second
int16_t prs_mr = 2;
//pressure oversampling rate (value from 0 to 7)
//2^prs_osr internal pressure measurements per result
//A higher value increases precision
int16_t prs_osr = 2;
//startMeasureBothCont enables background mode
//temperature and pressure ar measured automatically
//High precision and hgh measure rates at the same time are not available.
//Consult Datasheet (or trial and error) for more information
int16_t ret = Dps310PressureSensor.startMeasureBothCont(temp_mr, temp_osr, prs_mr, prs_osr);
}
void callback(char* topic, byte* payload, unsigned int length) {
tempConfig = payload[0];
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print(payload[i]);
}
Serial.print("\ttempConfig set to: ");
Serial.print(tempConfig);
Serial.println();
}
float average (float * array, int len) // assuming array is int.
{
long sum = 0L ; // sum will be larger than an item, long for safety.
for (int i = 0 ; i < len ; i++)
sum += array [i] ;
return ((float) sum) / len ; // average will be fractional, so float may be appropriate.
}
void setup() {
Serial.begin(115200);
initializeDPS310();
delay(100);
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
// attempt to connect to Wifi network:
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
// wait 1 second for re-trying
delay(1000);
}
Serial.print("Connected to ");
Serial.println(ssid);
//Set up the certificates and keys
client.setCACert(CA_cert); //Root CA certificate
client.setCertificate(ESP_cert); //for client verification if the require_certificate is set to true in the mosquitto broker config
client.setPrivateKey(ESP_key); //for client verification if the require_certificate is set to true in the mosquitto broker config
mqtt_client.setServer(mqtt_server, port);
mqtt_client.setCallback(callback);
}
void loop() {
uint8_t pressureCount = 20;
float pressure[pressureCount];
uint8_t temperatureCount = 20;
float temperature[temperatureCount];
unsigned long now = millis();
if (!mqtt_client.connected()) {
reconnect();
}
mqtt_client.loop();
if (now - lastMsg > 2000) {
lastMsg = now;
int16_t ret = Dps310PressureSensor.getContResults(temperature, temperatureCount, pressure, pressureCount);
if (ret == 0){
if(tempConfig == 49){
snprintf (msg, 256, "{ \"Timestamp\" : \"11:11:11\", \"Temperature\" : { \"value\" : %lg, \"units\" : \"degC\" }, \"Pressure\" : { \"value\" : %lg, \"units\" : \"Pascal\" } }", temperature[1],pressure[1]);
}
else if(tempConfig == 48){
snprintf (msg, 256, "{ \"Timestamp\" : \"11:11:11\", \"Temperature\" : { \"value\" : %lg, \"units\" : \"F\" }, \"Pressure\" : { \"value\" : %lg, \"units\" : \"Pascal\" } }", ((temperature[1]*1.8)+32),pressure[1]);
}
Serial.println(msg);
mqtt_client.publish("UNS/Hvl/IIoT/Status/Measurements", msg, true);
}
}
} |
import {
HttpException,
HttpStatus,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { UsersService } from 'src/users/users.service';
import { CreateStudentDto } from './dto/create-student.dto';
import { UpdateStudentDto } from './dto/update-student.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Connection, Repository } from 'typeorm';
import { Student } from './entities/student.entity';
import { Sport } from 'src/sports/entities/sport.entity';
import { SportsService } from 'src/sports/sports.service';
@Injectable()
export class StudentsService {
constructor(
@InjectRepository(Student)
private studentsRepository: Repository<Student>,
private usersService: UsersService,
private sportsService: SportsService,
private connection: Connection,
) {}
async create(createStudentDto: CreateStudentDto) {
const {
age,
weight,
height,
gender,
goals,
sports,
email,
name,
avatar_url,
} = createStudentDto;
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const user = await this.usersService.create({
email,
gender,
name,
age,
avatar_url,
});
const userSports = new Array<Sport>();
for (let i = 0; i < sports.length; i++) {
const newSport = await this.sportsService.findOne(sports[i]);
userSports.push(newSport);
}
const student = new Student(weight, height, goals);
student.user = user;
student.sports = [...userSports];
return this.studentsRepository.save(student);
} catch (error) {
await queryRunner.rollbackTransaction();
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
} finally {
await queryRunner.release();
}
}
findAll() {
return this.studentsRepository.find();
}
findOne(id: string) {
return this.studentsRepository.findOne(id);
}
async findOneByEmail(email: string) {
const user = await this.usersService.findOneByEmail(email);
return this.studentsRepository.findOne({ user: user });
}
async update(id: string, updateStudentDto: UpdateStudentDto) {
const { age, weight, height, gender, goals, sports } = updateStudentDto;
let student = await this.studentsRepository.findOne(id);
if (!student) {
throw new NotFoundException('No student found with the informed id.');
}
const userSports = new Array<Sport>();
for (let i = 0; i < sports.length; i++) {
const newSport = await this.sportsService.findOne(sports[i]);
userSports.push(newSport);
}
await this.usersService.update(student.user.id, {
gender,
age,
});
student = {
...student,
weight,
height,
goals,
sports: [...userSports],
};
return this.studentsRepository.save(student);
}
async remove(id: string) {
const student = await this.findOne(id);
if (!student) {
throw new NotFoundException('Student not found.');
}
const userToRemove = student.user;
await this.studentsRepository.remove(student);
await this.usersService.remove(userToRemove.id);
return { deleted: true };
}
} |
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';
import { UserEntity } from 'src/user/entities/user.entity';
@Injectable()
export class PostgresConfigService implements TypeOrmOptionsFactory {
constructor(private readonly configService: ConfigService) {}
createTypeOrmOptions(): TypeOrmModuleOptions {
return {
type: 'postgres',
host: this.configService.get<string>('DB_HOST'),
port: this.configService.get<number>('DB_PORT'),
username: this.configService.get<string>('DB_USERNAME'),
password: this.configService.get<string>('DB_PASSWORD'),
database: this.configService.get<string>('DB_NAME'),
entities: [UserEntity],
synchronize: true,
};
}
} |
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import redirect
import json
from rest_framework import status
from .serializers import *
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from django.http import JsonResponse
from .models import *
from .serializers import *
from rest_framework.viewsets import ModelViewSet
class BearerTokenAuthentication(TokenAuthentication):
keyword = 'Bearer'
class RegisterUsers(APIView):
def get(self, request):
return render(request,"register.html")
def post(self, request):
serializer = UserSerializer(data=request.data)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.save()
return render(request,'login.html')
class LoginUsers(APIView):
def get(self,request):
return render(request,"login.html")
def post(self,request):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key}, status=status.HTTP_200_OK)
#return redirect('success')
#return render(request,"success.html",{'token': token.key})
else:
return render(request, 'login.html')
# Inside views.py of your Django app
from django.shortcuts import render
import requests
class MovieReview(APIView):
def get(self,request):
print("oooooooooooooooooo")
return render(request,"success.html")
def post(self, request):
api_key = "961f8b8e"
title = request.data.get("title")
print(title)
if not title:
return JsonResponse({'error_message': 'Please provide a movie title'}, status=400)
url = f"http://www.omdbapi.com/?t={title}&apikey={api_key}"
response = requests.get(url)
if response.status_code == 200:
reviews = MovieRev.objects.filter(movie_title=title).values('review_text', 'user__username', 'rating')
movies = response.json()
reviews_json = list(reviews)
print(reviews_json)
return JsonResponse({'movies':movies,'reviews':reviews_json})
else:
return JsonResponse({'error_message': 'Failed to fetch movie details'}, status=500)
from .models import MovieRev
class Save_review(APIView):
authentication_classes = [BearerTokenAuthentication]
permission_classes = [IsAuthenticated]
def post(self,request):
movie_title = request.data.get('movie_title')
review_text = request.data.get('review_text')
rating = request.data.get('rating')
user = request.user
print(movie_title,user)
# Create a new MovieReview object and save it to the database
movie_review = MovieRev.objects.create(
user=user,
movie_title=movie_title,
review_text=review_text,
rating=rating
)
return JsonResponse({'message': 'Review saved successfully'}) |
require 'rails_helper'
RSpec.describe VpnApiResponse do
subject(:service) { described_class.new(response) }
let(:response_body) { {} }
describe '#ip' do
let(:ip_address) { Faker::Internet.ip_v4_address }
let(:response_body) { { 'ip' => ip_address } }
let(:response) { instance_double(Net::HTTPSuccess, code: '200', body: response_body.to_json) }
it 'returns the IP address' do
expect(service.ip).to eq(ip_address)
end
end
describe '#country' do
let(:response_body) { { 'location' => { 'country' => 'Spain' } } }
let(:response) { instance_double(Net::HTTPSuccess, code: '200', body: response_body.to_json) }
it 'returns the country' do
expect(service.country).to eq('Spain')
end
end
describe '#proxy' do
context 'when proxy information is available' do
let(:response_body) { { 'security' => { 'proxy' => true } } }
let(:response) { instance_double(Net::HTTPResponse, code: 200, body: response_body.to_json) }
it 'returns true' do
expect(service.proxy).to be_truthy
end
end
context 'when proxy information is not available' do
let(:response) { instance_double(Net::HTTPResponse, code: 200, body: response_body.to_json) }
it 'returns false' do
expect(service.proxy).to be_falsey
end
end
end
describe '#vpn' do
context 'when VPN information is available' do
let(:response_body) { { 'security' => { 'vpn' => true } } }
let(:response) { instance_double(Net::HTTPResponse, code: 200, body: response_body.to_json) }
it 'returns true' do
expect(service.vpn).to be_truthy
end
end
context 'when VPN information is not available' do
let(:response) { instance_double(Net::HTTPResponse, code: '200', body: response_body.to_json) }
it 'returns false' do
expect(service.vpn).to be_falsey
end
end
end
end |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/output.css" rel="stylesheet">
<title>Deepgram x {{ event.title }}</title>
</head>
<body class="bg-darkCharcoal text-white">
<header class="bg-fireEngine p-8 text-center">
<div class="max-w-2xl mx-auto">
<h1 class="text-2xl font-bold">{{ event.title }} Post-Event Management</h1>
<p>This pane is intended for organizers/producers only.</p>
<p>Smaller files = quicker transcripts. We accept video or audio files.</p>
</div>
</header>
<div class="bg-gray-200 m-6 p-6 text-darkCharcoal rounded">
<form class="grid grid-cols-2 gap-x-6 gap-y-4">
<input id="passphrase" type="password" name="passphrase" placeholder="Key" required>
<input id="file" type="file" name="file" required>
<input type="submit" value="Get transcription" class="col-span-2">
</form>
</div>
<div id="message" class="text-center"></div>
<script>
const form = document.querySelector('form')
const fileInput = document.getElementById('file')
const passphrase = document.getElementById('passphrase')
const message = document.getElementById('message')
let file
handleAudioFile = e => {
file = e.target.files
for (let i = 0; i <= file.length - 1; i++) { file = file[i] }
}
fileInput.addEventListener('change', handleAudioFile)
form.addEventListener('submit', e => {
e.preventDefault()
if(!file) return alert('You must select a file')
const formData = new FormData()
formData.append('file', file)
formData.append('key', passphrase.value)
message.textContent = 'Uploading file & generating transcript...'
fetch(location.pathname + '/transcribe', {
method: 'post',
body: formData,
})
.then(r => r.json())
.then(res => {
if(res.error) return alert(res.error)
stringToDownload(res.files.srt, `${file.name}.srt`)
stringToDownload(res.files.webvtt, `${file.name}.vtt`)
stringToDownload(res.transcript, `${file.name}.txt`)
message.textContent = 'Downloading output files for ' + file.name
})
.catch(err => console.log('Error occurred', err))
})
function stringToDownload(string, filename) {
const file = new File([string], filename, { type: 'text/plain' })
const link = document.createElement('a')
const url = URL.createObjectURL(file)
link.href = url
link.download = file.name
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(url)
}
</script>
</body>
</html> |
import React, { useState, useEffect } from "react";
import styles from "./rc.module.css"; // Import CSS file for styling
import img8 from "../pictures/user1.png";
import axios from "axios";
function StarRating() {
const [rating, setRating] = useState(0);
const [comment, setComment] = useState("");
const [comments, setComments] = useState([]);
const handleStarClick = (value) => {
setRating(value);
};
const handleCommentChange = (e) => {
setComment(e.target.value);
};
const handleSubmit = async (e) => {
e.preventDefault();
if (comment.trim() !== "") {
try {
await axios.post("http://localhost:8000/api/comments", {
rating,
comment,
});
setComment("");
setRating(0);
fetchComments();
} catch (error) {
console.error("Error submitting comment:", error);
}
}
};
const fetchComments = async () => {
try {
const response = await axios.get("http://localhost:8000/api/comments");
setComments(response.data);
} catch (error) {
console.error("Error fetching comments:", error);
}
};
useEffect(() => {
fetchComments();
}, []);
return (
<div>
<div>
<form onSubmit={handleSubmit}>
<div className={styles.starrating}>
{[1, 2, 3, 4, 5].map((value) => (
<span
key={value}
style={{
color: value <= rating ? "rgb(9, 192, 248)" : "gray",
left: "25px",
position: "relative",
}}
onClick={() => handleStarClick(value)}
>
★
</span>
))}
</div>
<div>
<label className={styles.Ratin}>Rating:</label>
<span className={styles.Ratinn}>{rating}</span>
</div>
<div>
<label className={styles.Review}>Review:</label>
<textarea
className={styles.text}
placeholder="Enter your Review..."
rows="3"
cols="50"
value={comment}
onChange={handleCommentChange}
/>
</div>
<button className={styles.submit} type="submit">
Submit
</button>
</form>
</div>
<div>
<ul className={styles.img}>
{comments.map((comment, index) => (
<img
key={index}
src={img8}
alt="Account"
className={styles.photo}
/>
))}
</ul>
<ul className={styles.comment}>
{comments.map((comment, index) => (
<li key={index} className={styles.commentt}>
<p className={styles.p}>{comment.comment}</p>
<span className={styles.span}>
{new Date(comment.createdAt).toLocaleDateString()}
</span>
</li>
))}
</ul>
</div>
</div>
);
}
export default StarRating; |
import pygame
from pygame.constants import QUIT, K_DOWN, K_UP, K_LEFT, K_RIGHT
import random
import os
pygame.init()
FPS = pygame.time.Clock()
HEIGHT = 800
WIDTH = 1200
FONT = pygame.font.SysFont('Courier New', 20)
COLOR_WHITE = (255, 255, 255)
COLOR_BLACK = (0, 0, 0)
COLOR_BLUE = (0, 0, 255)
COLOR_GREEN = (0, 255, 0)
main_display = pygame.display.set_mode((WIDTH, HEIGHT))
bg = pygame.transform.scale(pygame.image.load('background.png'), (WIDTH, HEIGHT))
bg_X1 = 0
bg_X2 = bg.get_width()
bg_move = 3
IMAGE_PATH = "Goose"
PLAYER_IMGS = os.listdir(IMAGE_PATH)
player_size = (20, 20)
player = pygame.image.load('player.png').convert_alpha() # pygame.Surface(50,50)
# player.fill(COLOR_BLACK)
player_rect = player.get_rect()
player_move_down = [0, 1]
player_move_right = [1, 0]
player_move_up = [0, -1]
player_move_left = [-4, 0]
playing = True
def create_enemy():
enemy_size = (30, 30)
enemy = pygame.image.load('enemy.png').convert_alpha()
# enemy.fill(COLOR_BLUE)
enemy_rect = pygame.Rect(WIDTH, random.randint(100, HEIGHT-100), *enemy_size)
enemy_move = [random.randint(-8, -4), 0]
return [enemy, enemy_rect, enemy_move]
def create_bonus():
bonus_size = (20, 20)
bonus = pygame.image.load('bonus.png').convert_alpha()
# bonus.fill(COLOR_GREEN)
bonus_rect = pygame.Rect(random.randint(100, WIDTH-100), 0, *bonus_size)
bonus_move = [0, random.randint(4, 8)]
return [bonus, bonus_rect, bonus_move]
CREATE_ENEMY = pygame.USEREVENT + 1
CREATE_BONUS = CREATE_ENEMY + 1
pygame.time.set_timer(CREATE_ENEMY, 1500)
pygame.time.set_timer(CREATE_BONUS, 2000)
CHANGE_IMAGE = pygame.USEREVENT + 3
pygame.time.set_timer(CHANGE_IMAGE, 150)
enemies = []
bonuses = []
score = 0
img_index = 0
player_rect.centery = HEIGHT // 2
while playing:
FPS.tick(120)
for event in pygame.event.get():
if event.type == QUIT:
playing = False
if event.type == CREATE_ENEMY:
enemies.append(create_enemy())
if event.type == CREATE_BONUS:
bonuses.append(create_bonus())
if event.type == CHANGE_IMAGE:
player = pygame.image.load(os.path.join(IMAGE_PATH, PLAYER_IMGS[img_index]))
img_index += 1
if img_index >= len(PLAYER_IMGS):
img_index = 0
bg_X1 -= bg_move
bg_X2 -= bg_move
if bg_X1 < -bg.get_width():
bg_X1 = bg.get_width()
if bg_X2 < -bg.get_width():
bg_X2 = bg.get_width()
main_display.blit(bg, (bg_X1, 0))
main_display.blit(bg, (bg_X2, 0))
keys = pygame.key.get_pressed()
if keys[K_DOWN] and player_rect.bottom < HEIGHT:
player_rect = player_rect.move(player_move_down)
if keys[K_RIGHT] and player_rect.right < WIDTH:
player_rect = player_rect.move(player_move_right)
if keys[K_UP] and player_rect.top > 0:
player_rect = player_rect.move(player_move_up)
if keys[K_LEFT] and player_rect.left > 0:
player_rect = player_rect.move(player_move_left)
for enemy in enemies:
enemy[1] = enemy[1].move(enemy[2])
main_display.blit(enemy[0], enemy[1])
if player_rect.colliderect(enemy[1]):
playing = False
for bonus in bonuses:
bonus[1] = bonus[1].move(bonus[2])
main_display.blit(bonus[0], bonus[1])
if player_rect.colliderect(bonus[1]):
score += 1
bonuses.pop(bonuses.index(bonus))
main_display.blit(FONT.render(str(score), True, COLOR_BLACK), (WIDTH - 50, 20))
main_display.blit(player, player_rect)
pygame.display.flip()
for enemy in enemies:
if enemy[1].left < 0:
enemies.pop(enemies.index(enemy))
for bonus in bonuses:
if bonus[1].bottom > HEIGHT:
bonuses.pop(bonuses.index(bonus))
# print(len(bonuses)) |
Title : Fundamentals of the *flutterbye*
Author : Michael Lowell Roberts
Copyright : (c) 2016, Michael Lowell Roberts
License : Apache License 2.0
Logo : True
[TITLE]
~ Center
[this document is an early work-in-progress.]{ :red }
~
# Scope
The purpose of this document is to informally specify, in concise terms[^concise-terms], the operational semantic called [flutterbye].
[^concise-terms]: Less so, if you're tempted to read the footnotes.
[flutterbye]: https://github.com/fmrl/flutterbye
# Overview
*flutterbye* is an operational semantic that resembles the actor model[^actor-model-help]; it is an intermediate representation of causality in a computer program.
[^actor-model-help]: For the purposes of understanding *flutterbye*, it is sufficient to understand [the actor model] to be an asynchronous message passing system, where message processors (i.e. *actors*) may have an associated state.
[the actor model]: http://en.wikipedia.org/wiki/Actor_model "Wikipedia: Actor Model"
We divide *flutterbye* into three primary components:
#. *storage*.
#. *fabric*.
#. *scheduler*.
## Storage
The storage component must conform to the semantics of a mutable key-value store.
## Fabric
The *fabric* is the portion of *flutterbye* that resembles the actor model. *Regions* correspond to actors and *effects* correspond to messages.
We reason about computer programs modeled using *regions* and *effects* as if the program were a distributed system[^as-if-distributed].
[^as-if-distributed]: Another way to think of actor systems is that they are the application of distributed programming techniques outside of the context of distributed programming.
### Effects
*Effects* represent what is normally referred to as a [side-effect] in computer science.
[side-effect]: https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29 "Wikipedia: Side effect (Computer Science)"
Effects are both produced and consumed by regions, as actors would produce and consume messages in an actor system.
An effect ($E$) is defined as follows:
~ Math
E=\left(I_R, x\right)
~
~ Center
| ------ | -------------------- |
| Symbol | Description |
| -------| -------------------- |
| $I_R$ | recipient region |
| $x$ | payload (undefined) |
| ------ | -------------------- |
{ .booktable }
~
### Regions
A *region* ($R$) is specified as follows:
~ Math
R=\left(I_R, T_c, S\right)
~
~ Center
| ------ | -------------------------- |
| Symbol | Description |
| -------| -------------------------- |
| $I_R$ | identity of the region $R$ |
| $T_c$ | causal transform |
| $S$ | state of region $R$ |
| ------ | -------------------------- |
{ .booktable }
~
#### Import Regions
*Import regions* represent input to the program. They are modeled as effect generators.
#### Export Regions
*Export regions* represent program output. They are modeled as logs with an undefined record schema.
#### Region Classes
A *region class* describes a group of regions that share a common causal transform (i.e. only differing in identity and state).
#### Region Modules
A collection of regions that include a single import region and a single export region are referred to as region modules. Region modules import and export effects exclusively.
#### Region Refinement
A region may be substituted for a region module, provided that the module exhibits behavior that correctly mimics the region it replaces. This substitution is called *region refinement*.
A placeholder region whose purpose is to serve as a site for refinement is called an *abstract region*.
Whether a region module serves as a correct refinement for a given abstract region should[^refinement-wip] be verifiable with a software verification tool such as [F*][fstar] or [Dafny].
[^refinement-wip]: We hope to turn this *should be verifiable* into an *is verifiable*.
[fstar]: http://www.fstar-lang.org/ "F* Home Page"
[Dafny]: http://research.microsoft.com/en-us/projects/dafny/ "Dafny Home Page"
### Causal Transform
The causal transform is a [total function] that expresses what would happen if the program were to advance one step forward.
[total function]: http://en.wikipedia.org/wiki/Partial_function#Total_function "Wikipedia: Total Function"
~ Math
T_c:\left(I_R, C, S\right)\rightarrow\left(S', \left\{E_1...E_n\right\}\right)
~
~ Center
| -------------------------- | ----------------------------- |
| Symbol | Description |
| -------------------------- | ----------------------------- |
| $T_c$ | causal transform |
| $I_R$ | identity of the region $R$ |
| $C$ | input effect (or *cause*) |
| $S$ | state of region $R$ |
| $S'$ | successor state of region $R$ |
| $\left\{E_1...E_n\right\}$ | multiset of output effects |
| -------------------------- | ----------------------------- |
{ .booktable }
~
The causal transform does not advance the state of the program. Rather, the scheduler uses the output of a region's causal transform to advance the state of the program by one step.
### Causal Threads
*Causal threads* are the paths of dependent calculations that are represented by stringing causal transforms together through the transmission of effects. A thread remains stable when a transform produces a single effect. A thread splits into multiple threads when a transform produces more than one effect. A thread terminates when a causal transform produces no effects.
Together, these threads describe the *causal fabric*, which serves as an exact specification of the causality in a computer program. The fabric also describes the maximum amount of concurrency a program may exhibit.
## Scheduler
The scheduler multiplexes causal threads onto either one thread or a thread pool. It does this by advancing the system one or more steps at a time. A full step consists of:
#. Retrieve the actor's state from storage.
#. Apply the actor's causal transform to the actor's state.
#. Replace the actor's previous state in storage with its new state.
#. Schedule new effects to be processed at a later time.
Causal transforms must be applied occur in a time order that conforms to a [topological sort]. Note that topological sort is a partial sort a
[topological sort]: https://en.wikipedia.org/wiki/Topological_sorting "Wikipedia: Topological Sort"
The schedule must fairly schedule effects. |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%-- <%@ taglib uri="http://www.springframework.org/security/tags"
prefix="sec"%> --%>
<jsp:include page="../includes/header_.jsp" />
<!-- Home -->
<div class="home">
<div class="home_background_container prlx_parent">
<div class="home_background prlx" style="background-image:url(${pageContext.request.contextPath}/resources/images/news_background.jpg)"></div>
</div>
</div>
<!-- News -->
<div class="news">
<div class="container">
<!-- 게시판 -->
<div class="container-fluid">
<div class="row">
<div style="width: 800px; margin:0 auto">
<div class="">
<div class="mb-4 text-warning">
<c:if test="${pageMaker.cri.category != 2}">
<h1>공지사항</h1>
</c:if>
<c:if test="${pageMaker.cri.category == 2}">
<h1>Q&A</h1>
</c:if>
</div>
<hr>
<c:if test="${pageMaker.cri.category != 2}">
<c:forEach items="${list}" var="board">
<div class="mt-3">
<div class="row pl-5">
<div class="col-md-6">
<h4>
<a class="text-dark" href='${pageContext.request.contextPath}/board/get${pageMaker.cri.listLink}&bno=${board.bno}'>
<c:out value="${board.title}"/>
</a>
</h4>
</div>
<div class="col-md-2"><c:out value="${board.writer}"/></div>
<div class="col-md-2"><fmt:formatDate value="${board.regDate}" /></div>
<div class="col-md-2">조회수 ${board.hitCount}</div>
</div>
</div>
<hr>
</c:forEach>
</c:if>
<c:if test="${pageMaker.cri.category == 2}">
<c:forEach items="${list}" var="board">
<div class="mt-3 " >
<div class="row pl-4">
<div class="col-md-6 d-flex ${board.parentNo == 0 ? '' : 'pl-5'}">
<c:if test="${board.parentNo != 0}">
<i class="fas fa-share fa-flip-vertical fa-md mb-3 mr-2"></i>
</c:if>
<c:if test="${board.parentNo == 0}"><div class="ml-3 pl-1"></div></c:if>
<h4>
<a class="text-dark" href='${pageContext.request.contextPath}/board/get${pageMaker.cri.listLink}&bno=${board.bno}'>
<c:out value="${board.title}"/>
</a>
</h4>
</div>
<div class="col-md-2"><c:out value="${board.writer}"/></div>
<div class="col-md-2"><fmt:formatDate value="${board.regDate}" /></div>
<div class="col-md-2">조회수 ${board.hitCount}</div>
</div>
</div>
<hr>
</c:forEach>
</c:if>
</div>
<div class="col-12 text-right">
<c:if test="${memberAuth ne 'ROLE_ADMIN'}">
<c:set var="adm" value="0" />
</c:if>
<c:if test="${memberAuth eq 'ROLE_ADMIN'}">
<c:set var="adm" value="1" />
</c:if>
<c:if test="${ (adm == 1 && pageMaker.cri.category == 1 ) || (pageMaker.cri.category != 1)}">
<a href="${pageContext.request.contextPath}/board/register?category=${pageMaker.cri.category}"id='regBtn' class="write btn btn-sm btn-outline-warning">글쓰기</a>
</c:if>
</div>
<!-- modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="myModalLabel">작성 확인</h5>
</div>
<div class="modal-body">처리가 완료되었습니다.</div>
<div class="modal-footer">
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</div>
</div>
<!-- 하단 페이징 -->
<nav class="d-flex justify-content-center mt-1" >
<ul class="pagination" style="display: inline-flex;">
<c:if test="${pageMaker.cri.category == 1}">
<c:if test="${pageMaker1.prev}">
<li class="paginate_button previous">
<a class="page-link" href="list${pageMaker1.cri.listLink2}&pageNum=${pageMaker1.startPage -1}">Previous</a>
</li>
</c:if>
<c:forEach begin="${pageMaker1.startPage}" end="${pageMaker1.endPage}" var="num">
<li class="page-item ${num == pageMaker1.cri.pageNum ? 'active' : ''}">
<a class="page-link" href="list${pageMaker1.cri.listLink2}&pageNum=${num}">${num}</a>
</li>
</c:forEach>
<c:if test="${pageMaker1.next}">
<li class="paginate_button next">
<a class="page-link" href="list${pageMaker1.cri.listLink2}&pageNum=${pageMaker1.endPage + 1}">Next</a>
</li>
</c:if>
</c:if>
<c:if test="${pageMaker.cri.category == 2}">
<c:if test="${pageMaker2.prev}">
<li class="paginate_button previous">
<a class="page-link" href="list${pageMaker2.cri.listLink2}&pageNum=${pageMaker2.startPage -1}">Previous</a>
</li>
</c:if>
<c:forEach begin="${pageMaker2.startPage}" end="${pageMaker2.endPage}" var="num">
<li class="page-item ${num == pageMaker2.cri.pageNum ? 'active' : ''}">
<a class="page-link" href="list${pageMaker2.cri.listLink2}&pageNum=${num}">${num}</a>
</li>
</c:forEach>
<c:if test="${pageMaker2.next}">
<li class="paginate_button next">
<a class="page-link" href="list${pageMaker2.cri.listLink2}&pageNum=${pageMaker2.endPage + 1}">Next</a>
</li>
</c:if>
</c:if>
</ul>
</nav>
<div id="dataTable_filter" class="dataTables_filter dataTables_length mb-4 mt-3" >
<form id="searchForm" class="form-inline">
<div class="col-12 d-flex justify-content-center">
<div class="row mt-2">
<select id="searchMenu" name="type" class="custom-select custom-select-sm mr-1" >
<option value="TWC"></option>
<option value="W">작성자</option>
<option value="T">제목</option>
<option value="C">내용</option>
</select>
<div class="input-group mb-1">
<input type="search" name="keyword" class="form-control col-10 form-control-sm mr-1" placeholder="" aria-controls="dataTable">
<div class="input-group-append">
<button class="btn btn-sm btn-outline-warning"><i class="fas fa-search"></i></button>
</div>
</div>
</div>
<input type="hidden" name="pageNum" value="${pageMaker.cri.pageNum}">
<input type="hidden" name="amount" value="${pageMaker.cri.amount}">
</div>
</form>
</div>
</div>
</div>
</div>
<!-- end -->
</div>
</div>
<jsp:include page="../includes/footer.jsp" />
<!-- 스크립트 -->
<script>
$(function(){
var result = '${result}';
checkModal(result);
/* 뒤로가기 처리 */
history.replaceState({},null,null);
function checkModal(result){
if(result === '' || history.state){
return;
}
if(parseInt(result)>0){
$(".modal-body").html("게시글 " + result + "번이 등록 되었습니다");
}
$("#myModal").modal("show");
}
});
</script> |
'use client'
import { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faDownload } from '@fortawesome/free-solid-svg-icons';
import axios from 'axios';
export default function Download(props:{Id:string}) {
const [isLoading, setIsLoading] = useState(false);
const handleDownload = async () => {
try {
// Set loading state
setIsLoading(true);
// Make API call to download the reports
const response = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/report/download?dept=${props.Id}`,{
responseType: 'blob', // Specify response type as blob
validateStatus: (status) => status >= 200 && status <= 500
});
// Check if the API call was successful (status code 200)
if (response.status === 200) {
// Trigger download
const blob = new Blob([response.data]);
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'reports.xlsx'; // Specify the desired filename
document.body.appendChild(a);
a.click();
// Clean up
window.URL.revokeObjectURL(url);
} else {
// Handle error response
console.error('Failed to download reports:', response.statusText);
}
} catch (error) {
console.error('Error downloading reports:', error);
} finally {
// Reset loading state
setIsLoading(false);
}
};
return (
<>
<button
onClick={handleDownload}
className={`absolute right-20 hidden md:block px-3 py-1 bg-white text-black text-sm rounded-md ${isLoading ? 'cursor-not-allowed' : 'cursor-pointer'}`}
disabled={isLoading}
>
{isLoading ? 'Downloading...' : 'Download Reports'}
</button>
<button className=' md:hidden' onClick={handleDownload}>
{/* <img src='/download.png'className='w-10 h-10' /> */}
<FontAwesomeIcon icon={faDownload} className='absolute right-16 mb-5 pb-5 h-5 w-5' />
</button>
</>
);
} |
package nc.liat6.frame.xml;
import nc.liat6.frame.xml.element.IXmlElement;
import nc.liat6.frame.xml.parser.BeanParser;
import nc.liat6.frame.xml.parser.XMLParser;
import nc.liat6.frame.xml.wrapper.XMLWrapper;
/**
* XML转换器,默认开启严格模式
* <p>
* 转换会遵循以下约定:
* <ul>
* <li>开启严格模式后,子节点为属性的,父节点设置type="bean"属性。</li>
* <li>子节点为数组的,父节点必须设置type="list"属性。</li>
* </ul>
* </p>
*
* @author 6tail
*
*/
public class XML{
/** 默认根节点 */
public static final String DEFAULT_ROOT_TAG = "data";
/** 可设置的全局根节点 */
public static String ROOT_TAG = DEFAULT_ROOT_TAG;
/** 是否极简(不缩进不换行)的默认设置 */
public static final boolean DEFAULT_TINY = true;
/** 是否极简(不缩进不换行)的全局设置 */
public static boolean TINY = DEFAULT_TINY;
/** 默认开启严格模式 */
public static final boolean DEFAULT_STRICT = true;
/** 是否开启严格模式的全局设置 */
public static boolean STRICT = DEFAULT_STRICT;
private XML(){}
/**
* 采用全局根节点,将对象转换为XML字符串
*
* @param o 对象
* @return XML字符串
*/
public static String toXML(Object o){
return toXML(o,TINY);
}
/**
* 采用全局根节点,将对象转换为XML字符串
*
* @param o 对象
* @param tiny 是否是极简(不缩进不换行)
* @return XML字符串
*/
public static String toXML(Object o,boolean tiny){
return toXML(o,tiny,ROOT_TAG);
}
/**
* 将对象转换为XML字符串
*
* @param o 对象
* @param tiny 是否是极简(不缩进不换行)
* @param rootTag 自定义根节点
* @return XML字符串
*/
public static String toXML(Object o,boolean tiny,String rootTag){
return toXML(o,tiny,rootTag,STRICT);
}
/**
* 将对象转换为XML字符串
*
* @param o 对象
* @param tiny 是否是极简(不缩进不换行)
* @param rootTag 自定义根节点
* @param strict 是否开启严格模式,开启后非数组父节点强制添加type="bean"属性
* @return XML字符串
*/
public static String toXML(Object o,boolean tiny,String rootTag,boolean strict){
StringBuilder s = new StringBuilder();
s.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
if(!tiny){
s.append("\r\n");
}
s.append(new XMLWrapper(tiny,strict).wrap(o,rootTag));
return s.toString();
}
/**
* 将XML字符串转换为对象,可能会丢失节点属性和部分注释
*
* @param s XML字符串
* @return 对象
*/
public static <T>T toBean(String s){
return toBean(fromXML(s));
}
/**
* 将XML转换为通用封装
*
* @param s XML字符串
* @return 对象
*/
public static IXmlElement fromXML(String s){
return new XMLParser().parse(s);
}
/**
* 将XML通用封装转换为对象,可能会丢失节点属性和部分注释
*
* @param xe
* @return
*/
public static <T>T toBean(IXmlElement xe){
return new BeanParser().parse(xe);
}
} |
#include "function_pointers.h"
#include <stdlib.h>
#include <stdio.h>
/**
* int_index - returns the index of the first element
* for which the cmp function does not return 0
* @array: array of integers
* @size: number of elements in array
* @cmp: pointer to the function int_index
* Return: index of first element
* that matches cmp, or -1 if none found
*/
int int_index(int *array, int size, int (*cmp)(int))
{
int i;
if (size <= 0 || array == NULL || cmp == NULL)
return (-1);
for (i = 0; i < size; i++)
{
if (cmp(array[i]))
return (i);
}
return (-1);
} |
from rest_framework import serializers
from django.contrib.auth.password_validation import validate_password
from user_profile.models import UserProfile
class UserRegistrationSerializer(serializers.ModelSerializer):
"""
Serializer for user registration.
Validates that the email is unique, passwords match, and the password
meets the required criteria.
"""
password = serializers.CharField(write_only=True, required=True,
validators=[validate_password])
password2 = serializers.CharField(write_only=True, required=True)
date_of_birth = serializers.DateField(
input_formats=["%Y/%m/%d", "%d/%m/%Y", "%m/%d/%Y"], required=False, allow_null=True)
class Meta:
model = UserProfile
fields = ('email', 'password', 'password2', 'first_name', 'last_name', 'date_of_birth')
def validate_email(self, value):
"""
Check that the email is unique.
:param value: The email to validate.
:return: The validated email.
:raises serializers.ValidationError: If the email is already in use.
"""
if UserProfile.objects.filter(email=value.lower()).exists():
raise serializers.ValidationError(
"A user with that email already exists.")
return value
def validate(self, attrs):
"""
Check that the two password fields match.
:param attrs: The validated data.
:return: The validated data.
:raises serializers.ValidationError: If the passwords do not match.
"""
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError({
"password": "Password fields didn't match."})
return attrs
def create(self, validated_data):
"""
Create a new user with the validated data.
:param validated_data: The data validated by the serializer.
:return: The newly created user.
"""
validated_data.pop('password2')
user = UserProfile.objects.create_user(**validated_data)
return user
class LoginSerializer(serializers.Serializer):
"""
Serializer for user login.
Validates that the credentials are entered correctly for login.
"""
email = serializers.EmailField(
required=True, max_length=254,
error_messages={'required': 'Please enter valid email address',
'blank': 'Please enter valid email address.'}
)
password = serializers.CharField(
required=True, max_length=128,
error_messages={'required': 'Please enter password',
'blank': 'Please enter password.'}
)
def validate_email(self, value):
"""
Converting email from request data to lowercase.
The email to validate.
:return: The validated email.
"""
value = value.lower()
return value
class UserSearchSerializer(serializers.ModelSerializer):
"""
Serializer for searching users by email or name.
"""
date_joined = serializers.DateTimeField(
format='%d/%m/%Y %H:%M:%S', required=False, allow_null=True)
date_of_birth = serializers.DateField(
format='%d/%m/%Y', required=False, allow_null=True)
class Meta:
model = UserProfile
fields = ('id', 'email', 'first_name', 'last_name', 'date_of_birth',
'date_joined', 'followers_count', 'request_count') |
import React, { useState } from "react";
import Form from "./components/form";
import "./App.scss";
import * as Yup from "yup";
interface Values {
time: string;
date: string;
reminder: string;
}
// ensure reminder is not empty
const valSchema: Yup.SchemaOf<Values> = Yup.object().shape({
time: Yup.string().required("required"),
date: Yup.string().required("required"),
reminder: Yup.string().required("required"),
});
const App = () => {
const [vals, setVals] = useState<Values>({
time: "",
date: "",
reminder: "",
});
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
// console.log(e.target.value);
setVals((prevState) => ({
...prevState,
[e.target.name]: e.target.value,
}));
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
// e.preventDefault();
console.log({ vals });
await fetch("http://localhost:3001/send", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify({ vals }),
})
.then((res) => res.json())
.then(async (res) => {
const resData = await res;
console.log(resData);
if (resData.status === "success") {
alert("Message Sent");
console.log("vals", vals);
} else if (resData.status === "fail") {
alert("Message failed to send");
}
})
.then(() => {
setVals({
time: "",
date: "",
reminder: "",
});
});
};
return (
<div className="page">
<h1 className="title">REMINDER</h1>
<Form
handleChange={handleChange}
handleSubmit={handleSubmit}
val={vals}
valSchema={valSchema}
/>
</div>
);
};
export default App; |
import React, { useState } from "react";
import "./Resister.css";
import {Link} from 'react-router-dom';
import resisterPic from '../../images/resister.jpg'
import axios from 'axios';
const Resister = () => {
const [resister_user,set_resister_user] = useState({name: '',username: '',email: '',password: ''})
const [inputErrors, set_input_errors] = useState({
name_error: '',
username_error: '',
email_error: '',
password_error: ''
})
const inputChange=(event)=>{
const {name,value} = event.target;
set_resister_user((predata)=>{
return {
...predata,
[name]: value
}
})
}
const inputErrorChange = (name,msg)=>{
set_input_errors((preData)=>{
return {
...preData,
[name]:msg
}
})
}
const formSubmit = async()=>{
let valid = inputValidation();
if(valid && emailValidation(resister_user.email)==true){
axios.post('/resister',resister_user, {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
}).then((response) => {
alert(response.data.msg)
if(response.data.done==true){
window.location='/login';
}
}).catch(function (error) {
console.log(error);
})
}
}
function inputValidation(){
set_input_errors({
name_error: '',
username_error: '',
email_error: '',
password_error: ''
})
let validation=true;
if(resister_user.name==''){
inputErrorChange('name_error','Field Can not be empty');
validation = false
}
if(resister_user.username==''){
inputErrorChange('username_error','Field Can not be empty');
validation = false
}
if(resister_user.email==''){
inputErrorChange('email_error','Field Can not be empty');
validation = false
}
if(resister_user.password==''){
inputErrorChange('password_error','Field Can not be empty');
validation = false
}
return validation
}
function emailValidation(){
let valid_email = String(resister_user.email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
if(!valid_email){
inputErrorChange('email_error','Please enter a valid email');
}
return valid_email
}
return (
<div>
<div className="resister-container container">
<h1 className="resister__main-heading">Welcome to C<span>oo</span>k B<span>oo</span>k</h1>
<div className="resister-form card d-flex flex-column justify-content-center px-3 pt-5">
<div className="row">
<div className="col-md-6">
<div action="" className="d-flex flex-column px-5 pb-5">
<div className="mb-3">
<label htmlFor="exampleInputName" className="form-label">Name</label>
<input type="text" className="form-control" id="exampleInputName" aria-describedby="nameHelp" onChange={inputChange} name="name" value={resister_user.name}></input>
<span className="text-danger">{inputErrors.name_error}</span>
</div>
<div className="mb-3">
<label htmlFor="exampleInputUsername" className="form-label">Username</label>
<input type="text" className="form-control" id="exampleInputUsername" aria-describedby="nameHelp" onChange={inputChange} name="username" value={resister_user.username}></input>
<span className="text-danger">{inputErrors.username_error}</span>
</div>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">Email address</label>
<input type="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" onChange={inputChange} name="email" value={resister_user.email}></input>
<span className="text-danger">{inputErrors.email_error}</span>
</div>
<div className="mb-3">
<label htmlFor="exampleInputPassword1" className="form-label">Password</label>
<input type="password" className="form-control" id="exampleInputPassword1" name="password" onChange={inputChange} value={resister_user.password}></input>
<span className="text-danger">{inputErrors.password_error}</span>
</div>
<button type="submit" className="btn resistration-btn" onClick={formSubmit}>Sign up</button>
<Link to="/login" className="text-center">
Already have account? Log in Here.
</Link>
</div>
</div>
<div className="col-md-6">
<img src={resisterPic} alt="" className="resistration-form__image" />
</div>
</div>
</div>
</div>
</div>
)
}
export default Resister |
<script setup>
/**
* TakeLabSample
*/
import { ref, inject, computed } from 'vue'
import { TextArea, Input, SelectCustomDate, ShowValue, Treeselect } from 'form'
import { formatDate } from 'shared'
import { Alert } from 'layout'
const props = defineProps({
type: {
default: () => null,
type: String
}
})
// Inject necessary services
const api = inject('api')
const useGlobalStore = inject('useGlobalStore')
const rapidStore = useGlobalStore('rapidStore')
const selectedRows = rapidStore.reactiveProperty(`selected-${props.type}-rows`)
const tabsStore = useGlobalStore('tabs')
const labResultsStore = useGlobalStore('labResults')
const slideAction = rapidStore.reactiveProperty(`slide-${props.type}`)
const parametersStore = useGlobalStore('parameters')
const data = ref(selectedRows.value[0])
const errors = ref({})
// Component state
const itemToTakeLabSample = ref({
available_quantity: data.value ? data.value.quantity : 0,
quantity: 0,
take: 0,
location_id: null,
updated_at: null,
note: ''
})
const generalErrors = ref({
isOpen: false,
error: ''
})
// Saves the "take lab sample" action
const save = async () => {
const endPoint = slideAction.value.action === 'TakeLabSample' ? 'stock/take_lab_sample' : 'stock/retake_lab_sample'
const objectData = {
id: data.value.id,
quantity: itemToTakeLabSample.value.quantity,
location_id: itemToTakeLabSample.value.location_id,
note: itemToTakeLabSample.value.note,
updated_at: itemToTakeLabSample.value.updated_at ? formatDate(itemToTakeLabSample.value.updated_at, 'utcDateTime') : null
}
const response = await api.post(endPoint, objectData)
if (response.success && props.type === 'inventory subitem') {
tabsStore.closeTab('inventory subitem')
tabsStore.activateTab({ name: 'Inventory', parentName: 'Inventory' })
}
if (!response.success && response.message && !response.errors) {
generalErrors.value = {
isOpen: true,
error: response.message
}
}
response.success && labResultsStore.fetch()
// Processing errors
response.errors && (errors.value = response.errors)
return response
}
// Retrieves the current quantity
const currentQuantity = computed(() => Object.freeze(itemToTakeLabSample.value.available_quantity))
// Retrieves the remaining quantity
const remaining = computed(() => Number(itemToTakeLabSample.value.available_quantity) - Number(itemToTakeLabSample.value.quantity))
// Retrieves only 'Final room', 'Freezing Room', 'Cure Room' and 'Vault' locations.
const getLocations = () => {
const allowedLocations = ['final-room', 'vault', 'freezing-room', 'cure-room']
const allLocations = parametersStore.getTreeSelectDataBySlug('locations')
return allLocations.filter(location => allowedLocations.includes(location.data.slug))
}
// Expose the save function to parent components
defineExpose({ save })
</script>
<template>
<section class="full">
<!-- Alert for general errors -->
<Alert
v-model="generalErrors.isOpen"
:has-close-button="true"
:content="generalErrors.error"
type="danger" />
<!-- Current quantity with its measure -->
<ShowValue
v-model="currentQuantity"
justify-end
:label="$t('Available quantity')">
{{ data?.measure.name }}
</ShowValue>
<hr class="air">
<!-- Quantity taken -->
<Input
v-model="itemToTakeLabSample.quantity"
inputClass="text-right"
:type="'number'"
:step="'1'"
:min="'0'"
:errors="errors?.quantity"
:label="$t('Quantity taken')"
:inline-label-right="data?.measure.name" />
<!-- Locations -->
<Treeselect
:errors="errors?.location_id"
:label="$t(`Location`)"
:class="{'!bg-red-100': errors.location_id }"
v-model="itemToTakeLabSample.location_id"
:options="getLocations()"
:placeholder="$t('Select Item')"
class="input" />
<hr class="air">
<!-- Remaining -->
<ShowValue
v-model="remaining"
justify-end
:label="$t('Remaining')">
{{ data?.measure.name }}
</ShowValue>
<!-- Note -->
<TextArea
:errors="errors?.note"
v-model="itemToTakeLabSample.note"
:placeholder="$t('Note')"
:label="$t('Note')" />
<!-- Select custom date -->
<SelectCustomDate
:errors="errors?.updated_at"
v-model="itemToTakeLabSample.updated_at" />
</section>
</template> |
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:FDL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Free Documentation License Usage
** Alternatively, this file may be used under the terms of the GNU Free
** Documentation License version 1.3 as published by the Free Software
** Foundation and appearing in the file included in the packaging of
** this file. Please review the following information to ensure
** the GNU Free Documentation License version 1.3 requirements
** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
** $QT_END_LICENSE$
**
****************************************************************************/
/*!
\page qtquick-deployment.html
\title Deploying QML Applications
\brief Provides information on how to use deploy QML applications.
QML documents are loaded and run by the QML runtime. This includes the Declarative UI engine
along with the built-in QML types and plugin modules. The QML runtime also provides access
to third-party QML types and modules.
Applications that use QML must invoke the QML runtime to run QML documents. You can do this by
creating a QQuickView or a QQmlEngine, as described below. In addition, the Declarative UI
package includes the qmlscene tool, which loads \c .qml files. This tool is useful for developing
and testing QML code without having to write a C++ application to load the QML runtime.
\section1 Deploying Applications with Qt Creator
\l{Qt Creator Manual}{Qt Creator} deploys and packages QML applications to various platforms.
For mobile devices, Qt Creator can directly bundle applications to the respective platform
package formats, such as APK.
When you run your applications on the target platform, your application needs to access
the location of the QML libraries. If you use \l{qmake Manual}{qmake}, the
\c QT_INSTALL_QML environment variable points to the location of the libraries. The
\l{Downloads}{Qt Installers} install the QML libraries in:
\c{<version>}\c{/}\e{<compiler>}\c{/qml} directory.
\section1 QML Caching
The QML runtime loads QML documents by parsing them and generating byte code. Most of the time,
the document hasn't changed since the last time it was loaded. To speed up this loading process,
the QML runtime maintains a cache file for each QML document. This cache file contains the
compiled byte code and a binary representation of the QML document structure. In addition, when
multiple applications use the same QML document, the memory needed for the code is shared between
application processes. The cache files are loaded via the \c mmap() system call on POSIX-compliant
operating systems or \c CreateFileMapping() on Windows, resulting in significant memory savings.
Each time you load a changed QML document, the cache is automatically re-created. Cache files are
located in a sub-directory of QStandardPaths::CacheLocation with the name "qmlcache". The file
extension is \c .qmlc for QML documents and \c .jsc for imported JavaScript modules.
\target Compiling Ahead of Time
\section1 Ahead-of-Time Compilation
The automatic caching of compiled QML documents into cache files results in significantly faster
application load time. However, the initial creation of cache files can still take time, especially
when the application starts for the very first time. To avoid that initial step and provide faster
startup times from the very beginning, Qt's build system allows you to perform the compilation step
for QML files ahead of time, when compiling the C++ parts of your application.
To deploy your application with QML files compiled ahead of time, you must organize the files and
the build system in a specific way:
\list
\li All QML documents (including JavaScript files) must be included as resources via
\l{The Qt Resource System}{Qt's Resource system}.
\li Your application must load the QML documents via the \c qrc:/// URL scheme.
\li You can enable Ahead-of-Time compilation using the \c CONFIG+=qtquickcompiler directive.
\li If you're using the CMake build system, then you can achieve this by inserting a
\c find_package(Qt5QuickCompiler) call into your \c CMakeLists.txt and replacing the use
of \c qt5_add_resources with \c qtquick_compiler_add_resources.
\endlist
One benefit of compiling ahead of time is that, in the event of syntax errors in your QML
documents, you are notified at application compile-time instead of at run-time, when the file is
loaded.
\section1 Prototyping with QML Scene
The Declarative UI package includes a QML runtime tool, \l{qtquick-qmlscene.html}{qmlscene},
which loads and displays QML documents. This is useful during the application development phase
for prototyping QML-based applications without writing your own C++ applications to invoke
the QML runtime.
\section1 Initializing the QML Runtime in Applications
To run an application that uses QML, your application must invoke the QML runtime. This is done
by writing a Qt C++ application that loads the QQmlEngine by either:
\list
\li Loading the QML file through a QQuickView instance.
\li Creating a QQmlEngine instance and loading QML files with QQmlComponent.
\endlist
\section2 Initializing with QQuickView
QQuickView is a QWindow-based class that can load QML files. For example, if there is a QML file,
\c application.qml, it will look like this:
\qml
import QtQuick 2.3
Rectangle { width: 100; height: 100; color: "red" }
\endqml
It can be loaded in a Qt application's \c main.cpp file like this:
\code
#include <QGuiApplication>
#include <QQuickView>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl::fromLocalFile("application.qml"));
view.show();
return app.exec();
}
\endcode
This creates a QWindow-based view that displays the contents of \c application.qml.
The application's \c .pro \l{Creating Project Files}{project file} must specify
the \c declarative module for the \c QT variable. For example:
\code
TEMPLATE += app
QT += quick
SOURCES += main.cpp
\endcode
\section2 Creating a QQmlEngine Directly
If \c application.qml doesn't have any graphical components, or if it's preferred to
avoid QQuickView for other reasons, the QQmlEngine can be constructed directly instead.
In this case, \c application.qml is loaded as a QQmlComponent instance rather than placed into
a view:
\code
#include <QGuiApplication>
#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlEngine engine;
QQmlContext *objectContext = new QQmlContext(engine.rootContext());
QQmlComponent component(&engine, "application.qml");
QObject *object = component.create(objectContext);
// ... delete object and objectContext when necessary
return app.exec();
}
\endcode
If you're not using any graphical items from Qt Quick, you can replace QGuiApplication with a
QCoreApplication in the code above. This way, you can use QML as a language without any
dependencies to the \l{Qt GUI} module.
\section1 Managing Resource Files with the Qt Resource System
The \l {The Qt Resource System}{Qt resource system} allows resource files to be stored as binary
files in an application executable. This can be useful when building a mixed QML/C++ application
as it enables QML files and other resources -- such as images and sound files -- to be referred
to through the resource system URI scheme rather than relative or absolute paths to filesystem
resources.
\note If you use the resource system, the application executable must be re-compiled whenever a
QML source file is changed, to update the resources in the package.
To use the resource system in a mixed QML/C++ application:
\list
\li Create a \c .qrc \l {The Qt Resource System}{resource collection file} that lists resource
files in XML format.
\li From C++, load the main QML file as a resource using the \c :/ prefix or as a URL with the
\c .qrc scheme.
\endlist
Once this is done, all files specified by relative paths in QML are loaded from the resource
system instead. Use of the resource system is completely transparent to the QML layer; this means
all QML code should refer to resource files using relative paths and should \b not use the \c .qrc
scheme. This scheme should only be used from C++ code to refer to resource files.
Here's an application packaged using the Qt resource system; its directory structure is as follows:
\code
project
|- example.qrc
|- main.qml
|- images
|- background.png
|- main.cpp
|- project.pro
\endcode
The \c main.qml and \c background.png files are packaged as resource files. This is done in the
\c example.qrc resource collection file:
\quotefile qmlapp/qtbinding/resources/example.qrc
Since \c background.png is a resource file, \c main.qml can refer to it using the relative path
specified in \c example.qrc:
\snippet qmlapp/qtbinding/resources/main.qml 0
To allow QML to locate resource files correctly, the \c main.cpp loads the main QML file,
\c main.qml, as a resource file using the \c .qrc scheme:
\snippet qmlapp/qtbinding/resources/main.cpp 0
Finally, \c project.pro uses the \c RESOURCES variable to indicate that \c example.qrc should
be used to build the application resources:
\quotefile qmlapp/qtbinding/resources/resources.pro
\section1 Related Information
\list
\li \l{Deploying Qt Applications}
\li \l{Qt Creator: Running on Multiple Platforms}{Running on Multiple Platforms}
\li \l{Qt Creator: Deploying to Devices}{Deploying to Devices}
\li \l{qtqml-cppintegration-data.html}{qtqml-cppintegration-exposecppattributes.html}{Exposing Attributes of C++ Types to QML}
\li \l{The Qt Resource System}
\endlist
*/ |
<!-- <p>employee works!</p>
<form
#userForm="ngForm" (ngSubmit)="onSubmit(userForm)">
<div class="col-md-4 mb-2">
<div class="form-group">
<label class="form-label fs-1">EmployeeName</label>
<input type="text" class="form-control" name="employeeName" #name="ngModel" pattern="^[A-Za-z]{5,20}$" placeholder="Name" required ngModel>
<div *ngIf="name.invalid && name.touched">
<small class="text-danger" *ngIf="name.errors?.['required']">name is required</small>
<small class="text-danger" *ngIf="name.errors?.['pattern']">Name should have only alphabets and minimum 5-20 characters</small>
</div>
</div>
<div class="form-group">
<label> Gender</label><br>
<input type="radio" name="genderId" value= 1 required ngModel #gender="ngModel">Male
<input type="radio" name="genderId" value= 2 required ngModel #gender="ngModel">Female
</div>
</div>
<div class="form-group">
<label>Date Of Birth</label>
<input type="date" #date="ngModel" class="form-control" required
name="dateOfBirth" ngModel>
<div *ngIf="!date.invalid && date.touched">
<small class="text-danger" *ngIf="date.errors?.['required']">Date of Birth is required</small>
</div>
</div>
<div class="form-group">
<label>Date Of Joining</label>
<input type="date" #dateofjoining="ngModel" class="form-control" required
name="dateofjoining" ngModel>
<div *ngIf="!dateofjoining.invalid && dateofjoining.touched">
<small class="text-danger" *ngIf="dateofjoining.errors?.['required']">Date of Joining is required</small>
</div>
</div>
<div class="form-group">
<label class="form-label fs-1">Email</label>
<input type="text" #email="ngModel" class="form-control" name="email" ngModel placeholder="Email" required>
<div *ngIf="email.invalid && email.touched">
<small class="text-danger" *ngIf="email.errors?.['required']">Email is required</small>
</div>
</div>
<div class="form-group">
<label class="form-label fs-1">Password</label>
<input type="text" #password="ngModel" class="form-control" name="password" ngModel placeholder="password" required>
<div *ngIf="password.invalid && password.touched">
<small class="text-danger" *ngIf="password.errors?.['required']">password is required</small>
</div>
</div>
<button [disabled]="userForm.invalid" type="submit" class="btn btn-primary">submit</button>
</form> -->
<table >
<tr>
<th>EmployeeName</th>
<th>Email</th>
<th>Date of Birth</th>
<th>Date of Joining</th>
<th>Age</th>
<th>Gender</th>
</tr>
<tr *ngFor="let item of employee">
<td>{{item.employeeName}}</td>
<td>{{item.email}}</td>
<td>{{item.dateOfBirth}}</td>
<td>{{item.dateOfJoining}}</td>
<td>{{item.age}}</td>
<td>{{item.genderId.name}}</td>
</tr>
</table> |
import 'package:matrimonial_app/components/common_widget.dart';
import 'package:matrimonial_app/components/my_images.dart';
import 'package:matrimonial_app/const/my_theme.dart';
import 'package:matrimonial_app/const/style.dart';
import 'package:matrimonial_app/main.dart';
import 'package:matrimonial_app/redux/libs/profile_picture_view_request/profile_picture_view_request_accept.dart';
import 'package:flutter/material.dart';
import 'package:one_context/one_context.dart';
import '../const/const.dart';
import '../redux/libs/profile_picture_view_request/profile_picture_view_request_reject.dart';
class ProfilePictureViewCard extends StatelessWidget {
final image;
final name;
final age;
final id;
final index;
final status;
ProfilePictureViewCard(
{this.image, this.name, this.age, this.id, this.index, this.status});
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 17),
/// box decoration
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.all(
Radius.circular(12.0),
),
boxShadow: [CommonWidget.box_shadow()]),
// child0
child: Row(
children: [
SizedBox(
height: 100,
width: 84.0,
child: ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(12.0),
bottomLeft: Radius.circular(12.0)),
child: MyImages.normalImage(image),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(
top: 10.0, bottom: 10.0, left: 10.0, right: 10.0),
child: Container(
height: 65,
child: Row(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'$name',
style: Styles.bold_arsenic_14,
),
Text(
'$age years',
style: Styles.regular_arsenic_14,
),
],
),
const Spacer(),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
status == 1
? Container(
padding: const EdgeInsets.symmetric(
horizontal: 4, vertical: 2),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: MyTheme.green,
),
child: Text(
'Accepted',
style: Styles.bold_white_10,
),
)
: Row(
children: [
GestureDetector(
onTap: () {
store.state.pictureProfileViewState!
.index = index;
profile_picture_accept_reject_show_dialog(
context,
isAcceptOrReject: true,
request_id: id);
},
child: Container(
height: 30,
width: 30,
decoration: const BoxDecoration(
color:
Color.fromRGBO(201, 227, 202, 1),
borderRadius: BorderRadius.all(
Radius.circular(32.0))),
child: const Center(
child:
// store
// .state
// .pictureProfileViewState
// .index ==
// index
// ? const SizedBox(
// height: 15,
// width: 15,
// child:
// CircularProgressIndicator(
// strokeWidth: 1,
// ),
// )
// :
Icon(
Icons.check,
size: 15,
color: Color.fromRGBO(0, 169, 57, 1),
),
),
),
),
Const.width10,
GestureDetector(
onTap: () {
profile_picture_accept_reject_show_dialog(
context,
isAcceptOrReject: false,
request_id: id,
);
},
child: Container(
height: 30,
width: 30,
decoration: const BoxDecoration(
color:
Color.fromRGBO(255, 221, 218, 1),
borderRadius: BorderRadius.all(
Radius.circular(32.0))),
child: const Center(
child: Icon(
Icons.close,
size: 15,
color: Color.fromRGBO(255, 75, 62, 1),
),
),
),
)
],
),
],
),
],
),
),
),
)
],
),
);
}
Future<void> profile_picture_accept_reject_show_dialog(mainContext,
{bool? isAcceptOrReject, request_id}) {
return showDialog<void>(
context: mainContext,
builder: (BuildContext context) {
return AlertDialog(
title: Text(
'Profile Picture View Request ${isAcceptOrReject! ? "Accept" : "Reject"}',
style: Styles.bold_arsenic_14,
),
content: Text(
'Are you sure you want to ${isAcceptOrReject ? "Accept" : "Reject"} this request?',
style: Styles.regular_arsenic_12,
textAlign: TextAlign.center,
),
actions: <Widget>[
TextButton(
style: TextButton.styleFrom(
textStyle: Theme.of(context).textTheme.labelLarge,
),
child: Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: const Color.fromRGBO(255, 221, 218, 1),
),
child: const Text('Cancel')),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
style: TextButton.styleFrom(
textStyle: Theme.of(context).textTheme.labelLarge,
),
child: Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: const Color.fromRGBO(201, 227, 202, 1),
),
child: const Text('Confirm')),
onPressed: () {
pleaseWaitDialog();
isAcceptOrReject
? store.dispatch(profilePictureViewRequestAcceptMiddleware(
id: request_id))
: store.dispatch(profilePictureViewRequestRejectMiddleware(
id: request_id));
Navigator.of(context).pop();
},
),
],
);
},
);
}
pleaseWaitDialog() {
return OneContext().showDialog<void>(
builder: (BuildContext context) {
store.state.pictureProfileViewState!.loadingContext = context;
return AlertDialog(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CommonWidget.circularIndicator,
const Text(
'Please Wait',
style: TextStyle(fontSize: 16),
),
],
),
);
},
);
}
} |
def caching_fibonacci():
#Створити порожній словник cache
cache = dict()
def fibonacci(n):
# Якщо n <= 0, повернути 0
# Якщо n == 1, повернути 1
# Якщо n у cache, повернути cache[n]
if n<=0: return 0
if n==1: return 1
if n in cache: return cache[n]
cache[n] = fibonacci(n - 1) + fibonacci(n - 2)
return cache[n]
return fibonacci
def main():
# Отримуємо функцію fibonacci
fib = caching_fibonacci()
# Використовуємо функцію fibonacci для обчислення чисел Фібоначчі
print(fib(10)) # Виведе 55
print(fib(15)) # Виведе 610
if __name__ == "__main__":
main() |
import { useEffect, useState } from 'react';
import { Product as ProductType } from '../types';
import { PostgrestError } from '@supabase/supabase-js';
import { supabase } from '../auth/supabaseClient';
const useFetchProducts = () => {
const [products, setProducts] = useState<ProductType[] | null>(null);
const [error, setError] = useState<PostgrestError | null>(null);
useEffect(() => {
const fetchProducts = async () => {
try {
const { data, error } = await supabase.from('products').select('*');
if (error) {
setError(error);
}
setProducts(data);
} catch (error) {
console.log(error);
}
};
fetchProducts();
}, []);
return { products, error };
};
export default useFetchProducts; |
import logging
from abc import ABC, abstractmethod
import numpy as np
from sklearn.metrics import accuracy_score, classification_report
class Evaluation(ABC):
"""
Abstract class defining strategy for evaluation our models
"""
@abstractmethod
def calculate_scores(self, y_true: np.ndarray, y_pred: np.ndarray):
"""
Calculates the scores for the model
Args:
y_true: True labels
y_pred: Predicted labels
Returns:
None
"""
pass
class ACCURACY(Evaluation):
"""
Evaluation Strategy that uses Accuracy
"""
def calculate_scores(self, y_true: np.ndarray, y_pred: np.ndarray):
try:
logging.info("Calculating Accuracy")
acc = accuracy_score(y_true, y_pred)
logging.info("Accuracy: {}".format(acc))
return acc
except Exception as e:
logging.error("Error in calculating accuracy: {}".format(e))
raise e
# class ClassificationReport(Evaluation):
# """
# Evaluation Strategy that uses Classification Report
# """
# def calculate_scores(self, y_true: np.ndarray, y_pred: np.ndarray):
# try:
# logging.info("Calculating Classification Report")
# cr = classification_report(y_true, y_pred)
# logging.info("Classification Report: {}".format(cr))
# return cr
# except Exception as e:
# logging.error("Error in calculating Classification Report: {}".format(e))
# raise e |
import { useInaccurateTimestamp } from "react-native-use-timestamp";
import * as Updates from "expo-updates";
import React, { useEffect, useRef, useState } from "react";
import { Modal, StyleSheet, View } from "react-native";
import { MyText } from "./MyText";
import { CustomButton } from "./CustomButton";
// How often do we want to render?
const INTERVAL_RENDER = 1000 * (__DEV__ ? 10 : 60);
// How often should it actually check for an update?
const INTERVAL_OTA_CHECK = 1000 * 60 * 15;
// const INTERVAL_OTA_CHECK = 1000 * 20
async function checkForUpdates() {
const update = await Updates.checkForUpdateAsync();
if (!update.isAvailable) {
throw new Error("No updates available");
}
const result = await Updates.fetchUpdateAsync();
if (!result.isNew) {
throw new Error("Fetched update is not new");
}
return true;
}
export function OtaUpdater() {
const now = useInaccurateTimestamp({ every: INTERVAL_RENDER });
const isMounted = useRef(true);
const [updateIsAvailable, setUpdateAvailable] = useState(false);
// Setting this to initially zero means there will _always_ be a check on
// mount, which is nice, because that means a check when the app starts.
const lastUpdate = useRef(0);
useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
useEffect(() => {
if (updateIsAvailable) {
return;
}
if (now - lastUpdate.current < INTERVAL_OTA_CHECK) {
return;
}
lastUpdate.current = now;
checkForUpdates()
.then(() => {
isMounted.current && setUpdateAvailable(true);
if (isMounted.current) {
Updates.reloadAsync();
}
})
.catch((_reason) => {
/* you can inspect _reason */
});
}, [now]);
const ModalComponent = () => {
return updateIsAvailable ? (
<Modal
statusBarTranslucent={true}
animationType='slide'
transparent={true}
presentationStyle='overFullScreen'
>
<View style={styles.container}>
<View style={styles.updateContainer}>
<MyText title="Hey there! We've got an update for you 🎉" h6 />
<CustomButton
style={styles.promoBtn}
title='Apply Update'
textStyle={styles.promoBtnText}
onPress={() => {
Updates.reloadAsync();
}}
/>
</View>
</View>
</Modal>
) : null;
};
return <ModalComponent />;
}
const styles = StyleSheet.create({
container: {
justifyContent: "center",
alignItems: "center",
flex: 1,
backgroundColor: "rgba(0, 0, 0, .3)",
},
updateContainer: {
alignItems: "center",
backgroundColor: "white",
borderWidth: 1,
borderColor: "#E7E7E9",
borderRadius: 5,
width: "85%",
paddingHorizontal: 15,
paddingVertical: 10,
},
promoBtn: {
paddingHorizontal: 12,
paddingVertical: 7,
marginTop: 20,
marginBottom: 10,
alignSelf: "center",
},
promoBtnText: {
fontSize: 11,
},
}); |
# OCR Android 离线中国身份证识别 Demo 使用指南
# Offline OCR Android Chinese ID card identification Demo Usage guide
## 简介 Intro
Android用离线身份证OCR识别. 包含了CV图像预处理, 以及OCR文字识别.
界面包含一个身份证拍摄框, 支持打开闪光灯. 会实时识别, 如果所需内容已完全识别, 就会跳转新的activity包含身份证信息.
**注意: 在第一次运行会要权限, 取得权限后可能会闪退, 属正常现象. 以后打开就可以正常使用.**
安装包地址:
[Release页面](https://github.com/Blackmesa-Canteen/android_ocr_demo/releases/tag/v0.2.0-alpha)
Android Chinese ID card identification with offline OCR. It includes CV image preprocessing and OCR text recognition.
The screen contains an ID card photo box and supports the flash. It will be recognized in real time, and if the required content is fully recognized, it will jump to a new activity containing ID information.
**Note: It is normal that the app asks for permission on the first run. After obtaining permission, it may blink back. You can open it later and use it normally.**
Installation package address:[Release page](https://github.com/Blackmesa-Canteen/android_ocr_demo/releases/tag/v0.2.0-alpha)
## 源码部署 Run the src
是可以正常运行的, 如果您这边出了问题, 大概率是缺失了paddleLite预测依赖库和openCV依赖库, 请参考以下开源项目的安装说明配置好依赖库:
[Paddle-Lite-Demo](https://github.com/PaddlePaddle/Paddle-Lite-Demo)
It should work. if not, it could be missing paddleLite predictive dependency library and openCV dependency library, please refer to the following open source project installation instructions to configure the dependency library: [Paddle-Lite-Demo](https://github.com/PaddlePaddle/Paddle-Lite-Demo)
## 升级预测模型 Upgrade models
**注意:**
如果预测模型有版本升级,建议同步更新 OPT 优化后的模型。例如,预测库升级至 2.10—rc 版本,需要做以下操作:
If the version of the prediction model has been upgraded, it is recommended to update the OPT optimized model simultaneously. For example, to upgrade the predictive library to version 2.10-RC, you need to do the following:
```shell
# 下载 PaddleOCR V2.0 版本的中英文 inference 模型
wget https://paddleocr.bj.bcebos.com/dygraph_v2.0/slim/ch_ppocr_mobile_v2.0_det_slim_infer.tar && tar xf ch_ppocr_mobile_v2.0_det_slim_infer.tar
wget https://paddleocr.bj.bcebos.com/dygraph_v2.0/slim/ch_ppocr_mobile_v2.0_rec_slim_infer.tar && tar xf ch_ppocr_mobile_v2.0_rec_slim_infer.tar
wget https://paddleocr.bj.bcebos.com/dygraph_v2.0/slim/ch_ppocr_mobile_v2.0_cls_slim_infer.tar && tar xf ch_ppocr_mobile_v2.0_cls_slim_infer.tar
# 获取 2.10 版本的 MAC 系统的 OPT 工具
wget https://github.com/PaddlePaddle/Paddle-Lite/releases/download/v2.10-rc/opt_mac
# 转换 V2.0 检测模型
./opt --model_file=./ch_ppocr_mobile_v2.0_det_slim_infer/inference.pdmodel --param_file=./ch_ppocr_mobile_v2.0_det_slim_infer/inference.pdiparams --optimize_out=./ch_ppocr_mobile_v2.0_det_slim_opt --valid_targets=arm --optimize_out_type=naive_buffer
# 转换 V2.0 识别模型
./opt --model_file=./ch_ppocr_mobile_v2.0_rec_slim_infer/inference.pdmodel --param_file=./ch_ppocr_mobile_v2.0_rec_slim_infer/inference.pdiparams --optimize_out=./ch_ppocr_mobile_v2.0_rec_slim_opt --valid_targets=arm --optimize_out_type=naive_buffer
# 转换 V2.0 方向分类器模型
./opt --model_file=./ch_ppocr_mobile_v2.0_cls_slim_infer/inference.pdmodel --param_file=./ch_ppocr_mobile_v2.0_cls_slim_infer/inference.pdiparams --optimize_out=./ch_ppocr_mobile_v2.0_cls_slim_opt --valid_targets=arm --optimize_out_type=naive_buffer
```
## Demo 代码介绍
先整体介绍下OCR 文字识别 Demo 的代码结构,然后再从 Java 和 C++ 两部分简要的介绍 Demo 每部分功能.
<p align="center"><img width="300" height="500" src="https://paddlelite-demo.bj.bcebos.com/demo/ocr/docs_img/android/ppocr_android_app.jpg"/></p>
1. `PaddleLite/` : 存放 PaddleLite 预测库
**备注:**
如需更新预测库,例如更新 Adnroid v8 动态库 `so`,则将新的动态库 `so` 更新到 `PaddleLite/cxx/libs/armv64-v8a` 目录
2. `OpenCV/` : 存放 OpenCV 预测库
3. `assets/` : 存放 OCR demo 的模型、测试图片、标签文件及 config 文件
**备注:**
- `./assets/ppocr_keys_v1.txt` 是中文字典文件,如果使用的模型是英文数字或其他语言的模型,则需要更换为对应语言的字典.
- 其他语言的字典文件,可从 PaddleOCR 仓库下载:https://github.com/PaddlePaddle/PaddleOCR/tree/release/2.3/ppocr/utils
4. `./src/main/cpp` : 存放 C++ 预测代码
- `cls_process.cc` : 方向分类器的推理全流程,包含预处理、预测和后处理三部分
- `rec_process.cc` : 识别模型 CRNN 的推理全流程,包含预处理、预测和后处理三部分
- `det_process.cc` : 检测模型 CRNN 的推理全流程,包含预处理、预测和后处理三部分
- `det_post_process` : 检测模型 DB 的后处理文件
- `pipeline.cc` : OCR 文字识别 Demo 推理全流程代码
- `Native.cc` : 用于 C++ 和 Java 间传递信息桥梁
- `CMakeLists.txt` : 预测代码的 MakeFile 文件
### Java 端
* common Java 包
在 `app/src/java/com/baidu/paddle/lite/demo/common` 目录下,实现摄像头和框架的公共处理,一般不用修改。其中,Utils.java 用于存放一些公用的且与 Java 基类无关的功能,例如模型拷贝、字符串类型转换等
* util Java 包
在`app/src/main/java/com/baidu/paddle/lite/demo/util`, 里面封装了对身份证信息处理的逻辑.
* ppocr_demo Java 包
在 `app/src/java/com/baidu/paddle/lite/demo/ppocr_demo` 目录下,实现 APP 界面消息事件和 Java/C++ 端代码互传的桥梁功能
* MainActivity
实现 APP 的创建、运行、释放功能
重点关注 `checkRun` 函数,实现 APP 界面值向 C++ 端值互传
```
public void checkRun() {
try {
Utils.copyAssets(this, labelPath);
String labelRealDir = new File(
this.getExternalFilesDir(null),
labelPath).getAbsolutePath();
Utils.copyAssets(this, configPath);
String configRealDir = new File(
this.getExternalFilesDir(null),
configPath).getAbsolutePath();
Utils.copyAssets(this, detModelPath);
String detRealModelDir = new File(
this.getExternalFilesDir(null),
detModelPath).getAbsolutePath();
Utils.copyAssets(this, clsModelPath);
String clsRealModelDir = new File(
this.getExternalFilesDir(null),
clsModelPath).getAbsolutePath();
Utils.copyAssets(this, recModelPath);
String recRealModelDir = new File(
this.getExternalFilesDir(null),
recModelPath).getAbsolutePath();
predictor.init(
this,
detRealModelDir,
clsRealModelDir,
recRealModelDir,
configRealDir,
labelRealDir,
cpuThreadNum,
cpuPowerMode);
} catch (Throwable e) {
e.printStackTrace();
}
}
```java
* Native
实现 Java 与 C++ 端代码互传的桥梁功能
**备注:**
Java 的 native 方法和 C++ 的 native 方法要一一对应
### C++ 端
* Native
实现 Java 与 C++ 端代码互传的桥梁功能,将 Java 数值转换为 c++ 数值,调用 c++ 端的完成 OCR 文字识别功能
**注意:**
Native 文件生成方法:
```
cd app/src/java/com/baidu/paddle/lite/demo/ppocr_demo
# 在当前目录会生成包含 Native 方法的头文件,用户可以将其内容拷贝至 `cpp/Native.cc` 中
javac -classpath D:\dev\android-sdk\platforms\android-29\android.jar -encoding utf8 -h . Native.java
```
* Pipeline
实现输入预处理、推理执行和输出后处理的流水线处理,支持多个模型的串行处理
* Utils
实现其他辅助功能,如 `NHWC` 格式转 `NCHW` 格式、字符串处理等
* 其他 CC 文件
* `cls_process.cc` : 方向分类器的推理全流程,包含预处理、预测和后处理三部分
* `rec_process.cc` : 识别模型 CRNN 的推理全流程,包含预处理、预测和后处理三部分
* `det_process.cc` : 检测模型 CRNN 的推理全流程,包含预处理、预测和后处理三部分
* `det_post_process.cc` : 检测模型 DB 的后处理文件
## 代码讲解 (使用 Paddle Lite `C++ API` 执行预测)
该示例基于 C++ API 开发,调用 Paddle Lite `C++s API` 包括以下五步。
更详细的 `API` 描述参考:[Paddle Lite C++ API ](https://paddle-lite.readthedocs.io/zh/latest/api_reference/c++_api_doc.html)。
```c++
#include <iostream>
// 引入 C++ API
#include "include/paddle_api.h"
#include "include/paddle_use_ops.h"
#include "include/paddle_use_kernels.h"
// 1. 设置 MobileConfig
MobileConfig config;
config.set_model_from_file(modelPath); // 设置 NaiveBuffer 格式模型路径
config.set_power_mode(LITE_POWER_NO_BIND); // 设置 CPU 运行模式
config.set_threads(4); // 设置工作线程数
// 2. 创建 PaddlePredictor
std::shared_ptr<PaddlePredictor> predictor = CreatePaddlePredictor<MobileConfig>(config);
// 3. 设置输入数据
std::unique_ptr<Tensor> input_tensor(std::move(predictor->GetInput(0)));
input_tensor->Resize({1, 3, 224, 224});
auto* data = input_tensor->mutable_data<float>();
for (int i = 0; i < ShapeProduction(input_tensor->shape()); ++i) {
data[i] = 1;
}
// 如果输入是图片,则可在第三步时将预处理后的图像数据赋值给输入 Tensor
// 4. 执行预测
predictor->run();
// 5. 获取输出数据
std::unique_ptr<const Tensor> output_tensor(std::move(predictor->GetOutput(0)));
std::cout << "Output shape " << output_tensor->shape()[1] << std::endl;
for (int i = 0; i < ShapeProduction(output_tensor->shape()); i += 100) {
std::cout << "Output[" << i << "]: " << output_tensor->data<float>()[i]
<< std::endl;
}
```
## 如何更新模型、输入/输出预处理
### 更新模型
1. 将优化后的新模型存放到目录 `./assets/` 下;
2. 如果模型名字跟工程中模型名字一模一样,则不需更新代码;否则话,需要修改 `./src/main/java/com/baidu/paddle/lite/demo/ppocr_demo/MainActivity.java` 中代码;
以将检测 det 模型更新为例,则先将优化后的模型存放到 `./assetss/ssd_mv3.nb` 下,然后更新 `MainActivity.java` 中代码
```shell
# 代码文件 `./src/main/java/com/baidu/paddle/lite/demo/ppocr_demo/MainActivity.java`
Utils.copyAssets(this, detModelPath);
String detRealModelDir = new File(
this.getExternalFilesDir(null),
detModelPath).getAbsolutePath();
# updata
Utils.copyAssets(this, "ssd_mv3.nb");
String detRealModelDir = new File(
this.getExternalFilesDir(null),
detModelPath).getAbsolutePath();
```
**注意:**
- 如果更新模型中的输入 Tensor、Shape、和 Dtype 发生更新:
- 更新文字方向分类器模型,则需要更新 `ppocr_demo/src/main/cpp/cls_process.cc` 中 `ClsPredictor::Preprocss` 函数
- 更新检测模型,则需要更新 `ppocr_demo/src/main/cpp/det_process.cc` 中 `DetPredictor::Preprocss` 函数
- 更新识别器模型,则需要更新 `ppocr_demo/src/main/cpp/rec_process.cc` 中 `RecPredictor::Preprocss` 函数
- 如果更新模型中的输出 Tensor 和 Dtype 发生更新:
- 更新文字方向分类器模型,则需要更新 `ppocr_demo/src/main/cpp/cls_process.cc` 中 `ClsPredictor::Postprocss` 函数
- 更新检测模型,则需要更新 `ppocr_demo/src/main/cpp/det_process.cc` 中 `DetPredictor::Postprocss` 函数
- 更新识别器模型,则需要更新 `ppocr_demo/src/main/cpp/rec_process.cc` 中 `RecPredictor::Postprocss` 函数
- 如果需要更新 `ppocr_keys_v1.txt` 标签文件,则需要将新的标签文件存放在目录 `./assets/` 下,并更新 `./src/main/java/com/baidu/paddle/lite/demo/ppocr_demo/MainActivity.java` 中代码;
```shell
# 代码文件 `./src/main/java/com/baidu/paddle/lite/demo/ppocr_demo/MainActivity.java`
Utils.copyAssets(this, labelPath);
String labelRealDir = new File(
this.getExternalFilesDir(null),
labelPath).getAbsolutePath();
# updata
Utils.copyAssets(this, "new_label.txt");
String labelRealDir = new File(
this.getExternalFilesDir(null),
labelPath).getAbsolutePath();
```
### 更新输入/输出预处理
1. 更新输入预处理
- 更新文字方向分类器模型,则需要更新 `ppocr_demo/src/main/cpp/cls_process.cc` 中 `ClsPredictor::Preprocss` 函数
- 更新检测模型,则需要更新 `ppocr_demo/src/main/cpp/det_process.cc` 中 `DetPredictor::Preprocss` 函数
- 更新识别器模型,则需要更新 `ppocr_demo/src/main/cpp/rec_process.cc` 中 `RecPredictor::Preprocss` 函数
2. 更新输出预处理
- 更新文字方向分类器模型,则需要更新 `ppocr_demo/src/main/cpp/cls_process.cc` 中 `ClsPredictor::Postprocss` 函数
- 更新检测模型,则需要更新 `ppocr_demo/src/main/cpp/det_process.cc` 中 `DetPredictor::Postprocss` 函数
- 更新识别器模型,则需要更新 `ppocr_demo/src/main/cpp/rec_process.cc` 中 `RecPredictor::Postprocss` 函数
## OCR 文字识别 Demo 工程详解
OCR 文字识别 Demo 由三个模型一起完成 OCR 文字识别功能,对输入图片先通过 `ch_ppocr_mobile_v2.0_det_slim_opt.nb` 模型做检测处理,然后通过 `ch_ppocr_mobile_v2.0_cls_slim_opt.nb` 模型做文字方向分类处理,最后通过 `ch_ppocr_mobile_v2.0_rec_slim_opt.nb` 模型完成文字识别处理。
1. `pipeline.cc` : OCR 文字识别 Demo 预测全流程代码
该文件完成了三个模型串行推理的全流程控制处理,包含整个处理过程的调度处理。
- `Pipeline::Pipeline(...)` 方法完成调用三个模型类构造函数,完成模型加载和线程数、绑核处理及 predictor 创建处理
- `Pipeline::Process(...)` 方法用于完成这三个模型串行推理的全流程控制处理
2. `cls_process.cc` 方向分类器的预测文件
该文件完成了方向分类器的预处理、预测和后处理过程
- `ClsPredictor::ClsPredictor()` 方法用于完成模型加载和线程数、绑核处理及 predictor 创建处理
- `ClsPredictor::Preprocess()` 方法用于模型的预处理
- `ClsPredictor::Postprocess()` 方法用于模型的后处理
3. `rec_process.cc` 识别模型 CRNN 的预测文件
该文件完成了识别模型 CRNN 的预处理、预测和后处理过程
- `RecPredictor::RecPredictor()` 方法用于完成模型加载和线程数、绑核处理及 predictor 创建处理
- `RecPredictor::Preprocess()` 方法用于模型的预处理
- `RecPredictor::Postprocess()` 方法用于模型的后处理
4. `det_process.cc` 检测模型 DB 的预测文件
该文件完成了检测模型 DB 的预处理、预测和后处理过程
- `DetPredictor::DetPredictor()` 方法用于完成模型加载和线程数、绑核处理及 predictor 创建处理
- `DetPredictor::Preprocess()` 方法用于模型的预处理
- `DetPredictor::Postprocess()` 方法用于模型的后处理
5. `db_post_process` 检测模型 DB 的后处理函数,包含 clipper 库的调用
该文件完成了检测模型 DB 的第三方库调用和其他后处理方法实现
- `std::vector<std::vector<std::vector<int>>> BoxesFromBitmap(...)` 方法从 Bitmap 图中获取检测框
- `std::vector<std::vector<std::vector<int>>> FilterTagDetRes(...)` 方法根据识别结果获取目标框位置 |
c Fortran version of AGNREF
c Ref. Hagen and Done (in prep.)
c
c Combines AGNSED (Kubota & Done 2018) with PEXMON (Nandra er al.
c 2007), and a thermal re-processor component. We assume a geometry
c where both the reflection and additional thermal component
c originate from the same region - taken to be some smooth wind
c covering a fraction of the sky. Hence these components are tied
c together.
c We also tie the normalisation of these to AGNSED, by assuming
c that all reflection/re-processing comes from illumination by the
c central X-ray corona. Hence we can write
c
c Lref = A*Lx*fc*0.5
c Lth = (1-A)*Lx*fc*0.5
c
c where Lx is the luminosity of the central X-ray corona, and fc is
c the covering fraction (in units d\Omega/4\pi) of the
c reflector/re-processor. Note that Lx is calculated
c self-consistently as in AGNSED
c The factor 0.5 comes from the fact that we only see the wind
c emission from one side - however the covering fraction includes
c both sides
c
c The model consists of four regions: a standard outer disc, a warm
c Comptonization region where the disc has not thermalised properly,
c a spherical inner corona modelled as a hot Comptonization region,
c and a distant re-processor/reflector
c
c The Comptonization is modelled using NTHCOMP (Zdziarski, Johnson &
c Magdziarz 1996; Zycki, Done & Smith 1999)
c-----------------------------------------------------------------------
c-----------------------------------------------------------------------
subroutine agnref(ear,ne,param,ifl,photar,photer)
implicit none
integer npars
parameter(npars=19)
integer ne, ifl
real ear(0:ne), photar(ne), param(npars), photer(ne)
real oldpar(npars)
integer Nnew !Defining own energy grid for model calc.
parameter(Nnew=2000) !Number of bin edges
real enew(0:Nnew), ph(Nnew) !ph is photon array on new grid
real dloge, newemin, newemax
real fstart(ne), fend(ne)
integer istart(ne), iend(ne)
logical parchange, echange
save oldpar
integer i, n !Iteration indeces
double precision zfac
c ear: Energy array
c ne: Size of energy array
c param: Parameter value array
c ifl: Spectrum number
c photar: flux array (size ne-1)
c
c param(1): Mass, Msol
c param(2): Distance, Mpc
c param(3): log mdot, Mass accretion rate, L/Ledd
c param(4): astar, BH spin
c param(5): cos inc, Inclination
c param(6): kTe_hot, hot corona temperature, keV
c param(7): kTe_warm, warm compton temperature, keV
c param(8): gamma_hot, hot corona photon index
c param(9): gamma_warm, warm compton photon index
c param(10): r_hot, hot corona radius, Rg
c param(11): r_warm, warm compton outer radius, Rg
c param(12): log r_out, outer disc radius, Rg
c param(13): hmax, scale height of corona, Rg
c param(14): fcov, Covering fraction of re-processor, dOmega/4pi
c param(15): kT_wind, Temperature of re-processor, keV
c param(16): Awind, Albedo of reprocessor
c param(17): blur, 0=off/1=on - whether to convolve pexmon with rdblur
c param(18): rin_blur, effective radius for rdblur, Rg
c param(19): redshift
c checking if parameters have changed
parchange=.false.
do i=1,npars,1
if (param(i).ne.oldpar(i)) parchange=.true.
end do
c Checking if we need to change energy grid
c The default extends from 1e-4 to 1e3 keV
zfac = (1.0 + param(19))
if (ear(0).eq.0.0) then
newemin=ear(1) - (ear(2)-ear(1))/10.0
else
newemin=min(1.0e-4, ear(0)*zfac)
end if
newemax=max(1.0e3, ear(ne)*zfac)
if ((enew(0).ne.newemin).or.(enew(Nnew).ne.newemax)) then
echange=.true.
end if
c Calculating new energy grid if necessary
if (echange) then
dloge=log10(newemax/newemin)/float(Nnew)
enew(0) = newemin
do n=1, Nnew, 1
enew(n)=10**(log10(enew(0))+dloge*float(n))
end do
end if
c Call model if parameters or energy grid have changed
if (parchange.or.echange) then
call calc_refspec(enew, Nnew, param, ifl, ph)
!Redshift correct energy bins
do n=1, Nnew, 1
enew(n) = enew(n)/zfac
ph(n) = ph(n)/zfac
end do
do i=1, npars, 1
oldpar(i)=param(i)
end do
end if
c Re-bin onto original xspec grid
call inibin(Nnew, enew, ne, ear, istart, iend, fstart, fend, 0)
call erebin(Nnew, ph, ne, istart, iend, fstart, fend, photar)
return
end
c-----------------------------------------------------------------------
c-----------------------------------------------------------------------
c Main subroutine for calculating disc spec, warm Comp spec, and
c hot Comp spec
c-----------------------------------------------------------------------
c-----------------------------------------------------------------------
subroutine calc_refspec(es, nn, param, ifl, ph)
c Function to calculate the SED. Calculates the spectral
c contribution from each region (disc, warm comp, hot comp,
c and reprocessor/outflow)
c Temperature found through the Novikov-Thorne equations
c
implicit none
integer nn, ifl
real es(0:nn), ph(nn), param(*)
real ph_ann(nn), phw_ann(nn), phh_ann(nn), phh_shape(nn) !disc, warm, hot
real ph_ref(nn), ph_rep(nn)
double precision M, mdot
double precision rout, rw, rh, rsg, risco
double precision astar, hmax
double precision kTh, kTw
double precision gammah, gammaw
double precision cos_inc, dist
double precision fcov_wind, kTwind, Awind, rin_blur
integer inc_blur
double precision pi, G, c, h, sigma_sb, mp, kB
double precision eta, Ledd, Mdot_edd, Rg
double precision dr_dex, nrd, nrw, nrh, nrseed
double precision dlog_rd, dlog_rw, dlog_rh, dlog_rseed
double precision rmid, dr
double precision kkev, kevhz, keverg
double precision dflux, en, dnphot, tr, tw
double precision calc_risco, calc_rsg, calc_fcol
double precision efficiency, nttemp, repnttemp
double precision lphseed, fcov, theta0
double precision lseed_ann, lseed_cann, ldiss_ann
double precision tseed_h, ysb
double precision Lx_tot, fx_tot
real pxpar(12), ntwpar(5), nthpar(5), rdpar(4), bbpar(2)
real pxpherr(nn), ntwpherr(nn), nthpherr(nn)
real phref_err(nn), phrd_err(nn), phbb_err(nn)
double precision dflux_rep
double precision normw_ann, normh_ann, norm_rep, norm_ref
double precision ntw_out, nth_out, px_out, rep_out
logical return_disc, return_warm, return_hot
logical return_ref, return_rep
integer i, n
c Constants
pi = 4.0*atan(1.0)
G = 6.67d-8 * 1.99d33 !Grav const. cm^-3 s^-1 Msol^-1
c = 3.0d10 !Speed of light. cm/s
h = 6.62617d-27 !Plank const. erg s
sigma_sb = 5.670367d-5 !Stefan-Boltzmann const. erg s^-1 cm^-2 K^-4
mp = 1.67d-24 !Proton mass. g
kB = 1.38d-16 !Boltzmann const. erg/K
c Unit conversion constants
kkev = 1.16048d7 !K/keV
kevhz = 2.417965d17 !Hz/keV
keverg = 1.60218d-9 !erg/keV
dr_dex = 30 !Radial resolution, Nbins per decade (ish)
c Read parameters
M = dble(param(1))
dist = dble(param(2)) !Mpc
mdot = dble(10**(param(3)))
astar = dble(param(4))
cos_inc = dble(param(5))
kTh = dble(abs(param(6)))
kTw = dble(abs(param(7)))
gammah = dble(param(8))
gammaw = dble(abs(param(9)))
rw = dble(param(11))
hmax = dble(param(13))
fcov_wind = dble(param(14))
kTwind = dble(abs(param(15)))
Awind = dble(abs(param(16)))
inc_blur = int(param(17))
rin_blur = dble(param(18))
c Getting accretion attributes
risco = calc_risco(astar)
eta = efficiency(risco)
rsg = calc_rsg(M, mdot)
Ledd = 1.39d38 * M !erg/s
Mdot_edd = Ledd/(eta * c**2) !g/s
Rg = (G*M)/c**2 !cm
dist = dist*1.0d6 !pc
dist = dist*3.086d18 !cm
c Filling parameter arrays (for those that dont change!!!)
c warm nthcomp params
ntwpar(1) = gammaw
ntwpar(2) = kTw
ntwpar(4) = 0.0 !BB assumed from each annulus
ntwpar(5) = 0.0 !Redshift - dealt with within this script
c hot nthomp params
nthpar(1) = gammah
nthpar(2) = kTh
nthpar(4) = 0.0
nthpar(5) = 0.0
c pexmon pars
pxpar(1) = gammah !photon index
pxpar(2) = 1.0d5 !fold E, keV
pxpar(3) = -1 !return only reflected
pxpar(4) = 0.0 !redshift, delt with elsewhere
pxpar(5) = 1.0 !Abundances, set to solar
pxpar(6) = 1.0 !Fe abundance, set to solar
pxpar(7) = acos(cos_inc) * (180.0/pi) !Inclination, deg
!pexmon normalisation will be tied to Lhot, later in script
c rdblur pars
rdpar(1) = -3.0 !Power law index
rdpar(2) = rin_blur !Effective bluring radius
rdpar(3) = 1.0d6 !Some large radius...
rdpar(4) = acos(cos_inc) * (180.0/pi)
c Black-Body pars
bbpar(1) = kTwind
bbpar(2) = 1.0
c Checking switching parameters
return_disc=.true.
return_warm=.true.
return_hot=.true.
return_ref=.true.
return_rep=.true.
if (param(12).lt.0.0) then !checkig outer radius
rout = rsg
else
rout = dble(10**param(12))
end if
if ((param(10).lt.0.0).or.(param(10).lt.risco)) then !Checking inner disc radius
rh = risco
return_hot=.false.
call xwrite('r_hot < risco!!! Setting r_hot = risco', 10)
else
rh = dble(param(10))
end if
if ((param(11).lt.0.0).or.(param(11).lt.risco)) then !Checking warm region
rw = risco
return_warm=.false.
return_hot=.false.
call xwrite('r_warm < risco!! Setting rw = risco', 10)
else
rw = dble(param(11))
end if
if (param(9).lt.0.0) then !if gammaw<0 show ONLY disc
return_warm=.false.
return_hot=.false.
return_ref=.false.
return_rep=.false.
end if
if (param(7).lt.0.0) then !if kTw<0 show ONLY warm Comp
return_disc=.false.
return_hot=.false.
return_ref=.false.
return_rep=.false.
end if
if (param(6).lt.0.0) then !if kTh<0 show ONLY hot comp
return_disc=.false.
return_warm=.false.
return_ref=.false.
return_rep=.false.
end if
if (param(15).lt.0.0) then !if kTwind<0 show ONLY thermal component
return_disc=.false.
return_warm=.false.
return_hot=.false.
return_ref=.false.
end if
if (param(16).lt.0.0) then !if Awind<0 show ONLY reflected component
return_disc=.false.
return_warm=.false.
return_hot=.false.
return_rep=.false.
end if
if (rw.le.rh) then
call xwrite('r_warm <= r_hot!!! Re-setting r_w = r_h', 10)
rw = rh
return_warm=.false.
end if
if (rw.ge.rout) then
call xwrite('r_warm >= r_out!!! Re-setting r_w = r_out', 10)
rw = rout
return_disc=.false.
end if
if (hmax.gt.rh) then
call xwrite('hmax > r_hot!!! Re-setting hmax = r_hot', 10)
hmax = rh
end if
c-----------------------------------------------------------------------
c Section for calculating hot compton region (ie corona)
c-----------------------------------------------------------------------
c First finding the total seed photon luminosity/flux
c Integrated flux from entire disc seen by corona
c This section gets calculated even if return_hot false, since
c we need the xray luminosity for normalisation of the reflected
c and re-processed components + disc temperature.
c The switch for including hot component in SED is instead further
c down the script
nrseed = (log10(rout) - log10(rh)) * dr_dex
nrseed = ceiling(nrseed) !round up to nearest integer
dlog_rseed = (log10(rout) - log10(rh))/nrseed
lphseed = 0.0
do i=1, int(nrseed), 1
rmid = 10**(log10(rh)+float(i-1)*dlog_rseed+dlog_rseed/2.0)
dr = 10**(log10(rmid) + dlog_rseed/2.0)
dr = dr - 10**(log10(rmid) - dlog_rseed/2.0)
if ((rmid+dr/2.0+dr).gt.rout) then !Ensuring bin within region
dr = rout - 10**(log10(rmid) - dlog_rseed/2.0)
end if
if (hmax.le.rmid) then
theta0 = asin(hmax/rmid)
fcov = theta0 - 0.5*sin(2.0*theta0) !corona covering fraction seen from rmid
else
fcov = 0.0
end if
tr = nttemp(rmid, M, mdot, Mdot_edd, astar, risco) !Temp. K
lseed_ann = sigma_sb * tr**4.0 !erg/s/cm^2
lseed_ann = lseed_ann * 4*pi*rmid*dr*Rg**2 * (fcov/pi) !erg/s
lseed_ann = lseed_ann/(4*pi * dist**2) !erg/s/cm^2
lphseed = lphseed + lseed_ann !total seed photon flux erg/s/cm^2
end do
c Now finding seed photon temperature
c Assumed to be ~inner disc temp
tseed_h = nttemp(rh, M, mdot, Mdot_edd, astar, risco) !K
if (rh.lt.rw) then
ysb = (gammaw*(4.0/9.0))**(-4.5) !Compton y-param for warm region
tseed_h = (tseed_h/kkev) * exp(ysb) !in keV
else
tseed_h = (tseed_h/kkev)
end if
!calling nthcomp now, since intrinsic shape does not change!!!
nthpar(3) = tseed_h
call donthcomp(es, nn, nthpar, ifl, phh_shape, nthpherr)
!total flux output from nthcom
nth_out = 0.0
do n=1, nn, 1
nth_out = nth_out + phh_shape(n)*es(n)*kevhz*h !erg/s/cm^2
end do
c Now calculating emission from each coronal annulus
nrh = (log10(rh) - log10(risco)) * dr_dex
nrh = ceiling(nrh) !round up to integer
dlog_rh = (log10(rh) - log10(risco))/nrh !actual spacing
fx_tot = 0.0 !total xray flux - erg/s/cm^2
do i=1, int(nrh), 1
rmid = 10**(log10(risco)+float(i-1)*dlog_rh+dlog_rh/2.0)
dr = 10**(log10(rmid) + dlog_rh/2.0)
dr = dr - 10**(log10(rmid) - dlog_rh/2.0)
if ((rmid+dr/2.0+dr).gt.rh) then !Ensuring bin within region
dr = rh - 10**(log10(rmid) - dlog_rh/2.0)
end if
tr = nttemp(rmid, M, mdot, Mdot_edd, astar, risco) !K
ldiss_ann = sigma_sb * tr**4.0
ldiss_ann = ldiss_ann * 4.0*pi*rmid*dr * Rg**2.0 !erg/s
ldiss_ann = ldiss_ann/(4.0*pi * dist**2.0) !erg/s/cm^2
!Assuming equall amounts of emission from each coronal annulus
lseed_cann = lphseed/(nrh-1.0)
normh_ann = ldiss_ann + lseed_cann !erg/s/cm^2
fx_tot = fx_tot + normh_ann !erg/s/cm^2
!Now applying normalisation
do n=1, nn, 1
if (nth_out.eq.0) then
phh_ann(n) = 0.0
else
phh_ann(n) = phh_shape(n) * (normh_ann/nth_out) !photons/s/cm^2
end if
end do
if (return_hot) then
c Adding to total output array
do n=1, nn, 1
if (i.eq.1) then
ph(n) = phh_ann(n) !if no disc or warm comp start from scratch
else
ph(n) = ph(n) + phh_ann(n)
end if
end do
end if
end do
Lx_tot = fx_tot * 4.0*pi*dist**2 !Xray lum - erg/s
c-----------------------------------------------------------------------
c Section for calculating the disc region
c-----------------------------------------------------------------------
if (return_disc) then
nrd = (log10(rout) - log10(rw)) * dr_dex !nr of bins in region
nrd = ceiling(nrd) !round up to nearest integer value
dlog_rd = (log10(rout) - log10(rw))/nrd
do i=1, int(nrd), 1
rmid = 10**(log10(rw)+float(i-1)*dlog_rd+dlog_rd/2.0)
dr = 10**(log10(rmid)+dlog_rd/2.0)
dr = dr - 10**(log10(rmid)-dlog_rd/2.0)
if ((rmid+dr/2.0 + dr).gt.rout) then !Makes big bin at edge
dr = rout - 10**(log10(rmid)-dlog_rd/2.0)
end if
tr=repnttemp(rmid,M,mdot,Mdot_edd,astar,risco,hmax,Lx_tot) !Temp. K
c Calculating BB emission over each energy
do n=1, nn, 1
en = dble(log10(es(n-1)) + log10(es(n)))
en = en/2.0 !Evaluate in mid bin
en = 10**en
if (en.lt.30.0*tr) then
dflux = (pi*2.0 * h * (en*kevhz)**3.0)/(c**2.0)
dflux = dflux * 1.0/(exp((h*en*kevhz)/(kB*tr)) - 1.0)
dflux = dflux * 4.0*pi*rmid*dr*(cos_inc/0.5) *Rg**2.0 !multiplying by area
dflux = dflux/(4.0*pi*dist**2.0) !erg/s/cm^2/Hz
ph_ann(n) = dflux/(h*kevhz*en) !photons/s/cm^2/Hz
ph_ann(n) = ph_ann(n)*kevhz*(es(n)-es(n-1)) !photons/s/cm^2
else
ph_ann(n) = 0.0d0
end if
end do
c Adding into main photon array
do n=1, nn, 1
if (i.eq.1) then
if (return_hot) then
ph(n) = ph(n) + ph_ann(n)
else
ph(n) = ph_ann(n) !if no hot start from scratch
end if
else
ph(n)=ph(n)+ph_ann(n)
end if
end do
end do
end if
c-----------------------------------------------------------------------
c Section for calculating the warm Compton region
c-----------------------------------------------------------------------
if (return_warm) then
nrw = (log10(rw) - log10(rh)) * dr_dex !nr bins in region
nrw = ceiling(nrw) !round up to nearest integer
dlog_rw = (log10(rw) - log10(rh))/nrw !actual bin size
do i=1, int(nrw), 1
rmid = 10**(log10(rh)+float(i-1)*dlog_rw + dlog_rw/2.0)
dr = 10**(log10(rmid) + dlog_rw/2.0)
dr = dr - 10**(log10(rmid) - dlog_rw/2.0)
if ((rmid+dr/2.0+dr).gt.rw) then !Ensuring bin within region
dr = rw - 10**(log10(rmid) - dlog_rw/2.0)
end if
tr=repnttemp(rmid,M,mdot,Mdot_edd,astar,risco,hmax,Lx_tot) !Temp. K
ntwpar(3) = tr/kkev !setting seed temp to disc annulus temp (keV)
c Calling nthcomp
call donthcomp(es, nn, ntwpar, ifl, phw_ann, ntwpherr) !photons/s/cm^s/
normw_ann = sigma_sb*tr**4.0
normw_ann = normw_ann*4.0*pi*rmid*dr*(cos_inc/0.5)*Rg**2.0 !erg/s/, emission from annulus
normw_ann = normw_ann/(4.0*pi*dist**2.0) !erg/s/cm^2/
c Finding total flux output from nthcomp
ntw_out = 0.0
do n=1, nn, 1
ntw_out = ntw_out + phw_ann(n)*es(n)*kevhz*h !erg/s/cm^2
end do
c Now applying normalisation
do n=1, nn, 1
if (ntw_out.eq.0) then
phw_ann(n) = 0.0
else
phw_ann(n) = phw_ann(n) * (normw_ann/ntw_out) !photons/s/cm^2
end if
end do
c Adding to total output array
do n=1, nn, 1
if(i.eq.1) then
if ((return_disc).or.(return_hot)) then
ph(n) = ph(n) + phw_ann(n)
else
ph(n) = phw_ann(n) !if no disc or hot we start from scratch!
end if
else
ph(n) = ph(n) + phw_ann(n)
end if
end do
end do
end if
c-----------------------------------------------------------------------
c Section for calculating reflected component (i.e pexmon)
c-----------------------------------------------------------------------
if (return_ref) then
!Calling pexmon - no longer splitting into annuli
call pexmon(es, nn, pxpar, ifl, ph_ref, phref_err)
!Applying rdblur if included
if (inc_blur.eq.1) then
call rdblur(es, nn, rdpar, ifl, ph_ref, phrd_err)
end if
!Finding total pexmon output
px_out = 0.0
do n=1, nn, 1
px_out = px_out + ph_ref(n)*es(n)*kevhz*h !erg/s/cm^2
end do
!Applying normalisation - Lref=Awind*Lx*fcov_wind
norm_ref = Awind*fx_tot*fcov_wind*0.5 !erg/s/cm^2
do n=1, nn, 1
if (px_out.eq.0.0) then
ph_ref(n) = 0.0
else
ph_ref(n)=ph_ref(n) * (norm_ref/px_out)
end if
end do
!Adding to total output array
do n=1, nn, 1
if ((return_disc).or.(return_warm).or.(return_hot)) then
ph(n) = ph(n) + ph_ref(n)
else
ph(n) = ph_ref(n) !if only reflected component
end if
end do
end if
c-----------------------------------------------------------------------
c Section for calculating re-processed thermal component
c-----------------------------------------------------------------------
if (return_rep) then
!Calculating black-body shape of wind
call bbody(es, nn, bbpar, ifl, ph_rep, phbb_err)
!Finding black-body output flux
rep_out = 0.0
do n=1, nn, 1
rep_out = rep_out + ph_rep(n)*es(n)*kevhz*h !erg/s/cm^2
end do
!Applying normalisation
norm_rep = (1.0-Awind) * fcov_wind * fx_tot*0.5 !erg/s/cm^2
do n=1, nn, 1
if (rep_out.eq.0.0) then
ph_rep(n) = 0.0
else
ph_rep(n) = ph_rep(n) * (norm_rep/rep_out)
end if
end do
!Adding to total output array
do n=1, nn, 1
if ((return_disc).or.(return_warm).or.(return_hot)) then
ph(n) = ph(n) + ph_rep(n)
else if (return_ref) then
ph(n) = ph(n) + ph_rep(n)
else
ph(n) = ph_rep(n) !if only reprocessed component
end if
end do
end if
end
c-----------------------------------------------------------------------
c-----------------------------------------------------------------------
c Functions for calculating disc properties
c e.g risco, eta (efficiency), rsg, disc T, etc.
c-----------------------------------------------------------------------
c-----------------------------------------------------------------------
function calc_risco(astar)
c Calculates the innermost stable circular orbit/marginally stable
c orbit
implicit none
double precision astar, calc_risco
double precision Z1_1, Z1_2, Z1, Z2
Z1_1 = (1.0 - astar**2.0)**(1.0/3.0)
Z1_2 = (1.0 + astar)**(1.0/3.0) + (1.0 - astar)**(1.0/3.0)
Z1 = 1.0 + Z1_1 * Z1_2
Z2 = sqrt(3.0 * astar**2.0 + Z1**2.0)
if(astar.ge.0.0) then
calc_risco = 3.0 + Z2 - sqrt((3.0-Z1) * (3.0+Z1+2.0*Z2))
else
calc_risco = 3.0 + Z2 + sqrt((3.0-Z1) * (3.0+Z1+2.0*Z2))
end if
return
end
function efficiency(risc)
c Calculates the accretion efficiency, s.t L_bol=eta*Mdot*c^2
c Uses GR case where eta = 1 - sqrt(1 - 2/(3*risco))
c Taken from: The Physics and Evolution of Active Galactic Nuclei,
c H. Netzer, 2013, p.38
implicit none
double precision risc, efficiency
efficiency = 1.0 - sqrt(1.0 - 2.0/(3.0*risc))
return
end
function calc_rsg(M, mdot)
c Calculates the self gravity radius following Laor & Netzer 1989
c
c Note! Assumes \alpha=0.1
implicit none
double precision M, mdot, calc_rsg
double precision m9, alpha
alpha = 0.1
m9 = M/1.0d9
calc_rsg = 2150*m9**(-2.0/9.0)*mdot**(4.0/9.0)*alpha**(2.0/9.0)
return
end
function NTpars(r, astar, risc)
c Calculates the Novikov-Thorne parameters at a given radius
implicit none
double precision r, astar, risc
double precision pi, y, yisc, y1, y2, y3
double precision B, C1, C2, C, NTpars
double precision C2_1, C2_2, C2_3
pi = 4.0*atan(1.0)
y = sqrt(r)
yisc = sqrt(risc)
y1 = 2.0*cos((acos(astar) - pi)/3.0)
y2 = 2.0*cos((acos(astar) + pi)/3.0)
y3 = -2.0*cos(acos(astar)/3.0)
B = 1.0 - (3.0/r) + ((2.0*astar)/(r**(3.0/2.0)))
C1 = 1 - (yisc/y) - ((3.0*astar)/(2.0*y)) * log(y/yisc)
C2_1 = (3.0*(y1-astar)**2.0)/(y*y1 * (y1-y2) * (y1-y3))
C2_1 = C2_1 * log((y-y1)/(yisc-y1))
C2_2 = (3.0*(y2-astar)**2.0)/(y*y2 * (y2-y1) * (y2-y3))
C2_2 = C2_2 * log((y-y2)/(yisc-y2))
C2_3 = (3.0*(y3-astar)**2.0)/(y*y3 * (y3-y1) * (y3-y2))
C2_3 = C2_3 * log((y-y3)/(yisc-y3))
C2 = C2_1 + C2_2 + C2_3
C = C1 - C2
NTpars = C/B
return
end
function nttemp(r, M, mdot, Mdot_edd, astar, risc)
c Function to calculate Novikov-Thorne temperature at radius r
implicit none
double precision r, M, mdot, Mdot_edd, astar, risc
double precision pi, G, sigma_sb, c, Rg, Rt
double precision NTpars
double precision nttemp
pi = 4.0*atan(1.0)
G = 6.67d-8 * 1.99d33 !cm^3 s^-1 Msol^-1
sigma_sb = 5.670367d-5 !erg cm^-2 s^-1 K^-4
c = 3.0d10 !cm/s
Rg = (G*M)/c**2.0 !cm
Rt = NTpars(r, astar, risc)
nttemp = (3.0*G*M*mdot*Mdot_edd)/(8*pi*sigma_sb*(r*Rg)**3) !K^4
nttemp = nttemp*Rt
nttemp = nttemp**(1.0/4.0) !K
return
end
function repnttemp(r, M, mdot, Mdot_edd, astar, risc, hmax, Lx)
c Disc temperature inclusing re-processing
implicit none
double precision r, M, mdot, Mdot_edd, astar, risc, hmax, Lx
double precision pi, G, sigma_sb, c, Rg, Rt
double precision repnttemp, nttemp, reptemp
double precision frep, Rphys, Hphys
pi = 4.0*atan(1.0)
G = 6.67d-8 * 1.99d33 !cm^3 s^-1 Msol^-1
sigma_sb = 5.670367d-5 !erg cm^-2 s^-1 K^-4
c = 3.0d10 !cm/s
Rg = (G*M)/c**2.0 !cm
Rphys = r*Rg !cm
Hphys = hmax*Rg !cm
frep = Lx/(4.0*pi * (Rphys**2.0 + Hphys**2.0)) !erg/s/cm^2
frep = frep * Hphys/sqrt(Rphys**2.0 + Hphys**2.0)
frep = frep * (1.0-0.3) !Disc albedo assumed as 0.3
reptemp = frep/sigma_sb
repnttemp = nttemp(r, M, mdot, Mdot_edd, astar, risc)
repnttemp = repnttemp**4.0
repnttemp = repnttemp + reptemp
repnttemp = repnttemp**(1.0/4.0) !K
return
end |
from shape import Shape
class CollisionException(Exception):
pass
class NoShapeException(Exception):
pass
class Board:
def __init__(self, cell_size: int, cols: int, rows: int):
self.cell_size = cell_size
self.cols = cols
self.rows = rows
# Last row of 1 at the bottom for conflict detection
self.matrix = [[0 if y < self.rows else 1 for _ in range(self.cols)] for y in range(self.rows + 1)]
self.shapes = []
self.current_shape = None
def start_position(self) -> (int, int):
return int(self.cols / 2), 0
def update_shape_in_board(self, shape: Shape, clean: bool = False):
for off_y, row in enumerate(shape.layout):
for off_x, val in enumerate(row):
if val and 0 <= off_y + shape.pos_y < self.rows and 0 <= off_x + shape.pos_x < self.cols:
self.matrix[off_y + shape.pos_y][off_x + shape.pos_x] = val if not clean else 0
def update(self, inc_y: int = 0, inc_x: int = 0, rotate: int = 0):
if not self.current_shape:
raise NoShapeException()
if self.detect_collision(self.current_shape):
raise CollisionException()
self.update_shape_in_board(self.current_shape, True)
self.current_shape.pos_y += inc_y
if 0 <= self.current_shape.get_left() + inc_x and self.current_shape.get_right() + inc_x <= self.cols:
self.current_shape.pos_x += inc_x
if rotate:
self.current_shape.rotate()
self.update_shape_in_board(self.current_shape)
def add_new_shape(self):
self.current_shape = Shape(*self.start_position())
self.update_shape_in_board(self.current_shape)
self.shapes.append(self.current_shape)
def detect_collision(self, shape: Shape) -> bool:
boundary = shape.get_bottom_boundary()
for (off_x, off_y) in boundary:
if (shape.pos_y + off_y == self.rows) or (self.matrix[shape.pos_y + off_y + 1][shape.pos_x + off_x] != 0):
return True
return False
def is_full(self) -> bool:
for val in self.matrix[0]:
if val != 0:
return True
return False
def remove_line(self, y: int):
for off_y in range(y, 1, -1):
for off_x in range(0, self.cols):
self.matrix[off_y][off_x] = self.matrix[off_y - 1][off_x]
def check_completed_lines(self):
for off_y, row in enumerate(self.matrix):
if off_y < self.rows and all(cell != 0 for cell in row):
self.remove_line(off_y) |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="innerText">이너텍스트</p>
<input id="inputValue" type="text" value="밸류">
<button onclick="secret()">아이디 체크</button>
<div id="styleDisplay">디스플레이스 css</div>
<img id="setImg" src="./img/html로고.gif">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<ul id="for">
</ul>
</body>
</html>
<script>
// 웹 html을 조작하는 대표적인 언어이다.
// innerText : html안에 텍스트를 가져옴
console.log(document.querySelector('#innerText'));
console.log(document.querySelector('#innerText').innerText)
// value : html안에 밸류값을 가져옴
console.log(document.querySelector('#inputValue'));
console.log(document.querySelector('#inputValue').value);
console.log(document.querySelector('#inputValue').type);
// style.display : html안에 css를 가져옴
console.log(document.querySelector('#styleDisplay').style);
console.log(document.querySelector('#styleDisplay').style.display);
document.querySelector('#styleDisplay').style.fontSize = '100px';
console.log(document.querySelector('#styleDisplay').style.display);
// setAttribute : html안에 속성을 조작
// document.querySelector('#setImg').setAttribute('변경 전','변경 후')
// 자체적인 프로그래밍을 할 수 있다.
// 변수선언(var) 변수이름(test) = ''
var test = 'stop';
console.log('test');
console.log(test);
console.log(test);
console.log(test);
var myArray = ['abc','def','ghi','jkl']
console.log(myArray);
console.log(myArray[0]);
console.log(myArray[1]);
console.log(myArray[2]);
console.log(myArray[3]);
console.log(document.querySelectorAll('.item'))
var inputValue = document.querySelector('#inputValue').value;
// if (inputValue == '밸류') {
// alert('밸류가 맞습니다.')
// } else {
// alert('밸류가 아닙니다.')
// }
// 클라이언트 단에서 웹 페이지가 동작하는 것을 담당한다.
for (var i=0; i<10; i++) {
var item = document.createElement('li');
item.innerText = i
document.querySelector('#for').appendChild(item)
}
function secret() {
var inputValue = document.querySelector('#inputValue').value
if (inputValue == '밸류') {
alert('밸류라는 아이디를 사용할 수 없습니다.')
} else {
alert('정상적인 아이디입니다.')
}
}
</script> |
import React from "react";
import Link from "next/link";
interface sideMenuProps {
closeSideMenu: (close: boolean) => void;
}
const SideMenu = (props: sideMenuProps): JSX.Element => {
const { closeSideMenu } = props;
const handleCloseSideMenu = (toggle: boolean) => {
closeSideMenu(toggle);
};
return (
<section className="mt-3 min-h-screen bg-white py-4 px-4">
<div className="mb-6 flex justify-end">
<button
type="button"
className="mt-2"
onClick={() => handleCloseSideMenu(false)}
>
<svg
xmlns="http://www.w3.org/2000/svg"
height="32"
viewBox="0 0 24 24"
width="32"
>
<path d="M0 0h24v24H0z" fill="none" />
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
</svg>
</button>
</div>
<ul className="flex h-full flex-col items-center justify-center font-medium text-black">
<li className="hover:text-gray-lighter my-6 ">
<Link
href="/"
className="focus:text-gray-lighter text-2xl"
onClick={() => handleCloseSideMenu(false)}
>
Home
</Link>
</li>
<li className="hover:text-gray-lighter my-6 ">
<Link
href="/gallery"
className="focus:text-gray-lighter text-2xl"
onClick={() => handleCloseSideMenu(false)}
>
Gallery
</Link>
</li>
<li className="hover:text-gray-lighter my-6 ">
<Link
href="/commissions"
className="focus:text-gray-lighter text-2xl"
onClick={() => handleCloseSideMenu(false)}
>
Commissions
</Link>
</li>
{/* <li className="my-6 hover:text-gray-lighter ">
<Link
href="/blog"
className="focus:text-gray-lighter text-2xl"
onClick={() => handleCloseSideMenu(false)}
>
Blog
</Link>
</li> */}
<li className="hover:text-gray-lighter my-6 ">
<Link
href="/about"
className="focus:text-gray-lighter text-2xl"
onClick={() => handleCloseSideMenu(false)}
>
About Me
</Link>
</li>
<li className="hover:text-gray-lighter my-6 ">
<Link
href="/about/#contacts"
className="focus:text-gray-lighter text-2xl"
onClick={() => handleCloseSideMenu(false)}
>
Contacts
</Link>
</li>
</ul>
</section>
);
};
export default SideMenu; |
package com.everis.base.task.MercadoLibreCristian;
import com.everis.base.page.MercadoLibrePage;
import net.serenitybdd.annotations.Step;
import net.serenitybdd.screenplay.Performable;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.actions.Enter;
import static net.serenitybdd.screenplay.Tasks.instrumented;
public class BuscarProducto implements Task {
private final String producto;
public BuscarProducto(String producto){
this.producto = producto;
}
public static Performable withData(String producto){
return instrumented(BuscarProducto.class, producto);
}
@Override
@Step("{0} envia datos")
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
Enter.theValue(producto).into(MercadoLibrePage.INP_PRODUCTO));
}
} |
import React from 'react'
import { Form, FormGroup } from 'components'
import { Typeahead } from 'react-bootstrap-typeahead'
import options from './../exampleData'
class BasicBehaviorsExample extends React.Component {
constructor(props) {
super(props)
this.state = {
disabled: false,
dropup: false,
minLength: 0
}
}
render() {
const { disabled, dropup, emptyLabel, minLength } = this.state
return (
<div>
<Typeahead
{...this.state}
emptyLabel={emptyLabel ? '' : undefined}
labelKey="name"
multiple
options={options}
placeholder="Choose a state..."
/>
<FormGroup>
<Form.Check checked={disabled} name="disabled" onChange={this._handleChange}>
Disable
</Form.Check>
<Form.Check checked={dropup} name="dropup" onChange={this._handleChange}>
Dropup menu
</Form.Check>
<Form.Check checked={!!minLength} name="minLength" onChange={this._handleChange}>
Require minimum input before showing results (2 chars)
</Form.Check>
<Form.Check checked={emptyLabel} name="emptyLabel" onChange={this._handleChange}>
Hide the menu when there are no results
</Form.Check>
</FormGroup>
</div>
)
}
_handleChange = (e) => {
const { checked, name } = e.target
const newState = { [name]: checked }
if (name === 'minLength') {
newState.minLength = checked ? 2 : 0
}
this.setState(newState)
}
}
export default BasicBehaviorsExample |
from typing import Annotated
from fastapi import FastAPI, Request, Form
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import JSONResponse
from paramiko.ssh_exception import SSHException
from yaml import safe_load
from sshcheck import CheckedServer
from sshcheck.exceptions import InvalidTargetException
app = FastAPI()
templates = Jinja2Templates(directory='templates')
# Load the policy
with open('policy.yml', 'r') as policy_file:
ssh_policy = safe_load(policy_file)
@app.get('/', tags=['get', 'form'])
async def root(request: Request):
message = "Enter an IP to check."
return templates.TemplateResponse(
'form.html',
context={
'request': request,
'port': 22,
'message': message
}
)
@app.get('/host/{host}', response_class=JSONResponse, tags=['json', 'get'])
def get_json_result(host: str, port: int = 22):
try:
svr = CheckedServer(hostname=host, port=port, policy=ssh_policy)
except InvalidTargetException as e:
response = {'error': e}
return response
try:
svr.check_ssh()
except SSHException as e:
response = {'error': e}
return response
return {
'hostname': svr.hostname,
'ip_address': svr.ip_address,
'port': svr.port,
'server_host_key_type': svr.host_key_type,
'server_host_key_status': svr.host_key_status.name.lower(),
'kex': svr.kex,
'hka': svr.hka,
'ciphers': svr.ciphers,
'mac': svr.mac,
'compress': svr.compress,
'lang_list': svr.lang_list,
}
@app.post('/', tags=['post', 'form'])
async def form_post(request: Request, host: Annotated[str, Form()], port: Annotated[int, Form()]):
try:
svr = CheckedServer(hostname=host, port=port, policy=ssh_policy)
except InvalidTargetException as e:
return templates.TemplateResponse(
'form.html',
context={
'host': host,
'port': port,
'request': request,
'message': e
}
)
try:
svr.check_ssh()
except SSHException as e:
return templates.TemplateResponse(
'form.html',
context={
'host': host,
'port': port,
'request': request,
'message': e
}
)
return templates.TemplateResponse(
'form.html',
context={
'host': host,
'port': port,
'request': request,
'svr': svr
}
)
app.mount('/', StaticFiles(directory="static"), name="static") |
import PropTypes from 'prop-types';
const ConstellationList = ({ articles, selectedArticleIndex, handleArticleSelect }) => {
if (!articles.length) {
return <p>Нет статей для отображения.</p>;
}
return (
<ul className="constellation-list">
{articles.map((article, index) => (
<li
key={article.id}
className={`article-item ${index === selectedArticleIndex ? 'selected' : ''}`}
onClick={() => handleArticleSelect(index)}
>
{article.title}
</li>
))}
</ul>
);
};
ConstellationList.propTypes = {
articles: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired, // Изменено на title
})
).isRequired,
selectedArticleIndex: PropTypes.number,
handleArticleSelect: PropTypes.func.isRequired,
};
export default ConstellationList; |
package stepdefinitions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import net.serenitybdd.annotations.Step;
import pages.GooglePageObject;
public class GoogleSearchSteps {
GooglePageObject googlePageObject;
@Step("{0} opens browser on Google Page")
@Given("user is on google search page")
public void user_is_on_google_search_page() {
googlePageObject.open();
}
@Step("{0} user enters a text in search box")
@When("user enters a text in search box")
public void user_enters_a_text_in_search_box() {
googlePageObject.writeOnSearchField("Automation Step by Step");
}
@Step("{0} user enters a text in search box")
@When("user enters a text read on sheet in row {word} in search box")
public void user_enters_a_text_read_on_googleSheet_in_search_box(String row) {
googlePageObject.readSheetAndWriteOnSearchField(Integer.parseInt(row));
}
@Step("{0} user enters a text in search box")
@When("user enters a text read on DataBase in {word} in search box")
public void user_enters_a_text_read_on_dataBase_in_search_box(String id) {
googlePageObject.readDBAndWriteOnSearchField(Integer.parseInt(id));
}
@Step("{0} user hits enter")
@When("hits enter")
public void hits_enter() {
googlePageObject.pressEnterOnSearchField();
}
@Step("{0} assert that Online Courses exist in PageSource")
@Then("user is navigated to search results")
public void user_is_navigated_to_search_results() {
googlePageObject.assertContent();
}
} |
import '@testing-library/jest-dom';
import { render, RenderResult } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CountSelector from './count-selector';
vi.mock('../../primitives', async () => {
return {
Plus: vi.fn(() => <div data-testid="plus" />),
Minus: vi.fn(() => <div data-testid="minus" />),
Text: vi.fn((args: any) => <div data-testid="text" {...args} />),
};
});
describe('CountSelector', () => {
let renderResult: RenderResult;
let onValueChange = vi.fn();
beforeEach(() => {
onValueChange = vi.fn();
renderResult = render(
<CountSelector onValueChange={onValueChange} label="Adults" value={2} />
);
});
it('should render successfully', () => {
expect(renderResult.baseElement).toBeTruthy();
});
it('should render plus button', () => {
expect(renderResult.getByTestId('plus')).toBeTruthy();
});
it('should render minus button', () => {
expect(renderResult.getByTestId('minus')).toBeTruthy();
});
it('should render label', () => {
expect(renderResult.getByTestId('text')).toHaveAttribute('value', 'Adults');
});
it('should render value', () => {
expect(renderResult.getByText('2')).toBeTruthy();
});
describe('click minus button', () => {
beforeEach(async () => {
await userEvent.click(renderResult.getByTestId('minus'));
});
it('should call onValueChange with -1', () => {
expect(onValueChange).toHaveBeenCalledWith(-1);
});
});
describe('click plus button', () => {
beforeEach(async () => {
await userEvent.click(renderResult.getByTestId('plus'));
});
it('should call onValueChange with 1', () => {
expect(onValueChange).toHaveBeenCalledWith(1);
});
});
}); |
<%= form_for(@job) do |f| %>
<% if @job.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@job.errors.count, "error") %>
prohibited this product from being saved:</h2>
<ul>
<% @job.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description, rows: 6 %>
</div>
<div class="field">
<%= f.label :city %><br>
<%= f.text_field :city %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %> |
package com.example.maskkotlin
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.maskkotlin.model.Store
import java.lang.String
import java.util.*
// item view 의 정보를 가지고 있는 클래스
class StoreViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var nameTextView: TextView = itemView.findViewById(R.id.name_text_view)
var addressTextView: TextView = itemView.findViewById(R.id.addr_text_view)
var distanceTextView: TextView = itemView.findViewById(R.id.distance_text_view)
var remainTextView: TextView = itemView.findViewById(R.id.remain_text_view)
var countTextView: TextView = itemView.findViewById(R.id.count_text_view)
}
class StoreAdapter : RecyclerView.Adapter<StoreViewHolder>() {
private var mItems: List<Store> = ArrayList<Store>()
// view holder 를 만드는 부분
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StoreViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_store, parent, false)
return StoreViewHolder(view)
}
// View Holder 에 데이터를 bind 하는 부분
override fun onBindViewHolder(holder: StoreViewHolder, position: Int) {
val store: Store = mItems[position]
holder.nameTextView.text = store.name
holder.addressTextView.text = store.addr
holder.distanceTextView.text = "1km"
var color = Color.GREEN
var count = "100개 이상"
var remainStat = "충분"
when (store.remain_stat) {
"plenty" -> {
remainStat = "충분"
count = "100개 이상"
color = Color.GREEN
}
"some" -> {
remainStat = "여유"
count = "30개 이상"
color = Color.CYAN
}
"few" -> {
remainStat = "매진 임박"
count = "2개 이상"
color = Color.RED
}
"empty" -> {
remainStat = "재고 없음"
count = "1개 이하"
color = Color.GRAY
}
else -> {
}
}
holder.remainTextView.text = remainStat
holder.countTextView.text = count
holder.remainTextView.setTextColor(color)
holder.countTextView.setTextColor(color)
}
// override fun getItemCount(): Int {
// return mItems.size
// }
override fun getItemCount(): Int = mItems.size
fun updateItems(items: List<Store>) {
mItems = items
notifyDataSetChanged()
}
} |
/*
* 작성자: 윤정도
* 생성일: 11/24/2022 5:39:23 PM
*
*/
#pragma once
#include <atomic>
// [원자성 깨졌는지 테스트 용]
#define BROKEN_ATOMICITY_TEST 0
// 1. 읽기락 획득시 쓰기락이 되어있는지
inline std::atomic<int> g_broken_read_atomicity;
// 2. 쓰기락 획득시 읽기락이 되어있는지
inline std::atomic<int> g_broken_write_atomicity;
class my_atomic_rwlock
{
public:
void read_acquire()
{
READ_ACQUIRE:
// 쓰기를 수행중인 쓰레드가 없어질때까지 기다린다.
while (write_flag.load()) {}
while (true)
{
++read_counter;
if (write_flag)
{
--read_counter;
// 디버깅용 변수
// 여기 들어오는 경우가 있을 수 있는지 체크용
#if BROKEN_ATOMICITY_TEST
++g_broken_read_atomicity;
#endif
goto READ_ACQUIRE;
}
break;
}
}
void read_release()
{
if (read_counter > 0)
--read_counter;
}
void write_acquire()
{
WRITE_ACQUIRE:
// 먼저 읽기를 수행중인 쓰레드가 없어야한다.
// 따라서 읽기 카운터가 0이 될때까지 스핀한다.
while (read_counter.load() > 0) {}
while (true)
{
bool write_expected = false;
// compare_exchange_strong()
// expected: 기대값
// desired: 대입값
// return: 성공적으로 대입연산이 수행되면 true를 반환,
// 만약 false를 반환할경우 실제 저장된 값을 expected에 대입해서 반환해준다.
// write_flag값이 false일 경우 true로 설정해줘서 쓰기 잠금을 획득해준다.
if (write_flag.compare_exchange_strong(write_expected, true))
{
// 만약 성공적으로 교체된 후 read_counter가 0이 아닌 경우에는
// 다시 read_counter가 0이 될때까지 기다린다.
if (read_counter != 0)
{
write_flag = false;
#if BROKEN_ATOMICITY_TEST
++g_broken_write_atomicity; // 디버깅용 변수
#endif
goto WRITE_ACQUIRE;
}
break;
}
}
}
void write_release()
{
write_flag = false;
}
int read_count() const
{
return read_counter;
}
// 읽기락이 되어있을 때는 무조건 쓰기락 상태가 아니어야한다.
bool is_read_locked() const
{
return read_counter > 0 && write_flag == false;
}
// 쓰기락이 되어있을 때는 무조건 읽기락 상태가 아니어야한다.
bool is_write_locked() const
{
return write_flag && read_counter == 0;
}
private:
std::atomic<bool> write_flag = false;
std::atomic<int> read_counter = 0;
}; |
---
import { round } from "culori"
import { defaultColors } from "@utils/colors"
const round0 = round(0)
---
<section class="">
<div class="flex flex-col py-2 sm:flex-row sm:items-center sm:divide-x-2 dark:divide-neutral-600">
<label class="flex items-center gap-2 py-2 pr-3 sm:py-0"
><div class="text-sm">Select a color</div>
<input
id="input_colorPicker"
type="color"
title="Pick me! Pick me!"
class="size-8 rounded-sm bg-transparent outline-none focus:outline focus:outline-2 focus:outline-offset-2 focus:outline-users-500 sm:h-8 sm:w-6 md:size-8"
value={defaultColors.hex}
/>
</label>
<label class="flex items-center gap-2 py-2 sm:px-2 sm:py-0 md:px-3">
<div class="text-sm">Hex</div>
<input
id="input_colorHex"
class="selection:text-users-text w-[4.5rem] border-0 border-b-2 border-neutral-300 p-1 text-center outline-none selection:bg-users-500 invalid:border-2 invalid:border-red-500 focus:border-2 focus:border-users-500 focus:ring-users-500 dark:border-neutral-600 dark:bg-neutral-800"
type="text"
title="Go ahead and Paste me!"
pattern="#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})"
maxlength="7"
value={defaultColors.hex}
/>
</label>
<div class="flex items-center gap-3 py-2 sm:px-2 sm:py-0 md:px-3">
<label class="flex items-center gap-2">
<div class="text-center text-sm">Hue (deg)</div>
<input
id="input_colorHsl_h"
class="w-10 border-0 border-b-2 border-neutral-300 p-1 text-center invalid:border-red-500 disabled:bg-neutral-100 dark:border-neutral-600 dark:bg-neutral-800 dark:disabled:bg-neutral-700 dark:disabled:text-neutral-300"
type="text"
min="0"
max="360"
disabled
value={round0(defaultColors.hsl.h)}
/>
</label>
<label class="flex items-center gap-2">
<div class="text-center text-sm">Saturation (%)</div>
<input
id="input_colorHsl_s"
class="w-10 border-0 border-b-2 border-neutral-300 p-1 text-center invalid:border-red-500 disabled:bg-neutral-100 dark:border-neutral-600 dark:bg-neutral-800 dark:disabled:bg-neutral-700 dark:disabled:text-neutral-300"
type="text"
min="0"
max="100"
disabled
value={round0(defaultColors.hsl.s * 100)}
/>
</label>
<label class="flex items-center gap-2">
<div class="text-center text-sm">Lightness (%)</div>
<input
id="input_colorHsl_l"
class="w-10 border-0 border-b-2 border-neutral-300 p-1 text-center invalid:border-red-500 disabled:bg-neutral-100 dark:border-neutral-600 dark:bg-neutral-800 dark:disabled:bg-neutral-700 dark:disabled:text-neutral-300"
type="text"
min="0"
max="100"
disabled
value={round0(defaultColors.hsl.l * 100)}
/>
</label>
</div>
<div class="py-2 sm:px-2 sm:py-0 md:px-3">
<button
id="btn_reset"
type="button"
class="text-users-text rounded-sm bg-users-500 px-3 py-1 font-medium hover:shadow-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-users-500"
>Reset</button
>
</div>
<div id="errorMsg" class="px-3 text-sm text-red-600 dark:text-red-400"></div>
</div>
<hr class="hidden group-[.hide-instructions]/instructions:block dark:border-neutral-600" />
</section>
<script>
import { formatHex, round, hsl, wcagContrast } from "culori"
import {
updateShades,
type RectangularColorSpaceTypes,
type PolarColorSpaceTypes,
type HueInterpolationMethodTypes,
type LightnessColorSpaceTypes,
updateMixes,
getNearestTwHue,
updateTwColors
} from "@utils/colors"
const round0 = round(0)
const form_color = document.getElementById("form_color") as HTMLFormElement
const input_colorPicker = document.getElementById("input_colorPicker") as HTMLInputElement
const input_colorHex = document.getElementById("input_colorHex") as HTMLInputElement
const input_colorHsl_h = document.getElementById("input_colorHsl_h") as HTMLInputElement
const input_colorHsl_s = document.getElementById("input_colorHsl_s") as HTMLInputElement
const input_colorHsl_l = document.getElementById("input_colorHsl_l") as HTMLInputElement
const div_errorMsg = document.getElementById("errorMsg") as HTMLDivElement
const btn_reset = document.getElementById("btn_reset") as HTMLButtonElement
let colorHex_l_50 = input_colorPicker.value
/**
* When the color picker changes, update all the colors
*/
input_colorPicker.addEventListener("change", (e) => updateColor(e.target as HTMLInputElement))
input_colorHex.addEventListener("input", (e) => updateColor(e.target as HTMLInputElement))
const setErrorMsg = (msg: string) => {
div_errorMsg.innerText = msg
setTimeout(() => {
div_errorMsg.innerText = ""
}, 5000)
}
/**
* When something is pasted in colorHex, verify that it's a valid hex color and update all the colors
*/
input_colorHex.addEventListener("paste", (e: ClipboardEvent) => {
const hexRegExp = new RegExp(/#[A-Fa-f0-9]{6}|#[A-Fa-f0-9]{3}/)
// /[#a-fA-F0-9]+/
let clipboardText = e.clipboardData?.getData("text/plain")
if (clipboardText !== undefined && clipboardText.length > 0) {
if (clipboardText.length > 7) {
setErrorMsg(
"Invalid color input. Hex color cannot be longer than 7 characters. Alpha values are not accepted"
)
e.preventDefault()
return false
}
} else if (clipboardText?.length === 7) {
const match = clipboardText.match(hexRegExp)
if (!match) {
setErrorMsg("Invalid color code. Only valid hex color codes (e.g. #000000) are accepted.")
e.preventDefault()
return false
}
} else {
setTimeout(() => {
updateColor(input_colorHex as HTMLInputElement)
}, 10)
return true
}
})
/**
* When the reset button is clicked, reset the form and update all the colors
*/
btn_reset.addEventListener("click", () => {
form_color.reset()
updateColor(input_colorPicker)
})
const select_tw_colors = document.getElementById("select_tw_1") as HTMLSelectElement
select_tw_colors.addEventListener("change", () => {
// wait for the color to change
setTimeout(() => {
const ul_tw_colors = document.getElementById("ul_tw_1") as HTMLUListElement
const twColor500 = window
.getComputedStyle(ul_tw_colors.children[5])
.getPropertyValue("background-color")
input_colorPicker.value = formatHex(twColor500)!
updateColor(input_colorPicker as HTMLInputElement)
}, 10)
})
/**
* When the color is changed, update all the elements with the new color
* @param input The \<input /\> element that triggered the update
*/
const updateColor = (input: HTMLInputElement) => {
if (input.checkValidity()) {
div_errorMsg.innerText = ""
if (input.id === "input_colorPicker") {
input_colorHex.value = input.value
} else if (input.id === "input_colorHex") {
input_colorPicker.value = input.value
}
const hslColor = hsl(input.value)
if (hslColor) {
const tw = getNearestTwHue(hslColor.h!)
const select_tw_1 = document.getElementById("select_tw_1") as HTMLSelectElement
if (select_tw_1.dataset.color !== tw.name) {
select_tw_1.value = tw.name
updateTwColors()
}
input_colorHsl_h.value = round0(hslColor.h!).toString()
input_colorHsl_s.value = round0(hslColor.s! * 100).toString()
input_colorHsl_l.value = round0(hslColor.l! * 100).toString()
hslColor.l = 0.5
colorHex_l_50 = formatHex(hslColor) as string
const contrastRatioWhite = wcagContrast(colorHex_l_50, "white")
const contrastRatioBlack = wcagContrast(colorHex_l_50, "black")
if (contrastRatioBlack > contrastRatioWhite) {
document.body.classList.add("black-check")
} else {
document.body.classList.remove("black-check")
}
document.body.setAttribute(
"style",
`--color-users-text: none 0% ${contrastRatioBlack > contrastRatioWhite ? "0" : "100"}%; --color-users-500: ${hslColor.h}deg ${hslColor.s * 100}% ${hslColor.l * 100}%; --color-users-s1: ${hslColor.h}deg ${1}% ${hslColor.l * 100}%; --color-users-s15: ${hslColor.h}deg ${15}% ${hslColor.l * 100}%;`
)
const shadeCols = document.querySelectorAll<HTMLElement>("[data-cs-type]")
if (shadeCols) {
for (const shadeCol of shadeCols) {
const selects = shadeCol.getElementsByTagName("select")
const ul = shadeCol.getElementsByTagName("ul")[0]
switch (shadeCol.dataset.csType) {
case "cs":
updateShades(
colorHex_l_50,
ul,
selects[0].options[selects[0].selectedIndex].value as LightnessColorSpaceTypes
)
break
case "rcs":
updateMixes(
colorHex_l_50,
ul,
selects[0].options[selects[0].selectedIndex].value as RectangularColorSpaceTypes
)
break
case "pcs":
updateMixes(
colorHex_l_50,
ul,
selects[0].options[selects[0].selectedIndex].value as PolarColorSpaceTypes,
selects[1].options[selects[1].selectedIndex].value as HueInterpolationMethodTypes
)
break
default:
break
}
}
}
}
resetPalettePicker()
} else {
div_errorMsg.innerText = "Invalid Color input"
}
}
/**
* Reset the radio buttons so that none of the color spaces are selected
*/
const resetPalettePicker = () => {
const rdo_palettes = document.getElementsByName("rdo_palette")
if (rdo_palettes) {
for (const input of rdo_palettes) {
if ((input as HTMLInputElement).checked) {
;(input as HTMLInputElement).checked = false
}
}
}
}
</script> |
from random import randint
class Dot:
def __init__(self, x, y):
self.x = x
self.y = y
# сравнение двух точек
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __repr__(self):
return f"Dot({self.x}, {self.y})"
# Классы исключений
class BoardException(Exception): #общий класс
pass
class BoardOutException(BoardException):
def __str__(self):
return "Вы пытаетесь высьрелить за доску!"
class BoardUsedException(BoardException):
def __str__(self):
return "Вы уже стреляли в эту клетку"
#исключение для размещения кореблей
class BoardWrongShipException(BoardException):
pass
class Ship:
#конструктор корабля
def __init__(self, bow, l, o): # o -orientation
self.bow = bow
self.l = l # длина корабля
self.o = o # Ориенатцяи корабля 0 -вертикаль 1- горизонталь
self.lives = l # кол-во жизней
@property # метод вычисляет cвойство
def dots(self):
ship_dots = []
for i in range(self.l):
cur_x = self.bow.x
cur_y = self.bow.y
if self.o == 0:
cur_x += i
elif self.o == 1:
cur_y += i
ship_dots.append(Dot(cur_x, cur_y))
return ship_dots
# метод выстрел, проверка попадания
def shooten(self, shot):
return shot in self.dots
class Board:
def __init__(self, hid=False, size=6):
self.size = size
self.hid = hid
self.count_kill = 0 #счетчик подбитых кораблей
# состояние полей
self.field = [ ["0"]*size for _ in range(size)] # заполняем 0
self.busy = [] # занятые точки, корабль либо выстрел
self.ships = [] # список кораблей
# вывод корабля на доску
def __str__(self): # метод вывода доски, вызовом print доски
res = ""
i = 0
for row in self.field: # счетчик-цикл прохода по строкам доски
res += f"\n{i+1} ▌ " + " | ".join(row) + " ▌"# +f" {i+1} | " + " | ".join(row) + " ▌" # номер строки +
i += 1
# скрытие клетки
if self.hid:
res = res.replace("■", "0")
return res
# метод проверяющий выхода точки за пределы поля
def out(self, d):
return not((0 <=d.x < self.size) and (0 <= d.y < self.size))
# КОРАБЛЬ НА ДОСКЕ
# МЕТОД КОНТУР КОРАБЛЯ
def contur(self, ship, verb =False):
# поле вокруг корабля
near = [
(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 0), (0, 1),
(1, -1), (1, 0), (1, 1),
]
for d in ship.dots:
for dx, dy in near:
cur = Dot(d.x + dx, d.y + dy)
if not(self.out(cur)) and cur not in self.busy:
if verb:
self.field[cur.x][cur.y] = "."
self.busy.append(cur)
# МЕТОД ДОБАВЛЕНИЯ КОРАБЛЯ
def add_ship(self, ship):
for d in ship.dots:
# не выходит точка за границу или не занята
if self.out(d) or d in self.busy: #
raise BoardWrongShipException()
for d in ship.dots:
self.field[d.x][d.y] = "■"
self.busy.append(d) # добав. точку в список занятых
self.ships.append(ship)
self.contur(ship)
def shot(self, d):
if self.out(d):
# исключение если точка вне границы
raise BoardOutException()
if d in self.busy:
# исключение если точка занята
raise BoardUsedException()
self.busy.append(d)
# проверка точки на принадлежность кораблю
for ship in self.ships:
if ship.shooten(d):
ship.lives -= 1
self.field[d.x][d.y] = "X"
if ship.lives == 0:
self.count_kill += 1
self.contur(ship, verb= True)
print("Корабль уничтожен!")
return False
else:
print("Попадание в корабль!")
return True
self.field[d.x][d.y] = "."
print("Мимо!")
return False
def begin(self):
self.busy = []
def defeat(self):
return self.count_kill == len(self.ships)
class Player:
def __init__(self, board, enemy):
self.board = board
self.enemy = enemy
def ask(self):
raise NotImplementedError()
def move(self):
while True:
try:
target = self.ask() # запрос координат на выстрел
repeat = self.enemy.shot(target)
return repeat
# неправльный выстрел, вызвать исключение
except BoardException as e:
print(e)
# Классы игроков компьютера и пользователя
class AI(Player):
def ask(self):
# генерация случайной точки для выстрела компа
d = Dot(randint(0,5), randint(0, 5))
print(f"Ход компьютера: {d.x+1} {d.y+1}")
return d
# запрос координат от пользователя
class User(Player):
def ask(self):
while True:
cords = input("Ваш ход: ").split()
if len(cords) != 2:
print("Введите 2 координаты! ")
continue
x, y = cords
if not(x.isdigit()) or not(y.isdigit()):
print(" Введите числа! ")
continue
x, y = int(x), int(y)
return Dot(x-1, y-1)
# Класс ИГРА И ГЕНЕРАЦИЯ ДОСОК
class Game:
def try_bord(self):
lens = [3, 2, 2, 1, 1, 1, 1] # длина кораблей
board = Board(size = self.size)
attempts = 0
for l in lens:
while True:
attempts += 1
if attempts > 2000: # кол-во попыток итераций для создания доски
return None
ship = Ship(Dot(randint(0, self.size), randint(0, self.size)), l, randint(0,1))
try:
board.add_ship(ship) # добавление корабля
break
except BoardWrongShipException:
pass
board.begin()
return board
# генерация доски
def random_board(self):
board = None
while board is None:
board = self.try_bord()
return board
def __init__(self, size = 6):
self.size = size
# создаем две доски для игрока и компьютера
pl = self.random_board()
pc = self.random_board()
pc.hid = True
# создаем двух игроков
self.ai = AI(pc, pl)
self.us = User(pl, pc)
def greet(self):
print("| игра МОРСКОЙ БОЙ |")
print(" формат ввода: х у ")
print(" x - номер строки ")
print(" у - номер столбца")
def print_boards(self):
print("-" * 20)
print("Доска пользователя: ")#+" "*10+"Доска компьютера:")
print(" ▌ 1 | 2 | 3 | 4 | 5 | 6 ▌ ", end=" ")
print(self.us.board)
print("-" * 20)
print("Доска компьютера:")
print(" ▌ 1 | 2 | 3 | 4 | 5 | 6 ▌ ", end=" ")
print(self.ai.board)
# for i in range(self.size):
print("-" * 20)
def loop(self):
num = 0 # номер хода
while True:
self.print_boards()
if num % 2 == 0:
print("Ходит пользователь!")
repeat = self.us.move()
else:
print("Ходит компьютер!")
repeat = self.ai.move()
if repeat:
num -= 1
if self.ai.board.defeat():
self.print_boards()
print("-"*20)
print("Пользователь выиграл!")
break
if self.us.board.defeat():
self.print_boards()
print("-"*20)
print("Компьютер выиграл!")
break
num += 1
# МЕТОД "СТАРТ"
def start(self):
self.greet()
self.loop()
# ЗАПУСК ИГРЫ
g = Game()
g.start() |
# Xhulia Turkaj SQL Bridge Course MSDS 2023 Week 2 Assignment
# Question 1. Videos table. Create one table to keep track of the videos.
# This table should include a unique ID, the title of the video, the length in minutes, and the URL.
# Populate the table with at least three related videos from YouTube
# or other publicly available resources.
CREATE TABLE videos
(
unique_ID INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
title VARCHAR(200) NOT NULL,
duration INT NULL,
url VARCHAR(300) NULL
);
INSERT INTO videos (title, duration, url)
VALUES
('SQL Tutorial - Full Database Course for Beginners', 260 , 'https://www.youtube.com/watch?v=HXV3zeQKqGY'),
('SQL Joins Explained |¦| Joins in SQL |¦| SQL Tutorial', 10, 'https://www.youtube.com/watch?v=9yeOJ0ZMUYw'),
( 'Learn Basic SQL in 15 Minutes | Business Intelligence For Beginners | SQL Tutorial For Beginners 1/3',17 ,'https://www.youtube.com/watch?v=kbKty5ZVKMY');
SELECT * FROM Videos;
# Question 2 Create and populate Reviewers table.
# Create a second table that provides at least two user reviews for each of at least two of the videos.
# These should be imaginary reviews that include columns for the user’s name (“Asher”, “Cyd”, etc.),
# the rating (which could be NULL, or a number between 0 and 5), and a short text review (“Loved it!”).
# There should be a column that links back to the ID column in the table of videos.
CREATE TABLE Reviewers
(
rating_id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
video_id INT NOT NULL,
user_name VARCHAR(50) NOT NULL,
rating INT CHECK (rating >= 0 AND rating <= 5) NULL,
review VARCHAR(500) NOT NULL
);
INSERT INTO Reviewers (video_id, user_name, rating, review)
VALUES
(1, 'xhulia', 2, 'Thorough explanation but the speaker talks too fast'),
(2, 'rogg@', 5, 'I owe this video the start of my new career'),
(1, 'moon', NULL, 'Better than those coding camps for sure!'),
(7, 'speaktomedata', 4, '');
SELECT * FROM Reviewers;
# Question 3 Report on Video Reviews.
# Write a JOIN statement that shows information from both tables.
SELECT
R.rating_id AS 'Rating ID',
R.user_name AS 'User Name',
R.video_id AS 'Video ID',
V.title AS 'Title',
R.rating AS 'Rating',
R.review AS 'Review',
V.url AS 'Video URL'
FROM Reviewers as R
INNER JOIN videos as V
ON R.video_iD = V.unique_ID; |
#### code/assembly_analysis/hgcA/clean_hgcA_coverage.R ####
# Written by Benjamin D. Peterson
# hgcA abundance normalized to the SCG coverage
#### Get ready. Get set ####
rm(list = ls())
setwd("/Users/benjaminpeterson/Documents/research/Everglades/")
library(stringr)
library(tidyverse)
#### Read in normalization vector ####
normalized.coverage.vector <- readRDS("dataEdited/assembly_analysis/SCGs/scg_normalization_vector.rds")
#### Read in list of good hgcA seqs ####
hgcA.list <- readLines("dataEdited/assembly_analysis/hgcA/identification/hgcA_good.txt")
#### List of file names with depth info ####
list.o.depth.files <- list.files(path = "dataEdited/assembly_analysis/hgcA/depth",
pattern = "hgcA_depth",
full.names = TRUE)
#### Read in and normalize depth data ####
raw.depth.counts <- lapply(list.o.depth.files,
function(fileName) {
metagenomeID = fileName %>%
gsub("dataEdited/assembly_analysis/hgcA/depth/", "", .) %>%
gsub("_hgcA_depth.tsv", "", .)
read.table(fileName,
stringsAsFactors = FALSE,
col.names = c("seqID", "depth", "length")) %>%
mutate(depth = depth * normalized.coverage.vector[metagenomeID]) %>%
mutate(read.origin = metagenomeID)
})
#### Combine data into dataframe ####
depth.data <- do.call(rbind,
raw.depth.counts) %>%
spread(key = read.origin, value = depth, fill = NA) %>%
rename(scaffoldID = seqID)
#### Write out file with depths for all sequences ####
write.csv(depth.data,
"dataEdited/assembly_analysis/hgcA/depth/hgcA_coverage_raw_scgNormalization.csv",
row.names = FALSE)
#### Clean depth file for final hgcA seqs ####
# Get a scaffold to ORF vector
scaffold.to.ORF <- sapply(depth.data$scaffoldID,
function(x) {
grep(x, hgcA.list, value = TRUE)
}) %>%
unlist()
# Keep only depth info for good seqs and sum abundance
depth.data.final <- depth.data %>%
mutate(seqID = scaffold.to.ORF[scaffoldID]) %>%
filter(!is.na(seqID)) %>%
mutate(total = KMBP005A + KMBP005B + KMBP005C + KMBP005D + KMBP005E +
KMBP005F + KMBP005G + KMBP005H + KMBP005I + KMBP005J + KMBP005K +
KMBP005L + KMBP006A + KMBP006B + KMBP006C + KMBP006D + KMBP006E +
KMBP006F) %>%
select(seqID, scaffoldID, length, total, KMBP005A, KMBP005B,
KMBP005C, KMBP005D, KMBP005E, KMBP005F, KMBP005G,
KMBP005H, KMBP005I, KMBP005J, KMBP005K, KMBP005L,
KMBP006A, KMBP006B, KMBP006C, KMBP006D, KMBP006E,
KMBP006F)
#### Read out depth file for final hgcA seqs ####
write.csv(depth.data.final,
"dataEdited/assembly_analysis/hgcA/depth/hgcA_coverage_scgNormalization.csv",
row.names = FALSE) |
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Update Center Info</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container mt-5">
<h2>Update Center Information</h2>
<form id="updateCenterForm">
<input type="hidden" id="repId" th:value="${repId}" />
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" name="address" required>
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" id="location" name="location" required>
</div>
<div class="form-group">
<label for="bio">Bio</label>
<textarea class="form-control" id="bio" name="bio" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Update Information</button>
</form>
</div>
<script>
$(document).ready(function() {
$('#updateCenterForm').on('submit', function(event) {
event.preventDefault();
const repId = $('#repId').val();
const name = $('#name').val();
const email = $('#email').val();
const address = $('#address').val();
const location = $('#location').val();
const bio = $('#bio').val();
console.log(email)
console.log("ID: "+repId);
console.log(location)
console.log(address)
const centerData = {
name: name,
email: email,
address: address,
location: location,
bio: bio
};
$.ajax({
url: `/Center/updateInfo/${repId}`,
type: 'PUT',
contentType: 'application/json',
data: JSON.stringify(centerData),
success: function(response) {
alert('Center information updated successfully');
},
error: function(error) {
alert('Error updating center information');
}
});
});
});
</script>
</body>
</html> |
type inputObject = {
timeStamp: string;
isQuery: boolean;
speed?: number;
distance?: number;
};
const input: string = `
6
00:00:01 100
00:15:01
00:30:01
01:00:01 50
03:00:01
03:00:05 140
`;
let processedInput: inputObject[] = processInput(input);
let calculatedInput: inputObject[] = calculateDistances(processedInput);
let output: string = generateOutput(calculatedInput);
console.log(output);
//Split input at a new line
function processInput(input: string): inputObject[] {
let sanitazedString = sanitazeInput(input);
return convertInputToObjectArray(sanitazedString);
}
function sanitazeInput(input: string): string[] {
let convertedInput: string[] = input.split("\n");
convertedInput = convertedInput.filter((line) => line !== "");
convertedInput.shift();
return convertedInput;
}
function convertInputToObjectArray(sanitazedInput: string[]): inputObject[] {
return sanitazedInput.map((string) => {
const splittedString: string[] = string.split(" ");
const timeStamp: string = splittedString[0];
let speed: number = parseInt(splittedString?.[1]);
if (isNaN(speed)) {
return {
timeStamp: timeStamp,
isQuery: true,
};
}
return {
timeStamp: timeStamp,
speed: speed,
isQuery: false,
};
});
}
function calculateDistances(input: inputObject[]): inputObject[] {
let currentSpeed: number = 0;
let currentDistance: number = 0;
let oldTimeInSeconds: number = 0;
return input.map((inputLine: inputObject) => {
const timeInSeconds = calculateTimeInSeconds(inputLine.timeStamp);
const lineDistance = currentSpeed * (timeInSeconds - oldTimeInSeconds);
oldTimeInSeconds = timeInSeconds;
currentDistance += lineDistance;
const calculatedInputLine: inputObject = {
...inputLine,
distance: currentDistance,
};
if (!inputLine.isQuery) {
currentSpeed = inputLine.speed! / 3.6 / 1000;
}
return calculatedInputLine;
});
}
function calculateTimeInSeconds(timeStamp: string): number {
const splittedTime: string[] = timeStamp.split(":");
const hours: number = parseInt(splittedTime[0]);
const minutes: number = parseInt(splittedTime[1]);
const seconds: number = parseInt(splittedTime[2]);
const calculatedTime = seconds + minutes * 60 + hours * 3600;
return calculatedTime;
}
function generateOutput(input: inputObject[]): string {
let output = "";
for (const inputLine of input) {
if (inputLine.isQuery) {
output += `\n${inputLine.timeStamp} ${inputLine.distance!.toFixed(2)} km`;
}
}
return output;
} |
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import Layout from '../components/Layout';
import { showLoading, hideLoading } from '../redux/alertsSlice';
import { toast } from 'react-hot-toast';
import axios from 'axios';
import { DatePicker, Table } from 'antd';
import moment from 'moment';
import { listOfAppointmentStatus, listOfClinics } from '../mock/LayoutMenu';
function Appointments() {
const [appointments, setAppointments] = useState([]);
const dispatch = useDispatch();
const getAppointmentsData = async () => {
try {
dispatch(showLoading());
const resposne = await axios.get('/api/user/get-appointments-by-user-id', {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
});
dispatch(hideLoading());
if (resposne.data.success) {
setAppointments(resposne.data.data);
}
} catch (error) {
dispatch(hideLoading());
}
};
const columns = [
{
title: 'Specialization',
dataIndex: 'specialization',
render: (text, record) => (
<span>
{listOfClinics.find((x) => x.value == record.doctorInfo.specialization)?.label ??
record.doctorInfo.specialization}
</span>
),
},
{
title: 'Doctor',
dataIndex: 'name',
render: (text, record) => (
<span>
{record.doctorInfo.firstName} {record.doctorInfo.lastName}
</span>
),
},
{
title: 'Phone',
dataIndex: 'phoneNumber',
render: (text, record) => <span>{record.doctorInfo.phoneNumber}</span>,
},
{
title: 'Date & Time',
dataIndex: 'createdAt',
render: (text, record) => (
<span>
{moment(record.date).format('DD-MM-YYYY')} {moment(record.time).format('HH:mm')}
</span>
),
},
{
title: 'Status',
dataIndex: 'status',
render: (text, record) => (
<span>{listOfAppointmentStatus.find((x) => x.value === record.status)?.label ?? record.status}</span>
),
},
];
useEffect(() => {
getAppointmentsData();
}, []);
return (
<Layout>
<h1 className='page-title'>Appointments</h1>
<hr />
<Table rowKey='_id' columns={columns} dataSource={appointments} />
</Layout>
);
}
export default Appointments; |
<?php
namespace App\Repository;
use App\Entity\User;
use App\Entity\Client;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<User>
*
* @method User|null find($id, $lockMode = null, $lockVersion = null)
* @method User|null findOneBy(array $criteria, array $orderBy = null)
* @method User[] findAll()
* @method User[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class UserRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
public function add(User $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(User $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function findAllWithPagination($page, $limit, $linkedClient) {
if ($linkedClient > 0) {
$qb = $this->createQueryBuilder('b')
->andWhere('b.client = :val')
->setParameter('val', $linkedClient)
->setFirstResult(($page - 1) * $limit)
->setMaxResults($limit);
} else {
$qb = $this->createQueryBuilder('b')
->setFirstResult(($page - 1) * $limit)
->setMaxResults($limit);
}
return $qb->getQuery()->getResult();
}
// /**
// * @return User[] Returns an array of User objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('u')
// ->andWhere('u.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('u.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?User
// {
// return $this->createQueryBuilder('u')
// ->andWhere('u.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
} |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $with = ['category', 'author'];
public function comments()
{
return $this->hasMany(Comment::class);
}
public function category()
{
// allows to display necessary category
// belongs to relationship
return $this->belongsTo(Category::class);
}
public function author()
{
// "a post belongs to a user"
// author is a user that has posts and own user_id (!not author_id)
return $this->belongsTo(User::class, 'user_id');
}
public function scopeFilter($query, array $filters)
{
// when() is system function
$query->when($filters['search'] ?? false, function ($query, $search) {
$query->where(fn($query) =>
$query->where('title', 'like', '%' . request('search') . '%')
->orWhere('body', 'like', '%' . request('search') . '%')
);
});
$query->when($filters['category'] ?? false, fn($query, $category) =>
$query->whereHas('category', fn ($query) =>
$query->where('slug', $category)
)
);
$query->when($filters['author'] ?? false, fn($query, $author) =>
$query->whereHas('author', fn ($query) =>
$query->where('username', $author)
)
);
}
} |
# Hero Component
The Hero Component directory contains a component that showcases the hero section of your web application. The hero section includes information about the counties served and contact options, allowing users to easily reach out to you via email or phone.
## Component: `Hero`
The `Hero` component displays the hero section of your web application. It includes the following elements:
- Counties served: Information about the counties where your mobile notary services are available.
- Hero text: A personalized message providing an overview of your services and inviting users to contact you.
- Contact buttons: Buttons that allow users to quickly reach out to you via email or phone.
## Usage
To use the `Hero` component in your application, follow these steps:
1. Import the `Hero` component into the file where you want to include the hero section.
```javascript
import Hero from './Hero/Hero';
// ... other imports ...
```
2. Place the `Hero` component in a prominent location, such as the top of your homepage, to capture users' attention and encourage them to take action.
```javascript
function App() {
return (
<div className="wrapper">
<Hero />
{/* ... other components ... */}
</div>
);
}
export default App;
```
### Dynamic Content Links
The `Hero` component dynamically generates contact links for email and phone. It replaces placeholder strings in the hero text with clickable links. Users can easily contact you by clicking on the "Email Me" and "Call Me" buttons.
### Counties Served Information
The hero section prominently displays the counties you serve, providing users with essential information about the areas where your mobile notary services are available. |
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:todo_project/screens/log/login_tab.dart';
import 'package:todo_project/shared/firebase/firebaseFunctions.dart';
import 'package:todo_project/shared/styles/colors.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class SignUpTab extends StatefulWidget {
static const String routeName="signup";
@override
State<SignUpTab> createState() => _SignUpTabState();
}
class _SignUpTabState extends State<SignUpTab> {
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController nameController = TextEditingController();
bool secure=true;
var formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: primaryColor,
body: Column(
children: [
Container(
height: 200.h,
width: double.infinity,
padding: EdgeInsets.all(16),
child:Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(AppLocalizations.of(context)!.appTitle,style: Theme.of(context)
.textTheme
.bodyLarge!
.copyWith(color:Colors.white,fontSize: 28.sp),
),
],
),
),
Expanded(
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.onBackground,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20.r),
topRight: Radius.circular(20.r))),
child: Padding(
padding: const EdgeInsets.all(30),
child: Form(
key: formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Center(
child: Text("Sign up",
style: Theme.of(context).textTheme.bodyLarge!.copyWith(
color: Theme.of(context).colorScheme.onPrimary)),
),
SizedBox(height: 30.h,),
TextFormField(
controller: nameController,
validator: (value) {
if (value == null || value.isEmpty) {
return "please enter your user name";
}
return null;
},
decoration: InputDecoration(
label: Text("User name",
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: Theme.of(context).colorScheme.onPrimary)),
prefixIcon: Icon(Icons.person_outlined,color: Theme.of(context).colorScheme.secondary),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
width: 2,
color:primaryColor,
),
borderRadius: BorderRadius.circular(12.r)
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
width: 2,
color:primaryColor,
),
borderRadius: BorderRadius.circular(12.r),
),
),
),
SizedBox(
height: 30.h,
),
TextFormField(
keyboardType: TextInputType.emailAddress,
controller: emailController,
validator: (value) {
if (value == null || value.isEmpty) {
return "please enter your Email";
}
final bool emailValid = RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[com]+")
.hasMatch(value);
if (!emailValid) {
return "please enter valid email";
}
return null;
},
decoration: InputDecoration(
label: Text("Email",
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: Theme.of(context).colorScheme.onPrimary)),
prefixIcon: Icon(Icons.email_rounded,color: Theme.of(context).colorScheme.secondary),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
width: 2,
color: primaryColor,
),
borderRadius: BorderRadius.circular(12.r)
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
width: 2,
color:primaryColor,
),
borderRadius: BorderRadius.circular(12.r)
),
),
),
SizedBox(
height: 30.h,
),
TextFormField(
obscureText: secure?true:false,
controller: passwordController,
validator: (value) {
if (value == null || value.isEmpty) {
return "please enter your password";
}
RegExp regex = RegExp(r'^(?=.*?[a-z])(?=.*?[0-9]).{8,}$');
if (!regex.hasMatch(value)) {
return 'Enter valid password';
}
return null;
},
decoration: InputDecoration(
label: Text("Password",
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: Theme.of(context).colorScheme.onPrimary
)),
prefixIcon: Icon(Icons.lock,color: Theme.of(context).colorScheme.secondary),
suffixIcon:IconButton(onPressed:() {
secure=!secure;
setState(() {
});
}, icon:Icon(Icons.remove_red_eye_rounded,color: Theme.of(context).colorScheme.secondary),),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
width: 2,
color:primaryColor,
),
borderRadius: BorderRadius.circular(12.r)
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
width: 2,
color:primaryColor,
),
borderRadius: BorderRadius.circular(12.r)
),
),
),
SizedBox(
height: 40.h,
),
Center(
child: ElevatedButton(
onPressed: () {
if (formKey.currentState!.validate()) {
FireBaseFunctions.createUser(
nameController.text,
emailController.text,
passwordController.text,
() {
Navigator.pushNamedAndRemoveUntil(
context,LoginTab.routeName, (route) => false);
},
(message) {
showDialog(
barrierDismissible: false,
context: context,
builder: (context) => AlertDialog(
title: Text("Error"),
content: Text(message),
actions: [
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text("Okey",
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: Colors.white)),
),
],
),
);
},
);
}
},
style: ButtonStyle(
padding: MaterialStatePropertyAll(
EdgeInsets.symmetric(horizontal: 70, vertical: 8),
),
shape: MaterialStatePropertyAll(RoundedRectangleBorder(
borderRadius: BorderRadiusDirectional.circular(12.r),
))),
child: Text("Sign Up",
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: Colors.white))),),
SizedBox(height: 40.h),
InkWell(
onTap: () {
Navigator.pushNamed(context, LoginTab.routeName);
},
child: Column(
children: [
Text("Already have an account ? ",
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: Theme.of(context).colorScheme.onPrimary,fontWeight: FontWeight.w200)),
SizedBox(height: 10.h,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Sign in",
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: Theme.of(context).colorScheme.onPrimary)),
SizedBox(width: 4.w,),
Icon(Icons.arrow_circle_right_outlined,color: Theme.of(context).colorScheme.secondary)
],
),
],
),
),
],
),
),
),
),
),
],
),
);
}
} |
package com.mycompany.myapp.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
/**
* A Ferme.
*/
@Entity
@Table(name = "ferme")
@SuppressWarnings("common-java:DuplicatedBlocks")
public class Ferme implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "adresse")
private String adresse;
@Column(name = "taille")
private Integer taille;
@OneToMany(mappedBy = "ferme")
@JsonIgnoreProperties(value = { "genetique", "nutritions", "conditionsDeVie", "maladies", "ferme" }, allowSetters = true)
private Set<Animal> animals = new HashSet<>();
@ManyToOne
private User user;
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return this.id;
}
public Ferme id(Long id) {
this.setId(id);
return this;
}
public void setId(Long id) {
this.id = id;
}
public String getAdresse() {
return this.adresse;
}
public Ferme adresse(String adresse) {
this.setAdresse(adresse);
return this;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public Integer getTaille() {
return this.taille;
}
public Ferme taille(Integer taille) {
this.setTaille(taille);
return this;
}
public void setTaille(Integer taille) {
this.taille = taille;
}
public Set<Animal> getAnimals() {
return this.animals;
}
public void setAnimals(Set<Animal> animals) {
if (this.animals != null) {
this.animals.forEach(i -> i.setFerme(null));
}
if (animals != null) {
animals.forEach(i -> i.setFerme(this));
}
this.animals = animals;
}
public Ferme animals(Set<Animal> animals) {
this.setAnimals(animals);
return this;
}
public Ferme addAnimal(Animal animal) {
this.animals.add(animal);
animal.setFerme(this);
return this;
}
public Ferme removeAnimal(Animal animal) {
this.animals.remove(animal);
animal.setFerme(null);
return this;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public Ferme user(User user) {
this.setUser(user);
return this;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Ferme)) {
return false;
}
return id != null && id.equals(((Ferme) o).id);
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "Ferme{" +
"id=" + getId() +
", adresse='" + getAdresse() + "'" +
", taille=" + getTaille() +
"}";
}
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<span class="navbar-text">
<div>
<span style="font-size: large; color: rgb(255, 255, 255); "> <b
th:text="${person.username}">TEXT</b></span>
<span style="font-size: medium; color: rgb(255, 255, 255); "> with roles:</span>
<span style="font-size: large; color: rgb(255, 255, 255); "> <td th:text="${person.stringRoles}">TEXT<td/></span>
</div>
</span>
<div>
<ul class="navbar-nav mr-auto">
<li class="nav-item-reverse">
<a class="nav-link" href="/logout">Logout</a>
</li>
</ul>
</div>
</nav>
<div>
<div class="row">
<div class="col-2">
<div class="nav flex-column nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical">
<a class="nav-link active" id="v-pills-home-tab" data-toggle="pill" href="#v-pills-home" role="tab"
aria-controls="v-pills-home" aria-selected="true">Admin</a>
<a class="nav-link" id="v-pills-profile-tab" data-toggle="pill" href="#v-pills-profile" role="tab"
aria-controls="v-pills-profile" aria-selected="false">User</a>
</div>
</div>
<div class="col-10">
<div class="tab-content" id="v-pills-tabContent">
<div class="tab-pane fade show active" id="v-pills-home" role="tabpanel"
aria-labelledby="v-pills-home-tab">
<h1>Admin panel</h1>
<nav>
<div class="nav nav-tabs" id="nav-tab" role="tablist">
<a class="nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab"
aria-controls="nav-home" aria-selected="true">Users table</a>
<a class="nav-link" id="nav-profile-tab" data-toggle="tab" href="#nav-profile" role="tab"
aria-controls="nav-profile" aria-selected="false">New user</a>
</div>
</nav>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="nav-home" role="tabpanel"
aria-labelledby="nav-home-tab">
<div class="card">
<div class="card-header">
<h3>All users</h3>
</div>
<div class="card-body">
<table class="table table-striped">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Age</th>
<th scope="col">Role</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
<tr th:each="userfromtable: ${users}">
<td th:text="${userfromtable.id}"/>
<td th:text="${userfromtable.username}"/>
<td th:text="${userfromtable.surname}"/>
<td th:text="${userfromtable.age}"/>
<td th:text="${userfromtable.stringRoles}"></td>
<td>
<button type="button" class="btn btn-info" data-toggle="modal"
th:data-target="${'#editModal'+userfromtable.id}">
Edit
</button>
<div class="modal fade"
th:id="${'editModal'+userfromtable.id}" tabindex="-1" role="dialog"
aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form th:method="PATCH"
th:action="@{/admin/{id}(id=${userfromtable.getId()})}"
th:object="${userfromtable}">
<div class="modal-header">
<h5 class="modal-title" id="editModalLabel">Edit
user</h5>
<button type="button" class="close"
data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="container">
<div class="row justify-content-center">
<div class="col-7 text-center form-group">
<label for="idEdit"><b>ID</b></label>
<input type="text"
th:value="${userfromtable.id}"
id="idEdit" class="form-control"
disabled/>
</div>
<div class="col-7 text-center form-group">
<label for="usernameEdit"><b>Username</b></label>
<input type="text" class="form-control"
th:name="username"
th:value="${userfromtable.username}"
id="usernameEdit"
required/>
</div>
<div class="col-7 text-center form-group">
<label for="surnameEdit"><b>Surname</b></label>
<input type="text" class="form-control"
th:name="surname"
th:value="${userfromtable.surname}"
required
id="surnameEdit"/>
</div>
<div class="col-7 text-center form-group">
<label for="ageEdit"><b>Age</b></label>
<input type="number" name="t"
th:name="age"
th:value="${userfromtable.age}"
min="0"
max="150" step="1"
class="form-control"
id="ageEdit"
required/>
</div>
<div class="col-7 text-center form-group">
<label for="passwordEdit"><b>Password</b></label>
<input type="password" class="form-control"
th:name="password"
th:value="${userfromtable.password}"
id="passwordEdit" readonly/>
</div>
<div class="col-7 text-center form-group">
<label
for="rolesEdit"><b>Roles:</b></label>
<select multiple
class="form-control form-control-md w-100"
id="rolesEdit" name="roles"
size="2"
required>
<option th:each="role: ${listRoles}" th:value="${role.getId()}">
<th:block th:text="${role.getAuthority()}">
</th:block>
</option>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-dismiss="modal">Close
</button>
<button type="submit" class="btn btn-primary">Edit
</button>
</div>
</form>
</div>
</div>
</div>
</td>
<td>
<button type="button" class="btn btn-danger" data-toggle="modal"
th:data-target="${'#deleteModal'+userfromtable.id}">
Delete
</button>
<div class="modal fade"
th:id="${'deleteModal'+userfromtable.id}" tabindex="-1"
role="dialog"
aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form th:method="DELETE"
th:action="@{/admin/{id}(id=${userfromtable.getId()})}"
th:object="${userfromtable}">
<div class="modal-header">
<h5 class="modal-title" id="daleteModalLabel">Delete
user</h5>
<button type="button" class="close"
data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="container">
<div class="row justify-content-center">
<div class="col-7 text-center form-group">
<label for="idDelete"><b>ID</b></label>
<input type="text"
th:value="${userfromtable.id}"
id="idDelete"
class="form-control"
disabled/>
</div>
<div class="col-7 text-center form-group">
<label for="usernameDelete"><b>Username</b></label>
<input type="text" class="form-control"
th:value="${userfromtable.username}"
id="usernameDelete" disabled/>
</div>
<div class="col-7 text-center form-group">
<label for="surnameDelete"><b>Surname</b></label>
<input type="text" class="form-control"
th:value="${userfromtable.surname}"
id="surnameDelete" disabled/>
</div>
<div class="col-7 text-center form-group">
<label for="ageDelete"><b>Age</b></label>
<input type="number" name="t"
th:value="${userfromtable.age}"
min="0"
max="150" step="1"
class="form-control"
id="ageDelete" disabled/>
</div>
<div class="col-7 text-center form-group">
<label for="rolesDelete"><b>Roles</b></label>
<select multiple
class="form-control form-control-md w-100"
id="rolesDelete" name="roles"
size="2"
disabled>
<option >
<th:block th:text="${userfromtable.stringRoles}">
</th:block>
</option>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer form-group">
<div class="form-group">
<button type="button" class="btn btn-secondary"
data-dismiss="modal">Close
</button>
<button type="submit" class="btn btn-danger">
Delete
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
<div class="card">
<h5 class="card-header">Add user</h5>
<div class="form-justify-content-center mx-auto col-4">
<div class="card-body text-center">
<form id="formNewUser" name="formNewUser" th:align="center"
th:action="@{/admin/registration}"
th:object="${user}"
method="POST">
<p>
<label class="container-fluid" for="newUserFirstName">
<b>Username</b>
<input class="form-control" type="text" name="firstName"
id="newUserFirstName" placeholder="username"
th:field="*{username}"
required>
</label>
</p>
<p>
<label class="container-fluid" for="nameAdd">
<b>Last name</b>
<input class="form-control" type="text" name="lastName"
id="nameAdd" placeholder="surname"
th:field="*{surname}"
required>
</label>
</p>
<p>
<label class="container-fluid" for="ageAdd"><b>Age</b>
<input type="number" name="t"
th:field="*{age}"
min="0"
max="150" step="1"
class="form-control"
id="ageAdd" required/>
</label>
</p>
<p>
<label class="container-fluid" for="passwordAdd">
<b>Password</b>
<input class="form-control" type="password" name="password"
id="passwordAdd" placeholder="password"
th:field="*{password}" required>
</label>
</p>
<p>
<label class="container-fluid" for="addUser">
<b>Role</b><br>
<select id="addUser" class="form-select w-100" name="roles"
multiple size="2">
<option th:each="role: ${listRoles}" th:value="${role.getId()}">
<th:block th:text="${role.getAuthority()}">
</th:block>
</option>
</select>
</label>
</p>
<button type="submit" id="newUserButton" class="btn btn-success">
Add new user
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="v-pills-profile" role="tabpanel" aria-labelledby="v-pills-profile-tab">
<h1>User information page</h1>
<div class="card">
<div class="card-header">
<h3>About user</h3>
</div>
<div class="card-body">
<table class="table ">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Age</th>
<th scope="col">Role</th>
</tr>
</thead>
<tbody>
<td th:text="${person.id}"/>
<td th:text="${person.username}"/>
<td th:text="${person.surname}"/>
<td th:text="${person.age}"/>
<td th:text="${person.stringRoles}"></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<body/>
<html/> |
import {gql} from "apollo-server-express";
import {DocumentNode} from "graphql";
export const typeDefs: DocumentNode = gql`
type Query {
tests: [Test]
test(uid: String!): Test!
shops: [Shop!]!
shop(uid: String!): Shop!
tag(uid: String!): Tag!
tagsByShopId(shopUid: String!): [Tag!]
item(uid: String!): Item!
itemsByShopId(shopUid: String!): [Item!]
itemsByTagId(tagUid: String!): [Item!]
image(uid: String!): Image!
}
type Mutation {
createTest(input: CreateTestInput!): Test!
updateTest(input: UpdateTestInput!): Test!
deleteTest(uid: String!): String!
createShop(input: createShopInput!): Shop!
updateShop(input: updateShopInput!): Shop!
deleteShop(uid: String!): String!
createTag(input: CreateTagInput!): Tag!
updateTag(input: UpdateTagInput!): Tag!
deleteTag(uid: String!): String!
createItem(input: CreateItemInput!): Item!
updateItem(input: UpdateItemInput!): Item!
deleteItem(uid: String!): String!
createImage(input: CreateImageInput!): Image!
deleteImage(uid: String!): String!
}
type Test {
uid: String!
text: String!
}
type Shop {
uid: String!
name: String!
zip: String!
address: String!
tel: String!
note: String!
}
type Tag {
uid: String!
shop_uid: String!
name: String!
note: String!
sort: Int!
}
type Item {
uid: String!
shop_uid: String!
tag_uid: String!
sort: Int!
name: String!
price: Float!
is_visible: Boolean!
is_sold: Boolean!
image_path: String!
}
type Image {
item_uid: String!
image_path: String!
}
input CreateTestInput {
text: String!
}
input UpdateTestInput {
uid: String!
text: String!
}
input createShopInput {
uid: String!
name: String!
zip: String!
address: String!
tel: String!
note: String!
}
input updateShopInput {
uid: String!
name: String!
zip: String!
address: String!
tel: String!
note: String!
}
input CreateTagInput {
shop_uid: String!
name: String!
note: String!
sort: Int!
}
input UpdateTagInput {
uid: String!
name: String!
note: String!
sort: Int!
}
input CreateItemInput {
shop_uid: String!
tag_uid: String!
sort: Int!
name: String!
price: Float!
is_visible: Boolean!
is_sold: Boolean!
image_path: String!
}
input UpdateItemInput {
uid: String!
tag_uid: String!
sort: Int!
name: String!
price: Float!
is_visible: Boolean!
is_sold: Boolean!
image_path: String!
}
input CreateImageInput {
item_uid: String!
image_path: String!
}
`; |
#!/usr/bin/env python
#
# SPDX-FileCopyrightText: 2022 Buoyant, Inc.
# SPDX-License-Identifier: Apache-2.0
#
# Copyright 2022 Buoyant, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http:#www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#--------------------------------------
#
# For more info, see README.md. If you've somehow found demosh without also
# finding its repo, it's at github.com/BuoyantIO/demosh.
import sys
import argparse
from . import __version__
from .shellstate import ShellState
from .demostate import DemoState
def main() -> None:
parser = argparse.ArgumentParser(description='Demo SHell: run shell scripts with commentary and pauses')
parser.add_argument('--version', action='version', version=f"%(prog)s {__version__}")
parser.add_argument('--debug', action='store_true', help="enable debug output")
parser.add_argument('--no-builtins', action='store_true', help="don't load builtin functions")
parser.add_argument('--no-init', action='store_true', help="don't run ~/.demoshrc on startup")
parser.add_argument('script', type=str, help="script to run")
parser.add_argument('args', type=str, nargs=argparse.REMAINDER, help="optional arguments to pass to script")
args = parser.parse_args()
scriptname = args.script
mode = "shell"
if scriptname.lower().endswith(".md"):
mode = "markdown"
script = open(scriptname, "r")
shellstate = ShellState(sys.argv[0], scriptname, args.args)
demostate = DemoState(shellstate, mode, script,
debug=args.debug,
load_builtins=not args.no_builtins,
load_init=not args.no_init)
try:
demostate.run()
finally:
demostate.sane()
if __name__ == "__main__":
main() |
//
// Created by Yancey on 2023/11/7.
//
#include "CPack.h"
#include "../node/param/NodeNormalId.h"
#include "../node/util/NodeAnd.h"
namespace CHelper {
CODEC(RepeatData, id, breakNodes, repeatNodes, isEnd)
CPack::CPack(const std::filesystem::path &path) {
#if CHelperDebug == true
size_t stackSize = Profile::stack.size();
#endif
Profile::push(ColorStringBuilder().red("init codes").build());
Node::NodeType::init();
Profile::next(ColorStringBuilder().red("loading manifest").build());
JsonUtil::getJsonFromFile(path / "manifest.json").get_to<Manifest>(manifest);
Profile::next(ColorStringBuilder().red("loading id data").build());
for (const auto &file: std::filesystem::recursive_directory_iterator(path / "id")) {
Profile::next(ColorStringBuilder()
.red("loading id data in path \"")
.purple(file.path().string())
.red("\"")
.build());
applyId(JsonUtil::getJsonFromFile(file));
}
Profile::next(ColorStringBuilder().red("loading json data").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::JSON_NODE;
for (const auto &file: std::filesystem::recursive_directory_iterator(path / "json")) {
Profile::next(ColorStringBuilder()
.red("loading json data in path \"")
.purple(file.path().string())
.red("\"")
.build());
applyJson(JsonUtil::getJsonFromFile(file));
}
Profile::next(ColorStringBuilder().red("loading repeat data").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::REPEAT_NODE;
for (const auto &file: std::filesystem::recursive_directory_iterator(path / "repeat")) {
Profile::next(ColorStringBuilder()
.red("loading repeat data in path \"")
.purple(file.path().string())
.red("\"")
.build());
applyRepeat(JsonUtil::getJsonFromFile(file));
}
Profile::next(ColorStringBuilder().red("loading commands").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::COMMAND_PARAM_NODE;
for (const auto &file: std::filesystem::recursive_directory_iterator(path / "command")) {
Profile::next(ColorStringBuilder()
.red("loading command in path \"")
.purple(file.path().string())
.red("\"")
.build());
applyCommand(JsonUtil::getJsonFromFile(file));
}
Profile::next(ColorStringBuilder().red("init cpack").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::NONE;
afterApply();
Profile::pop();
#if CHelperDebug == true
if (HEDLEY_UNLIKELY(Profile::stack.size() != stackSize)) {
CHELPER_WARN("error profile stack after loading cpack");
}
#endif
}
CPack::CPack(const nlohmann::json &j) {
#if CHelperDebug == true
size_t stackSize = Profile::stack.size();
#endif
Profile::push(ColorStringBuilder().red("init codes").build());
Node::NodeType::init();
Profile::next(ColorStringBuilder().red("loading manifest").build());
j.at("manifest").get_to(manifest);
Profile::next(ColorStringBuilder().red("loading id data").build());
for (const auto &item: j.at("id")) {
applyId(item);
}
Profile::next(ColorStringBuilder().red("loading json data").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::JSON_NODE;
for (const auto &item: j.at("json")) {
applyJson(item);
}
Profile::next(ColorStringBuilder().red("loading repeat data").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::REPEAT_NODE;
for (const auto &item: j.at("repeat")) {
applyRepeat(item);
}
Profile::next(ColorStringBuilder().red("loading command data").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::COMMAND_PARAM_NODE;
for (const auto &item: j.at("command")) {
applyCommand(item);
}
Profile::next(ColorStringBuilder().red("init cpack").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::NONE;
afterApply();
Profile::pop();
#if CHelperDebug == true
if (HEDLEY_UNLIKELY(Profile::stack.size() != stackSize)) {
CHELPER_WARN("error profile stack after loading cpack");
}
#endif
}
CPack::CPack(BinaryReader &binaryReader) {
#if CHelperDebug == true
size_t stackSize = Profile::stack.size();
#endif
Profile::push(ColorStringBuilder().red("init node types").build());
Node::NodeType::init();
Profile::next(ColorStringBuilder().red("loading manifest").build());
binaryReader.decode(manifest);
Profile::next(ColorStringBuilder().red("loading normal id data").build());
binaryReader.decode(normalIds);
Profile::next(ColorStringBuilder().red("loading namespace id data").build());
binaryReader.decode(namespaceIds);
Profile::next(ColorStringBuilder().red("loading item id data").build());
size_t itemIdSize = binaryReader.readSize();
for (int i = 0; i < itemIdSize; ++i) {
itemIds->push_back(binaryReader.read<std::shared_ptr<ItemId>>());
}
Profile::next(ColorStringBuilder().red("loading block id data").build());
size_t blockIdSize = binaryReader.readSize();
for (int i = 0; i < blockIdSize; ++i) {
blockIds->push_back(binaryReader.read<std::shared_ptr<BlockId>>());
}
Profile::next(ColorStringBuilder().red("loading json data").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::JSON_NODE;
binaryReader.decode(jsonNodes);
Profile::next(ColorStringBuilder().red("loading repeat data").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::REPEAT_NODE;
binaryReader.decode(repeatNodeData);
Profile::next(ColorStringBuilder().red("loading command data").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::COMMAND_PARAM_NODE;
binaryReader.decode(commands);
Profile::next(ColorStringBuilder().red("init cpack").build());
Node::NodeType::currentCreateStage = Node::NodeCreateStage::NONE;
afterApply();
Profile::pop();
#if CHelperDebug == true
if (HEDLEY_UNLIKELY(Profile::stack.size() != stackSize)) {
CHELPER_WARN("error profile stack after loading cpack");
}
#endif
}
void CPack::applyId(const nlohmann::json &j) {
auto type = JsonUtil::read<std::string>(j, "type");
if (HEDLEY_LIKELY(type == "normal")) {
auto id = j.at("id").get<std::string>();
auto content = std::make_shared<std::vector<std::shared_ptr<NormalId>>>();
const auto &contentJson = j.at("content");
content->reserve(contentJson.size());
for (const auto &item: contentJson) {
content->push_back(std::make_shared<NormalId>(item));
}
normalIds.emplace(std::move(id), std::move(content));
} else if (HEDLEY_LIKELY(type == "namespace")) {
auto id = j.at("id").get<std::string>();
auto content = std::make_shared<std::vector<std::shared_ptr<NamespaceId>>>();
const auto &contentJson = j.at("content");
content->reserve(contentJson.size());
for (const auto &item: contentJson) {
content->push_back(std::make_shared<NamespaceId>(item));
}
namespaceIds.emplace(std::move(id), std::move(content));
} else if (HEDLEY_LIKELY(type == "block")) {
const auto &blocksJson = j.at("blocks");
blockIds->reserve(blockIds->size() + blocksJson.size());
for (const auto &item: blocksJson) {
blockIds->push_back(std::make_shared<BlockId>(item));
}
} else if (HEDLEY_LIKELY(type == "item")) {
const auto &itemsJson = j.at("items");
itemIds->reserve(itemIds->size() + itemsJson.size());
for (const auto &item: itemsJson) {
itemIds->push_back(std::make_shared<ItemId>(item));
}
} else {
throw Exception::UnknownIdType(type);
}
}
void CPack::applyJson(const nlohmann::json &j) {
jsonNodes.push_back(j);
}
void CPack::applyRepeat(const nlohmann::json &j) {
repeatNodeData.emplace_back(j);
}
void CPack::applyCommand(const nlohmann::json &j) {
commands->push_back(j);
}
void CPack::afterApply() {
// json nodes
Profile::push(ColorStringBuilder().red("init json nodes").build());
for (const auto &item: jsonNodes) {
item->init(*this);
}
// repeat nodes
Profile::next(ColorStringBuilder().red("init repeat nodes").build());
for (const auto &item: repeatNodeData) {
if (HEDLEY_UNLIKELY(item.repeatNodes.size() != item.isEnd.size())) {
Profile::push(ColorStringBuilder().red("checking repeat node: ").purple(item.id).build());
throw std::runtime_error("fail to check repeat id because repeatNodes size not equal isEnd size");
}
}
// command param nodes
for (const auto &item: repeatNodeData) {
std::vector<const Node::NodeBase *> content;
content.reserve(item.repeatNodes.size());
for (const auto &item2: item.repeatNodes) {
std::vector<const Node::NodeBase *> perContent;
perContent.reserve(item2.size());
for (const auto &item3: item2) {
perContent.push_back(item3.get());
}
auto node = std::make_unique<Node::NodeAnd>(item.id, std::nullopt, Node::WhitespaceMode::NORMAL, std::move(perContent));
content.push_back(node.get());
repeatCacheNodes.push_back(std::move(node));
}
std::vector<const Node::NodeBase *> breakChildNodes;
breakChildNodes.reserve(item.breakNodes.size());
for (const auto &item2: item.breakNodes) {
breakChildNodes.push_back(item2.get());
}
std::unique_ptr<Node::NodeBase> unBreakNode = std::make_unique<Node::NodeOr>(
item.id, std::nullopt, std::move(content), false);
std::unique_ptr<Node::NodeBase> breakNode = std::make_unique<Node::NodeAnd>(
item.id, std::nullopt, Node::WhitespaceMode::NORMAL, std::move(breakChildNodes));
std::unique_ptr<Node::NodeBase> orNode = std::make_unique<Node::NodeOr>(
"NODE_REPEAT", "命令重复部分",
std::vector<const Node::NodeBase *>{unBreakNode.get(), breakNode.get()},
false);
repeatNodes.emplace(item.id, std::make_pair(&item, orNode.get()));
repeatCacheNodes.push_back(std::move(unBreakNode));
repeatCacheNodes.push_back(std::move(breakNode));
repeatCacheNodes.push_back(std::move(orNode));
}
for (const auto &item: repeatNodeData) {
for (const auto &item2: item.repeatNodes) {
for (const auto &item3: item2) {
item3->init(*this);
}
}
for (const auto &item2: item.breakNodes) {
item2->init(*this);
}
}
for (const auto &item: *commands) {
Profile::next(ColorStringBuilder().red("init command: \"").purple(StringUtil::join(",", item->name)).red("\"").build());
item->init(*this);
}
Profile::next(ColorStringBuilder().red("sort command nodes").build());
std::sort(commands->begin(), commands->end(),
[](const auto &item1, const auto &item2) {
return ((Node::NodePerCommand *) item1.get())->name[0] <
((Node::NodePerCommand *) item2.get())->name[0];
});
Profile::next(ColorStringBuilder().red("create main node").build());
mainNode = std::make_unique<Node::NodeCommand>("MAIN_NODE", "欢迎使用命令助手(作者:Yancey)", commands.get());
Profile::pop();
}
std::unique_ptr<CPack> CPack::createByDirectory(const std::filesystem::path &path) {
Profile::push(ColorStringBuilder().red("start load CPack by DIRECTORY: ").purple(path.string()).build());
std::unique_ptr<CPack> cpack = std::make_unique<CPack>(path);
Profile::pop();
return cpack;
}
std::unique_ptr<CPack> CPack::createByJson(const nlohmann::json &j) {
Profile::push(ColorStringBuilder().red("start load CPack by JSON").build());
std::unique_ptr<CPack> cpack = std::make_unique<CPack>(j);
Profile::pop();
return cpack;
}
std::unique_ptr<CPack> CPack::createByBinary(BinaryReader &binaryReader) {
Profile::push(ColorStringBuilder().red("start load CPack by binary").build());
std::unique_ptr<CPack> cpack = std::make_unique<CPack>(binaryReader);
Profile::pop();
return cpack;
}
void CPack::writeJsonToDirectory(const std::filesystem::path &path) const {
JsonUtil::writeJsonToFile(path / "manifest.json", manifest);
for (const auto &item: normalIds) {
nlohmann::json j;
j["id"] = item.first;
j["type"] = "normal";
j["content"] = item.second;
JsonUtil::writeJsonToFile(path / "id" / (item.first + ".json"), j);
}
for (const auto &item: namespaceIds) {
nlohmann::json j;
j["id"] = item.first;
j["type"] = "namespace";
j["content"] = item.second;
JsonUtil::writeJsonToFile(path / "id" / (item.first + ".json"), j);
}
{
nlohmann::json j;
j["type"] = "item";
j["items"] = *itemIds;
JsonUtil::writeJsonToFile(path / "id" / "items.json", j);
}
{
nlohmann::json j;
j["type"] = "block";
j["blocks"] = *blockIds;
JsonUtil::writeJsonToFile(path / "id" / "blocks.json", j);
}
for (const auto &item: jsonNodes) {
JsonUtil::writeJsonToFile(path / "json" / (item->id.value() + ".json"), item);
}
for (const auto &item: repeatNodeData) {
JsonUtil::writeJsonToFile(path / "repeat" / (item.id + ".json"), item);
}
for (const auto &item: *commands) {
JsonUtil::writeJsonToFile(
path / "command" / (((Node::NodePerCommand *) item.get())->name[0] + ".json"),
item);
}
}
nlohmann::json CPack::toJson() const {
nlohmann::json result;
result["manifest"] = manifest;
nlohmann::json idJson;
for (const auto &item: normalIds) {
nlohmann::json j;
j["id"] = item.first;
j["type"] = "normal";
j["content"] = item.second;
idJson.push_back(std::move(j));
}
for (const auto &item: namespaceIds) {
nlohmann::json j;
j["id"] = item.first;
j["type"] = "namespace";
j["content"] = item.second;
idJson.push_back(std::move(j));
}
{
nlohmann::json j;
j["type"] = "item";
j["items"] = itemIds;
idJson.push_back(std::move(j));
}
{
nlohmann::json j;
j["type"] = "block";
j["blocks"] = blockIds;
idJson.push_back(std::move(j));
}
result["id"] = std::move(idJson);
result["json"] = jsonNodes;
result["repeat"] = repeatNodeData;
result["command"] = commands;
return result;
}
void CPack::writeJsonToFile(const std::filesystem::path &path) const {
JsonUtil::writeJsonToFile(path, toJson());
}
void CPack::writeBsonToFile(const std::filesystem::path &path) const {
JsonUtil::writeBsonToFile(path, toJson());
}
void CPack::writeBinToFile(const std::filesystem::path &path) const {
std::filesystem::create_directories(path.parent_path());
Profile::push(ColorStringBuilder()
.red("writing binary cpack to file: ")
.purple(path.string())
.build());
std::ofstream f(path, std::ios::binary);
BinaryWriter binaryWriter(true, f);
//manifest
binaryWriter.encode(manifest);
//normal id
binaryWriter.encode(normalIds);
//namespace id
binaryWriter.encode(namespaceIds);
//item id
binaryWriter.encodeSize(itemIds->size());
for (const auto &item: *itemIds) {
binaryWriter.encode(std::static_pointer_cast<ItemId>(item));
}
//block id
binaryWriter.encodeSize(blockIds->size());
for (const auto &item: *blockIds) {
binaryWriter.encode(std::static_pointer_cast<BlockId>(item));
}
//json node
binaryWriter.encode(jsonNodes);
//repeat node
binaryWriter.encode(repeatNodeData);
//command
binaryWriter.encode(commands);
f.close();
Profile::pop();
}
std::shared_ptr<std::vector<std::shared_ptr<NormalId>>>
CPack::getNormalId(const std::string &key) const {
auto it = normalIds.find(key);
if (HEDLEY_UNLIKELY(it == normalIds.end())) {
#if CHelperDebug == true
CHELPER_WARN("fail to find normal ids by key: \"" + key + '\"');
#endif
return nullptr;
}
return it->second;
}
std::shared_ptr<std::vector<std::shared_ptr<NamespaceId>>>
CPack::getNamespaceId(const std::string &key) const {
if (HEDLEY_UNLIKELY(key == "blocks")) {
return blockIds;
} else if (HEDLEY_UNLIKELY(key == "items")) {
return itemIds;
}
auto it = namespaceIds.find(key);
if (HEDLEY_UNLIKELY(it == namespaceIds.end())) {
#if CHelperDebug == true
CHELPER_WARN("fail to find namespace ids by key: \"" + key + '\"');
#endif
return nullptr;
}
return it->second;
}
}// namespace CHelper |
import java.util.Locale;
import java.util.Scanner;
public class Exercise06 {
public static void run() {
System.out.println("Exercise06");
Locale.setDefault(Locale.US);
Scanner scanner = new Scanner(System.in);
double a, b, c;
a = scanner.nextDouble();
b = scanner.nextDouble();
c = scanner.nextDouble();
// (a área do triângulo retângulo que tem A por base e C por altura. )
double area_triangulo_retangulo = a * c / 2; // base * altura / 2
// a área do círculo de raio C. (pi = 3.14159)
double area_circulo = 3.14159 * Math.pow(c, 2); // a = pi * r²
// a área do trapézio que tem A e B por bases e C por altura.
double area_trapezio = ((a + b) / 2) * c;// a = ((a+b)/2)* altura
//a área do quadrado que tem lado B.
double area_quadrado = b * b;
//a área do retângulo que tem lados A e B.
double area_retangulo = a * b;
System.out.printf("TRIANGULO: %.3f%n", area_triangulo_retangulo);
System.out.printf("CIRCULO: %.3f%n", area_circulo);
System.out.printf("TRAPEZIO: %.3f%n", area_trapezio);
System.out.printf("QUADRADO: %.3f%n", area_quadrado);
System.out.printf("RETANGULO: %.3f%n", area_retangulo);
scanner.close();
}
} |
//
// AuthService.swift
// Simplified
//
// Created by Jed Kutai on 6/1/24.
//
import Foundation
import Firebase
import FirebaseAuth
import FirebaseFirestore
struct AuthService {
static func uploadUserData(uid: String, email: String) async {
let user = User(id: uid, email: email.lowercased())
guard let encodedUser = try? Firestore.Encoder().encode(user) else { return }
try? await Firestore.firestore().collection("users").document(uid).setData(encodedUser)
}
@MainActor
static func createAccount(email: String, password: String) async throws -> String {
do {
let result = try await Auth.auth().createUser(withEmail: email, password: password)
let uid = result.user.uid
await self.uploadUserData(uid: uid, email: email)
if let user = Auth.auth().currentUser {
try await user.sendEmailVerification()
}
return uid
} catch {
return "Error: \(error.localizedDescription)"
}
}
@MainActor
static func login(withEmail email: String, password: String) async throws -> String {
do {
let result = try await Auth.auth().signIn(withEmail: email, password: password)
let uid = result.user.uid
return uid
} catch {
print("DEBUG: \(error.localizedDescription)")
return "Error: \(error.localizedDescription)"
}
}
static func automaticLogin() async throws -> User? {
var loggedInUser: User?
if let user = Auth.auth().currentUser {
let uid = user.uid
do {
loggedInUser = try await FetchService.fetchUserByUid(uid: uid)
} catch {
loggedInUser = nil
}
}
return loggedInUser
}
static func signOut() async throws {
try Auth.auth().signOut()
}
static func resetPassword(withEmail email: String) async throws {
try await Auth.auth().sendPasswordReset(withEmail: email)
}
static func deleteAccount(withEmail email: String, password: String) async throws {
do {
if let user = Auth.auth().currentUser {
let userDoc = Firestore.firestore().collection("users").document(user.uid)
try await userDoc.delete()
try await user.delete()
}
} catch {
print("failed to delete account")
}
}
} |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateGalleriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('galleries', function (Blueprint $table) {
$table->id();
$table->string('name', 255)->nullable();
$table->string('photo', 255)->nullable();
$table->string('type', 30)->nullable();
$table->string('status')->nullable();
$table->string('file_attach')->nullable();
$table->mediumText('links_video')->nullable();
$table->mediumText('options')->nullable();
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('galleries');
}
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller.Helper;
import View.ClienteView;
import Model.Cliente;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.table.DefaultTableModel;
/**
*
* @author henri
*/
public class ClienteHelper implements IHelper{
private final ClienteView view;
public ClienteHelper(ClienteView view) {
this.view = view;
}
public boolean validarCampos(){
String nome = view.getTextNome().getText();
String rg = view.getTextRg().getText();
String telefone = view.getTextTelefone().getText();
String data = view.getTextData().getText();
String sexoCompleto = view.getjComboBoxSexo().getSelectedItem().toString();
String email = view.getTextEmail().getText();
String cep = view.getTextCep().getText();
String endereco = view.getTextEndereco().getText();
if(nome.equals("") || rg.equals("") || telefone.equals("( ) ") || data.equals(" / / ") || email.equals("") || cep.equals("") || endereco.equals("")){
view.exibeMensagem("Preencha todos os campos!");
return false;
}else if(rg.length() != 10){
view.exibeMensagem("O RG está incompleto!");
return false;
}else if(cep.length() != 8){
view.exibeMensagem("O CEP está incompleto!");
return false;
}else if(telefone.length() != 13){
view.exibeMensagem("O telefone está incompleto!");
return false;
}else if(data.length() != 10){
view.exibeMensagem("A data de nascimento está incompleta!");
return false;
}else{
// Obter a data atual
Date dataAtual = new Date();
Date dataDigitada = new Date();
// Formato da data
SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
try{
dataDigitada = formato.parse(data);
} catch (ParseException e) {
System.out.println("Formato de data inválido. Certifique-se de usar o formato dd/MM/yyyy.");
}
if(dataDigitada.after(dataAtual)){
view.exibeMensagem("A data de nascimento é maior que a data atual!");
return false;
}
return true;
}
}
public void preencherTabela(ArrayList<Cliente> clientes){
DefaultTableModel tableModel = (DefaultTableModel) view.getTabelaClientes().getModel();
tableModel.setNumRows(0);
//percorrer a lista preenchendo o table model
for (Cliente cliente : clientes) {
tableModel.addRow(new Object[]{
cliente.getId(),
cliente.getNome(),
cliente.getRg(),
cliente.getTelefone(),
cliente.getDataFormatada(),
cliente.getSexo(),
cliente.getEmail(),
cliente.getCep(),
cliente.getEndereco()
});
}
}
/*public void preencherClientes(ArrayList<Cliente> clientes) {
DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) view.getjComboBoxCliente().getModel();
for (Cliente cliente : clientes) {
comboBoxModel.addElement(cliente);
}
}*/
/*public void preencherServicos(ArrayList<Servico> servicos) {
DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) view.getjComboBoxServico().getModel();
for (Servico servico : servicos) {
comboBoxModel.addElement(servico);
}
}*/
/*public Cliente obterCliente() {
return (Cliente) view.getjComboBoxCliente().getSelectedItem();
}*/
/*public Servico obterServico() {
return (Servico) view.getjComboBoxServico().getSelectedItem();
}*/
/*public void setarValor(float valor) {
view.getTextValor().setText(valor+"");
}*/
@Override
public Object obterModelo() {
String nome = view.getTextNome().getText();
String rg = view.getTextRg().getText();
String telefone = view.getTextTelefone().getText();
String data = view.getTextData().getText();
String sexoCompleto = view.getjComboBoxSexo().getSelectedItem().toString();
char sexo;
if (sexoCompleto.equals("Masculino")){
sexo = 'M';
}else{
sexo = 'F';
}
String email = view.getTextEmail().getText();
String cep = view.getTextCep().getText();
String endereco = view.getTextEndereco().getText();
Cliente cliente = new Cliente(0, nome, sexo, data, telefone, email, rg, endereco, cep);
return cliente;
}
@Override
public void limparTela() {
view.getTextCep().setText("");
view.getTextData().setText("");
view.getTextEmail().setText("");
view.getTextEndereco().setText("");
view.getTextNome().setText("");
view.getTextRg().setText("");
view.getTextTelefone().setText("");
}
public void preencherCampos(Cliente cliente) {
view.getTextCep().setText(cliente.getCep());
view.getTextData().setText(cliente.getDataFormatada());
view.getTextEmail().setText(cliente.getEmail());
view.getTextEndereco().setText(cliente.getEndereco());
view.getTextNome().setText(cliente.getNome());
view.getTextRg().setText(cliente.getRg());
view.getTextTelefone().setText(cliente.getTelefone());
String sexo;
if(cliente.getSexo()=='M'){
sexo = "Masculino";
}else{
sexo = "Feminino";
}
view.getjComboBoxSexo().setSelectedItem(sexo);
}
} |
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import axios from 'axios'
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import Swal from 'sweetalert2'
import MainLayout from '../Layout/Layout.jsx'
const Login = () => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [showPassword, setShowPassword] = useState(false)
const [invalidPasswordError, setInvalidPasswordError] = useState(false)
const [status, setStatus] = useState('')
const [rememberMe, setRememberMe] = useState(false)
const endPoint = process.env.REACT_APP_BASE_URL
const handleRememberMeChange = () => {
setRememberMe(!rememberMe)
localStorage.setItem('rememberedEmail', email)
localStorage.setItem('rememberedPassword', password)
}
useEffect(() => {
const userToken = localStorage.getItem('user-token')
if (userToken) {
// If user is already logged in then redirect to the dashboard
window.location.href = '/dashboard'
}
//remembered email and password should move to session storage as i am clearing localstorage on logout
const rememberedEmail = localStorage.getItem('rememberedEmail')
const rememberedPassword = localStorage.getItem('rememberedPassword')
if (rememberedEmail && rememberedPassword) {
setEmail(rememberedEmail)
setPassword(rememberedPassword)
setRememberMe(true)
}
}, [])
const handleLogin = async (e) => {
try {
const response = await axios.post(
`http://${endPoint}:8080/user/auth/login/`,
{
email,
password,
}
)
if (response.status === 200) {
console.log('Response Data : ', response.data)
const user = JSON.stringify(response.data.userData)
localStorage.setItem('user-token', response.data.accessToken)
localStorage.setItem('isAdmin', response.data.userData.isAdmin)
localStorage.setItem('user', user)
Swal.fire({
icon: 'success',
title: response.data.message,
showConfirmButton: false,
timer: 2000,
})
setTimeout(() => {
window.location.href = '/dashboard'
}, 500)
if (rememberMe) {
sessionStorage.setItem('rememberedEmail', email)
sessionStorage.setItem('rememberedPassword', password)
}
}
} catch (error) {
console.log('error', error.response)
Swal.fire({
icon: 'error',
title: error.message,
showConfirmButton: false,
timer: 2000,
})
}
}
const handleKeyPress = (event) => {
if (event.key === 'Enter') {
event.preventDefault()
handleLogin()
}
}
return (
<MainLayout>
<div className="flex flex-wrap justify-center py-10">
<div className="w-full max-w-sm p-4 border rounded-lg shadow sm:p-6 md:p-8 bg-teal-950 border-gray-500">
<div className="space-y-6">
<h5 className="text-2xl font-bold text-gray-100 text-center">
Sign In
</h5>
<div>
<label
htmlFor="email"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Email or username
</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
id="email"
className="bg-gray-100 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-secondary-light focus:border-secondary-light block w-full p-2.5"
placeholder="name@company.com"
required
onKeyDown={handleKeyPress}
/>
</div>
<div>
<label
htmlFor="password"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Password
</label>
<div className="flex">
<input
type={showPassword ? 'text' : 'password'}
id="password"
placeholder="••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-secondary-light focus:border-secondary-light block w-full p-2.5 "
required
onKeyDown={handleKeyPress}
/>
<FontAwesomeIcon
icon={`fa-solid ${showPassword ? 'fa-eye-slash' : 'fa-eye'}`}
size="lg"
className="text-gray-500 hover:text-blue-500 cursor-pointer -ml-8 my-auto"
onClick={() => setShowPassword(!showPassword)}
/>
</div>
<p>{status}</p>
</div>
<div className="flex items-start">
<div className="flex items-start">
<div className="flex items-center h-5">
<input
id="remember"
type="checkbox"
value=""
className="w-4 h-4 rounded bg-gray-50 accent-secondary-light"
checked={rememberMe}
onChange={handleRememberMeChange}
/>
</div>
<label
htmlFor="remember"
className="ml-2 text-sm font-medium text-gray-100 "
>
Remember me
</label>
</div>
<Link
href="/"
className="ml-auto text-sm text-secondary-light hover:underline "
>
Forgot Password?
</Link>
</div>
<button
className=" flex mx-auto w-[2/4] text-white bg-secondary-light scale-100 hover:bg-secondary-dark focus:bg-secondary-dark hover:text-gray-100 font-bold rounded-lg text-md px-10 py-2 text-center "
onClick={handleLogin}
>
Continue
</button>
<p className="status">{status}</p>
<div className="text-sm font-medium text-gray-500 dark:text-gray-300">
Not registered?{' '}
<Link
to="/register"
className="text-secondary-light hover:underline "
>
Create account
</Link>
</div>
</div>
</div>
</div>
</MainLayout>
)
}
export default Login |
// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "options_reconstructor.hpp"
bool find_command_option(const std::vector<std::string> &args, const std::string &option)
{
return std::find(args.begin(), args.end(), option) != args.end();
}
std::string get_command_option(const std::vector<std::string> &args, const std::string &option)
{
auto it = std::find(args.begin(), args.end(), option);
if (it != args.end() && ++it != args.end())
{
return *it;
}
return std::string();
}
bool get_flag_option(const std::vector<std::string> &args, const std::string &option)
{
auto it = std::find(args.begin(), args.end(), option);
if (it != args.end())
{
return true;
}
return false;
}
bool parse_command_options(
int argc, char **argv,
size_t *depth,
rmw_qos_reliability_policy_t *reliability_policy,
rmw_qos_history_policy_t *history_policy,
bool *show_camera, bool *ceres_stdout,
size_t *mode,
bool *est_move, float *thresh_knn_ratio, float *thresh_ransac,
int *cpu_core, size_t *scene,
size_t *matching, size_t *extractor)
{
std::vector<std::string> args(argv, argv + argc);
if (find_command_option(args, "-h"))
{
std::stringstream ss;
ss << "Usage:" << std::endl;
ss << " -h: This message." << std::endl;
ss << " -r: Reliability QoS setting:" << std::endl;
ss << " 0 - best effort" << std::endl;
ss << " 1 - reliable (default)" << std::endl;
ss << " -d: Depth of the queue: only honored if used together with 'keep last'. "
<< "10 (default)" << std::endl;
ss << " -k: History QoS setting:" << std::endl;
ss << " 0 - only store up to N samples, configurable via the queue depth (default)" << std::endl;
ss << " 1 - keep all the samples" << std::endl;
if (show_camera != nullptr)
{
ss << " --show: Show Matching scene:" << std::endl;
ss << " 0 - Do not show the camera stream (default)" << std::endl;
ss << " 1 - Show the camera stream" << std::endl;
}
if (ceres_stdout != nullptr)
{
ss << " --ceres-stdout: Show Matching scene:" << std::endl;
ss << " 0 - Do not show (default)" << std::endl;
ss << " 1 - Show the ceres stdout" << std::endl;
}
if (mode != nullptr)
{
ss << " --mode: Select Mode:" << std::endl;
ss << " 0 - Normal" << std::endl;
ss << " 1 - Eye (default)" << std::endl;
}
if (est_move != nullptr)
{
ss << " --est-move: Estimation Movement. " << std::endl;
ss << " 0 - OFF (default)" << std::endl;
ss << " 1 - ON" << std::endl;
}
if (thresh_knn_ratio != nullptr)
{
ss << " --knn-ratio: Set Threshhold of knn matching ratio " << std::endl;
ss << " (default) : 0.7f" << std::endl;
}
if (thresh_ransac != nullptr)
{
ss << " --thresh-ransac: Set Threshhold of RANSAC used for " << std::endl;
ss << " (default) : 5.0" << std::endl;
}
if (cpu_core != nullptr)
{
ss << " --core: Set Number of CPU core used for Bundler" << std::endl;
ss << " (default) : 8 cores" << std::endl;
}
if (scene != nullptr)
{
ss << " --scene: Set Number of Scenes used for triangulation" << std::endl;
ss << " (default) : 4 scenes" << std::endl;
}
if (matching != nullptr)
{
ss << " --match: Set Matching method" << std::endl;
ss << " KNN : 0" << std::endl;
ss << " BruteForce : 1 (default)" << std::endl;
}
if (matching != nullptr)
{
ss << " --extractor: Set Extractor method" << std::endl;
ss << " ORB : 0" << std::endl;
ss << " AKAZE : 1 (default)" << std::endl;
ss << " BRISK : 2 " << std::endl;
ss << " SIFT : 3 " << std::endl;
ss << " SURF : 4 " << std::endl;
ss << " BRIEF : 5 " << std::endl;
}
std::cout << ss.str();
return false;
}
auto reliability_str = get_command_option(args, "-r");
if (!reliability_str.empty())
{
unsigned int r = std::stoul(reliability_str.c_str());
*reliability_policy =
r ? RMW_QOS_POLICY_RELIABILITY_RELIABLE : RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT;
}
auto depth_str = get_command_option(args, "-d");
if (!depth_str.empty())
{
*depth = std::stoul(depth_str.c_str());
}
auto history_str = get_command_option(args, "-k");
if (!history_str.empty())
{
unsigned int r = std::stoul(history_str.c_str());
*history_policy = r ? RMW_QOS_POLICY_HISTORY_KEEP_ALL : RMW_QOS_POLICY_HISTORY_KEEP_LAST;
}
auto show_camera_str = get_command_option(args, "--show");
if (!show_camera_str.empty())
{
*show_camera = std::stoul(show_camera_str.c_str()) != 0 ? true : false;
}
auto ceres_stdout_str = get_command_option(args, "--ceres-stdout");
if (!ceres_stdout_str.empty())
{
*ceres_stdout = std::stoul(ceres_stdout_str.c_str()) != 0 ? true : false;
}
auto mode_str = get_command_option(args, "--mode");
if (!mode_str.empty())
{
*mode = std::stoul(mode_str.c_str());
}
auto est_move_str = get_command_option(args, "--est-move");
if (!est_move_str.empty())
{
*est_move = std::stoul(est_move_str.c_str()) != 0 ? true : false;
}
auto thresh_knn_ratio_str = get_command_option(args, "--knn-ratio");
if (!thresh_knn_ratio_str.empty())
{
*thresh_knn_ratio = std::stoul(thresh_knn_ratio_str.c_str());
}
auto thresh_ransac_str = get_command_option(args, "--thresh-ransac");
if (!thresh_ransac_str.empty())
{
*thresh_ransac = std::stoul(thresh_ransac_str.c_str());
}
auto cpu_core_str = get_command_option(args, "--core");
if (!cpu_core_str.empty())
{
*cpu_core = std::stoul(cpu_core_str.c_str());
}
auto scene_str = get_command_option(args, "--scene");
if (!scene_str.empty())
{
*scene = std::stoul(scene_str.c_str());
}
auto matching_str = get_command_option(args, "--match");
if (!matching_str.empty())
{
*matching = std::stoul(matching_str.c_str());
}
auto extractor_str = get_command_option(args, "--extractor");
if (!extractor_str.empty())
{
*extractor = std::stoul(extractor_str.c_str());
}
return true;
} |
import { RouteObject } from "react-router-dom";
import { Typography } from "@mui/material";
import { MainLayout } from "@/components/layouts/MainLayout.tsx";
import { BoardView } from "@/features/boards/routes/BoardView.tsx";
import { BoardListView } from "@/features/boards/routes/BoardListView.tsx";
import { BoardSettings } from "@/features/boards/routes/BoardSettings.tsx";
const SamplePage = () => {
return <Typography>Hello World!</Typography>;
};
export const routes: RouteObject[] = [
{
path: "/",
element: (
<MainLayout>
<SamplePage />
</MainLayout>
),
},
{
path: "/boards",
element: (
<MainLayout>
<BoardListView />
</MainLayout>
),
},
{
path: "/boards/:boardId",
element: (
<MainLayout>
<BoardView />
</MainLayout>
),
},
{
path: "/boards/:boardId/settings",
element: (
<MainLayout>
<BoardSettings />
</MainLayout>
),
},
]; |
#!/usr/bin/env python3
"""This module contains functions for working with substitution ciphers.
It allows for automatically solving monoalphabetic substitution ciphers.
"""
import fitness
import frequency
from typing import Callable
from random import randint
def hill_climb(ciphertext: str, decrypt: Callable[[str, dict], str], key: dict, max_failures: int = 10000):
"""Basic hill climb based on randomly permuting a key
Args:
ciphertext: A input ciphertext
decrypt: A function that decrypts the ciphertext
key: An initial key
max_failures: The amount of permutations to try before assuming we've reached a maxima
"""
probs = fitness.get_probs()
cur_fitness = fitness.ngram_fitness(decrypt(ciphertext, key), probs)
failures = 0
attempted_mixes = []
while failures < max_failures:
rand1 = list(key.keys())[randint(0, len(key)-1)]
rand2 = list(key.keys())[randint(0, len(key)-1)]
mix = (rand1, rand2)
if mix not in attempted_mixes:
key2 = dict(key)
key2[rand1] = key[rand2]
key2[rand2] = key[rand1]
new_fitness = fitness.ngram_fitness(
decrypt(ciphertext, key2), probs)
if new_fitness > cur_fitness:
cur_fitness = new_fitness
key = key2
failures = 0
failures += 1
return key
def substitution_decode(ciphertext: str, key: dict):
"""Using a key, decode a substitution cipher
Case is ignored, to the extent that the function assumes that
upper-case ciphertext characters are always decoded to upper-case
plaintext characters. Any ciphertext character not in the key does
not get decoded
Args:
ciphertext: The ciphertext
key: A dictionary with keys as values and decryptions as values"""
output_text = ""
for c in ciphertext:
try:
if c.islower():
output_text += key[c.upper()].lower()
else:
output_text += key[c.upper()]
except:
output_text += c
return output_text
def substitution_solve(ciphertext: str, lang: str = 'en', max_failures: int = 1000):
"""Using hillclimbing, solve a monoalphabetic substitution cipher
The hillclimbing optimizes for the probability of 4-grams in the text.
Args:
ciphertext: The ciphertext to decode
lang: The language the ciphertext is in
max_failures: The amount of permutations to try before assuming we've reached a maxima"""
qprobs = fitness.get_probs(lang=lang)
sfreq = frequency.count_occurences(
frequency.get_ngrams(fitness.get_texts(lang), 1))
freq = frequency.count_occurences(frequency.get_ngrams(ciphertext, 1))
sfreq_sorted = sorted(sfreq.items(), key=lambda t: -t[1])
freq_sorted = sorted(freq.items(), key=lambda t: -t[1])
key = {}
for i in range(len(freq_sorted)):
key[freq_sorted[i][0]] = sfreq_sorted[i][0]
key = hill_climb(ciphertext, substitution_decode, key, max_failures)
return (substitution_decode(ciphertext, key), key)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Decrypt substitution ciphers")
parser.add_argument('--file', dest='file')
args = parser.parse_args()
with open(args.file, 'r') as ciphertext:
print(substitution_solve(ciphertext.read())) |
import numpy as np
from layer import Layer
from activation import Activation
class Tanh(Activation):
def __init__(self):
def tanh(x):
return np.tanh(x)
def tanh_prime(x):
return 1 - np.tanh(x) ** 2
super().__init__(tanh, tanh_prime)
class Sigmoid(Activation):
def __init__(self):
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_prime(x):
s = sigmoid(x)
return s * (1 - s)
super().__init__(sigmoid, sigmoid_prime)
class ReLU(Activation):
def __init__(self):
def relu(x):
tmp = np.zeros(x.shape)
self.output = np.maximum(tmp,x)
return self.output
def relu_prime(x):
x = relu(x)
self.output = np.where(x>0, 1, 0)
return self.output
super().__init__(relu, relu_prime)
class LeakyReLU(Activation):
def __init__(self):
self.leak = 0.01
def leakyrelu(x):
tmp = np.ones(x.shape)*self.leak
self.output = np.maximum(tmp,x)
return self.output
def leakyrelu_prime(x):
x = leakyrelu(x)
self.output = np.where(x>0, 1, self.leak)
return self.output
super().__init__(leakyrelu, leakyrelu_prime)
class Softmax(Layer):
def forward(self, input):
tmp = np.exp(input)
self.output = tmp / np.sum(tmp)
return self.output
def backward(self, output_gradient, learning_rate):
# This version is faster than the one presented in the video
n = np.size(self.output)
return np.dot((np.identity(n) - self.output.T) * self.output, output_gradient)
# Original formula:
# tmp = np.tile(self.output, n)
# return np.dot(tmp * (np.identity(n) - np.transpose(tmp)), output_gradient) |
# import libraries
import pandas as pd
from sqlalchemy import create_engine
import sys
def load_data(messages_filepath, categories_filepath):
"""
INPUT:
messages_filepath - csv file with the emergency messages
categories_filepath - csv file with the labels of each emergency message
OUTPUT:
df - DataFrame: Combined dataset with the messages and categories datasets merged using the common id
"""
# load messages dataset
messages = pd.read_csv(messages_filepath)
# load categories dataset
categories = pd.read_csv(categories_filepath)
# merge datasets
df = pd.merge(messages, categories)
return df
def clean_data(df):
"""
INPUT:
df - DataFrame: Combined dataset with the messages and categories datasets merged using the common id
OUTPUT:
df - Cleaned DataFrame
"""
# create a dataframe of the 36 individual category columns
categories = df['categories'].str.split(';', expand=True)
# select the first row of the categories dataframe
row = categories.iloc[0, :]
# use this row to extract a list of new column names for categories
category_colnames = [cat.split('-')[0] for cat in row]
# rename the columns of `categories`
categories.columns = category_colnames
# Convert category values to just numbers 0 or 1
for column in categories:
# set each value to be the last character of the string
categories[column] = [int(row[1]) for row in categories[column].str.split('-')]
# convert column from string to numeric
categories[column] = pd.to_numeric(categories[column])
# drop the original categories column from `df`
df.drop('categories', axis=1, inplace=True)
# concatenate the original dataframe with the new `categories` dataframe
df = pd.merge(df, categories, left_index=True, right_index=True)
# drop duplicates
df.drop_duplicates(inplace=True)
# drop rows with wrong values
inv_idx = df[(df.iloc[:, 4:] > 1).any(1)].index
df.drop(index=inv_idx, inplace=True)
return df
def save_data(df, database_filename):
"""
INPUT:
df - Cleaned DataFrame
database_filename - Desired name for the databese
OUTPUT:
stores the cleaned DataFrame in a SQLite database
"""
# Save the clean dataset into an sqlite database
engine = create_engine('sqlite:///{}'.format(database_filename))
df.to_sql(database_filename, engine, index=False, if_exists='replace')
def main():
"""
OUTPUT:
Load, clean and save the data
"""
if len(sys.argv) == 4:
messages_filepath, categories_filepath, database_filepath = sys.argv[1:]
print('Loading data...\n MESSAGES: {}\n CATEGORIES: {}'
.format(messages_filepath, categories_filepath))
df = load_data(messages_filepath, categories_filepath)
print('Cleaning data...')
df = clean_data(df)
print('Saving data...\n DATABASE: {}'.format(database_filepath))
save_data(df, database_filepath)
print('Cleaned data saved to database!')
else:
print('Please provide the filepaths of the messages and categories '\
'datasets as the first and second argument respectively, as '\
'well as the filepath of the database to save the cleaned data '\
'to as the third argument. \n\nExample: python process_data.py '\
'disaster_messages.csv disaster_categories.csv '\
'DisasterResponse.db')
if __name__ == '__main__':
main() |
###############################################################################
### Libraries ###
from kafka import KafkaConsumer, KafkaProducer
from kafka.structs import OffsetAndMetadata, TopicPartition
from kafka.coordinator.assignors.roundrobin import RoundRobinPartitionAssignor
from os import getcwd
from pprint import pprint
from bs4 import BeautifulSoup
from selenium import webdriver
from datetime import datetime
from pyvirtualdisplay import Display
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.firefox.options import Options
# from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
import os, sys, datetime, re, time, json, traceback, random, logging, pickle, requests
from pymongo import MongoClient
from pyvirtualdisplay import Display
import config_angellist as config
###############################################################################
###############################################################################
### Global Variables ###
# KAFKA Parameters
KAFKA_SERVER = "10.166.0.2:9095"
KAFKA_TOPIC_QUERIES = "queries_topic"
KAFKA_TOPIC_RESULTS = "results_topic"
# The url of the website for AngelList login
ANGELLIST_LOGIN_URL = 'https://angel.co/login'
# Cookies dir
CHROME_COOKIE_FILE = "cookies/chrome_cookie.pkl"
FIREFOX_COOKIE_FILE = "cookies/firefox_cookie.pkl"
# Stored browser/drivers of selenium
browsers = []
###############################################################################
def get_browser(browser_name='Firefox'):
# Selenium options for headless browser
options = Options()
# options.add_argument('--headless')
# options.add_argument('--disable-gpu')
# The browser (firefox or chrome) that Selenium will use
if browser_name == 'Firefox':
browser = webdriver.Remote(command_executor='127.0.0.1:4444/wd/hub',
desired_capabilities=DesiredCapabilities.FIREFOX, options=options)
elif browser_name == 'Chrome':
browser = webdriver.Remote(command_executor='127.0.0.1:5555/wd/hub',
desired_capabilities=DesiredCapabilities.CHROME, options=options)
browsers.append(browser)
return browser
###############################################################################
def get_cookies(browser, cookie_filename):
# Login to AngelList
browser.get(ANGELLIST_LOGIN_URL)
time.sleep(3)
# Check if cookies already exist
if os.path.isfile(cookie_filename):
print('Use existing cookies...', cookie_filename)
cookies = pickle.load(open(cookie_filename, 'rb'))
for cookie in cookies:
if 'expiry' in cookie:
cookie['expiry'] = int(str(cookie['expiry']).split('.', 1)[0])
# del cookie['expiry']
browser.add_cookie(cookie)
else:
print('Get cookies...', cookie_filename)
time.sleep(random.uniform(3, 8))
# Set email
browser.find_element_by_id('user_email').send_keys(config.email)
time.sleep(random.uniform(2, 5))
# Set password
browser.find_element_by_id('user_password').send_keys(config.password)
time.sleep(random.uniform(2, 5))
# Press submit button
browser.find_element_by_name('commit').click()
time.sleep(random.uniform(5, 10))
# Get cookies from browser and store them to a pickle
pickle.dump(browser.get_cookies(), open(cookie_filename,'wb'))
print('Done\n')
###############################################################################
def clean_queue(consumer):
print('\nClean queue...')
# consume and clean messages from topic 'results'
for msg in consumer:
consumer.commit()
print('Done\n')
###############################################################################
def random_crawling_pattern(firefox_browser, chrome_browser, total_companies):
# Random user-agent
random_browser = random.randint(0,1)
if random_browser == 0:
browser = chrome_browser
print('> Using CHROME')
else:
browser = firefox_browser
print('> Using FIREFOX')
# Actions for move cursor
actions = ActionChains(browser)
# Scroll randomly
random_scroll = random.randint(0,4)
if random_scroll == 0:
# go pg down: Keys.PAGE_DOWN
browser.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
time.sleep(2)
# go all up: Keys.HOME
browser.find_element_by_tag_name('body').send_keys(Keys.HOME)
elif random_scroll == 1:
# go pg down: Keys.PAGE_DOWN
browser.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
elif random_scroll == 2:
# go pg down: Keys.PAGE_DOWN
browser.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
time.sleep(1)
# go pg down: Keys.PAGE_DOWN
browser.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
time.sleep(1)
# go pg up: Keys.PAGE_UP
browser.find_element_by_tag_name('body').send_keys(Keys.PAGE_UP)
elif random_scroll == 3:
# go all down: Keys.END
browser.find_element_by_tag_name('body').send_keys(Keys.END)
elif random_scroll == 4:
# do nothing
pass
time.sleep(2)
# Go up at the top - move-slowly cursor in order to change website
try:
for i in range(0, 3):
actions.move_by_offset(20, 20).perform()
time.sleep(0.2)
except: # MoveTargetOutOfBoundsException: Message: (0, 850) is out of bounds of viewport
# print(' ', 'ERROR move_by_offset: 20, 20')
pass
try:
for i in range(0, 3):
actions.move_by_offset(-20, -20).perform()
time.sleep(0.2)
except: # MoveTargetOutOfBoundsException: Message: (0, 850) is out of bounds of viewport
# print(' ', 'ERROR move_by_offset: -5, -5')
pass
# Simulate random Right-Click
# # Click Random link
# random_scroll = random.randint(0,1)
# if random_scroll == 0:
# # Find all links
# list_random_links = browser.find_elements_by_tag_name("a")
# print('list_random_links:', len(list_random_links))
# list_random_links_v2 = []
# for i in range(0, len(list_random_links)):
# if 'https://angel.co/' in list_random_links[i].get_attribute('href'):
# list_random_links_v2.append(list_random_links[i])
# print('list_random_links_v2:', len(list_random_links_v2))
# # Select random link
# random_link = list_random_links_v2[random.randint(0, len(list_random_links_v2))]
# # Move cursor to random link
# actions.move_to_element(random_link).perform()
# time.sleep(1)
# # Click the random link
# random_link.click()
# time.sleep(3)
# Sleep for random time
# If we used at least 2 scrolls for parsing then wait less time
if total_companies >= 40:
time.sleep(random.randint(15,30))
else:
time.sleep(random.randint(25, 30))
# time.sleep(random.randint(15,30))
return browser
###############################################################################
def slave_start():
print('Start: slave_crawler')
print('='*50)
# Initialize Kafka producer and consumer
producer = KafkaProducer(bootstrap_servers=KAFKA_SERVER,
value_serializer=lambda x: json.dumps(x).encode('utf-8'))
consumer = KafkaConsumer(bootstrap_servers=KAFKA_SERVER,
value_deserializer=lambda x: json.loads(x.decode('utf-8')),
auto_offset_reset="earliest", consumer_timeout_ms=1000,
enable_auto_commit=True, group_id='qry-1', max_poll_interval_ms=3000000,
partition_assignment_strategy=[RoundRobinPartitionAssignor])
consumer.subscribe(KAFKA_TOPIC_QUERIES)
clean_queue(consumer)
try:
# Initialize browser
firefox_browser = get_browser(browser_name='Firefox')
chrome_browser = get_browser(browser_name='Chrome')
# Get cookies for AngelList account
get_cookies(firefox_browser, FIREFOX_COOKIE_FILE)
get_cookies(chrome_browser, CHROME_COOKIE_FILE)
num_errors = 0
browser = firefox_browser
print('Start consuming...')
print('='*50)
while True:
for msg in consumer:
print('Query: ' + str(msg.value))
crawled_data = msg.value
crawled_data['crawled_orgs'] = {}
consumer.commit()
if msg.value['stage'] == '1':
total_companies = -1
total_companies, crawled_orgs = first_phase_crawler(browser, msg.value['url'])
crawled_data['crawled_orgs'] = crawled_orgs
crawled_data['total_companies'] = total_companies
# If blacklisted
if total_companies == -1:
num_errors += 1
# push back to queue 'queries' because of error
producer.send(KAFKA_TOPIC_QUERIES, value=msg.value)
# Close consumer with error message
if num_errors == 3:
print('='*50)
print('EXIT...3 errors')
exit()
else:
num_errors = 0
producer.send(KAFKA_TOPIC_RESULTS, value=crawled_data)
print('-'*70)
# Insert randomness to crawling
browser = random_crawling_pattern(firefox_browser, chrome_browser, total_companies)
elif msg.value['stage'] == '2':
second_phase_crawler(browser, msg.value['url'])
finally:
print('\nCLOSE ALL BROWSERS...WAIT!')
for browser in browsers:
browser.quit()
print('Done\n')
print('='*50)
print('Finish: slave_crawler')
###############################################################################
def first_phase_crawler(browser, url):
print('Waiting for crawling...')
# Actions for move cursor
actions = ActionChains(browser)
# Get total companies for crawling
total_companies = get_orgs_number(browser, url)
# Dictionary that contains the crawled companies
crawled_orgs = dict()
# If less than 400 then crawl the companies
if total_companies > 0 and total_companies <= 400:
# Continue getting companies by pressing "more" button/item
companies_crawled = 0
errors_count = 0
time.sleep(5)
while(companies_crawled < total_companies):
count_new_companies, crawled_orgs = parse_results(crawled_orgs, browser)
companies_crawled += count_new_companies
print(' ' + datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S'),
', Count_new_companies:', str(count_new_companies), ', Companies_crawled:', str(companies_crawled))
try:
# Scroll at the end
browser.find_element_by_tag_name('body').send_keys(Keys.END)
time.sleep(1)
# Move curson to 'more' button
more_button = browser.find_element_by_class_name('more')
try:
actions.move_to_element(more_button).perform()
time.sleep(2)
except: # MoveTargetOutOfBoundsException: Message: (0, 850) is out of bounds of viewport
pass
# Press button 'more' to get the next items
more_button.click()
# browser.find_element_by_class_name('more').click()
time.sleep(random.randint(5,10))
except:
error_str = str(traceback.format_exc())
if errors_count == 3:
print(' ', 'ERROR: could not retrieved all companies!')
exit()
if ('Unable to locate element: .more' in error_str or
' Unable to locate element: {"method":"css selector","selector":".more"}' in error_str):
if companies_crawled < total_companies-1:
# Refresh page
browser.get(url)
time.sleep(10)
print(' ', 'Waiting: not yet retrieved all companies!...refresh page')
errors_count += 1
elif companies_crawled == total_companies-1:
break
else:
print(error_str)
exit()
return total_companies, crawled_orgs
###############################################################################
def get_orgs_number(browser, url):
# Get total companies for crawling
num_errors = 0
flag = False
total_companies = -1
# Get initial website of AngelList
browser.get(url)
time.sleep(5)
while num_errors < 3 and flag == False:
try:
class_count = browser.find_element_by_xpath("//div[contains(@class, 'count')]")
total_companies = int(class_count.text.replace(',', '').replace(' Companies', '').replace(' Company', ''))
flag = True
print(' ', 'Total companies: ' + str(total_companies))
except:
print(traceback.format_exc())
print(' ', 'Class <count> does not exist')
num_errors += 1
time.sleep(num_errors*3)
return total_companies
###############################################################################
def parse_results(crawled_orgs, browser):
html_source = browser.page_source
sourcedata = html_source.encode('utf-8')
soup = BeautifulSoup(sourcedata, 'html.parser')
all_divs_companies = soup.body.findAll('div', {'data-_tn': 'companies/row'})
count_new_companies = 0
for company_row in all_divs_companies:
# The object for storing in MongoDB
company_fields = {
'name': '',
'pitch': '',
'angel_link': '',
'joined_at': '',
'website': '',
'location': '',
'market': '',
'size': '',
'stage': '',
'total_raised': ''
}
try:
# Company column
company_col = company_row.select('div.company.column')
company_col_name = company_col[0].select('div.name')
company_col_name_href = company_col_name[0].select('a.startup-link')
company_fields['name'] = company_col_name_href[0].text
company_fields['angel_link'] = company_col_name_href[0]['href']
company_fields['pitch'] = company_col[0].select('div.pitch')[0].text.strip()
except:
# error if first row is the headers
continue
# Joined column
company_joined = company_row.select('div.column.joined')
if len(company_joined) >= 1:
company_fields['joined_at'] = company_joined[0].select('div.value')[0].text.strip()
# Location column
company_location = company_row.select('div.column.location')
company_location_tag = company_location[0].select('div.tag')
if len(company_location_tag) == 1:
company_fields['location'] = company_location_tag[0].text
# Market column
company_market = company_row.select('div.column.market')
company_market_tag = company_market[0].select('div.tag')
if len(company_market_tag) == 1:
company_fields['market'] = company_market_tag[0].text
# Website column
company_website = company_row.select('div.column.website')
if len(company_website) >= 1:
try:
company_fields['website'] = company_website[0].select('a')[0]['href']
except:
# print(' ', 'Something wrong with website:', str(company_website[0]))
pass
# Employees column
company_size = company_row.select('div.column.company_size')
company_fields['size'] = company_size[0].select('div.value')[0].text.strip()
if len(company_fields['size']) == '-':
company_fields['size'] = ''
# Stage column
company_stage = company_row.select('div.column.stage')
if len(company_stage) >= 1:
company_fields['stage'] = company_stage[0].select('div.value')[0].text
company_fields['stage'] = company_fields['stage'].strip().replace('-', '')
# Total raised column
company_raised = company_row.select('div.column.raised')
if len(company_raised) >= 1:
company_fields['total_raised'] = company_raised[0].select('div.value')[0].text
company_fields['total_raised'] = company_fields['total_raised'].strip().replace(',','').replace('-', '')
if not company_fields['name'] in crawled_orgs:
crawled_orgs[company_fields['name']] = company_fields
count_new_companies += 1
return count_new_companies, crawled_orgs
###############################################################################
def second_phase_crawler(browser):
pass
###############################################################################
if __name__ == "__main__":
slave_start() |
import {sum} from "./sum";
test("add two numbers" , ()=>{
expect(sum(1,2)).toBe(3)
});
////trying different matchers
test("to be zero" , ()=>{
const value = 0;
expect(value).not.toBeNull();
expect(value).toBeDefined();
expect(value).not.toBeUndefined();
expect(value).not.toBeTruthy(); //terminal indicates what and where went wrong; //toBeTruthy --> not.toBeTruthy
expect(value).toBeFalsy();
});
test('to be null', () => {
const value = null;
expect(value).toBeNull();
expect(value).toBeDefined();
expect(value).not.toBeUndefined(); //null != undefined
expect(value).not.toBeTruthy();
expect(value).toBeFalsy();
});
//error testing
const throwError = ()=>{
throw new Error('It doesn\'t works as expected'); //use throw not return
}
test('erorr testing' , ()=>{
expect(()=>throwError()).toThrow(Error) //to only check error is there or not
expect(()=>throwError()).toThrow('It doesn\'t works as expected') //to check exact statement
}) |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner.planPrinter;
import com.facebook.presto.spi.plan.PlanNodeId;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import java.util.Map;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.Math.max;
import static java.lang.Math.sqrt;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toMap;
public class HashCollisionPlanNodeStats
extends PlanNodeStats
{
private final Map<String, OperatorHashCollisionsStats> operatorHashCollisionsStats;
public HashCollisionPlanNodeStats(
PlanNodeId planNodeId,
Duration planNodeScheduledTime,
Duration planNodeCpuTime,
long planNodeInputPositions,
DataSize planNodeInputDataSize,
long planNodeRawInputPositions,
DataSize planNodeRawInputDataSize,
long planNodeOutputPositions,
DataSize planNodeOutputDataSize,
Map<String, OperatorInputStats> operatorInputStats,
Map<String, OperatorHashCollisionsStats> operatorHashCollisionsStats)
{
super(planNodeId, planNodeScheduledTime, planNodeCpuTime, planNodeInputPositions, planNodeInputDataSize, planNodeRawInputPositions, planNodeRawInputDataSize, planNodeOutputPositions, planNodeOutputDataSize, operatorInputStats);
this.operatorHashCollisionsStats = requireNonNull(operatorHashCollisionsStats, "operatorHashCollisionsStats is null");
}
public Map<String, Double> getOperatorHashCollisionsAverages()
{
return operatorHashCollisionsStats.entrySet().stream()
.collect(toMap(
Map.Entry::getKey,
entry -> entry.getValue().getWeightedHashCollisions() / operatorInputStats.get(entry.getKey()).getInputPositions()));
}
public Map<String, Double> getOperatorHashCollisionsStdDevs()
{
return operatorHashCollisionsStats.entrySet().stream()
.collect(toMap(
Map.Entry::getKey,
entry -> computedWeightedStdDev(
entry.getValue().getWeightedSumSquaredHashCollisions(),
entry.getValue().getWeightedHashCollisions(),
operatorInputStats.get(entry.getKey()).getInputPositions())));
}
private static double computedWeightedStdDev(double sumSquared, double sum, double totalWeight)
{
double average = sum / totalWeight;
double variance = (sumSquared - 2 * sum * average) / totalWeight + average * average;
// variance might be negative because of numeric inaccuracy, therefore we need to use max
return sqrt(max(variance, 0d));
}
public Map<String, Double> getOperatorExpectedCollisionsAverages()
{
return operatorHashCollisionsStats.entrySet().stream()
.collect(toMap(
Map.Entry::getKey,
entry -> entry.getValue().getWeightedExpectedHashCollisions() / operatorInputStats.get(entry.getKey()).getInputPositions()));
}
@Override
public PlanNodeStats mergeWith(PlanNodeStats other)
{
checkArgument(other instanceof HashCollisionPlanNodeStats, "other is not an instanceof HashCollisionPlanNodeStats");
PlanNodeStats merged = super.mergeWith(other);
return new HashCollisionPlanNodeStats(
merged.getPlanNodeId(),
merged.getPlanNodeScheduledTime(),
merged.getPlanNodeCpuTime(),
merged.getPlanNodeInputPositions(),
merged.getPlanNodeInputDataSize(),
merged.getPlanNodeRawInputPositions(),
merged.getPlanNodeRawInputDataSize(),
merged.getPlanNodeOutputPositions(),
merged.getPlanNodeOutputDataSize(),
merged.operatorInputStats,
operatorHashCollisionsStats);
}
} |
import { createApi } from '@reduxjs/toolkit/query/react';
import { axiosBaseQuery } from 'shared/config/axios';
import { TodoModel } from 'shared/interfaces';
export const todoApi = createApi({
reducerPath: 'todoApi',
baseQuery: axiosBaseQuery(),
tagTypes: ['Todo'],
endpoints: (builder) => ({
getAllTodo: builder.query<TodoModel[], string>({
query: () => {
return {
url: `/todo`,
};
},
providesTags: ['Todo'],
}),
getTodoByID: builder.query<TodoModel, number>({
query: (id: number) => {
return {
url: `todo/${id}`,
};
},
providesTags: ['Todo'],
}),
deleteTodoById: builder.mutation({
query: (id: number) => {
return {
url: `/todo/${id}`,
method: 'DELETE',
};
},
invalidatesTags: ['Todo'],
}),
toggleTodoStatus: builder.mutation<void, Omit<TodoModel, 'title'>>({
query: ({ id, completed }) => {
return {
url: `/todo/${id}`,
method: 'PATCH',
data: { completed },
};
},
invalidatesTags: ['Todo'],
}),
addNewTodo: builder.mutation<void, Omit<TodoModel, 'id'>>({
query: ({ title, completed }) => {
return {
url: '/todo/',
method: 'POST',
data: { title, completed },
};
},
invalidatesTags: ['Todo'],
}),
}),
});
export const {
useGetAllTodoQuery,
useGetTodoByIDQuery,
useDeleteTodoByIdMutation,
useToggleTodoStatusMutation,
useAddNewTodoMutation,
} = todoApi; |
import React, { useState } from "react";
import Carousel from "../../components/carousel/carousel";
import { FaCheck } from "react-icons/fa";
import { IoCloseCircle } from "react-icons/io5";
import { RxDimensions } from "react-icons/rx";
import { differenceInDays } from "date-fns";
import { useDispatch, useSelector } from "react-redux";
import { addBookingToCart } from "../../features/bookingsSlice";
export default function RoomsModal({ visible, close, room }) {
const { discount_programme, discount_rate } = useSelector(
(store) => store.bookings
);
const { userData } = useSelector((store) => store.login);
const dispatch = useDispatch();
const [arrivalDate, setArrivalDate] = useState("");
const [departureDate, setDepartureDate] = useState("");
const [numGuests, setNumGuests] = useState(1);
const handleRoomBooking = () => {
let nights = differenceInDays(
new Date(departureDate),
new Date(arrivalDate)
);
console.log("nights: ", nights);
const roomBooking = {
user_id: userData.id,
title: room.title,
startDate: new Date(arrivalDate).getTime(),
endDate: new Date(departureDate).getTime(),
num_guest: numGuests,
num_courses: null,
event_time: null,
rateInCent: room.rate,
type: "suites",
description: room.description,
discount_programme: null,
discount_rate: discount_programme,
imageurl: room.imageURLs[0],
totalAmount: (room.rate - discount_rate * room.rate) * numGuests * nights,
paid: false,
payment_ref: null,
};
console.log("New booking: ", roomBooking);
dispatch(addBookingToCart(roomBooking));
};
return (
<div
className="modal"
style={{
display: visible ? "block" : "none",
backgroundColor: "rgba(0, 0, 0, 0.7)",
position: "fixed",
top: 0,
left: 0,
width: "100%",
height: "100%",
padding: "20px",
zIndex: 10,
}}
>
<div
className="modal-content"
style={{
backgroundColor: "white",
borderRadius: "10px",
width: "90vw",
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
}}
>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
padding: "10px",
}}
>
<div>
<h2>{room.title}</h2>
</div>
<div>
<button
className="close-button"
onClick={close}
style={{
border: "none",
background: "none",
cursor: "pointer",
}}
>
<IoCloseCircle size={30} />
</button>
</div>
</div>
<div
style={{
overflow: "scroll",
height: "80vh",
}}
>
<div style={{ height: "30vh" }}>
<Carousel listOfImgURL={room.imageURLs} />
</div>
<div
style={{
padding: "20px",
}}
>
<div
style={{
borderBottom: "1px gray solid",
}}
>
<p>
<RxDimensions /> {room.floorSpace} m<sup>2</sup>
</p>
<p>{room.description}</p>
<br />
</div>
<div
style={{
borderBottom: "1px gray solid",
}}
>
<h3>Add suite to bookings</h3>
<div
style={{
display: "flex",
justifyContent: "space-between",
flexWrap: "wrap",
}}
>
<label style={{ marginBottom: "10px" }}>
Arrival Date:
<br />
<input
type="date"
value={arrivalDate}
onChange={(event) => setArrivalDate(event.target.value)}
/>
</label>
<br />
<label style={{ marginBottom: "10px" }}>
Departure Date:
<br />
<input
type="date"
value={departureDate}
onChange={(event) => setDepartureDate(event.target.value)}
/>
</label>
<label style={{ marginBottom: "10px" }}>
Guests:
<br />
<select
value={numGuests}
onChange={(event) =>
setNumGuests(parseInt(event.target.value, 10))
}
>
<option value={1}>1 guest</option>
<option value={2}>2 guests</option>
</select>
</label>
</div>
<button
className="w3-ripple"
style={{
fontSize: "15px",
padding: "10px",
backgroundColor: "#006c67",
color: "white",
border: "none",
borderRadius: "5px",
cursor: "pointer",
textDecoration: "none",
height: "5vh",
}}
onClick={handleRoomBooking}
>
Book Now
</button>
<br />
<br />
</div>
</div>
<div
className="amenities"
style={{
padding: "20px",
}}
>
<h3>Amenities</h3>
<div style={{ display: "flex" }}>
<div style={{ marginRight: "50px" }}>
<div>
<FaCheck /> Desk
</div>
<div>
<FaCheck /> Wardrobe
</div>
<div>
<FaCheck /> Bathroom with shower
</div>
<div>
<FaCheck /> Bathroom with bathtub
</div>
<div>
<FaCheck /> Hairdryer
</div>
<div>
<FaCheck /> Bathrobes
</div>
<div>
<FaCheck /> Slippers
</div>
<div>
<FaCheck /> Kitchenette
</div>
<div>
<FaCheck /> Individual controlled AC units
</div>
<div>
<FaCheck /> Washer/dryer
</div>
</div>
<div className="column">
<div>
<FaCheck /> Nespresso coffee machine
</div>
<div>
<FaCheck /> Eco stove/oven
</div>
<div>
<FaCheck /> Fridge/freezer
</div>
<div>
<FaCheck /> 49'' LED/LCD flat screen TV
</div>
<div>
<FaCheck /> High speed Wi-Fi
</div>
<div>
<FaCheck /> DSTV Hotel Bouquet
</div>
<div>
<FaCheck /> Microwave/dishwasher
</div>
<div>
<FaCheck /> Ensuite-bathroom
</div>
<div>
<FaCheck /> Private balcony/dining area
</div>
<div>
<FaCheck /> Keyless electronic unit entry
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
} |
import React from 'react'
const Education = ({education}) => {
return (
<section>
<h1>Educación</h1>
<ul>
{
education.map(
({ institution, startDate, endDate, area }) => {
const startYear = new Date(startDate).getFullYear()
const endYear =
endDate != null ? new Date(endDate).getFullYear() : "Actual"
const years = `${startYear} - ${endYear}`
return (
<li>
<article>
<header>
<div>
<h3>{institution}</h3>
</div>
<time>{years}</time>
</header>
<footer>
<p>{area}</p>
</footer>
</article>
</li>
)
}
)
}
</ul>
</section>
)
}
export default Education |
from rest_framework import serializers
from .models import User
class UserRegisterSerializer(serializers.ModelSerializer):
password2 = serializers.CharField()
class Meta:
model = User
fields = ['email', 'username', 'password', 'password2']
def save(self, *args, **kwargs):
user = User(
email=self.validated_data['email'],
username=self.validated_data['username'],
)
password = self.validated_data['password']
password2 = self.validated_data['password2']
if password != password2:
raise serializers.ValidationError({password: "Password does not match"})
user.set_password(password)
user.save()
return user |
<div class="row justify-content-center">
<div class="col-8">
<form name="editForm" role="form" novalidate (ngSubmit)="save()" [formGroup]="editForm">
<h2 id="jhi-camion-heading" data-cy="CamionCreateUpdateHeading" jhiTranslate="gestionStockLivraisonApp.camion.home.createOrEditLabel">
Create or edit a Camion
</h2>
<div>
<jhi-alert-error></jhi-alert-error>
<div class="form-group" [hidden]="editForm.get('id')!.value == null">
<label class="form-control-label" jhiTranslate="global.field.id" for="field_id">ID</label>
<input type="number" class="form-control" name="id" id="field_id" data-cy="id" formControlName="id" [readonly]="true" />
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="gestionStockLivraisonApp.camion.designation" for="field_designation"
>Designation</label
>
<input
type="text"
class="form-control"
name="designation"
id="field_designation"
data-cy="designation"
formControlName="designation"
/>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="gestionStockLivraisonApp.camion.date" for="field_date">Date</label>
<div class="d-flex">
<input
id="field_date"
data-cy="date"
type="datetime-local"
class="form-control"
name="date"
formControlName="date"
placeholder="YYYY-MM-DD HH:mm"
/>
</div>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="gestionStockLivraisonApp.camion.montantTotal" for="field_montantTotal"
>Montant Total</label
>
<input
type="number"
class="form-control"
name="montantTotal"
id="field_montantTotal"
data-cy="montantTotal"
formControlName="montantTotal"
/>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="gestionStockLivraisonApp.camion.vendeur" for="field_vendeur">Vendeur</label>
<select class="form-control" id="field_vendeur" data-cy="vendeur" name="vendeur" formControlName="vendeur">
<option *ngIf="editForm.get(['vendeur'])!.value == null" [ngValue]="null" selected></option>
<option
[ngValue]="vendeurOption.id === editForm.get('vendeur')!.value?.id ? editForm.get('vendeur')!.value : vendeurOption"
*ngFor="let vendeurOption of vendeursCollection; trackBy: trackVendeurById"
>
{{ vendeurOption.designation }}
</option>
</select>
</div>
<div *ngIf="editForm.get(['vendeur'])!.invalid && (editForm.get(['vendeur'])!.dirty || editForm.get(['vendeur'])!.touched)">
<small
class="form-text text-danger"
*ngIf="editForm.get(['vendeur'])?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
</div>
</div>
<div>
<button type="button" id="cancel-save" data-cy="entityCreateCancelButton" class="btn btn-secondary" (click)="previousState()">
<fa-icon icon="ban"></fa-icon> <span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button
type="submit"
id="save-entity"
data-cy="entityCreateSaveButton"
[disabled]="editForm.invalid || isSaving"
class="btn btn-primary"
>
<fa-icon icon="save"></fa-icon> <span jhiTranslate="entity.action.save">Save</span>
</button>
</div>
</form>
</div>
</div> |
defmodule StarkInfra.IssuingHolder.Log do
alias __MODULE__, as: Log
alias StarkInfra.Utils.Rest
alias StarkInfra.Utils.Check
alias StarkInfra.User.Project
alias StarkInfra.User.Organization
alias StarkInfra.Error
@moduledoc """
Groups IssuingHolder.Log related functions
"""
@doc """
Every time an IssuingHolder entity is updated, a corresponding IssuingHolder.Log
is generated for the entity. This log is never generated by the
user, but it can be retrieved to check additional information
on the IssuingHolder.
## Attributes:
- `:id` [string]: unique id returned when the log is created. ex: "5656565656565656"
- `:holder` [IssuingHolder]: IssuingHolder entity to which the log refers to.
- `:type` [string]: type of the IssuingHolder event which triggered the log creation. ex: "blocked", "canceled", "created", "unblocked", "updated"
- `:created` [DateTime]: creation datetime for the log. ex: ~U[2020-03-10 10:30:0:0]
"""
@enforce_keys [
:id,
:holder,
:type,
:created
]
defstruct [
:id,
:holder,
:type,
:created
]
@type t() :: %__MODULE__{}
@doc """
Receive a single IssuingHolder.Log struct previously created by the Stark Infra API by its id.
## Parameters (required):
- `:id` [string]: struct unique id. ex: "5656565656565656"
## Options:
- `:user` [Organization/Project, default nil]: Organization or Project struct returned from StarkInfra.project(). Only necessary if default project or organization has not been set in configs.
## Return:
- IssuingHolder.Log struct with updated attributes
"""
@spec get(
id: binary,
user: Project.t() | Organization.t() | nil
) ::
{ :ok, Log.t() } |
{ :error, [Error.t()] }
def get(id, options \\ []) do
Rest.get_id(
resource(),
id,
options
)
end
@doc """
Same as get(), but it will unwrap the error tuple and raise in case of errors.
"""
@spec get!(
id: binary,
user: Project.t() | Organization.t() | nil
) :: any
def get!(id, options \\ []) do
Rest.get_id!(
resource(),
id,
options
)
end
@doc """
Receive a stream of IssuingHolder.Log structs previously created in the Stark Infra API
## Options:
- `:limit` [integer, default nil]: maximum number of structs to be retrieved. Unlimited if nil. ex: 35
- `:ids` [list of strings, default nil]: list of ids to filter retrieved structs. ex: ["5656565656565656", "4545454545454545"]
- `:after` [Date or string, default nil]: date filter for structs created only after specified date. ex: ~D[2020-03-25]
- `:before` [Date or string, default nil]: date filter for structs created only before specified date. ex: ~D[2020-03-25]
- `:types` [list of strings, default nil]: filter for log event types. ex: ["created", "blocked"]
- `:holder_ids` [list of strings, default nil]: list of IssuingHolder ids to filter logs. ex: ["5656565656565656", "4545454545454545"]
- `:user` [Organization/Project, default nil]: Organization or Project struct returned from StarkInfra.project(). Only necessary if default project or organization has not been set in configs.
## Return:
- stream of IssuingHolder.Log structs with updated attributes
"""
@spec query(
ids: [binary],
limit: integer,
after: Date.t() | binary,
before: Date.t() | binary,
types: [binary],
holder_ids: [binary],
user: Project.t() | Organization.t() | nil
) ::
{ :ok, {binary, [Log.t()]} } |
{ :error, [Error.t()] }
def query(options \\ []) do
Rest.get_list(
resource(),
options
)
end
@doc """
Same as query(), but it will unwrap the error tuple and raise in case of errors.
"""
@spec query!(
ids: [binary],
limit: integer,
after: Date.t() | binary,
before: Date.t() | binary,
types: [binary],
holder_ids: [binary],
user: Project.t() | Organization.t() | nil
) :: any
def query!(options \\ []) do
Rest.get_list!(
resource(),
options
)
end
@doc """
Receive a list of up to 100 IssuingHolder.Log structs previously created in the Stark Infra API and the cursor to the next page.
Use this function instead of query if you want to manually page your requests.
## Options:
- `:cursor` [string, default nil]: cursor returned on the previous page function call
- `:ids` [list of strings, default nil]: list of ids to filter retrieved structs. ex: ["5656565656565656", "4545454545454545"]
- `:limit` [integer, default 100]: maximum number of structs to be retrieved. It must be an integer between 1 and 100. ex: 50
- `:after` [Date or string, default nil]: date filter for structs created only after specified date. ex: ~D[2020-03-25]
- `:before` [Date or string, default nil]: date filter for structs created only before specified date. ex: ~D[2020-03-25]
- `:types` [list of strings, default nil]: filter for log event types. ex: ["created", "blocked"]
- `:holder_ids` [list of strings, default nil]: list of IssuingHolder ids to filter logs. ex: ["5656565656565656", "4545454545454545"]
- `:user` [Organization/Project, default nil]: Organization or Project struct returned from StarkInfra.project(). Only necessary if default project or organization has not been set in configs.
## Return:
- list of IssuingHolder.Log structs with updated attributes
- cursor to retrieve the next page of IssuingHolder.Log structs
"""
@spec page(
cursor: binary,
ids: [binary],
limit: integer,
after: Date.t() | binary,
before: Date.t() | binary,
types: [binary],
holder_ids: [binary],
user: Project.t() | Organization.t() | nil
) ::
{ :ok, {binary, [Log.t()]} } |
{ :error, [Error.t()] }
def page(options \\ []) do
Rest.get_page(
resource(),
options
)
end
@doc """
Same as page(), but it will unwrap the error tuple and raise in case of errors.
"""
@spec page!(
cursor: binary,
ids: [binary],
limit: integer,
after: Date.t() | binary,
before: Date.t() | binary,
types: [binary],
holder_ids: [binary],
user: Project.t() | Organization.t() | nil
) :: any
def page!(options \\ []) do
Rest.get_page!(
resource(),
options
)
end
@doc false
def resource() do
{
"IssuingHolderLog",
&resource_maker/1
}
end
@doc false
def resource_maker(json) do
%Log{
id: json[:id],
holder: json[:holder],
type: json[:type],
created: json[:created] |> Check.datetime(),
}
end
end |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>C4T3</title>
</head>
<body>
<div>
<h1>Aplikasi Ubah Warna</h1>
<label>Warna Latar : </label>
<input type="color" id="bg-color" />
<label>Warna Teks :</label>
<input type="color" id="text-color" />
</div>
<script>
let bgColor = document.getElementById("bg-color");
let txtColor = document.getElementById("text-color");
bgColor.addEventListener("change", (event) => {
document.body.style.backgroundColor = bgColor.value;
});
txtColor.addEventListener("change", (event) => {
document.body.style.color = txtColor.value;
});
</script>
<h1>Kalkulator Luas dan Keliling Persegi</h1>
<div>
<label>Panjang</label>
<input type="number" class="angka-pertama" />
<label>Lebar</label>
<input type="number" class="angka-kedua" />
<button class="tombol-keliling">Hasil Keliling Persegi</button>
<button class="tombol-luas">Hasil Luas Persegi</button>
<h2 class="hasil"></h2>
</div>
<script>
const elementAngkaPertama = document.querySelector(".angka-pertama");
const elementAngkaKedua = document.querySelector(".angka-kedua");
const elementTombolKeliling = document.querySelector(".tombol-keliling");
const elementTombolLuas = document.querySelector(".tombol-luas");
const elementHasil = document.querySelector(".hasil");
elementTombolKeliling.addEventListener("click", function () {
const nilaiAngkaPertama = Number(elementAngkaPertama.value);
const nilaiAngkaKedua = Number(elementAngkaKedua.value);
const hasil = 2 * (nilaiAngkaPertama + nilaiAngkaKedua);
elementHasil.textContent = hasil;
});
elementTombolLuas.addEventListener("click", function () {
const nilaiAngkaPertama = Number(elementAngkaPertama.value);
const nilaiAngkaKedua = Number(elementAngkaKedua.value);
const hasil = nilaiAngkaPertama * nilaiAngkaKedua;
elementHasil.textContent = hasil;
});
</script>
</body>
</html> |
import { DndContext } from '@dnd-kit/core';
import { useState } from 'react';
import { Navbar, GameGridCell, Piece } from './components';
function App() {
const gameGridCellIds = ["11", "21", "31", "41", "51", "61", "71", "81", "91"];
const playerOnePieceIds = ["112", "212", "312", "412", "512", "612", "712", "812", "912"];
const playerTwoPieceIds = ["122", "222", "322", "422", "522", "622", "722", "822", "922"];
const [ myState, setMyState ] = useState(() => {
let cellValues = {};
for (let i = 0; i < gameGridCellIds.length; i++) {
cellValues[gameGridCellIds[i]] = null;
}
let pieceAvailability = {};
const pieceIds = [...playerOnePieceIds, ...playerTwoPieceIds];
for (let i = 0; i < pieceIds.length; i++) {
pieceAvailability[pieceIds[i]] = true;
}
return {playerToMove: "1", message:"", gameOver: false, cellValues, pieceAvailability};
})
const pieceMarkups = (() => {
let markups = {};
const ids = [...playerOnePieceIds, ...playerTwoPieceIds];
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
markups[id] = <Piece id={id} piecePriority={getPiecePriority(id)} disabled={myState.gameOver || !myState.pieceAvailability[id] || id[1] !== myState.playerToMove} />
}
return markups;
})();
return (
<div className='xl:h-screen bg-black text-white font-roboto overflow-hidden'>
<Navbar />
<DndContext onDragEnd={handleDragEnd} autoScroll={false}>
<div className='xl:flex xl:h-5/6'>
{/* Player One Area */}
<div className='xl:w-3/12 xl:h-full flex flex-col items-center xl:items-end pt-10 xl:pt-20'>
<div className='flex flex-col-reverse xl:flex-col gap-5'>
<div className='w-80 h-64 xl:w-64 xl:h-80 flex flex-wrap flex-col xl:flex-row'>
{playerOnePieceIds.map((id, _) =>
<div key={"pieceCell" + id} className="w-1/3 h-1/3 flex items-center justify-center">
{myState.pieceAvailability[id] ? pieceMarkups[id] : null}
</div>
)}
</div>
<p className='text-center text-gray'>Player One</p>
</div>
</div>
{/* Game Grid Area */}
<div className='xl:w-1/2 xl:h-full flex flex-col items-center pt-10'>
<div className='h-96 w-96 grid grid-rows-3 grid-cols-3 gap-1 bg-white'>
{gameGridCellIds.map((id, _) =>
<GameGridCell id={id} key={id}>
{myState.cellValues[id] ? pieceMarkups[myState.cellValues[id]] : null}
</GameGridCell>
)}
</div>
{myState.gameOver ?
<div className='pt-8 w-full flex flex-col'>
<p className='text-center'>{myState.message}</p>
<button className='mt-4 mx-auto w-16 h-12 rounded-lg text-3xl hover:bg-white hover:text-black transition-colors ease-in-out delay-50' onClick={restartGame}>⟳</button>
</div>
: null}
</div>
{/* Player Two Area */}
<div className='xl:w-3/12 xl:h-full flex flex-col items-center xl:items-start py-10 xl:pt-20 xl:pb-0'>
<div className='flex flex-col gap-5'>
<div className='w-80 h-64 xl:w-64 xl:h-80 flex flex-wrap flex-col-reverse xl:flex-row-reverse'>
{playerTwoPieceIds.map((id, _) =>
<div key={"pieceCell" + id} className="w-1/3 h-1/3 flex items-center justify-center">
{myState.pieceAvailability[id] ? pieceMarkups[id] : null}
</div>
)}
</div>
<p className='text-center text-gray'>Player Two</p>
</div>
</div>
</div>
</DndContext>
</div>
);
function restartGame() {
setMyState(() => {
const nextState = {...myState};
nextState.playerToMove = "1";
nextState.message = "";
nextState.gameOver = false;
for (let key in myState.cellValues) {
nextState.cellValues[key] = null;
}
for (let key in myState.pieceAvailability) {
nextState.pieceAvailability[key] = true;
}
return nextState;
})
}
function handleDragEnd(event) {
if (!event.over) return;
const pieceId = event.active.id;
const cellId = event.over.id;
if (!isValidMove(pieceId, cellId, myState.playerToMove)) return;
setMyState(() => {
let nextState = {...myState};
nextState.pieceAvailability[pieceId] = false;
nextState.cellValues[cellId] = pieceId;
if (checkPlayerWon()) {
nextState.message = `Player ${myState.playerToMove === "1" ? "One" : "Two"} Won!`;
nextState.gameOver = true;
} else {
nextState.playerToMove = myState.playerToMove === "1" ? "2" : "1";
if (checkNoPossibleMoves(nextState.playerToMove)) {
nextState.message = "Game Tied!";
nextState.gameOver = true;
}
}
return nextState;
})
}
function isValidMove(pieceId, cellId, playerToMove) {
if (pieceId[1] !== playerToMove) return false;
const currPieceId = myState.cellValues[cellId];
if (!currPieceId) return true;
if (currPieceId[1] !== playerToMove &&
getPiecePriority(pieceId) > getPiecePriority(currPieceId)) {
return true;
}
return false;
}
function getPiecePriority(pieceId) {
const remainder = parseInt(pieceId[0]) % 3;
if (remainder === 1) return 2;
else if (remainder === 2) return 1;
return remainder;
}
function checkPlayerWon() {
const cellValues = myState.cellValues;
try {
if (cellValues['11'][1] === cellValues['21'][1] && cellValues['21'][1] === cellValues['31'][1]) return true;
} catch (error) {}
try {
if (cellValues['41'][1] === cellValues['51'][1] && cellValues['51'][1] === cellValues['61'][1]) return true;
} catch (error) {}
try {
if (cellValues['71'][1] === cellValues['81'][1] && cellValues['81'][1] === cellValues['91'][1]) return true;
} catch (error) {}
try {
if (cellValues['11'][1] === cellValues['41'][1] && cellValues['41'][1] === cellValues['71'][1]) return true;
} catch (error) {}
try {
if (cellValues['21'][1] === cellValues['51'][1] && cellValues['51'][1] === cellValues['81'][1]) return true;
} catch (error) {}
try {
if (cellValues['31'][1] === cellValues['61'][1] && cellValues['61'][1] === cellValues['91'][1]) return true;
} catch (error) {}
try {
if (cellValues['11'][1] === cellValues['51'][1] && cellValues['51'][1] === cellValues['91'][1]) return true;
} catch (error) {}
try {
if (cellValues['31'][1] === cellValues['51'][1] && cellValues['51'][1] === cellValues['71'][1]) return true;
} catch (error) {}
return false;
}
function checkNoPossibleMoves(playerToMove) {
for (let i = 1; i <= 9; i++){
const pieceId = i + playerToMove + "2";
if (myState.pieceAvailability[pieceId]) {
// if there is a cell that can accept this piece then return false
for (let j = 0; j < gameGridCellIds.length; j++) {
const cellId = gameGridCellIds[j];
if (isValidMove(pieceId, cellId, playerToMove)) return false;
}
}
}
return true;
}
}
export default App; |
//
// LoginViewModel.swift
// StudyForCombine
//
// Created by OpenObject on 2022/12/05.
//
import Foundation
import Combine
class LoginViewModel {
@Published var login: String = ""
@Published var password: String = ""
@Published var isLoading = false
let validationResult = PassthroughSubject<String, Error>()
private(set) lazy var isInputValid = Publishers.CombineLatest($login, $password)
.map { $0.count > 2 && $0 == "abc" && $1.count > 2 && $1 == "123" }
.eraseToAnyPublisher()
private let credentialsValidator: CredentialsValidatorProtocol
init(credentailsValidator: CredentialsValidatorProtocol = CredentialsValidator()) {
self.credentialsValidator = credentailsValidator
}
func validateCredentials() {
isLoading = true
credentialsValidator.validateCredentials(login: login, password: password) { [weak self] result in
self?.isLoading = false
switch result {
case .success:
self?.validationResult.send("HELLO")
case let .failure(error):
self?.validationResult.send(completion: .failure(error))
}
}
}
}
// MARK: - CredentialsValidatorProtocol
// TODO: Promises 적용
protocol CredentialsValidatorProtocol {
func validateCredentials(
login: String,
password: String,
completion: @escaping (Result<(), Error>) -> Void)
}
/// This class acts as an example of asynchronous credentials validation
/// It's for demo purpose only. In the real world it would make an actual request or use other authentication method
final class CredentialsValidator: CredentialsValidatorProtocol {
func validateCredentials(
login: String,
password: String,
completion: @escaping (Result<(), Error>) -> Void) {
let time: DispatchTime = .now() + .milliseconds(Int.random(in: 200 ... 1_000))
DispatchQueue.main.asyncAfter(deadline: time) {
// hardcoded success
completion(.success(()))
}
}
} |
#ifndef PROFILER_H
#define PROFILER_H
#include <vector>
#include <string>
#include <functional>
#include <iostream>
#include <matplot/matplot.h>
#include <unordered_map>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include "Timer.h"
template <typename T>
class Profiler
{
private:
std::vector<double> sizes; // Store sizes of each vector
std::vector<double> times; // Store time taken for sorting each vector
struct SortResult
{
std::string m_function_name{};
double m_time{};
SortResult() = default;
SortResult(std::string name, double time) : m_function_name{ name }, m_time{ time } {}
bool operator<(const SortResult& other) const {
return m_time < other.m_time;
}
friend std::ostream& operator<<(std::ostream& os, const SortResult& sr) {
os << sr.m_time << "s";
return os;
}
};
static std::unordered_map<int, std::vector<SortResult>> all_times;
public:
/*
Profiles the passed function using the data provided
Graphs (time vs data size) and stores it as "filename.png"
*/
Profiler(std::vector<std::vector<T>> vec,
const std::function<void(std::vector<T>&)>& func,
const std::string filename)
{
for (auto& inner_vec : vec)
{
sizes.push_back(static_cast<double>(inner_vec.size()));
std::vector<T> copy = inner_vec;
int one_size = static_cast<int>(copy.size());
Timer::start();
func(copy);
double elapsed_time = Timer::end();
all_times[one_size].push_back(SortResult(filename, elapsed_time));
times.push_back(elapsed_time);
}
using namespace matplot;
auto p = plot(sizes, times, "-o");
title(filename);
xlabel("Vector Size");
ylabel("Time (seconds)");
save(filename + ".png");
std::cout << "Finished Profiling [" << filename << "]" << std::endl;
}
/*
Displays the results
Stores:
1- All the results in AllResults.md
2- The fastest performing algorithms for each data size in Fastest.md
*/
static void displayAndSaveAllResults()
{
std::ofstream allResultsFile("AllResults.md");
std::ofstream fastestFile("Fastest.md");
std::vector<int> sorted_keys;
for (const auto& pair : all_times)
sorted_keys.push_back(pair.first);
std::sort(sorted_keys.begin(), sorted_keys.end());
if (allResultsFile.good())
{
// Print header
std::string header = "| Size |";
std::string separator = "|--------|";
if (!all_times.empty()) {
auto headerResults = all_times.begin()->second;
std::sort(headerResults.begin(), headerResults.end(), [](const SortResult& a, const SortResult& b) {
return a.m_function_name < b.m_function_name;
});
for (const auto& sortResult : headerResults) {
header += " " + sortResult.m_function_name + " |";
separator += "--------------|";
}
}
std::cout << header << std::endl;
std::cout << separator << std::endl;
allResultsFile << header << "\n";
allResultsFile << separator << "\n";
for (int size : sorted_keys)
{
std::vector<SortResult> results = all_times[size];
std::sort(results.begin(), results.end(), [](const SortResult& a, const SortResult& b) {
return a.m_function_name < b.m_function_name;
});
std::string line = "| " + std::to_string(size) + " |";
for (const auto& sortResult : results) {
std::ostringstream streamObj;
streamObj << std::fixed << std::setprecision(10) << sortResult.m_time;
line += " " + streamObj.str() + "s |";
}
std::cout << line << std::endl;
allResultsFile << line << "\n";
}
}
if (fastestFile.good())
{
fastestFile << "| Size | Fastest Algorithm | Time |\n";
fastestFile << "|--------|-------------------|-------------|\n";
for (int size : sorted_keys)
{
std::vector<SortResult> results = all_times[size];
// Sorting based on time to find the fastest.
std::sort(results.begin(), results.end(), [](const SortResult& a, const SortResult& b) {
return a.m_time < b.m_time;
});
// Using the first result since it's the fastest.
std::ostringstream streamObj;
streamObj << std::fixed << std::setprecision(10) << results[0].m_time;
fastestFile << "| " << size << " | " << results[0].m_function_name << " | " << streamObj.str() << "s |\n";
}
}
allResultsFile.close();
fastestFile.close();
}
};
template <typename T>
std::unordered_map<int, std::vector<typename Profiler<T>::SortResult>> Profiler<T>::all_times;
#endif |
# negotiator
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
An HTTP content negotiator for Node.js
## Installation
```sh
$ npm install negotiator
```
## API
```js
var Negotiator = require('negotiator')
```
### Accept Negotiation
```js
availableMediaTypes = ['text/html', 'text/plain', 'application/json']
// The negotiator constructor receives a request object
negotiator = new Negotiator(request)
// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8'
negotiator.mediaTypes()
// -> ['text/html', 'image/jpeg', 'application/*']
negotiator.mediaTypes(availableMediaTypes)
// -> ['text/html', 'application/json']
negotiator.mediaType(availableMediaTypes)
// -> 'text/html'
```
You can check a working example at `examples/accept.js`.
#### Methods
##### mediaType()
Returns the most preferred media type from the client.
##### mediaType(availableMediaType)
Returns the most preferred media type from a list of available media types.
##### mediaTypes()
Returns an array of preferred media types ordered by the client preference.
##### mediaTypes(availableMediaTypes)
Returns an array of preferred media types ordered by priority from a list of
available media types.
### Accept-Language Negotiation
```js
negotiator = new Negotiator(request)
availableLanguages = ['en', 'es', 'fr']
// Let's say Accept-Language header is 'en;q=0.8, es, pt'
negotiator.languages()
// -> ['es', 'pt', 'en']
negotiator.languages(availableLanguages)
// -> ['es', 'en']
language = negotiator.language(availableLanguages)
// -> 'es'
```
You can check a working example at `examples/language.js`.
#### Methods
##### language()
Returns the most preferred language from the client.
##### language(availableLanguages)
Returns the most preferred language from a list of available languages.
##### languages()
Returns an array of preferred languages ordered by the client preference.
##### languages(availableLanguages)
Returns an array of preferred languages ordered by priority from a list of
available languages.
### Accept-Charset Negotiation
```js
availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5']
negotiator = new Negotiator(request)
// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2'
negotiator.charsets()
// -> ['utf-8', 'iso-8859-1', 'utf-7']
negotiator.charsets(availableCharsets)
// -> ['utf-8', 'iso-8859-1']
negotiator.charset(availableCharsets)
// -> 'utf-8'
```
You can check a working example at `examples/charset.js`.
#### Methods
##### charset()
Returns the most preferred charset from the client.
##### charset(availableCharsets)
Returns the most preferred charset from a list of available charsets.
##### charsets()
Returns an array of preferred charsets ordered by the client preference.
##### charsets(availableCharsets)
Returns an array of preferred charsets ordered by priority from a list of
available charsets.
### Accept-Encoding Negotiation
```js
availableEncodings = ['identity', 'gzip']
negotiator = new Negotiator(request)
// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5'
negotiator.encodings()
// -> ['gzip', 'identity', 'compress']
negotiator.encodings(availableEncodings)
// -> ['gzip', 'identity']
negotiator.encoding(availableEncodings)
// -> 'gzip'
```
You can check a working example at `examples/encoding.js`.
#### Methods
##### encoding()
Returns the most preferred encoding from the client.
##### encoding(availableEncodings)
Returns the most preferred encoding from a list of available encodings.
##### encodings()
Returns an array of preferred encodings ordered by the client preference.
##### encodings(availableEncodings)
Returns an array of preferred encodings ordered by priority from a list of
available encodings.
## See Also
The [accepts](https://npmjs.org/package/accepts#readme) module builds on
this module and provides an alternative interface, mime type validation,
and more.
## License
[MIT](LICENSE)
[npm-image]: https://img.shields.io/npm/v/negotiator.svg
[npm-url]: https://npmjs.org/package/negotiator
[node-version-image]: https://img.shields.io/node/v/negotiator.svg
[node-version-url]: http://nodejs.org/download/
[travis-image]: https://img.shields.io/travis/jshttp/negotiator/master.svg
[travis-url]: https://travis-ci.org/jshttp/negotiator
[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg
[coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master
[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg
[downloads-url]: https://npmjs.org/package/negotiator |
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<%= link_to 'CourseCatalog', root_path, class: "navbar-brand"%>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<% if logged_in? %>
<ul class="nav navbar-nav">
<li><%= link_to 'Home', user_path(current_user)%></li>
<li><%= link_to 'Subjects', subjects_path%></li>
<li><%= link_to 'Courses', courses_path%></li>
<li><%= link_to 'Instructors', instructors_path%></li>
<li><%= link_to 'Search',{:controller => "search", :action => "page", :search => {:name => "", :subject => ""}}%></li>
</ul>
<% end %>
<ul class="nav navbar-nav navbar-right">
<% if logged_in? %>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Settings <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><%= link_to 'Profile', user_path(current_user)%></li>
<li role="separator" class="divider"></li>
<li><%= link_to 'Log Out', logout_path, method: :delete%></li>
</ul>
</li>
<% else %>
<li><%= link_to "Log in", login_path %></li>
<% end %>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav> |
<template>
<div class="app-container">
角色列表
<!--查询表单-->
<div class="search-div">
<el-form label-width="70px" size="small">
<el-row>
<el-col :span="24">
<el-form-item label="角色名称">
<el-input
style="width: 100%"
v-model="searchObj.roleName"
placeholder="角色名称"
></el-input>
</el-form-item>
</el-col>
</el-row>
<el-row style="display: flex">
<el-button
type="primary"
icon="el-icon-search"
size="mini"
@click="fetchData()"
>搜索</el-button
>
<el-button icon="el-icon-refresh" size="mini" @click="resetData"
>重置</el-button
>
</el-row>
</el-form>
</div>
<!-- 工具条 -->
<div class="tools-div">
<el-button type="success" icon="el-icon-plus" size="mini" @click="add"
>添 加</el-button
>
<el-button class="btn-add" size="mini" @click="batchRemove()"
>批量删除</el-button
>
</div>
<!-- 表格 -->
<el-table
v-loading="listLoading"
:data="list"
stripe
border
style="width: 100%; margin-top: 10px"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" />
<el-table-column label="序号" width="70" align="center">
<template slot-scope="scope">
{{ (page - 1) * limit + scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column prop="roleName" label="角色名称" />
<el-table-column prop="roleCode" label="角色编码" />
<el-table-column prop="createTime" label="创建时间" width="160" />
<el-table-column label="操作" width="200" align="center">
<template slot-scope="scope">
<el-button
type="primary"
icon="el-icon-edit"
size="mini"
@click="edit(scope.row.id)"
title="修改"
/>
<el-button
type="danger"
icon="el-icon-delete"
size="mini"
@click="removeDataById(scope.row.id)"
title="删除"
/>
<el-button
type="warning"
icon="el-icon-baseball"
size="mini"
@click="showAssignAuth(scope.row)"
title="分配权限"
/>
</template>
</el-table-column>
</el-table>
<!-- 分页组件 -->
<el-pagination
:current-page="page"
:total="total"
:page-size="limit"
style="padding: 30px 0; text-align: center"
layout="total, prev, pager, next, jumper"
@current-change="fetchData"
/>
<!-- 弹框 -->
<el-dialog title="添加/修改" :visible.sync="dialogVisible" width="40%">
<el-form
ref="dataForm"
:model="sysRole"
label-width="150px"
size="small"
style="padding-right: 40px"
>
<el-form-item label="角色名称">
<el-input v-model="sysRole.roleName" />
</el-form-item>
<el-form-item label="角色编码">
<el-input v-model="sysRole.roleCode" />
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button
@click="dialogVisible = false"
size="small"
icon="el-icon-refresh-right"
>取 消</el-button
>
<el-button
type="primary"
icon="el-icon-check"
@click="saveOrUpdate()"
size="small"
>确 定</el-button
>
</span>
</el-dialog>
</div>
</template>
<script>
// 引入定义的接口的js文件
import api from '@/api/system/role'
export default {
// 定义初始值
data() {
return {
listLoading: false, // 是否显示加载
list: [], // 角色列表
total: 0, // 总记录数
page: 1, // 当前页
limit: 3, // 每页默认显示3条数据
searchObj: {}, // 条件查询封装对象
dialogVisible: false, // 是否弹框
sysRole: {}, // 封装添加表单的数据
selectValue: [] // 复选框选
}
},
// 页面渲染之前执行
created() {
// 调用列表方法,一进入页面就调用方法得到数据
this.fetchData()
},
methods: {
// 展现分配的权限
showAssignAuth(row) {
this.$router.push(
'/system/assignAuth?id=' + row.id + '&roleName=' + row.roleName
)
},
// 复选框发生变化时执行的方法
handleSelectionChange(selection) {
this.selectValue = selection
// console.log(this.selectValue)
},
//批量删除
batchRemove() {
//判断复选框是否为空
if (this.selectValue.length == 0) {
this.$message.warning('请选择要删除的记录!')
return
} else {
var idList = []
//获取id值
//遍历数组
for (let i = 0; i < this.selectValue.length; i++) {
let obj = this.selectValue[i]
let id = obj.id
idList.push(id)
}
this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 调用方法删除
api.batchRemove(idList).then((response) => {
// 提示信息
this.$message({
type: 'success',
message: '删除成功!'
})
// 刷新页面
this.fetchData()
})
})
}
},
// 点击确定
saveOrUpdate() {
//判断是添加还是修改
if (!this.sysRole.id) {
// 调用添加方法
this.saveRole()
} else {
this.updateRole()
}
},
// 点击修改-数据回显
edit(id) {
api.getRoleById(id).then((response) => {
this.dialogVisible = true
this.sysRole = response.data
})
},
//修改方法
updateRole() {
api.update(this.sysRole).then((response) => {
//提示信息
this.$message({
type: 'success',
message: '修改成功!'
})
//关闭弹窗
this.dialogVisible = false
//刷新数据
this.fetchData()
})
},
// 保存方法
saveRole() {
// 调用api方法
api.saveRole(this.sysRole).then((response) => {
//提示信息
this.$message({
type: 'success',
message: '添加成功!'
})
//关闭弹窗
this.dialogVisible = false
//刷新数据
this.fetchData()
})
},
// 点击添加,弹出框
add() {
this.dialogVisible = true
this.sysRole = {}
},
// 删除
removeDataById(id) {
this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 调用方法删除
api.removeId(id).then((response) => {
// 提示信息
this.$message({
type: 'success',
message: '删除成功!'
})
// 刷新页面
this.fetchData()
})
})
},
//重置
resetData() {
//清空单元格
this.searchObj = {}
//重新查询
this.fetchData()
},
fetchData(pageNum = 1) {
this.page = pageNum
// 调用api
// console.log(this.searchObj)
api
.getPageList(this.page, this.limit, this.searchObj)
.then((response, error) => {
// debugger
// this.listLoading = false
// console.log(response)
// console.log(response.data)
this.list = response.data.records
this.total = response.data.total
})
.catch((error) => {
console.log(error.message)
})
}
}
}
</script>
@/api/system/role |
1.变形(transform)
translate(x,y) 定义 2D 转换,沿着 X 和 Y 轴移动元素。 位移效果
translateX(n) 定义 2D 转换,沿着 X 轴移动元素。
translateY(n) 定义 2D 转换,沿着 Y 轴移动元素。
scale(x,y) 定义 2D 缩放转换,改变元素的宽度和高度。 缩放效果
scaleX(n) 定义 2D 缩放转换,改变元素的宽度。
scaleY(n) 定义 2D 缩放转换,改变元素的高度。
rotate(angle) 定义 2D 旋转,在参数中规定角度(-360deg - 360deg)。 旋转效果
skew(x-angle,y-angle) 定义 2D 倾斜转换,沿着 X 和 Y 轴。 变形效果
skewX(angle) 定义 2D 倾斜转换,沿着 X 轴。
skewY(angle) 定义 2D 倾斜转换,沿着 Y 轴。
matrix(a,b,c,d,e,f) 定义 2D变形,使用了6个值的矩阵。表示如下:
a c e
b d f
0 0 1
matrix用一个3行3列的矩阵表示,a和b列表示x轴,c和d列表示y轴,e和f列表示z轴
a和d表示缩放(如果没有缩放,值设为1)
b和c表示扭曲(如果没有扭曲,值为0)
e和f表示位移(如果没有位移,值为0)
如果旋转角度为θ,它会影响到a,b,c,d的值:
a = cosθ
b = sinθ
c = -sinθ
d = cosθ
如果扭曲skew(θ1,θ2),会影响到b和c的值:
b = tanθ1
c = tanθ2
每次旋转和扭曲都会产生一个新矩阵,最终形成的多个矩阵要做乘法运算。
如果对一个元素同时有旋转、扭曲、缩放和位移,这里需要用到多个矩阵相乘,要优先考虑旋转和缩放!!!
2.transform-origin:调整元素的基点。
transform-origin: x-axis y-axis z-axis;
属性值:
x-axis :定义视图被置于 X 轴的何处。可能的值:left,center,right,length,%。
y-axis :定义视图被置于 Y 轴的何处。可能的值:top,center,bottom,length,%。
z-axis :定义视图被置于 Z 轴的何处。可能的值:length。
3.perspective
让子元素获得透视效果。
perspective:length|none;
主流浏览器都不支持,谷歌要加-webkit-,或在长度后加单位。
4. transform-style
在3D空间中呈现被嵌套的元素(必须与 transform 属性一同使用)。
transform-style: flat|preserve-3d;
5.rotateZ
沿着Z轴的方向顺指针旋转。
6.transition:过渡动画
1)常规用法:
transition-property
transition-duration
transition-timing-function
transition-delay
2)简洁(复合)用法:
transition: property-name-list|all duration timing-function delay;
a)可以使用的属性有:
i)颜色:
color background-color border-color outline-color
ii)位置:
background-position left right top bottom
iii)长度:
max-height min-height max-width min-width height width
border-width margin padding outline-width outline-offset
font-size line-height text-indent vertical-align
border-spacing letter-spacing word-spacing
iv)数字:
opacity visibility z-index font-weight zoom
v)组合:
text-shadow transform box-shadow clip
vi)其它
gradient
b)duration:动画持续时间,一般以秒(s)或毫秒(ms)为单位
c)timing-function:动画函数
i)linear:匀速
ii)ease:变速(先慢后快,最后再慢)
iii)ease-in:变速(由慢到快)
iv)ease-out:变速(由快到慢)
v)ease-in-out:变速(慢速开始,慢速结束)
vi)cubic-bezier(n,n,n,n):自行设定变速,n的值在0-1之间
d)delay:动画延时时间,一般以秒(s)或毫秒(ms)为单位
7.关键帧动画
步骤:
1)设置关键帧
a)如果只有两个关键帧
@keyframes 动画名 {
0%:{样式表}
100%:{样式表}
}
或:
@keyframes 动画名 {
from:{样式表}
to:{样式表}
}
b)如果是多个关键帧
@keyframes 动画名 {
0%:{样式表}
25%:{样式表}
60%:{样式表}
...
100%:{样式表}
}
注意:这里的百分比一般是升序值,可以是0%-100%之间的做任意值,也可以是倒序。
2)实施动画
a)常规用法
animation-name:来自于@keyframes定义的动画名
animation-duration:动画持续时间,一般以秒(s)或毫秒(ms)为单位(默认为0)
animation-timing-function:动画函数
i)linear:匀速(默认值)
ii)ease:变速(先慢后快,最后再慢)
iii)ease-in:变速(由慢到快)
iv)ease-out:变速(由快到慢)
v)ease-in-out:变速(慢速开始,慢速结束)
vi)cubic-bezier(n,n,n,n):自行设定变速,n的值在0-1之间
animation-delay:动画延时时间,一般以秒(s)或毫秒(ms)为单位
animation-iteration-count:动画循环播放的次数
1)number:按设定次数循环播放(默认次数为1次)
2)infinite:一直循环播放
animation-direction:动画播放完后是否反向播放
1)normal:不反向(默认值)
2)alternate:反向
animation-play-state:动画播放或停止播放
1)paused:停止播放
2)running:播放(默认值)
b)简洁用法
animation:name duration timing-function delay iteration-count direction; |
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class UsersTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->insert([
[
'name' => 'María',
'first_surname' => 'García',
'second_surname' => 'Pérez',
'email' => 'maria.garcia@example.com',
'dni' => '12345678A',
'postal_code' => '29001',
'city' => 'Málaga',
'password' => Hash::make('password1234'),
'address' => 'Calle Mayor, 123',
'phone_number' => '123456789',
'birthdate' => '1990-05-15',
'profile_picture' => 'https://via.placeholder.com/150',
'role' => 'customer',
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
],
[
'name' => 'Juan',
'first_surname' => 'Rodríguez',
'second_surname' => 'López',
'email' => 'juan.rodriguez@example.com',
'dni' => '23456789B',
'postal_code' => '29002',
'city' => 'Málaga',
'password' => Hash::make('password1234'),
'address' => 'Avenida Libertad, 456',
'phone_number' => '987654321',
'birthdate' => '1985-09-22',
'profile_picture' => 'https://via.placeholder.com/150',
'role' => 'admin',
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
],
[
'name' => 'Laura',
'first_surname' => 'Martínez',
'second_surname' => 'Sánchez',
'email' => 'laura.martinez@example.com',
'dni' => '34567890C',
'postal_code' => '29003',
'city' => 'Málaga',
'password' => Hash::make('password1234'),
'address' => 'Plaza España, 789',
'phone_number' => '654321987',
'birthdate' => '1995-02-10',
'profile_picture' => 'https://via.placeholder.com/150',
'role' => 'customer',
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
],
[
'name' => 'Carlos',
'first_surname' => 'Fernández',
'second_surname' => 'Gómez',
'email' => 'carlos.fernandez@example.com',
'dni' => '45678901D',
'postal_code' => '29004',
'city' => 'Málaga',
'password' => Hash::make('password1234'),
'address' => 'Calle Real, 234',
'phone_number' => '789456123',
'birthdate' => '1980-11-30',
'profile_picture' => 'https://via.placeholder.com/150',
'role' => 'customer',
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
],
[
'name' => 'Elena',
'first_surname' => 'López',
'second_surname' => 'Martínez',
'email' => 'elena.lopez@example.com',
'dni' => '56789012E',
'postal_code' => '29005',
'city' => 'Málaga',
'password' => Hash::make('password1234'),
'address' => 'Avenida Andalucía, 567',
'phone_number' => '321654987',
'birthdate' => '1998-07-20',
'profile_picture' => 'https://via.placeholder.com/150',
'role' => 'customer',
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
],
]);
}
} |
import React, { useState, useEffect } from "react";
import heart from "../../src/cardsIcons/heart-solid.svg";
import diamond from "../../src/cardsIcons/diamond-solid.svg";
import spade from "../../src/cardsIcons/spade.svg";
import clover from "../../src/cardsIcons/clover-solid.svg";
import CardContainer from "./CardContainer";
import Button from "../button/Button";
import styled from "styled-components";
const DealtCardsContainer = styled.div`
display: flex;
gap: 1rem;
`;
const CardWrapper = styled.div`
border: 2px solid black;
padding: 1rem 2rem;
background-color: #fff;
border-radius: 1rem;
`;
const HiddenCard = styled.div`
width: 6.3rem;
background-image: url("/images/card-back.svg");
background-repeat: no-repeat;
`;
const CardNumber = styled.p`
font-size: 2rem;
text-align: center;
`;
const ScoreWrapper = styled.div`
background-color: #fff;
padding: 2rem;
display: flex;
flex-direction: column;
align-items: center;
`;
const Player = ({
cards,
children,
player,
computer,
dealNewPlayerCard,
handlePlayerHold,
hold,
getScore,
blackJack,
}) => {
const [dealtCards, setDealtCards] = useState([]);
const [score, setScore] = useState(0);
const handleDealNewPlayerCard = () => {
dealNewPlayerCard();
setDealtCards((prevState) => [...prevState, ...cards]);
};
const playerHoldHandler = () => {
handlePlayerHold();
};
const determineAceValue = () => {
return cards.reduce((prevVal, currentVal) => {
if (currentVal.name.toLowerCase().includes("ace") && score < 21) {
currentVal.value = 11;
} else if (currentVal.name.toLowerCase().includes("ace") && score > 21) {
currentVal.value = 1;
}
return prevVal + currentVal.value;
}, 0);
};
useEffect(() => {
setDealtCards([...cards]);
}, [cards]);
useEffect(() => {
const newScore = determineAceValue();
setScore(newScore);
getScore(newScore);
}, [dealtCards]);
const cardImg = (card) => {
const cardName = card.name.split(" ")[1].toLowerCase();
if (cardName === "heart") return heart;
if (cardName === "clover") return clover;
if (cardName === "spade") return spade;
if (cardName === "diamond") return diamond;
};
return (
<CardContainer>
<ScoreWrapper>
<h2>{children}</h2>
{score < 21 && player && <h3>Score: {score}</h3>}
{!blackJack && hold && computer && <h3>Score: {score}</h3>}
{blackJack && computer && <h3>Score: {score}</h3>}
{player && score > 21 && <h3>You lost Score: {score}</h3>}
{player && score === 21 && <h3>Blackjack Score: {score}</h3>}
</ScoreWrapper>
<DealtCardsContainer>
{cards.length > 0 &&
cards.map((card, i) => {
if (!blackJack && !hold && computer && i === 0) {
return <HiddenCard key={card.name} />;
}
if (hold && i === 0) {
return (
<CardWrapper key={card.name}>
<CardNumber>
{card.symbol}
<img
style={{ height: 53, width: 36 }}
src={cardImg(card)}
alt=""
/>
</CardNumber>
</CardWrapper>
);
}
return (
<CardWrapper key={card.name}>
<CardNumber>
{card.symbol}
<img
style={{ height: 53, width: 36 }}
src={cardImg(card)}
alt=""
/>
</CardNumber>
</CardWrapper>
);
})}
</DealtCardsContainer>
{!blackJack && !hold && player && dealtCards.length > 0 && score < 21 && (
<>
<Button onClick={handleDealNewPlayerCard}>New card</Button>
<Button onClick={playerHoldHandler}>Hold</Button>
</>
)}
</CardContainer>
);
};
export default Player; |
import React, { useState } from "react";
import { MenuIcon, SearchIcon, XIcon } from "lucide-react";
import { Input } from "./ui/input";
import { Switch } from "./ui/switch";
import { useTheme} from "@/components/theme-provider";
import type { Theme } from "@/components/theme-provider";
import { Button } from "./ui/button";
function Navigation({
query,
setQuery,
fetchRequest,
}: {
query: string;
setQuery: React.Dispatch<React.SetStateAction<string>>;
fetchRequest: (queryVal: string) => void;
}) {
const { theme, setTheme } = useTheme();
const [open, setOpen] = useState(false);
const [openSearchBar, setOpenSearchBar] = useState(false);
return (
<>
<nav className="pl-[27px] pr-[23px] pt-[18px] pb-[19px] flex justify-evenly">
<p className="font-pattaya font-normal w-full text-2xl md:text-3xl text-header">
Image Gallery
</p>
<div className="gap-7 w-full items-center text-header hidden md:flex">
<Input
onKeyDown={(e) => {
if (e.key === "Enter") {
fetchRequest(query);
}
}}
value={query}
onChange={(e) => setQuery(e.target.value)}
className={`w-[419px] h-10 ${
query != "" ? "bg-[#ECECEC]" : "bg-search"
} text-black focus:bg-[#ECECEC]`}
placeholder=" Search Images here"
/>
<ul className="flex font-Montserrat text-xs font-bold not-italic leading-normal gap-14">
<li>Explore</li>
<li>Collection</li>
<li>Community</li>
</ul>
</div>
<div className="hidden md:flex w-full items-center gap-2 justify-center">
<h3 className="font-Montserrat text-xs font-bold not-italic leading-normal w-fit text-header">
{theme !== "dark" ? "Dark Mode" : "Light Mode"}
</h3>
<Switch
defaultValue="light"
checked={theme == "dark"}
onCheckedChange={() => setTheme(theme == "dark" ? "light" : "dark")}
/>
</div>
<div className="flex gap-[2px] md:hidden">
<Button variant="link" onClick={() => setOpenSearchBar(true)}>
<SearchIcon size={18} />
</Button>
<Button variant="link" onClick={() => setOpen(true)}>
<MenuIcon size={24} />
</Button>
</div>
</nav>
{open && (
<NavigationMobile setTheme={setTheme} theme={theme} setOpen={setOpen} />
)}
{openSearchBar && (
<SearchModel setOpen={setOpenSearchBar} fetchRequest={fetchRequest} />
)}
</>
);
}
function SearchModel({ fetchRequest, setOpen }: { setOpen: React.Dispatch<React.SetStateAction<boolean>>; fetchRequest: (queryVal: string) => void }) {
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setOpen(false);
fetchRequest(e?.target[0].value);
}
return (
<section className="md:hidden fixed top-0 left-0 z-50 h-screen w-full bg-black/50 backdrop-blur-sm">
<div className="mt-20 mx-4 relative">
<Button variant="link" className="absolute -top-10 -right-2">
<XIcon
className="h-6"
onClick={() => {
setOpen(false);
}}
/>
</Button>
<form onSubmit={handleSubmit}>
<Input
name="search"
type="text"
autoFocus
className={`w-full h-14 bg-[#ECECEC] text-black focus:bg-[#ECECEC] active:bg-[#ECECEC]`}
placeholder=" Search Images here"
/>
</form>
</div>
</section>
);
}
function NavigationMobile({ theme, setTheme, setOpen }: { theme: string; setTheme: (query: Theme) => void; setOpen: React.Dispatch<React.SetStateAction<boolean>> }) {
return (
<div className="md:hidden fixed right-0 top-0 z-50 h-screen w-full grid grid-cols-5">
<div
role="button"
onClick={() => setOpen(false)}
className="col-span-2 bg-black/50 backdrop-blur-sm"
/>
<aside className="col-span-3 bg-background px-2 relative">
<Button
variant="link"
className="absolute top-4 right-5"
onClick={() => setOpen(false)}
>
<XIcon className="h-6" />
</Button>
<ul className="flex flex-col font-Montserrat mt-10 text-base font-bold not-italic leading-normal gap-4">
<li>Explore</li>
<li>Collection</li>
<li>Community</li>
</ul>
<div className="flex w-full items-center gap-2 justify-start mt-5">
<h3 className="font-Montserrat text-xs font-bold not-italic leading-normal w-fit text-header">
{theme !== "dark" ? "Dark Mode" : "Light Mode"}
</h3>
<Switch
defaultValue="light"
checked={theme == "dark"}
onCheckedChange={() => setTheme(theme == "dark" ? "light" : "dark")}
/>
</div>
</aside>
</div>
);
}
export default Navigation; |
function[perfSummary, onsets] = mental_learning(scr, stim, key, n_E_levels, n_to_reach, n_learningRepeats, timings)
%[perfSummary, onsets] = mental_learning(scr, stim, key, n_E_levels, n_to_reach, n_learningRepeats, timings)
% mental_learning will make the participant perform nXX repetitions of each
% effort level to see what each effort level means.
%
% INPUTS
% scr: structure with screen parameters
%
% stim: structure with stimuli parameters
%
% key: structure with key information
%
% n_E_levels: number of effort levels to learn
%
% n_to_reach: structure with number of answers to provide for each effort
% level
%
% n_learningRepeats: number of repetitions of each effort level
%
% timings: structure with relevant timings for the experiment
%
% OUTPUTS
% perfSummary: structure with summary of performance
%
% onsets: sturcture with onsets data
%% screen parameters
window = scr.window;
%% time parameters
time_limit = timings.time_limit;
t_max = timings.max_effort;
t_learning_rest = timings.learning_rest;
t_instructions = timings.instructions;
%% instructions
[onsets] = EpEm_learningInstructions(scr, stim, t_instructions);
%% error handling
errorLimits.useOfErrorMapping = false;
errorLimits.useOfErrorThreshold = false;
%% define main parameters
mentalE_prm = mental_effort_parameters();
% define number of trials to perform learning
n_learningTrials = n_learningRepeats*n_E_levels;
% initialize the numbers to be used
numberVector = mental_numbers(n_learningTrials);
learning_instructions = 'noInstructions';
% initialize var of interest
[perfSummary.trialSummary, trialSuccess, onsets.effortPeriod] = deal(cell(1,n_learningTrials));
%% perform learning
jTrial = 0;
for iEffortRepeat = 1:n_learningRepeats
for iEffortLevel = 1:n_E_levels
jTrial = jTrial + 1;
%% extract effort level for the current trial
n_max_to_reach_trial = n_to_reach.(['E_level_',num2str(iEffortLevel - 1)]);
%% extract start angle according to effort level of the current trial
mentalE_prm.startAngle = stim.difficulty.startAngle.(['level_',num2str(iEffortLevel-1)]);
%% perform the effort
[perfSummary.trialSummary{jTrial}, trialSuccess{jTrial}, onsets.effortPeriod{jTrial}] = mental_effort_perf_Nback(scr, stim, key,...
numberVector(jTrial,:), mentalE_prm, n_max_to_reach_trial,...
learning_instructions, time_limit, t_max, errorLimits);
%% Show a rest text and give some rest
DrawFormattedText(window, stim.MVC_rest.text,...
stim.MVC_rest.x, stim.MVC_rest.y, stim.MVC_rest.colour);
[~,timeNow] = Screen(window,'Flip');
onsets.rest(jTrial) = timeNow;
WaitSecs(t_learning_rest);
%% display number of trials done for the experimenter
disp(['Mental learning (2) trial ',num2str(jTrial),'/',num2str(n_learningTrials),' done']);
end % effort level
end % effort repetition
%% extract relevant data
perfSummary.numberVector = numberVector;
perfSummary.onsets = onsets;
perfSummary.trialSuccess = trialSuccess;
perfSummary.n_learningTrials = n_learningTrials;
perfSummary.n_E_levels = n_E_levels;
perfSummary.n_learningRepeats = n_learningRepeats;
perfSummary.timings = timings;
perfSummary.t_learning_rest = t_learning_rest;
end % function |
import glob
import os
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
BASE_DIR = r"aug"
TEST_SIZE = 0.10
VAL_SIZE = 0.10
RANDOM_STATE = 42
def extract_label_from_path(image_path, dir_position=-2, separator="/"):
return image_path.split(separator)[dir_position]
def save_as_csv(images, labels, file_name):
df = pd.DataFrame({"image_path": images, "labels": labels})
csv_file_path = os.path.join(BASE_DIR, file_name)
df.to_csv(csv_file_path, index=False)
images = glob.glob(f"{BASE_DIR}/**/*.jpg")
# aug/Mild/aug-_0_3489125.jpg
labels = [extract_label_from_path(image_path) for image_path in images]
# test split
X_, X_test, y_, y_test = train_test_split(
images, labels, test_size=TEST_SIZE, random_state=RANDOM_STATE, stratify=labels
)
# valid split
X_train, X_val, y_train, y_val = train_test_split(
X_, y_, test_size=VAL_SIZE, random_state=RANDOM_STATE, stratify=y_
)
if __name__=="__main__":
#save to csvs
save_as_csv(X_train, y_train, "train_aug.csv")
save_as_csv(X_val, y_val, "val_aug.csv")
save_as_csv(X_test, y_test, "test_aug.csv")
print("CSVs files generated successfully.")
plt.hist(y_test)
plt.title("Test data distribution1")
plt.savefig("data/Test_data_distribution1.png")
plt.show() |
import { defineStore } from 'pinia';
import { getDefaultProject, getProjects, updateDefaultProject } from '@/http/service/uniauth';
export interface Project {
label: string;
value: string;
[propName: string]: any;
}
interface ProjectConfig {
// 默认项目
defaultProject: string;
// 项目列表
projects: Project[];
// 默认项目 id
defaultProjectId: string;
}
// 存储项目相关的 store
export const useProjectsStore = defineStore({
id: 'projectStore',
state: (): ProjectConfig => ({
defaultProject: '',
projects: [],
defaultProjectId: '',
}),
getters: {
getDefaultProject(): string {
return this.defaultProject;
},
getProjects(): any[] {
return this.projects;
},
getDefaultProjectId(): string {
return this.defaultProjectId;
},
},
actions: {
// 获取项目列表
getAllProjects() {
getProjects({ appName: 'default' }).then((res: any) => {
if (res.success) {
this.projects = res?.data?.map((p: Project) => ({
label: `${p?.projectId} ${p?.projectName}`,
value: p?.projectId,
}));
}
});
},
// 设置默认 projectId
async setDefaultProjectId() {
const projectId = (await getDefaultProject())?.data?.projectId || '';
console.log(projectId, 'projectId');
this.defaultProjectId = projectId;
},
// 更新默认 projectId
async updateDefaultProjectId(projectId: string) {
await updateDefaultProject({ projectId });
sessionStorage.setItem('projectId', projectId);
this.defaultProjectId = projectId;
},
},
}); |
# Audio Processor Application
#
# This file is part of the Audio Connector Getting Started repository.
# https://github.com/industrial-edge/audio-connector-getting-started
#
# MIT License
#
# Copyright (c) 2022 Siemens Aktiengesellschaft
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import json, time, datetime
import numpy as np
from paho.mqtt import client as mqttc
from pkg.configuration_manager import ConfigurationManager, MetadataManager
from pkg.audio_packing import unpack_payload, unpack_metadata
from pkg.conn_diagnostics import AudioStreamDiagnostics
APP_NAME = "AudioProcessor"
CONFIG_FILE = '/app/config/config.json'
CONFIG_DATA = {}
CONFIG_MANAGER = None
METADATA_MANAGER = None
DIAGNOSTICS_ENGINE = None
MQTT_CLIENT = mqttc.Client(client_id=APP_NAME)
#### define supporting mqtt client methods
def on_connect(client, userdata, flags, rc):
if rc == 0: # 0 = connection successful
print(f"{APP_NAME}::[DATABUS] connected to MQTT broker", flush=True)
client.connected_flag = True # set flag
# resubscribe to all the topics in case of disconnection
CONFIG_DATA = CONFIG_MANAGER.get_config_data() # make sure CONFIG_DATA is up to date
# subscribe to metadata, wait for first message
print(f'{APP_NAME}::[DATABUS] resubscribing to {CONFIG_DATA["databus"]["metadata_topic"]}', flush=True)
client.subscribe(CONFIG_DATA["databus"]["metadata_topic"], qos=CONFIG_DATA["databus"]["metadata_qos"])
if METADATA_MANAGER.current["streaming_topic"] != "":
# also subscribe to streaming topic
print(f'{APP_NAME}::[DATABUS] resubscribing to {METADATA_MANAGER.current["streaming_topic"]}', flush=True)
client.subscribe(METADATA_MANAGER.current["streaming_topic"], qos=CONFIG_DATA["databus"]["streaming_qos"])
def on_disconnect(client, userdata, rc):
print(f'{APP_NAME}::[DATABUS] on_disconnect() called', flush=True)
client.connected_flag = False
if rc != 0:
#ERROR: unexpected broker disconection. Try to reconnect. Stop only if config file changes
while True:
try:
client.reconnect()
return
except:
#ERROR:broker not available. Keep trying
continue
def on_message(client, userdata, msg):
# case 1: metadata message handling
if msg.topic==CONFIG_DATA["databus"]["metadata_topic"]:
# unpack metadata payload
meta_changed = METADATA_MANAGER.update_metadata_objects(unpack_metadata(msg.payload)) # update internal objects
# set connection from config; can only be done once we have parsed a metadata message (update_metadata_objects)
if METADATA_MANAGER.current["connection_name"] != CONFIG_DATA["connection_name"]:
METADATA_MANAGER.set_connection(CONFIG_DATA["connection_name"]) # this will also set the streaming_topic
if meta_changed:
print(f'{APP_NAME}::[METADATA] metadata changed at source, adapting...',flush=True)
if METADATA_MANAGER.previous["streaming_topic"] != "":
# unsubscribe from previous streaming topic
print(f'{APP_NAME}::[STREAMING] unsubscribing from: {METADATA_MANAGER.previous["streaming_topic"]}',flush=True)
client.unsubscribe(METADATA_MANAGER.previous["streaming_topic"])
# subscribe to new streaming topic
print(f'{APP_NAME}::[STREAMING] subscribing to: {METADATA_MANAGER.current["streaming_topic"]}',flush=True)
client.subscribe(METADATA_MANAGER.current["streaming_topic"], qos=CONFIG_DATA["databus"]["streaming_qos"])
# Update Diagnostics Engine if sampling_rate changed
if DIAGNOSTICS_ENGINE.data_sampling_rate != METADATA_MANAGER.current["sampling_rate"][0]:
DIAGNOSTICS_ENGINE.set_sampling_rate(METADATA_MANAGER.current["sampling_rate"][0])
DIAGNOSTICS_ENGINE.reset() # reset statistics
# case 2: stream payload handling
elif msg.topic==METADATA_MANAGER.current["streaming_topic"]:
# unpack payload
msg_array, msg_timestamp, msg_array_shape = unpack_payload(msg.payload)
# Update Diagnostics Engine if frame_size changed
if DIAGNOSTICS_ENGINE.packet_size != msg_array_shape[0]:
DIAGNOSTICS_ENGINE.set_packet_size(msg_array_shape[0])
DIAGNOSTICS_ENGINE.reset() # reset statistics
# Upload to Diagnostics Engine
decimal_index = msg_timestamp.find('.')
msg_ts = datetime.datetime.fromisoformat(msg_timestamp[:decimal_index+7]) # drop the 7th decimal place and/or the Z
DIAGNOSTICS_ENGINE.store_packet(json.loads(msg.payload),ts=msg_ts)
# analyze data frame and publish result
data_packet = {
"timestamp":msg_timestamp,
"connection_name":METADATA_MANAGER.current["connection_name"],
"streaming_topic":METADATA_MANAGER.current["streaming_topic"],
"result":_compute_rms(msg_array[:,:METADATA_MANAGER.current["num_chan"]]).tolist()
}
client.publish(CONFIG_DATA["databus"]["output_topic"], json.dumps(data_packet), qos=CONFIG_DATA["databus"]["output_qos"])
# otherwise: ignore all other topics
else:
return
def _compute_rms(buff,axis=0):
return np.sqrt(np.mean(np.power(buff,2.0),axis))
if __name__ == "__main__":
# load CONFIG_FILE if it exists
if os.path.isfile(CONFIG_FILE):
CONFIG_MANAGER = ConfigurationManager(CONFIG_FILE)
CONFIG_DATA = CONFIG_MANAGER.get_config_data()
METADATA_MANAGER = MetadataManager(CONFIG_MANAGER)
else:
time.sleep(10)
exit(1)
# configure MQTT client
MQTT_CLIENT.on_connect = on_connect
MQTT_CLIENT.on_disconnect = on_disconnect
MQTT_CLIENT.on_message = on_message
MQTT_CLIENT.username_pw_set(CONFIG_DATA["databus"]['databus_username'], CONFIG_DATA["databus"]['databus_password'])
# start subscription
MQTT_CLIENT.connect(CONFIG_DATA["databus"]['databus_host'])
MQTT_CLIENT.subscribe(CONFIG_DATA["databus"]["metadata_topic"], qos=CONFIG_DATA["databus"]["metadata_qos"])
if METADATA_MANAGER.current["streaming_topic"] != "":
MQTT_CLIENT.subscribe(METADATA_MANAGER.current["streaming_topic"], qos=CONFIG_DATA["databus"]["streaming_qos"])
print(f'{APP_NAME}::[DATABUS] MQTT client subscriptions created!', flush=True)
# Start Diagnostics Engine
DIAGNOSTICS_ENGINE = AudioStreamDiagnostics(name="DATABUS",interval=60,history=10,
samp_rate=METADATA_MANAGER.current["sampling_rate"][0])
DIAGNOSTICS_ENGINE.start_reporting()
# blocking call to hold the program here
MQTT_CLIENT.loop_forever() |
# Copyright (C) 2019 Greenbone Networks GmbH
# Text descriptions are largely excerpted from the referenced
# advisory, and are Copyright (C) the respective author(s)
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
if(description)
{
script_oid("1.3.6.1.4.1.25623.1.0.704510");
script_version("2019-09-06T10:56:37+0000");
script_cve_id("CVE-2019-11500");
script_tag(name:"cvss_base", value:"7.5");
script_tag(name:"cvss_base_vector", value:"AV:N/AC:L/Au:N/C:P/I:P/A:P");
script_tag(name:"last_modification", value:"2019-09-06 10:56:37 +0000 (Fri, 06 Sep 2019)");
script_tag(name:"creation_date", value:"2019-08-30 02:00:15 +0000 (Fri, 30 Aug 2019)");
script_name("Debian Security Advisory DSA 4510-1 (dovecot - security update)");
script_category(ACT_GATHER_INFO);
script_copyright("Copyright (C) 2019 Greenbone Networks GmbH");
script_family("Debian Local Security Checks");
script_dependencies("gather-package-list.nasl");
script_mandatory_keys("ssh/login/debian_linux", "ssh/login/packages", re:"ssh/login/release=DEB(9|10)");
script_xref(name:"URL", value:"https://www.debian.org/security/2019/dsa-4510.html");
script_xref(name:"URL", value:"https://security-tracker.debian.org/tracker/DSA-4510-1");
script_tag(name:"summary", value:"The remote host is missing an update for the 'dovecot'
package(s) announced via the DSA-4510-1 advisory.");
script_tag(name:"vuldetect", value:"Checks if a vulnerable package version is present on the target host.");
script_tag(name:"insight", value:"Nick Roessler and Rafi Rubin discovered that the IMAP and ManageSieve
protocol parsers in the Dovecot email server do not properly validate
input (both pre- and post-login). A remote attacker can take advantage
of this flaw to trigger out of bounds heap memory writes, leading to
information leaks or potentially the execution of arbitrary code.");
script_tag(name:"affected", value:"'dovecot' package(s) on Debian Linux.");
script_tag(name:"solution", value:"For the oldstable distribution (stretch), this problem has been fixed
in version 1:2.2.27-3+deb9u5.
For the stable distribution (buster), this problem has been fixed in
version 1:2.3.4.1-5+deb10u1.
We recommend that you upgrade your dovecot packages.");
script_tag(name:"solution_type", value:"VendorFix");
script_tag(name:"qod_type", value:"package");
exit(0);
}
include("revisions-lib.inc");
include("pkg-lib-deb.inc");
res = "";
report = "";
if(!isnull(res = isdpkgvuln(pkg:"dovecot-core", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-dbg", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-dev", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-gssapi", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-imapd", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-ldap", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-lmtpd", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-lucene", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-managesieved", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-mysql", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-pgsql", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-pop3d", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-sieve", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-solr", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-sqlite", ver:"1:2.2.27-3+deb9u5", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-auth-lua", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-core", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-dev", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-gssapi", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-imapd", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-ldap", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-lmtpd", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-lucene", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-managesieved", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-mysql", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-pgsql", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-pop3d", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-sieve", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-solr", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-sqlite", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"dovecot-submissiond", ver:"1:2.3.4.1-5+deb10u1", rls:"DEB10"))) {
report += res;
}
if(report != "") {
security_message(data:report);
} else if(__pkg_match) {
exit(99);
}
exit(0); |
import { Grid } from "@mui/material";
import { useState } from "react";
import { ItemCard } from "../item_card/ItemCard";
import "./ItemGrid.css";
export const ItemGrid = (props) => {
const [selected, setSelected] = useState(null);
const onSelect = (i) => {
if (selected !== i.id) {
setSelected(i.id);
if (props.hasOwnProperty("onSelectionChanged")) {
props.onSelectionChanged(i);
}
}
};
return (
<Grid container rowSpacing={{ xs: 1, sm: 2, md: 3 }} columnSpacing={{ xs: 1, sm: 2, md: 3 }} sx={{ display: "flex", justifyContent: "center" }}>
{props.itemData.map((i) => (
<Grid item onClick={() => onSelect(i)} className="item-grid-container">
<ItemCard item={i} selected={i.id === selected}></ItemCard>
</Grid>
))}
</Grid>
);
}; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dapp</title>
</head>
<body>
<div>
<input type="text" id="counter"/>
<button onclick="increment()">Increment</button>
<button onclick="getCounter()">Get Counter</button>
</div>
<script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"
type="application/javascript"></script>
<script>
const CONTRACT_ABI=[
{
"inputs": [
{
"internalType": "uint256",
"name": "_counter",
"type": "uint256"
}
],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [],
"name": "getCounter",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "increment",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
];
const CONTRACT_ADDRES='0x5A4275544cA64dBFd31Ca8DaeAF267e214dc9dEe';
let signer;
let contract;
const provider = new ethers.providers.Web3Provider(
window.ethereum,
"goerli"
)
provider.send("eth_requestAccounts",[]).then(()=>{
provider.listAccounts().then((accounts)=>{
signer =provider.getSigner(accounts[0])
contract=new ethers.Contract(
CONTRACT_ADDRES,
CONTRACT_ABI,
signer
);
})
})
async function increment(){
await contract.increment()
}
async function getCounter(){
const counter = await contract.getCounter();
document.getElementById('counter').value=counter;
}
</script>
</body>
</html> |
#ifndef BANKING_FUNCTIONS_H
#define BANKING_FUNCTIONS_H
#include <iostream>
#include <string>
#include <map>
// Structure to store account information
struct Account
{
double balance{};
};
// Structure to store customer information
struct Customer
{
std::string name{};
std::string address{};
std::string phone_number{};
std::map<int, Account> accounts{}; // Map to store multiple accounts
};
// Function to add money to an account
void addMoney(Customer &customer, int account_number);
// Function to withdraw money from an account
void withdrawMoney(Customer &customer, int account_number);
// Function to display the account balance
void seeAccountBalance(const Customer &customer, int account_number);
// Function to add a new customer
void addCustomer(std::map<int, Customer> &customers);
// Function to add a new account for a customer
void addAccount(std::map<int, Customer> &customers);
// Function to log in to a customer's account
void loginAccount(std::map<int, Customer> &customers);
#endif // BANKING_FUNCTIONS_H |
import React, { useRef, useState } from 'react'
import ReactDOM from "react-dom";
import './Routes.css';
import { PRIVILEGES } from "../../helpers/constants"
import { Link, useLocation } from 'react-router-dom';
import useAlert from '../../components/useAlert';
import useFetch from '../../components/useFetch';
import useDidUpdateEffect from '../../components/useDidUpdateEffect';
import Spinner from '../../components/Spinner/Spinner';
import useDelete from '../../components/useDelete';
import useDialog from '../../components/useDialog';
import useBundledTable from '../../components/useBundledTable';
const routeURL = `${process.env.REACT_APP_BACKEND_HOST}/API/route/get/all`;
const routeCountURL = `${process.env.REACT_APP_BACKEND_HOST}/API/route/get/all/count`;
const routeDeleteURL = `${process.env.REACT_APP_BACKEND_HOST}/API/route/delete/`;
const routeBulkDeleteURL = `${process.env.REACT_APP_BACKEND_HOST}/API/route/delete/bulk`;
const colData = [
{ "id": "RouteID", "name": "Route ID" },
{ "id": "RouteName", "name": "Route Name" }
];
const idKey = "RouteID";
const modalTitle = "Do you want to delete this route?";
const modalBody = "This row will be deleted in the database, do you want to proceed?";
function Routes({ priv }) {
// HOOKS DECLARATIONS AND VARIABLES
const location = useLocation();
const [routeData, setRouteData] = useState([]);
const [totalRoutes, setTotalRoutes] = useState(null);
const {
searchParamQuery,
entryProps,
entryProps: {
currentEntries
},
filterParam,
paginationProps,
paginationProps: {
currentRoute
},
filteringProps,
tableProps,
bulkDeleteProps,
bulkDeleteProps: {
deleteBulkData,
setCurrentDeleteRows
},
BundledTable
} = useBundledTable({ data: routeData, dataCount: totalRoutes, bulkDeleteUrl: routeBulkDeleteURL });
// to determine if initial fetch of data is done
const [deleteRoute, deleteRouteResult] = useDelete(routeDeleteURL);
const fetchDepsCount = [currentEntries, currentRoute, deleteRouteResult, deleteBulkData];
const fetchDepsRoutes = [deleteRouteResult, deleteBulkData];
const [dataCount, loadingCount] = useFetch(routeCountURL + `?${filterParam}`, { customDeps: fetchDepsCount });
const [dataRoutes, loadingRoutes] = useFetch(routeURL + searchParamQuery, { customDeps: fetchDepsRoutes });
const confirmDelete = useRef();
const {
handleShow,
handleClose,
show,
DialogElements
} = useDialog();
const {
timerSuccessAlert,
timerErrorAlert,
passErrorMsg,
AlertElements,
clearErrorMsg,
errorMsg,
successMsg,
errorTimerValue
} = useAlert({ showLocationMsg: true });
const isWriteable = priv === PRIVILEGES.readWrite;
// FUNCTIONS AND EVENT HANDLERS
const handleDelete = (routeId) => {
handleShow();
confirmDelete.current = () => {
deleteRoute(routeId);
setCurrentDeleteRows(prev => [...prev].filter(o => o !== routeId));
handleClose();
}
}
const checkFetchedData = async () => {
if (dataRoutes && dataCount) {
if (dataCount.status === true) {
let count = dataCount.data.count;
if (dataRoutes.status === true) {
ReactDOM.unstable_batchedUpdates(() => {
setTotalRoutes(count);
setRouteData(dataRoutes.data);
});
if (!errorTimerValue) {
clearErrorMsg();
}
} else {
// resets everything when fetched is error
ReactDOM.unstable_batchedUpdates(() => {
setTotalRoutes(null);
setRouteData([]);
});
passErrorMsg(`${dataRoutes.msg}`);
}
} else {
passErrorMsg(`${dataCount.msg}`);
}
}
}
// LIFECYCLES
useDidUpdateEffect(() => {
checkFetchedData();
}, [dataRoutes, dataCount]);
useDidUpdateEffect(() => {
if (deleteRouteResult.status) {
timerSuccessAlert([deleteRouteResult.msg]);
} else {
timerErrorAlert([deleteRouteResult.msg]);
}
}, [deleteRouteResult]);
useDidUpdateEffect(() => {
if (deleteBulkData.status) {
timerSuccessAlert([deleteBulkData.msg]);
} else {
timerErrorAlert([deleteBulkData.msg]);
}
}, [deleteBulkData]);
// UI
const actionButtons = (routeID) => {
return (
<>
<Link to={`/routes/form/${routeID}${location.search}`} className="btn btn-icon-text btn-outline-secondary mr-3">
{isWriteable ? "Edit" : "Read"} Route
<i className={`mdi ${isWriteable ? "mdi-pencil" : "mdi-read"} btn-icon-append `}></i>
</Link>
{isWriteable && <button onClick={() => handleDelete(routeID)} className="btn btn-icon-text btn-outline-secondary mr-3">
Delete
<i className={`mdi mdi-delete btn-icon-append `}></i>
</button>}
</>
)
};
const addButtons = () => {
return (
<>
{isWriteable &&
<>
<Link to={`/routes/form/add${location.search}`} className="btn btn-outline-secondary float-sm-right d-block">
<i className="mdi mdi-account-plus"> </i>
Add Route
</Link>
</>
}
</>
)
}
return (
<>
<div>
<div className="page-header">
<h3 className="page-title"> Routes</h3>
</div>
<AlertElements errorMsg={errorMsg} successMsg={successMsg} />
<div className="row" data-testid="Route" >
<div className="col-lg-12 grid-margin stretch-card">
<div className="card">
<div className="card-body">
<h4 className="card-title"> Route Table </h4>
{(!!loadingRoutes || !!loadingCount) && <Spinner />}
<BundledTable
tableProps={tableProps}
entryProps={entryProps}
paginationProps={paginationProps}
colData={colData}
idKey={idKey}
actionButtons={actionButtons}
addButtons={addButtons}
filteringProps={filteringProps}
bulkDeleteProps={bulkDeleteProps}
/>
</div>
</div>
</div>
</div>
</div>
<DialogElements show={show} handleClose={handleClose} handleDelete={confirmDelete.current} modalTitle={modalTitle} modalBody={modalBody} />
</>
);
}
export default Routes; |
import { Contract } from 'ethers';
import { Deployment } from 'hardhat-deploy/types';
import { HardhatRuntimeEnvironment } from 'hardhat/types';
import { ethers } from 'hardhat';
import fs from 'fs';
import path from 'path';
/**
* This deployment file will help to check for changes and set the address of the new contract
*/
module.exports = async ({ getNamedAccounts, deployments, getChainId, network }: HardhatRuntimeEnvironment) => {
const { deploy, execute, read } = deployments;
const { deployer } = await getNamedAccounts();
console.log('Deployer: ', deployer);
const chainId = await getChainId();
let networkName = network.name.replace('_', '-');
if (networkName == 'hardhat') {
networkName = 'localhost';
}
console.log(network.name);
let bluebirdFactory: Deployment | null;
let bluebirdGrinder: Deployment | null;
let bluebirdManager: Deployment | null;
let BBYC: Deployment | null;
let azuki: Deployment | null;
bluebirdFactory = await deployments.getOrNull('BluebirdFactory');
bluebirdGrinder = await deployments.getOrNull('BluebirdGrinder');
bluebirdManager = await deployments.getOrNull('BluebirdManager');
BBYC = await deployments.getOrNull('BBYC');
azuki = await deployments.getOrNull('Azuki');
function getAddress(contract: Deployment | Contract | null) {
if (contract) {
return contract.address;
}
return '';
}
function getBlockNumber(contract: Deployment | Contract | null) {
if (contract) {
if (contract.receipt) return contract.receipt.blockNumber;
}
return '';
}
const entries = [
{
name: 'BluebirdGrinder.address',
value: getAddress(bluebirdGrinder),
blockNumber: getBlockNumber(bluebirdGrinder),
},
{
name: 'BluebirdManager.address',
value: getAddress(bluebirdManager),
blockNumber: getBlockNumber(bluebirdManager),
},
{ name: 'BBYC.address', value: getAddress(BBYC), blockNumber: getBlockNumber(BBYC) },
{ name: 'Azuki.address', value: getAddress(azuki), blockNumber: getBlockNumber(azuki) },
];
console.table(entries);
// Export Addresses and block numbers
const addressAndBlockNumbers = {
bluebird_grinder_address: getAddress(bluebirdGrinder),
bluebird_grinder_start_block: getBlockNumber(bluebirdGrinder),
bluebird_manager_address: getAddress(bluebirdManager),
bluebird_manager_start_block: getBlockNumber(bluebirdManager),
bbyc_address: getAddress(BBYC),
bbyc_start_block: getBlockNumber(BBYC),
azuki_address: getAddress(azuki),
azuki_start_block: getBlockNumber(azuki),
};
// Read config file from subgraph/packages/config
const config = JSON.parse(
fs.readFileSync(
path.join(__dirname, '..', '..', 'subgraph', 'packages', 'config', 'src', `${networkName}.json`),
'utf8'
)
);
const atlantisConfig = {
...config,
...addressAndBlockNumbers,
};
fs.writeFileSync(
path.join(__dirname, '..', '..', 'subgraph', 'packages', 'config', 'src', `${networkName}.json`),
JSON.stringify(atlantisConfig, null, 2)
);
};
module.exports.tags = ['Setter','All']; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.