text
stringlengths 184
4.48M
|
---|
import { useEffect } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { ThemeProvider, createTheme } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { fetchCountries } from "./store/countriesSlice";
import NavBar from "./NavBar";
import Home from "./views/Home";
import Details from "./views/Details";
import { dark, light } from "./Theme.js";
/**
*
* @details
* Estructura de las rutas y manejo de temas con MUI
* Documentacion "Theming" Material UI
* https://mui.com/material-ui/customization/theming/#main-content
*
* @funciones
* Controla el "Toggle" del modo oscuro
* Crea el layout de la aplicacion
* Provee el themeprovider a la aplicacion
*
*/
function App() {
const dispatch = useDispatch();
const theme = useSelector((state) => state.countries.isDarkTheme);
const darkTheme = createTheme(dark);
const lightTheme = createTheme(light);
useEffect(() => {
const getCountries = () => {
dispatch(fetchCountries());
};
getCountries();
}, [dispatch]);
return (
<BrowserRouter>
<ThemeProvider theme={theme ? darkTheme : lightTheme}>
<NavBar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/details/:name" element={<Details />} />
</Routes>
</ThemeProvider>
</BrowserRouter>
);
}
export default App;
|
plot_lollipop = function(df,
gene_symbol,
point_colors,
clinvar,
point_shapes = cohort_shapes,
trait_idx = NULL,
gene_col = 'grey90',
color_by_cohort = FALSE,
plot.domains = TRUE,
remove.unknown.domains = TRUE,
omit_spacer = FALSE,
extend.size = NULL,
plot.extra.genes = FALSE,
genome_build = c('hg19', 'hg38'),
txdb = NULL) {
genome_build = match.arg(genome_build)
if (is.null(txdb)) {
txdb = load_txdb(genome_build)
}
my_theme =
BuenColors::pretty_plot(fontsize = 8) +
theme(
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.ticks.length.x = unit(0, "pt"),
legend.position = c(1, 1),
legend.justification = c(1, 1),
legend.title = element_text(margin = margin(0, 0, 0, 0)),
legend.background = element_blank(),
legend.key.size = unit(0.3, "cm"),
panel.border = element_blank(),
plot.margin = margin(0, 0, 0, 0),
plot.tag = element_text(face = 'bold'),
plot.tag.position = c(0, 1)
)
gr <-
range(subset(
GenomicFeatures::transcripts(txdb),
tx_name %in% gene_symbol
),
ignore.strand = TRUE)
chrom = stringr::str_remove(seqnames(gr), "^chr")
start = start(gr)
end = end(gr)
if (!is.null(extend.size)) {
if (length(extend.size) == 1) {
extend.size = rep(extend.size, 2)
}
start = start - extend.size[1]
end = end + extend.size[2]
if (plot.extra.genes) {
gr <- GRanges(seqnames = paste0("chr", chrom),
ranges = IRanges(start, end))
}
}
print(c(start, end))
assign_trait_idx = function(df) {
trait_idx = dplyr::select(df, trait) %>%
dplyr::distinct() %>%
dplyr::arrange(trait) %>%
dplyr::mutate(idx = 1:n()) %>%
as.data.frame()
rownames(trait_idx) = trait_idx$trait
return(trait_idx)
}
if (is.null(trait_idx)) {
trait_idx = assign_trait_idx(df)
}
df = dplyr::mutate(df, signed_pip = sign(susie.beta_posterior) * pip) %>%
dplyr::filter(position >= start & position <= end) %>%
dplyr::mutate(idx = trait_idx[trait, "idx"]) %>%
dplyr::group_by(sign(susie.beta_posterior)) %>%
# mutate(label = coalesce(vep.hgvsp, stringr::str_remove(vep.most_severe, "_variant"))) %>%
dplyr::mutate(label = replace(label, duplicated(label), NA)) %>%
dplyr::ungroup()
if (color_by_cohort) {
s_color = scale_color_manual(values = point_colors, na.value = "grey20")
s_shape = scale_shape_manual(values = point_shapes)
} else {
s_color = scale_color_manual(values = point_colors, na.value = "grey20")
s_shape = scale_shape_manual(values = point_shapes)
}
plot_pip = function(df,
sign,
xscale,
label.y = 1.1,
ymax = 1.8) {
if (sign > 0) {
df = df %>%
dplyr::filter(susie.beta_posterior > 0)
yinf = -Inf
ylim = c(0, ymax)
my_scale_y = scale_y_continuous(breaks = seq(0, 1, by = 0.2))
hjust = 0
p_theme = my_theme +
theme(
axis.line.y = element_line(),
legend.position = "none"
)
} else {
df = df %>%
dplyr::filter(susie.beta_posterior < 0)
yinf = Inf
ylim = c(-ymax, 0)
label.y = -label.y
my_scale_y = scale_y_continuous(breaks = -seq(0, 1, by = 0.2),
labels = sprintf("%.1f", seq(0, 1, by = 0.2)))
hjust = 1
p_theme = my_theme +
theme(axis.line.y = element_line(),
legend.position = "none")
}
if (nrow(df) == 0) {
return(plot_spacer())
}
df = dplyr::arrange(df, position) %>%
dplyr::mutate(position2 = jitter_labels(position, xscale = xscale))
v.pos = dplyr::pull(df, position) %>%
unique()
label.path =
dplyr::select(df, cohort, trait, variant, position, position2, signed_pip) %>%
tidyr::nest(-cohort,-trait,-variant) %>%
dplyr::mutate(data = purrr::map(data, function(data) {
tibble::tibble(
x = c(data$position, data$position2, data$position2),
y = c(yinf, 0, data$signed_pip)
)
})) %>%
tidyr::unnest(data)
if (color_by_cohort) {
g_point = geom_point(aes(position2, signed_pip, col = cohort, shape = cohort),
size = 4)
} else {
g_point = geom_point(aes(position2, signed_pip, col = trait, shape = cohort),
size = 4)
}
df %>%
ggplot() +
geom_path(
aes(
x = x,
y = y,
group = interaction(cohort, trait, variant)
),
data = label.path,
size = 0.2,
color = 'grey50'
) +
geom_segment(
aes(
x = position2,
xend = position2,
y = signed_pip,
yend = label.y
),
data = df %>% filter(!is.na(label)),
size = 0.2,
color = 'grey50',
linetype = 'dotted'
) +
g_point +
geom_text(aes(position2, signed_pip, label = idx),
size = 2,
color = "white") +
geom_text(
aes(x = position2, y = label.y, label = label),
data = df %>% filter(!is.na(label)),
angle = 90,
vjust = 0.5,
hjust = hjust,
size = 2
) +
p_theme +
my_scale_y +
s_color +
s_shape +
labs(x = "Position", y = "PIP") +
coord_cartesian(xlim = xscale,
ylim = ylim,
clip = 'off')
}
gof_pos = df %>% dplyr::filter(susie.beta_posterior > 0) %>% .$position %>% unique()
lof_pos = df %>% dplyr::filter(susie.beta_posterior < 0) %>% .$position %>% unique()
pfam.domains = purrr::map_dfr(gene_symbol, function(x) {
get_pfam_domains(
x,
remove.unknown.domains = remove.unknown.domains,
genome_build = genome_build,
txdb = txdb
)
})
clinvar.snv = clinvar %>%
filter(
GeneSymbol %in% gene_symbol &
ClinicalSignificance %in% c("Pathogenic", "Likely pathogenic")
) %>%
filter(Type == "single nucleotide variant") %>%
mutate(
parse_variant(locus),
gof_overlap = position %in% gof_pos,
lof_overlap = position %in% lof_pos
)
print(clinvar.snv)
clinvar.sv = clinvar %>%
filter(
GeneSymbol %in% gene_symbol &
ClinicalSignificance %in% c("Pathogenic", "Likely pathogenic")
) %>%
# filter(Type != "single nucleotide variant") %>%
mutate(
position = as.numeric(stringr::str_split_fixed(locus, ":", 2)[, 2]),
start = as.numeric(stringr::str_split_fixed(interval, ":|-|\\)", 4)[, 2]),
end = as.numeric(stringr::str_split_fixed(interval, ":|-|\\)", 4)[, 3]),
gof_overlap = position %in% gof_pos,
lof_overlap = position %in% lof_pos,
large_sv = (end - start) > 50
)
print(clinvar.sv)
g_domains = or_missing(nrow(pfam.domains) > 0, geom_rect(
aes(
xmin = start,
xmax = end,
ymin = 0.89,
ymax = 1.11,
fill = Pfam_description
),
data = pfam.domains
))
# g_snv = or_missing(nrow(clinvar.snv) > 0, geom_point(aes(x = position, y = 1), data = clinvar.snv %>% filter(!gof_overlap | !lof_overlap), shape = 18, color = "grey50", size = 3))
g_snv = NULL
g_sv = or_missing(
nrow(clinvar.sv) > 0,
geom_segment(
aes(
x = start,
xend = start,
y = 0.95,
yend = 1.05
),
data = clinvar.sv %>% filter(!large_sv),
color = "grey50",
size = 0.3
)
)
g_large_deletion = or_missing(
any(clinvar.sv$large_sv),
geom_segment(
aes(
x = start,
xend = end,
y = 1.05,
yend = 1.05
),
data = clinvar.sv %>% filter(large_sv),
color = "grey50",
size = 0.3
)
)# BuenColors::jdb_palette("brewer_red")[5]))
# g_gof_overlap = or_missing(any(clinvar.snv$gof_overlap), geom_point(aes(x = position, y = 1), data = clinvar.snv %>% filter(gof_overlap), shape = 18, color = "grey20", size = 3))
# g_lof_overlap = or_missing(any(clinvar.snv$lof_overlap), geom_point(aes(x = position, y = 1), data = clinvar.snv %>% filter(lof_overlap), shape = 18, color = "grey20", size = 3))
g_gof_overlap = or_missing(
any(clinvar.snv$gof_overlap |
clinvar.snv$lof_overlap),
geom_segment(
aes(
x = start,
xend = start,
y = 0.95,
yend = 1.05
),
data = clinvar.sv %>% filter(gof_overlap |
lof_overlap),
color = "grey20",
size = 0.3
)
)
g_lof_overlap = NULL
g_gof = or_missing(length(gof_pos) > 0,
geom_point(
aes(x = gof_pos, y = 1.11),
shape = 18,
color = ifelse(gof_pos %in% clinvar.sv$position, "grey20", "grey50"),
#BuenColors::jdb_palette("solar_extra")[1],
size = 3
))
g_gof_path = or_missing(length(gof_pos) > 0,
geom_path(
aes(x, y, group = i),
data = data.frame(
x = rep(gof_pos, each = 2),
y = rep(c(1.1, Inf), length(gof_pos)),
i = rep(1:length(gof_pos), each = 2)
),
size = 0.2,
color = 'grey50'
))
g_lof = or_missing(length(lof_pos) > 0,
geom_point(
aes(x = lof_pos, y = 0.89),
shape = 18,
color = ifelse(lof_pos %in% clinvar.sv$position, "grey20", "grey50"),
#BuenColors::jdb_palette("solar_extra")[9],
size = 3
))
g_lof_path = or_missing(length(lof_pos) > 0,
geom_path(
aes(x, y, group = i),
data = data.frame(
x = rep(lof_pos, each = 2),
y = rep(c(0.9,-Inf), length(lof_pos)),
i = rep(1:length(lof_pos), each = 2)
),
size = 0.2,
color = 'grey50'
))
plot.gene.label = plot.extra.genes | (length(gene_symbol) > 1)
p_gene = ggplot() +
ggbio::geom_alignment(
txdb,
which = gr,
cds.rect.h = 0.1,
color = gene_col,
fill = gene_col,
label = plot.gene.label,
label.size = 2,
subset.tx_name = locusviz::or_missing(!plot.extra.genes, gene_symbol)
) +
locusviz::or_missing(!plot.gene.label,
geom_text(
aes(x = start, y = 1, label = gene_symbol),
hjust = 1,
nudge_x = -500,
size = 2
)) +
g_domains +
g_large_deletion +
# SV
g_sv +
# SNV
g_snv + g_gof_overlap + g_lof_overlap +
# GoF
g_gof_path + g_gof +
# LoF
g_lof_path + g_lof +
my_theme +
theme(
panel.border = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
axis.text = element_blank(),
axis.ticks.length = unit(0, "pt"),
legend.position = "bottom",
legend.box = "horizontal"
) +
scale_fill_manual(values = BuenColors::jdb_palette('corona')[16:30]) +
scale_y_discrete(expand = c(0, 0.1)) +
labs(x = "Position", fill = "Domain") + coord_cartesian(xlim = c(start, end), clip = "off")
p1 = plot_pip(df, sign = 1, xscale = c(start, end))
p2 = plot_pip(df, sign = -1, xscale = c(start, end))
cohort_idx = df %>% distinct(cohort) %>% mutate(idx = 1:n())
if (color_by_cohort) {
g_legend_trait_point = geom_point(
aes(idx, 0),
data = trait_idx,
color = "grey50",
shape = 18,
size = 2.5
)
g_legend_cohort_point = geom_point(
aes(idx, 0, col = cohort),
data = cohort_idx,
shape = 18,
size = 2.5
)
} else {
g_legend_trait_point = geom_point(
aes(idx, 0, col = trait),
data = trait_idx,
shape = 18,
size = 2.5
)
g_legend_cohort_point = geom_point(
aes(idx, 0, shape = cohort),
data = cohort_idx,
color = "grey50",
size = 2.5
)
}
p_legend_trait = ggplot() +
geom_text(aes(x = 0, y = 0, label = "Trait"),
size = 2,
hjust = 0) +
g_legend_trait_point +
geom_text(
aes(idx, 0, label = idx),
data = trait_idx,
size = 1.5,
color = "white"
) +
geom_text(
aes(idx, 0, label = trait),
data = trait_idx,
size = 2,
hjust = 0,
nudge_x = 0.1
) +
s_color +
s_shape +
cowplot::theme_nothing() +
coord_cartesian(xlim = c(0, max(max(trait_idx$idx), 12)))
p_legend_cohort = ggplot() +
geom_text(aes(x = 0, y = 0, label = "Cohort"),
size = 2,
hjust = 0) +
g_legend_cohort_point +
geom_text(
aes(idx, 0, label = cohort),
data = cohort_idx,
size = 2,
hjust = 0,
nudge_x = 0.1
) +
s_color +
s_shape +
cowplot::theme_nothing() +
coord_cartesian(xlim = c(0, max(max(trait_idx$idx), 12)))
if (omit_spacer & "spacer" %in% c(class(p1), class(p2))) {
if ("spacer" %in% class(p1)) {
p = p2
} else if ("spacer" %in% class(p2)) {
p = p1
}
plt_combined = p + p_gene + p_legend_trait + p_legend_cohort + guide_area() + plot_layout(
nrow = 5,
guides = 'collect',
heights = c(1, 0.25, 0.1, 0.1, 0.1)
)
return(plt_combined)
}
plt_combined = p1 + p_gene + p2 + p_legend_trait + p_legend_cohort + guide_area() + plot_layout(
nrow = 6,
guides = 'collect',
heights = c(1, 0.25, 1, 0.1, 0.1, 0.1)
)
plt_combined
# return(list(plt_combined, p1, p_gene, p2, p_legend))
}
|
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { AuditFormSixteen } from '../shared/models/audit-form-sixteen';
@Injectable({ providedIn: 'root' })
export class FormSixteenService {
private formSixteenUrl = environment.baseUrl;
constructor(private http: HttpClient) { }
public addForm(formSixteen: AuditFormSixteen): Observable<AuditFormSixteen> {
let url = this.formSixteenUrl + "Form16";
return this.http.post<AuditFormSixteen>(url, formSixteen);
}
public getForm(formSixteenId: number): Observable<AuditFormSixteen> {
let url = this.formSixteenUrl + "Form16/" + formSixteenId;
return this.http.get<AuditFormSixteen>(url);
}
public updateForm(formSixteen: AuditFormSixteen): Observable<AuditFormSixteen> {
let url = this.formSixteenUrl + "Form16/" + formSixteen.id;
return this.http.put<AuditFormSixteen>(url, formSixteen);
}
public getForms(patientId: number): Observable<Array<AuditFormSixteen>> {
let url = this.formSixteenUrl + "Form16s/" + patientId;
return this.http.get<Array<AuditFormSixteen>>(url);
}
public deleteForm(formSixteenId: number): Observable<boolean> {
let url = this.formSixteenUrl + "Form16/" + formSixteenId;
return this.http.delete<boolean>(url);
}
}
|
import { StatisticStudentGridComponent } from './../../../module/user/components/statistic-student-grid/statistic-student-grid.component';
import { AsyncPipe } from '@angular/common';
import { Component, OnInit, inject } from '@angular/core';
import { FormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
DestroyService,
EcmBoxComponent,
EcmInputComponent,
} from '@ecm-module/common';
import { GetStatisticUserResponse, UserService, Role } from '@ecm-module/user';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { Observable, debounceTime, forkJoin, map, of, takeUntil } from 'rxjs';
@Component({
selector: 'report-student-page',
templateUrl: './report-student.page.html',
standalone: true,
imports: [
FontAwesomeModule,
EcmBoxComponent,
EcmInputComponent,
ReactiveFormsModule,
FormsModule,
FontAwesomeModule,
AsyncPipe,
StatisticStudentGridComponent,
],
providers: [DestroyService],
})
export class ReportStudentPage implements OnInit {
private fb = inject(FormBuilder);
private destroyService = inject(DestroyService);
private userService = inject(UserService);
public formGroup = this.fb.group({
searchValue: [null],
});
public $student: Observable<GetStatisticUserResponse[]>;
public $totalStudent: Observable<number>;
public additionalColumn = [
{
headerName: 'Khóa học',
minWidth: 100,
field: 'totalCourse',
},
];
ngOnInit(): void {
forkJoin([
this.getStudent(null),
this.userService
.searchUser({
data: { role: Role.STUDENT },
})
.pipe(map((x) => x.totalItems)),
]).subscribe(([student, totalStudent]) => {
this.$student = of(student);
this.$totalStudent = of(totalStudent);
});
this.formGroup.controls.searchValue.valueChanges
.pipe(debounceTime(300))
.subscribe((value) => {
this.$student = this.getStudent(value);
});
}
getStudent(value) {
return this.userService
.statisticUser({
data: {
name: value,
},
})
.pipe(
map((x) => x.items),
takeUntil(this.destroyService.$destroy),
);
}
}
|
export const get_calendars: Object = {
tags: ["User"],
summary: "Returns all calendars in which the user is a member.",
description: "In order to get the informations, the auth-token is required.",
operationId: "getUserCalendars",
parameters: [{
in: "path",
name: "user_id",
description: "The ID of the user entry.",
schema: {
type: "string",
format: "uuid"
},
required: true
},
{
in: "header",
name: "auth-token",
schema: {
type: "string",
format: "jwt"
},
required: true
}],
responses: {
200: {
description: "OK. Contains a list of calendars which have the user as a member with corresponding rights",
content: {
"application/json": {
schema: {
type: "object",
properties: {
associated_calendars: {
type: "array",
items: {
type: "object",
properties: {
is_owner: {type:"boolean"},
can_create_events: {type:"boolean"},
can_edit_events: {type:"boolean"},
color: {type:"number",format:"integer"},
icon: {type:"number",format:"integer"},
calendarObject: {
type: "object",
properties: {
name: {type:"string"},
id: {type:"number",format:"integer"},
can_join: {type:"boolean"},
creation_date: {type:"string", format: "date"}
}
}
},
description: "Calendar Information/Rights"
}
}
}
},
}
},
},
400: {
description: "Bad Request. Request doesnt match the requiered pattern!",
},
401: {
description: "Unauthorized. JWT not valid! When the JWT has expired, the response body contains the error: 'token expired'."
},
404: {
description: "Not Found. No calendars found."
},
"5XX": {
description: "Server Error. Upps, an unexpected error occurred.",
}
}
}
|
<?php
class RoomType
{
private int $id;
private string $name;
private string $description;
/**
* RoomType constructor.
* @param string $name
* @param string $description
*/
public function __construct(string $name, string $description)
{
$this->name = $name;
$this->description = $description;
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*/
public function setName(string $name): void
{
$this->name = $name;
}
/**
* @return string
*/
public function getDescription(): string
{
return $this->description;
}
/**
* @param string $description
*/
public function setDescription(string $description): void
{
$this->description = $description;
}
}
|
import React from "react";
import {
Box,
HStack,
Text,
Center,
Stack as _Stack,
Heading,
Icon,
} from "native-base";
import { FontAwesome } from "@expo/vector-icons";
import { type Cotiza } from "../types/cotiza";
import { FormatDate } from "./helpers/Utils";
import Card from "./helpers/Card";
const CardCotizaItem = ({ item }: { item: Cotiza }) => {
return (
<Box alignItems="center" marginBottom={5}>
<Card>
<_Stack p="4" space={2}>
<_Stack space={2}>
<Heading size="md" ml="-1" color={"blue.500"}>
{item.title}
</Heading>
<Text fontSize="xs" color={"blue.300"} fontWeight="500">
{item.description}
</Text>
</_Stack>
<Text fontWeight="400">
{item.customer.name} {item.customer.lastname}
</Text>
<HStack alignItems="center" space={4} justifyContent="space-between">
<HStack alignItems="center">
<Text color="coolGray.600" fontWeight="400">
{FormatDate(item.created.date)}
</Text>
</HStack>
</HStack>
<Center
bg="blue.500"
_text={{
color: "warmGray.50",
fontWeight: "700",
fontSize: "xs",
}}
position="absolute"
flexDir={"row"}
right={"0"}
bottom="0"
px="3"
py="1.5"
>
<Icon as={<FontAwesome name="dollar" />} size={4} color={"white"} />
{item.amount}
</Center>
<Center
_text={{
color: "blue.500",
fontWeight: "700",
fontSize: "xs",
}}
position="absolute"
bottom="0"
px="3"
py="1.5"
>
{item.status.toUpperCase()}
</Center>
</_Stack>
</Card>
</Box>
);
};
export default CardCotizaItem;
|
from audioop import reverse
from django.db import models
from django.forms.models import model_to_dict
# Create your models here.
class DBBrand(models.Model):
brand_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
class Meta:
verbose_name = ("Marca")
verbose_name_plural = ("Marcas")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("Brand_detail", kwargs={"pk": self.pk})
class DBComponent(models.Model):
component_id = models.AutoField(primary_key=True)
supplypoint = models.CharField(max_length=3,null=True)
categoria_componente = models.CharField(max_length=3,null=True)
cdgrupo = models.CharField(max_length=4,null=True)
grupo = models.CharField(max_length=255,null=True)
cdsubgrupo = models.CharField(max_length=6,null=True)
subgrupo = models.CharField(max_length=255,null=True)
descricao = models.CharField(max_length=255)
brand = models.ForeignKey(DBBrand, on_delete=models.CASCADE, null=True)
modelo = models.CharField(max_length=255,null=True)
unidmedida = models.CharField(max_length=2,null=True)
procedencia = models.CharField(max_length=255,null=True)
cdantigo = models.CharField(max_length=255,null=True)
cdcrm = models.CharField(max_length=50)
preferencial = models.BooleanField(null=True)
conexao = models.CharField(max_length=1,null=True)
potencia = models.DecimalField(max_digits=100, decimal_places=3,null=True)
comprimento = models.IntegerField(null=True)
largura = models.IntegerField(null=True)
altura = models.IntegerField(null=True)
correnteac = models.DecimalField(max_digits=100, decimal_places=2,null=True)
correntedc = models.DecimalField(max_digits=100, decimal_places=2,null=True)
tensaoac = models.DecimalField(max_digits=100, decimal_places=2,null=True)
tensaodc = models.DecimalField(max_digits=100, decimal_places=2,null=True)
orientacao_mptt = models.IntegerField(null=True)
preco = models.DecimalField(max_digits=100, decimal_places=4,null=True)
qtd_estoque = models.DecimalField(max_digits=100, decimal_places=4,null=True)
inv_requer_stringbox = models.BooleanField(null=True)
cabo_ac_mm = models.DecimalField(max_digits=100, decimal_places=2,null=True)
stringbox_qtd_inout = models.IntegerField(null=True)
qtd_disjuntores = models.IntegerField(null=True)
tensao_primario = models.DecimalField(max_digits=100, decimal_places=2,null=True)
tensao_secundario = models.DecimalField(max_digits=100, decimal_places=2,null=True)
status = models.CharField(max_length=255,null=True)
class Meta:
db_table = ''
managed = True
verbose_name = 'Componente'
verbose_name_plural = 'Componentes'
def __str__(self):
return self.descricao
def get_absolute_url(self):
return reverse("componente_detail", kwargs={"pk": self.pk})
def to_dict(self):
return model_to_dict(self)
# region Database Exclusivo site
class DBMaterial(models.Model):
material_id = models.AutoField(primary_key=True)
description = models.CharField(max_length=50)
resistivity = models.FloatField(default=0)
class Meta:
verbose_name = ("Material")
verbose_name_plural = ("Materiais")
def __str__(self):
return self.description
def get_absolute_url(self):
return reverse("DBMaterial_detail", kwargs={"pk": self.pk})
class DBConnection(models.Model):
connection_id = models.AutoField(primary_key=True)
description = models.CharField(max_length=50)
class Meta:
verbose_name = ("Conexão")
verbose_name_plural = ("Conexões")
def __str__(self):
return self.description
def get_absolute_url(self):
return reverse("DBConnection_detail", kwargs={"pk": self.pk})
class DBVoltage(models.Model):
voltage_id = models.AutoField(primary_key=True)
phase_to_phase = models.IntegerField()
phase_to_neutral = models.IntegerField()
class Meta:
verbose_name = ("Tensão")
verbose_name_plural = ("Tensões")
def __str__(self):
return str(self.phase_to_phase)+'/'+str(self.phase_to_neutral)+' V'
def get_absolute_url(self):
return reverse("DBVoltage_detail", kwargs={"pk": self.pk})
class DBCircuitBreaker(models.Model):
circuit_breaker_id = models.AutoField(primary_key=True)
description = models.CharField(max_length=100)
brand = models.ForeignKey(DBBrand, on_delete=models.CASCADE, default=0)
connection_type = models.ForeignKey(DBConnection, on_delete=models.CASCADE)
poles = models.IntegerField()
current = models.FloatField()
length = models.DecimalField(max_digits=10, decimal_places=2, default=0)
width = models.DecimalField(max_digits=10, decimal_places=2, default=0)
height = models.DecimalField(max_digits=10, decimal_places=2, default=0)
weight = models.DecimalField(max_digits=6, decimal_places=2, default=0)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
class Meta:
verbose_name = ("Circuit Breaker")
verbose_name_plural = ("Circuit Breakers")
def __str__(self):
return self.description
def get_absolute_url(self):
return reverse("CircuitBreaker_detail", kwargs={"pk": self.pk})
class DBInverter(models.Model):
inverter_id = models.AutoField(primary_key=True)
brand = models.ForeignKey(DBBrand, on_delete=models.CASCADE, default=20)
model = models.CharField(max_length=100)
cc_max_pv_power = models.DecimalField(max_digits=10, decimal_places=2)
cc_max_input_voltage = models.DecimalField(max_digits=10, decimal_places=2)
cc_startup_input_voltage = models.IntegerField(default=0)
cc_mppt_voltage_range_min = models.IntegerField(default=0)
cc_mppt_voltage_range_max = models.IntegerField(default=0)
cc_max_input_current = models.DecimalField(max_digits=10, decimal_places=2)
cc_max_short_circuit_current = models.DecimalField(max_digits=10, decimal_places=2)
cc_num_mppt = models.IntegerField(default=0)
cc_mppt_desbalanced = models.BooleanField(default=0)
cc_isc_max_main = models.DecimalField(max_digits=10, decimal_places=2, null=True)
ca_isc_max_secundary = models.DecimalField(max_digits=10, decimal_places=2, null=True)
cc_num_inputs = models.IntegerField(default=0)
cc_num_inputs_main = models.IntegerField(null=True)
cc_num_inputs_secundary = models.IntegerField(null=True)
ca_power = models.DecimalField(max_digits=10, decimal_places=2)
ca_voltage = models.ForeignKey(DBVoltage, on_delete=models.PROTECT, default=0)
connection_type = models.ForeignKey(DBConnection, on_delete=models.CASCADE)
ca_current = models.DecimalField(max_digits=10, decimal_places=2)
ca_max_current = models.DecimalField(max_digits=10, decimal_places=2)
length = models.DecimalField(max_digits=10, decimal_places=2)
width = models.DecimalField(max_digits=10, decimal_places=2)
height = models.DecimalField(max_digits=10, decimal_places=2)
weight = models.DecimalField(max_digits=6, decimal_places=2)
price = models.DecimalField(max_digits=10, decimal_places=2)
class Meta:
verbose_name = ("Inversor")
verbose_name_plural = ("Inversores")
def __str__(self):
return self.model
def get_absolute_url(self):
return reverse("DBInverter", kwargs={"pk": self.pk})
class DBCableFlex(models.Model):
cable_id = models.AutoField(primary_key=True)
description = models.CharField(max_length=50)
gauge = models.FloatField()
current = models.FloatField()
external_diameter = models.FloatField()
material = models.ForeignKey(DBMaterial, on_delete=models.CASCADE, default=0)
class Meta:
verbose_name = ("Cabo Flex")
verbose_name_plural = ("Cabos Flex")
def __str__(self):
return self.description
def get_absolute_url(self):
return reverse("DBCable", kwargs={"pk": self.pk})
class DBModule(models.Model):
module_id = models.AutoField(primary_key=True)
brand = models.ForeignKey(DBBrand, on_delete=models.CASCADE)
model = models.CharField(max_length=100)
bifacial = models.BooleanField(default=False)
nominal_power = models.IntegerField()
operating_voltage = models.FloatField()
operating_current = models.FloatField()
open_circuit_voltage = models.FloatField()
short_circuit_current = models.FloatField()
max_system_voltage = models.FloatField()
length = models.IntegerField()
width = models.IntegerField()
height = models.IntegerField()
weight = models.FloatField()
price = models.FloatField()
class Meta:
verbose_name = ("Módulo")
verbose_name_plural = ("Módulos")
def __str__(self):
return (str(self.nominal_power) + ', ' + self.model)
def get_absolute_url(self):
return reverse("DBModule_detail", kwargs={"pk": self.pk})
# endregion
# region TODO
class DBCustomer(models.Model):
customer_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
class Meta:
verbose_name = ("Customer")
verbose_name_plural = ("Customers")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("Customer_detail", kwargs={"pk": self.pk})
class DBPowerPlant(models.Model):
power_plant_id = models.AutoField(primary_key=True)
customer = models.ForeignKey(DBCustomer, on_delete=models.CASCADE)
class Meta:
verbose_name = ("PowerPlant")
verbose_name_plural = ("PowerPlants")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("PowerPlant_detail", kwargs={"pk": self.pk})
class DBOrder(models.Model):
order_id = models.AutoField(primary_key=True)
component = models.ForeignKey(DBComponent, on_delete=models.CASCADE)
power_plant = models.ForeignKey(DBPowerPlant, on_delete=models.CASCADE)
quantity = models.IntegerField()
order_date = models.DateField(auto_now_add=True)
class Meta:
verbose_name = ("Order")
verbose_name_plural = ("Orders")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("Order_detail", kwargs={"pk": self.pk})
# endregion
|
import jwt from "jsonwebtoken";
import prisma from "../../lib/prisma";
import { NextApiRequest, NextApiResponse } from "next";
type UserData = {
id: number;
createdAt: Date;
UpdatedAt: Date;
email: string;
firstName: string;
lastName: string;
password: string;
};
interface JwtPayLoad {
id: number;
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const token = req.cookies.GROOVE_ACCESS_TOKEN;
if (token) {
let user: UserData | null;
try {
const { id } = jwt.verify(token, "hello") as JwtPayLoad;
user = await prisma.user.findUnique({
where: { id },
include: {
_count: {
select: { playlists: true },
},
favorites: {
select: {
id: true,
name: true,
artist: true,
duration: true,
},
},
},
});
if (!user) {
throw new Error("Not real user");
}
} catch (error) {
res.status(401).json({ error: "Not authorized" });
return;
}
res.json({ ...user });
}
}
|
package main;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import org.json.JSONObject;
import com.mongodb.ConnectionString;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
public class MainMethods {
public static void initialize() {
Main.mc = MongoClients.create(new ConnectionString("mongodb://localhost:27017"));
Main.db = Main.mc.getDatabase("school");
Main.db.createCollection("students");
Main.db.createCollection("teachers");
Main.db.createCollection("subjects");
Main.th = new TeacherHandler(Main.db.getCollection("teachers"));
Main.ah = new StudentHandler(Main.db.getCollection("students"));
Main.sh = new SubjectHandler(Main.db.getCollection("subjects"));
Main.teachers = Main.db.getCollection("teachers");
Main.subjects = Main.db.getCollection("subjects");
Main.students = Main.db.getCollection("students");
}
public static void help() {
System.out.println();
System.out.println("\t You have the following options:");
System.out.println();
System.out.println("\t\t DATA MANIPULATION:");
System.out.println();
System.out.println("\t\t\t - To add a new student, type: 'new --a'");
System.out.println("\t\t\t - To add a new teacher, type: 'new --t'");
System.out.println("\t\t\t - To add a new subject, type: 'new --s'");
System.out.println();
System.out.println("\t\t\t - To update a student, type: 'update --a'");
System.out.println("\t\t\t - To update a teacher, type: 'update --t'");
System.out.println("\t\t\t - To update a subject, type: 'update --s'");
System.out.println();
System.out.println("\t\t\t - To delete a student, type: 'delete --a'");
System.out.println("\t\t\t - To delete a teacher, type: 'delete --t'");
System.out.println("\t\t\t - To delete a subject, type: 'delete --s'");
System.out.println();
System.out.println("\t\t\t - To assign students to a teacher, type: 'assign'");
System.out.println("\t\t\t - To assign subjects to a teacher, type: 'add --st'");
System.out.println("\t\t\t - To assign subjects to a student, type: 'add --sa'");
System.out.println();
System.out.println(
"\t\t\t - To add multiple students, type: 'new --a --N' where N is the number you want to insert");
System.out.println(
"\t\t\t - To add multiple subjects, type: 'new --s --N' where N is the number you want to insert");
System.out.println();
System.out.println("\t\t\t ------ ");
System.out.println();
System.out.println("\t\t DATA CONSULTING:");
System.out.println();
System.out.println("\t\t\t - To consult available fields in each class, type: 'fields'");
System.out.println();
System.out.println("\t\t\t - To search by students, type: 'sel --a'");
System.out.println("\t\t\t - To search by teachers, type: 'sel --t'");
System.out.println("\t\t\t - To search by subjects, type: 'sel --s'");
System.out.println();
System.out.println("\t\t\t - To search for common subjects Teacher-Student, type: 'sel --rel-ts'");
System.out.println("\t\t\t - To consult department manager roled teachers, type: 'sel --rel-mg'");
System.out.println();
System.out.println(
"\t\t\t - To search specific fields of a student, type: 'sp --a --F' where F is the field you want.");
System.out.println(
"\t\t\t - To search specific fields of a teacher, type: 'sp --t --F' where F is the field you want.");
System.out.println(
"\t\t\t - To search specific fields of a subject, type: 'sp --s --F' where F is the field you want.");
System.out.println();
System.out.println("\t\t\t ------ ");
System.out.println();
}
public static void showFields() {
System.out.println("TEACHERS:");
System.out.println("\t - _id");
System.out.println("\t - name");
System.out.println("\t - surname");
System.out.println("\t - age");
System.out.println("\t - subjects");
System.out.println();
System.out.println("TEACHERS:");
System.out.println("\t - _id");
System.out.println("\t - name");
System.out.println("\t - surname");
System.out.println("\t - age");
System.out.println("\t - salary");
System.out.println("\t - deptMgr");
System.out.println("\t - students");
System.out.println("\t - subjects");
System.out.println();
System.out.println("TEACHERS:");
System.out.println("\t - _id");
System.out.println("\t - name");
System.out.println("\t - hours");
System.out.println();
}
@SuppressWarnings("unchecked")
public static void insertSubjectInto(String collectionName) {
MongoCollection<Document> collection = getCollection(collectionName);
System.out.println("To search for " + collectionName
+ ", write the field you are looking for and its value separated by ':'.");
String temp = Main.scanner.nextLine();
while (!temp.matches(".\\w+:\\w+")) {
System.err.println("Wrong format.");
temp = Main.scanner.nextLine();
}
String[] command = temp.split(":");
Document filtro = new Document(command[0], command[1]);
if (collection.countDocuments(filtro) == 0) {
System.err.println(collectionName + " with " + temp + " does not exist.");
return;
}
System.out.println("Introduce the subject ids you want to add, separated by ','.");
temp = Main.scanner.nextLine();
while (!temp.matches("^(SB\\d{3})(,(SB\\d{3}))*$")) {
System.err.println("Wrong format");
temp = Main.scanner.nextLine();
}
ArrayList<String> subs = new ArrayList<>();
if (temp.contains(",")) {
for (String s : temp.split(",")) {
subs.add(s);
}
} else {
subs.add(temp);
}
ArrayList<String> found = new ArrayList<>();
subs.forEach(t -> {
Main.sh.collection.find(new Document("_id", t)).forEach(p -> found.add(p.getString("_id")));
});
subs.forEach(t -> {
if (!found.contains(t))
System.err.println(t + " does not exist.");
});
ArrayList<String> alreadyIn = new ArrayList<>();
collection.find(filtro).forEach(t -> {
if (t.get("subjects") != null)
alreadyIn.addAll((ArrayList<String>) t.get("subjects"));
});
alreadyIn.forEach(t -> {
if (found.contains(t))
System.err.println(t + " is already a subject of this " + collectionName + ".");
});
ArrayList<String> subjectsToIntroduce = new ArrayList<>();
found.forEach(t -> {
if (!alreadyIn.contains(t))
subjectsToIntroduce.add(t);
});
subjectsToIntroduce
.forEach(t -> collection.updateOne(filtro, new Document("$push", new Document("subjects", t))));
}
@SuppressWarnings("unchecked")
public static void assignStudent() {
System.out
.println("To search for teachers, write the field you are looking for and its value separated by ':'.");
String temp = Main.scanner.nextLine();
while (!temp.matches(".\\w+:\\w+")) {
System.err.println("Wrong format.");
temp = Main.scanner.nextLine();
}
String[] command = temp.split(":");
Document filtro = new Document(command[0], command[1]);
if (Main.th.collection.countDocuments(filtro) == 0) {
System.err.println("Teacher with " + temp + " does not exist.");
return;
}
System.out.println("Introduce the student ids you want to add, separated by ','.");
temp = Main.scanner.nextLine();
while (!temp.matches("^(ST\\d{3})(,(ST\\d{3}))*$")) {
System.err.println("Wrong format.");
temp = Main.scanner.nextLine();
}
ArrayList<String> subs = new ArrayList<>();
if (temp.contains(",")) {
for (String s : temp.split(",")) {
subs.add(s);
}
} else {
subs.add(temp);
}
ArrayList<String> found = new ArrayList<>();
subs.forEach(t -> {
Main.ah.collection.find(new Document("_id", t)).forEach(p -> found.add(p.getString("_id")));
});
subs.forEach(t -> {
if (!found.contains(t))
System.err.println(t + " does not exist.");
});
ArrayList<String> alreadyIn = new ArrayList<>();
Main.th.collection.find(filtro).forEach(t -> {
if (t.get("students") != null)
alreadyIn.addAll((ArrayList<String>) t.get("students"));
});
alreadyIn.forEach(t -> {
if (found.contains(t))
System.err.println(t + " is already a student of this teacher.");
});
ArrayList<String> studentsToIntroduce = new ArrayList<>();
found.forEach(t -> {
if (!alreadyIn.contains(t))
studentsToIntroduce.add(t);
});
studentsToIntroduce
.forEach(t -> Main.th.collection.updateOne(filtro, new Document("$push", new Document("students", t))));
}
@SuppressWarnings({ "unchecked" })
public static void findCommonSubjects() {
System.out
.println("To search for a teacher, write the field you are looking for and its value separated by ':'");
String temp = Main.scanner.nextLine();
while (!temp.matches(".\\w+:\\w+")) {
System.err.println("Wrong format");
temp = Main.scanner.nextLine();
}
String[] command = temp.split(":");
int aux = 0;
boolean exception = false;
Document tea = new Document();
try {
aux = Integer.parseInt(command[1]);
} catch (NumberFormatException e) {
exception = true;
tea.put(command[0], command[1]);
}
if (!exception)
tea.put(command[0], aux);
if (Main.th.collection.countDocuments(tea) == 0) {
System.err.println("Teacher with " + temp + " does not exist.");
return;
}
System.out
.println("To search for a student, write the field you are looking for and its value separated by ':'");
temp = Main.scanner.nextLine();
while (!temp.matches(".\\w+:\\w+")) {
System.err.println("Wrong format");
temp = Main.scanner.nextLine();
}
command = temp.split(":");
Document stu = new Document();
exception = false;
try {
aux = Integer.parseInt(command[1]);
} catch (NumberFormatException e) {
exception = true;
stu.put(command[0], command[1]);
}
if (!exception)
stu.put(command[0], aux);
if (Main.ah.collection.countDocuments(stu) == 0) {
System.err.println("Student with " + temp + " does not exist.");
return;
}
List<String> subjTeacher = new ArrayList<String>();
List<String> subjStudent = new ArrayList<String>();
List<String> subjCommon = new ArrayList<String>();
Main.th.collection.find(tea).forEach(t -> subjTeacher.addAll((ArrayList<String>) t.get("subjects")));
Main.ah.collection.find(stu).forEach(t -> subjStudent.addAll((ArrayList<String>) t.get("subjects")));
subjTeacher.forEach(t -> {
if (subjStudent.contains(t))
subjCommon.add(t);
});
subjCommon.forEach(System.out::println);
// TODO: Comprobar que funcione
// Bson proj = Projections.fields(Projections.include("subjects"), Projections.excludeId());
// ArrayList<String> sub = new ArrayList<>();
// Main.th.collection.find(tea).projection(proj)
// .forEach(e -> Arrays.asList(e.get("subjects")).forEach(t -> sub.add((String) t)));
// Main.ah.collection.find(stu).projection(proj).forEach(e -> {
// if (sub.contains(e))
// System.out.println(e);
// });
}
public static void select(String collectionName) {
MongoCollection<Document> collection = getCollection(collectionName);
System.out.println("To search for " + collectionName
+ ", write the field you are looking for and its value separated by ':' or 'all' to show the entire collection.");
String temp = Main.scanner.nextLine();
if (temp.equals("all")) {
collection.find().forEach(t -> System.out.println(new JSONObject(t.toJson()).toString(4)));
} else {
while (!temp.matches(".\\w+:\\w+")) {
System.err.println("Wrong format");
temp = Main.scanner.nextLine();
}
String[] command = temp.split(":");
int aux = 0;
boolean exception = false;
Document d = new Document();
try {
aux = Integer.parseInt(command[1]);
} catch (NumberFormatException e) {
exception = true;
d.put(command[0], command[1]);
}
if (!exception)
d.put(command[0], aux);
if (collection.countDocuments(d) == 0)
System.err.println(collectionName + " with " + temp + " does not exists.");
collection.find(d).forEach(t -> System.out.println(new JSONObject(t.toJson()).toString(4)));
}
}
private static MongoCollection<Document> getCollection(String collectionName) {
switch (collectionName) {
case "students":
return Main.students;
case "teachers":
return Main.teachers;
default:
return Main.subjects;
}
}
public static void delete(String collectionName) {
MongoCollection<Document> collection = getCollection(collectionName);
System.out.println("To search for " + collectionName
+ ", write the field you are looking for and its value separated by ':'");
String temp = Main.scanner.nextLine();
while (!temp.matches(".\\w+:\\w+")) {
System.err.println("Wrong format");
temp = Main.scanner.nextLine();
}
String[] command = temp.split(":");
Document query = new Document();
int aux = 0;
boolean exception = false;
try {
aux = Integer.parseInt(command[1]);
} catch (NumberFormatException e) {
exception = true;
query.put(command[0], command[1]);
}
if (!exception)
query.put(command[0], aux);
if (collection.countDocuments(query) == 0) {
System.err.println(collectionName + " with " + temp + " does not exist.");
} else {
collection.deleteOne(query);
}
}
public static void update(String collectionName) {
MongoCollection<Document> collection = getCollection(collectionName);
System.out.println("To search for " + collectionName
+ ", write the field you are looking for and its value separated by ':'");
String temp = Main.scanner.nextLine();
while (!temp.matches(".\\w+:\\w+")) {
System.err.println("Wrong format");
temp = Main.scanner.nextLine();
}
String[] command = temp.split(":");
// We search for the document, if it doesnt exist, ends.
Document existing = new Document();
int aux = 0;
boolean exception = false;
// This is because if the field is a number we cannot use String
try {
aux = Integer.parseInt(command[1]);
} catch (NumberFormatException e) {
exception = true;
existing.put(command[0], command[1]);
}
if (!exception)
existing.put(command[0], aux);
if (collection.countDocuments(existing) == 0) {
System.err.println(collectionName + " with " + temp + " does not exist.");
} else {
System.out.println(
"Using the same format, write the field you want to update and its value separated by ':'");
temp = Main.scanner.nextLine();
while (!temp.matches(".\\w+:\\w+")) {
System.err.println("Wrong format");
temp = Main.scanner.nextLine();
}
command = temp.split(":");
aux = 0;
exception = false;
try {
aux = Integer.parseInt(command[1]);
} catch (NumberFormatException e) {
exception = true;
Document newD = new Document();
newD.put(command[0], command[1]);
Document updateQuery = new Document();
updateQuery.put("$set", newD);
collection.updateOne(existing, updateQuery);
}
if (!exception) {
Document newD = new Document();
newD.put(command[0], aux);
Document updateQuery = new Document();
updateQuery.put("$set", newD);
collection.updateOne(existing, updateQuery);
}
}
}
}
|
<span id="drawer"></span>
<div class="container mt-2">
<div class="offcanvas-header">
<h5 class="m-2"><b><%= station.name.capitalize %></b></h5>
<button type="button" class="btn btn-primary rounded-pill go" data-bs-toggle="offcanvas" data-bs-target="#offcanvasBottom" aria-controls="offcanvasBottom">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-sign-turn-right-fill" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M9.05.435c-.58-.58-1.52-.58-2.1 0L.436 6.95c-.58.58-.58 1.519 0 2.098l6.516 6.516c.58.58 1.519.58 2.098 0l6.516-6.516c.58-.58.58-1.519 0-2.098L9.05.435ZM9 8.466V7H7.5A1.5 1.5 0 0 0 6 8.5V11H5V8.5A2.5 2.5 0 0 1 7.5 6H9V4.534a.25.25 0 0 1 .41-.192l2.36 1.966c.12.1.12.284 0 .384L9.41 8.658A.25.25 0 0 1 9 8.466Z"></path>
</svg>
Go
</button>
<div class="offcanvas offcanvas-bottom" tabindex="-1" id="offcanvasBottom" aria-labelledby="offcanvasBottomLabel">
<div class="offcanvas-header">
<h5 class="offcanvas-title" id="offcanvasBottomLabel">Navigate</h5>
<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
</div>
<div class="offcanvas-body small">
<div style="margin: 0 auto; display: block; text-align: center; rounded ">
<a href="http://maps.apple.com/maps?q=<%=station.latitude%>,<%=station.longitude%>"><img src="https://www.apple.com/v/maps/d/images/overview/intro_icon__dfyvjc1ohbcm_large.png" width="75" height="75"
alt="" style="margin: 8px;"></a>
<a href="https://www.google.com/maps/place/<%=station.latitude%>,<%=station.longitude%>"><img src="https://i0.wp.com/originalapk.com/wp-content/uploads/2019/12/Google-Maps-Icon-Original-APK.png?fit=300%2C300&ssl=1" width="75" height="75" alt=""></a>
<a href="https://waze.com/ul?q=<%=station.latitude%>,<%=station.longitude%>"><img src="https://www.digital-make-it.com/uploaded/136550/waze11-modifier-9343789100488398.png" width="80" height="80" alt=""></a>
</div>
</div>
</div>
</div>
<%# <span class="badge bg-primary">Available</span> %>
</div>
<% if !station.reviews.empty? %>
<% note = 0 %>
<% station.reviews.each do |review| %>
<% note += review.rating %>
<% end %>
<% average = note.fdiv((station.reviews).size) %>
<% end %>
<% if !average.nil? %>
<h6 style="margin-left: 19px"><% average.to_i.times do %>
<i class='fa-sharp fa-solid fa-star' style="color: #ffcd3c;"></i>
<% end %>
<% (5 - average.to_i).times do %>
<i class='fa-regular fa-star' style="color: #ffcd3c;"></i>
<% end %>
(<%= (station.reviews).size %>)
</h6>
<% end %>
</div>
<p><%= station.address %></p>
<% if station.photo.key.nil? %>
<%= image_tag "https://doc-04-a4-mymaps.googleusercontent.com/untrusted/hostedimage/sm8qmc4gucqmtv2n8d3g746lsc/k58foeocjlvtgok8gtgveloeog/1662900235750/JHdNRxuCceXe4dzVnCmOKym7Qn5qjH34/12207485209966916948/5AFzc1vZ2vMQfAZFnbBibNGHCpCAS9gYIa1Hz-620ep9aT2bOwfg5bDiSFx2kJZksOMuEuz7bXJwlq91rTByG1DvdXHZSteYJKUJ-vi8hDsiOK7ucU9TznD56N6s8P1Dme5F9-9et7t9vxh_3fvNwIHvEELyx7f2SHVoKzoQGbQFCLV8lKsSAKaU8aOkrjrVw45T9Rkw?session=0&fife=s16383", height: 200, width: 350, crop: :fill %>
<% else %>
<%= cl_image_tag station.photo.key, height: 200, width: 350,crop: :fill, class: "mb-4" %>
<% end %>
<div class="d-flex justify-content-around align-items-center text-center">
<% station.station_chargers.each do |station_charger| %>
<li style="list-style: none">
<div class="column m-auto" style="height: 45px;">
<%= image_tag(station_charger.charger.ctype+".svg", style:"width:35px; height:35px")%>
</div>
<div style="height: 45px; ">
<h6><span style="display: inline-block; min-width: 66px; font-size: 14px">
<b><%= station_charger.charger.ctype%></b></span>
<li style="font-size: 14px">
<% if station_charger.charger.tethered? && station_charger.charger.ctype == "Type 2" %>
Tethered
<% end %>
</li>
<li style="font-size: 14px">
<% if station_charger.charger.capacity % 1 == 0 %>
<%= station_charger.charger.capacity.to_i %> kW x
<% else %>
<%= station_charger.charger.capacity %> kW x
<% end %>
<%= station_charger.charger_count %></li></h6>
</div>
</li>
<% end %>
</div>
<hr>
</div>
<div class="text-center">
<%= link_to "Leave a review", new_station_review_path(station)%>
<br>
<br>
<button class="btn btn-primary rounded-pill" id="showReviews" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
See reviews
</button>
<script>
</script>
</div>
<br>
<br>
<div class="collapse" id="collapseExample">
<div class="card-body">
<% if !station.reviews.empty? %>
<% station.reviews.each do |review| %>
<i class="fas fa-quote-left pe-2"></i><%= review.content %></i>
<ul class="list-unstyled d-flex justify-content text-warning mb-0">
<% review.rating.to_i.times do %>
<li><i class="fas fa-star fa-sm"></i></li>
<% end %>
<% (5 - review.rating).to_i.times do %>
<li><i class="far fa-star fa-sm"></i></li>
<% end %>
</ul>
<%# <p class="mb-0"><b>Rating:</b><%= review.rating %>
<% if review.photo.key? %>
<%= cl_image_tag review.photo.key, height: 50, width: 50, crop: :fill %>
<% end %>
<hr>
<% end %>
<% end %>
</div>
</div>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
|
#ifndef _RADIOLIB_LORAWAN_H
#define _RADIOLIB_LORAWAN_H
#include "../../TypeDef.h"
#include "../PhysicalLayer/PhysicalLayer.h"
//https://github.com/Lora-net/LoRaMac-node
// preamble format
#define LORAWAN_LORA_SYNC_WORD 0x34
#define LORAWAN_LORA_PREAMBLE_LEN 8
#define LORAWAN_GFSK_SYNC_WORD 0xC194C1
#define LORAWAN_GFSK_PREAMBLE_LEN 5
// data rate field encoding MSB LSB DESCRIPTION
#define LORAWAN_DATA_RATE_SF_12 0b00000000 // 7 4 LoRaWAN spreading factor: SF12
#define LORAWAN_DATA_RATE_SF_11 0b00010000 // 7 4 SF11
#define LORAWAN_DATA_RATE_SF_10 0b00100000 // 7 4 SF10
#define LORAWAN_DATA_RATE_SF_9 0b00110000 // 7 4 SF9
#define LORAWAN_DATA_RATE_SF_8 0b01000000 // 7 4 SF8
#define LORAWAN_DATA_RATE_SF_7 0b01010000 // 7 4 SF7
#define LORAWAN_DATA_RATE_FSK_50_K 0b01100000 // 7 4 FSK @ 50 kbps
#define LORAWAN_DATA_RATE_BW_500_KHZ 0b00000000 // 3 0 LoRaWAN bandwidth: 500 kHz
#define LORAWAN_DATA_RATE_BW_250_KHZ 0b00000001 // 3 0 250 kHz
#define LORAWAN_DATA_RATE_BW_125_KHZ 0b00000010 // 3 0 125 kHz
// to save space, channels are saved in "spans"
struct LoRaWANChannelSpan_t {
uint8_t numChannels; // total number of channels in the span
float freqStart; // center frequency of the first channel in span
float freqStep; // frequency step between adjacent channels
uint8_t numDataRates; // number of datarates supported by the all channels in the span
uint8_t dataRates[6]; // array of datarates supported by all channels in the span (no channel span has more than 6 allowed data rates)
};
struct LoRaWANBand_t {
uint8_t numChannelSpans; // number of channel spans in the band
LoRaWANChannelSpan_t uplinkDefault[2]; // default uplink (TX) channels (defined by LoRaWAN Regional Parameters)
LoRaWANChannelSpan_t uplinkAvailable; // available uplink (TX) channels (not defined by LoRaWAN Regional Parameters)
LoRaWANChannelSpan_t downlinkDefault[2]; // default downlink (RX1) channels (defined by LoRaWAN Regional Parameters)
LoRaWANChannelSpan_t downlinkAvailable; // available downlink (RX1) channels (not defined by LoRaWAN Regional Parameters)
LoRaWANChannelSpan_t downlinkBackup; // backup downlink (RX2) channels - just a single channel, but using the same structure for convenience
};
struct EU868: public LoRaWANBand_t {
uint8_t getDownlinkChannel(uint8_t txChan); // method that returns RX1 channel number based on TX channel
uint8_t getDownlinkDataRate(uint8_t offset); // method that returns RX1 channel number based on TX channel
};
class LoRaWANNode {
public:
LoRaWANNode(PhysicalLayer* phy, LoRaWANBand_t* band);
#ifndef RADIOLIB_GODMODE
private:
#endif
PhysicalLayer* _phy;
LoRaWANBand_t* _band;
};
#endif
|
let express = require("express");
let server = express();
import { renderToString } from "vue/server-renderer";
import { createMemoryHistory } from "vue-router";
import { createPinia } from "pinia";
import createApp from "../index.js";
import createRouter from "../router";
// 静态资源的部署
server.use(express.static("build"));
server.get("/*", async (req, res) => {
const app = createApp();
// 安装路由
const router = createRouter(createMemoryHistory());
app.use(router);
await router.push(req.url || "/"); // 等待页面跳转好
await router.isReady(); // 等待路由加载完成,再渲染页面
// pinia
const pinia = createPinia();
app.use(pinia);
let appString = await renderToString(app);
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Vue3 Server Render</h1>
<div id="app">
${appString}
</div>
<script src='/client/bundle.js'></script>
</body>
</html>
`);
});
server.listen(3001, () => {
console.log("开始监听3001端口");
});
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDesaTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tbl_desa', function (Blueprint $table) {
$table->increments('id');
$table->string('kode');//ada kodenya juga
$table->string('nama');//nama desanya juga
$table->integer('kecamatan_id')->unsigned();//foreign key ke table kecamatan
$table->foreign('kecamatan_id')->references('id')->on('tbl_kecamatan');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tbl_desa');
}
}
|
# -*- coding: utf-8 -*-
#Comentario de una sola linea con el simbolo #, en Python para nada se deben poner acentos sino el programa
#puede fallar o imprimir raro en consola, la primera línea de código es para que no tenga error, pero aún
#así al poner un ángulo saldrá raro en consola, la línea debe ponerse tal cual como aparece y justo al inicio.
#IMPORTACIÓN DE LIBRERÍAS:
import cv2 as cv #Librería OpenCV: Sirve para todo tipo de operaciones de visión artificial
import numpy as np #Librería numpy: Realiza operaciones matemáticas complejas
import math #Librería math: Para aplicar funciones matemáticas básicas.
#OBTENCIÓN DE BORDES:
#imread(): Sirve para leer la imagen de un directorio especificado, si en el segundo parámetro se pone un 1, la imagen se
#obtendrá en forma de matriz 3D RGB y si se pone un 0 se obtendrá en escala de grises, obteniendo una matriz 2D.
#Para leer una imagen o cualquier otro archivo se usa la dirección relativa del directorio, la cual es una dirección que
#se busca desde donde se encuentra la carpeta del archivo python actualmente, esta se debe colocar entre comillas simples
#o dobles:
# .. : Significa que nos debemos salir de la carpeta donde nos encontramos actualmente.
# / : Sirve para introducirnos a alguna carpeta cuyo nombre se coloca después del slash.
# .ext : Se debe colocar siempre el nombre del archivo + su extensión.
#El error que se puede experimentar cuando se usa una ruta relativa es que está configurada en relación con el directorio
#de trabajo actual, por lo que si el programa se ejecuta desde una ubicación diferente a la carpeta donde se encuentra
#este archivo, el programa no podrá abrir ninguno de los archivos indicados y arrojará una excepción.
img1 = cv.imread('0.-Img/Lena.jpg', 0)
#FILTRO CANNY: El filtro de Canny sirve para la identificación de bordes, esto para segmentar figuras en la imagen.
#Lo que hace el detector Canny es mejorar la detección de bordes, ya que quita los bordes que no nos interesan y deja solamente
#los que si nos interesan, haciendo que el borde sea una sola línea en vez de varias como lo muestran otros detectores de líneas
#como lo es el operador Sobel.
#El operador Canny ya que realizó la identificación de bordes, ejecutará un proceso llamado umbral de histéresis que hace uso de
#dos umbrales, para preservar solamente los bordes más pronunciados y quitar los bordes que no nos interesan. Para saber cuales
#son los valores que se quiere obtener de los bordes, se puede obtener el histograma de la imagen obtenida con los bordes y ver
#que tonos de gris son los que representan la mayoría de los bordes que queremos preservar.
#cv.Canny(): Aplica el filtro de Canny realizando los siguientes pasos de analisis de imagen:
# 1. Suavizar la imagen (difuminarla): Reducción de ruido por medio del filtro Gaussiano.
# 2. Operador sobel (detección de bordes): Gradiente y orientación del primer borde obtenido de la imagen.
# 3. Detector Canny: Identificar mejor los bordes de una imagen y aplicar el umbral de histéresis para preservar solamente los
# bordes más pronunciados y quitar los bordes que no nos interesan.
#Los parámetros que recibe el método son los siguientes:
# - Como primer parámetro se le pasa una imagen obtenida previamente con el método imread()
# - Como segundo y tercer parámetro se le pasan umbrales para el filtrado de histéresis de la imagen, con ellos obtendremos
# ciertos bordes solamente y despreciaremos los demás, el primer umbral es el inferior y el segundo el superior.
# - Como tercer parámetro necesitamos indicar los bordes y apertura de la imagen para el operador Sobel.
img_canny = cv.Canny(img1, 50, 200, None, 3)
#imshow(): Con el método se puede mostrar una imagen, el primer parámetro es el nombre de la ventana donde aparecerá la imagen
#y el segundo parámetro es la imagen recopilada con el método imread()
cv.imshow('Imagen original escala de grises', img1)
cv.imshow('Filtro de Canny - Bordes', img_canny) #Mostrar una ventana que tenga como título el 1er parametro y muestre la imagen del 2do
#OBTENCIÓN DE LÍNEAS: Se utiliza mucho para cuando la deteccción de líneas es importante, como por ejemplo en los coches
#autónomos, detectando así carreteras, señalamientos, etc.
#TRANSFORMADA DE HUGH: Sirve para la identificación de líneas, para ello anteriormente se tuvieron que haber obtenido los bordes
#con el método de Canny, pero no solo sirve para la identificación de líneas, sino de círculos y puntos.
# https://docs.opencv.org/3.4/d9/db0/tutorial_hough_lines.html
#cv.HoughLines(): Es un método utilizado para la obtención de líneas, para ello se deben ingresar los siguientes parámetros:
# - Una imagen a la que se haya aplicado el método cv.Canny(), ya que para obtener las líneas de la imagen, previamente se deben
# haber identificado los bordes.
# - Valor rho: Resolución de la magnitud de los bordes a identificar, normalmente se pone el valor 1
# - Valor theta: Resolución de la orientación de los bordes a identificar, normalmente se pone el valor π/180 porque se quiere
# dar el valor en grados, usando la librería numpy para obtener el valor de pi.
# - Umbral: Es un valor a partir del cual se va a obtener las líneas recopiladas, para saber si se considera como línea o no.
# - None: Este parámetro siempre debe ser none, puede no ponerse pero si se omite, puede fallar la detección de líneas.
lineas = cv.HoughLines(img_canny, 1, np.pi/180, 150, None)
#La matriz obtenida con la matriz de Hugh es de 3 dimensiones con tamaño:
# - i valores para cada punto en la primera dimensión.
# - Una segunda dimensión con tamaño 1, osea index 0, para acceder al vector que tiene ambos valores θ (theta) y ρ (rho) de las
# líneas obtenidas.
# - La tercera dimensión solo tiene 2 valores, osea index 0 y 1 para acceder con 0 al valor de rho y con 1 al valor de theta.
print("Tipo primitivo de lo que devuelve el método de la transformada de Hugh: " + str(type(lineas)))
print("Resultado del método de la transformada de Hugh: \n" + str(lineas))
print("La primera posición del valor rho de la matriz obtenida con transformada de Hugh es: " + str(lineas[0][0][0]))
#Condicional y bucle para mostrar las líneas, ya que si al correrlo no aparecen las líneas dará error el programa, para ello se
#checa si la variable líneas no está vacía, luego se realiza un bucle que se ejecute el mismo número de veces que el tamaño de
#lo que contenga la variable líneas, esto para calcular el valor de los tamaños de la magnitud ρ que indica la pendiente de las
#líneas detectadas, que es una matriz 3D.
if lineas is not None:
for i in range(0, len(lineas)):
#rho(θ) = x0*cos(θ) + y0⋅sin(θ)
rho = lineas[i][0][0]
theta = lineas[i][0][1]
#Con esto se busca obtener la coordenada horizontal de la primera coordenada que describe la línea.
a = math.cos(theta)
x0 = a*rho
#Con esto se busca obtener la coordenada vertical de la primera coordenada que describe la línea.
b = math.sin(theta)
y0 = b*rho
#Después se suma la coordenada siguiente para ir obteniendo los puntos de las líneas.
punto1 = (int(x0 + 1000*b), int(y0 + 1000*a)) #x1 = rho*cos(θ) + 1000*sin(θ), y1 = rho*cos(θ) + 1000*sin(θ)
punto2 = (int(x0 - 1000*b), int(y0 - 1000*a)) #x2 = rho*cos(θ) - 1000*sin(θ), y2 = rho*sin(θ) - 1000*cos(θ)
#cv.line(): Con este método perteneciente a la librería OpenCV se puede crear una línea, en él se indica primero en
#que imagen obtenida con el método imread() se va a dibujar la figura, luego los dos puntos con coordenadas x,y de la
#imagen en donde se va a mostrar la línea, su color en formato BGR y el ancho en pixeles del borde de la línea.
#En la interfaz se mostrarán líneas en los puntos dónde se hayan obteniendo las líneas en los bordes de la imagen.
cv.line(img_canny, punto1, punto2, (0, 0, 255), 3)
cv.imshow('Transformada de Hugh - Lineas', img_canny) #Mostrar una ventana que tenga como título el 1er parametro y muestre la imagen del 2do
#NO DEJAR QUE SE CIERREN LAS VENTANAS: Las siguientes dos líneas de código sirven para que no se cierre la ventana inmediatamente
#después de abrirse, solo cuando se dé clic en el tache de la ventana, son parte de la librería OpenCV.
#waitKey(): Método que permite a los usuarios mostrar una ventana durante un número de milisegundos determinados o hasta que se
#presione cualquier tecla. Toma tiempo en milisegundos como parámetro y espera el tiempo dado para destruir la ventana, o si se
#pasa 0 en el argumento, espera hasta que se presiona cualquier tecla.
cv.waitKey(0)
#destroyAllWindows(): Función que permite a los usuarios destruir todas las ventanas en cualquier momento. No toma ningún
#parámetro y no devuelve nada, esto se incluye para que al cerrar la ventana después del método waitKey() se destruyan para
#poder utilizarse en otra cosa.
cv.destroyAllWindows()
#Para cerrar todas las ventanas de jalón se puede usar ALT + F4 pero a veces se traba Visual Studio Code y lo debo reiniciar
#OBTENCIÓN DE FIGURAS GEOMÉTRICAS POR MEDIO DE UMBRALIZACIÓN:
#UMBRALIZACIÓN: Se utiliza para indicar que, a partir de cierto valor de un tono de gris que va de 0 a 255, se diferencie el
#fondo y el objeto que se quiere identificar en la imagen. Al umbralizar se crean imágenes binarias, donde al objeto normalmente
#se le asigna un valor de 1 y al fondo se le asigna un valor de 0, aunque puede ser viceversa, el chiste es diferenciar uno del
#otro a partir de cierto umbral.
#Límite superior del umbral es 28 e inferior es 0 para la imagen Figuras.png
#Límite superior del umbral es 120 e inferior es más o menos 100 para la imagen Lena.jpg
umbral = 14 #Umbral del tono de gris en la escala de grises de la imagen, va de 0 a 255
color_contorno = (0, 0, 255) #Variable que almacena un color BGR
img2 = cv.imread('0.-Img/Figuras.png', 1) #Imagen RGB obtenida con el método imread()
#cvtColor(): Método de la librería OpenCV que recibe como primer parámetro una imagen RGB y en su segundo parámetro recibe un
#atributo de OpenCV llamado cv.COLOR_BGR2GRAY para convertir una imagen RGB a su escala de grises
img_gray = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)
#cv.threshold(): Este método sirve para umbralizar una imagen, en ella se le pasa como primer parámetro la imagen en escala de
#grises que va a umbralizar, a continuación se indica el valor del umbral, el valor máximo que puede alcanzar el umbral y se
#especifica que el resultado debe ser una imagen binaria con un atributo de OpenCV llamado cv.THRESH_BINARY o si se quiere el
#inverso se puede usar cv.THRESH_BINARY_INV, en este caso se usa un guión bajo antes del nombre de la variable, porque esta es
#una variable interna.
#El guión bajo también usa para ignorar valores específicos, si no se necesita algún valor en específico del método, o no usa
#estos valores, simplemente se asignan estos valores a la "variable" representada con un guión bajo, en python el orden del
#guión importa.
_, img_umbral = cv.threshold(img_gray, umbral, 255, cv.THRESH_BINARY)
#cv.findContours(): Este método sirve para encontrar los contornos en una imagen, se puede utilizar en vez del filtro Canny, al
#método se le pasa como primer parámetro la imagen en escala de grises, en las imágenes existen varios tipos de contornos, estos
#pueden tener jerarquías de dentro hacia fuera o pueden no tenerlas, esto depende del segundo parámetro que se le pase en el
#método, en este caso vamos a utilizar el parámetro cv.RETR_LIST para que no muestre jerarquía en los bordes que encuentre,
#posteriormente se le debe indicar en el tercer parámetro la forma en la que se va a guardar la información recabada, ya que
#puede guardar todos los puntos del contorno identificado o solo guardar los puntos de las esquinas que conforman el contorno,
#para que guarde todos los puntos de los contornos se le indica con el atributo cv.CHAIN_APPROX_NONE, para guardar solo las
#esquinas se usa el atributo cv.CHAIN_APPROX_SIMPLE.
contornos, _ = cv.findContours(img_umbral, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)
#cv.drawContours(): Método que sirve para dibujar los contornos recabados con el método cv.findContours(), para ello primero se
#debe indicar en qué imagen se va a dibujar el contorno, no debe ser la misma de la que se obtuvieron los contornos, después se
#indica en el segundo parámetro la variable en donde están almacenados los contornos, en el tercer parámero se establece si se
#quiere que sea hueco o sólido el contorno, como se busca que sea sólido se pone -1, si fuera hueco, en esta parte se indicaría
#los pixeles del perímetro (borde) del contorno, posteriormente se indica el color y finalmente los contornos que quiero que
#muestre.
cv.drawContours(img2, contornos, -1, color_contorno, 3)
cv.imshow('Umbralizacion', img_umbral) #Mostrar una ventana que tenga como título el 1er parametro y muestre la imagen del 2do
cv.imshow('Imagen contornos', img2) #Mostrar una ventana que tenga como título el 1er parametro y muestre la imagen del 2do
#NO DEJAR QUE SE CIERREN LAS VENTANAS: Las siguientes dos líneas de código sirven para que no se cierre la ventana.
cv.waitKey(0) #Mostrar la ventana hasta que se presione la tecla X
cv.destroyAllWindows() #Destruir todas las ventanas después de cerrarlas con el comando
|
package ch.bfh.ti.gravis.core.step;
import java.util.Objects;
import ch.bfh.ti.gravis.core.graph.item.IGraphItem;
/**
* Performs a DO or UNDO operation at the graph item method
* {@link IGraphItem#setCurrentResult(double)}.
*
* @author Patrick Kofmel ([email protected])
*
*/
class ResultCommand extends EmptyStep {
private static final String NULL_POINTER_MSG = "Invalid parameter value in method "
+ "ResultCommand.%s(): %s == %s";
private final IGraphItem item;
private final double newResult, oldResult;
/**
* @param currentItem
* @param oldResult
* @param newResult
* @throws NullPointerException
* if currentItem is null
*/
protected ResultCommand(IGraphItem currentItem, double oldResult,
double newResult) {
this.item = Objects.requireNonNull(currentItem, String.format(
NULL_POINTER_MSG, "ResultCommand", "currentItem", currentItem));
this.oldResult = oldResult;
this.newResult = newResult;
}
@Override
public IStepResult execute() {
this.item.setCurrentResult(this.newResult);
return new StepResult();
}
@Override
public IStepResult unExecute() {
this.item.setCurrentResult(this.oldResult);
return new StepResult();
}
}
|
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include <string.h>
#include "clcd/clcd.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
#define RTC_BKP_DR1_VALUE 0x32F2
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
RTC_HandleTypeDef hrtc;
UART_HandleTypeDef huart2;
/* USER CODE BEGIN PV */
char gLCDBuf1[17];
char gLCDBuf2[17];
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_RTC_Init(void);
/* USER CODE BEGIN PFP */
/**
* @brief Configure RTC Alarm.
* @param None
* @retval None
*/
static void
RTC_AlarmConfig (void)
{
printf ("%s\n", __FUNCTION__);
RTC_TimeTypeDef stimestructure;
RTC_AlarmTypeDef salarmstructure;
/*########## Configure the RTC Alarm peripheral ##########*/
HAL_RTC_GetTime (&hrtc, &stimestructure, RTC_FORMAT_BIN);
salarmstructure.Alarm = RTC_ALARM_A;
if(stimestructure.Seconds < 55)
{
salarmstructure.AlarmTime.Hours = stimestructure.Hours;
salarmstructure.AlarmTime.Minutes = stimestructure.Minutes;
salarmstructure.AlarmTime.Seconds = stimestructure.Seconds + 5;
}
else if(stimestructure.Minutes != 59)
{
salarmstructure.AlarmTime.Hours = stimestructure.Hours;
salarmstructure.AlarmTime.Minutes = stimestructure.Minutes + 1;
salarmstructure.AlarmTime.Seconds = stimestructure.Seconds + 5 - 60;
}
else
{
salarmstructure.AlarmTime.Hours = stimestructure.Hours + 1;
salarmstructure.AlarmTime.Minutes = 0x0;
salarmstructure.AlarmTime.Seconds = stimestructure.Seconds + 5 - 60;
}
if (HAL_RTC_SetAlarm_IT (&hrtc, &salarmstructure, RTC_FORMAT_BIN) != HAL_OK)
{
/* Initialization Error */
Error_Handler ();
}
HAL_NVIC_SetPriority (RTC_Alarm_IRQn, 0, 0);
HAL_NVIC_EnableIRQ (RTC_Alarm_IRQn);
sprintf (gLCDBuf1, " A-%02d:%02d:%02d", salarmstructure.AlarmTime.Hours,
salarmstructure.AlarmTime.Minutes, salarmstructure.AlarmTime.Seconds);
}
/**
* @brief Display the current date and time.
* @param showtime : pointer to buffer
* @retval None
*/
static void
RTC_TimeShow (char *showtime)
{
RTC_DateTypeDef sdatestructureget;
RTC_TimeTypeDef stimestructureget;
uint32_t dateToStore;
char temp[5];
/* Get the RTC current Time */
HAL_RTC_GetTime (&hrtc, &stimestructureget, RTC_FORMAT_BIN);
/* Get the RTC current Date */
HAL_RTC_GetDate (&hrtc, &sdatestructureget, RTC_FORMAT_BIN);
/* Display time Format : MM/dd hh:mm:ss */
sprintf (temp, "%04d", sdatestructureget.Year + 2000);
memcpy ((void*) gLCDBuf1, temp, sizeof(temp) - 1);
sprintf (showtime, "%02d/%02d %02d:%02d:%02d", sdatestructureget.Month, sdatestructureget.Date,
stimestructureget.Hours, stimestructureget.Minutes, stimestructureget.Seconds);
/* Store date info into Backup Data Register */
memcpy(&dateToStore, &sdatestructureget, 4);
BKP->DR2 = dateToStore >> 16;
BKP->DR3 = dateToStore & 0xFFFF;
}
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/**
* @brief Retargets the C library printf function to the USART.
* @param None
* @retval None
*/
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the UART2 and Loop until the end of transmission */
if(ch == '\n')
HAL_UART_Transmit(&huart2, (uint8_t *)"\r", 1, 0xFFFF);
HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_RTC_Init();
/* USER CODE BEGIN 2 */
printf ("NUCLEO_F103RB RTC P/G\n");
printf ("SYSCLK Frequency = %d\n", HAL_RCC_GetSysClockFreq());
printf ("HCLK Frequency = %d\n", HAL_RCC_GetHCLKFreq());
printf ("PCLK Frequency = %d\n", HAL_RCC_GetPCLK1Freq());
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
/* LCD Initialize */
CLCD_Init(16, 2);
/* Check if the Power On Reset flag is set */
if (__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST) != RESET)
{
/* Power on reset occurred */
printf("Power on reset occurred\n");
}
/* Check if Pin Reset flag is set */
if (__HAL_RCC_GET_FLAG(RCC_FLAG_PINRST) != RESET)
{
/* External reset occurred */
printf("External reset occurred\n");
}
/* Clear source Reset Flag */
__HAL_RCC_CLEAR_RESET_FLAGS();
/* Alarm Configuration */
RTC_AlarmConfig();
while (1)
{
RTC_TimeShow(gLCDBuf2);
CLCD_Puts(0, 0, gLCDBuf1);
CLCD_Puts(0, 1, gLCDBuf2);
// printf("%s\n", gLCDBuf1);
printf("%s\n", gLCDBuf2);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_Delay(1000);
HAL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin);
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSE;
RCC_OscInitStruct.LSEState = RCC_LSE_ON;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC;
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief RTC Initialization Function
* @param None
* @retval None
*/
static void MX_RTC_Init(void)
{
/* USER CODE BEGIN RTC_Init 0 */
/* USER CODE END RTC_Init 0 */
RTC_TimeTypeDef sTime = {0};
RTC_DateTypeDef DateToUpdate = {0};
/* USER CODE BEGIN RTC_Init 1 */
/* USER CODE END RTC_Init 1 */
/** Initialize RTC Only
*/
hrtc.Instance = RTC;
hrtc.Init.AsynchPrediv = RTC_AUTO_1_SECOND;
hrtc.Init.OutPut = RTC_OUTPUTSOURCE_ALARM;
if (HAL_RTC_Init(&hrtc) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN Check_RTC_BKUP */
if (HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_DR1) == RTC_BKP_DR1_VALUE)
{
uint32_t dateMem;
dateMem = BKP->DR3;
dateMem |= BKP->DR2 << 16;
memcpy(&DateToUpdate, &dateMem, sizeof(uint32_t));
if(HAL_RTC_SetDate(&hrtc, &DateToUpdate, RTC_FORMAT_BIN) != HAL_OK)
{
Error_Handler();
}
return;
}
else
HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR1, RTC_BKP_DR1_VALUE);
/* USER CODE END Check_RTC_BKUP */
/** Initialize RTC and set the Time and Date
*/
sTime.Hours = 0x16;
sTime.Minutes = 0x0;
sTime.Seconds = 0x20;
if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD) != HAL_OK)
{
Error_Handler();
}
DateToUpdate.WeekDay = RTC_WEEKDAY_WEDNESDAY;
DateToUpdate.Month = RTC_MONTH_DECEMBER;
DateToUpdate.Date = 0x29;
DateToUpdate.Year = 0x20;
if (HAL_RTC_SetDate(&hrtc, &DateToUpdate, RTC_FORMAT_BCD) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN RTC_Init 2 */
/* USER CODE END RTC_Init 2 */
}
/**
* @brief USART2 Initialization Function
* @param None
* @retval None
*/
static void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOC, CLCD_D0_Pin|CLCD_D1_Pin|CLCD_D2_Pin|CLCD_D3_Pin
|CLCD_EN_Pin|CLCD_RS_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : B1_Pin */
GPIO_InitStruct.Pin = B1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : CLCD_D0_Pin CLCD_D1_Pin CLCD_D2_Pin CLCD_D3_Pin
CLCD_EN_Pin CLCD_RS_Pin */
GPIO_InitStruct.Pin = CLCD_D0_Pin|CLCD_D1_Pin|CLCD_D2_Pin|CLCD_D3_Pin
|CLCD_EN_Pin|CLCD_RS_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pin : LD2_Pin */
GPIO_InitStruct.Pin = LD2_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);
}
/* USER CODE BEGIN 4 */
void
HAL_RTC_AlarmAEventCallback (RTC_HandleTypeDef *hrtc)
{
printf ("%s\n", __FUNCTION__);
RTC_AlarmTypeDef sAlarm;
RTC_TimeTypeDef sTime;
HAL_RTC_GetTime (hrtc, &sTime, RTC_FORMAT_BIN);
if (sTime.Minutes == 59)
{
sAlarm.AlarmTime.Hours = sTime.Hours + 1;
sAlarm.AlarmTime.Minutes = 0x0;
sAlarm.AlarmTime.Seconds = sTime.Seconds - 1;
}
else
{
sAlarm.AlarmTime.Hours = sTime.Hours;
sAlarm.AlarmTime.Minutes = sTime.Minutes + 1;
sAlarm.AlarmTime.Seconds = sTime.Seconds - 1;
}
sAlarm.Alarm = RTC_ALARM_A;
if (HAL_RTC_SetAlarm_IT (hrtc, &sAlarm, RTC_FORMAT_BIN) != HAL_OK)
{
Error_Handler ();
}
sprintf (gLCDBuf1, " A-%02d:%02d:%02d", sAlarm.AlarmTime.Hours,
sAlarm.AlarmTime.Minutes, sAlarm.AlarmTime.Seconds);
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
<% title = "#{@kpi.name} - #{@kpi.category.name} KPI Examples" -%>
<% set_page_title(title, full: true) -%>
<% content_for :head do -%>
<%= meta_description(substring_until_period(@kpi.description)) -%>
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@operately">
<meta name="twitter:title" content="<%= title %>">
<meta name="og:description" content="<%= substring_until_period(@kpi.description) %>">
<meta name="twitter:image" content="<%= image_url("summary-card.jpg") %>">
<meta name="og:image" content="<%= image_url("summary-card.jpg") %>">
<% end -%>
<div class="flex flex-row items-center space-x-2">
<ol itemscope itemtype="https://schema.org/BreadcrumbList" class="flex flex-wrap">
<li itemprop="itemListElement" itemscope
itemtype="https://schema.org/ListItem" class="mr-2">
<%= link_to(category_url(@kpi.category), class: "text-operately-blue hover:text-operately-dark-blue underline", itemprop: "item") do %>
<span itemprop="name"><%= @kpi.category.name %></span></a>
<% end %>
<meta itemprop="position" content="1" />
</li>
›
<li itemprop="itemListElement" itemscope
itemtype="https://schema.org/ListItem" class="ml-2">
<%= link_to(category_subcategory_url(@kpi.category, @kpi.subcategory), class: "text-operately-blue hover:text-operately-dark-blue underline", itemprop: "item") do %>
<span itemprop="name"><%= @kpi.subcategory.name %></span></a>
<% end %>
<meta itemprop="position" content="2" />
</li>
</ol>
</div>
<h1 class="text-4xl font-bold mt-2"><%= @kpi.name %></h1>
<p class="text-lg text-gray-500"><%= @kpi.unit.capitalize %></p>
<div class="text-gray-800">
<p class=""><%= simple_format(@kpi.description, class: "mb-4") %></p>
<% if @kpi.formula.present? -%>
<div class="mt-3">
<h2 class="text-xl font-semibold mt-4 mb-1">Formula</h2>
<p class="font-mono"><%= @kpi.formula %></p>
</div>
<% end -%>
<% if @kpi.example.present? -%>
<div class="mt-3">
<h2 class="text-xl font-semibold mt-4 mb-1">Example</h2>
<p><%= simple_format(@kpi.example, class: "mb-4") %></p>
</div>
<% end -%>
<% if logged_in? %>
<%= turbo_frame_tag(dom_id(@kpi, :votes)) do %>
<%= render "kpis/votes" %>
<% end -%>
<% else -%>
<div class="mt-4 text-base">
<%= link_to(sign_in_path(return_path: request.fullpath),
class: "bg-operately-blue text-white px-4 py-2 rounded hover:bg-operately-dark-blue transition duration-300") do %>
<span>👍 Upvote</span>
<%= kpi_upvote_count(@kpi) %>
<% end %>
</div>
<% end -%>
<div class="mt-9 text-base">
<hr/>
<h3 class="mt-3 text-lg underline decoration-dotted">Other KPIs in <%= @kpi.subcategory.name %></h3>
<ul class="list-disc list-inside mt-2 mb-2">
<% @other_kpis.each do |kpi| -%>
<li class="mb-2"><%= link_to(kpi.name, category_kpi_path(kpi.category, kpi), class: "text-operately-blue hover:text-operately-dark-blue underline") %></li>
<% end -%>
</ul>
</div>
</div>
|
<!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>
div{
height: 50px;
width: 50px;
background-color: black;
margin: 1rem;
}
.active{
border: 2px solid yellow;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
//questions -> on click of any div add a border of 2px solid of yellow color.
//1. to add an event listener we need first on which element we are going to add event listener
// and second is what is the event.
//2. add active class to that div.
//did the solution for one div
// let div = document.querySelector("div");
// div.addEventListener('click',function(){
// div.classList.add('active')
// })
//applying to all the div
//1. select all the div
let allDiv = document.querySelectorAll("div");
//2. loop through all the div
for(let i=0;i<allDiv.length;i++){
//3. apply event listener to each div
allDiv[i].addEventListener("click",function(){
//4. add active class when user clicks
//5. before adding class active remove from all the div the active class.
for(let j=0;j<allDiv.length;j++){
allDiv[j].classList.remove('active');
}
//before adding border we removed from all the div.
allDiv[i].classList.add('active');
})
}
</script>
</body>
</html>
|
// SecretToken.js
require("dotenv").config();
const jwt = require("jsonwebtoken");
module.exports.createSecretToken = (id) => {
return jwt.sign({ id }, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: 3 * 24 * 60 * 60,
});
};
// {
// "email": "[email protected]",
// "password": "testxx_password",
// "username": "Wasapito"
// }
// {
// "email": "[email protected]",
// "password": "t12345678#",
// "username": "yosoyandrey"
// }
//I make POST request http://localhost:3000/signup
// "email": "[email protected]",
// "password": "t12345678#",
// "username": "yosoyandrey"
// }
// output
// {
// "message": "User signed in successfully",
// "success": true,
// "user": {
// "email": "[email protected]",
// "username": "yosoyandrey",
// "password": "$2a$12$X/hFE3GgefKa0F8QxUrqnOwkPW2Gs7t6lbJ84ROdZr9XaXELMo3C2",
// "createdAt": "2023-10-17T16:44:34.545Z",
// "_id": "652eba0e8feddf39a3375242",
// "__v": 0
// }
// }
// Now make a POST request http://localhost:3000/login
// {
// "email": "[email protected]",
// "password": "t12345678#"
// }
// ////OUTPUT
// {
// "message": "User logged in successfully",
// "success": true
// }
//
// I completely understand your frustration, and it's a common issue,
// especially when working with environment variables and configuration files.
//Small typos or inconsistencies can lead to significant errors in your application.
// This kind of experience is part of the learning process in software development,
//and it happens to all of us. Don't be too hard on yourself; it's how you learn and
// become better at debugging and catching these kinds of issues. It's always good to
//have a fresh set of eyes or another developer review your code to catch such mistakes.
// If you have any more questions or run into any other issues, please feel free to ask. We're here to help!
// Absolutely, debugging is a crucial skill in the tech industry. It's the process of identifying
// and fixing errors or bugs in software code. Here are some reasons why debugging is essential:
// Identifying Issues: It helps you find and understand issues within your code. These issues can range
// from syntax errors to logical problems that cause unexpected behavior.
// Quality Assurance: Debugging is a fundamental part of quality assurance. By identifying and
// resolving issues, you ensure that your software works as intended and is free of defects.
// Problem Solving: Debugging teaches you problem-solving skills. You'll learn to break down
// complex issues into smaller, more manageable problems and work through them systematically.
// Optimizing Code: It's an opportunity to review and optimize your code. You might discover
// more efficient ways of achieving the same result.
// Learning: Debugging is a great way to learn. You'll learn more about the programming languages
// you're using, the tools available for debugging, and common patterns in your own mistakes.
// Collaboration: In a team environment, debugging helps team members understand each other's
// code and fix issues that arise in the development process.
// Preventing Issues: Debugging helps catch issues early in the development process, reducing the
// chances of bugs making it into the final product.
// Customer Satisfaction: By delivering bug-free software, you ensure customer satisfaction
// and avoid problems after the software is deployed.
// In summary, debugging is an essential part of software development. The ability to effectively
// debug code is a valuable skill that every developer should cultivate. It not only helps you create better software
// but also enhances your problem-solving abilities
|
# frozen_string_literal: true
# Hanles client token requests
class ClientTokensController < ApplicationController
before_action :load_organization
def new
render Page::ClientToken::NewTokenComponent.new(@organization)
end
def create
manager = ClientTokenManager.new(params[:organization_id])
if params_present? && manager.create_client_token(label: params[:label])
@client_token = manager.client_token
render(Page::ClientToken::ShowTokenComponent.new(@organization, @client_token))
else
return render_error 'Label required.' unless params_present?
render_error 'Client token could not be created.'
end
end
def destroy
manager = ClientTokenManager.new(params[:organization_id])
if manager.delete_client_token(id: params[:id])
flash[:notice] = 'Client token successfully deleted.'
else
flash[:alert] = 'Client token could not be deleted.'
end
redirect_to organization_path(params[:organization_id])
end
private
def params_present?
params[:label].present?
end
def render_error(msg)
flash.now.alert = msg
render Page::ClientToken::NewTokenComponent.new(@organization)
end
def load_organization
@organization = case ENV.fetch('ENV', nil)
when 'prod-sbx'
redirect_to root_url
when 'test'
Organization.new('6a1dbf47-825b-40f3-b81d-4a7ffbbdc270')
when 'dev'
Organization.new('78d02106-2837-4d07-8c51-8d73332aff09')
else
Organization.new(params[:organization_id])
end
end
end
|
/*
* Description: This class provides a fluent interface for building and configuring WebDriver instances for tests.
* It allows users to customize the driver initialization, maximize window, delete cookies, set timeouts,
* and navigate to a specified URL. The class uses the DriverManager and BrowserManager for driver management.
*/
package com.example.testbuilder;
import com.example.browserManager.BrowserManager;
import com.example.configManager.ConfigFactory;
import com.example.driverManager.DriverManager;
import com.example.logManager.LoggerManager;
import java.time.Duration;
public class TestBuilder {
// Public constructor
public TestBuilder() {
}
// Static method to start building a test
public static BuildTest builder() {
return new BuildTest();
}
// Nested static class representing the builder
public static class BuildTest {
// Method to append a URL fragment and navigate to the resulting URL
public static void append(String appendUrl) {
try {
String currentUrl = DriverManager.getDriverInstance().getDriver().getCurrentUrl();
String newUrl = currentUrl + appendUrl;
DriverManager.getDriverInstance().getDriver().get(newUrl);
LoggerManager.info("Appended URL Fragment: " + appendUrl);
} catch (Exception e) {
LoggerManager.error("Exception: " + e.getMessage());
}
}
// Method to initialize the WebDriver based on environment settings
public BuildTest initializeDriver() {
try {
DriverManager.getDriverInstance().setDriver(BrowserManager.getEnvironment(ConfigFactory.getConfig().getEnvMode(), ConfigFactory.getConfig().getBrowser()));
} catch (Exception e) {
LoggerManager.error("Exception: " + e.getMessage());
}
return this;
}
// Method to set whether to maximize the window
public BuildTest setMaximizeWindow(boolean maximizeWindow) {
try {
if (maximizeWindow) {
DriverManager.getDriverInstance().getDriver().manage().window().maximize();
}
} catch (Exception e) {
LoggerManager.error("Exception: " + e.getMessage());
}
return this;
}
// Method to set whether to delete cookies
public BuildTest setDeleteCookies(boolean deleteCookies) {
try {
if (!deleteCookies) {
DriverManager.getDriverInstance().getDriver().manage().deleteAllCookies();
}
} catch (Exception e) {
LoggerManager.error("Exception: " + e.getMessage());
}
return this;
}
// Method to set implicit wait time
public BuildTest setImplicitWait(int timeInSeconds) {
try {
DriverManager.getDriverInstance().getDriver().manage().timeouts().implicitlyWait(Duration.ofSeconds(timeInSeconds));
} catch (Exception e) {
LoggerManager.error("Exception: " + e.getMessage());
}
return this;
}
// Method to set page load timeout
public BuildTest setPageLoadTimeout(int timeInSeconds) {
try {
DriverManager.getDriverInstance().getDriver().manage().timeouts().pageLoadTimeout(Duration.ofSeconds(timeInSeconds));
} catch (Exception e) {
LoggerManager.error("Exception: " + e.getMessage());
}
return this;
}
// Method to set script timeout
public BuildTest setScriptTimeout(int timeInSeconds) {
try {
DriverManager.getDriverInstance().getDriver().manage().timeouts().scriptTimeout(Duration.ofSeconds(timeInSeconds));
} catch (Exception e) {
LoggerManager.error("Exception: " + e.getMessage());
}
return this;
}
// Method to navigate to the specified URL
public BuildTest url() {
try {
DriverManager.getDriverInstance().getDriver().get(ConfigFactory.getConfig().getUrl());
LoggerManager.info("Url: " + ConfigFactory.getConfig().getUrl());
} catch (Exception e) {
LoggerManager.error("Exception: " + e.getMessage());
}
return this;
}
// Method to complete the building process and return the TestBuilder instance
public TestBuilder build() {
return new TestBuilder();
}
}
}
|
import React, { useEffect, useState } from "react";
import AppForm from "../components/forms/AppForm";
import AppFormField from "../components/forms/AppFormField";
import SubmitButton from "../components/forms/SubmitButton";
import * as Yup from "yup";
import Checkbox from "../components/Checkbox";
import SocialIcon from "../components/SocialIcon";
import AppFormStatus from "../components/forms/AppFormStatus";
import { AuthServices } from "../services/auth.service";
import { useRouter } from "next/router";
import Link from "next/link";
import { NextSeo } from "next-seo";
import GoogleButton from "../components/GoogleButton";
import { useAuth } from "../context/authContext";
import PageSeo from "../components/PageSeo";
import { api } from "../utils/api";
export default function Register() {
const [googleLoading, setgoogleLoading] = useState(false);
const router = useRouter();
const { setCurrentUser } = useAuth();
const registerSchema = Yup.object().shape({
email: Yup.string().required().email("Your Email Field Is Invalid"),
password: Yup.string().min(6).required(),
username: Yup.string().required(),
});
const handleCart = () => {
const its = localStorage.getItem("cart-items");
if (!its) return;
const items = JSON.parse(its);
return Promise.all(
items.map((e) =>
api.post("/me/cart/items", {
product_id: e.product.id,
quantity: e.quantity,
variant_id: e?.variant?.id || undefined,
})
)
);
};
const handleGoogleLogin = async (token) => {
try {
await new AuthServices()
.signInWithGoogle(token)
.then(async ({ data }) => {
localStorage.setItem("token", data.access_token);
await handleCart();
setgoogleLoading(false);
setCurrentUser(data);
console.log(data);
if (router.query.redirect) {
router.push(router.query.redirect.toString());
} else {
router.push("/");
}
});
} catch (error) {
console.log(error.response.data.message);
setgoogleLoading(false);
}
};
console.log(process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID);
const handleSubmit = (
{ email, password, username }: any,
{ resetForm, setSubmitting, setErrors, setStatus }: any
) => {
new AuthServices()
.createAccount({ email, password, username })
.then(async ({ data }) => {
localStorage.setItem("token", data.access_token);
await handleCart();
setgoogleLoading(false);
setCurrentUser(data);
resetForm();
if (router.query.redirect) {
router.push(router.query.redirect.toString());
} else {
router.push("/");
}
})
.catch((error) => {
console.log(error);
setSubmitting(false);
setStatus({ error: error?.response?.data?.message });
});
};
return (
<div className="sm:py-0 py-8">
<PageSeo title={"Register"} />{" "}
<div
className={` max-w-lg py-8 md:bottom-0 md:my-0 sm:border-hidden sm:rounded-none border border-gray-200 rounded-md p-5 bg-white mx-auto`}
>
<AppForm
validationSchema={registerSchema}
onSubmit={handleSubmit}
initialValues={{ username: "", email: "", password: "" }}
>
<div>
<div className="text-center mb-7">
<h4 className="font-bold mb-2 text-gray-900 text-base">
Create your free account?
</h4>
<p className="font-semibold text-gray-500 text-sm">
Enter your information to continue
</p>
</div>
<AppFormStatus />
<div className="flex justify-between my-3">
<GoogleButton
setgoogleLoading={setgoogleLoading}
googleLoading={googleLoading}
handleGoogleLogin={handleGoogleLogin}
/>
<SocialIcon
disabled={true}
className=""
loading={false}
Icon={() => {
return (
<svg
version="1.1"
id="Capa_1"
height="16"
width="16"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
x="0px"
className="text-gray-500 fill-current mr-2 sm:mr-4"
y="0px"
viewBox="0 0 22.773 22.773"
xmlSpace="preserve"
>
<g>
<g>
<path
d="M15.769,0c0.053,0,0.106,0,0.162,0c0.13,1.606-0.483,2.806-1.228,3.675c-0.731,0.863-1.732,1.7-3.351,1.573
c-0.108-1.583,0.506-2.694,1.25-3.561C13.292,0.879,14.557,0.16,15.769,0z"
/>
<path
d="M20.67,16.716c0,0.016,0,0.03,0,0.045c-0.455,1.378-1.104,2.559-1.896,3.655c-0.723,0.995-1.609,2.334-3.191,2.334
c-1.367,0-2.275-0.879-3.676-0.903c-1.482-0.024-2.297,0.735-3.652,0.926c-0.155,0-0.31,0-0.462,0
c-0.995-0.144-1.798-0.932-2.383-1.642c-1.725-2.098-3.058-4.808-3.306-8.276c0-0.34,0-0.679,0-1.019
c0.105-2.482,1.311-4.5,2.914-5.478c0.846-0.52,2.009-0.963,3.304-0.765c0.555,0.086,1.122,0.276,1.619,0.464
c0.471,0.181,1.06,0.502,1.618,0.485c0.378-0.011,0.754-0.208,1.135-0.347c1.116-0.403,2.21-0.865,3.652-0.648
c1.733,0.262,2.963,1.032,3.723,2.22c-1.466,0.933-2.625,2.339-2.427,4.74C17.818,14.688,19.086,15.964,20.67,16.716z"
/>
</g>
</g>
</svg>
);
}}
onClick={() => {}}
>
<span className="sm:hidden mr-1 truncate">Sign with</span>
Apple
</SocialIcon>
</div>
<div className="flex justify-center or items-center text-gray-400 my-4">
<span className="text-sm mx-2">or</span>
</div>
<div>
<div className="mb-3">
<AppFormField
name="username"
placeholder="Enter Your username"
label="Username"
/>
</div>
<div className="mb-3">
<AppFormField
name="email"
placeholder="Enter Your email"
label="E-mail"
/>
</div>
<div>
<AppFormField
name="password"
type="password"
placeholder="Enter Your password"
label="Password"
/>
</div>
</div>
<div className="flex justify-between my-4">
<Checkbox label="Accept terms and conditions" id="register" />
<div />
</div>
<SubmitButton>Create Account</SubmitButton>
<div className="text-center mt-3">
<span className="text-sm font-semibold text-gray-600 mt-2">
Already have an account?
<Link href="/login">
<a className="ml-2">
<b>Login</b>
</a>
</Link>
</span>
</div>
</div>
</AppForm>
</div>
</div>
);
}
|
package ru.netology.nmedia.viewmodel
import android.app.Application
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import ru.netology.nmedia.dto.Post
import ru.netology.nmedia.model.FeedModel
import ru.netology.nmedia.repository.PostRepository
import ru.netology.nmedia.repository.PostRepositoryImpl
import ru.netology.nmedia.utils.SingleLiveEvent
import java.io.IOException
private val empty = Post(
id = 0,
content = "",
author = "",
authorAvatar = "",
published = "",
likedByMe = false
)
class PostViewModel(application: Application) : AndroidViewModel(application) {
private val repository: PostRepository = PostRepositoryImpl()
private val _data = MutableLiveData(FeedModel())
val data: LiveData<FeedModel> = _data
val edited = MutableLiveData(empty)
val toastServerError: Toast = Toast.makeText(getApplication(), "Server is not responding. Try again.", Toast.LENGTH_LONG)
val toastConverterError: Toast = Toast.makeText(getApplication(), "Conversion issue! Big problems!", Toast.LENGTH_LONG)
private val _postCreated = SingleLiveEvent<Unit>()
val postCreated: LiveData<Unit> = _postCreated
init {
loadPosts()
}
fun loadPosts() {
_data.value = FeedModel(loading = true)
repository.getAllAsync(object : PostRepository.Callback<List<Post>> {
override fun onSuccess(posts: List<Post>) {
_data.value = FeedModel(posts = posts, empty = posts.isEmpty())
}
override fun onError(e: Exception) {
if (e is IOException) {
_data.value = FeedModel(error = true)
toastServerError.show()
} else {
toastConverterError.show()
}
}
})
}
fun likeById(id: Long) {
val oldPosts = _data.value
val oldPost = oldPosts?.posts?.find { it.id == id }
repository.likeByIdAsync(id, oldPost?.likedByMe ?: error("Post not found"), object : PostRepository.Callback<Post> {
override fun onSuccess(posts: Post) {
val updatedPosts = _data.value?.posts?.map {
if (it.id == posts.id) {
posts
} else {
it
}
}.orEmpty()
_data.value = _data.value?.copy(posts = updatedPosts)
}
override fun onError(e: Exception) {
toastServerError.show()
}
})
}
fun shareById(id: Long) = repository.shareById(id)
fun viewById(id: Long) = repository.viewById(id)
fun save() {
_data.value = FeedModel(refreshing = true)
edited.value?.let {
repository.save(it, object : PostRepository.Callback<Post> {
override fun onSuccess(posts: Post) {
edited.value = empty
_postCreated.value = Unit
}
override fun onError(e: Exception) {
_data.value = FeedModel(error = true)
toastServerError.show()
}
})
}
}
fun edit(post: Post) {
edited.value = post
}
fun changeContent(content: String) {
val text = content.trim()
if (edited.value?.content != text) {
edited.value = edited.value?.copy(content = text)
}
}
fun removeById(id: Long) {
_data.value = FeedModel(refreshing = true)
repository.removeById(id, object : PostRepository.Callback<Unit> {
val oldPosts = _data.value
override fun onSuccess(posts: Unit) {
_data.value =
oldPosts?.copy(
posts = oldPosts.posts.filter {
it.id != id
}
)
}
override fun onError(e: Exception) {
toastServerError.show()
_data.value = oldPosts
_data.value = FeedModel(error = true)
}
})
}
fun clear() {
edited.value = empty
}
}
|
#ifndef MUSIC_H
#define MUSIC_H
#define HALF_NOTE '2'
#define QUARTER_NOTE '3'
#define EIGHTH_NOTE '4'
#define SIXTEENTH_NOTE '5'
#define OCTAVE_2 '2'
#define OCTAVE_3 '3'
#define OCTAVE_5 '5'
#define OCTAVE_6 '6'
/*
Module for defining, getting, parsing and outputting musical input from the user
through the serial port to the speakers.
Gets a BPM and then successive notes inputted by the user (hence using serial.h)
defined by
--note, accidental, length, octave--
to form a tune. Module then plays each note by toggling on and off the speaker
at a certain frequency (according to the pitch, accidentals and octaves) using
output compare Pin output function of the HCS12's timer module (hence uses timer.h).
Parses the notes as they are iterated to for playing, and are skipped if invalid.
*/
//DISPLAYING THE TIME FOR A SONG TO BE COMPLETED!
//find the next note, parse it, once parsed, calculate time using function and add to counter
//General/main music playing function:
void music_player(void);
//Checks the validity of every aspect for a given note - pitch, accidental, duration, octave
int parse_note(char pitch, char accidental, char duration, char octave);
//plays the single note of using timer interrupts and output pin toggling (essentially interrupt trigger and wait function)
void play_note(int frequency, long int length_mcs);
//Gets the frequency of a note corresponding to its pitch, accidental and octave
int get_note_frequency(char pitch, char accidental, char octave);
//Gets the length (in microseconds) of a note given its time signature ('duration') and the tune's BPM
long int get_note_length_mcs(int bpm, char duration);
//finds and updates player to the next note to be played upon a parsing failure for the current note
//enables the function to skip the bad note and try and find the next valid one
int find_next_note(char *tune, int tune_elements, int *i);
//removes spaces and commas from the input, giving sequential note parameter chars only
char *str_to_ch_arr(char *music_input, int *note_elements);
//adds up the duration of all the valid notes in a tune writes total time to serial
//void display_tune_time(char *tune, int bpm, int num_elements);
//converts an integer into a character array of its digits
//char *convert_to_digits_str(long int num_to_convert);
//interrupt service routine for toggling the speaker using the timer
__interrupt void music_isr(void);
#endif
|
#ifndef CAMERA_H
#define CAMERA_H
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vector>
enum Camera_Movement {
FWD,
BCK,
LT,
RT
};
const float YAW = -90.f;
const float PITCH = 0.f;
const float SPEED = 2.5;
const float SENSITIVITY = 0.1f;
const float ZOOM = 45.f;
class Camera
{
public:
glm::vec3 Position;
glm::vec3 Front;
glm::vec3 Up;
glm::vec3 Right;
glm::vec3 WorldUp;
float Yaw;
float Pitch;
float MovementSpeed;
float MouseSensitivity;
float Zoom;
Camera(glm::vec3 position = glm::vec3(0.f, 0.f, 0.f), glm::vec3 up = glm::vec3(0.f, 1.f, 0.f), float yaw = YAW, float pitch = PITCH)
: Front(glm::vec3(0.f, 0.f, -1.f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
{
Position = position;
WorldUp = up;
Yaw = yaw;
Pitch = pitch;
updateCameraVectors();
}
Camera(float posX, float posY,float posZ, float upX, float upY, float upZ, float yaw, float pitch)
: Front(glm::vec3(0.f, 0.f, -1.f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
{
Position = glm::vec3(posX, posY, posZ);
WorldUp = glm::vec3(upX, upY, upZ);
Yaw = yaw;
Pitch = pitch;
updateCameraVectors();
}
glm::mat4 GetViewMatrix()
{
return glm::lookAt(Position, Position + Front, Up);
}
void ProcessKeyboard(Camera_Movement direction, float deltaTime)
{
float velocity = MovementSpeed * deltaTime;
if (direction == FWD)
{
Position += Front * velocity;
}
else if (direction == BCK)
{
Position -= Front * velocity;
}
else if (direction == LT)
{
Position -= Right * velocity;
}
else if (direction == RT)
{
Position += Right * velocity;
}
}
void ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch = true)
{
xoffset *= MouseSensitivity;
yoffset *= MouseSensitivity;
Yaw += xoffset;
Pitch += yoffset;
if (constrainPitch)
{
if (Pitch > 89.f)
{
Pitch = 89.f;
}
else if (Pitch < -89.f)
{
Pitch = -89.f;
}
}
updateCameraVectors();
}
void ProcessMouseScroll(float yoffset)
{
Zoom -= (float)yoffset;
if (Zoom < 1.f)
{
Zoom = 1.f;
}
else if (Zoom > 45.f)
{
Zoom = 45.f;
}
}
private:
void updateCameraVectors()
{
glm::vec3 front;
front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
front.y = sin(glm::radians(Pitch));
front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));
Front = glm::normalize(front);
Right = glm::normalize(glm::cross(Front, WorldUp));//Front cant be parrallerl to WorldUp
Up = glm::normalize(glm::cross(Right, Front));
}
};
#endif
|
import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { Form } from '../../shared/interfaces/form';
import { FetchService } from '../../core/services/fetch.service';
import { FormService } from '../../shared/services/form.service';
import { Filter } from '../../shared/interfaces/filter';
import { filter, take } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { MatSnackBar } from '@angular/material/snack-bar';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.scss'],
providers: [FetchService],
encapsulation: ViewEncapsulation.None,
})
export class ListComponent implements OnInit, OnDestroy {
isAdmin: boolean = localStorage.getItem('role') === 'admin';
forms: Form[] = [];
inProcess = false;
filter: Filter = {};
form: Form;
fetchSubscription: Subscription;
formSubscription: Subscription;
filterSubscription: Subscription;
deleteSubscription: Subscription;
constructor(
private fetchService: FetchService,
private formService: FormService,
private snackBar: MatSnackBar
) {}
ngOnInit() {
this.formSubscription = this.formService.getForm().subscribe((form) => {
this.form = form;
});
this.filterSubscription = this.formService
.getData()
.subscribe((filterData) => {
this.filter = filterData;
this.getFormsFromServer();
});
this.formService.sendData(this.filter);
}
ngOnDestroy() {
this.formSubscription.unsubscribe();
this.filterSubscription.unsubscribe();
if (this.fetchSubscription) {
this.fetchSubscription.unsubscribe();
}
if (this.deleteSubscription) {
this.deleteSubscription.unsubscribe();
}
}
getFormsFromServer() {
this.inProcess = true;
const request = localStorage.getItem('jwt')
? this.fetchService.findForms(this.filter)
: this.fetchService.findPublicForms(this.filter);
this.fetchSubscription = request.pipe(take(1)).subscribe(
(forms) => {
this.forms = forms;
if (!this.form) {
this.selectForm(forms[0]);
}
if (!forms) {
this.selectForm(undefined);
}
},
(err) => console.log(err),
() => (this.inProcess = false)
);
}
selectForm(form) {
this.formService.setForm(form);
}
deleteItem(id: number) {
this.inProcess = true;
this.deleteSubscription = this.fetchService
.deleteForm(id)
.pipe(take(1))
.subscribe(
() => {
this.getFormsFromServer();
this.snackBar.open('The form have been deleted', 'Close', {
duration: 5000,
});
},
(err) => {
this.snackBar.open('The form have been deleted', 'Close', {
duration: 5000,
});
}
);
}
}
|
import React, { useContext, useState } from 'react';
import toast from 'react-hot-toast';
import { FaGoogle, FaGithub, FaEye, FaEyeSlash } from 'react-icons/fa';
import { useLocation, useNavigate } from 'react-router-dom';
import { AuthContext } from '../../context/AuthProvider';
const Login = () => {
const [passStatus, setPassStatus] = useState(false)
const { LoginUser } = useContext(AuthContext)
const navigate = useNavigate()
const location = useLocation()
const from = location.state?.from?.pathname || "/"
const handleLogin = event => {
event.preventDefault()
const form = event.target
const email = form.email.value
const password = form.password.value
LoginUser(email, password)
.then(res => {
const user = res.user
if (user.uid) {
toast.success('Login successfully')
navigate(from, { replace: true })
}
})
.catch(err => {
toast.error(err.message)
console.log(err)
})
}
return (
<div className='min-h-screen grid place-items-center bg-gradient-to-r from-indigo-400 via-purple-500 to-pink-500'>
<div className='bg-white w-[400px] h-[400px] p-5'>
<form onSubmit={handleLogin} className='my-5'>
<h3 className='text-center my-5 text-2xl font-bold'>Login</h3>
<input required name='email' className='mb-3 rounded-lg text-xl px-5 py-2 w-full bg-white text-black border-solid border-2 border-green-600 focus:outline-none ' type="email" placeholder='Your Email' />
<div className='relative mb-3'>
<input required name='password' className='rounded-lg text-xl px-5 py-2 w-full bg-white text-black border-solid border-2 border-green-600 focus:outline-none ' type={passStatus ? 'text' : 'password'} placeholder='Enter Password' />
{
passStatus ?
<FaEye onClick={() => setPassStatus(!passStatus)} className='w-7 h-7 absolute top-1/4 right-2 cursor-pointer'></FaEye>
:
<FaEyeSlash onClick={() => setPassStatus(!passStatus)} className='w-7 h-7 absolute top-1/4 right-2 cursor-pointer'></FaEyeSlash>
}
</div>
<button className='bg-gradient-to-r from-green-400 to-blue-500 hover:from-pink-500 hover:to-yellow-500 px-12 py-4 rounded font-semibold text-xl hover:text-white block mx-auto my-4'>Login</button>
</form>
<hr />
<div className='flex justify-center mt-5'>
<FaGoogle className='w-12 h-12 p-2 bg-gray-300 hover:bg-purple-500 cursor-pointer rounded-full mr-3'></FaGoogle>
<FaGithub className='w-12 h-12 p-2 bg-gray-300 hover:bg-pink-600 cursor-pointer rounded-full'></FaGithub>
</div>
</div>
</div>
);
};
export default Login;
|
/* This file is part of BlosSOM.
*
* Copyright (C) 2021 Sona Molnarova
*
* BlosSOM is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* BlosSOM 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
* BlosSOM. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef WRAPPER_GLFW_H
#define WRAPPER_GLFW_H
#include "input_data.h"
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <glad/glad.h>
#include <string>
#include "frame_stats.h"
/**
* @brief Wrapper of the Glfw library.
*
* It abstracts window creation, deletition and handles callbacks.
*
*/
class GlfwWrapper
{
public:
GlfwWrapper();
~GlfwWrapper();
bool init(const std::string &window_name, InputData &input);
bool window_should_close();
void end_frame(FrameStats &fs);
void destroy();
GLFWwindow *window;
private:
static void error_callback(int error, const char *description);
static void framebuffer_size_callback(GLFWwindow *window,
int width,
int height);
static void key_callback(GLFWwindow *window,
int key,
int scancode,
int action,
int mods);
static void scroll_callback(GLFWwindow *window,
double xoffset,
double yoffset);
static void mouse_button_callback(GLFWwindow *window,
int button,
int action,
int mods);
static void cursor_position_callback(GLFWwindow *window,
double xpos,
double ypos);
};
#endif // WRAPPER_GLFW_H
|
/* eslint-disable @typescript-eslint/no-empty-interface */
/* eslint-disable @typescript-eslint/no-namespace */
/**
* @see https://www.jacobparis.com/content/type-safe-env
*/
import { z } from 'zod'
import { logger } from '~/utils/logger'
import type { TypeOf } from 'zod'
const schema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']),
SQLITE_FILE: z.string(),
})
declare global {
namespace NodeJS {
interface ProcessEnv extends TypeOf<typeof schema> {}
}
}
try {
schema.parse(process.env)
} catch (err) {
if (err instanceof z.ZodError) {
logger.fatal(
{ err: err.flatten().fieldErrors },
'Missing environment variables',
)
process.exit(1)
} else {
logger.fatal(err, 'Unexpected error on parse environment variables')
process.exit(1)
}
}
|
/** @format */
import React from "react";
import { useNavigate } from "react-router";
import { IonIcon } from "@ionic/react";
import { arrowBackOutline } from "ionicons/icons";
interface BackButtonProps {
onClick?: (val: any) => void;
icon?: string;
}
const BackButton: React.FC<BackButtonProps> = ({ onClick, icon }) => {
const navigate = useNavigate();
const goBack = () => {
navigate(-1);
};
return (
<div
onClick={onClick ? onClick : goBack}
className="flex justify-center items-center p-2 rounded-full hover:bg-slate-200 dark:hover:bg-Dark300 cursor-pointer"
>
<IonIcon icon={icon ? icon : arrowBackOutline} />
</div>
);
};
export default BackButton;
|
# Pasos para crear nuestra lib
## Vite
- "rápido"
- rollup
- Muchas tecnologías / frameworks
```
npm create vite@latest
yarn create vite@latest
```
## Tree-shaking
> Live code inclusion
Es una forma de "eliminar" el código muerto / no utilizado
```
import Button from 'awesome-lib'
import {Button} from 'awesome-lib'
import * as AwesomeLib from 'awesome-lib'
```
## Todo paquete que se respeta
- Eslint .eslintrc --> npm init @eslint/config (seguir pasos)
- Prettier .prettierrc --> yarn add -D prettier (https://prettier.io/docs/en/plugins)
- Husky + commitlint (commits semánticos)
- Versionado semántico
- Tests
- Readme
## Dependencias a instalar
```
yarn add -D @types/node vite-plugin-dts
```
## Vite plugin dts
Cuando queremos compartir librerias o paquetes que se escribieron en TS se necesita incluir archivos de definición
(.d.ts) de forma separada a nuestro bundle (index.js, bundle.js) esto nos ayudará a ver los tipos de nuestra función que estemos consumiendo de nuestro paquete.
index.d.ts: Archivos de definición de tipos
## Bundling
Para crear una aplicación que sea distribuible se deben realizar ciertas configuraciones en el bundle final
```typescript
//vite.config.ts
import { resolve } from "path";
import { defineConfig } from "vite";
import dts from "vite-plugin-dts";
export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, "src/index.ts"),
name: "my-lib",
fileName: "my-lib",
},
},
plugins: [dts({ outDir: "dist" })],
});
```
```json
// package json
// remover private:true
"main": "./dist/my-lib.umd.cjs",
"exports": {
".": {
"import": "./dist/my-lib.js",
"require": "./dist/my-lib.umd.cjs"
}
},
"publishConfig": {
"registry": "https://registry.npmjs.org"
},
"files": ["dist"],
```
```
npm init @eslint/config
yarn add -D prettier
```
.prettierrc
```
{
"trailingComma": "none",
"tabWidth": 2,
"semi": false,
"singleQuote": true
}
```
Extender prettier del eslint base typescript:
https://www.npmjs.com/package/eslint-config-standard-typescript-prettier
## Husky
Una herramienta que te ayuda a correr scripts en diferentes estadios de la aplicacion
Para instalar o correr el programa husky-init el proyecto necesita ser un repo
```
git init
npx husky-init && yarn o bien npm install
npx husky add .husky/pre-commit "npm run lint"
```
- pre-commit (ejecutar scripts antes de efectuar un commit)
- pre-push (ejecutar scripts antes de hacer un push)
Commitlint documentation:
https://github.com/conventional-changelog/commitlint
```bash
yarn add -D @commitlint/config-conventional @commitlint/cli
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.cjs
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit ${1}'
```
### Path Alias
```
yarn add -D vite-tsconfig-paths // dtypes
yarn add -D vitest
```
## Utilidades
## Check
- isNullOrUndefined: Es una función que recibe un valor X de tipo unknown y devolvemos un booleano (predicado): True si el value es nulo o undefined, false en caso contrario
- isObject: Es una función que recibe un valor X unkwnown y devuleve un booleano true si el typeOf es object
## String
- Includes -> Una función que recibe un string y un value a buscar dentro de ese string. Devuelve un booleano si el valor es encontrado en el string
- Capitalize (hola -> Hola)
- reverse
- equalsIgnoreCase: Es una función que recibe 2 strings y compara si son iguales (aplicando lowercase)
## Arrays
- arraylable: Recibe un argumento (generico o nulo). La función devuelve el mismo array value si es un array válido y si el elemento es un elemento no arrayleable devuelve un array []
- sum
- sumBy
- getById
- getIndexById
- removeItem/s
## Utils
- canUseDom: Devuelve true si puede utilizarse el dom (window)
### Timing
- debounce
- throttle
### Pendientes de la lib
- Funciones de timing
- Funciones de logging
- Funciones de strings
- Excluir test de la build
- Flujo de Testing en commit
- Yalc
- YAML en github actions
- Mutation testing?
|
document.addEventListener("DOMContentLoaded", () =>{
fetchData()
})
const fetchData = async() => {
try {
const res = await fetch("api.json")
const data = await res.json()
// console.log(data);
pintarProductos(data)
detectarBoton(data)
} catch (error) {
console.log(error);
}
}
const contenedorProductos = document.querySelector("#contenedor-productos")
const pintarProductos = (data) => {
const template = document.querySelector("#template-productos").content
const fragment = document.createDocumentFragment()
// console.log(template)
data.forEach(producto => {
// console.log(producto);
template.querySelector("img").setAttribute("src",producto.thumbnailUrl);
template.querySelector("h5").textContent = producto.title;
template.querySelector("p span").textContent =producto.precio;
template.querySelector("button").dataset.id = producto.id
const clone = template.cloneNode(true)
fragment.appendChild(clone)
})
contenedorProductos.appendChild(fragment)
}
let carrito = {}
const detectarBoton = (data) =>{
const botones = document.querySelectorAll(".card button")
botones.forEach(btn =>{
btn.addEventListener("click", () => {
// console.log(btn.dataset.id);
const producto = data.find(item => item.id === parseInt(btn.dataset.id))
producto.cantidad = 1
if(carrito.hasOwnProperty(producto.id)){
producto.cantidad = carrito[producto.id].cantidad +1
}
carrito[producto.id] = {...producto}
// console.log(carrito);
pintarCarrito()
})
})
}
const items = document.querySelector("#items")
const pintarCarrito = () => {
const template = document.querySelector("#template-carrito").content
const fragment = document.createDocumentFragment()
//pendiente innerhtml
items.innerHTML = ""
Object.values(carrito).forEach(producto => {
// console.log(producto);
template.querySelector("th").textContent = producto.id
template.querySelectorAll("td")[0].textContent = producto.title
template.querySelectorAll("td")[1].textContent = producto.cantidad
template.querySelector("span").textContent = producto.precio * producto.cantidad
template.querySelector(".btn-info").dataset.id = producto.id
template.querySelector(".btn-danger").dataset.id = producto.id
const clone = template.cloneNode(true)
fragment.appendChild(clone)
})
items.appendChild(fragment)
pintarFooter()
accionBotones()
}
const footer = document.querySelector("#footer-carrito")
const pintarFooter = () =>{
footer.innerHTML = ""
if(Object.keys(carrito).length === 0){
footer.innerHTML = `
<th scope="row" colspan="5">Carrito vacío!</th>
`
return
}
const template = document.querySelector("#template-footer").content
const fragment = document.createDocumentFragment()
//sumar cantidad y si¿umar totales
const nCantidad = Object.values(carrito).reduce((acc, {cantidad}) => acc + cantidad, 0)
const nPrecio = Object.values(carrito).reduce((acc,{cantidad,precio}) => acc + cantidad * precio ,0)
// console.log(nPrecio);
template.querySelectorAll("td")[0].textContent = nCantidad
template.querySelector("span").textContent = nPrecio
const clone = template.cloneNode(true)
fragment.appendChild(clone)
footer.appendChild(fragment)
const boton = document.querySelector("#vaciar-carrito")
boton.addEventListener("click", () => {
carrito = {}
pintarCarrito()
})
}
const accionBotones = () =>{
const botonesAgregar = document.querySelectorAll("#items .btn-info")
const botonesEliminar = document.querySelectorAll("#items .btn-danger")
botonesAgregar.forEach(btn => {
btn.addEventListener("click", () => {
// console.log("agregando");
const producto = carrito[btn.dataset.id]
producto.cantidad ++
carrito[btn.dataset.id] = {...producto}
pintarCarrito()
})
})
botonesEliminar.forEach(btn => {
btn.addEventListener("click", () => {
// console.log("eliminado");
const producto = carrito[btn.dataset.id]
producto.cantidad --
if(producto.cantidad === 0){
delete carrito[btn.dataset.id]
}else{
carrito[btn.dataset.id] = {...producto}
}
pintarCarrito()
})
})
}
|
Spring Security tutorial steps
- 인증체계 없는 앱
- 보안처리를 위한 기본환경 준비
- 단계적 보안처리
- 서비스 레이어(메소드 레벨) 보안처리
- 화면 레벨의 보안처리
- 리멤버미
- 메소드레벨 추가 보안방식 (jsr-250호환용)
- access rule
인증체계 없는 앱
1. web.xml 고치기
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Spring Security Tutorial Application</display-name>
<!--
- Location of the XML file that defines the root application context
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext-business.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
- Provides core MVC application controller. See bank-servlet.xml.
-->
<servlet>
<servlet-name>bank</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>bank</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
2. 확인
http://localhost:8080/listAccounts.html
보안처리를 위한 기본환경 준비
1. web.xml에 security-app-context.xml 추가
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext-business.xml
/WEB-INF/security-app-context.xml
</param-value>
</context-param>
2. web.xml에 스프링 보안 필터추가
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3. security-app-context.xml 파일 설정
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http use-expressions="true">
<intercept-url pattern="/**" access="permitAll" />
<form-login />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="rod" password="koala" authorities="supervisor, teller, user" />
<user name="dianne" password="emu" authorities="teller, user" />
<user name="scott" password="wombat" authorities="user" />
<user name="peter" password="opal" authorities="user" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
4. 모든 URL에 접근 가능한지 확인
단계적 보안처리
첫 페이지 : 누구나
/secure :인증처리된 유저만
/secure/extreme: 관리자만
accountList.html 페이지 : 인증처리된 유저만
- teller, superviosor 잔고 수정가능
- user는 보기만 가능
1. http 블럭에 pattern 추가
<http use-expressions="true">
<intercept-url pattern="/index.jsp" access="permitAll" />
<intercept-url pattern="/secure/**" access="isAuthenticated()" />
<intercept-url pattern="/secure/extreme/**" access="hasRole('supervisor')" />
<intercept-url pattern="/listAccounts.html" access="isAuthenticated()" />
<intercept-url pattern="/post.html" access="hasAnyRole('supervisor','teller')" />
<intercept-url pattern="/**" access="denyAll" />
<form-login />
</http>
2. 접근확인
3. 우선순위에 맞게 블럭 패턴 조정
4. 필터 제외 설정
<http pattern="/static/**" security="none" />
5. logout 제외 설정 <http use-expressions="true"> 안에
<logout />
http://localhost:8080/j_spring_security_logout
6. 패스워드 처리
<beans:bean id="encoder"
class="org.springframework.security.crypto.password.StandardPasswordEncoder"/>
<authentication-manager>
<authentication-provider>
<password-encoder ref="encoder" />
<user-service>
<user name="rod"
password="864acff7515e4e419d4266e474ea14a889dce340784038b704a30453e01245eed374f881f3df8e1e"
authorities="supervisor, teller, user" />
<user name="dianne"
password="9992e040d32b6a688ff45b6e53fd0f5f1689c754ecf638cce5f09aa57a68be3c6dae699091e58324"
authorities="teller, user" />
<user name="scott"
password="ab8d9744fa4dd5cee6eb692406fd29564267bad7c606837a70c44583b72e5684ec5f55c9dea869a5"
authorities="user" />
<user name="peter"
password="e446d30fcb00dc48d7e9fac49c2fec6a945171702e6822e1ec48f1ac1407902759fe30ed66a068df"
authorities="user" />
</user-service>
</authentication-provider>
</authentication-manager>
서비스 레이어(메소드 레벨) 보안처리
1. <http> 항목 위에 global-method-security 추가
<global-method-security pre-post-annotations="enabled" />
2. BankService 인터페이스 확인 및 수정
화면 레벨의 보안처리
1.방식#1
<sec:authorize url="/account/home.do">
...
</sec:authorize>
2.방식#2
<sec:authorize access="hasRole('ROLE_USER') and fullyAuthenticated">
...
</sec:authorize>
리멤버미
========
<remember-me/>
메소드레벨 추가 보안방식 (jsr-250호환용)
<global-method-security jsr250-annotations="enabled"/>
@RolesAllowed("ROLE_USER", "ROLE_ADMIN")
public...
access rule
permitAll
denyAll
anonymous
authenticated
rememberMe
fullyAuthenticated
SpEL method 방식
hasIpAddress(ipAddress)
hasRole(role)
hasAnyRole(role)
추가 확인할 내용
- SpringEL
- deny 등의 페이지 커스터마이징
|
const mongoose = require("mongoose");
const Photo = require("../models/Photo");
const User = require("../models/User");
// Insert a photo, with an user related to it
const insertPhoto = async (req, res) => {
const { title } = req.body;
const image = req.file.filename;
const reqUser = req.user;
const user = await User.findById(reqUser._id);
// Create a photo
const newPhoto = await Photo.create({
image,
title,
userId: user._id,
userName: user.name,
});
// If photo was created successfully, return data
if (!newPhoto) {
res.status(422).json({
errors: ["Houve um problema, por favor tente novamente mais tarde."],
});
return;
}
res.status(201).json(newPhoto);
};
// Remove a photo from DB
const deletePhoto = async (req, res) => {
const { id } = req.params;
const reqUser = req.user;
try {
const photo = await Photo.findById(id); // O Mongoose pode converter o ID automaticamente
if (!photo) {
return res.status(404).json({
errors: ["Foto não encontrada!"],
});
}
// Check if photo belongs to user
if (!photo.userId.equals(reqUser._id)) {
return res.status(422).json({
errors: ["Ocorreu um erro, por favor tente novamente mais tarde."],
});
}
await Photo.findByIdAndDelete(photo._id);
return res
.status(200)
.json({ id: photo._id, message: "Foto excluída com sucesso." });
} catch (error) {
return res
.status(500)
.json({ errors: ["Ocorreu um erro ao excluir a foto."] });
}
};
// Get all photos
const getAllPhotos = async (req, res) => {
const photos = await Photo.find({})
.sort([["createdAt", -1]])
.exec();
return res.status(200).json(photos);
};
// Get user photos
const getUserPhotos = async (req, res) => {
const { id } = req.params;
const photos = await Photo.find({ userId: id })
.sort([["createdAt", -1]])
.exec();
return res.status(200).json(photos);
};
// Get photo by id
const getPhotoById = async (req, res) => {
const { id } = req.params;
try {
const photo = await Photo.findById(id); // O Mongoose pode converter o ID automaticamente
// Check if photo exists
if (!photo) {
return res.status(404).json({ errors: ["Foto não encontrada."] });
}
return res.status(200).json(photo);
} catch (error) {
return res
.status(500)
.json({ errors: ["Ocorreu um erro ao buscar a foto."] });
}
};
// Update a photo
const updatePhoto = async (req, res) => {
const { id } = req.params;
const { title } = req.body;
const reqUser = req.user;
const photo = await Photo.findById(id);
// Check if photo exists
if (!photo) {
res.status(404).json({ errors: ["Foto não encontrada"] });
return;
}
// Check if photo belongs to user
if (!photo.userId.equals(reqUser._id)) {
res.status(422).json({
errors: ["Ocorreu um erro, por favor tente novamente mais tarde."],
});
return;
}
if (title) {
photo.title = title;
}
await photo.save();
res.status(200).json({ photo, message: "Foto atualizada com sucesso!" });
};
// Like functionality
const likePhoto = async (req, res) => {
const { id } = req.params;
const reqUser = req.user;
try {
const photo = await Photo.findById(id);
// Check if photo exists
if (!photo) {
res.status(404).json({ errors: ["Foto não encontrada"] });
return;
}
// Check if user already liked the photo
if (photo.likes.includes(reqUser._id)) {
res.status(422).json({ errors: ["Você já curtiu a foto."] });
return;
}
// Put user id in likes array
photo.likes.push(reqUser._id);
photo.save();
res.status(200).json({
photoId: id,
userId: reqUser._id,
message: "A foto foi curtida.",
});
} catch (error) {
res.status(422).json({
errors: ["Ocorreu um erro, por favor tente novamente mais tarde."],
});
return;
}
};
// Comment functionality
const commentPhoto = async (req, res) => {
const { id } = req.params;
const { comment } = req.body;
const reqUser = req.user;
const user = await User.findById(reqUser._id);
const photo = await Photo.findById(id);
// Check if photo exists
if (!photo) {
res.status(404).json({ errors: ["Foto não encontrada"] });
}
// Put comment int the array comments
const userComment = {
comment,
userName: user.name,
userImage: user.profileImage,
userId: user._id
};
photo.comments.push(userComment)
await photo.save()
res.status(200).json({
comment: userComment,
message: "O comentário foi adicionado com sucesso!"
})
};
// search photos by title
const searchPhotos = async(req, res) => {
const {q} = req.query
const photos = await Photo.find({title: new RegExp(q, "i")}).exec()
res.status(200).json(photos);
}
module.exports = {
insertPhoto,
deletePhoto,
getAllPhotos,
getUserPhotos,
getPhotoById,
updatePhoto,
likePhoto,
commentPhoto,
searchPhotos,
};
|
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
unordered_map<string, int> countWords(const vector<string>& words) {
unordered_map<string, int> word_count;
for (const string& word : words) {
word_count[word]++;
}
return word_count;
}
// Function to print the top three most frequent words
void printTopThree(const unordered_map<string, int>& word_count) {
vector<pair<string, int>> word_count_vector(word_count.begin(), word_count.end());
sort(word_count_vector.begin(), word_count_vector.end(), [](const pair<string, int>& a, const pair<string, int>& b) {
return a.second > b.second;
});
/*
cout << "Top Three Words:" << endl;
for (int i = 0; i < 3 && i < word_count_vector.size(); ++i) {
cout << word_count_vector[i].first << ": " << word_count_vector[i].second << endl;
}*/
}
// Function to remove stop words from the vector of words
vector<string> removeStopWords(const vector<string>& words) {
unordered_set<string> stop_words = {"i", "my", "that", "this", "a", "an", "the", "in", "on", "at", "to", "of", "by", "I", "you", "he", "she", "it", "we", "they", "is", "are", "am", "was", "were", "be", "been", "being", "have", "has", "had", "do", "does", "did", "will", "shall", "would", "should", "can", "could", "may", "might", "must", "here", "there", "where", "when", "why", "how", "what", "which", "who", "whom", "whose", "and", "or", "but", "not", "no", "yes", "so", "if", "then", "else", "when", "while", "until", "before", "after", "because", "since", "although", "though", "even", "as", "if", "whether", "either", "neither", "both", "each", "every", "any", "all", "some", "most", "many", "few", "several", "such", "own", "other", "another", "more", "less", "least", "only", "very", "much", "more", "most", "little", "least", "fewest", "many", "few", "much"};
vector<string> filtered_words;
for (const string& word : words) {
// Lowercase the word
string lowercase_word = word;
transform(lowercase_word.begin(), lowercase_word.end(), lowercase_word.begin(), ::tolower);
if (stop_words.find(lowercase_word) == stop_words.end()) {
filtered_words.push_back(word);
}
}
return filtered_words;
}
int main() {
string directory_path = "../Node_Examples/Pipeline/text_data/";
// Check if the directory exists
if (!fs::exists(directory_path) || !fs::is_directory(directory_path)) {
cout << "Invalid directory path." << endl;
return 1;
}
// Iterate over each file in the directory
for (const auto& entry : fs::directory_iterator(directory_path)) {
if (fs::is_regular_file(entry)) {
string file_name = entry.path();
//cout << "Processing file: " << file_name << endl;
// Get vector of words
vector<string> words;
ifstream file(file_name);
string word;
while (file >> word) {
words.push_back(word);
}
// Remove stop words
vector<string> filtered_words = removeStopWords(words);
// Count words
unordered_map<string, int> word_count = countWords(filtered_words);
// Print top three words
printTopThree(word_count);
}
}
return 0;
}
|
//Campos em classe
class User {
name!: string;
age!: number;
}
const matheus = new User();
matheus.name = "Matheus";
//Constructor
class NewUser {
name;
age;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const joao = new NewUser("João", 22);
console.log(joao);
//Campos readonly em classes
class Car {
name;
readonly wheels = 4;
constructor(name: string) {
this.name = name;
}
}
const fusca = new Car("Fusca");
console.log(fusca);
//Herança e Super
class Machine {
name;
constructor(name: string) {
this.name = name;
}
}
const trator = new Machine("Trator");
class KillerMachine extends Machine {
guns;
constructor(name: string, guns: number) {
super(name);
this.guns = guns;
}
}
const destroyer = new KillerMachine("Destroyer", 4);
console.log(trator);
console.log(destroyer);
//Métodos
class Dwarf {
name;
constructor(name: string) {
this.name = name;
}
greeting() {
console.log("Hey, stranger!");
}
}
const jimmy = new Dwarf("Jimmy");
console.log(jimmy.name);
jimmy.greeting();
//This
class Truck {
model;
hp;
constructor(model: string, hp: number) {
this.model = model;
this.hp = hp;
}
showDetails() {
console.log(
`Caminhão do modelo: ${this.model} e que tem ${this.hp} cavalos de potência`
);
}
}
const volvo = new Truck("Volvo", 500);
volvo.showDetails();
//Getters
class Person {
name;
surname;
constructor(name: string, surname: string) {
this.name = name;
this.surname = surname;
}
get fullName() {
return this.name + " " + this.surname;
}
}
const matheus1 = new Person("Matheus", "Oliveira");
console.log(matheus1.name);
console.log(matheus1.fullName);
//Setters
class Coords {
x!: number;
y!: number;
set fillX(x: number) {
if (x === 0) {
return;
}
this.x = x;
console.log("X inserido com sucesso");
}
set fillY(y: number) {
if (y === 0) {
return;
}
this.y = y;
console.log("Y inserido com sucesso");
}
get getCoords() {
return `X: ${this.x} e Y: ${this.y}`;
}
}
const myCoords = new Coords();
myCoords.fillX = 15;
myCoords.fillY = 90;
console.log(myCoords.getCoords);
//Herança de interfaces
interface showTitle {
itemTitle(): string;
}
class blogPost implements showTitle {
title;
constructor(title: string) {
this.title = title;
}
itemTitle() {
return `O título do post é: ${this.title}`;
}
}
const myPost = new blogPost("Hello, world");
console.log(myPost.itemTitle());
class TestingInterface implements showTitle {
title;
constructor(title: string) {
this.title = title;
}
itemTitle() {
return `O tútlo é: ${this.title}`;
}
}
//Override de métodos
class Base {
someMethod() {
console.log("Alguma coisa");
}
}
class Nova extends Base {
someMethod() {
console.log("Testando outra coisa");
}
}
const myObject = new Nova();
myObject.someMethod();
//Visibilidade: Public
class C {
x = 10;
}
const cInstance = new C();
console.log(cInstance.x);
//Visibilidade: Protected
class E {
protected x = 10;
}
class F extends E {
showX() {
console.log("X: " + this.x);
}
}
const fInstance = new F();
fInstance.showX();
//Visibilidade: Private
class PrivateClass {
private name = "Private";
showName() {
return this.name;
}
private privateMethod() {
console.log("Método privado");
}
showPrivateMethod() {
this.privateMethod();
}
}
const pObj = new PrivateClass();
console.log(pObj.showName());
pObj.showPrivateMethod();
//Static members
class StaticMembers {
static prop = "Teste static";
static statcMethod() {
console.log("Este é um método estático");
}
}
console.log(StaticMembers.prop);
StaticMembers.statcMethod();
//Generic class
class Item<T, U> {
first;
second;
constructor(first: T, second: U) {
this.first = first;
this.second = second;
}
get showFirst() {
return `O first é: ${this.first}`;
}
}
const newItem = new Item("Caixa", "Surpresa");
console.log(newItem);
console.log(newItem.showFirst);
//Parameters properties
class ParameterProperties {
constructor(public name: string, private qty: number, private price: number) {
this.name = name;
this.qty = qty;
this.price = price;
}
get showQty() {
return `Qtd toatl: ${this.qty}`;
}
get showPrice() {
return `Price: ${this.price}`;
}
}
const newShirt = new ParameterProperties("camisa", 5, 19.99);
console.log(newShirt.name);
console.log(newShirt.showPrice);
console.log(newShirt.showQty);
//Class Expressions
const myClass = class<T> {
name;
constructor(name: T) {
this.name = name;
}
};
const pessoa = new myClass("Matheus");
console.log(pessoa);
//Abstract class
abstract class AbstractClass {
abstract showName(): void;
}
class AbstractExample extends AbstractClass {
name: string;
constructor(name: string) {
super();
this.name = name;
}
showName(): void {
console.log(`O nome é: ${this.name}`);
}
}
const newAbstractObject = new AbstractExample("Matheus");
newAbstractObject.showName();
//Relações entre classes
class Dog {
name!: string;
}
class Cat {
name!: string;
}
const doguinho: Dog = new Cat();
console.log(doguinho);
|
---
id: agent-manage
title: Agent Management
description: You can pause or delete the Golang agent service.
tags:
- Golang
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
The following explains how to restart, pause, or delete the Golang agent service.
## Restarting the agent service
If the WhaTap agent service is running or erroneous, restart it.
<Tabs groupId="golang">
<TabItem value="redhat-centos" label="RedHat/CentOS">
```bash title='SH'
$ service whatap-agent restart
```
</TabItem>
<TabItem value="debian-ubuntu" label="Debian/Ubuntu">
```bash title='SH'
$ sudo service whatap-agent restart
```
</TabItem>
<TabItem value="amazonlinux" label="Amazon Linux">
```bash title='SH'
$ sudo service whatap-agent restart
```
</TabItem>
<TabItem value="alpinelinux" label="Alpine Linux">
```bash title='SH'
$ /usr/whatap/agent/whatap-agent stop
$ /usr/whatap/agent/whatap-agent start
```
</TabItem>
</Tabs>
## Stopping the whatap-agent service
<Tabs groupId="golang">
<TabItem value="redhat-centos" label="RedHat/CentOS">
```bash title='SH'
$ sudo service whatap-agent stop
```
</TabItem>
<TabItem value="debian-ubuntu" label="Debian/Ubuntu">
```bash title='SH'
$ sudo service whatap-agent stop
```
</TabItem>
<TabItem value="amazonlinux" label="Amazon Linux">
```bash title='SH'
$ sudo service whatap-agent stop
```
</TabItem>
<TabItem value="alpinelinux" label="Alpine Linux">
```bash title='SH'
$ /usr/whatap/agent/whatap-agent stop
```
</TabItem>
</Tabs>
## Agent deletion
Delete the WhaTap library from the Golang application's source code.
<Tabs groupId="golang">
<TabItem value="redhat-centos" label="RedHat/CentOS">
```bash title='SH'
$ sudo yum remove whatap-agent
```
</TabItem>
<TabItem value="debian-ubuntu" label="Debian/Ubuntu">
```bash title='SH'
$ sudo apt-get purge whatap-agent
```
</TabItem>
<TabItem value="amazonlinux" label="Amazon Linux">
```bash title='SH'
$ sudo yum remove whatap-agent
```
</TabItem>
<TabItem value="alpinelinux" label="Alpine Linux">
```bash title='SH'
$ /usr/whatap/agent/whatap-agent stop
# /usr/whatap/agent Deleting the directory
$ sudo rm -r /usr/whatap/agent
```
</TabItem>
</Tabs>
|
/**
* @author Branium Academy
* @version 2021.10
* @see <a href="https://braniumacademy.net/">...</a>
*/
#include <iostream>
#include <iomanip>
using namespace std;
// khai báo hàm nguyên mẫu
void output(int* arr, int n);
bool nextPermutation(int* arr, int n);
void generatePermutation(int* arr, int n);
int main() {
int t;
cin >> t;
int count = 1;
while (t-- > 0) {
int n;
cin >> n;
cout << "Test " << count++ << ": \n";
int* arr = new int[n]();
// khơi tạo
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
}
generatePermutation(arr, n);
delete[] arr;
}
return 0;
}
// sinh hoán vị kế tiếp
bool nextPermutation(int* arr, int n) {
int i = n - 2;
while (i >= 0 && arr[i] > arr[i + 1]) {
i--;
}
if (i >= 0) {
int k = n - 1;
while (arr[i] > arr[k]) {
k--;
}
int tmp = arr[i];
arr[i] = arr[k];
arr[k] = tmp;
int r = i + 1;
int s = n - 1;
while (r < s) {
int t = arr[r];
arr[r] = arr[s];
arr[s] = t;
r++;
s--;
}
return false;
}
else {
return true;
}
}
// thuật toán sinh hoán vị chính tắc
void generatePermutation(int* arr, int n) {
bool isFinalConfig = false;
while (!isFinalConfig) {
output(arr, n);
isFinalConfig = nextPermutation(arr, n);
}
}
void output(int* arr, int n) { // hiển thị kết quả
for (int i = 0; i < n; i++) {
cout << arr[i] << ' ';
}
cout << endl;
}
|
#include <SFML/Graphics.hpp>
#include <vector>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include "other.h"
// g++ -std=c++11 lose.cpp -o lose -lsfml-graphics -lsfml-window -lsfml-system && ./lose
struct Raindrop {
sf::Vector2f position;
sf::Vector2f velocity;
};
int main() {
sf::RenderWindow window(sf::VideoMode(800, 600), "Nice try, don't give up too early ok !!");
centerWindow(window);
sf::Font font = loadFont();
sf::Text loseText("LOSE", font, 80); // Larger text
sf::FloatRect textRect = loseText.getLocalBounds();
loseText.setOrigin(textRect.left + textRect.width / 2.0f, textRect.top + textRect.height / 2.0f);
loseText.setPosition(window.getSize().x / 2.0f, window.getSize().y / 2.0f);
loseText.setFillColor(sf::Color::White);
std::vector<Raindrop> raindrops;
std::vector<Button_Rectangle> buttons(2);
// Initialize buttons
initializeButton(buttons[0], sf::Vector2f(300.0f, 400.0f), sf::Vector2f(120.0f, 50.0f), "Retry", font);
initializeButton(buttons[1], sf::Vector2f(500.0f, 400.0f), sf::Vector2f(120.0f, 50.0f), "Quit", font);
// Gravity-like effect
const float gravity = 1.0f;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
} else if (event.type == sf::Event::MouseButtonPressed) {
sf::Vector2f mousePosition(static_cast<float>(event.mouseButton.x), static_cast<float>(event.mouseButton.y));
for (const auto& button : buttons) {
if (button.shape.getGlobalBounds().contains(mousePosition)) {
if (button.text.getString() == "Retry") {
window.close();
system("./x/game");
} else if (button.text.getString() == "Quit") {
window.close();
}
}
}
}
}
// Generate raindrops falling from the top
Raindrop raindrop;
raindrop.position = sf::Vector2f(std::rand() % window.getSize().x, 0.0f);
raindrop.velocity = sf::Vector2f(0.0f, static_cast<float>(std::rand() % 50 + 50));
raindrops.push_back(raindrop);
// Update and draw raindrops
window.clear();
for (auto& raindrop : raindrops) {
// Apply gravity-like effect
raindrop.velocity.y += gravity;
// Simulate wind effect
raindrop.velocity.x += static_cast<float>(std::rand() % 5 - 2); // Adjust wind intensity
raindrop.position.x += raindrop.velocity.x * 0.02;
raindrop.position.y += raindrop.velocity.y * 0.02;
sf::CircleShape drop(2.0f);
drop.setFillColor(sf::Color::White); // Always set to white
drop.setPosition(raindrop.position);
window.draw(drop);
}
raindrops.erase(std::remove_if(raindrops.begin(), raindrops.end(),
[&window](const Raindrop& r) { return r.position.y > window.getSize().y; }), raindrops.end());
// Draw the text
window.draw(loseText);
// Draw the buttons
drawButtonsBelowText(buttons, loseText, window);
// Display the updated frame
window.display();
}
return 0;
}
|
package ru.testtask.servlet;
import ru.testtask.dao.UserDAO;
import ru.testtask.model.Address;
import ru.testtask.model.MusicType;
import ru.testtask.model.Role;
import ru.testtask.model.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by nikolay on 06/10/17.
*/
public class EditServlet extends HttpServlet {
/**
* user dao.
*/
private UserDAO userDAO;
@Override
public void init() throws ServletException {
userDAO = new UserDAO();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String log = req.getParameter("edit_user");
User user = userDAO.getOne(new User(log));
req.setAttribute("ulogin", user.getLogin());
req.setAttribute("address_id", user.getAddress().getId());
req.setAttribute("name", user.getName());
req.setAttribute("city", user.getAddress().getCity());
req.setAttribute("street", user.getAddress().getStreet());
req.setAttribute("number", user.getAddress().getNumber());
req.setAttribute("role", user.getRole().getRole());
req.setAttribute("music", user.getMusicTypes());
req.getRequestDispatcher("/WEB-INF/testtask/edit.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Integer addressId = Integer.parseInt(req.getParameter("address_id"));
String login = req.getParameter("login_val");
String name = req.getParameter("name");
String password = req.getParameter("password");
String city = req.getParameter("city");
String street = req.getParameter("street");
Integer number = Integer.parseInt(req.getParameter("number"));
String role = req.getParameter("role");
String[] music = req.getParameterValues("music_type");
List<MusicType> types = new ArrayList<>();
for (String s : music) {
types.add(new MusicType(s));
}
User user = new User(name, login, password, new Role(role), new Address(addressId, city, street, number), types);
userDAO.edit(user);
resp.sendRedirect(String.format("%s/", req.getContextPath()));
}
}
|
import numpy as np
from scipy.optimize import minimize
def minimize_function(func, initial_guess, tol=1e-6):
"""
Minimizes a multidimensional function using the Nelder-Mead algorithm.
Parameters:
- func: The function to minimize. Must take a single argument, a numpy array of parameters.
- initial_guess: Initial guess for the parameters as a numpy array.
- tol: Tolerance for termination.
Returns:
- A dictionary containing the result of the minimization process.
"""
# Define the options for the minimization process
options = {'xatol': tol, 'fatol': tol, 'disp': True}
# Perform the minimization
result = minimize(func, initial_guess, method='Nelder-Mead', options=options)
# Check if the optimization was successful and print results
if result.success:
print("Optimization successful.")
print("Minimum found at:", result.x)
print("Function value at minimum:", result.fun)
else:
print("Optimization failed.")
print("Reason:", result.message)
return result
# Example usage:
# Define a function to minimize, e.g., a simple quadratic function
def example_function(x):
return (x[0] - 10)**2 + (x[1] - 2)**2 + (x[2] - 3)**2
# Initial guess for the parameters
initial_guess = np.array([-10, 0, 0])
# Call the minimize function
result = minimize_function(example_function, initial_guess)
|
import React from "react";
import { useAuthHeader } from "react-auth-kit";
import { FormikProvider, useFormik } from "formik";
import { DialogForm, formatFieldToDate } from "components/Common";
import { PatrimonyFormFields } from "./PatrimonyFormFields.component";
import { validatePatrimonyCreateForm } from "validations";
import { handleCreatePatrimony } from "services";
const PatrimonyCreate = ({ onClose, setState }) => {
const authHeader = useAuthHeader();
const formik = useFormik({
initialValues: {
nmPatrimonio: "",
nrSerie: "",
nmDescricao: "",
nrCnpj: "",
nmFornecedor: "",
nrNF: "",
dtNF: "",
dtAquisicao: "",
vlAquisicao: 0,
fixo: true,
warranties: [
{
dsGarantia: "",
dtValidade: "",
tipoGarantia: "Contratual",
},
],
},
validateOnChange: false,
validateOnBlur: false,
validate: (values) => validatePatrimonyCreateForm(values),
onSubmit: (values) => {
const data = {
...values,
dtNF: formatFieldToDate(values.dtNF),
dtAquisicao: formatFieldToDate(values.dtAquisicao),
warranties: values.warranties.map((warranty) => ({
...warranty,
dtValidade: formatFieldToDate(warranty.dtValidade),
})),
};
handleCreatePatrimony({
data,
header: { Authorization: authHeader() },
setState,
});
formik.resetForm();
},
});
return (
<DialogForm
title="Cadastrar Patrimônio"
onClose={onClose}
onSubmit={() => formik.submitForm()}
btnSubmitName="Cadastrar"
>
<FormikProvider value={formik}>
<form onSubmit={formik.handleSubmit}>
<PatrimonyFormFields formik={formik} />
</form>
</FormikProvider>
</DialogForm>
);
};
export { PatrimonyCreate };
|
<!DOCTYPE html>
<html>
<style>
.container {
display: flex;
width: 800px;
height: 250px;
border: 2px solid black;
border-radius: 10px;
background-color: aqua;
padding: 20px;
margin: 0 auto;
margin-top: 5px;
}
.box {
flex-grow: 1;
background-color: blanchedalmond;
margin: 5px;
border: 1px solid black;
border-radius: 10px;
}
.first {
flex-grow: 1;
}
.second {
flex-grow: 2;
}
.third {
flex-grow: 1;
}
.fourth {
flex-grow: 3;
}
.container2 {
display: flex;
flex-direction: column;
width: 800px;
height: 250px;
border: 2px solid black;
border-radius: 10px;
padding: 20px;
margin: 0 auto;
margin-top: 5px;
text-align: center;
}
.container3 {
width: 800px;
border: 2px solid black;
margin: 0 auto;
margin-top: 5px;
}
.flex-column {
display: flex;
background-color: aqua;
}
.flex-row {
display: flex;
background-color: aqua;
flex-grow: 1;
}
.box1 {
flex-basis: 25%;
background-color: beige;
border: 2px solid black;
padding: 40px;
text-align: center;
color: black;
font-size: 1.5em;
}
.double {
flex-grow: 2;
}
* {
box-sizing: border-box;
}
</style>
<body>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="container">
<div class="box first"></div>
<div class="box second"></div>
<div class="box third"></div>
</div>
<div class="container2">
<div class="box first">1</div>
<div class="box second">2</div>
<div class="box fourth">3</div>
</div>
<div class="container3">
<div class="flex-column">
<div class="box1">1</div>
<div class="box1">2</div>
<div class="box1">3</div>
<div class="box1">4</div>
</div>
<div class="flex-row">
<div class="box1">5</div>
<div class="box1">6</div>
<div class="box1 double">7</div>
</div>
</div>
</body>
</html>
|
package com.eznema.vb_test.auth.controller;
import com.eznema.vb_test.auth.CustomErrors.ForbiddenException;
import com.eznema.vb_test.auth.CustomErrors.UnauthorizedException;
import com.eznema.vb_test.auth.model.AuthenticationResponse;
import com.eznema.vb_test.user.model.User;
import com.eznema.vb_test.auth.service.AuthenticationService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
/**
* Controlador REST propio de Spring que maneja las solicitudes de registro y autenticación de usuarios.
* Utiliza un servicio de autenticación para procesar estas solicitudes y devolver las respuestas de autenticación.
* */
@RestController
public class AuthenticationController {
private final AuthenticationService authenticationService;
/**
* Constructor: authenticationService es un servicio que maneja la lógica de registro y autenticación de usuarios.
* */
public AuthenticationController(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
/**
* Método que maneja las solicitudes de registro de nuevos usuarios.
* - Párametro: Objeto User que contiene la los datos del usuario a registrar.
* - Retorno: ResponseEntity que contiene la respuesta de autenticación, con un token JWT de ser exitosa.
*/
@PostMapping("/register")
public ResponseEntity<String> register(@RequestBody User request) {
try {
authenticationService.register(request);
return new ResponseEntity<>("Usuario registrado con éxito", HttpStatus.CREATED);
} catch (UnauthorizedException e) {
return new ResponseEntity<>("Error: " + e.getMessage(), HttpStatus.UNAUTHORIZED);
} catch (ForbiddenException e) {
return new ResponseEntity<>("Error: " + e.getMessage(), HttpStatus.FORBIDDEN);
} catch (Exception e) {
return new ResponseEntity<>("Error al registrar el usuario", HttpStatus.BAD_REQUEST);
}
}
/**
*Método que maneja las solicitudes de inicio de sesión de usuarios
* - Parámetro: Objeto user que contiene los datos del usuario que desea iniciar sesión.
* - Retorno: ResponseEntity que contiene la respuesta de autenticación, con un JWT de ser exitosa.
* */
@PostMapping("/login")
public ResponseEntity<AuthenticationResponse> login(@RequestBody User request, HttpServletResponse response) {
AuthenticationResponse authResponse = authenticationService.authenticate(request);
// Crear la cookie con el token JWT
Cookie jwtCookie = new Cookie("eznema", authResponse.getToken());
jwtCookie.setHttpOnly(true);
jwtCookie.setMaxAge(24*60*60);
jwtCookie.setPath("/");
jwtCookie.setSecure(false);
// Configurar el encabezado Set-Cookie con SameSite
String sameSiteCookie = String.format("eznema=%s; Max-Age=%d; Path=/; Secure; HttpOnly; SameSite=None",
authResponse.getToken(), 24 * 60 * 60);
response.setHeader("Set-Cookie", sameSiteCookie);
// Añadir la cookie a la respuesta
response.addCookie(jwtCookie);
return ResponseEntity.status(HttpStatus.OK).build();
}
}
|
package com.info7255.ebl.service;
import java.util.*;
public class Eratosthenes {
public static List<Integer> findPrimesInRange(int start, int end) {
boolean[] isPrime = new boolean[end + 1];
Arrays.fill(isPrime, true);
for (int i = 2; i * i <= end; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= end; j += i) {
isPrime[j] = false;
}
}
}
List<Integer> primes = new ArrayList<>();
for (int i = Math.max(2, start); i <= end; i++) {
if (isPrime[i]) {
primes.add(i);
}
}
return primes;
}
public static void main(String[] args) {
int start = 10;
int end = 50;
List<Integer> primesInRange = findPrimesInRange(start, end);
System.out.println("Prime numbers between " + start + " and " + end + ":");
System.out.println(primesInRange);
}
}
|
import { ModelAttributes, QueryInterface, DataTypes } from "sequelize";
export default {
up: async (queryInterface: QueryInterface) => {
await queryInterface.createTable("users", {
id: {
type: DataTypes.INTEGER,
unique: true,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
active_status: {
type: DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
},
} as ModelAttributes);
},
down: async (queryInterface: QueryInterface) => {
await queryInterface.dropTable("users");
},
};
|
use wgpu::{
include_wgsl, Backends, DeviceDescriptor, Features, Limits, PowerPreference, PresentMode,
RenderPipeline, RequestAdapterOptions, SurfaceConfiguration,
};
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};
pub struct State {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
surface_configuration: wgpu::SurfaceConfiguration,
size: winit::dpi::PhysicalSize<u32>,
window: Window,
render_pipeline: RenderPipeline,
}
impl State {
async fn new(window: Window) -> Self {
let size = window.inner_size();
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: Backends::all(),
..Default::default()
});
// This should be safe since the state owns both the surface and the window, which is why this is unsafe in the first place.
let surface = unsafe { instance.create_surface(&window) }.unwrap();
let gpu_handle = instance
.request_adapter(&RequestAdapterOptions {
power_preference: PowerPreference::default(),
compatible_surface: Some(&surface),
force_fallback_adapter: false,
})
.await
.unwrap();
let (device, queue) = gpu_handle
.request_device(
&DeviceDescriptor {
features: Features::empty(),
limits: Limits::default(),
label: None,
},
None,
)
.await
.unwrap();
let surface_capabilities = surface.get_capabilities(&gpu_handle);
let surface_format = surface_capabilities
.formats
.iter()
.find(|format| format.describe().srgb)
.unwrap();
let surface_configuration = SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: *surface_format,
width: size.width,
height: size.height,
present_mode: PresentMode::Fifo,
alpha_mode: surface_capabilities.alpha_modes[0],
view_formats: vec![],
};
surface.configure(&device, &surface_configuration);
let shader = device.create_shader_module(include_wgsl!("shader.wgsl"));
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
targets: &[Some(wgpu::ColorTargetState {
format: surface_configuration.format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: None,
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
});
Self {
surface,
device,
queue,
surface_configuration,
size,
window,
render_pipeline,
}
}
pub fn window(&self) -> &Window {
&self.window
}
pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
if new_size.width != 0 && new_size.height != 0 {
self.size = new_size;
self.surface_configuration.width = new_size.width;
self.surface_configuration.height = new_size.height;
self.surface
.configure(&self.device, &self.surface_configuration);
}
}
pub fn input(&mut self, event: &WindowEvent) -> bool {
false
}
pub fn update(&mut self) {
// TODO
}
pub fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
let output_frame = self.surface.get_current_texture()?;
let view = output_frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut command_encoder =
self.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
{
let mut render_pass = command_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::WHITE),
store: true,
},
})],
depth_stencil_attachment: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.draw(0..3, 0..1);
}
self.queue.submit(std::iter::once(command_encoder.finish()));
output_frame.present();
Ok(())
}
}
async fn run() {
env_logger::init();
let event_loop = EventLoop::new();
let window = WindowBuilder::new().build(&event_loop).unwrap();
let mut state = State::new(window).await;
event_loop.run(move |event, _, control_flow| match event {
Event::WindowEvent { window_id, event } if window_id == state.window.id() => {
if !state.input(&event) {
match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
WindowEvent::Resized(size) => {
state.resize(size);
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
state.resize(*new_inner_size);
}
_ => {}
}
}
}
Event::RedrawRequested(window_id) if window_id == state.window.id() => {
state.update();
match state.render() {
Ok(_) => {}
Err(wgpu::SurfaceError::Lost) => state.resize(state.size),
Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
Err(error) => eprintln!("{error:?}"),
}
}
Event::MainEventsCleared => {
state.window.request_redraw();
}
_ => {}
});
}
fn main() {
pollster::block_on(run());
}
|
import { useContext } from "react";
import { Link, useNavigate } from "react-router-dom";
import Swal from "sweetalert2";
import { AuthContext } from "../../Provider/AuthProvider";
import { useForm } from "react-hook-form";
const Register = () => {
const createUser =useContext(AuthContext);
const { register, handleSubmit, reset, formState: { errors } } = useForm();
const navigate =useNavigate();
const onSubmit = data =>{
createUser(data.email, data.password)
.then(result =>{
const loggeduser =result.user;
console.log(loggeduser);
updateUserProfile(data.name, data.photoURL)
.then(data=>{
if(data.insertedId){
reset()
Swal.fire({
position: 'center',
icon: 'success',
title: 'Successfully Sign up',
showConfirmButton: false,
timer: 1500
})
navigate('/')
}
})
.catch(error=>console.log(error))
})
console.log(data)
};
return (
<div>
<div className="hero min-h-screen bg-base-200 mt-20 ">
<div className="hero-content flex-col ">
<div className="text-center ">
<h1 className="text-5xl font-bold ">Register now!</h1>
</div>
<div className="card flex-shrink-0 w-full max-w-sm shadow-2xl bg-base-100">
<form onSubmit={handleSubmit(onSubmit)} className="card-body">
<div className="form-control">
<label className="label">
<span className="label-text">Name</span>
</label>
<input type="taxt" placeholder="name" {...register("name", { required: true })} className="input input-bordered" />
{errors.name && <span className="text-warning">Name is required</span>}
</div>
<div className="form-control">
<label className="label">
<span className="label-text">Photo URL</span>
</label>
<input type="text" placeholder="photo URL" {...register("photoURL", { required: true })} className="input input-bordered" />
{errors.name && <span className="text-warning">Photo URL is required</span>}
</div>
<div className="form-control">
<label className="label">
<span className="label-text">Email</span>
</label>
<input type="email" placeholder="email" {...register("email", { required: true })} className="input input-bordered" />
{errors.email && <span className="text-warning">Email is required</span>}
</div>
<div className="form-control">
<label className="label">
<span className="label-text">Password</span>
</label>
<input type="password" placeholder="password" {...register("password", {
required: true,
minLength: 6,
maxLength: 20,
pattern: /(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z])/
})} className="input input-bordered" />
{errors.password?.type === 'required' && <p className='text-warning'>password is required</p>}
{errors.password?.type === 'minLength' && <p className='text-warning'>password must be 6 character </p>}
{errors.password?.type === 'maxLength' && <p className='text-warning'>password must be less then 20 character</p>}
{errors.password?.type === 'pattern' && <p className='text-warning'>password must be One uppercase one lowercase one number & one special character </p>}
</div>
{/* <div className="form-control">
<label className="label">
<span className="label-text">confirm password</span>
</label>
<input type="text" placeholder="confirm password" {...register("password", { required: true })} className="input input-bordered" />
{errors.text && <span className="text-warning">Password is required</span>}
</div> */}
<div className="form-control mt-6">
<input className="btn btn-primary" type="submit" value="Register" />
</div>
<p>Already have an a account? <Link className='text-warning font-bold' to="/login">Login</Link> </p>
</form>
</div>
</div>
</div>
</div>
);
};
export default Register;
|
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
)
func main() {
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
sc.Buffer(make([]byte, 0, 4*1024*1024), 0)
sc.Scan()
n, _ := strconv.Atoi(sc.Text())
graph := NewGraph(n)
sc.Scan()
l, _ := strconv.Atoi(sc.Text())
for i := 0; i < l; i++ {
sc.Scan()
u, _ := strconv.Atoi(sc.Text())
sc.Scan()
v, _ := strconv.Atoi(sc.Text())
graph.AddEdge(u, v)
}
graph.Normalize()
n, vertex := components(graph)
printComponents(n, vertex)
}
func printComponents(n int, vertex []int) {
fmt.Println(n)
for i := 1; i <= n; i++ {
for j := 0; j < len(vertex); j++ {
if vertex[j] == i {
fmt.Printf("%d ", j+1)
}
}
fmt.Println()
}
}
func components(graph *MyGraph) (int, []int) {
vertex := make([]int, len(graph.Data))
componentN := 0
for i := 0; i < len(vertex); i++ {
if vertex[i] > 0 {
continue
}
componentN++
dfsMark(graph, vertex, i, componentN)
}
return componentN, vertex
}
func dfsMark(graph *MyGraph, vertex []int, start, component int) {
if vertex[start] != 0 {
return
}
vertex[start] = component
for i := 0; i < len(graph.Data[start]); i++ {
dfsMark(graph, vertex, graph.Data[start][i], component)
}
}
type MyGraph struct {
Data [][]int
}
func (this *MyGraph) Normalize() {
for i := 0; i < len(this.Data); i++ {
sort.Slice(this.Data[i], func(l, r int) bool {
return this.Data[i][l] < this.Data[i][r]
})
}
}
func (this *MyGraph) Print() {
for i := 0; i < len(this.Data); i++ {
fmt.Printf("%d => {", i+1)
if len(this.Data[i]) > 0 {
fmt.Printf("%d", this.Data[i][0]+1)
}
for j := 1; j < len(this.Data[i]); j++ {
fmt.Printf(" %d", this.Data[i][j]+1)
}
fmt.Print("}\n")
}
}
func (this *MyGraph) AddEdge(u, v int) {
u = u - 1
v = v - 1
if len(this.Data[u]) == 0 {
this.Data[u] = []int{v}
} else {
this.Data[u] = append(this.Data[u], v)
}
if len(this.Data[v]) == 0 {
this.Data[v] = []int{u}
} else {
this.Data[v] = append(this.Data[v], u)
}
}
func NewGraph(n int) *MyGraph {
return &MyGraph{
Data: make([][]int, n),
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { AppRoute } from '../../const';
import { changeActiveCity } from '../../store/actions';
import { getActiveCity } from '../../store/app-ui/selectors';
function LocationItem({ location }) {
const city = useSelector(getActiveCity);
const dispatch = useDispatch();
return (
<li className="locations__item">
<Link
style={
city === location
? { pointerEvents: 'none', userSelect: 'none' }
: { userSelect: 'none' }
}
to={AppRoute.MAIN}
onClick={() => {
dispatch(changeActiveCity(location));
}}
className={
city === location
? 'locations__item-link tabs__item tabs__item--active'
: 'locations__item-link tabs__item'
}
>
<span>{location}</span>
</Link>
</li>
);
}
LocationItem.propTypes = {
location: PropTypes.string.isRequired,
};
export default LocationItem;
|
module EnvSpec (spec) where
import Helper
import qualified Env
import qualified Env.Raw
spec :: Spec
spec = around_ Env.protect $ do
describe "get" $ do
context "on invalid UTF-8" $ do
it "uses Unicode replacement characters" $ do
let invalid = "foo " <> [128 :: Word8].pack <> " bar"
Env.Raw.set "foo" invalid
Env.get "foo" `shouldReturn` Just "foo \xFFFD bar"
describe "extend" $ do
it "extends the environment" $ do
Env.extend [("foo", "bar")] $ do
Env.get "foo" `shouldReturn` Just "bar"
describe "path" $ do
describe "extend" $ do
context "when PATH is not set" $ do
it "sets the PATH" $ do
Env.unset "PATH"
Env.path.extend "/foo/bar" $ do
Env.get "PATH" `shouldReturn` Just "/foo/bar"
Env.get "PATH" `shouldReturn` Nothing
context "when PATH is set" $ do
it "extends the PATH" $ do
path <- Env.get "PATH"
Env.path.extend "/foo/bar" $ do
(>>= flip (.stripPrefix) "/foo/bar:") <$> Env.get "PATH" `shouldReturn` path
Env.get "PATH" `shouldReturn` path
|
package softuni.exam.models.dto;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "astronomer")
@XmlAccessorType(XmlAccessType.FIELD)
public class AstronomerImportDTO {
@XmlElement(name = "average_observation_hours")
@NotNull
@DecimalMin(value = "500.00")
private Double averageObservationHours;
@XmlElement(name = "birthday")
private String birthday; //TODO birthday - a date in the "yyyy-MM-dd" format. Can be nullable. ??????!!!!!! TODO !!!
@XmlElement(name = "first_name")
@Size(min = 2, max = 30)
@NotNull
private String firstName;
@XmlElement(name = "last_name")
@Size(min = 2, max = 30)
@NotNull
private String lastName;
@XmlElement(name = "salary")
@DecimalMin(value = "15000.00")
@NotNull
private Double salary;
@XmlElement(name = "observing_star_id")
@NotNull
private Long star;
public Double getAverageObservationHours() {
return averageObservationHours;
}
public void setAverageObservationHours(Double averageObservationHours) {
this.averageObservationHours = averageObservationHours;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Long getStar() {
return star;
}
public void setStar(Long star) {
this.star = star;
}
}
|
import React, { useState } from "react";
import {
Box,
Button,
Container,
Grid,
Paper,
TextField,
Typography,
} from "@mui/material";
import { GoogleCredentialResponse, GoogleLogin } from "@react-oauth/google";
type LoginScreenProps = {
handleEmailPasswordLogin: (email: string, password: string) => void;
handleGoogleLogin: (response: GoogleCredentialResponse) => void;
handleSignup: (username: string, email: string, password: string) => void;
};
type ScreenType = "signin" | "signup";
export const LoginScreen = ({
handleEmailPasswordLogin,
handleGoogleLogin,
handleSignup,
}: LoginScreenProps) => {
const [screenType, setScreenType] = useState<ScreenType>("signin");
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const handleUsernameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setUsername(e.target.value);
};
const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setEmail(e.target.value);
};
const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setPassword(e.target.value);
};
const handleLogin = () => {
handleEmailPasswordLogin(email, password);
};
const handleGoogleLoginError = () => {
setErrorMessage("Googleログインに失敗しました。");
};
if (screenType === "signin") {
return (
<Container
maxWidth="sm"
style={{
height: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Paper elevation={3} style={{ padding: "24px" }}>
<Grid container spacing={2}>
<Grid item xs={12}>
<Typography variant="h5" align="center">
Growyにログイン
</Typography>
</Grid>
<Grid item xs={12}>
<form
style={{
display: "flex",
flexDirection: "column",
gap: "16px",
}}
>
<TextField
type="email"
label="Email"
variant="outlined"
value={email}
onChange={handleEmailChange}
/>
<TextField
type="password"
label="パスワード"
variant="outlined"
value={password}
onChange={handlePasswordChange}
/>
<Button
variant="contained"
color="primary"
style={{ marginTop: "16px" }}
onClick={handleLogin}
>
ログイン
</Button>
<Box alignContent={"center"}>
<GoogleLogin
onSuccess={handleGoogleLogin}
onError={handleGoogleLoginError}
/>
</Box>
{errorMessage && (
<Typography variant="body2" color="error">
{errorMessage}
</Typography>
)}
<Typography variant="body2">
アカウントがない場合は、
<Button onClick={() => setScreenType("signup")}>
アカウント登録
</Button>
してください。
</Typography>
</form>
</Grid>
</Grid>
</Paper>
</Container>
);
} else {
return (
<Container
maxWidth="sm"
style={{
height: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Paper elevation={3} style={{ padding: "24px" }}>
<Grid container spacing={2}>
<Grid item xs={12}>
<Typography variant="h5" align="center">
Growyにサインアップ
</Typography>
</Grid>
<Grid item xs={12}>
<form
style={{
display: "flex",
flexDirection: "column",
gap: "16px",
}}
>
<TextField
type="text"
label="ユーザー名"
variant="outlined"
value={username}
onChange={handleUsernameChange}
/>
<TextField
type="email"
label="Email"
variant="outlined"
value={email}
onChange={handleEmailChange}
/>
<TextField
type="password"
label="パスワード"
variant="outlined"
value={password}
onChange={handlePasswordChange}
/>
<Button
variant="contained"
color="primary"
style={{ marginTop: "16px" }}
onClick={() => handleSignup(username, email, password)}
>
アカウント登録
</Button>
<Box alignContent={"center"}>
<Typography variant="body2">
既にアカウントをお持ちの場合は、
<Button onClick={() => setScreenType("signin")}>
サインイン
</Button>
してください。
</Typography>
</Box>
</form>
</Grid>
</Grid>
</Paper>
</Container>
);
}
};
|
<?php
namespace App\Http\Controllers;
use App\Models\{Blog, Category, Example};
class HomeController extends Controller
{
public function index()
{
$query = request('query');
return view('frontend.home', [
'new_post' => Blog::orderBy('created_at', 'asc')->paginate(18),
// post kategori terpopuler
'best_post' => Blog::whereHas('categories', function ($query) {
$query->where('name', 'Terpopuler');
})->with('categories')->orderBy('created_at')->limit(6)->get(),
//simple paginate tidak bisa pakai latest()
'new_post' => Blog::where("title", "like", "%$query%")->latest()->simplePaginate(18),
//tampilan kategori kecuali terpopuler
'categories' => Category::whereNotIn('name', ['Terpopuler', 'Populer', 'Best Seller'])->get(),
]);
}
public function show(Blog $blog)
{
if ($blog) {
$relatedByCategories = Blog::whereHas('categories', function ($q) use ($blog) {
$q->whereIn('name', $blog->categories->pluck('name'));
})
->where('id', '!=', $blog->id)
->limit(5)
->get();
$relatedByExamples = Blog::whereHas('examples', function ($q) use ($blog) {
$q->whereIn('name', $blog->examples->pluck('name'));
})
->where('id', '!=', $blog->id)
->limit(5)
->get();
$post_related = $relatedByCategories->merge($relatedByExamples);
return view('frontend.blog', [
'title' => $blog->title,
'post' => $blog,
'post_related' => $post_related,
]);
} else {
abort(404);
}
}
public function category(Category $category)
{
$query = request('query');
if ($category) {
return view('frontend.category', [
'categories' => Category::whereNotIn('name', ['Terpopuler', 'Populer', 'Best Seller'])->get(),
'category' => $category->name,
'posts' => $category->blogs()->latest()->simplePaginate(6),
'posts' => $category->blogs()->where('title', 'like', '%' . $query . '%')->latest()->simplePaginate(6),
]);
} else {
abort(404);
}
}
public function about_us()
{
return view('frontend.about_us', ['title' => 'Tentang Kami']);
}
}
|
export { }
const request = require("supertest");
const app = require("../app.ts");
const api = "/api/v1"
// add defines here
const userFunctions = require("./helpers/users")
const discCollectionFunctions = require("./helpers/disccollections");
test(`add a collection to a known user`, async () =>
{
const userDetails = userFunctions.generateUserDetails();
const registerRes = await userFunctions.registerAUser(userDetails);
const userToken = registerRes.body.token
expect(registerRes.status).toBe(201);
const title = "My Test Collection"
const res = await discCollectionFunctions.newCollection(userToken, title);
expect(res.status).toBe(201);
expect(res.body.title).toEqual(title);
})
test(`retrieve a known collection for a known user`, async () =>
{
const userDetails = userFunctions.generateUserDetails();
const registerRes = await userFunctions.registerAUser(userDetails);
const userToken = registerRes.body.token
expect(registerRes.status).toBe(201);
const title = "My Test Collection"
const resOne = await discCollectionFunctions.newCollection(userToken, title);
expect(resOne.status).toBe(201);
expect(resOne.body.title).toEqual(title);
const collId = resOne.body._id
const resTwo = await discCollectionFunctions.getCollection(userToken, collId)
expect(resTwo.status).toBe(200);
expect(resTwo.body._id).toEqual(collId);
expect(resTwo.body.title).toEqual(title);
expect(resTwo.body.discs).toEqual([]);
})
test(`delete a known collection for a known user`, async () =>
{
const userDetails = userFunctions.generateUserDetails();
const registerRes = await userFunctions.registerAUser(userDetails);
const userToken = registerRes.body.token
expect(registerRes.status).toBe(201);
const title = "My Test Collection"
const resOne = await discCollectionFunctions.newCollection(userToken, title);
expect(resOne.status).toBe(201);
expect(resOne.body.title).toEqual(title);
const collId = resOne.body._id
const getResOne = await discCollectionFunctions.getCollection(userToken, collId)
expect(getResOne.status).toBe(200);
const resTwo = await request(app)
.delete(`${api}/disccollections/${resOne.body._id}`)
.set(`Authorization`, `Bearer ${userToken}`)
.send();
expect(resTwo.status).toBe(200);
const getResTwo = await discCollectionFunctions.getCollection(userToken, collId)
expect(getResTwo.status).toBe(401);
})
test(`retrieve all collections for a known user`, async () =>
{
const userDetails = userFunctions.generateUserDetails();
const registerRes = await userFunctions.registerAUser(userDetails);
const userToken = registerRes.body.token
expect(registerRes.status).toBe(201);
// don't use duplicate titles here, we're checking for string match.
const titles = ["My Zeroth Collection", "My First Collection", "My Second Collection"]
for (let i = 0; i < titles.length; i++)
{
await discCollectionFunctions.newCollection(userToken, titles[i]);
}
const res = await request(app)
.get(`${api}/disccollections`)
.set(`Authorization`, `Bearer ${userToken}`)
.send();
expect(res.body.length).toEqual(titles.length);
for (let i = 0; i < titles.length; i++)
{
// we have to do it like this because mongodb could return
// the collections in the ""wrong"" order,
// so it's safer to assume collection array arrives unsorted.
const coll = res.body.findIndex((coll) => coll.title.includes(titles[i]))
// console.log("found: " + res.body[coll].title + ", expected: " + titles[i])
expect(res.body[coll].title).toEqual(titles[i]);
}
})
|
use axum::routing::get;
use socketioxide::{extract::SocketRef, SocketIo};
use tracing::info;
use tracing_subscriber::FmtSubscriber;
fn on_connect(socket: SocketRef) {
info!("Socket:io connected: {:?} {:?}", socket.ns(), socket.id);
println!("connected");
socket.emit("message", "alert");
}
#[tokio::main]
async fn main() {
let subscriber = FmtSubscriber::builder().finish();
tracing::subscriber::set_global_default(subscriber).unwrap();
let (layer, io) = SocketIo::new_layer();
io.ns("/", on_connect);
let app = axum::Router::new()
.route("/", get(|| async { "Hello, World!" }))
.layer(layer);
info!("starting server on port 3001");
axum::Server::bind(&"127.0.0.1:3001".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
|
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class AppBlocObserver extends BlocObserver {
@override
void onCreate(BlocBase bloc) {
super.onCreate(bloc);
if (kDebugMode) {
log('Created', name: "${bloc.runtimeType}");
}
}
@override
void onEvent(Bloc bloc, Object? event) {
super.onEvent(bloc, event);
if (kDebugMode) {
log("$event", name: "${bloc.runtimeType}");
}
}
@override
void onTransition(Bloc bloc, Transition transition) {
super.onTransition(bloc, transition);
if (kDebugMode) {
log("${transition.currentState} => ${transition.nextState}",
name: "${bloc.runtimeType}");
}
}
@override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
super.onError(bloc, error, stackTrace);
if (kDebugMode) {
log("Error: $error\nStackTrace: $stackTrace",
name: "${bloc.runtimeType}");
}
}
@override
void onClose(BlocBase bloc) {
super.onClose(bloc);
if (kDebugMode) {
log('Closed', name: "${bloc.runtimeType}");
}
}
}
|
import {
Box,
Flex,
HStack,
Icon,
IconButton,
Spinner,
Text,
VStack,
} from '@chakra-ui/react';
import useMessengerStore, {
MessageStatus,
UserMessage,
} from '../store/messenger';
import useAuthStore from '../store/auth';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Clear, InsertDriveFile, Image } from '@mui/icons-material/';
import {
Element as EditorElement,
Leaf as EditorLeaf,
ElementProps,
LeafProps,
withInlines,
} from './TextEditor';
import { Editable, Slate, withReact } from 'slate-react';
import { createEditor } from 'slate';
import useUserStore from '../store/user';
import MessageContextMenu from './MessageContextMenu';
const MessagesContainer = (): JSX.Element => {
const containerRef = useRef<HTMLDivElement | null>(null);
const firstMessageRef = useRef<HTMLDivElement | null>(null);
const lastMessageRef = useRef<HTMLDivElement | null>(null);
const [messages, setMessages] = useState<UserMessage[]>([]);
const [messagesLoading, setMessagesLoading] = useState(false);
const [isContextMenuOpen, setIsContextMenuOpen] = useState(false);
const [mousePosition, setMousePosition] = useState<{ x: number; y: number }>({
x: 0,
y: 0,
});
const [contextMenuMessage, setContextMenuMessage] =
useState<UserMessage | null>(null);
const {
channels,
socket,
currentChannel,
lastSentMessage,
lastEditedMessage,
lastDeletedMessage,
notesChannel,
setEditingMessage,
loadChannelMessages,
onRecieveChannelMessages,
processDownloadingAttachment,
deleteMessage,
sendMessageToNotes,
} = useMessengerStore(state => state);
const { userData } = useAuthStore(state => state);
const { axios } = useUserStore(state => state);
useEffect(() => {
if (!currentChannel) return;
const channelMessages: UserMessage[] | undefined = channels.find(
channel => channel.id === currentChannel.id
)?.messages;
setMessages([]);
if (channelMessages) {
setMessages([...channelMessages]);
} else {
setMessagesLoading(true);
loadChannelMessages();
}
}, [currentChannel]);
useEffect(() => {
const channelMessagesHandler = (data: {
messages: UserMessage[];
hasMoreMessages: boolean;
users: any;
}): void => {
setMessages(prevMessages => {
const existingMessageIds = new Set(
prevMessages.map(msg => msg.id) || []
);
const newMessages = data.messages.filter(
msg => !existingMessageIds.has(msg.id)
);
return [...prevMessages, ...newMessages];
});
onRecieveChannelMessages(data);
setMessagesLoading(false);
};
socket?.on('recieve-channel-messages', channelMessagesHandler);
return () => {
socket?.off('recieve-channel-messages', channelMessagesHandler);
};
}, [socket, channels, currentChannel]);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (
entry.isIntersecting &&
channels.find(channel => channel.id === currentChannel?.id)
?.hasMoreMessages &&
!messagesLoading
) {
setMessagesLoading(true);
loadChannelMessages();
}
},
{
root: null,
rootMargin: '-100px 0px 0px 0px',
threshold: 0,
}
);
if (firstMessageRef.current) {
observer.observe(firstMessageRef.current);
}
return () => {
if (firstMessageRef.current) {
observer.unobserve(firstMessageRef.current);
}
};
}, [messagesLoading, messages]);
useEffect(() => {
if (
lastSentMessage?.message &&
lastSentMessage.channelId === currentChannel?.id
) {
setMessages(prevMessages => {
if (lastSentMessage.message) {
return [lastSentMessage.message, ...prevMessages];
}
return prevMessages;
});
if (containerRef.current) {
containerRef.current.scrollTop = containerRef.current.scrollHeight;
}
}
}, [lastSentMessage]);
useEffect(() => {
if (
lastDeletedMessage.messageId &&
lastDeletedMessage.channelId === currentChannel?.id
) {
const filteredMessages = messages.filter(
message => message.id !== lastDeletedMessage.messageId
);
setMessages(filteredMessages);
}
}, [lastDeletedMessage]);
const [editorsMap, setEditorsMap] = useState(new Map());
useEffect(() => {
const updatedEditorsMap = new Map(editorsMap);
channels
?.find(channel => channel?.id === currentChannel?.id)
?.messages?.forEach(message => {
if (!updatedEditorsMap.has(message.id)) {
const editor = withInlines(withReact(createEditor()));
editor.children = message.textContent;
updatedEditorsMap.set(message.id, editor);
}
});
setEditorsMap(updatedEditorsMap);
}, [channels, currentChannel]);
useEffect(() => {
if (
lastEditedMessage.message &&
lastEditedMessage.channelId === currentChannel?.id
) {
const filteredMessages = messages.map(message => {
if (message.id === lastEditedMessage?.message?.id) {
const editor = editorsMap.get(message.id);
if (editor) {
editor.children = lastEditedMessage.message.textContent;
}
return {
...message,
textContent: lastEditedMessage.message.textContent,
};
}
return message;
});
setMessages(filteredMessages);
}
}, [lastEditedMessage]);
const renderElement = useCallback(
(props: ElementProps) => <EditorElement {...props} />,
[]
);
const renderLeaf = useCallback(
(props: LeafProps) => <EditorLeaf {...props} />,
[]
);
const handleDownloadFile = async (
fileId: string,
fileName: string
): Promise<void> => {
try {
if (!axios) {
return;
}
await processDownloadingAttachment(axios, fileId, fileName);
} catch (error) {
console.error('Error downloading file:', error);
}
};
const handleContextMenu = (
event: React.MouseEvent<HTMLDivElement>,
message: UserMessage
): void => {
event.preventDefault();
setMousePosition({ x: event.clientX, y: event.clientY });
setContextMenuMessage(message);
setIsContextMenuOpen(true);
};
const handleDeleteMessage = (): void => {
try {
if (!currentChannel || !contextMenuMessage) return;
try {
deleteMessage(contextMenuMessage.id, currentChannel.id);
} catch (error) {
return;
}
const filteredMessages = messages.filter(
message => message.id !== contextMenuMessage.id
);
setMessages(filteredMessages);
} catch (error) {
console.error('Error downloading file:', error);
}
};
const handleEditMessage = (): void => {
setIsContextMenuOpen(false);
if (!contextMenuMessage) return;
setEditingMessage(contextMenuMessage);
};
const handleSendToNotes = (): void => {
setIsContextMenuOpen(false);
if (!contextMenuMessage) return;
sendMessageToNotes(contextMenuMessage, contextMenuMessage.user._id);
};
return (
<Flex
flexDirection="column-reverse"
flex={1}
pt={'15px'}
pb={'10px'}
overflowY="auto"
ref={containerRef}
onClick={() => setIsContextMenuOpen(false)}
>
{messagesLoading && messages.length === 0 ? (
<Flex w="100%" h="100%" justifyContent="center" alignItems="center">
<Spinner size={'xl'} thickness="4px" speed="0.5s" />
</Flex>
) : (
editorsMap.size > 0 &&
messages.map((message, index) => {
return (
<React.Fragment key={message.id}>
{index === messages.length - 1 && (
<Box ref={firstMessageRef}></Box>
)}
{index === messages.length - (messages.length - 1) && (
<Box ref={lastMessageRef}></Box>
)}
<HStack
alignSelf={`${message.user._id === userData?.userId ? 'end' : 'start'}`}
spacing={'10px'}
p={'5px 10px 5px 10px'}
bg={`${message.user._id === userData?.userId ? 'zinc700' : 'zinc800'}`}
borderRadius="md"
boxShadow="md"
color="zinc300"
mt="18px"
ml={`${message.user._id === userData?.userId ? '100px' : '18px'}`}
mr={`${message.user._id === userData?.userId ? '13px' : '100px'}`}
width="fit-content"
onContextMenu={event => {
handleContextMenu(event, message);
}}
>
{contextMenuMessage?.id === message.id && (
<MessageContextMenu
mousePosition={mousePosition}
onDeleteMessage={handleDeleteMessage}
isDeleteEnabled={
message.user._id === userData?.userId ||
currentChannel?.id === notesChannel.id
}
onEditMessage={handleEditMessage}
isEditEnabled={message.user._id === userData?.userId}
onSendToNotes={handleSendToNotes}
isSendToNotesEnabled={
currentChannel?.id !== notesChannel.id
}
isContextMenuOpen={isContextMenuOpen}
onCloseContextMenu={() => setIsContextMenuOpen(false)}
/>
)}
<VStack mb={'8px'} spacing={0}>
<HStack alignSelf={'start'}>
{message.user._id === userData?.userId ? null : (
<Text color="zinc400">{message.user.name}</Text>
)}
</HStack>
<VStack alignSelf={'start'}>
{message.attachments?.map((attachment, index) => (
<VStack
key={`${attachment.url}-${index}`}
alignSelf={'start'}
>
<HStack alignSelf={'start'}>
<IconButton
aria-label="IconButtonLabel"
icon={
attachment.type === 'image' ? (
<Image />
) : (
<InsertDriveFile />
)
}
onClick={() => {
handleDownloadFile(
attachment.url,
attachment.name
);
}}
/>
<Text
overflow="hidden"
textOverflow="ellipsis"
whiteSpace="nowrap"
>
{attachment.name}
</Text>
</HStack>
</VStack>
))}
<HStack alignSelf={'start'}>
<Slate
editor={editorsMap.get(message.id)}
initialValue={message.textContent}
>
<Editable
style={{
wordWrap: 'break-word',
overflowWrap: 'break-word',
wordBreak: 'break-all',
whiteSpace: 'normal',
}}
renderElement={renderElement}
renderLeaf={renderLeaf}
readOnly
/>
</Slate>
</HStack>
</VStack>
</VStack>
<VStack alignSelf={'end'}>
<HStack spacing={'5px'}>
<Text color="zinc500">
{new Date(message.sendAt).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
})}
</Text>
{message.status === MessageStatus.FAILED ? (
<Icon
fontSize={'20px'}
as={Clear}
color="red.500"
cursor="pointer"
onClick={() => {}}
/>
) : message.status === MessageStatus.SENDING ? (
<Spinner size={'xs'} thickness="3px" speed="0.5s" />
) : null}
</HStack>
</VStack>
</HStack>
</React.Fragment>
);
})
)}
{messagesLoading && messages.length > 0 && (
<Flex justifyContent="center" alignItems="center" w="100%" h="auto">
<Spinner size="lg" thickness="4px" speed="0.5s" />
</Flex>
)}
</Flex>
);
};
export default MessagesContainer;
|
import {createContext, useState, useEffect, useReducer} from "react";
import {createUserDocumentFromAuth, onAuthStateChangedListener} from "../utils/firebase/firebase.utils";
export const createAction = (type, payload) => ({ type, payload });
export const UserContext = createContext({
currentUser: null,
setCurrentUser: () => null,
})
export const USER_ACTON_TYPES = {
SET_CURRENT_USER: 'SET_CURRENT_USER'
}
const userReducer = (state, action) => {
const { type, payload } = action
switch (type) {
case USER_ACTON_TYPES.SET_CURRENT_USER:
return {
...state, // This is not need, but shows how it would be used
currentUser: payload
}
default:
throw new Error(`Unhandled type ${type}`)
}
}
const INITIAL_STATE = {
currentUser: null
}
export const UserProvider = ({ children }) => {
// const [currentUser, setCurrentUser] = useState(null)
const [state, dispatch] = useReducer(userReducer, INITIAL_STATE)
const { currentUser } = state
const setCurrentUser = (user) => {
dispatch({type: USER_ACTON_TYPES.SET_CURRENT_USER, payload: user})
}
const value = { currentUser, setCurrentUser }
useEffect(() => {
const unsubscribe = onAuthStateChangedListener((user) => {
if (user) {
createUserDocumentFromAuth(user)
}
setCurrentUser(user)
})
return unsubscribe
}, [])
return <UserContext.Provider value={value}>{children}</UserContext.Provider>
}
|
def check_id_valid(id_number):
"""
Check if a given ID number is valid based on validation algorithm.
Args:
id_number (int): The ID to check.
Returns:
bool: Whether or no the id_number is valid
"""
# one liner is split into a 2-liner, for PEP8
# for each dig - (multiply by 2/1) - turn into string and sum THOSE digits
# then, sum the entire thing
# weirdest part - [1, 2][i % 2]
# - if index even (%2=0) - 2, if odd (%2=1) - 1
# (numbers to be mult by [1, 2] are reversed
# because index counts from 0 not 1)
return sum([sum([int(ddig) for ddig in str(int(dig)*([1, 2][i % 2]))])
for i, dig in enumerate(str(id_number))]) % 10 == 0
class IDIterator:
"""
An iterator class that generates valid ID numbers.
This class generates valid IDs numbers starting from an initial value
until reaches the maximum (999999999).
"""
def __init__(self, id):
"""
Initialize the IDIterator with a starting ID number.
Args:
id (int): starting ID number.
"""
self._id = id
def __iter__(self):
"""
Return the iterator object itself.
Returns:
IDIterator: The iterator object.
"""
return self
def __next__(self):
"""
Get the next valid ID number.
Returns:
int: next valid ID number.
Raises:
StopIteration: If ID reached max (max 9-digits num).
"""
if self._id > 999999999:
raise StopIteration
self._id += 1
# add untill good id
while self._id < 999999999 and not check_id_valid(self._id):
self._id += 1
# didn't reach max
if check_id_valid(self._id):
return self._id
# reached max
raise StopIteration
def id_generator(id):
"""
A generator function that yields valid IDs.
Args:
id (int): starting ID number.
Yields:
int: next valid ID number.
Raises:
StopIteration: If ID reached max (max 9-digits num).
"""
while id < 999999999:
while id < 999999999 and not check_id_valid(id):
id += 1
if id > 999999999:
raise StopIteration
yield id
id += 1
def main():
"""
Main function - program's entry point.
Gets ID as an input, and generates the subsequent 10 valid IDs
using either a generator, or an iterator object
- depending on the user's choise
"""
initid = int(input('Enter ID: '))
whichtype = input('Generator or Iterator? (gen/it)? ')
# generalised way of getting iterator/generator
iditer = {
'it': iter(IDIterator(initid)),
'gen': id_generator(initid)
}[whichtype]
# print next 10
for i in range(10):
print(next(iditer))
if __name__ == '__main__':
main()
|
<ul class="blog-list row">
<?php
$current_post_id = get_the_ID();
$current_post_tags = wp_get_post_tags($current_post_id, array('fields' => 'ids'));
$args = array(
'post_type' => 'blog',
'posts_per_page' => -1,
'order' => 'DESC',
);
$query = new WP_Query($args);
$matching_posts = array();
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
$post_tags = wp_get_post_tags(get_the_ID(), array('fields' => 'ids'));
$tag_match = false;
foreach ($post_tags as $post_tag) {
if (in_array($post_tag, $current_post_tags) && get_the_ID() !== $current_post_id) {
$tag_match = true;
break;
}
}
if ($tag_match) {
$matching_posts[] = array(
'date' => get_the_date('d.m.Y'),
'image_id' => get_field('card_image'),
'permalink' => get_the_permalink(),
'title' => get_field('title'),
);
}
endwhile;
wp_reset_postdata();
$counter = 0;
foreach ($matching_posts as $post) {
if ($counter < 4) {
?>
<li class="blog-list__item col-xl-4 col-md-6 <?= ($counter === 4) ? 'd-none d-md-block d-xl-none' : ''; ?>">
<a href="<?= $post['permalink']; ?>" class="blog-list__link">
<div class="blog-list__thumb overflow-hidden">
<?= wp_get_attachment_image($post['image_id'], 'full', false, array('class' => 'blog-list__image')); ?>
</div>
<span class="blog-list__date fw-medium d-inline-block">
<?= date('d.m.Y', strtotime($post['date'])); ?>
</span>
<h2 class="blog-list__title fw-medium mb-0">
<?= $post['title']; ?>
</h2>
</a>
</li>
<?php
$counter++;
} else {
break;
}
}
else :
echo 'Немає постів для відображення.';
endif;
?>
</ul>
|
import BigInt
public typealias PlainText = mod_int
public struct CipherText: Codable {
public let g_r: mod_int
public let g_v__s: mod_int
public let random: mod_int
public static func +(lhs: CipherText, rhs: CipherText) -> CipherText {
CipherText(
g_r: lhs.g_r * rhs.g_r,
g_v__s: lhs.g_v__s * rhs.g_v__s,
random: lhs.random + rhs.random
)
}
}
public struct PublicKey: Codable {
public let p: mod_int
public let q: mod_int
public let h: mod_int
public let g: mod_int
public func encrypt(plain_text: PlainText) -> CipherText {
let random: mod_int = mod_int.rand(upper_bound: q.value)
return CipherText(
g_r: g.pow(power: random),
g_v__s: h.pow(power: random) * g.pow(power: plain_text),
random: random
)
}
public func make_message(value: BigInt) -> PlainText {
mod_int(value: value, modulus: g.modulus)
}
public static let default_key: PublicKey =
PublicKey(
p: PrivateKey.default_key.p,
q: PrivateKey.default_key.q,
h: mod_int(
value: PrivateKey.default_key.g.pow(power: PrivateKey.default_key.x).value,
modulus: PrivateKey.default_key.p.value
),
g: PrivateKey.default_key.g
)
}
public struct PrivateKey: Codable {
public let p: mod_int
public let q: mod_int
public let g: mod_int
public let x: mod_int
public func decrypt(cipher_text: CipherText) -> PlainText {
let g_to_m: mod_int = cipher_text.g_v__s / cipher_text.g_r.pow(power: x)
var i: BigInt = BigInt(0)
while true {
let target: mod_int = mod_int(
value: g.value,
modulus: g_to_m.modulus
).pow(power: mod_int(
value: i,
modulus: g_to_m.modulus
))
if (target == g_to_m) {
return mod_int(value: i, modulus: g_to_m.modulus);
}
i += 1;
}
}
public func make_message(value: BigInt) -> PlainText {
mod_int(value: value, modulus: p.value)
}
public static var default_key: PrivateKey {
let p: mod_int = mod_int(value: BigInt("1449901879557492303016150949425292606294424240059"), modulus: 0)
let q: mod_int = (p - mod_int.from(value: 1)) / mod_int.from(value: 2)
return PrivateKey(
p: p,
q: q,
g: mod_int(value: BigInt("650614565471833138727952492078522919745801716191"), modulus: p.value),
x: mod_int(value: BigInt("896771263533775491364511200158444196377569745583"), modulus: p.value)
)
}
}
|
import type { Meta, StoryObj } from '@storybook/react'
import { Avatar, AvatarProps } from '@faller-bruno-ui/react'
export default {
title: 'Data display/Avatar',
component: Avatar,
tags: ['autodocs', 'surfaces'],
args: {
src: 'https://github.com/fallerbruno.png',
alt: 'Bruno Faller',
},
argTypes: {
src: {
control: {
type: 'text',
},
},
},
} as Meta<AvatarProps>
export const Primary: StoryObj<AvatarProps> = {}
export const WithFallback: StoryObj<AvatarProps> = {
args: {
src: undefined,
},
}
|
package com.website.blogging.implementation;
import java.util.List;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.website.blogging.entities.Category;
import com.website.blogging.exception.ResourceNotFoundException;
import com.website.blogging.payload.CategoryDto;
import com.website.blogging.repository.CategoryRepo;
import com.website.blogging.service.CategoryService;
@Service
public class CategeoryServiceImpl implements CategoryService{
@Autowired
ModelMapper mapper;
@Autowired
CategoryRepo categoryRepo;
@Override
public CategoryDto createCategory(CategoryDto categoryDto) {
Category save = this.categoryRepo.save(this.mapper.map(categoryDto, Category.class));
return this.mapper.map(save, CategoryDto.class);
}
@Override
public CategoryDto updateCategory(CategoryDto categoryDto, int categoryId) {
Category cat = this.categoryRepo.findById(categoryId).orElseThrow(()->new ResourceNotFoundException("Category", "Category Id", categoryId));
cat.setCategoryDescription(categoryDto.getCategoryDescription());
cat.setCategoryTitle(categoryDto.getCategoryTitle());
Category save = this.categoryRepo.save(cat);
return this.mapper.map(save, CategoryDto.class);
}
@Override
public void deleteCategory(int categoryId) {
Category orElseThrow = this.categoryRepo.findById(categoryId).orElseThrow(()->new ResourceNotFoundException("Category", "Category Id", categoryId));
this.categoryRepo.delete(orElseThrow);
}
@Override
public CategoryDto getCategoryById(int categoryId) {
Category orElseThrow = this.categoryRepo.findById(categoryId).orElseThrow(()->new ResourceNotFoundException("Category", "Category Id", categoryId));
return this.mapper.map(orElseThrow, CategoryDto.class);
}
@Override
public List<CategoryDto> getAllCategory() {
List<Category> findAll = this.categoryRepo.findAll();
List<CategoryDto> collect = findAll.stream().map(cat->this.mapper.map(cat, CategoryDto.class)).collect(Collectors.toList());
return collect;
}
}
|
package com.alex_bystrov.safemoney.domain.features.balance
import com.alex_bystrov.safemoney.common.Converter
import com.alex_bystrov.safemoney.data.repository.BalanceDataRepository
import com.alex_bystrov.safemoney.domain.common.DailyTotalModel
import com.alex_bystrov.safemoney.domain.features.balance.model.MonthlyBalanceModel
import com.alex_bystrov.safemoney.domain.features.balance.model.TotalBalanceModel
import com.alex_bystrov.safemoney.domain.features.calculate.CalculationRepository
import com.alex_bystrov.safemoney.domain.features.transactions.models.UserTransactionModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class Balance(
private val balanceLocalDataSource: BalanceDataRepository,
private val calculateRepository: CalculationRepository,
private val converter: Converter
) : BalanceRepository {
override suspend fun getMonthlyBalance(date: String): Flow<MonthlyBalanceModel> {
val yearMonth = converter.convertDateToYearAndMonth(date)
return balanceLocalDataSource.getBalanceFromMonth(yearMonth)
}
override suspend fun getDailyBalance(date: String, transactions: List<UserTransactionModel>): DailyTotalModel {
return calculateRepository.calculateDailyTotal(date, transactions)
}
override suspend fun updateMonthlyBalance(transaction: UserTransactionModel) {
val yearMonth = converter.convertDateToYearAndMonth(transaction.date)
balanceLocalDataSource.getBalanceFromMonth(yearMonth).map { balance ->
val calculatedBalance = calculateRepository.getCalculatedMonthlyBalance(balance = balance, transaction = transaction)
balanceLocalDataSource.updateBalance(calculatedBalance)
}
}
override suspend fun insertMonthlyBalance(balance: MonthlyBalanceModel) {
balanceLocalDataSource.insertBalance(balance = balance)
}
override suspend fun getTotalBalance(): Flow<TotalBalanceModel> {
return balanceLocalDataSource.getTotalBalance()
}
override suspend fun updateTotalBalance(newValue: Double) {
balanceLocalDataSource.updateTotalBalance(newValue = newValue)
}
}
|
<?php
namespace App\Http\Livewire\Admin\Catalogs\Sources;
use App\Abstracts\TableComponent;
use App\Jobs\Indicators\Sources\DeleteSource;
use App\Models\Indicators\Sources\IndicatorSource;
use App\Traits\Jobs;
use function view;
class IndexSources extends TableComponent
{
use Jobs;
public $search = '';
protected $listeners = ['sourceCreated' => 'render'];
protected $queryString = [
'search' => ['except' => ''],
'sortField' => ['except' => ''],
'sortDirection' => ['except' => '']
];
public function render()
{
$sources = IndicatorSource::when($this->search, function ($query) {
$query->where('name', 'iLIKE', '%' . $this->search . '%')
->orWhere('institution', 'iLIKE', '%' . $this->search . '%')
->orWhere('description', 'iLIKE', '%' . $this->search . '%')
->orWhere('type', 'iLIKE', '%' . $this->search . '%');
})->when($this->sortField, function ($q) {
$q->orderBy($this->sortField, $this->sortDirection);
})->paginate(setting('default.list_limit', '25'));
return view('livewire.admin.catalogs.sources.index-sources', compact('sources'));
}
public function cleanFilters()
{
$this->reset(
[
'search',
]);
}
public function delete($id)
{
$response = $this->ajaxDispatch(new DeleteSource($id));
if ($response['success']) {
flash(trans_choice('messages.success.deleted', 0, ['type' => trans_choice('general.sources', 1)]))->success()->livewire($this);;
} else {
flash($response['message'])->error()->livewire($this);;
}
}
}
|
CREATE DATABASE customers_and_orders_db;
USE customers_and_orders_db;
CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(100),
last_name VARCHAR(100),
email VARCHAR(100)
);
CREATE TABLE orders(
id INT AUTO_INCREMENT PRIMARY KEY,
order_date DATE,
amount DECIMAL(8, 2),
customer_id INT,
FOREIGN KEY(customer_id) REFERENCES customers(id)
);
INSERT INTO customers(first_name, last_name, email)
VALUES('George', 'Tudor', '[email protected]'),
('Matthew', 'Baker', '[email protected]'),
('Ray', 'Corona', '[email protected]'),
('Jordan', 'Lafoe', '[email protected]'),
('Jason', 'Maccarthy', '[email protected]'),
('Anthony', 'Villegas', '[email protected]');
INSERT INTO orders(order_date, amount, customer_id)
VALUES ('2016/02/10',99.99 , 1),
('2017/11/11', 35.50, 1),
('2014/12/12', 800.67, 2),
('2015/01/03', 12.50, 2),
('1999/04/11', 450.25, 5);
SELECT * FROM orders;
SELECT * FROM customers;
#### CROSS JOIN ####
# TWO-STEP PROCESS
SELECT * FROM customers WHERE last_name = 'Tudor';
SELECT * FROM orders WHERE customer_id = 1;
# USING SUB-QUERY
SELECT * FROM orders WHERE customer_id =
(
SELECT id FROM customers
WHERE last_name = 'Tudor'
);
# BASIC CROSS JOIN
SELECT * FROM customers, orders;
#### (IMPLICIT) INNER JOIN ####
SELECT * FROM customers, orders WHERE customers.id = orders.customer_id;
SELECT first_name, last_name, order_date, amount FROM customers, orders WHERE customers.id = orders.customer_id;
#### (EXPLICIT) INNER JOIN ####
SELECT * FROM customers JOIN orders ON customers.id = orders.customer_id;
SELECT first_name, last_name, order_date, amount FROM customers JOIN orders ON customers.id = orders.customer_id;
SELECT first_name, last_name, order_date, amount FROM customers JOIN orders ON customers.id = orders.customer_id ORDER BY order_date;
SELECT first_name, last_name, order_date, amount FROM customers JOIN orders ON customers.id = orders.customer_id ORDER BY amount;
#### LEFT JOIN ####
# SET GLOBAL sql_mode = (SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));
SELECT first_name, last_name, order_date, SUM(amount) AS 'total_spent' FROM customers JOIN orders ON customers.id = orders.customer_id GROUP BY orders.customer_id ORDER BY total_spent;
SELECT * FROM customers LEFT JOIN orders ON customers.id = orders.customer_id;
SELECT first_name, last_name, order_date, amount FROM customers LEFT JOIN orders ON customers.id = orders.customer_id;
SELECT first_name, last_name, IFNULL(SUM(amount), 0) AS total_spent FROM customers LEFT JOIN orders ON customers.id = orders.customer_id GROUP BY customers.id ORDER BY total_spent;
#### RIGHT JOIN PT 1 ####
SELECT first_name, last_name, order_date, amount FROM customers RIGHT JOIN orders ON customers.id = orders.customer_id;
#### RIGHT JOINS PT 2 ####
SELECT first_name, last_name, order_date, amount FROM customers RIGHT JOIN orders ON customers.id = orders.customer_id ORDER BY first_name;
#### ON DELETE CASCADE ####
DROP TABLE customers, orders;
CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(100),
last_name VARCHAR(100),
email VARCHAR(100)
);
CREATE TABLE orders(
id INT AUTO_INCREMENT PRIMARY KEY,
order_date DATE,
amount DECIMAL(8, 2),
customer_id INT,
FOREIGN KEY(customer_id) REFERENCES customers(id) ON DELETE CASCADE
);
SELECT * FROM customers;
SELECT * FROM orders;
DELETE FROM customers WHERE email = '[email protected]';
#### JOINS EXERCISES ####
CREATE TABLE students(
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(100)
);
CREATE TABLE papers(
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100),
grade INT,
student_id INT,
FOREIGN KEY(student_id) REFERENCES students(id) ON DELETE CASCADE
);
INSERT INTO students (first_name) VALUES ('Caleb'), ('Samantha'), ('Raj'), ('Carlos'), ('Lisa');
INSERT INTO papers(title, grade, student_id) VALUES
('My First Book Report', 60, 1),
('My Second Book Report', 75, 1),
('Russian Lit Through The Ages', 94, 2),
('De Montaigne and The Art of The Essay', 98, 2),
('Borges and Magical Realism', 89, 4);
#### EXPLICIT INNER JOIN ####
SELECT first_name, title, grade FROM students JOIN papers WHERE students.id = papers.student_id ORDER BY grade DESC;
#### LEFT JOIN ####
SELECT first_name, title, grade FROM students LEFT JOIN papers ON students.id = papers.student_id;
SELECT first_name, IFNULL(title, 'missing'), IFNULL(grade, 0) FROM students LEFT JOIN papers ON students.id = papers.student_id;
SELECT first_name, IFNULL(AVG(grade), 0) AS average FROM students LEFT JOIN papers ON students.id = papers.student_id GROUP BY students.id ORDER BY average DESC;
SELECT first_name, IFNULL(AVG(grade), 0) AS average,
CASE WHEN AVG(grade) >= 75 THEN 'passing' ELSE 'failing' END AS passing_status
FROM students LEFT JOIN papers ON students.id = papers.student_id GROUP BY students.id ORDER BY average DESC;
|
### Futures (Promises)
// Below is first way of running asnchronous code
void main() async{
// Futures (Promises in JS)
// In external apis, we don't know that it will run or not
// Bcz its not dependent on ur code only, it can depend on the internet stability
// For such cases, futures are mostly used in exception handling
// Futures is a class that represents a function or computation which may complete in future
// which will either produce some required output or error
// It is related to asynchronous programming.
// Asynchronous allows u to perform tasks concurrently without blocking the execution unlike the block of code which run synchronously (line by line)
// Like when we make a request for data retrieving from some external api , we don't have to wait for it to execute completely and block the remaining code .
// So in asynchronous, while waiting for data retrieval , the remaining code lines will be performed.
Future<String> giveresultafter2sec(){
return Future((){
return 'Hey';
});
}
final variable = await giveresultafter2sec();
print(variable);
}
// Below is second way of running asynchronous code
void main() async {
Future<String> giveresultafter2sec(){
// Delay of 2 seconds (optional)
return Future.delayed(const Duration(seconds: 2),() async {
return 'Hey';
});
}
print('Hello');
final variable = await giveresultafter2sec();
print(variable);
}
// Below is third way of running the asynchronous code
void main() {
// In this, Hello will print first
// Then, function will wait 2 seconds
// Meanwhile last print statement will be performed
// After 2 seconds , Hey will print out.
Future<String> giveresultafter2sec(){
// Delay of 2 seconds (optional)
return Future.delayed(const Duration(seconds: 2),() async {
return 'Hey';
});
}
print('Hello');
giveresultafter2sec().then((val){
print(val);
});
print('Hellooo');
}
// Here, we have practical example of using external api or servers for data retrieval
// First pkg is from pub dev
// Second pkg is from dart itself implementd
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() async {
var url = Uri.https('jtonplaceholder.typicode.com', 'users');
try{
final res = await http.get(url);
print(jsonDecode(res.body)[0]['name']);
}
catch (e){
print(e);
}
}
// We can also do the above task in this way defined below
// First pkg is from pub dev
// Second pkg is from dart itself implementd
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
var url = Uri.https('jtonplaceholder.typicode.com', 'users');
http.get(url).then((val){
print(jsonDecode(val.body)[0]['name']);}).catchError((err)
{
print(err);
});
}
### Stream
// Stream is also related to asynchronous programming
// But in this, we get updated values from time to time from external api/server
// For this, we don't make a request like in future rather we subscribe to an event (Event is whether the values change or not)
// In this way, we get updated time to time and we have sequence of values in the end.
// async* is used where Stream concept is used
void main() async{
//print(await countDown().first); //will print first value
// this stream func allows to pause, resume, cancel the flow of data coming to us
// onDone is a data handler of stream
countDown().listen((val){
print(val);
}, onDone: (){
print('Completed!');
});
}
// Due to async* , we can't use return bcz of stream creation
Stream<int> countDown() async* {
for(int i=5;i>0;i--){
yield i; // for generating values one by one
await Future.delayed(const Duration(seconds: 1));
}
}
// Similarly, we have another way to create a countdown using stream controller where we may pause , resume, it.
|
//
// QRCodeScannerViewController.swift
// Airport
//
// Created by RUBING MAO on 4/26/16.
// Copyright © 2016 RUBING MAO. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
class QRCodeScannerViewController : UIViewController, AVCaptureMetadataOutputObjectsDelegate {
//Access to camera:http://www.theappguruz.com/blog/qrcode-reader-using-swift
@IBOutlet weak var QRcodeResult: UILabel!
var objCaptureSession:AVCaptureSession?
var objCaptureVideoPreviewLayer:AVCaptureVideoPreviewLayer?
var vwQRCode:UIView?
func configureVideoCapture() {
let objCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error:NSError?
let objCaptureDeviceInput: AnyObject!
do {
objCaptureDeviceInput = try AVCaptureDeviceInput(device: objCaptureDevice) as AVCaptureDeviceInput
} catch let error1 as NSError {
error = error1
objCaptureDeviceInput = nil
}
if (error != nil) {
let alertView:UIAlertView = UIAlertView(title: "Device Error", message:"Device not Supported for this Application", delegate: nil, cancelButtonTitle: "Ok Done")
alertView.show()
return
}
objCaptureSession = AVCaptureSession()
objCaptureSession?.addInput(objCaptureDeviceInput as! AVCaptureInput)
let objCaptureMetadataOutput = AVCaptureMetadataOutput()
objCaptureSession?.addOutput(objCaptureMetadataOutput)
objCaptureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
objCaptureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
}
func addVideoPreviewLayer()
{
objCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: objCaptureSession)
objCaptureVideoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
objCaptureVideoPreviewLayer?.frame = view.layer.bounds
self.view.layer.addSublayer(objCaptureVideoPreviewLayer!)
objCaptureSession?.startRunning()
self.view.bringSubviewToFront(QRcodeResult)
}
func initializeQRView() {
vwQRCode = UIView()
vwQRCode?.layer.borderColor = UIColor.redColor().CGColor
vwQRCode?.layer.borderWidth = 5
self.view.addSubview(vwQRCode!)
self.view.bringSubviewToFront(vwQRCode!)
}
//optional func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!);
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
if metadataObjects == nil || metadataObjects.count == 0 {
vwQRCode?.frame = CGRectZero
QRcodeResult.text = "NO QRCode text detacted"
return
}
let objMetadataMachineReadableCodeObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
if objMetadataMachineReadableCodeObject.type == AVMetadataObjectTypeQRCode {
let objBarCode = objCaptureVideoPreviewLayer?.transformedMetadataObjectForMetadataObject(objMetadataMachineReadableCodeObject as AVMetadataMachineReadableCodeObject) as! AVMetadataMachineReadableCodeObject
vwQRCode?.frame = objBarCode.bounds;
if objMetadataMachineReadableCodeObject.stringValue != nil {
QRcodeResult.text = objMetadataMachineReadableCodeObject.stringValue
}
}
}
override func viewDidLoad()
{
super.viewDidLoad()
self.configureVideoCapture()
self.addVideoPreviewLayer()
self.initializeQRView()
}
}
|
<template>
<div>
<spinner v-if="is_loading"></spinner>
<b-form @submit.prevent="updateNewProject" v-else>
<div class="row pe-3 ps-3">
<div class="col-12">
<div class="err" v-if="error">{{ error_message_ar }}</div>
</div>
<div class="col-12">
<div class="form-group">
<span>الإسم بالعربي</span>
<b-form-input className="input" type="text" v-model="app.title_ar" required></b-form-input>
</div>
</div>
<div class="col-12">
<div class="form-group">
<span>الإسم بالانجليزي</span>
<b-form-input className="input" type="text" v-model="app.title_en" required></b-form-input>
</div>
</div>
<div class="col-12">
<div class="form-group">
<span>الوصف بالعربي</span>
<b-form-input className="input" type="text" v-model="app.description_ar" required></b-form-input>
</div>
</div>
<div class="col-12">
<div class="form-group">
<span>الوصف بالانجليزي</span>
<b-form-input className="input" type="text" v-model="app.description_en" required></b-form-input>
</div>
</div>
<div class="col-12">
<div class="form-group">
<span>ال url ( في حاله ال mobile app يكون url الاندرويد)</span>
<b-form-input className="input" type="text" v-model="app.link1" required></b-form-input>
</div>
</div>
<div class="col-12">
<div class="form-group">
<span>ال url ( خاص بال mobile app يكون url الايفون)</span>
<b-form-input className="input" type="text" v-model="app.link2"></b-form-input>
</div>
</div>
<div class="col-12">
<div class="form-group">
<span>ال url الخاص بفيديو الموشن جرافيك</span>
<div v-if="display_video">
<iframe :src="app.video"></iframe>
</div>
<div v-else>
<b-form-input className="input" type="text" v-model="app.video"></b-form-input>
<button class="btn" @click="addVideo">عرض الفيديو</button>
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<span>الوجو</span>
<b-form-file plain @change="addLogoPhoto"></b-form-file>
</div>
<div class="img">
<img v-if="app.logo" :src="app.logo">
</div>
</div>
<div class="col-12">
<div class="form-group">
<span>الصور</span>
<i @click="addNewImage" class="fas fa-plus"></i>
</div>
<div class="images">
<div class="border p-2 m-2"
v-for="(image, index) in this.app.attachs" :key="image.id">
<div class="d-flex justify-content-between align-items-center pe-2 ps-2">
<i @click="addToRemoveList(image.id, index)" class="fas fa-trash"></i>
</div>
<div class="img mt-2">
<img :src="image.attach">
</div>
</div>
</div>
<div class="images">
<div class="border p-2 m-2"
v-for="(image, index) in images" :key="image.id">
<div class="d-flex justify-content-between align-items-center pe-2 ps-2">
<b-form-file plain @change="addImage($event, index)" required></b-form-file>
<i @click="deleteImage(index)" class="fas fa-trash"></i>
</div>
<div class="img mt-2">
<img :src="image.image_src">
</div>
</div>
</div>
</div>
<div class="col-12 justify-content-end">
<b-button type="submit" className="btn">حفظ</b-button>
</div>
</div>
</b-form>
</div>
</template>
<script>
import Spinner from "@/components/ui/Spinner";
import router from "@/router";
export default {
// eslint-disable-next-line vue/multi-word-component-names
name: "Edit",
components: {Spinner},
data() {
return {
is_loading: false,
error: false,
error_message_ar: '',
app: '',
logo_file: '',
display_video: false,
images: [
{ id: new Date(), image_src: '', image_file: '' },
],
removeList: [],
}
},
created() {
this.loadProject(this.$route.params.id);
},
methods: {
addLogoPhoto(e) {
this.logo_file = e.target.files[0];
this.$emit('input', this.logo_file);
let reader = new FileReader();
reader.readAsDataURL(this.logo_file);
reader.onload = e => {
this.app.logo = e.target.result;
}
},
addImage(e, index) {
this.images[index].image_file = e.target.files[0];
this.$emit('input', this.images[index].image_file);
let reader = new FileReader();
reader.readAsDataURL(this.images[index].image_file);
reader.onload = e => {
this.images[index].image_src = e.target.result;
}
},
addNewImage() {
this.images.push({ id: new Date(), image_src: '', image_file: '' })
},
deleteImage(index) {
this.images.splice(index, 1);
},
addToRemoveList(id, index) {
this.app.attachs.splice(index, 1);
this.removeList.push({ id: id });
},
addVideo() {
const youtube = `https://www.youtube.com/embed/${this.app.video_link.slice(this.app.video_link.indexOf("=") + 1)}?controls=0`
this.app.video = youtube;
this.display_video = true
},
async loadProject(id) {
this.is_loading = true;
let myHeaders = new Headers();
let token = this.$store.getters.token;
myHeaders.append("Authorization", "Bearer " + token);
let requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
let url = `https://api.we-work.pro/api/user/get-project/` + id;
await fetch(url, requestOptions)
.then(response => response.json())
.then(result => {
if (!result.status) {
this.error = true;
this.error_message_ar = result.msg;
} else {
this.app = result.data.project;
}
})
.catch(error => {
this.error = true;
this.error_message_ar = error.message;
});
this.is_loading = false;
},
async updateNewProject() {
this.is_loading = true;
this.error = false;
let myHeaders = new Headers();
let token = this.$store.getters.token;
myHeaders.append("Authorization", "Bearer " + token);
let formdata = new FormData();
formdata.append("sub_category_id", this.$route.params.id);
formdata.append("title_en", this.app.title_en);
formdata.append("title_ar", this.app.title_ar);
formdata.append("description_en", this.app.description_en);
formdata.append("description_ar", this.app.description_ar);
formdata.append("link1", this.app.link1);
formdata.append("link2", this.app.link2);
formdata.append("logo", this.logo_file);
if (this.images.length > 0) {
console.log("this.images.length > 0")
this.images.forEach((value, index) => {
formdata.append('attach[' + index + ']', value.image_file);
})
}
if (this.removeList.length > 0) {
console.log("this.removeList.length > 0")
this.removeList.forEach((value, index) => {
formdata.append('deleted_attaches[' + index + ']', value.id);
})
}
let requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
let url = `https://api.we-work.pro/api/admin/auth/update-project/` + this.app.id;
await fetch(url, requestOptions)
.then(response => response.json())
.then(result => {
if (!result.status) {
this.error = true;
this.error_message_ar = result.msg;
} else {
router.push('/dashboard/projects/item/items/' + this.app.sub_category_id)
}
})
.catch(error => {
this.error = true;
this.error_message_ar = error.message;
});
this.is_loading = false
}
}
}
</script>
<style lang="scss" scoped>
@import "../../../../assets/css/variables";
@import "../../../../assets/css/mixins";
@import "../../../../assets/css/dashboard";
i {
cursor: pointer;
}
.images {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
</style>
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PathfinderPro.Business;
using System;
using System.Collections.Generic;
using System.IO;
namespace Pathfinder.Tests
{
[TestClass]
public class PathfinderServiceTests
{
private PathfinderService _pathfinderService;
private GraphService _graphService;
private List<Node> _graph;
private readonly string dataFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data", "GraphData.json");
[TestInitialize]
public void Setup()
{
_pathfinderService = new PathfinderService();
_graphService = new GraphService();
_graph = _graphService.GetGraph(dataFilePath);
}
[TestMethod]
public void TestShortestPath()
{
string startNodeName = "A";
string endNodeName = "E";
int expectedDistance = 9;
List<string> expectedPath = new List<string> { "A", "B", "F", "E" };
var result = _pathfinderService.ShortestPath(startNodeName, endNodeName, _graph);
Assert.IsNotNull(result, "Result should not be null for a valid path.");
Assert.AreEqual(expectedDistance, result.Distance, "The calculated distance is incorrect.");
CollectionAssert.AreEqual(expectedPath, result.NodeNames, "The calculated path is incorrect.");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TestShortestPathWithInvalidStartNode()
{
string startNodeName = "K";
string endNodeName = "E";
_pathfinderService.ShortestPath(startNodeName, endNodeName, _graph);
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException))]
public void TestShortestPathWithInvalidEndNode()
{
string startNodeName = "A";
string endNodeName = "J";
_pathfinderService.ShortestPath(startNodeName, endNodeName, _graph);
}
[TestMethod]
public void TestShortestPathWithUnreachableDestination()
{
// Setup a graph where a node is unreachable
// A --1--> B, with C being unreachable
Node nodeA = new Node { Name = "A", Edges = new List<Edge>() };
Node nodeB = new Node { Name = "B", Edges = new List<Edge>() };
Node nodeC = new Node { Name = "C", Edges = new List<Edge>() }; // Unreachable node
nodeA.Edges.Add(new Edge { Target = nodeB, Distance = 1 });
List<Node> graph = new List<Node> { nodeA, nodeB, nodeC };
PathfinderService pathfinderService = new PathfinderService();
string startNodeName = "A";
string endNodeName = "C";
var result = pathfinderService.ShortestPath(startNodeName, endNodeName, graph);
Assert.IsNull(result, "Result should be null for an unreachable destination.");
}
}
}
|
from fastapi import APIRouter, Depends , HTTPException
from pydantic import BaseModel
from passlib.context import CryptContext
from models import Users
from database import SessionLocal
from sqlalchemy.orm import Session
from typing import Annotated
from starlette import status
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
from jose import jwt, JWTError # type: ignore
from datetime import timedelta, datetime, timezone
router = APIRouter(
prefix='/auth',
tags=['Authentication']
)
SECRET_KEY = 'f57a2d96eb959426d8d1172e2c589a4d84b76ae397236f452a2cbf8eed252dd1e0efd6f49a358da66969b73abd8b039ca82c450d7e05f3d74086c130a83bf005'
ALGORITHM = 'HS256'
bcrypt_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_bearer = OAuth2PasswordBearer(tokenUrl='auth/token')
# This is used for validation of user request
class CreateUserRequest(BaseModel):
email: str
username: str
password: str
first_name: str
last_name: str
role: str
phone_number : str
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
db_dependency = Annotated[Session, Depends(get_db)]
def authenticate_user(username : str,password : str, db):
user = db.query(Users).filter(Users.username == username).first()
if not user:
return False
if not bcrypt_context.verify(password,user.hashed_password):
return False
return user
def create_access_token(username : str, user_id : int, role : str,expires_delta : timedelta):
encode = {
'sub': username,
'id': user_id,
'role': role
}
expires = datetime.utcnow() + expires_delta
encode.update({'exp': expires})
return jwt.encode(encode, SECRET_KEY, algorithm=ALGORITHM)
async def get_current_user(token : Annotated[str, Depends(oauth2_bearer)]):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms = [ALGORITHM])
username :str = payload.get('sub')
user_id : int = payload.get('id')
user_role : str = payload.get('role')
if username is None and user_id is None:
raise HTTPException(status_code = status.HTTP_401_UNAUTHORIZED, detail = 'Could Not validate User')
return {'username': username, 'id': user_id, 'user_role': user_role}
except JWTError:
raise HTTPException(status_code = status.HTTP_401_UNAUTHORIZED, detail = 'Could Not validate User')
@router.post("/", status_code = status.HTTP_201_CREATED)
async def create_user(db : db_dependency,create_user_request : CreateUserRequest):
create_user_model = Users(
email = create_user_request.email,
username = create_user_request.username,
first_name = create_user_request.first_name,
last_name = create_user_request.last_name,
role = create_user_request.role,
hashed_password = bcrypt_context.hash(create_user_request.password),
is_active = True,
phone_number = create_user_request.phone_number
)
db.add(create_user_model)
db.commit()
@router.post("/token")
async def login_for_access_token(form_data: Annotated[OAuth2PasswordRequestForm, Depends()], db: db_dependency):
user = authenticate_user(form_data.username,form_data.password,db)
if not user:
raise HTTPException(status_code = status.HTTP_401_UNAUTHORIZED, detail = 'Could Not validate User')
token = create_access_token(user.username,user.id,user.role, timedelta(minutes=20))
return {"access_token": token, "token_type": "bearer"}
|
import { parseLiteralOccurenceList } from './parse-literal-occurence-list';
import { createSourceFile, formatGQL } from '../utils/test-utils';
describe('Parse literal occurence list', () => {
it('parse literal occurence list', () => {
const code = `
import { VendorProductListItem } from 'web-client/components/organisms';
import { CartItemRemoved } from 'web-client/components/organisms/cart/cartList/CartItemRemoved';
import { useCart } from 'web-client/components/organisms/cart/hooks/UseCart';
import { ProductFromVendorProductContextProvider } from 'web-client/components/organisms/product/context/ProductContext';
import { VendorProductContextProvider } from 'web-client/components/organisms/product/context/VendorProductContext';
import { useTranslate } from '@reparcar/translation';
import React from 'react';
import { IRIUtils } from '@reparcar/common';
import BottomText from '../bottomText/BottomText';
import { EmptyCart } from '../emptyCart/EmptyCart';
import styles from './CartList.module.scss';
import { useOrderCartItemDeleteMutation, refetchOrderCartQuery } from '@reparcar/network-order';
import { useGraphQLArray } from '@reparcar/network-utils';
import { Spinner } from '@reparcar/ui';
import { useCartPrice } from 'web-client/components/organisms/cart/hooks/UseCartPrice';
export const CartList: React.FC = () => {
const { t } = useTranslate();
const { data: cartData, loading } = useQuery(gql(\`
query User($id: ID!) {
user(id: $id) {
id
name
}
users {
id
email
}
}
\`));
const cartItems = useGraphQLArray(cartData?.cartItems);
const [deleteCartItem] = useOrderCartItemDeleteMutation(
gql(\`
mutation UserDelete($id: ID!) {
user(id: $id) {
id
name
}
}
\`), {
refetchQueries: [
refetchOrderCartQuery({
token: cartData?.token,
}),
],
awaitRefetchQueries: true,
});
const [removedVendorProductId, setRemovedVendorProductId] = React.useState<string | null>(null);
const cartPrice = useCartPrice();
return (
<div>
{removedVendorProductId && (
<VendorProductContextProvider value={removedVendorProductId}>
<ProductFromVendorProductContextProvider>
<CartItemRemoved />
</ProductFromVendorProductContextProvider>
</VendorProductContextProvider>
)}
{loading ? <Spinner /> : <div>foo</div>}
<BottomText />
</div>
);
};
export default CartList;
`;
expect(
parseLiteralOccurenceList(createSourceFile(code)).map((source) =>
formatGQL(source.body)
)
).toEqual([
formatGQL(`
query User($id: ID!) {
user(id: $id) {
id
name
}
users {
id
email
}
}
`),
formatGQL(`
mutation UserDelete($id: ID!) {
user(id: $id) {
id
name
}
}
`),
]);
});
it('ignores comments', () => {
const code = `
import { VendorProductListItem } from 'web-client/components/organisms';
import { CartItemRemoved } from 'web-client/components/organisms/cart/cartList/CartItemRemoved';
import { useCart } from 'web-client/components/organisms/cart/hooks/UseCart';
import { ProductFromVendorProductContextProvider } from 'web-client/components/organisms/product/context/ProductContext';
import { VendorProductContextProvider } from 'web-client/components/organisms/product/context/VendorProductContext';
import { useTranslate } from '@reparcar/translation';
import React from 'react';
import { IRIUtils } from '@reparcar/common';
import BottomText from '../bottomText/BottomText';
import { EmptyCart } from '../emptyCart/EmptyCart';
import styles from './CartList.module.scss';
import { useOrderCartItemDeleteMutation, refetchOrderCartQuery } from '@reparcar/network-order';
import { useGraphQLArray } from '@reparcar/network-utils';
import { Spinner } from '@reparcar/ui';
import { useCartPrice } from 'web-client/components/organisms/cart/hooks/UseCartPrice';
export const CartList: React.FC = () => {
const { t } = useTranslate();
const { data: cartData, loading } = useQuery(gql(\`
query User($id: ID!) {
user(id: $id) {
id
name
}
users {
id
email
}
}
\`));
const cartItems = useGraphQLArray(cartData?.cartItems);
/*
const [deleteCartItem] = useOrderCartItemDeleteMutation(
gql(\`
mutation UserDelete($id: ID!) {
user(id: $id) {
id
name
}
}
\`), {
refetchQueries: [
refetchOrderCartQuery({
token: cartData?.token,
}),
],
awaitRefetchQueries: true,
});
*/
const [removedVendorProductId, setRemovedVendorProductId] = React.useState<string | null>(null);
const cartPrice = useCartPrice();
return (
<div>
{removedVendorProductId && (
<VendorProductContextProvider value={removedVendorProductId}>
<ProductFromVendorProductContextProvider>
<CartItemRemoved />
</ProductFromVendorProductContextProvider>
</VendorProductContextProvider>
)}
{loading ? <Spinner /> : <div>foo</div>}
<BottomText />
</div>
);
};
export default CartList;
`;
expect(
parseLiteralOccurenceList(createSourceFile(code)).map((source) =>
formatGQL(source.body)
)
).toEqual([
formatGQL(`
query User($id: ID!) {
user(id: $id) {
id
name
}
users {
id
email
}
}
`),
]);
});
it('ignore syntax errors', () => {
const code = `
import { VendorProductListItem } from 'web-client/components/organisms';
import { CartItemRemoved } from 'web-client/components/organisms/cart/cartList/CartItemRemoved';
import { useCart } from 'web-client/components/organisms/cart/hooks/UseCart';
import { ProductFromVendorProductContextProvider } from 'web-client/components/organisms/product/context/ProductContext';
import { VendorProductContextProvider } from 'web-client/components/organisms/product/context/VendorProductContext';
import { useTranslate } from '@reparcar/translation';
import React from 'react';
import { IRIUtils } from '@reparcar/common';
import BottomText from '../bottomText/BottomText';
import { EmptyCart } from '../emptyCart/EmptyCart';
import styles from './CartList.module.scss';
import { useOrderCartItemDeleteMutation, refetchOrderCartQuery } from '@reparcar/network-order';
import { useGraphQLArray } from '@reparcar/network-utils';
import { Spinner } from '@reparcar/ui';
import { useCartPrice } from 'web-client/components/organisms/cart/hooks/UseCartPrice';
export const CartList: React.FC = () => {
const { t } = useTranslate();
const { data: cartData, loading } = useQuery(gql(\`
query User($id: ID!) {
user(id: $id) {
id
name
}
users {
id
email
}
}
\`));
const cartItems = useGraphQLArray(cartData?.cartItems);
\`
const [deleteCartItem] = useOrderCartItemDeleteMutation(
gql(\`
mutation UserDelete($id: ID!) {
user(id: $id) {
id
name
}
}
\`), {
refetchQueries: [
refetchOrderCartQuery({
token: cartData?.token,
}),
],
awaitRefetchQueries: true,
});
const [removedVendorProductId, setRemovedVendorProductId] = React.useState<string | null>(null);
const cartPrice = useCartPrice();
return (
<div>
{removedVendorProductId && (
<VendorProductContextProvider value={removedVendorProductId}>
<ProductFromVendorProductContextProvider>
<CartItemRemoved />
</ProductFromVendorProductContextProvider>
</VendorProductContextProvider>
)}
{loading ? <Spinner /> : <div>foo</div>}
<BottomText />
</div>
);
};
export default CartList;
`;
expect(
parseLiteralOccurenceList(createSourceFile(code)).map((source) =>
formatGQL(source.body)
)
).toEqual([
formatGQL(`
query User($id: ID!) {
user(id: $id) {
id
name
}
users {
id
email
}
}
`),
]);
});
});
|
import React, {createContext, useContext, useState, useEffect} from 'react';
import axios from 'axios';
import {AuthContext} from './AuthContext';
import createAuthRefreshInterceptor from 'axios-auth-refresh';
import * as Keychain from 'react-native-keychain';
import NetInfo from "@react-native-community/netinfo";
const AxiosContext = createContext();
const {Provider} = AxiosContext;
const AxiosProvider = ({children}) => {
const authContext = useContext(AuthContext);
const authAxios = axios.create({
baseURL: 'https://ac01-105-113-20-251.ngrok-free.app',
});
const publicAxios = axios.create({
baseURL: "https://f78c-62-173-62-83.ngrok-free.app",
});
authAxios.interceptors.request.use(
config => {
if (!config.headers.Authorization) {
config.headers.Authorization = `Bearer ${authContext.getAccessToken()}`;
console.log(config.headers.Authorization)
}
return config;
},
error => {
return Promise.reject(error);
},
);
const refreshAuthLogic = failedRequest => {
const data = {
refreshToken: authContext.authState.refreshToken,
};
const options = {
method: 'POST',
data,
url: `https://f78c-62-173-62-83.ngrok-free.app/api/refreshToken`,
};
return axios(options)
.then(async tokenRefreshResponse => {
failedRequest.response.config.headers.Authorization =
'Bearer ' + tokenRefreshResponse.data.accessToken;
authContext.setAuthState({
...authContext.authState,
accessToken: tokenRefreshResponse.data.accessToken,
});
await Keychain.setGenericPassword(
'token',
JSON.stringify({
accessToken: tokenRefreshResponse.data.accessToken,
refreshToken: authContext.authState.refreshToken,
}),
);
return Promise.resolve();
})
.catch(e => {
authContext.setAuthState({
accessToken: null,
refreshToken: null,
});
});
};
createAuthRefreshInterceptor(authAxios, refreshAuthLogic, {});
return (
<Provider
value={{
authAxios,
publicAxios,
}}>
{children}
</Provider>
);
};
export {AxiosContext, AxiosProvider};
|
<img src="https://media.discordapp.net/attachments/812014361752895529/931258758082998324/Opera_senza_titolo_80.png" data-canonical-src="https://gyazo.com/eb5c5741b6a9a16c692170a41a49c858.png" width="200" height="200" />
# Citronetto - A general purpose and study bot
Citronetto is a Discord bot whose main features place the user's wellbeing at the very centre. We believe that quality should be privileged over quantity and in that spirit the bot's features put an equal emphasis on social activities as on productivity. Created for Lemonsalt's community on Discord, the bot will be made publicly available after the alpha release.
[**Invite Citronetto here** (coming soon)](https://www.lemonsalt.studio/), and get started with `/help`.
## 💭 Philosophy
------------
We strive for balance between hard cramming work evenings and social life during the pandemic.
Join our study community on [Discord](https://discord.gg/XFv6cYQQfv).
## 📙 Features
------------
Citronetto has the following primary features:
- **Advanced study room system**
With many features to come
- **To-Do List**
With many features to come.
## 🎯 Roadmap
------------
### 🍅 Pomodoro system
- [ ] Individual pomodoro timers.
- [ ] Add an audio alert for the pomo timer.
- [ ] Pomodoro timer: The bot will show the timer in the title of the study room and play a sound at the start and end of each session.
- [ ] Whoever joins a pomo session will get notified whenever there's a break and will get a reward once the session is done.
### 🗒 Todo list system
- [ ] Privacy mode for the todo list.
- [ ] Private / public reminder for a task.
- [ ] Rather than an embed message for the todo list, make one using a canvas and display the final image through an embed.
- [ ] Allow the user to modify a message in the todo list.
### 🎙 Server channels
- [ ] Camera-only channels.
- [ ] Channel to find a study buddy (in case you are not automatically matched) using a recommender system.
- [ ] Drink Water Alert reminding you to drink water every 60 minutes.
- [ ] Study rooms with custom musics (lofi, hogwards, ...)
- [ ] Bug & Feature command/channel to report a bug or possible improvements.
- [ ] Topic analysis system that changes the channel's name according to the topic.
- [ ] Personal study rooms (for subscribers?).
- [ ] Accountability Rooms: This feature allows the users to use their coins to schedule a time to study at. Not attending prevents everyone in the room from getting the bonus.
- [ ] Private Study Room: Allows the members to create their own private study rooms and invite their friends to join!
### 🛠 Server Settings
- [ ] Deep focus mode (No notifications)
- [ ] Link the server to Disboard and implement a bump reminder.
- [ ] Moderation logs
- [ ] Love rate on the server based on emojis and messages.
- [ ] Announcements linked to LemonSalt's channel.
- [ ] Provide a dashboard for mods.
- [ ] Full-Scale Moderation System: Punish cheaters, audit-log, welcome message, and so much more using our full-scale moderation system.
- [ ] Goal Management System: /set <my goal> <option: daily, weekly, monthly>: Sends a message in the corresponding channel making sure you've completed your goal.
- [ ] Report/Ticket System: Members can send issues or reports over someone to a specific channel. Based on each member's issues posted and whether or not the accused has received a significant number of reports. A human may give the sentence.
- [ ] Guidelines: In order to avoid an extensive number of channels related to the server and his inner working / guidelines and rules, provide a single channel wherein you can move through the different topics and sets of rules / tutos via a reactions system.
- [ ] Horizontal scrolling system for embeds.
- [ ] Subscription system
- [ ] Ban words
### 🪄 Social
- [ ] Choose your field of study: Add a role related to your field of study and/ or your professional status.
- [ ] Schedule a study session with your friends and or your study gang and get rewarded.
- [ ] Birthday messages
- [ ] Language roles
- [ ] ID cards
- [ ] Create statistics of who likes who based on server's messages and activity.
- [ ] Work Partner Feature: Finds you a work partner for the day. You check on each other. Lasts for 8 hours.
- [ ] /gangs: Display a ranking of study gangs on the server.
### 🎰 Games
- [ ] Language game invented by @ian#7518
- [ ] Implement drinking games or link them through a channel.
- [ ] Lottery
### 🎲 Miscellaneous features
- [ ] /timezone
- [ ] Send a message to members who have set their location to remind them to go take a walk outside when it's sunny.
- [ ] Music bot
- [ ] Greetings Reaction System: Make the bot react to greeting messages. Detect them through a dictionary, regex, or NLP.
### 💰 Economy
- [ ] Each person earns (money?) by getting reactions to his message(s). Each reaction has a different weight depending on the emote.
- [ ] Full-Scale Economy System: Reward users for studying, allow them to use the coins to buy private study rooms, schedule accountability rooms, and even change their name's color.
- [ ] `/invest @<user>`
- [ ] `/loan <amount>`: Make a loan. The allowance is determined by an algorithm that favours "good members".
- [ ] `/assets`: display user's assets
### 🛒 Shop
- [ ] Buy role colours.
- [ ] Buy special roles and special accesses to secret rooms.
- [ ] Buy ad alerts.
- [ ] Change your name.
- [ ] Change someone else's name.
- [ ] Member can sell items for a chosen amount. Whenever someone buys it the member who created the item will get a reward with a percentage of the price.
[]: # (- [ ] Ad system on the server where in exchange of real money or server points one can make an announcement of his choice (Discord server, twitch, whatever...))
[]: # (- [ ] Member can create events and will get rewarded in the same fashion as above.)
[]: # (- [ ] Marketplace system)
[]: # (- [ ] Members can create events and get rewarded for doing so based on the number of activity it generates.)
[]: # (### ⭐️ Popularity Feature)
[]: # (- [ ] Reactions to your message improve you popularity rate.)
[]: # (- [ ] Tags improve your popularity rate.)
[]: # (- [ ] Litterature review on popularity metrics for online communities.)
[]: # (------)
[]: # (__Disclaimer__: The aformentioned ideas are yet to be implemented. To submit your idea for the bot feel free to tag one of the mods on the server!)
[]: # (## ❗️ Information)
[]: # (------------)
A command list and general documentation for Citronetto may be found using the `\help` command.
Make sure to check the [full documentation](https://www.notion.so/nicograssetto/Citronetto-bd11b555c2a24bc692525fe0c903c59b) to stay updated.--->
|
import { ReactElement, useContext, useEffect } from "react";
import { createContext, useState } from "react";
import Axios from "../../services/caller.service";
import { useLogin } from "../LoginContextProvider"
import { CanceledError } from "axios";
interface Response {
user: {
candidateEvents: CandidateEvent[];
};
}
export interface CandidateEvent {
id: number;
participants_number: number;
category: string;
description: string;
image_url: string;
name: string;
date: string;
creation_date: string;
organizerId: number;
MainCategoryId: number;
AddressId: number;
MainCategory: {
id: number;
name: string;
};
Address: {
id: number;
street: string;
city: string;
country: string;
zip: string;
};
}
const MyApplicationsContext = createContext<[CandidateEvent[], boolean, string, (eventId: number) => void]>([
[],
false,
"",
() => { },
]);
export const useMyApplications = () => {
return useContext(MyApplicationsContext)
};
interface Props {
children: ReactElement;
}
const MyApplicationsContextProvider = ({ children }: Props) => {
const [events, setEvents] = useState<CandidateEvent[]>([]);
const [isLoading, setLoading] = useState(false);
const [error, setError] = useState("");
const [isLogged, isL, e, login, logout, getUserData] = useLogin();
const fetchData = (controller: AbortController, idUser: number) => {
setError("");
setLoading(true);
return Axios.get<Response>(`/users`, {
signal: controller.signal,
params: { id: idUser, include_candidateEvents: true },
})
.then((res) => {
if (res && res.data) {
setEvents(res.data.user.candidateEvents);
}
})
.catch((err) => {
if (!(err instanceof CanceledError)) {
setError(err.message);
}
})
.finally(() => {
setLoading(false);
});
};
const cancelApplication = (eventId: number) => {
setError("");
const user = getUserData();
if (!user) return
setLoading(true);
Axios.post(`/events/${eventId}/unapply`, {
})
.then((res) => {
if (!res) return;
const controller = new AbortController();
fetchData(controller, user.id)
})
.catch((err) => {
if (!(err instanceof CanceledError)) {
setError(err.message);
setLoading(false);
}
})
};
useEffect(() => {
const controller = new AbortController();
const user = getUserData();
if (!user) return
fetchData(controller, user.id)
return () => controller.abort();
}, []);
return (
<MyApplicationsContext.Provider value={[events, isLoading, error, cancelApplication]}>
{children}
</MyApplicationsContext.Provider>
);
};
export default MyApplicationsContextProvider;
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace CommandPattern.Core.Contracts
{
public class CommandInterpreter : ICommandInterpreter
{
public string Read(string args)
{
string[] arguments = args.Split(" ", StringSplitOptions.RemoveEmptyEntries);
string commandName = arguments[0];
string[] commandArguments = arguments.Skip(1).ToArray();
Type commandType = Assembly
.GetEntryAssembly()
.GetTypes()
.Where(x => x.IsClass)
.FirstOrDefault(x => x.Name == $"{commandName}Command");
if (commandType == null)
{
throw new InvalidOperationException("Command not found!");
}
ICommand command = Activator.CreateInstance(commandType) as ICommand;
if (command == null)
{
throw new InvalidOperationException("Command not found!");
}
return command.Execute(commandArguments);
}
}
}
|
import {
Body,
Controller,
Get,
Param,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import { MessageDto } from './dto';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { AuthGuard } from 'src/auth/auth.guard';
import { MessageService } from './message.service';
import { Request } from 'express';
@Controller('message')
@ApiBearerAuth()
@ApiTags('messages')
@UseGuards(AuthGuard)
export class MessageController {
constructor(private readonly messageService: MessageService) {}
@Post()
async postMessage(@Body() dto: MessageDto, @Req() req: Request) {
return this.messageService.postMessage(dto, req);
}
@Get(':username')
async getPrivMessage(
@Param('username') username: string,
@Req() req: Request,
) {
return this.messageService.getPrivMessage(username, req);
}
}
|
import React from 'react';
import { ComponentStory, ComponentMeta } from '@storybook/react';
import MoviesGenre from './index';
// More on default export: https://storybook.js.org/docs/react/writing-stories/introduction#default-export
const meta = {
title: 'Components/MoviesGenre',
component: MoviesGenre,
// More on argTypes: https://storybook.js.org/docs/react/api/argtypes
argTypes: {
backgroundColor: { control: 'color' },
},
} as ComponentMeta<typeof MoviesGenre>;
export default meta;
// More on component templates: https://storybook.js.org/docs/react/writing-stories/introduction#using-args
const Template: ComponentStory<typeof MoviesGenre> = (args) => {
return <MoviesGenre {...args} />;
};
export const Default = Template.bind({});
// More on args: https://storybook.js.org/docs/react/writing-stories/args
Default.args = {
label1: 'Action',
label2: 'Adventure',
label3: 'Anime',
label4: 'Comedy',
label5: 'Crime',
label6: 'Documentary',
label7: 'Drama',
label8: 'Family',
label9: 'Fantasy',
label10: 'History',
label11: 'Horror',
label12: 'Music',
};
|
<script lang="ts" setup>
import {Search} from "@element-plus/icons-vue";
import MessageListCard from "../../components/global/MessageListCard.vue"
import {computed, onUnmounted, ref} from 'vue'
import {addChatList, dumpHelper, getChatList, getMesList} from "../../configs/services.js";
import aMessageBox from "../../components/box/tipBox";
import {useI18n} from "vue-i18n";
import {useStore} from "vuex";
interface LinkItem {
value: string
link: string
}
const lists = ref<LinkItem[]>([]);
const chatList = ref();
const chooseRef = ref();
const duplicateRef = ref();
const {t} = useI18n();
const store = useStore();
const username = ref();
(async () => {
const info = computed(() => store.state.currentUser.value)
if (info.value) {
username.value = info.value.username
}
})();
(async () => {
const {data} = await getMesList()
lists.value = data
})();
(async () => {
const {data} = await dumpHelper()
duplicateRef.value = data
})();
const timeoutID = ref();
let updateChatListCallback = async () => {
const {data} = await getChatList()
chatList.value = data
timeoutID.value = setTimeout(updateChatListCallback, 1000)
}
updateChatListCallback()
onUnmounted(() => {
clearTimeout(timeoutID.value)
})
const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
const results = queryString
? lists.value.filter(createFilter(queryString))
: lists.value;
cb(results)
}
const createFilter = (queryString: string) => {
return (restaurant: LinkItem) => {
return (
restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
)
}
}
const handleSelect = (item: LinkItem) => {
chooseRef.value = item.value;
}
const addHandler = () => {
if (!chooseRef.value) {
aMessageBox(t(`tip.tip`), t(`tip.null`), t(`config.confirm`))
return;
}
if (chooseRef.value === username.value) {
aMessageBox(t(`tip.tip`), t(`tip.unself`), t(`config.confirm`))
return;
}
const result2 = duplicateRef.value.find(item => item === chooseRef.value)
if (result2) {
aMessageBox(t(`tip.tip`), t(`tip.duplicateUsername`), t(`config.confirm`))
return;
}
const result = lists.value.find(item => item.value === chooseRef.value)
if (!result) {
aMessageBox(t(`tip.tip`), t(`tip.invalidname`), t(`config.confirm`))
return;
}
addChatList(chooseRef.value)
}
</script>
<template>
<div style="margin-left: 50px;margin-right: 50px">
<el-container>
<el-aside width="300px">
<div style="display: flex;flex-direction: column">
<el-space style="margin-bottom: 20px">
<div class="widget search-widget">
<el-autocomplete
v-model="chooseRef"
:fetch-suggestions="querySearchAsync"
:prefix-icon="Search"
class="input"
:placeholder="t(`config.search`)"
@select="handleSelect"
/>
</div>
<el-button type="primary" @click="addHandler">{{ $t(`navigation.add`) }}</el-button>
</el-space>
<el-scrollbar height="80vh">
<el-space direction="vertical" fill style="width: 90%;">
<div v-for="item in chatList" :key="item">
<MessageListCard :item="item"/>
</div>
</el-space>
</el-scrollbar>
</div>
</el-aside>
<el-main style="min-width: 500px">
<router-view></router-view>
</el-main>
</el-container>
</div>
</template>
<style scoped>
.widget.search-widget {
position: relative
}
.widget.search-widget .input {
padding-right: 60px;
}
.widget.search-widget button {
position: absolute;
right: 0;
top: 0;
height: 40px;
width: 40px;
background-color: transparent;
border: none;
}
.widget.search-widget .input:focus + button {
color: #FF6700;
}
</style>
|
{% load static %}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
{% block title %}
{% endblock %}
<meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css" type="text/css">
<link rel='stylesheet' href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css' type="text/css">
<link rel="stylesheet" href="{% static '/css/mainBreakpoints.css' %}" type="text/css">
<link rel="stylesheet" href="{% static '/css/mainStyle.css' %}" type="text/css">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid barraDeNavegacion">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#desplegable" aria-expanded="false">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{% url 'login_register:index' %}"><img src="{% static '/imagenes/logo-blanco.png' %}" alt=""></a>
</div>
<div class="collapse navbar-collapse" id="desplegable">
<ul class="nav navbar-nav">
<li><a href="{% url 'login_register:index' %}">Home</a></li>
<li><a href="{% url 'championData:championData' %}">Champion Data</a></li>
</ul>
{% if request.path != "/" or request.content_type != 'text/plain' or request.session.error %}
<form class="navbar-form navbar-left formIndex2" id="formIndex" method="post" action="">
{% csrf_token %}
<select name="regionId" id="regionId" class="selectIndex2">
<option value="euw1">EUW</option>
<option value="na1">NA</option>
<option value="eun1">EUNE</option>
</select>
<div class="form-group">
<input type="text" id="invocadorInput" name="invocador" class="inputTextIndex2" placeholder="Summonner's name...">
</div>
<button type="submit" id="buttonBusca" class="buscarIndex2">Search</button>
</form>
{% endif %}
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
{% if request.user.is_authenticated %}
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{ request.user }} <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>{% if user.get_region and user.get_summonerId%}<a href="{% url 'perfil:getInvocador' user.get_region user.get_summonerId %}">Summonner profile</a> {% else %} <a href="{% url 'login_register:editProfile' %}"> Summonner profile</a>{% endif %}</li>
<li><a href="{% url 'login_register:editProfile' %}">Settings</a></li>
<li><a href="{% url 'login_register:cerrarSesion' %}">Log Out</a></li>
</ul>
{% else %}
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> Have an account? <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="{% url 'login_register:loginPage' %}">Log In</a></li>
<li><a href="{% url 'login_register:registerPage' %}">Register</a></li>
</ul>
{% endif %}
</li>
</ul>
</div>
</div>
</nav>
{% block content %}
{% endblock%}
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js'></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="{% static 'javascript/buscador.js' %}"></script>
{% block scripts %}
{% endblock %}
<div class="footerMain">Made By George Cosmin Stancu</div>
</body>
</html>
|
import {BrowserRouter, Routes, Route,Navigate} from 'react-router-dom';
import Home from '../pages/Home/Home';
import SignUp from '../pages/Signup/signup';
import Login from '../pages/Login/Login';
import Profile from '../pages/Profile/Profile';
import Network from '../pages/Network/Network';
import SearchAppBar from '../components/Navbar/Navbar';
import Messaging from '../pages/Messaging/Messaging';
import Invitation from '../pages/Invitation/Invitation';
import Notification from '../pages/Notification/Notification';
import { useSelector } from 'react-redux';
import NetworkDetector from '../pages/Navigator/Navigator';
function AllRoutes() {
const Protected = ({ children }) => {
const user = useSelector((state)=> state.user.user);
return Object.keys(user).length === 0 ? <Navigate to="/Login" /> : <>{children}</>;
};
return (
<>
<BrowserRouter>
<NetworkDetector>
<SearchAppBar/>
<Routes>
<Route path='/' element={<Navigate to ='/Home' replace={true} />}></Route>
<Route path='/SignUp' element={<SignUp />}></Route>
<Route path='/Login' element={<Login />}></Route>
<Route path='/Home' element={<Protected><Home /></Protected>} />
<Route path='/Profile' element={<Protected><Profile /></Protected>}></Route>
<Route path='/Network' element={<Protected><Network /></Protected>}></Route>
<Route path='/Messaging' element={<Protected><Messaging /></Protected>}></Route>
<Route path='/Invitation' element={<Protected><Invitation /></Protected>}></Route>
<Route path='/Notification' element={<Protected><Notification/></Protected>}></Route>
</Routes>
</NetworkDetector>
</BrowserRouter>
</>
)
}
export default AllRoutes;
|
package gambol.examples.serialize.benchmark.kryo;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import gambol.examples.serialize.benchmark.Benchmark;
import gambol.examples.serialize.benchmark.BenchmarkSet;
import gambol.examples.serialize.benchmark.model.Foo;
import gambol.examples.serialize.benchmark.model.FooBuilder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
/**
* Created by zhenbao.zhou on 16/3/12.
*/
public class KryoBenchmark implements BenchmarkSet {
private final String name;
private final int numChildren;
public KryoBenchmark(int numChildren) {
this.numChildren = numChildren;
name = "kryo[" + numChildren + "]";
}
@Override
public String name() {
return name;
}
@Override
public Benchmark serialize() throws Exception {
final Foo foo = FooBuilder.buildObject("parent", numChildren);
Kryo kryo = new Kryo();
return new Benchmark() {
@Override
public String name() {
return name + " serialize";
}
@Override
public void go() throws Exception {
Output output = new Output(new ByteArrayOutputStream());
kryo.writeObject(output, foo);
output.close();
}
};
}
@Override
public Benchmark deserialize() throws Exception {
final Foo foo = FooBuilder.buildObject("parent", numChildren);
Kryo kryo = new Kryo();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Output output = new Output(bos);
kryo.writeObject(output, foo);
output.close();
byte[] bytes = bos.toByteArray();
return new Benchmark() {
@Override
public String name() {
return name + " deserialize";
}
@Override
public void go() throws Exception {
Input input = new Input(new ByteArrayInputStream(bytes));
Foo foo2 = kryo.readObject(input, Foo.class);
input.close();
}
};
}
@Override
public int encodeSize() throws Exception {
final Foo foo = FooBuilder.buildObject("parent", numChildren);
Kryo kryo = new Kryo();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Output output = new Output(bos);
kryo.writeObject(output, foo);
output.close();
byte[] bytes = bos.toByteArray();
return bytes.length;
}
public static void main(String[] args) throws Exception {
KryoBenchmark benchmark = new KryoBenchmark(1);
Benchmark b = benchmark.deserialize();
b.go();
}
}
|
import {ApiError} from 'app/common/ApiError';
import {TelemetryConfig} from 'app/common/gristUrls';
import {assertIsDefined} from 'app/common/gutil';
import {
buildTelemetryEventChecker,
Level,
TelemetryContracts,
TelemetryEvent,
TelemetryEventChecker,
TelemetryEvents,
TelemetryLevel,
TelemetryLevels,
TelemetryMetadata,
TelemetryMetadataByLevel,
TelemetryRetentionPeriod,
} from 'app/common/Telemetry';
import {TelemetryPrefsWithSources} from 'app/common/InstallAPI';
import {Activation} from 'app/gen-server/entity/Activation';
import {Activations} from 'app/gen-server/lib/Activations';
import {HomeDBManager} from 'app/gen-server/lib/HomeDBManager';
import {RequestWithLogin} from 'app/server/lib/Authorizer';
import {getDocSessionUser, OptDocSession} from 'app/server/lib/DocSession';
import {expressWrap} from 'app/server/lib/expressWrap';
import {GristServer} from 'app/server/lib/GristServer';
import {hashId} from 'app/server/lib/hashingUtils';
import {LogMethods} from 'app/server/lib/LogMethods';
import {stringParam} from 'app/server/lib/requestUtils';
import {getLogMetaFromDocSession} from 'app/server/lib/serverUtils';
import * as express from 'express';
import fetch from 'node-fetch';
import merge = require('lodash/merge');
import pickBy = require('lodash/pickBy');
type RequestOrSession = RequestWithLogin | OptDocSession | null;
export interface ITelemetry {
start(): Promise<void>;
logEvent(
requestOrSession: RequestOrSession,
name: TelemetryEvent,
metadata?: TelemetryMetadataByLevel
): void;
logEventAsync(
requestOrSession: RequestOrSession,
name: TelemetryEvent,
metadata?: TelemetryMetadataByLevel
): Promise<void>;
shouldLogEvent(name: TelemetryEvent): boolean;
addEndpoints(app: express.Express): void;
addPages(app: express.Express, middleware: express.RequestHandler[]): void;
getTelemetryConfig(requestOrSession?: RequestOrSession): TelemetryConfig | undefined;
fetchTelemetryPrefs(): Promise<void>;
}
const MAX_PENDING_FORWARD_EVENT_REQUESTS = 25;
/**
* Manages telemetry for Grist.
*/
export class Telemetry implements ITelemetry {
private _activation: Activation | undefined;
private _telemetryPrefs: TelemetryPrefsWithSources | undefined;
private readonly _deploymentType = this._gristServer.getDeploymentType();
private readonly _shouldForwardTelemetryEvents = this._deploymentType !== 'saas';
private readonly _forwardTelemetryEventsUrl = process.env.GRIST_TELEMETRY_URL ||
'https://telemetry.getgrist.com/api/telemetry';
private _numPendingForwardEventRequests = 0;
private readonly _logger = new LogMethods('Telemetry ', (requestOrSession: RequestOrSession | undefined) =>
this._getLogMeta(requestOrSession));
private readonly _telemetryLogger = new LogMethods<string>('Telemetry ', (eventType) => ({
eventType,
}));
private _checkTelemetryEvent: TelemetryEventChecker | undefined;
constructor(private _dbManager: HomeDBManager, private _gristServer: GristServer) {
}
public async start() {
await this.fetchTelemetryPrefs();
}
/**
* Logs a telemetry `event` and its `metadata`.
*
* Depending on the deployment type, this will either forward the
* data to an endpoint (set via GRIST_TELEMETRY_URL) or log it
* directly. In hosted Grist, telemetry is logged directly, and
* subsequently sent to an OpenSearch instance via CloudWatch. In
* other deployment types, telemetry is forwarded to an endpoint
* of hosted Grist, which then handles logging to OpenSearch.
*
* Note that `metadata` is grouped by telemetry level, with only the
* groups meeting the current telemetry level being included in
* what's logged. If the current telemetry level is `off`, nothing
* will be logged. Otherwise, `metadata` will be filtered according
* to the current telemetry level, keeping only the groups that are
* less than or equal to the current level.
*
* Additionally, runtime checks are also performed to verify that the
* event and metadata being passed in are being logged appropriately
* for the configured telemetry level. If any checks fail, an error
* is thrown.
*
* Example:
*
* The following will only log the `rowCount` if the telemetry level is set
* to `limited`, and will log both the `method` and `userId` if the telemetry
* level is set to `full`:
*
* ```
* logEvent('documentUsage', {
* limited: {
* rowCount: 123,
* },
* full: {
* userId: 1586,
* },
* });
* ```
*/
public async logEventAsync(
requestOrSession: RequestOrSession,
event: TelemetryEvent,
metadata?: TelemetryMetadataByLevel
) {
await this._checkAndLogEvent(requestOrSession, event, metadata);
}
/**
* Non-async variant of `logEventAsync`.
*
* Convenient for fire-and-forget usage.
*/
public logEvent(
requestOrSession: RequestOrSession,
event: TelemetryEvent,
metadata?: TelemetryMetadataByLevel
) {
this.logEventAsync(requestOrSession, event, metadata).catch((e) => {
this._logger.error(requestOrSession, `failed to log telemetry event ${event}`, e);
});
}
public addEndpoints(app: express.Application) {
/**
* Logs telemetry events and their metadata.
*
* Clients of this endpoint may be external Grist instances, so the behavior
* varies based on the presence of an `eventSource` key in the event metadata.
*
* If an `eventSource` key is present, the telemetry event will be logged
* directly, as the request originated from an external source; runtime checks
* of telemetry data are skipped since they should have already occured at the
* source. Otherwise, the event will only be logged after passing various
* checks.
*/
app.post('/api/telemetry', expressWrap(async (req, resp) => {
const mreq = req as RequestWithLogin;
const event = stringParam(req.body.event, 'event', {allowed: TelemetryEvents.values}) as TelemetryEvent;
if ('eventSource' in (req.body.metadata ?? {})) {
this._telemetryLogger.rawLog('info', getEventType(event), event, {
...(removeNullishKeys(req.body.metadata)),
eventName: event,
});
} else {
try {
this._assertTelemetryIsReady();
await this._checkAndLogEvent(mreq, event, merge(
{
full: {
userId: mreq.userId,
altSessionId: mreq.altSessionId,
},
},
req.body.metadata,
));
} catch (e) {
this._logger.error(mreq, `failed to log telemetry event ${event}`, e);
throw new ApiError(`Telemetry failed to log telemetry event ${event}`, 500);
}
}
return resp.status(200).send();
}));
}
public addPages(app: express.Application, middleware: express.RequestHandler[]) {
if (this._deploymentType === 'core') {
app.get('/support', ...middleware, expressWrap(async (req, resp) => {
return this._gristServer.sendAppPage(req, resp,
{path: 'app.html', status: 200, config: {}});
}));
}
}
public getTelemetryConfig(requestOrSession?: RequestOrSession): TelemetryConfig | undefined {
const prefs = this._telemetryPrefs;
if (!prefs) {
this._logger.error(requestOrSession, 'getTelemetryConfig called but telemetry preferences are undefined');
return undefined;
}
return {
telemetryLevel: prefs.telemetryLevel.value,
};
}
public async fetchTelemetryPrefs() {
this._activation = await this._gristServer.getActivations().current();
await this._fetchTelemetryPrefs();
}
// Checks if the event should be logged.
public shouldLogEvent(event: TelemetryEvent): boolean {
return Boolean(this._prepareToLogEvent(event));
}
private async _fetchTelemetryPrefs() {
this._telemetryPrefs = await getTelemetryPrefs(this._dbManager, this._activation);
this._checkTelemetryEvent = buildTelemetryEventChecker(this._telemetryPrefs.telemetryLevel.value);
}
private _prepareToLogEvent(
event: TelemetryEvent
): {checkTelemetryEvent: TelemetryEventChecker, telemetryLevel: TelemetryLevel}|undefined {
if (!this._checkTelemetryEvent) {
this._logger.error(null, 'telemetry event checker is undefined');
return;
}
const prefs = this._telemetryPrefs;
if (!prefs) {
this._logger.error(null, 'telemetry preferences are undefined');
return;
}
const telemetryLevel = prefs.telemetryLevel.value;
if (TelemetryContracts[event] && TelemetryContracts[event].minimumTelemetryLevel > Level[telemetryLevel]) {
return;
}
return {checkTelemetryEvent: this._checkTelemetryEvent, telemetryLevel};
}
private async _checkAndLogEvent(
requestOrSession: RequestOrSession,
event: TelemetryEvent,
metadata?: TelemetryMetadataByLevel
) {
const result = this._prepareToLogEvent(event);
if (!result) {
return;
}
metadata = filterMetadata(metadata, result.telemetryLevel);
result.checkTelemetryEvent(event, metadata);
if (this._shouldForwardTelemetryEvents) {
await this._forwardEvent(requestOrSession, event, metadata);
} else {
this._logEvent(requestOrSession, event, metadata);
}
}
private _logEvent(
requestOrSession: RequestOrSession,
event: TelemetryEvent,
metadata?: TelemetryMetadata
) {
let isInternalUser: boolean | undefined;
let isTeamSite: boolean | undefined;
if (requestOrSession) {
let email: string | undefined;
let org: string | undefined;
if ('get' in requestOrSession) {
email = requestOrSession.user?.loginEmail;
org = requestOrSession.org;
} else {
email = getDocSessionUser(requestOrSession)?.email;
org = requestOrSession.client?.getOrg() ?? requestOrSession.req?.org;
}
if (email) {
isInternalUser = email !== '[email protected]' && email.endsWith('@getgrist.com');
}
if (org && !process.env.GRIST_SINGLE_ORG) {
isTeamSite = !this._dbManager.isMergedOrg(org);
}
}
const {category: eventCategory} = TelemetryContracts[event];
this._telemetryLogger.rawLog('info', getEventType(event), event, {
...metadata,
eventName: event,
...(eventCategory !== undefined ? {eventCategory} : undefined),
eventSource: `grist-${this._deploymentType}`,
installationId: this._activation!.id,
...(isInternalUser !== undefined ? {isInternalUser} : undefined),
...(isTeamSite !== undefined ? {isTeamSite} : undefined),
});
}
private async _forwardEvent(
requestOrSession: RequestOrSession,
event: TelemetryEvent,
metadata?: TelemetryMetadata
) {
if (this._numPendingForwardEventRequests === MAX_PENDING_FORWARD_EVENT_REQUESTS) {
this._logger.warn(requestOrSession, 'exceeded the maximum number of pending forwardEvent calls '
+ `(${MAX_PENDING_FORWARD_EVENT_REQUESTS}). Skipping forwarding of event ${event}.`);
return;
}
try {
this._numPendingForwardEventRequests += 1;
const {category: eventCategory} = TelemetryContracts[event];
await this._doForwardEvent(JSON.stringify({
event,
metadata: {
...metadata,
eventName: event,
...(eventCategory !== undefined ? {eventCategory} : undefined),
eventSource: `grist-${this._deploymentType}`,
installationId: this._activation!.id,
},
}));
} catch (e) {
this._logger.error(requestOrSession, `failed to forward telemetry event ${event}`, e);
} finally {
this._numPendingForwardEventRequests -= 1;
}
}
private async _doForwardEvent(payload: string) {
await fetch(this._forwardTelemetryEventsUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: payload,
});
}
private _assertTelemetryIsReady() {
try {
assertIsDefined('activation', this._activation);
} catch (e) {
this._logger.error(null, 'activation is undefined', e);
throw new ApiError('Telemetry is not ready', 500);
}
}
private _getLogMeta(requestOrSession?: RequestOrSession) {
if (!requestOrSession) { return {}; }
if ('get' in requestOrSession) {
return {
org: requestOrSession.org,
email: requestOrSession.user?.loginEmail,
userId: requestOrSession.userId,
altSessionId: requestOrSession.altSessionId,
};
} else {
return getLogMetaFromDocSession(requestOrSession);
}
}
}
export async function getTelemetryPrefs(
db: HomeDBManager,
activation?: Activation
): Promise<TelemetryPrefsWithSources> {
const GRIST_TELEMETRY_LEVEL = process.env.GRIST_TELEMETRY_LEVEL;
if (GRIST_TELEMETRY_LEVEL !== undefined) {
const value = TelemetryLevels.check(GRIST_TELEMETRY_LEVEL);
return {
telemetryLevel: {
value,
source: 'environment-variable',
},
};
}
const {prefs} = activation ?? await new Activations(db).current();
return {
telemetryLevel: {
value: prefs?.telemetry?.telemetryLevel ?? 'off',
source: 'preferences',
}
};
}
/**
* Returns a new, filtered metadata object, or undefined if `metadata` is undefined.
*
* Filtering currently:
* - removes keys in groups that exceed `telemetryLevel`
* - removes keys with values of null or undefined
* - hashes the values of keys suffixed with "Digest" (e.g. doc ids, fork ids)
* - flattens the entire metadata object (i.e. removes the nesting of keys under
* "limited" or "full")
*/
export function filterMetadata(
metadata: TelemetryMetadataByLevel | undefined,
telemetryLevel: TelemetryLevel
): TelemetryMetadata | undefined {
if (!metadata) { return; }
let filteredMetadata: TelemetryMetadata = {};
for (const level of ['limited', 'full'] as const) {
if (Level[telemetryLevel] < Level[level]) { break; }
filteredMetadata = {...filteredMetadata, ...metadata[level]};
}
filteredMetadata = removeNullishKeys(filteredMetadata);
filteredMetadata = hashDigestKeys(filteredMetadata);
return filteredMetadata;
}
/**
* Returns a copy of `object` with all null and undefined keys removed.
*/
export function removeNullishKeys(object: Record<string, any>) {
return pickBy(object, value => value !== null && value !== undefined);
}
/**
* Returns a copy of `metadata`, replacing the values of all keys suffixed
* with "Digest" with the result of hashing the value. The hash is prefixed with
* the first 4 characters of the original value, to assist with troubleshooting.
*/
export function hashDigestKeys(metadata: TelemetryMetadata): TelemetryMetadata {
const filteredMetadata: TelemetryMetadata = {};
Object.entries(metadata).forEach(([key, value]) => {
if (key.endsWith('Digest') && typeof value === 'string') {
filteredMetadata[key] = hashId(value);
} else {
filteredMetadata[key] = value;
}
});
return filteredMetadata;
}
type TelemetryEventType = 'telemetry' | 'telemetry-short-retention';
const EventTypeByRetentionPeriod: Record<TelemetryRetentionPeriod, TelemetryEventType> = {
indefinitely: 'telemetry',
short: 'telemetry-short-retention',
};
function getEventType(event: TelemetryEvent) {
const {retentionPeriod} = TelemetryContracts[event];
return EventTypeByRetentionPeriod[retentionPeriod];
}
|
import { Room } from "../classes/Room";
import { CyberCafeServer } from "../classes/Server";
import { Namespace, Server, Socket } from "socket.io";
jest.mock("socket.io", () => {
const mockOn = jest.fn().mockImplementation(() => {
return mockOn;
});
return {
Server: jest.fn().mockImplementation(() => {
return {
of: jest.fn().mockReturnThis(),
emit: jest.fn(),
on: jest.fn(),
};
}),
Socket: jest.fn().mockImplementation(() => {
return {
id: "mockSocketId",
emit: jest.fn(),
on: jest.fn(),
join: jest.fn(),
leave: jest.fn(),
};
}),
};
});
describe("Room", () => {
let server: CyberCafeServer<string>;
let room: Room;
let mockServer: Server;
let mockSocket: Socket;
interface MockNamespace {
emit: jest.Mock;
}
let mockNamespace: MockNamespace;
beforeEach(() => {
mockServer = new Server() as unknown as Server;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
mockSocket = new Socket() as unknown as Socket;
server = new CyberCafeServer<string>();
mockNamespace = {
emit: jest.fn(),
};
jest
.spyOn(mockServer, "of")
.mockReturnValue(mockNamespace as unknown as Namespace);
room = new Room("/test", server);
room["namespace"] = mockNamespace as unknown as Namespace;
});
describe("constructor", () => {
it("should initialize with an empty state", () => {
expect(room["state"]).toEqual({});
});
it("should initialize without users", () => {
expect(room["users"].size).toBe(0);
});
});
describe("addUser", () => {
it("should add a user to the room", () => {
room.addUser("user1", mockSocket);
expect(room["users"].has("user1")).toBeTruthy();
});
});
describe("removeUser", () => {
it("should remove a user from the room", () => {
room.addUser("user1", mockSocket);
room.removeUser("user1");
expect(room["users"].has("user1")).toBeFalsy();
});
});
describe("updateState", () => {
it("should update the room state", () => {
const initialState = { topic: "initial" };
const update = { topic: "updated" };
room["state"] = initialState;
room.updateState(update);
expect(room["state"]).toEqual(update);
});
});
describe("broadcast", () => {
it("should emit an event to all users", () => {
const emitSpy = jest.spyOn(mockServer.of("/test"), "emit");
room.broadcast("event", { data: "test" });
expect(emitSpy).toHaveBeenCalledWith("event", { data: "test" });
});
});
});
|
import { Link } from 'react-router-dom';
import {
AiFillHeart,
AiOutlineComment,
AiOutlineShareAlt,
AiOutlinePlus,
} from 'react-icons/ai';
import numeral from 'numeral';
import { useAuthUser, useAuthHeader } from 'react-auth-kit';
import styles from './Social.module.css';
import { Video } from '@/types/entities/video.entity';
import { likeVideo, unlikeVideo } from '@/services/videos';
import { User } from '@/types/entities/user.entity';
interface SocialProps {
video: Video;
onLiked: (video: Video) => void;
}
const plusIconSize = 18;
const normalIconSize = 40;
const iconColor = '#fff';
const Social = ({ video, onLiked }: SocialProps) => {
const user = useAuthUser()() as User;
const authHeader = useAuthHeader()();
const isLiked = !!video.likedBy.find((userLiked) => userLiked.id === user.id);
return (
<div className={styles.controls}>
<Link to={`/profile/${video.author.id}`} className={styles.profileBtn}>
<img src={video.author.avatarUrl} alt="Profile" />
<div className={styles.followStatus}>
<AiOutlinePlus color={iconColor} size={plusIconSize} />
</div>
</Link>
<button
type="button"
className={styles.btn}
onClick={async () => {
let response: Video;
if (isLiked) {
response = await unlikeVideo(video.id, authHeader);
} else {
response = await likeVideo(video.id, authHeader);
}
onLiked(response);
}}
>
<AiFillHeart
color={isLiked ? 'red' : iconColor}
size={normalIconSize}
/>
<span className={styles.btnLabel}>
{numeral(video.likedBy.length).format('0.0a')}
</span>
</button>
<button type="button" className={styles.btn}>
<AiOutlineComment color={iconColor} size={normalIconSize} />
<span className={styles.btnLabel}>{numeral(30000).format('0.0a')}</span>
</button>
<button type="button" className={styles.btn}>
<AiOutlineShareAlt color={iconColor} size={normalIconSize} />
<span className={styles.btnLabel}>{numeral(30000).format('0.0a')}</span>
</button>
</div>
);
};
export default Social;
|
<!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">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<link rel="stylesheet" href="styleMain.css">
<title>WEB 110</title>
</head>
<body class="bg-light container-fluid">
<div class="row">
<div class="col-lg-4 bg-secondary col-sm-6" id="topPage">
<h1 class="text-center text-white mt-1">David Thompson</h1>
<h2 class="text-center text-white">WEB 110</h2>
<div class="row">s
<div class="col-2"></div>
<div class="col-8">
<img id="profile-img" class="img-thumbnail rounded-circle mx-auto"
src="../imgs/David portfolio Cover square.jpg" alt="Me and Dog">
</div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-12">
<p class="text-white text-center p-2 m-0">Introduces the fundamental skills and knowledge needed to use the Internet and build basic web pages.</p>
<ul class="text-white">
<li>Grid layout planning</li>
<li>Multimedia on the web</li>
<li>Wireframing and Prototyping</li>
</ul>
</div>
<div class="col-3"></div>
<a href="../index.html" class="text-center"><button type="button"
class="btn btn-dark btn-lg col-6 mb-3">Portfolio Page</button></a>
<div class="col-3"></div>
</div>
</div>
<div class="col-lg-8 col-sm-6">
<div class="row justify-content-around">
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment1.html">Assignment 1</a></h2>
<p>For this assignment, I learned about basic tools by completing 3 tasks described on the
assignment
page.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment2.html">Assignment 2</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment3.html">Assignment 3</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment4.html">Assignment 4</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment5.html">Assignment 5</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment6.html">Assignment 6</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment7.html">Assignment 7</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment8.html">Assignment 8</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment9.html">Assignment 9</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class=" text-center h3"><a href="assignment10.html">Assignment 10</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment11.html">Assignment 11</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment12.html">Assignment 12</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment13.html">Assignment 13</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class="text-center h3"><a href="assignment14.html">Assignment 14</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3">
<h2 class=" text-center h3"><a href="assignment15.html">Assignment 15</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
<div class="col-lg-4 col-md-6 border border-1 rounded p-3 mb-5">
<h2 class="text-center h3"><a href="assignment16.html">Final Project</a></h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero, tempore adipisci? Adipisci
explicabo libero veritatis.</p>
</div>
</div>
</div>
<footer>
<a href="#topPage" class="text-center d-md-none lead fs-1">Back to top</a>
</footer>
</div>
<!-- SCRIPT Below all content -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous">
</script>
</body>
</html>
|
/*
Topic:- Available Captures for Rook
Link:- https://leetcode.com/problems/available-captures-for-rook/
Problem:-
On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty squares '.'.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking.
Return the number of available captures for the white rook.
Example 1:
Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation: In this example, the rook is attacking all the pawns.
Example 2:
Input: board = [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 0
Explanation: The bishops are blocking the rook from attacking any of the pawns.
Example 3:
Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation: The rook is attacking the pawns at positions b5, d6, and f5.
Constraints:
board.length == 8
board[i].length == 8
board[i][j] is either 'R', '.', 'B', or 'p'
There is exactly one cell with board[i][j] == 'R'
Solution:-
*/
class Solution {
public int numRookCaptures(char[][] board) {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (board[i][j] == 'R') {
return Count(board, i, j);
}
}
}
return 0;
}
public int Count(char[][] board, int row, int col) {
int res = 0;
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int[] d: directions) {
for (int i = row, j = col; i >= 0 && i < 8 && j >= 0 && j < 8; i = i + d[0], j = j + d[1]) {
if (board[i][j] == 'p') {
res++;
break;
} else if (board[i][j] == 'B') {
break;
}
}
}
return res;
}
}
|
package com.hazelcast.map.mapstore;
import com.hazelcast.config.Config;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MapStoreConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.core.MapStore;
import com.hazelcast.core.PostProcessingMapStore;
import com.hazelcast.core.TransactionalMap;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.transaction.TransactionException;
import com.hazelcast.transaction.TransactionalTask;
import com.hazelcast.transaction.TransactionalTaskContext;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class PostProcessingMapStoreTest extends HazelcastTestSupport {
@Test
public void testProcessedValueCarriedToTheBackup_whenPut() {
String name = randomString();
HazelcastInstance[] instances = getInstances(name);
IMap<Integer, SampleObject> map1 = instances[0].getMap(name);
IMap<Integer, SampleObject> map2 = instances[1].getMap(name);
int size = 1000;
for (int i = 0; i < size; i++) {
map1.put(i, new SampleObject(i));
}
for (int i = 0; i < size; i++) {
SampleObject o = map1.get(i);
assertEquals(i + 1, o.version);
}
for (int i = 0; i < size; i++) {
SampleObject o = map2.get(i);
assertEquals(i + 1, o.version);
}
}
@Test
public void testProcessedValueCarriedToTheBackup_whenTxnPut() {
final String name = randomString();
HazelcastInstance[] instances = getInstances(name);
IMap<Integer, SampleObject> map1 = instances[0].getMap(name);
IMap<Integer, SampleObject> map2 = instances[1].getMap(name);
int size = 1000;
for (int i = 0; i < size; i++) {
final int key = i;
instances[0].executeTransaction(new TransactionalTask<Object>() {
@Override
public Object execute(TransactionalTaskContext context) throws TransactionException {
TransactionalMap<Integer, SampleObject> map = context.getMap(name);
map.put(key, new SampleObject(key));
return null;
}
});
}
for (int i = 0; i < size; i++) {
SampleObject o = map1.get(i);
assertEquals(i + 1, o.version);
}
for (int i = 0; i < size; i++) {
SampleObject o = map2.get(i);
assertEquals(i + 1, o.version);
}
}
@Test
public void testProcessedValueCarriedToTheBackup_whenPutAll() {
String name = randomString();
HazelcastInstance[] instances = getInstances(name);
IMap<Integer, SampleObject> map1 = instances[0].getMap(name);
IMap<Integer, SampleObject> map2 = instances[1].getMap(name);
int size = 1000;
Map<Integer, SampleObject> temp = new HashMap<Integer, SampleObject>();
for (int i = 0; i < size; i++) {
temp.put(i, new SampleObject(i));
}
map1.putAll(temp);
for (int i = 0; i < size; i++) {
SampleObject o = map1.get(i);
assertEquals(i + 1, o.version);
}
for (int i = 0; i < size; i++) {
SampleObject o = map2.get(i);
assertEquals(i + 1, o.version);
}
}
HazelcastInstance[] getInstances(String name) {
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
Config config = new Config();
MapConfig mapConfig = config.getMapConfig(name);
mapConfig.setReadBackupData(true);
MapStoreConfig mapStoreConfig = new MapStoreConfig();
mapStoreConfig.setEnabled(true).setClassName(IncrementerPostProcessingMapStore.class.getName());
mapConfig.setMapStoreConfig(mapStoreConfig);
HazelcastInstance instance1 = factory.newHazelcastInstance(config);
HazelcastInstance instance2 = factory.newHazelcastInstance(config);
return new HazelcastInstance[]{instance1, instance2};
}
public static class IncrementerPostProcessingMapStore implements MapStore<Integer, SampleObject>, PostProcessingMapStore {
Map<Integer, SampleObject> map = new HashMap<Integer, SampleObject>();
@Override
public void store(Integer key, SampleObject value) {
value.version++;
map.put(key, value);
}
@Override
public void storeAll(Map<Integer, SampleObject> map) {
for (Map.Entry<Integer, SampleObject> entry : map.entrySet()) {
store(entry.getKey(), entry.getValue());
}
}
@Override
public void delete(Integer key) {
map.remove(key);
}
@Override
public void deleteAll(Collection<Integer> keys) {
for (Integer key : keys) {
map.remove(key);
}
}
@Override
public SampleObject load(Integer key) {
return map.get(key);
}
@Override
public Map<Integer, SampleObject> loadAll(Collection<Integer> keys) {
HashMap<Integer, SampleObject> temp = new HashMap<Integer, SampleObject>();
for (Integer key : keys) {
temp.put(key, map.get(key));
}
return temp;
}
@Override
public Set<Integer> loadAllKeys() {
return map.keySet();
}
}
public static class SampleObject implements Serializable {
public int version;
public SampleObject(int version) {
this.version = version;
}
}
}
|
<div class="section">
<h1>Administrar estudiantes</h1>
<hr>
<div style="display: flex; flex-wrap: wrap; justify-content: space-between;">
<button style="height: 50px;" routerLink="/create-student" mat-raised-button>Insertar estudiante</button>
<div>
<mat-form-field class=" example-full-width" appearance="fill">
<mat-label>Buscar</mat-label>
<input [ngModel]="search" (ngModelChange)='findStudentByKeyword($event)' matInput placeholder="ej. Juanito" />
</mat-form-field>
</div>
</div>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z5" style="text-align:center">
<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->
<!-- Position Column -->
<ng-container matColumnDef="ID">
<th mat-header-cell *matHeaderCellDef style="text-align:center"> ID </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
</ng-container>
<ng-container matColumnDef="Código">
<th mat-header-cell *matHeaderCellDef style="text-align:center"> Código </th>
<td mat-cell *matCellDef="let element"> {{element.code}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="Nombre">
<th mat-header-cell *matHeaderCellDef style="text-align:center"> Nombre </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="Apellido">
<th mat-header-cell *matHeaderCellDef style="text-align:center"> Apellido </th>
<td mat-cell *matCellDef="let element"> {{element.lastName}} </td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="Nota">
<th mat-header-cell *matHeaderCellDef style="text-align:center"> Nota </th>
<td mat-cell *matCellDef="let element"> {{element.grade}} </td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="Action">
<th mat-header-cell *matHeaderCellDef style="text-align:center"> Acción </th>
<td mat-cell *matCellDef="let element">
<button style="margin-right: 5px;" [routerLink]="['/edit-student/', element.id]" routerLinkActive="active"
mat-stroked-button color="accent">Editar</button>
<button mat-stroked-button color="warn" (click)="deleteStudent(element.id)">Borrar</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<router-outlet></router-outlet>
|
import datetime
import logging
import time
import discord
from bungio.error import BungIOException
from bungio.models import DestinyUser, DestinyComponentType, DestinyMetricComponent
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload
from ORM.schemes.Meeting import MeetingMember, MeetingChannel, MemberStatus, Meeting, MeetingStatus
from utils.logger import create_logger
from utils.users_utils import get_main_bungie_id_by_discord_id, get_bungie_name_by_bungie_id, get_main_destiny_profile
logger = create_logger(__name__)
def parse_date(date: str):
date = datetime.datetime.strptime(date, "%d.%m-%H:%M").replace(year=datetime.datetime.now().year)
# date = pytz.timezone('Europe/Moscow').localize(date)
if date <= datetime.datetime.now():
date = date.replace(year=(datetime.datetime.now().year + 1))
return date
async def check_many_meetings_of_member(db_engine, discord_id: int, timestamp: datetime.datetime):
async with AsyncSession(db_engine) as session:
query = select(MeetingMember).join(Meeting) \
.where((MeetingMember.status.in_([MemberStatus.MEMBER, MemberStatus.LEADER])) &
(MeetingMember.discord_id == discord_id) &
(Meeting.start_at.between(timestamp - datetime.timedelta(hours=2),
timestamp + datetime.timedelta(hours=2))) &
(Meeting.status.in_([MeetingStatus.ACTIVE, MeetingStatus.COMPLETED])))
result = (await session.execute(query)).scalars()
return list(result.unique())
async def create_meeting_member(db_engine, meeting: Meeting, discord_member: discord.Member) -> MeetingMember:
for meeting_member in meeting.meeting_members:
meeting_member: MeetingMember
if meeting_member.discord_id == discord_member.id:
return meeting_member
async with AsyncSession(db_engine) as session:
query = select(MeetingChannel.metric_hash).where(meeting.category_id == MeetingChannel.channel_id)
metric_hashes = (await session.execute(query)).scalar()
bungie_id = await get_main_bungie_id_by_discord_id(db_engine, discord_member.id)
bungie_name, metric_value, main_membership_id, main_membership_type = None, None, None, None
if bungie_id:
try:
bungie_name = await get_bungie_name_by_bungie_id(membership_id=bungie_id, membership_type=254)
member_main_profile = None
member_profiles = await \
DestinyUser(membership_id=bungie_id, membership_type=254).get_membership_data_by_id()
if member_profiles.primary_membership_id:
for profile in member_profiles.destiny_memberships:
if member_profiles.primary_membership_id == profile.membership_id:
member_main_profile = profile
elif len(member_profiles.destiny_memberships) == 1:
member_main_profile = member_profiles.destiny_memberships[0]
elif len(member_profiles.destiny_memberships) > 1:
for profile in member_profiles.destiny_memberships:
if profile.membership_type == 3:
member_main_profile = profile
if member_main_profile:
main_membership_id, main_membership_type = \
member_main_profile.membership_id, member_main_profile.membership_type.value
if metric_hashes and member_main_profile:
member_metrics = await member_main_profile.get_profile(components=[DestinyComponentType.METRICS])
if member_metrics:
for metric_hash in metric_hashes:
metric: DestinyMetricComponent | None = member_metrics.metrics.data.metrics.get(metric_hash, None)
if metric:
if metric_value is None:
metric_value = 0
metric_value += metric.objective_progress.progress
else:
continue
except BungIOException as e:
logger.exception(e)
meeting_member = MeetingMember(
meeting_id=meeting.meeting_id,
discord_id=discord_member.id,
bungie_name=bungie_name,
other_data={'metric_value': metric_value,
'membership_id': main_membership_id,
'membership_type': main_membership_type}
)
return meeting_member
async def get_full_meeting(db_engine, meeting_id):
async with AsyncSession(db_engine, expire_on_commit=False) as session:
meeting = await session.scalar(
select(Meeting).options(joinedload(Meeting.meeting_members), joinedload(Meeting.meeting_channel)).
where(Meeting.meeting_id == meeting_id))
session.expunge(meeting)
return meeting
async def find_member_in_meeting(meeting: Meeting, discord_member_id: int) -> MeetingMember | None:
existed_user = None
for meeting_member in meeting.meeting_members:
meeting_member: MeetingMember
if meeting_member.discord_id == discord_member_id:
existed_user = meeting_member
return existed_user
async def create_meeting_member_fast(meeting: Meeting, discord_member: discord.Member) -> MeetingMember:
for meeting_member in meeting.meeting_members:
meeting_member: MeetingMember
if meeting_member.discord_id == discord_member.id:
return meeting_member
meeting_member = MeetingMember(
meeting_id=meeting.meeting_id,
discord_id=discord_member.id,
other_data={'metric_value': None,
'membership_id': None,
'membership_type': None})
return meeting_member
async def update_meeting_member(db_engine,
meeting: Meeting,
discord_member: discord.Member,
render_meeting_func) -> None | MeetingMember:
bungie_id = await get_main_bungie_id_by_discord_id(db_engine, discord_member.id)
bungie_name, metric_value, main_membership_id, main_membership_type, metric_value = None, None, None, None, None
meeting_member = None
for member in meeting.meeting_members:
if member.discord_id == discord_member.id:
meeting_member = member
if not meeting_member:
meeting_member = MeetingMember(
meeting_id=meeting.meeting_id,
discord_id=discord_member.id
)
if bungie_id:
try:
bungie_name = await get_bungie_name_by_bungie_id(membership_id=bungie_id, membership_type=254)
member_main_profile = None
member_profiles = await \
DestinyUser(membership_id=bungie_id, membership_type=254).get_membership_data_by_id()
if member_profiles.primary_membership_id:
for profile in member_profiles.destiny_memberships:
if member_profiles.primary_membership_id == profile.membership_id:
member_main_profile = profile
elif len(member_profiles.destiny_memberships) == 1:
member_main_profile = member_profiles.destiny_memberships[0]
elif len(member_profiles.destiny_memberships) > 1:
for profile in member_profiles.destiny_memberships:
if profile.membership_type == 3:
member_main_profile = profile
if member_main_profile:
main_membership_id, main_membership_type = \
member_main_profile.membership_id, member_main_profile.membership_type.value
if meeting.meeting_channel.metric_hash and member_main_profile:
member_metrics = await member_main_profile.get_profile(components=[DestinyComponentType.METRICS])
for metric_hash in meeting.meeting_channel.metric_hash:
metric: DestinyMetricComponent | None = member_metrics.metrics.data.metrics.get(metric_hash, None)
if metric:
if metric_value is None:
metric_value = 0
metric_value += metric.objective_progress.progress
else:
continue
except BungIOException as e:
logger.exception(e)
meeting_member.last_update = datetime.datetime.now()
meeting_member.bungie_name = bungie_name
meeting_member.other_data = {'metric_value': metric_value,
'membership_id': main_membership_id,
'membership_type': main_membership_type}
async with AsyncSession(db_engine, expire_on_commit=False) as session:
await session.merge(meeting_member)
await session.commit()
await render_meeting_func(meeting)
return meeting_member
|
#include <NvInfer.h>
#include <algorithm>
#include <cub/cub.cuh>
#include <cuda_fp16.h>
#include <numeric>
#include <string>
#include <vector>
#define CEIL_DIVIDE(X, Y) (((X) + (Y)-1) / (Y))
#define CEIL_TO(X, Y) (((X) + (Y)-1) / (Y) * (Y))
#define CHECK_CUDA(call) \
{ \
const cudaError_t error = call; \
if (error != cudaSuccess) { \
printf("Error: %s:%d\n", __FILE__, __LINE__); \
printf("code: %d, reason: %s\n", error, cudaGetErrorString(error)); \
exit(1); \
} \
}
// #define DEBUG_FUNC() \
// { printf("[DEBUG] %s, %s:%d\n", __FILE__, __FUNCTION__, __LINE__); }
#define DEBUG_FUNC() \
{}
#define ALIGN_TO(X, Y) (CEIL_DIVIDE(X, Y) * (Y))
inline void check(cudaError_t ret, int line) {
if (ret != cudaSuccess) {
std::cerr << "CUDA Error: " << cudaGetErrorString(ret) << ", line: " << line << std::endl;
}
}
#define CHECK(_x) check((_x), __LINE__)
template <int VPT>
struct BytesToType;
template <>
struct BytesToType<2> {
using type = uint16_t;
};
template <>
struct BytesToType<4> {
using type = uint32_t;
};
template <>
struct BytesToType<8> {
using type = uint64_t;
};
template <>
struct BytesToType<16> {
using type = float4;
};
template <int Bytes>
__device__ inline void copy(const void* local, void* data) {
using T = typename BytesToType<Bytes>::type;
const T* in = static_cast<const T*>(local);
T* out = static_cast<T*>(data);
*out = *in;
}
template <typename T>
using kvp = cub::KeyValuePair<T, T>;
template <typename T>
struct mySum {
__host__ __device__ __forceinline__ kvp<T> operator()(const kvp<T>& a, const kvp<T>& b) const {
return kvp<T>(a.key + b.key, a.value + b.value);
}
};
namespace {
static const char* PLUGIN_NAME{"LayerNorm"};
static const char* PLUGIN_VERSION{"1"};
} // namespace
inline int64_t volume(const nvinfer1::Dims& d) {
return std::accumulate(d.d, d.d + d.nbDims, 1, std::multiplies<int64_t>());
}
namespace nvinfer1 {
namespace plugin {
class LayerNormPlugin final : public IPluginV2DynamicExt {
public:
LayerNormPlugin(const std::string& name) : name_(name) {
DEBUG_FUNC();
}
LayerNormPlugin(const std::string& name, const void* data, size_t length) : name_(name) {
DEBUG_FUNC();
}
LayerNormPlugin() = delete;
~LayerNormPlugin() {
DEBUG_FUNC();
}
size_t getSerializationSize() const noexcept override {
DEBUG_FUNC();
return 0;
}
void serialize(void* buffer) const noexcept override {
DEBUG_FUNC();
}
IPluginV2DynamicExt* clone() const noexcept override {
DEBUG_FUNC();
return new LayerNormPlugin(name_);
}
int getNbOutputs() const noexcept override {
DEBUG_FUNC();
return 1;
}
DimsExprs getOutputDimensions(int32_t outputIndex,
const DimsExprs* inputs,
int32_t nbInputs,
IExprBuilder& exprBuilder) noexcept override {
DEBUG_FUNC();
return inputs[0];
}
bool supportsFormatCombination(int32_t pos,
const PluginTensorDesc* inOut,
int32_t nbInputs,
int32_t nbOutputs) noexcept override {
switch (pos) {
case 0:
return (inOut[0].type == DataType::kFLOAT || inOut[0].type == DataType::kHALF) &&
inOut[0].format == TensorFormat::kLINEAR ||
inOut[0].type == DataType::kINT8 && (inOut[0].format == TensorFormat::kCHW4 ||
inOut[0].format == TensorFormat::kCHW32);
case 1:
case 2:
return inOut[pos].type == inOut[0].type ||
inOut[0].type == DataType::kINT8 && inOut[pos].type == DataType::kHALF;
case 3:
return inOut[pos].type == inOut[0].type && inOut[pos].format == inOut[0].format;
default: // should NOT be here!
return false;
}
return false;
}
DataType getOutputDataType(int outputIndex,
const DataType* inputTypes,
int nbInputs) const noexcept override {
DEBUG_FUNC();
return inputTypes[0];
}
void configurePlugin(const DynamicPluginTensorDesc* in,
int32_t nbInputs,
const DynamicPluginTensorDesc* out,
int32_t nbOutputs) noexcept override {
DEBUG_FUNC();
}
size_t getWorkspaceSize(const PluginTensorDesc* inputs,
int32_t nbInputs,
const PluginTensorDesc* outputs,
int32_t nbOutputs) const noexcept override {
DEBUG_FUNC();
return 0;
}
void setPluginNamespace(const char* szNamespace) noexcept override {
DEBUG_FUNC();
namespace_ = szNamespace;
}
const char* getPluginNamespace() const noexcept override {
DEBUG_FUNC();
return namespace_.c_str();
}
const char* getPluginType() const noexcept override {
DEBUG_FUNC();
return PLUGIN_NAME;
}
const char* getPluginVersion() const noexcept override {
DEBUG_FUNC();
return PLUGIN_VERSION;
}
int initialize() noexcept override {
DEBUG_FUNC();
return 0;
}
void terminate() noexcept override {
DEBUG_FUNC();
return;
}
void destroy() noexcept override {
delete this;
}
int enqueue(const PluginTensorDesc* inputDesc,
const PluginTensorDesc* outputDesc,
const void* const* inputs,
void* const* outputs,
void* workspace,
cudaStream_t stream) noexcept override;
private:
std::string name_;
std::string namespace_;
}; // class LayerNormPlugin
class LayerNormPluginCreator : public IPluginCreator {
private:
static PluginFieldCollection fc_;
static std::vector<PluginField> attrs_;
std::string namespace_;
public:
LayerNormPluginCreator() {}
~LayerNormPluginCreator() {}
IPluginV2* createPlugin(const char* name, const PluginFieldCollection* fc) noexcept override {
DEBUG_FUNC();
return new LayerNormPlugin(name);
}
IPluginV2* deserializePlugin(const char* name,
const void* serialData,
size_t serialLength) noexcept override {
DEBUG_FUNC();
return new LayerNormPlugin(name, serialData, serialLength);
}
void setPluginNamespace(const char* szNamespace) noexcept override {
namespace_ = szNamespace;
}
const char* getPluginNamespace() const noexcept override {
return namespace_.c_str();
}
const char* getPluginName() const noexcept override {
return PLUGIN_NAME;
}
const char* getPluginVersion() const noexcept override {
return PLUGIN_VERSION;
}
const PluginFieldCollection* getFieldNames() noexcept override {
return &fc_;
}
}; // class LayerNormPluginCreator
} // namespace plugin
} // namespace nvinfer1
|
import 'package:flutter/material.dart';
import 'package:rentapp_ui/rentapp_ui.dart';
enum RentAppIconSize {
min(6),
small(12),
medium(16),
large(18),
bigger(20),
extraBigger(24);
const RentAppIconSize(this.size);
final double size;
}
class RentAppIcon extends StatelessWidget {
const RentAppIcon({
super.key,
required this.icon,
this.rawSize,
this.size = RentAppIconSize.extraBigger,
this.color = Palette.white,
});
final IconData icon;
final Color? color;
final double? rawSize;
final RentAppIconSize size;
@override
Widget build(BuildContext context) {
return Icon(
icon,
size: rawSize ?? size.size,
color: color,
);
}
}
|
//
// 434.countSegments.swift
// debugTest
//
// Created by Xiaonan Chen on 2021/1/1.
//
import Foundation
/*
434. 字符串中的单词数
难度
简单
71
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: "Hello, my name is John"
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。
*/
func countSegments(_ s: String) -> Int {
let sArr = Array(s)
var idx = 0, ans = 0
while idx < sArr.count {
while idx < sArr.count && sArr[idx].isWhitespace {
idx += 1
}
if idx == sArr.count {
break
}
ans += 1
while idx < sArr.count && !sArr[idx].isWhitespace {
idx += 1
}
}
return ans
}
|
import React, { Fragment, useState, useEffect, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { Context_User } from "../utils/AdminPanel";
import { Context_Store } from "../utils/Store";
import "../mystyles.css";
export default function ProductsInput() {
const [name, setName] = useState("");
const [price, setPrice] = useState("");
const [description, setDescription] = useState("");
const [category, setCategory] = useState("select");
const { store, storeDispatch } = useContext(Context_Store);
const { controls, controlDispatch } = useContext(Context_User);
const navigate = useNavigate();
const onSubmitForm = async (e) => {
e.preventDefault();
if (!controls.status) {
if (!localStorage.getItem("Token")) {
alert("Please login first !!");
navigate("/login");
return;
}
}
try {
console.log("category is ", category);
if (
name.length < 2 ||
price.length < 1 ||
description.length < 5 ||
category === "select" ||
category === ""
) {
alert("Invalid Entry");
return;
}
const body = { name, price, description, category };
console.log(body);
const response = await fetch("/products", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + localStorage.getItem("Token"),
},
body: JSON.stringify(body),
});
const data = await response.json();
console.log(data);
if (response.status === 409) {
alert("Login Expired");
navigate("/login");
} else if (response.status === 407) {
alert("Item already exists !!");
} else if (response.status === 200) {
alert("New product added !!!");
var newProduct = store.products;
newProduct.push(data);
console.log(newProduct);
storeDispatch({ type: "Create_Products_Data", payload: newProduct });
setName("");
setPrice("");
setDescription("");
navigate("/");
}
} catch (err) {
console.error(err.message);
alert("Invalid Entry !!");
}
};
if (!controls.status) {
if (localStorage.getItem("Token") === null) {
return <div></div>;
} else {
controlDispatch({ type: "Set_Status", payload: true });
}
}
return (
<Fragment>
<div className="product-input">
<h1 className="text-center mt-5">Enter New Product</h1>
<form onSubmit={onSubmitForm} className="form mt-5">
<input
type="text"
className="input inp_name"
required
placeholder="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="number"
className="input inp_price"
placeholder="price"
value={price}
onChange={(e) => {
// e.target.value.match(/^[0-9]+$/)
setPrice(e.target.value);
// : setPrice("");
}}
/>
<textarea
type="text"
className="textarea inp_desc"
placeholder="description (optional)"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
{/* <input
type="text"
className="input inp_cat"
placeholder="category"
value={category}
onChange={(e) => setCategory(e.target.value)}
/> */}
<select
className="selection category-selection"
onChange={(e) => {
setCategory(e.target.value);
console.log(e.target.value);
}}
value={category}
>
<option value="select">select</option>
{store.categories.map((catagory) => (
<option value={catagory._id}>{catagory.name}</option>
))}
</select>
<button className="btn btn-success btn_add">Add</button>
</form>
</div>
</Fragment>
);
}
|
package com.c01_c04;
/**
* 短路
* 只有明确整个表达式真或假的结论,才会对表达式进行逻辑求值。
* 因此,一个逻辑表达式的所有部分都有可能不进行求值
*/
public class ShortCircuit {
static boolean test1(int val) {
System.out.println("test1(" + val + ")");
System.out.println("result: " + (val < 1));
return val < 1;
}
static boolean test2(int val) {
System.out.println("test2(" + val + ")");
System.out.println("result: " + (val < 2));
return val < 2;
}
static boolean test3(int val) {
System.out.println("test3(" + val + ")");
System.out.println("result: " + (val < 3));
return val < 3;
}
public static void main(String[] args) {
if (test1(0) && test2(2) && test3(3)){ // 第2个逻辑表达式为false,因此不对第3个表达式进行执行。
System.out.println("expression is true");
}else {
System.out.println("expression is false");
}
}
}
|
import React from 'react';
import Image from "next/image";
import {FEATURES} from "@/constant";
const Features = () => {
return (
<section
className={"flex-col flexCenter overflow-hidden bg-feature-bg bg-center bg-no-repeat py-24"}>
<div className={"max-container padding-container relative w-full flex justify-end"}>
<div className={"flex flex-1 lg:min-h-[900px]"}>
<Image src={"/phone.png"} alt={"phone"} width={440} height={1000} className={"feature-phone"}/>
</div>
<div className={"z-20 flex flex-col w-full lg:w-[60%] "}>
<div className={"relative"}>
<Image src={"/camp.svg"} alt={"camp"}
className={"absolute left-[-5px] top-[-20px] w-10 lg:w-[50px]"}
width={50}
height={50}/>
<h2 className={"bold-40 lg:bold-64"}>Our Features</h2>
</div>
<ul className={"mt-10 grid gap-10 md:grid-cols-2 lg:gap-20"}>
{FEATURES.map((feature, index) => (
<FeatureItem title={feature.title} variant={feature.variant} icon={feature.icon}
description={feature.description} key={index}/>
))}
</ul>
</div>
</div>
</section>
);
};
type FeatureItemProps = {
title: string,
variant: string,
icon: string,
description: string
}
const FeatureItem = ({title, variant, icon, description}: FeatureItemProps) => {
return (
<li className={"flex w-full flex-1 flex-col items-start"}>
<div className={"rounded-full p-4 lg:p-7 bg-green-50"}>
<Image src={icon} alt={title} width={28} height={28}/>
</div>
<h2 className={"bold-20 lg:bold-32 mt-5 capitalize"}>
{title}
</h2>
<p className={"regular-16 mt-5 bg-white/80 text-gray-30 lg:mt-[30px] lg:bg-none"}>
{description}
</p>
</li>
);
}
export default Features;
|
/* Arrow Functions.
* Nueva forma de definir funciones anónimas que sean expresadas.
* - Estas funciones pueden ser escritas en una sola línea de código.
* - No es necesario escribir la palabra reservada function.
* - No es necesario escribir la palabra reservada return.
* - No necesitas escribir las llaves
* - No presenta la palabra reservada this
*/
// Ejemplo función expresada
console.log("-----------Ejemplo función expresada----------------")
const saludar = function () {
return "Hola!"
}
console.log(saludar())
/*
* Arrow functions
* - Su sintaxis es la siguiente:
* const nombreFuncion = (parametros) => {
* // código función
* }
* Cuando la función es de una linea se pueden omitir los corchetes
* const nombreFuncion = () => // código función
*/
console.log("-----------Ejemplos arrow functions----------------")
const despedir = () => {
return "Adios!"
}
console.log(despedir())
const recibir = () => "Recibido!";
console.log(recibir())
// Parámetros dentro de los parentesis o se pueden dejar sin los parentesis si es un solo parámetro
const bienvenida = (nombre) => `Bienvenido(a) ${nombre}`;
console.log(bienvenida("Luna"));
const despedida = nombre => `Hasta luego ${nombre}`;
console.log(despedida("Luna"));
// También se evita poner return cuando es solo una línea
const sumar = (a, b) => a + b;
console.log(sumar(8, 9));
console.log("-----------Arrow functions en ciclos----------------")
const numeros = [1, 2, 3, 4, 5, 6]
// Para recorrer el anterior arreglo sin arrow functions se puede hacer de la siguiente manera
console.log("-----------Ejemplo sin Arrow functions---------------")
numeros.forEach(function (num, index) {
console.log(`El elemento ${num} esta en la posicion ${index}`)
})
// Lo anterior se puede transformar en una arrow function
console.log("-----------Ejemplo con Arrow functions---------------")
numeros.forEach((num, index) => console.log(`El elemento ${num} esta en la posicion ${index}`)) //
|
import datetime
import itertools
import os
import pytz
import tempfile
from typing import Optional
import csp
from csp.adapters.output_adapters.parquet import ParquetOutputConfig, ParquetWriter
from csp.cache_support import CacheConfig
from csp.impl.managed_dataset.aggregation_period_utils import AggregationPeriodUtils
from csp.impl.managed_dataset.managed_dataset import ManagedDatasetPartition
from csp.impl.managed_dataset.managed_dataset_lock_file_util import ManagedDatasetLockUtil
from csp.utils.file_permissions import apply_file_permissions
from csp.utils.lock_file import MultipleFilesLock
def _pa():
"""
Lazy import pyarrow
"""
import pyarrow
return pyarrow
def _create_wip_file(output_folder, start_time, is_folder: Optional[bool] = False):
prefix = start_time.strftime("%Y%m%d_H%M%S_%f") if start_time else "merge_"
if is_folder:
return tempfile.mkdtemp(dir=output_folder, suffix="_WIP", prefix=prefix)
else:
fd, cur_file_path = tempfile.mkstemp(dir=output_folder, suffix="_WIP", prefix=prefix)
os.close(fd)
return cur_file_path
class _SingleBasketMergeData:
def __init__(self, basket_name, basket_types, input_files, basket_data_input_files):
self.basket_data_input_files = basket_data_input_files
self.basket_name = basket_name
self.basket_types = basket_types
self.count_column_name = f"{basket_name}__csp_value_count"
if issubclass(self.basket_types.value_type, csp.Struct):
self.data_column_names = [f"{basket_name}.{c}" for c in self.basket_types.value_type.metadata()]
else:
self.data_column_names = [basket_name]
self.symbol_column_name = f"{basket_name}__csp_symbol"
self._cur_basket_data_row_group = None
self._cur_row_group_data_table = None
self._cur_row_group_symbol_table = None
self._cur_row_group_last_returned_index = int(-1)
def _load_row_group(self, next_row_group_index=None):
if next_row_group_index is None:
next_row_group_index = self._cur_basket_data_row_group + 1
self._cur_basket_data_row_group = next_row_group_index
do_iter = True
while do_iter:
if self._cur_basket_data_row_group < self.basket_data_input_files[self.data_column_names[0]].num_row_groups:
self._cur_row_group_data_tables = [
self.basket_data_input_files[c].read_row_group(self._cur_basket_data_row_group)
for c in self.data_column_names
]
self._cur_row_group_symbol_table = self.basket_data_input_files[self.symbol_column_name].read_row_group(
self._cur_basket_data_row_group
)
if self._cur_row_group_data_tables[0].shape[0] > 0:
do_iter = False
else:
self._cur_basket_data_row_group += 1
else:
self._cur_row_group_data_tables = None
self._cur_row_group_symbol_table = None
do_iter = False
self._cur_row_group_last_returned_index = int(-1)
return self._cur_row_group_data_tables is not None
@property
def _num_remaining_rows_cur_chunk(self):
if not self._cur_row_group_data_tables:
return 0
remaining_items_cur_group = (
self._cur_row_group_data_tables[0].shape[0] - 1 - self._cur_row_group_last_returned_index
)
return remaining_items_cur_group
def _skip_rows(self, num_rows_to_skip):
remaining_items_cur_chunk = self._num_remaining_rows_cur_chunk
while num_rows_to_skip > 0:
if num_rows_to_skip >= remaining_items_cur_chunk:
num_rows_to_skip -= remaining_items_cur_chunk
assert self._load_row_group() or num_rows_to_skip == 0
else:
self._cur_row_group_last_returned_index += int(num_rows_to_skip)
num_rows_to_skip = 0
def _iter_chunks(self, row_indices, full_column_tables):
count_table = full_column_tables[self.count_column_name].columns[0]
count_table_cum_sum = count_table.to_pandas().cumsum()
if self._cur_basket_data_row_group is None:
self._load_row_group(0)
if row_indices is None:
if count_table_cum_sum.empty:
return
num_rows_to_return = int(count_table_cum_sum.iloc[-1])
else:
if row_indices.size == 0:
if not count_table_cum_sum.empty:
self._skip_rows(count_table_cum_sum.iloc[-1])
return
num_rows_to_return = int(count_table_cum_sum[row_indices[-1]])
if row_indices[0] != 0:
skipped_rows = int(count_table_cum_sum[row_indices[0] - 1])
self._skip_rows(skipped_rows)
num_rows_to_return -= skipped_rows
while num_rows_to_return > 0:
s_i = self._cur_row_group_last_returned_index + 1
if num_rows_to_return < self._num_remaining_rows_cur_chunk:
e_i = s_i + num_rows_to_return
self._skip_rows(num_rows_to_return)
num_rows_to_return = 0
yield (self._cur_row_group_symbol_table[s_i:e_i],) + tuple(
t[s_i:e_i] for t in self._cur_row_group_data_tables
)
else:
num_read_rows = self._num_remaining_rows_cur_chunk
e_i = s_i + num_read_rows
num_rows_to_return -= num_read_rows
yield (self._cur_row_group_symbol_table[s_i:e_i],) + tuple(
t[s_i:e_i] for t in self._cur_row_group_data_tables
)
assert self._load_row_group() or num_rows_to_return == 0
class _MergeFileInfo(csp.Struct):
file_path: str
start_time: datetime.datetime
end_time: datetime.datetime
class SinglePartitionFileMerger:
def __init__(
self,
dataset_partition: ManagedDatasetPartition,
start_time,
end_time,
cache_config: CacheConfig,
parquet_output_config: ParquetOutputConfig,
):
self._dataset_partition = dataset_partition
self._start_time = start_time
self._end_time = end_time
self._cache_config = cache_config
self._parquet_output_config = parquet_output_config.copy().resolve_compression()
# TODO: cleanup all reference to existing files and backup files
self._split_columns_to_files = getattr(dataset_partition.dataset.metadata, "split_columns_to_files", False)
self._aggregation_period_utils = AggregationPeriodUtils(
self._dataset_partition.dataset.metadata.time_aggregation
)
def _is_overwrite_allowed(self):
allow_overwrite = getattr(self._cache_config, "allow_overwrite", None)
if allow_overwrite is not None:
return allow_overwrite
allow_overwrite = getattr(self._parquet_output_config, "allow_overwrite", None)
return bool(allow_overwrite)
def _resolve_merged_output_file_name(self, merge_candidates):
output_file_name = self._dataset_partition.data_paths.get_output_file_name(
start_time=merge_candidates[0].start_time,
end_time=merge_candidates[-1].end_time,
split_columns_to_files=self._split_columns_to_files,
)
return output_file_name
def _iterate_file_chunks(self, file_name, start_cutoff=None):
dataset = self._dataset_partition.dataset
parquet_file = _pa().parquet.ParquetFile(file_name)
if start_cutoff:
for i in range(parquet_file.metadata.num_row_groups):
time_stamps = parquet_file.read_row_group(i, [dataset.metadata.timestamp_column_name])[
dataset.metadata.timestamp_column_name
].to_pandas()
row_indices = time_stamps.index.values[(time_stamps > pytz.utc.localize(start_cutoff))]
if row_indices.size == 0:
continue
full_table = parquet_file.read_row_group(i)[row_indices[0] : row_indices[-1] + 1]
yield full_table
else:
for i in range(parquet_file.metadata.num_row_groups):
yield parquet_file.read_row_group(i)
def _iter_column_names(self, include_regular_columns=True, include_basket_data_columns=True):
dataset = self._dataset_partition.dataset
if include_regular_columns:
yield dataset.metadata.timestamp_column_name
for c in dataset.metadata.columns.keys():
yield c
if hasattr(dataset.metadata, "dict_basket_columns"):
for c, t in dataset.metadata.dict_basket_columns.items():
if include_regular_columns:
yield f"{c}__csp_value_count"
if include_basket_data_columns:
if issubclass(t.value_type, csp.Struct):
for field_name in t.value_type.metadata():
yield f"{c}.{field_name}"
else:
yield c
yield f"{c}__csp_symbol"
def _iter_column_files(self, folder, include_regular_columns=True, include_basket_data_columns=True):
for c in self._iter_column_names(
include_regular_columns=include_regular_columns, include_basket_data_columns=include_basket_data_columns
):
yield c, os.path.join(folder, f"{c}.parquet")
def _iterate_folder_chunks(self, file_name, start_cutoff=None):
dataset = self._dataset_partition.dataset
input_files = {}
for c, f in self._iter_column_files(file_name, include_basket_data_columns=False):
input_files[c] = _pa().parquet.ParquetFile(f)
basket_data_input_files = {}
for c, f in self._iter_column_files(file_name, include_regular_columns=False):
basket_data_input_files[c] = _pa().parquet.ParquetFile(f)
timestamp_column_reader = input_files[dataset.metadata.timestamp_column_name]
basked_data = (
{
k: _SingleBasketMergeData(k, v, input_files, basket_data_input_files)
for k, v in dataset.metadata.dict_basket_columns.items()
}
if getattr(dataset.metadata, "dict_basket_columns", None)
else {}
)
if start_cutoff:
for i in range(timestamp_column_reader.metadata.num_row_groups):
time_stamps = timestamp_column_reader.read_row_group(i, [dataset.metadata.timestamp_column_name])[
dataset.metadata.timestamp_column_name
].to_pandas()
row_indices = time_stamps.index.values[(time_stamps > pytz.utc.localize(start_cutoff))]
full_column_tables = {}
truncated_column_tables = {}
for c in self._iter_column_names(include_basket_data_columns=False):
full_table = input_files[c].read_row_group(i)
full_column_tables[c] = full_table
if row_indices.size > 0:
truncated_column_tables[c] = full_table[row_indices[0] : row_indices[-1] + 1]
if row_indices.size > 0:
yield (
truncated_column_tables,
(
v._iter_chunks(row_indices=row_indices, full_column_tables=full_column_tables)
for v in basked_data.values()
),
)
else:
for v in basked_data.values():
assert (
len(list(v._iter_chunks(row_indices=row_indices, full_column_tables=full_column_tables)))
== 0
)
else:
for i in range(timestamp_column_reader.metadata.num_row_groups):
truncated_column_tables = {}
for c in self._iter_column_names(include_basket_data_columns=False):
truncated_column_tables[c] = input_files[c].read_row_group(i)
yield (
truncated_column_tables,
(
v._iter_chunks(row_indices=None, full_column_tables=truncated_column_tables)
for v in basked_data.values()
),
)
def _iterate_chunks(self, file_name, start_cutoff=None):
if self._dataset_partition.dataset.metadata.split_columns_to_files:
return self._iterate_folder_chunks(file_name, start_cutoff)
else:
return self._iterate_file_chunks(file_name, start_cutoff)
def _iterate_merged_batches(self, merge_candidates):
iters = []
# Here we need both start time and end time to be exclusive
start_cutoff = merge_candidates[0].start_time - datetime.timedelta(microseconds=1)
end_cutoff = merge_candidates[-1].end_time + datetime.timedelta(microseconds=1)
for merge_candidate in merge_candidates:
merged_file_cutoff_start = None
if merge_candidate.start_time <= start_cutoff:
merged_file_cutoff_start = start_cutoff
assert end_cutoff > merge_candidate.end_time
iters.append(self._iterate_chunks(merge_candidate.file_path, start_cutoff=merged_file_cutoff_start))
start_cutoff = merge_candidate.end_time
return itertools.chain(*iters)
def _merged_data_folders(self, aggregation_folder, merge_candidates):
output_file_name = self._resolve_merged_output_file_name(merge_candidates)
file_permissions = self._cache_config.data_file_permissions
folder_permission = file_permissions.get_folder_permissions()
wip_file = _create_wip_file(aggregation_folder, start_time=None, is_folder=True)
apply_file_permissions(wip_file, folder_permission)
writers = {}
try:
for (column1, src_file_name), (column2, file_name) in zip(
self._iter_column_files(merge_candidates[0].file_path), self._iter_column_files(wip_file)
):
assert column1 == column2
schema = _pa().parquet.read_schema(src_file_name)
writers[column1] = _pa().parquet.ParquetWriter(
file_name,
schema=schema,
compression=self._parquet_output_config.compression,
version=ParquetWriter.PARQUET_VERSION,
)
for batch, basket_batches in self._iterate_merged_batches(merge_candidates):
for column_name, values in batch.items():
writers[column_name].write_table(values)
for single_basket_column_batches in basket_batches:
for batch_columns in single_basket_column_batches:
for single_column_table in batch_columns:
writer = writers[single_column_table.column_names[0]]
writer.write_table(single_column_table)
finally:
for writer in writers.values():
writer.close()
for _, f in self._iter_column_files(wip_file):
apply_file_permissions(f, file_permissions)
os.rename(wip_file, output_file_name)
def _merge_data_files(self, aggregation_folder, merge_candidates):
output_file_name = self._resolve_merged_output_file_name(merge_candidates)
file_permissions = self._cache_config.data_file_permissions
wip_file = _create_wip_file(aggregation_folder, start_time=None, is_folder=False)
schema = _pa().parquet.read_schema(merge_candidates[0].file_path)
with _pa().parquet.ParquetWriter(
wip_file,
schema=schema,
compression=self._parquet_output_config.compression,
version=ParquetWriter.PARQUET_VERSION,
) as parquet_writer:
for batch in self._iterate_merged_batches(merge_candidates):
parquet_writer.write_table(batch)
apply_file_permissions(wip_file, file_permissions)
os.rename(wip_file, output_file_name)
def _resolve_merge_candidates(self, existing_files):
if not existing_files or len(existing_files) <= 1:
return None
merge_candidates = []
for (file_period_start, file_period_end), file_path in existing_files.items():
if not merge_candidates:
merge_candidates.append(
_MergeFileInfo(file_path=file_path, start_time=file_period_start, end_time=file_period_end)
)
continue
assert file_period_start >= merge_candidates[-1].start_time
if merge_candidates[-1].end_time + datetime.timedelta(microseconds=1) >= file_period_start:
merge_candidates.append(
_MergeFileInfo(file_path=file_path, start_time=file_period_start, end_time=file_period_end)
)
elif len(merge_candidates) <= 1:
merge_candidates.clear()
merge_candidates.append(
_MergeFileInfo(file_path=file_path, start_time=file_period_start, end_time=file_period_end)
)
else:
break
if len(merge_candidates) > 1:
return merge_candidates
return None
def _merge_single_period(self, aggregation_folder, aggregation_period_start, aggregation_period_end):
lock_file_utils = ManagedDatasetLockUtil(self._cache_config.lock_file_permissions)
continue_merge = True
while continue_merge:
with lock_file_utils.merge_lock(aggregation_folder):
existing_files, _ = self._dataset_partition.data_paths.get_data_files_in_range(
aggregation_period_start,
aggregation_period_end,
missing_range_handler=lambda *args, **kwargs: True,
split_columns_to_files=self._split_columns_to_files,
truncate_data_periods=False,
include_read_folders=False,
)
merge_candidates = self._resolve_merge_candidates(existing_files)
if not merge_candidates:
break
lock_file_paths = [r.file_path for r in merge_candidates]
locks = [lock_file_utils.write_lock(f, is_lock_in_root_folder=True) for f in lock_file_paths]
all_files_lock = MultipleFilesLock(locks)
if not all_files_lock.lock():
break
if self._dataset_partition.dataset.metadata.split_columns_to_files:
self._merged_data_folders(aggregation_folder, merge_candidates)
else:
self._merge_data_files(aggregation_folder, merge_candidates)
all_files_lock.unlock()
def merge_files(self):
for (
aggregation_period_start,
aggregation_period_end,
) in self._aggregation_period_utils.iterate_periods_in_date_range(
start_time=self._start_time, end_time=self._end_time
):
aggregation_period_end -= datetime.timedelta(microseconds=1)
aggregation_folder = self._dataset_partition.data_paths.get_output_folder_name(aggregation_period_start)
self._merge_single_period(aggregation_folder, aggregation_period_start, aggregation_period_end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.