text
stringlengths 184
4.48M
|
|---|
//
// QuestionTests.swift
// KuisTests
//
// Created by Albert Pangestu on 20/12/21.
//
import XCTest
@testable import Kuis
class QuestionTests: XCTestCase {
private var question: Question!
override func setUp() {
self.question = Question()
}
func test_InitialQuestionTitle() {
XCTAssertEqual(self.question.title, "")
}
func test_UpdateQuestionTitle() {
self.question.updateQuestion("Who invented the E = mc^2?")
XCTAssertEqual(self.question.title, "Who invented the E = mc^2?")
}
func test_InitialQuestionAnswers() {
XCTAssertEqual(self.question.incorrectAnswers, Array(repeating: "", count: 3))
}
func test_AddMoreThanThreeAnswersGetsAnError() {
XCTAssertThrowsError(try self.question.addIncorrectAnswers(["Albert Einstein", "Abraham Lincoln", "Mahatama Gandhi", "Michael Jordan"])) { error in
XCTAssertEqual(error as? QuestionError,
QuestionError.AnswerExceedsTheLimit)
}
}
func test_InitialQuestionCorrectAnswer() {
XCTAssertEqual(self.question.correctAnswer, "")
}
// MARK: - Helpers
private func addAnswers() {
try? self.question.addIncorrectAnswers(["Albert Einstein", "Abraham Lincoln", "Mahatama Gandhi"])
}
}
|
import os
import pandas as pd
from typing import Any, List
from attr import define, field
from utils import printv
from models.model_utils import SystemMessage, HumanMessage, AIMessage, BaseMessage
from logger import get_logger
log = get_logger()
@define
class NegotiationAgent:
# message params
msg_prompt: str = 'prompt_0'
msg_max_len: int = 64
msg_input_msg_history: int = -1
msg_input_note_history: int = 1
# notes params
note_prompt: str = 'prompt_0'
note_max_len: int = 64
note_input_msg_history: int = -1
note_input_note_history: int = -1
# model
model: Any = None
model_name: str = field(default='gpt-3.5-turbo')
model_provider: str = field(default='openai')
model_key_path: str = field(default='secrets.json')
model_key: Any = field(default='dlab_key')
model_budget: float = field(default=5.)
temperature: float = field(default=0.)
# visibility of other sides payoffs
visibility: int = field(default=0)
# keep track of what agents think they can achieve
notes_history: list = field(factory=list)
msg_history: list = field(factory=list)
achievable_payoffs: dict = field(factory=dict)
agreement_prompt: str = 'We agree on all issues.'
# agent character
agent_name: str = 'You'
agent_name_ext: str = 'Representative'
agent_id: int = 0
internal_description: dict = field(factory=dict)
external_description: dict = field(factory=dict)
system_description: SystemMessage = field(default=SystemMessage(''))
# format negotiation as if the 'user msg' is the other NegotiatingAgent, and the 'system msg' provides prompts
format_as_dialogue: bool = field(default=False)
verbosity: int = field(default=1)
debug_mode: bool = field(default=False)
show_rounds: bool = True
_current_round_num: int = field(default=0)
_max_rounds: int = field(default=0)
_note_prompt_filename: str = field(default=None)
_msg_prompt_filename: str = field(default=None)
init_settings = locals()
def __attrs_post_init__(self):
self._note_prompt_filename = self.note_prompt
self._msg_prompt_filename = self.msg_prompt
# read in prompts
self.note_prompt = self.get_msg_note_prompt(self._note_prompt_filename, is_note=True)
self.msg_prompt = self.get_msg_note_prompt(self._msg_prompt_filename, is_note=False)
self.model.debug_mode = self.debug_mode
self.model.budget = self.model_budget
self.agent_name = self.internal_description['name']
self.agent_name_ext = self.external_description['name']
def copy_agent_history_from_transcript(self, transcript: str, agent_id: int):
transcript = pd.read_csv(transcript)
transcript = transcript[transcript['agent_id'] == agent_id]
self.msg_history = [(self.agent_name, m) for m in transcript['message'].to_list()]
self.notes_history = [(self.agent_name, m) for m in transcript['note'].to_list()]
def _verbose_generative_print(self, dialogue_context, is_note=False):
if self.format_as_dialogue:
x = ['<dialogue style>']
for c in dialogue_context:
x.append(f'[{c.role}]\n{c.content}')
x = '\n'.join(x)
else:
x = dialogue_context[0].content
gen_type = "NOTE" if is_note else "MSG"
printv(f'\n[{gen_type} PROMPT]\n {x} \n', self.verbosity, 1, c=self._get_print_color(),
debug=self.verbosity == 2)
def _correct_transcript_artifact(self, content) -> str:
# TODO: log these corrections, as they technically break the instructions
# due to being presented a 'transcript' of the ongoing negotiation, some models try to respond using their
# transcript tag, e.g. 'You: I disagree', instead of just 'I disagree'.
# this can be potentially very confusing to the next chat model trying to interpret the transcript
if not isinstance(content, str):
return content
self_check_1 = f'{self.agent_name}:'
self_check_2 = f'{self.agent_name_ext}:'
if self_check_1 in content[:len(self_check_1)]:
return content[len(self_check_1):]
elif self_check_2 in content[:len(self_check_2)]:
return content[len(self_check_2):]
else:
return content
def _get_print_color(self):
return ['blue', 'red'][self.agent_id]
def generate_message(self, c_msg_history):
# msg prompt structure
# system_msg(game, side, agent, issues) + user_msg(c_msg, note, msg, c_msg, note, prompt) -> agent_msg: msg
dialogue_context = self.prepare_msg_note_input(c_msg_history)
context = self._prepare_gen_context(dialogue_context)
self._verbose_generative_print(context, is_note=False)
msg = self.model(context)
msg = self._correct_transcript_artifact(msg)
self.msg_history.append((self.agent_name, msg))
printv(f'<{self.agent_name_ext} - msg>: {msg}', self.verbosity, c=self._get_print_color())
return msg
def generate_note(self, c_msg_history):
# note prompt structure:
# system_msg(game, side, agent, issues) + user_msg(c_msg, note, msg, c_msg, prompt) --> agent_msg: note
dialogue_context = self.prepare_msg_note_input(c_msg_history)
context = self._prepare_gen_context(dialogue_context)
self._verbose_generative_print(context, is_note=True)
note = self.model(context)
note = self._correct_transcript_artifact(note)
self.notes_history.append((self.agent_name, note))
printv(f'\n<{self.agent_name_ext} - note>: {note}\n', self.verbosity, c=self._get_print_color())
return note
def _prepare_gen_context(self, dialogue_context):
if self.model_provider == 'google' and self.format_as_dialogue:
# NOTE: google-dialogue will only allow a note-history of 1 for messages, and 0 for notes
# google rules:
# 1. only 'odd' number of messages, i.e., first-and-last message must be of type HumanMessage
# 2. only 2-authors, i.e., meta-instructions must be in system-context (SystemMessage)
# 3. must be alternating: never have two messages of same type repeating
system_context = self.system_description.copy()
# most recent message will always be the next prompt
next_prompt = dialogue_context[-1].content
# remove from the dialogue history
dialogue_context = dialogue_context[:-1]
first_dummy_msg = HumanMessage('Let us start the negotiations')
if len(dialogue_context) > 0:
# either: first c_msg OR first note
first_msg = dialogue_context[0].copy()
last_msg = dialogue_context[-1].copy()
if not isinstance(first_msg, HumanMessage):
# first message needs to be human
dialogue_context = [first_dummy_msg] + dialogue_context
if isinstance(last_msg, AIMessage):
# google does not allow non-alternating message dialogue, i.e. AIMessage -> AIMessage not allowed
# previous generation must be a note -> concat to system_msg and remove from dialogue
note = f'Also keep in mind the mental note you wrote:\n"{last_msg.content}"\n'
dialogue_context = dialogue_context[:-1]
system_context = SystemMessage(f'{system_context.content}\n\n{next_prompt}\n\n{note}')
elif isinstance(last_msg, HumanMessage):
# last message was a c_msg, next message will be a note
system_context = SystemMessage(f'{system_context.content}\n\n{next_prompt}')
else:
# no notes/messages have been written yet -> this will be the first
dialogue_context = [first_dummy_msg]
system_context = SystemMessage(f'{system_context.content}\n\n{next_prompt}')
context = [system_context] + dialogue_context
else:
context = [self.system_description] + dialogue_context
return context
def prepare_msg_note_input(self, c_msg_history: list, simulate_msg: bool = False, transcript_only: bool = False
) -> List[BaseMessage]:
"""
Create input context for writing the next message/note.
We loop backwards, only added context as far as our 'memory' is allowed to go.
:param c_msg_history: messages generated by the other agent
:param simulate_msg: add 'dummy' msg to transcript to measure contact capacity
:param transcript_only: only return the transcript history
:return: context msg
"""
# to check generative capacity moving forward without overriding real history
n_h = self.notes_history.copy()
m_h = self.msg_history.copy()
cm_h = c_msg_history.copy()
# is this the first message/note?
first_msg_note = (len(n_h) == 0 or len(m_h) == 0) and len(cm_h) == 0
# IF need to simulate msg create phantom note --> needed to check for context overflow
n_h = self._format_context_simulation(simulate_msg=simulate_msg, notes_history=n_h)
# more notes than messages indicates next generation will be a message
msg = len(n_h) > len(m_h)
# select part of dialogue history to present in the context
neg_history = self._select_dialogue_history(next_is_msg=msg, notes_history=n_h, msg_history=m_h,
c_msg_history=cm_h)
# format history as either (1) ai_msg-human_msg sequence (format_as_dialogue), or (2) human_msg transcript
neg_transcript = self._format_dialogue_history(neg_history)
# if no notes appear in the transcript -> do not mention them to avoid unnecessary confusion
neg_transcript = self._format_dialogue_transcript_preamble(next_is_msg=msg, is_first_msg_note=first_msg_note,
neg_transcript=neg_transcript)
# if 'interrogation' mode is on, we only want the negotiation history so far, since we're providing a prompt
if transcript_only:
return neg_transcript if self.format_as_dialogue else [HumanMessage(neg_transcript)]
generative_input = self._format_next_prompt(is_msg=msg, is_first_msg_note=first_msg_note,
dialogue=neg_transcript)
return generative_input
def _format_context_simulation(self, simulate_msg, notes_history):
if simulate_msg:
if len(notes_history) > 0: # repeat previous note
notes_history.append(notes_history[-1])
else: # if no note history exists, create a dummy note
dummy_note = "hello " * self.note_max_len
notes_history.append((self.agent_name, dummy_note))
return notes_history
def _select_dialogue_history(self, next_is_msg, notes_history, msg_history, c_msg_history):
n_h, m_h, cm_h = notes_history, msg_history, c_msg_history
max_len = max(max(len(n_h), len(m_h)), len(cm_h))
max_m = self.msg_input_msg_history if next_is_msg else self.note_input_msg_history
max_n = self.msg_input_note_history if next_is_msg else self.note_input_note_history
if max_m < 0:
max_m = 1e5
if max_n < 0:
max_n = 1e5
neg_history = []
for i in range(1, max_len + 1):
if next_is_msg and (i <= max_n) and (0 < len(n_h)):
neg_history.append(('mental note', n_h.pop()))
if i <= max_m:
if 0 < len(cm_h):
neg_history.append(('offer', cm_h.pop()))
if 0 < len(m_h):
neg_history.append(('offer', m_h.pop()))
if not next_is_msg and (i <= max_n) and (0 < len(n_h)):
neg_history.append(('mental note', n_h.pop()))
if (i == max_len) and (0 < len(cm_h)) and (i <= max_m):
neg_history.append(('offer', cm_h.pop()))
# reverse order to have the oldest message/note appear first
neg_history = neg_history[::-1]
return neg_history
def _format_dialogue_history(self, neg_history_):
neg_transcript = [] if self.format_as_dialogue else ''
for i_type, (a, i) in neg_history_:
if self.format_as_dialogue:
base_msg = AIMessage(i, alt_role=self.agent_name_ext) if a == self.agent_name else HumanMessage(i)
neg_transcript.append(base_msg)
else:
if i_type == 'mental note':
neg_transcript += f'\n{a}: ({i_type}) {i}'
else:
neg_transcript += f'\n{a}: {i}'
return neg_transcript
def _format_dialogue_transcript_preamble(self, next_is_msg, is_first_msg_note, neg_transcript):
# if no notes appear in the transcript -> do not mention them to avoid unnecessary confusion
notes_invisible = (next_is_msg and self.msg_input_note_history == 0) or \
(not next_is_msg and self.note_input_note_history == 0)
if not self.format_as_dialogue and len(neg_transcript) > 0:
if is_first_msg_note:
if next_is_msg and not notes_invisible:
neg_transcript = f'\nA log of your mental notes so far:\n\n' \
f'<start transcript>\n {neg_transcript} \n<end transcript>\n'
else:
transcript_pre_amble = '\nTranscript of ongoing negotiations and your mental notes so far:\n'
# do not mention mental notes if none will be present
if notes_invisible:
transcript_pre_amble.replace('and your mental notes ', '')
neg_transcript = f'{transcript_pre_amble}\n<start transcript>\n{neg_transcript}\n<end transcript>\n\n'
return neg_transcript
def _format_next_prompt(self, is_msg, is_first_msg_note, dialogue):
self.note_prompt = self.get_msg_note_prompt(self._note_prompt_filename, is_note=True)
self.msg_prompt = self.get_msg_note_prompt(self._msg_prompt_filename, is_note=False)
# Add prompt to generate next note/message
next_prompt = self.msg_prompt if is_msg else self.note_prompt
agreement_prompt = f"\nOnly if you agree with the other party on acceptable offers for all issues " \
f"respond with: '{self.agreement_prompt}', and nothing else."
if is_first_msg_note:
to_replace = "Reflect on the negotiations transcript so far"
replacement = "You are to start the negotiations"
next_prompt = next_prompt.replace(to_replace, replacement)
else:
if is_msg:
next_prompt += agreement_prompt
if self.format_as_dialogue:
# remove mentions of a 'transcript' for dialogue format
next_prompt = next_prompt.replace('negotiations transcript', 'negotiations')
if self.model_provider == 'google':
next_prompt = HumanMessage(next_prompt)
else:
next_prompt = SystemMessage(next_prompt)
generative_input = dialogue + [next_prompt] if len(dialogue) > 0 else [next_prompt]
else:
next_prompt = next_prompt + dialogue if len(dialogue) > 0 else next_prompt
generative_input = [HumanMessage(next_prompt)]
return generative_input
def step(self, c_msg_history, round_num, max_rounds):
# log round num and max rounds
self._current_round_num = round_num
self._max_rounds = max_rounds
# create mental note
self.generate_note(c_msg_history)
# create external message
new_msg = self.generate_message(c_msg_history)
return new_msg
def check_context_len_step(self, c_msg_history) -> bool:
# 1. enough context token space to generate note?
# 2. enough context token space to generate msg?
dialogue_context = self.prepare_msg_note_input(c_msg_history)
context = [self.system_description] + dialogue_context
capacity = self.model.check_context_len(context=context, max_gen_tokens=self.note_max_len)
if not capacity:
return capacity
dialogue_context = self.prepare_msg_note_input(c_msg_history, simulate_msg=True)
context = [self.system_description] + dialogue_context
capacity = self.model.check_context_len(context=context, max_gen_tokens=self.msg_max_len)
return capacity
def get_settings(self):
return self.init_settings
def get_msg_note_prompt(self, prompt_name, is_note=False):
prompt_path = 'data/note_prompts' if is_note else 'data/message_prompts'
max_len = self.note_max_len if is_note else self.msg_max_len
if not prompt_name.endswith('.txt'):
prompt_name += '.txt'
prompt = open(os.path.join(prompt_path, prompt_name)).read()
if self.show_rounds:
prompt = f"""You are currently on round {self._current_round_num}.
You only have {self._max_rounds} to reach an agreement otherwise the payoff will be 0. \n\n""" + prompt
if is_note:
if max_len > 0:
prompt += f'\nYour note can never exceed {max_len} words.\n\n'
prompt += open(os.path.join(prompt_path, 'note_standard_suffix.txt')).read()
else:
if max_len > 0:
prompt += f'\nYour offer can never exceed {max_len} words.'
return prompt
def set_system_description(self, game, agent_id, other_agent_desc=None):
system_description = game.get_system_msg(agent_id=agent_id,
agent_desc_int=self.internal_description,
other_agent_desc=other_agent_desc,
visibility=self.visibility)
self.system_description = SystemMessage(system_description)
printv(f'\n[system prompt]\n{system_description}\n', self.verbosity, 1, c=self._get_print_color())
def update_external_description(self, game, agent_id):
"""When the agent plays the role of representative, and the game specifies party names, update external name"""
if self.agent_name_ext == "Representative":
try:
party = game.parties[agent_id]
self.agent_name_ext = f'{self.agent_name_ext} {party}'
self.external_description['name'] = self.agent_name_ext
except Exception as e:
print(f'warning: unable to update external description - {e}')
def __getitem__(self, key):
return getattr(self, key)
|
/*
In my latest project, I created a site where users are able to create designs based on different templates, fonts, and colors.
This snippet of code was to show how I solved creating a sidemenu options for users to choose from.
The brand menu is where users can choose from different colors that were generated under brand names.
These colors are read by CSS and translated into the users' designs.
Similarly the font menu is where users can change the font used within their design.
These fonts are generated by Google API fonts and can thus easily be read by CSS as well.
The biggest problem I ran into was being able to save the fonts and colors that were chosen and updating
the design to these new colors and fonts.
I remedied this by saving the fonts and colors in the backend database which could then be dispatched
into the frontend so that the designs could have the updated fonts and colors upon being opened.
*/
export default function CreateDesign() {
//useState React Hooks to set menu statuses and starting fonts and colors
const [showBrandMenu, setShowBrandMenu] = useState(false);
const [showFontMenu, setShowFontMenu] = useState(false);
const [color, setColor] = useState('');
const [font, setFont] = useState('');
//a function that opens the brand submenu so users could select the color they wanted for their design
const openBrandMenu = () => {
if (showBrandMenu) return; //if it's already open, exit out of the function
setShowBrandMenu(true); //else set its state to true
};
//useEffect React Hook to add an on click event listener that opened and closed the brand menu
useEffect(() => {
if (!showBrandMenu) return;
const closeBrandMenu = () => {
setShowBrandMenu(false);
};
document.addEventListener('click', closeBrandMenu);
return () => document.removeEventListener("click", closeBrandMenu);
}, [showBrandMenu]); //dependency array held the status of the brand menu, and only changed when this value changed
//Similar functions for the font menu
const openFontMenu = () => {
if (showBrandMenu) return;
setShowFontMenu(true);
};
useEffect(() => {
if (!showFontMenu) return;
const closeFontMenu = () => {
setShowFontMenu(false);
};
document.addEventListener('click', closeFontMenu);
return () => document.removeEventListener("click", closeFontMenu);
}, [showFontMenu]);
//JSX that was returned; what users saw on the webpage
return (
<>
{/* utilizaion of the openBrandMenu function */}
<button id='sidebar' onClick={openBrandMenu}>
<img src={colors} alt='temp' height='40px' />
Background Colors
</button>
{/* if the brand menu is open, this is what shows... */}
{showBrandMenu && (
<div id='temp-menu-item'>
<div className='brands-menu-item'>
<div id='temp-brand-title'>
Brands
</div>
<div className="colors-container">
{/* mapping through the brands object received in the dispatch */}
{Object.values(brands).map(brand => (
<div className="des-brand-colors">
<div id='des-brand-name'>
{brand.name}
</div>
<div id='brand-color-container'>
{/* mapping through the different colors set inside brands */}
{brand.colors.map(color => (
<div
id='each-color'
onClick={() => {
// setting the color to the name that was clicked (CSS color names)
setColor(color.name);
}}
style={{
backgroundColor: `${color.name}`
}}
>
</div>
))}
</div>
</div>
))}
</div>
</div>
<div className='brands-menu-item'>
<div id='color-title'>
Colors
</div>
<div className='color-container'>
{/* mapping through all of the colors registered by CSS */}
{colorsByHue.map(color => (
<div
id='each-color'
onClick={() => {
// setting the color to the name that was clicked
setColor(color.alias);
}}
style={{
backgroundColor: `${color.alias}`
}}
>
</div>
))}
</div>
</div>
</div>
)}
<button id='sidebar' onClick={openFontMenu}>
<img src={fonts} alt='temp' height='34px' />
Fonts
</button>
{/* if the font menu is open, this is what shows... */}
{showFontMenu && (
<div id='temp-menu-item'>
{/* mapping through Google API fonts */}
{__fonts.map(font => (
<div
id='each-font'
onClick={() => {
// setting the font to the one the user clicked on
setFont(font.family)
}}
style={{
fontSize: '18px'
}}
>
{font.family}
</div>
))}
</div>
)}
</>
)
}
|
library(tidyverse)
library(here)
library(ggsci)
library(patchwork)
library(flextable)
library(specr)
source(here("preregistrations/1_pilot/scripts/custom_functions/functions_corrplot.R"))
pilot_data = read_csv(here("data/1_pilot/2_cleaned_data.csv")) |> mutate(study = "pilot")
study1_data = read_csv(here("data/2_study1/2_cleaned_data.csv")) |> mutate(study = "study1")
# IV correlations ---------------------------------------------------------
iv_cor_pooled_table <- bind_rows(
pilot_data |>
mutate(id = paste0("pilot", id)) |>
rename(
vio_comp = violence_composite,
unp_obj_comp = unpredictability_obj,
unp_subj_comp = unpredictability_subj,
unp_comp = unpredictability_composite,
pcunp_mean = unp_mean,
nvs_mean = violence_mean
),
study1_data |>
mutate(id = paste0("study1", id))
) |>
select(nvs_mean, fighting_mean, vio_comp,
quic_total_mean, pcunp_mean, chaos_mean, change_env_mean, unp_obj_comp, unp_subj_comp, unp_comp) |>
corr_table(
numbered = T,
sample_size = F,
c.names = c("Neigh. violence", "Fighting", "Violence comp.",
"QUIC", "Perc. unpredictability", "CHAOS", "Env. change", "Obj. unpredictability", "Subj. Unpredictability", "Unpredictability comp."),
stats = c("mean", "sd", "median", "min", "max", "skew", "kurtosis")
) |>
add_column(empty1 = "", .after = 4) |>
mutate(across(
everything(),
~ifelse(is.na(.), "", .)
)) |>
mutate(across(
everything(),
~formatC(., digits = 2, width = 3, flag = "0", format = 'f'))) |>
flextable() |>
width("empty1", width = .2) |>
width(j = 1, width = .75) |>
set_header_labels(Variable = "", empty1 = "") |>
add_header_row(
values = c(" ", "Violence exposure", " ", "Environmental unpredictability"),
colwidths = c(1, 3, 1, 7)
) |>
border_remove() |>
border(i = 1, j = c("1","2","3","4","5","6","7","8","9"), border.bottom = fp_border_default(), part = "header") |>
border(i = 1, border.top = fp_border_default(), part = "header") |>
border(i = 2, border.bottom = fp_border_default(), part = "header") |>
border(i = 17, border.bottom = fp_border_default(), part = "body") |>
align(i = 1:12, j = 1, align = "left", part = "body") |>
bold(i = 1:2, part = "header") |>
align(i = 1:2, align = c("center"), part = "header") |>
set_table_properties(width = 1, layout = "autofit")
demographics_table <- list(
age = map_dfr(list(pilot_data, study1_data), function(x) {
x |>
summarise(stat = paste0(paste0(round(mean(dems_age, na.rm = T),2), " (", round(sd(dems_age, na.rm = T), 2), ")"))) |>
mutate(categories = "Mean age (SD)") |>
mutate(study = x |> pull(study) |> unique())
}),
sex = map_dfr(list(pilot_data, study1_data), function(x) {
x |>
group_by(dems_sex) |>
tally() |>
mutate(stat = formatC(round(n/sum(n)*100,2), digits = 2, width = 3, flag = "0", format = 'f')) |>
mutate(
categories = case_when(
dems_sex == 0 ~ "sex - Male",
dems_sex == 1 ~ "sex - Female",
dems_sex == 2 ~ "sex - Intersex",
dems_sex == 3 ~ "sex - Prefer not to say"
),
study = x |> pull(study) |> unique()
)}),
ethnicity = map_dfr(list(pilot_data, study1_data), function(x) {
x |>
mutate(dems_ethnicity = ifelse(dems_ethnicity_mixed == 1, "Mixed", dems_ethnicity)) |>
group_by(dems_ethnicity) |>
tally() |>
mutate(stat = formatC(round(n/sum(n)*100,2), digits = 2, width = 3, flag = "0", format = 'f')) |>
mutate(categories = forcats::fct_relevel(dems_ethnicity, "White, Caucasian, Anglo, European American",
"Asian or Asian American (e.g., Chinese, Japanese, and others)",
"Hispanic of Latino (e.g., Mexican American, Central American, and others)",
"Black or African American", "Filipino", "Native American/Alaskan Native/indigenous",
"Middle Eastern", "Mixed", "Prefer not to say")) |>
arrange(categories) |>
mutate(
categories = paste0("eth - ", categories),
study = x |> pull(study) |> unique())
}),
dems_edu = map_dfr(list(pilot_data, study1_data), function(x) {
x |>
mutate(
dems_edu = case_when(
dems_edu == 1 ~ "Some high school",
dems_edu == 2 ~ "GED",
dems_edu == 3 ~ "High school diploma",
dems_edu == 4 ~ "Some college but no college degree",
dems_edu == 5 ~ "Associate's degree",
dems_edu == 6 ~ "Bachelor's or RN degree",
dems_edu == 7 ~ "Master's degree",
dems_edu == 8 ~ "Doctoral or law degree",
dems_edu == 9 ~ "Prefer not to say"
)
) |>
group_by(dems_edu) |>
tally() |>
mutate(stat = formatC(round(n/sum(n)*100,2), digits = 2, width = 3, flag = "0", format = 'f')) |>
mutate(categories = forcats::fct_relevel(dems_edu, "Some high school", "GED", "High school diploma", "Some college but no college degree",
"Associate's degree","Bachelor's or RN degree","Master's degree","Doctoral or law degree")) |>
arrange(categories) |>
mutate(
study = x |> pull(study) |> unique(),
categories = paste0("edu - ", categories))
}),
dems_class = map_dfr(list(pilot_data, study1_data), function(x) {
x |>
mutate(
dems_class_current = case_when(
dems_class_current == 1 ~ "Poor",
dems_class_current == 2 ~ "Working class",
dems_class_current == 3 ~ "Middle class",
dems_class_current == 4 ~ "Upper-middle class",
dems_class_current == 5 ~ "Upper class",
dems_class_current == 6 ~ "Don't know/prefer not to say",
)
) |>
group_by(dems_class_current) |>
tally() |>
mutate(stat = formatC(round(n/sum(n)*100,2), digits = 2, width = 3, flag = "0", format = 'f')) |>
mutate(categories = forcats::fct_relevel(dems_class_current, "Poor","Working class","Middle class","Upper-middle class",
"Upper class","Don't know/prefer not to say")) |>
arrange(categories) |>
mutate(
study = x |> pull(study) |> unique(),
cateogires = paste0("class - ", categories))
})
) |>
bind_rows() |>
select(categories, stat, study) |>
pivot_wider(names_from = study, values_from = stat) |>
mutate(categories = str_remove(categories, ".*-\\s")) |>
mutate(across(c(pilot, study1), ~ifelse(is.na(.), "0", .))) |>
add_row(.after = 1, categories = "Sex (%)") |>
add_row(.after = 6, categories = "Ethnicity (%)") |>
add_row(.after = 16, categories = "Highest education (%)") |>
add_row(.after = 25, categories = "Social class (%)") |>
flextable() |>
set_header_labels(
categories = "",
pilot = "Pilot study",
study1 = "Study 1"
) |>
border_remove() |>
border(i = 1, border.top = fp_border_default(), part = "header") |>
border(i = 1, border.top = fp_border_default(), part = "body") |>
border(i = 32, border.bottom = fp_border_default(), part = "body") |>
set_table_properties(width = 1, layout = "autofit") |>
bold(i = c(1, 2, 7, 17, 26), j = 1) |>
bold(i = 1, j = 2:3, part = "header") |>
padding(i=c(3:6, 8:16, 18:25, 27:32), j=1, padding.left=20)
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.sourceforge.musicsvg.svg.impl;
import com.google.inject.Inject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import net.sourceforge.musicsvg.annotations.SVGSource;
import net.sourceforge.musicsvg.svg.SVGDocument;
import net.sourceforge.musicsvg.svg.SVGWidget;
import org.apache.batik.dom.util.DOMUtilities;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
*
* @author Dav
*/
public class SVGDocumentImpl implements SVGDocument {
public static final String ATTRIBUTE_ID = "id";
public static final String ATTRIBUTE_HREF = "href";
public static final String SVG_NAMESPACE = "http://www.w3.org/2000/svg";
public static final String XLINK_NAMESPACE = "http://www.w3.org/1999/xlink";
private Document doc;
private Document sourceDocument;
@Inject
void injectSourceDocument(
@SVGSource Document source) {
sourceDocument = source;
}
@Inject
public void injectDocument(Document doc) {
this.doc = doc;
}
@Override
public Element createElement(String type, Integer id) {
if (type == null) {
return null;
}
Element elt = doc.createElementNS(SVG_NAMESPACE, type);
if (id != null) {
elt.setAttribute(ATTRIBUTE_ID, id.toString());
}
return elt;
}
@Override
public void addElement(Element elt) {
doc.getDocumentElement().appendChild(elt);
}
@Override
public Element createElement(SVGWidget svgWidget, Integer id) {
if (svgWidget == null) {
return null;
}
Element elt = createElement(svgWidget.getType(), id);
elt.setAttributeNS(XLINK_NAMESPACE, ATTRIBUTE_HREF, "#" + svgWidget.getWidgetName());
return elt;
}
@Override
public void importElement(String widgetName) {
Element elt = sourceDocument.getElementById(widgetName);
Node importedNode = doc.importNode(elt, true);
doc.getDocumentElement().appendChild(importedNode);
}
@Override
public void save(File file) throws IOException {
// TODO: create a FileWriter and inject FileWriter and PrintWriter ?
FileWriter fileWrite = new FileWriter(file);
PrintWriter writer = new PrintWriter(fileWrite);
DOMUtilities.writeDocument(doc, writer);
writer.close();
}
}
|
package io.github.jartool.storage.service.impl;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.PathUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.system.SystemUtil;
import io.github.jartool.storage.common.Constants;
import io.github.jartool.storage.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;
/**
* FileStorageService
*
* @author jartool
*/
@Service
public class FileStorageService implements StorageService {
private static final Log log = LogFactory.get();
/**
* rootLocation
*
*/
private final Path rootLocation;
@Autowired
public FileStorageService(@Value("${jartool.storage.file.storage-path:}") String fileStoragePath) {
if (CharSequenceUtil.isBlank(fileStoragePath)) {
fileStoragePath = FileUtil
.mkdir(new File(CharSequenceUtil.format("{}{}",
SystemUtil.getUserInfo().getHomeDir(),
Constants.File.DIR_STORAGE)))
.getAbsolutePath();
}
this.rootLocation = Paths.get(fileStoragePath);
}
@Override
public void init() {
try {
Files.createDirectories(rootLocation);
} catch (IOException e) {
throw new IllegalArgumentException(Constants.Error.STORAGE_INIT, e);
}
}
/**
* store
*
* @param file file
*/
@Override
public void store(MultipartFile file) {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
if (CharSequenceUtil.isEmpty(filename)) {
throw new IllegalArgumentException(Constants.Error.STORAGE_FILE_NULL);
}
if (file.isEmpty()) {
throw new IllegalArgumentException(CharSequenceUtil.format(Constants.Error.STORAGE_FILE_EMPTY, filename));
}
if (filename.contains("..")) {
throw new IllegalArgumentException(CharSequenceUtil.format(Constants.Error.STORAGE_FILE_FORMAT, filename));
}
try {
Files.copy(file.getInputStream(), this.rootLocation.resolve(filename), StandardCopyOption.REPLACE_EXISTING);
log.info(CharSequenceUtil.format(Constants.Log.FILE_STORE_SUCCESS, filename));
} catch (IOException e) {
throw new IllegalArgumentException(CharSequenceUtil.format(Constants.Error.STORAGE_FILE_STORE, filename), e);
}
}
/**
* loadAll
*
* @return {@code Stream<Path>}
*/
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path->this.rootLocation.relativize(path));
} catch (IOException e) {
throw new IllegalArgumentException(Constants.Error.STORAGE_FILE_READ_FILES, e);
}
}
/**
* 负载
*
* @param fileName fileName
* @return {@code Path}
*/
@Override
public Path load(String fileName) {
return rootLocation.resolve(fileName);
}
/**
* loadAsResource
*
* @param fileName fileName
* @return {@code Resource}
*/
@Override
public Resource loadAsResource(String fileName) {
try {
Path file = load(fileName);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new IllegalArgumentException(CharSequenceUtil.format(Constants.Error.STORAGE_FILE_READ_FILE, fileName));
}
} catch (MalformedURLException e) {
throw new IllegalArgumentException(CharSequenceUtil.format(Constants.Error.STORAGE_FILE_READ_FILE, fileName), e);
}
}
/**
* delete file
*
* @param fileName fileName
*/
@Override
public void delete(String fileName) {
try {
Path file = load(fileName);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
PathUtil.del(file);
log.info(CharSequenceUtil.format(Constants.Log.FILE_DELETE_SUCCESS, fileName));
} else {
throw new IllegalArgumentException(CharSequenceUtil.format(Constants.Error.STORAGE_FILE_READ_FILE, fileName));
}
} catch (MalformedURLException e) {
throw new IllegalArgumentException(CharSequenceUtil.format(Constants.Error.STORAGE_FILE_READ_FILE, fileName), e);
}
}
/**
* delete all file
*
*/
@Override
public void deleteAll() {
FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
}
|
/*
* Created by Rohan Maity on 11/1/21 3:19 PM
* Copyright (c) 2021 . All rights reserved.
* Last modified 11/1/21 3:12 PM
*/
package io.rot.labs.projectconf.ui.upcoming
import android.os.Bundle
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import io.rot.labs.projectconf.R
import io.rot.labs.projectconf.TestComponentRule
import io.rot.labs.projectconf.data.local.db.FakeEventsDatabaseService
import io.rot.labs.projectconf.utils.testHelper.RVMatcher.atPositionOnView
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class UpComingFragmentTest {
val component = TestComponentRule(InstrumentationRegistry.getInstrumentation().targetContext)
@get:Rule
val rule = RuleChain.outerRule(component)
lateinit var fakeDbService: FakeEventsDatabaseService
@Before
fun setup() {
fakeDbService = component.testComponent!!.getEventsDatabaseService() as FakeEventsDatabaseService
}
@Test
fun upcomingEventsAvailable_shouldDisplay() {
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
Thread.sleep(1500)
onView(withId(R.id.rvEvents)).check(matches(isDisplayed()))
onView(withId(R.id.rvEvents)).check(
matches(
atPositionOnView(
1,
withText("PragmaConf"),
R.id.tvConfName
)
)
)
onView(withId(R.id.rvEvents)).check(
matches(
atPositionOnView(
2,
withText("KotlinersConf"),
R.id.tvConfName
)
)
)
}
@Test
fun upcomingEventsConnectError_shouldShowRetry() {
fakeDbService.toThrowConnectException = true
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
onView(withId(R.id.btnNoConnectionRetry)).check(matches(isDisplayed()))
}
@Test
fun upcomingEventsTimeoutError_shouldShowRetry() {
fakeDbService.toThrowTimeOutException = true
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
onView(withId(R.id.btnErrorRetry)).check(matches(isDisplayed()))
}
@Test
fun upcomingEventsPython_shouldNavigate_To_Python_EventsList() {
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
Thread.sleep(1500)
onView(withId(R.id.ivPython)).perform(ViewActions.click())
onView(withId(R.id.tvGenericTitle)).check(matches(withText("PYTHON")))
}
@Test
fun upcomingEventsRust_shouldNavigate_To_Rust_EventsList() {
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
Thread.sleep(1500)
onView(withId(R.id.ivRust)).perform(ViewActions.click())
onView(withId(R.id.tvGenericTitle)).check(matches(withText("RUST")))
}
@Test
fun upcomingEventsGoLang_shouldNavigate_To_Golang_EventsList() {
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
Thread.sleep(1500)
onView(withId(R.id.ivGolang)).perform(ViewActions.click())
onView(withId(R.id.tvGenericTitle)).check(matches(withText("GOLANG")))
}
@Test
fun upcomingEventsGraphQl_shouldNavigate_To_GraphQl_EventsList() {
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
Thread.sleep(1500)
onView(withId(R.id.ivGraphql)).perform(ViewActions.click())
onView(withId(R.id.tvGenericTitle)).check(matches(withText("GRAPHQL")))
}
@Test
fun upcomingEventsCloudDevOps_shouldNavigate_To_CloudDevOps_EventsList() {
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
Thread.sleep(1500)
onView(withId(R.id.techBannerPager)).check(matches(isDisplayed()))
onView(withId(R.id.techBannerPager))
.perform(ViewActions.click())
onView(withId(R.id.tvCloudDevOpsList)).check(matches(isDisplayed()))
onView(withId(R.id.tvCloudDevOpsList)).check(matches(withText("Cloud and DevOps")))
}
@Test
fun upcomingEventsMobileDev_shouldNavigate_To_MobileDev_EventsList() {
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
Thread.sleep(1500)
onView(withId(R.id.techBannerPager)).check(matches(isDisplayed()))
onView(withId(R.id.techBannerPager))
.perform(ViewActions.swipeLeft())
Thread.sleep(1000)
onView(withId(R.id.techBannerPager))
.perform(ViewActions.click())
onView(withId(R.id.tvMobileDevList)).check(matches(isDisplayed()))
onView(withId(R.id.tvMobileDevList)).check(matches(withText("Mobile Development")))
}
@Test
fun upcomingEventsDesign_shouldNavigate_To_Design_EventsList() {
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
Thread.sleep(1500)
onView(withId(R.id.techBannerPager)).check(matches(isDisplayed()))
onView(withId(R.id.techBannerPager))
.perform(ViewActions.swipeLeft())
onView(withId(R.id.techBannerPager))
.perform(ViewActions.swipeLeft())
Thread.sleep(1000)
onView(withId(R.id.techBannerPager))
.perform(ViewActions.click())
onView(withId(R.id.tvDesignList)).check(matches(isDisplayed()))
onView(withId(R.id.tvDesignList)).check(matches(withText("Design")))
}
@Test
fun upcomingEventsJVM_Universe_shouldNavigate_To_JVM_Universe_EventsList() {
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
Thread.sleep(1500)
onView(withId(R.id.techBannerPager)).check(matches(isDisplayed()))
onView(withId(R.id.techBannerPager))
.perform(ViewActions.swipeLeft())
onView(withId(R.id.techBannerPager))
.perform(ViewActions.swipeLeft())
onView(withId(R.id.techBannerPager))
.perform(ViewActions.swipeLeft())
Thread.sleep(1000)
onView(withId(R.id.techBannerPager))
.perform(ViewActions.click())
onView(withId(R.id.tvJvmUniverseList)).check(matches(isDisplayed()))
onView(withId(R.id.tvJvmUniverseList)).check(matches(withText("JVM Universe")))
}
@Test
fun upcomingEventsJS_Land_shouldNavigate_To_JS_Land_EventsList() {
launchFragmentInContainer<UpComingFragment>(Bundle(), R.style.Theme_ProjectConf)
Thread.sleep(1500)
onView(withId(R.id.techBannerPager)).check(matches(isDisplayed()))
onView(withId(R.id.techBannerPager))
.perform(ViewActions.swipeLeft())
onView(withId(R.id.techBannerPager))
.perform(ViewActions.swipeLeft())
onView(withId(R.id.techBannerPager))
.perform(ViewActions.swipeLeft())
onView(withId(R.id.techBannerPager))
.perform(ViewActions.swipeLeft())
Thread.sleep(1000)
onView(withId(R.id.techBannerPager))
.perform(ViewActions.click())
onView(withId(R.id.tvJSLandList)).check(matches(isDisplayed()))
onView(withId(R.id.tvJSLandList)).check(matches(withText("JS Land")))
}
}
|
import { useEffect, useState } from "react";
import BemNav from "../../components/bem/bemNav";
import BemOrders from "../../components/bem/BemOrders";
import BemProducts from "../../components/bem/bemProducts";
import BemRescues from "../../components/bem/bemRescues";
import BemUsers from "../../components/bem/bemUsers";
import { useQuery } from "@tanstack/react-query";
const fetchRescues = async () => {
const response = await fetch("/api/data/rescues");
const data = await response.json();
return data;
};
const fetchProducts = async () => {
const response = await fetch("/api/data/products");
const data = await response.json();
return data;
};
const fetchOrders = async () => {
//fetch orders from api
const response = await fetch("/api/data/orders");
const data = await response.json();
// const openOrders = data.filter((order) => order.status === "new");
return data;
};
const fetchUsers = async () => {
const response = await fetch("/api/data/users");
const data = await response.json();
return data;
};
const BemPage = () => {
const [currentModule, setCurrentModule] = useState("orders");
const [isDataLoading, setIsDataLoading] = useState(true);
const [allOrders, setAllOrders] = useState();
const [allProducts, setAllProducts] = useState();
const [allRescues, setAllRescues] = useState();
const [allUsers, setAllUsers] = useState();
const usersQuery = useQuery({
queryKey: ["users"],
queryFn: fetchUsers,
enabled: true,
});
const ordersQuery = useQuery({
queryKey: ["orders"],
queryFn: fetchOrders,
enabled: true,
});
const productsQuery = useQuery({
queryKey: ["products"],
queryFn: fetchProducts,
enabled: true,
});
const rescuesQuery = useQuery({
queryKey: ["rescuesa"],
queryFn: fetchRescues,
enabled: true,
});
// useEffect(() => {
// if (ordersQuery.status == "success") {
// setAllOrders(ordersQuery.data);
// }
// }, [ordersQuery.status, ordersQuery.data, ordersQuery.isLoading]);
// useEffect(() => {
// if (rescuesQuery.status == "success") {
// setAllOrders(rescuesQuery.data);
// }
// }, [rescuesQuery.status, rescuesQuery.data, rescuesQuery.isLoading]);
// useEffect(() => {
// if (productsQuery.status == "success") {
// if (productsQuery.data) {
// setAllOrders(productsQuery.data);
// }
// }
// }, [productsQuery.status, productsQuery.data, productsQuery.isLoading]);
// useEffect(() => {
// if (usersQuery.status == "success") {
// setAllOrders(usersQuery.data);
// }
// }, [usersQuery.status, usersQuery.data, usersQuery.isLoading]);
return (
<div>
{productsQuery.status === "success" ? (
<div>
{rescuesQuery.status === "success" ? (
<div>
{ordersQuery.status === "success" ? (
<div>
{usersQuery.status === "success" ? (
<div>
<div>
<BemNav
currentModule={
currentModule
}
setCurrentModule={
setCurrentModule
}
/>
</div>
<div>
<div>
{currentModule ===
"orders" && (
<BemOrders
allOrders={
ordersQuery.data
}
allProducts={
productsQuery.data
}
ordersRefetch={
ordersQuery.refetch
}
/>
)}
</div>
<div>
{currentModule ===
"products" && (
<BemProducts
allProducts={
productsQuery.data
}
/>
)}
</div>
<div>
{currentModule ===
"users" && (
<BemUsers
allUsers={
usersQuery.data
}
userRefetch={usersQuery.refetch}
/>
)}
</div>
<div>
{currentModule ===
"rescues" && (
<BemRescues
allRescues={
rescuesQuery.data
}
rescueRefetch ={rescuesQuery.refetch}
/>
)}
</div>
</div>
</div>
) : (
<div> Loading ... </div>
)}
</div>
) : (
<div> Loading ...</div>
)}
</div>
) : (
<div> Loading ...</div>
)}
</div>
) : (
<div> Loading ...</div>
)}
</div>
);
};
export default BemPage;
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('user_institutions', function (Blueprint $table) {
$table->id('user_institution_id');
$table->foreignId('user_id')->nullable()
->constrained('users', 'user_id')
->cascadeOnUpdate()
->cascadeOnDelete();
$table->foreignId('institution_id')->nullable()
->constrained('institutions', 'institution_id')
->cascadeOnUpdate()
->cascadeOnDelete();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('user_institutions');
}
};
|
#### 算法
贪心+无数有趣的细节
**高能预警:** 本题**细节较多**,请仔细食用。
#### 思路
从小数点往后搜,直到遇见第一个$\geq 5$的数字,它就是我们要四舍五入的第一个。然后从它开始往回搜,只要$\geq 5$就四舍五入。
#### 正确性
小数点后位数靠前的数字越大,值越大,所以我们将第一个能“$5$入”的点“入”掉(因为这样才能使得“入”过去的$1$价值最大)。
那为什么往回搜的时候能入则入呢?
+ 因为往回搜的数必然是小于$5$的,只有当前的数往前进了位才有可能$\geq 5$,所以我们只能给当前数进位(如果它可以)。
#### 细节
+ 整数位上不能四舍五入(但可以进位)!
+ 小数位与整数位的进位要分开处理!
+ 可能出现一个也不能进的情况!
+ 整数的最高位有可能进$1$! (如:$99.459$)
+ 记得判断没有小数点的情况!
大概就这么多了……
#### 参考代码
```cpp
/*
* @Author: When_C
* @Date: 2020-11-19 19:29:11
* @Last Modified by: When_C
* @Last Modified time: 2020-11-19 19:49:45
*/
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 2e5 + 10;
int n,t,a[maxn],top;
char c[maxn];
int main(){
scanf("%d%d%s", &n, &t, c + 1);
int loc,pos = -1;
for(int i = 1; i <= n; ++ i){
if(c[i] >= '0' && c[i] <= '9') a[++top] = c[i] - '0';
else loc = top + 1;
}
for(int i = loc; i <= top; ++ i)
if(a[i] >= 5){pos = i; break;}
if(pos > 0){
int pre = 1; pos -= 1; t -= 1;
for(int i = pos; i >= 1; -- i){
if(!pre && (!t || i < loc)) break;
a[i] += pre; pre = 0;
if(a[i] > 10) pre = 1, a[i] %= 10;
if(a[i] == 10){
pre = 1; a[i] %= 10;
if(i >= loc) pos -= 1;
}
if(a[i] >= 5 && t && i >= loc) pre += 1, pos -= 1, t--;
}
if(pre) a[0] = 1;
}
if(a[0]) printf("%d", a[0]);
for(int i = 1; i <= pos; ++ i){
printf("%d", a[i]);
if(i == loc - 1 && i != pos) printf(".");
}
if(pos < 0) printf("%s", c + 1);
return 0;
}
```
|
#pragma once
#include <vector>
#include <string>
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include "Eigen/Eigen"
using namespace std;
using namespace Eigen;
using namespace boost::property_tree;
struct dh_param{
int id;
double d;
double theta_offset;
double a;
double alpha;
friend ostream& operator<<(ostream& out, const dh_param& ref)
{
out << "id = " << ref.id << "\t" << "d = " << ref.d << "\t" << "theta_offset = " << ref.theta_offset << "\t" << "a = " << ref.a << "\t" << "alpha = " << ref.alpha << endl;
return out;
}
};
struct joint {
double angle;
int coder_cnt;
double min;
double max;
friend ostream& operator<<(ostream& out, const joint& ref)
{
out << "angle: " << ref.angle << "\t" << "coder_cnt: " << ref.coder_cnt << "\t" << "min: " << ref.min << "\t" << "max: " << ref.max <<endl;
return out;
}
};
struct motor {
double gear_ratio;
int bits;
double velocity_ave_max_deg;
double velocity_instant_max_deg;
friend ostream& operator<<(ostream& out, const motor& ref)
{
out << "gear_ratio: " << ref.gear_ratio << "\t" << "bits: " << ref.bits << endl;
return out;
}
};
struct driver {
vector<int> enable;
vector<int> disable;
vector<int> clear_warning;
vector<int> ignore_status;
friend ostream& operator<<(ostream& out, const driver& ref)
{
out << "enable: ";
for(const int& t : ref.enable) {
out << t << "\t" ;
out << endl;
}
out << "disable: ";
for(const int& t : ref.disable) {
out << t << "\t" ;
out << endl;
}
out << "clear_warning: ";
for(const int& t : ref.clear_warning) {
out << t << "\t" ;
out << endl;
}
out << "ignore_status: ";
for(const int& t : ref.ignore_status) {
out << t << "\t" ;
out << endl;
}
return out;
}
};
class JsonConfigLoader {
private:
JsonConfigLoader();
static JsonConfigLoader *instance;
string default_file_path;
static ptree root;
public:
static JsonConfigLoader* GetInstance();
static void ReleaseINstance();
static bool initialized; /*judge whether .json has been loaded*/
static int num_joints; /*number of robots joints*/
static vector<dh_param> dh_table; /*define vector to store DH parameter according dh_param*/
static vector<int> zero_point;
static vector<double> home_poseJoint; /*define vector to store Home Position of Joints of Robot */
static vector<joint> joints;
static vector<motor> motors;
static driver driver_instance;
ptree GetRoot() const {
return root;
}
bool UpdateRobotJsonConfig(string file_path); /*Parse json to update the stored data vector*/
bool LoadRobotJsonConfig(string file_path); /*Initial, call UpdateRobotJsonConfig()*/
bool SaveRobotJsonConfig(string file_path, VectorXd save_joints, VectorXd save_motors_positions); /*Store the joints "angle" and "coder_cnt" as json*/
};
|
import React, {useMemo, useReducer} from 'react';
import {Text, View, TouchableOpacity, Image, StyleSheet} from 'react-native'
import Estrelas from '../../../componentes/Estrelas';
const distanciaEmMetros = (distancia) => {
console.log('distanciaEmMetros');
return `${distancia}m`
}
export default function Produtor({nome, imagem, distancia, estrelas}) {
const [selecionado, inverterSelecionado] = useReducer(
(selecionado) => !selecionado,
false
);
const distanciaTexto = useMemo(() => distanciaEmMetros(distancia), [distancia]);
return <TouchableOpacity
style={estilo.cartao}
onPress={inverterSelecionado}
>
<Image source={imagem} style={estilo.imagem} accessibilityLabel={nome} />
<View style={estilo.informacoes}>
<View>
<Text style={estilo.nome}>{nome}</Text>
<Estrelas quantidade={estrelas}
editavel={selecionado}
grande={selecionado}/>
</View>
<Text style={estilo.distancia}>{distanciaTexto}</Text>
</View>
</TouchableOpacity>
}
const estilo = StyleSheet.create({
cartao: {
backgroundColor: '#F6F6F6',
marginVertical: 8,
marginHorizontal: 16,
borderRadius: 6,
flexDirection: 'row',
elevation: 2,
},
imagem: {
width: 48,
height: 48,
borderRadius: 6,
marginVertical: 16,
marginLeft: 16,
},
informacoes: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
marginLeft: 8,
marginVertical: 16,
marginRight: 16,
},
nome: {
fontSize: 14,
lineHeight: 22,
fontWeight: 'bold',
},
distancia: {
fontSize: 12,
lineHeight: 19,
}
})
|
package tn.esprit.foyeruniversiteeya.controllers;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tn.esprit.foyeruniversiteeya.entities.Foyer;
import tn.esprit.foyeruniversiteeya.entities.Universite;
import tn.esprit.foyeruniversiteeya.services.FileStorageService;
import tn.esprit.foyeruniversiteeya.services.FoyerExcelExporter;
import tn.esprit.foyeruniversiteeya.services.IFoyerService;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@RestController
@AllArgsConstructor
@RequestMapping("/Foyer")
public class FoyerController {
private final IFoyerService foyerService;
private final FileStorageService fileStorageService;
@PostMapping("/addfoyer")
public Foyer addFoyer(@RequestBody Foyer foyer) {
return foyerService.addFoyer(foyer);
}
@GetMapping("/foyer/{id}")
Foyer retrieveFoyer(@PathVariable Long id) {
return foyerService.getFoyer(id);
}
@GetMapping("/foyer")
List<Foyer> retrieveFoyers() {
return foyerService.getAllFoyers();
}
@DeleteMapping("/deletefoyer/{id}")
void deleteFoyer(@PathVariable Long id) {
foyerService.deleteFoyer(id);
}
@PutMapping("/updatefoyer")
Foyer updateFoyer(@RequestBody Foyer foyer){
return foyerService.updateFoyer(foyer);
}
/*Foyer updateFoyer(@PathVariable(value = "idFoyer") Long id,@RequestBody Foyer foyer){
return foyerService.updateFoyer(id,foyer);
}*/
/* @PostMapping("/addfoyer")
Foyer ajouterFoyerEtAffecterAUniversite(@RequestBody Foyer foyer,@PathVariable long idUniversity ){
}*/
@GetMapping("/export-to-excel")
public void exportIntoExcelFile(HttpServletResponse response) throws IOException {
response.setContentType("application/octet-stream");
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String currentDateTime = dateFormatter.format(new Date());
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=foyer" + currentDateTime + ".xlsx";
response.setHeader(headerKey, headerValue);
List<Foyer> listOfFoyers = foyerService.getTheListStudent();
FoyerExcelExporter generator = new FoyerExcelExporter(listOfFoyers);
generator.generateExcelFile(response);
}
}
|
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using SuperHeroAPI.Models.Request;
using SuperHeroAPI.Models.Response;
using SuperHeroAPI.Services;
using System.Net.Http.Json;
namespace IntegrationTests.Tests
{
public class AuthenticationTests
{
[Fact]
public async void Signup()
{
// Arrange
var application = new SuperHeroWebApplicationFactory();
using (var scope = application.Services.CreateScope())
{
AuthenticationRequest request = new AuthenticationRequest();
request.Username = "user";
request.Password = "password";
var client = application.CreateClient();
// Act
var response = await client.PostAsJsonAsync("/auth/signup", request);
// Assert
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
responseBody.Should().NotBeNullOrEmpty();
var tokenService = scope.ServiceProvider.GetRequiredService<TokenService>();
tokenService.IsValidToken(responseBody).Should().BeTrue();
}
}
[Fact]
public async void Signin()
{
// Arrange
var application = new SuperHeroWebApplicationFactory();
using (var scope = application.Services.CreateScope())
{
AuthenticationRequest request = new AuthenticationRequest();
request.Username = "eduardo";
request.Password = "senha";
var client = application.CreateClient();
// Act
var response = await client.PostAsJsonAsync("/auth/signin", request);
// Assert
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
responseBody.Should().NotBeNullOrEmpty();
var tokenService = scope.ServiceProvider.GetRequiredService<TokenService>();
tokenService.IsValidToken(responseBody).Should().BeTrue();
}
}
[Fact]
public async void Signin_WrongPassword()
{
// Arrange
var application = new SuperHeroWebApplicationFactory();
AuthenticationRequest request = new AuthenticationRequest();
request.Username = "eduardo";
request.Password = "password";
var client = application.CreateClient();
// Act
var response = await client.PostAsJsonAsync("/auth/signin", request);
// Assert
response.StatusCode.Should().Be(System.Net.HttpStatusCode.BadRequest);
var responseBody = await response.Content.ReadFromJsonAsync<ErrorResponse>();
responseBody.Should().NotBeNull();
responseBody!.Message.Should().Be("Invalid credentials.");
}
[Fact]
public async void Signup_UsernameAlreadyTaken()
{
// Arrange
var application = new SuperHeroWebApplicationFactory();
AuthenticationRequest request = new AuthenticationRequest();
request.Username = "eduardo";
request.Password = "password";
var client = application.CreateClient();
// Act
var response = await client.PostAsJsonAsync("/auth/signup", request);
// Assert
response.StatusCode.Should().Be(System.Net.HttpStatusCode.BadRequest);
var responseBody = await response.Content.ReadFromJsonAsync<ErrorResponse>();
responseBody.Should().NotBeNull();
responseBody!.Message.Should().Be("Username already taken.");
}
}
}
|
### [题目传送门](https://www.luogu.com.cn/problem/CF205B)
------------
### 题意:
给定 $n$ 个数,每次任选一个区间,将区间内的每个数 $+1$,问最少操作几次才能使得原序列变成一个不下降子序列?
------------
### 思路:
不下降子序列就是序列中后一个数不能小于前一个数。
可以从前往后遍历整个序列,如果前一个数大于后一个数,则操作次数就是**两个数的差值**。最后把所有操作次数累加就能得出答案。
------------
### 注意:
这道题一定开 long long!否则就会[错误](https://www.luogu.com.cn/record/68084663)。
------------
### code:
```cpp
#include <bits/stdc++.h>
using namespace std;
long long n;
long long a[100005],cnt;
int main(){
cin>>n;
for(long long i=1;i<=n;i++) cin>>a[i];
for(long long i=1;i<n;i++){
if(a[i]>a[i+1])
cnt+=a[i]-a[i+1];
}
cout<<cnt<<endl;
return 0;
}
```
|
### Simple C++ Chat Application
This repository contains a simple chat application implemented in C++ using Microsoft Visual Studio Code. The application consists of two main components: a server and a client.
### Features
- **Real-time Communication**: Users can connect to the server and send/receive messages in real-time.
- **Multiple Client Support**: The server supports multiple client connections concurrently, enabling group communication.
- **User-Friendly Interface**: The client provides a user-friendly interface for sending and receiving messages.
- **Error Handling**: The application includes error handling mechanisms to gracefully deal with connection failures and other issues.
### Dependencies
- **WinSock Library**: The application relies on the WinSock library for socket programming on Windows platforms.
- **C++ Standard Library**: Standard C++ libraries are used for threading, input/output, and other functionalities.
### Usage
1. **Server Setup**: Compile and run the server application. It listens for incoming connections from clients.
2. **Client Setup**: Compile and run the client application. Enter the server's IP address and port number to connect.
3. **Chatting**: Once connected, users can send messages to the server, which broadcasts them to all other connected clients.
### Server Setup
The server terminal when it's running and waiting for client connections:

### Client Setup
### Chatting
Screenshots of both client terminals engaged in a chat conversation:
- Client1 Terminal:

- Client2 Terminal:

### Code Structure
- **Server**: The server code (`server.cpp`) handles socket initialization, client connections, and message broadcasting.
- **Client**: The client code (`client.cpp`) manages socket connection to the server, sending and receiving messages.
### How to Compile and Run
```bash
# Server Compilation
g++ server.cpp -o server -lws2_32
# Server Execution
./server
# Client Compilation
g++ client.cpp -o client -lws2_32
# Client Execution
./client
|
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const NotDataError = require('../errors/NotDataError');
const IncorrectDataError = require('../errors/IncorrectDataError');
const EmailExistsError = require('../errors/EmailExistsError');
const getUsersAll = (req, res, next) => {
User.find({})
.then((users) => res.status(200).send(users))
.catch(next);
};
const getUserMe = (req, res, next) => {
const userId = req.user._id;
User.findById(userId)
.then((user) => {
if (!user) {
throw new NotDataError('Пользователь по указанному _id не найден');
}
return res.status(200).send(user);
})
.catch((err) => {
if (err.name === 'ValidationError') {
next(new IncorrectDataError('Некорректный _id'));
}
next(err);
});
};
const addUser = (req, res, next) => {
const user = {
name: req.body.name,
about: req.body.about,
avatar: req.body.avatar,
email: req.body.email,
password: req.body.password,
};
bcrypt.hash(user.password, 10)
.then((hash) => {
user.password = hash;
User.create(user)
.then(() => {
delete user.password;
res.status(200).send(user);
})
.catch((err) => {
if (err.name === 'ValidationError') {
next(new IncorrectDataError('Переданы некорректные данные'));
} else if (err.code === 11000) {
next(new EmailExistsError('Пользователь с таким email уже существует'));
} else {
next(err);
}
});
})
.catch(next);
};
const getUser = (req, res, next) => {
const { userId } = req.params;
User.findById(userId)
.then((user) => {
if (!user) {
next(new NotDataError('Пользователь по указанному _id не найден'));
} else {
next(res.status(200).send(user));
}
})
.catch((err) => {
if (err.name === 'CastError') {
next(new IncorrectDataError('Некорректный _id'));
return;
}
next(err);
});
};
const updateUserInfo = (req, res, next) => {
const userInfo = {
name: req.body.name,
about: req.body.about,
};
User.findByIdAndUpdate(req.user._id, userInfo, { new: true, runValidators: true })
.then((user) => {
if (!user) {
throw new NotDataError('Пользователь по указанному _id не найден');
}
return res.status(200).send(user);
})
.catch((err) => {
if (err.name === 'ValidationError') {
next(new IncorrectDataError('Переданы некорректные данные'));
return;
}
next(err);
});
};
const updateUserAvatar = (req, res, next) => {
const userAvatar = {
avatar: req.body.avatar,
};
User.findByIdAndUpdate(req.user._id, userAvatar, { new: true, runValidators: true })
.then((user) => {
if (!user) {
throw new NotDataError('Пользователь по указанному _id не найден');
}
return res.status(200).send(user);
})
.catch((err) => {
if (err.name === 'ValidationError') {
next(new IncorrectDataError('Переданы некорректные данные'));
return;
}
next(err);
});
};
const login = (req, res, next) => {
const { email, password } = req.body;
User.findUserByCredentials(email, password)
.then(() => {
// Создадим токен
User.findOne({ email }).select('+password')
.then((user) => {
const token = jwt.sign({ _id: user._id }, 'some-secret-key', { expiresIn: '7d' });
// Вернём токен
res.status(200).send({ token });
});
})
.catch(next);
};
module.exports = {
getUsersAll,
addUser,
getUser,
updateUserInfo,
updateUserAvatar,
login,
getUserMe,
};
|
import {
Post,
UseInterceptors,
UploadedFile,
Controller,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import * as path from 'path';
@Controller('upload')
export class UploadController {
@Post('file')
@UseInterceptors(
FileInterceptor('file', {
storage: diskStorage({
destination: './uploads',
filename: (req, file, cb) => {
const filename =
path.parse(file.originalname).name.replace(/\s/g, '') + Date.now();
const extention = path.parse(file.originalname).ext;
cb(null, `${filename}${extention}`);
},
}),
}),
)
uploadFile(@UploadedFile() file: Express.Multer.File) {
return { UploadedFilePath: file.path };
}
}
|
import { FormEvent, useState } from 'react';
import { Link, useHistory } from 'react-router-dom';
import { Toaster } from 'react-hot-toast';
import toast from 'react-hot-toast';
import illustrationImg from '../assets/images/illustration.svg';
import logoImg from '../assets/images/logo.svg';
import { Button } from '../components/Button';
import { database } from '../services/firebase';
import { useAuth } from '../hooks/useAuth';
import '../styles/auth.scss';
export function NewRoom() {
const { user } = useAuth();
const history = useHistory();
const [ newRoom, setNewRoom ] = useState('');
async function handleCreateRoom(event: FormEvent) {
event.preventDefault();
if (newRoom.trim() === '') {
return;
}
if (!user) {
toast.error("Para criar uma sala, é necessário fazer o login.");
return;
}
const roomRef = database.ref('rooms');
const firebaseRoom = await roomRef.push({
title: newRoom,
authorId: user?.id,
})
history.push(`/admin/rooms/${firebaseRoom.key}`);
}
return (
<div id="page-auth">
<Toaster
position="top-center"
reverseOrder={false}
/>
<aside>
<img src={illustrationImg} alt="Ilustração simbolizando perguntas e respostas" />
<strong>Toda pergunta tem uma resposta.</strong>
<p>Aprenda e compartilhe conhecimento com outras pessoas</p>
</aside>
<main>
<div className="main-content">
<img src={logoImg} alt="Letmeask" />
<h2>Crie uma nova sala</h2>
<form onSubmit={handleCreateRoom}>
<input
type="text"
placeholder="Nome da sala"
onChange={event => setNewRoom(event.target.value)}
value={newRoom}
/>
<Button type="submit">
Criar sala
</Button>
</form>
<p>
Quer entrar em uma sala existente? <Link to="/">Clique aqui</Link>
</p>
</div>
</main>
</div>
);
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLogsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('logs', function (Blueprint $table) {
$table->increments('id');
$table->string('table_name',20);
$table->string('operation',20);
$table->text('old_value')->nullable();
$table->text('new_value')->nullable();
$table->text('user');
$table->string('table_before')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('logs');
}
}
|
import {Requirement, TripRequirements} from "./models/TripRequirements";
import {
Grid,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Typography,
} from "@mui/material";
import {FetchStatus} from "./models/FetchStatus";
import {format} from "date-fns";
import "./RequirementResults.css";
export default function RequirementResults({
tripRequirements,
fetchStatus,
}: RequirementResultsProps) {
if (FetchStatus.INITIAL === fetchStatus) {
return null;
}
if (FetchStatus.ERROR === fetchStatus || !tripRequirements) {
return <Typography variant="h5">Error Occurred. Try again.</Typography>;
}
const {
startDate,
finishDate,
foodRequirements,
itemRequirements,
shelterRequirements,
} = tripRequirements;
return (
<Grid container justifyContent="center">
<Typography variant="h5">Results: </Typography>
<Grid container item justifyContent="center" className="dates-container">
<DateResult label="Start date" date={startDate}/>
<DateResult label="Finish date" date={finishDate}/>
</Grid>
<Grid container item justifyContent="space-between" xs={12} md={6}>
<RequirementResult
label="Food requirements"
requirements={foodRequirements}
/>
<RequirementResult
label="Item requirements"
requirements={itemRequirements}
/>
<RequirementResult
label="Shelter requirements"
requirements={shelterRequirements}
/>
</Grid>
</Grid>
);
}
function DateResult({label, date}: DateResultProps) {
return (
<Grid item xs={6} md={4}>
<Typography sx={{fontWeight: 'bold'}}>{label}</Typography>
<Typography>{format(new Date(date), "yyyy-MM-dd")}</Typography>
</Grid>
);
}
function RequirementResult({label, requirements}: RequirementResultProps) {
if (!requirements?.length) {
return null;
}
return (
<Grid item xs={12} md={5} marginY={3}>
<Typography sx={{fontWeight: 'bold'}}>{label}</Typography>
<TableContainer>
<Table>
<TableHead>
<TableRow>
<TableCell sx={{fontWeight: 'bold'}}>Name</TableCell>
<TableCell sx={{fontWeight: 'bold'}}>Count</TableCell>
</TableRow>
</TableHead>
<TableBody>
{requirements.filter(item => item.count > 0).map(({name, count}, index) => (
<TableRow key={name}>
<TableCell>{name}</TableCell>
<TableCell>{count}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Grid>
);
}
interface RequirementResultsProps {
tripRequirements: TripRequirements | null;
fetchStatus: FetchStatus;
}
interface DateResultProps {
label: string;
date: string;
};
interface RequirementResultProps {
label: string;
requirements: Requirement[];
}
|
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template
*/
package com.mycompany.simple_chatbot.servlet;
import com.mycompany.simple_chatbot.config.util.StringConstants;
import com.mycompany.simple_chatbot.config.util.URLUtils;
import com.mycompany.simple_chatbot.model.UserInfo;
import com.mycompany.simple_chatbot.service.RedisService;
import com.mycompany.simple_chatbot.service.impl.RedisServiceImpl;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author lesan
*/
@WebServlet(name = "HomeServlet", urlPatterns = {"/"})
public class HomeServlet extends HttpServlet {
private RedisService redisService = RedisServiceImpl.getInstance();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserInfo userInfo = (UserInfo)request.getSession().getAttribute(StringConstants.USER_SESSION);
String tokenValue = redisService.getValueByKey(userInfo == null ? "" : userInfo.getUserToken());
if (userInfo == null || tokenValue == null) {
response.sendRedirect(URLUtils.getFullURL(URLUtils.LOGIN_URL));
} else
{
String url = URLUtils.getFullURL(URLUtils.CHAT_URL);
response.sendRedirect(url);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
import {useNavigation} from '@react-navigation/native';
import React, {useState} from 'react';
import {Image, Text, TouchableOpacity, View} from 'react-native';
import images from '../assets/icon/images';
import Entypo from 'react-native-vector-icons/Entypo';
type Props = {
title: string;
subtitle?: string;
showMoreVisible?: boolean;
hideBack?: boolean;
onCountChange?: (count: number) => void;
};
export default function Header(props: Props) {
const {title, subtitle, onCountChange, showMoreVisible, hideBack} = props;
const [headerCount, setHeaderCount] = useState(0);
const navigation = useNavigation();
function _renderGoBack() {
if (!navigation?.canGoBack() || hideBack) return null;
return (
<TouchableOpacity
onPress={() => {
navigation.goBack();
}}>
<Entypo name="chevron-left" size={30} color="black" />
{/* <Image source={images.ArrowBack} style={{width: 48, height: 48}} /> */}
</TouchableOpacity>
);
}
function _renderShowMore() {
if (!showMoreVisible) return null;
return <Image source={images.More} style={{width: 48, height: 48}} />;
}
return (
<View
style={{
flexDirection: 'row',
height: 60,
marginBottom: 2,
backgroundColor: 'white',
alignItems: 'center',
paddingHorizontal: 8,
}}>
{_renderGoBack()}
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text
style={{
fontSize: 20,
color: 'black',
fontFamily: 'EuclidCircularA-Bold',
}}>
{title}
</Text>
</View>
{_renderShowMore()}
</View>
);
}
|
package ru.sber.shareit.controller;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import ru.sber.shareit.controller.BookingController;
import ru.sber.shareit.dto.booking.BookingDto;
import ru.sber.shareit.dto.booking.BookingDtoFull;
import ru.sber.shareit.dto.item.ItemDto;
import ru.sber.shareit.dto.user.UserInfoDto;
import ru.sber.shareit.entity.enums.BookingStatus;
import ru.sber.shareit.service.BookingService;
import ru.sber.shareit.util.UserIdUtil;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.ArgumentMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(controllers = BookingController.class)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@AutoConfigureMockMvc(addFilters = false)
class BookingControllerTest {
@MockBean
private BookingService bookingService;
@MockBean
private final UserIdUtil userIdUtil;
private final MockMvc mvc;
private final BookingDto bookingDto = new BookingDto(
1L,
LocalDateTime.now().plusDays(1),
LocalDateTime.now().plusDays(2),
1L,
null,
null
);
private final BookingDtoFull bookingDtoFull = new BookingDtoFull(
1L,
LocalDateTime.now().plusDays(1).truncatedTo(ChronoUnit.SECONDS),
LocalDateTime.now().plusDays(2).truncatedTo(ChronoUnit.SECONDS),
new ItemDto(
1L,
"Item1",
"Test item 1",
true,
1L,
null,
null,
null,
new ArrayList<>(),
"NEUTRAL",
"Рязань"
),
new UserInfoDto(1L, "test1", "User1",
"test1@email.com", "ROLE_USER", "Рязань"),
BookingStatus.WAITING
);
@SneakyThrows
@Test
void performCreateItemTest_whenBookingCreated_thenReturnViewGetItemById() {
Mockito.
when(bookingService.create(anyLong(), any()))
.thenReturn(bookingDtoFull);
mvc.perform(post("/bookings/create/1")
.characterEncoding(StandardCharsets.UTF_8)
.flashAttr("booking", bookingDto)
.accept(MediaType.TEXT_HTML))
.andExpect(view().name("redirect:/items/1"))
.andExpect(status().is(302));
}
@SneakyThrows
@Test
void getOwnerBookingsTest_whenBookingsFound_thenReturnViewGetBookingsOwner() {
List<BookingDtoFull> bookings = List.of(bookingDtoFull);
Mockito
.when(bookingService.getOwnerBookings(anyLong(), anyString(), anyInt(), anyInt()))
.thenReturn(bookings);
mvc.perform(get("/bookings/owner")
.characterEncoding(StandardCharsets.UTF_8)
.accept(MediaType.TEXT_HTML))
.andExpect(view().name("bookings/get-bookings-owner"))
.andExpect(model().attribute("bookings", bookings))
.andExpect(status().isOk());
}
@SneakyThrows
@Test
void getBookingByIdTest_whenBookingFound_thenReturnViewGetBookingById() {
Mockito
.when(bookingService.getById(anyLong(), anyLong()))
.thenReturn(bookingDtoFull);
mvc.perform(get("/bookings/1")
.characterEncoding(StandardCharsets.UTF_8)
.accept(MediaType.TEXT_HTML))
.andExpect(view().name("bookings/get-booking-by-id"))
.andExpect(model().attribute("booking", bookingDtoFull))
.andExpect(status().isOk());
}
@SneakyThrows
@Test
void approveBookingTest_whenBookingApprove_thenReturnViewGetBookingById() {
mvc.perform(patch("/bookings/1?approved=true")
.characterEncoding(StandardCharsets.UTF_8)
.accept(MediaType.TEXT_HTML))
.andExpect(view().name("redirect:/bookings/1"))
.andExpect(status().is(302));
}
@SneakyThrows
@Test
void getUserBookingsTest_whenBookingsFound_thenReturnViewGetBookingsUser() {
List<BookingDtoFull> bookings = List.of(bookingDtoFull);
Mockito
.when(bookingService.getUserBookings(anyLong(), anyString(), anyInt(), anyInt()))
.thenReturn(bookings);
mvc.perform(get("/bookings")
.characterEncoding(StandardCharsets.UTF_8)
.accept(MediaType.TEXT_HTML))
.andExpect(view().name("bookings/get-bookings-user"))
.andExpect(model().attribute("bookings", bookings))
.andExpect(status().isOk());
}
}
|
// Defining the package and all imports for the Lakewood Tennis Club Controller
package com.example.myapp.controller;
//Importing all the necessary classes and packages
import com.example.myapp.model.PadelPlusClub;
import com.example.myapp.repositories.PadelPlusClubRepository;
import com.example.myapp.services.PadelPlusClubService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.List;
// Defining the rest controller for handling all of the related Padel Plus Lakewood Tennis Club requests
@RestController
@RequestMapping("/api")
// Allowing cross-origin requests from all origins
@CrossOrigin(origins = "*")
public class PadelPlusClubController {
// Autowiring the Padel Plus Club Repository
@Autowired
private PadelPlusClubRepository padelPlusClubRepository;
// Autowiring the Padel Plus Club service
@Autowired
private PadelPlusClubService padelPlusClubService;
// Fetches Padel Plus Club courts by multiple search criterias
@GetMapping("/padelplusclub")
public List<PadelPlusClub> getPadelPlusCourtsBySurfaceAndHoursAndEnvironmentAndAvailability(
@RequestParam(value = "surface", required = true) String surface,
@RequestParam(value = "hours", required = true) String hours,
@RequestParam(value = "environment", required = true) String environment,
@RequestParam(value = "availability", required = true) String availability) {
// Checking to see if all search parameters are provided
if (!surface.isEmpty() && !hours.isEmpty() && !environment.isEmpty() && !availability.isEmpty()) {
// Fetch courts based on the provided criteria and availability
return padelPlusClubRepository.findBySurfaceAndHoursAndEnvironmentAndAvailability(
surface.toLowerCase(), hours, environment.toLowerCase(), availability);
} else {
// If any of the parameters are missing, it will return an empty list
return Collections.emptyList();
}
}
// Updates Padel Plus club slots
@CrossOrigin(origins = "*")
@PatchMapping("/padelplusclub/{id}")
public PadelPlusClub updatePadelplusClubSlots(
@PathVariable(value = "id") Integer ppcId,
@RequestParam(value = "fieldName", required = true) String fieldName,
@RequestParam(value = "value", required = true) Boolean value) {
PadelPlusClub ppc = padelPlusClubRepository.findById(ppcId)
.orElseThrow(IllegalArgumentException::new);
padelPlusClubService.updateField(ppcId, fieldName, value);
return ppc;
}
}
|
import { createClient } from '@supabase/supabase-js'
import { env } from 'bun'
const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_SERVICE_ROLE_KEY)
async function list_buckets() {
const { data, error } = await supabase.storage.listBuckets()
if (error) {
console.error('Error: listing storage_buckets', error.message)
return []
}
return data
}
async function empty_buckets(bucketIds: string[] = []) {
await Promise.all(
bucketIds.map(async (bucketId) => {
const { data, error } = await supabase.storage.emptyBucket(bucketId)
if (error) {
console.error('Error listing storage_files', error.message)
return
}
console.log('Bucket emptied', bucketId)
})
)
}
async function delete_buckets(bucketIds: string[] = []) {
await Promise.all(
bucketIds.map(async (bucketId) => {
const { error } = await supabase.storage.deleteBucket(bucketId)
if (error) {
console.error('Error deleting storage_buckets', error.message)
return
}
console.log('Bucket deleted', bucketId)
})
)
}
async function main() {
const buckets = await list_buckets()
const bucketIds = buckets.map((bucket) => bucket.id)
// TODO: next step: backup storage files
await empty_buckets(bucketIds)
await delete_buckets(bucketIds)
}
main().catch((e) => {
console.error(e)
process.exit(1)
})
|
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { UsersService } from '../users/users.service';
import { Computer, ComputerDocument } from './schemas/computer.schema';
import { CreateComputerDTO } from './dto/create-computer.dto';
import {
COMPUTER_NOT_FOUND,
getComputerCreatedMessage,
getComputerUpdatedMessage,
getComputerDeletedMessage,
} from './computer.constants';
import { ISuccessMessage } from '../../interfaces/successMessage.interface';
@Injectable()
export class ComputersService {
constructor(
@InjectModel(Computer.name) private computerModel: Model<ComputerDocument>,
private readonly userService: UsersService,
) {}
async getAllComputers(): Promise<ComputerDocument[]> {
const computers = await this.computerModel
.find()
.populate('lastModifier', 'username')
.exec();
return computers;
}
async createComputer(
createComputerDto: CreateComputerDTO,
username: string,
): Promise<ISuccessMessage> {
const computer = new this.computerModel(createComputerDto);
const modifier = await this.userService.getUserByUsername(username);
computer.lastModifier = modifier;
await computer.save();
return {
message: getComputerCreatedMessage(computer.pcName),
};
}
async updateComputer(
createComputerDto: CreateComputerDTO,
username: string,
id: string,
): Promise<ISuccessMessage> {
try {
const computer = await this.computerModel
.findByIdAndUpdate(id, createComputerDto, { new: true })
.exec();
const modifier = await this.userService.getUserByUsername(username);
computer.lastModifier = modifier;
await computer.save();
return { message: getComputerUpdatedMessage(computer.pcName) };
} catch (error) {
throw new NotFoundException(COMPUTER_NOT_FOUND);
}
}
async deleteComputer(id: string): Promise<ISuccessMessage> {
try {
const computer = await this.computerModel.findByIdAndRemove(id).exec();
return { message: getComputerDeletedMessage(computer.pcName) };
} catch (error) {
throw new NotFoundException(COMPUTER_NOT_FOUND);
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using VerifyCS = Roslintor.Test.CSharpAnalyzerVerifier<
Roslintor.Analyzers.ComplexityAnalyzers.Class.ClassCyclomaticComplexityAnalyzer>;
namespace Roslintor.Tests.ComplexityAnalyzerTests.Class
{
[TestClass]
public class ClassComplexityAnalyzerTests
{
[TestMethod]
public async Task ClassCyclomaticComplexityAnalysis_Should_ReturnClassCyclomaticComplexityLevelGood()
{
var test = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
public class TestClass
{
public void MethodName(string name)
{
var x = 1;
}
}
}";
await VerifyCS.VerifyAnalyzerAsync(test);
}
[TestMethod]
public async Task ClassCyclomaticComplexityAnalysis_Should_ReturnClassCyclomaticComplexityLevelTooHigh()
{
var test = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
public class {|#0:TestClass|}
{
public void MethodName(string name)
{
var x = 0;
var k = 1;
if (x > k)
{
while(x > 0)
{
x = 2;
}
}
if(k > x)
{
for(int i=0;i<x; i++)
{
k = 1;
}
}
if(k == x)
{
while (k < 0)
{
x++;
}
}
}
public void MethodName1(string name)
{
var x = 0;
var k = 2;
if (x > k)
{
while(x > 0)
{
x = 2;
}
}
if(k > x)
{
for(int i=0;i<x; i++)
{
k = 4;
}
}
if(k == x)
{
while (k < 0)
{
x++;
}
}
}
public void MethodName2(string name)
{
var x = 0;
var k = 33;
if (x > k)
{
while(x > 0)
{
x = 63;
}
}
if(k > x)
{
for(int i=0;i<x; i++)
{
k = 4;
}
}
if(k == x)
{
while (k < 0)
{
x++;
}
}
}
public void MethodName3(string name)
{
var x = 0;
var k = 223;
if (x > k)
{
while(x > 0)
{
x = 215;
}
}
if(k > x)
{
for(int i=0;i<x; i++)
{
k = 4;
}
}
if(k == x)
{
while (k < 0)
{
x++;
}
}
}
public void MethodName4(string name)
{
var x = 0;
var k = 334;
if (x > k)
{
while(x > 0)
{
x = 632;
}
}
if(k > x)
{
for(int i=0;i<x; i++)
{
k = 4;
}
}
if(k == x)
{
while (k < 0)
{
x++;
}
}
}
}
}";
var expected = VerifyCS.Diagnostic("CAR004").WithLocation(0).WithArguments("TestClass", "35");
await VerifyCS.VerifyAnalyzerAsync(test, expected);
}
}
}
|
\documentclass[expose, en]{thesis}
\thesissetup{%
name={Felix Möller}, %
id={2287872}, %
mail={utywh@student.kit.edu}, %
titlede={/}, %
titleen={Continual Active Learning for Effective Model Stealing Attacks}, %
thesis=BSc, %MSc
registration={January 6th, 2023}, %
submission={April 28th, 2023}, %
degree={Informatik}, %
supervisor={Jun.-Prof. Dr. Christian Wressnegger},
cosupervisor={Prof. Dr. Thorsten Strufe}
}
\usepackage{lipsum}
\usepackage{multicol}
\usepackage{multirow}
\usepackage{pgfgantt}
\usepackage{pifont}
\usepackage{tabularx}
\usepackage{tikz}
\usepackage{wasysym}
\usepackage{xcolor}
\begin{document}
\maketitle
\section{Introduction}
%Some intro to the topic: What is it about? What is the specific problem
%that should be addressed in this work?
Machine Learning, especially Deep Learning, is a resource-intensive task. Modern models can have millions of parameters
and require a lot of data to be trained. This makes model development difficult for small companies or individuals.
Big-tech companies like Google, Amazon and Microsoft however have access to a lot of computing power which they
now monetize by offering Machine-Learning as a Service (MLaaS). MLaaS-Plattforms allow users to train their models in the cloud
and query them for predictions. While MLaaS makes Machine Learning more accessible it also poses a security risk. Numerous works
have shown that it is possible to steal models from MLaaS-Plattforms by consecutively querying the target model, i.e. the model which
runs on the cloud and can be queried \cite{tramer2016stealing} \cite{reith2019efficiently}. The queries are then used to train a local model, also called the substitute model which is
intended to approximate the target model as good as possible.
The aim of this bachelor thesis is to further improve upon the Model Stealing process. Most recent works in the area of Model Stealing
have made use of Active Learning to improve the quality of the substitute model and ultimately reduce the number of queries needed to approximate
the target model sufficiently. However, in each iteration of the Active Learning process, an entirely new model has to be trained. This thesis aims to
combine Active Learning with Continual Learning to speed up the training process of the substitute model and make it approximate the target model
better.
\subsection{Motivation}
%What is the motivation for this work? Why should this topic be
%elaborated?
The main motivation for this work is that there are still opportunities to further improve the Model Stealing process.
Namely, Continual Learning has not been brought into the context of Model Stealing yet (to the best of our knowledge).
Continual Learning is different from traditional Machine Learning in that it aims to learn new tasks while retaining knowledge
of old tasks. That way, when the distribution of the data changes, the existing model can be adapted to the new distribution
instead of having to train a new model from scratch as it would be the case in traditional Machine Learning.
Given that Continual Learning has been shown to be effective in other domains, it is reasonable to assume that it can
lead to significant improvements in the Model Stealing process as well.
\subsection{Scope}
%Since you cannot solve all problems, what is the particular scope of
%your research? Which methods/approaches should be applied or
%implemented?
The particular scope of this thesis is to implement and evaluate a continual Active Learning approach for Model Stealing.
More concretely, the Active Learning strategies CoreSet \cite{sener2017active}, LC \cite{lewis1995sequential}, BALD \cite{gal2017deep}
and BADGE \cite{ash2019deep} should be implemented in combination
with the Continual Learning strategies MAS \cite{aljundi2018memory}, EWC \cite{kirkpatrick2017overcoming}, ALASSO \cite{park2019continual}
and IMM \cite{lee2017overcoming}. These combinations of Active Learning and Continual Learning should
then be transferred to the Model Stealing process and evaluated on the MNIST,CIFAR-10, CIFAR-100 and (optionally) ImageNet datasets.
The focus of the evaluation should be to test how well Deep Neural Networks for image classification can be extracted using
this continual Active Learning approach.
\section{Related Work}
The related work has to be divided into three parts: The first part is focused on Model Stealing,
the second part is focused on Active Learning and the third part is focused on Continual Learning.
\subsection{Model Stealing}
For the Model Stealing and the Active Learning part, \cite{chandrasekaran2020exploring} draws important
conclusions between Model Stealing and Active Learning. It therefore follows that the Active Learning
domain should be closely followed by researchers in the Model Stealing domain and vice versa because the
two domains are closely related. \cite{pal2020activethief} provide a more practical approach by developing
a model extraction framework for Deep Neural Networks based on Active Learning. Their framework which is called
ActiveThief is able to extract a model simply by providing an unlabeled thief dataset. The use of Active Learning to
select which points to label next showed to be effective because it significantly reduced the number of queries
needed to extract the model. Given that Model Stealing can have tremendous negative consequences, there has been research on
how to prevent it. One approach which is called Protecting against DNN Model Stealing Attacks (PRADA) \cite{juuti2019prada},
aims to detect Model Stealing attacks by observing the distribution of the queried data and raising an alarm when it deviates
significantly from the distribution that would be expected from a legitimate user. Rather than passively detecting Model Stealing
attacks, another approach named Prediction Poisoning \cite{orekondy2019prediction} actively adds noise to the model's predictions.
\subsection{Active Learning}
% Talk about CoreSet, LC, BALD and BADGE
For the Active Learning part we will focus on the Active Learning approaches that will be used in the evaluation. These are
CoreSet \cite{sener2017active}, LC \cite{lewis1995sequential}, Bayesian Active Learning by disagreement (BALD) \cite{gal2017deep}
and Batch Active Learning by Diverse Gradient Embeddings (BADGE) \cite{ash2019deep}. The CoreSet strategy \cite{sener2017active}
proposes that the model should be learned by the subset which will be able to classify the remaining points best. LC Active Learning \cite{lewis1995sequential}
iteratively labels the samples where the current model is most uncertain of the classes they belong to. The third strategy called BALD is a specific Bayesian
Active Learning strategy that makes use of Monte Carlo Dropout \cite{gal2016dropout} to approximate the uncertainty of the model. The final approach,
BADGE computes the gradient embedding of the current model's output layer and uses them to extend the labeled dataset.
\subsection{Continual Learning}
% Talk about MAS, EWC, ALASSO and IMM
As for the Active Learning part, we will focus on Related Work on the Continual Learning approaches that will be used in the evaluation.
These are Memory Aware Synapses (MAS) \cite{aljundi2018memory}, Elastic Weight Consolidation (EWC) \cite{kirkpatrick2017overcoming},
asymmetric loss approximation with single-side overestimation (ALASSO) \cite{park2019continual} and
Incremental Moment Matching (IMM) \cite{lee2017overcoming}. The first Continual Learning strategy, MAS \cite{aljundi2018memory}, continually computes the importance of
a neural network's parameter via the gradient of the learned function with respect to that parameter. When learning a new task, changes to the important parameters
of the network are penalized, which enables the learning of new tasks without forgetting previously learned ones. The second strategy, EWC \cite{kirkpatrick2017overcoming},
uses a similar approach, however the importance of the parameters is computed by the Fisher Information Matrix. The third approach, ALASSO \cite{park2019continual},
uses a loss function that overestimates the loss in areas where the true loss cannot be observed and behaves like a regular loss function in areas where it can.
The final approach, IMM \cite{lee2017overcoming}, uses Bayesian Neural Networks to match the moments of tasks' posterior distributions.
A more detailed overview, including even more Continual Learning approaches, can be found in \cite{mundt2020wholistic}. They provide a good summary of the existing
Continual Learning approaches and how they link together with Active Learning.
\section{Evaluation}
For the evaluation the datasets CIFAR-10, CIFAR-100, MNIST and optionally ImageNet will be used. The Active Learning strategies that will be used are
CoreSet \cite{sener2017active}, LC \cite{lewis1995sequential}, BALD \cite{gal2017deep} and BADGE. The Continual Learning strategies that will be used are MAS \cite{aljundi2018memory},
EWC \cite{kirkpatrick2017overcoming}, ALASSO \cite{park2019continual} and IMM \cite{lee2017overcoming}. The baseline of our evaluation will be the ActiveThief
framework proposed in \cite{pal2020activethief}. If there is enough time to do so, then we will also evaluate how our Continual Learning approach performs
when Model Stealing defense mechanisms like \cite{juuti2019prada} and \cite{orekondy2019prediction} are used.
\clearpage
\section{Schedule}
% THIS IS AN EXAMPLE, I.E. ADAPT THE TASKS TO YOUR NEEDS
\ifthenelse{\equal{\mythesistype}{BSc}}
{ % for BSc Thesis
\begin{figure}[h!]
\centering
\begin{ganttchart}[hgrid, vgrid,]{1}{16}
\gantttitle{Week}{16} \\
\gantttitlelist{1,...,16}{1} \\
\ganttbar{\nameref{sec:task1}}{1}{5} \\
\ganttbar{Implement Model Stealing workflow}{6}{7} \\
\ganttbar{Run experiments}{8}{10} \\
\ganttmilestone{Status Presentation}{8} \\
\ganttbar{Rehearsal + Representation-based AL}{10}{12} \\
\ganttbar{Write thesis}{13}{16} \\
\ganttmilestone{Submit first draft}{14} \\
\ganttbar{Print and Submit}{16}{16} \\
\ganttmilestone{Final Presentation}{16}
\end{ganttchart}
\caption{Schedule of the Bachelor's thesis}
\label{fig:timeschedule}
\end{figure}
}
{% for MSc Thesis
\begin{figure}[htbp]
\centering
\begin{ganttchart}[hgrid, vgrid,]{1}{24}
\gantttitle{Week}{24} \\
\gantttitlelist{1,...,24}{1} \\
\ganttbar{\nameref{sec:task1}}{1}{4} \\
\ganttbar{\nameref{sec:task2}}{5}{9} \\
\ganttmilestone{Status Presentation}{6} \\
\ganttbar{\nameref{sec:task3}}{7}{17} \\
\ganttbar{\nameref{sec:task4}}{18}{23} \\
\ganttbar{Print and Submission}{24}{24} \\
\ganttmilestone{Final Presentation}{24}
\end{ganttchart}
\caption{Schedule of the Master's thesis}
\label{fig:timeschedule}
\end{figure}
}
\subsection{Combine Active Learning with Continual Learning strategy}
\label{sec:milestone1}
The first large milestone is to combine Active Learning with Continual Learning. Currently, the
problem is that Active Learning strategies train a new model from scratch in each iteration. Given that these models
are often Deep Neural Networks, this is a time and resource consuming process. To solve this problem,
Continual Learning strategies should be used to train a single model which can be updated in each iteration
of the Active Learning process. Doing exactly this will be the goal of the first milestone.
\subsubsection{Implement AL + CL strategies}
\label{sec:task1}
The goal of this task is to implement the Active Learning strategies CoreSet \cite{sener2017active}, LC \cite{lewis1995sequential}, BALD \cite{gal2017deep}
and BADGE \cite{ash2019deep} as well as the Continual Learning strategies MAS \cite{aljundi2018memory},
EWC \cite{kirkpatrick2017overcoming}, ALASSO \cite{park2019continual} and IMM \cite{lee2017overcoming}. Since the chair's framework has already implemented
the four Active Learning strategies, we will only need to implement the Continual Learning strategies. For the
implementation of each method, one needs to check whether the papers which introduced the method provide an implementation. If they
do then it needs to be tested whether it works as intended. If it does not work as intended or no implementation
is provided, then the methods need to be implemented from scratch.
\paragraph{Must-haves:}
\begin{itemize}
\item Implement MAS Continual Learning strategy
\item Implement EWC Continual Learning strategy
\item Implement ALASSO Continual Learning strategy
\item Implement IMM Continual Learning strategy
\end{itemize}
\paragraph{Nice-to-haves:}
\begin{itemize}
\item Potentially implement more Active Learning and/or Continual Learning strategies
\end{itemize}
\subsection{Transfer Continual Active Learning to Model Stealing}
Transferring the Continual Active Learning approach to the Model Stealing domain will be the
second milestone. The goal of this step is to speed up the process of Model Stealing. This shall be achieved by updating
the current substitute model in each iteration of the Active Learning process instead of training a new model from scratch.
For this to work we need to integrate the Continual Active Learning strategies into the ActiveThief \cite{pal2020activethief} framework.
After the new Model Stealing workflow is implemented we can run experiments to determine how well our new approach
performs. To run the experiments, we will use the datasets CIFAR-10, CIFAR-100 and MNIST . If there is enough
time we will also run experiments on ImageNet and we will see how effective Model Stealing defense methods like
\cite{orekondy2019prediction} and \cite{juuti2019prada} are against our new approach. Another nice-to-have would be to
insert Exemplar Rehearsal \cite{gepperth2016bio} and Representation-based Active Learning \cite{ren2021survey} into the ActiveThief framework
and see how well they perform.
\subsubsection{Implement Model Stealing workflow and run experiments}
\label{sec:task2}
\paragraph{Must-haves:}
\begin{itemize}
\item Integrate the Continual Active Learning strategies into ActiveThief framework
\item Well-formatted output for Model Stealing workflow (like in training phase of Tensorflow models)
\item Run experiments on CIFAR-10 dataset
\item Run experiments on CIFAR-100 dataset
\item Run experiments on MNIST dataset
\end{itemize}
\paragraph{Nice-to-haves:}
\begin{itemize}
\item Run experiments on ImageNet dataset
\item Run experiments with Model Stealing defense mechanisms (PRADA \cite{juuti2019prada} and Prediction Poisoning \cite{orekondy2019prediction})
\item Insert Exemplar Rehearsal into Continual Learning framework
\item Insert Representation-based Active Learning into Active Learning framework
\item Run experiments with Exemplar Rehearsal Continual Learning and Representation-based Active Learning
\end{itemize}
\newpage
\bibliographystyle{plain}
\bibliography{expose}
\newpage
\section*{Implementation}
This document is the foundation for the implementation of the
\emph{\thesistype} and describes the contents and goals that must be fulfilled.
Please consider the general \emph{\thesistype} requirements of your examination
regulations. If you are in doubt please contact the
\href{https://www.informatik.kit.edu/sul.php}{examination office}.
\subsubsection*{Task Definition and Supervision}
\vspace*{5mm}
\begin{tabularx}{\textwidth}{@{}XX}
\mysupervisor & \rule[-0.5ex]{\linewidth}
{1pt}\newline\itshape(Date, Signature)\\[5ex]
\end{tabularx}
\vspace*{10mm}
\subsubsection*{Student}
\vspace*{5mm}
\begin{tabularx}{\textwidth}{@{}XX}
\myname & \rule[-0.5ex]{\linewidth}{1pt}\newline\itshape(Date, Signature)
\end{tabularx}
\end{document}
|
<?php
namespace App\Http\Middleware;
use Closure;
use Inertia\Inertia;
use Illuminate\Http\Request;
use App\Models\Establishment;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
class SetSessionData
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (Auth::user()) {
if (session()->get('auth.guest_mode') && !$request->cookie('guest_mode')) {
try {
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
} catch (\Throwable $th) {
}
return redirect('/login')->with('error', 'session expiré');
}
if (!session()->get('auth.role_name') || Auth::user()->id != (session()->get('auth')->id ?? false)) {
$auth = Auth::user();
$auth->role_id = $auth->roles()->first()->id;
$auth->role_name = $this->role($auth);
if ($request->cookie('guest_mode') !== null) {
$auth->guest_mode = json_decode($request->cookie('guest_mode'))->id;
}
session()->put('auth', $auth);
}
Inertia::share('auth_user', function () {
return session()->get('auth');
});
if (!session()->get('establishments_list')) {
session()->put('establishments_list', Establishment::all());
}
Inertia::share('max_session_for_renewal', 4);
Inertia::share('permissions', [
'edit_subscription' => auth()->user()->isAdmin(),
'comment_subscription' => auth()->user()->isAdmin(),
'create_subscription_fro_renewal' => auth()->user()->isAdmin(),
'edit_recuperation_request' => auth()->user()->isAdmin(),
]);
}
$route_name = Route::currentRouteName();
Inertia::share('current_route_name', $route_name);
Inertia::share('current_url', url()->current());
Inertia::share('req', request()->all());
if ($route_name == 'login') {
Inertia::share('page_title', 'Se connecter');
} else if ($route_name == 'signup') {
Inertia::share('page_title', "S'inscrire");
}
return $next($request);
}
private function role($user)
{
if ($user->isAdmin()) {
return "admin";
} elseif ($user->isProspect()) {
return "prospect";
} elseif ($user->isCustomer()) {
return "customer";
} elseif ($user->isCoach()) {
return "coach";
} elseif ($user->isAssistant()) {
return "assistant";
} elseif ($user->isIntervenant()) {
return "intervenant";
}
}
}
|
# Data-mining-in-IRIS-dataset
Clustering model was used in order to obtain best accuracy.
1. K-Means Clustering:-
The Κ-means clustering algorithm uses iterative refinement to produce a final result. The algorithm inputs are the number of clusters Κ and the data set. The data set is a collection of features for each data point. The algorithms starts with initial estimates for the Κ centroids, which can either be randomly generated or randomly selected from the data set.
• Specify the desired number of clusters K: Let us choose k=2 for these 5 data points in 2-D space.
• Randomly assign each data point to a cluster: Let’s assign three points in cluster 1 shown using red color and two points in cluster 2 shown using grey color.
• Compute cluster centroids: The centroids of data points in the red cluster is shown using red cross and those in grey cluster using grey cross.
• Re-assign each point to the closest cluster centroids: Note that only the data point at the bottom is assigned to the red cluster even though it’s closer to the centroids of grey cluster. Thus, we assign that data point into grey cluster.
• Re-compute cluster centroids: Now, re-computing the centroids for both the clusters.
• Repeat steps 4 and 5 until no improvements are possible: Similarly, we’ll repeat the 4th and 5th steps until we’ll reach global optima. When there will be no further switching of data points between two clusters for two successive repeats. It will mark the termination of the algorithm if not explicitly mentioned.
|
import 'package:get_storage/get_storage.dart';
class Prefs {
late GetStorage _storage;
final String _USER_TOKEN_KEY = "userTokenKey";
final String _ON_BOARD_SCREEN = "onBoard";
Prefs() {
_storage = GetStorage();
}
Future<void> setUserToken(String token) async {
return _storage.write(_USER_TOKEN_KEY, token);
}
Future<String> getUserToken() async {
return _storage.read<String>(_USER_TOKEN_KEY) ?? "";
}
Future<void> clearUser() async {
_storage.remove(_USER_TOKEN_KEY);
}
Future<void> setOnBoard(bool isShown) async {
return _storage.write(_ON_BOARD_SCREEN, isShown);
}
Future<bool> getOnBoard() async {
return _storage.read<bool>(_ON_BOARD_SCREEN) ?? false;
}
Future<void> clearOnBoard() async {
_storage.remove(_ON_BOARD_SCREEN);
}
}
|
import axios from "axios";
// Rappel pour l'installer -> npm i axios
export const getPokemonById = async (id) => {
// L'url a consomer
const url = `https://pokeapi.co/api/v2/pokemon-species/${id}`;
// Réaliser la requete avec Axios et renvoyé la promesse
return axios.get(url)
.then(({data}) => {
// Mapping vers un objet pour notre projet
return {
id: data.id,
name: {
en: data.names.find(val => val.language.name === 'en').name,
fr: data.names.find(val => val.language.name === 'fr').name
},
genus: data.genera.find(val => val.language.name === 'fr').genus,
isLegendary: data.is_legendary,
isBaby: data.is_baby
}
})
.catch(() => {
return null;
});
}
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="domain.*, java.util.List, persistence.*,java.util.Collections"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<script type="text/javascript">
// 1.모두 체크
function allChk(obj){
var chkObj = document.getElementsByName("RowCheck");
var rowCnt = chkObj.length - 1;
var check = obj.checked;
if (check) {
for (var i=0; i<=rowCnt; i++){
if(chkObj[i].type == "checkbox")
chkObj[i].checked = true;
}
} else {
for (var i=0; i<=rowCnt; i++) {
if(chkObj[i].type == "checkbox"){
chkObj[i].checked = false;
}
}
}
}
//2. 선택했는지 확인
function chk(){
var userid = "";
var memberChk = document.getElementsByName("RowCheck");
var chked = false;
var indexid = false;
for(i=0; i < memberChk.length; i++){
if(memberChk[i].checked){
if(indexid){
userid = userid + '-';
}
userid = userid + memberChk[i].value;
indexid = true;
}
}
if(!indexid){
alert("삭제할 리스트를 체크해 주세요");
return false;
}
}
</script>
<title>훈민점음</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/the-big-picture.css" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="fonts/material-icon/css/material-design-iconic-font.min.css">
</head>
<body>
<style>
h2{
font-family: "Nanum Gothic", sans-serif;
}
</style>
<!-- Navigation -->
<%
String sessionId = (String) session.getAttribute("sessionId");
%>
<nav style="background-color:#545b62!important" class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="./home.jsp"><img src="images/logo.png" width="150px" heigt="80px"></a><button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<c:choose>
<c:when test="${empty sessionId}">
<li class="nav-item">
<a style="color:white" class="nav-link" href="<c:url value="/loginform.jsp"/>"> 로그인</a>
</li>
</c:when>
<c:when test="${sessionId eq 'admin'}">
<li class="nav-item">
<a style="color:white" class="nav-link" href="<c:url value="/adminPage.jsp"/>">회원관리</a>
</li>
<li class="nav-item">
<a style="color:white" class="nav-link" href="MemberServlet?cmd=logout"target="_self">로그아웃</a>
</li>
</c:when>
<c:otherwise>
<li class="nav-item">
<a style="color:white" class="nav-link" href="MemberServlet?cmd=logout"target="_self">로그아웃</a>
</li>
<li class="nav-item">
<a style="color:white" class="nav-link" href="<c:url value ="/memberUpdate.jsp"/>">회원수정</a>
</li>
</c:otherwise>
</c:choose>
<li class="nav-item">
<a style="color:white" class="nav-link" href="<c:url value ="/introduction.jsp"/>">프로젝트 소개</a>
</li>
<li class="nav-item">
<a style="color:white" class="nav-link" href="<c:url value ="/service.jsp"/>">서비스</a>
</li>
<li class="nav-item">
<a style="color:white" class="nav-link" href="<c:url value ="/freeBoard.jsp"/>">커뮤니티</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- 내용 -->
<div class="container">
<div class="row">
<div class="col-lg-3 fixed">
<h2 class="my-4">서비스</h2>
<div class="list-group">
<a href="<c:url value ="/service.jsp"/>" class="list-group-item">변환</a>
<c:choose>
<c:when test="${empty sessionId}">
<a href="<c:url value ="/loginform.jsp"/>" class="list-group-item active">최근 목록 보기</a>
</c:when>
<c:otherwise>
<a href="<c:url value ="/recentList.jsp"/>" class="list-group-item active">최근 목록 보기</a>
</c:otherwise>
</c:choose>
</div>
</div>
<!-- Board-->
<div class="col-lg-9" style="margin-top:30px">
<form action="OcrServlet?cmd=ocr_delete" name= ocrForm method="post" onsubmit="return chk();">
<h2 class="text-black mt-0">최근 변환 목록</h2>
<table style="table-layout: fixed" class="table table-bordered">
<thead>
<tr>
<th width="30px"><input id="allCheck" style="display:inline" type="checkbox" onclick="allChk(this);"/></th>
<th width="200px">내용</th>
</tr>
</thead>
<tbody>
<%
OcrDAO dao = new OcrDAO();
List<OcrVO> ocrList = dao.getMemberList(sessionId);
for(OcrVO vo : ocrList){
%>
<tr>
<c:set var="data" value="<%=vo.getContent() %>" />
<c:if test="${not empty data}">
<td width="30px"><input style="display:inline" type="checkbox" name="RowCheck" value="<%=vo.getNum()%>"/></td>
<td onClick="location.href='OcrServlet?cmd=ocr&num=<%=vo.getNum()%>'" width="200px" style="text-overflow: ellipsis; overflow: hidden; white-space: nowrap"><nobr><c:out value="${data}" /></nobr></td>
</c:if>
</tr>
<%
}
%>
</tbody>
</table>
<hr>
<input type="submit" value="삭제" >
</form>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
|
import 'package:emindmatterssystemadminside/constant.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:emindmatterssystemadminside/manageInfo/data%20model/HelpCrisisModel.dart';
import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher.dart';
import '../edit/EditHelpCrisisForm.dart';
class DisplayHelpCrisisInfoForm extends StatefulWidget {
@override
_DisplayHelpCrisisInfoFormState createState() => _DisplayHelpCrisisInfoFormState();
}
class _DisplayHelpCrisisInfoFormState extends State<DisplayHelpCrisisInfoForm> {
final FirebaseFirestore _db = FirebaseFirestore.instance;
List<String> _selectedCrisisIds = [];
bool _isAllSelected = false;
List<String> _allCrisisIds = [];
int _rowCounter = 0;
// Declare the search controller
final TextEditingController _searchController = TextEditingController();
// Declare the search query variable
String _searchQuery = '';
@override
void initState() {
super.initState();
_db.collection('helpCrisis').snapshots().listen((QuerySnapshot snapshot) {
setState(() {
_allCrisisIds = snapshot.docs.map((doc) => doc.id).toList();
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: pShadeColor1,
automaticallyImplyLeading: false,
title: Row(
children: [
Expanded(
child: TextField(
controller: _searchController,
decoration: InputDecoration(
hintText: 'Search by name or author',
suffixIcon: Row(
mainAxisSize: MainAxisSize.min, // Added to keep icons together
children: [
IconButton(
icon: Icon(Icons.search),
onPressed: () {
setState(() {
_searchQuery = _searchController.text.toLowerCase();
});
},
),
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
setState(() {
_searchController.clear();
_searchQuery = '';
});
},
),
],
),
),
),
),
],
),
actions: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Checkbox(
value: _isAllSelected,
onChanged: (bool? value) {
setState(() {
_isAllSelected = value!;
_selectedCrisisIds.clear();
if (_isAllSelected) {
_selectedCrisisIds.addAll(_allCrisisIds);
}
});
},
),
Text('Select All'),
SizedBox(width: 20.0),
],
),
IconButton(
icon: Icon(Icons.delete, color: Colors.red,),
onPressed: _selectedCrisisIds.isEmpty
? null
: () => _deleteSelectedCrisis(),
),
Text('Delete'),
SizedBox(width: 20.0),
IconButton(
icon: Icon(Icons.edit, color: pShadeColor9,),
onPressed: _selectedCrisisIds.length == 1 // Allow edit only when one crisis is selected
? () => _editSelectedCrisis()
: null,
),
Text('Edit'),
SizedBox(width: 30.0),
],
),
],
),
body: SingleChildScrollView(
child: Container(
width: MediaQuery.of(context).size.width * 1.0, // Adjust width as needed
child: StreamBuilder(
stream: _searchQuery.isEmpty
? _db.collection('helpCrisis').snapshots()
: _db.collection('helpCrisis').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center( // Center widget added for better positioning
child: CircularProgressIndicator(),
);
}
_rowCounter = 0;
return DataTable(
columnSpacing: 20.0, // Added spacing between columns
dataRowMinHeight: 200.0, // Set a minimum height for each row
dataRowMaxHeight: 200.0, // Set a maximum height for each row
columns: [
DataColumn(label: Text('Number', style: TextStyle(fontWeight: FontWeight.bold)),), // Added for row numbers
DataColumn(label: Text('Name', style: TextStyle(fontWeight: FontWeight.bold)),),
DataColumn(label: Text('Description', style: TextStyle(fontWeight: FontWeight.bold)),),
DataColumn(label: Text('Phone No', style: TextStyle(fontWeight: FontWeight.bold)),),
DataColumn(label: Text('Address', style: TextStyle(fontWeight: FontWeight.bold)),),
DataColumn(label: Text('Website Link', style: TextStyle(fontWeight: FontWeight.bold))),
DataColumn(label: Text('Author', style: TextStyle(fontWeight: FontWeight.bold)),),
DataColumn(
label: SizedBox(
width: 120, // Set a fixed width
child: Text('Date Created', style: TextStyle(fontWeight: FontWeight.bold))
)
),
DataColumn(label: Text('Select', style: TextStyle(fontWeight: FontWeight.bold)),), // Added a DataColumn for Select
],
rows: snapshot.data!.docs.map((QueryDocumentSnapshot document) {
_rowCounter++;
HelpCrisisModel crisis = HelpCrisisModel.fromMap(document.data() as Map<String, dynamic>, document.id);
// Enhanced Search Logic
bool isMatch = _searchQuery.split(' ').any((word) =>
crisis.name.toLowerCase().contains(word) ||
(crisis.author?.toLowerCase().contains(word) ?? false)
);
if (isMatch) {
final isSelected = _selectedCrisisIds.contains(crisis
.crisisId);
return DataRow(
cells: [
DataCell(Text(_rowCounter.toString()),),
DataCell(Text(crisis.name,)),
DataCell(
Container(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Text(
crisis.description ?? 'N/A',
),
),
),
),
),
DataCell(Text(crisis.phoneNo ?? 'N/A')),
DataCell(
Container(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Text(
crisis.address ?? 'N/A',
),
),
),
),
),
DataCell(
GestureDetector(
onTap: () => _launchURL(crisis.websiteLink),
child: Text(
crisis.websiteLink ?? 'N/A',
style: TextStyle(
color: Colors.blue,
decoration: TextDecoration.underline,
),
),
),
),
DataCell(Text(crisis.author ?? 'N/A')),
DataCell(Text(DateFormat('dd/MM/yyyy').format(
crisis.dateCreated),)),
DataCell(
Checkbox(
value: isSelected,
onChanged: (bool? value) {
setState(() {
if (value == true) {
_selectedCrisisIds.add(crisis.crisisId);
} else {
_selectedCrisisIds.remove(crisis.crisisId);
}
});
},
),
),
],
color: MaterialStateColor.resolveWith((states) {
final int index = snapshot.data!.docs.indexOf(document);
return index % 2 == 0 ? Colors.white : Colors.grey
.shade200;
}),
);
} else {
return null;
}
}).where((element) => element != null).cast<DataRow>().toList(),
);
},
),
),
),
);
}
Future<void> _loadCrisisData() async {
try {
QuerySnapshot snapshot = await _db.collection('helpCrisis').get();
setState(() {
_allCrisisIds = snapshot.docs.map((doc) => doc.id).toList();
});
} catch (e) {
print('Error loading crisis data: $e');
}
}
Future<void> _deleteSelectedCrisis() async {
try {
await Future.forEach(_selectedCrisisIds, (String crisisId) async {
await _db.collection('helpCrisis').doc(crisisId).delete();
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Selected crisis deleted successfully!')),
);
setState(() {
_selectedCrisisIds.clear();
_isAllSelected = false;
});
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to delete crisis: $e')),
);
}
}
void _editSelectedCrisis() async {
if (_selectedCrisisIds.length == 1) {
String selectedCrisisId = _selectedCrisisIds.first;
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditHelpCrisisForm(crisisId: selectedCrisisId),
),
);
if (result == true) { // If the data was updated
_loadCrisisData(); // Reload the data
}
}
}
void _launchURL(String? url) async {
if (url != null) {
final Uri uri = Uri.parse(url);
if (await canLaunchUrl(uri)) {
await launchUrl(uri);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to launch the website')),
);
}
}
}
}
|
package service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
import utility.Database;
import model.Contact;
public class ContactDaoImpl implements Contactdao{
private static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
private static final String QUERY_ALL = "SELECT * FROM contact";
private static final String QUERY_BY_ID = "SELECT * FROM contact WHERE id = ?";
private static final String QUERY_SAVE = "INSERT INTO contact(first_name, last_name, mobile_number, email_address, address) VALUES(?, ?, ?, ?, ?)";
private static final String QUERY_UPDATE = "UPDATE contact SET first_name = ?, last_name = ?, mobile_number = ?, email_address = ?, address = ? WHERE id = ?";
private static final String QUERY_DELETE_BY_ID = "DELETE FROM contact WHERE id = ?";
@Override
public List<Contact> findAll() {
List<Contact> contacts = new ArrayList<>();
try (Connection connection = Database.getDBConnection();
PreparedStatement statement = connection.prepareStatement(QUERY_ALL);
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
Contact contact = new Contact();
contact.setId(resultSet.getInt("id"));
contact.setContactName(resultSet.getString("contact_name"));
contact.setContactImage(resultSet.getString("contactImage"));
contact.setcontactNumber(resultSet.getString("address"));
contacts.add(contact);
}
} catch (Exception exception) {
LOGGER.severe(exception.getMessage());
}
return contacts;
}
@Override
public Optional<Contact> findById(long id) {
ResultSet resultSet = null;
try (Connection connection = Database.getDBConnection();
PreparedStatement statement = connection.prepareStatement(QUERY_BY_ID);) {
statement.setLong(1, id);
resultSet = statement.executeQuery();
while (resultSet.next()) {
Contact contact = new Contact();
contact.setId(resultSet.getInt("id"));
contact.setContactName(resultSet.getString("contact_name"));
contact.setContactImage(resultSet.getString("contactImage"));
contact.setcontactNumber(resultSet.getString("address"));
return Optional.ofNullable(contact);
}
} catch (Exception exception) {
LOGGER.severe(exception.getMessage());
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException sqlException) {
LOGGER.severe(sqlException.getMessage());
}
}
}
return Optional.empty();
}
@Override
public void addContact(Contact contact) {
try (Connection connection = Database.getDBConnection();
PreparedStatement statement = connection.prepareStatement(QUERY_SAVE);) {
int counter = 1;
statement.setString(counter++, contact.getContactName());
statement.setString(counter++, contact.getContactNumber());
statement.setString(counter++, contact.getContactImage());
statement.executeUpdate();
} catch (SQLException sqlException) {
LOGGER.severe(sqlException.getMessage());
}
}
@Override
public void viewContact(Contact contact) {
try (Connection connection = Database.getDBConnection();
PreparedStatement statement = connection.prepareStatement(QUERY_SAVE);) {
int counter = 1;
statement.setString(counter++, contact.getContactName());
statement.setString(counter++, contact.getContactNumber());
statement.setString(counter++, contact.getContactImage());
statement.executeUpdate();
} catch (SQLException sqlException) {
LOGGER.severe(sqlException.getMessage());
}
}
@Override
public void updateContact(Contact contact) {
try (Connection connection = Database.getDBConnection();
PreparedStatement statement = connection.prepareStatement(QUERY_UPDATE);) {
int counter = 1;
statement.setString(counter++, contact.getContactName());
statement.setString(counter++, contact.getContactNumber());
statement.setString(counter++, contact.getContactImage());
statement.setLong(counter++, contact.getId());
statement.executeUpdate();
} catch (SQLException sqlException) {
LOGGER.severe(sqlException.getMessage());
}
}
@Override
public void deleteContact(long id) {
try (Connection connection = Database.getDBConnection();
PreparedStatement statement = connection.prepareStatement(QUERY_DELETE_BY_ID);) {
int counter = 1;
statement.setLong(counter++, id);
statement.executeUpdate();
} catch (SQLException sqlException) {
LOGGER.severe(sqlException.getMessage());
}
}
}
|
'use client';
import Image from 'next/image';
import React, { useState, useEffect } from 'react';
import { deleteStudent, editStudent, fetchStudents } from './action';
import DeleteComponent from './DeleteComponent';
import EditComponent from './EditComponent';
import TeacherList from './TeacherList';
import Unauthorised from '@/components/Unauthorised';
import { StudentType } from '@/lib/types/types';
import { useSession } from 'next-auth/react';
import LoadingPage from '../loading';
const AllStudentsPage = () => {
const { data: session } = useSession();
const [students, setStudents] = useState<StudentType[]>([]);
const [searchQuery, setSearchQuery] = useState('');
const [filteredStudents, setFilteredStudents] = useState([] as StudentType[]);
const [loading, setLoading] = useState(true);
const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
setSearchQuery(event.target.value);
};
useEffect(() => {
setLoading(true);
fetchStudents().then((fetchedStudents) => {
setStudents(fetchedStudents);
setLoading(false);
});
}, []);
useEffect(() => {
const search = searchQuery.toLowerCase().trim();
const filtered = students.filter((student) => {
const fullName = `${student.firstName} ${student.lastName}`.toLowerCase();
return fullName.includes(search) || student.currentClass.toLowerCase().includes(search);
});
setFilteredStudents(filtered);
}, [searchQuery, students]);
if (session && session.user.role !== 'adminRole') {
return <Unauthorised />;
}
const updateScreen = (studentId: string) => {
setStudents((prev) => prev.filter((student) => student.studentId !== studentId));
};
return (
<div className="overflow-x-auto flex flex-col justify-center items-center">
<div className=" flex flex-col gap-4 sm:flex-row mt-2">
<TeacherList />
<input
type="text"
placeholder="Search by name or class"
value={searchQuery}
onChange={handleSearch}
className="border border-gray-300 rounded-md p-2"
/>
</div>
{loading ? (
<>
<div className="font-bold text-lg text-center mt-5">Loading Students ...</div>
<LoadingPage />
</>
) : filteredStudents.length > 0 ? (
<table className="table max-w-[600px] mt-5">
<thead>
<tr>
<th>
<label>
<input type="checkbox" className="checkbox" />
</label>
</th>
<th className="text-center">Picture and Name</th>
<th>Date Registered</th>
<th className="text-center">Action</th>
</tr>
</thead>
<tbody>
{filteredStudents.map((student) => (
<tr key={student.studentId} className="hover">
<th>
<label>
<input type="checkbox" className="checkbox" />
</label>
</th>
<td>
<div className="flex items-center space-x-3">
<div className="avatar">
<div className="mask mask-squircle w-12 h-12">
<Image
src={student.profilePhotoUrl || ''}
width={40}
height={40}
alt={student.firstName}
/>
</div>
</div>
<div>
<div className="font-bold">{`${student.firstName[0]
.toUpperCase()
.concat(student.firstName.slice(1))} ${student.lastName[0]
.toUpperCase()
.concat(student.lastName.slice(1))}`}</div>
<div className="text-sm opacity-50">{student.gender}</div>
</div>
</div>
</td>
<td>
{student.currentClass}
<br />
<span className="badge badge-ghost badge-sm">
{student.createdAt.toLocaleString()}
</span>
</td>
<td className="flex items-center justify-center gap-2">
<EditComponent id={student.studentId} editStudent={editStudent} />
<DeleteComponent
studentId={student.studentId}
deleteStudent={deleteStudent}
profilePhotoUrl={student.profilePhotoUrl || ''}
updateScreen={updateScreen}
/>
</td>
</tr>
))}
</tbody>
</table>
) : (
<div className="font-bold text-lg text-center mt-5">No Student Found</div>
)}
</div>
);
};
export default AllStudentsPage;
|
//package algosecon;
//
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//
//public class SimpleTree<T> {
// public SimpleTreeNode<T> Root; // корень, может быть null
// public int count = 0;
//
// public SimpleTree(SimpleTreeNode<T> root) {
// Root = root;
// }
//
// public void AddChild(SimpleTreeNode<T> ParentNode, SimpleTreeNode<T> NewChild) {
// if (ParentNode.Children != null) {
// ParentNode.Children.add(NewChild);
// } else {
// List<SimpleTreeNode<T>> children = new ArrayList<>();
// children.add(NewChild);
// ParentNode.Children = children;
// }
//
// NewChild.Parent = ParentNode;
// // ваш код добавления нового дочернего узла существующему ParentNode
// }
//
// public void DeleteNode(SimpleTreeNode<T> NodeToDelete) {
// NodeToDelete.Parent.Children.remove(NodeToDelete);
// if (NodeToDelete.Parent.Children.isEmpty())
// NodeToDelete.Parent.Children = null;
// NodeToDelete.Parent = null;
// NodeToDelete.Children = null;
// // ваш код удаления существующего узла NodeToDelete
// }
//
// public List<SimpleTreeNode<T>> GetAllNodes() {
// List<SimpleTreeNode<T>> result = new ArrayList<>();
// result.add(this.Root);
// // ваш код выдачи всех узлов дерева в определённом порядке
// return getAllNodes(result, this.Root);
// }
//
// public List<SimpleTreeNode<T>> FindNodesByValue(T val) {
// List<SimpleTreeNode<T>> result = new ArrayList<>();
// if (this.Root.NodeValue == val)
// result.add(Root);
// if (Root.Children != null)
// getNodeByValue(Root.Children, val, result);
// // ваш код поиска узлов по значению
// return result.isEmpty() ? null : result;
// }
//
// public void MoveNode(SimpleTreeNode<T> OriginalNode, SimpleTreeNode<T> NewParent) {
// if (!this.Root.equals(OriginalNode)) {
// OriginalNode.Parent.Children.remove(OriginalNode);
// NewParent.Children.add(OriginalNode);
// OriginalNode.Parent = NewParent;
// }
// // ваш код перемещения узла вместе с его поддеревом --
// // в качестве дочернего для узла NewParent
// }
//
// public int Count() {
// if (this.Root.Children == null)
// return 1;
// return getNodeCount(Root, 1);
// }
//
// public int LeafCount() {
// if (this.Root.Children == null)
// return 1;
// return getLeafCount(this.Root, 0);
// }
//
// public ArrayList<T> EvenTrees() {
// ArrayList<T> res = new ArrayList<>();
// Map<SimpleTreeNode<T>, Boolean> visit = new HashMap<>();
// int allNodes = this.Count();
// dfs(visit, Root, res, allNodes);
//
// return res;
// }
//
// private void dfs(Map<SimpleTreeNode<T>, Boolean> visit, SimpleTreeNode<T> node, ArrayList<T> res, int allNodesCount) {
// visit.put(node, true);
//// int currComponentNode = 0;
// // iterate over all neighbor of node u
// if (node.Children != null && !node.Children.isEmpty()) {
// for (SimpleTreeNode<T> child : node.Children) {
// if (!visit.containsKey(child)) {
// int nodesCountFromCurrNode = getNodeCount(child, 1);
// if ((allNodesCount - nodesCountFromCurrNode) % 2 == 0 && nodesCountFromCurrNode % 2 == 0) {
// res.add(node.NodeValue);
// res.add(child.NodeValue);
// }
// dfs(visit, child, res, allNodesCount);
// }
// }
// }
// }
//
// private void getNodeByValue(List<SimpleTreeNode<T>> children, T value, List<SimpleTreeNode<T>> result) {
// for (SimpleTreeNode<T> node : children) {
// if (node.NodeValue == value)
// result.add(node);
// if (node.Children != null)
// getNodeByValue(node.Children, value, result);
// }
// }
//
// private List<SimpleTreeNode<T>> getAllNodes(List<SimpleTreeNode<T>> result, SimpleTreeNode<T> root) {
// if (root.Children != null) {
// result.addAll(root.Children);
// for (SimpleTreeNode<T> node : root.Children) {
// getAllNodes(result, node);
// }
// }
// return result;
// }
//
// private int getLeafCount(SimpleTreeNode<T> root, Integer count) {
// if (root.Children == null)
// return count + 1;
//
// for (SimpleTreeNode<T> node : root.Children) {
// count = getLeafCount(node, count);
// }
//
// return count;
// }
//
// private int getNodeCount(SimpleTreeNode<T> root, int count) {
// if (root.Children != null) {
// count += root.Children.size();
// for (SimpleTreeNode<T> node : root.Children) {
// count += getNodeCount(node, 0);
// }
// }
// return count;
// }
//}
|
package com.wa.apiaccount.core.model.domain;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class AcctMktRecExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public AcctMktRecExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Long value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Long> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Long> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andRequestIdIsNull() {
addCriterion("request_id is null");
return (Criteria) this;
}
public Criteria andRequestIdIsNotNull() {
addCriterion("request_id is not null");
return (Criteria) this;
}
public Criteria andRequestIdEqualTo(String value) {
addCriterion("request_id =", value, "requestId");
return (Criteria) this;
}
public Criteria andRequestIdNotEqualTo(String value) {
addCriterion("request_id <>", value, "requestId");
return (Criteria) this;
}
public Criteria andRequestIdGreaterThan(String value) {
addCriterion("request_id >", value, "requestId");
return (Criteria) this;
}
public Criteria andRequestIdGreaterThanOrEqualTo(String value) {
addCriterion("request_id >=", value, "requestId");
return (Criteria) this;
}
public Criteria andRequestIdLessThan(String value) {
addCriterion("request_id <", value, "requestId");
return (Criteria) this;
}
public Criteria andRequestIdLessThanOrEqualTo(String value) {
addCriterion("request_id <=", value, "requestId");
return (Criteria) this;
}
public Criteria andRequestIdLike(String value) {
addCriterion("request_id like", value, "requestId");
return (Criteria) this;
}
public Criteria andRequestIdNotLike(String value) {
addCriterion("request_id not like", value, "requestId");
return (Criteria) this;
}
public Criteria andRequestIdIn(List<String> values) {
addCriterion("request_id in", values, "requestId");
return (Criteria) this;
}
public Criteria andRequestIdNotIn(List<String> values) {
addCriterion("request_id not in", values, "requestId");
return (Criteria) this;
}
public Criteria andRequestIdBetween(String value1, String value2) {
addCriterion("request_id between", value1, value2, "requestId");
return (Criteria) this;
}
public Criteria andRequestIdNotBetween(String value1, String value2) {
addCriterion("request_id not between", value1, value2, "requestId");
return (Criteria) this;
}
public Criteria andFlowIdIsNull() {
addCriterion("flow_id is null");
return (Criteria) this;
}
public Criteria andFlowIdIsNotNull() {
addCriterion("flow_id is not null");
return (Criteria) this;
}
public Criteria andFlowIdEqualTo(String value) {
addCriterion("flow_id =", value, "flowId");
return (Criteria) this;
}
public Criteria andFlowIdNotEqualTo(String value) {
addCriterion("flow_id <>", value, "flowId");
return (Criteria) this;
}
public Criteria andFlowIdGreaterThan(String value) {
addCriterion("flow_id >", value, "flowId");
return (Criteria) this;
}
public Criteria andFlowIdGreaterThanOrEqualTo(String value) {
addCriterion("flow_id >=", value, "flowId");
return (Criteria) this;
}
public Criteria andFlowIdLessThan(String value) {
addCriterion("flow_id <", value, "flowId");
return (Criteria) this;
}
public Criteria andFlowIdLessThanOrEqualTo(String value) {
addCriterion("flow_id <=", value, "flowId");
return (Criteria) this;
}
public Criteria andFlowIdLike(String value) {
addCriterion("flow_id like", value, "flowId");
return (Criteria) this;
}
public Criteria andFlowIdNotLike(String value) {
addCriterion("flow_id not like", value, "flowId");
return (Criteria) this;
}
public Criteria andFlowIdIn(List<String> values) {
addCriterion("flow_id in", values, "flowId");
return (Criteria) this;
}
public Criteria andFlowIdNotIn(List<String> values) {
addCriterion("flow_id not in", values, "flowId");
return (Criteria) this;
}
public Criteria andFlowIdBetween(String value1, String value2) {
addCriterion("flow_id between", value1, value2, "flowId");
return (Criteria) this;
}
public Criteria andFlowIdNotBetween(String value1, String value2) {
addCriterion("flow_id not between", value1, value2, "flowId");
return (Criteria) this;
}
public Criteria andUserNoIsNull() {
addCriterion("user_no is null");
return (Criteria) this;
}
public Criteria andUserNoIsNotNull() {
addCriterion("user_no is not null");
return (Criteria) this;
}
public Criteria andUserNoEqualTo(String value) {
addCriterion("user_no =", value, "userNo");
return (Criteria) this;
}
public Criteria andUserNoNotEqualTo(String value) {
addCriterion("user_no <>", value, "userNo");
return (Criteria) this;
}
public Criteria andUserNoGreaterThan(String value) {
addCriterion("user_no >", value, "userNo");
return (Criteria) this;
}
public Criteria andUserNoGreaterThanOrEqualTo(String value) {
addCriterion("user_no >=", value, "userNo");
return (Criteria) this;
}
public Criteria andUserNoLessThan(String value) {
addCriterion("user_no <", value, "userNo");
return (Criteria) this;
}
public Criteria andUserNoLessThanOrEqualTo(String value) {
addCriterion("user_no <=", value, "userNo");
return (Criteria) this;
}
public Criteria andUserNoLike(String value) {
addCriterion("user_no like", value, "userNo");
return (Criteria) this;
}
public Criteria andUserNoNotLike(String value) {
addCriterion("user_no not like", value, "userNo");
return (Criteria) this;
}
public Criteria andUserNoIn(List<String> values) {
addCriterion("user_no in", values, "userNo");
return (Criteria) this;
}
public Criteria andUserNoNotIn(List<String> values) {
addCriterion("user_no not in", values, "userNo");
return (Criteria) this;
}
public Criteria andUserNoBetween(String value1, String value2) {
addCriterion("user_no between", value1, value2, "userNo");
return (Criteria) this;
}
public Criteria andUserNoNotBetween(String value1, String value2) {
addCriterion("user_no not between", value1, value2, "userNo");
return (Criteria) this;
}
public Criteria andSlotSeqIsNull() {
addCriterion("slot_seq is null");
return (Criteria) this;
}
public Criteria andSlotSeqIsNotNull() {
addCriterion("slot_seq is not null");
return (Criteria) this;
}
public Criteria andSlotSeqEqualTo(Integer value) {
addCriterion("slot_seq =", value, "slotSeq");
return (Criteria) this;
}
public Criteria andSlotSeqNotEqualTo(Integer value) {
addCriterion("slot_seq <>", value, "slotSeq");
return (Criteria) this;
}
public Criteria andSlotSeqGreaterThan(Integer value) {
addCriterion("slot_seq >", value, "slotSeq");
return (Criteria) this;
}
public Criteria andSlotSeqGreaterThanOrEqualTo(Integer value) {
addCriterion("slot_seq >=", value, "slotSeq");
return (Criteria) this;
}
public Criteria andSlotSeqLessThan(Integer value) {
addCriterion("slot_seq <", value, "slotSeq");
return (Criteria) this;
}
public Criteria andSlotSeqLessThanOrEqualTo(Integer value) {
addCriterion("slot_seq <=", value, "slotSeq");
return (Criteria) this;
}
public Criteria andSlotSeqIn(List<Integer> values) {
addCriterion("slot_seq in", values, "slotSeq");
return (Criteria) this;
}
public Criteria andSlotSeqNotIn(List<Integer> values) {
addCriterion("slot_seq not in", values, "slotSeq");
return (Criteria) this;
}
public Criteria andSlotSeqBetween(Integer value1, Integer value2) {
addCriterion("slot_seq between", value1, value2, "slotSeq");
return (Criteria) this;
}
public Criteria andSlotSeqNotBetween(Integer value1, Integer value2) {
addCriterion("slot_seq not between", value1, value2, "slotSeq");
return (Criteria) this;
}
public Criteria andTranSeqIsNull() {
addCriterion("tran_seq is null");
return (Criteria) this;
}
public Criteria andTranSeqIsNotNull() {
addCriterion("tran_seq is not null");
return (Criteria) this;
}
public Criteria andTranSeqEqualTo(Integer value) {
addCriterion("tran_seq =", value, "tranSeq");
return (Criteria) this;
}
public Criteria andTranSeqNotEqualTo(Integer value) {
addCriterion("tran_seq <>", value, "tranSeq");
return (Criteria) this;
}
public Criteria andTranSeqGreaterThan(Integer value) {
addCriterion("tran_seq >", value, "tranSeq");
return (Criteria) this;
}
public Criteria andTranSeqGreaterThanOrEqualTo(Integer value) {
addCriterion("tran_seq >=", value, "tranSeq");
return (Criteria) this;
}
public Criteria andTranSeqLessThan(Integer value) {
addCriterion("tran_seq <", value, "tranSeq");
return (Criteria) this;
}
public Criteria andTranSeqLessThanOrEqualTo(Integer value) {
addCriterion("tran_seq <=", value, "tranSeq");
return (Criteria) this;
}
public Criteria andTranSeqIn(List<Integer> values) {
addCriterion("tran_seq in", values, "tranSeq");
return (Criteria) this;
}
public Criteria andTranSeqNotIn(List<Integer> values) {
addCriterion("tran_seq not in", values, "tranSeq");
return (Criteria) this;
}
public Criteria andTranSeqBetween(Integer value1, Integer value2) {
addCriterion("tran_seq between", value1, value2, "tranSeq");
return (Criteria) this;
}
public Criteria andTranSeqNotBetween(Integer value1, Integer value2) {
addCriterion("tran_seq not between", value1, value2, "tranSeq");
return (Criteria) this;
}
public Criteria andAmtIsNull() {
addCriterion("amt is null");
return (Criteria) this;
}
public Criteria andAmtIsNotNull() {
addCriterion("amt is not null");
return (Criteria) this;
}
public Criteria andAmtEqualTo(BigDecimal value) {
addCriterion("amt =", value, "amt");
return (Criteria) this;
}
public Criteria andAmtNotEqualTo(BigDecimal value) {
addCriterion("amt <>", value, "amt");
return (Criteria) this;
}
public Criteria andAmtGreaterThan(BigDecimal value) {
addCriterion("amt >", value, "amt");
return (Criteria) this;
}
public Criteria andAmtGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("amt >=", value, "amt");
return (Criteria) this;
}
public Criteria andAmtLessThan(BigDecimal value) {
addCriterion("amt <", value, "amt");
return (Criteria) this;
}
public Criteria andAmtLessThanOrEqualTo(BigDecimal value) {
addCriterion("amt <=", value, "amt");
return (Criteria) this;
}
public Criteria andAmtIn(List<BigDecimal> values) {
addCriterion("amt in", values, "amt");
return (Criteria) this;
}
public Criteria andAmtNotIn(List<BigDecimal> values) {
addCriterion("amt not in", values, "amt");
return (Criteria) this;
}
public Criteria andAmtBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("amt between", value1, value2, "amt");
return (Criteria) this;
}
public Criteria andAmtNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("amt not between", value1, value2, "amt");
return (Criteria) this;
}
public Criteria andInsertTimeIsNull() {
addCriterion("insert_time is null");
return (Criteria) this;
}
public Criteria andInsertTimeIsNotNull() {
addCriterion("insert_time is not null");
return (Criteria) this;
}
public Criteria andInsertTimeEqualTo(Date value) {
addCriterion("insert_time =", value, "insertTime");
return (Criteria) this;
}
public Criteria andInsertTimeNotEqualTo(Date value) {
addCriterion("insert_time <>", value, "insertTime");
return (Criteria) this;
}
public Criteria andInsertTimeGreaterThan(Date value) {
addCriterion("insert_time >", value, "insertTime");
return (Criteria) this;
}
public Criteria andInsertTimeGreaterThanOrEqualTo(Date value) {
addCriterion("insert_time >=", value, "insertTime");
return (Criteria) this;
}
public Criteria andInsertTimeLessThan(Date value) {
addCriterion("insert_time <", value, "insertTime");
return (Criteria) this;
}
public Criteria andInsertTimeLessThanOrEqualTo(Date value) {
addCriterion("insert_time <=", value, "insertTime");
return (Criteria) this;
}
public Criteria andInsertTimeIn(List<Date> values) {
addCriterion("insert_time in", values, "insertTime");
return (Criteria) this;
}
public Criteria andInsertTimeNotIn(List<Date> values) {
addCriterion("insert_time not in", values, "insertTime");
return (Criteria) this;
}
public Criteria andInsertTimeBetween(Date value1, Date value2) {
addCriterion("insert_time between", value1, value2, "insertTime");
return (Criteria) this;
}
public Criteria andInsertTimeNotBetween(Date value1, Date value2) {
addCriterion("insert_time not between", value1, value2, "insertTime");
return (Criteria) this;
}
public Criteria andStateIsNull() {
addCriterion("state is null");
return (Criteria) this;
}
public Criteria andStateIsNotNull() {
addCriterion("state is not null");
return (Criteria) this;
}
public Criteria andStateEqualTo(Integer value) {
addCriterion("state =", value, "state");
return (Criteria) this;
}
public Criteria andStateNotEqualTo(Integer value) {
addCriterion("state <>", value, "state");
return (Criteria) this;
}
public Criteria andStateGreaterThan(Integer value) {
addCriterion("state >", value, "state");
return (Criteria) this;
}
public Criteria andStateGreaterThanOrEqualTo(Integer value) {
addCriterion("state >=", value, "state");
return (Criteria) this;
}
public Criteria andStateLessThan(Integer value) {
addCriterion("state <", value, "state");
return (Criteria) this;
}
public Criteria andStateLessThanOrEqualTo(Integer value) {
addCriterion("state <=", value, "state");
return (Criteria) this;
}
public Criteria andStateIn(List<Integer> values) {
addCriterion("state in", values, "state");
return (Criteria) this;
}
public Criteria andStateNotIn(List<Integer> values) {
addCriterion("state not in", values, "state");
return (Criteria) this;
}
public Criteria andStateBetween(Integer value1, Integer value2) {
addCriterion("state between", value1, value2, "state");
return (Criteria) this;
}
public Criteria andStateNotBetween(Integer value1, Integer value2) {
addCriterion("state not between", value1, value2, "state");
return (Criteria) this;
}
public Criteria andLastTimeIsNull() {
addCriterion("last_time is null");
return (Criteria) this;
}
public Criteria andLastTimeIsNotNull() {
addCriterion("last_time is not null");
return (Criteria) this;
}
public Criteria andLastTimeEqualTo(Date value) {
addCriterion("last_time =", value, "lastTime");
return (Criteria) this;
}
public Criteria andLastTimeNotEqualTo(Date value) {
addCriterion("last_time <>", value, "lastTime");
return (Criteria) this;
}
public Criteria andLastTimeGreaterThan(Date value) {
addCriterion("last_time >", value, "lastTime");
return (Criteria) this;
}
public Criteria andLastTimeGreaterThanOrEqualTo(Date value) {
addCriterion("last_time >=", value, "lastTime");
return (Criteria) this;
}
public Criteria andLastTimeLessThan(Date value) {
addCriterion("last_time <", value, "lastTime");
return (Criteria) this;
}
public Criteria andLastTimeLessThanOrEqualTo(Date value) {
addCriterion("last_time <=", value, "lastTime");
return (Criteria) this;
}
public Criteria andLastTimeIn(List<Date> values) {
addCriterion("last_time in", values, "lastTime");
return (Criteria) this;
}
public Criteria andLastTimeNotIn(List<Date> values) {
addCriterion("last_time not in", values, "lastTime");
return (Criteria) this;
}
public Criteria andLastTimeBetween(Date value1, Date value2) {
addCriterion("last_time between", value1, value2, "lastTime");
return (Criteria) this;
}
public Criteria andLastTimeNotBetween(Date value1, Date value2) {
addCriterion("last_time not between", value1, value2, "lastTime");
return (Criteria) this;
}
public Criteria andCommentIsNull() {
addCriterion("comment is null");
return (Criteria) this;
}
public Criteria andCommentIsNotNull() {
addCriterion("comment is not null");
return (Criteria) this;
}
public Criteria andCommentEqualTo(String value) {
addCriterion("comment =", value, "comment");
return (Criteria) this;
}
public Criteria andCommentNotEqualTo(String value) {
addCriterion("comment <>", value, "comment");
return (Criteria) this;
}
public Criteria andCommentGreaterThan(String value) {
addCriterion("comment >", value, "comment");
return (Criteria) this;
}
public Criteria andCommentGreaterThanOrEqualTo(String value) {
addCriterion("comment >=", value, "comment");
return (Criteria) this;
}
public Criteria andCommentLessThan(String value) {
addCriterion("comment <", value, "comment");
return (Criteria) this;
}
public Criteria andCommentLessThanOrEqualTo(String value) {
addCriterion("comment <=", value, "comment");
return (Criteria) this;
}
public Criteria andCommentLike(String value) {
addCriterion("comment like", value, "comment");
return (Criteria) this;
}
public Criteria andCommentNotLike(String value) {
addCriterion("comment not like", value, "comment");
return (Criteria) this;
}
public Criteria andCommentIn(List<String> values) {
addCriterion("comment in", values, "comment");
return (Criteria) this;
}
public Criteria andCommentNotIn(List<String> values) {
addCriterion("comment not in", values, "comment");
return (Criteria) this;
}
public Criteria andCommentBetween(String value1, String value2) {
addCriterion("comment between", value1, value2, "comment");
return (Criteria) this;
}
public Criteria andCommentNotBetween(String value1, String value2) {
addCriterion("comment not between", value1, value2, "comment");
return (Criteria) this;
}
public Criteria andRequestIdLikeInsensitive(String value) {
addCriterion("upper(request_id) like", value.toUpperCase(), "requestId");
return (Criteria) this;
}
public Criteria andFlowIdLikeInsensitive(String value) {
addCriterion("upper(flow_id) like", value.toUpperCase(), "flowId");
return (Criteria) this;
}
public Criteria andUserNoLikeInsensitive(String value) {
addCriterion("upper(user_no) like", value.toUpperCase(), "userNo");
return (Criteria) this;
}
public Criteria andCommentLikeInsensitive(String value) {
addCriterion("upper(comment) like", value.toUpperCase(), "comment");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Flex Panels 💪</title>
<link
href="https://fonts.googleapis.com/css?family=Amatic+SC"
rel="stylesheet"
type="text/css"
/>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="panels">
<div class="panel panel1">
<p>Hey</p>
<p>Let's</p>
<p>Dance</p>
</div>
<div class="panel panel2">
<p>Give</p>
<p>Take</p>
<p>Receive</p>
</div>
<div class="panel panel3">
<p>Experience</p>
<p>It</p>
<p>Today</p>
</div>
<div class="panel panel4">
<p>Give</p>
<p>All</p>
<p>You can</p>
</div>
<div class="panel panel5">
<p>Life</p>
<p>In</p>
<p>Motion</p>
</div>
</div>
<script>
let panels = document.querySelectorAll(`.panel`);
panels.forEach((panel) => {
panel.addEventListener("click", function () {
this.classList.toggle("open");
});
});
panels.forEach((panel) => {
panel.addEventListener("transitionend", function (e) {
console.log(e.propertyName);
if (e.propertyName.includes("flex"))
this.classList.toggle("open-active");
});
});
</script>
</body>
</html>
|
package ManipulaçãoDeStrings;
public class TestaStrings {
public static void main(String[] args) {
//maneiras de criar uma string
String nomeDireto = "Java";
String nomeIndireto = new String("Java");
char[] nome = new char[]{'K', 'a', 'u'};
String nome1 = new String(nome);
StringBuilder sb1 = new StringBuilder("Java");
String nome2 = new String( sb1);
//se uma String é referência a um objeto, então ela tbm pode aceitar valor nullo
String nomeNulo = null;
//Concatenação de Strings
String nomeDaProva = "Certificação" + " " + "Java";
String nomeDaProvaComNulo = nomeDaProva + " " + nomeNulo;
System.out.println(nomeDaProvaComNulo); //é possível concaternar strings com null
System.out.println("Certificação " + 1500);
//Strings são mutáveis
String s = "caelum";
s.toUpperCase();
//continua minusculo pq depois que a string foi criada, ela não muda
System.out.println(s);
//Solução
s = s.toUpperCase(); //atribua a alteração à string
System.out.println(s);
System.out.println(s.charAt(0));
//String é nada mais que um array, por isso para acessar um caracter em uma dada posição, basta acessar a posição
System.out.println(s.charAt(3));
//System.out.println(s.charAt(-1)); //exception
//tamanho da string
System.out.println(s.length());
//verifica se a string é vazia
System.out.println("".isEmpty()); //isEmpty retorna true ou false
System.out.println(" ".isEmpty()); //espaços em branco não são vazios
//Método trim para remover espaços
System.out.println(" João ".trim());
//replace
System.out.println(s.replace('A', 'E')); //troca de char
System.out.println(s.replace("CAE", "ALU"));
//tirar um pedaço de string
String java = "Java";
System.out.println(java.substring(1, 3));
//Comparação de strings
System.out.println("Java".equals("java"));
System.out.println("Java".equalsIgnoreCase("java")); //ignora as letras maiusculas
//verifica a ordem alfabética de quem vem antes ou depois
System.out.println("Certificado".compareTo("Arnaldo")); //retorna positivo se o que eu to comparando vier depois
System.out.println("Certificado".compareTo("Certificado")); //retorna 0 pq são iguais
System.out.println("Certificado".compareTo("certificado"));
System.out.println("Certificado".compareToIgnoreCase("certificado"));
System.out.println("Certificado".compareTo("Grécia")); //retorna negativo pq Grécia vem depois dele
String texto = "Pretendo fazer a prova de certificação de Java";
System.out.println(texto.indexOf("Pretendo")); //me fala a posição da primeira ocorrência da string pretendo (0)
System.out.println(texto.indexOf("prova"));
System.out.println(texto.indexOf("pretendia")); //retorna -1 se a palavra não existe
System.out.println(texto.lastIndexOf("a")); //procura de tras pra frente
System.out.println(texto.indexOf("e", 10)); //procure a letra e a partir da posição 10
System.out.println(texto.lastIndexOf("a", 10)); //procure a letra até a posição 10
System.out.println(texto.startsWith("Pretendia")); //retorna true se a string começa com essa palavra
System.out.println(texto.startsWith("Pretendo")); //nesse caso retorna true
System.out.println(texto.endsWith("Pretendia")); //verifica se a string termina com essa palavras
StringBuilder sb = new StringBuilder("guilherme");
System.out.println(sb.indexOf("e") + sb.lastIndexOf("e"));
System.out.println(sb.indexOf("k") + sb.lastIndexOf("k"));
}
}
|
/*
* This file is part of the StegX project.
* Copyright (C) 2018 StegX Team
*
* StegX 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @file stegx_common.h
* @brief Définitions communes à la partie privée et public de la bibliothèque.
* @details Ce fichier peut-être inclus par les programme utilisant la
* bibliothèque ainsi que par les différents modules de la bibliothèque. Il
* contient des types, des structures et des variables globales.
*/
#ifndef STEGX_COMMON_H
#define STEGX_COMMON_H
/*
* Types
*/
/**
* Mode permettant de distinguer les deux fonctionnalités proposés par
* l'application.
* */
enum mode {
STEGX_MODE_INSERT, /*!< Mode insertion/dissimulation de données. */
STEGX_MODE_EXTRACT /*!< Mode extraction de données. */
};
/** Type du mode d'utilisation de la bibliothèque. */
typedef enum mode mode_e;
/**
* Algorithmes proposés par l'application (sans prendre compte du format du
* fichier hôte) (attention, l'ordre ne doit pas être modifié).
*/
enum algo {
STEGX_ALGO_LSB = 0, /*!< Least Significant Bit : modification du bit de poids faible. */
STEGX_ALGO_EOF, /*!< End-Of-File : concaténation avec le fichier à cacher. */
STEGX_ALGO_METADATA, /*!< Métadonnée : stockage du fichier à cacher dans les métadonnées du fichier hôte. */
STEGX_ALGO_EOC, /*!< End-Of-Chunk : stockage du fichier à cacher après chaque chunk. */
STEGX_ALGO_JUNK_CHUNK, /*!< Chunk poubelle : stockage du fichier dans des chunks invalides. */
STEGX_NB_ALGO /*!< Nombres d'algorithmes proposés par l'application. */
};
/** Type d'un algortihme proposé par l'application. */
typedef enum algo algo_e;
/** Méthode de protection des données. */
enum method {
STEGX_WITHOUT_PASSWD, /*!< Aucun mot de passe choisi par l'utilisateur. */
STEGX_WITH_PASSWD /*!< Mot de passe choisi par l'utilisateur. */
};
/** Type de la méthode de protection des données. */
typedef enum method method_e;
/** Type de la structure privée stockant les informations de la bibliothèque. */
typedef struct info info_s;
/*
* Variables
*/
/**
* Variable globale pointant sur un tableau de booléen de taille \r{STEGX_NB_ALGO}.
* Si stegx_propos_algo[i] est égal à 1, alors on peut utiliser l'algorithme
* correspondant à algo_e égal à i. Sinon, on ne peut pas.
*/
extern algo_e *stegx_propos_algos;
/*
* Structures
*/
/**
* @brief Informations concernant uniquement l'insertion de données.
*/
struct stegx_info_insert {
char *hidden_path; /*!< Chaîne de caractères representant le nom du fichier a cacher (requis). */
algo_e algo; /*!< Algorithme qui sera utilisé pour la dissimulation (requis uniquement si CLI). */
};
/** Type des informations concernant uniquement l'insertion. */
typedef struct stegx_info_insert stegx_info_insert_s;
/**
* @brief Informations du choix de l'utilisateur.
* @details Cette structure est à remplir par les interfaces avec les choix de
* l'utilisateur.
* @req Les pointeurs ne doivent pas êtres null pour les champs requis et
* doivent pointer sur des zones mémoires allouées.
*/
struct stegx_choices {
char *host_path; /*!< Chemin du fichier hôte à analyser (requis). */
char *res_path; /*!< Chemin du fichier/dossier résultant (requis). */
char *passwd; /*!< Mot de passe choisi par l'utilisateur (optionnel). */
mode_e mode; /*!< Mode d'utilisation (requis). */
stegx_info_insert_s *insert_info; /*!< Structure stockant les informations de l'insertion (requis si insertion). */
};
/** Type des informations du choix de l'utilisateur. */
typedef struct stegx_choices stegx_choices_s;
#endif /* ifndef STEGX_COMMON_H */
|
<!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>btn follows mouse</title>
</head>
<body>
<div class="btn-container">
<button class="btn">test button</button>
</div>
<style>
body {
margin: 0px;
padding: 0px;
display: flex;
align-items: center;
justify-content: center;
background-color: rgb(237, 237, 237);
font-family: "Rufina", serif;
height: 400vh;
width: 100%;
}
.btn-container {
outline: 2px dashed black;
outline-offset: -2px;
border-radius: 10px;
transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
}
.btn {
border: none;
padding: 10px 30px;
font-size: 15px;
font-weight: 600;
position: relative;
background-color: #aee8fa;
color: black;
border-radius: 8px;
outline: none;
outline-offset: -2px;
cursor: pointer;
transition: top 0.08s, left 0.08s;
transition: background-color 0.2s cubic-bezier(0.5, 1, 0.5, 1),
color 0.2s cubic-bezier(0.5, 1, 0.5, 1);
transition-timing-function: background-color ease-in-out;
transition-timing-function: ease-out;
}
.btn:focus {
outline: 4px solid rgb(41, 41, 41);
outline-offset: 3px;
}
.btn:hover {
background-color: #336484;
color: white;
}
</style>
<script>
let button = document.querySelector("button");
let btn = document.querySelector(".btn");
let btnContainer = document.querySelector(".btn-container");
console.log(btn);
const follow = (e) => {
btn.style.top = `${(e.pageY - btnContainer.offsetTop) * 0.1}px`;
btn.style.left = `${(e.pageX - btnContainer.offsetLeft) * 0.2}px`;
};
window.addEventListener("mousemove", follow);
</script>
</body>
</html>
|
#pragma once
#include <stdio.h>
#include"allegro5/allegro.h"
#include"allegro5/allegro_image.h"
#include <iostream>
class Brick
{
private:
const int sizeX = 60; //dimensions of each brick
const int sizeY = 15;
const int locationX;
const int locationY;
bool destroyed; //flag to indicate if destroyed
bool super; //flag ro indicate if super brick
int superLevel; //indicates the level if superbrick
int puBrick; //indicates if power up brick
// ALLEGRO_BITMAP *brick = NULL;
public:
ALLEGRO_BITMAP *brick = NULL;
Brick(int lx=0, int ly=0,int pU = 0, bool s = false) :locationX(lx), locationY(ly)
{
destroyed = false;
super = s;
superLevel = 3;
puBrick = pU;
if (super)
{
if (!al_init_image_addon()) {
fprintf(stderr, "Failed to initialize image addon!\n");
}
brick = al_load_bitmap("super.bmp");
al_draw_bitmap(brick, locationX, locationY, 0);
}
else
{
if (!al_init_image_addon()) {
fprintf(stderr, "Failed to initialize image addon!\n");
}
brick = al_load_bitmap("final.bmp");
al_draw_bitmap(brick, locationX, locationY,0);
}
if (!brick)
{
fprintf(stderr, "Failed to create player bitmap!\n");
}
};
~Brick()
{
al_destroy_bitmap(brick);
};
int getLocX();
int getLocY();
int getSizeX();
int getSizeY();
bool isPowerUp();
bool isDestroyed();
int getSuperLevel();
void setSuperLevel(int);
bool isSuper();
void destroy(bool result);
ALLEGRO_BITMAP *getBitMap(); //returns the bitmap of the brick
bool detectCollisionVertical(const int ball_x, const int ball_y, const int ball_dx, const int ball_dy, const int BALL_SIZE_RADIUS);//ball to brick detection
bool detectCollisionHorizontal(const int ball_x, const int ball_y, const int ball_dx, const int ball_dy, const int BALL_SIZE_RADIUS);//ball to brick detection
};
|
using SampleHierarchies.Data.Mammals;
using SampleHierarchies.Enums;
using SampleHierarchies.Interfaces.Data.Mammals;
using SampleHierarchies.Interfaces.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SampleHierarchies.Gui
{
public sealed class ElephantScreen : Screen
{
#region Properties And Ctor
/// <summary>
/// Data service.
/// </summary>
private IDataService _dataService;
/// <summary>
/// Ctor.
/// </summary>
/// <param name="dataService">Data service reference</param>
public ElephantScreen(IDataService dataService) : base(dataService)
{
_dataService = dataService;
}
#endregion Properties And Ctor
#region Public Methods
public override void EnterScreen()
{
try
{
ElephantScreenChoices choice = (ElephantScreenChoices)currentField;
switch (choice)
{
case ElephantScreenChoices.List:
ListElephant();
screenLines.Clear();
Show();
break;
case ElephantScreenChoices.Create:
AddElephant();
screenLines.Clear();
Show();
break;
case ElephantScreenChoices.Delete:
DeleteElephant();
screenLines.Clear();
Show();
break;
case ElephantScreenChoices.Modify:
EditElephantMain();
screenLines.Clear();
Show();
break;
case ElephantScreenChoices.Exit:
Console.WriteLine("Going back to parent menu.");
return;
}
}
catch
{
Console.WriteLine("Invalid choice. Try again.");
}
}
/// <inheritdoc/>
public override void Show()
{
while (true)
{
var list = new List<ScreenLineEntry>
{
new ScreenLineEntry { Text = "0. Exit" },
new ScreenLineEntry { Text = "1. List all elephant" },
new ScreenLineEntry { Text = "2. Create a new elephant" },
new ScreenLineEntry { Text = "2. Delete existing elephant" },
new ScreenLineEntry { Text = "2. Modify existing elephant" }
};
ScreenDefinitionJson = _dataService.settings.ElephantScreenColor;
ScreenRender(list);
SwitchHandler();
return;
}
}
#endregion // Public Methods
#region Private Methods
/// <summary>
/// List all dogs.
/// </summary>
private void ListElephant()
{
Console.WriteLine();
if (_dataService?.Animals?.Mammals?.Elephants is not null &&
_dataService.Animals.Mammals.Elephants.Count > 0)
{
Console.WriteLine("Here's a list of elephants:");
int i = 1;
foreach (Elephant elephant in _dataService.Animals.Mammals.Elephants)
{
Console.Write($"Elephant number {i}, ");
elephant.Display();
i++;
}
Console.ReadLine();
}
else
{
Console.WriteLine("The list of elephant is empty.");
Console.ReadLine();
}
}
/// <summary>
/// Add a elephant.
/// </summary>
private void AddElephant()
{
try
{
Elephant elephant = AddEditElephant();
_dataService?.Animals?.Mammals?.Elephants?.Add(elephant);
Console.WriteLine("Dog with name: {0} has been added to a list of elephant", elephant.Name);
}
catch
{
Console.WriteLine("Invalid input.");
}
}
/// <summary>
/// Deletes a Elephant.
/// </summary>
private void DeleteElephant()
{
try
{
Console.Write("What is the name of the elephant you want to delete? ");
string? name = Console.ReadLine();
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
Elephant? elephant = (Elephant?)(_dataService?.Animals?.Mammals?.Elephants
?.FirstOrDefault(d => d is not null && string.Equals(d.Name, name)));
if (elephant is not null)
{
_dataService?.Animals?.Mammals?.Elephants?.Remove(elephant);
Console.WriteLine("Elephant with name: {0} has been deleted from a list of elephants", elephant.Name);
}
else
{
Console.WriteLine("Elephant not found.");
}
}
catch
{
Console.WriteLine("Invalid input.");
}
}
/// <summary>
/// Edits an existing Elephant after choice made.
/// </summary>
private void EditElephantMain()
{
try
{
Console.Write("What is the name of the elephant you want to edit? ");
string? name = Console.ReadLine();
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
Elephant? elephant = (Elephant?)(_dataService?.Animals?.Mammals?.Elephants
?.FirstOrDefault(d => d is not null && string.Equals(d.Name, name)));
if (elephant is not null)
{
Elephant elephantEdited = AddEditElephant();
elephant.Copy(elephantEdited);
Console.Write("Elephant after edit:");
elephant.Display();
}
else
{
Console.WriteLine("Elephant not found.");
}
}
catch
{
Console.WriteLine("Invalid input. Try again.");
}
}
/// <summary>
/// Adds/edit specific Elephant.
/// </summary>
/// <exception cref="ArgumentNullException"></exception>
private Elephant AddEditElephant()
{
Console.Write("What name of the elephant? ");
string? name = Console.ReadLine();
Console.Write("What is the Elephant's age? ");
string? ageAsString = Console.ReadLine();
Console.Write("What height of the elephant? ");
string? heightAsString = Console.ReadLine();
Console.Write("What weight of the elephant? ");
string? weightAsString = Console.ReadLine();
Console.Write("What tusk lenght of the elephant? ");
string? tusklenghtAsString = Console.ReadLine();
Console.Write("What long lifespan of the elephant? ");
string? longlifespanAsString = Console.ReadLine();
Console.Write("What social behavior of the elephant? ");
string? socialbehavior = Console.ReadLine();
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
if (ageAsString is null)
{
throw new ArgumentNullException(nameof(ageAsString));
}
if (heightAsString is null)
{
throw new ArgumentNullException(nameof(heightAsString));
}
if (weightAsString is null)
{
throw new ArgumentNullException(nameof(weightAsString));
}
if (tusklenghtAsString is null)
{
throw new ArgumentNullException(nameof(tusklenghtAsString));
}
if (longlifespanAsString is null)
{
throw new ArgumentNullException(nameof(longlifespanAsString));
}
if (socialbehavior is null)
{
throw new ArgumentNullException(nameof(socialbehavior));
}
int age = Int32.Parse(ageAsString);
float height = float.Parse(heightAsString);
float weight = float.Parse(weightAsString);
float tusklenght = float.Parse(tusklenghtAsString);
int longlifespan = Int32.Parse(longlifespanAsString);
Elephant elephant = new Elephant(name, age, height, weight, tusklenght, longlifespan, socialbehavior);
return elephant;
}
#endregion // Private Methods
}
}
|
package com.example.freenowapp.ui.homeView.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.freenowapp.bases.BaseFragment
import com.example.freenowapp.databinding.FragmentVehicalsPagerBinding
import com.example.freenowapp.ui.homeView.adapters.VehiclesAdapter
import com.example.freenowapp.ui.homeView.uiModel.Vehicle
import com.example.freenowapp.ui.homeView.viewModel.VehiclesSharedViewModel
import com.example.freenowapp.ui.homeView.viewModel.VehiclesViewModel
import com.example.freenowapp.utils.ViewState
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class VehicleListFragment : BaseFragment() {
private lateinit var binding: FragmentVehicalsPagerBinding
private lateinit var vehiclesAdapter: VehiclesAdapter
private val viewModel: VehiclesViewModel by viewModel()
private val sharedViewModel: VehiclesSharedViewModel by sharedViewModel()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
super.onCreateView(inflater, container, savedInstanceState)
binding = FragmentVehicalsPagerBinding.inflate(inflater, container, false)
return attachToRootView(binding.root)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
observeViewModel()
}
private fun observeViewModel() {
viewModel.viewState.observe(viewLifecycleOwner, Observer {
when (it) {
is ViewState.Error -> {
hideLoading()
showError(
errorMessage = getString(it.error),
positiveAction = { viewModel.onRefreshData() },
negativeAction = { requireActivity().onBackPressed() }
)
}
ViewState.Loading -> {
showLoading()
}
ViewState.Success -> {
hideErrorState()
hideLoading()
}
}
})
viewModel.vehicles.observe(viewLifecycleOwner, Observer {
setupRecyclerView(it)
})
}
private fun setupRecyclerView(vehicles: List<Vehicle>) {
vehiclesAdapter = VehiclesAdapter(vehicles,
VehiclesAdapter.VehiclesClickListener { vehicle ->
sharedViewModel.onVehicleSelected(vehicle)
})
with(binding.VehicalsRecyclerView) {
layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
adapter = vehiclesAdapter
}
}
}
|
import React from 'react';
import { Link } from 'react-router-dom';
import { padNumber, capitalizeFirstLetter } from '../utils/helper';
import { Pokemon } from '../types';
interface CardListProps {
pokemonList: Pokemon[];
}
const CardList: React.FC<CardListProps> = ({ pokemonList }) => {
return (
<div>
<h1>Pokédex</h1>
<div className="card-list-container">
{pokemonList.map((pokemon) => (
<Link to={`/pokemon/${pokemon.name}`} key={pokemon.name}>
<div className="pokemon-card">
<img
src={`https://assets.pokemon.com/assets/cms2/img/pokedex/full/${padNumber(
pokemon.url.split('/')[6],
3
)}.png`}
alt={pokemon.name}
/>
<p>{capitalizeFirstLetter(pokemon.name)}</p>
</div>
</Link>
))}
</div>
</div>
);
};
export default CardList;
|
import {
ClientFeatureRepository,
EdgeFeatureHubConfig,
FeatureState,
FeatureValueType,
Readyness,
SSEResultState
} from '../app';
import { expect } from 'chai';
describe('Readiness listeners should fire on appropriate events', () => {
let repo: ClientFeatureRepository;
beforeEach(() => {
repo = new ClientFeatureRepository();
});
it('should allow us to set readiness on the config', () => {
const fhConfig = new EdgeFeatureHubConfig('http://localhost:8080', '123*123');
fhConfig.repository(repo);
let readinessTrigger = 0;
let lastReadiness: Readyness | undefined = undefined;
const triggerHandler = fhConfig.addReadinessListener((state) => {
lastReadiness = state;
readinessTrigger++;
});
expect(fhConfig.readyness).to.eq(Readyness.NotReady);
expect(readinessTrigger).to.eq(1);
const features = [
{ id: '1', key: 'banana', version: 1, type: FeatureValueType.Boolean, value: true },
];
repo.notify(SSEResultState.Features, features);
expect(fhConfig.readyness).to.eq(Readyness.Ready);
expect(lastReadiness).to.eq(Readyness.Ready);
expect(readinessTrigger).to.eq(2);
fhConfig.removeReadinessListener(triggerHandler);
repo.notReady();
// real readiness updates
expect(fhConfig.readyness).to.eq(Readyness.NotReady);
// but the trigger does not fire
expect(readinessTrigger).to.eq(2);
expect(lastReadiness).to.eq(Readyness.Ready);
});
it('should start not ready, receive a list of features and become ready and on failure be failed', () => {
let readinessTrigger = 0;
let lastReadiness: Readyness | undefined = undefined;
repo.addReadinessListener((state) => {
lastReadiness = state;
return readinessTrigger++;
});
expect(repo.readyness).to.eq(Readyness.NotReady);
expect(readinessTrigger).to.eq(1);
const features = [
{ id: '1', key: 'banana', version: 1, type: FeatureValueType.Boolean, value: true } as FeatureState,
];
repo.notify(SSEResultState.Features, features);
expect(repo.readyness).to.eq(Readyness.Ready);
expect(lastReadiness).to.eq(Readyness.Ready);
expect(readinessTrigger).to.eq(2);
repo.notify(SSEResultState.Failure, null);
expect(repo.readyness).to.eq(Readyness.Failed);
expect(lastReadiness).to.eq(Readyness.Failed);
expect(readinessTrigger).to.eq(3);
});
it('we should be able to be ready and then be still ready on a bye', () => {
let readinessTrigger = 0;
let lastReadiness: Readyness | undefined = undefined;
repo.addReadinessListener((state) => {
lastReadiness = state;
return readinessTrigger++;
});
const features = [
{ id: '1', key: 'banana', version: 1, type: FeatureValueType.Boolean, value: true } as FeatureState,
];
repo.notify(SSEResultState.Features, features);
repo.notify(SSEResultState.Bye, undefined);
expect(repo.readyness).to.eq(Readyness.Ready);
expect(lastReadiness).to.eq(Readyness.Ready);
expect(readinessTrigger).to.eq(2);
});
it('should allow us to register disinterest in the initial notready status', () => {
let readinessTrigger = 0;
let lastReadiness: Readyness | undefined = undefined;
const listener = (state) => {
lastReadiness = state;
return readinessTrigger++;
};
repo.addReadinessListener(listener, true);
expect(lastReadiness).to.be.undefined;
expect(readinessTrigger).to.eq(0);
const features = [
{ id: '1', key: 'banana', version: 1, type: FeatureValueType.Boolean, value: true } as FeatureState,
];
repo.notify(SSEResultState.Features, features);
expect(lastReadiness).to.eq(Readyness.Ready);
expect(readinessTrigger).to.eq(1);
repo.notReady();
expect(lastReadiness).to.eq(Readyness.NotReady);
repo.removeReadinessListener(listener);
repo.notify(SSEResultState.Features, features);
expect(lastReadiness).to.eq(Readyness.NotReady);
});
});
|
import { useEffect, useState } from 'react';
import { Container } from './styles';
interface Props {
filledStarsQuantity: number;
}
const Stars = ({ filledStarsQuantity }: Props) => {
const blankStarsQty = 5 - filledStarsQuantity;
return (
<Container>
{[...Array(filledStarsQuantity)].map((item, idx) => (
<img
src="/corebiz-dev-test/filledStar.svg"
alt="Estrela pintada"
key={idx}
/>
))}
{[...Array(blankStarsQty)].map((item, idx) => (
<img
src="/corebiz-dev-test/emptyStar.svg"
alt="Estrela vazia"
key={idx}
/>
))}
</Container>
);
};
export default Stars;
|
// Patterns
/* Patterns are a great way to understand loops in any programming language */
#include <iostream>
using namespace std;
// A horizontal line of n stars
void p1(int n) {
for(int i = 0; i < n; i++)
cout << '*';
}
// A vertical line of n stars
void p2(int n) {
for(int i = 0; i < n; i++)
cout << "*\n";
}
// n by n grid of stars
void p3(int n) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
cout << '*';
}
cout << '\n';
}
}
// n by n grid of numbers from 1 to n
void p4(int n) {
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
cout << j;
}
cout << '\n';
}
}
// Inverted right-angled triangle with stars
void p5(int n) {
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= (n-i); j++) {
cout << ' ';
}
for(int k = 1; k <= i; k++) {
cout << '*';
}
cout << '\n';
}
}
int main() {
p1(5);
cout << endl << "\n";
p2(5);
cout << endl << "\n";
p3(5);
cout << endl << "\n";
p4(5);
cout << endl << "\n";
p5(5);
}
|
package hash;
import java.security.MessageDigest;
import util.HexUtil;
/**
* 해시 함수를 사용하여 평문의 해시값을 생성하는 예제.
* SHA-256 알고리즘을 사용하여 "Hello World" 문자열의 해시값을 계산하고,
* 계산된 해시값을 바이트 배열과 16진수 문자열로 출력한다.
*/
public class HashExample {
public static void main(String[] args) throws Exception {
String algorithm = "SHA-256";
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
System.out.println("Alogorithm :" + algorithm);
String plaintext = "Hello World";
System.out.println("Target text : " + plaintext);
byte[] hash = messageDigest.digest(plaintext.getBytes());
System.out.print("Hash : ");
for (byte b : hash)
System.out.printf("%02X ", b);
System.out.println("\n해쉬 길이 : " + hash.length + " byte");
// 바이트 배열을 16진수 문자열로 변환
String hexOutput = HexUtil.bytesToHex(hash);
System.out.println("Hash of plaintext : " + hexOutput);
}
}
|
import { Tabs } from 'nextra/components'
## generateSchema Function
**Overview**
The generateSchema function is a utility function that generates a Yup validation schema based on the specified configuration. It supports generating schemas for string, number, date, and custom input types and can also incorporate locale-specific validations.
<Tabs items={['Usage', 'Props']}>
<Tabs.Tab>
```js
import { generateSchema, FormBuilderConfiguration } from 'path-to-your-module';
const config: FormBuilderConfiguration = {
// ... your config here
};
const schema = generateSchema(config);
```
</Tabs.Tab>
<Tabs.Tab>
**params**
{<table>
<thead>
<tr>
<th>params</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>config</td>
<td>FormBuilderConfiguration</td>
<td>Configuration object to build the schema</td>
</tr>
</tbody>
</table>}
**FormBuilderConfiguration Type**
{<table>
<thead>
<tr>
<th>Property</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>schemas</td>
<td>Array of objects</td>
<td>List of schema configurations for the form fields</td>
</tr>
<tr>
<td>locale</td>
<td>Array of objects</td>
<td>List of locale objects for localized validations</td>
</tr>
</tbody>
</table>}
**Schema Type in schemas Array**
{<table>
<thead>
<tr>
<th>Property</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>name</td>
<td>string</td>
<td>The name of the field</td>
</tr>
<tr>
<td>constraint</td>
<td>object</td>
<td>Defines the validation rules for the field</td>
</tr>
<tr>
<td>hasLocal</td>
<td>boolean</td>
<td>Whether to apply locale-specific validations</td>
</tr>
</tbody>
</table>}
**Constraint Type**
{<table>
<thead>
<tr>
<th>Property</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>inputType</td>
<td>string</td>
<td>The input type ('string', 'number', 'date', 'custom')</td>
</tr>
<tr>
<td>validationSchema</td>
<td>object</td>
<td>Specific validation schema based on the input type</td>
</tr>
</tbody>
</table>}
**StringValidation Type**
{<table>
<thead>
<tr>
<th>Property</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>required</td>
<td>object</td>
<td>Specifies whether the field is required. Contains `flag` (boolean) and `errorMessage` (string).</td>
</tr>
<tr>
<td>length</td>
<td>object</td>
<td>Specifies the exact length the string should be. Contains `number` (number) and `errorMessage` (string).</td>
</tr>
<tr>
<td>min</td>
<td>object</td>
<td>Specifies the minimum length the string can be. Contains `number` (number) and `errorMessage` (string).</td>
</tr>
<tr>
<td>max</td>
<td>object</td>
<td>Specifies the maximum length the string can be. Contains `number` (number) and `errorMessage` (string).</td>
</tr>
<tr>
<td>type</td>
<td>object</td>
<td>Specifies the specific type of the string (like 'email', 'url', 'uuid'). Contains `valueType` (string) and `errorMessage` (string).</td>
</tr>
<tr>
<td>lowercase</td>
<td>object</td>
<td>Specifies if the string should be in lowercase. Contains `flag` (boolean) and `errorMessage` (string).</td>
</tr>
<tr>
<td>uppercase</td>
<td>object</td>
<td>Specifies if the string should be in uppercase. Contains `flag` (boolean) and `errorMessage` (string).</td>
</tr>
</tbody>
</table>}
**NumberValidation Type**
{<table>
<thead>
<tr>
<th>Property</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>required</td>
<td>object</td>
<td>Specifies whether the field is required. Contains `flag` (boolean) and `errorMessage` (string).</td>
</tr>
<tr>
<td>min</td>
<td>object</td>
<td>Specifies the minimum value the number can be. Contains `number` (number) and `errorMessage` (string).</td>
</tr>
<tr>
<td>max</td>
<td>object</td>
<td>Specifies the maximum value the number can be. Contains `number` (number) and `errorMessage` (string).</td>
</tr>
<tr>
<td>positive</td>
<td>object</td>
<td>Specifies if the number should be positive. Contains `flag` (boolean) and `errorMessage` (string).</td>
</tr>
<tr>
<td>negative</td>
<td>object</td>
<td>Specifies if the number should be negative. Contains `flag` (boolean) and `errorMessage` (string).</td>
</tr>
<tr>
<td>onlyInteger</td>
<td>object</td>
<td>Specifies if the number should be an integer. Contains `flag` (boolean) and `errorMessage` (string).</td>
</tr>
</tbody>
</table>}
**DateValidation Type**
{<table>
<thead>
<tr>
<th>Property</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>required</td>
<td>object</td>
<td>Specifies whether the field is required. Contains `flag` (boolean) and `errorMessage` (string).</td>
</tr>
<tr>
<td>min</td>
<td>object</td>
<td>Specifies the minimum date value. Contains `value` (Date) and `errorMessage` (string).</td>
</tr>
<tr>
<td>max</td>
<td>object</td>
<td>Specifies the maximum date value. Contains `value` (Date) and `errorMessage` (string).</td>
</tr>
</tbody>
</table>}
</Tabs.Tab>
</Tabs>
## Example Usage
```js
import { generateSchema } from './path-to-your-schema-generator-file';
import { FormBuilderConfiguration } from '../model/form-builder-config';
const config: FormBuilderConfiguration = {
schemas: [
{
name: 'email',
constraint: {
inputType: 'string',
validationSchema: {
required: {
flag: true,
errorMessage: 'Email is required',
},
type: {
valueType: 'email',
errorMessage: 'Invalid email format',
},
},
hasLocal: false,
},
},
{
name: 'age',
constraint: {
inputType: 'number',
validationSchema: {
required: {
flag: true,
errorMessage: 'Age is required',
},
min: {
number: 18,
errorMessage: 'Age must be at least 18',
},
},
hasLocal: false,
},
},
],
locale: [
{ code: 'en' },
{ code: 'am' },
],
};
const schema = generateSchema(config);
```
In this example, an email field and an age field are being validated. The email field is required and must match the email format, while the age field is required and must be at least 18. The schema generated by generateSchema can then be used to validate form data using Yup's validation methods.
|
import os
import sys
import psycopg2
import pandas as pd
import matplotlib.pyplot as plt
import argparse
import numpy as np
def get_connection():
db_url = "postgresql://postgres:TGBCFSFxiLVUyNZInoIAfClDtkrTwZau@monorail.proxy.rlwy.net:18855/railway"
conn = psycopg2.connect(db_url)
cursor = conn.cursor()
return conn, cursor
def fetch_data():
conn, cursor = get_connection()
query = "SELECT * FROM inference_timestep_analysis"
cursor.execute(query)
data = cursor.fetchall()
columns = [desc[0] for desc in cursor.description]
cursor.close()
conn.close()
return pd.DataFrame(data, columns=columns)
def map_model_names(model_name):
model_mapping = {
'ADPR_x0': 'ADPR',
'MB_ADPR_x0': 'MB-ADPR',
'SAD_x0': 'S-ADPR',
'S_SAD_x0': 'F-ADPR',
'LS_SAD_x0': 'LF-ADPR'
}
return model_mapping.get(model_name, model_name)
def get_model_color(model_name):
color_mapping = {
'ADPR': 'blue',
'MB-ADPR': 'green',
'S-ADPR': 'red',
'F-ADPR': 'orange',
'LF-ADPR': 'purple'
}
return color_mapping.get(model_name, 'black')
def plot_and_save_graphs(data, dataset, timesteps, output_dir):
metrics = ['precision', 'recall', 'ndcg', 'coverage_item', 'coverage_item_hit']
model_order = ['ADPR_x0', 'MB_ADPR_x0', 'SAD_x0', 'S_SAD_x0', 'LS_SAD_x0']
for metric in metrics:
plt.figure()
for model in model_order:
model_data = data[data['model'] == model]
if timesteps:
model_data = model_data[model_data['inference_timestamp'].isin(timesteps)]
model_data.sort_values('inference_timestamp')
mapped_model_name = map_model_names(model)
color = get_model_color(mapped_model_name)
metric_values = [float(m) for m in model_data[metric]]
if timesteps:
timesteps_values = [str(t) for t in model_data['inference_timestamp']]
print(timesteps_values)
print(metric_values)
plt.plot(timesteps_values, metric_values, label=mapped_model_name, color=color, marker='o')
else:
plt.plot(model_data['inference_timestamp'], metric_values, label=mapped_model_name, color=color, marker='o')
plt.title(f'{metric.capitalize()} over Timesteps for {dataset} dataset')
plt.xlabel('Inference Timestep')
plt.ylabel(metric.capitalize())
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) # Legend outside the plot
plt.grid(False) # Remove background grid
y_min, y_max = plt.gca().get_ylim()
y_ticks = np.linspace(y_min, y_max, num=6)
plt.yticks(y_ticks)
if timesteps is not None:
plt.xticks(range(len(timesteps)), [str(t) for t in timesteps])
# plt.gca().yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f'{x:.4f}')) # Format y-axis
plt.savefig(os.path.join(output_dir, f'{dataset}-{metric}.png'), bbox_inches='tight')
plt.close()
def main(timesteps=None, output_dir='graphs'):
# Create the output directory if it does not exist
output_dir = os.path.join(os.getcwd(), output_dir)
os.makedirs(output_dir, exist_ok=True)
data = fetch_data()
for dataset in data['dataset'].unique():
dataset_data = data[data['dataset'] == dataset]
plot_and_save_graphs(dataset_data, dataset, timesteps, output_dir)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Generate and save graphs from inference timestep analysis.')
parser.add_argument('--timesteps', type=int, nargs='*', default=None, help='List of timesteps to consider (e.g., 1 5 50 100). If not provided, all timesteps will be used.')
parser.add_argument('--output_dir', type=str, default='graphs', help='Directory to save the generated graphs.')
args = parser.parse_args()
main(timesteps=args.timesteps, output_dir=args.output_dir)
|
/* eslint-disable @typescript-eslint/no-explicit-any */
import { MoreVertical, Star } from 'lucide-react'
import { Card, CardContent, CardHeader } from '../ui/card'
import { Carousel, CarouselContent, CarouselItem } from '../ui/carousel'
import Autoplay from "embla-carousel-autoplay"
import { HotelType } from '@/types'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '../ui/dropdown-menu'
interface Props extends HotelType {}
function HotelCard(props: Props) {
return (
<Card className="overflow-hidden">
<CardHeader className="p-0 relative">
<Carousel
className="w-full"
plugins={[
Autoplay({
delay: 2000,
}) as any
]}
>
<CarouselContent>
{props.imageUrl.map((image) => (
<CarouselItem key={`hotelImage:${props._id}`}>
<div className="h-80 w-full overflow-hidden">
<img className="h-full w-full object-cover" src={image} alt="hotel-img" loading="lazy" />
</div>
</CarouselItem>
))}
</CarouselContent>
</Carousel>
<DropdownMenu>
<DropdownMenuTrigger className='w-fit absolute z-10 rounded-full bg-white p-1 right-1 shadow-md'>
<MoreVertical/>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>Edit</DropdownMenuItem>
<DropdownMenuItem>Delete</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</CardHeader>
<CardContent className="space-y-2 mt-3 p-1">
<div className="flex flex-row items-center justify-between font-bold">
<p>{props.name}</p>
<div className="flex flex-row gap-1 items-center text-sm">
<Star className="fill-black h-5" />
{props.rating}
</div>
</div>
<p className="text-sm">{props.city}, {props.country}</p>
<div className="flex flex-row items-center gap-2">
{props.facilities.slice(0, 3).map(facility => (
<div className="border w-fit text-xs text-primary-blue font-bold bg-slate-200 px-2 rounded-2xl" key={`facility:${props._id}`}>
<p>{facility}</p>
</div>
))}
</div>
<p className="font-bold">₹{props.pricePerNight} <span className="font-normal text-slate-500">per night</span></p>
</CardContent>
</Card>
)
}
export default HotelCard
|
package com.project.rmfr.member.controller;
import com.project.rmfr.member.dto.MembersDto;
import com.project.rmfr.member.entity.Members;
import com.project.rmfr.member.service.MemberService;
import com.project.rmfr.utils.MailUtils;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequiredArgsConstructor
@Slf4j
public class MemberRestApiController {
private final HttpSession httpSession;
private final MemberService memberService;
private final MailUtils mailUtils;
/*
* 아이디 중복 체크
*/
@GetMapping("/rest/member/usernameDupChk/{username}")
public boolean usernameDupChk(@PathVariable("username") String username) {
return memberService.usernameDuplicateChk(username);
}
/*
* 이메일 인증
* type { s : 회원 가입(signup), c : 단순 인증(cert) }
*/
@GetMapping("/rest/member/emailValid/{emailAddress}/{type}")
public Map<String, Object> emailValid(@PathVariable("emailAddress") String emailAddress, @PathVariable("type") String type) {
return mailUtils.sendEmail(emailAddress, type);
}
/*
* 로그인 여부 확인
* 1. principal에 저장된 userid get
* 2. userid로 간단한 유저 정보 return
*/
@GetMapping("/rest/member/loginchk")
public Map<String, MembersDto> loginChk(Principal principal) {
Map<String, MembersDto> loginInfo = new HashMap<>();
try {
String mId = principal.getName();
loginInfo.put("info", memberService.getSimpleMemberInfo(mId));
} catch (Exception e) {
log.info("principal is null.");
loginInfo.put("info", null);
}
return loginInfo;
}
/*
* 회원 정보 상세(회원 정보 수정 화면)
*/
@GetMapping("/rest/member/loginUserDetails")
public Map<String, MembersDto> loginUserDetails(Principal principal) {
Map<String, MembersDto> loginInfo = new HashMap<>();
try {
String mId = principal.getName();
loginInfo.put("info", memberService.getDetailMemberInfo(mId));
} catch (Exception e) {
log.info("principal is null.");
loginInfo.put("info", null);
}
return loginInfo;
}
/*
* 회원 정보 수정 시 현재 비밀번호 인증
*/
@GetMapping("/rest/member/pwChk/{password}")
public boolean pwChk(@PathVariable("password") String password, Principal principal) {
boolean chk = false;
try {
String mId = principal.getName();
chk = memberService.passwordChecked(mId, password);
} catch (Exception e) {
log.info("principal is null");
}
return chk;
}
/*
* 가입된 이메일 주소인지 체크
*/
@GetMapping("/rest/member/mailChkExists/{mEmail}/{mId}")
public List<String> mailChkExists(@PathVariable("mEmail") String mEmail, @PathVariable(value = "mId", required = false) String mId) {
List<String> chk = new ArrayList<>();
try {
if ( "0".equals(mId) ) {
chk = memberService.mailChkExists(mEmail);
} else {
MembersDto dto = memberService.getDetailMemberInfo(mId);
if ( dto.getMId() == null ) {
chk.add("501");
} else {
String rst = mEmail.equals(dto.getMEmail()) ? "200" : "502";
chk.add(rst);
}
}
} catch (Exception e) {
log.info("principal is null");
}
return chk;
}
}
|
<template>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-avatar@latest/dist/avatar.min.css" rel="stylesheet">
<div class="Generate">
<h1 class="title mb-3">Генератор заданий</h1>
{{ isFileUploading }}
<div v-if="isEmail">
{{ isEmail }}
</div>
<div v-if="tasks.message === 'Извините для вас тест не сгенерирован!'">
<p>На этой странице вы можете сгенерировать вариант</p>
<div class="btn-group mb-3" role="group" aria-label="Basic example">
<button type="button" @click="generateTask()" class="btn btn-primary">Сгенерировать вариант</button>
</div>
</div>
<div v-if="tasks.message !== 'Извините для вас тест не сгенерирован!' && isEmail === ''">
<p>Для вас уже доступен сгенерированный вариант</p>
</div>
<div v-if="tasks.message !== 'Извините для вас тест не сгенерирован!' && isEmail === ''">
<div class="card mt-4">
<div class="card-body">
<h3 class="card-title mb-3">Отправка ответа</h3>
<div v-if="fileUploading !== 'http://192.168.1.3:8000/test_generatorundefined'">
<ul class="list-inline">
<li class="list-inline-item">
<div>Файл уже загружен</div>
</li>
<li class="list-inline-item">
<a :href="fileUploading">Решение</a>
</li>
<div>Вы можете обновить свой ответ, отправив новый файл.</div>
</ul>
</div>
<div class="input-group">
<input type="file" class="form-control" id="file" ref="file" v-on:change="handleFileUpload()">
<button class="btn btn-outline-secondary" type="button" @click="submitFile()">
Отправить ответ
</button>
</div>
<div class="mt-2">
{{fileUploadingMessage}}
</div>
</div>
</div>
<div class="card mt-4">
<div class="card-body">
<h3 class="card-title">Сгенерированный вариант</h3>
<div v-for="task in tasks.data">
<div class="card mt-4">
<div class="card-body">
<h5 class="card-subtitle mb-2 text-muted">Задание {{ task.task_number }}</h5>
<ul class="list-group list-group-flush">
<li class="list-group-item">
<h5 class="card-title">Необходимо вычислить</h5>
<div class="d-flex justify-content-center mt-5">
<vue-mathjax :formula="'$$' + task.example + '$$'"></vue-mathjax>
</div>
</li>
<!-- <li class="list-group-item">
<h5 class="card-title">Ответ</h5>
<div class="d-flex justify-content-center mt-5">
<vue-mathjax :formula="'$$' + task.answer + '$$'"></vue-mathjax>
</div>
</li> -->
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'Main',
data() {
return {
profile: [],
tasks: [],
tokeno: '',
isGeneratedTasks: false,
processGenerate: '',
isEmail: '',
file: '',
isFileUploading: '',
fileUploading: '',
fileUploadingMessage: ''
}
},
mounted() {
this.getTask(),
this.isFileUpload()
},
methods: {
async isFileUpload() {
this.$store.commit('setIsLoading', true)
await axios
.post('/users/student_decision/', {
headers: { 'Authorization': 'Token ' + this.$store.state.token }
})
.then(response => {
this.fileUploading = 'http://192.168.1.3:8000/test_generator' + response.data.filename
})
.catch(error => {
if (error.response) {
this.isFileUploading = error.response.data.message
}
console.log(error)
})
this.$store.commit('setIsLoading', false)
},
async submitFile() {
this.$store.commit('setIsLoading', true)
let formData = new FormData();
formData.append('decision', this.file);
await axios
.post('/test_generator/upload_decision/',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(response => {
this.fileUploadingMessage = response.data.message
this.isFileUpload()
})
.catch(error => {
if (error.response) {
this.fileUploadingMessage = error.response.data.message
}
});
this.$store.commit('setIsLoading', false)
},
handleFileUpload() {
this.file = this.$refs.file.files[0];
},
async getTask() {
this.$store.commit('setIsLoading', true)
await axios
.post('/test_generator/show_test/', {
headers: { 'Authorization': 'Token ' + this.$store.state.token }
})
.then(response => {
this.tasks = response.data
this.isGeneratedTasks = true
})
.catch(error => {
if (error.response) {
this.isEmail = error.response.data.detail
}
console.log(error)
this.isGeneratedTasks = false
})
this.$store.commit('setIsLoading', false)
},
async generateTask() {
this.$store.commit('setIsLoading', true)
this.processGenerate = 'Генерируется вариант'
await axios
.post('/test_generator/generate/', {
headers: { 'Authorization': 'Token ' + this.$store.state.token }
})
.then(response => {
this.profile = response.data
this.processGenerate = 'Вариант сгенерирован'
this.$router.push('/account')
})
.catch(error => {
console.log(error)
this.processGenerate = 'Ошибка'
})
this.$store.commit('setIsLoading', false)
}
}
}
</script>
<style scoped>
</style>
|
import { Component } from '@angular/core';
import { SkillsService } from 'src/app/services/skills.service';
import { Skills } from 'src/app/models/skills';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-new-skl',
templateUrl: './new-skl.component.html',
styleUrls: ['./new-skl.component.css']
})
export class NewSklComponent {
form: FormGroup;
constructor(private formBuilder: FormBuilder, private sklServ: SkillsService) {
this.form = this.formBuilder.group(
{
name: ['', [Validators.required, Validators.min(0), Validators.max(100)]],
percentage: ['', [Validators.required, Validators.min(0), Validators.max(100)]],
}
)
}
ngOnInit(): void {
}
//Declaraciones
get Name() {
return this.form.get('name');
}
get Percentage() {
return this.form.get('percentage');
}
//Validaciones
get NameValid() {
return this.Name?.touched && !this.Name.valid;
}
get PercentageValid() {
return this.Percentage?.touched && !this.Percentage.valid;
}
onNew(): void {
if (this.form.valid) {
const skl = new Skills(this.form.value.name, this.form.value.percentage);
this.sklServ.save(skl).subscribe(data => {
alert("Habilidad añadida");
window.location.reload();
}, error => {
alert("Error");
this.form.reset();
});
}
}
clean(): void {
this.form.reset();
}
}
|
// [!region contract]
#[starknet::interface]
pub trait ISimpleContract<TContractState> {
fn get_value(self: @TContractState) -> u32;
fn get_owner(self: @TContractState) -> starknet::ContractAddress;
fn set_value(ref self: TContractState, value: u32);
}
#[starknet::contract]
pub mod SimpleContract {
use starknet::{get_caller_address, ContractAddress};
#[storage]
struct Storage {
value: u32,
owner: ContractAddress
}
#[constructor]
pub fn constructor(ref self: ContractState, initial_value: u32) {
self.value.write(initial_value);
self.owner.write(get_caller_address());
}
#[abi(embed_v0)]
pub impl SimpleContractImpl of super::ISimpleContract<ContractState> {
fn get_value(self: @ContractState) -> u32 {
self.value.read()
}
fn get_owner(self: @ContractState) -> ContractAddress {
self.owner.read()
}
fn set_value(ref self: ContractState, value: u32) {
assert(self.owner.read() == get_caller_address(), 'Not owner');
self.value.write(value);
}
}
}
// [!endregion contract]
// [!region tests]
#[cfg(test)]
mod tests {
// Import the interface and dispatcher to be able to interact with the contract.
use super::{SimpleContract, ISimpleContractDispatcher, ISimpleContractDispatcherTrait};
// Import the deploy syscall to be able to deploy the contract.
use starknet::{SyscallResultTrait, syscalls::deploy_syscall};
use starknet::{
ContractAddress, get_caller_address, get_contract_address, contract_address_const
};
// Use starknet test utils to fake the contract_address
use starknet::testing::set_contract_address;
// Deploy the contract and return its dispatcher.
fn deploy(initial_value: u32) -> ISimpleContractDispatcher {
// Declare and deploy
let (contract_address, _) = deploy_syscall(
SimpleContract::TEST_CLASS_HASH.try_into().unwrap(),
0,
array![initial_value.into()].span(),
false
)
.unwrap_syscall();
// Return the dispatcher.
// The dispatcher allows to interact with the contract based on its interface.
ISimpleContractDispatcher { contract_address }
}
#[test]
fn test_deploy() {
let initial_value: u32 = 10;
let contract = deploy(initial_value);
assert_eq!(contract.get_value(), initial_value);
assert_eq!(contract.get_owner(), get_contract_address());
}
#[test]
fn test_set_as_owner() {
// Fake the contract address to owner
let owner = contract_address_const::<'owner'>();
set_contract_address(owner);
// When deploying the contract, the owner is the caller.
let contract = deploy(10);
assert_eq!(contract.get_owner(), owner);
// As the current caller is the owner, the value can be set.
let new_value: u32 = 20;
contract.set_value(new_value);
assert_eq!(contract.get_value(), new_value);
}
#[test]
#[should_panic]
fn test_set_not_owner() {
let owner = contract_address_const::<'owner'>();
set_contract_address(owner);
let contract = deploy(10);
// Fake the contract address to another address
let not_owner = contract_address_const::<'not owner'>();
set_contract_address(not_owner);
// As the current caller is not the owner, the value cannot be set.
let new_value: u32 = 20;
contract.set_value(new_value);
// Panic expected
}
#[test]
#[available_gas(150000)]
fn test_deploy_gas() {
deploy(10);
}
}// [!endregion tests]
// [!region tests_with_state]
#[cfg(test)]
mod tests_with_states {
// Only import the contract
use super::SimpleContract;
// For accessing storage variables and entrypoints,
// we must import the contract member state traits and implementation.
use SimpleContract::{
SimpleContractImpl, valueContractMemberStateTrait, ownerContractMemberStateTrait
};
use starknet::contract_address_const;
use starknet::testing::set_caller_address;
use core::num::traits::Zero;
#[test]
fn test_standalone_state() {
let mut state = SimpleContract::contract_state_for_testing();
// As no contract was deployed, the constructor was not called on the state
// - with valueContractMemberStateTrait
assert_eq!(state.value.read(), 0);
// - with SimpleContractImpl
assert_eq!(state.get_value(), 0);
assert_eq!(state.owner.read(), Zero::zero());
// We can still directly call the constructor to initialize the state.
let owner = contract_address_const::<'owner'>();
// We are not setting the contract address but the caller address here,
// as we are not deploying the contract but directly calling the constructor function.
set_caller_address(owner);
let initial_value: u32 = 10;
SimpleContract::constructor(ref state, initial_value);
assert_eq!(state.get_value(), initial_value);
assert_eq!(state.get_owner(), owner);
// As the current caller is the owner, the value can be set.
let new_value: u32 = 20;
state.set_value(new_value);
assert_eq!(state.get_value(), new_value);
}
// But we can also deploy the contract and interact with it using the dispatcher
// as shown in the previous tests, and still use the state for testing.
use super::{ISimpleContractDispatcher, ISimpleContractDispatcherTrait};
use starknet::{
ContractAddress, SyscallResultTrait, syscalls::deploy_syscall, testing::set_contract_address
};
#[test]
fn test_state_with_contract() {
let owner = contract_address_const::<'owner'>();
let not_owner = contract_address_const::<'not owner'>();
// Deploy as owner
let initial_value: u32 = 10;
set_contract_address(owner);
let (contract_address, _) = deploy_syscall(
SimpleContract::TEST_CLASS_HASH.try_into().unwrap(),
0,
array![initial_value.into()].span(),
false
)
.unwrap_syscall();
let mut contract = ISimpleContractDispatcher { contract_address };
// create the state
// - Set back as not owner
set_contract_address(not_owner);
let mut state = SimpleContract::contract_state_for_testing();
// - Currently, the state is not 'linked' to the contract
assert_ne!(state.get_value(), initial_value);
assert_ne!(state.get_owner(), owner);
// - Link the state to the contract by setting the contract address
set_contract_address(contract.contract_address);
assert_eq!(state.get_value(), initial_value);
assert_eq!(state.get_owner(), owner);
// Mutating the state from the contract change the testing state
set_contract_address(owner);
let new_value: u32 = 20;
contract.set_value(new_value);
set_contract_address(contract.contract_address);
assert_eq!(state.get_value(), new_value);
// Mutating the state from the testing state change the contract state
set_caller_address(owner);
state.set_value(initial_value);
assert_eq!(contract.get_value(), initial_value);
// Directly mutating the state allows to change state
// in ways that are not allowed by the contract, such as changing the owner.
let new_owner = contract_address_const::<'new owner'>();
state.owner.write(new_owner);
assert_eq!(contract.get_owner(), new_owner);
set_caller_address(new_owner);
state.set_value(new_value);
assert_eq!(contract.get_value(), new_value);
}
}
}// [!endregion tests_with_state]
|
package adPortalstepdefinitions;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import adPortalManagers.PageObjectManager;
import adPortalManagers.WebDriverManager;
import adPortalUtilities.AdPortalScreenShots;
import adportalPageObjects.LogInPage;
import adportalPageObjects.RequestDashBoardPage;
import adportalPageObjects.SignUpPage;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import dataProvider.ConfigFileReader;
public class AdPortal_NewUser_FAQ_Link_Functionality_StepDefinition {
WebDriver driver;
ConfigFileReader configFileReader;
JavascriptExecutor executor;
LogInPage logInPage;
SignUpPage signUpPage;
RequestDashBoardPage requestDashBoardPage;
PageObjectManager pageObjectManager;
WebDriverManager webDriverManager;
AdPortalScreenShots adPortalScreenShots;
@Given("^I am a new SSU user to Ad Portal$")
public void new_SSU_User_SignUp() throws InterruptedException {
webDriverManager = new WebDriverManager();
driver = WebDriverManager.getDriver();
driver.manage().timeouts().implicitlyWait(4000, TimeUnit.SECONDS);
configFileReader = new ConfigFileReader();
pageObjectManager = new PageObjectManager(driver);
configFileReader.getApplicationUrl();
signUpPage = pageObjectManager.getSignUpPage();
signUpPage.navigateTo_SignUpPage();
signUpPage.enter_FirstName("Media");
signUpPage.enter_LastName("Solutions");
signUpPage.enter_BusinessName("Spectrum Reach");
signUpPage.enter_ZipCode("80111");
signUpPage.enter_PhoneNumber("1234567890");
signUpPage.enter_Email("QATestEmail@charter.com");
signUpPage.enter_ConfirmEmail("QATestEmail@charter.com");
signUpPage.enter_Password("Spectrum123!");
signUpPage.eneter_ConfirmPassword("Spectrum123!");
signUpPage = pageObjectManager.getSignUpPage();
signUpPage.click_CheckBox();
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.close();
driver.switchTo().window(tabs.get(0));
requestDashBoardPage = new RequestDashBoardPage(driver);
signUpPage.click_nextStep();
Thread.sleep(17000);
}
@When("^I log in using newly signed up log in email and password$")
public void user_LogIn_Using_New_Email_And_Password() {
webDriverManager = new WebDriverManager();
driver = WebDriverManager.getDriver();
configFileReader = new ConfigFileReader();
pageObjectManager = new PageObjectManager(driver);
signUpPage = pageObjectManager.getSignUpPage();
signUpPage.navigateTo_SignUpPage();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("SignUp Page is still loading");
e.printStackTrace();
}
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,100)");
signUpPage.explicitly_Wait_ForLogInLink();
signUpPage.click_Login();
logInPage = pageObjectManager.getLogInPage();
logInPage.enter_LogInEmail("QATestEmail@charter.com");
logInPage.enter_LogInPassword("Spectrum123!");
logInPage.clickLogIn();
}
@Then("^I should land on the AdPortal new dashboard$")
public void requestDashBoard_Verification() {
requestDashBoardPage = new RequestDashBoardPage(driver);
requestDashBoardPage.explicitly_Wait_For_FAQ_Links();
adPortalScreenShots = new AdPortalScreenShots(driver);
adPortalScreenShots.takeScreenShotNewDashBoardView_FAQ_Link();
}
@Then("^I should see the FAQ links$")
public void verify_Presence_Of_FAQ_Links() {
requestDashBoardPage = new RequestDashBoardPage(driver);
requestDashBoardPage.verify_FAQ_Header();
}
@Then("^When I select the links the links should open the relevant FAQ page in a new browser tab$")
public void open_FAQ_Page() {
requestDashBoardPage = new RequestDashBoardPage(driver);
requestDashBoardPage.click_LinkText();
}
}
|
import { CssBaseline, Zoom } from "@mui/material"
import { SnackbarProvider } from "notistack"
import React from "react"
import ReactDOM from "react-dom/client"
import { BrowserRouter, Route, Routes } from "react-router-dom"
import App from "./App"
import Home from "./routes/Home"
import Preferences from "./routes/Preferences"
import Register from "./routes/Register"
import Scan from "./routes/Scan"
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<CssBaseline />
<SnackbarProvider
maxSnack={3}
anchorOrigin={{ vertical: "top", horizontal: "center" }}
TransitionComponent={Zoom}
>
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}>
<Route index element={<Home />} />
<Route path="/scan" element={<Scan />} />
<Route path="/register" element={<Register />} />
<Route path="/preferences" element={<Preferences />} />
</Route>
</Routes>
</BrowserRouter>
</SnackbarProvider>
</React.StrictMode>
)
|
Donut Math Code -
k;double sin()
,cos();main(){float A=
0,B=0,i,j,z[1760];char b[
1760];printf("\x1b[2J");for(;;
){memset(b,32,1760);memset(z,0,7040)
;for(j=0;6.28>j;j+=0.07)for(i=0;6.28
>i;i+=0.02){float c=sin(i),d=cos(j),e=
sin(A),f=sin(j),g=cos(A),h=d+2,D=1/(c*
h*e+f*g+5),l=cos (i),m=cos(B),n=s\
in(B),t=c*h*g-f* e;int x=40+30*D*
(l*h*m-t*n),y= 12+15*D*(l*h*n
+t*m),o=x+80*y, N=8*((f*e-c*d*g
)*m-c*d*e-f*g-l *d*n);if(22>y&&
y>0&&x>0&&80>x&&D>z[o]){z[o]=D;;;b[o]=
".,-~:;=!*#$@"[N>0?N:0];}}/*#****!!-*/
printf("\x1b[H");for(k=0;1761>k;k++)
putchar(k%80?b[k]:10);A+=0.04;B+=
0.02;}}/*****####*******!!=;:~
~::==!!!**********!!!==::-
.,~~;;;========;;;:~-.
..,--------,*/
Donut Math Pseudocode -
const float theta_spacing = 0.07;
const float phi_spacing = 0.02;
const float R1 = 1;
const float R2 = 2;
const float K2 = 5;
// Calculate K1 based on screen size: the maximum x-distance occurs
// roughly at the edge of the torus, which is at x=R1+R2, z=0. we
// want that to be displaced 3/8ths of the width of the screen, which
// is 3/4th of the way from the center to the side of the screen.
// screen_width*3/8 = K1*(R1+R2)/(K2+0)
// screen_width*K2*3/(8*(R1+R2)) = K1
const float K1 = screen_width*K2*3/(8*(R1+R2));
render_frame(float A, float B) {
// precompute sines and cosines of A and B
float cosA = cos(A), sinA = sin(A);
float cosB = cos(B), sinB = sin(B);
char output[0..screen_width, 0..screen_height] = ' ';
float zbuffer[0..screen_width, 0..screen_height] = 0;
// theta goes around the cross-sectional circle of a torus
for (float theta=0; theta < 2*pi; theta += theta_spacing) {
// precompute sines and cosines of theta
float costheta = cos(theta), sintheta = sin(theta);
// phi goes around the center of revolution of a torus
for(float phi=0; phi < 2*pi; phi += phi_spacing) {
// precompute sines and cosines of phi
float cosphi = cos(phi), sinphi = sin(phi);
// the x,y coordinate of the circle, before revolving (factored
// out of the above equations)
float circlex = R2 + R1*costheta;
float circley = R1*sintheta;
// final 3D (x,y,z) coordinate after rotations, directly from
// our math above
float x = circlex*(cosB*cosphi + sinA*sinB*sinphi)
- circley*cosA*sinB;
float y = circlex*(sinB*cosphi - sinA*cosB*sinphi)
+ circley*cosA*cosB;
float z = K2 + cosA*circlex*sinphi + circley*sinA;
float ooz = 1/z; // "one over z"
// x and y projection. note that y is negated here, because y
// goes up in 3D space but down on 2D displays.
int xp = (int) (screen_width/2 + K1*ooz*x);
int yp = (int) (screen_height/2 - K1*ooz*y);
// calculate luminance. ugly, but correct.
float L = cosphi*costheta*sinB - cosA*costheta*sinphi -
sinA*sintheta + cosB*(cosA*sintheta - costheta*sinA*sinphi);
// L ranges from -sqrt(2) to +sqrt(2). If it's < 0, the surface
// is pointing away from us, so we won't bother trying to plot it.
if (L > 0) {
// test against the z-buffer. larger 1/z means the pixel is
// closer to the viewer than what's already plotted.
if(ooz > zbuffer[xp,yp]) {
zbuffer[xp, yp] = ooz;
int luminance_index = L*8;
// luminance_index is now in the range 0..11 (8*sqrt(2) = 11.3)
// now we lookup the character corresponding to the
// luminance and plot it in our output:
output[xp, yp] = ".,-~:;=!*#$@"[luminance_index];
}
}
}
}
// now, dump output[] to the screen.
// bring cursor to "home" location, in just about any currently-used
// terminal emulation mode
printf("\x1b[H");
for (int j = 0; j < screen_height; j++) {
for (int i = 0; i < screen_width; i++) {
putchar(output[i,j]);
}
putchar('\n');
}
}
Donut Math Script -
(function() {
var _onload = function() {
var pretag = document.getElementById('d');
var canvastag = document.getElementById('canvasdonut');
var tmr1 = undefined, tmr2 = undefined;
var A=1, B=1;
var asciiframe=function() {
var b=[];
var z=[];
A += 0.07;
B += 0.03;
var cA=Math.cos(A), sA=Math.sin(A),
cB=Math.cos(B), sB=Math.sin(B);
for(var k=0;k<1760;k++) {
b[k]=k%80 == 79 ? "\n" : " ";
z[k]=0;
}
for(var j=0;j<6.28;j+=0.07) { // j <=> theta
var ct=Math.cos(j),st=Math.sin(j);
for(i=0;i<6.28;i+=0.02) { // i <=> phi
var sp=Math.sin(i),cp=Math.cos(i),
h=ct+2, // R1 + R2*cos(theta)
D=1/(sp*h*sA+st*cA+5), // this is 1/z
t=sp*h*cA-st*sA; // this is a clever factoring of some of the terms in x' and y'
var x=0|(40+30*D*(cp*h*cB-t*sB)),
y=0|(12+15*D*(cp*h*sB+t*cB)),
o=x+80*y,
N=0|(8*((st*sA-sp*ct*cA)*cB-sp*ct*sA-st*cA-cp*ct*sB));
if(y<22 && y>=0 && x>=0 && x<79 && D>z[o])
{
z[o]=D;
b[o]=".,-~:;=!*#$@"[N>0?N:0];
}
}
}
pretag.innerHTML = b.join("");
};
window.anim1 = function() {
if(tmr1 === undefined) {
tmr1 = setInterval(asciiframe, 50);
} else {
clearInterval(tmr1);
tmr1 = undefined;
}
};
// This is a reimplementation according to my math derivation on the page
var R1 = 1;
var R2 = 2;
var K1 = 150;
var K2 = 5;
var canvasframe=function() {
var ctx = canvastag.getContext('2d');
ctx.fillStyle='#000';
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
if(tmr1 === undefined) { // only update A and B if the first animation isn't doing it already
A += 0.07;
B += 0.03;
}
// precompute cosines and sines of A, B, theta, phi, same as before
var cA=Math.cos(A), sA=Math.sin(A),
cB=Math.cos(B), sB=Math.sin(B);
for(var j=0;j<6.28;j+=0.3) { // j <=> theta
var ct=Math.cos(j),st=Math.sin(j); // cosine theta, sine theta
for(i=0;i<6.28;i+=0.1) { // i <=> phi
var sp=Math.sin(i),cp=Math.cos(i); // cosine phi, sine phi
var ox = R2 + R1*ct, // object x, y = (R2,0,0) + (R1 cos theta, R1 sin theta, 0)
oy = R1*st;
var x = ox*(cB*cp + sA*sB*sp) - oy*cA*sB; // final 3D x coordinate
var y = ox*(sB*cp - sA*cB*sp) + oy*cA*cB; // final 3D y
var ooz = 1/(K2 + cA*ox*sp + sA*oy); // one over z
var xp=(150+K1*ooz*x); // x' = screen space coordinate, translated and scaled to fit our 320x240 canvas element
var yp=(120-K1*ooz*y); // y' (it's negative here because in our output, positive y goes down but in our 3D space, positive y goes up)
// luminance, scaled back to 0 to 1
var L=0.7*(cp*ct*sB - cA*ct*sp - sA*st + cB*(cA*st - ct*sA*sp));
if(L > 0) {
ctx.fillStyle = 'rgba(255,255,255,'+L+')';
ctx.fillRect(xp, yp, 1.5, 1.5);
}
}
}
}
window.anim2 = function() {
if(tmr2 === undefined) {
tmr2 = setInterval(canvasframe, 50);
} else {
clearInterval(tmr2);
tmr2 = undefined;
}
};
asciiframe();
canvasframe();
}
if(document.all)
window.attachEvent('onload',_onload);
else
window.addEventListener("load",_onload,false);
})();
|
/*
* Name: Carl Markowski
* CS1450 M/W
* Due: Jan 26,2022
* Assignment 1
* This program will display my ability to manipulate arrays and use files
*/
import java.util.Random;
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Arrays;
public class MarkowskiCarlAssignment1 {
public static void main(String[] args) throws IOException {
// Creation of the file "assignment1.txt" and the creation of the print function
File fileName = new File("assignment1.txt");
PrintWriter outputFile = new PrintWriter(fileName);
// Filling the size variables with random integers and printing the numbers to
// the console and file
Random r = new Random();
int size1 = (int) (r.nextInt(15));
int size2 = (int) (r.nextInt(15));
System.out.println("Size1 = " + size1);
System.out.println("Size2 = " + size2);
// Creation of the array using the two sizes from the previous random function
// Using a for loop to fill the array with random integers and write them to the
// console and to the file
int[] array = new int[size1 + size2];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 49);
System.out.println(array[i]);
outputFile.println(array[i]);
}
System.out.println("Read " + size1 + " values from file. Placing values into the first array.");
System.out.println("Read " + size2 + " values from file. Placing values into the second array.");
outputFile.close();
// Scanner setup to read from file and place "size1" integers into "array1"
Scanner readFile = new Scanner(fileName);
// While loop used to fill "array1" with the integers from the file
int[] array1 = new int[size1];
int num = 0;
while (readFile.hasNextInt() && num < array1.length) {
array1[num] = readFile.nextInt();
num++;
}
// While loop used to fill "array2" with the integers from the file
int[] array2 = new int[size2];
int num2 = 0;
while (readFile.hasNextInt() && num2 < array2.length) {
array2[num2] = readFile.nextInt();
num2++;
}
readFile.close();
// Sort() method used to sort the two arrays before being merged together
Arrays.sort(array1);
Arrays.sort(array2);
// Counters made to loop through the different arrays
// New array created to be used for merged and sorted values
int max = 0;
int array1Index = 0;
int array2Index = 0;
int mergedArrayIndex = 0;
int arraySize = size1 + size2;
int[] mergedArray = new int[arraySize];
// While loop and embedded if else statements used to compare values in "array1"
// and "array2" and
// put them into the "mergedArray"
while (array1Index < size1 && array2Index < size2) {
if (array1[array1Index] < array2[array2Index]) {
mergedArray[mergedArrayIndex] = array1[array1Index];
array1Index++;
} else if (array1[array1Index] > array2[array2Index]) {
mergedArray[mergedArrayIndex] = array2[array2Index];
array2Index++;
} else if (array1[array1Index] == array2[array2Index]) {
mergedArray[mergedArrayIndex] = array1[array1Index];
mergedArrayIndex++;
mergedArray[mergedArrayIndex] = array2[array2Index];
array1Index++;
array2Index++;
}
mergedArrayIndex++;
}
// While loop used to iterate through any remaining values in "array1" and
// compare them
// to the mergedArray
while (array1Index < size1) {
mergedArray[mergedArrayIndex] = array1[array1Index];
array1Index++;
mergedArrayIndex++;
}
// While loop used to iterate through any remaining values in "array2" and
// comare them
// to the mergedArray
while (array2Index < size2) {
mergedArray[mergedArrayIndex] = array2[array2Index];
array2Index++;
mergedArrayIndex++;
}
System.out.println("\nRandom values sotred in order in merged array");
// For loop used to print put the values in mergedArray
for (int i = 0; i < mergedArray.length; i++) {
System.out.println(mergedArray[i]);
}
System.out.println("File is in directory: " + fileName.getAbsolutePath());
}
}
|
functions.php
function myfilter_2() {
$category_filter = $_POST['categoryfilter'];
$taxonomy_filter = $_POST['taxonomyfilter'];
$director_filter = $_POST['directorfilter'];
$args = array(
'post_type' => 'movies',
'posts_per_page' => -1,
'tax_query' => array(),
);
if (!empty($category_filter)) {
$args['tax_query'][] = array(
'taxonomy' => 'movies_taxonomy',
'field' => 'id',
'terms' => $category_filter,
);
}
if (!empty($taxonomy_filter)) {
$args['tax_query'][] = array(
'taxonomy' => 'location_taxonomy',
'field' => 'id',
'terms' => $taxonomy_filter,
);
}
if (!empty($director_filter)) {
$args['tax_query'][] = array(
'taxonomy' => 'director_taxonomy',
'field' => 'id',
'terms' => $director_filter,
);
}
$the_query = new WP_Query($args);
if ($the_query->have_posts()) :
while ($the_query->have_posts()) : $the_query->the_post();
echo '<h2>' . get_the_title() . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo '<p>No posts found</p>';
endif;
die();
}
add_action('wp_ajax_myfilter_2', 'myfilter_2');
add_action('wp_ajax_nopriv_myfilter_2', 'myfilter_2');
template-page.php
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter-3">
<?php
if( $terms = get_terms( array( 'taxonomy' => 'movies_taxonomy', 'orderby' => 'name' ) ) ) :
echo '<select name="categoryfilter"><option value="">Select Category...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
endforeach;
echo '</select>';
endif;
if( $terms_2 = get_terms( array( 'taxonomy' => 'location_taxonomy', 'orderby' => 'name' ) ) ) :
echo '<select name="taxonomyfilter"><option value="">Select Taxonomy...</option>';
foreach ( $terms_2 as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
endforeach;
echo '</select>';
endif;
if( $terms_3 = get_terms( array( 'taxonomy' => 'director_taxonomy', 'orderby' => 'name' ) ) ) :
echo '<select name="directorfilter"><option value="">Select Director ...</option>';
foreach ( $terms_3 as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
endforeach;
echo '</select>';
endif;
?>
<button>Apply filter</button>
<input type="hidden" name="action" value="myfilter_2">
</form>
<div id="response">
<?php
$args = array(
'post_type' => 'movies',
'posts_per_page' => -1
);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; endif; ?>
<?php wp_reset_postdata(); ?>
</div>
js file
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#filter-3').submit(function(){
var filter = $('#filter-3');
$.ajax({
url: filter.attr('action'),
data: filter.serialize(),
type: filter.attr('method'),
success:function(data){
$('#response').html(data);
}
});
return false;
});
});
</script>
|
<!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 rel="stylesheet" href="css/master.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@300;400;600&display=swap" rel="stylesheet">
<title>Float</title>
</head>
<body>
<!-- Intestazione Titolo e sottotilo -->
<header>
<h1>
Meet our Team
</h1>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla fugit consequatur eligendi magni dolorem fuga debitis architecto culpa sed deserunt! Dolores cumque fuga minus perferendis laboriosam optio est ea corporis.
</p>
</header>
<!-- Sezione centrale con riquadri -->
<main>
<!-- Prima fila di colonne -->
<section class="structure">
<div class="row">
<div class="colonna">
<div class="contenuto-colonna">
<img src="img/male1.png" alt="male1">
<span>MARCO BIANCHI</span>
<p>Designer</p>
<a class="email" href="email">marcobianchi@team.com</a>
</div>
</div>
<div class="colonna">
<div class="contenuto-colonna">
<img src="img/female1.png" alt="famle1">
<span>LAURA ROSSI</span>
<p>Front-end Developer</p>
<a class="email"href="email">laurarossi@team.com</a>
</div>
</div>
<div class="colonna">
<div class="contenuto-colonna">
<img src="img/male2.png" alt="male2">
<span>GIORGIO VERDI</span>
<p>Back-end Developer</p>
<a class="email"href="email">diorgioverdi@team.com</a>
</div>
</div>
</div>
</section>
<!-- Seconda fila di colonne -->
<section class="structure2">
<div class="row">
<div class="row">
<div class="colonna2">
<div class="contenuto-colonna">
<img src="img/female2.png" alt="female2">
<span>MARTA IPSUM</span>
<p>SEO Specialist</p>
<a class="email" href="email">martaipsum@team.com</a>
</div>
</div>
<div class="colonna2">
<div class="contenuto-colonna">
<img src="img/male3.png" alt="male3">
<span>ROBERTO LOREM</span>
<p>Project Manager</p>
<a class="email"href="email">robertolorem@team.com</a>
</div>
</div>
<div class="colonna2">
<div class="contenuto-colonna">
<img src="img/female3.png" alt="female3">
<span>DANIELA AMET</span>
<p>Analyst</p>
<a class="email"href="email">danielaamet@team.com</a>
</div>
</div>
</div>
</section>
</main>
</body>
</html>
|
import dlt
from dlt.sources.helpers import requests
@dlt.source(max_table_nesting=2)
def source(pokemon_api_url: str):
""""""
# note that we deselect `pokemon_list` - we do not want it to be loaded
@dlt.resource(write_disposition="replace", selected=False)
def pokemon_list():
"""Retrieve a first page of Pokemons and yield it. We do not retrieve all the pages in this example"""
yield requests.get(pokemon_api_url).json()["results"]
# transformer that retrieves a list of objects in parallel
@dlt.transformer
def pokemon(pokemons):
"""Yields details for a list of `pokemons`"""
# @dlt.defer marks a function to be executed in parallel
# in a thread pool
@dlt.defer
def _get_pokemon(_pokemon):
return requests.get(_pokemon["url"]).json()
# call and yield the function result normally, the @dlt.defer takes care of parallelism
for _pokemon in pokemons:
yield _get_pokemon(_pokemon)
# a special case where just one item is retrieved in transformer
# a whole transformer may be marked for parallel execution
@dlt.transformer
@dlt.defer
def species(pokemon_details):
"""Yields species details for a pokemon"""
species_data = requests.get(pokemon_details["species"]["url"]).json()
# link back to pokemon so we have a relation in loaded data
species_data["pokemon_id"] = pokemon_details["id"]
# just return the results, if you yield,
# generator will be evaluated in main thread
return species_data
# create two simple pipelines with | operator
# 1. send list of pokemons into `pokemon` transformer to get pokemon details
# 2. send pokemon details into `species` transformer to get species details
# NOTE: dlt is smart enough to get data from pokemon_list and pokemon details once
return (
pokemon_list | pokemon,
pokemon_list | pokemon | species
)
if __name__ == "__main__":
# build duck db pipeline
pipeline = dlt.pipeline(
pipeline_name="pokemon", destination="duckdb", dataset_name="pokemon_data"
)
# the pokemon_list resource does not need to be loaded
load_info = pipeline.run(source("https://pokeapi.co/api/v2/pokemon"))
print(load_info)
|
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) {
return null;
}
return this.items.pop();
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
class QueueUsingStack {
constructor() {
this.stack1 = new Stack();
this.stack2 = new Stack();
}
enqueue(item){
while(!this.isEmpty1()){
this.stack2.push(this.stack1.pop())
}
this.stack1.push(item);
while(!this.isEmpty2()){
this.stack1.push(this.stack2.pop());
}
}
dequeue(){
return this.stack1.pop();
}
peek(){
return this.stack1.peek();
}
isEmpty1(){
return this.stack1.isEmpty()
}
isEmpty2(){
return this.stack2.isEmpty();
}
}
const queue = new QueueUsingStack();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);
console.log(queue.peek());
console.log(queue.dequeue());
console.log(queue.peek());
console.log(queue.dequeue());
console.log(queue.peek());
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script>
let search_form = {
init: function(){
$('#search_btn').click(function(){
$('#search_form').attr({
method: 'post',
action: '/marker/search'
});
$('#search_form').submit();
});
}
};
$(function(){
search_form.init();
});
</script>
<!-- partial -->
<div class="content-wrapper">
<div class="row">
<div class="col-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Search</h4>
<form id="search_form" class="form-inline">
<label for="title" style="margin-right: 10px">Title</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="title" name="title" placeholder="Input Title" value="${ms.title}">
<label for="writer" style="margin: 0 10px">Writer</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="writer" name="writer" placeholder="Input Writer" value="${ms.writer}">
<label for="title" style="margin: 0 10px">Keyword</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="keyword" name="keyword" placeholder="Input Keyword" value="${ms.keyword}">
<label for="star" style="margin: 0 10px">Star</label>
<select id="star" name="star" value="${ms.star}" class="form-control mb-2 mr-2">
<option value="">전체</option>
<option value="1" <c:if test="${ms.star==1}">selected</c:if> >1</option>
<option value="2" <c:if test="${ms.star==2}">selected</c:if>>2</option>
<option value="3" <c:if test="${ms.star==3}">selected</c:if>>3</option>
<option value="4" <c:if test="${ms.star==4}">selected</c:if>>4</option>
<option value="5" <c:if test="${ms.star==5}">selected</c:if>>5</option>
</select>
<button type="button" id="search_btn" class="btn btn-primary mb-2" style="margin-left: 20px">Search</button>
</form>
</div>
</div>
</div>
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Marker List</h4>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>IMG</th>
<th>ID</th>
<th>Title</th>
<th>Lat</th>
<th>Lng</th>
<th>Star</th>
<th>Detail</th>
<th>Writer</th>
<th>Keyword</th>
</tr>
</thead>
<tbody>
<c:forEach var="obj" items="${marker}">
<tr>
<td class="py-1"><img src="/uimg/${obj.img}"></td>
<td><a href="/marker/detail?id=${obj.id}">${obj.id}</a></td>
<td>${obj.title}</td>
<td>${obj.lat}</td>
<td>${obj.lng}</td>
<td>${obj.star}</td>
<td>${obj.detail}</td>
<td>${obj.writer}</td>
<td>${obj.keyword}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
|
很有意思的题。
给定 $n$ 张卡,第 $i$ 张的价格为 $c_i$
你有两种方式获得卡牌:
- 随机抽一张卡,花费为 $x$,如果得到了一个已经有的卡,那么返还 $\frac{x}{2}$
- 直接购买一张卡,花费为 $c_i$
求期望花多少集齐所有卡。
精度要求 $10^{-9}$
$n\le 100,\sum c_i\le 10^4$
----
### Solution
注意到决策一定是先抽卡,然后再全买。
那么我们可以改变决策的方式,变成选择一种方式获得卡:
- 按照规则随机抽卡。
- 随机抽一张没有的卡并获得,花费为这张卡的花费。
我们发现这种情况下的最优解和原问题等价。
同时,由于每次抽卡均为随机抽卡,所以假设我们抽了 $i$ 张不同的卡出来,那么这 $i$ 张卡也将是随机的卡,换而言之原集中每种大小为 $i$ 的子集被抽出的概率均相同!
现在考虑我们有 $i$ 张卡,期望花费多少得到 $i+1$ 张卡,不难发现期望花费为:$(\frac{n}{n-i}+1)\times \frac{x}{2}$,前面表示期望抽的次数,$+1$ 表示最后一次抽会额外附带 $\frac{x}{2}$ 的贡献。
修改规则后,我们发生如果剩余的权值和为 $c$,当前剩余 $k$ 个元素,那么问题等价于期望以 $\frac{c}{k}$ 的贡献得到一个元素,否则以 $(\frac{n}{k}+1)\times \frac{x}{2}$ 的贡献得到一个元素。
于是我们只需要比对这两者的大小,如果 $\frac{c}{k}$ 更大,那么以其期望产生贡献,否则以 $(\frac{n}{k}+1)\times \frac{x}{2}$ 产生贡献。
将每一种情况发生的概率乘以贡献求和即为答案。
注意到所有子集的等价性,保留 $k$ 个数使得权值和为 $c$ 的概率是可以算出来的,于是这个题就做完了,复杂度 $\mathcal O(n^2\sum c)$
- 其实就是为了保证精度,边算边除以 $\frac{1}{\binom{n}{k}}$,$\binom{n}{k}\leftarrow \binom{n}{k-1}\times \frac{n-k+1}{k}$
$Code:$
```cpp
#include<bits/stdc++.h>
using namespace std ;
#define rep( i, s, t ) for( register int i = (s); i <= (t); ++ i )
#define drep( i, s, t ) for( register int i = (t); i >= (s); -- i )
#define D long double
int gi() {
char cc = getchar() ; int cn = 0, flus = 1 ;
while( cc < '0' || cc > '9' ) { if( cc == '-' ) flus = - flus ; cc = getchar() ; }
while( cc >= '0' && cc <= '9' ) cn = cn * 10 + cc - '0', cc = getchar() ;
return cn * flus ;
}
const int N = 100 + 5 ;
int n, c[N], m ;
D ans, t, f[N][10005] ;
D Min(D x, D y) { return min(x, y) ; }
signed main()
{
n = gi(), t = gi(), t /= 2.0 ;
rep( i, 1, n ) c[i] = gi(), m += c[i] ; f[0][0] = 1 ;
rep( i, 1, n ) drep( k, 1, i ) rep( j, c[i], m )
f[k][j] = (f[k][j] + f[k - 1][j - c[i]] * k / (1.0 * (n - k + 1)) ) ;
rep( k, 1, n ) rep( j, 0, m )
ans = (ans + f[k][j] * Min( ((D)n / (D)k + 1) * t, (D)j / ((D)k)) ) ;
printf("%.10Lf\n", ans ) ;
return 0 ;
}
```
|
import { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { loginUserAction } from "../../../../redux/slice/users/usersSlice";
import "./css/Login.css";
import { FaGooglePlusG, FaFacebookF, FaGithub, FaLinkedinIn, FaEye, FaEyeSlash} from "react-icons/fa";
import Loading from "../../../Messages/Loading/Loading";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import ErrorMsg from "../../../Messages/SweetAlert/SweetError";
import { resetErrorAction } from "../../../../redux/slice/global/globalActions";
function Login() {
// Dispatch & Navigate
const dispatch = useDispatch();
const navigate = useNavigate();
// States
const [formData, setFormData] = useState({
email: "",
password: "",
});
const [show, setShow] = useState(false);
// Handlers
const handleToggle = () => setShow((show) => !show);
const onChangeHandler = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const onSubmitHandler = (e) => {
e.preventDefault();
dispatch(loginUserAction(formData));
setFormData({
email: "",
password: "",
});
};
// Get Data form Store
const { error, loading, userInfo } = useSelector(state => state?.users?.userAuth);
// ! Toastify
if(error) {
toast.error(error?.message);
dispatch(resetErrorAction());
};
// if(Object.keys(userInfo).length > 0) {
// toast.success("Logged in");
// // dispatch(resetSuccessAction());
// };
// ! Redirect
useEffect(()=>{
if (userInfo?.userFound || localStorage.getItem("userInfo")) window.location.href = "/";
}, [userInfo])
// useEffect(()=>{
// if (userInfo?.userFound) navigate("/admin");
// }, [userInfo]);
// useEffect(()=>{
// if (userInfo?.userFound?.isAdmin) navigate("/admin");
// else navigate("/customer-profile");
// }, [userInfo]);
return (
<>
<ToastContainer position="bottom-right" autoClose={5000} hideProgressBar={false} newestOnTop closeOnClick rtl={false}
pauseOnFocusLoss draggable={false} pauseOnHover={false} theme="light" />
<section className="login">
<div className="container">
<div className="login_cart">
<div className="login_left-panel">
{/* {error && <ErrorMsg message={error?.message} />} */}
<form onSubmit={onSubmitHandler}>
<h1>Login to your account</h1>
<div className="social-icons">
<a href="" className="icon"><FaGooglePlusG className="react-icons react-googlePlus" /></a>
<a href="" className="icon"><FaFacebookF className="react-icons react-facebook" /></a>
<a href="" className="icon"><FaGithub className="react-icons react-github" /></a>
<a href="" className="icon"><FaLinkedinIn className="react-icons react-linkEdin" /></a>
</div>
<div className="input-login">
<input type="email" placeholder="Email" name="email" value={formData.email} onChange={onChangeHandler} />
</div>
<div className="input-password">
<input type={show ? "text" : "password"} placeholder="Password" name="password" value={formData.password} onChange={onChangeHandler} />
<div className="show_hide" onClick={handleToggle}>
{show ? <FaEyeSlash className="react-icons react-show-hide" /> : <FaEye className="react-icons react-show-hide" /> }
</div>
</div>
<span>Don't have an account yet? <Link to="/register">Sign Up</Link></span>
{loading ? <Loading /> : <button>Sign In</button>}
</form>
</div>
<div className="login_right-panel"></div>
</div>
</div>
</section>
</>
);
}
export default Login;
|
import { useCallback, useLayoutEffect, useRef } from 'react';
export const useEvent = <T extends (...args: any[]) => any>(fn: T): T => {
const fnRef = useRef<T>(fn);
useLayoutEffect(() => {
fnRef.current = fn;
});
return useCallback((...args: Parameters<T>): ReturnType<T> => {
return fnRef.current.apply(null, args);
}, [fnRef,]) as T;
};
|
import React, { useState } from "react";
import { Link } from "react-router-dom";
import "./index.css";
import { GiHamburgerMenu } from "react-icons/gi";
import { IoMdClose } from "react-icons/io";
export default function Navbar() {
const [active, setActive] = useState(false);
return (
<nav className="navigation font-sans flex flex-col text-left sm:flex-row sm:text-left sm:justify-between py-6 px-10 w-[100%] bg-secondary text-white">
<div className="hidden md:block">
<Link href="/" className="text-3xl font-bold text-primary">
Isescholl
</Link>
</div>
<ul className="hidden md:flex md:flex-row md:justify-end md:gap-10 md:w-full">
<li>
<Link to={"/"}>Home</Link>
</li>
<li>
<Link to={"/class-detail"}>Classes</Link>
</li>
<li>
<Link to={"/student-will-die"}>Student Who Will Die</Link>
</li>
<li>
<Link to={"/student-will-marry"}>Student Who Will Marry</Link>
</li>
</ul>
{/* Responsive */}
<div className="flex items-center justify-between md:hidden">
<Link href="/" className="text-3xl font-bold text-primary">
Isescholl
</Link>
{active === true ? <IoMdClose className="text-[24px] cursor-pointer" onClick={() => setActive((prev) => !prev)} /> : <GiHamburgerMenu className="text-[24px] cursor-pointer" onClick={() => setActive((prev) => !prev)} />}
</div>
<ul className={`flex-col gap-2 mt-4 md:hidden ${active === true ? "flex" : "hidden"}`}>
<li>
<Link to={"/"}>Home</Link>
</li>
<li>
<Link to={"/class-detail"}>Classes</Link>
</li>
<li>
<Link to={"/student-will-die"}>Student Who Will Die</Link>
</li>
<li>
<Link to={"/student-will-marry"}>Student Who Will Marry</Link>
</li>
</ul>
</nav>
);
}
|
#ifndef LIBDC_ERROR_ERROR_H
#define LIBDC_ERROR_ERROR_H
/*
* Copyright 2021-2022 D'Arcy Smith.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifndef __STDC_LIB_EXT1__
typedef int errno_t;
#endif
/**
* Error states.
*/
typedef enum
{
DC_ERROR_NONE = 0, /**< There is no error */
DC_ERROR_CHECK, /**< The error is due to a failed check */
DC_ERROR_ERRNO, /**< The error is due to errno being set */
DC_ERROR_SYSTEM, /**< The error is from a library call that doesn't set errno
*/
DC_ERROR_USER, /**< The error is from a non-standard function */
}
dc_error_type;
struct dc_error;
struct dc_error *dc_error_create(bool report);
/**
*
* @param err
* @return
*/
bool dc_error_is_reporting(struct dc_error *err);
/**
*
* @param err
* @param on
*/
void dc_error_set_reporting(struct dc_error *err, bool on);
const char *dc_error_get_message(const struct dc_error *err);
/**
*
* @param err
*/
void dc_error_reset(struct dc_error *err);
/**
*
* @param err
*/
void dc_error_default_error_reporter(const struct dc_error *err);
/**
*
* @param err
* @param file_name
* @param function_name
* @param line_number
*/
void dc_error_check(struct dc_error *err, const char *file_name,
const char *function_name, size_t line_number);
/**
*
* @param err
* @param file_name
* @param function_name
* @param line_number
* @param err_code
*/
void dc_error_errno(struct dc_error *err, const char *file_name,
const char *function_name, size_t line_number,
errno_t err_code);
/**
*
* @param err
* @param file_name
* @param function_name
* @param line_number
* @param msg
* @param err_code
*/
void dc_error_system(struct dc_error *err, const char *file_name,
const char *function_name, size_t line_number,
const char *msg, int err_code);
/**
*
* @param err
* @param file_name
* @param function_name
* @param line_number
* @param msg
* @param err_code
*/
void dc_error_user(struct dc_error *err, const char *file_name,
const char *function_name, size_t line_number,
const char *msg, int err_code);
/**
*
* @param err
* @return
*/
bool dc_error_has_error(const struct dc_error *err);
/**
*
* @param err
* @return
*/
bool dc_error_has_no_error(const struct dc_error *err);
/**
*
* @param err
* @param code
* @return
*/
bool dc_error_is_errno(const struct dc_error *err, errno_t code);
errno_t dc_errno_get_errno(const struct dc_error *err);
#define DC_ERROR_RAISE_CHECK(err) \
dc_error_check((err), __FILE__, __func__, __LINE__)
#define DC_ERROR_RAISE_ERRNO(err, code) \
dc_error_errno((err), __FILE__, __func__, __LINE__, (code))
#define DC_ERROR_RAISE_SYSTEM(err, msg, code) \
dc_error_system((err), __FILE__, __func__, __LINE__, (msg), (code))
#define DC_ERROR_RAISE_USER(err, msg, code) \
dc_error_user((err), __FILE__, __func__, __LINE__, (msg), (code))
#ifdef __cplusplus
}
#endif
#endif // LIBDC_ERROR_ERROR_H
|
#include <iostream>
#include "StackEmptyException.h"
#pragma once
template<class data_type>
class stack
{
struct Node {
data_type value;
Node* link;
};
private:
int size_of_stack;
Node* top_element;
public:
stack();
bool empty();
void push(data_type element);
void pop();
data_type top();
int size();
};
template<class data_type> stack<data_type>::stack() {
size_of_stack = 0;
top_element = 0;
}
template<class data_type> bool stack<data_type>::empty() {
if (top_element== 0)return true;
else return false;
}
template<class data_type> void stack<data_type>::push(data_type element) {
Node* new_element = new Node();
new_element->value = element;
new_element->link = top_element;
top_element = new_element;
size_of_stack++;
}
template<class data_type> void stack<data_type>::pop() throw(StackEmptyException) {
try {
if (empty()) throw StackEmptyException("The stack is empty!");
Node* temp = top_element;
top_element = top_element->link;
delete(temp);
size_of_stack--;
}
catch (StackEmptyException e) {
cout << e.getMSG() << '\n';
}
}
template<class data_type> data_type stack<data_type>::top() throw(StackEmptyException) {
try {
if (empty()) throw StackEmptyException("The Stack is empty!");
return top_element->value;
}
catch (StackEmptyException e) {
cout << e.getMSG() << '\n';
}
}
template<class data_type> int stack<data_type>::size() {
return size_of_stack;
}
|
import {useState} from "react";
//style
import "./style.scss";
function CommentsList({onAddComment, comments, hash}) {
const [text, setText] = useState("");
const [color, setColor] = useState("");
const changeColor = (e) => {
setColor(e.target.value)
};
const changeTextarea = (e) => {
const value = e.target.value?.trimStart();
setText(value)
};
const addComment = (e) => {
e.preventDefault();
if (text?.length <= 2) {
return;
}
onAddComment({
id: comments?.length + 1,
hash: 0,
text: text,
color: color || "#000000"
})
setText("");
setColor("");
};
return (
<div className="comments">
<h2>
Comments #{hash}
</h2>
<div className="comments-block">
{comments.map((comment, index) => (
<div
key={index}
className="comments-element"
>
<div
className="comments-element-color"
style={{background: comment?.color}}
>
</div>
<div className="comments-element-text">
{comment?.text}
</div>
</div>
))}
</div>
<form className="comments-bottom" onSubmit={addComment}>
<div className="comments-color">
<input
type="color"
onChange={changeColor}
value={color || "#000000"}
/>
</div>
<div className="comments-text">
<textarea
placeholder="Type comment here ..."
required={true}
minLength={3}
value={text}
onChange={changeTextarea}
/>
</div>
<div className="comments-btn">
<button
type="submit"
className="btn btn-add"
>
Add New
</button>
</div>
</form>
</div>
)
}
export default CommentsList;
|
package main;
import ai.PathFinder;
import entity.Entity;
import entity.Player;
import entity.Projectile;
import entity.video.GameOver;
import entity.video.LwlUp;
import entity.video.SalonGiris;
import tile.TileManager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class GamePanel extends JPanel implements Runnable , MouseMotionListener {
//VİDEOS
SalonGiris salonGiris= new SalonGiris(this);
GameOver gameOver= new GameOver(this);
LwlUp lwlUp= new LwlUp(this);
public PathFinder pFinder = new PathFinder(this);
//SCREEN SETTİNG
public final int originalTileSize = 32; //32x32 px tile
public final double scale = 1.5;
public final int tileSize = (int)(scale*originalTileSize) ;
public final int maxScreenCol =20;
public final int maxScreenRow=12;
public final int screenWidth= tileSize*maxScreenCol;
public final int screenHeight = tileSize*maxScreenRow;
public int mouseX=0;
public int mouseY=0;
//WORLD SETTİNGS
public final int maxMap=10;
public int currentMap=0;
public final int maxWorldCol = 50;
public final int maxWorldRow = 50;
//FOR FULLSCREEN
int screenwidth2= screenWidth;
int screenHeight2= screenHeight;
BufferedImage tempScreen;
Graphics2D g2;
public boolean fullScreenOn=true;
int FPS=60;
//GAMESTATE
public int gameState;
public final int titleState=0;
public final int playState=1;
public final int pauseState=2;
public final int dialogueState=3;
public final int characterState=4;
public final int optionsState=5;
public final int gameOverState=6;
public final int cutSceneState=7;
public final int tradeState=8;
private boolean isMusicStopped=false;
//SYSTEM
public UI ui = new UI(this);
public TileManager tileM = new TileManager(this);
public KeyHandler keyH = new KeyHandler(this);
public MouseHandler mouseHandler= new MouseHandler(this);
Sound se = new Sound();
Sound music = new Sound();
Sound pauseMenuMusic = new Sound();
public CollisionChecker cChecker = new CollisionChecker(this);
public AssetSetter aSetter = new AssetSetter(this);
public EventHandler eHandler = new EventHandler(this);
Config config = new Config(this);
Thread gameThread;// oyunda paralel zaman ayarı buradan olacak
public MusicThread musicThread;
// ENTITY AND OBJECT
public Player player = new Player(this, keyH, mouseHandler);
public Entity obj[][]= new Entity[maxMap][100];
public Entity npc[][]= new Entity[maxMap][100];
public Entity monster[][]= new Entity[maxMap][100];
public Entity hareketli[][]= new Entity[maxMap][100];
public Entity entity= new Entity(this);
public ArrayList<Entity> entityList= new ArrayList<>();
public ArrayList<Projectile> projectileList= new ArrayList<>();
public ArrayList<Entity> particleList = new ArrayList<>();
public GamePanel (){
this.setPreferredSize(new Dimension(screenWidth,screenHeight));
this.setBackground(Color.BLACK);
this.setDoubleBuffered(true);
this.setFocusable(true);
this.addKeyListener(keyH);
this.addMouseMotionListener(this);
}
public void setupGame(){
aSetter.setObject();
aSetter.setNPC();
aSetter.setMonster();
aSetter.setHareketli();
player.setDefaultPositions();//BUNU BURDAN KALDIR
gameState=titleState;
tempScreen= new BufferedImage(screenWidth,screenHeight,BufferedImage.TYPE_INT_ARGB);
g2 = (Graphics2D)tempScreen.getGraphics();
if (fullScreenOn==true){
setFullScreen();}
playMusic(9);
}
public void retry() {
player.setDefaultPositions();
player.restoreLifeMana();
aSetter.setNPC();
aSetter.setMonster();
aSetter.setHareketli();
playMusic(0);
}
public void restart(){
player.setDefaultPositions();
player.restoreLifeMana();
aSetter.setObject();
aSetter.setNPC();
aSetter.setMonster();
aSetter.setHareketli();
}
public void setFullScreen(){
//cihaz ayarlarını edinme kısmı
GraphicsEnvironment ge= GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
gd.setFullScreenWindow(Main.window);
screenwidth2=Main.window.getWidth();
screenHeight2=Main.window.getHeight();
}
public void startGameThread(){
gameThread= new Thread(this);
gameThread.start();
}
@Override
public void run() {
double drawTimeInterval = 1000000000/FPS;
double delta =0;
long lastTime = System.nanoTime();
long currentTime;
long timer=0;
int drawCount=0;
while (gameThread!=null){ //Bu döngü içerisinde draw ve update seri biçimde gerçekleşecek
currentTime= System.nanoTime();
delta+= (currentTime-lastTime)/drawTimeInterval;
timer+= currentTime-lastTime;
lastTime=currentTime;
if (delta>=1){
update(); //UpDate
drawToTempScreen(); //buffered ımage çizimi
drawToScreen(); //screen image cizimi
delta--;
drawCount++;
}
if(timer>=1000000000){
System.out.println("FPS: "+drawCount);
drawCount=0;
timer=0;
}
}
}
public void update(){ //Update işlemini yapacak
if (gameState==playState){
player.update();
for (int i=0; i<npc[1].length; i++){
if(npc[currentMap][i]!=null){
npc[currentMap][i].update();
}
}
for (int i =0; i<monster[1].length; i++){
if (monster[currentMap][i] !=null){
if (monster[currentMap][i].alive==true && monster[currentMap][i].dying==false){
monster[currentMap][i].update();}
if (monster[currentMap][i].alive==false){
monster[currentMap][i].checkDrop();
monster[currentMap][i] = null;
}}
}
for (int i =0; i<hareketli[1].length; i++){
if (hareketli[currentMap][i]!=null){
hareketli[currentMap][i].update();}}
for (int i =0; i< projectileList.size(); i++){
if (projectileList.get(i) !=null){
if (projectileList.get(i).alive==true){
projectileList.get(i).update();}
if (projectileList.get(i).alive==false){
projectileList.remove(i);
}}
}
for (int i =0; i< particleList.size(); i++){
if (particleList.get(i) !=null){
if (particleList.get(i).alive==true){
particleList.get(i).update();}
if (particleList.get(i).alive==false){
particleList.remove(i);
}}
}
if (isMusicStopped==true){
music.resume();
isMusicStopped=false;
} }
if (gameState==pauseState){
music.pause();
isMusicStopped=true;
}
if(gameState==dialogueState&& player.lwlUp==true){
lwlUp.update();
}
if(gameState==dialogueState&& eHandler.salongiris==true){
salonGiris.update();
}
if (gameState == pauseState && musicThread == null) {
musicThread = new MusicThread(this);
musicThread.start();
} else if (gameState != pauseState && musicThread != null) {
musicThread.stopMusicThread();
musicThread = null;
}
if (gameState==gameOverState){
gameOver.update();
}
}
public void drawToTempScreen(){
//TİTLE SCREEN
if (gameState==titleState){
ui.draw(g2);
}
else {
//TILE
tileM.draw(g2);
//ADD Entities to the list
entityList.add(player);
for (int i=0; i<npc[1].length;i++){
if (npc[currentMap][i]!=null){
entityList.add(npc[currentMap][i]);}
}
for (int i =0; i<obj[1].length;i++){
if (obj[currentMap][i]!=null){
entityList.add(obj[currentMap][i]);}
}
for (int i =0; i<hareketli[1].length;i++){
if (hareketli[currentMap][i]!=null){
entityList.add(hareketli[currentMap][i]);}
}
for (int i=0; i<monster[1].length;i++){
if (monster[currentMap][i]!=null){
entityList.add(monster[currentMap][i]);}
}
for (int i=0; i< projectileList.size();i++){
if (projectileList.get(i)!=null){
entityList.add(projectileList.get(i));}
}
for (int i=0; i< particleList.size();i++){
if (particleList.get(i)!=null){
entityList.add(particleList.get(i));}
}
//SORT
Collections.sort(entityList, new Comparator<Entity>() {
@Override
public int compare(Entity e1, Entity e2) {
int result=Integer.compare(e1.worldY,e2.worldY);
return result;
}
});
for (int i=0; i<entityList.size(); i++){
entityList.get(i).draw(g2);
}
//EMpty entity list
entityList.clear();
//UI
ui.draw(g2);}
}
public void drawToScreen(){
Graphics g =getGraphics();
g.drawImage(tempScreen,0,0,screenwidth2,screenHeight2,null);
g.dispose();
}
public void playMusic(int i){
music.setFile(i);
music.play();
music.loop();
}
public void stopMusic(){
music.stop();
}
public void playSE(int i){
se.setFile(i);
se.play();
}
public void stopSE(){
se.stop();
}
public void playPauseMenuMusic(int i){
pauseMenuMusic.setFile(i);
pauseMenuMusic.play();
}
public void stopPauseMenuMusic(int i){
pauseMenuMusic.stop();
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
mouseX=e.getX();
mouseY=e.getY();
}
}
|
import * as yup from 'yup'
import { AuthError } from '@/models/shared'
import { EnvelopeIcon, LockClosedIcon, UserIcon } from '@heroicons/react/24/outline'
import { Input } from '@/components/forms/input'
import { RoleEnum } from '@/models/crud'
import { authOptions } from '../api/auth/[...nextauth]'
import { getServerSession } from 'next-auth'
import { isAxiosError, unWrapAuthError } from '@/utils/errors'
import { signIn } from 'next-auth/react'
import { useAuthApi } from '@/utils/api/auth'
import { useForm } from 'react-hook-form'
import { validateTokenRoleRequest } from '@/middleware/validateTokenRole'
import { yupResolver } from '@hookform/resolvers/yup'
import Alert from '@/components/shared/alert'
import AuthCard from '@/components/auth/authCard'
import DatePickerWithHookForm from '@/components/forms/datePickerWithHookForm'
import Footer from '@/components/layout/footer'
import Head from 'next/head'
import Link from 'next/link'
import Menu from '@/components/layout/menu'
import React, { useEffect } from 'react'
import heavilyWavedLine from '@/images/heavilyWavedLine.svg'
import logoPointingDown from '@/images/logoPointingYellowBand.svg'
import useTranslation from '@/hooks/useTranslation'
type SignUpFormDataType = {
firstName: string
lastName: string
dateOfBirth: Date
email: string
password: string
passwordConfirmation: string
}
const SignUpFormSchema = yup
.object()
.shape({
firstName: yup.string().required('First Name is required'),
lastName: yup
.string()
.required('Last Name is required')
.matches(/^[a-zA-Z\s]*$/, 'Name can only contain letters and spaces'),
dateOfBirth: yup
.date()
.max(new Date(), 'Date of Birth cannot be in the future')
.required('Date of Birth is required'),
email: yup.string().email('Invalid email').required('Email is required'),
password: yup
.string()
.min(8, 'Password must be at least 8 characters')
.required('Password is required'),
passwordConfirmation: yup
.string()
.oneOf([yup.ref('password')], 'Passwords must match')
.required('Password Confirmation is required'),
})
.required()
interface ServerProps {
error: string | null
callbackUrl: string | null
}
const Signup = (props: ServerProps) => {
const authApi = useAuthApi()
const t = useTranslation()
const [signUpButtonDisabled, setSignUpButtonDisabled] = React.useState(false)
const {
register,
handleSubmit,
control,
formState: { errors },
} = useForm<SignUpFormDataType>({
resolver: yupResolver(SignUpFormSchema),
})
const [alertData, setAlertData] = React.useState<{
message: string
variant: 'success' | 'info' | 'warning' | 'error'
open: boolean
}>({
message: '',
variant: 'info',
open: false,
})
const closeAlert = () => {
setAlertData({ ...alertData, open: false })
}
//use the scroll position to show the message
const scrollToTop = () => {
window.scrollTo({
top: 25,
behavior: 'smooth',
})
}
const onSubmitHandler = async (data: SignUpFormDataType) => {
try {
closeAlert()
setSignUpButtonDisabled(true)
await authApi.signUp({
firstName: data.firstName,
lastName: data.lastName,
dateOfBirth: data.dateOfBirth.toISOString(),
email: data.email,
password: data.password,
})
// sign in the user using next-auth
await signIn('credentials', {
email: data.email,
password: data.password,
redirect: false,
})
scrollToTop()
setAlertData({
message: 'Check your email to confirm your account',
variant: 'success',
open: true,
})
} catch (error) {
setSignUpButtonDisabled(false)
if (isAxiosError<AuthError>(error)) {
const errors = unWrapAuthError(error)
setAlertData({
message: errors[0].message || 'Something went wrong',
variant: 'error',
open: true,
})
}
}
}
useEffect(() => {
if (props.error) {
setAlertData({
message: props.error,
variant: 'error',
open: true,
})
}
}, [props.error])
return (
<>
<Head>
<title>NinjaCo | Sign Up</title>
<meta name="description" content="Sign Up to NinjaCo" />
</Head>
<main className="relative w-full h-screen">
<Menu
menuOption={{
logoToUse: 'dark',
startBackgroundDark: false,
startTextWhite: false,
isSticky: false,
startWithBottomBorder: true,
startButtonDark: true,
}}
></Menu>
<AuthCard title="Sign Up" titleImage={logoPointingDown} underLineImage={heavilyWavedLine}>
<Alert
className="my-3"
message={alertData.message}
variant={alertData.variant}
open={alertData.open}
close={closeAlert}
/>
<form onSubmit={handleSubmit(onSubmitHandler)} className="flex flex-col gap-4" id="form">
<Input
{...register('firstName')}
label={t.Auth.signUp.firstName}
placeholder="John"
StartIcon={UserIcon}
error={errors.firstName?.message}
isRequired={true}
/>
<Input
{...register('lastName')}
label={t.Auth.signUp.lastName}
placeholder="Smith"
StartIcon={UserIcon}
error={errors.lastName?.message}
isRequired={true}
/>
<DatePickerWithHookForm
control={control}
name={register('dateOfBirth').name} // we only need the "name" prop
label={t.Auth.signUp.dateOfBirth as string}
error={errors.dateOfBirth?.message}
isRequired={true}
/>
<Input
{...register('email')}
label={t.Auth.signUp.email}
placeholder={t.Auth.signUp.email as string}
StartIcon={EnvelopeIcon}
error={errors.email?.message}
isRequired={true}
/>
<Input
{...register('password')}
type="password"
label={t.Auth.signUp.password}
placeholder={t.Auth.signUp.password as string}
StartIcon={LockClosedIcon}
error={errors.password?.message}
isRequired={true}
/>
<Input
{...register('passwordConfirmation')}
type="password"
label={t.Auth.signUp.confirmPassword}
placeholder={t.Auth.signUp.confirmPassword as string}
StartIcon={LockClosedIcon}
error={errors.passwordConfirmation?.message}
isRequired={true}
/>
<button
type="submit"
form="form"
value="Submit"
className="w-full btn bg-brand-200 text-brand hover:bg-brand hover:text-brand-50 focus:outline-none focus:ring-1 focus:ring-offset-1 focus:ring-brand-500 disabled:bg-gray-300"
disabled={signUpButtonDisabled}
>
{t.Auth.signUp.signUp}
</button>
</form>
<div className="w-full flex justify-between text-xs mt-6">
<Link className="cursor-pointer text-brand-500" href="/">
{t.Auth.signUp.backToHome}
</Link>
<Link href="/auth/signin" className="cursor-pointer text-brand font-semibold">
{t.Auth.signUp.signIn}
</Link>
</div>
</AuthCard>
<Footer />
</main>
</>
)
}
export const getServerSideProps = async (context) => {
const { query, req, res } = context
const error = query.error as string | null
const callbackUrl = query.callbackUrl as string | null
const session = await getServerSession(req, res, authOptions)
if (session) {
const canUserAccessCreatorPage = await validateTokenRoleRequest(
[RoleEnum.CREATOR, RoleEnum.ADMIN],
session.accessToken
)
if (canUserAccessCreatorPage && canUserAccessCreatorPage.payload) {
const canUserAccessAdminPage = await validateTokenRoleRequest(
[RoleEnum.ADMIN],
session.accessToken
)
if (canUserAccessAdminPage && canUserAccessAdminPage.payload) {
return {
redirect: {
destination: '/admin',
permanent: false,
},
}
}
return {
redirect: {
destination: '/creator',
permanent: false,
},
}
}
return {
redirect: {
destination: (query.redirectTo as string | undefined) || '/app',
permanent: false,
},
}
}
return {
props: {
error: error || null,
callbackUrl: callbackUrl || null,
},
}
}
export default Signup
|
import { Artist, Track } from "@/types"
export function sortObjectByValues(obj: { [key: string]: number }) {
const sortedEntries = Object.entries(obj).sort((a, b) => b[1] - a[1])
return sortedEntries
}
export const metaGenres = [
"rock",
"pop",
"country",
"rap",
"jazz",
"indie",
"bluegrass",
"progressive",
"metal",
"classical",
"alternative",
]
export const popularityDescription = (popularity: number) => {
if (popularity >= 100) {
return `Your musical taste aligns with mainstream trends, and you enjoy the latest and greatest hits from the biggest global superstars. You actively follow pop culture and are likely to be up-to-date with the latest music releases and popular trends.`
} else if (popularity >= 50) {
return `You have a preference for well-known artists and songs. You tend to gravitate towards music that has broader recognition and appeal, enjoying the energy and familiarity of popular tracks.`
} else if (popularity >= 40) {
return `Your musical taste is moderately mainstream. While you appreciate some popular artists and hits, you also seek out music that may not be on everyone's radar, allowing you to enjoy a diverse range of songs.`
} else if (popularity >= 30) {
return `You strike a balance between mainstream hits and lesser-known tracks. Your musical taste is versatile, allowing you to enjoy both popular chart-toppers and lesser-known songs that resonate with you on a personal level.`
} else if (popularity >= 20) {
return `Your musical preferences lean towards niche and alternative genres. You appreciate the creativity and experimentation found in less mainstream music, and you enjoy supporting artists who have a dedicated following.`
} else if (popularity >= 10) {
return `You have an eclectic taste in music, always on the lookout for hidden gems and obscure tracks from underground artists. You enjoy the thrill of discovering new sounds that most people might not have heard of yet.`
} else {
return `You must be trying to be different.`
}
}
export function getMostAndLeastPopularTrack(array: Track[]) {
const sortedArray = array.sort(
(a: any, b: any) => b.popularity - a.popularity
)
return [sortedArray[0], sortedArray[sortedArray.length - 1]]
}
export function getMostAndLeastPopularArtist(array: Artist[]) {
const sortedArray = array.sort(
(a: any, b: any) => b.popularity - a.popularity
)
return [sortedArray[0], sortedArray[sortedArray.length - 1]]
}
// helper functions to map data
export const mapArtists = (items: any[]) =>
items.map((artist: any) => ({
name: artist.name,
image: artist.images.length > 0 ? artist.images[0].url : null,
spotifyUrl: `https://open.spotify.com/artist/${artist.id}`,
popularity: artist.popularity,
genres: artist.genres,
}))
export const mapTracks = (items: any[]) =>
items.map((track: any) => ({
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
image: track.album.images[0].url,
popularity: track.popularity,
spotifyUrl: track.external_urls.spotify,
explicit: track.explicit,
}))
export const extractBandsFromResponse = (response: string) => {
// regex to match each numbered item and capture its content
const matches = response.match(
/\d+\.\s*(.*?)(?=\n\d+\.|\n$|\nRecommended Bands|$)/g
)
if (matches) {
// map over the matches and extract the band names by removing the nubmers and dots
return matches.map((match) => match.replace(/\d+\.\s*/, "").trim())
}
// return an empty array of no matches are found
return []
}
export const calculateUserGenres = (allTopArtists: Artist[]) => {
let sortedGenresArray: { genre: string; count: number }[] = []
try {
const genresMap = new Map<string, number>()
allTopArtists.forEach((artist: Artist) => {
artist.genres.forEach((genre: string) => {
const genreWords = genre.split(" ")
genreWords.forEach((g: string) => {
if (metaGenres.includes(g)) {
genresMap.set(g, (genresMap.get(g) || 0) + 1)
}
})
if (genreWords.length === 1) {
genresMap.set(genre, (genresMap.get(genre) || 0) + 1)
}
})
})
const genresArray: { genre: string; count: number }[] = []
genresMap.forEach((value, key) => {
genresArray.push({ genre: key, count: value })
})
sortedGenresArray = genresArray.sort((a, b) => b.count - a.count)
} catch (error) {
console.error("Error calculating user genres:", error)
} finally {
return sortedGenresArray
}
}
|
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.example.backend.service;
import com.example.backend.model.Appeal;
import com.example.backend.repository.AppealRepository;
import jakarta.transaction.Transactional;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
/**
*
* @author Polly
*/
@Service
public class AppealService {
@Autowired
private AppealRepository appealRepository;
public Page<Appeal> getNotAnsweredAppeals(Pageable pageable) {
return appealRepository.getNotAnsweredList(pageable);
}
public Page<Appeal> getAnsweredAppeals(Pageable pageable) {
return appealRepository.getAnsweredList(pageable);
}
public void deleteAllAppeals() {
appealRepository.deleteAll();
}
@Transactional
public void updateAnsweredAppeals(List<Integer> listId){
appealRepository.updateAnswered(listId);
}
public void addAppeal(Appeal appeal) {
appealRepository.saveAndFlush(appeal);
}
}
|
from rest_framework import serializers
from users.models import UserFollow
class UserFollowSerializer(serializers.ModelSerializer):
class Meta:
model = UserFollow
fields = ("id", "user_from", "user_to", "created")
read_only_fields = ("created",)
class UserFollowCreateSerializer(UserFollowSerializer):
class Meta(UserFollowSerializer.Meta):
read_only_fields = UserFollowSerializer.Meta.read_only_fields + ("user_from",)
def validate_user_to(self, user_to):
if self.context.get("user_from") == user_to:
raise serializers.ValidationError("You cannot follow yourself.")
return user_to
|
<script setup lang="ts">
import type CloudIframe from "../../ts/CloudIframe";
const props = defineProps<{
ctrl: CloudIframe;
}>();
import MessageSimple from "@chromane/front/vue/comp/MessageSimple.vue";
import Form from "@chromane/front/vue/form/Form.vue";
import Button from "@chromane/front/vue/comp/Button.vue";
import { reactive } from "vue";
// todo:
// add form validation here
// and required fields ( message )
// name and email - optional
let model = reactive({
stage_name: "initial",
//
form_state: {} as any,
form_fields: [
{
name: "name",
title: "Your name",
type: "text",
},
{
name: "email",
title: "Your email",
type: "text",
},
{
name: "message",
title: "Message",
type: "textarea",
},
],
});
async function send_feedback() {
props.ctrl.blocking_inc();
await props.ctrl.firebase_manager.backend_proxy.common.send_user_feedback({
client_id: "website",
hostname: "Bloom chrome extension",
name: model.form_state.name,
email: model.form_state.email,
message: model.form_state.message,
});
model.form_state = {};
model.stage_name = "message_sent";
props.ctrl.blocking_dec();
}
function continue_click() {
model.stage_name = "initial";
}
</script>
<template>
<div class="page popup">
<div
class="page-inner"
v-if="model.stage_name === 'initial'"
>
<MessageSimple
class="mb-4"
:model="{
type: 'info',
title: 'Send us a message',
text: 'Thank you for installing and using this extension. You can use the form below to send us a message with your thoughts about this plugin. If you have any issues, or suggestions - we would be happy to work on them.',
}"
></MessageSimple>
<Form
:form_fields="model.form_fields"
:form_state="model.form_state"
></Form>
<Button
:model="{
text: 'Send',
}"
v-on:button_click="send_feedback"
></Button>
</div>
<div
class="page-inner"
v-if="model.stage_name === 'message_sent'"
>
<MessageSimple
class="mb-4"
:model="{
type: 'positive',
title: 'Message sent',
text: 'Thank you for sending us your message. We will try work on it as soon as possible.',
}"
></MessageSimple>
<Button
:model="{
text: 'Continue',
}"
v-on:button_click="continue_click"
></Button>
</div>
</div>
</template>
<style></style>
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shopping/provider/auth.dart';
import 'package:shopping/provider/cards.dart';
import 'package:shopping/provider/product.dart';
import 'package:shopping/screens/product_detail_screen.dart';
class ProductItem extends StatelessWidget {
@override
Widget build(BuildContext context) {
final product=Provider.of<Product>(context);
final authData=Provider.of<Auth>(context,listen: false);
final cart=Provider.of<Cart>(context,listen: false);
return ClipRRect(
borderRadius: BorderRadius.circular(10),
child: GridTile(
child: GestureDetector(
onTap: () {
Navigator.of(context).pushNamed(ProductDetailScreen.routeName,arguments: product.id);
},
child: Image.network(
product.imageUrl,
fit: BoxFit.cover,
),
),
footer: GridTileBar(
backgroundColor: Colors.black87,
leading: IconButton(
icon: Icon(product.isFavorite? Icons.favorite : Icons.favorite_border,),
color: Theme.of(context).accentColor,
onPressed: () {
product.toggleFavoriteStatus(authData.token.toString(),authData.userId.toString());
},
),
title: Text(
product.title,
textAlign: TextAlign.center,
),
trailing: IconButton(
icon: const Icon(
Icons.shopping_cart,
),
onPressed: () {
cart.addItem(product.id,
product.title,
product.price);
Scaffold.of(context).hideCurrentSnackBar();
Scaffold.of(context).showSnackBar(SnackBar(content: Text('Iteim added to cart'),
duration: const Duration(seconds: 2),
action: SnackBarAction(label: 'UNDO',onPressed: (){
cart.removeSingleItem(product.id);
},),));
},
color: Theme.of(context).accentColor,
),
),
),
);
}
}
|
package yte.obs_proje.yte_obs_proje.exam.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import yte.obs_proje.yte_obs_proje.common.response.MessageResponse;
import yte.obs_proje.yte_obs_proje.exam.controller.request.AddExamRequest;
import yte.obs_proje.yte_obs_proje.exam.controller.request.UpdateExamRequest;
import yte.obs_proje.yte_obs_proje.exam.controller.response.ExamQueryModel;
import yte.obs_proje.yte_obs_proje.exam.service.ExamService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequiredArgsConstructor
@Validated
@RequestMapping("/exams")
public class ExamController {
private final ExamService examService;
@PostMapping
@PreAuthorize("hasAnyAuthority('Academician','Assistant')")
public MessageResponse addExam(@Valid @RequestBody AddExamRequest addExamRequest) {
return examService.addExam(addExamRequest.toDomainEntity());
}
@PutMapping("{id}")
@PreAuthorize("hasAnyAuthority('Academician','Assistant')")
public MessageResponse updateExam(@Valid @RequestBody UpdateExamRequest updateExamRequest, @PathVariable Long id) {
return examService.updateExam(id, updateExamRequest.toDomainEntity());
}
@DeleteMapping("{id}")
@PreAuthorize("hasAnyAuthority('Academician','Assistant')")
public MessageResponse getExamById(@PathVariable Long id) {
return examService.deleteExamById(id);
}
@GetMapping
@PreAuthorize("hasAnyAuthority('Academician','Assistant','Student')")
public List<ExamQueryModel> getAllExams() {
return examService.getAllExam()
.stream()
.map(exam -> new ExamQueryModel(exam))
.toList();
}
@GetMapping("{id}")
public ExamQueryModel getById(@PathVariable Long id) {
return new ExamQueryModel(examService.getById(id));
}
}
|
// import 'dart:async';
// import 'package:flutter/material.dart';
// import 'package:loginsignup/screens/login_screen.dart';
// import 'package:loginsignup/screens/signup_screen.dart';
// import 'package:loginsignup/util/slide.dart';
// import 'package:loginsignup/util/slide_dots.dart';
// import 'package:loginsignup/util/slide_item.dart';
// class GettingStartedScreen extends StatefulWidget {
// @override
// _GettingStartedScreenState createState() => _GettingStartedScreenState();
// }
// class _GettingStartedScreenState extends State<GettingStartedScreen> {
// int _currentPage = 0;
// final PageController _pageController = PageController(initialPage: 0);
// @override
// void initState() {
// super.initState();
// Timer.periodic(Duration(seconds: 5), (Timer timer) {
// if (_currentPage < 2) {
// _currentPage++;
// } else {
// _currentPage = 0;
// }
// _pageController.animateToPage(
// _currentPage,
// duration: Duration(milliseconds: 300),
// curve: Curves.easeIn,
// );
// });
// }
// @override
// void dispose() {
// super.dispose();
// _pageController.dispose();
// }
// _onPageChanged(int index) {
// setState(() {
// _currentPage = index;
// });
// }
// @override
// Widget build(BuildContext context) {
// return Scaffold(
// body: Container(
// color: Colors.white,
// child: Padding(
// padding: const EdgeInsets.all(20),
// child: Column(
// children: <Widget>[
// Expanded(
// child: Stack(
// alignment: AlignmentDirectional.bottomCenter,
// children: <Widget>[
// PageView.builder(
// scrollDirection: Axis.horizontal,
// controller: _pageController,
// onPageChanged: _onPageChanged,
// itemCount: slideList.length,
// itemBuilder: (ctx, i) => SlideItem(i),
// ),
// Stack(
// alignment: AlignmentDirectional.topStart,
// children: <Widget>[
// Container(
// margin: const EdgeInsets.only(bottom: 35),
// child: Row(
// mainAxisSize: MainAxisSize.min,
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// for(int i = 0; i<slideList.length; i++)
// if( i == _currentPage )
// SlideDots(true)
// else
// SlideDots(false)
// ],
// ),
// )
// ],
// )
// ],
// ),
// ),
// SizedBox(
// height: 20,
// ),
// Column(
// crossAxisAlignment: CrossAxisAlignment.stretch,
// children: <Widget>[
// TextButton(
// child: Text(
// 'Getting Started',
// style: TextStyle(
// fontSize: 18,
// ),
// ),
// shape: RoundedRectangleBorder(
// borderRadius: BorderRadius.circular(5),
// ),
// padding: const EdgeInsets.all(15),
// color: Theme.of(context).primaryColor,
// textColor: Colors.white,
// onPressed: () {
// Navigator.of(context).pushNamed(SignupScreen.routeName);
// },
// ),
// Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// Text(
// 'Have an account?',
// style: TextStyle(
// fontSize: 18,
// ),
// ),
// TextButton(
// child: Text(
// 'Login',
// style: TextStyle(fontSize: 18),
// ),
// onPressed: () {
// Navigator.of(context).pushNamed(LoginScreen.routeName);
// },
// ),
// ],
// ),
// ],
// )
// ],
// ),
// ),
// ),
// );
// }
// }
|
#ifndef BOENKENSPRITEMOVING_H
#define BOENKENSPRITEMOVING_H
#include "qtboenkensprite.h"
namespace ribi {
namespace bnkn {
///SpriteMoving is an abstract base class
struct SpriteMoving: public Sprite
{
SpriteMoving(
const double x,
const double y,
const int size,
const unsigned char r,
const unsigned char g,
const unsigned char b
);
virtual ~SpriteMoving();
double CalcImpulseAngle() const noexcept;
double CalcImpulseSpeed() const noexcept;
virtual void Draw(QPainter& painter) const override;
double GetDeltaX() const noexcept { return m_dx; }
double GetDeltaY() const noexcept { return m_dy; }
virtual void Move() = 0;
void Move(const double dx, const double dy) { m_dx += dx; m_dy += dy; }
//void SetDeltaX(const double dx) noexcept { m_dx = dx; }
//void SetDeltaY(const double dy) noexcept { m_dy = dy; }
virtual void SetSpeed(const double dx, const double dy) noexcept { m_dx = dx; m_dy = dy; }
static void SetFriction(const double friction);
static void Collision(SpriteMoving * const p1, SpriteMoving * const p2);
///Debugging purposes
static int CountMovingSprites() noexcept { return sm_n_moving_sprites; }
protected:
double m_dx;
double m_dy;
static double m_friction;
static int sm_n_moving_sprites;
};
} //~namespace bnkn
} //~namespace ribi
#endif // BOENKENSPRITEMOVING_H
|
//
// ConjugationRowView.swift
// Spanish Lookup
//
// Created by Jake Crouchley on 22/05/2023.
//
import SwiftUI
struct ConjugationRowView: View {
var searchTerm: String
@State var conjugationGroup: ConjugationGroup
@State var matchingConjugation: Conjugation?
func getMatchingConjugations(searchTerm: String, conjugations: [Conjugation]) -> [Conjugation] {
return conjugations.filter { conjugation in
return conjugation.conjugation?.starts(with: searchTerm.lowercased()) ?? false
}
}
var body: some View {
VStack(alignment: .leading) {
Text(conjugationGroup.infinitive ?? "")
Text(conjugationGroup.infinitive_english ?? "")
.font(.subheadline)
.italic()
if (searchTerm != "" && matchingConjugation != nil) {
HStack {
Text(matchingConjugation?.conjugation ?? "")
Text("(\(matchingConjugation?.mood ?? "") \(matchingConjugation?.tense ?? ""))")
}
.font(.caption)
.padding(.top, 4)
}
}
.onAppear(perform: {
matchingConjugation = getMatchingConjugations(searchTerm: searchTerm, conjugations: conjugationGroup.conjugationsFlatArray).first
})
.onChange(of: searchTerm) { newValue in
matchingConjugation = getMatchingConjugations(searchTerm: newValue, conjugations: conjugationGroup.conjugationsFlatArray).first
}
}
}
struct ConjugationRowView_Previews: PreviewProvider {
let example = ConjugationGroup.example
static var previews: some View {
ConjugationRowView(searchTerm: "cur", conjugationGroup: ConjugationGroup.example)
}
}
|
#include <iostream>
#include <cstring>
using namespace std;
class Koncert {
protected:
char naziv[20];
char location[20];
float priceTicket;
public:
static float discount;
Koncert(const char *naziv = " ", const char *location = " ", float priceTicket = 0.0) {
strcpy(this->naziv, naziv);
strcpy(this->location, location);
this->priceTicket = priceTicket;
}
Koncert(const Koncert &c) {
strcpy(this->naziv, c.naziv);
strcpy(this->location, c.location);
this->priceTicket = c.priceTicket;
}
const char *getNaziv() const {
return naziv;
}
static float getSezonskiPopust() {
return discount;
}
static void setSezonskiPopust(float discount) {
Koncert::discount = discount;
}
virtual float cena() {
return priceTicket * (1 - discount);
}
virtual ~Koncert() {}
};
class ElektronskiKoncert : public Koncert {
char *nameDj;
float timeDuration;
bool dayNight;
void copy(const ElektronskiKoncert &c) {
this->nameDj = new char[strlen(c.nameDj) + 1];
strcpy(this->nameDj, c.nameDj);
this->timeDuration = c.timeDuration;
this->dayNight = c.dayNight;
}
public:
ElektronskiKoncert(const char *naziv = " ", const char *loation = " ", float priceTicket = 0.0,
const char *nameDj = " ", float partyDuration = 0.0, bool dayNight = true)
: Koncert(naziv, loation, priceTicket) {
this->nameDj = new char[strlen(nameDj) + 1];
strcpy(this->nameDj, nameDj);
this->timeDuration = partyDuration;
this->dayNight = dayNight;
}
ElektronskiKoncert(const ElektronskiKoncert &c) : Koncert(c) {
copy(c);
}
ElektronskiKoncert &operator=(const ElektronskiKoncert &o) {
if (this != &o) {
delete[] nameDj;
Koncert::operator=(o);
copy(o);
}
return *this;
}
float cena() override {
float c = Koncert::cena();
if (timeDuration > 7) {
c += 360;
} else if (timeDuration > 5) {
c += 150;
}
if (dayNight) {
c -= 50;
} else {
c += 100;
}
return c;
}
~ElektronskiKoncert() {
delete[] nameDj;
}
};
void najskapKoncert(Koncert **koncerti, int n) {
Koncert *max = koncerti[0];
int vkElek = 0;
for (int i = 1; i < n; ++i) {
if (dynamic_cast<ElektronskiKoncert *>(koncerti[i])) {
vkElek++;
}
if (max->cena() < koncerti[i]->cena()) {
max = koncerti[i];
}
}
cout << "Najskap koncert: " << max->getNaziv() << " " << max->cena() << endl;
cout << "Elektronski koncerti: " << vkElek << " od vkupno " << n << endl;
}
bool prebarajKoncert(Koncert **koncerti, int n, char *naziv, bool elektronski) {
if (elektronski) {
for (int i = 0; i < n; ++i) {
if (dynamic_cast<ElektronskiKoncert * >(koncerti[i]) && strcmp(koncerti[i]->getNaziv(),naziv) == 0) {
cout << koncerti[i]->getNaziv() << " " << koncerti[i]->cena() << endl;
return true;
}
}
} else {
for (int i = 0; i < n; ++i) {
if (strcmp((koncerti[i])->getNaziv(), naziv) == 0) {
cout << koncerti[i]->getNaziv() << " " << koncerti[i]->cena() << endl;
return true;
}
}
}
return false;
}
float Koncert::discount = 0.2;
int main() {
int tip, n, novaCena;
char naziv[100], lokacija[100], imeDJ[40];
bool dnevna;
float cenaBilet, novPopust;
float casovi;
cin >> tip;
if (tip == 1) {//Koncert
cin >> naziv >> lokacija >> cenaBilet;
Koncert k1(naziv, lokacija, cenaBilet);
cout << "Kreiran e koncert so naziv: " << k1.getNaziv() << endl;
} else if (tip == 2) {//cena - Koncert
cin >> naziv >> lokacija >> cenaBilet;
Koncert k1(naziv, lokacija, cenaBilet);
cout << "Osnovna cena na koncertot so naziv " << k1.getNaziv() << " e: " << k1.cena() << endl;
} else if (tip == 3) {//ElektronskiKoncert
cin >> naziv >> lokacija >> cenaBilet >> imeDJ >> casovi >> dnevna;
ElektronskiKoncert s(naziv, lokacija, cenaBilet, imeDJ, casovi, dnevna);
cout << "Kreiran e elektronski koncert so naziv " << s.getNaziv() << " i sezonskiPopust "
<< s.getSezonskiPopust() << endl;
} else if (tip == 4) {//cena - ElektronskiKoncert
cin >> naziv >> lokacija >> cenaBilet >> imeDJ >> casovi >> dnevna;
ElektronskiKoncert s(naziv, lokacija, cenaBilet, imeDJ, casovi, dnevna);
cout << "Cenata na elektronskiot koncert so naziv " << s.getNaziv() << " e: " << s.cena() << endl;
} else if (tip == 5) {//najskapKoncert
} else if (tip == 6) {//prebarajKoncert
Koncert **koncerti = new Koncert *[5];
int n;
koncerti[0] = new Koncert("Area", "BorisTrajkovski", 350);
koncerti[1] = new ElektronskiKoncert("TomorrowLand", "Belgium", 8000, "Afrojack", 7.5, false);
koncerti[2] = new ElektronskiKoncert("SeaDance", "Budva", 9100, "Tiesto", 5, true);
koncerti[3] = new Koncert("Superhiks", "PlatoUkim", 100);
koncerti[4] = new ElektronskiKoncert("CavoParadiso", "Mykonos", 8800, "Guetta", 3, true);
char naziv[100];
najskapKoncert(koncerti, 5);
} else if (tip == 7) {//prebaraj
Koncert **koncerti = new Koncert *[5];
int n;
koncerti[0] = new Koncert("Area", "BorisTrajkovski", 350);
koncerti[1] = new ElektronskiKoncert("TomorrowLand", "Belgium", 8000, "Afrojack", 7.5, false);
koncerti[2] = new ElektronskiKoncert("SeaDance", "Budva", 9100, "Tiesto", 5, true);
koncerti[3] = new Koncert("Superhiks", "PlatoUkim", 100);
koncerti[4] = new ElektronskiKoncert("CavoParadiso", "Mykonos", 8800, "Guetta", 3, true);
char naziv[100];
bool elektronski;
cin >> elektronski;
if (prebarajKoncert(koncerti, 5, "Area", elektronski)) {
cout << "Pronajden" << endl;
} else { cout << "Ne e pronajden" << endl; }
if (prebarajKoncert(koncerti, 5, "Area", !elektronski)) {
cout << "Pronajden" << endl;
} else { cout << "Ne e pronajden" << endl; }
} else if (tip == 8) {//smeni cena
Koncert **koncerti = new Koncert *[5];
int n;
koncerti[0] = new Koncert("Area", "BorisTrajkovski", 350);
koncerti[1] = new ElektronskiKoncert("TomorrowLand", "Belgium", 8000, "Afrojack", 7.5, false);
koncerti[2] = new ElektronskiKoncert("SeaDance", "Budva", 9100, "Tiesto", 5, true);
koncerti[3] = new Koncert("Superhiks", "PlatoUkim", 100);
koncerti[2]->setSezonskiPopust(0.9);
najskapKoncert(koncerti, 4);
}
return 0;
}
|
import React, {useCallback, useEffect, useState} from "react";
import styled from "styled-components";
import palette from "../../lib/styles/palette";
const TagBoxBlock = styled.div`
width: 100%;
border-top: 1px solid ${palette.gray[2]};
padding-top: 2rem;
h4 {
color: ${palette.gray[8]};
margin-top: 0;
margin-bottom: 0.5rem;
}
`;
const TagForm = styled.form`
border-radius: 4px;
overflow: hidden; /* 넘치는 부분 안보여줌 */
display: flex;
width: 256px;
border: 1px solid ${palette.gray[9]}; /* 스타일 초기화 */
input, button {
outline: none;
border: none;
font-size: 1rem;
}
input {
padding: 0.5rem;
flex: 1;
min-width: 0;
}
button {
cursor: pointer;
padding-right: 1rem;
padding-left: 1rem;
border: none;
background: ${palette.gray[8]};
color: white;
font-weight: bold;
&:hover {
background: ${palette.gray[6]};
}
}
`;
const Tag = styled.div`
margin-right: 0.5rem;
color: ${palette.gray[5]};
cursor: pointer;
&:hover {
opacity: 0.5; /* 불투명도. 요소 뒤쪽 콘텐츠가 숨겨지는 정도 */
}
`;
const TagListBlock = styled.div`
display: flex;
margin-top: 0.5rem;
`;
// React.memo를 사용하여 tag 값이 바뀔 때만 리렌더링되도록 처리
const TagItem = React.memo(({tag, onRemove}) => (
<Tag onClick={() => onRemove(tag)}>#{tag}</Tag>
));
const TagList = React.memo(({tags, onRemove}) => (
<TagListBlock>
{tags.map(tag => (
<TagItem key={tag} tag={tag} onRemove={onRemove}/>
))}
</TagListBlock>
));
const TagBox = ({onChangeTags, tags}) => {
const [input, setInput] = useState('');
const [localTags, setLocalTags] = useState([]);
const insertTag = useCallback(
tag => {
if (!tag) return; // 공백이면 추가하지 않음
if (localTags.includes(tag)) return; // 이미 존재하면 추가하지 않음
const nextTags = [...localTags, tag]; // 기존 태그들 + 입력한 태그를 배열로 한 것을 nextTags 변수에 저장
setLocalTags(nextTags); // localTags를 nextTags로 바꾸고
onChangeTags(nextTags); // tags: nextTags
},
[localTags, onChangeTags],
);
const onRemove = useCallback(
tag => {
const nextTags = localTags.filter(t => t !== tag); // localTags에서 t !== tag를 만족하는 tag들만 nextTags로 저장
setLocalTags(nextTags);
onChangeTags(nextTags);
},
[localTags, onChangeTags],
);
const onChange = useCallback(
e => {
setInput(e.target.value);
},
[]
);
const onSubmit = useCallback(
e => {
e.preventDefault();
insertTag(input.trim()); // 앞뒤 공백을 없앤 후 등록
setInput(''); // input 초기화
},
[input, insertTag]
);
// tags 값이 바뀔 때
useEffect(() => {
setLocalTags(tags);
}, [tags]);
return (
<TagBoxBlock>
<h4>태그</h4>
<TagForm onSubmit={onSubmit}>
<input
placeholder="태그를 입력하세요."
value={input}
onChange={onChange}
/>
<button type="submit">추가</button>
</TagForm>
<TagList tags={localTags} onRemove={onRemove}/>
</TagBoxBlock>
);
};
export default TagBox;
|
use std::fmt;
#[derive(Clone, Copy, PartialEq, PartialOrd)]
struct Beers(i32);
struct Wall {
max: Beers,
current: Beers,
}
impl Wall {
fn from(n: i32) -> Self {
Self { max: Beers(n), current: Beers(n) }
}
fn next(&mut self) -> Beers {
self.current = Beers((self.current.0 - 1).rem_euclid(self.max.0 + 1));
self.current
}
}
impl fmt::Display for Beers {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
n if n > 1 => write!(f, "{} bottles", n),
n if n == 1 => write!(f, "{} bottle", n),
_ => write!(f, "no more bottles"),
}
}
}
fn main() {
let arg = std::env::args().last();
let mut wall = Wall::from(3);
loop {
let current = wall.current;
let next = wall.next();
let action = if current == Beers(0) { "Go to the store and buy some more" } else { "Take one down and pass it around" };
println!("\n{current} of beer on the wall, {current} of beer.\n{action}, {next} of beer on the wall.");
if arg == Some("break".to_string()) && next == wall.max {
break
}
}
}
|
import { fakeQuery, fakeRemove, fakeAdd, fakeUpdate, fakeActive, fakeGetTreeData } from '@/services/Basic/Dept';
export default {
namespace: 'deptManage',
state: {
data: {
list: [],
pagination: {},
},
queryResult: {
status: 'ok',
message: '',
},
treeData: [],
},
effects: {
*fetch ({ payload }, { call, put }) {
const response = yield call(fakeQuery, payload);
yield put({
type: 'saveQueryData',
payload: response,
});
},
*add ({ payload, callback }, { call, put }) {
const response = yield call(fakeAdd, payload);
yield put({
type: 'saveData',
payload: response,
});
if (callback) callback();
},
*remove ({ payload, callback }, { call, put }) {
const response = yield call(fakeRemove, payload);
yield put({
type: 'saveData',
payload: response,
});
if (callback) callback();
},
*update ({ payload, callback }, { call, put }) {
const response = yield call(fakeUpdate, payload);
yield put({
type: 'saveData',
payload: response,
});
if (callback) callback();
},
*active ({ payload, callback }, { call, put }) {
const response = yield call(fakeActive, payload);
yield put({
type: 'saveData',
payload: response,
});
if (callback) callback();
},
*getTreeData ({ payload }, { call, put }) {
alert('getTreeData');
const response = yield call(fakeGetTreeData, payload);
yield put({
type: 'saveTreeData',
payload: response,
});
},
},
reducers: {
saveQueryData (state, action) {
return {
...state,
data: { list: action.payload },
};
},
saveData (state, action) {
return {
...state,
queryResult: action.payload ? action.payload : {},
};
},
saveTreeData (state, action) {
return {
...state,
treeData: action.payload.list,
};
},
},
};
|
import React, { Component } from "react";
import axios from 'axios';
import Table from 'react-bootstrap/Table';
import WineTableRow from './WineTableRow';
export default class WineList extends Component {
constructor(props) {
super(props)
this.state = {
wines: []
};
}
componentDidMount() {
axios.get('http://localhost:4000/wines/')
.then(res => {
this.setState({
wines: res.data
});
})
.catch((error) => {
console.log(error);
})
}
DataTable() {
return this.state.wines.map((res, i) => {
return <WineTableRow obj={res} key={i} />;
});
}
render() {
return (<div className="table-wrapper">
<Table striped bordered hover className="table-dark table-sm">
<thead>
<tr>
<th>Name of wine</th>
<th>Name of winery</th>
<th>Type of wine</th>
<th>Price($)</th>
<th>Rating</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.DataTable()}
</tbody>
</Table>
</div>);
}
}
|
const shapeClasses =
'w-14 h-14 justify-center items-center rounded-lg text-white';
const itemClasses =
'flex flex-row w-full border p-3 rounded-lg gap-3 text-center';
const tagClasses = 'bg-slate-100 px-2 rounded-md';
const tagContainerClasses = 'flex gap-2 text-indigo-500';
export default function Order() {
return (
<div className="flex flex-row flex-wrap gap-3 border-2 border-indigo-300 h-full p-3 rounded-lg">
<h1 className="w-full text-indigo-500 font-bold text-2xl">Order</h1>
<pre className={tagContainerClasses}>
1.
<span className={tagClasses}>order-last</span>
</pre>
<div className={itemClasses}>
<div className={`${shapeClasses} bg-indigo-600 flex order-last`}>
01
</div>
<div className={`${shapeClasses} bg-indigo-300 flex`}>02</div>
<div className={`${shapeClasses} bg-indigo-300 flex`}>03</div>
</div>
<pre className={tagContainerClasses}>
2.
<span className={tagClasses}>order-first</span>
</pre>
<div className={itemClasses}>
<div className={`${shapeClasses} bg-indigo-300 flex`}>01</div>
<div className={`${shapeClasses} bg-indigo-300 flex`}>02</div>
<div className={`${shapeClasses} bg-indigo-600 flex order-first`}>
03
</div>
</div>
<pre className={tagContainerClasses}>
3.
<span className={tagClasses}>order-[number]</span>
</pre>
<div className={itemClasses}>
<div className={`${shapeClasses} bg-indigo-600 flex order-2`}>01</div>
<div className={`${shapeClasses} bg-indigo-600 flex order-3`}>02</div>
<div className={`${shapeClasses} bg-indigo-600 flex order-1`}>03</div>
</div>
</div>
);
}
|
@extends('userend.layout.master')
@section('content')
<nav class="page-breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#">Job</a></li>
<li class="breadcrumb-item active" aria-current="page">List</li>
</ol>
</nav>
<div class="row">
<div class="col-md-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<a href="{{route('job.create')}}" type="button" class="btn btn-inverse-primary btn-icon-text">
<i class="btn-icon-prepend" data-feather="plus-circle"></i>
Create
</a>
{{-- filter --}}
<span><h6 class="py-4">Filter</h6></span>
<select class="form-select w-25" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
{{-- filter end --}}
<div class="table-responsive pt-3">
<table class="table table-bordered">
<thead>
<tr>
<th>
#
</th>
<th>
Name
</th>
<th>
Author
</th>
<th>
Create at
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody>
@foreach ($circulars as $circular)
<tr>
<td>
{{$circulars->firstItem() + $loop->index}}
</td>
<td>
{{$circular->title}}
</td>
<td>
{{$circular->user_id}}
</td>
<td>
{{$circular->created_at->format('d M Y')}}
</td>
<td>
<form action="{{route('job.destroy', $circular->id)}}" method="post" style="display: inline">
@csrf
@method('DELETE')
<button type="submit" onclick="return confirm('Sure ! Delete Job ?')" class="btn btn-danger btn-xs btn-icon">
<i data-feather="trash"></i>
</button>
</form>
<a href="{{route('job.edit', $circular->id)}}" type="button" class="btn btn-warning btn-xs btn-icon">
<i data-feather="check-square"></i>
</a>
<a href="{{route('job.show', $circular->id)}}" type="button" class="btn btn-success btn-xs btn-icon">
<i data-feather="eye"></i>
</a>
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="py-3">
{{$circulars->links()}}
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
@push('plugin-styles')
<!-- Plugin css import here -->
@endpush
@push('plugin-scripts')
<!-- Plugin js import here -->
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
@endpush
@push('custom-scripts')
<!-- Custom js here -->
@if (Session::has('create'))
<script>
const Toast = Swal.mixin({
toast: true
, position: 'top-end'
, showConfirmButton: false
, timer: 3000
, timerProgressBar: true
, didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success'
, title: 'Job has been created!'
})
</script>
@endif
@if (Session::has('update'))
<script>
const Toast = Swal.mixin({
toast: true
, position: 'top-end'
, showConfirmButton: false
, timer: 3000
, timerProgressBar: true
, didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success'
, title: 'Job has been updated !'
})
</script>
@endif
@if (Session::has('delete'))
<script>
const Toast = Swal.mixin({
toast: true
, position: 'top-end'
, showConfirmButton: false
, timer: 3000
, timerProgressBar: true
, didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'warning'
, title: 'Job has been deleted !'
})
</script>
@endif
@endpush
|
require('dotenv').config();
import 'reflect-metadata';
import { createConnection, getConnectionOptions, useContainer } from 'typeorm';
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import { buildSchema } from 'type-graphql';
import { Container } from 'typedi';
import cookieParser from 'cookie-parser';
import { verify } from 'jsonwebtoken';
import addSeconds from 'date-fns/addSeconds';
import addDays from 'date-fns/addDays';
import { createTokens } from './auth';
import { ACCESS_TOKEN_SECRET, REFRESH_TOKEN_SECRET } from './helpers/secrets';
import { AuthResolver } from './resolvers/AuthResolver';
import { ResourceResolver } from './resolvers/ResourceResolver';
import { ResourceViewsResolver } from './resolvers/ResourceViewsResolver';
import { ResourceRatingResolver } from './resolvers/ResourceRatingResolver';
import { UserRoleResolver } from './resolvers/UserRoleResolver';
import { UserFavouriteResolver } from './resolvers/UserFavouriteResolver';
import { UserResolver } from './resolvers/UserResolver';
import { User } from './entity/User';
useContainer(Container);
(async () => {
const app = express();
app.use(cookieParser());
const options = await getConnectionOptions(
process.env.NODE_ENV || 'development'
);
await createConnection({ ...options, name: 'default' });
const apolloServer = new ApolloServer({
schema: await buildSchema({
resolvers: [
AuthResolver,
ResourceResolver,
ResourceViewsResolver,
ResourceRatingResolver,
UserRoleResolver,
UserResolver,
UserFavouriteResolver,
],
container: Container,
validate: true,
emitSchemaFile: {
path: __dirname + '/schema.graphql',
commentDescriptions: true,
},
}),
context: ({ req, res }) => ({ req, res }),
playground: {
settings: {
'request.credentials': 'include',
},
},
});
app.use(async (req, res, next) => {
const accessToken = req.cookies['access-token'];
const refreshToken = req.cookies['refresh-token'];
if (!accessToken && !refreshToken) {
return next();
}
try {
const data = verify(accessToken, ACCESS_TOKEN_SECRET!) as {
userId: number;
};
req.userId = data.userId;
return next();
} catch {}
if (!refreshToken) {
next();
}
let data;
try {
data = verify(refreshToken, REFRESH_TOKEN_SECRET!) as {
userId: number;
count: number;
};
} catch {
return next();
}
const user = await User.findOne(data.userId);
if (!user || user.count !== data.count) {
return next();
}
const tokens = createTokens(user);
res.cookie('refresh-token', tokens.refreshToken, {
expires: addDays(new Date(), 7),
});
res.cookie('access-token', tokens.accessToken, {
expires: addSeconds(new Date(), 15),
});
req.userId = data.userId;
next();
});
apolloServer.applyMiddleware({ app, cors: false });
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log(`server started at http://localhost:${port}/graphql`);
});
})();
|
<template>
<FullScreenModal
v-if="loaded"
@onClose="closeModal()"
:path="['Contact binnen besmettelijke periode', taskFragments.general.label]"
>
<!-- eslint-disable-next-line vuejs-accessibility/no-static-element-interactions -->
<template v-slot:header @click="closeModal" @keyup.enter="closeModal">
<span v-if="meta">
{{ meta.caseId }} /
<strong>{{ meta.name }}</strong>
</span>
</template>
<template v-slot:action>
<div class="contact-editing-modal-action">
<LastUpdated />
<BDropdown
class="m-md-2 dbco-select"
variant="link"
v-if="taskFragments.inform.status"
:disabled="!hasTaskEditPermission"
>
<template #button-content>
<span data-testid="inform-status">
<span
:class="[
'icon',
`icon--status-${getContentForStatus(taskFragments.inform.status).icon}`,
]"
>
</span
>{{ getContentForStatus(taskFragments.inform.status).label }}
</span>
</template>
<BDropdownItem
v-for="status in Object.values(InformStatusV1)"
:key="status"
@click="updateInformStatus(status)"
>
<div>
<span :class="['icon', `icon--status-${getContentForStatus(status).icon}`]"></span
>{{ getContentForStatus(status).label }}
</div>
</BDropdownItem>
</BDropdown>
<BButton block variant="primary" @click="closeModal()" class="text-nowrap">Terug naar index</BButton>
</div>
</template>
<template v-slot:sidebar>
<CovidCaseSidebar :schema="$as.any(schemaSidebar())" />
</template>
<FormRenderer :rules="$as.defined(rootSchema).rules.task" :schema="schema()" storeType="task" />
</FullScreenModal>
</template>
<script lang="ts">
import type { PropType } from 'vue';
import { defineComponent } from 'vue';
import CovidCaseSidebar from '@/components/caseEditor/CovidCaseSidebar/CovidCaseSidebar.vue';
import LastUpdated from '@/components/caseEditor/LastUpdated/LastUpdated.vue';
import FullScreenModal from '@/components/modals/FullScreenModal/FullScreenModal.vue';
import { getRootSchema, getSchema } from '@/components/form/ts/formSchema';
import { mapGetters } from 'vuex';
import { PermissionV1, InformStatusV1 } from '@dbco/enum';
import type { Schema } from '@/components/form/ts/schemaType';
import { StoreType } from '@/store/storeType';
import type { TaskStoreState } from '@/store/task/taskStore';
interface Data {
loaded: boolean;
InformStatusV1: typeof InformStatusV1;
rootSchema?: Schema | null;
}
export default defineComponent({
name: 'ContactEditingModal',
components: { FullScreenModal, CovidCaseSidebar, LastUpdated },
props: {
contact: { type: Object as PropType<TaskStoreState> },
},
data() {
return {
loaded: false,
InformStatusV1: InformStatusV1,
rootSchema: undefined,
} as Data;
},
async created() {
await this.$store.dispatch('task/LOAD', this.selectedTaskUuid);
await this.$store.commit('task/CHANGE', {
path: 'uuid',
values: this.selectedTaskUuid,
});
this.rootSchema = getRootSchema();
this.loaded = true;
},
async destroyed() {
await this.$store.dispatch(`${StoreType.TASK}/FETCH_TASKS`, this.caseUuid);
await this.emptySelectedTask();
},
computed: {
// eslint-disable-next-line no-warning-comments
// TODO: Cast mapGetters to resolve correct types
// mapRootGetters
...mapGetters({
meta: `${StoreType.INDEX}/meta`,
caseUuid: `${StoreType.INDEX}/uuid`,
taskFragments: `${StoreType.TASK}/fragments`,
}),
hasTaskEditPermission() {
return this.$store.getters['userInfo/hasPermission'](PermissionV1.VALUE_taskEdit);
},
selectedTaskUuid() {
return this.$store.getters[`${StoreType.TASK}/selectedTaskUuid`];
},
taskRules() {
return this.rootSchema?.rules.task;
},
},
methods: {
schema: () => getSchema('contact-modal-contagious'),
schemaSidebar: () => getSchema('contact-modal-contagious-sidebar'),
getContentForStatus: (status: string) => {
switch (status) {
case InformStatusV1.VALUE_uninformed:
return { icon: 'uninformed', label: 'Nog niet geïnformeerd' };
case InformStatusV1.VALUE_unreachable:
return { icon: 'unreachable', label: 'Geen gehoor' };
case InformStatusV1.VALUE_emailSent:
return { icon: 'email-sent', label: 'Alleen gemaild' };
case InformStatusV1.VALUE_informed:
return { icon: 'informed', label: 'Geïnformeerd' };
}
return { icon: '', label: 'Onbekend' };
},
updateInformStatus(status: InformStatusV1) {
return this.$store.dispatch(`task/UPDATE_FORM_VALUE`, {
inform: { ...this.taskFragments.inform, status: status },
});
},
async closeModal() {
this.$emit('onClose');
await this.emptySelectedTask();
},
async emptySelectedTask() {
await this.$store.commit(`${StoreType.TASK}/EMPTY_SELECTED_TASK_UUID`);
},
},
});
</script>
<style lang="scss">
.contact-editing-modal-action {
display: flex;
flex-direction: row;
align-items: center;
.dropdown-menu {
width: 230px;
li {
padding: 8px;
font-size: 0.875rem;
}
}
}
</style>
|
# Importer from OpenQASM 2 to Qiskit
[](https://opensource.org/licenses/Apache-2.0) [](https://github.com/jakelishman/qiskit-qasm2/releases) [](https://pypi.org/project/qiskit-qasm2/) [](https://coveralls.io/github/jakelishman/qiskit-qasm2?branch=main)
> [!IMPORTANT]
>
> This package is obsolete. It was vendored into Qiskit itself as of `qiskit==0.43.0` (via
> `qiskit-terra==0.24.0` at the time), at version `0.5.3` of this package. There is no longer any
> need to install this package; simply use `qiskit.qasm2.load` or `qiskit.qasm2.loads`. The Qiskit
> version is actively developed, and this package is not being updated any more.
>
> All references to Qiskit in the README and in the package itself mean Qiskit versions `<0.43`,
> before this package was vendored into Qiskit.
This repository provides the Python package `qiskit_qasm2`, which provides a
fast parser of OpenQASM 2 into Qiskit's `QuantumCircuit`. It is often 10x or
more faster than Qiskit's native parser. The API is simple:
- `qiskit_qasm2.load` takes a filename, and returns `QuantumCircuit`;
- `qiskit_qasm2.loads` takes an OpenQASM 2 program in a string, and returns
`QuantumCircuit`.
The full documentation is published to https://jakelishman.github.io/qiskit-qasm2.
A simple parsing example:
```python
import qiskit_qasm2
program = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0], q[1];
measure q -> c;
"""
qiskit_qasm2.loads(program).draw()
```
```text
┌───┐ ┌─┐
q_0: ┤ H ├──■──┤M├───
└───┘┌─┴─┐└╥┘┌─┐
q_1: ─────┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c: 2/═══════════╩══╩═
0 1
```
## Features
The parser supports all of [the OpenQASM 2
specification](https://arxiv.org/abs/1707.03429v2),
including:
- register definitions and usage (`qreg` and `creg`);
- the `qelib1.inc` as a special builtin include, precisely as described in the
paper;
- general includes, with an option to specify the search path;
- custom `gate` and `opaque` declarations;
- gate, measurement and reset broadcasting;
- conditioned gate applications, measurements and reset;
- constant folding with the scientific calculator functions in gate parameter
lists;
- mathematical expressions on parameters within custom gate bodies.
In addition, the parser also includes options to:
- modify the search path for `include` statements in OpenQASM 2;
- define overrides for how some named OpenQASM 2 gate applications should be
converted into Qiskit form;
- define new builtin quantum instructions for OpenQASM 2;
- define new builtin classical scientific-calculator functions.
Qiskit's builtin parser makes some extra-spec additions by default, with no
option to disable them. This mostly takes the form of custom gate overrides,
and various additional gates in Terra's vendored version of `qelib1.inc`
compared to the description in the paper. This parser is more type-safe than
Qiskit's, but does include [a compatibility mode](https://jakelishman.github.io/qiskit-qasm2/parse.html#qiskit-compatibility)
to ease the transition from using Qiskit's parser.
## Installation
Install the latest release of the `qiskit_qasm2` package from pip:
```bash
pip install qiskit_qasm2
```
## Developing
If you're looking to contribute to this project, please first read
[our contributing guidelines](CONTRIBUTING.md).
Set up your development environment by installing the development requirements
with pip:
```bash
pip install -r requirements-dev.txt tox
```
This installs a few more packages than the dependencies of the package at
runtime, because there are some tools we use for testing also included, such as
`tox` and `pytest`.
You will also need a working Rust toolchain. The easiest way to install one is
[by using rustup](https://rustup.rs/) on Linux, macOS or Windows.
After the development requirements are installed, you can install an editable
version of the package with
```bash
pip install -e .
```
After this, any changes you make to the library code will immediately be present
when you open a new Python interpreter session.
This package was mostly an excuse for me to learn a bit more about how lexers
are written at a low level. This is why the Rust crate doesn't use any
lexer-generation libraries. You can read a bit more about the architecture and
some of the design decisions in [the developer section of the
documentation](https://jakelishman.github.io/qiskit-qasm2/dev.html).
### Building documentation
After the development requirements have been installed, the command
```bash
tox -e docs
```
will build the HTML documentation, and place it in `docs/_build/html`. The
documentation state of the `main` branch of this repository is published to
https://jakelishman.github.io/qiskit-qasm2.
### Code style and linting
The Python components of this repository are formatted using `black`, and the
Rust components with `rustfmt`. You can run these on the required files by
running
```bash
tox -e style
```
The full lint suite can be run with
```bash
tox -e lint
```
## License
This project is licensed under [version 2.0 of the Apache License](LICENSE).
|
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript</title>
<link rel="stylesheet" href="style.css">
<style>
body {
background-image: linear-gradient(to left, #161b3e53, #ffb30062);
}
</style>
<script src="javaScript.js" ></script>
</head>
<body>
<header>
<h1>JavaScript</h1>
<nav>
<a class="nave" href="index.html" target="_blank">INDICE</a><br>
<a class="nave" href="css.html" target="_blank">CSS</a>
<a class="nave" href="html.html" target="_blank">HTML</a>
<a class="nave" href="git.html" target="_blank">Git y Github</a>
</nav>
</header>
<nav>
<a class="subindice" href="#adquirir">Adq elementos de html</a>
<a class="subindice" href="#arrays">Arrays</a>
<a class="subindice" href="#condicionales">Condicionales</a>
<a class="subindice" href="#operadores">Operadores</a>
<a class="subindice" href="#blucles">Blucles</a>
<a class="subindice" href=""></a>
<a class="subindice" href=""></a>
</nav>
<p><b class="comenta">Comentar: </b> Por linea // , por parrafos /* */</p> <br>
<hr>
<p><b>AGREGAR SCRIPT A HTML</b><br>
script src="eventos.js">/script .. / . Ponemos la etiqueta script con el nombre del archivo js dentro de head o
body segun cuando queramos que se ejecute</script>
</p>
<hr>
<p>JavaScript es sensible a Mayusculas y caracteres, las variables siempre comienzan en minuscula y luego en
mayusculas</p><br>
<ul>
<p> <b>Variables</b> Pueden contener "texto", numeros, etiquetas(acciones) etc
<li><span>var :</span> Pueden ser modificadas y redeclaradas <span style="color: green; font-size: 23px;">
✓ ✓</span></li>
<li><span>let :</span> Pueden ser modificadas pero no redeclaradas <span
style="color: green; font-size: 20px;">✓</span> <span
style="color: red; font-size: 16px;">❌ </span></li>
<li><span>const :</span> NO pueden ser modificadas ni redeclaradas </span> <span
style="color: red; font-size: 16px;">❌ ❌ </span></li>
<li>Se abren con corchete y al final se pone; si colocamos varios valores las separamos con , </li>
</ul>
</p>
<hr>
<p><b id="adquirir">Adquirir los elementos de html</b><br> Como en css, debemos colocal un id o class en html a lo que deseamos
manipular <br>
<br>
<br>
</p>
<ol>
<li>elemento/variable = <b>document.getElementById</b>(id/nombreEnHtml); Devuelve una referencia al elemento por
su id </li>
En js creamos una variable, con document.getElementById (documento obtener elemento por
Identificación) traemos el id asignado en html <br><br>
<li>document.<b>addEventlistener</b> (agregar detector de eventos)= Es un escuchador que indica al navegador que
este atento a la interacción del
usuario
document.addEventListener('tipo de evento',función); se le indica como quiere ser escuchado y que funcion
realizar al escucharse <br>
document es el documento con el id que guarde en una variable
<ul class="letrasPequenas"> <b>Tipo de eventos</b>
<li><b>blur</b> Cuando el elemento pierde el foco.</li>
<li><b>click </b>El usuario hace clic sobre el elemento.</li>
<li><b>dblclick </b> El usuario hace doble clic sobre el elemento.</li>
<li><b>focus</b> El elemento gana el foco.</li>
<li><b>keydown</b> El usuario presiona una tecla.</li>
<li><b>keypress</b> El usuario presiona una tecla y la mantiene pulsada.</li>
<li><b>keyup </b> El usuario libera la tecla.</li>
<li><b>load</b> El documento termina su carga.</li>
<li><b>mousedown</b> El usuario presiona el botón del ratón en un elemento.</li>
<li><b>mousemove</b> El usuario mueve el puntero del ratón sobre un elemento.</li>
<li><b>mouseout</b> El usuario mueve el puntero fuera de un elemento.</li>
<li><b>mouseover</b> El usuario mantiene el puntero sobre un elemento.</li>
<li><b>mouseup</b> El usuario libera el botón pulsado del ratón sobre un elemento.</li>
<li><b>unload</b> El documento se descarga, bien porque se cierra la ventana, bien porque se navega a
otra página.</li>
</ul>
<li>canvas<b>.getContext</b>(contextType, contextAttributes); ./ retorna un contexto de dibujo en el lienzo <br>
Creamos una variable en la que gardamos la variable en la que traimos el id, le asignamos en getContext/
contexto ( <b> "2d"</b>)</li>
<img src="imagenes/context.jpg" alt="contextos">
<li><b></b></li>
<li><b></b></li>
</ul>
<p><b>EJEMPLOS</b><br>
var teclas = { ../ Las teclas del teclado tienen un numero, las ponemos llamar con su nombre y su respectivo
numero<br>
UP: 38,<br>
DOWN: 40,<br>
LEFT: 37,<br>
RIGHT: 39 <br>
};
</p>
<hr>
<p><b id="arrays">ARRAYS y ejemplos</b> <br>
<p class="letrasPequenas">Creamos una variable, donde le asignamos <b>new Array()</b> vacio <br>
O en vez de new array colocamos = <b>[ ];</b> <br>
Para agregar contenido llamamos la variable usamos <b>.push</b>("nuevoContenido") push(empujar) <br> <br>
ejm 1 const ciudadesDisponibles = new Array();AGREGAMOS CON UN CORCHETE <br>
ejm 2 const ciudadesMasVendidas =[ ];<br>
ciudadesDisponibles.push("Bogota"); <br>
ciudadesDisponibles.push("Quito"); <br>
ciudadesDisponibles.push("Lima"); <br>
console.log(ciudadesDisponibles);</p>
<p><b>METODOS de array</b><br>
<img src="imagenes/metodos.png" alt=""> pequeña explicacion: <a target="_blank" href="https://www.pinterest.es/pin/468022586291963210/">video</a></p>
<img src="imagenes/js.jpg" alt="ejemplos de js">
</p>
<p class="letrasPequenas"><b>Conocer la Cantidad de la lista</b><br>
console.log(ciudadesDisponibles[2]); Aparecera Lima, la posicion inicial es 0 <br></p>
<p class="letrasPequenas"><b>Conocer la Posicion en la lista</b><br>
const cantidadCiudades = ciudadesDisponibles.length; /. .length(longitud) <br>
console.log(`Tenemos ${cantidadCiudades} ciudades disponibles`); Aparecera Tenemos 3 ciudades disponibles <br></p>
<br></p>
<hr>
<p> <b id="condicionales">CONDICIONALES</b>
<br>
<ul>
<li><b>if</b> para especificar un bloque de código que se ejecutará, si una condición especificada es verdadera</li>
<li><b>else</b> para especificar un bloque de código que se ejecutará, si la misma condición es falsa (es como un SI NO has esto)</li>
<li><b>else if</b> para especificar una nueva condición para probar, si la primera condición es falsa</li>
<li><b>switch</b></li>para especificar muchos bloques alternativos de código que se ejecutarán.
</ul>
<dl><b>if</b>
<dt> para especificar un bloque de código JavaScript que se ejecutará si una condición es verdadera.
<dd>Sintaxis <br>
if (condition) { <br>
// bloque de código que se ejecutará si la condición es verdadera
}</dd>
</dt>
</dl>
<dl><b>else</b>
<dt> para especificar un bloque de código que se ejecutará si la condición es falsa.
<dd>if (condition) { <br>
// bloque de código que se ejecutará si la condición es verdadera} <br>
else { <br>
// bloque de código que se ejecutará si la condición es falsa
}</dd>
</dt>
</dl>
<dl><b>else if</b>
<dt>para especificar una nueva condición si la primera condición es falsa.
<dd>if (condition1) { <br>
bloque de código que se ejecutará si la condición 1 es verdadera } <br>
else if (condition2) { <br>
bloque de código que se ejecutará si la condición1 es falsa y la condición2 es verdadera }<br>
else {
bloque de código que se ejecutará si la condición1 es falsa y la condición2 es falsa }</dd>
</dt>
</dl>
<dl><b></b>
<dt>
<dd></dd>
</dt>
</dl>
</br>
</p>
<hr>
<p><b id="operadores">OPERADORES</b><br>
<dl>
<dl><b>O=||</b>
<dd> ejemplo if (edadComprador >= 18 || estaAcompañado)
</dd>
</dl>
</dl>
<dl>
<dl> <b>Y=&&</b>
<dd class="letrasPequenas" >if (tienePasaje && (edadComprador >= 18) || estaAcompañado){ <br>
console.log("Comprador con pasaje. Feliz viaje"); <br>
} <br>
else { <br>
console.log("Comprador sin pasaje. No es posible hacer el embarque"): <br>
}
</dd>
</dl>
</dl>
</p>
<hr>
<p><b id="blucles">BUCLES / CICLOS</b> <a href="https://es.javascript.info/while-for"> explicacion</a>
<ul>
<li><b>for</b> por <br>
<dl>ciclo for se repite hasta que una condición especificada se evalúe como false
<dt> for ([expresiónInicial]; [expresiónCondicional]; <br> [expresiónDeActualización])
instrucción
<dd>for (let i = 0; i < 3; i++) { // muestra 0, luego 1, luego 2 <br>
alert(i);
}</dd>
</dt>
</dl>
</li>
<li><b>do while</b> hacer mientras <br>
<dl>El bucle primero ejecuta el cuerpo, luego comprueba la condición, y, mientras sea un valor verdadero, la ejecuta una y otra vez.
<dt>do { <br>
// cuerpo del bucle <br>
} while (condition);
<dd>En el siguiente ejemplo, el bucle do itera al menos una vez y se repite hasta que i ya no sea menor que 5. <br>
let i = 0; do { i += 1; console.log(i); } while (i < 5); otro ejemplo <br>
let i = 0; <br>
do {<br>
alert( i );<br>
i++;<br>
} while (i < 3);</dd>
</dt>
</dl></li>
<li><b>while</b> mientras <br>
<dl>Una declaración while ejecuta sus instrucciones siempre que una condición especificada se evalúe como true. Una instrucción while tiene el siguiente aspecto: <br>
<dt>while (condición) <br>
expresión <br>
Si la condición se vuelve false, la instrucción dentro del bucle se deja de ejecutar y el control pasa a la instrucción que sigue al bucle.
<br>
<dd>ejemplo 1 <br>
let n = 0;<br>
let x = 0; <br>
while (n < 3) { <br>
n++;<br>
x += n;} <br>
</dd>
<dd>ejemplo 2 <br>
let i = 0; <br>
while (i < 3) { // muestra 0, luego 1, luego 2 <br>
alert( i ); <br>
i++; <br>
}</dd>
<dd> <b>Las llaves no son requeridas para un cuerpo de una sola línea</b> <br>
Si el cuerpo del bucle tiene una sola sentencia, podemos omitir las llaves {…} <br>
let i = 3;<br>
while (i) alert(i--);</dd>
</dt>
</dl></li>
<li><b>labeled </b> etiquetado</li>
<li><b>break</b></li>
<li><b>continue</b></li>
<li><b>for in</b></li>
<li><b>for of</b></li>
</ul></p>
<img src="imagenes/operadores.jpg">
<footer><strong>Trucos</strong>
<ul>
<li><b>Hora</b> <br>
Aplasta en el cuadro y aparecera tu hora <button onclick="mostrar()" id="hora" width="30px" height="30px">hora</button> <br>
<p class="letrasPequenas" > en el boton de html ponemos onclick="funcion/mostrar" el nombre de la funcion de javascript que queremos que se ejecute <br>
<img src="imagenes/hora.jpg" alt="funcion de la hora"></p>
</li>
</ul>
</footer>
</body>
</html>
|
import { Observable } from 'rxjs';
import { Injectable, inject } from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivateFn,
Router,
RouterStateSnapshot,
UrlTree,
} from '@angular/router';
import { CacheServiceService } from '../cache/cache-service.service';
import { SessionStateService } from '../session/session-state.service';
import { UserService } from '../user/user.service';
import { Role } from 'src/app/type';
@Injectable({
providedIn: 'root',
})
export class CanActiveService {
constructor(
private cacheService: CacheServiceService,
private router: Router,
private stateStateService: SessionStateService,
private userService: UserService
) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
if (this.cacheService.getCookie('token')) {
const authority: Role = route.data['authority'];
if (authority && !this.userService.hasAuthority(authority)) {
this.router.navigate(['forbidden'], { replaceUrl: true });
return false;
}
return true;
} else {
this.stateStateService.storeUrl(state.url);
this.router.navigate(['login']);
return false;
}
}
canActiveLogin(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
if (this.cacheService.getCookie('token')) {
this.router.navigate(['']);
return false;
}
return true;
}
}
export const ActiveGuard: CanActivateFn = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree => {
return inject(CanActiveService).canActivate(route, state);
};
export const ActiveLoginGuard: CanActivateFn = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree => {
return inject(CanActiveService).canActiveLogin(route, state);
};
|
import { NgModule } from '@angular/core';
import { CanActivate, Routes, RouterModule } from '@angular/router';
import { SignupComponent } from '../components/signup/signup.component';
import { LoginComponent } from '../components/login/login.component';
import { SettingsComponent } from '../components/settings/settings.component';
const routes: Routes = [
{ path: 'signup', component: SignupComponent, },
{ path: 'login', component: LoginComponent, outlet: 'NotLoggedIn' },
{ path: 'usersettings', component: SettingsComponent, },
{ path: '**', component: LoginComponent, },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: []
})
export class AppRoutingModule { }
|
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { NOMI_ROUTES } from './../index';
import { useNormeStore } from './../store';
import FormNorma from './FormNorma.vue';
import { MyRouter } from '@src/helpers/MyRouter';
import { getDefaultNorma, INormaForm } from '../models/Norma';
import { MyMsg } from '@src/shared/MyMsg';
const store = useNormeStore();
const titolo_form = 'Add new standard';
const loading = ref(false);
async function salvaNorma(pojo: INormaForm) {
try {
loading.value = true;
let result = await store.saveNorma(pojo);
loading.value = false;
if (result) {
MyMsg.showSucessMsg(`Standard ${result.title} added!`);
} else {
MyMsg.showWarningMsg('Error, Standard not updated.');
}
goBack();
} catch (error) {
console.log(error);
MyMsg.showErrorMsg('Error during standard adding');
goBack();
}
}
function handleError(campi: any) {
MyMsg.showErrorMsg('Please, check mandatory fields');
}
function goBack() {
MyRouter.pushRoute(NOMI_ROUTES.LIST);
}
</script>
<template>
<div>
<FormNorma
v-show="!loading"
@m_submit="salvaNorma"
@m_cancel="goBack"
@m_error="handleError"
:config="store.formConfig"
:payload="getDefaultNorma()"
:titolo="titolo_form"
></FormNorma>
<div v-show="loading">Please wait...</div>
</div>
</template>
<style scoped></style>
|
<script setup>
import { RouterLink, RouterView } from 'vue-router'
import { onMounted, reactive, ref } from 'vue';
import useRoles from '@/composables/useRoles';
import useAuth from '@/composables/useAuth';
import { EyeIcon, EyeSlashIcon } from "@heroicons/vue/24/solid"
import Formtest from '@/components/Formtest.vue'
// import Formgdp from '@/components/Formgdp.vue'
const showPassword = ref(false);
//const { getRoles, roles, } = useRoles();
const { errors, loading } = useAuth();
const user = reactive({
username: 'Sigha',
lastname: 'Marc',
email: 'marcsigha@gmail.com',
password: '',
parishOfficial: 1,
role: 1
})
const roles = [
{name:'fidele'},
{name:'siege'},
{name:'diocese'},
{name:'charge paroissial'},
{name:'groupe de priere'}];
onMounted(async () => {
// await getRoles();
console.log(roles)
console.log(roles.name)
console.log(user.username)
});
</script>
<template>
<div class="flex items-center justify-center w-full min-h-screen p-3 bg-white">
<div class="flex flex-col items-center justify-center w-1/2 p-4 h-auto bg-slate-100 rounded-lg shadow">
<div class="relative w-36 h-36 rounded-full overflow-clip shadow">
<img src="/assets/bdt.jpg" class="relative w-full h-full object-cover"/>
<div class="absolute w-6 h-6 rounded-full bg-gray-400"></div>
</div>
<form class="flex flex-col w-full py-3 px-4">
<div class="w-full mt-3">
<label class="">
<span v-if="user.role == 1">Nom du Fidele</span>
<span v-else-if="user.role == 5">Nom de la Paroisse</span>
<span v-else-if="user.role == 4">Nom du groupe de prière </span>
<span v-else-if="user.role == 6">Nom du diocèse </span>
<span v-else-if="user.role == 7">Nom du Siège </span>
</label>
<input v-model="user.username" class="border-gray-300 mt-1 border form-input p-2 outline-none block rounded-lg shadow-sm w-full" type="text" placeholder="Ex: Marc"/>
</div>
<div class="w-full mt-3" v-if="user.role == 1">
<label class="">Prénom du Fidele</label>
<input v-model="user.lastname" class="border-gray-300 mt-1 border form-input p-2 outline-none block rounded-lg shadow-sm w-full" type="text" placeholder="Ex: Emmanuel"/>
</div>
<div class="w-full mt-3">
<label class="">Type de profil</label>
<select v-model="roles.name" class="form-select p-2 outline-none mt-1 border block border-gray-300 rounded-lg shadow-sm w-full">
<template v-for="role in roles" :key="role.id">
<option v-if="role.name != 'Public' && role.name != 'Admin'" :value="roles.name">{{ role.name }}</option>
</template>
</select>
</div>
<div class="w-full mt-3" v-if="user.role == 1">
<label class="">Chargé paroissial</label>
<div class=" flex mt-1 items-center space-x-2">
<input type="radio" class="form-radio border-gray-300" id="yes" v-model="user.parishOfficial" :value="{number: 1}">
<label for="yes">Oui</label>
<input type="radio" class="form-radio border-gray-300" id="no" v-model="user.parishOfficial" :value="{number: false}">
<label for="no">Non</label>
</div>
</div>
<div class="w-full mt-3">
<label class="">Adresse mail</label>
<input v-model="user.email" class="border-gray-300 border form-input p-2 mt-1 outline-none block rounded-lg shadow-sm w-full" type="text" placeholder="Ex: nom@xyz.com"/>
</div>
<input class="p-2 mt-8 rounded-lg bg-gradient-to-r from-blue-500 to-blue-600 text-white font-semibold cursor-pointer" type="submit" value="Modifier"/>
</form>
</div>
</div>
<hr class="my-4">
<div class="flex items-center justify-center w-full min-h-screen p-3 bg-white">
<div class="flex flex-col items-center justify-center w-1/2 p-4 h-auto bg-slate-100 rounded-lg shadow">
<h1>INFORMATIONS SUPPLEMENTAIRES</h1>
<form class="flex flex-col w-full py-3 px-4 border-none" v-if="roles.name === 'fidele'">
<Formtest />
<input class="p-2 mt-8 rounded-lg bg-gradient-to-r from-blue-500 to-blue-600 text-white font-semibold cursor-pointer" type="submit" value="Enregistrer"/>
</form>
<form class="flex flex-col w-full py-3 px-4 border-none" v-if="roles.name === 'siege'">
<Formtest />
<input class="p-2 mt-8 rounded-lg bg-gradient-to-r from-blue-500 to-blue-600 text-white font-semibold cursor-pointer" type="submit" value="Enregistrer"/>
</form>
<form class="flex flex-col w-full py-3 px-4 border-none" v-if="roles.name === 'diocese'">
<Formtest />
<input class="p-2 mt-8 rounded-lg bg-gradient-to-r from-blue-500 to-blue-600 text-white font-semibold cursor-pointer" type="submit" value="Enregistrer"/>
</form>
<form class="flex flex-col w-full py-3 px-4 border-none" v-if="roles.name === 'charge paroissial'">
<Formtest />
<input class="p-2 mt-8 rounded-lg bg-gradient-to-r from-blue-500 to-blue-600 text-white font-semibold cursor-pointer" type="submit" value="Enregistrer"/>
</form>
<form class="flex flex-col w-full py-3 px-4 border-none" v-if="roles.name === 'groupe de priere'">
<!-- <Formgdp /> -->
<input class="p-2 mt-8 rounded-lg bg-gradient-to-r from-blue-500 to-blue-600 text-white font-semibold cursor-pointer" type="submit" value="Enregistrer"/>
</form>
</div>
</div>
</template>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.