text
stringlengths 184
4.48M
|
---|
function uniquePaths(m: number, n: number): number {
// 定义 dp[i][j] 是 i,j 位置时的路径总数
let dp: number[][] = new Array(m + 1).fill(0);
for (let i = 0; i < dp.length; i++) {
dp[i] = new Array(n + 1).fill(0);
}
// base case
for (let i = 0; i < m; i++) {
dp[i][0] = 1;
}
for (let j = 0; j < n; j++) {
dp[0][j] = 1;
}
// 找关系
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
};
|
process.stdin.setEncoding('utf8');
process.stdin.on('data', (data) => {
// 입력받은 숫자를 data에 받는다.
const n = data.split(' '); //data(입력받은 숫자)를 배열로 변경
const a = Number(n[0]),
b = Number(n[1]); //a는 한줄에 대한 별의 갯수, b는 몇줄 출력
for (let i = 0; i < b; i++) {
//i선언 몇줄(b)만큼 반복
let str = ''; // 출력할 변수 선언
for (let j = 0; j < a; j++) {
// j선언 후 별을 한 줄에 몇개 찍을지 반복
str = str + '*';
}
console.log(str);
}
});
//a 는 5, b는 3
//추천 코드
//핵심 메소드 repeat()
process.stdin.setEncoding('utf8');
process.stdin.on('data', (data) => {
const n = data.split(' ');
const a = Number(n[0]),
b = Number(n[1]);
const row = '*'.repeat(a);
for (let i = 0; i < b; i++) {
console.log(row);
}
});
|
import os
import os.path as osp
import torch
import cv2
import json
import time
import numpy as np
from torch.autograd import Variable
import torch.nn.functional as F
from torch import nn
import mmcv
from mmcv.runner import get_dist_info
from mmcv.engine import collect_results_cpu
import tqdm
from mmseg.datasets.tools.vis_apollosim import LaneVis
def postprocess(output, anchor_len=10):
proposals = output[0]
logits = F.softmax(proposals[:, 5 + 3 * anchor_len:], dim=1)
score = 1 - logits[:, 0]
proposals[:, 5 + 3 * anchor_len:] = logits # [N, 2]
proposals[:, 1] = score
results = {'proposals_list': proposals.cpu().numpy()}
return results # [1, 7, 16]
def test_apollosim(model,
data_loader,
eval=True,
show=False,
out_dir=None,
**kwargs):
"""Test with single GPU by progressive mode.
Args:
model (nn.Module): Model to be tested.
data_loader (utils.data.Dataloader): Pytorch data loader.
show (bool): Whether show results during inference. Default: False.
eval (bool): Whether evaluate results. Defalut: True.
out_dir (str, optional): If specified, the results will be dumped into
the directory to save output results.
"""
# when none of them is set true, return segmentation results as
# a list of np.array.
model.eval()
results = []
dataset = data_loader.dataset
loader_indices = data_loader.batch_sampler
pred_file = osp.join(out_dir, 'lane3d_prediction.json')
print("testing model...")
for batch_indices, data in tqdm.tqdm(zip(loader_indices, data_loader)):
with torch.no_grad():
outputs = model(return_loss=False, **data)
for output in outputs['proposals_list']:
result = postprocess(output, anchor_len=dataset.anchor_len)
results.append(result) # [7, 16]
dataset.format_results(results, pred_file)
# evaluating
if eval:
print("evaluating results...")
test_result = dataset.eval(pred_file)
json_result = {}
json_result['AP'] = test_result['AP']
json_result['F_score'] = test_result['F_score']
json_result['x_error_close'] = test_result['x_error_close']
json_result['x_error_far'] = test_result['x_error_far']
json_result['z_error_close'] = test_result['z_error_close']
json_result['z_error_far'] = test_result['z_error_far']
print('F-score:', test_result['F_score'])
print('AP:', test_result['AP'])
print("x error close / far:", test_result['x_error_close'], test_result['x_error_far'])
print("z error close / far:", test_result['z_error_close'], test_result['z_error_far'])
print("save test result to", osp.join(out_dir, 'evaluation_result.json'))
with open(osp.join(out_dir, 'evaluation_result.json'), 'w') as f:
json.dump(test_result, f)
# visualizing
if show:
save_dir = osp.join(out_dir, 'vis')
mmcv.mkdir_or_exist(save_dir)
print("visualizing results at", save_dir)
visualizer = LaneVis(dataset)
visualizer.visualize(pred_file, gt_file = dataset.eval_file, img_dir = dataset.data_root,
save_dir = save_dir, prob_th=model.module.test_cfg.test_conf)
def test_apollosim_multigpu(model,
data_loader,
eval=True,
show=False,
out_dir=None,
**kwargs):
"""Test with single GPU by progressive mode.
Args:
model (nn.Module): Model to be tested.
data_loader (utils.data.Dataloader): Pytorch data loader.
show (bool): Whether show results during inference. Default: False.
eval (bool): Whether evaluate results. Defalut: True.
out_dir (str, optional): If specified, the results will be dumped into
the directory to save output results.
"""
# when none of them is set true, return segmentation results as
# a list of np.array.
rank, world_size = get_dist_info()
tmpdir = os.path.join(out_dir, 'tmp')
model.eval()
results = []
dataset = data_loader.dataset
loader_indices = data_loader.batch_sampler
pred_file = osp.join(out_dir, 'lane3d_prediction.json')
print("testing model...")
if rank == 0:
prog_bar = mmcv.ProgressBar(len(dataset))
for batch_indices, data in tqdm.tqdm(zip(loader_indices, data_loader)):
with torch.no_grad():
outputs = model(return_loss=False, **data)
for output in outputs['proposals_list']:
result = postprocess(output, anchor_len=dataset.anchor_len)
results.append(result) # [7, 16]
if rank == 0:
batch_size = len(result) * world_size
for _ in range(batch_size):
prog_bar.update()
results = collect_results_cpu(results, len(dataset), tmpdir)
if rank == 0:
dataset.format_results(results, pred_file)
else:
return
# evaluating
if eval:
print("evaluating results...")
test_result = dataset.eval(pred_file)
json_result = {}
json_result['AP'] = test_result['AP']
json_result['F_score'] = test_result['F_score']
json_result['x_error_close'] = test_result['x_error_close']
json_result['x_error_far'] = test_result['x_error_far']
json_result['z_error_close'] = test_result['z_error_close']
json_result['z_error_far'] = test_result['z_error_far']
print('F-score:', test_result['F_score'])
print('AP:', test_result['AP'])
print("x error close / far:", test_result['x_error_close'], test_result['x_error_far'])
print("z error close / far:", test_result['z_error_close'], test_result['z_error_far'])
print("save test result to", osp.join(out_dir, 'evaluation_result.json'))
with open(osp.join(out_dir, 'evaluation_result.json'), 'w') as f:
json.dump(test_result, f)
# visualizing
if show:
save_dir = osp.join(out_dir, 'vis')
mmcv.mkdir_or_exist(save_dir)
print("visualizing results at", save_dir)
visualizer = LaneVis(dataset)
visualizer.visualize(pred_file, gt_file = dataset.eval_file, img_dir = dataset.data_root,
save_dir = save_dir, prob_th=model.module.test_cfg.test_conf)
|
// Licensed under the Open Software License version 3.0
use super::config::PassiveEndpointConfig;
use crate::{nut::sender::UninterruptiblePowerSupplyData, one_wire::sender::MeasuredTemperature};
use rocket::{get, http::Status, routes, serde::json::Json, Build, Rocket, State};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, sync::Arc};
use tokio::sync::{broadcast, RwLock};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
struct ApiToken<'a>(&'a str);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
struct ApiResponse<T> {
success: bool,
error: Option<String>,
data: Option<T>,
}
impl<T> ApiResponse<T> {
fn new(data: Option<T>) -> Self {
// If data is None, error is "not found"
let error = match data.is_none() {
true => Some(String::from("not found")),
false => None,
};
Self {
success: error.is_none(),
error,
data,
}
}
}
#[derive(Debug, Clone, Default)]
struct CachedData {
// By category
temperature_sensors: Arc<RwLock<Vec<MeasuredTemperature>>>,
upses: Arc<RwLock<Vec<UninterruptiblePowerSupplyData>>>,
// By category + hw.id
temperature_sensors_by_hw_id: Arc<RwLock<HashMap<String, MeasuredTemperature>>>,
upses_by_hw_id: Arc<RwLock<HashMap<String, UninterruptiblePowerSupplyData>>>,
}
impl CachedData {
pub async fn get_temperature_sensors(&self) -> Vec<MeasuredTemperature> {
self.temperature_sensors.read().await.clone()
}
pub async fn get_temperature_sensor_by_hw_id(&self, id: String) -> Option<MeasuredTemperature> {
self.temperature_sensors_by_hw_id
.read()
.await
.get(&id)
.cloned()
}
pub async fn set_sensors(&self, sensors: Vec<MeasuredTemperature>) {
*self.temperature_sensors.write().await = sensors.clone();
let hash_map = &mut self.temperature_sensors_by_hw_id.write().await;
hash_map.clear();
for sensor in sensors {
hash_map.insert(sensor.meta.hw.id.clone(), sensor);
}
}
pub async fn get_upses(&self) -> Vec<UninterruptiblePowerSupplyData> {
self.upses.read().await.clone()
}
pub async fn get_ups_by_hw_id(&self, id: String) -> Option<UninterruptiblePowerSupplyData> {
self.upses_by_hw_id.read().await.get(&id).cloned()
}
pub async fn set_upses(&self, upses: Vec<UninterruptiblePowerSupplyData>) {
*self.upses.write().await = upses.clone();
let mut hash_map = self.upses_by_hw_id.write().await;
hash_map.clear();
for ups in upses {
hash_map.insert(ups.meta.hw.id.clone(), ups);
}
}
}
async fn start_cache_updater_loop(
mut shutdown_rx: broadcast::Receiver<()>,
cache: Arc<CachedData>,
mut one_wire_rx: broadcast::Receiver<Vec<MeasuredTemperature>>,
mut ups_monitoring_rx: broadcast::Receiver<Vec<UninterruptiblePowerSupplyData>>,
) {
loop {
tokio::select! {
Ok(value) = one_wire_rx.recv() => {
tracing::trace!("{:?}", value);
cache.set_sensors(value).await;
}
Ok(value) = ups_monitoring_rx.recv() => {
tracing::trace!("{:?}", value);
cache.set_upses(value).await;
}
_ = shutdown_rx.recv() => {
tracing::trace!("Shutting down cache updater loop");
break;
}
}
}
}
#[get("/temperature")]
async fn get_temperature_sensors_route(
cache: &State<Arc<CachedData>>,
) -> Json<ApiResponse<Vec<MeasuredTemperature>>> {
Json(ApiResponse::new(Some(
cache.get_temperature_sensors().await,
)))
}
#[get("/temperature/<id>")]
async fn get_temperature_sensor_by_hw_id_route(
cache: &State<Arc<CachedData>>,
id: String,
) -> (Status, Json<ApiResponse<MeasuredTemperature>>) {
let data = cache.get_temperature_sensor_by_hw_id(id).await;
let data = ApiResponse::new(data);
if !data.success {
return (Status::NotFound, Json(data));
}
(Status::Ok, Json(data))
}
#[get("/ups")]
async fn get_upses_route(
cache: &State<Arc<CachedData>>,
) -> Json<ApiResponse<Vec<UninterruptiblePowerSupplyData>>> {
Json(ApiResponse::new(Some(cache.get_upses().await)))
}
#[get("/ups/<id>")]
async fn get_ups_by_hw_id_route(
cache: &State<Arc<CachedData>>,
id: String,
) -> (Status, Json<ApiResponse<UninterruptiblePowerSupplyData>>) {
let data = cache.get_ups_by_hw_id(id).await;
let data = ApiResponse::new(data);
if !data.success {
return (Status::NotFound, Json(data));
}
(Status::Ok, Json(data))
}
fn rocket(cache: Arc<CachedData>) -> Rocket<Build> {
rocket::build().manage(cache).mount(
"/",
routes![
get_temperature_sensors_route,
get_temperature_sensor_by_hw_id_route,
get_upses_route,
get_ups_by_hw_id_route
],
)
}
pub async fn start_passive_endpoint_loop(
shutdown_rx: broadcast::Receiver<()>,
config: PassiveEndpointConfig,
one_wire_rx: broadcast::Receiver<Vec<MeasuredTemperature>>,
ups_monitoring_rx: broadcast::Receiver<Vec<UninterruptiblePowerSupplyData>>,
) {
// Check if module is enabled
if !config.is_enabled() {
tracing::trace!("Module is disabled");
return;
}
let cache = Arc::new(CachedData::default());
// Simple API that returns cached data as JSON
tracing::trace!("Starting passive endpoint loop");
let mut shutdown_rx_clone = shutdown_rx.resubscribe();
let cache_arc_clone: Arc<CachedData> = cache.clone();
let rocket_handle = tokio::spawn(async move {
let prepared_rocket = rocket(cache_arc_clone)
.configure(rocket::Config {
port: config.get_port(),
shutdown: rocket::config::Shutdown {
ctrlc: false,
..Default::default()
},
..Default::default()
})
.launch();
tokio::select! {
_ = prepared_rocket => {},
_ = shutdown_rx_clone.recv() => {
tracing::trace!("Aborting rocket");
}
}
});
// Cache updater
let cache_updater_handle = tokio::spawn(async move {
start_cache_updater_loop(shutdown_rx, cache, one_wire_rx, ups_monitoring_rx).await;
});
let _ = tokio::try_join!(rocket_handle, cache_updater_handle);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::types::Example;
use rocket::{
http::{ContentType, Status},
local::asynchronous::Client,
uri,
};
#[tokio::test]
async fn test_get_sensors_empty_cache() {
let cache = Arc::new(CachedData::default());
let client = Client::tracked(rocket(cache.clone())).await.unwrap();
let response = client
.get(uri!(super::get_temperature_sensors_route))
.dispatch()
.await;
// Basic checks
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::JSON));
// Inspect JSON response
let response = response.into_string().await.unwrap();
let response: ApiResponse<Vec<MeasuredTemperature>> =
serde_json::from_str(&response).unwrap();
assert!(response.success);
assert!(response.error.is_none());
assert_eq!(response.data.unwrap(), vec![]);
}
#[tokio::test]
async fn test_get_sensors_with_updated_data() {
let cache = Arc::new(CachedData::default());
let client = Client::tracked(rocket(cache.clone())).await.unwrap();
let response = client
.get(uri!(super::get_temperature_sensors_route))
.dispatch()
.await;
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::JSON));
let sensors = vec![MeasuredTemperature::example()];
cache.set_sensors(sensors.clone()).await;
let response = client
.get(uri!(super::get_temperature_sensors_route))
.dispatch()
.await;
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::JSON));
let response = response.into_string().await.unwrap();
let response: ApiResponse<Vec<MeasuredTemperature>> =
serde_json::from_str(&response).unwrap();
assert!(response.success);
assert!(response.error.is_none());
assert_eq!(response.data.unwrap(), sensors);
}
#[tokio::test]
async fn test_get_sensor_by_hw_id() {
let cache = Arc::new(CachedData::default());
let client = Client::tracked(rocket(cache.clone())).await.unwrap();
let sensors = vec![MeasuredTemperature::example()];
cache.set_sensors(sensors.clone()).await;
let response = client
.get(uri!(super::get_temperature_sensor_by_hw_id_route(
sensors[0].meta.hw.id.clone()
)))
.dispatch()
.await;
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::JSON));
let response = response.into_string().await.unwrap();
let response: ApiResponse<MeasuredTemperature> = serde_json::from_str(&response).unwrap();
assert!(response.success);
assert!(response.error.is_none());
assert!(response.data.is_some());
assert_eq!(response.data.unwrap(), sensors[0]);
}
#[tokio::test]
async fn test_get_sensor_by_hw_id_404() {
let cache = Arc::new(CachedData::default());
let client = Client::tracked(rocket(cache)).await.unwrap();
let response = client
.get(uri!(super::get_temperature_sensor_by_hw_id_route(
String::from("non-existent-id")
)))
.dispatch()
.await;
assert_eq!(response.status(), Status::NotFound);
assert_eq!(response.content_type(), Some(ContentType::JSON));
let response = response.into_string().await.unwrap();
let response: ApiResponse<MeasuredTemperature> = serde_json::from_str(&response).unwrap();
assert!(!response.success);
assert!(response.error.is_some());
assert!(response.data.is_none());
}
#[tokio::test]
async fn test_get_upses_empty_cache() {
let cache = Arc::new(CachedData::default());
let client = Client::tracked(rocket(cache.clone())).await.unwrap();
let response = client.get(uri!(super::get_upses_route)).dispatch().await;
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::JSON));
let response = response.into_string().await.unwrap();
let response: ApiResponse<Vec<UninterruptiblePowerSupplyData>> =
serde_json::from_str(&response).unwrap();
assert!(response.success);
assert!(response.error.is_none());
assert_eq!(response.data.unwrap(), vec![]);
}
#[tokio::test]
async fn test_get_upses_with_updated_data() {
let cache = Arc::new(CachedData::default());
let client = Client::tracked(rocket(cache.clone())).await.unwrap();
let response = client.get(uri!(super::get_upses_route)).dispatch().await;
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::JSON));
let upses = vec![UninterruptiblePowerSupplyData::example()];
cache.set_upses(upses.clone()).await;
let response = client.get(uri!(super::get_upses_route)).dispatch().await;
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::JSON));
let response = response.into_string().await.unwrap();
let response: ApiResponse<Vec<UninterruptiblePowerSupplyData>> =
serde_json::from_str(&response).unwrap();
assert!(response.success);
assert!(response.error.is_none());
assert_eq!(response.data.unwrap(), upses);
}
#[tokio::test]
async fn test_get_ups_by_hw_id() {
let cache = Arc::new(CachedData::default());
let client = Client::tracked(rocket(cache.clone())).await.unwrap();
let upses = vec![UninterruptiblePowerSupplyData::example()];
cache.set_upses(upses.clone()).await;
let response = client
.get(uri!(super::get_ups_by_hw_id_route(
upses[0].meta.hw.id.clone(),
)))
.dispatch()
.await;
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::JSON));
let response = response.into_string().await.unwrap();
let response: ApiResponse<UninterruptiblePowerSupplyData> =
serde_json::from_str(&response).unwrap();
assert!(response.success);
assert!(response.error.is_none());
assert!(response.data.is_some());
assert_eq!(response.data.unwrap(), upses[0]);
}
#[tokio::test]
async fn test_get_ups_by_hw_id_404() {
let cache = Arc::new(CachedData::default());
let client = Client::tracked(rocket(cache)).await.unwrap();
let response = client
.get(uri!(super::get_ups_by_hw_id_route(String::from(
"non-existent-id"
))))
.dispatch()
.await;
assert_eq!(response.status(), Status::NotFound);
assert_eq!(response.content_type(), Some(ContentType::JSON));
let response = response.into_string().await.unwrap();
let response: ApiResponse<UninterruptiblePowerSupplyData> =
serde_json::from_str(&response).unwrap();
assert!(!response.success);
assert!(response.error.is_some());
assert!(response.data.is_none());
}
}
|
<h3 id="handouts-of-workflow-charts-are-available-for-the-qiime-workflow-discussed-in-these-tutorials">Handouts of workflow charts are available for the QIIME workflow discussed in these tutorials:</h3>
<ul>
<li><a href="https://github.com/edamame-course/docs/tree/gh-pages/extra/Handouts/QIIMEFlowChart_IlluminaPairedEnds_13aug2014.pdf?raw=true">Paired-End Illumina</a></li>
<li><a href="https://github.com/edamame-course/docs/tree/gh-pages/extra/Handouts/QIIMEFlowChart_454_13aug2014.pdf?raw=true">454</a></li>
</ul>
<h2 id="getting-started">Getting started</h2>
<p>Make a new directory <code>mkdir</code> in which to put all of your QIIME-related analyses for today and tomorrow, and then ‘cd’ to move into that directory. Execute all commands from within this directory.</p>
<p><code>
mkdir QIIMETutorial
</code></p>
<p><code>
cd QIIMETutorial
</code></p>
<h2 id="assembling-illumina-paired-end-sequences">Assembling Illumina paired-end sequences</h2>
<h3 id="download-schloss-mouse-data">1.1 Download Schloss mouse data</h3>
<p>These data are 16S rRRNA V4 amplicons sequenced with MiSeq technology: </p>
<p><em>If you are a Mac user</em>, about half-way down the page, click on <a href="http://www.mothur.org/wiki/MiSeq_SOP">Example data from Schloss lab - http://www.mothur.org/wiki/MiSeq_SOP</a>. </p>
<p><img src="https://github.com/edamame-course/docs/raw/gh-pages/img/QIIMETutorial1_IMG/IMG_01.jpg" alt="img1" />.</p>
<p>Unzip (the directory with the data will be called MiSeq_SOP) and move it into the “QIIMETutorial” directory. </p>
<p><em>If you are on the EC2 or the QIIME Virtual Box</em>, download the Schloss data from the terminal, using <code>wget</code> : </p>
<p><code>
wget http://www.mothur.org/w/images/d/d6/MiSeqSOPData.zip
</code></p>
<p><code>
unzip MiSeqSOPData.zip
</code></p>
<p>This will make the directory “MISeq_SOP.” Move this into the QIIMETutorial directory.</p>
<h3 id="use-mkdir-to-create-a-new-directory-called-pandaseqmergedreads">1.2 Use <code>mkdir</code> to create a new directory called “pandaseq_merged_reads”</h3>
<p><code>
mkdir pandaseq_merged_reads
</code></p>
<h3 id="join-paired-end-illumina-reads-with-pandaseq">1.3 Join paired end Illumina reads with PANDAseq**</h3>
<p><code>
pandaseq -f MiSeq_SOP/F3D0_S188_L001_R1_001.fastq -r MiSeq_SOP/F3D0_S188_L001_R2_001.fastq -w pandaseq_merged_reads/F3D0_S188.fasta -g pandaseq_merged_reads/F3D0_S188.log -L 255 -t 0.90
</code>
Let’s look carefully at the anatomy of this command.</p>
<ul>
<li><code>pandaseq</code> calls the package of pandaseq scripts.</li>
<li><code>-f MiSeq_SOP/F3D0_S188_L001_R1_001.fastq</code> tells the script where to find the forward read.</li>
<li><code>-r</code> tells the script where to find its matching reverse read.</li>
<li><code>-w pandaseq_merged_reads/F3D0_S188.fasta</code> directs the script to make a new fasta file of the assembled reads and to put it in the “pandaseq_merged_reads” directory.</li>
<li><code>-g pandaseq_merged_reads/F3D0_S188.log</code> Selects an option of creating a log file.</li>
<li><code>-L</code> specifies the maximum length of the assembled reads, which, in truth, should be 251 bp. This is a very important option to specify, otherwise PANDAseq will assemble a lot of crazy-long sequences.</li>
</ul>
<p>All of the above information, and more options, are fully described in the <a href="http://neufeldserver.uwaterloo.ca/~apmasell/pandaseq_man1.html">PANDAseq Manual.</a>. The log file includes details as to how well the merging went.</p>
<h3 id="sanity-check-1-and-file-inspection">1.4 Sanity check #1 and file inspection.</h3>
<p>There are some questions you may be having: What does pandaseq return? Are there primers/barcodes on the assembled reads? Are these automatically trimmed?</p>
<p>It turns out, that PANDAseq, by default, removes primers and barcodes (There are also options to keep primers, please see the manual link above). Given that we used the default pandaseq options, how do we check to make sure that what we expect to happen actually did happen?</p>
<p>We know the V4 forward primer sequence that the Schloss lab used because these sequences are provided in Kozich et al. 2013.</p>
<p>Here is the V4 primer sequence : GTCCAGCMGCCGCGGTAA</p>
<p>We can search for that sequence in the assembled sequence file, using the <code>grep</code> function. </p>
<p><code>
cd pandaseq_merged_reads
</code></p>
<p><code>
head F3D0_S188.fasta
</code></p>
<p><img src="https://github.com/edamame-course/docs/raw/gh-pages/img/QIIMETutorial1_IMG/IMG_02.jpg" alt="img2" /> </p>
<p><code>
grep GTCCAGCMGCCGCGGTAA F3D0_S188.fasta
</code></p>
<p>When you execute the above command, the terminal does not return anything. This means that the primer sequence was not found in the file, suggesting that PANDAseq did, in fact, trim them.</p>
<p>We can double check our sanity by using a positive control. Let’s use <code>grep</code> to find a character string that we know is there, for instance the “M00967” string identifying the first sequence.</p>
<p><code>
grep M00967 F3D0_S188.fasta
</code></p>
<p>Whoa! That is hard to read all of those lines. Let’s put the results into a list by appending <code>> list.txt</code> to the command. The “>” symbol means to output the results to a new file, which is specified next. </p>
<p><code>
grep M00967 F3D0_S188.fasta > list.txt
</code></p>
<p>This creates a new file called “list.txt”, in which all instances of the character string “M00967” are provided. Let’s look at the head.</p>
<p><code>
head list.txt
</code></p>
<p><img src="https://github.com/edamame-course/docs/raw/gh-pages/img/QIIMETutorial1_IMG/IMG_03.jpg" alt="img3" /> </p>
<p>Our positive control worked, and we should be convinced and joyous that we executed <code>grep</code> correctly AND that the primers were trimmed by PANDAseq. We can now remove the list file.</p>
<p><code>
rm list.txt
</code></p>
<h3 id="automate-paired-end-merging-with-a-shell-script">1.5 Automate paired-end merging with a shell script.</h3>
<p>We would have to execute an iteration of the PANDAseq command for every pair of reads that need to be assembled. This could take a long time. So, we’ll use a shell script to automate the task. </p>
<p>Download this <a href="https://github.com/edamame-course/docs/raw/gh-pages/misc/QIIMETutorial_Misc/SchlossSampleNames.txt">list</a> (<em>VB/EC2 users</em>, use <code>wget</code>) of all the unique sample names and move it to your QIIMETutorial directory. </p>
<p>Then, download this shell <a href="https://github.com/edamame-course/docs/raw/gh-pages/misc/QIIMETutorial_Misc/pandaseq_merge.sh">script</a> (<em>VB/EC2 users</em>, use <code>wget</code>) and move it to your QIIMETutorial directory. </p>
<p>Change permissions on the script</p>
<p><code>
chmod +x pandaseq_merge.sh
</code></p>
<p>Execute the script from the QIIMETutorial Directory.</p>
<p><code>
./pandaseq_merge.sh
</code></p>
<h3 id="sanity-check-2">1.6 Sanity check #2.</h3>
<p>How many files were we expecting from the assembly? There were 19 pairs to be assembled, and we are generating one assembled fasta and one log for each. Thus, the pandaseq_merged_reads directory should contain 38 files. We use the <code>wc</code> command to check the number of files in the directory.</p>
<p><code>
ls -1 pandaseq_merged_reads | wc -l
</code></p>
<p>The terminal should return the number “38.” Congratulations, you lucky duck! You’ve assembled paired-end reads! </p>
<p><img src="https://github.com/edamame-course/docs/raw/gh-pages/img/QIIMETutorial1_IMG/IMG_04.jpg" alt="img4" /> </p>
<h2 id="moving-assembled-reads-into-the-qiime-environment">Moving assembled reads into the QIIME environment</h2>
<p>While working through the tutorial, open your web browser and navigate to this <a href="http://www.qiime.org/scripts/index.html">page</a>. It provides an index of qiime scripts and options. We will be using the default for most of the time, but for each script, it is useful to open its documentation and assess the alternative options.</p>
<h3 id="understanding-the-qiime-mapping-file">2.1 Understanding the QIIME mapping file.</h3>
<p>QIIME requires a <a href="http://qiime.org/documentation/file_formats.html">mapping file</a> for most analyses. This file is important because it links the sample IDs with their metadata (and, with their primers/barcodes if using QIIME for quality-control). Because we are super-amazing, we’ve already created a mapping file for the Schloss data for you. <a href="https://github.com/edamame-course/docs/raw/gh-pages/misc/QIIMETutorial_Misc/Schloss_Map.txt">Download it</a> (<em>VB/EC2</em> users, use <code>wget</code>), and move it to your QIIMETutorial directory.</p>
<p>Let’s spend few moments getting to know the mapping file:</p>
<p><code>
more Schloss_Map.txt
</code></p>
<p><img src="https://github.com/edamame-course/docs/raw/gh-pages/img/QIIMETutorial1_IMG/IMG_05.jpg" alt="img5" /> </p>
<p>A clear and comprehensive mapping file should contain all of the information that will be used in downstream analyses. The mapping file includes both categorical (qualitative) and numeric (quantitative) contextual information about a sample. This could include, for example, information about the subject (sex, weight), the experimental treatment, time or spatial location, and all other measured variables (e.g., pH, oxygen, glucose levels). Creating a clear mapping file will provide direction as to appropriate analyses needed to test hypotheses. Basically, all information for all anticipated analyses should be in the mapping file.</p>
<p><em>Hint</em>: Mapping files are also a great way to organize all of the data for posterity in the research group. New lab members interested in repeating the analysis should have all of the required information in the mapping file. PIs should ask their students to curate and deposit both mapping files and raw data files.</p>
<p>Guidelines for formatting map files:
- Mapping files should be tab-delimited
- The first column must be “#SampleIDs” (commented out using the <code>#</code>).
- SampleIDs are VERY IMPORTANT. Choose wisely! Ideally, a user who did not design the experiment should be able to distiguishes the samples easily, as is the case with the Schloss data. SampleIDs must be alphanumeric characters or periods. They cannot have underscores.
- The last column must be “Description”.
- There can be as many in-between columns of contextual data as needed.
- If you plan to use QIIME for quality control (which we do not need because the PANDAseq merger included QC), the BarcodeSequence and LinkerPrimer sequence columns are also needed, as the second and third columns, respectively.
- Excel can cause formatting heartache. See more details <a href="misc/QIIMETutorial_Misc/MapFormatExcelHeartAche.md">here</a>.</p>
<h3 id="call-qiime">2.2 Call QIIME</h3>
<p>For Mac users, to enter the QIIME environment in all of its glory, use <code>macqiime</code>.</p>
<p>A good command to know is:</p>
<p><code>
print_qiime_config.py
</code></p>
<p><img src="https://github.com/edamame-course/docs/raw/gh-pages/img/QIIMETutorial1_IMG/IMG_09.jpg" alt="img9" /> </p>
<p>This will give you really important information about versions of software, etc. You will need this info</p>
<h3 id="merging-assembled-reads-into-the-one-big-ol-data-file">2.3 Merging assembled reads into the one big ol’ data file.</h3>
<p>QIIME expects all of the data to be in one file, and, currently, we have one separate fastq file for each assembled read. We will add labels to each sample and merge into one fasta using the <code>add_qiime_labels.py</code> script. Documentation is <a href="http://qiime.org/scripts/add_qiime_labels.html">here</a>.</p>
<p><code>
add_qiime_labels.py -i pandaseq_merged_reads/ -m Schloss_Map.txt -c InputFileName -n 1 -o combined_fasta
</code></p>
<p>This script creates a new directory called “combined_fasta.” Use <code>cd</code> and <code>ls</code> to navigate to that directory and examine the files. Inspect the new file “combined_seqs.fna.”</p>
<p><code>
head combined_seqs.fna
</code></p>
<p><img src="https://github.com/edamame-course/docs/raw/gh-pages/img/QIIMETutorial1_IMG/IMG_06.jpg" alt="img6" /> </p>
<p>Observe that QIIME has added the SampleIDs from the mapping file to the start of each sequence. This allows QIIME to quickly link each sequence to its sampleID and metadata.</p>
<p>While we are inspecting the combined_seqs.fna file, let’s confirm how many sequences we have in the dataset.</p>
<p><code>
count_seqs.py -i combined_seqs.fna
</code></p>
<p>This is a nice QIIME command to call frequently, because it provides the total number of sequences in a file, as well as some information about the lengths of those sequences. But, suppose we wanted to know more than the median/mean of these sequences?</p>
<p>Another trick with QIIME is that you can call all the mothur commands within the QIIME environment, which is very handy. mothur offers a very useful command called <code>summary.seqs</code>, which operates on a fasta/fna file to give summary statistics about its contents. We will cover mothur in all its glory later, but for now, execute the command:</p>
<p><code>
mothur
</code></p>
<p><code>
summary.seqs(fasta=combined_seqs.fna)
</code></p>
<p>Note that both summary.seqs and count_seqs.py have returned the same total number of seqs in the .fna file. Use the following command to quit the mothur environment and return to QIIME. </p>
<p><img src="img/QIIMETutorial1_IMG/summary_seqs.jpg" alt="img" /></p>
<p><code>
quit()
</code></p>
<h5 id="optional-step---chimera-checking-with-usearch-before-picking-otus--usearch-is-an-add-on-to-macqiime-extra-installation-steps-required">2.3.2 Optional step* : chimera checking with USEARCH before picking OTUs. USEARCH is an add-on to MacQIIME (extra installation steps required).</h5>
<h3 id="picking-operational-taxonomic-units-otus">2.4 Picking Operational Taxonomic Units, OTUs.</h3>
<p>Picking OTUs is sometimes called “clustering,” as sequences with some threshold of identity are “clustered” together to into an OTU.</p>
<p><em>Important decision</em>: Should I use a de-novo method of picking OTUs or a reference-based method, or some combination? (<a href="http://www.mendeley.com/catalog/interpreting-16s-metagenomic-data-without-clustering-achieve-subotu-resolution/">Or not at all?</a>). The answer to this will depend, in part, on what is known about the community a priori. For instance, a human or mouse gut bacterial community will have lots of representatives in well-curated 16S databases, simply because these communities are relatively well-studied. Therefore, a reference-based method may be preferred. The limitation is that any taxa that are unknown or previously unidentified will be omitted from the community. As another example, a community from a lesser-known environment, like Mars or a cave, or a community from a relatively less-explored environment would have fewer representative taxa in even the best databases. Therefore, one would miss a lot of taxa if using a reference-based method. The third option is to use a reference database but to set aside any sequences that do not have good matches to that database, and then to cluster these de novo.</p>
<p>We use the <code>pick_otus.py</code> script in QIIME for this step. Documentation is <a href="http://qiime.org/scripts/pick_otus.html?highlight=pick_otus">here</a>.
The default QIIME 1.8.0 method for OTU picking is uclust (de novo, but there is a reference-based alternative, see below), but we will use the CD-HIT algorithm (de novo). However, we encourage you to explore different OTU clustering algorithms to understand how they perform. They are not created equal. Honestly, we are using CD-HIT here because because it is fast.</p>
<p>Make sure you are in the QIIMETutorial directory to start. This will take a few (<10ish) minutes.</p>
<p><code>
pick_otus.py -i combined_fasta/combined_seqs.fna -m cdhit -o cdhit_picked_otus/ -s 0.97 -n 100
</code></p>
<p>In the above script:
- We tell QIIME to look in the “combined_fasta” directory for the input file <code>-i</code>, “combined_seqs.fna”.
- We chose the clustering method CD-HIT <code>-m</code>
- We defined an output file “cdhit_picked_otus” <code>-o</code>. Names of output files are important, because there are many options for each analysis. Using the algorithm choice in the directory name is key for comparing the output of multiple algothims (for instance, if you wanted to compare how picking OTUs with CD-HIT and with uclust may influence your results.)
- We define OTUs at 97% sequence identity <code>-s 0.97</code>
- We opt for a pre-filtering step, unique to CD-HIT <code>-n</code> = 100.</p>
<p>Inspect the log and the resulting combined_seqs_otus.txt file, using <code>head</code>. You should see an OTU ID (yellow box), starting at “0” the the left most column. After that number, there is a list of Sequence IDs that have been clustered into that OTU ID. The first part of the sequence ID is the SampleID from which it came (green box), and the second part is the sequence number within that sample (purple box). </p>
<p><img src="https://github.com/edamame-course/docs/raw/gh-pages/img/QIIMETutorial1_IMG/IMG_07.jpg" alt="img7" /></p>
<p>From the head of the combined_seqs_otus.txt file, we can see that OTU 0 has many sequence associated with it, including sequence 9757 from from sample F3D8.S196. We also see that OTU 3 only has one sequence associated with it. The log file has goodies about the algorithm and options chosen. Keep this (and all) log file, because when you are writing the paper you may not remember what version of which clustering algorithm you used.</p>
<h3 id="pick-a-representative-sequence-from-each-otu">2.5 Pick a representative sequence from each OTU.</h3>
<p>Representative sequences are those that will be aligned and used to build a tree. They are selected as the one sequence, out of its whole OTU cluster, that will “define” its OTUs. As you can imagine, understanding how these “rep seqs” are chosen is very important. Here, we will use the default method (the first sequence listed in the OTU cluster) of QIIME’s <code>pick_rep_set.py</code> script; documentation <a href="http://qiime.org/scripts/pick_rep_set.html">here</a>.</p>
<p><code>
mkdir cdhit_rep_seqs/
</code></p>
<p><code>
pick_rep_set.py -i cdhit_picked_otus/combined_seqs_otus.txt -f combined_fasta/combined_seqs.fna -o cdhit_rep_seqs/cdhit_rep_seqs.fasta -l cdhit_rep_seqs/cdhit_rep_seqs.log
</code></p>
<p>As before, we specify the input files (the script needs the OTU clusters and the raw sequence file as input), and then we additionally specified the a new directory for the results.
Inspect the head of the new fasta file, cdhit_rep_seqs.fasta.</p>
<p><img src="https://github.com/edamame-course/docs/raw/gh-pages/img/QIIMETutorial1_IMG/IMG_08.jpg" alt="img8" /></p>
<p>As before, we see the OTU ID given first (consecutively, starting with 0), and then the sequence ID of the representative sequence, and then the full nucleotide information for the sequence. Notice that for OTU 0, which only had one sequence in its “cluster”, is defined by that one sequence. Don’t be shy - go ahead and compare it to the combined_seqs_otus.txt file of OTU clusters.</p>
<p>Take a gander at the log file, as well. </p>
<h3 id="align-representative-sequences">2.6 Align representative sequences.</h3>
<p>Navigate back to the QIIMETutorial directory. We will align our representative sequences using PyNAST, which uses a “gold” reference template for the alignment. QIIME uses a “gold” pre-aligned template made from the greengenes database. The default alignment to the template is minimum 75% sequence identity and minimum length 150. The default minimum length is not great for short reads like we have, so we will be more generous and change the default. What should we change it to?</p>
<p><code>
count_seqs.py -i cdhit_rep_seqs/cdhit_rep_seqs.fasta
</code></p>
<p>Given that our average assembled read length is ~252 bp, let’s decide that at least 100 bp must align. We will have the <code>-e</code> option to 100. The alignment will take a few minutes. Documentation for <code>align_seqs.py</code> is <a href="http://qiime.org/scripts/align_seqs.html">here</a>.</p>
<p><code>
align_seqs.py -i cdhit_rep_seqs/cdhit_rep_seqs.fasta -o pynast_aligned/ -e 100
</code></p>
<p>Navigate into the pynast_aligned directory. There are three files waiting there: one file of sequences that failed to align, one of sequences that did align, and a log file. Inspect each.</p>
<p><code>
count_seqs.py -i cdhit_rep_seqs_failures.fasta
</code></p>
<p><code>
count_seqs.py -i cdhit_rep_seqs_aligned.fasta
</code></p>
<p>We see that there were ~3 rep. sequences that failed to align, and approximately 682 that did. (Also, notice what short-read alignments generally look like…not amazing).</p>
<p><em>Sanity check?</em> If you like, <a href="http://blast.ncbi.nlm.nih.gov/Blast.cgi?PAGE_TYPE=BlastSearch&BLAST_SPEC=MicrobialGenomes">BLAST</a> the top sequence that failed to align to convince yourself that it is, indeed, a pitiful failure.</p>
<p>If, in the future, you ever have a large proportion of rep seqs that fail to align, it could be due to:
* Hooray! These are novel organisms! (But, think about the habitat before jumping to conclusions. As lucky as we would be to discover new species in the mouse gut, this is unlikely.)
* The alignment parameters were too stringent for short reads, causing “real” sequences to fail alignment.
* The paired-end merger algorithm (e.g., pandaseq) did not do a perfect job, and concatenated ends that do not belong together.
* Some combination of the above, as well as some other scenarios.</p>
<p>We will filter out these failed-to-align sequences (really, the removing the entire OTU cluster that they represent) from the dataset after we make the OTU table. In the meantime, let’s create a text file of all the names of the rep. sequence OTU IDs that we want to remove. We only have three failures, so we easily could do it by hand. What if we had more? Here’s how to automate the generation of the “cdhit_rep_seqs_failures_names.txt” file using the <code>grep</code> command. We will not go into details, but general grep help is <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?grep">here</a>. Navigate back into the QIIMETutorial directory to run the grep command.</p>
<p><code>
grep -o -E "^>\w+" pynast_aligned/cdhit_rep_seqs_failures.fasta | tr -d ">" > pynast_aligned/cdhit_rep_seqs_failures_names.txt
</code></p>
<p>Congratulations! You just had the QIIME of Your Life!</p>
<p><img src="https://github.com/edamame-course/docs/raw/gh-pages/img/QIIMETutorial1_IMG/IMG_10.jpg" alt="img10" /> </p>
<h2 id="where-to-find-qiime-resources-and-help">Where to find QIIME resources and help</h2>
<ul>
<li><a href="qiime.org">QIIME</a> offers a suite of developer-designed <a href="http://www.qiime.org/tutorials/tutorial.html">tutorials</a>.</li>
<li><a href="http://www.qiime.org/scripts/index.html">Documentation</a> for all QIIME scripts.</li>
<li>There is a very active <a href="https://groups.google.com/forum/#!forum/qiime-forum">QIIME Forum</a> on Google Groups. This is a great place to troubleshoot problems, responses often are returned in a few hours!</li>
<li>The <a href="http://qiime.wordpress.com/">QIIME Blog</a> provides updates like bug fixes, new features, and new releases.</li>
<li>QIIME development is on <a href="https://github.com/biocore/qiime">GitHub</a>.</li>
</ul>
<hr />
<hr />
|
# Example with Spring
Creating a RESTful API with Spring is a common task for many developers. Here's a step-by-step guide on how to create a simple API using Spring Boot, one of the most popular frameworks for building Java applications.
## Step 1: Set Up Your Development Environment
Before you start, make sure you have the following installed:
* Java Development Kit (JDK)
* Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse
* Maven or Gradle for dependency management
* Postman or a similar tool for testing APIs
## Step 2: Create a New Spring Boot Project
Open your IDE and create a new Spring Boot project.
Choose a group and artifact ID for your project.
Select the Spring Web dependency.
Spring Boot's project setup wizard in most IDEs simplifies this process.
## Step 3: Define a Data Model
In this example, let's create a simple API for managing a list of tasks. Define a data model class for tasks:
```
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private boolean completed;
// Getters and setters
}
```
Step 4: Create a Repository
Create a repository interface to interact with the database. You can use Spring Data JPA for this:
```
public interface TaskRepository extends JpaRepository<Task, Long> {
// Custom queries can go here if needed
}
```
## Step 5: Create a Service
Create a service class to handle business logic:
```
@Service
public class TaskService {
@Autowired
private TaskRepository taskRepository;
public List<Task> getAllTasks() {
return taskRepository.findAll();
}
public Task createTask(Task task) {
return taskRepository.save(task);
}
public Task updateTask(Long id, Task task) {
if (!taskRepository.existsById(id)) {
throw new ResourceNotFoundException("Task not found with id: " + id);
}
task.setId(id);
return taskRepository.save(task);
}
public void deleteTask(Long id) {
taskRepository.deleteById(id);
}
}
```
## Step 6: Create a Controller
Create a REST controller to define API endpoints:
```
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
@Autowired
private TaskService taskService;
@GetMapping
public List<Task> getAllTasks() {
return taskService.getAllTasks();
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Task createTask(@RequestBody Task task) {
return taskService.createTask(task);
}
@PutMapping("/{id}")
public Task updateTask(@PathVariable Long id, @RequestBody Task task) {
return taskService.updateTask(id, task);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteTask(@PathVariable Long id) {
taskService.deleteTask(id);
}
}
```
## Step 7: Run Your Application
You can run your Spring Boot application using the IDE or with the following command:
```
./mvnw spring-boot:run
```
## Step 8: Test Your API
Use Postman or a similar tool to test your API by sending HTTP requests to the defined endpoints:
* GET /api/tasks to retrieve all tasks.
* POST /api/tasks to create a new task.
* PUT /api/tasks/{id} to update an existing task.
* DELETE /api/tasks/{id} to delete a task.
## Step 9: Documentation (Optional)
You can use tools like Swagger or Springfox to generate API documentation for your endpoints.
Congratulations! You've created a simple RESTful API using Spring Boot. You can expand on this foundation by adding authentication, validation, and more complex business logic as needed for your project.
⭐️ From [DarlanNoetzold](https://github.com/DarlanNoetzold)
|
import { createBrowserRouter } from 'react-router-dom';
import App from '../App.jsx';
import ErrorPage from '../components/ErrorPage.jsx';
import RestaurantList from '../components/RestaurantList.jsx';
import RestaurantMenu from '../components/RestaurantMenu.jsx';
import Checkout from '../components/Checkout.jsx';
import SearchPage from '../components/SearchPage.jsx';
import SignUpPage from '../components/SignUpPage.jsx';
import LoginPage from '../components/LoginPage.jsx';
import ProtectedRoute from '../components/ProtectedRoute.jsx';
const router = createBrowserRouter([
{
path: '/',
element: <App />,
errorElement: <ErrorPage />,
children: [
{
path: '/',
element: <RestaurantList />,
},
{
element: <ProtectedRoute />,
children: [
{
path: '/sign-up',
element: <SignUpPage />
},
{
path: '/login',
element: <LoginPage />
},
],
},
{
path: '/restaurant/:restaurantId',
element: <RestaurantMenu />
},
{
path: '/checkout',
element: <Checkout />
},
{
path: '/search',
element: <SearchPage />
}
],
},
]);
export default router;
|
# Implement Anything-as-a-Source with SmartHR and Okta Workflows
## Overview
This template demonstrates how to use Anything-as-a-Source (XaaS) to import records from SmartHR. The workflow requests records from SmartHR using the **SmartHR - Search Employees** card and stores the resulting list of records in a temporary Workflows table. The workflow then processes those records by creating import sessions and handling bulk import requests. These imports are handled based on the number of records to import and the parameters outlined in the XaaS documentation.
## Prerequisites
Before you get started, here are the things you need:
- Access to an Okta tenant with Okta Workflows enabled for your org
- Access to a SmartHR tenant
## Setup Steps
1. Create and configure a Custom Identity Source using the instructions at [Use Anything-as-a-Source](https://help.okta.com/en-us/Content/Topics/users-groups-profiles/usgp-use-anything-as-a-source.htm). This template functions as an API client for XaaS, as described in the **Synchronize data with a Custom Identity Source** section.
1. Set up a Workflows connection for SmartHR. See [Authorization](https://help.okta.com/wf/en-us/Content/Topics/Workflows/connector-reference/smarthr/overviews/authorization.htm)
1. Go to the **Implementing anything-as-a-source with SmartHR using Okta Workflows** folder and edit the **Orchestrate Import from SmartHR** flow. Ensure that the **Okta - List Users with Search** card uses your Okta connection. Also ensure that the **SmartHR - Search Employees** card uses the correct connection to SmartHR.
1. Edit the **XaaS Import Session Handler** and **XaaS Bulk Import Request Handler** flows to use the Okta connection on the Okta cards.
1. In the **Scheduled Flows** folder, edit both the **Import from SmartHR (Create & Activate)** and **Import from SmartHR (Deactivate & Delete)** flows. Update the **Scheduled Flow** event card in both flows to meet your requirements.
1. In the **Utilities** folder, change the **Create Import Session** and **Delete Import Session** flows so that the Okta cards use the correct connection.
## Testing this Flow
For testing, Okta recommends configuring this template in an Okta Preview environment.
If you don't want to test a full import, you can request a small batch of records from SmartHR:
1. Go to the **Implementing anything-as-a-source with SmartHR using Okta Workflows** folder
1. Edit the **SmartHR - Search Employees** card in the **Orchestrate Import from SmartHR** flow and add a small value for the **Record Limit** field.
1. You can manually initiate an import. Go the **Scheduled Flows** folder and click **Test** in the **Import from SmartHR (Create & Activate)** flow.
1. To verify the results, open the Okta Admin Console. Go to **Reports > Import Monitoring** and expand on the entry created by your test import.
## Limitations & Known Issues
- To understand in depth how the Anything-as-a-Source process works, see the following Okta documentation: [Use Anything-as-a-Source](https://help.okta.com/en-us/Content/Topics/users-groups-profiles/usgp-use-anything-as-a-source.htm) and [Build an Anything-as-a-Source custom client integration](https://developer.okta.com/docs/guides/anything-as-a-source/).
|
#pragma once
#include "Player.h"
#include "Boss.h"
#include "Bullet.h"
#include "Script.h"
#include "PauseMenu.h"
#include "GameOverMenu.h"
#include <SFML/Graphics.hpp>
#include <memory>
#include <random>
class Stage
{
public:
constexpr static int playAreaW = 384;
constexpr static int playAreaH = 448;
constexpr static int playAreaX = 32;
constexpr static int playAreaY = 16;
enum class State
{
Null,
Normal,
Paused,
GameOver
};
Stage();
void update(float delta);
void draw(sf::RenderTarget& target, float delta) const;
void pause();
void resume();
void useContinue();
void showGameOverMenu();
sf::Texture projectiles;
sf::Texture background;
sf::Texture hud;
sf::Texture characters;
// keep below objects
Script script;
Player player;
std::unique_ptr<Boss> boss;
std::vector<Bullet> bullets;
std::vector<Bullet> playerBullets;
float gameplayDelta = 1.0f;
std::mt19937 randomEngine{ 69420 };
inline float random(float from, float to)
{
float t = static_cast<float>(randomEngine()) / static_cast<float>(std::mt19937::max());
return from + (to - from) * t;
}
private:
constexpr static int m_hudX = 16;
constexpr static int m_hudY = 32;
void mUpdateAll(float delta);
void mPhysicsUpdateAll(float delta);
void mEndUpdateAll(float delta);
void mDrawAll(float delta) const;
void mBatchBullets(float delta) const;
void mDebugDraw(float delta) const;
void mDrawPlayAreaHud(float delta) const;
void mDrawBg(sf::RenderTarget& target, float delta) const;
void mDrawPlayArea(sf::RenderTarget& target, float delta) const;
void mDrawHud(sf::RenderTarget& target, float delta) const;
State m_state = State::Normal;
mutable sf::VertexArray m_bulletsBuf{ sf::Quads };
mutable sf::RenderTexture m_playArea;
PauseMenu* m_pauseMenu = nullptr;
GameOverMenu* m_gameOverMenu = nullptr;
sf::Texture m_scriptTexture;
};
|
Input: arr[] = {22, 14, 8, 17, 35, 3}
Output: Minimum element is: 3
Maximum element is: 35
We have to find the maximum and minimum element.
Brute Force Approach:
1.Sorting the Array
2.returning first and last element
Arrays.sort(arr);
min = arr[0];
max = arr[n - 1];
But the Time complexity is O(nlogn) because of sorting
Let solve this with linear time complexity and constant time
1.intilaze min with Integer max value
2. Intilaze max with Integer min value
3.run loop from 0 to n-1 update the max and min values using Math.min() and Math.max()
int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
for(int i=0;i<N;i++){
min=Math.min(min,A[i]);
max=Math.max(max,A[i]);
}
|
import { memo, useState, useEffect } from 'react';
import './comment.scss';
import defaultAvatar from '../../../assets/defaultAvatar.png';
import { Spin } from 'react-cssfx-loading/lib';
import { Gif } from '@giphy/react-components';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faThumbsUp, faArrowTurnUp, faEllipsis } from '@fortawesome/free-solid-svg-icons';
import commentAPI from '../../../services/commentAPI';
import timeFormat from '../../../utils/timeFormat';
import { Link, useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux/es/exports';
import { addReplyComment, addReplyChildComment } from '../../../redux/commentSlice';
import { useSelector } from 'react-redux/es/exports';
function Comment({ comment, role, showCommentBar, childCommentShow }) {
const $ = document.querySelector.bind(document)
const themeMode = useSelector(state => state.auth.themeMode) === 'dark' ? ' dark' : ''
const currentUser = useSelector(state => state.auth.login.user.userInformation)
const currentUserId = currentUser.userId
const navigate = useNavigate()
const dispatch = useDispatch()
const isSaveDataBase = comment.id ? ' save' : null
const [likeArr, setLikeArr] = useState(comment.like ? JSON.parse(comment.like) : [])
const [timeAgo, setTimeAgo] = useState(timeFormat.timeAgo(comment.createdAt))
const [replyNumber, setReplyNumber] = useState(getTotalReply())
const [isShowReply, setIsShowReply] = useState(false)
const [loadingChildComment, setLoadingChildComment] = useState(false)
useEffect(() => {
const T = setInterval(() => {
setTimeAgo(timeFormat.timeAgo(comment.createdAt))
},1000*60)
return () => {
clearInterval(T)
}
}, [comment.createdAt])
function getTotalReply() {
switch (role) {
case 'parent-comment':
return comment.replyComment?.totalReplyComment
case 'reply-comment':
return comment.replyChildComment?.totalReplyChildComment
default:
break;
}
}
async function handleLikeComment() {
if (isSaveDataBase) {
let likeComment = {
action: 'update_like',
userId: currentUserId,
}
switch (role) {
case 'parent-comment':
likeComment.parentCommentId = comment.id
break;
case 'reply-comment':
likeComment.replyCommentId = comment.id
break;
case 'reply-child-comment':
likeComment.replyChildCommentId = comment.id
break;
default:
break;
}
const res = await commentAPI.updateComment(likeComment)
if (res.data.errCode === 0) {
let likeButton = $(`li[id="like-button ${role+'-'+comment.id}"]`)
if (likeButton.classList.contains('liked')) {
likeButton.classList.remove('liked')
const index = likeArr.indexOf(currentUserId)
likeArr.splice(index, 1)
setLikeArr([...likeArr])
} else {
likeButton.classList.add('liked')
setLikeArr([ ...likeArr, currentUserId ])
}
}
}
}
async function handleShowReply() {
setLoadingChildComment(true)
if (isSaveDataBase) {
setIsShowReply(true)
try {
switch (role) {
case 'parent-comment':
const resCase1 = await commentAPI.getComment({ parentCommentId: comment.id })
dispatch(addReplyComment(resCase1.data.replyComment))
setReplyNumber(null)
break;
case 'reply-comment':
const resCase2 = await commentAPI.getComment({ replyCommentId: comment.id })
dispatch(addReplyChildComment(resCase2.data.replyChildComment))
setReplyNumber(null)
break;
default:
break;
}
} catch (error) {
throw new Error(error)
}
}
}
function likeStatus() {
if (likeArr?.includes(currentUserId)) {
return 'liked'
}
return ''
}
return (
<div className={"comment"+themeMode}>
<Link to={`/${comment.userId}`} className="wrap-avatar-user-comment">
<img
className="avatar-user-comment" alt=""
src={comment.userAvatar ? comment.userAvatar : defaultAvatar}
/>
</Link>
<div className="wrap-comment-body">
<div className="wrap-comment-content">
<div className="wrap-comment-text">
<div id={role+`-${comment.id}-content`} className="comment-text">
<span
className="comment-user"
onClick={() => navigate(`/${comment.userId}`)}
>{comment.userFullName}</span>
{
(comment.commentType === 'text') &&
<span className="comment-text-content">{comment.commentContent}</span>
}
{
(comment.commentType === 'text-image') &&
<span className="comment-text-content">{(JSON.parse(comment.commentContent)).text}</span>
}
{
(likeArr?.length > 0) &&
<div
id={"interactive-group "+role+"-"+comment.id}
className="wrap-interactive-group"
>
<div className="wrapper-icon">
<FontAwesomeIcon icon={faThumbsUp} className="like-icon" />
</div>
<span className="like-num">{likeArr.length}</span>
</div>
}
</div>
</div>
{
(comment.commentType === 'text-image') &&
<img className="img-comment" alt="" src={(JSON.parse(comment.commentContent)).image}/>
}
{
(comment.commentType === 'image') &&
<img className="img-comment" alt="" src={comment.commentContent}/>
}
{
(comment.commentType === 'sticker') &&
<img className="sticker-comment" alt="" src={comment.commentContent}/>
}
{
(comment.commentType === 'gif') &&
<div style={{"marginBottom": 4}}>
<Gif
gif={JSON.parse(comment.commentContent)} width={300} hideAttribution={true}
onGifClick={(gif, e) => {
e.preventDefault()
}}
/>
</div>
}
<ul className="interactive-comment">
<li
className={"i-comment-item disable-select "+likeStatus()+isSaveDataBase}
onClick={handleLikeComment} id={"like-button "+role+"-"+comment.id}
>Thích</li>
<li
className={"i-comment-item disable-select"+isSaveDataBase}
onClick={() => {
showCommentBar()
if (!isShowReply) {
handleShowReply()
}
}}
>Phản hồi</li>
<li className="i-comment-item time disable-select">{timeAgo}</li>
</ul>
{
(replyNumber > childCommentShow) &&
<div
className="show-reply-comment disable-select"
id={"show-reply-comment "+role+"-"+comment.id}
onClick={() => handleShowReply()}
>
<div className="show-reply-comment-icon-wrap">
<FontAwesomeIcon icon={faArrowTurnUp} className="show-reply-comment-icon"/>
</div>
<span className="show-reply-comment-desc">Xem {replyNumber} phản hồi</span>
{
loadingChildComment
&&
<div className="wrap-loading-child-comment-icon">
<Spin color={themeMode === ' dark' ? '#b0b3b8' : '#616161'} />
</div>
}
</div>
}
</div>
<div className="wrap-comment-option">
<span className="wrap-comment-btn">
<div role="button" className="comment-option-btn">
<FontAwesomeIcon icon={faEllipsis} className="option-icon"/>
</div>
</span>
</div>
</div>
</div>
)
}
export default memo(Comment);
|
package com.example.mybatis.configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class PersistenceConfig {
@Bean
public DataSource dataSource(){
return DataSourceBuilder
.create()
.driverClassName("com.mysql.cj.jdbc.Driver")
.url("jdbc:mysql://localhost:3306/mybatis")
.username("root")
.password("root")
.build();
}
@Bean
public SqlSessionFactory sessionFactory() throws Exception{
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource());
return factoryBean.getObject();
}
}
|
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2014 CERN
* @author Maciej Suminski <maciej.suminski@cern.ch>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifndef MODULE_TOOLS_H
#define MODULE_TOOLS_H
#include <tool/tool_interactive.h>
#include <origin_viewitem.h>
namespace KIGFX
{
class VIEW;
class VIEW_CONTROLS;
}
class BOARD;
class PCB_EDIT_FRAME;
/**
* Class MODULE_TOOLS
*
* Module editor specific tools.
*/
class MODULE_TOOLS : public TOOL_INTERACTIVE
{
public:
MODULE_TOOLS();
~MODULE_TOOLS();
/// @copydoc TOOL_INTERACTIVE::Reset()
void Reset( RESET_REASON aReason ) override;
/// @copydoc TOOL_INTERACTIVE::Init()
bool Init() override;
/**
* Function PlacePad()
* Places a pad in module editor.
*/
int PlacePad( const TOOL_EVENT& aEvent );
/**
* Function EnumeratePads()
* Tool for quick pad enumeration.
*/
int EnumeratePads( const TOOL_EVENT& aEvent );
/**
* Function CopyItems()
*
* Copies selected items to the clipboard. Works only in "edit modules" mode.
*/
int CopyItems( const TOOL_EVENT& aEvent );
/**
* Function PastePad()
*
* Pastes items from the clipboard. Works only in "edit modules" mode.
*/
int PasteItems( const TOOL_EVENT& aEvent );
/**
* Function CreateArray
*
* Creates an array of objects using settings from a dialog
*/
int CreateArray( TOOL_EVENT& aEvent );
/**
* Function ModuleTextOutlines()
*
* Toggles display mode for module texts (outline/filled).
*/
int ModuleTextOutlines( const TOOL_EVENT& aEvent );
/**
* Function ModuleEdgeOutlines()
*
* Toggles display mode for module edges (outline/filled).
*/
int ModuleEdgeOutlines( const TOOL_EVENT& aEvent );
///> Sets up handlers for various events.
void SetTransitions() override;
private:
KIGFX::VIEW* m_view;
KIGFX::VIEW_CONTROLS* m_controls;
BOARD* m_board;
PCB_EDIT_FRAME* m_frame;
///> Axis 0 marker
KIGFX::ORIGIN_VIEWITEM* m_axisOrigin;
};
#endif
|
package com.example.web.model;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column
private String username;
@Column
private String password;
@Column
private String name;
@Column
private String surname;
@Column
private int age;
@ManyToMany (fetch = FetchType.EAGER)
@JoinTable(name="UserRoles", joinColumns = @JoinColumn(name="user"), inverseJoinColumns = @JoinColumn(name = "role"))
private Set<Role> roles = new HashSet<>();
public User() {
}
public User(String name, String surname, int age, String login, String pass) {
this.name = name;
this.surname = surname;
this.age = age;
this.username = login;
this.password = pass;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void addRole(Role role) {
this.roles.add(role);
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
", surname='" + surname + '\'' +
", age=" + age +
'}';
}
}
|
package core;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** JUnit test class for {@link Expense} class. */
public class ExpenseTest {
private Expense expense;
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
/** Setup method to initialize common test data. */
@BeforeEach
public void setUp() {
expense = new Expense(LocalDate.now(), "Groceries", 100.0, "Weekly shopping");
}
/** Test to verify that the Expense object is correctly initialized. */
@Test
public void testExpenseInitialization() {
assertNotNull(expense);
assertEquals(LocalDate.now().format(formatter), expense.getDate());
assertEquals("Groceries", expense.getCategory());
assertEquals(100.0, expense.getPrice());
assertEquals("Weekly shopping", expense.getDescription());
}
/** Test to verify that the empty constructor creates a valid Expense object. */
@Test
public void testEmptyConstructor() {
Expense expense = new Expense();
assertNotNull(expense);
}
/**
* Test to verify that the constructor with date, category, price and description parameters
* creates a valid Expense object.
*/
@Test
public void testConstructor() {
Expense expense1 = new Expense("14.07.1980", "PC", 6000.0, "New PC");
assertNotNull(expense1);
assertThrows(
IllegalArgumentException.class,
() -> new Expense("01.01.1990", "PC", -6000.0, "New PC"),
"Negative price should throws illehalArgumentException");
assertThrows(
IllegalArgumentException.class,
() -> new Expense("01.01.1990", "", 6000.0, "New PC"),
"Empty categorie should throws illehalArgumentException");
assertThrows(
IllegalArgumentException.class,
() -> new Expense("01.01.1990", "", 6000.0, ""),
"Empty description should throws illehalArgumentException");
}
@Test
public void testSetDateString() {
assertThrows(IllegalArgumentException.class, () -> expense.setDateString(""));
assertThrows(
IllegalArgumentException.class,
() -> expense.setDateString("12-12-2022"),
"This should lead to illegalArgumentException, because is wrong format");
}
/** Test to verify that setting a null date throws an IllegalArgumentException. */
@Test
public void testSetDateNull() {
assertThrows(IllegalArgumentException.class, () -> expense.setDate(null));
}
/** Test to verify that setting a negative price throws an IllegalArgumentException. */
@Test
public void testSetNegativePrice() {
assertThrows(IllegalArgumentException.class, () -> expense.setPrice(-1.0));
}
/** Test to verify that setting a null or empty category throws an IllegalArgumentException. */
@Test
public void testSetNullOrEmptyCategory() {
assertThrows(IllegalArgumentException.class, () -> expense.setCategory(null));
assertThrows(IllegalArgumentException.class, () -> expense.setCategory(""));
}
/** Test to verify that setting a null or empty description throws an IllegalArgumentException. */
@Test
public void testSetNullOrEmptyDescription() {
assertThrows(IllegalArgumentException.class, () -> expense.setDescription(null));
assertThrows(IllegalArgumentException.class, () -> expense.setDescription(""));
}
/** Test to verify that the toString method returns the expected string. */
@Test
public void testToString() {
String expected =
String.format(
"| %s | %s | %s | %.2fkr |",
expense.getDate(), expense.getCategory(), expense.getDescription(), expense.getPrice());
assertEquals(expected, expense.toString());
}
/**
* Test to verify that the equals method returns true when comparing two Expense objects with the
* same description, category, date and price.
*/
@Test
public void testEquals() {
Expense expense1 = new Expense(LocalDate.now(), "Groceries", 100.0, "Weekly shopping");
assertEquals(true, expense.equals(expense1));
assertEquals(false, expense.equals(new Object()));
assertEquals(
false,
expense.equals(new Expense(LocalDate.now(), "Groceries", 100.0, "Weekly shopping1")));
assertEquals(
false,
expense.equals(new Expense(LocalDate.now(), "GroceriesQ", 100.0, "Weekly shopping")));
assertEquals(
false, expense.equals(new Expense(LocalDate.now(), "Groceries", 100.1, "Weekly shopping")));
assertEquals(
false,
expense.equals(new Expense(LocalDate.now(), "Groceries", 100.0, "Weekly shopping1")));
}
/**
* Test to verify that the equals method returns true when comparing two Expense objects with the
* same description, category, date and price.
*/
@Test
public void testHashCode() {
assertEquals(
Objects.hash(
expense.getDescription(), expense.getCategory(), expense.getDate(), expense.getPrice()),
expense.hashCode());
}
}
|
import React, { useState, useEffect } from 'react'
import { useContext } from 'react';
import { useParams } from 'react-router-dom'
import JokeService from '../services/JokeService'
import AuthContext from './Auth/Auth-context';
function ViewComments(props) {
const [comments,setComments] = useState([])
const {id} = useParams();
const authCtx = useContext(AuthContext);
useEffect(() => {
getJokeComments()
},[])
const getJokeComments = async() =>{
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authCtx.token}`,
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Origin': '*'
},
};
try {
const response = await fetch(`http://localhost:8081/api/v1/jokes/comment/${id}`, requestOptions)
const data =await response.json()
setComments(data.comments)
}
catch (err) {
console.error(err)
}
};
// const deleteComment = (commentId)=>{
// JokeService.deleteComment(commentId).then((response)=>{
// getJokeComments();
// }).catch(error=>{
// console.log(error);
// })
// }
const deleteComment = async(commentId)=>{
const requestOptions = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authCtx.token}`,
'Access-Control-Allow-Methods': 'DELETE',
'Access-Control-Allow-Origin': '*'
},
};
try {
const response = await fetch(`http://localhost:8081/api/v1/jokes/comment/${commentId}`, requestOptions)
getJokeComments();
}
catch (err) {
console.error(err)
}
};
return (
<div className="container">
{/* <h1 className="text-center"> Comments</h1> */}
<table className="table table-striped">
<thead>
<tr>
<th>Joke Comment</th>
</tr>
</thead>
<tbody>
{
comments.map(
comment =>
<tr key = {comment.id}>
<td>{comment.comment}</td>
<td>
<button className="btn btn-danger" onClick={()=> deleteComment(comment.id)} size="sm">Delete</button>
</td>
</tr>
)
}
</tbody>
</table>
</div>
)
}
export default ViewComments;
|
library center_body;
import 'package:flutter/material.dart';
class CenterBody extends StatelessWidget {
final String message;
final IconData icon;
const CenterBody({super.key, required this.message, required this.icon});
@override
Widget build(BuildContext context) => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 7),
child: Icon(icon,
size: 68,
color: Theme.of(context)
.colorScheme
.onBackground
.withOpacity(0.5))),
Text(message,
style: TextStyle(
fontSize: 18,
color: Theme.of(context)
.colorScheme
.onBackground
.withOpacity(0.5))),
],
),
);
}
|
"""This test checks that AxSearch is functional.
It also checks that it is usable with a separate scheduler.
"""
import numpy as np
import ray
from ray.tune import run
from ray.tune.schedulers import AsyncHyperBandScheduler
from ray.tune.suggest.ax import AxSearch
def hartmann6(x):
alpha = np.array([1.0, 1.2, 3.0, 3.2])
A = np.array([
[10, 3, 17, 3.5, 1.7, 8],
[0.05, 10, 17, 0.1, 8, 14],
[3, 3.5, 1.7, 10, 17, 8],
[17, 8, 0.05, 10, 0.1, 14],
])
P = 10**(-4) * np.array([
[1312, 1696, 5569, 124, 8283, 5886],
[2329, 4135, 8307, 3736, 1004, 9991],
[2348, 1451, 3522, 2883, 3047, 6650],
[4047, 8828, 8732, 5743, 1091, 381],
])
y = 0.0
for j, alpha_j in enumerate(alpha):
t = 0
for k in range(6):
t += A[j, k] * ((x[k] - P[j, k])**2)
y -= alpha_j * np.exp(-t)
return y
def easy_objective(config, reporter):
import time
time.sleep(0.2)
for i in range(config["iterations"]):
x = np.array([config.get("x{}".format(i + 1)) for i in range(6)])
reporter(
timesteps_total=i,
hartmann6=hartmann6(x),
l2norm=np.sqrt((x**2).sum()))
time.sleep(0.02)
if __name__ == "__main__":
import argparse
from ax.service.ax_client import AxClient
parser = argparse.ArgumentParser()
parser.add_argument(
"--smoke-test", action="store_true", help="Finish quickly for testing")
args, _ = parser.parse_known_args()
ray.init()
config = {
"num_samples": 10 if args.smoke_test else 50,
"config": {
"iterations": 100,
},
"stop": {
"timesteps_total": 100
}
}
parameters = [
{
"name": "x1",
"type": "range",
"bounds": [0.0, 1.0],
"value_type": "float", # Optional, defaults to "bounds".
"log_scale": False, # Optional, defaults to False.
},
{
"name": "x2",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x3",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x4",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x5",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x6",
"type": "range",
"bounds": [0.0, 1.0],
},
]
client = AxClient(enforce_sequential_optimization=False)
client.create_experiment(
parameters=parameters,
objective_name="hartmann6",
minimize=True, # Optional, defaults to False.
parameter_constraints=["x1 + x2 <= 2.0"], # Optional.
outcome_constraints=["l2norm <= 1.25"], # Optional.
)
algo = AxSearch(client, max_concurrent=4)
scheduler = AsyncHyperBandScheduler(metric="hartmann6", mode="max")
run(easy_objective,
name="ax",
search_alg=algo,
scheduler=scheduler,
**config)
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../Cubit_login_signup_se/Cubit_login_sigunp_se.dart';
import '../Cubit_login_signup_se/State_login_sigunp_se.dart';
import '../pages/Bottom_navigation_seller/mainofseller.dart';
import '../signup_se/singup_with_email_shape_se.dart';
class login_with_email_body_se extends StatelessWidget {
var visable = Icon(
Icons.visibility,
color: Color(0xff4c5166),
);
var visableoff = Icon(
Icons.visibility_off,
color: Color(0xff4c5166),
);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (BuildContext context) => passwordCubit(),
child: BlocConsumer<passwordCubit ,PasswordState>(
listener: (context, state) { },
builder: (context, state){
return Padding(
padding: EdgeInsets.all(30),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
SizedBox(
height: 40,
),
Container(
margin: EdgeInsets.all(0.0),
child: TextField(
decoration: InputDecoration(
labelText: "E-Mail",
hintText: "Enter E-Mail",
hintStyle: TextStyle(fontSize: 20,color: Colors.white,),
labelStyle: TextStyle(fontSize: 30,color: Colors.white,),
prefixIcon: Icon(Icons.alternate_email)),
keyboardType: TextInputType.emailAddress,
),
),
Container(
margin: EdgeInsets.fromLTRB(0, 20, 20, 20),
child: TextField(
obscureText: passwordCubit.get(context).sec,
decoration: InputDecoration(
labelText: "password",
hintText: "Enter password",
prefixIcon: Icon(Icons.lock),
suffixIcon: IconButton(
onPressed: () {
passwordCubit.get(context).visableof();
},
icon: passwordCubit.get(context).sec ? visableoff : visable,
),
hintStyle: TextStyle(fontSize: 20,color: Colors.white,),
labelStyle: TextStyle(fontSize: 30,color: Colors.white,),
),
keyboardType: TextInputType.visiblePassword,
),
),
SizedBox(
height: 20.0,
),
Container(
child: Column(
children: <Widget>[
SizedBox(
height: 50,
width: double.infinity,
child: RaisedButton(
color: Color.fromRGBO(234, 231, 222, 1),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=> const mainofseller())); },
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25)),
child: Text('Log in ',
style: TextStyle(
color: Color.fromRGBO(100, 50, 77, 1),
fontSize: 15))),
)
],
),
),
SizedBox(
width: 5.0,
height: 20.0,
),
FlatButton(
onPressed: () {
Navigator.of(context).pushNamed('forget');
},
child: Text(
'Forgetyour password',
style: TextStyle(color: Colors.black, fontSize: 20),
)),
SizedBox(
height: 20.0,
),
Container(
child: Column(
children: <Widget>[
SizedBox(
height: 50,
width: double.infinity,
child: RaisedButton(
color: Color.fromRGBO(238, 75, 42, 1),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=> singup_with_email_shape_se()));
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25)),
child: Text('Sign up ',
style: TextStyle(
color: Color.fromRGBO(234, 231, 222, 1),
fontSize: 15))),
)
],
),
),
],
),
),
);
}
),
);
}
}
|
import { Environment, useChainInfo, ZERO_ADDRESS } from '@0xflair/react-common';
import {
NftToken,
TokenBalance,
useNftTokensByWallet,
useTokenBalances,
} from '@0xflair/react-data-query';
import { useERC721Symbol } from '@0xflair/react-openzeppelin';
import { BigNumber, BigNumberish, BytesLike } from 'ethers';
import _ from 'lodash';
import * as React from 'react';
import { ReactNode, useEffect, useMemo, useState } from 'react';
import { Chain, useAccount, useBalance } from 'wagmi';
import { useStreamTicketToken, useTokenStream } from '../hooks';
import { useStreamTokensInCustody } from '../hooks/useStreamTokensInCustody';
import { TokenStream } from '../types';
type StreamContextValue = {
data: {
env?: Environment;
// Resources
chainId: number;
chainInfo?: Chain;
contractAddress?: string;
stream?: TokenStream;
ticketTokens?: NftToken[];
walletAddress?: BytesLike;
// On-chain values
ticketTokenAddress?: BytesLike;
ticketTokenSymbol?: BytesLike;
streamNativeBalance?: ReturnType<typeof useBalance>['data'];
streamERC20Balances?: TokenBalance[];
tokenIdsInCustody?: BigNumberish[];
// Helpers
tokenBalances?: TokenBalance[];
ticketTokenIds?: BigNumberish[];
selectedTicketTokens?: NftToken[];
selectedTicketTokenIds?: BigNumberish[];
};
error: {
// Resources
streamError?: string | Error | null;
walletNftsError?: string | Error | null;
tokenIdsInCustodyError?: string | Error | null;
// On-chain values
ticketTokenAddressError?: string | Error | null;
ticketTokenSymbolError?: string | Error | null;
streamNativeBalanceError?: string | Error | null;
streamERC20BalancesError?: string | Error | null;
};
isLoading: {
// Resources
streamLoading?: boolean;
walletNftsLoading?: boolean;
tokenIdsInCustodyLoading?: boolean;
// On-chain values
ticketTokenAddressLoading?: boolean;
ticketTokenSymbolLoading?: boolean;
streamNativeBalanceLoading?: boolean;
streamERC20BalancesLoading?: boolean;
};
refetchTokensInCustody: () => Promise<any>;
refetchWalletNfts: () => Promise<any>;
refetchStreamERC20Balances: () => Promise<any>;
setSelectedTicketTokens: (tokens: NftToken[]) => void;
};
export const StreamContext = React.createContext<StreamContextValue | null>(
null,
);
type FunctionalChildren = (
contextValue: StreamContextValue,
) => ReactNode | ReactNode[];
type Props = {
/** Environment can be either 'prod' (default) or 'env' */
env?: Environment;
/** ChainID where the token stream is deployed */
chainId: number | string;
/** Contract address of the token stream */
contractAddress: string;
/** Optional custom wallet address to claim on behalf of */
walletAddress?: BytesLike;
/** Child elements or a factory function that returns child elements */
children: FunctionalChildren | ReactNode | ReactNode[];
};
export const StreamProvider = ({
env = Environment.PROD,
chainId: rawChainId,
contractAddress,
walletAddress,
children,
}: Props) => {
const chainId = Number(rawChainId);
const chainInfo = useChainInfo(chainId);
const { data: account } = useAccount();
const [selectedTicketTokens, setSelectedTicketTokens] =
useState<NftToken[]>();
const finalWalletAddress = walletAddress?.toString() ?? account?.address;
const {
data: stream,
error: streamError,
isLoading: streamLoading,
} = useTokenStream({
env,
chainId,
contractAddress,
});
const {
data: ticketTokenAddress_,
error: ticketTokenAddressError,
isLoading: ticketTokenAddressLoading,
} = useStreamTicketToken({
env,
chainId,
contractAddress,
});
const ticketTokenAddress =
ticketTokenAddress_?.toString() || stream?.config?.ticketToken || '';
const {
data: walletNfts,
error: walletNftsError,
isLoading: walletNftsLoading,
sendRequest: refetchWalletNfts,
} = useNftTokensByWallet({
env,
chainId,
collectionAddress: ticketTokenAddress,
walletAddress: finalWalletAddress,
enabled: Boolean(finalWalletAddress && ticketTokenAddress),
});
const {
data: tokenIdsInCustody,
error: tokenIdsInCustodyError,
isLoading: tokenIdsInCustodyLoading,
refetchTokensInCustody,
} = useStreamTokensInCustody({
chainId,
contractAddress,
ticketTokenAddress,
walletAddress: finalWalletAddress,
watch: Boolean(finalWalletAddress && ticketTokenAddress),
});
const {
data: ticketTokenSymbol,
error: ticketTokenSymbolError,
isLoading: ticketTokenSymbolLoading,
} = useERC721Symbol({
chainId,
contractAddress: ticketTokenAddress,
enabled: Boolean(ticketTokenAddress),
});
const {
data: streamNativeBalance,
error: streamNativeBalanceError,
isLoading: streamNativeBalanceLoading,
} = useBalance({
chainId,
addressOrName: contractAddress,
enabled: Boolean(contractAddress),
watch: true,
});
const {
data: streamERC20Balances,
error: streamERC20BalancesError,
isLoading: streamERC20BalancesLoading,
sendRequest: refetchStreamERC20Balances,
} = useTokenBalances({
env,
chainId,
address: contractAddress,
enabled: Boolean(contractAddress),
});
const ticketTokens = useMemo(() => {
return _.uniqBy(
[
...(walletNfts || []).map(
(token) =>
({
...token,
tokenId: BigNumber.from(token.tokenId).toString(),
} as NftToken),
),
...(tokenIdsInCustody || []).map(
(tokenId) =>
({
tokenId: BigNumber.from(tokenId).toString(),
contractAddress: ticketTokenAddress,
ownerAddress: stream?.contractAddress,
} as NftToken),
),
],
'tokenId',
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
walletNfts,
tokenIdsInCustody,
ticketTokenAddress,
stream?.contractAddress,
finalWalletAddress,
]);
const tokenBalances = useMemo(() => {
const tokens: TokenBalance[] = [];
if (streamNativeBalance && streamNativeBalance.value.gt(0)) {
tokens.push({
chainId,
ownerAddress: contractAddress as string,
balance: streamNativeBalance.value.toString(),
tokenAddress: ZERO_ADDRESS,
decimals: chainInfo?.nativeCurrency?.decimals.toString() || '18',
symbol: streamNativeBalance.symbol,
icon: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png',
name: chainInfo?.nativeCurrency?.name || streamNativeBalance.symbol,
});
}
tokens.push(
...(streamERC20Balances?.filter((token) =>
BigNumber.from(token.balance).gt(0),
) || []),
);
return tokens;
}, [
streamNativeBalance,
streamERC20Balances,
chainId,
contractAddress,
chainInfo?.nativeCurrency?.decimals,
chainInfo?.nativeCurrency?.name,
]);
const ticketTokenIds = useMemo(() => {
return ticketTokens?.map(({ tokenId }) => tokenId) || [];
}, [ticketTokens]);
useEffect(() => {
if (ticketTokens) {
setSelectedTicketTokens(ticketTokens);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ticketTokens, ticketTokens.length, walletAddress, account?.address]);
const selectedTicketTokenIds = useMemo(() => {
return selectedTicketTokens?.map(({ tokenId }) => tokenId) || [];
}, [selectedTicketTokens]);
const value = {
data: {
env,
// Resources
chainId,
chainInfo,
contractAddress,
stream,
ticketTokens,
walletAddress: finalWalletAddress,
// On-chain values
ticketTokenAddress,
ticketTokenSymbol,
streamNativeBalance,
streamERC20Balances,
tokenIdsInCustody,
// Helpers
tokenBalances,
ticketTokenIds,
selectedTicketTokens,
selectedTicketTokenIds,
},
error: {
// Resources
streamError,
walletNftsError,
// On-chain values
ticketTokenAddressError,
ticketTokenSymbolError,
streamNativeBalanceError,
streamERC20BalancesError,
tokenIdsInCustodyError,
},
isLoading: {
// Resources
streamLoading,
walletNftsLoading,
// On-chain values
ticketTokenAddressLoading,
ticketTokenSymbolLoading,
streamNativeBalanceLoading,
streamERC20BalancesLoading,
tokenIdsInCustodyLoading,
},
refetchTokensInCustody,
refetchWalletNfts,
refetchStreamERC20Balances,
setSelectedTicketTokens,
};
return React.createElement(
StreamContext.Provider,
{ value },
typeof children === 'function' ? children(value) : children,
);
};
export const useStreamContext = () => {
const context = React.useContext(StreamContext);
if (!context) throw Error('Must be used within <StreamProvider>');
return context;
};
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:filmarsivim/CustomNavBar.dart';
import 'package:flutter/material.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
class detaySayfasi extends StatefulWidget {
final DocumentSnapshot product;
const detaySayfasi({Key? key, required this.product}) : super(key: key);
@override
State<detaySayfasi> createState() => _detaySayfasiState();
}
class _detaySayfasiState extends State<detaySayfasi> {
var film = FirebaseFirestore.instance.collection('Filmler');
late YoutubePlayerController _controller;
@override
void initState() {
super.initState();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final videoUrl = widget.product['fragman'];
final videoID = YoutubePlayer.convertUrlToId(videoUrl);
_controller = YoutubePlayerController(
initialVideoId: videoID!,
flags: const YoutubePlayerFlags(
autoPlay: false,
));
}
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<QuerySnapshot>(
stream: film.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> asyncSnapshot) {
if (asyncSnapshot.hasError) {
return Center(
child: Text('Hata'),
);
}
if (asyncSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Text('Bekleyin'),
);
}
return ListView.builder(
itemCount: 1,
itemBuilder: (context, index) {
return Stack(
children: [
Opacity(
opacity: 0.4,
child: Image(
image: NetworkImage(
widget.product['afiş'],
),
height: 200,
width: double.infinity,
fit: BoxFit.cover,
),
),
SingleChildScrollView(
child: SafeArea(
child: Column(
children: [
Padding(
padding: EdgeInsets.symmetric(
vertical: 10, horizontal: 25),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
InkWell(
onTap: () {
Navigator.pop(context);
},
child: Icon(
Icons.arrow_back,
color: Colors.white,
size: 30,
),
),
],
),
),
SizedBox(
height: 100,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: FittedBox(
fit: BoxFit.fill,
child: Row(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(20),
),
child: ClipRRect(
borderRadius:
BorderRadius.circular(20),
child: Image(
image: NetworkImage(
widget.product['afiş']),
height: 250,
width: 180,
),
),
),
Column(
children: [
Text(
widget.product['FilmAd'],
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w500,
),
),
SizedBox(height: 10,),
Row(
children: [
Text(
widget.product['yıl'],
style: TextStyle(
color: Colors.white70,
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
SizedBox(width: 20,),
Icon(
Icons.star,
color: Colors.amber,
),
SizedBox(
width: 5,
),
Text(
widget.product['imdb'],
style: TextStyle(
color: Colors.white54,
fontSize: 16,
),
)
],
),
SizedBox(height: 10,),
Text(
widget.product['Tür'][0] + ' / ' +widget.product['Tür'][1],
style: TextStyle(
color: Colors.white70,
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
],
),
],
)),
),
SizedBox(
height: 20,
),
Padding(
padding: EdgeInsets.only(left: 30, right: 30),
child: Text(
widget.product['konu'],
textAlign: TextAlign.justify,
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
),
SizedBox(height: 50,),
Padding(
padding: EdgeInsets.only(left: 30,right: 30,bottom: 20),
child: YoutubePlayer(
controller: _controller,
showVideoProgressIndicator: true,
),
)
],
),
),
),
],
);
});
}),
bottomNavigationBar: CustomNavBar(),
);
}
@override
void dispose (){
super.dispose();
_controller.dispose();
}
}
|
/**
* @file game.h
* @brief Basic Game Functions.
* @author Vincent Penelle <vincent.penelle@u-bordeaux.fr>
* @details Freely inspired from Course of projet technologiques 2, 2021.
* @copyright University of Bordeaux. All rights reserved, 2022.
**/
#ifndef __GAME_H__
#define __GAME_H__
#include <stdbool.h>
/**
* @brief Standard unsigned integer type.
**/
typedef unsigned int uint;
/**
* @brief Size of the default game grid.
**/
#define DEFAULT_SIZE 7
/**
* @brief Different squares used in the game.
**/
typedef enum
{
/* states */
BLANK = 0, /**< a blank square */
LIGHTBULB = 1, /**< a light bulb */
BLACK0 = 8, /**< a numbered black wall (with 0 adjacent lights) */
BLACK1, /**< a numbered black wall (with 1 adjacent light) */
BLACK2, /**< a numbered black wall (with 2 adjacent lights) */
BLACK3, /**< a numbered black wall (with 3 adjacent lights) */
BLACK4, /**< a numbered black wall (with 4 adjacent lights) */
BLACKU, /**< an unnumbered black wall (any number of adjacent lights) */
} square;
/**
* @brief The structure pointer that stores the game state.
**/
typedef struct game_s *game;
/**
* @brief Loads a game from the file @p filename.
*
* @param filename
* @return game
*/
game game_load(char *filename);
/**
* @brief Returns a copy of @p g.
*
* @param g
* @return game
*/
game game_copy(game g);
/**
* @brief Resets the game by removing all lightbulbs.
*
* @param g
*/
void game_reset(game g);
/**
* @brief Loads a game from a description as a string as in Simon Tatham's website.
*
* @param description The description of the grid
* @param nb_rows
* @param nb_cols
* @return game
*/
game string_to_game(char *description, uint nb_rows, uint nb_cols);
/**
* @brief Prints the game @p g as text on the standard output stream.
* @details The different squares are respectively displayed as text, based on a
* square-character mapping table. If @p utf8 is set, the display will use UTF8 symbols.
* @param g the game
* @param utf8 controls set of characters used
* @pre @p g must be a valid pointer toward a game structure.
**/
void game_print(const game g, bool utf8);
/**
* @brief Prints the game @p g as text in the file whose name is @p filename.
* Format compatible with the loading function.
*
* @param g
* @param filename
*/
void game_print_to_file(game g, char *filename);
/**
* @brief The structure pointer that stores the game state.
**/
typedef struct game_s *game;
/**
* @brief Creates a new empty game with defaut size.
* @details All squares are initialized with blank squares.
* @return the created game
**/
game game_new_empty(uint n, uint m);
/**
* @brief Deletes the game and frees the allocated memory.
* @param g the game to delete
* @pre @p g must be a valid pointer toward a game structure.
**/
void game_delete(game g);
/**
* @brief Returns true if cell (@p row,@p col) is lighted by some light in @p g.
*
* @param g
* @param row
* @param col
* @return true
* @return false
*/
bool is_lighted(game g, uint row, uint col);
/**
* @brief Sets the value of a given square.
* @details This function is useful for initializing the squares of an empty
* game.
* @param g the game
* @param row row index
* @param col column index
* @param s the square value
* @pre @p g must be a valid pointer toward a game structure.
* @pre @p row < game height
* @pre @p col < game width
* @pre @p s must be a valid square value.
**/
void game_set_square(game g, uint row, uint col, square s);
/**
* @brief Gets the raw value of a given square.
* @param g the game
* @param row row index
* @param col column index
* @pre @p g must be a valid pointer toward a game structure.
* @pre @p row < game height
* @pre @p col < game width
* @return the square value
**/
square game_get_square(const game g, uint row, uint col);
/**
* @brief Test if a given square is blank.
* @param g the game
* @param row row index
* @param col column index
* @pre @p g must be a valid pointer toward a game structure.
* @pre @p row < game height
* @pre @p col < game width
* @return true if the square is blank
**/
bool game_is_blank(const game g, uint row, uint col);
/**
* @brief Test if a given square is a lightbulb.
* @param g the game
* @param row row index
* @param col column index
* @pre @p g must be a valid pointer toward a game structure.
* @pre @p row < game height
* @pre @p col < game width
* @return true if the square is a lightbulb
**/
bool game_is_lightbulb(const game g, uint row, uint col);
/**
* @brief Test if a given square is black (whether or not it is numbered).
* @param g the game
* @param row row index
* @param col column index
* @pre @p g must be a valid pointer toward a game structure.
* @pre @p row < game height
* @pre @p col < game width
* @return true if the square is black
**/
bool game_is_black(const game g, uint row, uint col);
/**
* @brief Get the number of lightbulbs expected against a black wall.
* @param g the game
* @param row row index
* @param col column index
* @pre @p g must be a valid pointer toward a game structure.
* @pre @p row < game height
* @pre @p col < game width
* @return the back wall number, or -1 if it is unumbered
**/
int game_get_black_number(const game g, uint row, uint col);
/**
* @brief Returns the number of rows of @p g.
*
* @param g
* @return uint
*/
uint game_nb_rows(game g);
/**
* @brief Returns the number of cols of @p g.
*
* @param g
* @return uint
*/
uint game_nb_cols(game g);
#endif
|
import { GetQuery, parseQuery, SetQuery } from "./parseQuery";
import { InvalidCommandError, InvalidNumberOfArgumentsError, NoCommandError } from "./errors";
import { Command } from "./Command";
describe("parseQuery", () => {
it("throws NoCommandError if query is an empty string", () => {
expect(() => parseQuery("")).toThrow(new NoCommandError());
});
it("throws InvalidCommandError if command is invalid", () => {
expect(() => parseQuery("nani")).toThrow(new InvalidCommandError());
});
it("throws InvalidNumberOfArguments if Get has no arguments", () => {
expect(() => parseQuery("get")).toThrow(new InvalidNumberOfArgumentsError());
});
it("throws InvalidNumberOfArguments if Delete has no arguments", () => {
expect(() => parseQuery("delete")).toThrow(new InvalidNumberOfArgumentsError());
});
it("throws InvalidNumberOfArguments if Set has no arguments", () => {
expect(() => parseQuery("set")).toThrow(new InvalidNumberOfArgumentsError());
});
it("throws InvalidNumberOfArguments if Set has only one argument", () => {
expect(() => parseQuery("set user:1")).toThrow(new InvalidNumberOfArgumentsError());
});
it("throws InvalidNumberOfArguments if value starts with a quote but doesn't end with it", () => {
expect(() => parseQuery('set user:1 "Violet Evergarden')).toThrow(new InvalidNumberOfArgumentsError());
});
it("returns a GetQuery if the command is Get", () => {
const expected: GetQuery = {
command: Command.Get,
key: "user:1",
};
expect(parseQuery("get user:1")).toEqual(expected);
});
it("returns a SetQuery if the command is Set", () => {
const expected: SetQuery = {
command: Command.Set,
key: "user:1",
value: "Violet",
};
expect(parseQuery('set user:1 "Violet"')).toEqual(expected);
});
it("returns a SetQuery if the command is Set and the value is unquoted", () => {
const expected: SetQuery = {
command: Command.Set,
key: "user:1",
value: "Violet",
};
expect(parseQuery("set user:1 Violet")).toEqual(expected);
});
it("returns a SetQuery if the command is Set and has spaces", () => {
const expected: SetQuery = {
command: Command.Set,
key: "user:1",
value: "Violet Evergarden",
};
expect(parseQuery('set user:1 "Violet Evergarden"')).toEqual(expected);
});
it("returns a SetQuery if the command is Set and has spaces", () => {
const expected: SetQuery = {
command: Command.Set,
key: "user:1",
value: "Violet Evergarden",
};
expect(parseQuery('set user:1 "Violet Evergarden"')).toEqual(expected);
});
});
// describe("parseQuery", () => {
// it('throws NoCommandError is query is an empty string', () => {
// expect(() => originalParseQuery('')).toThrow(new NoCommandError())
// })
// });
|
from fastapi import WebSocket, WebSocketDisconnect, Depends, HTTPException
from fastapi.routing import APIRouter
from typing import List
from collections import deque
import json
import os
router = APIRouter()
class WaitingListManager:
def __init__(self, volume_path: str):
self.volume_path = volume_path
self.load_waiting_list_from_volume()
self.websocket_clients: List[WebSocket] = []
def load_waiting_list_from_volume(self):
file_path = f"{self.volume_path}/waiting_lists.json"
if os.path.exists(file_path):
with open(file_path, 'r') as file:
data = json.load(file)
self.waiting_lists = {queue_id: deque(data[queue_id]) for queue_id in data}
else:
self.waiting_lists = {}
def save_waiting_lists_to_volume(self):
with open(f"{self.volume_path}/waiting_lists.json", 'w') as file:
print("-------saving-----")
json.dump({queue_id: list(self.waiting_lists[queue_id]) for queue_id in self.waiting_lists}, file)
def get_waiting_list(self, queue_id: str):
return list(self.waiting_lists.get(queue_id, deque()))
def add_customer(self, queue_id: str, position: str):
if queue_id not in self.waiting_lists:
self.waiting_lists[queue_id] = deque()
self.waiting_lists[queue_id].append(position)
self.update_waiting_list(queue_id)
def remove_customer(self, queue_id: str):
if queue_id in self.waiting_lists and self.waiting_lists[queue_id]:
self.waiting_lists[queue_id].popleft()
self.update_waiting_list(queue_id)
async def connect_websocket(self, websocket: WebSocket):
await websocket.accept()
self.websocket_clients.append(websocket)
def disconnect_websocket(self, websocket: WebSocket):
self.websocket_clients.remove(websocket)
def update_waiting_list(self, queue_id: str):
self.save_waiting_lists_to_volume()
for client in self.websocket_clients:
try:
client.send_text("update")
except Exception as e:
print(e)
waiting_list_manager = WaitingListManager(volume_path="/app/data")
@router.websocket("/ws/{queue_id}")
async def websocket_endpoint(queue_id: str, websocket: WebSocket):
await waiting_list_manager.connect_websocket(websocket)
try:
while True:
await websocket.receive_text()
except WebSocketDisconnect:
waiting_list_manager.disconnect_websocket(websocket)
# Uncomment the following route if you want to use the commented-out POST endpoint
# @router.post("/add-to-queue/{queue_id}/{position}")
# async def add_to_queue(queue_id: str, position: str, waiting_list_manager: WaitingListManager = Depends()):
# waiting_list_manager.add_customer(queue_id, position)
# return {"message": f"User {position} added to the waiting list for employee {queue_id}."}
|
import 'package:flutter/material.dart';
import 'package:toonflix/widgets/custom_button.dart';
import 'package:toonflix/widgets/money_card.dart';
void main() {
runApp(const App());
}
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
bool viewAll = false;
void onPressed() {
setState(() {
viewAll = !viewAll;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: const Color(0xFF181818),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 24.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 32.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
const Text(
'Hey, Jatie',
style: TextStyle(
color: Colors.white,
fontSize: 24.0,
fontWeight: FontWeight.bold,
),
),
Text(
'Welcome back',
style: TextStyle(
color: Colors.white.withOpacity(0.5),
),
),
],
),
],
),
const SizedBox(
height: 36.0,
),
Text(
'Total Balance',
style: TextStyle(
color: Colors.white.withOpacity(0.5),
fontSize: 20.0,
),
),
const Text(
'\$1 234 567',
style: TextStyle(
color: Colors.white,
fontSize: 36.0,
fontWeight: FontWeight.bold,
),
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
const CustomButton(
backgroundColor: Color(0xFFF2B33A),
textData: 'Transfer',
textColor: Colors.black,
),
CustomButton(
backgroundColor: Colors.grey[900],
textData: 'Request',
textColor: Colors.white,
),
],
),
const SizedBox(
height: 48.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
const Text(
'Wallets',
style: TextStyle(
color: Colors.white,
fontSize: 28.0,
fontWeight: FontWeight.bold,
),
),
GestureDetector(
onTap: onPressed,
child: viewAll
? const TextWidget()
: Text(
'View All',
style: TextStyle(
color: Colors.white.withOpacity(0.5),
),
),
),
],
),
const SizedBox(
height: 16.0,
),
const MoneyCard(
name: 'Euro',
amount: '6 248',
code: 'EUR',
icon: Icons.euro_symbol,
),
MoneyCard(
name: 'Dollar',
amount: '55 622',
code: 'USD',
icon: Icons.attach_money,
isInvert: true,
offset: Offset(0, viewAll ? 0 : -24),
),
MoneyCard(
name: 'Bitcoin',
amount: '28',
code: 'BTC',
icon: Icons.currency_bitcoin,
offset: Offset(0, viewAll ? 0 : -48),
),
],
),
),
),
),
);
}
}
class TextWidget extends StatefulWidget {
const TextWidget({
super.key,
});
@override
State<TextWidget> createState() => _TextWidgetState();
}
class _TextWidgetState extends State<TextWidget> {
@override
void initState() {
super.initState();
print('initState');
}
@override
void dispose() {
super.dispose();
print('dispose');
}
@override
Widget build(BuildContext context) {
print('build');
return Text(
'View Less',
style: TextStyle(
color: Colors.white.withOpacity(0.5),
),
);
}
}
|
class FeedingsController < ApplicationController
before_action :set_feeding, only: %i[show edit update destroy]
def index
@q = Feeding.ransack(params[:q])
@feedings = @q.result(distinct: true).includes(:dog).page(params[:page]).per(10)
end
def show; end
def new
@feeding = Feeding.new
end
def edit; end
def create
@feeding = Feeding.new(feeding_params)
if @feeding.save
message = "Feeding was successfully created."
if Rails.application.routes.recognize_path(request.referer)[:controller] != Rails.application.routes.recognize_path(request.path)[:controller]
redirect_back fallback_location: request.referer, notice: message
else
redirect_to @feeding, notice: message
end
else
render :new
end
end
def update
if @feeding.update(feeding_params)
redirect_to @feeding, notice: "Feeding was successfully updated."
else
render :edit
end
end
def destroy
@feeding.destroy
message = "Feeding was successfully deleted."
if Rails.application.routes.recognize_path(request.referer)[:controller] != Rails.application.routes.recognize_path(request.path)[:controller]
redirect_back fallback_location: request.referer, notice: message
else
redirect_to feedings_url, notice: message
end
end
private
def set_feeding
@feeding = Feeding.find(params[:id])
end
def feeding_params
params.require(:feeding).permit(:dog_id, :amount, :food_name)
end
end
|
const express = require('express');
const router = express.Router();
const uuid = require('uuid');
const sampleJson = require('../../public/sample_json');
router.get('/', (req, res) => {
res.json(sampleJson);
});
router.get('/:id', (req, res) => {
if (found) {
res.json(sampleJson.filter((entry) => entry.Id === parseInt(req.params.id)));
} else {
res.status(400).json({ msg: `sample with Id ${req.params.id} not found` });
}
});
router.post('/', (req, res) => {
if (!req.body.Name || !req.body.Age) {
res.status(400).json({ msg: `Invalid email or name; received ${req.body.Name} ${req.body.Age}` });
} else {
const newSample = {
Id: uuid.v4(),
Name: req.body.Name,
Age: req.body.Age
};
sampleJson.push(newSample);
res.send(newSample);
}
});
router.put('/:id', (req, res) => {
var index = sampleJson.findIndex((entry) => entry.Id === parseInt(req.params.id));
if (!index) {
res.status(404).json({ msg: `Id ${req.params.id} is invalid` });
} else if (!req.body.Name && !req.body.Age) {
res.status(400).json({ msg: `Invalid email or name; received ${req.body.Name} ${req.body.Age}` });
} else {
const newSample = {
Id: parseInt(req.params.id),
Name: req.body.Name || sampleJson[index].Name,
Age: req.body.Age || sampleJson[index].Age
};
sampleJson[index] = newSample;
res.json(sampleJson);
}
});
module.exports = router;
|
/*
* Copyright 2022 AppDynamics Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opentelemetry.contrib.generator.telemetry;
import io.opentelemetry.contrib.generator.core.dto.ResourceDefinition;
import io.opentelemetry.contrib.generator.core.dto.GeneratorResource;
import io.opentelemetry.contrib.generator.telemetry.dto.GeneratorInput;
import io.opentelemetry.contrib.generator.telemetry.logs.LogsGenerator;
import io.opentelemetry.contrib.generator.telemetry.metrics.MetricsGenerator;
import io.opentelemetry.contrib.generator.telemetry.traces.TracesGenerator;
import io.opentelemetry.contrib.generator.telemetry.transport.PayloadHandler;
import io.opentelemetry.contrib.generator.telemetry.transport.TransportStorage;
import io.opentelemetry.contrib.generator.core.ResourceModelGenerator;
import io.opentelemetry.contrib.generator.core.RuntimeModificationsThread;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Main API class if using the Telemetry Generator as a Java library in your code.
*/
@Slf4j
public class TelemetryGenerator {
private final GeneratorInput input;
private final PayloadHandler payloadHandler;
private final String requestID;
@Getter
private final TransportStorage transportStorage;
private Map<String, List<GeneratorResource>> resourceModel;
@Getter
private GeneratorsMonitor generatorsMonitor;
public TelemetryGenerator(GeneratorInput input, PayloadHandler payloadHandler) {
this(input, payloadHandler, RandomStringUtils.randomAlphanumeric(32));
}
public TelemetryGenerator(GeneratorInput input, PayloadHandler payloadHandler, String requestID) {
this(input, payloadHandler, requestID, false);
}
public TelemetryGenerator(GeneratorInput input, PayloadHandler payloadHandler, boolean storePayloadStatuses) {
this(input, payloadHandler, RandomStringUtils.randomAlphanumeric(32), storePayloadStatuses);
}
public TelemetryGenerator(GeneratorInput input, PayloadHandler payloadHandler, String requestID, boolean storePayloadStatuses) {
this.input = input;
this.payloadHandler = payloadHandler;
this.requestID = requestID;
this.transportStorage = storePayloadStatuses ? new TransportStorage() : null;
}
public void runGenerator() {
input.validate(requestID);
log.info("Received data generation request with metrics = (" + input.isHasMetrics() + "), logs = (" +
input.isHasLogs() + "), traces = (" + input.isHasTraces() + ")");
ResourceModelProvider.putResourceModel(requestID, getResourceModel());
if (input.isHasMetrics()) {
var metricsGenerator = new MetricsGenerator(input.getMetricDefinitions(), payloadHandler, requestID, transportStorage);
metricsGenerator.runGenerator();
}
if (input.isHasTraces()) {
input.getTraceDefinitions().initTrees(requestID);
var tracesGenerator = new TracesGenerator(input.getTraceDefinitions(), payloadHandler, requestID, transportStorage);
tracesGenerator.runGenerator();
}
if (input.isHasLogs()) {
var logsGenerator = new LogsGenerator(input.getLogDefinitions(), payloadHandler, requestID, transportStorage);
logsGenerator.runGenerator();
}
ScheduledExecutorService runtimeModsExecutor = null;
if (input.getResourceDefinitions().isHasRuntimeModifications()) {
var runtimeModifications = new RuntimeModificationsThread(requestID, input.getResourceDefinitions().getResources().stream()
.map(eachType -> CollectionUtils.emptyIfNull(eachType.getRuntimeModifications()))
.flatMap(Collection::stream).collect(Collectors.toList()));
runtimeModsExecutor = Executors.newScheduledThreadPool(1);
runtimeModsExecutor.scheduleAtFixedRate(runtimeModifications, 0, 2000, TimeUnit.MILLISECONDS);
}
generatorsMonitor = new GeneratorsMonitor(requestID, input);
generatorsMonitor.monitorThreads();
if (input.getResourceDefinitions().isHasRuntimeModifications() && runtimeModsExecutor != null) {
runtimeModsExecutor.shutdown();
}
}
public Map<String, List<GeneratorResource>> getResourceModel() {
if (resourceModel == null) {
Map<String, ResourceDefinition> resourcesMap = input.getResourceDefinitions().getResources().stream()
.collect(Collectors.toMap(ResourceDefinition::getName, Function.identity()));
var resourceModelGenerator = new ResourceModelGenerator(resourcesMap, requestID);
resourceModel = resourceModelGenerator.getResourceModel();
}
return resourceModel;
}
}
|
from .database import db
from flask_login import UserMixin
class Users(UserMixin, db.Model):
__tablename__ = "users"
user_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_name = db.Column(db.String(200), unique=True, nullable=False)
password = db.Column(db.String(200), nullable=False)
role = db.Column(db.String(200), nullable=False)
def get_id(self):
return str(self.user_id)
class Sections(db.Model):
__tablename__ = "sections"
section_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
section_name = db.Column(db.String(200), nullable=False)
class Products(db.Model):
__tablename__ = "products"
product_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
product_name = db.Column(db.String(200), nullable=False)
manufacture_date = db.Column(db.Date)
expiry_date = db.Column(db.Date)
rate_per_unit = db.Column(db.Float, nullable=False)
unit = db.Column(db.String(200), nullable=False, default='Rs')
section_id = db.Column(db.Integer, db.ForeignKey('sections.section_id', onupdate='CASCADE'))
section = db.relationship('Sections', backref=db.backref('products', lazy=True))
quantity_available = db.Column(db.Integer, db.CheckConstraint('quantity_available >= 0', name='check_min_quantity') , nullable=False)
class CartItem(db.Model):
__tablename__ = "cartitems"
cart_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id', onupdate='CASCADE'), nullable=False)
item_id = db.Column(db.Integer, db.ForeignKey('products.product_id', onupdate='CASCADE'), nullable=False)
quantity = db.Column(db.Integer, nullable=False, default=1)
item = db.relationship('Products', backref=db.backref('products', lazy=True))
class Orders(db.Model):
__tablename__ = "orders"
order_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id', onupdate='CASCADE'), nullable=False)
item_id = db.Column(db.Integer, db.ForeignKey('products.product_id', onupdate='CASCADE'), nullable=False)
quantity = db.Column(db.Integer, nullable=False, default=1)
item = db.relationship('Products', backref=db.backref('Items', lazy=True))
|
import React, { useEffect } from 'react';
import { Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper } from '@mui/material';
import { useTheme } from '@mui/material/styles';
import Chart from 'chart.js/auto';
import { Line } from 'react-chartjs-2';
const groups = [
{ id: 1, name: '1A', avgGrade: 'A', studentsPlaying: 10, aprobados: 15, reprobados: 15,},
{ id: 2, name: '1B', avgGrade: 'B', studentsPlaying: 5, aprobados: 14, reprobados: 16,},
{ id: 3, name: '2A', avgGrade: 'C', studentsPlaying: 23, aprobados: 10, reprobados: 20,},
{ id: 4, name: '2B', avgGrade: 'A', studentsPlaying: 15, aprobados: 25, reprobados: 5,}
];
const createPieChart = (canvas, group, theme) => {
const existingChart = Chart.getChart(canvas);
if (existingChart) {
existingChart.destroy();
}
const chartData = {
labels: ['Aprobados', 'Reprobados'],
datasets: [{
data: [group.aprobados, group.reprobados],
backgroundColor: [
theme.palette.primary.main,
theme.palette.secondary.main,
theme.palette.error.main,
],
}],
};
new Chart(canvas, {
type: 'pie',
data: chartData,
});
};
const Groups = () => {
const theme = useTheme();
useEffect(() => {
groups.forEach((group) => {
const canvas = document.getElementById(`pieChart-${group.id}`);
if (canvas) {
createPieChart(canvas, group, theme);
}
});
}, [theme]);
return (
<>
<Typography variant="h4" component="h1" gutterBottom>
Grupos
</Typography>
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell style={{ backgroundColor: theme.palette.primary.main, color: theme.palette.primary.contrastText }}>Grupo</TableCell>
<TableCell style={{ backgroundColor: theme.palette.primary.main, color: theme.palette.primary.contrastText }}>Calificación Promedio</TableCell>
<TableCell style={{ backgroundColor: theme.palette.primary.main, color: theme.palette.primary.contrastText }}>Estudiantes Jugando</TableCell>
</TableRow>
</TableHead>
<TableBody>
{groups.map((group) => (
<TableRow key={group.id} style={{ backgroundColor: theme.palette.background.default }}>
<TableCell>{group.name}</TableCell>
<TableCell>{group.avgGrade}</TableCell>
<TableCell>{group.studentsPlaying}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
<div style={{ display: 'flex', justifyContent: 'space-around', marginTop: "10%"}}>
{groups.map((group) => (
<div key={group.id}>
<canvas id={`pieChart-${group.id}`} width="100" height="100"></canvas>
<Typography variant="body2" align="center">{`Group ${group.name}`}</Typography>
</div>
))}
</div>
</>
);
};
export default Groups
|
#!/usr/bin/env python3.10
# pylint: disable=invalid-name
# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring
import argparse
import sys
from argparse import Namespace
from lib import run_with_state # type: ignore
CHECKS = (
("format python using black", ("poetry", "run", "black", "./")),
("format python using isort", ("poetry", "run", "isort", "./")),
("check python using flake8", ("poetry", "run", "flake8", "./")),
("check python using bandit", ("poetry", "run", "bandit", "./")),
("check python using mypy", ("poetry", "run", "mypy", "scripts", "src")),
("check python using pylint", ("poetry", "run", "pylint", "scripts", "src")),
("check yaml using yamllint", ("poetry", "run", "yamllint", "./")),
)
def parse_args() -> Namespace:
parser = argparse.ArgumentParser(
prog="lint-codebase",
description="Lint the codebase",
)
return parser.parse_args()
def main() -> int:
results = [run_with_state(message, command) for message, command in CHECKS]
return 1 if sum(results) else 0
if __name__ == "__main__":
kwargs = parse_args()
sys.exit(main(**kwargs.__dict__))
|
// create a type name with a string
type Data = {name: string}
let student: Data = {
name: "Rehan"
}
// create a type age with a number
type Data1 = {age:number}
let person: Data1 = {
age: 42
}
// create a type isFetching with boolean
type Data2 = {isFetching: boolean}
let person2: Data2 = {
isFetching: true
}
// create an array of numbers
let arr: number[] = [12,25,25,42]
let arr2: Array<number> = [10,15,14]
// create an array of strings (using array constructor generic type)
let arr3: string[] = ["a", "b", "c"]
let arr4: Array<string> = ["a", "b", "c"]
// create a tuple , which keeps a string as the first value, and boolean as the second
let eomployee: [string, boolean] = ["steve", true]
// create an enum
// it should have User, SuperUser, Admin, SuperAdmin
enum Card {
User = 'Ram',
SuperUser = "Shyam",
Admin = 'Aniket',
SuperAdmin = 'Raghav'
};
// create a function that takes 2 arguments, x, y both numbers
//it should return the product of the 2 numbers
function product(x:number,y:number): number{
return x*y;
}
const product2 = (x:number,y:number):number => {
return x*y;
}
// create a function that takes 2 arguments, x ,y both numbers,
// it should divide output ( x / y )
function divide(x:number,y:number): number{
return x/y;
}
const divide2 = (x:number,y:number):number => {
return x/y;
}
console.log(divide2(12,25));
// create a function that takes a name and prints it without returning anything
const printSome = ({name, prints}): void => {
console.log(`${name} ${prints}`)
}
|
// Copyright Marina Oprea 313CAb 2022-2023
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "op_on_color.h"
#include "struct.h"
#include "auxiliars.h"
#include "commands.h"
// function allocates color matrix
// and returns pointer to its address
colored_image **alloc_matrix_color(int height, int width)
{
colored_image **a;
a = malloc(height * sizeof(colored_image *));
if (!a) {
fprintf(stderr, "malloc() failed\n");
return NULL;
}
for (int i = 0; i < height; i++) {
a[i] = malloc(width * sizeof(colored_image));
if (!a[i]) {
fprintf(stderr, "malloc() failed\n");
i--;
while (i >= 0) {
free(a[i]);
i--;
}
free(a);
return NULL;
}
}
return a;
}
// function loads color matrix from file
colored_image **load_color(char *filename, int type, int *height, int *width)
{
colored_image **image;
if (type % 10 == 0) {
FILE *in = fopen(filename, "rt");
if (!in)
return NULL;
unsigned char c;
int auxr, auxg, auxb;
fscanf(in, "P%c%d%d%d\n", &c, width, height, &auxr);
image = alloc_matrix_color(*height, *width);
if (!image)
return NULL;
for (int i = 0; i < *height; i++)
for (int j = 0; j < *width; j++) {
fscanf(in, "%d%d%d", &auxr, &auxg, &auxb);
image[i][j].R = (unsigned char)auxr;
image[i][j].G = (unsigned char)auxg;
image[i][j].B = (unsigned char)auxb;
}
fclose(in);
} else {
FILE *in = fopen(filename, "r");
if (!in)
return NULL;
int aux;
int aux2;
fscanf(in, "P%d%d%d%d", &aux2, width, height, &aux);
image = alloc_matrix_color(*height, *width);
if (!image)
return NULL;
fseek(in, 1, SEEK_CUR);
for (int i = 0; i < *height; i++)
for (int j = 0; j < *width; j++) {
fread(&image[i][j].R, sizeof(unsigned char), 1, in);
fread(&image[i][j].G, sizeof(unsigned char), 1, in);
fread(&image[i][j].B, sizeof(unsigned char), 1, in);
}
fclose(in);
}
return image;
}
// function frees allocated memory for color matrix
void free_matrix_color(colored_image **a, int m)
{
for (int i = 0; i < m; i++)
free(a[i]);
free(a);
}
// function saves color matrix to file given by name
void save_color(char *filename, colored_image **im, int height, int width,
int ascii)
{
if (ascii == 1) {
FILE *out = fopen(filename, "wt");
fprintf(out, "P3\n%d %d\n", width, height);
fprintf(out, "%d\n", MAX_VAL);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++)
fprintf(out, "%hhu %hhu %hhu ", im[i][j].R, im[i][j].G,
im[i][j].B);
fprintf(out, "\n");
}
fclose(out);
} else {
FILE *out = fopen(filename, "w");
fprintf(out, "P6\n%d %d\n%d\n", width, height, MAX_VAL);
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++) {
fwrite(&im[i][j].R, sizeof(unsigned char), 1, out);
fwrite(&im[i][j].G, sizeof(unsigned char), 1, out);
fwrite(&im[i][j].B, sizeof(unsigned char), 1, out);
}
fclose(out);
}
}
// function that returns pixel value corresponding to image kernel application
// on (x, y)-upper-lefted corner
colored_image apply_pixel(filter *f, int type, colored_image **im, int x, int y)
{
colored_image ans;
double val1 = 0., val2 = 0., val3 = 0.;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
val1 += (double)((int)im[x + i][y + j].R * f[type].kernel[i][j]);
val2 += (double)((int)im[x + i][y + j].G * f[type].kernel[i][j]);
val3 += (double)((int)im[x + i][y + j].B * f[type].kernel[i][j]);
}
val1 = round(val1 / (double)f[type].divide);
val2 = round(val2 / (double)f[type].divide);
val3 = round(val3 / (double)f[type].divide);
ans.R = clamp(val1, 0, MAX_VAL);
ans.G = clamp(val2, 0, MAX_VAL);
ans.B = clamp(val3, 0, MAX_VAL);
return ans;
}
// function crops color matrix
// allocates memory for the cropped version, deallocates the old one
// and return address of new matrix
// function updates current selection to the full cropped image
colored_image **crop_color(colored_image **im, int *height, int *width,
int *x1, int *y1, int *x2, int *y2)
{
colored_image **new_im = alloc_matrix_color(*y2 - *y1, *x2 - *x1);
for (int i = *y1; i < *y2; i++)
for (int j = *x1; j < *x2; j++)
new_im[i - *y1][j - *x1] = im[i][j];
free_matrix_color(im, *height);
*height = *y2 - *y1;
*width = *x2 - *x1;
select_all(x1, y1, x2, y2, *height, *width, 0);
return new_im;
}
// function rotates the full matrix and returns a pointer to its new memory
// address; it also deallocates memory of the old matrix
colored_image **rotate_full_color(colored_image **im, int *height, int *width)
{
colored_image **im_new = alloc_matrix_color(*width, *height);
for (int i = 0; i < *height; i++)
for (int j = 0; j < *width; j++)
im_new[j][*height - i - 1] = im[i][j];
free_matrix_color(im, *height);
swap_int_values(height, width);
return im_new;
}
// function that calls full rotation function in case of full selection
// or rotates a selection of the image
void rotate_color(colored_image ***im, int *x1, int *y1, int *x2, int *y2,
int *height, int *width)
{
if (*x1 == 0 && *x2 == *width && *y1 == 0 && *y2 == *height) {
*im = rotate_full_color(*im, height, width);
swap_int_values(x2, y2);
return;
}
int dim = *x2 - *x1;
colored_image **aux = alloc_matrix_color(dim, dim);
for (int i = *y1; i < *y2; i++)
for (int j = *x1; j < *x2; j++)
aux[j - *x1][dim - (i - *y1) - 1] = (*im)[i][j];
for (int i = *y1; i < *y2; i++)
for (int j = *x1; j < *x2; j++)
(*im)[i][j] = aux[i - *y1][j - *x1];
free_matrix_color(aux, dim);
}
|
//
// CoreDataManager.swift
// 12Zapisok
//
// Created by Anton Makarov on 13.09.2021.
// Copyright © 2021 A.Makarov. All rights reserved.
//
import CoreData
final class CoreDataManager: NSObject {
var managedObjectContext: NSManagedObjectContext?
var storeName = "CoreDataStore"
static let shared = CoreDataManager()
override init() {
super.init()
managedObjectContext = persistentContainer.viewContext
}
// MARK: - Core Data Stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: storeName)
container.loadPersistentStores { _, error in
if let error = error as NSError? {
fatalError("Error in loading persistent store \(error), \(error.userInfo)")
}
}
return container
}()
// MARK: - Core Data Saving Support
func saveContext () {
do {
try managedObjectContext?.save()
} catch let saveError as NSError {
fatalError("SaveContext error: \(saveError.localizedDescription)")
}
}
func fetchObjects<T: NSManagedObject>(entityClass: T.Type, predicate: NSPredicate? = nil) -> [T] {
let fetchRequest = NSFetchRequest<T>(entityName: T.entityName())
fetchRequest.predicate = predicate
do {
return try managedObjectContext?.fetch(fetchRequest) ?? []
} catch {
Logger.error(msg: error.localizedDescription)
return []
}
}
func fetchObject<T: NSManagedObject>(entityClass: T.Type, predicate: NSPredicate? = nil) -> T? {
return fetchObjects(entityClass: T.self, predicate: predicate).last
}
func fetchObjectById<T: NSManagedObject>(entityClass: T.Type, id: Int) -> T? {
let predicate = NSPredicate(format: "id = %ld", id)
return fetchObjects(entityClass: T.self, predicate: predicate).last
}
}
extension NSManagedObject {
public class func entityName() -> String {
let name = NSStringFromClass(self)
return name.components(separatedBy: ".").last ?? name
}
}
|
# Chapter 2.01 - Enabling the SAP Fiori Elements Flexible Programming Model
The following series of chapters (part 2 - starting with this chapter 2.01) introduces the **SAP Fiori elements flexible programming model**, which bridges the gap between freestyle UI5 development and [SAP Fiori elements](https://ui5.sap.com/#/topic/03265b0408e2432c9571d6b3feb6b1fd).
The application we built so far in part 1 used a freestyle approach, meaning we built our own custom view with specific controls and controller logic. In contrast to that, SAP Fiori elements provide predefined [floorplans](https://ui5.sap.com/#/topic/797c3239b2a9491fa137e4998fd76aa7.html) (think "application layouts") for common business application use cases. Using this approach, the framework (SAPUI5) generates an application by interpreting metadata that is part of the consumed OData backend services. The specific parts of OData metadata that define the way a backend service is represented in frontend applications are called "annotations" and are mandatory when using SAP Fiori elements.
Usually you would decide before starting a new development which of the two approaches you want to use to build your application. The [SAP Fiori Tools](https://help.sap.com/docs/SAP_FIORI_tools/17d50220bcd848aa854c9c182d65b699/2d8b1cb11f6541e5ab16f05461c64201.html?locale=en-US) provide guided application generators for both approaches.

However, the situation is not exactly black and white, as the [SAP Fiori elements flexible programming model](https://sapui5.hana.ondemand.com/test-resources/sap/fe/core/fpmExplorer/index.html#/overview/introduction) provides building blocks (macros), which are metadata-driven UI controls that can be used in any (freestyle) SAPUI5 application. This flexible programming model is perfect for our use case, as we already have a working freestyle UI5 application and solely want to enhance it - while learning about SAP Fiori elements and OData annotations along the way. The instructions given in this chapter align with the [the official documentation](https://sapui5.hana.ondemand.com/test-resources/sap/fe/core/fpmExplorer/index.html#/buildingBlocks/guidance/guidanceCustomApps), but are more detailed and more specific to our use case.
At the end of this chapter we will have enabled the Fiori elements flexible programming model for our custom UI5 application. Essentially, we will have turned our application into an SAP Fiori elements application.
## Steps
[1. Duplicate the existing application](#1-duplicate-the-existing-application)<br>
[2. Extend the `sap/fe/core/AppComponent` instead of the `sap/ui/core/UIComponent`](#2-extend-the-sapfecoreappcomponent-instead-of-the-sapuicoreuicomponent)<br>
[3. Use OData V4](#3-use-odata-v4)<br>
[4. Add OData V4 model settings](#4-add-odata-v4-model-settings)<br>
[5. Add routing to the `webapp/manifest.json`](#5-add-routing-to-the-webappmanifestjson)<br>
[6. Remove the `rootView` from the `webapp/manifest.json`](#6-remove-the-rootview-from-the-webappmanifestjson)<br>
[7. Add dependencies to the `webapp/manifest.json`](#7-add-dependencies-to-the-webappmanifestjson)<br>
[8. Use SAPUI5 instead of OpenUI5](#8-use-sapui5-instead-of-openui5)<br>
[9. Rebuild the `webapp/view/App.view.xml`](#9-rebuild-the-webappviewappviewxml)<br>
[10. Use the `sap/fe/core/PageController` instead of the `sap/ui/core/mvc/Controller`](#10-use-the-sapfecorepagecontroller-instead-of-the-sapuicoremvccontroller)<br>
[11. Change `ui5.yaml` configuration](#11-change-ui5yaml-configuration)<br>
[12. Test the new app](#12-test-the-new-app)<br>
### 1. Duplicate the existing application
➡️ Duplicate your existing UI5 application living in `webapp/`. Then rename the copy to `freestyle-webapp/`.
This is what our project's structure now looks like:
```text
- bookshop/
+ node_modules/
+ freestyle-webapp/
+ webapp/
- manifest.yaml
- package-lock.json
- package.json
- ui5.yaml
- xs-app.json
```
We duplicated our existing application to preserve the progress we made in the previous chapters (`freestyle-webapp/`). The structural changes we are about to make to our application require us to delete parts of the application (and thus the progress we made).
### 2. Extend the `sap/fe/core/AppComponent` instead of the `sap/ui/core/UIComponent`
➡️ Replace the content of the existing `webapp/Component.js` with the following code:
```javascript
sap.ui.define([
"sap/fe/core/AppComponent",
], function (AppComponent) {
"use strict"
return AppComponent.extend(
"sap.codejam.Component", {
metadata : {
"interfaces": [
"sap.ui.core.IAsyncContentCreation"
],
manifest: "json"
},
init : function () {
AppComponent.prototype.init.apply(
this,
arguments
)
}
})
})
```
We now use and extend the `sap/fe/core/AppComponent` instead of the `sap/ui/core/UIComponent` to make sure our [component](/chapters/chapter001/readme.md#4-create-an-webappcomponentjs-file) runs within the SAP Fiori elements framework.
### 3. Use OData V4
The SAP Fiori elements Flexible Programming Model is only available for OData V4, meaning it's not compatible with the OData service we are currently consuming, which is version 2 of the protocol. Luckily, our remote backend service provide endpoints for both V2 and V4, so all we have to do is change the data source in our `webapp/manifest.json`.
➡️ Replace the `sap.app.dataSources` section of the `webapp/manifest.json` with the following code:
```json
,
"dataSources": {
"remoteBookshop": {
"uri": "/browse/",
"type" : "OData",
"settings" : {
"odataVersion" : "4.0"
}
}
}
```
We changed the OData uri (different endpoint of the remote bookshop service) and changed the version to V4.
### 4. Add OData V4 model settings
➡️ Replace the default model in the `sap.ui5.models` section of the `webapp/manifest.json` with the following code:
```json
"": {
"dataSource": "remoteBookshop",
"settings": {
"synchronizationMode": "None",
"operationMode": "Server",
"autoExpandSelect": true,
"earlyRequests": true
}
}
```
We added a few settings to our default model that are specific to OData V4. Let's go through them step-by-step:
- We set the `operationMode` to `Server`, which is mandatory for filtering and sorting queries with OData V4.
- We set the `synchronizationMode` to `None`, which is also mandatory for OData V4.
- `"autoExpandSelect": true` makes sure the `$expand` and `$select` OData query parameters are automatically being used, which we need for nested entities like `Genre` (https://developer-advocates-free-tier-central-hana-cloud-instan3b540fd6.cfapps.us10.hana.ondemand.com/browse/Books?$expand=genre).
- `"earlyRequests": true` makes sure the OData service metadata is called as early as possible.
### 5. Add routing to the `webapp/manifest.json`
➡️ Add the following code to the `sap.ui5` section of the `webapp/manifest.json`:
```json
,
"routing": {
"routes": [
{
"pattern": ":?query:",
"name": "mainPage",
"target": "mainPage"
}
],
"targets": {
"mainPage": {
"type": "Component",
"id": "mainPage",
"name": "sap.fe.core.fpm",
"options": {
"settings": {
"viewName": "sap.codejam.view.App",
"entitySet": "Books",
"navigation": {}
}
}
}
}
}
```
We added a new `sap.ui5.routing` section to our application descriptor file in which we define all `routes` (think "pages") our application contains. Currently we have just one route and target, but that will change shortly. Let's go through the additions step by step:
- We describe a `pattern` for our route, which allows us to access it by attaching it to the URL of our application.
- Our route also has a `name` and a `target`, which points to the `mainPage` object we define in the `targets` section.
- The `targets` section is where we provide content information for the pages of our app. If we where to follow a freestyle UI5 approach, we could directly point to an xml file at this point, but within the SAP Fiori elements framework we specify the type as `Component` and use `sap.fe` templates for the pages.
- For our `mainPage` we use the `sap.fe.core.fpm` template component, which allows us to point to our own `sap.codejam.view.App` xml view, but have it run inside the SAP Fiori elements flexible programming model. We define the main `entitySet` (coming from the backend OData service) we want to use on the page. We leave the `navigation` section empty for now, as we currently only have one route.
### 6. Remove the `rootView` from the `webapp/manifest.json`
➡️ Remove the entire `rootView` section (inside `sap.ui5`) from the `webapp/manifest.json` file.
It was mandatory to remove the `rootView` from our application descriptor as we now have a dedicated `sap.ui5.routing` section and want the SAP Fiori elements framework to handle the routing, including embedding our views.
### 7. Add dependencies to the `webapp/manifest.json`
➡️ Add the following code at the beginning of the `sap.ui5` section of the `webapp/manifest.json`:
```json
,
"dependencies": {
"minUI5Version": "1.60.0",
"libs": {
"sap.ui.core": {},
"sap.m": {},
"sap.fe.macros": {},
"sap.fe.templates": {}
}
}
```
We added SAP Fiori elements related libraries to our dependencies to make sure they are preloaded by the SAPUI5 (performance optimizations) and are available at runtime.
This is what our `webapp/manifest.json` now looks like:
```json
{
"sap.app": {
"id": "codejam",
"type": "application",
"title": "CodeJam Bookshop",
"applicationVersion": {
"version": "1.0.0"
},
"dataSources": {
"remoteBookshop": {
"uri": "/browse/",
"type" : "OData",
"settings" : {
"odataVersion" : "4.0"
}
}
}
},
"sap.ui5": {
"models": {
"": {
"dataSource": "remoteBookshop",
"settings": {
"synchronizationMode": "None",
"operationMode": "Server",
"autoExpandSelect": true,
"earlyRequests": true
}
},
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "sap.codejam.i18n.i18n"
}
}
},
"resources": {
"css": [
{
"uri": "css/style.css"
}
]
},
"routing": {
"routes": [
{
"pattern": ":?query:",
"name": "mainPage",
"target": "mainPage"
}
],
"targets": {
"mainPage": {
"type": "Component",
"id": "mainPage",
"name": "sap.fe.core.fpm",
"options": {
"settings": {
"viewName": "sap.codejam.view.App",
"entitySet": "Books",
"navigation": {}
}
}
}
}
},
"dependencies": {
"minUI5Version": "1.60.0",
"libs": {
"sap.ui.core": {},
"sap.m": {},
"sap.fe.macros": {},
"sap.fe.templates": {}
}
}
}
}
```
### 8. Use SAPUI5 instead of OpenUI5
➡️ Replace `openui5` with `sapui5` in the `webapp/index.html` and specify a version, so the bootstrapping (the script tag) looks like this:
```html
<script
id="sap-ui-bootstrap"
src="https://sapui5.hana.ondemand.com/1.108/resources/sap-ui-core.js"
data-sap-ui-theme="sap_horizon"
data-sap-ui-async="true"
data-sap-ui-libs="sap.m"
data-sap-ui-compatVersion="edge"
data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
data-sap-ui-resourceroots='{
"sap.codejam": "./"
}'>
</script>
```
- We moved from OpenUI5 to SAPUI5, because SAP Fiori elements are not available and not part of OpenUI5. Check the [base readme](/README.md#sapui5-vs-openui5) to learn more about the differences between SAPUI5 and OpenUI5.
- We also specified a [long-term maintenance version](https://sapui5.hana.ondemand.com/versionoverview.html) of SAPUI5. Interestingly, we didn't specify a patch number, which means we will always load the latest patch ([patch-level independent bootstrap](https://blogs.sap.com/2022/04/14/sapui5-patch-level-independent-bootstrap)).
### 9. Rebuild the `webapp/view/App.view.xml`
➡️ Replace the content of the `webapp/view/App.view.xml` with the following code:
```xml
<mvc:View
xmlns="sap.m"
xmlns:mvc="sap.ui.core.mvc"
controllerName="sap.codejam.controller.App"
xmlns:macros="sap.fe.macros">
<App id="Main">
<pages>
<Page title="{i18n>Bookshop}">
<content>
<macros:Table metaPath="@com.sap.vocabularies.UI.v1.LineItem" id="booksTable" />
</content>
</Page>
</pages>
</App>
</mvc:View>
```
We removed almost all the content of our app view and replaced it with a `<macros:Table />`, which is a so called **building block** that we can use in SAP Fiori elements flexible programming model enabled applications. We pass it a `metaPath` pointing to specific **OData annotations** using the [SAP UI vocabulary](https://github.com/SAP/odata-vocabularies/blob/main/vocabularies/UI.md). As described [earlier](#chapter-201---enabling-the-sap-fiori-elements-flexible-programming-model), annotations are mandatory when using SAP Fiori elements. Luckily, they have already been implemented as part of the OData backend application (built with the SAP Cloud Application Programming model) and are ready to be consumed.
<details>
<summary>How have the OData annotations been implemented? 💬</summary>
<br>
> This is what the annotation file in the backend looks like:
>
>```cds
>using {CatalogService} from '../srv/cat-service';
>
>// List Report
>annotate CatalogService.Books with @(
> UI: {
> LineItem: [
> {
> $Type: 'UI.DataField',
> Label: 'Book',
> Value: title
> },
> {
> $Type: 'UI.DataField',
> Label: 'Author',
> Value: author
> },
> {
> $Type: 'UI.DataField',
> Label: 'Genre',
> Value: genre.name
> },
> {
> $Type: 'UI.DataField',
> Label: 'Price',
> Value: price
> },
> {
> $Type: 'UI.DataField',
> Label: 'Stock',
> Value: stock
> }
> ]
> }
>);
>```
>
>Although annotations are considered backend development and therefore not exactly the scope of this repository, it is important to understand how annotations work and how SAP Fiori elements is able to interpret them:
>
>CDS based OData annotations are one of the superpowers of the SAP Cloud Application Programming Model. It automatically picks up and reads annotation files and serves the provided information in the service [metadata document](https://developer-advocates-free-tier-central-hana-cloud-instan3b540fd6.cfapps.us10.hana.ondemand.com/browse/$metadata). This is the document our SAP Fiori elements application interprets and uses to build the UI. Let's go through the annotations file step by step:
>
>- It uses the [UI vocabulary](https://github.com/SAP/odata-vocabularies/blob/main/vocabularies/UI.md) developed by SAP to describe how the entity should to be displayed in user interfaces. Generally a vocabulary is a collection of terms that can be used to describe and give meaning to OData services.
>- It describes a `LineItem`, which is a collection (array) of data fields (think "columns") suitable to be visualized in a table or list.
>- The objects of the `LineItem` array are of type `UI.DataField` and therefore simply represent a piece of data. Each data field (think "column") has a `Label` and a `Value`, the latter comes directly from our Books entity.
>
>You can learn more about annotations in this [document](https://github.com/SAP-samples/odata-basics-handsonsapdev/blob/annotations/bookshop/README.md).
</details>
### 10. Use the `sap/fe/core/PageController` instead of the `sap/ui/core/mvc/Controller`
➡️ Replace the content of the `webapp/controller/App.controller.js` with the following code:
```javascript
sap.ui.define([
"sap/fe/core/PageController"
], function (PageController) {
"use strict"
return PageController.extend("sap.codejam.controller.App", {})
})
```
Similar to what we did in [step 2](#2-extend-the-sapfecoreappcomponent-instead-of-the-sapuicoreuicomponent) we now use the `PageController` provided by SAP Fiori elements instead of the core UI5 controller. This is to make sure our controller code runs within the SAP Fiori elements framework and has access to its [extension APIs](https://ui5.sap.com/#/api/sap.fe.core.PageController%23methods/getExtensionAPI). The `sap/fe/core/PageController` itself extends the `sap/ui/core/mvc/Controller`.
### 11. Change `ui5.yaml` configuration
Now that we are consuming a different OData service endpoint (V4), we need to tweak the UI5 server configuration in the `ui5.yaml` file:
➡️ Replace the current content of the `ui5.yaml` file with the following code:
```yaml
specVersion: '2.6'
metadata:
name: bookshop
type: application
server:
customMiddleware:
- name: fiori-tools-proxy
afterMiddleware: compression
configuration:
backend:
- path: /browse
url: https://developer-advocates-free-tier-central-hana-cloud-instan3b540fd6.cfapps.us10.hana.ondemand.com
```
We changed the path to the backend service (via the `fiori-tools-proxy`) to `/browse`, as we are now consuming a different OData service endpoint (V4). This configuration has to match our `webapp/manifest.json` file.
### 12. Test the new app
➡️ Stop the UI5 server (`control + c`) and restart it `npm run dev` so the the server configuration changes take effect.

We enabled the SAP Fiori elements flexible programming model for our custom SAPUI5 application and used the Table building block, powered by OData annotations. You might have to resize your browser window to see all the columns of the Table. We will continue to fine tune and work on our application in the following chapters.
Continue to [Chapter 2.02 - Adding an Object Page](/chapters/2.02-object-page/)
|
<template>
<chart />
</template>
<script lang="ts">
import { defineComponent, onMounted, onUnmounted, reactive } from "vue";
import Chart from "./chart/draw";
export default defineComponent({
components: {
Chart,
},
setup() {
// 下层数据
const dataArr = [
{
number: 150,
text: "今日构建总量",
},
{
number: 144,
text: "总共完成数量",
},
{
number: 361,
text: "正在编译数量",
},
{
number: 571,
text: "未通过数量",
},
];
// 对应图标
const iconFont = [
"icon-diagnose",
"icon-monitoring",
"icon-cloudupload",
"icon-clouddownload",
];
const numberData = reactive([]);
let intervalInstance = null;
onMounted(() => {
setData();
changeTiming();
});
const setData = () => {
dataArr.forEach((e) => {
numberData.push({
config: {
number: [e.number],
toFixed: 1,
content: "{nt}",
style: {
fontSize: 24,
},
},
text: e.text,
});
});
};
const changeTiming = () => {
intervalInstance = setInterval(() => {
changeNumber();
}, 2000);
};
const changeNumber = () => {
numberData.forEach((item, index) => {
item.config.number[0] += ++index;
item.config = { ...item.config };
});
};
onUnmounted(() => {
clearInterval(intervalInstance);
});
return { numberData, iconFont };
},
});
</script>
<style lang="scss" scoped></style>
|
# See: https://adventofcode.com/2022/day/1
:use 'Range'
:use 'Record'
:use 'String'
:use 'Number'
def partition = do (array, low, high)
# choose the rightmost element as pivot
pivot = array[high]
# pointer for greater element
i = low - 1
# traverse through all elements
# compare each element with pivot
for j in :range(low, high)
array[j] <= pivot then
# If element smaller than pivot is found
# swap it with the greater element pointed by i
i = i + 1
# Swapping element at i with element at j
(array[i], array[j]) = (array[j], array[i])
end
end
# Swap the pivot element with the greater element specified by i
array[i + 1], array[high] = array[high], array[i + 1]
# Return the position from where partition is done
return i + 1
end
def qsort[.Record](low, high)
low < high then
# Find pivot element such that
# element smaller than pivot are on the left
# element greater than pivot are on the right
pi = partition(self, low, high)
# Recursive call on the left of pivot
self:qsort(low, pi - 1)
# Recursive call on the right of pivot
self:qsort(pi + 1, high)
end
end
def io = :use 'io'
def Elf {
snacks
}
impl Elf
def cals
self.snacks:fold(0) do (cals, snack) cals + snack end
end
end
impl .String
def to_elf
snacks = self:split('\n'):map do return @1:to_n end
return { snacks }
end
def solve
elves = self:split('\n\n'):map do return @1:to_elf:cals end
solution = elves:fold(0) do (max, elf) return elf > max and elf or max end
return solution
end
end
status, puzzle = io:open('input.txt', 'r')
status == .ok or status:panic
status, puzzle = puzzle:read
status == .ok or status:panic
puzzle:solve:print
|
#!/bin/env python3
# -*- coding: utf-8 -*-
"""
@summary: A module for all result classesin this package
@author: Frank Brehm
@contact: frank@brehm-online.com
@copyright: © 2023 by Frank Brehm, Berlin
"""
from __future__ import absolute_import
import logging
from .stats import HourlyStats, MessageStatsTotals, HourlyStatsSmtpd
from .stats import DailyStatsDict, MessageStatsPerDay, SmtpdStats
from .stats import CommonStatsDict
__version__ = '0.5.5'
__author__ = 'Frank Brehm <frank@brehm-online.com>'
__copyright__ = '(C) 2023 by Frank Brehm, Berlin'
LOG = logging.getLogger(__name__)
class PostfixLogSums(object):
"""A class for encaplsulating the results of parsing of postfix logfiles."""
# -------------------------------------------------------------------------
def __init__(self, smtpd_stats=False):
"""Constructor."""
self._smtpd_stats = False
self.smtpd_stats = smtpd_stats
self.reset()
# -------------------------------------------------------------------------
@property
def smtpd_stats(self):
"""Generate smtpd connection statistics."""
return self._smtpd_stats
@smtpd_stats.setter
def smtpd_stats(self, value):
self._smtpd_stats = bool(value)
# -------------------------------------------------------------------------
def reset(self):
"""Resetting all counters and result structs."""
self._files_index = None
self.amavis_msgs = 0
self.bounced = {}
self.bounced_messages_per_hour = HourlyStats()
self.cleanup_warnings = {}
self.connections_time = 0
self.connections_total = 0
self.days_counted = 0
self.deferred = {}
self.deferred_messages_per_hour = HourlyStats()
self.delivered_messages_per_hour = HourlyStats()
self.discards = {}
self.fatals = {}
self.files = []
self.holds = {}
self.lines_considered = 0
self.lines_total = 0
self.logdate_oldest = None
self.logdate_latest = None
self.master_msgs = {}
self.message_details = {}
self.messages_per_day = DailyStatsDict(stats_class=MessageStatsPerDay)
self.msgs_total = MessageStatsTotals()
self.no_message_size = {}
self.panics = {}
self.postfix_messages = {}
self.postfix_script = {}
self.rcpt_domain = CommonStatsDict()
self.rcpt_user = CommonStatsDict()
self.received_messages_per_hour = HourlyStats()
self.rejected_messages_per_hour = HourlyStats()
self.rejects = {}
self.sending_domain_data = CommonStatsDict()
self.sending_user_data = CommonStatsDict()
self.smtp_messages = {}
self.smtp_connection_details = {
'other': {},
'trusted': {},
'untrusted': {},
}
self.smtp_connections = {
'other': 0,
'total': 0,
'trusted': 0,
'untrusted': 0,
}
self.smtpd_per_day = DailyStatsDict(stats_class=SmtpdStats)
self.smtpd_per_domain = CommonStatsDict()
self.smtpd_messages_per_hour = None
if self.smtpd_stats:
self.smtpd_messages_per_hour = HourlyStatsSmtpd()
self.warnings = {}
# -------------------------------------------------------------------------
def start_logfile(self, logfile):
"""Creates an entry for a new logfile in self.files and sets self.files_index
to the index of the new created entry."""
entry = {
'file': logfile,
'lines_total': 0,
'lines_considered': 0,
}
self.files.append(entry)
self._files_index = len(self.files) - 1
# -------------------------------------------------------------------------
def incr_lines_total(self, increment=1):
"""Increment all counters for all evaluated lines."""
self.lines_total += increment
if self._files_index is not None:
self.files[self._files_index]['lines_total'] += increment
# -------------------------------------------------------------------------
def incr_lines_considered(self, increment=1):
"""Increment all counters for all considered lines."""
self.lines_considered += increment
if self._files_index is not None:
self.files[self._files_index]['lines_considered'] += increment
# -------------------------------------------------------------------------
def as_dict(self, short=True, pure=False):
"""
Transforms the elements of the object into a dict
@param short: don't include local properties in resulting dict.
@type short: bool
@return: structure as dict
@rtype: dict
"""
res = {}
for key in self.__dict__:
if short and key.startswith('_') and not key.startswith('__'):
continue
# LOG.debug("Typecasting {!r} ...".format(key))
if key in ('msgs_total', 'messages_per_day', 'smtpd_per_day'):
res[key] = getattr(self, key).dict()
elif isinstance(getattr(self, key), CommonStatsDict):
res[key] = getattr(self, key).as_dict(pure=pure)
elif key == 'files':
if pure:
res[key] = []
for f in self.files:
fs = {
'file': str(f['file']),
'lines_considered': f['lines_considered'],
'lines_total': f['lines_total'],
}
res[key].append(fs)
else:
res[key] = self.__dict__[key]
elif key == 'smtpd_messages_per_hour':
# LOG.debug("Typecasting smtpd_messages_per_hour into a list ...")
if self.smtpd_messages_per_hour is None:
res[key] = None
else:
res[key] = self.smtpd_messages_per_hour.as_list(pure=pure)
elif key in (
'bounced_messages_per_hour', 'deferred_messages_per_hour',
'delivered_messages_per_hour', 'received_messages_per_hour',
'rejected_messages_per_hour'):
if pure:
res[key] = getattr(self, key).as_list()
else:
res[key] = self.__dict__[key]
elif key in ('logdate_latest', 'logdate_oldest'):
if pure:
dt = getattr(self, key, None)
if dt:
dt = dt.isoformat(' ')
res[key] = dt
else:
res[key] = self.__dict__[key]
elif key in ('messages_per_day', ):
if pure:
stats_dict = getattr(self, key)
if isinstance(stats_dict, dict):
res[key] = {}
for day in getattr(self, key).keys():
stats = stats_dict[day].dict()
res[key][day] = stats
else:
res[key] = None
else:
res[key] = self.__dict__[key]
if not pure:
res['__class_name__'] = self.__class__.__name__
return res
# -------------------------------------------------------------------------
def dict(self):
"""Typecast into a regular dict."""
return self.as_dict(pure=True)
if __name__ == "__main__":
pass
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 list
|
'use client';
import React, { memo } from 'react';
import Checkbox from '@mui/material/Checkbox';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import CircularProgress from '@mui/material/CircularProgress';
import CheckBoxOutlineBlankIcon from '@mui/icons-material/CheckBoxOutlineBlank';
import CheckBoxIcon from '@mui/icons-material/CheckBox';
import {
FastField,
FastFieldAttributes,
FieldInputProps,
FieldMetaProps,
FormikProps,
FormikValues,
getIn,
} from 'formik';
const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
const checkedIcon = <CheckBoxIcon fontSize="small" />;
interface Props<T> {
name: string;
options: T[];
displayLabel?: string;
displaySelected?: string;
label?: string | JSX.Element;
searchValue?: string;
handleChangeSearchValue?: (e: React.ChangeEvent<HTMLInputElement>) => void;
handleBlurSearchValue?: React.FocusEventHandler<HTMLInputElement | HTMLTextAreaElement>;
disabled?: boolean;
limit?: number;
isLoading?: boolean;
multiple?: boolean;
placeholder?: string;
handleChange?: (value: T | T[] | null, event: React.SyntheticEvent<Element, Event>) => void;
}
interface MultiSelectProps<T> extends Props<T> {
field: FieldInputProps<T | T[]>;
meta: FieldMetaProps<T | T[]>;
setFieldValue: (name: string, value: T | T[] | null) => void;
}
function AutoCompleteComponent<T>(props: MultiSelectProps<T>) {
const {
name,
disabled,
options,
label,
field,
meta,
isLoading,
multiple,
displayLabel = 'name',
displaySelected = 'id',
limit = 10,
placeholder,
handleChange,
setFieldValue,
searchValue = '',
handleChangeSearchValue,
handleBlurSearchValue,
} = props;
const getDefaultOptionLabel = (option: T) => getIn(option, displayLabel) ?? '';
const defaultHandleChange = (
event: React.SyntheticEvent<Element, Event>,
value: T | T[] | null,
) => {
if (!value) {
value = null;
}
if (handleChange) {
handleChange(value, event);
} else {
setFieldValue(name, value);
}
};
return (
<Autocomplete
{...field}
value={field?.value ?? (multiple ? [] : null)}
multiple={multiple}
id={name}
loading={isLoading}
limitTags={limit}
disabled={disabled}
options={options ?? []}
isOptionEqualToValue={(option, value) =>
getIn(option, displaySelected) === getIn(value, displaySelected)
}
renderOption={(props, option, { selected }) => {
return (
<li {...props}>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 5 }}
checked={selected}
/>
{getIn(option, displayLabel)}
</li>
);
}}
disableCloseOnSelect={multiple ? true : false}
getOptionLabel={getDefaultOptionLabel}
onChange={defaultHandleChange}
// noOptionsText="Không có dữ liệu"
size="small"
renderInput={(params) => (
<TextField
{...params}
label={label}
InputLabelProps={{
htmlFor: name,
shrink: true,
}}
value={searchValue}
onChange={handleChangeSearchValue}
InputProps={{
...params.InputProps,
endAdornment: (
<>
{isLoading ? <CircularProgress color="inherit" size={15} /> : null}
{params.InputProps.endAdornment}
</>
),
}}
onBlur={handleBlurSearchValue}
placeholder={placeholder}
error={Boolean(meta.touched && meta.error)}
helperText={meta.touched && meta.error ? meta.error : ''}
/>
)}
/>
);
}
const shouldComponentUpdate = (
nextProps: FastFieldAttributes<Props<any> & { formik: FormikValues }>,
currentProps: FastFieldAttributes<Props<any> & { formik: FormikValues }>,
) =>
nextProps?.options !== currentProps?.options ||
nextProps?.value !== currentProps?.value ||
nextProps?.handleChange !== currentProps?.handleChange ||
nextProps?.disabled !== currentProps?.disabled ||
Object.keys(nextProps).length !== Object.keys(currentProps).length ||
getIn(nextProps.formik.values, currentProps.name) !==
getIn(currentProps.formik.values, currentProps.name) ||
getIn(nextProps.formik.errors, currentProps.name) !==
getIn(currentProps.formik.errors, currentProps.name) ||
getIn(nextProps.formik.touched, currentProps.name) !==
getIn(currentProps.formik.touched, currentProps.name);
function AutocompleteCustom<T = any>(props: Props<T>) {
return (
<FastField {...props} name={props.name} shouldUpdate={shouldComponentUpdate}>
{({
field,
meta,
form,
}: {
field: FieldInputProps<T | T[]>;
meta: FieldMetaProps<T | T[]>;
form: FormikProps<T | T[]>;
}) => (
<AutoCompleteComponent<T>
{...props}
field={field}
meta={meta}
setFieldValue={form.setFieldValue}
/>
)}
</FastField>
);
}
const MemoizedMultiSelectCustom = memo(AutocompleteCustom) as <T = any>(
props: Props<T>,
) => React.JSX.Element;
export { MemoizedMultiSelectCustom as AutocompleteCustom };
|
@extends('backend.layouts.master')
@section('content')
<div class="content-wrapper">
<!-- Content Header (Page header) -->
@include('backend.layouts.ba')
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<!-- left column -->
<div class="col-md-12">
<div class="col-12">
@if ($errors->any())
<div>
<ul style="list-style: none;">
@foreach ($errors->all() as $error)
<li class="alert alert-danger">{{$error}}</li>
@endforeach
</ul>
</div>
@endif
</div>
<!-- general form elements -->
<div class="card card-primary">
<!-- /.card-header -->
<!-- form start -->
<form action="{{route('category.store')}}" method="POST" enctype="multipart/form-data">
@csrf
{{-- Title input --}}
<div class="card-body">
<div class="form-group">
<label for="title">Title <span class="text-danger">*</span></label>
<input type="text" name="title" class="form-control" placeholder="Title" value="{{old('title')}}">
</div>
<div class="col-sm-12 col-md-12">
<!-- textarea -->
<div class="form-group">
<label>Summary</label>
<textarea id="summary" class="form-control" name="summary" placeholder="Enter ...">{{old('summary')}}</textarea>
</div>
</div>
<div class="col-sm-12">
<!-- select -->
<div class="form-group">
<label>Status</label>
<select name="status" class="form-control">
<option>-- Select --</option>
<option value="active" {{old('status') == 'active' ? "selected" : ''}}>Active</option>
<option value="inactive" {{old('status') == 'inactive' ? 'selecetd' : ''}}>Inactive</option>
</select>
</div>
</div>
<div class="col-sm-12">
<!-- select -->
<div class="form-group">
<label>Is Parent: </label>
<input type="checkbox" name="is_parent" id="is_parent" value="1"> tick to make it Parent
</div>
</div>
<div class="col-sm-12" id="parent_cat_div">
<!-- select -->
<div class="form-group">
<label>Parent Category</label>
<select name="parent_id" class="form-control">
<option>-- Parent Category --</option>
@foreach ($parent_category as $pc)
<option value="{{$pc->id}}" {{old('parent_id') == $pc->id ? 'selected' : ''}}>{{$pc->title}}</option>
@endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="exampleInputFile">File input</label>
<div class="input-group">
<span class="input-group-btn">
<a id="lfm" data-input="thumbnail" data-preview="holder" class="btn btn-primary">
<i class="fa fa-picture-o"></i> Choose
</a>
</span>
<input id="thumbnail" class="form-control" type="text" name="photo">
</div>
<div id="holder" style="margin-top:15px;max-height:100px;"></div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<!-- /.card -->
</div>
<!--/.col (left) -->
</div>
<!-- /.row -->
</div><!-- /.\iner-fluid -->
</section>
<!-- /.content -->
</div>
@endsection
@section('scripts')
<script src="/vendor/laravel-filemanager/js/stand-alone-button.js"></script>
<script>
$('#lfm').filemanager('image');
</script>
<script>
$(document).ready(function() {
$('#summary').summernote();
});
</script>
<script>
$(document).ready(function () {
$('#is_parent').change(function(e){
e.preventDefault();
let is_checked = $('#is_parent').prop('checked');
if(is_checked){
$('#parent_cat_div').addClass('d-none');
//console.log($('#parent_cat_div select'));
$('#parent_cat_div select').val('');
}else{
$('#parent_cat_div').removeClass('d-none');
// console.log($('#parent_cat_div select').val());
// console.log($('#parent_cat_div select'));
}
});
});
</script>
@endsection
|
mod buffer;
mod pass;
mod geometry;
use geometry::*;
mod text;
use text::*;
mod selection_box;
use selection_box::*;
use super::circuit::*;
use crate::app::math::Vec2f;
use eframe::egui_wgpu::RenderState;
use egui::TextureId;
use vello::kurbo::*;
use vello::peniko::*;
use wgpu::{FilterMode, Texture, TextureView};
pub use vello::peniko::Color;
struct RenderTarget {
texture: Texture,
view: TextureView,
}
fn create_render_target(render_state: &RenderState, width: u32, height: u32) -> RenderTarget {
use wgpu::*;
let desc = TextureDescriptor {
label: Some("Viewport"),
size: Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba8Unorm,
usage: TextureUsages::RENDER_ATTACHMENT
| TextureUsages::TEXTURE_BINDING
| TextureUsages::STORAGE_BINDING,
view_formats: &[],
};
let texture = render_state.device.create_texture(&desc);
let view = texture.create_view(&TextureViewDescriptor::default());
RenderTarget { texture, view }
}
pub const BASE_ZOOM: f32 = 10.0; // Logical pixels per unit
pub const LOGICAL_PIXEL_SIZE: f32 = 1.0 / BASE_ZOOM;
pub struct ViewportColors {
pub background_color: Color,
pub grid_color: Color,
pub component_color: Color,
pub selected_component_color: Color,
}
pub struct Viewport {
render_target: RenderTarget,
texture_id: TextureId,
renderer: vello::Renderer,
scene: vello::Scene,
geometry: GeometryStore,
text_pass: TextPass,
selection_box_pass: SelectionBoxPass,
}
impl Viewport {
pub fn create(render_state: &RenderState, width: u32, height: u32) -> Self {
let render_target = create_render_target(render_state, width, height);
let texture_id = render_state.renderer.write().register_native_texture(
&render_state.device,
&render_target.view,
FilterMode::Nearest,
);
let renderer = vello::Renderer::new(
&render_state.device,
&vello::RendererOptions {
surface_format: None,
timestamp_period: render_state.queue.get_timestamp_period(),
},
)
.unwrap();
Self {
render_target,
texture_id,
renderer,
scene: vello::Scene::new(),
geometry: GeometryStore::new(),
text_pass: TextPass::create(render_state),
selection_box_pass: SelectionBoxPass::create(render_state),
}
}
pub fn resize(&mut self, render_state: &RenderState, width: u32, height: u32) -> bool {
if (self.render_target.texture.width() == width)
&& (self.render_target.texture.height() == height)
{
return false;
}
self.render_target = create_render_target(render_state, width, height);
render_state
.renderer
.write()
.update_egui_texture_from_wgpu_texture(
&render_state.device,
&self.render_target.view,
FilterMode::Nearest,
self.texture_id,
);
true
}
#[inline]
pub fn texture_id(&self) -> TextureId {
self.texture_id
}
pub fn draw(
&mut self,
render_state: &RenderState,
circuit: Option<&Circuit>,
colors: &ViewportColors,
) {
let width = self.render_target.texture.width();
let height = self.render_target.texture.height();
let resolution = Vec2f::new(width as f32, height as f32);
let (offset, zoom) = circuit
.map(|c| (c.offset(), c.zoom()))
.unwrap_or((Vec2f::default(), DEFAULT_ZOOM));
let mut fragment = vello::SceneFragment::new();
let mut builder = vello::SceneBuilder::for_fragment(&mut fragment);
draw_grid(&mut builder, resolution, offset, zoom, colors.grid_color);
if let Some(circuit) = circuit {
draw_wires(&mut builder, circuit);
draw_components(&mut builder, circuit, colors, &self.geometry);
}
let mut builder = vello::SceneBuilder::for_scene(&mut self.scene);
// Draw a dummy rectangle to prevent a crash in case there is no other geometry
builder.fill(
Fill::NonZero,
Affine::IDENTITY,
colors.background_color,
None,
&Rect::ZERO,
);
let transform = Affine::FLIP_Y
.then_translate((-offset.x as f64, offset.y as f64).into())
.then_scale((zoom * BASE_ZOOM) as f64)
.then_translate(((width as f64) * 0.5, (height as f64) * 0.5).into());
builder.append(&fragment, Some(transform));
self.renderer
.render_to_texture(
&render_state.device,
&render_state.queue,
&self.scene,
&self.render_target.view,
&vello::RenderParams {
base_color: colors.background_color,
width,
height,
},
)
.unwrap();
if let Some(circuit) = circuit {
self.text_pass.draw(
render_state,
&self.render_target.view,
circuit,
resolution,
offset,
zoom,
colors,
);
if let Some((box_a, box_b)) = circuit.selection_box() {
self.selection_box_pass.draw(
render_state,
&self.render_target.view,
resolution,
offset,
zoom,
box_a,
box_b,
colors.selected_component_color,
);
}
}
}
}
fn draw_grid(
builder: &mut vello::SceneBuilder,
resolution: Vec2f,
offset: Vec2f,
zoom: f32,
color: Color,
) {
if zoom > 0.99 {
let step = if zoom > 1.99 { 1 } else { 2 };
let grid_width = resolution.x / (zoom * BASE_ZOOM);
let grid_height = resolution.y / (zoom * BASE_ZOOM);
let left = (offset.x - (grid_width * 0.5)).floor() as i32;
let right = (offset.x + (grid_width * 0.5)).ceil() as i32;
let bottom = (offset.y - (grid_height * 0.5)).floor() as i32;
let top = (offset.y + (grid_height * 0.5)).ceil() as i32;
let rect = Rect {
x0: ((-LOGICAL_PIXEL_SIZE as f64) / 2.0) * (step as f64),
x1: ((LOGICAL_PIXEL_SIZE as f64) / 2.0) * (step as f64),
y0: ((-LOGICAL_PIXEL_SIZE as f64) / 2.0) * (step as f64),
y1: ((LOGICAL_PIXEL_SIZE as f64) / 2.0) * (step as f64),
};
for y in (bottom..=top).filter(|&y| (y % step) == 0) {
for x in (left..=right).filter(|&x| (x % step) == 0) {
builder.fill(
Fill::NonZero,
Affine::translate((x as f64, y as f64)),
color,
None,
&rect,
);
}
}
}
}
fn draw_wires(builder: &mut vello::SceneBuilder, circuit: &Circuit) {
// NOTE: vello currently does not actually support joins and caps other than "round"
let stroke = Stroke::new(2.0 * LOGICAL_PIXEL_SIZE)
.with_join(Join::Miter)
.with_caps(Cap::Round);
for (i, segment) in circuit.wire_segments().iter().enumerate() {
let stroke_color = if circuit.selection().contains_wire_segment(i) {
Color::rgb8(80, 80, 255)
} else {
Color::BLUE
};
let mut path = BezPath::new();
path.move_to((segment.endpoint_a.x as f64, segment.endpoint_a.y as f64));
for midpoint in &segment.midpoints {
path.line_to((midpoint.x as f64, midpoint.y as f64));
}
path.line_to((segment.endpoint_b.x as f64, segment.endpoint_b.y as f64));
builder.stroke(&stroke, Affine::IDENTITY, stroke_color, None, &path);
}
}
fn draw_components(
builder: &mut vello::SceneBuilder,
circuit: &Circuit,
colors: &ViewportColors,
geometry: &GeometryStore,
) {
use crate::app::component::*;
// NOTE: vello currently does not actually support joins and caps other than "round"
let stroke = Stroke::new(2.0 * LOGICAL_PIXEL_SIZE)
.with_join(Join::Miter)
.with_caps(Cap::Butt);
for (i, component) in circuit.components().iter().enumerate() {
let transform = Affine::scale_non_uniform(if component.mirrored { -1.0 } else { 1.0 }, 1.0)
.then_rotate(component.rotation.radians())
.then_translate((component.position.x as f64, component.position.y as f64).into());
let stroke_color = if circuit.selection().contains_component(i) {
colors.selected_component_color
} else {
colors.component_color
};
let geometry = match component.kind {
ComponentKind::AndGate { .. } => &geometry.and_gate_geometry,
ComponentKind::OrGate { .. } => &geometry.or_gate_geometry,
ComponentKind::XorGate { .. } => &geometry.xor_gate_geometry,
ComponentKind::NandGate { .. } => &geometry.nand_gate_geometry,
ComponentKind::NorGate { .. } => &geometry.nor_gate_geometry,
ComponentKind::XnorGate { .. } => &geometry.xnor_gate_geometry,
};
builder.fill(
Fill::NonZero,
transform,
colors.background_color,
None,
geometry.fill_path(),
);
builder.stroke(
&stroke,
transform,
stroke_color,
None,
geometry.stroke_path(),
);
for anchor in component.anchors() {
let color = match anchor.kind {
AnchorKind::Input => Color::LIME,
AnchorKind::Output => Color::RED,
AnchorKind::BiDirectional => Color::YELLOW,
AnchorKind::Passive => Color::BLUE,
};
let shape = Circle::new(
(anchor.position.x as f64, anchor.position.y as f64),
(LOGICAL_PIXEL_SIZE * 2.0) as f64,
);
builder.fill(Fill::NonZero, Affine::IDENTITY, color, None, &shape);
}
}
}
|
1a. Display the first and last names of all actors from the table actor.
Ans:select first_name, last_name from actor;
1b. Display the first and last name of each actor in a single column in upper case letters. Name the column Actor Name.
Ans: SELECT UPPER(CONCAT(firstName, ' ', last_name)) AS `Actor Name`
FROM actor;
2a. You need to find the ID number, first name, and last name of an actor, of whom you know only the first name, "Joe." What is one query would you use to obtain this information?
Ans: SELECT actor_id, first_name, , last_name
FROM actor
WHERE firstName = "Joe";
2b. Find all actors whose last name contain the letters GEN:
Ans: SELECT actor_id, first_name, last_name
FROM actor
WHERE last_name like '%GEN%';
2c. Find all actors whose last names contain the letters LI. This time, order the rows by last name and first name, in that order:
Ans: SELECT actor_id, last_name, first_name
FROM actor
WHERE last_name like '%LI%';
2d. Using IN, display the country_id and country columns of the following countries: Afghanistan, Bangladesh, and China:
Ans: SELECT country_id, country
FROM country
WHERE country IN
('Afghanistan', 'Bangladesh', 'China')
3a. Add a middle_name column to the table actor. Position it between first_name and last_name. Hint: you will need to specify the data type.
Ans: ALTER TABLE actor
ADD COLUMN middle_name VARCHAR(25) AFTER first_name;
3b. You realize that some of these actors have tremendously long last names. Change the data type of the middle_name column to blobs.
Ans: ALTER TABLE actor
MODIFY COLUMN middle_name BLOB;
3c. Now delete the middle_name column.
Ans: ALTER TABLE actor
DROP COLUMN middle_name;
4a. List the last names of actors, as well as how many actors have that last name.
Ans: SELECT last_name, COUNT(*) AS 'NO. of Actors'
FROM actor GROUP BY last_name;
4b. List last names of actors and the number of actors who have that last name, but only for names that are shared by at least two actors
Ans: SELECT last_name, COUNT(*) AS 'NO. of Actors'
FROM actor GROUP BY last_name HAVING COUNT(*) >= 2;
4c. Oh, no! The actor HARPO WILLIAMS was accidentally entered in the actor table as GROUCHO WILLIAMS, the name of Harpo's second cousin's husband's yoga teacher. Write a query to fix the record.
Ans: UPDATE actor
SET first_name = 'HARPO'
WHERE First_name = "Groucho" AND last_name = "Williams";
4d. Perhaps we were too hasty in changing GROUCHO to HARPO. It turns out that GROUCHO was the correct name after all! In a single query, if the first name of the actor is currently HARPO, change it to GROUCHO. Otherwise, change the first name to MUCHO GROUCHO, as that is exactly what the actor will be with the grievous error. BE CAREFUL NOT TO CHANGE THE FIRST NAME OF EVERY ACTOR TO MUCHO GROUCHO, HOWEVER! (Hint: update the record using a unique identifier.)
Ans: query first: to find it's id
SELECT first_name, actor_id FROM sakila.actor where first_name= 'HARPO';
Query Second: update using
UPDATE actor
SET first_name = 'GROUCHO'
WHERE actor_id = 17
5a. You cannot locate the schema of the address table. Which query would you use to re-create it?
Ans: DESCRIBE sakila.address;
6a. Use JOIN to display the first and last names, as well as the address, of each staff member. Use the tables staff and address:
Ans: SELECT first_name, last_name, address
FROM staff
JOIN address
ON staff.address_id = address.address_id;
6b. Use JOIN to display the total amount rung up by each staff member in August of 2005. Use tables staff and payment.
Ans: SELECT payment.staff_id, staff.first_name, staff.last_name, payment.amount, payment.payment_date
FROM staff INNER JOIN payment ON
staff.staff_id = payment.staff_id AND payment_date LIKE '2005-08%';
6c. List each film and the number of actors who are listed for that film. Use tables film_actor and film. Use inner join.
Ans: SELECT film.title AS 'Film', COUNT(film_actor.actor_id) AS `NO. of Actors`
FROM film_actor
INNER JOIN film
ON film_actor.film_id= film.film_id
GROUP BY film.title;
6d. How many copies of the film Hunchback Impossible exist in the inventory system?
Ans:
SELECT title,
(SELECT COUNT(*) FROM inventory
WHERE film.film_id = inventory.film_id
) AS 'Number of Copies'
FROM film
WHERE title = "Hunchback Impossible";
6e. Using the tables payment and customer and the JOIN command, list the total paid by each customer. List the customers alphabetically by last name:
Ans: SELECT c.first_name, c.last_name, sum(p.amount) AS `Total Paid`
FROM customer c
JOIN payment p
ON c.customer_id= p.customer_id
GROUP BY c.last_name;
7a. The music of Queen and Kris Kristofferson have seen an unlikely resurgence. As an unintended consequence, films starting with the letters K and Q have also soared in popularity. Use subqueries to display the titles of movies starting with the letters K and Q whose language is English.
Ans:
SELECT title
FROM film WHERE title
LIKE 'K%' OR title LIKE 'Q%'
AND title IN
(
SELECT title
FROM film
WHERE language_id = 1
);
7b. Use subqueries to display all actors who appear in the film Alone Trip.
Ans: SELECT first_name, last_name
FROM actor
WHERE actor_id IN
(
Select actor_id
FROM film_actor
WHERE film_id IN
(
SELECT film_id
FROM film
WHERE title = 'Alone Trip'
));
7c. You want to run an email marketing campaign in Canada, for which you will need the names and email addresses of all Canadian customers. Use joins to retrieve this information.
Ans: SELECT cus.first_name, cus.last_name, cus.email
FROM customer cus
JOIN address a
ON (cus.address_id = a.address_id)
JOIN city cty
ON (cty.city_id = a.city_id)
JOIN country
ON (country.country_id = cty.country_id)
WHERE country.country= 'Canada';
7d. Sales have been lagging among young families, and you wish to target all family movies for a promotion. Identify all movies categorized as famiy films.
Ans:
SELECT title, description FROM film
WHERE film_id IN
(
SELECT film_id FROM film_category
WHERE category_id IN
(
SELECT category_id FROM category
WHERE name = "Family"
));
7e. Display the most frequently rented movies in descending order.
Ans:
SELECT f.title, COUNT(rental_id) AS 'Times Rented'
FROM rental r
JOIN inventory i
ON (r.inventory_id = i.inventory_id)
JOIN film f
ON (i.film_id = f.film_id)
GROUP BY f.title
ORDER BY `Times Rented` DESC;
7f. Write a query to display how much business, in dollars, each store brought in.
Ans:
SELECT s.store_id, SUM(amount) AS 'Revenue'
FROM payment p
JOIN rental r
ON (p.rental_id = r.rental_id)
JOIN inventory i
ON (i.inventory_id = r.inventory_id)
JOIN store s
ON (s.store_id = i.store_id)
GROUP BY s.store_id;
7g. Write a query to display for each store its store ID, city, and country.
Ans:
SELECT s.store_id, cty.city, country.country
FROM store s
JOIN address a
ON (s.address_id = a.address_id)
JOIN city cty
ON (cty.city_id = a.city_id)
JOIN country
ON (country.country_id = cty.country_id);
7h. List the top five genres in gross revenue in descending order. (Hint: you may need to use the following tables: category, film_category, inventory, payment, and rental.)
Ans:
SELECT c.name AS 'Genre', SUM(p.amount) AS 'Gross'
FROM category c
JOIN film_category fc
ON (c.category_id=fc.category_id)
JOIN inventory i
ON (fc.film_id=i.film_id)
JOIN rental r
ON (i.inventory_id=r.inventory_id)
JOIN payment p
ON (r.rental_id=p.rental_id)
GROUP BY c.name ORDER BY Gross LIMIT 5;
8a. In your new role as an executive, you would like to have an easy way of viewing the Top five genres by gross revenue. Use the solution from the problem above to create a view. If you haven't solved 7h, you can substitute another query to create a view.
Ans:
CREATE VIEW genre_revenue AS
SELECT c.name AS 'Genre', SUM(p.amount) AS 'Gross'
FROM category c
JOIN film_category fc
ON (c.category_id=fc.category_id)
JOIN inventory i
ON (fc.film_id=i.film_id)
JOIN rental r
ON (i.inventory_id=r.inventory_id)
JOIN payment p
ON (r.rental_id=p.rental_id)
GROUP BY c.name ORDER BY Gross LIMIT 5;
8b. How would you display the view that you created in 8a?
Ans:
SELECT * FROM genre_revenue;
8c. You find that you no longer need the view top_five_genres. Write a query to delete it.
Ans:
SELECT * FROM genre_revenue;
|
<template>
<b-navbar class="header" :class="{ lightMode: lightMode }" toggleable="md">
<b-navbar-brand class="brand" to="/">
<img
v-if="lightMode"
class="brand__logo"
src="../assets/icons/logoOrange.png"
alt="Gazu"
/>
<img
v-else
class="brand__logo"
src="../assets/icons/logoGray.png"
alt="Gazu"
/>
</b-navbar-brand>
<b-navbar-toggle class="toggler" target="nav-collapse">
<span class="navbar-toggler-icon"></span>
</b-navbar-toggle>
<b-collapse class="menu" id="nav-collapse" is-nav>
<b-navbar-nav class="menu__nav">
<b-nav-item class="menu__nav-item active" href="#profile">{{
$t("message.headerProfile")
}}</b-nav-item>
<b-nav-item class="menu__nav-item" href="#skills">{{
$t("message.headerSkills")
}}</b-nav-item>
<b-nav-item class="menu__nav-item" href="#projects">{{
$t("message.headerProjects")
}}</b-nav-item>
<b-nav-item class="menu__nav-item" href="#contact">{{
$t("message.headerContact")
}}</b-nav-item>
</b-navbar-nav>
<div class="menu__button-light">
<label class="menu__button-switch">
<input type="checkbox" @input="switchMode" v-model="lightMode" />
<span class="menu__button-slider"></span>
</label>
<b-form-select
v-model="locale"
:options="locales"
v-on:change="changeLanguage"
class="mb-2 lang-button"
></b-form-select>
</div>
</b-collapse>
</b-navbar>
</template>
<script>
export default {
data() {
return {
locale: "en-US",
locales: [
{ text: "en-US", value: "en-US" },
{ text: "pt-BR", value: "br" },
],
lightMode: false,
isActive: false,
};
},
methods: {
changeLanguage() {
this.$i18n.locale = this.locale;
},
switchMode() {
this.$emit("switchMode");
},
deactivateNavLinks() {
const navLinks = document.querySelectorAll(".nav-link");
navLinks.forEach((link) => link.classList.remove("active"));
},
checkSectionInView() {
const sections = document.querySelectorAll("section");
sections.forEach((section) => {
const top = section.offsetTop - 140;
const bottom = top + section.offsetHeight;
if (window.pageYOffset >= top && window.pageYOffset < bottom) {
const navLink = document.querySelector(
`.nav-link[href="#${section.id}"]`
);
this.deactivateNavLinks();
navLink.classList.add("active");
}
});
},
},
mounted() {
window.addEventListener("scroll", this.checkSectionInView);
},
};
</script>
<style>
.header {
background-color: rgba(60, 60, 60);
padding: 0rem 4rem !important;
border-bottom: solid 2px rgb(0, 0, 0);
position: sticky !important;
top: 0;
z-index: 1;
}
.brand__logo {
width: 8rem;
height: 8rem;
}
.toggler {
margin-right: 15px;
width: 50px;
}
.nav-link {
font-family: "DM Sans", sans-serif;
color: rgb(255, 140, 0) !important;
font-size: 1.2rem;
font-weight: 500;
align-items: center;
display: flex !important;
padding: 0 30px !important;
}
.nav-link.active {
background-color: rgb(255, 140, 0) !important;
color: black !important;
box-shadow: 3px 3px 5px 2px rgba(0, 0, 0, 0.5);
border-radius: 5px;
}
.cabecalho-menu {
display: flex;
}
.menu__nav {
display: flex;
align-items: center;
margin-right: 60px;
}
.menu {
display: flex;
justify-content: right;
width: 80%;
}
/* BOTAO LIGHT MODE E O ESTILO DO LIGHT MODE ABAIXO*/
.menu__button-light {
padding: 10px;
width: 350px;
display: flex;
align-items: center;
justify-content: center;
margin-right: 2%;
}
.header.lightMode {
background-color: rgb(255, 140, 0);
}
.lightMode .nav-link {
color: rgb(60, 60, 60) !important;
font-weight: 500;
}
.lightMode .nav-link.active {
color: darkorange !important;
font-weight: 500;
background-color: rgb(60, 60, 60) !important;
}
.menu__button-switch {
position: relative;
display: inline-block;
width: 73px;
height: 38px;
border: solid rgb(255, 140, 0) 2px;
border-radius: 10%;
}
.menu__button-switch input {
opacity: 0;
width: 0;
height: 0;
}
.menu__button-slider {
width: 68px;
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgb(60, 60, 60);
-webkit-transition: 0.4s;
transition: 0.4s;
border-radius: 9%;
}
.menu__button-slider:before {
position: absolute;
content: "";
height: 27px;
width: 32px;
left: 4px;
bottom: 4px;
background-color: rgb(218, 218, 218);
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:checked + .menu__button-slider {
background-color: rgb(60, 60, 60);
}
input:focus + .menu__button-slider {
box-shadow: 0 0 1px rgba(8, 9, 87, 255);
}
input:checked + .menu__button-slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
.custom-select::-ms-expand {
color: white;
}
.custom-select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-image: url("../assets/icons/logo-lang.png") !important;
background-repeat: no-repeat !important;
background-position: right center !important;
background-size: 18px 18px !important;
padding-right: 25px !important;
color: white;
border: none;
border-radius: 5px;
font-size: 0.5rem;
width: 30% !important;
}
.lang-button {
background-color: rgb(60, 60, 60) !important;
margin-bottom: 0 !important;
font-family: "DM Sans", sans-serif;
color: darkorange !important;
border: 2px darkorange solid !important;
margin-left: 40px;
}
@media screen and (max-width: 768px) {
}
@media screen and (max-width: 1200px) {
.header {
padding: 0 1rem !important;
}
.nav-link {
padding: 10px !important;
}
.menu__nav {
margin-right: 10px;
}
.menu__button-light {
padding: 10px 0px;
width: 250px;
margin-right: 0%;
}
.lang-button {
background-color: rgb(60, 60, 60) !important;
margin-bottom: 0 !important;
font-family: "DM Sans", sans-serif;
color: darkorange !important;
border: 2px darkorange solid !important;
margin-left: 10px;
padding: 2px !important;
}
}
</style>
|
#lang simply-scheme
; Write a procedure fringe that takes as argument a tree (represented as a list) and returns a list whose
; elements are all the leaves of the tree arranged in left-toright order. For example,
; (define x (list (list 1 2) (list 3 4)))
; (fringe x)
; (1 2 3 4)
; (fringe (list x x))
; (1 2 3 4 1 2 3 4)
(define x (list (list 1 2) (list 3 4)))
(define (fringe x)
(cond ((null? x) '())
((not (pair? x)) (list x))
(else (append (fringe (car x))
(fringe (cdr x))))))
(fringe x)
(fringe (list x x))
|
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable jsx-a11y/img-redundant-alt */
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { usersAction } from "../redux/slice/users";
import { setLogedInUser } from "../redux/slice/logedInUser";
import Socailf from "../components/Socailf";
import SocialG from "../components/Socialgoogle";
const Login = () => {
const Users = useSelector((state) => state.users.users);
// const loggedInUser = useSelector((state) => state.logedInUser.logedInUser);
const dispatch = useDispatch();
const navigate = useNavigate();
const [user, setUser] = useState({
email: "",
password: "",
});
useEffect(() => {
dispatch(usersAction());
}, [dispatch]);
const handlechange = (event) => {
const { name, value } = event.target;
setUser((prevData) => ({
...prevData,
[name]: value,
}));
};
const handleclick = (event) => {
event.preventDefault();
if (!user.email || !user.password) {
console.log("Please fill in all fields.");
return;
}
const existingUser = Users.find((u) => u.email === user.email);
if (existingUser && user.password === existingUser.password) {
console.log("Logged in");
dispatch(setLogedInUser(existingUser));
navigate("/home");
} else {
console.log("Invalid Email or Password ");
}
};
return (
<section className="text-center text-lg-start">
<style>
{`
.cascading-right {
margin-right: -50px;
}
@media (max-width: 991.98px) {
.cascading-right {
margin-right: 0;
}
}
.btngreen{
color:#198754
}
`}
</style>
<div className="container py-4">
<div className="row g-0 align-items-center">
<div className="col-lg-6 mb-5 mb-lg-0">
<div
className="card cascading-right"
style={{
background: "hsla(0, 0%, 100%, 0.55)",
backdropFilter: "blur(30px)",
}}
>
<div className="card-body p-5 shadow-5 text-center">
<h2 className="fw-bold mb-5 btngreen">Log In</h2>
<form onSubmit={handleclick}>
<div className="form-outline mb-4">
<input
type="email"
id="form3Example3"
className="form-control"
name="email"
placeholder="Email address"
onChange={handlechange}
/>
<label
className="form-label"
htmlFor="form3Example3"
></label>
</div>
<div className="form-outline mb-4">
<input
type="password"
id="form3Example4"
className="form-control"
name="password"
placeholder="Password"
onChange={handlechange}
/>
<label
className="form-label"
htmlFor="form3Example4"
></label>
</div>
<button
type="submit"
className="btn btn-success btn-block mb-4"
>
Log In
</button>
<div className="text-center">
<p>or sign up with:</p>
<div>
<div>
<button
type="button"
className=" btn btn-link btn-floating mx-1 "
>
<Socailf />
</button>
{/* <Google /> */}
<button
type="button"
className=" btn btn-link btn-floating mx-1 "
style={{ height: "3.5rem" }}
>
<SocialG />
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div className="d-none d-lg-block col-lg-6 mb-5 mb-lg-0">
<img src="images/3.jpg" style={{ width: "100%" }} alt="login-photo" />
</div>
</div>
</div>
</section>
);
};
export default Login;
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
* Author: [Dorey, Dylan]
* Last Updated: [04/23/2024]
* [The fuel pump of a bike engine that burns fuel at different rates]
*/
public class FuelPump : MonoBehaviour
{
//reference to our facade (bike engine)
public BikeEngine engine;
//coroutine variable for burning fuel
public IEnumerator burnFuel;
private void Start()
{
//initialize the coroutine variable to the BurnFuel method
burnFuel = BurnFuel();
}
/// <summary>
/// Burns fuel at a desired burn rate
/// </summary>
/// <returns> the time to wait before burning more fuel </returns>
public IEnumerator BurnFuel()
{
while (true)
{
//wait one second before burning more fuel
yield return new WaitForSeconds(1f);
//take the engines fuel amount and subtract the fuel burn rate
engine.fuelAmount -= engine.burnRate;
//if the engine runs out of fuel
if(engine.fuelAmount <= 0f)
{
//turn off the engine and exit the coroutine
engine.TurnOff();
yield return 0;
}
}
}
/// <summary>
/// TESTING PURPOSES ONLY ( DO NOT USE IN PRODUCTION CODE ) EXTREMELY INEFFICIENT
/// </summary>
private void OnGUI()
{
//change the UI color to green
GUI.color = Color.green;
//display the engine's fuel amount
GUI.Label(new Rect(100, 40, 500, 20), "Fuel: " + engine.fuelAmount);
}
}
|
import Debug "mo:base/Debug";
import Time "mo:base/Time";
import Float "mo:base/Float";
actor DBank {
stable var currentValue: Float = 300;
// currentValue := 300;
stable var startTime = Time.now(); //nanoseconds since 1970-01-01.
// startTime := Time.now();
Debug.print(debug_show(startTime));
public func topUp(amount: Float) {
currentValue += amount;
Debug.print(debug_show(currentValue));
};
public func withdraw(amount: Float){
let tempValue: Float = currentValue - amount;
if(tempValue >= 0){
currentValue -= amount;
Debug.print(debug_show(currentValue));
} else {
Debug.print("Amount too large, currentValue less than zero.")
}
};
public query func checkBalance() : async Float {
return currentValue;
};
public func compound() {
let currentTime = Time.now();
let timeElapsedInNanoSecond = currentTime - startTime;
let timeElapsedInSecond = timeElapsedInNanoSecond / 1000000000;
// 1% interest per second
currentValue := currentValue * (1.01 ** Float.fromInt(timeElapsedInSecond));
// reset to the pervious compoundede time
startTime := currentTime;
}
}
|
require('dotenv').config();
const puppeteer = require('puppeteer');
describe("Jakob's Law Usability Test", () => {
let browser;
let page;
beforeAll(async () => {
browser = await puppeteer.launch({
headless: true,
// executablePath: 'C:/path/to/your/chromium' // Optional: use a custom Chromium path
});
page = await browser.newPage();
});
afterAll(async () => {
await browser.close();
});
test('should have a visible and working navigation bar', async () => {
await page.goto(process.env.HOME_URL);
const navBarExists = await page.$('nav') !== null;
expect(navBarExists).toBe(true);
const navLinks = await page.$$eval('nav a', links => links.length);
expect(navLinks).toBeGreaterThan(0);
});
test('should have a visible and clickable logo that returns to home page', async () => {
await page.goto(process.env.CONTACT_URL);
const logoExists = await page.$('a.logo') !== null;
expect(logoExists).toBe(true);
await page.click('a.logo');
await page.waitForNavigation();
const homeTitle = await page.title();
expect(homeTitle).toBe('Home - Example'); // Adjust this to the expected title of the Home page
});
test('should have consistent button styles and behavior', async () => {
await page.goto(process.env.ABOUT_URL);
const buttons = await page.$$('button');
expect(buttons.length).toBeGreaterThan(0);
for (const button of buttons) {
const buttonStyle = await button.evaluate(node => window.getComputedStyle(node).getPropertyValue('background-color'));
expect(buttonStyle).toBe('rgb(0, 123, 255)'); // Example: Bootstrap primary button color
const buttonDisabled = await button.evaluate(node => node.disabled);
if (!buttonDisabled) {
await button.click();
// Verify expected behavior after clicking the button (e.g., navigation, modal popup)
}
}
});
test('should have familiar form input elements', async () => {
await page.goto(process.env.CONTACT_URL);
const formExists = await page.$('form') !== null;
expect(formExists).toBe(true);
const inputTypes = ['text', 'email', 'password', 'submit'];
for (const type of inputTypes) {
const inputExists = await page.$(`input[type="${type}"]`) !== null;
expect(inputExists).toBe(true);
}
});
});
|
import React, { useState } from "react";
function Login() {
// State to store each input field value
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
//State to manage the loading screen and it's visibility
const [loading, setLoading] = useState(false);
//Function to handle form submission
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true); //Activate the loading screen
try {
//POST request to the backend login endpoint for authentication
const response = await fetch("/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username, password }),
});
const data = await response.json();
} finally {
setLoading(false); // Deactivate loading screen
}
};
// Display loading screen if 'loading' is true
if (loading) {
return <div>Loading...</div>;
}
// Login form with username and password fields
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Username"
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Login</button>
</form>
</div>
);
}
export default Login;
|
# rockycao
# coding: UTF-8
import numpy as np
import glob
import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
from tqdm import tqdm
import matplotlib.pyplot as plt
from os import getcwd
from sklearn.preprocessing import OneHotEncoder
###################################################
# In order for this code to work, you need to place this file in the same
# directory as the midi_manipulation.py file and the Pop_Music_Midi directory
import midi_manipulation
def get_songs(path):
files = glob.glob('{}/*.mid*'.format(path))
songs = []
for f in tqdm(files):
try:
song = np.array(midi_manipulation.midiToNoteStateMatrix(f))
if np.array(song).shape[0] > 50:
songs.append(song)
except Exception as e:
raise e
return songs
songs = get_songs('Pop_Music_Midi') # These songs have already been converted from midi to msgpack
print("{} songs processed".format(len(songs)))
###################################################
### HyperParameters
# First, let's take a look at the hyperparameters of our model:
TRAINING_PHASE = True
n_units = 256 # number of RNN units
lowest_note = midi_manipulation.lowerBound # the index of the lowest note on the piano roll
highest_note = midi_manipulation.upperBound # the index of the highest note on the piano roll
note_range = highest_note - lowest_note # the note range
num_timesteps = 10 # This is the number of timesteps that we will create at a time
eval_time_steps = 2 # how many timesteps of the input we want to use for backpropagation
n_visible = 2 * note_range * num_timesteps # This is the size of the visible layer.
n_hidden = 50 # This is the size of the hidden layer
num_epochs = 200 # The number of training epochs that we are going to run. For each epoch we go through the entire data set.
batch_size = 100 # The number of training examples that we are going to send through the RBM at a time.
lr = tf.constant(0.005, tf.float32) # The learning rate of our model
### Variables:
# Next, let's look at the variables we're going to use:
x = tf.placeholder(tf.float32, [batch_size, num_timesteps, n_visible], name="x") # The placeholder variable that holds our data
y = tf.placeholder(tf.float32, [batch_size, eval_time_steps, n_visible], name="y") # hold backprop input
W = tf.Variable(tf.random_normal([n_visible, n_hidden], 0.01),
name="W") # The weight matrix that stores the edge weights
bh = tf.Variable(tf.zeros([1, n_hidden], tf.float32, name="bh")) # The bias vector for the hidden layer
bv = tf.Variable(tf.zeros([1, n_visible], tf.float32, name="bv")) # The bias vector for the visible layer
#### Helper functions.
# This function lets us easily sample from a vector of probabilities
def sample(probs):
# Takes in a vector of probabilities, and returns a random vector of 0s and 1s sampled from the input vector
return tf.floor(probs + tf.random_uniform(tf.shape(probs), 0, 1))
# This function runs the gibbs chain. We will call this function in two places:
# - When we define the training update step
# - When we sample our music segments from the trained RBM
def gibbs_sample(k):
# Runs a k-step gibbs chain to sample from the probability distribution of the RBM defined by W, bh, bv
def gibbs_step(count, k, xk):
# Runs a single gibbs step. The visible values are initialized to xk
hk = sample(tf.sigmoid(tf.matmul(xk, W) + bh)) # Propagate the visible values to sample the hidden values
xk = sample(
tf.sigmoid(tf.matmul(hk, tf.transpose(W)) + bv)) # Propagate the hidden values to sample the visible values
return count + 1, k, xk
# Run gibbs steps for k iterations
ct = tf.constant(0) # counter
[_, _, x_sample] = control_flow_ops.while_loop(lambda count, num_iter, *args: count < num_iter,
gibbs_step, [ct, tf.constant(k), x])
# This is not strictly necessary in this implementation, but if you want to adapt this code to use one of TensorFlow's
# optimizers, you need this in order to stop tensorflow from propagating gradients back through the gibbs step
x_sample = tf.stop_gradient(x_sample)
return x_sample
### Run the graph!
# Now it's time to start a session and run the graph!
cell = tf.contrib.rnn.BasicLSTMCell(n_units)
initial_state = cell.zero_state(batch_size, tf.float32)
rnn_outputs, _rnn_states = tf.nn.dynamic_rnn(cell, x,initial_state=initial_state, time_major=False)
rnn_outputs_on_last_t_step = tf.slice(
rnn_outputs,
[0, num_timesteps - (1 + eval_time_steps), 0],
[batch_size, eval_time_steps, n_units])
final_projection = lambda z: tf.contrib.layers.linear(z, num_outputs=n_visible, activation_fn=tf.nn.sigmoid)
predicted = tf.map_fn(final_projection, rnn_outputs_on_last_t_step)
# Error and backprop
error = tf.nn.l2_loss(tf.subtract(tf.abs(y),tf.abs(predicted)))
train_step = tf.train.AdamOptimizer(lr).minimize(error)
# Prediction error and accuracy
accuracy = tf.reduce_mean(tf.subtract(tf.abs(y),tf.abs(predicted)))
if TRAINING_PHASE:
with tf.Session() as sess:
# First, we train the model
# initialize the variables of the model
init = tf.global_variables_initializer()
sess.run(init)
saver = tf.train.Saver()
# Run through all of the training data num_epochs times
for epoch in tqdm(range(num_epochs)):
error_function = np.zeros(num_epochs)
accuracy_function = np.zeros(num_epochs)
learning_rate_array = np.zeros(num_epochs)
batch = 0
tr_x = []
tr_y = []
for song in songs:
# The songs are stored in a time x notes format. The size of each song is timesteps_in_song x 2*note_range
song = np.array(song)
song = song[:int(np.floor(song.shape[0] / num_timesteps) * num_timesteps)]
song = np.reshape(song, [int(song.shape[0] / num_timesteps), int(song.shape[1] * num_timesteps)])
# Train the RBM on batch_size examples at a time
for i in range(0, len(song), num_timesteps):
if i+num_timesteps > len(song):
continue
sample = song[i:i + num_timesteps]
tr_x.append(sample)
tr_y.append(sample[-eval_time_steps:])
batch += 1
if batch == batch_size:
break
tr_x = np.array(tr_x)
tr_y = np.array(tr_y)
training_accuracy, prediction_error, _ = sess.run(
[accuracy,
error,
train_step],
feed_dict={x: tr_x, y: tr_y})
error_function[epoch] = prediction_error
accuracy_function[epoch] = training_accuracy
print(" accuracy and prediction error: {}, {}".format(training_accuracy, prediction_error))
saver.save(sess, getcwd()+'\\weight\\LSTM-weights', global_step=epoch)
# Plots for network optimization at end of each epoch
plt.subplot(311)
plt.xlabel("Batch number")
plt.ylabel("error")
plt.plot(error_function)
'''
plt.subplot(312)
plt.xlabel("Batch number")
plt.ylabel("Accuracy: mean difference between data point")
plt.plot(accuracy_function)
plt.subplot(313)
plt.xlabel("Batch number")
plt.ylabel("Learning rate")
plt.plot(learning_rate_array)
'''
plt.show()
# Now the model is fully trained, so let's make some music!
# Run a gibbs chain where the visible nodes are initialized to 0
#sample = gibbs_sample(1).eval(session=sess, feed_dict={x: np.zeros((50, n_visible))})
else:
with tf.Session() as sess:
# First, we train the model
# initialize the variables of the model
init = tf.global_variables_initializer()
sess.run(init)
tf.train.Saver().restore(sess, getcwd()+"\\weight\\LSTM-weights-199")
tr_x = []
tr_y = []
batch = 0
for song in songs:
# The songs are stored in a time x notes format. The size of each song is timesteps_in_song x 2*note_range
# Here we reshape the songs so that each training example is a vector with num_timesteps x 2*note_range elements
song = np.array(song)
song = song[:int(np.floor(song.shape[0] / num_timesteps) * num_timesteps)]
song = np.reshape(song, [int(song.shape[0] / num_timesteps), int(song.shape[1] * num_timesteps)])
# Train the RBM on batch_size examples at a time
for i in range(0, len(song), num_timesteps):
if i + num_timesteps > len(song):
continue
sample = song[i:i + num_timesteps]
tr_x.append(sample)
tr_y.append(sample[-eval_time_steps:])
batch += 1
if batch == batch_size:
break
tr_x = np.array(tr_x)
tr_y = np.array(tr_y)
output = sess.run(
predicted,
feed_dict={x: tr_x})
output = output.reshape(200,n_visible)
for i in range(output.shape[0]):
if not any(output[i, :]):
continue
# Here we reshape the vector to be time x notes, and then save the vector as a midi file
S = np.reshape(output[i, :], (num_timesteps, 2 * note_range))
F = []
for array in S:
pos = np.argmax(array)
array = np.zeros( 2 * note_range)
array[pos] = 1
F.append(array)
midi_manipulation.noteStateMatrixToMidi(F, "generated_chord_{}".format(i))
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;
using PaperSouls.Runtime.Items;
using PaperSouls.Runtime.Data;
namespace PaperSouls.Runtime.Inventory
{
[System.Serializable]
internal class InventoryManger
{
public List<InventorySlot> InventorySlots;
public int NumOfInventorySlots => InventorySlots.Count;
public UnityAction<InventorySlot> OnInventoryChange;
private Vector2Int _inventorySize;
/// <summary>
/// Create an inventory of size numRows by numCols
/// </summary>
public InventoryManger(int numRows, int numCols) : this(new Vector2Int(numRows, numCols)) { }
/// <summary>
/// Create an inventory of size given by a Vector2Int
/// </summary>
public InventoryManger(Vector2Int inventorySize)
{
this._inventorySize = inventorySize;
int size = inventorySize.x * inventorySize.y;
InventorySlots = new(size);
for (int i = 0; i < size; i++) InventorySlots.Add(new());
}
/// <summary>
/// Deseralize a List of Seralizanble inventory slots
/// </summary>
public InventoryManger(List<SerializableInventorySlot> slots)
{
InventorySlots = new();
foreach (SerializableInventorySlot slot in slots) InventorySlots.Add(slot.Deserialize());
}
/// <summary>
/// Gets the inventory slot that contains an item
/// </summary>
public bool GetInventorySlotForItem(Item item, out List<InventorySlot> inventorySlots)
{
inventorySlots = this.InventorySlots.Where(inventorySlots => inventorySlots.ItemData == item).ToList();
return inventorySlots.Count > 0;
}
/// <summary>
/// Gets the inventory slot that is empty
/// </summary>
public bool GetFreeInventorySlot(out InventorySlot slot)
{
slot = InventorySlots.FirstOrDefault(i => i.ItemData == null);
return slot != null;
}
/// <summary>
/// Add an item to a empty inventory slot
/// </summary>
public bool AddToInventoryFreeSlot(Item item, int amount)
{
if (GetFreeInventorySlot(out InventorySlot freeSlot))
{
if (item.maxStackSize < amount)
{
freeSlot.UpdateInventorySlot(item, item.maxStackSize);
AddToInventory(item, amount - item.maxStackSize);
} else freeSlot.UpdateInventorySlot(item, amount);
OnInventoryChange?.Invoke(freeSlot);
return true;
}
return false;
}
/// <summary>
/// Add an item to the next available inventory slot
/// </summary>
public bool AddToInventory(Item item, int amount)
{
if (GetInventorySlotForItem(item, out List<InventorySlot> inventorySlots))
{
foreach (InventorySlot slot in inventorySlots)
{
if (slot.CheckRoomLeftInStack(amount))
{
slot.AddToStack(amount);
OnInventoryChange?.Invoke(slot);
return true;
}
}
}
return AddToInventoryFreeSlot(item, amount);
}
/// <summary>
/// Add an item to ith inventory slot if available
/// </summary>
public bool AddToInventory(Item item, int amount, int index)
{
if (index >= NumOfInventorySlots) return false;
if (InventorySlots[index].ItemData == null)
{
InventorySlots[index].UpdateInventorySlot(item, amount);
OnInventoryChange?.Invoke(InventorySlots[index]);
return true;
}
else if (InventorySlots[index].CheckRoomLeftInStack(amount))
{
InventorySlots[index].AddToStack(amount);
OnInventoryChange?.Invoke(InventorySlots[index]);
return true;
}
return false;
}
/// <summary>
/// Returns true if item is in inventory
/// </summary>
public bool HasItem(Item item, int count = 1)
{
int countInInv =
InventorySlots
.Where(slot => slot.ItemData == item)
.Sum(slot => slot.StackSize);
return countInInv >= count;
}
/// <summary>
/// Takes 'count' items from the inventory if theres enought space
/// Returns true if there were enough items else false
/// </summary>
public bool TakeItem(Item item, int count)
{
if (!HasItem(item, count)) return false;
IEnumerable<InventorySlot> slotsOfItem = InventorySlots.Where(
slot => slot.ItemData == item
);
int leftToRemove = count;
foreach (var slot in slotsOfItem) {
int toRemove = Mathf.Min(slot.StackSize, leftToRemove);
slot.RemoveFromStack(toRemove);
leftToRemove -= toRemove;
OnInventoryChange?.Invoke(slot);
if (leftToRemove == 0) break;
}
return true;
}
public List<SerializableInventorySlot> Seralize()
{
List<SerializableInventorySlot> serializableSlots = new();
foreach (InventorySlot slot in InventorySlots) serializableSlots.Add(new((slot.ItemData != null) ? slot.ItemData.id : -1, slot.StackSize));
return serializableSlots;
}
}
}
|
<!DOCTYPE html>
<html>
<head>
<title>TechEd+ Backend разработка</title>
<style>
{% if u_theme == "theme1"%}
body {
font-family: Arial, sans-serif;
background-color: #0970ff;
color: #ffffff;
margin: 0;
padding: 0;
}
button{
border-radius: 10px;
transition: background-color 0.3s ease; /* Плавный переход для hover */
appearance: none;
border: 0;
background: #4676D7;
color: #fff;
padding: 8px 16px;
font-size: 16px;
}
button:hover{
background-color: #065ac8;
}
button:active{
background-color: #054496;
}
h1, h2 {
margin: 0;
padding: 0;
}
/* Стили для шапки */
.header {
background-color: rgb(0, 49, 156);
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
}
.header img {
width: 80px;
}
.services {
display: flex;
}
/* Стили для основного контента */
.content {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.Cname {
background-color: rgb(107, 12, 215);
color: #f9f9f9;
text-align: center;
padding: 50px 0;
}
h2 {
font-size: 24px;
margin-top: 30px;
}
p {
font-size: 18px;
line-height: 1.5;
}
ul, ol {
font-size: 16px;
list-style-type: none;
margin-top: 10px;
}
li {
margin-bottom: 10px;
}
a {
color: #ffffff;
text-decoration: none;
}
a:hover {
color: #999999;
}
.contentMain{
text-align: center;
background-color: #ffffff;
border-radius: 2%;
height: 600px;
padding: 10px;
color: black;
width: 100%;
height: 30%;
position: relative;
word-wrap: break-word;
overflow-wrap: break-word;
}
.greyform{
background-color: #897ee3;
padding: 10px;
border-radius: 5px;
text-align: left;
width: 300px;
padding-bottom: 90px;
position: relative;
}
.centerGO{
}
.text{
margin-right: 70px;
margin-top: 10px;
margin-left: 70px;
}
.text{
margin-right: 70px;
margin-top: 10px;
margin-left: 70px;
}
{% elif u_theme == "theme2"%}
body {
font-family: Arial, sans-serif;
background: url('https://w.forfun.com/fetch/c6/c6b3b78a23b1262fcd61b6dda5e272da.jpeg');
color: #ffffff;
margin: 0;
padding: 0;
}
button{
border-radius: 10px;
transition: background-color 0.3s ease; /* Плавный переход для hover */
appearance: none;
border: 0;
background: #4676D7;
color: #fff;
padding: 8px 16px;
font-size: 16px;
}
button:hover{
background-color: #065ac8;
}
button:active{
background-color: #054496;
}
h1, h2 {
margin: 0;
padding: 0;
}
/* Стили для шапки */
.header {
background-color: #000000;
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
}
.header img {
width: 80px;
}
.services {
display: flex;
}
/* Стили для основного контента */
.content {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.Cname {
background-color: rgb(107, 12, 215);
color: #f9f9f9;
text-align: center;
padding: 50px 0;
}
h2 {
font-size: 24px;
margin-top: 30px;
}
p {
font-size: 18px;
line-height: 1.5;
}
ul, ol {
font-size: 16px;
list-style-type: none;
margin-top: 10px;
}
li {
margin-bottom: 10px;
}
a {
color: #ffffff;
text-decoration: none;
}
a:hover {
color: #999999;
}
.contentMain{
text-align: center;
background-color: #ffffff;
border-radius: 2%;
padding: 30px;
color: black;
width: 100%;
height: 30%;
position: relative;
word-wrap: break-word;
overflow-wrap: break-word;
}
.greyform{
background-color: #897ee3;
padding: 10px;
border-radius: 5px;
text-align: left;
width: 300px;
padding-bottom: 90px;
position: relative;
}
.text{
margin-right: 70px;
margin-top: 10px;
margin-left: 70px;
}
{% elif u_theme == "theme3"%}
body {
font-family: Arial, sans-serif;
background: url('https://w.forfun.com/fetch/26/263b73d772df647688e1fe0fe74c3270.jpeg');
color: #ffffff;
margin: 0;
padding: 0;
}
button{
border-radius: 10px;
transition: background-color 0.3s ease; /* Плавный переход для hover */
appearance: none;
border: 0;
background: #47008e;
color: #fff;
padding: 8px 16px;
font-size: 16px;
}
button:hover{
background-color: #5f03ab;
}
button:active{
background-color: #39006f;
}
h1, h2 {
margin: 0;
padding: 0;
}
/* Стили для шапки */
.header {
background-color: rgb(52, 0, 95);
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
}
.header img {
width: 80px;
}
.services {
display: flex;
}
/* Стили для основного контента */
.content {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.Cname {
background-color: rgb(107, 12, 215);
color: #f9f9f9;
text-align: center;
padding: 50px 0;
}
h2 {
font-size: 24px;
margin-top: 30px;
}
p {
font-size: 18px;
line-height: 1.5;
}
ul, ol {
font-size: 16px;
list-style-type: none;
margin-top: 10px;
}
li {
margin-bottom: 10px;
}
a {
color: #ffffff;
text-decoration: none;
}
a:hover {
color: #999999;
}
.contentMain{
text-align: center;
background-color: #ffffff;
border-radius: 2%;
height: 600px;
padding: 10px;
color: black;
width: 100%;
height: 30%;
position: relative;
word-wrap: break-word;
overflow-wrap: break-word;
}
.greyform{
word-break: break-all;
display: block;
background-color: #897ee3;
padding: 10px;
border-radius: 5px;
text-align: left;
width: 300px;
padding-bottom: 90px;
position: relative;
}
.centerGO{
}
.text{
margin-right: 70px;
margin-top: 10px;
margin-left: 70px;
}
.text{
margin-right: 70px;
margin-top: 10px;
margin-left: 70px;
}
{% endif %}
</style>
</head>
<body>
{% if u_theme == "theme2" or u_theme == "theme3"%}
<img src="https://im.wampi.ru/2023/08/26/ClipDropImage1693075241003.png" style="
width: 50px;
left: 20px;
position: absolute;
top: 190px;
cursor: pointer;" id="backP" onmouseover="changeCursor()">
{% else %}
<img src="https://im.wampi.ru/2023/06/19/angle-left.png" style="
width: 50px;
left: 20px;
position: absolute;
top: 190px;
cursor: pointer;" id="backP" onmouseover="changeCursor()">
{% endif %}
<div class="header">
<img src="https://ie.wampi.ru/2023/07/19/ClipDropImage1689779800774.png" style="width: 130px;left: 20px;margin-left: 30px;">
<div class="services">
<h1 style="
position: relative;
left: 120px;
top: 35px;
">Backend разработка</h1>
<p style="
position: relative;
margin-left: 100px;
margin-right: 100px;
border-left-width: 10px;
padding-left: 120px;
padding-right: 80px;
left: 60px;">Бэкенд - это серверная сторона любого сайта или приложения, которая отвечает за все то, что на самом деле происходит, но вы не видите этого у себя на экранах. Потому он и называется Back-end, ведь это как бы задняя, скрытая сторона программных продуктов.</p>
</div>
</div>
<div class="content">
<div class="contentMain">
<div class="text">
<h1>Введение в Backend-разработку</h1>
<h2>Что такое Backend?</h2>
<p>Backend - это область разработки, которая занимается созданием серверной части веб-приложений. Backend-разработчики отвечают за обработку данных, бизнес-логику и взаимодействие с базами данных.</p>
<h2>Мастерство Backend-разработчика</h2>
<p>Backend-разработчику необходимо обладать навыками:</p>
<ul>
<li>Языки программирования, такие как Java, Python, Ruby, PHP, Node.js, для создания серверной логики.</li>
<li>Фреймворки, такие как Django, Flask, Ruby on Rails, Laravel, для ускорения разработки и повышения безопасности.</li>
<li>Управление базами данных с помощью SQL или NoSQL, например, MySQL, PostgreSQL или MongoDB.</li>
<li>API (Application Programming Interface) для взаимодействия с другими веб-сервисами.</li>
<li>Знание систем управления версиями, таких как Git.</li>
</ul>
<h2>Разработка Backend-приложений</h2>
<p>Для разработки Backend-приложений необходимо:</p>
<ol>
<li>Выбрать язык программирования и фреймворк, соответствующий требованиям проекта.</li>
<li>Создать логику обработки запросов и взаимодействия с базой данных.</li>
<li>Реализовать безопасность приложения, включая аутентификацию и авторизацию.</li>
<li>Настроить и оптимизировать серверное окружение для обработки запросов и обеспечения масштабируемости.</li>
</ol>
<h2>Популярные Backend-технологии</h2>
<p>Существует множество технологий и инструментов, которые используются в Backend-разработке:</p>
<ul>
<li>Java и фреймворк Spring</li>
<li>Python и фреймворк Django</li>
<li>Node.js и фреймворк Express</li>
<li>PHP и фреймворк Laravel</li>
<li>Ruby и фреймворк Ruby on Rails</li>
<li>ASP.NET и фреймворк ASP.NET Core</li>
<li>Базы данных, такие как MySQL, PostgreSQL, MongoDB</li>
</ul>
<h2>Заключение</h2>
<p>Backend-разработка является важной частью создания веб-приложений и вовлекает в себя множество технологий и навыков. Разработка серверной части приложений позволяет обрабатывать данные, управлять бизнес-логикой и взаимодействовать с базами данных. Надеемся, что это введение в Backend-разработку было полезным!</p>
</div>
{% if user_vision == True%}
<div class="centerGO">
<a href="{% url 'send_user_courses' course='Backend' %}"><button type="button">Изучать</button></a> <!-- <a href=""><button type="button"> Закончить изучение</button></a> -->
</div>
{% else %}
{% endif %}
<h2 style="
position: relative;
left: -400px;
">Материалы и ресурсы</h2>
<ul>
<div class="greyform" style="padding-bottom: 10px;padding-right: 120px;">
<li><a href="https://habr.com/ru/companies/ruvds/articles/488340/" style="color: black;">Профессия: бэкенд-разработчик / Хабр</a></li>
<li><a href="https://practicum.yandex.ru/blog/chem-otlichaetsya-backend-i-frontend/" style="color: black;">Frontend и Backend-разработка: что это, в чем разница</a></li>
<li><a href="https://htmlacademy.ru/blog/job/backend-is-ok" style="color: black;">12 вопросов о бэкенде, которые не стыдно задавать в 2022</a></li>
</div>
</ul>
</div>
</div>
</body>
<script>
document.getElementById('backP').addEventListener('click', () => {
history.back();
});
</script>
</html>
|
package BT2_phamvitruycap.person;
import java.util.Stack;
public class Person {
//Tạo class "Person" với các thông tin: name, age, gender, address, phone
private String name;
private int age;
private String gender;
private String address;
private String phone;
//Hàm xây dựng không có tham số
public Person ()
{
name = "Phương";
age = 20;
address = "BÌnh định";
gender = "Nữ";
phone = "0336727019";
}
//Hàm xây dựng không có tham số
public Person(String name, int age, String gender, String address, String phone) {
this.name = name;
this.age = age;
this.gender = gender;
this.address = address;
this.phone = phone;
}
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
//Các hàm get truy xuất thông tin
public String getname()
{
return name;
}
public int getAge()
{
return age;
}
public String getGender()
{
return gender;
}
protected String getAddress()
{
return address;
}
protected String getPhone()
{
return phone;
}
protected void getinfo()
{
System.out.println("Tên: " + getname());
System.out.println("Tuổi: " + getAge());
System.out.println("Giới tính: " + getGender());
System.out.println("Địa chỉ: " + getAddress());
System.out.println("SDT" + getPhone());
}
public void getinfoCompanyClass()
{
System.out.println("Tên: " + getname());
System.out.println("Tuổi: " + getAge());
System.out.println("Giới tính: " + getGender());
}
}
/* BÀI TẬP PHẦN PACKAGE VÀ PHẠM VI TRUY CẬP
- Tại package "person" :
+ Tạo class "Person" với các thông tin: name, age, gender, address, phone
+ Hàm xây dựng và hàm get tương ứng để giải quyết bài toán theo yêu cầu
+ Tạo class "Information" để gọi lại tất cả các thông tin từ class Person
- Tại package "company" :
Yêu cầu: + Tạo class "Company" để gọi lại thông tin từ class Person: name, age, gender. Còn lại các thông tin khác không được hiển thị ra. */
|
# views.py
from flask import render_template, request, redirect, url_for, session, Blueprint, flash, jsonify
from models import User
from extensions import db, bcrypt
from flask_bcrypt import Bcrypt
views = Blueprint("views", __name__)
bcrypt = Bcrypt()
@views.route("/signup", methods=["GET", "POST"])
def signup():
if request.method == "POST":
username = request.form["username"]
email = request.form["email"]
password = bcrypt.generate_password_hash(request.form["password"]).decode(
"utf-8"
)
if (
User.query.filter_by(username=username).first()
or User.query.filter_by(email=email).first()
):
# User already exists
flash("Username or email already in use.", "error")
return redirect(url_for("views.signup")), 400
new_user = User(username=username, email=email, password=password)
db.session.add(new_user)
db.session.commit()
flash("Account created successfully, please login.", "success")
return redirect(url_for("views.login")), 201
return render_template("signup.html", title="Sign Up")
@views.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
email = request.form["email"]
password = request.form["password"]
user = User.query.filter_by(email=email).first()
if user and bcrypt.check_password_hash(user.password, password):
session["username"] = user.username
flash("Logged in successfully.", "success")
return redirect(url_for("views.home")), 200
else:
flash("Invalid email or password.", "error")
return redirect(url_for("views.home")) , 401
return render_template("login.html", title="Login")
@views.route("/logout")
def logout():
session.pop("username", None)
flash("You have been logged out.", "info")
return redirect(url_for("views.login")) , 200
@views.route("/")
def home():
if "username" in session:
return render_template("home.html", title="Home")
flash("Please login to view this page.", "info")
return redirect(url_for("views.login")), 200
@views.route("/delete/<user>", methods=['DELETE'])
def delete(user):
data = User.query.filter_by(username=user).first()
if data:
db.session.delete(data)
db.session.commit()
session.pop("username", None)
print('Your account has been deleted!')
return jsonify({'success': True})
#return redirect(url_for('views.login')), 200
else:
print("Not working")
return redirect(url_for('views.signup'))
@views.route("/update/<user>", methods=['GET', 'PATCH'])
def update(user):
if request.method == 'GET':
return render_template("update.html", title="Update")
else:
new_password = request.json.get('new_password')
data = User.query.filter_by(username=user).first()
if data:
# Update the password field with the new password
password = bcrypt.generate_password_hash(new_password).decode("utf-8")
data.password = password
# Commit the changes to the database
db.session.commit()
print('Your password has been updated!')
return redirect(url_for("views.login")), 200
else:
print('User not found!', 'error')
return redirect(url_for("views.home")), 404
|
import uuid
from django.contrib.auth.models import User, Permission, Group
from django.contrib.contenttypes.models import ContentType
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.db.models import Model
from django.test import TestCase, RequestFactory
from tokenize import String
class XFTestCase(TestCase):
"""
Serves as a base class with methods that can help you generate your test data
"""
fixtures = ['default_pages_and_perspectives_data.json']
def generate_user(self, username: str=None, password: str=None, first_name: str=None, last_name: str=None,
email: str=None):
"""
Generates a user and adds extension methods on this user to assist in easily performing the following
1. assigning model permission to the user:
call this method user.assign_model_permission(permission: String, model: Model)
2. assign a permission token to a user:
call user.assign_token(token_name: String, tokens_model: Model). Tokens are special permissions for access
to particular areas in your application. They are generally prefixed with token_ e.g. token_ui_cd4
3. remove token:
call user.remove_token(token_name: String)
4. assign a user to a group: call user.assign_to(group: Group)
:param username: Optional
:param password: Optional
:param first_name: Optional
:param last_name: Optional
:param email: Optional
:return:
"""
user = User.objects.create_user(
username=str(uuid.uuid4()) if username is None else username,
email=email,
password='empty' if password is None else password,
first_name="first" if first_name is None else first_name,
last_name="last" if last_name is None else last_name,
)
user.save()
def assign_model_permission(self, permission_to_assign: String, model: Model):
permission_to_assign = '{}_{}'.format(permission_to_assign, model._meta.model_name)
content_type, created = ContentType.objects.get_or_create(app_label=model._meta.app_label,
model=model._meta.model_name)
permission, created = Permission.objects.get_or_create(
codename=permission_to_assign,
content_type=content_type,
defaults={'name': 'Can list records'},
)
self.user_permissions.add(permission)
reloaded_user = User.objects.get(pk=self.pk)
return reloaded_user
def assign_token(self, token: String, model):
content_type, created = ContentType.objects.get_or_create(
app_label=model._meta.app_label,
model=model._meta.model_name
)
permission, created = Permission.objects.get_or_create(
codename=token,
content_type=content_type,
defaults={'name': token.replace('_', ' ')},
)
self.user_permissions.add(permission)
reloaded_user = User.objects.get(pk=self.pk)
return reloaded_user
def remove_token(self, token: String):
self.user_permissions.remove(Permission.objects.get(codename=token))
reloaded_user = User.objects.get(pk=self.pk)
return reloaded_user
def assign_to_group(self, group: Group):
self.groups.add(group)
reloaded_user = User.objects.get(pk=self.pk)
return reloaded_user
User.assign_model_permission = assign_model_permission
User.assign_token = assign_token
User.remove_token = remove_token
User.assign_to = assign_to_group
return user
def setup_request(self, request, user: User, session_data: dict=None):
request.user = user
"""Annotate a request object with a session"""
middleware = SessionMiddleware()
middleware.process_request(request)
request.session.save()
"""Annotate a request object with a messages"""
middleware = MessageMiddleware()
middleware.process_request(request)
request.session.save()
if session_data is not None:
for key, value in session_data:
request.session[key] = value
request.session.save()
return request
def generate_request(self, path: str=None, user: User=None):
factory = RequestFactory()
request = factory.get('/' if path is None else path)
if user:
request.user = user
return request
|
package main
import (
"errors"
"net/http"
"github.com/Joanoni/inutil"
)
type ExecuteInput struct {
Method string `json:"method"`
Url string `json:"url"`
Header []Header `json:"header"`
Payload any `json:"payload"`
}
type Header struct {
Name string `json:"name"`
Value string `json:"value"`
}
type ExecuteOutput struct {
Body any `json:"body"`
StatusCode int `json:"statusCode"`
}
func main() {
s := inutil.Start(&inutil.StartInput{
Server: &inutil.StartServerInput{
Port: ":7963",
},
Log: &inutil.StartLogInput{
InternalLog: inutil.StartLogEnvInput{
Development: true,
Stage: true,
Production: true,
},
DebugLog: inutil.StartLogEnvInput{
Development: true,
Stage: true,
Production: true,
},
TimeFormat: inutil.LogFormat,
},
Enviroment: inutil.Enviroment_Development,
})
s.Server.Use(inutil.MiddlewareCors())
s.Server.Use(inutil.MiddlewareLog())
s.Server.Use(inutil.MiddlewareSafety())
s.Server.Get("/api/test/get", okHandler)
s.Server.Get("/api/test/error", errorHandler)
s.Server.Post("/api/test/post", postHandler)
s.Server.Post("/api/execute", executeHandler)
s.Server.Run()
}
func okHandler(c *inutil.Context) {
data := map[string]any{
"hello": "world",
}
inutil.JSON(inutil.Return[map[string]any]{
Message: "success",
Data: &data,
Success: true,
StatusCode: inutil.StatusOK,
}, c)
}
func postHandler(c *inutil.Context) {
var body any
err := c.Body(&body)
if c.HandleError(err) {
return
}
inutil.LogDebug(body)
inutil.JSON(inutil.Return[any]{
Message: "success",
Data: &body,
Success: true,
StatusCode: inutil.StatusOK,
}, c)
}
func errorHandler(c *inutil.Context) {
c.HandleError(errors.New("erro feio"))
}
func executeHandler(c *inutil.Context) {
var input ExecuteInput
err := c.Body(&input)
if c.HandleError(err) {
return
}
inutil.LogDebug(input)
headers := http.Header{}
for _, header := range input.Header {
inutil.LogDebug(header)
headers.Set(header.Name, header.Value)
}
var resp inutil.Return[inutil.RequestReponse[*any]]
if input.Payload == nil {
resp = inutil.Request[any](inutil.RequestInput{
Method: input.Method,
Url: input.Url,
Payload: nil,
Header: headers,
}, c)
} else {
resp = inutil.Request[any](inutil.RequestInput{
Method: input.Method,
Url: input.Url,
Payload: &inutil.RequestPayloadInput{
Body: input.Payload,
ContentType: inutil.ApplicationJSON,
},
Header: headers,
}, c)
}
inutil.LogDebug(resp)
inutil.JSON(inutil.Return[ExecuteOutput]{
Message: resp.Message,
Data: &ExecuteOutput{
Body: resp.Data.Body,
StatusCode: resp.Data.StatusCode,
},
Success: true,
StatusCode: inutil.StatusOK,
}, c)
}
|
import { Component, ViewEncapsulation, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { IUser } from '@appCore/models/User';
import { ClientService } from '@appCore/services/client.service';
import { StoreServices } from '@appCore/services/store.services';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CrudServiceShop } from '@appCore/services/crud.shop';
import { firebase } from '@appCore/firebase/firebase-config';
import * as moment from 'moment';
import Swal from 'sweetalert2';
@Component({
selector: 'app-checker',
templateUrl: './checker.component.html',
styleUrls: ['./checker.component.scss'],
encapsulation: ViewEncapsulation.None,
providers: [CrudServiceShop],
})
export class ClientCheckerModalComponent implements OnInit {
clientData: IUser = {
uid: '',
photoURL: 'Loading....',
displayName: './assets/images/avatars/avatar.jpg',
};
isReg: boolean = false;
isLoad: boolean = false;
isSaving: boolean = false;
contactForm: FormGroup;
shopLocation: any = {};
private fgn: String;
shopStatus: string ='';
constructor(
public matDialogRef: MatDialogRef<ClientCheckerModalComponent>,
@Inject(MAT_DIALOG_DATA) private _data: any,
private _clientSrvc: ClientService,
private _StoreServices: StoreServices,
private _formBuilder: FormBuilder,
private _CrudServiceShop: CrudServiceShop
) {
this._clientSrvc.onUserDataInfo.subscribe((userData) => {
this.clientData = userData;
});
this._StoreServices.onAutoShop.subscribe((response) => {
const statuses:string[] = ['REJECTED', 'PENDING'];
setTimeout(() => {
if (!!(response|| {}).uid) {
this.shopStatus = response.status;
this.isReg = true;
this.isLoad = true;
if (this.isReg && !statuses.includes( response.status)) {
this.matDialogRef.close();
}
}else {
this.isLoad = true;
this.isReg = false;
}
}, 1000);
});
this.contactForm = this.createContactForm();
}
ngOnInit(): void { }
createContactForm(): FormGroup {
const phone = '^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-s./0-9]*$';
const mobilePattern = '^((\\+91-?)|0)?[0-9]{10}$';
const urlPattern = '(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?';
return this._formBuilder.group({
name: ['', Validators.required],
secondName: ['', Validators.required],
mobile: ['', [Validators.required, Validators.pattern(mobilePattern)]],
phone: ['', [Validators.required, Validators.pattern(phone)]],
email: ['', [Validators.required, Validators.email]],
domain: ['', [Validators.required, Validators.pattern(urlPattern)]],
founded: ['', Validators.required],
address: ['', Validators.required],
notes: [],
});
}
patchValuesHere(data) {
this.contactForm.patchValue({ address: data });
}
onSave(): void {
this.isSaving = true;
const formData = this.contactForm.getRawValue();
formData.uid = this.clientData.uid;
formData.status = 'PENDING';
formData.founded = moment(formData.founded).format('dddd, MMMM Do YYYY');
formData.dateCreated = firebase.firestore.Timestamp.fromDate(new Date());
formData.shopLocation = this.shopLocation;
setTimeout(() => {
this._CrudServiceShop.insertNewShop(formData).then(() => {
Swal.fire('Good job!', 'Submission completed!', 'success');
this.isSaving = false;
})
}, 1000)
}
handleAddressChange(googleProps: any) {
this.contactForm.patchValue({ address: googleProps.formatted_address });
const { location } = googleProps.geometry;
this.shopLocation = {
latitude: location.lat(),
longitude: location.lng(),
};
}
}
|
package model;
import repository.AccRepository;
import repository.EmpRepository;
import Util.Validate;
import java.util.Scanner;
import java.util.regex.Pattern;
public class AccountModel {
public static final String RED = "\u001B[31m";
public static final String RESET = "\u001B[0m";
public static final String YELLOW = "\u001B[33m";
public static final String BACKGROUND_CYAN = "\u001B[45m";
public static final String BACKGROUND_WHITE= "\u001B[47m";
public static final String BACKGROUND_GREEN = "\u001B[42m";
private static final String GREEN = "\u001B[35m";
private static final String GREEN2 = "\u001B[32m";
static Validate validate = new Validate();
public static final int LENGTH_MIN = 0;
public static final int LENGTH_MAX_ID = 5;
public static final int LENGTH_MAX_NAME = 30;
//1. Attributes
private int acc_Id;
private String acc_name;
private String acc_pass;
private boolean role_acc;
private String emp_id;
private boolean acc_Status;
//2. Set,get
public int getAcc_Id() {
return acc_Id;
}
public void setAcc_Id(int acc_Id) {
this.acc_Id = acc_Id;
}
public String getAcc_name() {
return acc_name;
}
public void setAcc_name(String acc_name) {
this.acc_name = acc_name;
}
public String getAcc_pass() {
return acc_pass;
}
public void setAcc_pass(String acc_pass) {
this.acc_pass = acc_pass;
}
public String getEmp_id() {
return emp_id;
}
public void setEmp_id(String emp_id) {
this.emp_id = emp_id;
}
public boolean isAcc_Status() {
return acc_Status;
}
public void setAcc_Status(boolean acc_Status) {
this.acc_Status = acc_Status;
}
public boolean isRole_acc() {
return role_acc;
}
public void setRole_acc(boolean role_acc) {
this.role_acc = role_acc;
}
//3. Constructor
public AccountModel() {
}
public AccountModel(String acc_name, String acc_pass, boolean role_acc, String emp_id, boolean acc_Status) {
this.acc_name = acc_name;
this.acc_pass = acc_pass;
this.role_acc = role_acc;
this.emp_id = emp_id;
this.acc_Status = acc_Status;
}
//4. Input, Output
public void inputAcc(Scanner scanner){
this.acc_name = validateAccName(scanner);
this.acc_pass = validatePass(scanner);
this.role_acc = validateRole(scanner);
this.emp_id = validateEmpInAcc(scanner);
this.acc_Status = validateAccStatus(scanner);
}
public void displayAccountMessage(){
String acc_status_in = this.acc_Status ? "Hoạt động" : "Khoá";
String role = this.role_acc ? "ADMIN" : "USER";
System.out.printf("|\t%-6d |\t%-15.15s |\t%-10.10s |\t%-10.10s |\t%-10.10s |\t%-10.10s \n",
this.acc_Id, this.acc_name, this.acc_pass, this.emp_id, role, acc_status_in);
}
//5 Business methods
public String validateAccName(Scanner scanner){
do {
System.out.println("Nhập tên tài khoản");
String userName = scanner.nextLine();
byte error = 0;
String regex = "^[A-Za-z_][A-Za-z0-9_]{4,29}$";
if (!Pattern.matches(regex,userName)){
System.out.println("Tên không chứa kí tự đặc biệt. từ 4 kí tự");
error++;
}
if(validate.isStrNull(userName)){
System.out.println("Không được để trống");
error++;
}
if (!validate.isLength(userName,LENGTH_MIN,LENGTH_MAX_NAME)){
System.out.printf("Độ dài không quá %d kí tự \n.", LENGTH_MAX_NAME);
error++;
}
AccountModel acc = AccRepository.getAccByName(userName);
if (acc!=null){
System.out.println("Tên tài khoản đã tồn tại");
error++;
}
if (error ==0){
return userName;
}
}while (true);
}
public String validatePass (Scanner scanner){
do {
System.out.println("Nhập Mật khẩu");
String passStr = scanner.nextLine();
byte error = 0;
if (validate.isStrNull(passStr)){
System.out.println("Không được để trống");
error++;
}
if (validate.isPassWord(passStr)){
System.out.println("Sai định dạng. Mật khẩu có độ dài 8-30 kí tự");
error++;
}
if (error ==0 ){
return passStr;
}
}while (true);
}
public boolean validateRole (Scanner scanner){
do {
System.out.println("Cấp quyền cho tài khoản. ");
System.out.println(" 0. Admin 1. User ");
try {
byte choice = Byte.parseByte(scanner.nextLine());
switch (choice){
case 0: return true;
case 1: return false;
default:
System.out.println(RED+"Lựa chọn của bạn không hợp lệ"+RESET);
break;
}
}catch (Exception e){
System.out.println(RED+"Lựa chọn của bạn không hợp lệ"+RESET);
}
}while (true);
}
public String validateEmpInAcc(Scanner scanner){
do {
System.out.println("Mã nhân viên:");
String empId = scanner.nextLine();
byte error = 0;
EmployeeModel emp = EmpRepository.getEmpById(empId);
if (emp == null){
System.out.println("Nhân viên này không tồn tại");
error++;
}
if (!validate.isLength(empId,LENGTH_MIN,LENGTH_MAX_ID)){
System.out.printf("Độ dài không quá %d kí tự \n.", LENGTH_MAX_ID);
error++;
}
if (validate.isStrNull(empId)){
System.out.println("Không được để trống.");
error++;
}
if(AccRepository.checkExitsInAccByEmpById(empId)){
System.out.println("Nhân viên này đã được tạo tài khoản.");
error++;
}
if (error == 0){
return empId;
}
}while (true);
}
public boolean validateAccStatus(Scanner scanner) {
System.out.println("Trạng thái Tài khoản: ");
System.out.println("1. Hoạt động 2.Khoá");
byte error = 0;
do {
try {
byte statusProduct = Byte.parseByte(scanner.nextLine());
switch (statusProduct){
case 1: case 0:
return true;
case 2:
return false;
default:
System.out.println("Lựa chọn của bạn không có.");
break;
}
} catch (NumberFormatException numberFormatException){
System.out.println("Vui lòng nhập số 1 hoặc số 2 hoặc Enter để bỏ qua");
} catch (Exception e){
System.out.println("Vui lòng nhập số 1 hoặc số 2 hoặc Enter để bỏ qua");
}
} while (true);
}
}
|
<!DOCTYPE html>
<html>
<head>
<title>First Non-Repeating Character</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
h1 {
text-align: center;
margin-top: 20px;
}
label {
display: block;
margin: 10px 0;
}
input[type="text"] {
padding: 10px;
border-radius: 5px;
border: none;
box-shadow: 0 0 5px gray;
width: 80%;
max-width: 400px;
}
button {
padding: 10px 20px;
background-color: dodgerblue;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
margin-left: 10px;
}
button:hover {
background-color: deepskyblue;
}
p {
margin-top: 20px;
font-size: 1.2em;
font-weight: bold;
}
</style>
</head>
<body>
<h1>First Non-Repeating Character Finder</h1>
<form>
<label for="inputString">Enter a string:</label>
<input type="text" id="inputString" placeholder="Enter a string">
<button type="button" onclick="showFirstNonRepeating()">Find first non-repeating character</button>
</form>
<p id="result"></p>
<script>
function firstNonRepeatingChar(str) {
// Create an empty object to store the count of each character
const charCount = {};
// Iterate through the string and count each character occurrence
for (let i = 0; i < str.length; i++) {
const char = str[i];
charCount[char] = charCount[char] ? charCount[char] + 1 : 1;
}
// Find the first character with a count of 1
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (charCount[char] === 1) {
return char;
}
}
// If no non-repeating character is found, return null
return null;
}
function showFirstNonRepeating() {
const inputString = document.getElementById("inputString").value;
const firstNonRepeating = firstNonRepeatingChar(inputString);
const resultElement = document.getElementById("result");
if (firstNonRepeating) {
resultElement.innerHTML = "The first non-repeating character is: " + firstNonRepeating;
resultElement.style.color = "green";
} else {
resultElement.innerHTML = "No non-repeating character found.";
resultElement.style.color = "red";
}
}
</script>
</body>
</html>
|
import 'package:flutter/material.dart';
import 'package:flutter_ahlul_quran_app/common/contants.dart';
import 'package:flutter_ahlul_quran_app/cubit/surah/surah_cubit.dart';
import 'package:flutter_ahlul_quran_app/ui/ayat.page.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SurahPage extends StatefulWidget {
const SurahPage({super.key});
@override
State<SurahPage> createState() => _SurahPageState();
}
class _SurahPageState extends State<SurahPage> {
@override
void initState() {
context.read<SurahCubit>().getAllSurah();
super.initState();
}
// @override
// void initState() {
// context.read<SurahCubit>()
// super.initState();
// }
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.white),
title: const Text("Al Qur'an", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.white),),
centerTitle: true,
backgroundColor: AppColors.primary,
),
body: BlocBuilder<SurahCubit, SurahState>(
builder: (context, state) {
if (state is SurahLoading) {
return const Center(
child: CircularProgressIndicator.adaptive(),
);
}
if (state is SurahLoaded) {
return ListView.builder(
itemBuilder: (context, index) {
final surah = state.listSurah[index];
return InkWell(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return AyatPage(surah: surah,);
}));
},
child: Card(
child: ListTile(
leading: CircleAvatar(backgroundColor: AppColors.primary,
child: Text('${surah.nomor}',
style: const TextStyle(color: AppColors.white),
),
),
title: Text('${surah.namaLatin}, ${surah.nama}'),
subtitle: Text('${surah.arti}, ${surah.jumlahAyat} Ayat'),
),
),
);
},
);
}
return const Center(
child: Text('No Data'),
);
},
),
);
}
}
|
## 롤(ROLE)
---
- 사용자에게 허가할 수 있는 **권한들의 집합**
- 롤을 이용하면 권한 부여와 회수를 쉽게 가능
- 롤은 CREATE ROLE 권한을 가진 USER에 의해서 생성됨
- 한 사용자가 여러 개의 ROLE을 ACCESS 할 수 있고, 여러 사용자에게 ROLE을 부여 가능
- 시스템 권한을 부여 & 취소할 때와 동일한 명령을 사용하여 사용자에게 부여하고 취소함
- 사용자는 ROLE에 ROLE을 부여할 수 있음
- Orable DB를 설치하면 기본적으로 CONNECT, RESOURCE, DBA ROLE이 제공됨

<br>
### 1. ROLE 생성하기
```SQL
CREATE ROLE manager;
```
### 2. ROLE에 권한 부여하기
```SQL
GRANT CREATE SESSION, CREATE TABLE TO manager;
```
### 3. 권한이 부여된 ROLE을 USER나 ROLE에 부여하기
```SQL
GRANT manager TO scott, test; // scott, test라는 유저에게 부여한다는 의미
```
|
#pragma once
#ifndef HGUARD__UTIL__FORMATTERS_HH_
#define HGUARD__UTIL__FORMATTERS_HH_
#include "Common.hh"
/****************************************************************************************/
namespace fmt {
inline namespace v8 {
template <>
struct formatter<::timespec>
{
private:
static constexpr double nsec_to_second = 1'000'000'000.0;
public:
//NOLINTNEXTLINE(*convert-member-functions-to-static)
constexpr auto parse(format_parse_context const &ctx) -> decltype(ctx.begin())
{
auto const *const it = ctx.begin();
if (it + 1 != ctx.end() && *it != '}')
throw format_error("invalid format");
return it;
}
template <typename FormatContext>
constexpr auto format(::timespec const &p, FormatContext &ctx) -> decltype(ctx.out())
{
double const sec = static_cast<double>(p.tv_sec); //NOLINT(*use-auto)
double const nsec = static_cast<double>(p.tv_nsec); //NOLINT(*use-auto)
double const val = sec + (nsec / nsec_to_second);
return format_to(ctx.out(), FMT_COMPILE("{}s"), val);
}
};
template <>
struct formatter<util::hacks::path>
{
//NOLINTNEXTLINE(*convert-member-functions-to-static)
constexpr auto parse(format_parse_context const &ctx) -> decltype(ctx.begin())
{
auto const *const it = ctx.begin();
if (it + 1 != ctx.end() && *it != '}')
throw format_error("invalid format");
return it;
}
template <typename FormatContext>
constexpr auto format(util::hacks::path const &p, FormatContext &ctx) -> decltype(ctx.out())
{
return format_to(ctx.out(), FMT_COMPILE("{}"), p.string());
}
};
template <>
struct formatter<std::error_code>
{
//NOLINTNEXTLINE(*convert-member-functions-to-static)
constexpr auto parse(format_parse_context const &ctx) -> decltype(ctx.begin())
{
auto const *const it = ctx.begin();
if (it + 1 != ctx.end() && *it != '}')
throw format_error("invalid format");
return it;
}
template <typename FormatContext>
constexpr auto format(std::error_code const &p, FormatContext &ctx) -> decltype(ctx.out())
{
return format_to(ctx.out(), FMT_COMPILE("({}: '{}`)"), p.value(), p.message());
}
};
} // namespace v8
} // namespace fmt
///****************************************************************************************/
#endif
|
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from src.controllers import account, auth, transaction
from src.database import database
from src.exceptions import AccountNotFoundError, BusinessError
@asynccontextmanager
async def lifespan(app: FastAPI):
await database.connect()
yield
await database.disconnect()
tags_metadata = [
{
"name": "auth",
"description": "Operations for authentication.",
},
{
"name": "account",
"description": "Operations to maintain accounts.",
},
{
"name": "transaction",
"description": "Operations to maintain transactions.",
},
]
app = FastAPI(
title="Transactions API",
version="1.0.0",
summary="Microservice to maintain withdrawal and deposit operations from current accounts.",
description="""
Transactions API is the microservice for recording current account transactions. 💸💰
## Account
* **Create accounts**.
* **List accounts**.
* **List account transactions by ID**.
## Transaction
* **Create transactions**.
""",
openapi_tags=tags_metadata,
redoc_url=None,
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(auth.router, tags=["auth"])
app.include_router(account.router, tags=["account"])
app.include_router(transaction.router, tags=["transaction"])
@app.exception_handler(AccountNotFoundError)
async def account_not_found_error_handler(request: Request, exc: AccountNotFoundError):
return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"detail": "Account not found."})
@app.exception_handler(BusinessError)
async def business_error_handler(request: Request, exc: BusinessError):
return JSONResponse(status_code=status.HTTP_409_CONFLICT, content={"detail": str(exc)})
|
<?php
declare(strict_types=1);
/*
* This file is part of CycloneDX PHP Library.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) OWASP Foundation. All Rights Reserved.
*/
namespace CycloneDX\Core\Models\License;
/**
* Disjunctive license with name - aka NamedLicense.
*
* @author jkowalleck
*/
class NamedLicense
{
use _DisjunctiveLicenseBase;
/**
* If SPDX does not define the license used, this field may be used to provide the license name.
*
* Implementation detail: allow empty strings.
*
* @psalm-suppress PropertyNotSetInConstructor
*/
private string $name;
public function getName(): string
{
return $this->name;
}
public function setName(string $name): static
{
$this->name = $name;
return $this;
}
public function __construct(string $name)
{
$this->setName($name);
}
}
|
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Book List</title>
</head>
<body>
<div class="container">
<div class="row py-1 mt-4">
<!-- First Column -->
<div class="col-md-6 offset-md-3">
<div class="card-header">
Book Management System
</div>
<!-- Form -->
<fieldset class="form-group border p-3">
<legend class="w-auto px-2">Login Details</legend><hr>
<form action="#" th:action="@{/login}" th:object="${user}" method="post" id="enrollment-form" onsubmit="handleSumbit(event)">
<div class="row mb-3">
<div class="col-3 col-md-4 text-start">
<label for="User Id" class="form-label">User Id</label>
</div>
<div class="col-9 col-md-8 text-center">
<input type="email" placeholder="xyz@gmail.com" class="form-input m-0 w-100 rounded border-1" name="username" maxlength="50" required/>
</div>
</div>
<div class="row mb-3">
<div class="col-3 col-md-4 text-start">
<label for="Password" class="form-label">Password</label>
</div>
<div class="col-9 col-md-8 text-center">
<input type="password" placeholder="12345" class="form-input m-0 w-100 rounded border-1" name="password" maxlength="50" required/>
</div>
</div>
<div class="row mb-3 mt-2">
<div class="col">
<button type="submit" class="btn btn-success">Login</button>
<button class="btn btn-danger" type="reset" onclick="">Clear</button>
</div>
</div>
</form>
</fieldset>
</div>
</div>
</div>
<!-- Footer -->
<footer class="text-center text-dark fixed-bottom back_color">
<div class="container">
<hr>
<p class="m-0">© 2021-2022 Java Fresher Training</p>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>
|
---
title: "You'll Never Believe the Surprising Trick to Spelling 'Batteries' Correctly!"
ShowToc: true
date: "2023-03-31"
author: "Earle Natalie"
tags: ["Spelling Tips","Educational Content"]
---
# You'll Never Believe the Surprising Trick to Spelling 'Batteries' Correctly!
Spelling can be a tricky business, especially when it comes to words that have multiple spellings or ones that are rarely used. One of the most commonly misspelled words is 'batteries', but don't worry, we have a trick that will help you spell it correctly every time!
## I. Introduction
When it comes to spelling, it's important to understand the root words and their meanings in order to spell them correctly. 'Batteries' is a compound word made up of two root words: 'battery' and 'ies'.
## II. The Trick to Spelling 'Batteries'
The trick to correctly spelling 'batteries' is to understand the two root words. 'Battery' is a noun that refers to a device that stores energy, while 'ies' is a plural suffix. To remember the correct spelling, just think of the plural form of 'battery' - 'batteries'.
## III. Conclusion
In conclusion, understanding the root words and their meanings is the key to correctly spelling 'batteries'. Not only will it help you remember the correct spelling, but it will also help you understand the meaning of the word. So, take some time to practice spelling 'batteries' and you'll have it down in no time!
{{< youtube lgs-M0qofl0 >}}
If you've ever wondered how to spell the word 'batteries', you're not alone. Many people struggle with this tricky word. However, there's a surprisingly simple trick to get it right every time. All you have to do is remember that the word “batteries” has two “t”s and two “e”s. This helpful mnemonic device makes it easy to remember how to spell the word correctly. With this helpful trick, you'll never have to worry about spelling 'batteries' wrong again.
## Frequently Asked Questions (FAQ) :
**Q1: What is the surprising trick to spelling 'batteries' correctly?**
**A1:** The surprising trick to spelling 'batteries' correctly is to remember that the 'ie' comes after the 't'. So it is spelled 'batteries', not 'batterys'.
**Q2: How can remembering the 'ie' help you spell 'batteries' correctly?**
**A2:** Remembering the 'ie' helps you spell 'batteries' correctly because it is easy to forget that the 'ie' comes after the 't'. By remembering this, you can spell 'batteries' correctly every time.
**Q3: Why is it important to spell 'batteries' correctly?**
**A3:** It is important to spell 'batteries' correctly because it is a common word and it is used in many contexts. If you spell it incorrectly, it can lead to confusion or misunderstandings.
**Q4: What other words have similar spelling rules to 'batteries'?**
**A4:** Other words that have similar spelling rules to 'batteries' include 'potatoes', 'tomatoes', and 'furniture'. In each of these words, the 'ie' comes after the 't'.
**Q5: What tips can you give to help someone remember the spelling of 'batteries'?**
**A5:** To help someone remember the spelling of 'batteries', you can suggest they break the word down into smaller parts and focus on the 'ie' coming after the 't'. You can also suggest they practice writing the word out multiple times to help them remember the spelling.
|
/*
* FreeRTOS Kernel V10.2.0
* Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* 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.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/*
NOTE : Tasks run in system mode and the scheduler runs in Supervisor mode.
The processor MUST be in supervisor mode when vTaskStartScheduler is
called. The demo applications included in the FreeRTOS.org download switch
to supervisor mode prior to main being called. If you are not using one of
these demo application projects then ensure Supervisor mode is used.
*/
/*
* Creates all the demo application tasks, then starts the scheduler. The WEB
* documentation provides more details of the demo application tasks.
*
* Main.c also creates a task called "Check". This only executes every three
* seconds but has the highest priority so is guaranteed to get processor time.
* Its main function is to check that all the other tasks are still operational.
* Each task (other than the "flash" tasks) maintains a unique count that is
* incremented each time the task successfully completes its function. Should
* any error occur within such a task the count is permanently halted. The
* check task inspects the count of each task to ensure it has changed since
* the last time the check task executed. If all the count variables have
* changed all the tasks are still executing error free, and the check task
* toggles the onboard LED. Should any task contain an error at any time
* the LED toggle rate will change from 3 seconds to 500ms.
*
*/
/* Standard includes. */
#include <stdlib.h>
#include <stdio.h>
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "lpc21xx.h"
/* Peripheral includes. */
#include "serial.h"
#include "GPIO.h"
#include "queue.h"
#include "string.h"
/*-----------------------------------------------------------*/
/* Constants to setup I/O and processor. */
#define mainBUS_CLK_FULL ( ( unsigned char ) 0x01 )
/* Constants for the ComTest demo application tasks. */
#define mainCOM_TEST_BAUD_RATE ( ( unsigned long ) 115200 )
extern unsigned char txBuffer[200];
TaskHandle_t * Load1Simulation_Handler = NULL;
TaskHandle_t * Load2Simulation_Handler = NULL;
uint8_t RisingFlag1 =0;
uint8_t FallingFlag1 =0;
uint8_t RisingFlag2 =0;
uint8_t FallingFlag2 =0;
/*
* Configure the processor for use with the Keil demo board. This is very
* minimal as most of the setup is managed by the settings in the project
* file.
*/
static void prvSetupHardware( void );
/*-----------------------------------------------------------*/
/*Using Queue*/
unsigned char Button1_Rising_Monitor [20];
unsigned char Button1_Falling_Monitor [20];
unsigned char Button2_Rising_Monitor [20];
unsigned char Button2_Falling_Monitor [20];
unsigned char Periodic_Tx [20];
TaskHandle_t * Button1_Handler = NULL;
TaskHandle_t * Button2_Handler = NULL;
TaskHandle_t * PeriodicTx_Handler = NULL;
TaskHandle_t * UartRx_Handler = NULL;
QueueHandle_t xQueue1 ,xQueue2,xQueue3;
void Button_1_Monitor( void * pvParameters )
{
//giving the task an ID tag = 1
vTaskSetApplicationTaskTag( NULL, ( void * ) 1 );
uint8_t now , last;
TickType_t xLastWakeTime;
const TickType_t xFrequency = 50;
// Initialise the xLastWakeTime variable with the current time.
xLastWakeTime = xTaskGetTickCount();
for( ;; )
{
/* Task code goes here. */
now = GPIO_read(PORT_0 , PIN0);
//detect rising and falling edges
if (now != last) {
if (now > 0) //rising edge
{
RisingFlag1=1;
strcpy((char *)&Button1_Rising_Monitor, "\nRising edge1");
xQueueSend( xQueue1 ,( void * ) &Button1_Rising_Monitor ,0);
}
else if (now == 0) //falling edge
{
FallingFlag1 = 1;
strcpy((char *)&Button1_Falling_Monitor, "\nFalling edge1");
xQueueSend( xQueue1 ,( void * ) &Button1_Falling_Monitor,0);
}
last = now;
RisingFlag1=0;
FallingFlag1=0;
}
vTaskDelayUntil( &xLastWakeTime, xFrequency );
}
}
void Button_2_Monitor( void * pvParameters )
{
//giving the task an ID tag = 2
vTaskSetApplicationTaskTag( NULL, ( void * ) 2 );
uint8_t now , last;
TickType_t xLastWakeTime;
const TickType_t xFrequency = 50;
// Initialise the xLastWakeTime variable with the current time.
xLastWakeTime = xTaskGetTickCount();
for( ;; )
{
/* Task code goes here. */
now = GPIO_read(PORT_0 , PIN1);
RisingFlag2=0;
FallingFlag2=0;
//detect rising and falling edges
if (now != last) {
if (now > 0) //rising edge
{
RisingFlag2=1;
strcpy((char *)&Button2_Rising_Monitor, "\nRising edge2");
xQueueSend( xQueue2 ,( void * ) &Button2_Rising_Monitor ,0);
}
else if (now == 0) //falling edge
{
FallingFlag2 = 1;
strcpy((char *)&Button2_Falling_Monitor, "\nFalling edge2");
xQueueSend( xQueue2 ,( void * ) &Button2_Falling_Monitor ,0 );
}
last = now;
}
vTaskDelayUntil( &xLastWakeTime, xFrequency );
}
}
void Periodic_Transmitter( void * pvParameters )
{
//giving the task an ID tag = 3
vTaskSetApplicationTaskTag( NULL, ( void * ) 3 );
TickType_t xLastWakeTime;
const TickType_t xFrequency = 100;
// Initialise the xLastWakeTime variable with the current time.
xLastWakeTime = xTaskGetTickCount();
strcpy((char *)&Periodic_Tx, "\nperiod ");
for( ;; )
{
/* Task code goes here. */
xQueueSend( xQueue3 ,( void * ) &Periodic_Tx , 0);
vTaskDelayUntil( &xLastWakeTime, xFrequency );
}
}
void Uart_Receiver( void * pvParameters )
{
//giving the task an ID tag = 4
vTaskSetApplicationTaskTag( NULL, ( void * ) 4 );
char string [20];
TickType_t xLastWakeTime;
const TickType_t xFrequency = 20;
// Initialise the xLastWakeTime variable with the current time.
xLastWakeTime = xTaskGetTickCount();
for( ;; )
{
/* Task code goes here. */
//ButtonState = GPIO_read(PORT_0 , PIN0);
//sending Button_1_monitor data
while (xQueueReceive(xQueue1, string, (TickType_t) 0))
{
vSerialPutString((signed char *) string, (unsigned short) 20);
xSerialPutChar('\n');
}
//sending Button_2_monitor data
while (xQueueReceive(xQueue2, string, (TickType_t) 0))
{
vSerialPutString((signed char *) string, (unsigned short) 20);
xSerialPutChar('\n');
}
//sending Periodic_Tx data
while (xQueueReceive(xQueue3, string, (TickType_t) 0))
{
vSerialPutString((signed char *) string, (unsigned short) 20);
xSerialPutChar('\n');
}
vTaskDelayUntil( &xLastWakeTime, xFrequency );
}
}
void vApplicationTickHook (void)
{
GPIO_write(PORT_0, PIN2 , PIN_IS_HIGH);
GPIO_write(PORT_0, PIN2 , PIN_IS_LOW);
//write your code here
}
void Load_1_Simulation ( void * pvParameters )
{
//giving the task an ID tag = 5
vTaskSetApplicationTaskTag( NULL, ( void * ) 5 );
TickType_t xLastWakeTime = xTaskGetTickCount();
uint32_t i = 0;
for( ; ; )
{
for( i = 0 ; i <= 37000; i++); //5ms period
/*Periodicity: 10*/
vTaskDelayUntil( &xLastWakeTime ,(TickType_t) 10);
}
}
void Load_2_Simulation ( void * pvParameters )
{
//giving the task an ID tag = 6
vTaskSetApplicationTaskTag( NULL, ( void * ) 6 );
TickType_t xLastWakeTime = xTaskGetTickCount();
uint32_t i = 0;
for( ; ; )
{
for( i = 0 ; i <= 88800; i++); //12ms period
/*Periodicity: 100*/
vTaskDelayUntil( &xLastWakeTime , (TickType_t)100);
}
}
/*
* Application entry point:
* Starts all the other tasks, then starts the scheduler.
*/
int main( void )
{
/* Setup the hardware for use with the Keil demo board. */
prvSetupHardware();
xSerialPortInitMinimal( mainCOM_TEST_BAUD_RATE);
xQueue1 = xQueueCreate( 20, sizeof( char[20] ) );
xQueue2 = xQueueCreate( 20, sizeof( char[20] ) );
xQueue3 = xQueueCreate( 20, sizeof( char[20] ) );
/* Create Tasks here */
xTaskPeriodicCreate(
Button_1_Monitor, /* Function that implements the task. */
"Button_1_Monitor", /* Text name for the task. */
50, /* Stack size in words, not bytes. */
NULL, /* Parameter passed into the task. */
1, /* Priority at which the task is created. */
Button1_Handler,/* Used to pass out the created task's handle. */
50);
xTaskPeriodicCreate(
Button_2_Monitor, /* Function that implements the task. */
"Button_1_Monitor", /* Text name for the task. */
50, /* Stack size in words, not bytes. */
NULL, /* Parameter passed into the task. */
1, /* Priority at which the task is created. */
Button2_Handler,/* Used to pass out the created task's handle. */
50);
xTaskPeriodicCreate(
Periodic_Transmitter, /* Function that implements the task. */
"Periodic_Tx", /* Text name for the task. */
50, /* Stack size in words, not bytes. */
NULL, /* Parameter passed into the task. */
1, /* Priority at which the task is created. */
PeriodicTx_Handler,/* Used to pass out the created task's handle. */
100);
xTaskPeriodicCreate(
Uart_Receiver, /* Function that implements the task. */
"Uart_Receiver", /* Text name for the task. */
100, /* Stack size in words, not bytes. */
NULL, /* Parameter passed into the task. */
1, /* Priority at which the task is created. */
UartRx_Handler,/* Used to pass out the created task's handle. */
20);
xTaskPeriodicCreate(
Load_1_Simulation, /* Function that implements the task. */
"LOAD 1 SIMULATION", /* Text name for the task. */
100, /* Stack size in words, not bytes. */
( void * ) 0, /* Parameter passed into the task. */
1, /* Priority at which the task is created. */
Load1Simulation_Handler, /* Used to pass out the created task's handle. */
10); /* Period for the task */
xTaskPeriodicCreate(
Load_2_Simulation, /* Function that implements the task. */
"LOAD 1 SIMULATION", /* Text name for the task. */
100, /* Stack size in words, not bytes. */
( void * ) 0, /* Parameter passed into the task. */
1, /* Priority at which the task is created. */
Load2Simulation_Handler, /* Used to pass out the created task's handle. */
100); /* Period for the task */
/* Now all the tasks have been started - start the scheduler.
NOTE : Tasks run in system mode and the scheduler runs in Supervisor mode.
The processor MUST be in supervisor mode when vTaskStartScheduler is
called. The demo applications included in the FreeRTOS.org download switch
to supervisor mode prior to main being called. If you are not using one of
these demo application projects then ensure Supervisor mode is used here. */
vTaskStartScheduler();
/* Should never reach here! If you do then there was not enough heap
available for the idle task to be created. */
for( ;; );
}
/*-----------------------------------------------------------*/
/* Function to reset timer 1 */
void timer1Reset(void)
{
T1TCR |= 0x2;
T1TCR &= ~0x2;
}
/* Function to initialize and start timer 1 */
static void configTimer1(void)
{
T1PR = 1000;
T1TCR |= 0x1;
}
static void prvSetupHardware( void )
{
/* Perform the hardware setup required. This is minimal as most of the
setup is managed by the settings in the project file. */
/* Configure UART */
xSerialPortInitMinimal(mainCOM_TEST_BAUD_RATE);
/* Configure GPIO */
GPIO_init();
/* Config trace timer 1 and read T1TC to get current tick */
configTimer1();
/* Setup the peripheral bus to be the same as the PLL output. */
VPBDIV = mainBUS_CLK_FULL;
}
/*-----------------------------------------------------------*/
|
using Core.Constants;
using Core.Interfaces.Service;
using Core.Models.DTO;
using Core.Models.Param;
using Core.Models.ServerObject;
using Core.Utils;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Threading;
namespace Api.Controllers
{
public class TemplateController : BaseApiController
{
#region Fields
private readonly ITemplateService _service;
private readonly IDictionaryService _dictionaryService;
#endregion
#region Constructor
public TemplateController(IHustServiceCollection serviceCollection,
ITemplateService service,
IDictionaryService dictionaryService) : base(serviceCollection)
{
_service = service;
_dictionaryService = dictionaryService;
}
#endregion
/// <summary>
/// Lấy template nhập khẩu
/// </summary>
/// <returns></returns>
[HttpGet("download")]
public async Task<IActionResult> DownloadTemplateImportDictionary()
{
var res = new ServiceResult();
try
{
var fileBytes = await _service.DowloadTemplateImportDictionary();
if(fileBytes == null || fileBytes.Length == 0)
{
return StatusCode((int)HttpStatusCode.NoContent);
}
return File(fileBytes, FileContentType.OctetStream, TemplateConfig.FileDefaultName.DownloadDefaultTemplate);
}
catch (Exception ex)
{
this.ServiceCollection.HandleControllerException(res, ex);
return StatusCode((int)HttpStatusCode.InternalServerError, res);
}
}
/// <summary>
/// Xuất khẩu
/// </summary>
/// <returns></returns>
[HttpGet("export")]
public async Task<IActionResult> ExportDictionary([FromQuery] string dictionaryId)
{
var res = new ServiceResult();
try
{
// Lấy thông tin của từ điển
var dict = (await _dictionaryService.GetDictionaryById(dictionaryId)).Data as Dictionary;
if(dict == null)
{
return StatusCode((int)HttpStatusCode.NoContent);
}
// Lấy file
var fileBytes = await _service.ExportDictionary(dict.UserId.ToString(), dict.DictionaryId.ToString());
if (fileBytes == null || fileBytes.Length == 0)
{
return StatusCode((int)HttpStatusCode.NoContent);
}
// Tạo tên file
var fileName = _service.GetExportFileName(dict.DictionaryName);
return File(fileBytes, FileContentType.OctetStream, fileName);
}
catch (Exception ex)
{
this.ServiceCollection.HandleControllerException(res, ex);
return StatusCode((int)HttpStatusCode.InternalServerError, res);
}
}
/// <summary>
/// Backup data và gửi vào email
/// </summary>
/// <param name="email"></param>
/// <param name="dictionaryId"></param>
/// <returns></returns>
[HttpGet("backup")]
public async Task<IServiceResult> BackupData([FromQuery] string email, string dictionaryId)
{
var res = new ServiceResult();
try
{
return await _service.BackupData(email, dictionaryId);
}
catch (Exception ex)
{
this.ServiceCollection.HandleControllerException(res, ex);
}
return res;
}
/// <summary>
/// Nhập khẩu bước 1 (validate)
/// </summary>
/// <returns></returns>
[HttpPost("import")]
public async Task<IServiceResult> ImportDictionary()
{
var res = new ServiceResult();
try
{
var file = HttpContext.Request.Form.Files[0];
var dictionaryId = HttpContext.Request.Form["dictionaryId"].ToString();
//var data = (await _service.ImportDictionary(dictionaryId, file)).Data as byte[];
//return File(data, FileContentType.Excel, "File error.xlsx");
return await _service.ImportDictionary(dictionaryId, file);
}
catch (Exception ex)
{
this.ServiceCollection.HandleControllerException(res, ex);
}
return res;
}
/// <summary>
/// Nhập khẩu (lưu dữ liệu)
/// </summary>
/// <returns></returns>
[HttpPost("do_import")]
public async Task<IServiceResult> DoImportDictionary([FromBody]string importSession)
{
var res = new ServiceResult();
try
{
return await _service.DoImport(importSession);
}
catch (Exception ex)
{
this.ServiceCollection.HandleControllerException(res, ex);
}
return res;
}
}
}
|
package com.suslanium.wordsfactory.presentation.ui.common
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import com.suslanium.wordsfactory.presentation.ui.theme.ButtonSmall
import com.suslanium.wordsfactory.presentation.ui.theme.Dark
import com.suslanium.wordsfactory.presentation.ui.theme.DarkGray
import com.suslanium.wordsfactory.presentation.ui.theme.HeadingH4
import com.suslanium.wordsfactory.presentation.ui.theme.ParagraphMedium
import com.suslanium.wordsfactory.presentation.ui.theme.PrimaryColor
@Composable
fun TextAlertDialog(
title: String, message: String, acceptButtonText: String, onAccept: () -> Unit
) {
AlertDialog(containerColor = Color.White, onDismissRequest = onAccept, title = {
Text(text = title, style = HeadingH4, color = Dark)
}, text = {
Text(text = message, style = ParagraphMedium, color = DarkGray)
}, confirmButton = {
Button(
onClick = onAccept, colors = ButtonDefaults.buttonColors(
contentColor = Color.White, containerColor = PrimaryColor
)
) {
Text(text = acceptButtonText, style = ButtonSmall)
}
})
}
|
(ns shopping-cart.resource-test
(:require
[clojure.test :refer [deftest is testing use-fixtures]]
[shopping-cart.event-store :as events]
[shopping-cart.system :as system]
[donut.system :as ds]
[jsonista.core :as j]
[shopping-cart.shopping-cart :as shopping-cart]
[shopping-cart.product-catalog :as product-catalog]))
(use-fixtures :each (ds/system-fixture ::system/test))
(defn extract [system]
{:handler (get-in system [::ds/instances :http :handler])
:event-store (get-in system [::ds/instances :components :event-store])
:shopping-cart-store (get-in system [::ds/instances :components :shopping-cart-store])
:product-catalog-gateway (get-in system [::ds/instances :components :product-catalog-gateway])})
(defn request->map [request]
(-> request
:body
slurp
(j/read-value j/keyword-keys-object-mapper)))
(deftest health-test
(let [{:keys [handler]} (extract ds/*system*)
request (handler {:request-method :get
:uri "/health"})]
(testing "Calling health returns 200"
(is (= {:status 200
:body "healthy"}
request)))))
(deftest events-test
(let [{:keys [handler event-store]} (extract ds/*system*)
_ (handler {:request-method :post
:uri (str "/shoppingcart/" 1 "/items")
:body-params {:product-ids [1]}})
request (handler {:request-method :get
:uri "/events"})]
(testing "/events"
(testing "Calling events returns 200"
(is (= 200 (:status request))))
(testing "Contains events"
(is (= 1
(count (request->map request))))))
(testing "Contains events"
(let [[event :as events] (events/get-events event-store)]
(is (= 1 (count events)))
(is (= "ShoppingCartItemAdded" (:EVENTS/TYPE event)))))))
(deftest GET-cart-test
(let [{:keys [handler shopping-cart-store]} (extract ds/*system*)
shopping-cart-id 1
expected {:user-id 1
:items []}]
(testing "GET returns cart"
(let [request (handler {:request-method :get
:uri (str "/shoppingcart/" shopping-cart-id)})]
(testing "request"
(testing "returns 200"
(is (= 200 (:status request))))
(testing "body"
(is (= {:user-id 1
:items []}
(request->map request)))))
(testing "store"
(is (= expected
(shopping-cart/get-cart shopping-cart-store shopping-cart-id))))))))
(deftest POST-cart-item-test
(let [{:keys [handler
shopping-cart-store
product-catalog-gateway
event-store]} (extract ds/*system*)
cart-id 1
product-id 1
request (handler {:request-method :post
:uri (str "/shoppingcart/" cart-id "/items")
:body-params {:product-ids [product-id]}})
product (first (product-catalog/get-products product-catalog-gateway [product-id]))
expected {:user-id cart-id
:items [product]}]
(testing "POST adds item to cart"
(testing "returns 200"
(is (= 200 (:status request))))
(testing "returns body"
(is (= expected
(request->map request)))))
(testing "Shopping cart store"
(is (= expected
(shopping-cart/get-cart shopping-cart-store cart-id))))
(testing "Contains events"
(let [[event :as events] (events/get-events event-store)]
(is (= 1 (count events)))
(is (= "ShoppingCartItemAdded" (:EVENTS/TYPE event)))))))
(deftest POST-multiple-cart-items-test
(let [{:keys [handler shopping-cart-store product-catalog-gateway event-store]} (extract ds/*system*)
cart-id 1
product-id-1 1
product-id-2 2
[product-1 product-2] (product-catalog/get-products product-catalog-gateway [product-id-1 product-id-2])
request (handler {:request-method :post
:uri (str "/shoppingcart/" cart-id "/items")
:body-params {:product-ids [product-id-1 product-id-2]}})
expected {:user-id cart-id
:items [product-1 product-2]}]
(testing "POST adds item to cart"
(testing "returns 200"
(is (= 200 (:status request))))
(testing "body"
(is (= expected (request->map request)))))
(testing "Shopping cart store"
(is (= expected
(shopping-cart/get-cart shopping-cart-store cart-id))))
(testing "Contains events"
(let [[first-event second-event :as events] (events/get-events event-store)]
(is (= 2 (count events)))
(is (= "ShoppingCartItemAdded" (:EVENTS/TYPE first-event)))
(is (= "ShoppingCartItemAdded" (:EVENTS/TYPE second-event)))))))
(deftest DELETE-cart-item-test
(let [{:keys [handler shopping-cart-store event-store]} (extract ds/*system*)
cart-id 1
product-id 1
_ (handler {:request-method :post
:uri (str "/shoppingcart/" cart-id "/items")
:body-params {:product-ids [product-id]}})
request (handler {:request-method :delete
:uri (str "/shoppingcart/" cart-id "/items")
:body-params {:product-ids [product-id]}})
expected {:user-id cart-id
:items []}]
(testing "DELETE removes item from cart"
(testing "returns 200"
(is (= 200 (:status request))))
(testing "returns body"
(is (= expected (request->map request)))))
(testing "Shopping cart store"
(is (= expected
(shopping-cart/get-cart shopping-cart-store cart-id))))
(testing "Contains events"
(let [[first-event second-event :as events] (events/get-events event-store)]
(is (= 2 (count events)))
(is (= "ShoppingCartItemAdded" (:EVENTS/TYPE first-event)))
(is (= "ShoppingCartItemRemoved" (:EVENTS/TYPE second-event)))))))
|
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import entrada.Teclado;
public class Actividad_2x01 {
public static void main(String[] args) {
try {
int opcion = -1;
do {
imprimirMenu();
opcion = Teclado.leerEntero("Opcion: ");
menu(opcion);
}while(opcion != 0);
}
catch (IOException ioe) {
System.out.println("Error al leer del fichero:");
System.out.println(ioe.getMessage());
ioe.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException sqle) {
System.err.println("El libro está referenciado en un libro de la base de datos.");
}
}
/*
* input: Lista de libros para imprimir
* Descripción: Recorre la lista con un for-each e imprime cada elemento con el método toString() de la clase Libro
*/
public static void imprimirLista(List<Libro> listaLibros) {
for(Libro libro: listaLibros) {
System.out.println(libro.toString());
}
System.out.println("Se han consultado " + listaLibros.size() + " libros de la base de datos.");
}
/*
* Opción 1 del menú
* Descripción: Pide parámetros del constructor del libro a insertar en la base de datos. Utiliza la clase AccesoLibro
* y su método insertar.
*/
public static void insertar() throws ClassNotFoundException, SQLException {
String isbn = Teclado.leerCadena("Isbn: ");
String titulo = Teclado.leerCadena("Título: ");
String escritor = Teclado.leerCadena("Escritor: ");
int agnoPublicacion = Teclado.leerEntero("Año de publicación");
double puntuacion = Teclado.leerReal("Puntuación: ");
AccesoLibro.insertar(isbn, titulo, escritor, agnoPublicacion, puntuacion);
System.out.println("Se ha insertado un libro en la base de datos.");
}
/*
* Opción 2 del menú
* Descripción: Pide código del libro a borrar. Busca el libro que contenga ese código con el método eliminar(codigo)
* de la clase AccesoLibro y si encuentra el libro, lo borra de la base de datos
*/
public static void eliminar() throws ClassNotFoundException, SQLException {
int codigo = Teclado.leerEntero("Código: ");
int filasEliminadas = AccesoLibro.eliminar(codigo);
if (filasEliminadas == 0) {
System.out.println("No existe ningún libro con ese código en la base de datos.");
}
else {
System.out.println("Se ha eliminado un libro de la base de datos.");
}
}
/*
* Opción 3 del menú
* Descripción: Recorre la lista de libros generada por el método consultarTodos() de la clase AccesoLibro.
* Por cada registro/libro recorrido de la lista de libros, imprime su información con el método imprimirLista(listaLibros)
*/
public static void consultarTodos() throws ClassNotFoundException, SQLException {
List<Libro> listaLibros = AccesoLibro.consultarTodos();
if(listaLibros.size() == 0)
System.out.println("No se ha encontrado ningún libro en la base de datos.");
else {
imprimirLista(listaLibros);
}
}
/*
* Opción 4 del menú
* Descripción: Recorre la lista de libros generada por el método consultarTodos() de la clase AccesoLibro.
* Por cada registro/libro recorrido de la lista de libros, imprime su información con el método imprimirLista(listaLibros)
*/
public static void consultarVarios() throws ClassNotFoundException, SQLException {
String escritor = Teclado.leerCadena("Escritor: ");
List<Libro> listaLibros = AccesoLibro.consultarVarios(escritor);
if(listaLibros.size() == 0)
System.out.println("No existe ningún libro con ese escritor en la base de datos.");
else
imprimirLista(listaLibros);
}
/*
* Opción 5 del menú
* Descripción: Recorre la lista de libros generada por el método consultarNoPrestados() de la clase AccesoLibro.
* Por cada registro/libro recorrido de la lista de libros que no esté en el registro de libros prestados,
* imprime su información con el método imprimirLibros(listaLibros)
*/
public static void consultarNoPrestados() throws ClassNotFoundException, SQLException {
List<Libro> listaLibros = AccesoLibro.consultarNoPrestados();
if(listaLibros.size() == 0)
System.out.println("No existe ningún libro no prestado en la base de datos.");
else {
imprimirLista(listaLibros);
}
}
/*
* Opción 6 del menú
* Descripción: Recorre la lista de libros generada por el método consultarDevueltos() de la clase AccesoLibro.
* Por cada registro/libro recorrido de la lista de libros cuya fecha de devolución sea la introducida por parámetro,
* imprime su información con el método imprimirLibros(listaLibros)
*/
public static void consultarDevueltos() throws ClassNotFoundException, SQLException {
String fechaDevolucion = Teclado.leerCadena("Fecha de devolución: ");
List<Libro> listaLibros = AccesoLibro.consultarDevueltos(fechaDevolucion);
if(listaLibros.size() == 0)
System.out.println("No existe ningún libro devuelto en esa fecha en la base de datos.");
else {
imprimirLista(listaLibros);
}
}
/*
* Descripción: Describe las opciones del menú
*/
public static void imprimirMenu() {
System.out.println("0) Salir del programa.\n1) Insertar un libro en la base de datos.\n"
+ "2) Eliminar un libro, por código, de la base de datos.\n"
+ "3) Consultar todos los libros de la base de datos.\n"
+ "4) Consultar varios libros, por escritor, de la base de datos, ordenados por puntuación decendente.\n"
+ "5) Consultar los libros no prestados de la base de datos.\n"
+ "6) Consultar los libros devueltos, en una fecha, de la base de datos");
}
/*
* Input: opción a elegir del menú
* Descrición: Tras obtener la opción introducidas por parámetro, entra en el switch y ejecuta la opción pertinente
*/
public static void menu(int opcion) throws IOException, ClassNotFoundException, SQLException {
switch (opcion) {
case 0:
break;
case 1:
insertar();
break;
case 2:
eliminar();
break;
case 3:
consultarTodos();
break;
case 4:
consultarVarios();
break;
case 5:
consultarNoPrestados();
break;
case 6:
consultarDevueltos();
break;
default:
System.out.println("La opcion de menu debe estar comprendida entre 0 y 6.");
}
}
}
|
package common
import (
"context"
"encoding/json"
"fmt"
red "github.com/go-redis/redis"
"github.com/zeromicro/go-zero/core/logx"
"minicode.com/sirius/go-back-server/config/cfgredis"
"minicode.com/sirius/go-back-server/service/userbehavior/model/usermgo"
"minicode.com/sirius/go-back-server/service/userbehavior/rpc/internal/svc"
"minicode.com/sirius/go-back-server/utils/mylogrus"
)
type UserInfoCommon struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewUserInfoCommon(ctx context.Context, svcCtx *svc.ServiceContext) *UserInfoCommon {
return &UserInfoCommon{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (c *UserInfoCommon) GetUserInfoById(id string) (userInfo *usermgo.User, err error) {
userInfoKey := fmt.Sprintf(cfgredis.UserInfo, id)
getCmd := c.svcCtx.Redis.Get(userInfoKey)
info, redisErr := getCmd.Result()
if redisErr != nil && redisErr != red.Nil {
filed := map[string]interface{}{"sender": "USER-BEHAVIOR-RPC", "code": 0, "uin": "", "req": "", "resp": "", "track_data": ""}
c.svcCtx.MyLogger.WithFields(mylogrus.GetCommonField(c.ctx, filed)).Error("获取账号信息失败redis")
return nil, redisErr
}
if info != "" {
userInfo = new(usermgo.User)
err = json.Unmarshal([]byte(info), userInfo)
if err != nil {
filed := map[string]interface{}{"sender": "USER-BEHAVIOR-RPC", "code": 0, "uin": "", "req": "", "resp": "", "track_data": ""}
c.svcCtx.MyLogger.WithFields(mylogrus.GetCommonField(c.ctx, filed)).Error("账号信息序列化失败")
return
}
if userInfo.AvatarId == 0 {
userInfo.AvatarId = 1 // 默认头像
}
return
}
userInfo, err = c.svcCtx.MgoAccountsModel.FindOne(c.ctx, id)
if err != nil && err != usermgo.ErrNotFound {
filed := map[string]interface{}{"sender": "USER-BEHAVIOR-RPC", "code": 0, "uin": "", "req": "", "resp": "", "track_data": ""}
c.svcCtx.MyLogger.WithFields(mylogrus.GetCommonField(c.ctx, filed)).Error("获取账号信息失败db")
return nil, err
}
if userInfo != nil {
if userInfo.AvatarId == 0 {
userInfo.AvatarId = 1 // 默认头像
}
infoJsonMarshalStr, err := json.Marshal(userInfo)
if err != nil {
filed := map[string]interface{}{"sender": "USER-BEHAVIOR-RPC", "code": 0, "uin": "", "req": "", "resp": "", "track_data": ""}
c.svcCtx.MyLogger.WithFields(mylogrus.GetCommonField(c.ctx, filed)).Error("用户信息json加密失败")
} else {
c.svcCtx.Redis.Set(userInfoKey, string(infoJsonMarshalStr), cfgredis.Expiration60M)
}
}
return
}
|
public class JniTest
{
private static void Test(
String name,
Object actual,
Object expected,
String actualAsString,
String expectedAsString)
{
if (!actual.equals(expected))
{
System.out.println(String.format(
"Test: %s failed\nExpected: \"%s\", Actual: \"%s\"",
name,
expected,
actual));
JniTest.exitCode = -1;
}
else
{
System.out.println(String.format("Test: %s passed", name));
}
}
private static void Test(
String name,
String actual,
String expected)
{
JniTest.Test(name, actual, expected, actual, expected);
}
public static void main(String[] args)
{
var actualVersion = JniWrapper.get_jni_version();
var expectedVersion = 0x000A0000;
JniTest.Test(
"Get JNI Version",
actualVersion,
expectedVersion,
String.format("0x%08X", actualVersion),
String.format("0x%08X", expectedVersion));
JniTest.Test(
"Read Native String Constant",
JniWrapper.read_constant_string(),
"Hello from C");
JniTest.Test(
"Write Java String to Native Library",
JniWrapper.write_string("Hello from Java"),
"Hello from Java");
JniTest.Test(
"Write Java Char Array to Native Library",
JniWrapper.write_char_array("Hello from Java".toCharArray()),
"Hello from Java");
var helper = new JniHelper();
JniTest.Test(
"Write String Member to Native Library",
JniWrapper.write_string_member(helper),
"Set from Java");
JniWrapper.set_string_member(helper);
JniTest.Test(
"Set String Member from Native Library",
helper.stringMember,
"Set from C");
JniWrapper.execute_java_function(helper);
JniTest.Test(
"Execeute Java Function from Native Library",
helper.stringMember,
"Hello, Managed World");
helper = JniWrapper.instantiate_java_class();
JniTest.Test(
"Instantiate Java Class",
helper.stringMember,
"Instantiated from C");
JniTest.Test(
"Call Native Library to Set System Time",
JniWrapper.set_and_write_time_in_seconds(1000),
"1000");
System.exit(exitCode);
}
public static int exitCode = 0;
}
|
// Copyright (c) 2020-2023 Träger
// 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 debug from 'debug';
import { CommandList } from './CommandList';
import { ConsolenReader } from './ConsolenReader';
import { IParser } from './IParser';
import { IWorker } from './IWorker';
import { Parsers } from './Parsers';
import { Value } from './Value';
const debugApi = debug('pylontech:api');
type resultForGet = { batteries: string[]; batterienames: any; allData: any };
const PWR = 'pwr';
const POWER = 'power';
const STAT = 'stat';
const STATISTIC = 'statistic';
const BAT = 'bat';
const SOH = 'soh';
const INFO = 'info';
const LOG = 'log';
const TIME = 'time';
const CELLS = 'cells';
const SYSTEMINFO = 'systeminfo';
const SYSINFO = 'sysinfo';
const UNIT = 'unit';
abstract class WorkerAbstract implements IWorker {
protected _consolenReader: ConsolenReader = new ConsolenReader();
protected _commands: CommandList[] = [];
protected _activeCmd: CommandList | undefined;
protected _timeout: number = 5000;
protected _started: boolean = false;
protected _parsers: Parsers;
protected _noPrompt: boolean = false;
protected _model: string;
constructor(model: string) {
debugApi('MyWorkerAbstract.constructor');
this._model = model;
this._parsers = new Parsers(model);
this._consolenReader.on('data', this._onData.bind(this));
this._consolenReader.on('needsenddata', this.sendData.bind(this));
}
protected _onData(data: Buffer): void {
const dataString = data.toString();
debugApi('MyWorkerAbstract._onData', 'data:', dataString, 'this._activeCmd:', this._activeCmd);
const parser: IParser | undefined = this._parsers.getParser();
let result: any = {};
if (parser !== undefined) {
result = parser.parseData(dataString);
}
if (this._activeCmd) {
clearTimeout(this._activeCmd.timeout);
this._activeCmd.resolve(result);
this._activeCmd = undefined;
}
this._nextcommand();
}
protected _nextcommand(): void {
debugApi('MyWorkerAbstract._nextcommand', 'this._activeCmd:', this._activeCmd, 'this._started:', this._started);
if (!this._activeCmd && this._started) {
this._activeCmd = this._commands.shift();
if (this._activeCmd) {
this._parsers.setCMD(this._activeCmd.cmd);
this.sendData(this._activeCmd.cmd + '\r');
this._activeCmd.timeout = setTimeout(this._ontimeout.bind(this), this._timeout);
}
}
}
protected _ontimeout(): void {
debugApi('MyWorkerAbstract._ontimeout', 'this._activeCmd:', this._activeCmd);
if (this._activeCmd) {
this._activeCmd.reject(new Error('timeout'));
this._activeCmd = undefined;
this._consolenReader._flush(() => {
this._nextcommand();
});
}
}
protected _connected(): void {
debugApi('MyWorkerAbstract._connected', 'this._activeCmd:', this._activeCmd);
if (!this._noPrompt) {
this.sendData('\r\n');
}
this._started = true;
this._nextcommand();
}
public sendCommand(cmd: string): Promise<any> {
debugApi('MyWorkerAbstract.sendCommand', 'cmd:', cmd);
return new Promise<any>((resolve, reject) => {
this._commands.push({ cmd, resolve, reject, timeout: undefined });
this._nextcommand();
});
}
public sendSpeedInit(): Promise<void> {
debugApi('MyWorkerAbstract.sendSpeedInit');
return new Promise<void>((resolve, reject) => {
try {
const setSpeed = Buffer.from('7E32303031343638324330303438353230464343330D', 'hex');
this.sendDataB(setSpeed);
setTimeout(() => {
resolve();
}, 1000);
} catch (err) {
reject(err);
}
});
}
abstract sendDataB(data: Buffer): void;
abstract sendData(data: string): void;
abstract open(): Promise<void>;
abstract close(): Promise<boolean>;
protected async _getAlldata(batteries: string[], cmd: string): Promise<any> {
return new Promise<any>((resolve, reject) => {
const promises: Promise<any>[] = [];
batteries.forEach((bat: string) => {
promises.push(this.sendCommand(`${cmd} ${bat}`));
});
Promise.all(promises)
.then((vals: any[]) => {
let all: any = {};
vals.forEach(val => {
all = Object.assign(all, val);
});
resolve(all);
})
.catch(reject);
});
}
protected async _getUsPwr(): Promise<{ pwrs: any; batteries: string[] }> {
return new Promise<{ pwrs: any; batteries: string[] }>((resolve, reject) => {
this.sendCommand(PWR)
.then(pwrs => {
const batteries: string[] = [];
if (pwrs && pwrs.pwr) {
const pwr: any = pwrs.pwr;
Object.keys(pwr).forEach((key: string) => {
const pwrVal: any = pwr[key];
if (pwrVal.basest instanceof Value) {
const pwrBase: Value = pwrVal.basest;
if (pwrBase.value !== 'Absent') {
batteries.push(key);
}
}
});
}
resolve({ pwrs, batteries });
})
.catch(reject);
});
}
protected async _getUsInfo(p: { pwrs: any; batteries: string[] }, info: boolean, power: boolean): Promise<resultForGet> {
return new Promise<resultForGet>((resolve, reject) => {
this._getAlldata(p.batteries, INFO)
.then((infos: any) => {
const allData: any = {};
const batterienames: any = {};
Object.keys(infos).forEach((key: string) => {
if (infos[key].info && infos[key].info.barcode && infos[key].info.barcode instanceof Value) {
batterienames[key] = infos[key].info.barcode.value;
if (info) {
allData[infos[key].info.barcode.value] = infos[key];
delete allData[infos[key].info.barcode.value].info.barcode;
}
}
});
p.batteries.forEach((bat: any) => {
if (batterienames[bat]) {
if (power) {
allData[batterienames[bat]].power = allData[batterienames[bat]].power
? Object.assign(allData[batterienames[bat]].power, p.pwrs.pwr[bat])
: p.pwrs.pwr[bat];
}
if (!allData.info) allData.info = {};
allData.info[`${bat}`] = {
barcode: new Value(batterienames[bat], 'string', '', 'Barcode'),
connected: new Value(true, 'boolean', '', 'Connected'),
};
}
});
resolve({ batteries: p.batteries, batterienames, allData });
})
.catch(reject);
});
}
protected async _getUsNormal(p: resultForGet, what: string, to: string, process: boolean): Promise<resultForGet> {
return new Promise<resultForGet>((resolve, reject) => {
if (process) {
this._getAlldata(p.batteries, what)
.then((data: any) => {
Object.keys(data).forEach((key: string) => {
if (p.batterienames[key] && p.allData[p.batterienames[key]] && data[key][what]) {
p.allData[p.batterienames[key]][to] = p.allData[p.batterienames[key]][to]
? Object.assign(p.allData[p.batterienames[key]].power, data[key][what])
: data[key][what];
}
});
resolve(p);
})
.catch(reject);
} else {
resolve(p);
}
});
}
protected async _getUsBatterie(p: resultForGet, what: string, process: boolean): Promise<resultForGet> {
return new Promise<resultForGet>((resolve, reject) => {
if (process) {
this._getAlldata(p.batteries, what)
.then((data: any) => {
Object.keys(data).forEach((key: string) => {
if (p.batterienames[key] && data[key][what]) {
Object.keys(data[key][what]).forEach((batnr: string) => {
const batkey = `battery${(parseInt(batnr, 10) + 1).toString().padStart(2, '0')}`;
p.allData[p.batterienames[key]][batkey] = p.allData[p.batterienames[key]][batkey]
? Object.assign(p.allData[p.batterienames[key]][batkey], data[key][what][batnr])
: data[key][what][batnr];
});
}
});
resolve(p);
})
.catch(reject);
} else {
resolve(p);
}
});
}
protected async _getOne(allData: any, what: string, name: string, process: boolean): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (process) {
this.sendCommand(what)
.then(data => {
if (data[what]) {
if (allData[name]) {
function copy(to: any, from: any): void {
Object.keys(from).forEach(key => {
if (to[key]) {
copy(to[key], from[key]);
} else {
to[key] = from[key];
}
});
}
copy(allData[name], data[what]);
} else {
allData[name] = data[what];
}
}
resolve(allData);
})
.catch(reject);
} else {
resolve(allData);
}
});
}
protected _getDataUS(option: any): Promise<any> {
return new Promise<any>((resolve, reject) => {
this._getUsPwr()
.then((p: { pwrs: any; batteries: string[] }) => {
this._getUsInfo(p, option.info, option.power)
.then((p: resultForGet) => {
this._getUsNormal(p, PWR, POWER, option.power)
.then(p => {
this._getUsNormal(p, STAT, STATISTIC, option.statistic)
.then(p => {
this._getUsBatterie(p, BAT, option.celldata)
.then(p => {
this._getUsBatterie(p, SOH, option.cellsoh)
.then(p => {
this._getOne(p.allData, LOG, LOG, option.log)
.then(allData => {
this._getOne(allData, TIME, TIME, option.time)
.then(allData => {
resolve(allData);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
});
}
protected _getDataFORCE(option: any): Promise<any> {
return new Promise<any>((resolve, reject) => {
this._getOne({}, INFO, INFO, option.info)
.then(allData => {
this._getOne(allData, SYSINFO, SYSTEMINFO, option.sysinfo)
.then(allData => {
this._getOne(allData, PWR, POWER, option.power)
.then(allData => {
this._getOne(allData, UNIT, UNIT, option.unit)
.then(allData => {
this._getOne(allData, STAT, STATISTIC, option.statistic)
.then(allData => {
this._getOne(allData, BAT, CELLS, option.celldata)
.then(allData => {
this._getOne(allData, SOH, CELLS, option.cellsoh)
.then(allData => {
this._getOne(allData, LOG, LOG, option.log)
.then(allData => {
this._getOne(allData, TIME, TIME, option.time)
.then(allData => {
if (!allData.info) {
allData.info = {};
}
allData.info['1'] = {
connected: new Value(true, 'boolean', '', 'Connected'),
};
resolve(allData);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
});
}
public getData(option: any): Promise<any> {
if (typeof option.info == 'undefined') option.info = true;
if (typeof option.power == 'undefined') option.power = true;
if (typeof option.unit == 'undefined') option.unit = true;
if (typeof option.statistic == 'undefined') option.statistic = true;
if (typeof option.celldata == 'undefined') option.celldata = true;
if (typeof option.cellsoh == 'undefined') option.cellsoh = true;
if (typeof option.log == 'undefined') option.log = true;
if (typeof option.time == 'undefined') option.time = true;
return this._model == 'FORCE' ? this._getDataFORCE(option) : this._getDataUS(option);
}
}
export = WorkerAbstract;
|
setwd('C:/Users/Praahas/Projects/R-Lab/Movie-Ratings')
# Grammar of Graphics
#Data
#Aesthetics - things we see axes,color, size
#Geometries - square, dot, circle, triangle
#Statistics
#Facets
#Co-Ordinates
#Theme
movies<-read.csv('movie1.csv')
movies
colnames(movies)
colnames(movies)<-c("Film","Genre","CriticRating","AudienceRating","BudgetMillions","Year")
str(movies)
movies$Genre<-as.factor(movies$Genre)
movies$Year<-as.factor(movies$Year)
summary(movies)
#Aesthetics
library(ggplot2)
#Add Geometry
ggplot(data=movies,aes(x=CriticRating,y=AudienceRating))+
geom_point()
#Add color
ggplot(data=movies,aes(x=CriticRating,y=AudienceRating,colour=Genre))+
geom_point()
#Add Size
ggplot(data=movies,aes(x=CriticRating,y=AudienceRating,colour=Genre,size=BudgetMillions))+
geom_point()
#Example to see working of LAyer by layer plotting of ggplot
p<-ggplot(data=movies,aes(x=CriticRating,y=AudienceRating,colour=Genre,size=BudgetMillions))
p + geom_point()
p + geom_line()
p+geom_line()+geom_point()
#Overriding Aesthetics
q<-ggplot(data=movies,aes(x=CriticRating,y=AudienceRating,colour=Genre,size=BudgetMillions))
#Add Geom Layer
q+geom_point()
#Overriding aesthetics
q+geom_point(aes(size=CriticRating))
q+geom_point(aes(colour=BudgetMillions))
q+geom_point()#q object remains as it is. we only modified teh layers by overriding it
#Overriding axes
q+geom_point(aes(x=BudgetMillions))+
xlab("Budget MIllions $$$")
#Till here we mapped aesthetitics. Now we shall set aesthetics here
q+geom_line(size=1)+geom_point()#Setting Aesthetics
#mapping vs Setting
r<-ggplot(data=movies,aes(x=CriticRating,y=AudienceRating))
r+geom_point()
#add color
r+geom_point(aes(colour=Genre))# use aes() function when mappingh to a variable
r+geom_point(colour="DarkGreen")#setting
r+geom_point(size=10)# use aes() function when mappingh to a variable
r+geom_point(aes(size=10))#Error
#histogram and density charts
s<-ggplot(data=movies,aes(x=BudgetMillions))
s+geom_histogram(binwidth = 10)
#Histogram - binwidth controls how wide each bar is. Each bar tells how many movie falls under that category
#addcolor
s+geom_histogram(binwidth=10,aes(fill=Genre))
s+geom_histogram(binwidth=10,aes(fill=Genre),colour="Black")
s+geom_histogram(binwidth=10,aes(fill=Genre),colour="Black")
s+geom_density(aes(fill=Genre),position="stack")
#Starting Layer
t<-ggplot(data=movies,aes(x=AudienceRating))
#alternate way
t<-ggplot(data=movies)
t+geom_histogram(binwidth=10,aes(x=AudienceRating),fill="White",colour="Blue")
t+geom_histogram(binwidth=10,fill="White",colour="Blue")
t<-ggplot(data=movies)
t+geom_histogram(binwidth = 10,aes(x=AudienceRating),fill="White",colour="Blue")
t+geom_histogram(binwidth = 10,aes(x=CriticRating),fill="White",colour="Blue")
#Critic Rating Looks UNiformly distributed because They review movies based on technical parameters, camera work, acting, sound work etc
#Audience Rating is normal distributed because of biases
#Skeleton Plot
t<-ggplot()
#Statistical Transformations
?geom_smooth
u<-ggplot(data=movies,aes(x=CriticRating,y=AudienceRating,colour=Genre))
u+geom_point()+geom_smooth(fill=NA)
#Observe - If critics give an action movie and a horror movie a score of 75, then statistically it is very likely that theaudience wioul rate the action movie higher.
#this is observed in the graph
#boxplots
u<-ggplot(data=movies,aes(x=Genre, y=AudienceRating,colour=Genre))
u+geom_boxplot()
u+geom_boxplot(size=1.2)
u+geom_boxplot(size=1.2)+geom_point()
#tip/hack
u+geom_boxplot(size=1.2)+geom_point()+geom_jitter()
u+geom_jitter()+geom_boxplot(size=1.2,alpha=0.3)
#Meaning of Boxplots
#BAsed on genre where is teh mean and what is the statistically likely rating a movie will get
#THriller has the narrowest box ie variance is low and gets the best rating
#IF a movie is made then depending on the genre,
#Actiopn movie may get somewhere around 60-57
#Horror has the lowest
#ROmance and Drama is pretty good
#boxplots
u<-ggplot(data=movies,aes(x=Genre, y=CriticRating,colour=Genre))
u+geom_boxplot()
u+geom_boxplot(size=1.2)
u+geom_boxplot(size=1.2)+geom_point()
#tip/hack
u+geom_boxplot(size=1.2)+geom_point()+geom_jitter()
u+geom_jitter()+geom_boxplot(size=1.2,alpha=0.3)
#Facets
v<-ggplot(data=movies,aes(x=BudgetMillions))
v+geom_histogram(binwidth=10,aes(fill=Genre),colour="Black")
v<-ggplot(data=movies,aes(x=BudgetMillions))
v+geom_histogram(binwidth=10,aes(fill=Genre),colour="Black")+
facet_grid(Genre~.)
v<-ggplot(data=movies,aes(x=BudgetMillions))
v+geom_histogram(binwidth=10,aes(fill=Genre),colour="Black")+
facet_grid(Genre~.,scales="free")
#scatterplots
w<-ggplot(data=movies,aes(x=CriticRating,y=AudienceRating,colour=Genre))
w+geom_point(size=3)
#facets
w+geom_point(size=3)+
facet_grid(Genre~.)
w+geom_point(size=3)+
facet_grid(Year~.)
w+geom_point(size=3)+
facet_grid(Genre~Year)
w+geom_point(size=3)+
geom_smooth()+
facet_grid(Genre~Year)
w+geom_point(aes(size=BudgetMillions))+
geom_smooth()+
facet_grid(Genre~Year)
#Co-ordinates - settign co-ordinates
m<-ggplot(data=movies,aes(x=CriticRating,y=AudienceRating,size=BudgetMillions,colour=Genre))
m+geom_point()
m+geom_point()+
xlim(50,100)+
ylim(50,100)
#Above method wont work well always as shown below
n<-ggplot(data=movies,aes(x=BudgetMillions))
n+geom_histogram(binwidth=10,aes(fill=Genre),colour="Black")+
ylim(0,50)
#instead use zoom
n+geom_histogram(binwidth=10,aes(fill=Genre),colour="Black")+
coord_cartesian(ylim=c(0,50))
w<-ggplot(data=movies,aes(x=CriticRating,y=AudienceRating,colour=Genre))
w+geom_point(aes(size=BudgetMillions))+
geom_smooth()+
facet_grid(Genre~Year)+
coord_cartesian(ylim=c(0,100))
#observation
#CEO wanted this info
#Action - when critics rate it low, audience tend to rate it low too
#And when critics rate it high, audience tend to rate it high as well
#Audience have rarely rated comedies low, regardless of how the critics rate them
#Audience ratings have slowly improved for comedies over teh years
#Action also has shown good performance
#Drama looks good too..rating over 50 consistently
#Theme
o<-ggplot(data=movies,aes(x=BudgetMillions))
h<-o+geom_histogram(binwidth=10,aes(fill=Genre),colour="Black")
#Add axes label + label formatting
h+xlab("Money Axis")+
ylab("Number of Movies")+
theme(axis.title.x= element_text(colour="DarkGreen",size=30),
axis.title.y = element_text(colour="Red",size=30))
h+xlab("Money Axis")+
ylab("Number of Movies")+
theme(axis.title.x= element_text(colour="DarkGreen",size=30),
axis.title.y = element_text(colour="Red",size=30),
axis.text.x=element_text(size=20),
axis.text.y=element_text(size=20))
#legend formatting
h+xlab("Money Axis")+
ylab("Number of Movies")+
theme(axis.title.x= element_text(colour="DarkGreen",size=30),
axis.title.y = element_text(colour="Red",size=30),
axis.text.x=element_text(size=20),
axis.text.y=element_text(size=20),
legend.title=element_text(size=30),
legend.text=element_text(size=20),
legend.position=c(1,1),
legend.justification=c(1,1))
#Title Formatting
h+xlab("Money Axis")+
ylab("Number of Movies")+
ggtitle("Movie Budget Distribution")+
theme(axis.title.x= element_text(colour="DarkGreen",size=30),
axis.title.y = element_text(colour="Red",size=30),
axis.text.x=element_text(size=20),
axis.text.y=element_text(size=20),
legend.title=element_text(size=30),
legend.text=element_text(size=20),
legend.position=c(1,1),
legend.justification=c(1,1),
plot.title = element_text(colour="DarkBlue",
size=40,
family="Courier"))
|
package br.ufc.quixada.blog.models;
import java.sql.Timestamp;
// import com.fasterxml.jackson.annotation.JsonBackReference;
// import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
// import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Table(name = "comentarios", schema = "public")
@Data
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Comentario {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
private String corpo;
@Temporal(TemporalType.TIMESTAMP)
private Timestamp dataDeCriacao;
@JsonIgnore
@ManyToOne(cascade = CascadeType.REMOVE)
private Post post;
@JsonIgnore
@ManyToOne(cascade = CascadeType.REMOVE)
private Usuario usuario;
}
|
import datetime
import errno
import os
import time
from collections import defaultdict, deque
import torch
import torch.distributed as dist
class SmoothedValue:
"""
跟踪一系列数值,通过一个窗口计算得到窗口均值
Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self, window_size=20, fmt=None):
if fmt is None:
fmt = "{median:.4f} ({global_avg:.4f})"
# 双端队列
self.deque = deque(maxlen=window_size)
# 总值
self.total = 0.0
# 计次
self.count = 0
# 格式
self.fmt = fmt
def update(self, value, n=1):
"""
更新n个值
@param value: 数值
@param n: 数量
@return: 无
"""
self.deque.append(value)
self.count += n
self.total += value * n
def synchronize_between_processes(self):
"""
进程间同步 Warning: does not synchronize the deque!
@return: 无
"""
t = reduce_across_processes([self.count, self.total])
t = t.tolist()
self.count = int(t[0])
self.total = t[1]
@property
def median(self):
""" 中位数 """
d = torch.tensor(list(self.deque))
return d.median().item()
@property
def avg(self):
""" 平均值 """
d = torch.tensor(list(self.deque), dtype=torch.float32)
return d.mean().item()
@property
def global_avg(self):
""" 全局平均值 """
return self.total / self.count
@property
def max(self):
""" 最大值 """
return max(self.deque)
@property
def value(self):
""" 最后一个值 """
return self.deque[-1]
def __str__(self):
""" 字符串 """
return self.fmt.format(
median=self.median, avg=self.avg, global_avg=self.global_avg, max=self.max, value=self.value
)
class ConfusionMatrix:
""" 混淆矩阵 """
def __init__(self, num_classes):
# 种类数量
self.num_classes = num_classes
# 混淆矩阵 mat[i][j]表示标签为i预测为j的数量
self.mat = None
def update(self, target, pred):
"""
根据标签值与预测值更新混淆矩阵
@param target: 标签值 y.flatten()
@param pred: 预测值 pred.argmax(1).flatten()
@return:
"""
# 创建混淆矩阵
n = self.num_classes
if self.mat is None:
self.mat = torch.zeros((n, n), dtype=torch.int64, device=target.device)
# 推理模式下计算
with torch.inference_mode():
# 有效性矩阵 1代表有效 0代表无效
k = (target >= 0) & (target < n)
# 筛选出有效的值计算索引
# 对于一个样本(target, pred),其对应的值为值为target * n + pred
inds = n * target[k].to(torch.int64) + pred[k]
# 计数并转换,更新混淆矩阵
self.mat += torch.bincount(inds, minlength=n ** 2).reshape(n, n)
def reset(self):
"""
重置混淆矩阵
@return: 无
"""
self.mat.zero_()
def compute(self):
"""
计算
@return: 全局准确度, 准确度, 交并比
"""
h = self.mat.float()
# 类别准确度
acc = torch.diag(h) / h.sum(1)
# 类别交并比
iu = torch.diag(h) / (h.sum(1) + h.sum(0) - torch.diag(h))
# 类别dice
dice = 2 * torch.diag(h) / (h.sum(1) + h.sum(0))
# 全局准确度
gAcc = torch.diag(h).sum() / h.sum()
# 平均交并比
mIou = iu.mean()
# 平均Dice
mDice = dice.mean()
return acc, iu, dice, gAcc, mIou, mDice
def reduce_from_all_processes(self):
"""
进程间reduce?
@return: 无
"""
reduce_across_processes(self.mat)
def __str__(self):
""" 字符串 """
acc, iu, dice, gAcc, mIou, mDice = self.compute()
acc_str = ', '.join([f"{i:.2f}%" for i in (acc * 100).tolist()])
dice_str = ', '.join([f"{i:.2f}%" for i in (dice * 100).tolist()])
iou_str = ', '.join([f"{i:.2f}%" for i in (iu * 100).tolist()])
return f"gAcc: {gAcc.item() * 100:.2f}%, mDice: {mDice.item() * 100:.2f}%, mIou: {mIou.item() * 100:.2f}%\n" + \
f"Acc: {acc_str}\nDice: {dice_str}\nIou: {iou_str}\n"
class MetricLogger:
""" 度量记录器 """
def __init__(self, delimiter="\t"):
# 计量器 本质为字典 默认值为一个SmoothValue
self.meters = defaultdict(SmoothedValue)
# 分隔符
self.delimiter = delimiter
def update(self, **kwargs):
"""
更新度量标准
@param kwargs: 参数 形式为name=meter
@return: 无
"""
for k, v in kwargs.items():
if isinstance(v, torch.Tensor):
v = v.item()
if not isinstance(v, (float, int)):
raise TypeError(f"This method expects the value of the input arguments to be of type float or int, instead got {type(v)}")
# 更新第k个度量
self.meters[k].update(v)
def __getattr__(self, attr):
""" 属性 """
if attr in self.meters:
return self.meters[attr]
if attr in self.__dict__:
return self.__dict__[attr]
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{attr}'")
def __str__(self):
""" 字符串 """
loss_str = []
for name, meter in self.meters.items():
loss_str.append(f"{name}: {str(meter)}")
return self.delimiter.join(loss_str)
def synchronize_between_processes(self):
"""
进程间同步
@return: 无
"""
for meter in self.meters.values():
meter.synchronize_between_processes()
def add_meter(self, name, meter):
"""
添加度量器
@param name: 度量名称
@param meter: 度量标准
@return: 无
"""
self.meters[name] = meter
def log_every(self, iterable, print_freq, header=None):
"""
打印
@param iterable: 可迭代对象
@param print_freq: 打印频率
@param header: 头部
@return: 无
"""
i = 0
# 检查需不需要header
if not header:
header = ""
# 起止时间
start_time = time.time()
end = time.time()
# 迭代时间
iter_time = SmoothedValue(fmt="{avg:.4f}")
data_time = SmoothedValue(fmt="{avg:.4f}")
# 格式 ':xd' -> 长度为x的整数,可迭代对象长度为78 -> :2d, 1478 -> :4d
space_fmt = ":" + str(len(str(len(iterable)))) + "d"
# # 打印信息
if torch.cuda.is_available():
# 若cuda可用则添加内存信息
log_msg = self.delimiter.join(
[header, "[{0" + space_fmt + "}/{1}]", "eta: {eta}", "{meters}", "time: {time}", "data: {data}", "max mem: {memory:.0f}",]
)
else:
log_msg = self.delimiter.join(
[header, "[{0" + space_fmt + "}/{1}]", "eta: {eta}", "{meters}", "time: {time}", "data: {data}"]
)
# MB单位
MB = 1024.0 * 1024.0
# 遍历可迭代对象
for obj in iterable:
# 更新时间
data_time.update(time.time() - end)
yield obj # 按需生成值
iter_time.update(time.time() - end)
# 如果需要打印
if i % print_freq == 0:
# 剩余秒
eta_seconds = iter_time.global_avg * (len(iterable) - i)
# 剩余时间字符串
eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
if torch.cuda.is_available():
print(log_msg.format(i, len(iterable), eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time), memory=torch.cuda.max_memory_allocated() / MB,))
else:
print(log_msg.format(i, len(iterable), eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time)))
i += 1
# 更新结束时间
end = time.time()
# 总时间
total_time = time.time() - start_time
# 总时间字符串
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
print(f"{header} Total time: {total_time_str}")
def cat_list(images, fill_value=0):
"""
将一组图像拼为一个批次 batch
@param images: 图像
@param fill_value: 填充值
@return: 一个批次的图像
"""
# 图像中的最大尺寸
max_size = tuple(max(s) for s in zip(*[img.shape for img in images]))
# 一个批次的形状
batch_shape = (len(images),) + max_size
# 一个批次的图像填充默认值
batched_imgs = images[0].new(*batch_shape).fill_(fill_value)
# 将原来图像填充回去
for img, pad_img in zip(images, batched_imgs):
pad_img[..., :img.shape[-2], :img.shape[-1]].copy_(img)
return batched_imgs
def collate_fn(batch):
"""
处理数据加载器组装一个批次的逻辑
@param batch: 批次
@return:
"""
images, targets = list(zip(*batch))
# 图像填充0
batched_imgs = cat_list(images, fill_value=0)
# 标签填充255
batched_targets = cat_list(targets, fill_value=255)
return batched_imgs, batched_targets
def mkdir(path):
"""
创建文件夹
@param path: 路径
@return: 无
"""
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def setup_for_distributed(is_master):
"""
设置分布式计算,该函数禁用了非主进程的打印,替换了print函数
This function disables printing when not in master process
@param is_master: 是否为主进程
@return: 无
"""
import builtins as __builtin__
# 保存print
builtin_print = __builtin__.print
# 定义新的print
def print(*args, **kwargs):
# 找出force选项,若不存在则设为False
force = kwargs.pop("force", False)
# 如果为主进程,或非主进程设置了强制输出(force=True)
if is_master or force:
builtin_print(*args, **kwargs)
# 将print设置为自定义的print函数
__builtin__.print = print
def is_dist_avail_and_initialized():
"""
检查分布式训练环境是否可用和是否已经初始化
@return: 分布式训练环境是否可用和是否已经初始化
"""
# 检查 PyTorch 是否支持分布式训练
if not dist.is_available():
return False
# 检查当前 PyTorch 进程是否已经初始化为分布式进程
if not dist.is_initialized():
return False
return True
def get_world_size():
"""
获取当前分布式训练环境的进程数量(world size)。在分布式训练中,world size 表示运行在所有节点上的总进程数
@return: 所有节点上的总进程数
"""
if not is_dist_avail_and_initialized():
return 1
return dist.get_world_size()
def get_rank():
"""
获取当前进程在分布式训练环境中的排名(rank)。在分布式训练中,每个进程都有一个唯一的排名,通常从 0 开始。
@return: 当前进程在分布式训练环境中的排名
"""
if not is_dist_avail_and_initialized():
return 0
return dist.get_rank()
def is_main_process():
"""
检查当前进程是否是主进程。在分布式训练环境中,主进程通常负责一些特殊的任务,例如数据加载、模型保存等。
@return: 当前进程排名若为0则为主进程
"""
return get_rank() == 0
def save_on_master(*args, **kwargs):
"""
在分布式训练环境中只在主进程保存模型。在分布式训练中,只有主进程通常负责保存模型,以避免多个进程同时尝试写入相同的文件。
@param args: 参数
@param kwargs: 关键字参数
@return:
"""
if is_main_process():
torch.save(*args, **kwargs)
def init_distributed_mode(args):
"""
初始化分布式训练模式,用于在分布式训练模式下初始化相关参数和环境。
@param args: 参数
@return: 无
"""
# 检查环境变量
if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
args.rank = int(os.environ["RANK"])
args.world_size = int(os.environ["WORLD_SIZE"])
args.gpu = int(os.environ["LOCAL_RANK"])
# 使用 SLURM 环境
elif "SLURM_PROCID" in os.environ:
args.rank = int(os.environ["SLURM_PROCID"])
args.gpu = args.rank % torch.cuda.device_count()
# 检查参数中是否已经存在 rank
elif hasattr(args, "rank"):
pass
else:
print("Not using distributed mode")
args.distributed = False
return
# 初始化分布式环境
args.distributed = True
torch.cuda.set_device(args.gpu)
args.dist_backend = "nccl"
print(f"| distributed init (rank {args.rank}): {args.dist_url}", flush=True)
torch.distributed.init_process_group(
backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank
)
torch.distributed.barrier()
setup_for_distributed(args.rank == 0)
def reduce_across_processes(val):
"""
在分布式训练环境中将不同进程的值进行归约操作
@param val: 值
@return:
"""
# 若非分布式环境
if not is_dist_avail_and_initialized():
# nothing to sync, but we still convert to tensor for consistency with the distributed case.
return torch.tensor(val)
# 分布式环境
t = torch.tensor(val, device="cuda")
dist.barrier()
dist.all_reduce(t)
# 最终结果
return t
|
import React, { useState } from 'react';
import {
Progress,
Box,
ButtonGroup,
Button,
Heading,
Flex,
FormControl,
GridItem,
FormLabel,
Input,
Select,
SimpleGrid,
InputLeftAddon,
InputGroup,
Textarea,
FormHelperText,
InputRightElement,
} from '@chakra-ui/react';
import { ViewIcon, ViewOffIcon } from '@chakra-ui/icons'
import { useToast } from '@chakra-ui/react';
import Swal from 'sweetalert2'
import { useNavigate } from 'react-router-dom';
const Form1 = () => {
const [show, setShow] = React.useState(false);
const handleClick = () => setShow(!show);
return (
<>
<Heading w="100%" textAlign={'center'} fontWeight="normal" mb="2%">
User Registration
</Heading>
<Flex>
<FormControl mr="5%">
<FormLabel htmlFor="first-name" fontWeight={'normal'}>
First name
</FormLabel>
<Input id="first-name" placeholder="First name" />
</FormControl>
<FormControl>
<FormLabel htmlFor="last-name" fontWeight={'normal'}>
Last name
</FormLabel>
<Input id="last-name" placeholder="First name" />
</FormControl>
</Flex>
<FormControl mt="2%">
<FormLabel htmlFor="email" fontWeight={'normal'}>
Email address
</FormLabel>
<Input id="email" type="email" />
<FormHelperText>We'll never share your email.</FormHelperText>
</FormControl>
<FormControl>
<FormLabel htmlFor="password" fontWeight={'normal'} mt="2%">
Password
</FormLabel>
<InputGroup size="md">
<Input
pr="4.5rem"
type={show ? 'text' : 'password'}
placeholder="Enter password"
/>
<InputRightElement width="4.5rem">
<Button h="1.75rem" size="sm" onClick={handleClick}>
{show ? 'Hide' : 'Show'}
</Button>
</InputRightElement>
</InputGroup>
</FormControl>
</>
);
};
const Form2 = () => {
return (
<>
<Heading w="100%" textAlign={'center'} fontWeight="normal" mb="2%">
User Details
</Heading>
<FormControl isRequired as={GridItem} colSpan={[6, 3]}>
<FormLabel
htmlFor="country"
fontSize="sm"
fontWeight="md"
color="gray.700"
_dark={{
color: 'gray.50',
}}>
Country / Region
</FormLabel>
<Select
id="country"
name="country"
autoComplete="country"
placeholder="Select option"
focusBorderColor="brand.400"
shadow="sm"
size="sm"
required= {true}
w="full"
rounded="md">
<option>United States</option>
<option>Canada</option>
<option>Mexico</option>
<option>India</option>
<option>Russia</option>
<option>China</option>
<option>Mexico</option>
<option>Bangladesh</option>
</Select>
</FormControl>
<FormControl isRequired as={GridItem} colSpan={6}>
<FormLabel
htmlFor="street_address"
fontSize="sm"
fontWeight="md"
color="gray.700"
_dark={{
color: 'gray.50',
}}
mt="2%">
Street address
</FormLabel>
<Input
type="text"
name="street_address"
id="street_address"
autoComplete="street-address"
focusBorderColor="brand.400"
shadow="sm"
size="sm"
w="full"
rounded="md"
required= {true}
/>
</FormControl>
<FormControl as={GridItem} colSpan={[6, 6, null, 2]}>
<FormLabel
htmlFor="city"
fontSize="sm"
fontWeight="md"
color="gray.700"
_dark={{
color: 'gray.50',
}}
mt="2%">
City
</FormLabel>
<Input
type="text"
name="city"
id="city"
autoComplete="city"
focusBorderColor="brand.400"
shadow="sm"
size="sm"
w="full"
rounded="md"
/>
</FormControl>
<FormControl isRequired as={GridItem} colSpan={[6, 3, null, 2]}>
<FormLabel
htmlFor="state"
fontSize="sm"
fontWeight="md"
color="gray.700"
_dark={{
color: 'gray.50',
}}
mt="2%">
State / Province
</FormLabel>
<Input
type="text"
name="state"
id="state"
autoComplete="state"
focusBorderColor="brand.400"
shadow="sm"
size="sm"
w="full"
rounded="md"
required={true}
/>
</FormControl>
<FormControl isRequired as={GridItem} colSpan={[6, 3, null, 2]}>
<FormLabel
htmlFor="postal_code"
fontSize="sm"
fontWeight="md"
color="gray.700"
_dark={{
color: 'gray.50',
}}
mt="2%">
ZIP / Postal
</FormLabel>
<Input
type="text"
name="postal_code"
id="postal_code"
autoComplete="postal-code"
focusBorderColor="brand.400"
shadow="sm"
size="sm"
w="full"
rounded="md"
required={true}
/>
</FormControl>
</>
);
};
const Form3 = () => {
const [showPassword, setShowPassword] = useState(false);
return (
<>
<Heading w="100%" textAlign={'center'} fontWeight="normal">
Payment
</Heading>
<SimpleGrid columns={1} spacing={6}>
<FormControl isRequired id="cardno" >
<FormLabel>Card Number</FormLabel>
<Input required={true} type="number" placeholder='1234 1234 1234 1234' />
</FormControl>
<FormControl isRequired id="date" >
<FormLabel>Exp Date</FormLabel>
<Input required={true} type="date" placeholder='1234 1234 1234 1234' />
</FormControl>
<FormControl isRequired id="password" >
<FormLabel>CVV</FormLabel>
<InputGroup>
<Input required={true} type={showPassword ? 'text' : 'password'} />
<InputRightElement h={'full'}>
<Button
variant={'ghost'}
onClick={() =>
setShowPassword((showPassword) => !showPassword)
}>
{showPassword ? <ViewIcon /> : <ViewOffIcon />}
</Button>
</InputRightElement>
</InputGroup>
</FormControl>
<FormControl id="firstName" isRequired>
<FormLabel>Name on Card</FormLabel>
<Input required={true} type="text" />
</FormControl>
<FormControl id="firstName" isRequired>
<FormLabel>Billing Address</FormLabel>
<Input required={true} type="text" placeholder='Country' />
<Input required={true} type="text" placeholder='Address' />
<FormHelperText>
Brief description for your profile. URLs are hyperlinked.
</FormHelperText>
</FormControl>
</SimpleGrid>
</>
);
};
export default function Payment() {
const navigate=useNavigate();
const [step, setStep] = useState(1);
const [progress, setProgress] = useState(33.33);
return (
<>
<Box
borderWidth="1px"
rounded="lg"
shadow="1px 1px 3px rgba(0,0,0,0.3)"
maxWidth={800}
p={6}
m="10px auto"
as="form">
<Progress
hasStripe
value={progress}
mb="5%"
mx="5%"
isAnimated></Progress>
{step === 1 ? <Form2 /> : <Form3 />}
<ButtonGroup mt="5%" w="100%">
<Flex w="100%" justifyContent="space-between">
<Flex>
<Button
onClick={() => {
setStep(step - 1);
setProgress(progress - 33.33);
}}
isDisabled={step === 1}
colorScheme="teal"
variant="solid"
w="7rem"
mr="5%">
Back
</Button>
<Button
w="7rem"
isDisabled={step === 2}
onClick={() => {
setStep(step + 1);
if (step === 2) {
setProgress(100);
} else {
setProgress(progress + 33.33);
}
}}
colorScheme="teal"
variant="outline">
Next
</Button>
</Flex>
{step === 2 ? (
<Button
w="7rem"
colorScheme="red"
variant="solid"
onClick={() => {
Swal.fire(
'Order Placed!!',
'Your order will be delivered in 5-8 business days!!',
'success'
)
navigate('/')
}}>
Thank You
</Button>
) : null}
</Flex>
</ButtonGroup>
</Box>
</>
);
}
|
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { RegistrationComponent } from './registration/registration.component';
import { StudentListComponent } from './student-list/student-list.component';
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'student/create', component: RegistrationComponent },
{ path: 'students', component: StudentListComponent },
{ path: 'login', component: LoginComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
/* Gtk+ User Interface Builder
* Copyright (C) 1998 Damon Chaplin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef GLADE_UTILS_H
#define GLADE_UTILS_H
#include <gtk/gtkfeatures.h>
#include <gtk/gtkbox.h>
#include <gtk/gtkfixed.h>
#include <gtk/gtktable.h>
#include <gtk/gtkpacker.h>
#include <gtk/gtktoolbar.h>
#include <gtk/gtkwindow.h>
#include <gtk/gtkobject.h>
#include "gbwidget.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Days of the week, 'Sun' ... 'Sat'. */
extern gchar *GladeDayNames[];
/* Months of the year, 'Jan' ... 'Dec'. */
extern gchar *GladeMonthNames[];
/* This shows a simple dialog box with a label and an 'OK' button.
If transient_widget is not NULL, then its toplevel window is found and used
to set the transient_for property (this also works for menu widgets).
Example usage:
glade_util_show_message_box ("Error saving file", NULL);
*/
void glade_util_show_message_box (const gchar *message,
GtkWidget *transient_widget);
/* This creates a dialog box with a message and a number of buttons.
* Signal handlers can be supplied for any of the buttons.
* NOTE: The dialog is automatically destroyed when any button is clicked.
* default_button specifies the default button, numbered from 1..
* data is passed to the signal handler.
Example usage:
gchar *buttons[] = { "Yes", "No", "Cancel" };
GtkSignalFunc signal_handlers[] = { on_yes, on_no, NULL };
glade_util_show_dialog ("Do you want to save the current project?",
3, buttons, 3, signal_handlers, NULL);
*/
GtkWidget* glade_util_create_dialog_with_buttons (const gchar *message,
gint nbuttons,
const gchar *buttons[],
gint default_button,
GtkSignalFunc signal_handlers[],
gpointer data,
GtkWidget *transient_widget);
/* This shows a dialog box with a message and an Entry for entering a value.
* When the OK button is pressed the handler of the specified widget will
* be called with the value and the given data.
* NOTE: The dialog is automatically destroyed when any button is clicked.
Example usage:
glade_util_show_entry_dialog ("Name:", "default", widget, on_dialog_ok,
"NewName");
void
on_dialog_ok(GtkWidget *widget, gchar *value, gpointer data)
{
...
*/
typedef gint (*GbEntryDialogFunc) (GtkWidget *widget,
gchar *value,
gpointer data);
void glade_util_show_entry_dialog(const gchar *message,
const gchar *initial_value,
GtkWidget *widget,
GbEntryDialogFunc signal_handler,
gpointer data,
GtkWidget *transient_widget);
/* This creates a dialog with OK & Cancel buttons, usable in plain GTK or
Gnome, and returns a vbox which the caller can place widgets in.
If transient_for is non-NULL, the window it is in is used to set the
transient for relationship, so the dialog will always be above the widget.
The callback will be called when the OK button is pressed. */
GtkWidget* glade_util_create_dialog (const gchar *title,
GtkWidget *transient_for,
GtkSignalFunc ok_handler,
gpointer ok_handler_data,
GtkWidget **vbox);
typedef enum
{
GladeEscCloses,
GladeEscDestroys
} GladeEscAction;
/* This event handler performs the selected GladeEscAction when Esc is
pressed in a dialog.
It is not necessary for GnomeDialogs. */
gint glade_util_check_key_is_esc (GtkWidget *widget,
GdkEventKey *event,
gpointer data);
/* This returns a new entry ready to insert in a dialog.
The entry is set up so that <Return> will invoke the default action. The
returned widget must be added to a container in the dialog. */
extern GtkWidget *
glade_util_entry_new (GtkObject *dialog);
/* This returns a new spinbutton ready to insert in a dialog.
A pointer to the spin button is added as object data to the dialog. The
spinbutton is set up so that <Return> will invoke the default action. The
returned widget must be added to a container in the dialog. */
extern GtkWidget *
glade_util_spin_button_new (GtkObject *dialog,
const gchar *key,
GtkAdjustment *adjustment,
gfloat climb_rate,
guint digits);
/* This returns the index of the given gint with the given array of gints.
If the value is not found it outputs a warning and returns -1.
This function is intended to be used for finding the index when using
properties which are choices. */
gint glade_util_int_array_index (const gint array[],
gint array_size,
gint value);
/* This returns the index of the given string with the given array of strings.
If the value is not found it outputs a warning and returns -1.
This function is intended to be used for finding the index when using
properties which are choices. */
gint glade_util_string_array_index (const gchar *array[],
gint array_size,
const gchar *value);
/* This returns TRUE if the two strings are equivalent. Note that NULL is
considered equivalent to the empty string. */
gboolean glade_util_strings_equivalent (const gchar *string1,
const gchar *string2);
/* This returns a copy of the given string, or NULL if the string is NULL
or empty, i.e. "". */
gchar* glade_util_copy_string (const gchar *string);
/* Returns TRUE if string contains substring. Returns FALSE if substring is
not found or is NULL. */
gboolean glade_util_strstr (const gchar *string,
const gchar *substring);
gchar* glade_util_find_start_of_tag_name (const gchar * tag_name);
gchar* glade_util_create_modifiers_string (guint8 modifier_flags);
/* This creates a GtkPixmap widget, using a colormap and xpm data from an
'#include'd pixmap file. */
GtkWidget* glade_util_create_pixmap_using_colormap (GdkColormap *colormap,
gchar **xpm_data);
/* This returns TRUE if the widget is a toplevel project component,
i.e. a window, dialog or popup menu. */
gboolean glade_util_is_component (GtkWidget *widget);
/* This returns the toplevel widget containing the given widget. It is similar
to gtk_widget_get_toplevel() but is also walks up menus. */
GtkWidget* glade_util_get_toplevel (GtkWidget *widget);
/* This returns the closest ancestor of the given widget which is a GbWidget.*/
GtkWidget* glade_util_get_parent (GtkWidget *widget);
/* This tries to find a named widget in a component. It returns the widget or
NULL if it wasn't found. */
GtkWidget* glade_util_find_widget (GtkWidget *widget, gchar *name);
/* This is used when setting up keyboard accelerators resulting from underlined
keys in labels. It returns the widget to add the accelerator to, and the
signal to emit. If the label is in a button, then the accelerator is
connected to the button's "activate" signal. If not, it tries to find the
widget to the right of the label, and connects to its "set_focus" signal. */
GtkWidget* glade_util_find_default_accelerator_target (GtkWidget *label,
gchar **signal);
/* This looks up the hierarchy, starting from widget, trying to find a
GtkButton or subclass. It returns the button widget or NULL if not found. */
GtkWidget* glade_util_find_parent_button (GtkWidget *widget);
/* Returns the index of a widget in a box. Note that the box packing
property means that widgets may not be displayed in this order. */
gint glade_util_get_box_pos (GtkBox *box,
GtkWidget *widget);
/* Returns the structure corresponding to the given widget in a table. */
GtkTableChild* glade_util_find_table_child (GtkTable *table,
GtkWidget *widget);
GtkBoxChild* glade_util_find_box_child (GtkBox *box,
GtkWidget *widget);
GtkFixedChild* glade_util_find_fixed_child (GtkFixed *fixed,
GtkWidget *widget);
GtkPackerChild* glade_util_find_packer_child (GtkPacker *packer,
GtkWidget *widget);
GtkToolbarChild* glade_util_find_toolbar_child (GtkWidget *toolbar,
GtkWidget *child,
gint *pos,
GList **elem);
/* This returns the GtkLabel's text, including the underline characters.
It is needed since GtkLabel doesn't provide the opposite function to
gtk_label_parse_uline(). The returned string should be freed after use. */
gchar* glade_util_get_label_text (GtkWidget *label);
/* These close the given window, so that if it is shown again it appears in
the same place. */
gint glade_util_close_window_on_delete (GtkWidget *widget,
GdkEvent *event,
gpointer data);
gint glade_util_close_window (GtkWidget *widget);
/*
* File Utility Functions.
*/
/* Returns TRUE if the given file exists. */
gboolean glade_util_file_exists (const gchar *filename);
GladeError* glade_util_file_last_mod_time (const gchar *filename,
time_t *last_mod_time);
/* Copies src to dest, returning a GladeError if an error occurs. */
GladeError* glade_util_copy_file (const gchar *src,
const gchar *dest);
/* Creates a directory if it doesn't already exist. */
GladeError* glade_util_ensure_directory_exists (const gchar *directory);
/*
* Filename Utility Functions.
*/
/* Adds a filename onto a directory to make a complete pathname.
The directory may or may not end in '/'. file must be a simple filename.
Free the returned string when no longer needed. */
gchar* glade_util_make_path (const gchar *dir,
const gchar *file);
/* This turns a relative pathname into an absolute one based on the given
base directory (which MUST be absolute).
e.g. "/home/damon" + "../dave/test" -> "/home/dave/test"
The returned path should be freed when no longer needed. */
gchar* glade_util_make_absolute_path (const gchar *dir,
const gchar *file);
/* This turns an absolute pathname into an relative one based on the given
base directory. Both arguments must be absolute paths, and should be in
canonical form, i.e. not containing '..', '.' or multiple '/'s together.
The returned value may or may not end with a '/', depending on the
arguments. The returned path should be freed when no longer needed. */
gchar* glade_util_make_relative_path (const gchar *base_dir,
const gchar *file);
/* Returns TRUE if file is in dir. Both paths must be absolute. file can
be a directory, and both can end in '/' or not. Note that we assume
that both are in proper form, i.e. there are no instances of '//', '.',
or '..' in either. */
gboolean glade_util_directory_contains_file (const gchar *dir,
const gchar *file);
/* Returns TRUE if the 2 directories are equivalent. Both must be absolute
paths, and may or may not end in '/'. */
gboolean glade_util_directories_equivalent (const gchar *dir1,
const gchar *dir2);
/* This is similar to GLib's dirname, but it makes sure the dirname ends with
a G_DIR_SEPARATOR. */
gchar* glade_util_dirname (const gchar *file_name);
/* This returns the parent directory of the given directory, which may or may
not end in a G_DIR_SEPARATOR. The returned string should be freed. */
gchar* glade_util_parent_directory (const gchar *dir);
/* This searches the $HOME/Projects directory to find the default directory to
use for the next project, e.g. $HOME/Projects/project1. The returned
directory should be freed when no longer needed. */
GladeError* glade_util_get_next_free_project_directory (gchar **project_directory_return,
gint *project_num_return);
/* Sets the TZ environment variable to the given value, e.g. "UTC", returning
the old setting.
NOTE: You must call glade_util_reset_timezone() some time later to restore
the original TZ. Pass glade_util_reset_timezone() the string that
glade_util_set_timezone() returns. */
gchar* glade_util_set_timezone (const gchar *tz);
void glade_util_reset_timezone (gchar *tz);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* GLADE_UTILS_H */
|
"use strict";
var _legacy = require("./legacy");
var _styledSystem = require("../../styled-system");
var width = (0, _legacy.style)({
prop: 'width'
});
var color = (0, _legacy.style)({
prop: 'color',
key: 'colors'
});
var backgroundColor = (0, _legacy.style)({
prop: 'backgroundColor',
alias: 'bg',
key: 'colors'
});
var theme = {
colors: {
blue: '#07c',
black: '#111'
}
};
test('returns a style function', function () {
var func = (0, _legacy.style)({
prop: 'width'
});
expect(typeof func).toBe('function');
});
test('function returns a style object', function () {
var style = width({
width: '50%'
});
expect(style).toEqual({
width: '50%'
});
});
test('returns values from theme', function () {
var style = color({
theme: theme,
color: 'blue'
});
expect(style).toEqual({
color: '#07c'
});
});
test('handles aliased props', function () {
var style = backgroundColor({
theme: theme,
bg: 'blue'
});
expect(style).toEqual({
backgroundColor: '#07c'
});
});
test('returns 0', function () {
var style = width({
width: 0
});
expect(style).toEqual({
width: 0
});
});
test('returns responsive style objects', function () {
var style = width({
width: ['100%', '50%']
});
expect(style).toEqual({
width: '100%',
'@media screen and (min-width: 40em)': {
width: '50%'
}
});
});
test('returns responsive style objects for all breakpoints', function () {
var style = width({
width: ['100%', '75%', '50%', '33%', '25%']
});
expect(style).toEqual({
width: '100%',
'@media screen and (min-width: 40em)': {
width: '75%'
},
'@media screen and (min-width: 52em)': {
width: '50%'
},
'@media screen and (min-width: 64em)': {
width: '33%'
}
});
});
test('skips undefined responsive values', function () {
var style = width({
width: ['100%',, '50%']
});
expect(style).toEqual({
width: '100%',
'@media screen and (min-width: 52em)': {
width: '50%'
}
});
});
test('parses object values', function () {
var style = width({
width: {
_: '100%',
2: '50%'
}
});
expect(style).toEqual({
width: '100%',
'@media screen and (min-width: 64em)': {
width: '50%'
}
});
});
test('array values longer than breakpoints does not reset returned style object', function () {
var a = width({
width: ['100%',,,,, '50%', '25%']
});
expect(a).toEqual({
width: '100%'
});
});
test('shimmed width only supports width prop', function () {
var a = (0, _styledSystem.width)({
width: 1,
height: 32,
maxWidth: 768
});
expect(a).toEqual({
width: '100%'
});
});
|
# Import necessary libraries
from flask import Flask, request, jsonify
from flask_cors import CORS
from analysis_model import perform_analysis
import subprocess
import numpy as np
app = Flask(__name__)
CORS(app)
# Function to run the analysis and predictor scripts
def run_analysis_and_predictor():
try:
# Run the analysis script
subprocess.run(['python', 'analysis_model.py'], check=True)
# Run the predictor script
subprocess.run(['python', 'predictor.py'], check=True)
# Load the predicted labels and sentiment result after running the predictor script
predicted_labels = np.loadtxt('predicted_labels.txt', dtype=int)
sentiment_result = calculate_sentiment_result(predicted_labels)
return predicted_labels, sentiment_result
except Exception as e:
print(f"Error during analysis and prediction: {e}")
return None, None
# Function to calculate sentiment result
def calculate_sentiment_result(predicted_labels):
positive_count = np.sum(predicted_labels == 1)
total_count = len(predicted_labels)
sentiment_result = (positive_count / total_count) * 100 if total_count > 0 else 0
return sentiment_result
# Trigger the analysis and predictor on startup
predicted_labels, initial_sentiment_result = run_analysis_and_predictor()
# Handle the API request
@app.route('/api/sentiment', methods=['GET', 'POST'])
def sentiment_analysis():
global predicted_labels
if request.method == 'GET':
try:
# Compute sentiment_result based on the frequency of positive labels
sentiment_result = calculate_sentiment_result(predicted_labels)
# Print sentiment_result to the console
print("Sentiment Result:", sentiment_result)
# Return sentiment result and predicted labels in the JSON response
response_data = {'sentiment': sentiment_result, 'predicted_labels': predicted_labels.tolist()}
return jsonify(response_data)
except Exception as e:
print("Error during sentiment analysis:", e)
return jsonify({'error': 'Internal Server Error'}), 500
@app.route('/start-apps', methods=['GET'])
def start_apps():
try:
# Start both apps using the script
subprocess.run(['python', 'run_apps.py'], check=True)
return jsonify({'message': 'Apps started successfully'})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
|
import {
Box,
CircularProgress,
IconButton,
List,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
Skeleton,
Typography,
} from "@mui/material";
import { produce } from "immer";
import { ReactNode, useMemo, useReducer, useState } from "react";
import { useTranslation } from "react-i18next";
import { usePromise as usePromiseWrapper, useUpdateEffect } from "react-use";
import { Action } from "redux";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import * as R from "ramda";
import GroupIcon from "@mui/icons-material/Group";
import { useSnackbar } from "notistack";
import { GroupDetailsDTO } from "../../../../common/types";
import usePromiseWithSnackbarError from "../../../../hooks/usePromiseWithSnackbarError";
import { deleteGroup, getGroups } from "../../../../services/api/user";
import { sortByName } from "../../../../services/utils";
import ConfirmationDialog from "../../../common/dialogs/ConfirmationDialog";
import useEnqueueErrorSnackbar from "../../../../hooks/useEnqueueErrorSnackbar";
import { RESERVED_GROUP_NAMES } from "../utils";
import Header from "./Header";
import UpdateGroupDialog from "./dialog/UpdateGroupDialog";
import { getAuthUser } from "../../../../redux/selectors";
import useAppSelector from "../../../../redux/hooks/useAppSelector";
import { isSearchMatching } from "../../../../utils/textUtils";
/**
* Types
*/
enum GroupActionKind {
ADD = "ADD",
EDIT = "EDIT",
DELETE = "DELETE",
RESET = "RESET",
}
export type GroupEdit = Partial<GroupDetailsDTO> & {
id: GroupDetailsDTO["id"];
};
interface GroupAction extends Action<string> {
payload?:
| GroupDetailsDTO["id"]
| GroupDetailsDTO
| GroupDetailsDTO[]
| GroupEdit;
}
/**
* Utils
*/
const reducer = produce<GroupDetailsDTO[], [GroupAction]>((draft, action) => {
const { payload } = action;
switch (action.type) {
case GroupActionKind.ADD: {
draft.push(payload as GroupDetailsDTO);
return;
}
case GroupActionKind.EDIT: {
const { id, ...newData } = payload as GroupEdit;
const index = draft.findIndex((group) => group.id === id);
if (index > -1) {
draft[index] = { ...draft[index], ...newData };
}
return;
}
case GroupActionKind.DELETE: {
const index = draft.findIndex((group) => group.id === payload);
if (index > -1) {
draft.splice(index, 1);
}
return;
}
case GroupActionKind.RESET:
return payload as GroupDetailsDTO[];
}
});
/**
* Component
*/
function Groups() {
const [groupToDelete, setGroupToDelete] = useState<GroupDetailsDTO>();
const [groupToEdit, setGroupToEdit] = useState<GroupDetailsDTO>();
const [groupsInLoading, setGroupsInLoading] = useState<GroupDetailsDTO[]>([]);
const [groups, dispatch] = useReducer(reducer, []);
const [searchValue, setSearchValue] = useState("");
const { enqueueSnackbar } = useSnackbar();
const enqueueErrorSnackbar = useEnqueueErrorSnackbar();
const mounted = usePromiseWrapper();
const { t } = useTranslation();
const authUser = useAppSelector(getAuthUser);
const {
data: initialGroups,
isLoading,
reload: reloadFetchGroups,
} = usePromiseWithSnackbarError(() => getGroups({ details: true }), {
errorMessage: t("settings.error.groupsError"),
});
useUpdateEffect(() => {
setGroupToDelete(undefined);
setGroupToEdit(undefined);
setGroupsInLoading([]);
dispatch({ type: GroupActionKind.RESET, payload: initialGroups || [] });
}, [initialGroups]);
const filteredAndSortedGroups = useMemo(() => {
let list = groups
.filter((gp) => !RESERVED_GROUP_NAMES.includes(gp.name))
.map((gp) => ({
...gp,
users: gp.users.filter((user) => user.id !== authUser?.id),
}));
if (searchValue) {
list = groups?.filter((group) => {
return isSearchMatching(searchValue, group.name);
});
}
return sortByName(list);
}, [searchValue, groups, authUser]);
// Utils
const addGroup = (group: GroupDetailsDTO) => {
dispatch({ type: GroupActionKind.ADD, payload: group });
};
const editGroup = (group: GroupEdit) => {
dispatch({ type: GroupActionKind.EDIT, payload: group });
};
// Event Handlers
const handleDeleteGroup = () => {
if (!groupToDelete) {
return;
}
const group = groupToDelete;
setGroupsInLoading((prev) => [...prev, group]);
setGroupToDelete(undefined);
mounted(deleteGroup(group.id))
.then(() => {
dispatch({ type: GroupActionKind.DELETE, payload: group.id });
enqueueSnackbar(t("settings.success.groupDelete", { 0: group.name }), {
variant: "success",
});
})
.catch((err) => {
enqueueErrorSnackbar(
t("settings.error.groupDelete", { 0: group.name }),
err,
);
})
.finally(() => {
setGroupsInLoading((prev) => prev.filter((u) => u !== group));
});
};
// JSX
return (
<Box
sx={{
display: "flex",
flexDirection: "column",
height: 1,
}}
>
<Header
setSearchValue={setSearchValue}
addGroup={addGroup}
reloadFetchGroups={reloadFetchGroups}
/>
<List sx={{ overflow: "auto" }}>
{R.cond([
// Loading
[
() => isLoading,
() =>
Array.from({ length: 3 }, (v, k) => k).map((v) => (
<ListItem key={v} disablePadding>
<Skeleton sx={{ width: 1, height: 50 }} />
</ListItem>
)) as ReactNode,
],
// Group list
[
() => filteredAndSortedGroups.length > 0,
() =>
filteredAndSortedGroups.map((group) => (
<ListItem
key={group.id}
secondaryAction={
groupsInLoading.includes(group) ? (
<Box sx={{ display: "flex" }}>
<CircularProgress color="inherit" size={25} />
</Box>
) : (
<>
<IconButton onClick={() => setGroupToEdit(group)}>
<EditIcon />
</IconButton>
<IconButton
edge="end"
onClick={() => setGroupToDelete(group)}
>
<DeleteIcon />
</IconButton>
</>
)
}
disablePadding
>
<ListItemButton onClick={() => setGroupToEdit(group)}>
<ListItemIcon>
<GroupIcon />
</ListItemIcon>
<ListItemText primary={group.name} />
</ListItemButton>
</ListItem>
)),
],
// No group
[
R.T,
() => (
<Typography sx={{ m: 2 }} align="center">
{t("settings.noGroup")}
</Typography>
),
],
])()}
</List>
{groupToDelete && (
<ConfirmationDialog
titleIcon={DeleteIcon}
onCancel={() => setGroupToDelete(undefined)}
onConfirm={handleDeleteGroup}
alert="warning"
open
>
{t("settings.question.deleteGroup", { 0: groupToDelete.name })}
</ConfirmationDialog>
)}
{groupToEdit && (
<UpdateGroupDialog
open
group={groupToEdit}
editGroup={editGroup}
reloadFetchGroups={reloadFetchGroups}
closeDialog={() => setGroupToEdit(undefined)}
/>
)}
</Box>
);
}
export default Groups;
|
//
// The MIT License (MIT)
//
// Copyright (c) 2024 Advanced Micro Devices, Inc.,
// Fatalist Development AB (Avalanche Studio Group),
// and Miguel Petersen.
//
// All Rights Reserved.
//
// 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.
//
using System.Collections.Generic;
using System.Collections.ObjectModel;
using ReactiveUI;
using Studio.Models.Workspace.Objects;
namespace Studio.ViewModels.Workspace.Objects
{
public class ResourceValidationDetailViewModel : ReactiveObject, IValidationDetailViewModel
{
/// <summary>
/// Current selected resource
/// </summary>
public ResourceValidationObject? SelectedResource
{
get => _selectedResource;
set => this.RaiseAndSetIfChanged(ref _selectedResource, value);
}
/// <summary>
/// Is the collection paused?
/// </summary>
public bool Paused
{
get => _paused;
set
{
this.RaiseAndSetIfChanged(ref _paused, value);
PauseChanged();
}
}
/// <summary>
/// All resources
/// </summary>
public ObservableCollection<ResourceValidationObject> Resources { get; } = new();
/// <summary>
/// Find a resource
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ResourceValidationObject? FindResource(uint id)
{
if (_lookup.TryGetValue(id, out ResourceValidationObject? validationObject))
{
return validationObject;
}
// Not found
return null;
}
/// <summary>
/// Invoked on pause state changes
/// </summary>
private void PauseChanged()
{
// Update all objects
foreach (ResourceValidationObject validationObject in Resources)
{
validationObject.Paused = _paused;
}
}
/// <summary>
/// Find or add a resource
/// </summary>
/// <param name="resource"></param>
/// <returns></returns>
public ResourceValidationObject FindOrAddResource(Resource resource)
{
ulong key = resource.Key;
// Existing?
if (_lookup.TryGetValue(key, out ResourceValidationObject? validationObject))
{
// Recommit the resource info if needed
if (validationObject.Resource.IsUnknown && !resource.IsUnknown)
{
validationObject.Resource = resource;
}
return validationObject;
}
// Not found, create it
validationObject = new ResourceValidationObject()
{
Resource = resource,
Paused = _paused
};
// Auto-assign if none
if (Resources.Count == 0)
{
SelectedResource = validationObject;
}
// Add to lookups
_lookup.Add(key, validationObject);
Resources.Insert(0, validationObject);
// Trim
while (Resources.Count > MaxResources)
{
_lookup.Remove(Resources[^1].Resource.Key);
Resources.RemoveAt(Resources.Count - 1);
}
// OK
return validationObject;
}
/// <summary>
/// Max number of resources
/// </summary>
private static int MaxResources = 100;
/// <summary>
/// Lookup table
/// </summary>
private Dictionary<ulong, ResourceValidationObject> _lookup = new();
/// <summary>
/// Internal selection
/// </summary>
private ResourceValidationObject? _selectedResource;
/// <summary>
/// Internal pause state
/// </summary>
private bool _paused;
}
}
|
import React, { useState } from "react";
import { Box, Paper, Card, CardContent, TextField, Typography, Button , CircularProgress} from "@mui/material";
import NavBar from "./NavBar";
import Resume from "./Resume";
import ProfileResume from "./ProfileResume";
import axios from 'axios';
import { responsiveProperty } from "@mui/material/styles/cssUtils";
const Profile = () => {
const [values, setValues] = useState({
// Profile-Information
firstname: "john",
lastname: "Doe",
email: "john.doe@example.com",
phone: "123-456-7890",
website: "https://example.com",
github: "https://github.com/johndoe",
linkedin: "https://www.linkedin.com/in/johndoe",
twitter: "https://twitter.com/johndoe",
facebook: "https://www.facebook.com/johndoe",
instagram: "https://www.instagram.com/johndoe",
// Education Information
college: "University of Example",
fromyear1: "2010",
toyear1: "2014",
qualification1: "Bachelor's Degree",
description1: "Some description",
school: "High School Example",
fromyear2: "2006",
toyear2: "2010",
qualification2: "High School Diploma",
description2: "Some description",
// Project Information...
title1: "Project 1",
link1: "https://project1.example.com",
projectDescription1: "Description of Project 1",
title2: "Project 2",
link2: "https://project2.example.com",
projectDescription2: "Description of Project 2",
title3: "Project 3",
link3: "https://project3.example.com",
projectDescription3: "Description of Project 3",
// Experience Information
institute1: "Company 1",
position1: "Software Engineer",
duration1: "2 years",
experienceDescription1: "Worked on various projects...",
institute2: "Company 2",
position2: "Web Developer",
duration2: "1 year",
experienceDescription2: "Developed web applications...",
// Extra Information
skill1: "JavaScript",
skill2: "React",
skill3: "Node.js",
skill4: "HTML",
skill5: "CSS",
skill6: "Git",
interest1: "Reading",
interest2: "Traveling",
interest3: "Cooking",
interest4: "Music",
interest5: "Photography",
interest6: "Gaming",
});
const handleChange = (field, value) => {
setValues((prevValues) => ({
...prevValues,
[field]: value,
}));
};
const question = "Provide a brief description of my experience working at Google as a software engineer for 3 years for my resume (30 words)";
const [Tech1, setTech1] = useState("");
const [Tech2, setTech2] = useState("");
const [Tech3, setTech3] = useState("");
const [ExperienceDescription2, setExperienceDescription2] = useState("");
const [ExperienceDescription1, setExperienceDescription1] = useState("");
const [ProjectDescription1, setProjectDescription1] = useState("");
const [ProjectDescription2, setProjectDescription2] = useState("");
const [ProjectDescription3, setProjectDescription3] = useState("");
const [loading1, setLoading1] = useState(false);
const [loading2, setLoading2] = useState(false);
const [loading3, setLoading3] = useState(false);
const [loading4, setLoading4] = useState(false);
const [loading5, setLoading5] = useState(false);
const askGPT1 = async (question) => {
setLoading1(true);
try {
const response = await axios.post(' /ask-gpt', { question });
setProjectDescription1(response.data.answer);
console.log(response.data.answer);
} catch (error) {
console.error(error);
}
setTimeout(() => {
setLoading1(false);
}, 2000);
};
const askGPT2 = async (question) => {
setLoading2(true);
try {
const response = await axios.post(' /ask-gpt', { question });
setProjectDescription2(response.data.answer);
console.log(response.data.answer);
} catch (error) {
console.error(error);
}
setTimeout(() => {
setLoading2(false);
}, 2000);
};
const askGPT = async (question) => {
setLoading3(true);
try {
const response = await axios.post(' /ask-gpt', { question });
setProjectDescription3(response.data.answer);
console.log(response.data.answer);
} catch (error) {
console.error(error);
}
setTimeout(() => {
setLoading3(false);
}, 2000);
};
const askGPT3 = async (question) => {
setLoading4(true);
try {
const response = await axios.post(' /ask-gpt', { question });
setExperienceDescription1(response.data.answer);
console.log(response.data.answer);
} catch (error) {
console.error(error);
}
setTimeout(() => {
setLoading4(false);
}, 2000);
};
const askGPT4 = async (question) => {
setLoading5(true);
try {
const response = await axios.post(' /ask-gpt', { question });
setExperienceDescription2(response.data.answer);
console.log(response.data.answer);
} catch (error) {
console.error(error);
}
setTimeout(() => {
setLoading5(false);
}, 2000);
};
return (
<>
<NavBar />
<div style={{
background: 'linear-gradient(180deg, #E7EEFA 50%, #FFFFFF 100%)',
fontFamily: "'Roboto Slab', serif",
}}>
<Card style={{
marginTop: 0,
padding: "10px",
maxWidth: 1000,
// maxHeight:1400,
width: "100%",
marginLeft: -10,
height: 2000, // Set a fixed height for the scrollable area
overflowY: "auto",
// Allow vertical scrolling
}}>
<CardContent>
<Box
display="flex"
justifyContent="center"
alignItems="center"
minHeight="15vh"
>
<Paper
style={{
backgroundColor: '#4C667E',
color: "white",
padding: "10px",
maxWidth: 900,
width: "100%",
marginLeft: 10,
fontSize: 20
}}
>
PERSONAL DETAILS
</Paper>
</Box>
<Card style={{ marginTop: -20, padding: "10px", maxWidth: 900, width: "100%", marginLeft: 30 }}>
<CardContent>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>First Name</Typography>
<TextField
label="First Name"
variant="outlined"
style={{ width: 400 }}
value={values.firstname}
onChange={(e) => handleChange("firstname", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Last Name</Typography>
<TextField
label="Last Name"
variant="outlined"
style={{ width: 400 }}
value={values.lastname}
onChange={(e) => handleChange("lastname", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Email</Typography>
<TextField
label="Email"
variant="outlined"
style={{ width: 400 }}
value={values.email}
onChange={(e) => handleChange("email", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Phone</Typography>
<TextField
label="Phone"
variant="outlined"
style={{ width: 400 }}
value={values.phone}
onChange={(e) => handleChange("phone", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Website</Typography>
<TextField
label="Website"
variant="outlined"
style={{ width: 400 }}
value={values.website}
onChange={(e) => handleChange("website", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>GitHub</Typography>
<TextField
label="GitHub"
variant="outlined"
style={{ width: 400 }}
value={values.github}
onChange={(e) => handleChange("github", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>LinkedIn</Typography>
<TextField
label="LinkedIn"
variant="outlined"
style={{ width: 400 }}
value={values.linkedin}
onChange={(e) => handleChange("linkedin", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Twitter</Typography>
<TextField
label="Twitter"
variant="outlined"
style={{ width: 400 }}
value={values.twitter}
onChange={(e) => handleChange("twitter", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Facebook</Typography>
<TextField
label="Facebook"
variant="outlined"
style={{ width: 400 }}
value={values.facebook}
onChange={(e) => handleChange("facebook", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Instagram</Typography>
<TextField
label="Instagram"
variant="outlined"
style={{ width: 400 }}
value={values.instagram}
onChange={(e) => handleChange("instagram", e.target.value)}
/>
</div>
</div>
</CardContent>
</Card>
<Box
display="flex"
justifyContent="center"
alignItems="center"
minHeight="15vh"
>
<Paper
style={{
backgroundColor: '#4C667E',
color: "white",
padding: "10px",
maxWidth: 900,
width: "100%",
marginLeft: 10,
fontSize: 20
}}
>
EDUCATIONAL DETAILS
</Paper>
</Box>
<Card style={{ marginTop: -20, padding: "10px", maxWidth: 900, width: "100%", marginLeft: 30 }}>
<CardContent>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>College</Typography>
<TextField
label="College"
variant="outlined"
style={{ width: 400 }}
value={values.college}
onChange={(e) => handleChange("college", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>From year</Typography>
<TextField
label="From year1"
variant="outlined"
style={{ width: 400 }}
value={values.fromyear1}
onChange={(e) => handleChange("fromyear1", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>To Year</Typography>
<TextField
label="To year1"
variant="outlined"
style={{ width: 400 }}
value={values.toyear1}
onChange={(e) => handleChange("toyear1", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Qualification</Typography>
<TextField
label="Qualification"
variant="outlined"
style={{ width: 400 }}
value={values.qualification1}
onChange={(e) => handleChange("qualification1", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Description</Typography>
<TextField
label="Description"
variant="outlined"
style={{ width: 400 }}
value={values.description1}
onChange={(e) => handleChange("description1", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>School</Typography>
<TextField
label="School"
variant="outlined"
style={{ width: 400 }}
value={values.school}
onChange={(e) => handleChange("school", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>From Year</Typography>
<TextField
label="From Year"
variant="outlined"
style={{ width: 400 }}
value={values.fromyear2}
onChange={(e) => handleChange("fromyear2", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>To Year</Typography>
<TextField
label="To Year"
variant="outlined"
style={{ width: 400 }}
value={values.toyear2}
onChange={(e) => handleChange("toyear2", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Qualification</Typography>
<TextField
label="Qualification"
variant="outlined"
style={{ width: 400 }}
value={values.qualification2}
onChange={(e) => handleChange("qualification2", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Description</Typography>
<TextField
label="Description"
variant="outlined"
style={{ width: 400 }}
value={values.description2}
onChange={(e) => handleChange("description2", e.target.value)}
/>
</div>
</div>
</CardContent>
</Card>
<Box
display="flex"
justifyContent="center"
alignItems="center"
minHeight="15vh"
>
<Paper
style={{
backgroundColor: '#4C667E',
color: "white",
padding: "10px",
maxWidth: 900,
width: "100%",
marginLeft: 10,
fontSize: 20
}}
>
PROJECTS
</Paper>
</Box>
<Card style={{ marginTop: -20, padding: "10px", maxWidth: 900, width: "100%", marginLeft: 30 }}>
<CardContent>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Title</Typography>
<TextField
label="Title"
variant="outlined"
style={{ width: 400 }}
value={values.title1}
onChange={(e) => handleChange("title1", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Link</Typography>
<TextField
label="Link"
variant="outlined"
style={{ width: 400 }}
value={values.link1}
onChange={(e) => handleChange("link1", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -200 }}>Project Description</Typography>
<TextField
label="Project Description"
variant="outlined"
style={{ width: 400 }}
value={values.projectDescription1}
onChange={(e) => handleChange("projectDescription1", e.target.value)}
/>
</div>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -200 }}>Technologies Used</Typography>
<TextField
label="Technologies used"
variant="outlined"
style={{ width: 400 }}
value={Tech1}
onChange={(e) => setTech1(e.target.value)}
/>
</div>
</div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -30 }}>AI Description</Typography>
<TextField
label="output"
variant="outlined"
style={{ width: 800 }}
multiline
rows={4}
value={ProjectDescription1}
// onChange={(e) => handleChange("experienceDescription2", e.target.value)}
onChange={(e) => setProjectDescription1(e.target.value)}
/>
<Button style={{backgroundColor:'#4C667E' ,marginTop:10,color: 'white' ,marginLeft:-15}} onClick={() => askGPT1(`Can you provide a concise description of my project named ${values.title1} using ${Tech1} for my resume? Highlight key achievements and skills in about 30 words.`)} >
{loading1 ? <CircularProgress size={24} style={{color:'white'}} /> : 'MAGIC'}
</Button>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" ,marginTop:20}}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Title</Typography>
<TextField
label="Title"
variant="outlined"
style={{ width: 400 }}
value={values.title2}
onChange={(e) => handleChange("title2", e.target.value)}
/>
</div>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Link</Typography>
<TextField
label="Link"
variant="outlined"
style={{ width: 400 }}
value={values.link2}
onChange={(e) => handleChange("link2", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -200 }}>Project Description</Typography>
<TextField
label="Project Description"
variant="outlined"
style={{ width: 400 }}
value={values.projectDescription2}
onChange={(e) => handleChange("projectDescription2", e.target.value)}
/>
</div>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -200 }}>Technologies Used</Typography>
<TextField
label="Technologies used"
variant="outlined"
style={{ width: 400 }}
value={Tech2}
onChange={(e) => setTech2(e.target.value)}
/>
</div>
</div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -30 }}>AI Description</Typography>
<TextField
label="output"
variant="outlined"
style={{ width: 800 }}
multiline
rows={4}
value={ProjectDescription2}
// onChange={(e) => handleChange("experienceDescription2", e.target.value)}
onChange={(e) => setProjectDescription2(e.target.value)}
/>
<Button style={{backgroundColor:'#4C667E' ,marginTop:10,color: 'white',marginLeft:-15}} onClick={() => askGPT2(`Can you provide a concise description of my project named ${values.title2} using ${Tech2} for my resume? Highlight key achievements and skills in about 30 words.`)} >
{loading2 ? <CircularProgress size={24} style={{color:'white'}} /> : 'MAGIC'}
</Button>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px",marginTop:20 }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Title</Typography>
<TextField
label="Title"
variant="outlined"
style={{ width: 400 }}
value={values.title3}
onChange={(e) => handleChange("title3", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Link</Typography>
<TextField
label="Link"
variant="outlined"
style={{ width: 400 }}
value={values.link3}
onChange={(e) => handleChange("link3", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -200 }}>Project Description</Typography>
<TextField
label="Project Description"
variant="outlined"
style={{ width: 400 }}
value={values.projectDescription3}
onChange={(e) => handleChange("projectDescription3", e.target.value)}
/>
</div>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -200 }}>Technologies Used</Typography>
<TextField
label="Technologies used"
variant="outlined"
style={{ width: 400 }}
value={Tech3}
onChange={(e) => setTech3(e.target.value)}
/>
</div>
</div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -30 }}>AI Description</Typography>
<TextField
label="output"
variant="outlined"
style={{ width: 800 }}
multiline
rows={4}
value={ProjectDescription3}
// onChange={(e) => handleChange("experienceDescription2", e.target.value)}
onChange={(e) => setProjectDescription3(e.target.value)}
/>
<Button style={{backgroundColor:'#4C667E',marginTop:10,color: 'white',marginLeft:-15}} onClick={() => askGPT(`Can you provide a concise description of my project named ${values.title3} using ${Tech3} for my resume? Highlight key achievements and skills in about 30 words.`)}>
{loading3 ? <CircularProgress size={24} /> : 'MAGIC'}
</Button>
</CardContent>
</Card>
<Box
display="flex"
justifyContent="center"
alignItems="center"
minHeight="15vh"
>
<Paper
style={{
backgroundColor: '#4C667E',
color: "white",
padding: "10px",
maxWidth: 900,
width: "100%",
marginLeft: 10,
fontSize: 20
}}
>
WORK EXPERINCE
</Paper>
</Box>
<Card style={{ marginTop: -20, padding: "10px", maxWidth: 900, width: "100%", marginLeft: 30 }}>
<CardContent>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Company</Typography>
<TextField
label="Company"
variant="outlined"
style={{ width: 400 }}
value={values.institute1}
onChange={(e) => handleChange("institute1", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Position</Typography>
<TextField
label="Position"
variant="outlined"
style={{ width: 400 }}
value={values.position1}
onChange={(e) => handleChange("position1", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Duration</Typography>
<TextField
label="Duration"
variant="outlined"
style={{ width: 400 }}
value={values.duration1}
onChange={(e) => handleChange("duration1", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -200 }}>Experince Description</Typography>
<TextField
label="Experince Description"
variant="outlined"
style={{ width: 400 }}
value={values.experienceDescription1}
onChange={(e) => handleChange("experienceDescription1", e.target.value)}
/>
</div>
</div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -30 }}>AI Description</Typography>
<TextField
label="output"
variant="outlined"
style={{ width: 800 }}
multiline
rows={4}
value={ExperienceDescription1}
// onChange={(e) => handleChange("experienceDescription2", e.target.value)}
onChange={(e) => setExperienceDescription1(e.target.value)}
/>
<Button style={{backgroundColor:'#4C667E' ,marginTop:10,color: 'white',marginLeft:-15}} onClick={() => askGPT3(`Can you provide a concise description of my ${values.duration1} experience as a ${values.position1} at ${values.institute1} for my resume? Highlight key achievements and skills in about 30 words.`)}>
{loading4 ? <CircularProgress size={24} style={{color:'white'}}/> : 'MAGIC'}
</Button>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px",marginTop:20 }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Company</Typography>
<TextField
label="Company"
variant="outlined"
style={{ width: 400 }}
value={values.institute2}
onChange={(e) => handleChange("institute2", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Position</Typography>
<TextField
label="Position"
variant="outlined"
style={{ width: 400 }}
value={values.position2}
onChange={(e) => handleChange("position2", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Duration</Typography>
<TextField
label="Duration"
variant="outlined"
style={{ width: 400 }}
value={values.duration2}
onChange={(e) => handleChange("duration2", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -200 }}>Experience Description</Typography>
<TextField
label="Experince Description"
variant="outlined"
style={{ width: 400 }}
value={values.experienceDescription2}
onChange={(e) => handleChange("experienceDescription2", e.target.value)}
/>
</div>
</div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -30 }}>AI Description</Typography>
<TextField
label="output"
variant="outlined"
style={{ width: 800 }}
multiline
rows={4}
value={ExperienceDescription2}
// onChange={(e) => handleChange("experienceDescription2", e.target.value)}
onChange={(e) => setExperienceDescription2(e.target.value)}
/>
<Button style={{backgroundColor: '#4C667E',marginTop:10,color: 'white',marginLeft:-15}} onClick={() => askGPT4(`Can you provide a concise description of my ${values.duration2} experience as a ${values.position2} at ${values.institute2} for my resume? Highlight key achievements and skills in about 30 words.`)}>
{loading5 ? <CircularProgress size={24} style={{color:'white'}} /> : 'MAGIC'}
</Button>
</CardContent>
</Card>
<Box
display="flex"
justifyContent="center"
alignItems="center"
minHeight="15vh"
>
<Paper
style={{
backgroundColor: '#4C667E',
color: "white",
padding: "10px",
maxWidth: 900,
width: "100%",
marginLeft: 10,
fontSize: 20
}}
>
EXTRA DETAILS
</Paper>
</Box>
<Card style={{ marginTop: -20, padding: "10px", maxWidth: 900, width: "100%", marginLeft: 30 }}>
<CardContent>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Skill1</Typography>
<TextField
label="Skill1"
variant="outlined"
style={{ width: 400 }}
value={values.skill1}
onChange={(e) => handleChange("skill1", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Skill2</Typography>
<TextField
label="Skill2"
variant="outlined"
style={{ width: 400 }}
value={values.skill2}
onChange={(e) => handleChange("skill2", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Skill3</Typography>
<TextField
label="Skill3"
variant="outlined"
style={{ width: 400 }}
value={values.skill3}
onChange={(e) => handleChange("skill3", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Skill4</Typography>
<TextField
label="Skill4"
variant="outlined"
style={{ width: 400 }}
value={values.skill4}
onChange={(e) => handleChange("skill4", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Skill5</Typography>
<TextField
label="Skill5"
variant="outlined"
style={{ width: 400 }}
value={values.skill5}
onChange={(e) => handleChange("skill5", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Skill6</Typography>
<TextField
label="Skill6"
variant="outlined"
style={{ width: 400 }}
value={values.skill6}
onChange={(e) => handleChange("skill6", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Intrest1</Typography>
<TextField
label="Intrest1"
variant="outlined"
style={{ width: 400 }}
value={values.interest1}
onChange={(e) => handleChange("interest1", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Intrest2</Typography>
<TextField
label="Intrest2"
variant="outlined"
style={{ width: 400 }}
value={values.interest2}
onChange={(e) => handleChange("interest2", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Intrest3</Typography>
<TextField
label="Intrest3"
variant="outlined"
style={{ width: 400 }}
value={values.interest3}
onChange={(e) => handleChange("interest3", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Intrest4</Typography>
<TextField
label="Intrest4"
variant="outlined"
style={{ width: 400 }}
value={values.interest4}
onChange={(e) => handleChange("interest4", e.target.value)}
/>
</div>
</div>
<div style={{ display: "flex", flexDirection: "row", marginBottom: "10px" }}>
<div style={{ marginRight: "10px" }}>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Intrest5</Typography>
<TextField
label="Intrest5"
variant="outlined"
style={{ width: 400 }}
value={values.interest5}
onChange={(e) => handleChange("interest5", e.target.value)}
/>
</div>
<div>
<Typography variant="h6" style={{ marginBottom: "10px", marginLeft: -300 }}>Intrest6</Typography>
<TextField
label="Intrest6"
variant="outlined"
style={{ width: 400 }}
value={values.interest6}
onChange={(e) => handleChange("interest6", e.target.value)}
/>
</div>
</div>
</CardContent>
</Card>
</CardContent>
</Card>
{/* <Resume firstName={values.firstname}/> */}
<ProfileResume values={values} />
</div>
</>
);
};
export default Profile;
|
import os, shutil, logging, argparse, subprocess
from pydub_0_25_1.pydub import AudioSegment as audio
from random import choice
from mutagen.easyid3 import EasyID3
from simple_image_download import simple_image_download as simp
#Configures subprocess to not open terminal window
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
#Configuring argparser for command line inputs
parser = argparse.ArgumentParser()
parser.add_argument(
"-log",
"--log",
default="warning",
help=(
"Provide logging level. "
"Example --log debug', default='warning'"),
)
options = parser.parse_args()
levels = {
'critical': logging.CRITICAL,
'error': logging.ERROR,
'warn': logging.WARNING,
'warning': logging.WARNING,
'info': logging.INFO,
'debug': logging.DEBUG
}
level = levels.get(options.log.lower())
if level is None:
raise ValueError(
f"log level given: {options.log}"
f" -- must be one of: {' | '.join(levels.keys())}")
logging.basicConfig(level=level)
logger = logging.getLogger(__name__)
#Getting the user's root directory ('C:', 'D:', etc.) and
#assigning a global folder to contain all the files and data the code needs to run
rootDir = os.getcwd().split('\\')[0]
globalFolder = os.getcwd()#os.path.join(rootDir, "\\YT_Data")
forbiddenChr = ['\\',
'/',
'?',
'<',
'>',
',',
'|',
':',
'*',
'"',]
def TitleStandardization(title, forbiddenChars, simpleImDown_folder=False):
if simpleImDown_folder==True:
forbiddenChars.append(' ')
T = ""
for ind in range(len(title)):
char = title[ind]
if ( ord(char) < 31 ) or ( ord(char) > 126 ) or ( char in forbiddenChars ):
T += "_"
elif ( ind == len(title)-1 ) and ( char in [' ', '.'] ):
T += "_"
else:
T += title[ind]
return T
#Find if 'file' is in the 'path' provided
def find(file, path, ext='webm'):
contains = False
nm = ""
asExt = False
for name in os.listdir(path):
# if (name == file or ".".join(name.split('.')[:-1]) == file) and name.split('.')[-1] == ext:
if ( name == file or ".".join(name.split('.')[:-1]) == file ):
contains = True
nm = name
if name.split('.')[-1] == ext: #If file exists, checks if the extension is the desired one
asExt = True
break
else:
contains = False
nm = name
return contains, nm, asExt
#Convert .webm file to .mp3
def Cvt2Mp3(loc, f_name):
file_name = ".".join(f_name.split('.')[:-1]) if len(f_name.split('.')) > 1 else f_name
file_type = f_name.split('.')[-1]
#
file = os.path.join(loc, file_name)
renamed = TitleStandardization(file_name, forbiddenChr)
rnmFile = os.path.join(loc, renamed)
#
aud_file = audio.from_file("%s"%(file+"."+file_type), format=file_type) #Converting .webm file to .mp3
os.remove((file+"."+file_type))
aud_file.export(rnmFile+".mp3", format="mp3")
#
return rnmFile+".mp3"
#Updates file's metadata
def GetMetadata(file, aud):
path = os.path.abspath(file) #Get file's absolute path (as a string)
pivotFile = os.path.join(globalFolder, "pivotFile.mp3") #Creates a pivotFile to manage copying, deleting and updating the original file
simpleImagesFolder = os.path.join(globalFolder, "simple_images") #Variable to contain the folder path of thumbnails
thumbnailFolder = os.path.join(simpleImagesFolder, TitleStandardization(aud.title, forbiddenChr, simpleImDown_folder=True)) #"~~THE USED LIBRARY AUTOMATICALLY CREATES A FOLDER CALLED 'simple_images'"
#These lines download the thumbnails from google using the title of the video
# response = simp.simple_image_download()
simp().download(TitleStandardization(aud.title, forbiddenChr, simpleImDown_folder=True), 5, progressBar=False)
#Move original file to the temp. one
shutil.move(path, pivotFile)
#Randomly choses one of the 5 thumbails returned from google search engine
# images = [i for g, h, i in os.walk(thumbnailFolder)]
thumbnail = os.path.join(thumbnailFolder, choice(os.listdir(thumbnailFolder)))
#Joins the thumbnail and the video
ffmpegFolder = os.path.join(__file__, os.path.join("ffmpeg", "bin") + "ffmpeg.exe")
# os.system("""ffmpeg -loglevel warning -i "%s" -i "%s" -map_metadata 0 -map 0:0 -map 1:0 -c copy -id3v2_version 3 -metadata:s:v comment="Cover (front)" "%s" """%(pivotFile, thumbnail, path))
# os.system(f"{ffmpegFolder} -loglevel warning -i '{pivotFile}' -i '{thumbnail}' -map_metadata 0 -map 0:0 -map 1:0 -c copy -id3v2_version 3 -metadata:s:v comment='Cover (front)' '{path}'")
subprocess.call(f"""ffmpeg -loglevel warning -i "{pivotFile}" -i "{thumbnail}" -map_metadata 0 -map 0:0 -map 1:0 -c copy -id3v2_version 3 -metadata:s:v comment="Cover (front)" "{path}" """, startupinfo=si, shell=True)
#Provides metadata properties to the file
audio = EasyID3(path)
audio['artist'] = aud.author
audio['performer'] = aud.author
audio['composer'] = aud.author
audio['title'] = aud.title
audio['date'] = aud.published.split('-')[0]
audio['originaldate'] = aud.published.split('-')[0]
audio.save()
# Cleans directories and removes unnecessary files
for f in os.listdir(thumbnailFolder):
if file.lower() != "thumbnail.jpg":
os.remove((os.path.join(thumbnailFolder, f)))
subprocess.call("""rmdir "%s" """%thumbnailFolder, startupinfo=si, shell=True)
subprocess.call("""rmdir "%s" """%simpleImagesFolder, startupinfo=si, shell=True)
os.remove(pivotFile)
def getAllPlaylistItems(response, youtube, playlist_id):
#Inspiration from 'https://gist.github.com/nkpro2000sr/e6aa5429319d5143f19b6cc29567be0b'
nextPageToken = response.get('nextPageToken')
IDs = list()
while ( 'nextPageToken' in response ):
nextPage = youtube.playlistItems().list(
part = "snippet",
playlistId = playlist_id,
maxResults = 50,
pageToken=nextPageToken
).execute()
#
response['items'] = response['items'] + nextPage['items']
#
if 'nextPageToken' not in nextPage:
response.pop('nextPageToken', None)
else:
nextPageToken = nextPage['nextPageToken']
#
for item in response['items']:
IDs.append(item['snippet']['resourceId']['videoId'])
#
return IDs
|
import clsx from 'clsx';
import * as React from 'react';
import { RegisterOptions, useFormContext } from 'react-hook-form';
import Typography, {
TypographyColor,
} from '@/components/typography/Typography';
import clsxm from '@/lib/clsxm';
enum CheckboxSize {
'sm',
'base',
}
export type CheckboxProps = {
label: string;
name: string;
value?: string | number;
helperText?: string;
readOnly?: boolean;
hideError?: boolean;
validation?: RegisterOptions;
size?: keyof typeof CheckboxSize;
color?: keyof typeof TypographyColor;
} & Omit<React.ComponentPropsWithoutRef<'input'>, 'size'>;
export default function Checkbox({
label,
name,
value,
placeholder = '',
helperText,
readOnly = false,
hideError = false,
validation,
size = 'base',
color = 'primary',
...rest
}: CheckboxProps) {
const {
register,
formState: { errors },
} = useFormContext();
const error = errors[name];
return (
<div>
<div className='flex items-start gap-2'>
<input
{...register(name, validation)}
{...rest}
type='checkbox'
name={name}
id={`${name}_${value}`}
value={value}
disabled={readOnly}
className={clsxm(
// add top margin so the checkbox align with the text
'mt-[0.25em]',
'shrink-0',
'border-white rounded-sm border-2 focus:ring-0',
'checked:bg-blue-400 checked:hover:bg-blue-600 checked:focus:bg-blue-400 checked:active:bg-blue-700',
readOnly &&
'cursor-not-allowed bg-gray-100 disabled:checked:bg-blue-300',
error && 'border-red-400 bg-red-100',
size === 'sm' && 'h-3.5 w-3.5',
)}
placeholder={placeholder}
aria-describedby={name}
/>
<Typography
color={color}
className={clsx(readOnly && 'cursor-not-allowed')}
as='label'
htmlFor={`${name}_${value}`}
variant={clsx({ b2: size === 'base', b3: size === 'sm' })}
>
{label}
</Typography>
</div>
<div className='mt-1'>
{!(!hideError && error) && helperText && <p>{helperText}</p>}
{!hideError && error && (
<Typography variant='body'>{error?.message}</Typography>
)}
</div>
</div>
);
}
|
# models.py - is created for table database model
# every model represents a table in database
from sqlalchemy import (
TIMESTAMP,
Boolean,
Column,
Integer,
String,
text,
ForeignKey,
)
from .database import Base
from sqlalchemy.orm import relationship
class Post(Base):
__tablename__ = "posts" # tablename in database(PostgreSQL)
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, nullable=False)
content = Column(String, nullable=False)
# server_default == constrain in SQL
published = Column(Boolean, server_default="TRUE", nullable=False)
created_at = Column(
TIMESTAMP(timezone=True),
nullable=False,
server_default=text("now()"),
)
# create ID for foreign key
owner_id = Column(
Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
)
# Relationship between users and posts
owner = relationship("User")
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, nullable=False)
email = Column(String(255), nullable=False, unique=True)
password = Column(String(255), nullable=False)
created_at = Column(
TIMESTAMP(timezone=True),
nullable=False,
server_default=text("now()"),
)
phone_number = Column(String)
class Vote(Base):
__tablename__ = "votes"
user_id = Column(
Integer,
ForeignKey("users.id", ondelete="CASCADE"),
primary_key=True,
)
post_id = Column(
Integer,
ForeignKey("posts.id", ondelete="CASCADE"),
primary_key=True,
)
|
import { PersonAddOutlined, PersonRemoveOutlined } from "@mui/icons-material";
import { Box, IconButton, Typography, useTheme } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { setFriends } from "../state";
import FlexBetween from "./FlexBetween";
import UserImage from "./UserImage";
const Friend = ({ friendId, name, subtitle, userPicturePath }) => {
const dispatch = useDispatch();
const navigate = useNavigate();
const { _id } = useSelector((state) => state.user);
const token = useSelector((state) => state.token);
const friends = useSelector((state) => state.user.friends);
const { palette } = useTheme();
const primaryLight = palette.primary.light;
const primaryDark = palette.primary.dark;
const main = palette.neutral.main;
const medium = palette.neutral.medium;
const isFriend = friends.find((friend) => friend._id === friendId);
const patchFriend = async () => {
const response = await fetch(
`http://localhost:3001/users/${_id}/${friendId}`,
{
method: "PATCH",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
);
const data = await response.json();
dispatch(setFriends({ friends: data }));
};
return (
<FlexBetween>
<FlexBetween gap="1rem">
<UserImage image={userPicturePath} size="55px" />
<Box
onClick={() => {
navigate(`/profile/${friendId}`);
navigate(0);
}}
>
<Typography
color={main}
variant="h5"
fontWeight="500"
sx={{
"&:hover": {
color: palette.primary.light,
cursor: "pointer",
},
}}
>
{name}
</Typography>
<Typography color={medium} fontSize="0.75rem">
{subtitle}
</Typography>
</Box>
</FlexBetween>
<IconButton
onClick={() => patchFriend()}
sx={{ backgroundColor: primaryLight, p: "0.6rem" }}
>
{isFriend ? (
<PersonRemoveOutlined sx={{ color: primaryDark }} />
) : (
<PersonAddOutlined sx={{ color: primaryDark }} />
)}
</IconButton>
</FlexBetween>
);
};
export default Friend;
|
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsUUID } from 'class-validator';
export class HorseNameAliasDto {
@ApiProperty({ example: 'Derbi king' })
@IsNotEmpty()
horseName: string;
@ApiProperty()
@IsNotEmpty()
@IsUUID()
horseId: string;
createdBy?: number | null;
isDefault?: boolean | false;
isActive?: boolean | false;
}
|
import { useStateProvider } from "../context/StateContext";
import { reducerCases } from "../context/constants";
import {
HOST,
IMAGES_URL,
SET_USER_IMAGE,
SET_USER_INFO,
} from "../utils/constants";
import axios from "axios";
import Image from "next/image";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
function Profile() {
const router = useRouter();
const [{ userInfo }, dispatch] = useStateProvider();
const [isLoaded, setIsLoaded] = useState(false);
const [imageHover, setImageHover] = useState(false);
const [image, setImage] = useState(undefined);
const [errorMessage, setErrorMessage] = useState("");
const [data, setData] = useState({
userName: "",
fullName: "",
description: "",
});
useEffect(() => {
const handleData = { ...data };
if (userInfo) {
if (userInfo?.username) handleData.userName = userInfo?.username;
if (userInfo?.description) handleData.description = userInfo?.description;
if (userInfo?.fullName) handleData.fullName = userInfo?.fullName;
console.log({ userInfo });
if (userInfo?.imageName) {
const fileName = image;
fetch(userInfo.imageName).then(async (response) => {
const contentType = response.headers.get("content-type");
const blob = await response.blob();
// @ts-ignore
const files = new File([blob], fileName, { contentType });
// @ts-ignore
setImage(files);
});
}
setData(handleData);
setIsLoaded(true);
}
}, [userInfo]);
const handleFile = (e) => {
let file = e.target.files;
const fileType = file[0]["type"];
const validImageTypes = ["image/gif", "image/jpeg", "image/png"];
if (validImageTypes.includes(fileType)) {
setImage(file[0]);
}
};
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
const setProfile = async () => {
try {
const response = await axios.post(
SET_USER_INFO,
{ ...data },
{ withCredentials: true }
);
if (response.data.userNameError) {
setErrorMessage("Enter a Unique Username");
} else {
let imageName = "";
if (image) {
const formData = new FormData();
formData.append("images", image);
const {
data: { img },
} = await axios.post(SET_USER_IMAGE, formData, {
withCredentials: true,
headers: {
"Content-Type": "multipart/form-data",
},
});
imageName = img;
}
dispatch({
type: reducerCases.SET_USER,
userInfo: {
...userInfo,
...data,
image: imageName.length ? HOST + "/" + imageName : false,
},
});
router.push("/");
}
} catch (err) {
console.error(err);
}
};
const inputClassName =
"block p-4 w-full text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-blue-500 focus:border-blue-500";
const labelClassName =
"mb-2 text-lg font-medium text-gray-900 dark:text-white";
return (
<>
{isLoaded && (
<div className="flex flex-col items-center justify-start min-h-[80vh] gap-3">
{errorMessage && (
<div>
<span className="text-red-600 font-bold">{errorMessage}</span>
</div>
)}
<h2 className="text-3xl">Welocme to Fiverr Clone</h2>
<h4 className="text-xl">
Please complete your profile to get started
</h4>
<div className="flex flex-col items-center w-full gap-5">
<div
className="flex flex-col items-center cursor-pointer"
onMouseEnter={() => setImageHover(true)}
onMouseLeave={() => setImageHover(false)}
>
<label className={labelClassName} htmlFor="">
Select a profile Picture
</label>
<div className="bg-purple-500 h-36 w-36 flex items-center justify-center rounded-full relative">
{image ? (
<Image
src={URL.createObjectURL(image)}
alt="profile"
fill
className="rounded-full"
/>
) : (
<span className="text-6xl text-white">
{userInfo.email[0].toUpperCase()}
</span>
)}
<div
className={`absolute bg-slate-400 h-full w-full rounded-full flex items-center justify-center transition-all duration-100 ${
imageHover ? "opacity-100" : "opacity-0"
}`}
>
<span
className={` flex items-center justify-center relative`}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="w-12 h-12 text-white absolute"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z"
clipRule="evenodd"
/>
</svg>
<input
type="file"
onChange={handleFile}
className="opacity-0"
multiple={true}
name="profileImage"
/>
</span>
</div>
</div>
</div>
<div className="flex gap-4 w-[500px]">
<div>
<label className={labelClassName} htmlFor="userName">
Please select a username
</label>
<input
className={inputClassName}
type="text"
name="userName"
id="userName"
placeholder="Username"
value={data.userName}
onChange={handleChange}
/>
</div>
<div>
<label className={labelClassName} htmlFor="fullName">
Please enter your full Name
</label>
<input
className={inputClassName}
type="text"
name="fullName"
id="fullName"
placeholder="Full Name"
value={data.fullName}
onChange={handleChange}
/>
</div>
</div>
<div className="flex flex-col w-[500px]">
<label className={labelClassName} htmlFor="description">
Description
</label>
<textarea
name="description"
id="description"
value={data.description}
onChange={handleChange}
className={inputClassName}
placeholder="description"
></textarea>
</div>
<button
className="border text-lg font-semibold px-5 py-3 border-[#1DBF73] bg-[#1DBF73] text-white rounded-md"
type="button"
onClick={setProfile}
>
Set Profile
</button>
</div>
</div>
)}
</>
);
}
export default Profile;
|
import React from 'react';
import {
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalBody,
ModalCloseButton,
Text,
} from '@chakra-ui/react';
import { PropTypes } from 'prop-types';
const TermsConditionModal = ({ onClose, isOpen }) => {
return (
<Modal isOpen={isOpen} onClose={onClose} size={{ base: 'xs', md: 'xl' }}>
<ModalOverlay />
<ModalContent>
<ModalHeader>Terms & Conditions</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Text>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum
</Text>
</ModalBody>
</ModalContent>
</Modal>
);
};
TermsConditionModal.propTypes = {
onClose: PropTypes.func,
isOpen: PropTypes.bool,
};
TermsConditionModal.defaultProps = {
isOpen: false,
onClose: () => {},
};
export default TermsConditionModal;
|
import { join, resolve } from 'node:path';
import { build, gotoPage } from '@e2e/helper';
import { expect, test } from '@playwright/test';
import { pluginReact } from '@rsbuild/plugin-react';
const fixtures = resolve(__dirname, '../');
test('externals', async ({ page }) => {
const rsbuild = await build({
cwd: fixtures,
runServer: true,
plugins: [pluginReact()],
rsbuildConfig: {
output: {
externals: {
'./aaa': 'aa',
},
},
source: {
preEntry: './src/ex.js',
},
},
});
await gotoPage(page, rsbuild);
const test = page.locator('#test');
await expect(test).toHaveText('Hello Rsbuild!');
const testExternal = page.locator('#test-external');
await expect(testExternal).toHaveText('1');
const externalVar = await page.evaluate('window.aa');
expect(externalVar).toBeDefined();
rsbuild.clean();
await rsbuild.close();
});
test('should not external dependencies when target is web worker', async () => {
const rsbuild = await build({
cwd: fixtures,
plugins: [pluginReact()],
rsbuildConfig: {
output: {
targets: ['web-worker'],
externals: {
react: 'MyReact',
},
},
},
});
const files = await rsbuild.unwrapOutputJSON();
const content =
files[Object.keys(files).find((file) => file.endsWith('.js'))!];
expect(content.includes('MyReact')).toBeFalsy();
rsbuild.clean();
});
|
package com.amadeus.controller;
import com.amadeus.dto.request.CreateFlightRequestDto;
import com.amadeus.dto.request.DeleteFlightRequestDto;
import com.amadeus.dto.request.FlightSearchRequestDto;
import com.amadeus.dto.request.UpdateFlightRequestDto;
import com.amadeus.dto.response.FlightResponseDto;
import com.amadeus.dto.response.ResponseDto;
import com.amadeus.exception.ErrorMessage;
import com.amadeus.repository.entity.Flights;
import com.amadeus.service.FlightService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Size;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static com.amadeus.constants.FlightsConstant.*;
@RestController
@RequestMapping(value = FLIGHTS, produces = {MediaType.APPLICATION_JSON_VALUE})
@RequiredArgsConstructor
@Validated
public class FlightController {
private final FlightService flightService;
@Operation(
summary = "Create new flight REST API",
description = "REST API to create flight inside Amadeus Flight Search"
)
@ApiResponses({
@ApiResponse(
responseCode = "201",
description = "HTTP Status CREATED"
),
@ApiResponse(
responseCode = "1222",
description = "Given airports name cannot find. Check names",
content = @Content(
schema = @Schema(implementation = ErrorMessage.class)
)
)
}
)
@PostMapping(CREATE)
public ResponseEntity<ResponseDto> createFlight(@RequestBody @Valid CreateFlightRequestDto dto) {
flightService.createFlight(dto);
return ResponseEntity.status(HttpStatus.CREATED).body(new ResponseDto(STATUS_201, MESSAGE_201));
}
@Operation(
summary = "Fetch Flight Details REST API",
description = "REST API to fetch flight based on a String id"
)
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "HTTP Status OK"
),
@ApiResponse(
responseCode = "1133",
description = "Airport could not find with giving id",
content = @Content(
schema = @Schema(implementation = ErrorMessage.class)
)
)
}
)
@GetMapping(FETCH)
public ResponseEntity<FlightResponseDto> fetchById(@RequestParam @Size(min = 24, max = 24, message = "ID must be 24 characters, not less or not more.") String id) {
FlightResponseDto flightResponseDto = flightService.fetchById(id);
return ResponseEntity.status(HttpStatus.OK).body(flightResponseDto);
}
@Operation(
summary = "Fetch all Flights Details REST API",
description = "REST API to All fetch Flights"
)
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "HTTP Status OK"
)
}
)
@GetMapping(FETCH_ALL)
public ResponseEntity<List<Flights>> fetchAllFlights() {
return ResponseEntity.status(HttpStatus.OK).body(flightService.findAll());
}
@Operation(
summary = "Delete Flight REST API",
description = "REST API to delete Flight based on String id"
)
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "HTTP Status OK"
),
@ApiResponse(
responseCode = "1233",
description = "Flight could not find with giving string id",
content = @Content(
schema = @Schema(implementation = ErrorMessage.class)
)
)
}
)
@DeleteMapping(DELETE)
public ResponseEntity<ResponseDto> deleteFlight(@RequestBody @Valid DeleteFlightRequestDto dto) {
flightService.deleteFlight(dto);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseDto(STATUS_200, MESSAGE_200));
}
@Operation(
summary = "Update Flight Details REST API",
description = "REST API to update Flight details based on string id"
)
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "HTTP Status OK"
),
@ApiResponse(
responseCode = "1233",
description = "Flight could not find with giving string id",
content = @Content(
schema = @Schema(implementation = ErrorMessage.class)
)
)
}
)
@PutMapping(UPDATE)
public ResponseEntity<ResponseDto> updateFlight(@RequestBody @Valid UpdateFlightRequestDto dto) {
boolean isUpdated = flightService.updateFlight(dto);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseDto(STATUS_200, MESSAGE_200));
}
@Operation(
summary = "Search flights in all of saved flights REST API",
description = "REST API to Search Flight details based on given details"
)
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "HTTP Status OK"
),
@ApiResponse(
responseCode = "4211",
description = "Parameter error",
content = @Content(
schema = @Schema(implementation = ErrorMessage.class)
)
)
}
)
@PostMapping(SEARCH_FLIGHT)
public ResponseEntity<List<FlightResponseDto>> searchFlight(@RequestBody @Valid FlightSearchRequestDto dto) {
return ResponseEntity.status(HttpStatus.OK).body(flightService.searchFlight(dto));
}
}
|
// nanorange/algorithm/all_of.hpp
//
// Copyright (c) 2018 Tristan Brindle (tcbrindle at gmail dot com)
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef NANORANGE_ALGORITHM_ALL_OF_HPP_INCLUDED
#define NANORANGE_ALGORITHM_ALL_OF_HPP_INCLUDED
#include <nanorange/ranges.hpp>
NANO_BEGIN_NAMESPACE
// [range.alg.all_of]
namespace detail {
struct all_of_fn {
private:
template <typename I, typename S, typename Proj, typename Pred>
static constexpr bool impl(I first, S last, Pred& pred, Proj& proj)
{
while (first != last) {
if (!nano::invoke(pred, nano::invoke(proj, *first))) {
return false;
}
++first;
}
return true;
}
public:
template <typename I, typename S, typename Proj = identity, typename Pred>
constexpr std::enable_if_t<
input_iterator<I> && sentinel_for<S, I> &&
indirect_unary_predicate<Pred, projected<I, Proj>>,
bool>
operator()(I first, S last, Pred pred, Proj proj = Proj{}) const
{
return all_of_fn::impl(std::move(first), std::move(last),
pred, proj);
}
template <typename Rng, typename Proj = identity, typename Pred>
constexpr std::enable_if_t<
input_range<Rng> &&
indirect_unary_predicate<Pred, projected<iterator_t<Rng>, Proj>>,
bool>
operator()(Rng&& rng, Pred pred, Proj proj = Proj{}) const
{
return all_of_fn::impl(nano::begin(rng), nano::end(rng),
pred, proj);
}
};
} // namespace detail
NANO_INLINE_VAR(detail::all_of_fn, all_of)
NANO_END_NAMESPACE
#endif
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Project</title>
<!-- main css file -->
<link rel="stylesheet" href="css/main.css">
<!-- normalize css file -->
<link rel="stylesheet" href="css/normalize.css">
<!-- google fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Work+Sans:wght@200;300;400;600;800&display=swap" rel="stylesheet">
<!-- font awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<!-- header -->
<div class="header">
<div class="container">
<img class="logo" src="images/logo.png" alt="logo">
<div class="links">
<span class="icon">
<span></span>
<span></span>
<span></span>
</span>
<ul>
<li><a href="#services">Services</a></li>
<li><a href="#portfolio">Portfolio</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</div>
</div>
<!-- ----------------------------------------------------------------------------->
<!-- landing -->
<section class="landing">
<div class="intro-text">
<h1>Hello There</h1>
<p>We are Leon - Super Creative & Minimal Agency Web Template</p>
</div>
</section>
<!-- ----------------------------------------------------------------------------->
<!-- features -->
<section class="features">
<div class="container">
<div class="feat">
<i class="fab fa-free-code-camp fa-3x"></i>
<h3>Tell Us Your Idea</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore, minus eius! Eligendi autem molestias aspernatur!</p>
</div>
<div class="feat">
<i class="far fa-gem fa-3x"></i>
<h3>We Will Do All The Work</h3>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dolores, possimus. Numquam ipsum harum aperiam optio!</p>
</div>
<div class="feat">
<i class="fas fa-globe-europe fa-3x"></i>
<h3>Your Product Is Worldwide</h3>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dolores, possimus. Numquam ipsum harum aperiam optio!</p>
</div>
</div>
</section>
<!-- ----------------------------------------------------------------------------->
<!-- services -->
<section class="services" id="services">
<h2 class="special-heading">Services</h2>
<p>Don't be busy,be productive</p>
<div class="services-content">
<!-- first column -->
<div class="services-content-col">
<!-- services graphic design -->
<div class="services-col">
<i class="fas fa-print fa-2x"></i>
<div class="ser-col ser-graphic-design">
<h3>Graphic Design</h3>
<p>Graphic design is the process of visual communication and problem-solving using one or more of typography, photography and illustration.</p>
</div>
</div>
<!-- services UI & UX -->
<div class="services-col">
<i class="far fa-comment-alt fa-2x"></i>
<div class="ser-col ser-UI">
<h3>UI & UX</h3>
<p>Process of enhancing user satisfaction with a product by improving the usability, accessibility, and pleasure provided in the interaction.</p>
</div>
</div>
</div>
<!-- second column -->
<div class="services-content-col">
<!-- web design -->
<div class="services-col">
<i class="fas fa-palette fa-2x"></i>
<div class="ser-col ser-web-design">
<h3>Web Design</h3>
<p>Web design encompasses many different skills and disciplines in the production and maintenance of websites</p>
</div>
</div>
<!-- web Development -->
<div class="services-col">
<i class="fas fa-desktop fa-2x"></i>
<div class="ser-col ser-web-design">
<h3>Web Development</h3>
<p>Web development is a broad term for the work involved in developing a web site for the Internet or an intranet. </p>
</div>
</div>
</div>
<!-- third column -->
<div class="services-content-col">
<div class="services-col">
<div class="ser-col image">
<img src="images/pexels-photo-3022417.jpeg" alt="">
</div>
</div>
</div>
</div>
</section>
<!-- ----------------------------------------------------------------------------->
<!-- portfolio -->
<section class="portfolio" id="portfolio">
<div class="container">
<h2 class="special-heading">Portfolio</h2>
<p>If you do it right, it will last forever.</p>
<div class="portfolio-section">
<div class="protfolio-col">
<img src="images/portfolio-1.jpg" alt="">
<div class="card">
<h3>Project Here</h3>
<p>My creative ability is very difficult to measure because it can manifest in so many surprising and.</p>
</div>
</div>
<div class="protfolio-col">
<img src="images/portfolio-2.jpg" alt="">
<div class="card">
<h3>Project Here</h3>
<p>My creative ability is very difficult to measure because it can manifest in so many surprising and.</p>
</div>
</div>
<div class="protfolio-col">
<img src="images/portfolio-3.jpg" alt="">
<div class="card">
<h3>Project Here</h3>
<p>My creative ability is very difficult to measure because it can manifest in so many surprising and.</p>
</div>
</div>
</div>
</div>
</section>
<!-- ----------------------------------------------------------------------------->
<!-- about -->
<section class="about" id="about">
<div class="about-container">
<h2 class="special-heading">About</h2>
<p>Less is more work</p>
<div class="about-content">
<div class="image">
<img src="images/about.jpg" alt="">
</div>
<div class="about-text">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil nemo neque voluptate tempora velit cum non, fuga vitae architecto delectus sed maxime rerum impedit aliquam obcaecati, aut excepturi iusto laudantium! </p>
<hr>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quibusdam placeat quia, enim voluptate rerum debitis cum quasi, labore quae consectetur recusandae hic quas sed quod. Corrupti fuga explicabo velit perferendis.</p>
</div>
</div>
</div>
</section>
<!-- ----------------------------------------------------------------------------->
<!-- contact -->
<section class="contact" id="contact">
<div class="container">
<h2 class="special-heading">Contact</h2>
<p>We are born to create</p>
<div class="contact-1">
<p>Feel free to drop us a line at:</p>
<a href="">leonagency@mail.com</a>
<div class="social">
<span>Find Us On Social Networks</span>
<i class="fab fa-youtube"></i>
<i class="fab fa-facebook-f"></i>
<i class="fab fa-twitter"></i>
</div>
</div>
</div>
</section>
<!-- ----------------------------------------------------------------------------->
<div class="footer">
<div class="container">
<p>© 2021 <span>Leon</span> All Right Reserved</p>
</div>
</div>
</html>
|
#ifndef TYPES_H
#define TYPES_H
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <cstdint>
#include <format>
#include <string>
#include <iostream>
#define NSPEEDS 9
#define NUM_THREADS 28
typedef struct
{
int nx; /* no. of cells in x-direction */
int ny; /* no. of cells in y-direction */
int maxIters; /* no. of iterations */
float density; /* density per cell */
float viscosity; /* kinematic viscosity of fluid */
float velocity; /* inlet velocity */
int type; /* inlet type */
float omega; /* relaxation parameter */
} t_param;
/* struct to hold the distribution of different speeds */
typedef struct
{
float speeds[NSPEEDS];
} t_speed;
class speed_identifier {
private:
std::uint32_t _data;
public:
speed_identifier() : _data{0} {}
speed_identifier(const speed_identifier&) = default;
speed_identifier(const float& v) : _data{reinterpret_cast<const std::uint32_t&>(v)} {}
speed_identifier(const std::uint32_t v) : _data{v} {}
operator float() const { return reinterpret_cast<const float&>(_data); }
operator std::uint32_t() const { return _data; }
void set_speed(unsigned int speed) {
speed &= 0x0000000fU;
_data &= 0xfffffff0U;
_data |= speed;
}
unsigned int get_speed() const {
return _data & 0x0000000fU;
}
void set_x(unsigned int x) {
x &= 0x00003fffU;
_data &= 0xfffc000fU;
_data |= x << 4;
}
unsigned int get_x() const {
return (_data & 0x0003fff0U) >> 4;
}
void set_y(unsigned int y) {
y &= 0x00003fffU;
_data &= 0x0003ffff;
_data |= y << 18;
}
unsigned int get_y() const {
return _data >> 18;
}
operator std::string() const {
return std::format("from speed:{}, x:{}, y:{}", get_speed(), get_x(), get_y());
}
};
#endif
|
package com.example.controller;
import cn.hutool.core.collection.CollUtil;
import com.common.Result;
import com.example.controller.request.CategoryPageRequest;
import com.example.entity.Category;
import com.example.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@CrossOrigin
@RequestMapping("/category") // 关系到views中前端网页的地址
@RestController
public class CategoryController {
@Autowired
ICategoryService categoryService;
@PostMapping("/save")
public Result save(@RequestBody Category obj){
categoryService.save(obj);
return Result.success();
}
@PutMapping("/update")
public Result update(@RequestBody Category obj){
categoryService.update(obj);
return Result.success();
}
@DeleteMapping("/delete/{id}")
public Result delete(@PathVariable Integer id){
categoryService.deleteById(id); //操纵数据库
return Result.success();
}
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id){
Category obj = categoryService.getById(id);
return Result.success(obj);
}
@GetMapping("/list")
public Result list(){
List<Category> list = categoryService.list();
return Result.success(list);
}
@GetMapping("/tree")
public Result tree(){
List<Category> list = categoryService.list();
// List<Category> treelist = list.stream().filter(v -> v.getPid() == null).collect(Collectors.toList()); //第一层
return Result.success(createTree(null,list));
}
private List<Category> createTree(Integer pid, List<Category> categories) { //遍历
List<Category> treeList = new ArrayList<>();
for (Category category : categories) {
if(pid==null){
if(category.getPid()==null){
treeList.add(category);
category.setChildren(createTree(category.getId(),categories));
}
}else{
if (pid.equals( category.getPid())) { //如果相等传到treeList中
treeList.add(category);
category.setChildren(createTree(category.getId(), categories));
}
}
if(CollUtil.isEmpty(category.getChildren())){
category.setChildren(null);
}
}
return treeList;
}
@GetMapping("/page")
public Result page(CategoryPageRequest categoryPageRequest){
return Result.success(categoryService.page(categoryPageRequest));
}
}
|
# 大模型(LLMs)参数高效微调(PEFT) 面
- 微调方法是啥?如何微调?
<aside>
💡
微调(Fine-tuning)是一种迁移学习的技术,用于在一个已经预训练好的模型基础上,通过进一步训练来适应特定的任务或数据集。微调可以在具有相似特征的任务之间共享知识,从而加快训练速度并提高模型性能。
以下是一般的微调步骤:
1. 选择预训练模型:选择一个在大规模数据集上预训练好的模型,如ImageNet上的预训练的卷积神经网络(如ResNet、VGG等)。这些模型通常具有良好的特征提取能力。
2. 冻结底层权重:将预训练模型的底层权重(通常是卷积层)固定住,不进行训练。这是因为底层权重通常学习到了通用的特征,可以被用于许多不同的任务。
3. 替换顶层分类器:将预训练模型的顶层分类器(通常是全连接层)替换为适合特定任务的新的分类器。新的分类器的输出节点数量应该与任务的类别数相匹配。
4. 解冻部分权重(可选):根据任务的复杂性和可用的训练数据量,可以选择解冻一些底层权重,以便更好地适应新的任务。这样可以允许底层权重进行微小的调整,以更好地适应新任务的特征。
5. 进行训练:使用特定任务的训练数据集对新的分类器进行训练。可以使用较小的学习率进行训练,以避免对预训练模型的权重进行过大的更新。
6. 评估和调整:在训练完成后,使用验证集或测试集评估模型的性能。根据评估结果,可以进行调整,如调整学习率、调整模型结构等。
微调的关键是在预训练模型的基础上进行训练,从而将模型的知识迁移到特定任务上。通过这种方式,可以在较少的数据和计算资源下,快速构建和训练高性能的模型。
</aside>
- 为什么需要 PEFT?
<aside>
💡
PEFT(Performance Estimation and Modeling for Fine-Tuning)是一种用于微调任务的性能估计和建模方法。它的主要目的是帮助研究人员和从业者在微调过程中更好地理解和预测模型的性能,并进行更有效的模型选择和调优。
以下是一些需要使用PEFT的情况:
1. 模型选择:在微调之前,通常需要选择一个合适的预训练模型。PEFT可以帮助评估和比较不同预训练模型在特定任务上的性能,从而选择最适合的模型。
2. 超参数调优:微调过程中可能涉及到一些超参数的选择,如学习率、批量大小等。PEFT可以帮助预估不同超参数设置下模型的性能,并指导超参数的调优。
3. 计算资源规划:微调通常需要大量的计算资源,如显存、GPU时间等。PEFT可以帮助估计不同模型和数据集规模下的计算资源需求,以便更好地规划和分配资源。
4. 模型压缩和加速:在一些场景下,需要将模型压缩或加速,以便在资源受限的设备上进行推理。PEFT可以帮助评估不同压缩和加速技术对模型性能的影响,并指导模型优化的方向。
PEFT通过模型的性能估计和建模,可以提供更准确的预测和指导,帮助研究人员和从业者更好地进行微调任务的设计和优化。
</aside>
- 介绍一下 PEFT?
<aside>
💡
PEFT(Performance Estimation and Modeling for Fine-Tuning)是一种用于微调任务的性能估计和建模方法。它的目的是帮助研究人员和从业者在微调过程中更好地理解和预测模型的性能,并进行更有效的模型选择和调优。
PEFT的主要思想是通过预测模型在微调任务上的性能,提供对不同模型和参数设置的性能估计。这样可以避免在大规模数据集上进行昂贵的微调实验,从而节省时间和计算资源。
PEFT的关键步骤包括:
1. 数据采样:从原始数据集中采样一小部分数据用于性能估计。这样可以减少计算开销,同时保持采样数据与原始数据集的分布一致性。
2. 特征提取:使用预训练模型提取采样数据的特征表示。这些特征通常具有很好的表达能力,可以用于性能估计。
3. 性能估计模型:基于采样数据的特征表示,建立一个性能估计模型。这个模型可以是简单的线性回归模型,也可以是更复杂的神经网络模型。
4. 性能预测:使用性能估计模型对未知数据的性能进行预测。通过输入微调任务的特征表示,模型可以输出预测的性能指标,如准确率、F1分数等。
通过PEFT,研究人员和从业者可以在微调之前,通过预测模型的性能,选择最佳的预训练模型、超参数设置和资源规划策略。这样可以加速模型的开发和优化过程,提高微调任务的效率和性能。
</aside>
- PEFT 有什么优点?
<aside>
💡
PEFT具有以下几个优点:
1. 节省时间和计算资源:传统的微调方法需要在大规模数据集上进行昂贵的实验,耗费大量时间和计算资源。而PEFT通过性能估计和建模,可以避免这些实验,节省时间和计算开销。
2. 提供准确的性能预测:PEFT通过建立性能估计模型,可以对未知数据的性能进行预测。这样可以提供准确的性能指标,帮助研究人员和从业者更好地理解模型的性能。
3. 辅助模型选择和调优:PEFT可以帮助选择最佳的预训练模型、超参数设置和资源规划策略。通过预测模型的性能,可以指导模型选择和调优的方向,提高微调任务的效率和性能。
4. 可解释性和可扩展性:PEFT的性能估计模型可以是简单的线性回归模型,也可以是更复杂的神经网络模型。这使得PEFT具有很好的可解释性和可扩展性,可以适应不同的微调任务和数据集。
5. 适用于资源受限的场景:在一些资源受限的场景下,如移动设备或边缘计算环境,无法进行大规模的微调实验。PEFT可以帮助估计模型在这些设备上的性能,并指导模型压缩和加速的方向。
综上所述,PEFT通过性能估计和建模,提供了一种高效、准确和可解释的方法,帮助研究人员和从业者进行微调任务的设计和优化。
</aside>
- 微调方法批处理大小模式GPU显存速度?
<aside>
💡
微调方法的批处理大小、模型大小和GPU显存之间存在一定的关系,可以影响微调的速度和性能。下面是一些常见的情况:
1. 批处理大小(Batch Size):批处理大小是指在每次迭代中同时处理的样本数量。较大的批处理大小可以提高GPU的利用率,加快训练速度,但可能会导致显存不足的问题。如果批处理大小过大,无法适应GPU显存的限制,可能需要减小批处理大小或使用分布式训练等方法来解决显存不足的问题。
2. 模型大小(Model Size):模型大小指的是微调任务中使用的模型的参数量和内存占用。较大的模型通常需要更多的显存来存储参数和激活值,可能会导致显存不足的问题。在GPU显存有限的情况下,可以考虑使用轻量级模型或模型压缩等方法来减小模型大小,以适应显存限制。
3. GPU显存:GPU显存是指GPU设备上可用的内存大小。如果微调任务所需的显存超过了GPU显存的限制,会导致显存不足的问题。在这种情况下,可以采取一些策略来解决显存不足,例如减小批处理大小、减小模型大小、使用分布式训练、使用混合精度训练等。
总之,微调方法的批处理大小、模型大小和GPU显存之间存在相互影响的关系。需要根据具体的情况来选择合适的参数设置,以在保证性能的同时,充分利用GPU资源并避免显存不足的问题。
</aside>
- Peft 和 全量微调区别?
<aside>
💡
PEFT(Performance Estimation for Fine-Tuning)和全量微调(Full Fine-Tuning)是两种不同的微调方法,它们在性能估计和实际微调过程中的数据使用上存在一些区别。
1. 数据使用:全量微调使用完整的微调数据集进行模型的训练和调优。这意味着需要在大规模数据集上进行昂贵的实验,耗费大量时间和计算资源。
而PEFT则通过性能估计和建模的方式,避免了在完整数据集上进行实验的过程。PEFT使用一部分样本数据来训练性能估计模型,然后利用该模型对未知数据的性能进行预测。
1. 时间和计算开销:全量微调需要在完整数据集上进行训练和调优,耗费大量时间和计算资源。尤其是在大规模数据集和复杂模型的情况下,全量微调的时间和计算开销会更大。
相比之下,PEFT通过性能估计和建模的方式,避免了在完整数据集上进行实验的过程,从而节省了时间和计算开销。
1. 性能预测准确性:全量微调通过在完整数据集上进行训练和调优,可以获得较为准确的性能指标。因为全量微调是在实际数据上进行的,所以能够更好地反映模型在真实场景中的性能。
PEFT通过性能估计和建模的方式,可以预测模型在未知数据上的性能。虽然PEFT的性能预测准确性可能不如全量微调,但可以提供一个相对准确的性能指标,帮助研究人员和从业者更好地理解模型的性能。
综上所述,PEFT和全量微调在数据使用、时间和计算开销以及性能预测准确性等方面存在一些区别。选择使用哪种方法应根据具体情况和需求来决定。
</aside>
- 多种不同的高效微调方法对比
<aside>
💡
在高效微调方法中,有几种常见的方法可以比较,包括迁移学习、知识蒸馏和网络剪枝。下面是对这些方法的简要比较:
1. 迁移学习(Transfer Learning):迁移学习是一种通过利用预训练模型的知识来加速微调的方法。它可以使用在大规模数据集上预训练的模型作为初始模型,并在目标任务上进行微调。迁移学习可以大大减少微调所需的训练时间和计算资源,并且通常能够达到较好的性能。
2. 知识蒸馏(Knowledge Distillation):知识蒸馏是一种将大型复杂模型的知识转移到小型模型中的方法。它通过在预训练模型上进行推理,并使用其输出作为目标标签,来训练一个较小的模型。知识蒸馏可以在保持较小模型的高效性能的同时,获得接近于大型模型的性能。
3. 网络剪枝(Network Pruning):网络剪枝是一种通过减少模型的参数和计算量来提高微调效率的方法。它通过对预训练模型进行剪枝,去除冗余和不必要的连接和参数,从而减少模型的大小和计算量。网络剪枝可以显著减少微调所需的训练时间和计算资源,并且通常能够保持较好的性能。
这些高效微调方法都有各自的特点和适用场景。迁移学习适用于目标任务与预训练任务相似的情况,可以快速获得较好的性能。知识蒸馏适用于需要在小型模型上进行微调的情况,可以在保持高效性能的同时减少模型大小。网络剪枝适用于需要进一步减少微调所需资源的情况,可以在保持较好性能的同时减少模型大小和计算量。
综上所述,选择适合的高效微调方法应根据具体任务需求和资源限制来决定。不同方法之间也可以结合使用,以进一步提高微调的效率和性能。
</aside>
- 当前高效微调技术存在的一些问题
<aside>
💡
尽管高效微调技术在提高微调效率方面取得了一些进展,但仍然存在一些问题和挑战:
1. 性能保持:一些高效微调技术可能在提高效率的同时,对模型性能产生一定的影响。例如,网络剪枝可能会削减模型的容量,导致性能下降。因此,在使用高效微调技术时需要权衡效率和性能之间的关系,并进行适当的调整和优化。
2. 通用性:目前的高效微调技术通常是针对特定的模型架构和任务设计的,可能不具备通用性。这意味着对于不同的模型和任务,可能需要重新设计和实现相应的高效微调技术。因此,需要进一步研究和开发通用的高效微调技术,以适应不同场景和需求。
3. 数据依赖性:一些高效微调技术可能对数据的分布和规模具有一定的依赖性。例如,迁移学习通常需要目标任务和预训练任务具有相似的数据分布。这可能限制了高效微调技术在一些特殊或小规模数据集上的应用。因此,需要进一步研究和改进高效微调技术,使其对数据的依赖性更加灵活和适应性更强。
4. 可解释性:一些高效微调技术可能会引入一些黑盒操作,使得模型的解释和理解变得困难。例如,知识蒸馏可能会导致模型的输出不再直接对应于原始数据标签。这可能会影响模型的可解释性和可信度。因此,需要进一步研究和改进高效微调技术,以提高模型的可解释性和可理解性。
综上所述,当前高效微调技术在性能保持、通用性、数据依赖性和可解释性等方面仍然存在一些问题和挑战。随着研究的深入和技术的发展,相信这些问题将逐渐得到解决,并推动高效微调技术的进一步发展和应用。
</aside>
- 高效微调技术最佳实践
<aside>
💡
以下是一些高效微调技术的最佳实践:
1. 选择合适的预训练模型:预训练模型的选择对于高效微调至关重要。选择在大规模数据集上训练过的模型,例如ImageNet上的模型,可以获得更好的初始参数和特征表示。
2. 冻结部分层:在微调过程中,可以选择冻结预训练模型的一部分层,只微调模型的一部分层。通常,较低层的特征提取层可以被冻结,只微调较高层的分类层。这样可以减少微调所需的训练时间和计算资源。
3. 适当调整学习率:微调过程中,学习率的调整非常重要。通常,可以使用较小的学习率来微调模型的较高层,以避免过大的参数更新。同时,可以使用较大的学习率来微调模型的较低层,以更快地调整特征表示。
4. 数据增强:数据增强是一种有效的方法,可以增加训练数据的多样性,提高模型的泛化能力。在微调过程中,可以使用各种数据增强技术,例如随机裁剪、翻转和旋转等,以增加训练数据的数量和多样性。
5. 早停策略:在微调过程中,使用早停策略可以避免过拟合。可以监测验证集上的性能,并在性能不再提升时停止微调,以避免过多训练导致模型在验证集上的性能下降。
6. 结合其他高效微调技术:可以结合多种高效微调技术来进一步提高微调的效率和性能。例如,可以使用知识蒸馏来将大型模型的知识转移到小型模型中,以减少模型的大小和计算量。
综上所述,高效微调技术的最佳实践包括选择合适的预训练模型、冻结部分层、适当调整学习率、使用数据增强、使用早停策略以及结合其他高效微调技术。这些实践可以帮助提高微调的效率和性能,并在资源受限的情况下获得更好的结果。
</aside>
- PEFT 存在问题?
<aside>
💡
PEFT(Performance Estimation and Modeling for Fine-Tuning)是一种用于估计和建模微调过程中性能的方法。尽管PEFT在一些方面具有优势,但也存在一些问题和挑战:
1. 精度限制:PEFT的性能估计是基于预训练模型和微调数据集的一些统计特征进行建模的。这种建模方法可能无法准确地捕捉到微调过程中的复杂性和不确定性。因此,PEFT的性能估计结果可能存在一定的误差和不确定性,无法完全准确地预测微调性能。
2. 数据偏差:PEFT的性能估计和建模依赖于预训练模型和微调数据集的统计特征。如果这些特征与实际应用场景存在显著差异,PEFT的性能估计可能不准确。例如,如果微调数据集与目标任务的数据分布不一致,PEFT的性能估计可能会有较大的偏差。
3. 模型依赖性:PEFT的性能估计和建模依赖于预训练模型的质量和性能。如果预训练模型本身存在一些问题,例如表示能力不足或训练偏差等,PEFT的性能估计可能会受到影响。因此,PEFT的性能估计结果可能在不同的预训练模型之间存在差异。
4. 计算复杂性:PEFT的性能估计和建模可能需要大量的计算资源和时间。尤其是在大规模模型和数据集上,PEFT的计算复杂性可能会变得非常高。这可能限制了PEFT在实际应用中的可行性和可扩展性。
综上所述,尽管PEFT在性能估计和建模方面具有一定的优势,但仍然存在精度限制、数据偏差、模型依赖性和计算复杂性等问题。在使用PEFT时,需要注意这些问题,并进行适当的验证和调整,以确保性能估计的准确性和可靠性。
</aside>
- 能不能总结一下各种参数高效微调方法?
<aside>
💡
当涉及到高效微调方法时,有几个关键的参数和技术可以考虑:
1. 冻结层:在微调过程中,可以选择冻结预训练模型的一部分层,只微调模型的一部分层。通常,较低层的特征提取层可以被冻结,只微调较高层的分类层。这样可以减少微调所需的训练时间和计算资源。
2. 学习率调整:微调过程中,学习率的调整非常重要。可以使用较小的学习率来微调模型的较高层,以避免过大的参数更新。同时,可以使用较大的学习率来微调模型的较低层,以更快地调整特征表示。
3. 数据增强:数据增强是一种有效的方法,可以增加训练数据的多样性,提高模型的泛化能力。在微调过程中,可以使用各种数据增强技术,例如随机裁剪、翻转和旋转等,以增加训练数据的数量和多样性。
4. 早停策略:在微调过程中,使用早停策略可以避免过拟合。可以监测验证集上的性能,并在性能不再提升时停止微调,以避免过多训练导致模型在验证集上的性能下降。
5. 知识蒸馏:知识蒸馏是一种将大型模型的知识转移到小型模型中的方法,以减少模型的大小和计算量。通过将预训练模型的输出作为目标标签,可以在微调过程中使用知识蒸馏来提高小型模型的性能。
这些参数和技术可以根据具体的任务和数据集进行调整和应用。综合考虑这些方法,可以提高微调的效率和性能,并在资源受限的情况下获得更好的结果。
</aside>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0px;
margin: 0px;
}
ul{
list-style: none;
}
.menu{
display: flex;
border: 1px solid black;
}
.menu .menu-item{
width: 150px;
height: 50px;
background-color: powderblue;
}
.sub-menu{ /*display : none; <-> display:block; =>transition 효과못줌 */
height: 0px;
overflow: hidden; /* 넘치는 내용은 감추기*/
}
/*
.menu-item:hover{
height: 300px;
transition: 0.5s;
}
*/
.menu:hover .sub-menu{
height: 300px; /* height : 0px; overflow:hidden -> height:300px;*/
}
.menu:hover .menu-item{
height: 300px;
transition: 0.4s;
}
.visual{
height: 400px;
background-color: lightcoral;
}
</style>
</head>
<body>
<ul class="menu">
<li class="menu-item">상위메뉴
<ul class="sub-menu">
<li>하위메뉴1</li>
<li>하위메뉴1</li>
<li>하위메뉴1</li>
</ul>
</li>
<li class="menu-item">상위메뉴
<ul class="sub-menu">
<li>하위메뉴2</li>
<li>하위메뉴2</li>
<li>하위메뉴2</li>
</ul>
</li>
<li class="menu-item">상위메뉴
<ul class="sub-menu">
<li>하위메뉴3</li>
<li>하위메뉴3</li>
<li>하위메뉴3</li>
</ul>
</li>
<li class="menu-item">상위메뉴
<ul class="sub-menu">
<li>하위메뉴4</li>
<li>하위메뉴4</li>
<li>하위메뉴4</li>
</ul>
</li>
</ul>
<div class="visual"></div>
</body>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.