text stringlengths 184 4.48M |
|---|
const path = require('path');
const ejs = require('ejs');
const userModel = require('../model/user.model');
const recipeModel = require('../model/recipe.model');
class AdminController{
async getUsers(req, res) {
const template = path.join(__dirname, '..', '..', 'frontend', 'view', 'users.ejs');
const users = await userModel.getAll();
const role = req.user.role;
let html = await ejs.renderFile(template, { role, users });
res.send(html);
}
async getChangeRecipe(req, res) {
const template = path.join(__dirname, '..', '..', 'frontend', 'view', 'recipe-change.ejs');
const recipeId = req.params.id;
const role = req.user.role;
const recipe = await recipeModel.getRecipe(recipeId);
const ingredients = await recipeModel.getIngredients(recipeId)
const steps = await recipeModel.getSteps(recipeId)
let html = await ejs.renderFile(template, { role, recipe, ingredients, steps });
res.send(html);
}
async updateUser(req, res) {
const userId = req.params.id;
let { name, last_name, login, role } = req.body;
if (role === 'Администратор') role = 2;
else role = 1;
try {
await userModel.updateUser(userId, name, last_name, login, role);
return res.status(200).json({ message: 'Данные пользователя успешно обновлены' });
} catch (error) {
return res.status(500).json({ message: 'Ошибка при обновлении данных пользователя', error: error.message });
}
}
async deleteUser(req, res) {
const userId = req.params.id;
try {
await userModel.deleteById(userId);
return res.status(200).json({ message: 'Данные пользователя успешно обновлены' });
} catch (error) {
return res.status(500).json({ message: 'Ошибка при обновлении данных пользователя', error: error.message });
}
}
async deleteRecipe(req, res) {
const recipeId = req.params.id;
try {
await recipeModel.deleteById(recipeId);
return res.status(200).json({ message: 'Рецепт удалён' });
} catch (error) {
return res.status(500).json({ message: 'Ошибка при удалении рецепта', error: error.message });
}
}
}
module.exports = new AdminController(); |
import {Fragment, useMemo} from 'react';
import {useCart} from '@shopify/hydrogen-react';
import {Navigation} from 'swiper/modules';
import {Swiper, SwiperSlide} from 'swiper/react';
import {Disclosure} from '@headlessui/react';
import type {CartLine} from '@shopify/hydrogen/storefront-api-types';
import {Svg} from '~/components';
import type {CartUpsellProps} from '../Cart.types';
import {CartUpsellItem} from './CartUpsellItem';
export function CartUpsell({closeCart, settings}: CartUpsellProps) {
const {lines = []} = useCart();
const cartLines = lines as CartLine[];
const {message = '', products = []} = {...settings?.upsell};
const productsNotInCart = useMemo(() => {
if (!cartLines?.length || !products?.length) return [];
return products.filter(({product}) => {
return !cartLines.some((line) => {
return line.merchandise.product.handle === product.handle;
});
});
}, [cartLines, products]);
const showUpsell = lines?.length > 0 && productsNotInCart?.length > 0;
return showUpsell ? (
<Disclosure
as="div"
className="flex flex-col border-t border-t-border"
defaultOpen
>
{({open}) => (
<>
<Disclosure.Button
aria-label={`${open ? 'Collapse' : 'Expand'} upsells`}
type="button"
className="relative px-4 py-3"
>
<h3 className="px-5 text-center text-xs font-normal">{message}</h3>
<div className="absolute right-4 top-1/2 -translate-y-1/2 text-mediumDarkGray">
{open ? (
<Svg
className="w-4 text-current"
src="/svgs/minus.svg#minus"
title="Minus"
viewBox="0 0 24 24"
/>
) : (
<Svg
className="w-4 text-current"
src="/svgs/plus.svg#plus"
title="Plus"
viewBox="0 0 24 24"
/>
)}
</div>
</Disclosure.Button>
<Disclosure.Panel as={Fragment}>
<Swiper
className="mb-4 w-full px-2"
grabCursor
modules={[Navigation]}
navigation={{
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
}}
slidesPerView={1}
spaceBetween={0}
>
{productsNotInCart.map(({product}, index) => {
return (
<SwiperSlide key={index}>
<CartUpsellItem
closeCart={closeCart}
handle={product.handle}
isOnlyUpsell={products.length === 1}
/>
</SwiperSlide>
);
})}
{/* Navigation */}
<div>
<div className="swiper-button-prev left-0 after:hidden">
<Svg
className="max-w-[1rem] text-text"
src="/svgs/chevron-left.svg#chevron-left"
title="Arrow Left"
viewBox="0 0 24 24"
/>
</div>
<div className="swiper-button-next right-0 after:hidden">
<Svg
className="max-w-[1rem] text-text"
src="/svgs/chevron-right.svg#chevron-right"
title="Arrow Right"
viewBox="0 0 24 24"
/>
</div>
</div>
</Swiper>
</Disclosure.Panel>
</>
)}
</Disclosure>
) : null;
}
CartUpsell.displayName = 'CartUpsell'; |
package com.valkov;
public class Car {
private int cylinders;
private String name;
private int wheels;
private boolean engine;
public Car(int cylinders, String name) {
this.cylinders = cylinders;
this.name = name;
this.wheels = 4;
this.engine = true;
}
public int getCylinders() {
return cylinders;
}
public String getName() {
return name;
}
public int getWheels() {
return wheels;
}
public boolean isEngine() {
return engine;
}
public String startEngine() {
return "Engine has been started";
}
public String accelerate() {
return "Car is accelerating";
}
public String brake() {
return "Car is braking";
}
}
class Mercedes extends Car{
public Mercedes(int cylinders, String name) {
super(cylinders, name);
}
@Override
public String startEngine() {
return "Mercedes has started";
}
@Override
public String accelerate() {
return "Mercedes is accelerating";
}
@Override
public String brake() {
return "Mercedes is braking";
}
}
class Ford extends Car{
public Ford(int cylinders, String name) {
super(cylinders, name);
}
@Override
public String startEngine() {
return "Ford has started";
}
@Override
public String accelerate() {
return "Ford is accelerating";
}
@Override
public String brake() {
return "Ford is braking";
}
}
class Peugot extends Car{
public Peugot(int cylinders, String name) {
super(cylinders, name);
}
@Override
public String startEngine() {
return getClass().getSimpleName()+ " has started";
}
@Override
public String accelerate() {
return getClass().getSimpleName()+ " is accelerating";
}
@Override
public String brake() {
return getClass().getSimpleName()+" is braking";
}
} |
package com.example.isuautosched;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.button.MaterialButton;
import com.google.type.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.TimeZone;
public class DayCalendarScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day_calendar);
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime dateTime = LocalDateTime.now();
/* MOCK DATA */
// JSONArray mockData = new JSONArray();
// try {
// JSONObject data = new JSONObject();
// data.put("name", "testname1");
// data.put("start", "2021-12-10 16:00");
// data.put("end", "2021-12-10 16:40");
// mockData.put(data);
// data = new JSONObject();
// data.put("name", "testname2");
// data.put("start", "2021-12-10 17:00");
// data.put("end", "2021-12-10 17:40");
// mockData.put(data);
// } catch(JSONException e) {
// e.printStackTrace();
// }
//
// LinearLayout eventList = (LinearLayout) findViewById(R.id.eventList);
// // Generate conflict circles
// for (int i = 0; i < mockData.length(); i++) {
// // Attempt to generate the button
// try {
// // Format times
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-dd HH:mm", Locale.ENGLISH);
// LocalDateTime start = LocalDateTime.parse(mockData.getJSONObject(i).getString("start"), formatter);
// LocalDateTime end = LocalDateTime.parse(mockData.getJSONObject(i).getString("end"), formatter);
// eventList.addView(generateConflictBubble(mockData.getJSONObject(i).getString("name"), start, end));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
/* MOCK DATA */
// Get Conflicts
JSONObject sessionId = new JSONObject();
try {
sessionId.put("userid",CurrentUser.getId());
sessionId.put("sessionid",CurrentUser.getSessionId());
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue queue = Volley.newRequestQueue(DayCalendarScreen.this);
CustomJsonArrayRequest groupListRequest = new CustomJsonArrayRequest(Request.Method.POST, Constants.BASE_URL + "calendar/day/" + dateTime.atZone(zoneId).toEpochSecond(), sessionId, new Response.Listener<org.json.JSONArray>() {
@Override
public void onResponse(JSONArray response) {
System.out.println(response);
// Display conflicts
if (response.length() > 0) {
LinearLayout eventList = (LinearLayout) findViewById(R.id.eventList);
// Generate conflict circles
for (int i = 0; i < response.length(); i++) {
// Attempt to generate the button
try {
// Format times
String startTime = response.getJSONObject(i).getString("start");
String[] stuff = startTime.split("T", 2);
String endTime = response.getJSONObject(i).getString("end");
String[] otherStuff = endTime.split("T", 2);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-dd HH:mm", Locale.ENGLISH);
LocalDateTime start = LocalDateTime.parse(stuff[0] + " " + stuff[1], formatter);
LocalDateTime end = LocalDateTime.parse(otherStuff[0] + " " + otherStuff[1], formatter);
eventList.addView(generateConflictBubble(response.getJSONObject(i).getString("name"), start, end));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(DayCalendarScreen.this);
alertDialogBuilder.setTitle("Error");
alertDialogBuilder.setMessage(error.getMessage());
alertDialogBuilder.setPositiveButton("Ok", null);
alertDialogBuilder.setNegativeButton("", null);
alertDialogBuilder.create().show();
}
});
queue.add(groupListRequest);
}
LinearLayout generateConflictBubble(String name, LocalDateTime start, LocalDateTime end) {
LinearLayout conflictBubble = new LinearLayout(DayCalendarScreen.this);
TextView nameDisplay = new TextView(DayCalendarScreen.this);
TextView timeDisplay = new TextView(DayCalendarScreen.this);
TextView border = new TextView(DayCalendarScreen.this);
nameDisplay.setText(name);
timeDisplay.setText(start.getHour() + ":" + start.getMinute() + "-" + end.getHour() + ":" + end.getMinute());
border.setText("-------------------------------");
conflictBubble.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
conflictBubble.setOrientation(LinearLayout.VERTICAL);
float scale = getResources().getDisplayMetrics().density;
conflictBubble.setPadding((int) Math.ceil(10 * scale),(int) Math.ceil(10 * scale),(int) Math.ceil(10 * scale),(int) Math.ceil(10 * scale));
conflictBubble.addView(nameDisplay);
conflictBubble.addView(timeDisplay);
conflictBubble.addView(border);
return conflictBubble;
}
} |
using System;
namespace Server.Items
{
public abstract class BaseGiftCloak : BaseGiftClothing
{
public BaseGiftCloak(int itemID)
: this(itemID, 0) { }
public BaseGiftCloak(int itemID, int hue)
: base(itemID, Layer.Cloak, hue) { }
public BaseGiftCloak(Serial serial)
: base(serial) { }
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[Flipable]
public class GiftCloak : BaseGiftCloak, IArcaneEquip
{
#region Arcane Impl
private int m_MaxArcaneCharges,
m_CurArcaneCharges;
[CommandProperty(AccessLevel.GameMaster)]
public int MaxArcaneCharges
{
get { return m_MaxArcaneCharges; }
set
{
m_MaxArcaneCharges = value;
InvalidateProperties();
Update();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public int CurArcaneCharges
{
get { return m_CurArcaneCharges; }
set
{
m_CurArcaneCharges = value;
InvalidateProperties();
Update();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public bool IsArcane
{
get { return (m_MaxArcaneCharges > 0 && m_CurArcaneCharges >= 0); }
}
public void Update()
{
if (IsArcane)
ItemID = 0x26AD;
else if (ItemID == 0x26AD)
ItemID = 0x1515;
if (IsArcane && CurArcaneCharges == 0)
Hue = 0;
}
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
if (IsArcane)
list.Add(1061837, "{0}\t{1}", m_CurArcaneCharges, m_MaxArcaneCharges); // arcane charges: ~1_val~ / ~2_val~
}
public override void OnSingleClick(Mobile from)
{
base.OnSingleClick(from);
if (IsArcane)
LabelTo(
from,
1061837,
String.Format("{0}\t{1}", m_CurArcaneCharges, m_MaxArcaneCharges)
);
}
public void Flip()
{
if (ItemID == 0x1515)
ItemID = 0x1530;
else if (ItemID == 0x1530)
ItemID = 0x1515;
}
#endregion
[Constructable]
public GiftCloak()
: this(0) { }
[Constructable]
public GiftCloak(int hue)
: base(0x1515, hue)
{
Weight = 5.0;
}
public GiftCloak(Serial serial)
: base(serial) { }
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)1); // version
if (IsArcane)
{
writer.Write(true);
writer.Write((int)m_CurArcaneCharges);
writer.Write((int)m_MaxArcaneCharges);
}
else
{
writer.Write(false);
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch (version)
{
case 1:
{
if (reader.ReadBool())
{
m_CurArcaneCharges = reader.ReadInt();
m_MaxArcaneCharges = reader.ReadInt();
if (Hue == 2118)
Hue = ArcaneGem.DefaultArcaneHue;
}
break;
}
}
if (Weight == 4.0)
Weight = 5.0;
}
}
[Flipable(0x230A, 0x2309)]
public class GiftFurCape : BaseGiftCloak
{
[Constructable]
public GiftFurCape()
: this(0) { }
[Constructable]
public GiftFurCape(int hue)
: base(0x230A, hue)
{
Weight = 4.0;
}
public GiftFurCape(Serial serial)
: base(serial) { }
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} |
//! A tx for a PoS unbond that removes staked tokens from a self-bond or a
//! delegation to be withdrawn in or after unbonding epoch.
use namada_tx_prelude::*;
#[transaction(gas = 1119469)]
fn apply_tx(ctx: &mut Ctx, tx_data: Tx) -> TxResult {
let signed = tx_data;
let data = signed.data().ok_or_err_msg("Missing data").map_err(|err| {
ctx.set_commitment_sentinel();
err
})?;
let withdraw = transaction::pos::Withdraw::try_from_slice(&data[..])
.wrap_err("failed to decode Withdraw")?;
let slashed =
ctx.withdraw_tokens(withdraw.source.as_ref(), &withdraw.validator)?;
if !slashed.is_zero() {
debug_log!("New withdrawal slashed for {}", slashed.to_string_native());
}
Ok(())
}
#[cfg(test)]
mod tests {
use namada::ledger::pos::{OwnedPosParams, PosVP};
use namada::proof_of_stake::types::GenesisValidator;
use namada::proof_of_stake::unbond_handle;
use namada::types::dec::Dec;
use namada::types::storage::Epoch;
use namada_tests::log::test;
use namada_tests::native_vp::pos::init_pos;
use namada_tests::native_vp::TestNativeVpEnv;
use namada_tests::tx::*;
use namada_tx_prelude::address::testing::{
arb_established_address, arb_non_internal_address,
};
use namada_tx_prelude::address::InternalAddress;
use namada_tx_prelude::borsh_ext::BorshSerializeExt;
use namada_tx_prelude::chain::ChainId;
use namada_tx_prelude::key::testing::arb_common_keypair;
use namada_tx_prelude::key::RefTo;
use namada_tx_prelude::proof_of_stake::parameters::testing::arb_pos_params;
use proptest::prelude::*;
use super::*;
proptest! {
/// In this test we setup the ledger and PoS system with an arbitrary
/// initial state with 1 genesis validator, a delegation bond if the
/// withdrawal is for a delegation, arbitrary PoS parameters and
/// a we generate an arbitrary withdrawal that we'd like to apply.
///
/// After we apply the withdrawal, we're checking that all the storage
/// values in PoS system have been updated as expected and then we also
/// check that this transaction is accepted by the PoS validity
/// predicate.
#[test]
fn test_tx_withdraw(
(initial_stake, unbonded_amount) in arb_initial_stake_and_unbonded_amount(),
withdraw in arb_withdraw(),
// A key to sign the transaction
key in arb_common_keypair(),
pos_params in arb_pos_params(None)) {
test_tx_withdraw_aux(initial_stake, unbonded_amount, withdraw, key,
pos_params).unwrap()
}
}
fn test_tx_withdraw_aux(
initial_stake: token::Amount,
unbonded_amount: token::Amount,
withdraw: transaction::pos::Withdraw,
key: key::common::SecretKey,
pos_params: OwnedPosParams,
) -> TxResult {
// Remove the validator stake threshold for simplicity
let pos_params = OwnedPosParams {
validator_stake_threshold: token::Amount::zero(),
..pos_params
};
let is_delegation = matches!(
&withdraw.source, Some(source) if *source != withdraw.validator);
let consensus_key = key::testing::keypair_1().ref_to();
let protocol_key = key::testing::keypair_2().ref_to();
let eth_cold_key = key::testing::keypair_3().ref_to();
let eth_hot_key = key::testing::keypair_4().ref_to();
let commission_rate = Dec::new(5, 2).expect("Cannot fail");
let max_commission_rate_change = Dec::new(1, 2).expect("Cannot fail");
let genesis_validators = [GenesisValidator {
address: withdraw.validator.clone(),
tokens: if is_delegation {
// If we're withdrawing a delegation, we'll give the initial
// stake to the delegation instead of the
// validator
token::Amount::zero()
} else {
initial_stake
},
consensus_key,
protocol_key,
eth_cold_key,
eth_hot_key,
commission_rate,
max_commission_rate_change,
metadata: Default::default(),
}];
let pos_params =
init_pos(&genesis_validators[..], &pos_params, Epoch(0));
let native_token = tx_host_env::with(|tx_env| {
let native_token = tx_env.wl_storage.storage.native_token.clone();
if is_delegation {
let source = withdraw.source.as_ref().unwrap();
tx_env.spawn_accounts([source]);
// To allow to unbond delegation, there must be a delegation
// bond first.
// First, credit the bond's source with the initial stake,
// before we initialize the bond below
tx_env.credit_tokens(source, &native_token, initial_stake);
}
native_token
});
if is_delegation {
// Initialize the delegation - unlike genesis validator's self-bond,
// this happens at pipeline offset
ctx().bond_tokens(
withdraw.source.as_ref(),
&withdraw.validator,
initial_stake,
)?;
}
// Unbond the `unbonded_amount` at the starting epoch 0
ctx().unbond_tokens(
withdraw.source.as_ref(),
&withdraw.validator,
unbonded_amount,
)?;
tx_host_env::commit_tx_and_block();
// Fast forward to pipeline + unbonding + cubic_slashing_window_length
// offset epoch so that it's possible to withdraw the unbonded
// tokens
tx_host_env::with(|env| {
for _ in 0..(pos_params.pipeline_len
+ pos_params.unbonding_len
+ pos_params.cubic_slashing_window_length)
{
env.wl_storage.storage.block.epoch =
env.wl_storage.storage.block.epoch.next();
}
});
let bond_epoch = if is_delegation {
Epoch(pos_params.pipeline_len)
} else {
Epoch::default()
};
let withdraw_epoch = Epoch(
pos_params.pipeline_len
+ pos_params.unbonding_len
+ pos_params.cubic_slashing_window_length,
);
assert_eq!(
tx_host_env::with(|env| env.wl_storage.storage.block.epoch),
Epoch(
pos_params.pipeline_len
+ pos_params.unbonding_len
+ pos_params.cubic_slashing_window_length
)
);
let tx_code = vec![];
let tx_data = withdraw.serialize_to_vec();
let mut tx = Tx::new(ChainId::default(), None);
tx.add_code(tx_code, None)
.add_serialized_data(tx_data)
.sign_wrapper(key);
let signed_tx = tx;
// Read data before we apply tx:
let pos_balance_key = token::balance_key(
&native_token,
&Address::Internal(InternalAddress::PoS),
);
let pos_balance_pre: token::Amount = ctx()
.read(&pos_balance_key)?
.expect("PoS must have balance");
assert_eq!(pos_balance_pre, initial_stake);
let unbond_src = withdraw
.source
.clone()
.unwrap_or_else(|| withdraw.validator.clone());
let handle = unbond_handle(&unbond_src, &withdraw.validator);
let unbond_pre =
handle.at(&bond_epoch).get(ctx(), &withdraw_epoch).unwrap();
assert_eq!(unbond_pre, Some(unbonded_amount));
apply_tx(ctx(), signed_tx)?;
// Read the data after the tx is executed
let unbond_post =
handle.at(&withdraw_epoch).get(ctx(), &bond_epoch).unwrap();
assert!(
unbond_post.is_none(),
"Because we're withdraw the full unbonded amount, there should be \
no unbonds left"
);
let pos_balance_post: token::Amount = ctx()
.read(&pos_balance_key)?
.expect("PoS must have balance");
assert_eq!(pos_balance_pre - pos_balance_post, unbonded_amount);
// Use the tx_env to run PoS VP
let tx_env = tx_host_env::take();
let vp_env = TestNativeVpEnv::from_tx_env(tx_env, address::POS);
let result = vp_env.validate_tx(PosVP::new);
let result =
result.expect("Validation of valid changes must not fail!");
assert!(
result,
"PoS Validity predicate must accept this transaction"
);
Ok(())
}
fn arb_initial_stake_and_unbonded_amount()
-> impl Strategy<Value = (token::Amount, token::Amount)> {
// Generate initial stake
token::testing::arb_amount_non_zero_ceiled((i64::MAX / 8) as u64)
.prop_flat_map(|initial_stake| {
// Use the initial stake to limit the unbonded amount from the
// stake
let unbonded_amount =
token::testing::arb_amount_non_zero_ceiled(
u128::try_from(initial_stake).unwrap() as u64,
);
// Use the generated initial stake too too
(Just(initial_stake), unbonded_amount)
})
}
fn arb_withdraw() -> impl Strategy<Value = transaction::pos::Withdraw> {
(
arb_established_address(),
prop::option::of(arb_non_internal_address()),
)
.prop_map(|(validator, source)| {
transaction::pos::Withdraw {
validator: Address::Established(validator),
source,
}
})
}
} |
import { createContext, ReactNode, useContext, useEffect, useRef, useState } from 'react';
import { toast } from 'react-toastify';
import { api } from '../services/api';
import { Product, Stock } from '../types';
interface CartProviderProps {
children: ReactNode;
}
interface UpdateProductAmount {
productId: number;
amount: number;
}
interface CartContextData {
cart: Product[];
addProduct: (productId: number) => Promise<void>;
removeProduct: (productId: number) => void;
updateProductAmount: ({ productId, amount }: UpdateProductAmount) => void;
}
const CartContext = createContext<CartContextData>({} as CartContextData);
export function CartProvider({ children }: CartProviderProps): JSX.Element {
const [cart, setCart] = useState<Product[]>(() => {
const prevCart = localStorage.getItem('@RocketShoes:cart')
return prevCart !== null ? JSON.parse(prevCart) : [];
});
useEffect(() => {
prevCartRef.current = cart
})
const prevCartRef = useRef<Product[]>();
const prevCartValue = prevCartRef.current ?? cart;
useEffect(() => {
if(prevCartValue !== cart){
localStorage.setItem('@RocketShoes:cart', JSON.stringify(cart))
}
}, [cart, prevCartValue])
const addProduct = async (productId: number) => {
try {
const updatedCart = [...cart]
const productInTheCart = updatedCart.find(product => product.id === productId)
const { data: stock } = await api.get(`/stock/${productId}`)
const currentAmount = productInTheCart ? productInTheCart.amount : 0;
const amount = currentAmount + 1
if (amount > stock.amount) {
toast.error('Quantidade solicitada fora de estoque')
return
}
if (productInTheCart) {
productInTheCart.amount = amount
} else {
const { data: product } = await api.get(`/products/${productId}`)
const newProduct = {
...product,
amount: 1
}
updatedCart.push(newProduct)
}
setCart(updatedCart)
} catch {
toast.error('Erro na adição do produto')
}
};
const removeProduct = (productId: number) => {
try {
const updatedCart = [...cart]
const productIndex = updatedCart.findIndex(product => product.id === productId)
if (productIndex <= -1) throw new Error()
updatedCart.splice(productIndex, 1)
setCart(updatedCart)
} catch {
toast.error('Erro na remoção do produto')
}
};
const updateProductAmount = async ({
productId,
amount,
}: UpdateProductAmount) => {
try {
if(amount <= 0) return
const { data: stock} = await api.get(`/stock/${productId}`)
if(amount > stock.amount){
toast.error('Quantidade solicitada fora de estoque')
return
}
const updatedCart = [...cart]
const productExists = updatedCart.find(product => product.id === productId)
if(productExists){
productExists.amount = amount
setCart(updatedCart)
}else{
throw new Error()
}
} catch {
toast.error('Erro na alteração de quantidade do produto')
}
};
return (
<CartContext.Provider
value={{ cart, addProduct, removeProduct, updateProductAmount }}
>
{children}
</CartContext.Provider>
);
}
export function useCart(): CartContextData {
const context = useContext(CartContext);
return context;
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.one{
font-size: 20px;
color: blue;
border: 1px solid green;
}
</style>
</head>
<body>
<div class = "one">Class One - 1</div>
<div class = "one">Class One - 1</div>
<div class = "one">Class One - 1</div>
<hr>
<div class = "apple">
<div class = "banana">banana</div>
<div class = "kiwi">kiwi</div>
</div>
<h3>h3-1</h3>
<h3>h3-2</h3>
<h3>h3-3</h3>
<h3>h3-4</h3>
<script>
//복수개의 엘리면트를 반환 - class 명이 one 인 모든 요소값을 반환
var a1 = document.getElementsByClassName("one");
document.write("class one은 총 " + a1.length + "개 입니다<br>");
//a1의 첫번째 요소의 style값중 font-size를 50px로 변경
a1[0].style.fontSize="50px";
//a2의 2번째 요소의 color값을 "Red" 로변경
a1[1].style.color="red";
//a1전체에 일괄적으로 글꼴변경
for(var a of a1){
a.style.fontFamily = "궁서체";
}
//a3의 3번째 요소의 border를 "3px solid gray" 로 변경
a1[2].style.border="3px solid gray";
//복수개의 엘리먼트를 반환- 태그명이 div 인 모든 요소값을 반환
var a2=document.getElementsByTagName("div");
document.write(`div 의 갯수는 총 ${a2.length}개입니다<br>`);//6
//a2 배열 전체에 일괄적으로 배경색 추가하기
// for(var idx in a2){
// a2[idx].style.backgroundColor="#ffffcc";
// }
for(var i=0;i<a2.length;i++){
a2[i].style.backgroundColor="#ffffcc";
}
//클래스명이 one인 엘리먼트의 첫번째 값 1개만 반환 (배열x)
var a3 = document.querySelector(".one");
document.write("class one 은 총 " + a3.length + "개 입니다.<br>");
a3.style.fontSize = "70px";
//클래스명이 one인 엘리먼트이 모든값을 배열형태로 반환
var a4 = document.querySelectorAll(".one");
document.write("class one 은 총 " + a4.length + "개 입니다.<br>");
for(var a of a4)
{
a.style.color="magenta";
}
//class apple 바로 아래의 class명이 banana인 요소값
var a5=document.querySelector(".apple>.banana");
a5.style.textDecoration="underline";
//class apple 바로 아래의 class명아 kiwi인 요소값
var a6 = document.querySelector(".apple >.kiwi");
a6.style.color="green";
//복수개의 엘리먼트 반환 - 배열타입
var a7 = document.querySelectorAll("h3");
document.write("태그 h3은 총 " + a7.length + "개 입니다.<br>");
for(var a of a7){
a.style.backgroundColor="lightgray";
}
</script>
</body>
</html> |
//! Fuzz target to generate random invalid body and query to the router and check it doesn't panic
#![allow(unused_attributes)]
#![no_main]
use std::char::REPLACEMENT_CHARACTER;
use std::env;
use std::process::Child;
use std::process::Command;
use std::process::Stdio;
use std::sync::atomic::AtomicBool;
use std::sync::OnceLock;
use std::time::Duration;
use libfuzzer_sys::fuzz_target;
use serde_json::json;
const ROUTER_CMD: &str = "router";
const ROUTER_CONFIG_PATH: &str = "./examples/graphql/local.graphql";
const ROUTER_URL: &str = "http://localhost:4000";
static ROUTER_INIT: AtomicBool = AtomicBool::new(false);
static ROUTER_PROCESS: OnceLock<ChildProcessGuard> = OnceLock::new();
#[derive(Debug)]
struct ChildProcessGuard(Child);
impl Drop for ChildProcessGuard {
fn drop(&mut self) {
if let Err(e) = self.0.kill() {
eprintln!("Could not kill child process: {}", e);
}
}
}
fuzz_target!(|data: &[u8]| {
let _ = env_logger::try_init();
if !ROUTER_INIT.swap(true, std::sync::atomic::Ordering::Relaxed) {
let mut cmd =
Command::new(env::var("ROUTER_CMD").unwrap_or_else(|_| ROUTER_CMD.to_string()))
.arg("--supergraph")
.arg(
env::var("ROUTER_CONFIG_PATH")
.unwrap_or_else(|_| ROUTER_CONFIG_PATH.to_string()),
)
.arg("--hot-reload")
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.spawn()
.expect("cannot launch the router");
std::thread::sleep(Duration::from_secs(3));
if let Ok(Some(exit_status)) = cmd.try_wait() {
panic!("the router exited with exit code : {}", exit_status);
}
ROUTER_PROCESS
.set(ChildProcessGuard(cmd))
.expect("cannot set the router child process");
}
let query = data.to_vec();
let http_client = reqwest::blocking::Client::new();
let router_response = http_client.post(ROUTER_URL).body(query.clone()).send();
if let Err(err) = router_response {
eprintln!("bad body: {query:?}");
panic!("{}", err);
}
let query = String::from_utf8_lossy(data).replace(REPLACEMENT_CHARACTER, "");
let http_client = reqwest::blocking::Client::new();
let router_response = http_client
.post(ROUTER_URL)
.json(&json!({"query": query}))
.send();
if let Err(err) = router_response {
eprintln!("bad query: {query:?}");
panic!("{}", err);
}
}); |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package abstractFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Weslei
*/
public class CustomerTest {
@Test
public void printCommonCustomerBenefits() {
AbstractFactory factory = new FactoryCustomerCommon();
Customer customer = new Customer(factory);
assertEquals("Beneficios cliente comum", customer.printBenefits());
}
@Test
public void printCommonCustomerDiscount() {
AbstractFactory factory = new FactoryCustomerCommon();
Customer customer = new Customer(factory);
assertEquals("Descontos cliente comum", customer.printDiscount());
}
@Test
public void printVipCustomerBenefits() {
AbstractFactory factory = new FactoryCustomerVip();
Customer customer = new Customer(factory);
assertEquals("Beneficios cliente vip", customer.printBenefits());
}
@Test
public void printVipCustomerDiscount() {
AbstractFactory factory = new FactoryCustomerVip();
Customer customer = new Customer(factory);
assertEquals("Descontos cliente vip", customer.printDiscount());
}
} |
import React, { useState } from 'react'
import './Buscador.css'
import { Link } from 'react-router-dom'
const Buscador = () => {
const urlBase = 'https://api.themoviedb.org/3/search/multi'
const API_KEY = ''
const [busqueda, setBusqueda] = useState('')
const [peliculas, setPeliculas] = useState([])
const [series, setSeries] = useState([])
const handleInputChange = e => {
setBusqueda(e.target.value)
}
const handleSubmit = async e => {
e.preventDefault()
await fetchPeliculas()
}
const fetchPeliculas = async () => {
try {
const response = await fetch(
`${urlBase}?query=${busqueda}&api_key=${API_KEY}&language=es-MX`
)
const data = await response.json()
// Separar películas y series en diferentes arreglos
const peliculasResult = data.results.filter(
item => item.media_type === 'movie'
)
const seriesResult = data.results.filter(item => item.media_type === 'tv')
setPeliculas(peliculasResult)
setSeries(seriesResult)
} catch (error) {
console.error('Ha ocurrido un error: ', error)
}
}
return (
<div className='container'>
<h1 className='title'>Buscador de Películas y Series</h1>
<form onSubmit={handleSubmit} className='search-form'>
<input
type='text'
placeholder='Escribe el título de una película o serie'
value={busqueda}
onChange={handleInputChange}
className='search-input'
/>
<button type='submit' className='search-button'>
Buscar
</button>
</form>
{/* Contenedor de la búsqueda */}
<div className='movie-list'>
{/* Sección de Películas */}
<h2>Películas</h2>
<div className='movie-section'>
{peliculas.map(pelicula => (
<div key={pelicula.id} className='movie-card'>
<Link to={'/movies/' + pelicula.id}>
<img
src={`https://image.tmdb.org/t/p/w500${pelicula.poster_path}`}
alt={pelicula.title || pelicula.name}
className='movie-poster'
/>
<h2 className='movie-title'>
{pelicula.title || pelicula.name}
</h2>
</Link>
</div>
))}
</div>
{/* Sección de Series */}
<h2>Series</h2>
<div className='series-section'>
{series.map(serie => (
<div key={serie.id} className='movie-card'>
<Link to={'/serie/' + serie.id}>
<img
src={`https://image.tmdb.org/t/p/w500${serie.poster_path}`}
alt={serie.title || serie.name}
className='movie-poster'
/>
<h2 className='movie-title'>{serie.title || serie.name}</h2>
</Link>
</div>
))}
</div>
</div>
</div>
)
}
export default Buscador |
###############################################################################
# OpenVAS Vulnerability Test
#
# CentOS Update for rdma CESA-2013:0509 centos6
#
# Authors:
# System Generated Check
#
# Copyright:
# Copyright (c) 2013 Greenbone Networks GmbH, http://www.greenbone.net
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2
# (or any later version), as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
###############################################################################
include("revisions-lib.inc");
tag_insight = "Red Hat Enterprise Linux includes a collection of InfiniBand and iWARP
utilities, libraries and development packages for writing applications
that use Remote Direct Memory Access (RDMA) technology.
A denial of service flaw was found in the way ibacm managed reference
counts for multicast connections. An attacker could send specially-crafted
multicast packets that would cause the ibacm daemon to crash.
(CVE-2012-4517)
It was found that the ibacm daemon created some files with world-writable
permissions. A local attacker could use this flaw to overwrite the
contents of the ibacm.log or ibacm.port file, allowing them to mask
certain actions from the log or cause ibacm to run on a non-default port.
(CVE-2012-4518)
CVE-2012-4518 was discovered by Florian Weimer of the Red Hat Product
Security Team and Kurt Seifried of the Red Hat Security Response Team.
The InfiniBand/iWARP/RDMA stack components have been upgraded to more
recent upstream versions.
This update also fixes the following bugs:
* Previously, the "ibnodes -h" command did not show a proper usage message.
With this update the problem is fixed and "ibnodes -h" now shows the
correct usage message. (BZ#818606)
* Previously, the ibv_devinfo utility erroneously showed iWARP cxgb3
hardware's physical state as invalid even when the device was working. For
iWARP hardware, the phys_state field has no meaning. This update patches
the utility to not print out anything for this field when the hardware is
iWARP hardware. (BZ#822781)
* Prior to the release of Red Hat Enterprise Linux 6.3, the kernel created
the InfiniBand device files in the wrong place and a udev rules file was
used to force the devices to be created in the proper place. With the
update to 6.3, the kernel was fixed to create the InfiniBand device files
in the proper place, and so the udev rules file was removed as no longer
being necessary. However, a bug in the kernel device creation meant that,
although the devices were now being created in the right place, they had
incorrect permissions. Consequently, when users attempted to run an RDMA
application as a non-root user, the application failed to get the necessary
permissions to use the RDMA device and the application terminated. This
update puts a new udev rules file in place. It no longer attempts to create
the InfiniBand devices since they already exist, but it does correct the
device permissions on the files. (BZ#834428)
* Previously, using the "perfquery -C" command with a host name caused the
perfquer ...
Description truncated, for more information please check the Reference URL";
tag_solution = "Please Install the Updated Packages.";
tag_affected = "rdma on CentOS 6";
if(description)
{
script_tag(name : "affected" , value : tag_affected);
script_tag(name : "solution" , value : tag_solution);
script_tag(name : "insight" , value : tag_insight);
script_xref(name : "URL" , value : "http://lists.centos.org/pipermail/centos-announce/2013-March/019488.html");
script_oid("1.3.6.1.4.1.25623.1.0.881644");
script_version("$Revision: 9372 $");
script_tag(name:"last_modification", value:"$Date: 2018-04-06 10:56:37 +0200 (Fri, 06 Apr 2018) $");
script_tag(name:"creation_date", value:"2013-03-12 09:59:28 +0530 (Tue, 12 Mar 2013)");
script_cve_id("CVE-2012-4517", "CVE-2012-4518");
script_tag(name:"cvss_base", value:"5.0");
script_tag(name:"cvss_base_vector", value:"AV:N/AC:L/Au:N/C:N/I:N/A:P");
script_tag(name:"qod_type", value:"package");
script_tag(name:"solution_type", value:"VendorFix");
script_xref(name: "CESA", value: "2013:0509");
script_name("CentOS Update for rdma CESA-2013:0509 centos6 ");
script_tag(name:"summary", value:"Check for the Version of rdma");
script_category(ACT_GATHER_INFO);
script_copyright("Copyright (c) 2013 Greenbone Networks GmbH");
script_family("CentOS Local Security Checks");
script_dependencies("gather-package-list.nasl");
script_mandatory_keys("ssh/login/centos", "ssh/login/rpms");
exit(0);
}
include("pkg-lib-rpm.inc");
release = get_kb_item("ssh/login/release");
res = "";
if(release == NULL){
exit(0);
}
if(release == "CentOS6")
{
if ((res = isrpmvuln(pkg:"rdma", rpm:"rdma~3.6~1.el6", rls:"CentOS6")) != NULL)
{
security_message(data:res);
exit(0);
}
if (__pkg_match) exit(99); # Not vulnerable.
exit(0);
} |
// Copyright 2024 The Abseil Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
#ifndef ABSL_DEBUGGING_INTERNAL_BOUNDED_UTF8_LENGTH_SEQUENCE_H_
#define ABSL_DEBUGGING_INTERNAL_BOUNDED_UTF8_LENGTH_SEQUENCE_H_
#include <cstdint>
#include "absl/base/config.h"
#include "absl/numeric/bits.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
// A sequence of up to max_elements integers between 1 and 4 inclusive, whose
// insertion operation computes the sum of all the elements before the insertion
// point. This is useful in decoding Punycode, where one needs to know where in
// a UTF-8 byte stream the n-th code point begins.
//
// BoundedUtf8LengthSequence is async-signal-safe and suitable for use in
// symbolizing stack traces in a signal handler, provided max_elements is not
// improvidently large. For inputs of lengths accepted by the Rust demangler,
// up to a couple hundred code points, InsertAndReturnSumOfPredecessors should
// run in a few dozen clock cycles, on par with the other arithmetic required
// for Punycode decoding.
template <uint32_t max_elements>
class BoundedUtf8LengthSequence {
public:
// Constructs an empty sequence.
BoundedUtf8LengthSequence() = default;
// Inserts `utf_length` at position `index`, shifting any existing elements at
// or beyond `index` one position to the right. If the sequence is already
// full, the rightmost element is discarded.
//
// Returns the sum of the elements at positions 0 to `index - 1` inclusive.
// If `index` is greater than the number of elements already inserted, the
// excess positions in the range count 1 apiece.
//
// REQUIRES: index < max_elements and 1 <= utf8_length <= 4.
uint32_t InsertAndReturnSumOfPredecessors(
uint32_t index, uint32_t utf8_length) {
// The caller shouldn't pass out-of-bounds inputs, but if it does happen,
// clamp the values and try to continue. If we're being called from a
// signal handler, the last thing we want to do is crash. Emitting
// malformed UTF-8 is a lesser evil.
if (index >= max_elements) index = max_elements - 1;
if (utf8_length == 0 || utf8_length > 4) utf8_length = 1;
const uint32_t word_index = index/32;
const uint32_t bit_index = 2 * (index % 32);
const uint64_t ones_bit = uint64_t{1} << bit_index;
// Compute the sum of predecessors.
// - Each value from 1 to 4 is represented by a bit field with value from
// 0 to 3, so the desired sum is index plus the sum of the
// representations actually stored.
// - For each bit field, a set low bit should contribute 1 to the sum, and
// a set high bit should contribute 2.
// - Another way to say the same thing is that each set bit contributes 1,
// and each set high bit contributes an additional 1.
// - So the sum we want is index + popcount(everything) + popcount(bits in
// odd positions).
const uint64_t odd_bits_mask = 0xaaaaaaaaaaaaaaaa;
const uint64_t lower_seminibbles_mask = ones_bit - 1;
const uint64_t higher_seminibbles_mask = ~lower_seminibbles_mask;
const uint64_t same_word_bits_below_insertion =
rep_[word_index] & lower_seminibbles_mask;
int full_popcount = absl::popcount(same_word_bits_below_insertion);
int odd_popcount =
absl::popcount(same_word_bits_below_insertion & odd_bits_mask);
for (uint32_t j = word_index; j > 0; --j) {
const uint64_t word_below_insertion = rep_[j - 1];
full_popcount += absl::popcount(word_below_insertion);
odd_popcount += absl::popcount(word_below_insertion & odd_bits_mask);
}
const uint32_t sum_of_predecessors =
index + static_cast<uint32_t>(full_popcount + odd_popcount);
// Now insert utf8_length's representation, shifting successors up one
// place.
for (uint32_t j = max_elements/32 - 1; j > word_index; --j) {
rep_[j] = (rep_[j] << 2) | (rep_[j - 1] >> 62);
}
rep_[word_index] =
(rep_[word_index] & lower_seminibbles_mask) |
(uint64_t{utf8_length - 1} << bit_index) |
((rep_[word_index] & higher_seminibbles_mask) << 2);
return sum_of_predecessors;
}
private:
// If the (32 * i + j)-th element of the represented sequence has the value k
// (0 <= j < 32, 1 <= k <= 4), then bits 2 * j and 2 * j + 1 of rep_[i]
// contain the seminibble (k - 1).
//
// In particular, the zero-initialization of rep_ makes positions not holding
// any inserted element count as 1 in InsertAndReturnSumOfPredecessors.
//
// Example: rep_ = {0xb1, ... the rest zeroes ...} represents the sequence
// (2, 1, 4, 3, ... the rest 1's ...). Constructing the sequence of Unicode
// code points "Àa🂻中" = {U+00C0, U+0061, U+1F0BB, U+4E2D} (among many
// other examples) would yield this value of rep_.
static_assert(max_elements > 0 && max_elements % 32 == 0,
"max_elements must be a positive multiple of 32");
uint64_t rep_[max_elements/32] = {};
};
} // namespace debugging_internal
ABSL_NAMESPACE_END
} // namespace absl
#endif // ABSL_DEBUGGING_INTERNAL_BOUNDED_UTF8_LENGTH_SEQUENCE_H_ |
import joblib
import cv2
import mediapipe as mp
import pandas as pd
import numpy as np
import rclpy
from geometry_msgs.msg import Twist
## initialize pose estimator
mp_drawing = mp.solutions.drawing_utils
mp_pose = mp.solutions.pose
pose = mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5)
mp_holistic = mp.solutions.holistic
model = joblib.load('20240122_174537_model_97.8342354297638.pkl')
class_labels = ['ad','au','lup','rup']
command_label = [[-1.0,0.0],[1.0,0.0],[1.0,1.0],[1.0,-1.0]]
rclpy.init()
msg = Twist()
node = rclpy.create_node('Turtle_controll')
publisher = node.create_publisher(Twist,'/turtle1/cmd_vel',10)
cap = cv2.VideoCapture(0)
while cap.isOpened():
# read frame
_, frame = cap.read()
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# process the frame for pose detection
pose_results = pose.process(frame_rgb)
left_shoulder = pose_results.pose_landmarks.landmark[mp_holistic.PoseLandmark.LEFT_SHOULDER]
right_shoulder = pose_results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_SHOULDER]
left_elbow = pose_results.pose_landmarks.landmark[mp_holistic.PoseLandmark.LEFT_ELBOW]
right_elbow = pose_results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_ELBOW]
left_wrist = pose_results.pose_landmarks.landmark[mp_holistic.PoseLandmark.LEFT_WRIST]
right_wrist = pose_results.pose_landmarks.landmark[mp_holistic.PoseLandmark.LEFT_WRIST]
data = [left_shoulder.x/(1/left_shoulder.z),left_shoulder.y/(1/left_shoulder.z),right_shoulder.x/(1/right_shoulder.z),right_shoulder.y/(1/right_shoulder.z),left_elbow.x/(1/left_elbow.z),left_elbow.y/(1/left_elbow.z),right_elbow.x/(1/right_elbow.z),right_elbow.y/(1/right_elbow.z),left_wrist.x/(1/left_wrist.z),left_wrist.y/(1/left_wrist.z),right_wrist.x/(1/right_wrist.z),right_wrist.y/(1/right_wrist.z)]
data = np.array(data).reshape(1,-1)
output = model.predict(data)
output = np.argmax(output)
print(class_labels[output])
msg.linear.x, msg.angular.z = command_label[output][0], command_label[output][1]
publisher.publish(msg)
# draw skeleton on the frame
mp_drawing.draw_landmarks(frame, pose_results.pose_landmarks, mp_pose.POSE_CONNECTIONS)
# display the frame
cv2.imshow('Output', frame)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
while rclpy.ok():
rclpy.spin_once(node)
node.destroy_node()
rclpy.shutdown() |
fetch('quizData.json')
.then(response => response.json())
.then(data => {
// Use the loaded data as your quizData
const quizData = data;
function shuffleQuizData() {
for (let i = quizData.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[quizData[i], quizData[j]] = [quizData[j], quizData[i]];
}
}
const quizContainer = document.getElementById('quiz');
const resultContainer = document.getElementById('result');
const submitButton = document.getElementById('submit');
const retryButton = document.getElementById('retry');
const showAnswerButton = document.getElementById('showAnswer');
const timerElement = document.getElementById('timer');
let currentQuestion = 0;
let score = 0;
let incorrectAnswers = [];
// Set the time limit for each question (in seconds)
const questionTimeLimit = 20;
let timeLeft = questionTimeLimit;
let timerInterval;
function startTimer() {
timeLeft = questionTimeLimit;
timerElement.textContent = `Time Left: ${timeLeft} seconds`;
// Clear any existing timer interval
clearInterval(timerInterval);
// Start the timer
timerInterval = setInterval(function () {
timeLeft--;
timerElement.textContent = `Time Left: ${timeLeft} seconds`;
if (timeLeft === 0) {
// Time's up, move to the next question
clearInterval(timerInterval);
// checkAnswer();
clearInterval(timerInterval);
currentQuestion++;
if (currentQuestion < quizData.length) {
displayQuestion();
} else {
// No more questions, display the result
displayResult();
}
}
}, 1000);
}
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
function displayQuestion() {
const questionData = quizData[currentQuestion];
startTimer();
const questionElement = document.createElement('div');
questionElement.className = 'question';
questionElement.innerHTML = questionData.question;
const optionsElement = document.createElement('div');
optionsElement.className = 'options';
const shuffledOptions = [...questionData.options];
shuffleArray(shuffledOptions);
for (let i = 0; i < shuffledOptions.length; i++) {
const option = document.createElement('label');
option.className = 'option';
const radio = document.createElement('input');
radio.type = 'radio';
radio.name = 'quiz';
radio.value = shuffledOptions[i];
const optionText = document.createTextNode(shuffledOptions[i]);
option.appendChild(radio);
option.appendChild(optionText);
optionsElement.appendChild(option);
}
quizContainer.innerHTML = '';
quizContainer.appendChild(questionElement);
quizContainer.appendChild(optionsElement);
}
function checkAnswer() {
const selectedOption = document.querySelector('input[name="quiz"]:checked');
if (selectedOption) {
const answer = selectedOption.value;
if (answer === quizData[currentQuestion].answer) {
score++;
} else {
incorrectAnswers.push({
question: quizData[currentQuestion].question,
incorrectAnswer: answer,
correctAnswer: quizData[currentQuestion].answer,
});
}
currentQuestion++;
selectedOption.checked = false;
if (currentQuestion < quizData.length) {
displayQuestion();
} else {
displayResult();
}
}
}
function displayResult() {
clearInterval(timerInterval);
timerElement.style.display = 'none';
quizContainer.style.display = 'none';
submitButton.style.display = 'none';
retryButton.style.display = 'inline-block';
showAnswerButton.style.display = 'inline-block';
resultContainer.innerHTML = `You scored ${score} out of ${quizData.length}!`;
}
function retryQuiz() {
currentQuestion = 0;
score = 0;
incorrectAnswers = [];
quizContainer.style.display = 'block';
submitButton.style.display = 'inline-block';
retryButton.style.display = 'none';
showAnswerButton.style.display = 'none';
resultContainer.innerHTML = '';
displayQuestion();
}
function showAnswer() {
quizContainer.style.display = 'none';
submitButton.style.display = 'none';
retryButton.style.display = 'inline-block';
showAnswerButton.style.display = 'none';
let incorrectAnswersHtml = '';
for (let i = 0; i < incorrectAnswers.length; i++) {
incorrectAnswersHtml += `
<p>
<strong>Question:</strong> ${incorrectAnswers[i].question}<br>
<strong>Your Answer:</strong> ${incorrectAnswers[i].incorrectAnswer}<br>
<strong>Correct Answer:</strong> ${incorrectAnswers[i].correctAnswer}
</p>
`;
}
resultContainer.innerHTML = `
<p>You scored ${score} out of ${quizData.length}!</p>
<p>Incorrect Answers:</p>
${incorrectAnswersHtml}
`;
}
submitButton.addEventListener('click', checkAnswer);
retryButton.addEventListener('click', retryQuiz);
showAnswerButton.addEventListener('click', showAnswer);
// Reset the quiz when the retry button is clicked
retryButton.addEventListener('click', () => {
currentQuestion = 0;
score = 0;
incorrectAnswers = [];
resultContainer.innerHTML = '';
shuffleQuizData(); // Shuffle the questions again for the next play
displayQuestion();
});
displayQuestion();
}) |
//
// YCJellyView.m
// YCJellyView
//
// Created by daniel on 2017/8/4.
// Copyright © 2017年 daniel. All rights reserved.
//
#import "YCJellyView.h"
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kMinHeight 0
#define kControlViewW 1
#define kControlViewH 1
#define kControlViewColor [UIColor clearColor]
#define kDefaultControlX (kScreenW / 2.0)
#define kDefaultControlY kMinHeight
#define kScale 0.7
@interface YCJellyView ()
{
CGFloat _controlX;
CGFloat _controlY;
CAShapeLayer *_shapeLayer;
UIView *_controlView;
CADisplayLink *_displayLink;
BOOL _isInAnimation;
}
@end
@implementation YCJellyView
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
//添加涂层
_shapeLayer = [[CAShapeLayer alloc] init];
_shapeLayer.fillColor = [UIColor greenColor].CGColor;
[self.layer addSublayer:_shapeLayer];
//初始化控制点坐标
_controlX = kDefaultControlX;
_controlY = kDefaultControlY;
//添加控制点视图
_controlView = [[UIView alloc] initWithFrame:CGRectMake(_controlX, _controlY, kControlViewW, kControlViewH)];
_controlView.backgroundColor = kControlViewColor;
[self addSubview:_controlView];
//添加手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanAction:)];
[self addGestureRecognizer:pan];
//添加定时器,CADisplayLink一秒钟刷新60次,做动画一般使用CADisplayLink而不是NSTimer
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(caculateControlPoint)];
[_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
_displayLink.paused = YES; //默认暂停定时器
_isInAnimation = NO;
}
//更新图层路径
[self updateShapeLayerPath];
return self;
}
#pragma mark - 更新图层路径
- (void)updateShapeLayerPath {
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 0)]; //dot1
[path addLineToPoint:CGPointMake(kScreenW, 0)]; //dot2
[path addLineToPoint:CGPointMake(kScreenW, kMinHeight)]; //dot3
[path addQuadCurveToPoint:CGPointMake(0, kMinHeight) //dot4
controlPoint:CGPointMake(_controlX, _controlY)]; //控制点
[path closePath];
_shapeLayer.path = path.CGPath;
}
#pragma mark - 处理手势拖动
- (void)handlePanAction:(UIPanGestureRecognizer *)pan {
if (!_isInAnimation) {
if (pan.state == UIGestureRecognizerStateChanged) {
CGPoint translationP = [pan translationInView:self]; //拖动时触摸点位置
CGFloat currentY = kDefaultControlY + translationP.y * kScale;
_controlY = currentY < kMinHeight ? kMinHeight : currentY; //改变控制点位置
_controlY = currentY >= kScreenH ? kScreenH : _controlY;
_controlX = kDefaultControlX + translationP.x;
_controlView.frame = CGRectMake(_controlX, _controlY, kControlViewW, kControlViewH);
[self updateShapeLayerPath]; //计算完更新路径
}else if(pan.state == UIGestureRecognizerStateEnded ||
pan.state == UIGestureRecognizerStateFailed ||
pan.state == UIGestureRecognizerStateCancelled ){
_displayLink.paused = NO;
_isInAnimation = YES;
[UIView animateWithDuration:1.0
delay:0
usingSpringWithDamping:0.5
initialSpringVelocity:0.0
options:UIViewAnimationOptionCurveLinear
animations:^{
_controlView.frame = CGRectMake(kDefaultControlX, kDefaultControlY, kControlViewW, kControlViewH);
} completion:^(BOOL finished) {
if (finished) {
_displayLink.paused = YES;
_isInAnimation = NO;
}
}
];
}
}
}
#pragma mark - 开启定时器计算当前控制点的位置
- (void)caculateControlPoint {
CALayer *layer = _controlView.layer.presentationLayer;
_controlX = layer.position.x;
_controlY = layer.position.y;
[self updateShapeLayerPath];
}
@end |
import React, { Component } from "react";
import Moment from "react-moment";
export class ProfileCreds extends Component {
render() {
const { experience, education } = this.props;
const timeFormat = "YYYY/MM/DD";
const expItems = experience.map(exp => (
<li className="list-group-item" key={exp._id}>
<h4>{exp.company}</h4>
<p>
<Moment format={timeFormat}>{exp.from}</Moment> -
{exp.to === null ? (' Now') : (<Moment format={timeFormat}>{exp.to}</Moment>)}
</p>
<p><strong>Position:</strong>{exp.title}</p>
<p>
{exp.location === '' ? null : (<h5><strong>Location: </strong>{exp.location}</h5>)}
</p>
<p>
{exp.description === '' ? null : (<h5><strong>Description: </strong>{exp.description}</h5>)}
</p>
</li>
))
const eduItems = education.map(edu => (
<li className="list-group-item" key={edu._id}>
<h4>{edu.school}</h4>
<p>
<Moment format={timeFormat}>{edu.from}</Moment> -
{edu.to === null ? (' Now') : (<Moment format={timeFormat}>{edu.to}</Moment>)}
</p>
<p><strong>Degree:</strong>{edu.degree}</p>
<p><strong>Field Of Study:</strong>{edu.fieldofstudy}</p>
<p>
{edu.description === '' ? null : (<h5><strong>Description: </strong>{edu.description}</h5>)}
</p>
</li>
))
return (
<div className="row">
<div className="col-md-6">
<h3 className="text-center text-info">
Experience
</h3>
{expItems.length > 0 ? (
<ul className="list-group">{expItems}</ul>
) : (
<p className="text-center">No Experience Listed</p>
)}
</div>
<div className="col-md-6">
<h3 className="text-center text-info">
Education</h3>
{eduItems.length > 0 ? (
<ul className="list-group">{eduItems}</ul>
) : (
<p className="text-center">No Education Listed</p>
)}
</div>
</div>
);
}
}
export default ProfileCreds; |
package ma.youcode.aftasclubbackendapi.services.implementation;
import lombok.RequiredArgsConstructor;
import ma.youcode.aftasclubbackendapi.dto.LevelDto;
import ma.youcode.aftasclubbackendapi.dto.requests.LevelRequest;
import ma.youcode.aftasclubbackendapi.entities.Level;
import ma.youcode.aftasclubbackendapi.exceptions.NotFoundExceptions.LevelNotFoundException;
import ma.youcode.aftasclubbackendapi.repositories.LevelRepository;
import ma.youcode.aftasclubbackendapi.services.LevelService;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class LevelServiceImpl implements LevelService {
private final LevelRepository levelRepository;
private final ModelMapper mapper;
@Override
public List<LevelDto> getAll() {
List<Level> levels = levelRepository.findAll();
if (levels.isEmpty())
throw new LevelNotFoundException("No Levels Found");
return levels.stream().map(level -> mapper.map(level, LevelDto.class)).toList();
}
@Override
public Page<LevelDto> getAll(Pageable pageable) {
Page<Level> levels = levelRepository.findAll(pageable);
if (levels.isEmpty())
throw new LevelNotFoundException("No Levels Found");
return levels.map(level -> mapper.map(level, LevelDto.class));
}
@Override
public Optional<LevelDto> find(Integer code) {
Optional<Level> level = levelRepository.findById(code);
if (level.isEmpty())
throw new LevelNotFoundException("Level Not Found with Code: " + code);
return Optional.of(mapper.map(level, LevelDto.class));
}
@Override
public Optional<LevelDto> create(LevelRequest levelRequest) {
Level level = mapper.map(levelRequest, Level.class);
Level savedLevel = levelRepository.save(level);
return Optional.of(mapper.map(savedLevel, LevelDto.class));
}
@Override
public Optional<LevelDto> update(LevelRequest levelRequest, Integer code) {
Optional<Level> levelFound = levelRepository.findById(code);
if (levelFound.isEmpty())
throw new LevelNotFoundException("Level Not Found With Code: " + code);
else {
Level level = levelFound.get();
level.setCode(level.getCode());
level.setDescription(levelRequest.getDescription());
level.setPoints(levelRequest.getPoints());
Level updatedLevel = levelRepository.save(level);
return Optional.of(mapper.map(updatedLevel, LevelDto.class));
}
}
@Override
public boolean destroy(Integer code) {
Optional<Level> levelToDelete = levelRepository.findById(code);
if (levelToDelete.isPresent()) {
levelRepository.delete(levelToDelete.get());
return true;
} else throw new LevelNotFoundException("Level Not Found With Code: " + code);
}
} |
// This software is Copyright by the Board of Trustees of Michigan
// State University (c) Copyright 2016.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// 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 <http://www.gnu.org/licenses/>.
//
// Authors:
// Jeromy Tompkins
// NSCL
// Michigan State University
// East Lansing, MI 48824-1321
#ifndef GATEBUILDER1DDIALOG_H
#define GATEBUILDER1DDIALOG_H
#include "GSlice.h"
#include <QDialog>
#include <utility>
class TPad;
class QLineEdit;
class QValidator;
namespace Ui {
class GateBuilder1DDialog;
}
namespace Viewer
{
class QRootCanvas;
class HistogramBundle;
/*! Dialog for editing 1D gates (aka slices)
*
* This actually operates almost identically to the GateBuilderDialog
* except that it maintains a GSlice rather than a GGate. See the
* GateBuilderDialog docs for the working of this.
*
* The accept() and reject() methods decorate the standard QDialog::accept() and
* QDialog::reject() methods.
*/
class GateBuilder1DDialog : public QDialog
{
Q_OBJECT
public:
explicit GateBuilder1DDialog(QRootCanvas& canvas,
HistogramBundle& hist,
GSlice* pSlice = nullptr,
QWidget *parent = nullptr);
~GateBuilder1DDialog();
signals:
/*! Emitted when a user accepts changes
*
* \param pSlice pointer to slice that will be kept by DockableGateManager
*/
void completed(GSlice* pSlice);
public slots:
virtual void accept();
virtual void reject();
virtual void onMousePress(QRootCanvas* pad);
virtual void onMouseRelease(QRootCanvas* pad);
virtual void onClick(QRootCanvas* pad);
/*! Set the name and also update the accept button */
void onNameChanged(QString name);
void lowEditChanged();
void highEditChanged();
void onLowChanged(double x1, double y1, double x2, double y2);
void onHighChanged(double x1, double y1, double x2, double y2);
private:
// Update lines and text
void updateLow(double x);
void updateHigh(double x);
// Update text edits
void updateLowEdit(double x);
void updateHighEdit(double x);
// utility to determine if user is focused on low entry
bool focusIsLow();
// Hides the original lines
void removeOldLines(GSlice& pSlice);
void connectSignals();
private:
Ui::GateBuilder1DDialog *ui;
QRootCanvas& m_canvas;
HistogramBundle& m_histPkg;
GSlice m_editSlice;
GSlice* m_pOldSlice;
QLineEdit* m_editFocus;
QValidator* m_editValidator;
std::pair<int, int> m_lastMousePressPos;
};
} // end of namespace
#endif // GATEBUILDER1DDIALOG_H |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_XmlConnect
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Customer order details helper
*
* @category Mage
* @package Mage_XmlConnect
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_XmlConnect_Helper_Customer_Order extends Mage_Core_Helper_Abstract
{
/**#@+
* Price display type
* @see Mage_Weee_Helper_Data::typeOfDisplay(...);
*/
const PRICE_DISPLAY_TYPE_1 = 1;
const PRICE_DISPLAY_TYPE_2 = 2;
const PRICE_DISPLAY_TYPE_4 = 4;
const PRICE_DISPLAY_TYPE_14 = 14;
/**#@-*/
/**
* Add Weee taxes child to the XML
*
* @param Mage_Core_Block_Template $renderer Product renderer
* @param Mage_Sales_Model_Order_Item $item
* @param Mage_XmlConnect_Model_Simplexml_Element $priceXml
* @param Mage_XmlConnect_Model_Simplexml_Element $subtotalXml
* @param bool $isIncludeTax
* @return null
*/
public function addPriceAndSubtotalToXml(Mage_Core_Block_Template $renderer, Mage_Sales_Model_Order_Item $item,
Mage_XmlConnect_Model_Simplexml_Element $priceXml, Mage_XmlConnect_Model_Simplexml_Element $subtotalXml,
$isIncludeTax = false
) {
$weeeParams = array();
$typesOfDisplay = $renderer->getTypesOfDisplay();
if ($isIncludeTax) {
$nodeName = 'including_tax';
$nodeLabel = Mage::helper('tax')->__('Incl. Tax');
$inclPrice = $renderer->helper('checkout')->getPriceInclTax($item);
$inclSubtotal = $renderer->helper('checkout')->getSubtotalInclTax($item);
if ($typesOfDisplay[self::PRICE_DISPLAY_TYPE_14]) {
$price = $inclPrice + $renderer->getWeeeTaxAppliedAmount();
$subtotal = $inclSubtotal + $item->getWeeeTaxAppliedRowAmount();
} else {
$price = $inclPrice - $renderer->getWeeeTaxDisposition();
$subtotal = $inclSubtotal - $item->getWeeeTaxRowDisposition();
}
$weeeParams['include'] = $inclPrice;
} else {
$nodeName = 'excluding_tax';
$nodeLabel = Mage::helper('tax')->__('Excl. Tax');
if ($typesOfDisplay[self::PRICE_DISPLAY_TYPE_14]) {
$price = $item->getPrice() + $renderer->getWeeeTaxAppliedAmount()
+ $renderer->getWeeeTaxDisposition();
$subtotal = $item->getRowTotal() + $item->getWeeeTaxAppliedRowAmount()
+ $item->getWeeeTaxRowDisposition();
} else {
$price = $item->getPrice();
$subtotal = $item->getRowTotal();
}
}
$configNode = array(
'value' => $this->formatPrice($renderer, $price)
);
if ($renderer->helper('tax')->displaySalesBothPrices()) {
$configNode['label'] = $nodeLabel;
}
$this->addWeeeTaxesToPriceXml(
$renderer, $item, $priceXml->addCustomChild($nodeName, null, $configNode), $weeeParams
);
$configNode['value'] = $this->formatPrice($renderer, $subtotal);
$weeeParams['include'] = $isIncludeTax ? $inclSubtotal : null;
$weeeParams['is_subtotal'] = true;
$this->addWeeeTaxesToPriceXml(
$renderer, $item, $subtotalXml->addCustomChild($nodeName, null, $configNode), $weeeParams
);
}
/**
* Add Product options to XML
*
* @param Mage_Core_Block_Template $renderer Product renderer
* @param Mage_XmlConnect_Model_Simplexml_Element $itemXml
* @return null
*/
public function addItemOptionsToXml(Mage_Core_Block_Template $renderer,
Mage_XmlConnect_Model_Simplexml_Element $itemXml
) {
$options = $renderer->getItemOptions();
if (!empty($options)) {
$optionsXml = $itemXml->addChild('options');
foreach ($options as $option) {
$value = false;
$formatedOptionValue = $renderer->getFormatedOptionValue($option);
if (isset($formatedOptionValue['full_view']) && isset($formatedOptionValue['value'])) {
$value = $formatedOptionValue['value'];
} elseif (isset($option['print_value'])) {
$value = $option['print_value'];
} elseif (isset($option['value'])) {
$value = $option['value'];
}
if ($value) {
$optionsXml->addCustomChild('option', strip_tags($value), array('label' => $option['label']));
}
}
}
}
/**
* Add Weee taxes child to the XML
*
* @param Mage_Core_Block_Template $renderer Product renderer
* @param Mage_Sales_Model_Order_Item $item
* @param Mage_XmlConnect_Model_Simplexml_Element $parentXml
* @param array $params Params for Weee taxes: 'include' - Price including tax, 'is_subtotal' - Flag of subtotal
* @return null
*/
public function addWeeeTaxesToPriceXml(Mage_Core_Block_Template $renderer, Mage_Sales_Model_Order_Item $item,
Mage_XmlConnect_Model_Simplexml_Element $parentXml, $params = array()
) {
$weeTaxes = $renderer->getWeeeTaxes();
if (empty($weeTaxes)) {
return;
}
$typesOfDisplay = $renderer->getTypesOfDisplay();
$row = isset($params['is_subtotal']) && $params['is_subtotal'] ? 'row_' : '';
/** @var $weeeXml Mage_XmlConnect_Model_Simplexml_Element */
if ($typesOfDisplay[self::PRICE_DISPLAY_TYPE_1]) {
$weeeXml = $parentXml->addChild('weee');
foreach ($weeTaxes as $tax) {
$weeeXml->addCustomChild('tax', $this->formatPrice($renderer, $tax[$row . 'amount']),
array('label' => $tax['title'])
);
}
} elseif ($typesOfDisplay[self::PRICE_DISPLAY_TYPE_2] || $typesOfDisplay[self::PRICE_DISPLAY_TYPE_4]) {
$weeeXml = $parentXml->addChild('weee');
foreach ($weeTaxes as $tax) {
$weeeXml->addCustomChild('tax', $this->formatPrice($renderer, $tax[$row . 'amount_incl_tax']),
array('label' => $tax['title'])
);
}
}
if ($typesOfDisplay[self::PRICE_DISPLAY_TYPE_2]) {
if (!is_null($params['include'])) {
// including tax
if (isset($params['is_subtotal'])) {
$total = $params['include'] + $item->getWeeeTaxAppliedRowAmount();
} else {
$total = $params['include'] + $renderer->getWeeeTaxAppliedAmount();
}
} else {
// excluding tax
if ($params['is_subtotal']) {
$total = $item->getRowTotal() + $item->getWeeeTaxAppliedRowAmount()
+ $item->getWeeeTaxRowDisposition();
} else {
$total = $item->getPrice() + $renderer->getWeeeTaxAppliedAmount()
+ $renderer->getWeeeTaxDisposition();
}
}
if (!isset($weeeXml)) {
$weeeXml = $parentXml->addChild('weee');
}
$weeeXml->addCustomChild(
'total',
$this->formatPrice($renderer, $total),
array('label' => $renderer->helper('weee')->__('Total'))
);
}
}
/**
* Add item quantities to the XML
*
* @param Mage_Core_Block_Template $renderer Product renderer
* @param Mage_XmlConnect_Model_Simplexml_Element $quantityXml
* @param Mage_Sales_Model_Order_Item $item
* @return null
*/
public function addQuantityToXml(Mage_Core_Block_Template $renderer,
Mage_XmlConnect_Model_Simplexml_Element $quantityXml, Mage_Sales_Model_Order_Item $item
) {
$qty = 1 * $item->getQtyOrdered();
if ($qty > 0) {
$quantityXml->addCustomChild('value', $qty, array('label' => Mage::helper('xmlconnect')->__('Ordered')));
}
$qty = 1 * $item->getQtyShipped();
if ($qty > 0) {
$quantityXml->addCustomChild('value', $qty, array('label' => Mage::helper('xmlconnect')->__('Shipped')));
}
$qty = 1 * $item->getQtyCanceled();
if ($qty > 0) {
$quantityXml->addCustomChild('value', $qty, array('label' => Mage::helper('xmlconnect')->__('Canceled')));
}
$qty = 1 * $item->getQtyRefunded();
if ($qty > 0) {
$quantityXml->addCustomChild('value', $qty, array('label' => Mage::helper('xmlconnect')->__('Refunded')));
}
}
/**
* Format price using order currency
*
* @param Mage_Core_Block_Template $renderer Product renderer
* @param float $price
* @return string
*/
public function formatPrice(Mage_Core_Block_Template $renderer, $price)
{
return $renderer->getOrder()->getOrderCurrency()->formatPrecision($price, 2, array(), false);
}
} |
import React, { useState } from 'react';
import axios from 'axios'; // Import axios for making HTTP requests
import './Search.css'; // Import CSS file for styling
// Define interface for weather data received from API
interface WeatherData {
coord: { lon: number; lat: number };
weather: { id: number; main: string; description: string; icon: string }[];
base: string;
main: {
temp: number;
feels_like: number;
temp_min: number;
temp_max: number;
pressure: number;
humidity: number;
};
visibility: number;
wind: { speed: number; deg: number };
clouds: { all: number };
dt: number;
sys: { type: number; id: number; country: string; sunrise: number; sunset: number };
timezone: number;
id: number;
name: string;
cod: number;
}
// Define the Search component
const Search = () => {
// Define state variables
const [searchQuery, setSearchQuery] = useState(''); // For storing the search query
const [sortQuery, setSortQuery] = useState(''); // For storing the sorting option
const [results, setResults] = useState<WeatherData[]>([]); // For storing search results
const [sortedResults, setSortedResults] = useState<WeatherData[]>([]); // For storing sorted search results
const [error, setError] = useState(''); // For storing error messages
// Define API key and URL
const apiKey = 'cf24472b0d7c7b3902b765c907705dfc';
const apiUrl = 'https://api.openweathermap.org/data/2.5/weather';
// Function to handle search button click
const handleSearch = async () => {
if (!searchQuery) { // Check if search query is empty
setError('Please enter a location'); // Set error message
return; // Exit function
}
try {
const response = await axios.get<WeatherData>(`${apiUrl}?q=${searchQuery}&appid=${apiKey}&units=metric`); // Make API call
setResults([response.data]); // Set search results
setError(''); // Clear error
} catch (error) {
console.error('Error fetching data:', error); // Log error to console
setError('Error fetching data. Please try again.'); // Set error message
}
};
// Function to handle sorted results button click
const handleSort = () => {
if (!sortQuery) { // Check if sorting option is selected
setError('Please select a sorting option'); // Set error message
return; // Exit function
}
const sorted = [...results].sort((a, b) => { // Sort the results array
if (sortQuery === 'name') { // If sorting by name
return a.name.localeCompare(b.name); // Sort by name
}
const valA = a[sortQuery as keyof WeatherData]; // Get value of sorting field for object A
const valB = b[sortQuery as keyof WeatherData]; // Get value of sorting field for object B
if (typeof valA === 'string' && typeof valB === 'string') { // If both values are strings
return valA.localeCompare(valB); // Sort by string comparison
} else if (typeof valA === 'number' && typeof valB === 'number') { // If both values are numbers
return valA - valB; // Sort by numerical comparison
}
return 0; // Default return value
});
setSortedResults(sorted); // Set sorted results
setError(''); // Clear error
};
// Function to handle change in sort by option
const handleSortByChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
setSortQuery(event.target.value); // Update sorting option
setError(''); // Clear error
};
// Render the component
return (
<div className="card-search">
<h2>Search</h2>
{/* Search by location input */}
<div>
<input type="text" placeholder="Search location..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
<button onClick={handleSearch}>Search</button>
</div>
{/* Enter location and sort by input */}
<div>
<input type="text" placeholder="Enter location..." />
<select value={sortQuery} onChange={handleSortByChange}>
<option value="">-- Sort by --</option>
<option value="weather.0.id">ID</option>
<option value="name">Location name</option>
<option value="weather.0.description">Description</option>
<option value="main.temp">Temperature</option>
<option value="main.feels_like">Feels Like</option>
<option value="main.temp_min">Minimum Temperature</option>
<option value="main.temp_max">Maximum Temperature</option>
</select>
<button onClick={handleSort}>Sorted Results</button>
</div>
{/* Error message display */}
{error && <p>{error}</p>}
{/* Display search results */}
<div className="result-box">
{(results.length > 0 || sortedResults.length > 0) && (
<div>
{sortedResults.length > 0 ? ( // If sorted results are available
sortedResults.map((result, index) => (
<div key={index}>
<p>ID: {result.weather[0].id}</p>
<p>Location name: {result.name}</p>
<p>Description: {result.weather[0].description}</p>
<p>Temperature: {result.main.temp} °C</p>
<p>Feels Like: {result.main.feels_like} °C</p>
<p>Minimum Temperature: {result.main.temp_min} °C</p>
<p>Maximum Temperature: {result.main.temp_max} °C</p>
</div>
))
) : (
results.map((result, index) => ( // If regular results are available
<div key={index}>
<p>ID: {result.weather[0].id}</p>
<p>Location name: {result.name}</p>
<p>Description: {result.weather[0].description}</p>
<p>Temperature: {result.main.temp} °C</p>
<p>Feels Like: {result.main.feels_like} °C</p>
<p>Minimum Temperature: {result.main.temp_min} °C</p>
<p>Maximum Temperature: {result.main.temp_max} °C</p>
</div>
))
)}
</div>
)}
</div>
</div>
);
};
export default Search; // Export the Search component |
import React, { FC } from "react";
import Container from "../layout/Container";
import TextLink from "../atoms/TextLink";
import Text from "../atoms/Text";
import { IoPricetagOutline } from "react-icons/io5";
import Image from "next/image";
const TourCard: FC<TourCardProps> = ({
id,
title,
description,
pay,
image,
}) => {
return (
<Container>
<div className="w-full h-fit rounded-lg shadow-[0px_0px_35px_rgba(0,0,0,.07)] flex">
<Image
src={image}
alt="tour image"
width={100}
height={100}
className="w-4/12 h-32 object-cover rounded-bl-lg rounded-tl-lg"
/>
<div className="pl-3 w-8/12 py-2 space-y-1">
<TextLink
textStyle="HeadingTwo"
value={title}
href={`/tour/detail/${id}`}
/>
<Text textStyle="DescriptionBlogCard" value={description} />
<div className={`flex items-center space-x-2`}>
<Text textStyle="Bold" value={<IoPricetagOutline />} />
<Text
textStyle="Bold"
value={`Rp. ${pay?.toLocaleString("id-ID")}/Pax`}
/>
</div>
</div>
</div>
</Container>
);
};
export default TourCard; |
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Movie</title>
<link rel="stylesheet" type="text/css" th:href="@{/webjars/bootstrap/css/bootstrap.min.css}"/>
</head>
<body>
<nav class="navbar-expand-lg navbar navbar-dark bg-dark">
<a class="navbar-brand" href="#" hidden>Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
</div>
</nav>
<div th:if="${listMovies == null}">
<a th:href="@{'/movie/new/'}" class="btn btn-primary">Add First Movie</a>
</div>
<div th:unless="${listMovies == null}">
<div class="container text-center" >
<h1 style="text-align: center">List Movies</h1>
<div>
<table class="table text-center">
<thead class="thead-dark">
<th>Name</th>
<th>Description</th>
<th>Rating</th>
<th>Realse Date</th>
<th>Image</th>
<th></th>
</thead>
<tbody>
<th:block th:each="movies : ${listMovies}">
<tr>
<td>[[${movies.nameMovies}]]</td>
<td>[[${movies.description}]]</td>
<td>[[${movies.rating}]]</td>
<td>[[${movies.realseDate}]]</td>
<td>[[${movies.image}]]</td>
<td>
<a th:href="@{'/movie/edit/' + ${movies.idMovies}}" class="btn btn-primary">Edit</a>
<a th:href="@{'/movie/delete/' + ${movies.idMovies}}" class="btn btn-danger">Delete</a>
</td>
</tr>
</th:block>
</tbody>
</table>
</div>
<a th:href="@{'/movie/new/'}" class="btn btn-primary">Add Movie</a>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html> |
<template>
<div>
<div class="p-5 mb-4 primarystyledcard rounded-3 shadow">
<div class="container-fluid py-5">
<div class="row align-items-start">
<div class="col my-auto">
<h1 class="display-2 fw-bold">Events</h1>
</div>
<div class="col my-auto">
<p class="col-md-8 fs-4 text-md-end float-md-end">
Check out past and upcoming lectures and workshops
</p>
</div>
</div>
</div>
</div>
<h1 class="mb-3" v-if="(lectures.filter(lecture => (new Date(lecture.date)) > (Date.now()))).length > 0">Upcoming</h1>
<div class="row row-cols-1 row-cols-md-2 g-4">
<div class="col" v-for="lecture in (lectures.filter(lecture => (new Date(lecture.date)) > (Date.now()))).sort((a, b) => new Date(a.date) - new Date(b.date))" v-bind:key="lecture._id">
<Nuxt-Link
style="text-decoration: none; color: inherit"
:to="'/events/'+lecture._id"
>
<div
class="card card-cover h-100 overflow-hidden rounded-4 shadow"
v-bind:style=" 'background: linear-gradient( rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4) ), url('+createLectureImageUrl(lecture.image)+');' "
>
<div
class="d-flex flex-column h-100 px-5 pb-3 text-white text-shadow-1 pt-6"
>
<span class="pt-5 mt-5 mb-4"><p>{{ (new Date(lecture.date)).toLocaleDateString() }}</p><h1 class="display-6 lh-1 fw-bold">{{lecture.name}}</h1></span>
</div>
</div>
</Nuxt-Link>
</div>
</div>
<h1 class="my-3">Completed</h1>
<div class="row row-cols-1 row-cols-md-2 g-4">
<div class="col" v-for="lecture in (lectures.filter(lecture => (new Date(lecture.date)) < (Date.now()))).sort((a, b) => new Date(b.date) - new Date(a.date))" v-bind:key="lecture._id">
<Nuxt-Link
style="text-decoration: none; color: inherit"
:to="'/events/'+lecture._id"
>
<div
class="card card-cover h-100 overflow-hidden rounded-4 shadow"
v-bind:style=" 'background: linear-gradient( rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4) ), url('+createLectureImageUrl(lecture.image)+');' "
>
<div
class="d-flex flex-column h-100 px-5 pb-3 text-white text-shadow-1 pt-6"
>
<span class="pt-5 mt-5 mb-4"><p>{{ (new Date(lecture.date)).toLocaleDateString() }}</p><h1 class="display-6 lh-1 fw-bold">{{lecture.name}}</h1></span>
</div>
</div>
</Nuxt-Link>
</div>
</div>
</div>
</template>
<style scoped>
.primarystyledcard {
background-color: #393939;
color: #fffbfe;
}
.secondarystyledcard {
background-color: #7a7d7d;
color: #fffbfe;
}
.card {
background-repeat: no-repeat;
background-position: 50% 50%;
background-size: cover !important;
transition: 0.3s;
}
</style>
<script>
export default {
middleware: 'isAuthenticated',
async asyncData({ $axios }) {
const lectures = await $axios.$get('getLectures')
return { lectures }
},
methods: {
createLectureImageUrl(inputstring) {
/* if the inputstring starts with https, then it is a url, otherwise it is a local file */
if (inputstring.startsWith('https')) {
return inputstring
} else {
return require(`~/assets/images/lectures/${inputstring}`)
}
}
}
}
</script> |
/*
* Use existing Bootstrap 4 classes and
* variables to extend - override CF7 style
*
* Useful CF7 classes:
* .wpcf7 the wrapper element
* .wpcf7-form
* .wpcf7-form-control
* .wpcf7-text
* .wpcf7-email
* .wpcf7-textarea
* .wpcf7-submit
*/
// keep a max width in case it is just the form and nothing else
// we do not want a form spanning whole page
.fl-contact-form {
max-width: 600px;
margin: 0 auto !important;
// all inputs except radios and checkboxes inherit from form-control
input[type=text],
input[type=search],
input[type=url],
input[type=tel],
input[type=number],
input[type=range],
input[type=date],
input[type=month],
input[type=week],
input[type=time],
input[type=datetime],
input[type=datetime-local],
input[type=color],
input[type=email],
input[type=file],
input[type=submit],
select,
textarea {
@extend .form-control;
}
// submit button, inherit .btn and .btn-outline-primary classes.
.fl-button{
@extend .btn;
@extend .btn-outline-primary;
}
// set paragraphs to behave like divs with class .form-group
p {
@extend .form-group;
}
// Hide Labels
label {
@extend .sr-only;
}
// not valid tip for each control
.fl-contact-error {
color: $brand-danger !important;
}
// validation errors ourput bottom of form
.fl-send-error {
@extend .form-control;
color: $brand-danger !important;
border: 1px solid $gray-lighter !important;
}
} |
/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
/****************************************************************************
Regression.h
****************************************************************************/
#ifndef _Regression_h
#define _Regression_h
#include "inktomi++.h"
#include "Regex.h"
//
// Each module should provide one or more regression tests
//
// An example:
//
// REGRESSION_TEST(Addition)(RegressionTest *t, int atype, int *pstatus) {
// if (1 + 1 != 2)
// *pstatus = REGRESSION_TEST_FAILED;
// if (atype > REGRESSION_TEST_NIGHTLY) // try again
// if (1 + 1 != 2)
// *pstatus = REGRESSION_TEST_FAILED;
// rprintf(t, "it worked, 1+1 really is 2!");
// *pstatus return REGRESSION_TEST_PASSED;
// }
//
//
// status values
#define REGRESSION_TEST_PASSED 1
#define REGRESSION_TEST_INPROGRESS 0
#define REGRESSION_TEST_FAILED -1
#define REGRESSION_TEST_NOT_RUN -2
// regression types
#define REGRESSION_TEST_NONE 0
#define REGRESSION_TEST_QUICK 1
#define REGRESSION_TEST_NIGHTLY 2
#define REGRESSION_TEST_EXTENDED 3
// use only for testing TS error handling!
#define REGRESSION_TEST_FATAL 4
// regression options
#define REGRESSION_OPT_EXCLUSIVE (1 << 0)
struct RegressionTest;
typedef void TestFunction(RegressionTest * t, int type, int *status);
struct RegressionTest
{
const char *name;
TestFunction *function;
RegressionTest *next;
int status;
int printed;
int opt;
RegressionTest(const char *name_arg, TestFunction * function_arg, int aopt);
static int final_status;
static int ran_tests;
static DFA dfa;
static RegressionTest *current;
static int run(char *name = NULL);
static int run_some();
static int check_status();
};
#define REGRESSION_TEST(_f) \
void RegressionTest_##_f(RegressionTest * t, int atype, int *pstatus); \
RegressionTest regressionTest_##_f(#_f,&RegressionTest_##_f, 0);\
void RegressionTest_##_f
#define EXCLUSIVE_REGRESSION_TEST(_f) \
void RegressionTest_##_f(RegressionTest * t, int atype, int *pstatus); \
RegressionTest regressionTest_##_f(#_f,&RegressionTest_##_f, REGRESSION_OPT_EXCLUSIVE);\
void RegressionTest_##_f
int rprintf(RegressionTest * t, const char *format, ...);
char *regression_status_string(int status);
extern int regression_level;
#define SignalError(_buf, _already) \
{ \
if(_already == false) pmgmt->signalManager(MGMT_SIGNAL_CONFIG_ERROR, _buf); \
_already = true; \
Warning(_buf); \
} \
#define _Regression_h
#endif /* _Regression_h */ |
import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { RadioGroup } from "./RadioGroup";
import { TextArea } from "../TextArea/TextArea";
export default {
title: "COMPONENTS/Radio/RadioGroup",
component: RadioGroup,
argTypes: {
groupName: {
description:
"Name of the radio group. This name automatically propagates to each Radio component in a RadioGroup.",
},
radioProps: {
control: false,
description:
"An array of Radio component properties. See the Radio component for a complete list.",
},
},
args: {
groupName: "default-group",
},
parameters: {
docs: {
description: {
component:
"Two or more Radio components may be contained in a RadioGroup component in order to manage the selected state and show/hide any children provided within the `radioProps` object.",
},
},
},
} as ComponentMeta<typeof RadioGroup>;
const Template: ComponentStory<typeof RadioGroup> = ({ ...rest }) => (
<RadioGroup {...rest} />
);
const children = [
<RadioGroup
groupName="children"
radioProps={[
{
id: "child-1",
value: "child-1",
label: "Child 1",
children: [
<TextArea
fieldName="child-textarea"
id="child-textarea"
label="Child 1 TextArea"
/>,
<RadioGroup
groupName="child-1-children"
radioProps={[
{
id: "child-1-child-1",
value: "child-1-child-1",
label: "Child 1 Child 1",
children: [
<TextArea
fieldName="child-1-child-textarea"
id="child-1-child-textarea"
label="Child 1 Child 1 TextArea"
/>,
],
},
{
id: "child-1-child-2",
value: "child-1-child-2",
label: "Child 1 Child 2",
},
]}
/>,
],
},
{
id: "child-2",
value: "child-2",
label: "Child 2",
children: [
<TextArea
fieldName="child-textarea"
id="child-textarea"
label="Child 2 TextArea"
/>,
],
},
]}
/>,
];
export const DefaultGroup = Template.bind({});
DefaultGroup.args = {
groupName: "default-group",
radioProps: [
{ id: "radio-1", value: "radio-1", label: "Radio 1" },
{ id: "radio-2", value: "radio-2", label: "Radio 2" },
{ id: "radio-3", value: "radio-3", label: "Radio 3", disabled: true },
],
};
export const WithChildren = Template.bind({});
WithChildren.args = {
groupName: "with-children",
radioProps: [
{
id: "with-children-1",
value: "with-children-1",
label: "Radio 1",
children,
},
{
id: "with-children-2",
value: "with-children-2",
label: "Radio 2",
children: [
<p>A child may be any JSX element.</p>,
<TextArea
fieldName="with-children-2-textarea"
id="with-children-2-textarea"
label="Radio 2 TextArea"
/>,
],
},
],
};
WithChildren.parameters = {
docs: {
description: {
story:
"Children are passed as an array of JSX elements to the parent Radio's `radioProps`. When passing Radio components as children, ensure they are wrapped in their own RadioGroup component (with a unique `name`) to capture state and correctly show/hide any children they may have. Children of children may also be passed this way in order to have a hirarchy several levels deep. See the code example below.",
},
},
};
export const Tile = Template.bind({});
Tile.args = {
groupName: "tile-group",
radioProps: [
{
id: "tile-radio-1",
value: "tile-radio-1",
label: "Radio 1",
isTile: true,
},
{
id: "tile-radio-2",
value: "tile-radio-2",
label: "Radio 2",
isTile: true,
},
{
id: "tile-radio-3",
value: "tile-radio-3",
label: "Radio 3",
isTile: true,
disabled: true,
},
],
};
export const TileWithDescription = Template.bind({});
TileWithDescription.args = {
groupName: "tile-desc-group",
radioProps: [
{
id: "tile-desc-radio-1",
value: "tile-desc-radio-1",
label: "Radio 1",
isTile: true,
tileDescription: "Radio 1 tile description.",
},
{
id: "tile-desc-radio-2",
value: "tile-desc-radio-2",
label: "Radio 2",
isTile: true,
tileDescription: "Radio 2 tile description.",
},
{
id: "tile-desc-radio-3",
value: "tile-desc-radio-3",
label: "Radio 3",
isTile: true,
tileDescription: "Radio 3 tile description.",
disabled: true,
},
],
}; |
#include <stdio.h>
#include <string.h>
union datos
{
char celular[15];
char correo[20];
};
typedef struct
{
int matricula;
char nombre[20];
char carrera[20];
float promedio;
union datos personales;
} alumno;
void Lectura(alumno *a);
int main(void)
{
alumno a1 = {120, "Maria", "Contabilidad", 8.9, {.celular = "5-158-40-50"}}, a2, a3;
printf("Alumno 2\n");
printf("Ingrese la matricula: ");
scanf("%d", &a2.matricula);
fflush(stdin);
printf("Ingrese el nombre: ");
fgets(a2.nombre, sizeof(a2.nombre), stdin);
fflush(stdin);
printf("Ingrese la carrera: ");
fgets(a2.carrera, sizeof(a2.carrera), stdin);
printf("Ingrese el promedio: ");
scanf("%f", &a2.promedio);
fflush(stdin);
printf("Ingrese el correo electronico: ");
fgets(a2.personales.correo, sizeof(a2.personales.correo), stdin);
printf("Alumno 3\n");
Lectura(&a3);
/* Impresion de resultados. */
printf("\nDatos del alumno 1\n");
printf("%d\n", a1.matricula);
puts(a1.nombre);
puts(a1.carrera);
printf("%.2f\n", a1.promedio);
puts(a1.personales.celular);
puts(a1.personales.correo);
strcpy(a1.personales.correo, "hgimenez@hotmail.com");
puts(a1.personales.celular);
puts(a1.personales.correo);
printf("\nDatos del alumno 2\n");
printf("%d\n", a2.matricula);
puts(a2.nombre);
puts(a2.carrera);
printf("%.2f\n", a2.promedio);
puts(a2.personales.celular);
puts(a2.personales.correo);
printf("Ingrese el telefono celular del alumno 2: ");
fflush(stdin);
fgets(a2.personales.celular, sizeof(a2.personales.celular), stdin);
puts(a2.personales.celular);
puts(a2.personales.correo);
printf("\nDatos del alumno 3\n");
printf("%d\n", a3.matricula);
puts(a3.nombre);
puts(a3.carrera);
printf("%.2f\n", a3.promedio);
puts(a3.personales.celular);
puts(a3.personales.correo);
return 0;
}
void Lectura(alumno *a)
{
printf("\nIngresa la matricula: ");
scanf("%d", &a->matricula);
fflush(stdin);
printf("Ingrese el nombre: ");
fgets(a->nombre, sizeof(a->nombre), stdin);
fflush(stdin);
printf("Ingrese la carrera: ");
fgets(a->carrera, sizeof(a->carrera), stdin);
printf("Ingrese el promedio: ");
scanf("%f", &a->promedio);
fflush(stdin);
printf("Ingrese el telefono celular: ");
fgets(a->personales.celular, sizeof(a->personales.celular), stdin);
} |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Ldap
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Attribute.php 22996 2010-09-22 17:01:46Z sgehrig $
*/
/**
* @see Zend_Ldap_Converter
*/
#require_once 'Zend/Ldap/Converter.php';
/**
* Zend_Ldap_Attribute is a collection of LDAP attribute related functions.
*
* @category Zend
* @package Zend_Ldap
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Ldap_Attribute
{
const PASSWORD_HASH_MD5 = 'md5';
const PASSWORD_HASH_SMD5 = 'smd5';
const PASSWORD_HASH_SHA = 'sha';
const PASSWORD_HASH_SSHA = 'ssha';
const PASSWORD_UNICODEPWD = 'unicodePwd';
/**
* Sets a LDAP attribute.
*
* @param array $data
* @param string $attribName
* @param scalar|array|Traversable $value
* @param boolean $append
* @return void
*/
public static function setAttribute(array &$data, $attribName, $value, $append = false)
{
$attribName = strtolower($attribName);
$valArray = array();
if (is_array($value) || ($value instanceof Traversable))
{
foreach ($value as $v)
{
$v = self::_valueToLdap($v);
if ($v !== null) $valArray[] = $v;
}
}
else if ($value !== null)
{
$value = self::_valueToLdap($value);
if ($value !== null) $valArray[] = $value;
}
if ($append === true && isset($data[$attribName]))
{
if (is_string($data[$attribName])) $data[$attribName] = array($data[$attribName]);
$data[$attribName] = array_merge($data[$attribName], $valArray);
}
else
{
$data[$attribName] = $valArray;
}
}
/**
* Gets a LDAP attribute.
*
* @param array $data
* @param string $attribName
* @param integer $index
* @return array|mixed
*/
public static function getAttribute(array $data, $attribName, $index = null)
{
$attribName = strtolower($attribName);
if ($index === null) {
if (!isset($data[$attribName])) return array();
$retArray = array();
foreach ($data[$attribName] as $v)
{
$retArray[] = self::_valueFromLdap($v);
}
return $retArray;
} else if (is_int($index)) {
if (!isset($data[$attribName])) {
return null;
} else if ($index >= 0 && $index<count($data[$attribName])) {
return self::_valueFromLdap($data[$attribName][$index]);
} else {
return null;
}
}
return null;
}
/**
* Checks if the given value(s) exist in the attribute
*
* @param array $data
* @param string $attribName
* @param mixed|array $value
* @return boolean
*/
public static function attributeHasValue(array &$data, $attribName, $value)
{
$attribName = strtolower($attribName);
if (!isset($data[$attribName])) return false;
if (is_scalar($value)) {
$value = array($value);
}
foreach ($value as $v) {
$v = self::_valueToLdap($v);
if (!in_array($v, $data[$attribName], true)) {
return false;
}
}
return true;
}
/**
* Removes duplicate values from a LDAP attribute
*
* @param array $data
* @param string $attribName
* @return void
*/
public static function removeDuplicatesFromAttribute(array &$data, $attribName)
{
$attribName = strtolower($attribName);
if (!isset($data[$attribName])) return;
$data[$attribName] = array_values(array_unique($data[$attribName]));
}
/**
* Remove given values from a LDAP attribute
*
* @param array $data
* @param string $attribName
* @param mixed|array $value
* @return void
*/
public static function removeFromAttribute(array &$data, $attribName, $value)
{
$attribName = strtolower($attribName);
if (!isset($data[$attribName])) return;
if (is_scalar($value)) {
$value = array($value);
}
$valArray = array();
foreach ($value as $v)
{
$v = self::_valueToLdap($v);
if ($v !== null) $valArray[] = $v;
}
$resultArray = $data[$attribName];
foreach ($valArray as $rv) {
$keys = array_keys($resultArray, $rv);
foreach ($keys as $k) {
unset($resultArray[$k]);
}
}
$resultArray = array_values($resultArray);
$data[$attribName] = $resultArray;
}
/**
* @param mixed $value
* @return string|null
*/
private static function _valueToLdap($value)
{
return Zend_Ldap_Converter::toLdap($value);
}
/**
* @param string $value
* @return mixed
*/
private static function _valueFromLdap($value)
{
try {
$return = Zend_Ldap_Converter::fromLdap($value, Zend_Ldap_Converter::STANDARD, false);
if ($return instanceof DateTime) {
return Zend_Ldap_Converter::toLdapDateTime($return, false);
} else {
return $return;
}
} catch (InvalidArgumentException $e) {
return $value;
}
}
/**
* Converts a PHP data type into its LDAP representation
*
* @deprected use Zend_Ldap_Converter instead
* @param mixed $value
* @return string|null - null if the PHP data type cannot be converted.
*/
public static function convertToLdapValue($value)
{
return self::_valueToLdap($value);
}
/**
* Converts an LDAP value into its PHP data type
*
* @deprected use Zend_Ldap_Converter instead
* @param string $value
* @return mixed
*/
public static function convertFromLdapValue($value)
{
return self::_valueFromLdap($value);
}
/**
* Converts a timestamp into its LDAP date/time representation
*
* @param integer $value
* @param boolean $utc
* @return string|null - null if the value cannot be converted.
*/
public static function convertToLdapDateTimeValue($value, $utc = false)
{
return self::_valueToLdapDateTime($value, $utc);
}
/**
* Converts LDAP date/time representation into a timestamp
*
* @param string $value
* @return integer|null - null if the value cannot be converted.
*/
public static function convertFromLdapDateTimeValue($value)
{
return self::_valueFromLdapDateTime($value);
}
/**
* Sets a LDAP password.
*
* @param array $data
* @param string $password
* @param string $hashType
* @param string|null $attribName
* @return null
*/
public static function setPassword(array &$data, $password, $hashType = self::PASSWORD_HASH_MD5,
$attribName = null)
{
if ($attribName === null) {
if ($hashType === self::PASSWORD_UNICODEPWD) {
$attribName = 'unicodePwd';
} else {
$attribName = 'userPassword';
}
}
$hash = self::createPassword($password, $hashType);
self::setAttribute($data, $attribName, $hash, false);
}
/**
* Creates a LDAP password.
*
* @param string $password
* @param string $hashType
* @return string
*/
public static function createPassword($password, $hashType = self::PASSWORD_HASH_MD5)
{
switch ($hashType) {
case self::PASSWORD_UNICODEPWD:
/* see:
* http://msdn.microsoft.com/en-us/library/cc223248(PROT.10).aspx
*/
$password = '"' . $password . '"';
if (function_exists('mb_convert_encoding')) {
$password = mb_convert_encoding($password, 'UTF-16LE', 'UTF-8');
} else if (function_exists('iconv')) {
$password = iconv('UTF-8', 'UTF-16LE', $password);
} else {
$len = strlen($password);
$new = '';
for($i=0; $i < $len; $i++) {
$new .= $password[$i] . "\x00";
}
$password = $new;
}
return $password;
case self::PASSWORD_HASH_SSHA:
$salt = substr(sha1(uniqid(mt_rand(), true), true), 0, 4);
$rawHash = sha1($password . $salt, true) . $salt;
$method = '{SSHA}';
break;
case self::PASSWORD_HASH_SHA:
$rawHash = sha1($password, true);
$method = '{SHA}';
break;
case self::PASSWORD_HASH_SMD5:
$salt = substr(sha1(uniqid(mt_rand(), true), true), 0, 4);
$rawHash = md5($password . $salt, true) . $salt;
$method = '{SMD5}';
break;
case self::PASSWORD_HASH_MD5:
default:
$rawHash = md5($password, true);
$method = '{MD5}';
break;
}
return $method . base64_encode($rawHash);
}
/**
* Sets a LDAP date/time attribute.
*
* @param array $data
* @param string $attribName
* @param integer|array|Traversable $value
* @param boolean $utc
* @param boolean $append
* @return null
*/
public static function setDateTimeAttribute(array &$data, $attribName, $value, $utc = false,
$append = false)
{
$convertedValues = array();
if (is_array($value) || ($value instanceof Traversable))
{
foreach ($value as $v) {
$v = self::_valueToLdapDateTime($v, $utc);
if ($v !== null) $convertedValues[] = $v;
}
}
else if ($value !== null) {
$value = self::_valueToLdapDateTime($value, $utc);
if ($value !== null) $convertedValues[] = $value;
}
self::setAttribute($data, $attribName, $convertedValues, $append);
}
/**
* @param integer $value
* @param boolean $utc
* @return string|null
*/
private static function _valueToLdapDateTime($value, $utc)
{
if (is_int($value)) {
return Zend_Ldap_Converter::toLdapDateTime($value, $utc);
}
else return null;
}
/**
* Gets a LDAP date/time attribute.
*
* @param array $data
* @param string $attribName
* @param integer $index
* @return array|integer
*/
public static function getDateTimeAttribute(array $data, $attribName, $index = null)
{
$values = self::getAttribute($data, $attribName, $index);
if (is_array($values)) {
for ($i = 0; $i<count($values); $i++) {
$newVal = self::_valueFromLdapDateTime($values[$i]);
if ($newVal !== null) $values[$i] = $newVal;
}
}
else {
$newVal = self::_valueFromLdapDateTime($values);
if ($newVal !== null) $values = $newVal;
}
return $values;
}
/**
* @param string|DateTime $value
* @return integer|null
*/
private static function _valueFromLdapDateTime($value)
{
if ($value instanceof DateTime) {
return $value->format('U');
} else if (is_string($value)) {
try {
return Zend_Ldap_Converter::fromLdapDateTime($value, false)->format('U');
} catch (InvalidArgumentException $e) {
return null;
}
} else return null;
}
} |
import React, { useState } from 'react';
import { useMutation } from '@apollo/react-hooks';
import PASS_FORGOT_MUTATION from './PASSWORD_FORGOT_MUTATION';
const PasswordForgot = () => {
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
const passwordForgotMutation = useMutation(
PASS_FORGOT_MUTATION,
{
variables: {
input: { email },
},
},
);
const mutate = async () => {
const r = await passwordForgotMutation();
setMessage(r.data.passwordForgot.message);
};
return (
<div>
<div>
<input
placeholder="Enter your email address"
onChange={(e) => {
setEmail(e.target.value);
}}
value={email}
/>
<button onClick={mutate} type="button">Submit</button>
</div>
<div>
{ message }
</div>
</div>
);
};
export default PasswordForgot; |
---
title: Gerar documento a partir de modelo no OneNote - Aspose.Note
linktitle: Gerar documento a partir de modelo no OneNote - Aspose.Note
second_title: API Java Aspose.Note
description: Gere documentos dinâmicos facilmente usando Aspose.Note para Java. Siga nosso guia passo a passo para geração eficiente de documentos a partir de modelos.
type: docs
weight: 18
url: /pt/java/onenote-text-manipulation/generate-document-from-template/
---
## Introdução
Você deseja agilizar a geração de documentos em seu aplicativo Java? Aspose.Note for Java fornece uma solução poderosa. Neste tutorial, orientaremos você na geração de documentos a partir de modelos usando Aspose.Note para Java, tornando todo o processo fácil e eficiente.
## Pré-requisitos
Antes de mergulhar no tutorial, certifique-se de ter os seguintes pré-requisitos:
- Uma compreensão básica da programação Java.
- Aspose.Note para biblioteca Java. Se não estiver instalado, baixe-o em[aqui](https://releases.aspose.com/note/java/).
- Um documento modelo (por exemplo, "JobOffer.one") para geração de documentos.
## Importar pacotes
Comece importando os pacotes necessários para o seu projeto Java. Esta etapa garante que você tenha acesso a todas as funcionalidades fornecidas pelo Aspose.Note for Java.
```java
import com.aspose.note.*;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import com.aspose.note.RichText
```
## Etapa 1: definir dados do modelo
Aqui, definimos um hashmap (`D`) com pares de valores-chave representando os dados do modelo. Esses valores substituirão os espaços reservados no documento modelo.
```java
// O caminho para o diretório de documentos.
String dataDir = "Your Document Directory";
HashMap<String, String> D = new HashMap<>();
D.put("Company", "Atlas Shrugged Ltd");
D.put("CandidateName", "John Galt");
D.put("JobTitle", "Chief Entrepreneur Officer");
D.put("Department", "Sales");
D.put("Salary", "123456 USD");
D.put("Vacation", "30");
D.put("StartDate", "29 Feb 2024");
D.put("YourName", "Ayn Rand");
```
Certifique-se de substituir "Seu diretório de documentos" pelo caminho do diretório real.
## Etapa 2: carregar documento modelo
Agora, carregamos o documento modelo ("JobOffer.one") usando o`Document`classe de Aspose.Note para Java.
```java
// Carregue o documento modelo no Aspose.Note.
Document d = new Document(Paths.get(dataDir, "JobOffer.one").toString());
```
## Etapa 3: substituir palavras do modelo
Nesta etapa, iteramos pelos nós filhos do documento para substituir as palavras do modelo pelos valores correspondentes do hashmap.
```java
// Vamos substituir todas as palavras do modelo
for (RichText e : d.getChildNodes(RichText.class)) {
for (Map.Entry<String, String> replace : D.entrySet()) {
e.replace(String.format("${%s}", replace.getKey()), replace.getValue());
}
}
```
Isso garante que cada espaço reservado no documento seja substituído pelos dados relevantes.
## Etapa 4: salve o documento gerado
Após substituir as palavras do modelo, salvamos o documento modificado com um novo nome (por exemplo, "JobOffer_out.one") no diretório especificado.
```java
// Salve o documento modificado com um novo nome (por exemplo, "JobOffer_out.one") no diretório especificado.
d.save(Paths.get(dataDir, "JobOffer_out.one").toString());
```
## Etapa 5: confirme a geração bem-sucedida
Por fim, exibimos uma mensagem de confirmação para indicar que o documento foi gerado com sucesso.
```java
// Exibir uma mensagem de confirmação.
System.out.println("\nThe document is generated successfully.");
```
Com essas etapas detalhadas e trechos de código correspondentes, você pode gerar documentos perfeitamente a partir de modelos usando Aspose.Note para Java. Se você tiver mais alguma dúvida, fique à vontade para perguntar!
Agora, com esses trechos de código incorporados, você tem um guia passo a passo abrangente com código para gerar documentos usando Aspose.Note para Java. Sinta-se à vontade para entrar em contato se tiver mais alguma dúvida!
## Conclusão
Parabéns! Você aprendeu com sucesso como gerar documentos a partir de modelos usando Aspose.Note para Java. Este processo simplificado pode melhorar significativamente o fluxo de trabalho de geração de documentos.
## Perguntas frequentes
### Posso usar Aspose.Note for Java com outras linguagens de programação?
Aspose.Note suporta principalmente Java, mas existem versões disponíveis para outras linguagens como .NET.
### O Aspose.Note for Java é compatível com diferentes formatos de documentos?
Sim, Aspose.Note suporta vários formatos, incluindo OneNote, PDF e imagens.
### Onde posso encontrar mais exemplos e documentação?
Consulte o[documentação](https://reference.aspose.com/note/java/) para obter orientações e exemplos abrangentes.
### Como posso obter suporte para Aspose.Note para Java?
Visite a[Fórum Aspose.Note](https://forum.aspose.com/c/note/28)para buscar assistência da comunidade e apoio da Aspose.
### Existe um teste gratuito disponível?
Sim, você pode acessar um[teste grátis](https://releases.aspose.com/) para explorar os recursos antes de fazer uma compra. |
import { useSelector, useDispatch } from 'react-redux';
import images from '../constants/images';
import '../styles/UserPage.css';
import { GoPencil } from 'react-icons/go';
import UserLink from '../components/UserLink';
import { useEffect, useState } from 'react';
import axios from 'axios';
import { updateUser } from '../state/userSlice.js';
const UserPage = () => {
const { user } = useSelector((state) => state.user.user);
const dispatch = useDispatch();
const [isEditable, setIsEditable] = useState(false);
const [name, setName] = useState(user?.name || '');
const [dateOfBirth, setDateOfBirth] = useState(user?.dateOfBirth || '');
const [weight, setWeight] = useState(user?.weight || '');
const [height, setHeight] = useState(user?.height || '');
const [success, setSuccess] = useState('');
useEffect(() => {
const fetchUser = async () => {
const response = await axios.get(
`http://localhost:3001/api/users/${user._id}`
);
if (response) {
dispatch(
updateUser({
user: response.data,
})
);
}
};
fetchUser();
}, [user]);
const formatDate = (dateString) => {
if (!dateString) return '';
const date = new Date(dateString);
const day = date.getDate().toString().padStart(2, '0');
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const year = date.getFullYear();
const formattedDate = `${day}/${month}/${year}`;
return formattedDate;
};
const submitUpdateUser = async (e) => {
e.preventDefault();
try {
const response = await axios.patch(
`http://localhost:3001/api/users/${user._id}`,
{
name,
dateOfBirth,
weight,
height,
}
);
if (response) {
dispatch(
updateUser({
user: response.data,
})
);
setSuccess('Personal information updated successfully!');
}
setIsEditable(false);
} catch (err) {
console.error(err);
}
};
const handleEditClick = (e) => {
e.preventDefault();
setIsEditable(!isEditable);
};
return (
<div className="user-container">
<div className="user-inner-container">
<div className="user-page-info-container">
<UserLink />
<div className="user-info-heading-container">
<h1 className="user-info-heading">PERSONAL INFORMATION</h1>
<div className="user-info-underline"></div>
</div>
<form className="user-info-form" onSubmit={submitUpdateUser}>
<label htmlFor="name" className="form-label">
Name
<input
className={isEditable ? 'form-input' : 'form-input disabled'}
type="text"
id="name"
name="name"
value={name}
placeholder={user?.name}
disabled={!isEditable}
onChange={(e) => setName(e.target.value)}
/>
</label>
<label htmlFor="email" className="form-label">
Email
<input
className="form-input disabled"
type="email"
id="email"
name="email"
placeholder={user?.email}
disabled
/>
</label>
<label htmlFor="dob" className="form-label">
Date of Birth
<input
className={isEditable ? 'form-input' : 'form-input disabled'}
type="text"
id="dob"
name="dob"
value={formatDate(dateOfBirth)}
disabled={!isEditable}
placeholder={user?.dateOfBirth}
onFocus={(e) => (e.target.type = 'date')}
onBlur={(e) => (e.target.type = 'text')}
onChange={(e) => setDateOfBirth(e.target.value)}
/>
</label>
<label htmlFor="name" className="form-label">
Gender
<input
className="form-input disabled"
type="text"
id="gender"
name="gender"
placeholder={`${user?.gender
.charAt(0)
.toUpperCase()}${user?.gender.substring(1)}`}
disabled
/>
</label>
<label htmlFor="weight" className="form-label">
Weight
<input
className={isEditable ? 'form-input' : 'form-input disabled'}
type="text"
id="weight"
name="weight"
value={weight}
placeholder={user?.weight}
onChange={(e) => setWeight(e.target.value)}
disabled={!isEditable}
/>
</label>
<label htmlFor="height" className="form-label">
Height
<input
className={isEditable ? 'form-input' : 'form-input disabled'}
type="text"
id="height"
name="name"
value={height}
placeholder={user?.height}
onChange={(e) => setHeight(e.target.value)}
disabled={!isEditable}
/>
</label>
<p className="success">{success}</p>
<div className="user-button-container">
<button className="secondary-button" onClick={handleEditClick}>
Edit information
</button>
<button
className="primary-button user-primary-button"
type="submit"
disabled={!isEditable}
>
Submit
</button>
</div>
</form>
</div>
<div className="user-page-image-container">
{user.gender === 'male' ? (
<img className="user-page-image" src={images.male_user} />
) : (
<img className="user-page-image" src={images.female_user} />
)}
</div>
</div>
</div>
);
};
export default UserPage; |
import React from 'react'
import {Title} from '../../u0-common/u0.2-components/Title/Title'
import Fade from 'react-reveal/Fade'
import {Button} from '../../u0-common/u0.2-components/Button/Button';
import {useForm} from 'react-hook-form';
import emailjs from 'emailjs-com';
import s from './Contact.module.scss'
export const Contact = React.memo(() => {
let [notification, setNotification] = React.useState({flag: false, message: ''})
const {register, handleSubmit, errors, setError} = useForm();
const onSubmit = async (data, e) => {
emailjs.sendForm('service_gag1lwr', 'template_gy4co6o', e.target, 'user_hIeN5iRzerHb2xlKmzrAe')
.then(result => {
if (result.status === 200) {
e.target.reset()
setNotification({flag: true, message: 'The message was sent successfully. Thanks!'})
setTimeout(() => {
setNotification({flag: false, message: ''})
}, 5000)
} else {
setError('username', 'validate');
setNotification({flag: true, message: 'Something went wrong:(The message was not sent'})
setTimeout(() => {
setNotification({flag: false, message: ''})
}, 5000)
}
})
.catch(err => {
setError('username', 'validate');
setNotification({flag: true, message: 'Something went wrong:(The message was not sent'})
setTimeout(() => {
setNotification({flag: false, message: ''})
}, 5000)
})
}
return (
<div className={s.contactBlock}>
<div className={s.messageSuccess} style={{opacity: notification.flag ? '1' : ''}}>
<span>{notification.message}</span>
</div>
<div className={s.container} id='contact'>
<Fade clear>
<Title title={'Contact'}
titleDescription={`If you wanna get in touch, talk to me about a project collaboration or just say hi,
fill in the awesome form below or send an email.`}
/>
<div className={s.formWrapper}>
<form onSubmit={handleSubmit(onSubmit)} className={s.contactForm}>
<input name="email"
type="text"
placeholder={'Email'}
ref={register({
required: 'This is required',
pattern: {
value: /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
message: 'Invalid email address',
},
})}/>
{errors.email && <span className={s.notificationEmail}>{errors.email.message}</span>}
<input name="name"
type="text"
placeholder={'Name'}
ref={register({
required: true,
validate: value => value.length >= 2
})}/>
{errors.name &&
<span className={s.notificationName}>Your last name is less than 2 characters</span>}
<textarea name="message"
placeholder={'Message'}
ref={register}/>
<Button type="submit"
newStyle
button
disabled={!!notification.flag}
className={s.contactBtn}
>Send message</Button>
</form>
</div>
</Fade>
</div>
</div>
)
}) |
import React, { useState, useEffect } from "react";
import Book from "../Book/Book";
import { IBook } from "@/types/book";
import { Text, Box, Flex } from "@radix-ui/themes";
import { Input } from "../ui/input";
import { Button } from "../ui/button";
const FindYourBooks: React.FC = () => {
const [searchText, setSearchText] = useState("");
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
const [books, setBooks] = useState<IBook[]>([]);
const [loading, setLoading] = useState(false);
const fetchBooks = async () => {
setLoading(true);
try {
const response = await fetch(
`https://api.itbook.store/1.0/search/${searchText}/${currentPage}`
);
if (!response.ok) {
throw new Error("Failed to fetch data");
}
const data = await response.json();
setBooks(data.books);
setTotalPages(Math.ceil(data.total / 10)); // the API gives back only 10 books, so I calculated from it, I also modified becuase of the grid to 2x5 instead of the requested 5x5
setLoading(false);
} catch (error) {
console.error("Error fetching data:", error);
setLoading(false);
}
};
useEffect(() => {
fetchBooks();
}, [searchText, currentPage]);
const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSearchText(event.target.value);
};
const handlePageChange = (page: number) => {
setCurrentPage(page);
};
return (
<Box className="p-16 text-left w-full">
<Flex justify={"between"} align={"center"}>
<Text className="text-2xl uppercase text-orange-800 font-bold">
Find your books
</Text>
<Input
type="text"
className="w-60"
value={searchText}
onChange={handleSearchChange}
placeholder="find your books"
/>
</Flex>
{loading ? (
<Box>Loading...</Box>
) : (
<div>
<div className="grid grid-cols-1 lg:grid-cols-5 gap-2">
{books.map((book: IBook) => (
<Book book={book} key={book.isbn13} />
))}
</div>
{books.length > 0 && (
<Flex justify={"center"}>
<Box>
<Box className="m-2">
{currentPage > 1 && (
<Button
variant="outline"
onClick={() => handlePageChange(currentPage - 1)}
className="m-2"
>
Previous
</Button>
)}
{currentPage < totalPages && (
<Button
variant="outline"
onClick={() => handlePageChange(currentPage + 1)}
className="m-2"
>
Next
</Button>
)}
</Box>
<Text as="div" align="center">
Page {currentPage} of {totalPages}
</Text>
</Box>
</Flex>
)}
</div>
)}
</Box>
);
};
export default FindYourBooks; |
import * as React from 'react';
import type { IconDefinition } from '@fortawesome/fontawesome-common-types';
import { faTwitter, faDiscord } from '@fortawesome/free-brands-svg-icons';
type SvgPosition = {
readonly x: number;
readonly y: number;
};
type SvgSize = {
readonly width: number;
readonly height: number;
};
const SvgIcon: React.VFC<
{
readonly icon: IconDefinition;
readonly size: number;
} & SvgPosition
> = ({ x, y, size, icon }) => {
const [width, height, , , paths] = icon.icon;
const normalizedPaths = [paths].flat();
return (
<g transform={`translate(${x},${y}) scale(${size / width},${size / height})`}>
{normalizedPaths.map((path, i) => (
<path key={i} d={path} />
))}
</g>
);
};
const Avatar: React.VFC<
{
readonly avatarUrl?: string;
readonly radius?: number;
} & SvgPosition &
SvgSize
> = ({ x, y, width, height, radius = 10, avatarUrl }) =>
avatarUrl != null ? (
<>
<clipPath id="avatar">
<rect x={x} y={y} width={width} height={height} rx={radius} ry={radius} />
</clipPath>
<image clipPath="url(#avatar)" href={avatarUrl} x={x} y={y} width={width} height={height} />
</>
) : (
<rect fill="#9ca3af" x={x} y={y} width={width} height={height} rx={radius} ry={radius} />
);
const CheckBox: React.VFC<{
readonly checked: boolean;
}> = ({ checked }) => (
<>
<rect stroke="#4B5563" strokeWidth={2} fill="transparent" x={0} y={-20} width={20} height={20} rx={2} ry={2} />
{checked && (
<path
stroke="blue"
fill="transparent"
strokeWidth={3}
d="
M 4 -14.5
L 9 -5
l 23 -20
"
/>
)}
</>
);
export const CardSvg: React.VFC<{
readonly width?: string;
readonly height?: string;
readonly avatarUrl?: string;
readonly miswLogoUrl: string;
readonly generation: number;
readonly handle: string;
readonly workshops: readonly string[];
readonly squads: readonly string[];
readonly twitterScreenName?: string;
readonly discordId?: string;
}> = ({ width, height, avatarUrl, miswLogoUrl, generation, handle, workshops, squads, twitterScreenName, discordId }) => (
<svg version="1.1" baseProfile="full" width={width} height={height} viewBox="0 0 1200 630" xmlns="https://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="white" />
<Avatar avatarUrl={avatarUrl} x={30} y={30} width={150} height={150} />
<g color="#111827">
<text x={240} y={150} fill="currentcolor" fontSize={100}>
{generation}
<tspan fontSize={60} fontWeight="normal">
代
</tspan>
</text>
<text x={785} y={150} fontSize={80} fill="currentcolor" textAnchor="middle">
{handle}
</text>
<line x1={210} y1={175} x2={1200 - 30} y2={175} stroke="black" strokeWidth={5} strokeLinecap="round" />
</g>
<g color="#111827" transform="translate(210,300)">
<g>
<text fill="currentcolor" fontSize={30}>
{[...'研究会'].map((c, i) => (
<tspan key={c} dx={i === 0 ? 0 : 10}>
{c}
</tspan>
))}
</text>
<g transform="translate(150,0)">
<CheckBox checked={workshops.includes('プログラミング')} />
<text dx={40} fill="currentcolor" fontSize={30}>
プログラミング
</text>
</g>
<g transform="translate(450,0)">
<CheckBox checked={workshops.includes('MIDI')} />
<text dx={40} fill="currentcolor" fontSize={30}>
MIDI
</text>
</g>
<g transform="translate(600,0)">
<CheckBox checked={workshops.includes('CG')} />
<text dx={40} fill="currentcolor" fontSize={30}>
CG
</text>
</g>
</g>
<g transform="translate(0,70)">
<text x={40} fill="currentcolor" fontSize={30}>
班
</text>
<line stroke="currentcolor" strokeWidth={2} strokeLinecap="round" x1={140} y1={5} x2={690} y2={5} />
<text x={150} width={690 - 140 - 40} fill="currentcolor" fontSize={30}>
{squads.map((squad, i) =>
i === 0 ? (
squad
) : (
<>
<tspan dx={5}>,</tspan>
<tspan dx={10}>{squad}</tspan>
</>
),
)}
</text>
</g>
</g>
<g color="#111827" transform="translate(210,500)">
{[
twitterScreenName != null ? (
<>
<SvgIcon icon={faTwitter} x={40} y={-23} size={30} />
<text fill="currentcolor" x={150} fontSize={30}>
@{twitterScreenName}
</text>
</>
) : null,
discordId != null ? (
<>
<SvgIcon icon={faDiscord} x={40} y={-23} size={30} />
<text fill="currentcolor" x={150} fontSize={30}>
{discordId}
</text>
</>
) : null,
]
.filter((x) => x != null)
.map((el, i) => (
<g key={i} transform={`translate(0,${70 * i})`}>
{el}
</g>
))}
</g>
<image href={miswLogoUrl} x={1200 - 600 / 3 - 30} y={630 - 243 / 3 - 15} width={600 / 3} height={243 / 3} />
</svg>
); |
/*
* Copyright (c) 2008 Vijay Kumar B. <vijaykumar@bravegnu.org>
*
* Based on testcases/kernel/syscalls/waitpid/waitpid01.c
* Original copyright message:
*
* Copyright (c) International Business Machines Corp., 2001
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* NAME
* move_pages11.c
*
* DESCRIPTION
* Failure when trying move shared pages.
*
* ALGORITHM
* 1. Allocate a shared memory in NUMA node A.
* 2. Fork another process.
* 3. Use move_pages() to move the pages to NUMA node B, with the
* MPOL_MF_MOVE_ALL.
* 4. Check if errno is set to EPERM.
*
* USAGE: <for command-line>
* move_pages11 [-c n] [-i n] [-I x] [-P x] [-t]
* where, -c n : Run n copies concurrently.
* -i n : Execute test n times.
* -I x : Execute test for x seconds.
* -P x : Pause for x seconds between iterations.
* -t : Turn on syscall timing.
*
* History
* 05/2008 Vijay Kumar
* Initial Version.
*
* Restrictions
* None
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <semaphore.h>
#include <errno.h>
#include <pwd.h>
#include "test.h"
#include "move_pages_support.h"
#define TEST_PAGES 2
#define TEST_NODES 2
enum {
SEM_CHILD_SETUP,
SEM_PARENT_TEST,
MAX_SEMS
};
void setup(void);
void cleanup(void);
char *TCID = "move_pages11";
int TST_TOTAL = 1;
/*
* child() - touches shared pages, and waits for signal from parent.
* @pages: shared pages allocated in parent
* @sem: semaphore to sync with parent
*/
void child(void **pages, sem_t * sem)
{
int i;
for (i = 0; i < TEST_PAGES; i++) {
char *page;
page = pages[i];
page[0] = 0xAA;
}
/* Setup complete. Ask parent to continue. */
if (sem_post(&sem[SEM_CHILD_SETUP]) == -1)
tst_resm(TWARN, "error post semaphore: %s", strerror(errno));
/* Wait for testcase in parent to complete. */
if (sem_wait(&sem[SEM_PARENT_TEST]) == -1)
tst_resm(TWARN, "error wait semaphore: %s", strerror(errno));
exit(0);
}
int main(int argc, char **argv)
{
tst_parse_opts(argc, argv, NULL, NULL);
setup();
#if HAVE_NUMA_MOVE_PAGES
unsigned int i;
int lc;
unsigned int from_node;
unsigned int to_node;
int ret;
ret = get_allowed_nodes(NH_MEMS, 2, &from_node, &to_node);
if (ret < 0)
tst_brkm(TBROK | TERRNO, cleanup, "get_allowed_nodes: %d", ret);
/* check for looping state if -i option is given */
for (lc = 0; TEST_LOOPING(lc); lc++) {
void *pages[TEST_PAGES] = { 0 };
int nodes[TEST_PAGES];
int status[TEST_PAGES];
pid_t cpid;
sem_t *sem;
/* reset tst_count in case we are looping */
tst_count = 0;
ret = alloc_shared_pages_on_node(pages, TEST_PAGES, from_node);
if (ret == -1)
continue;
for (i = 0; i < TEST_PAGES; i++) {
nodes[i] = to_node;
}
sem = alloc_sem(MAX_SEMS);
if (sem == NULL) {
goto err_free_pages;
}
/*
* Fork a child process so that the shared pages are
* now really shared between two processes.
*/
cpid = fork();
if (cpid == -1) {
tst_resm(TBROK, "forking child failed: %s",
strerror(errno));
goto err_free_sem;
} else if (cpid == 0) {
child(pages, sem);
}
/* Wait for child to setup and signal. */
if (sem_wait(&sem[SEM_CHILD_SETUP]) == -1)
tst_resm(TWARN, "error wait semaphore: %s",
strerror(errno));
ret = numa_move_pages(0, TEST_PAGES, pages, nodes,
status, MPOL_MF_MOVE_ALL);
if (ret == -1 && errno == EPERM)
tst_resm(TPASS, "move_pages failed with "
"EPERM as expected");
else
tst_resm(TFAIL|TERRNO, "move_pages did not fail "
"with EPERM ret: %d", ret);
/* Test done. Ask child to terminate. */
if (sem_post(&sem[SEM_PARENT_TEST]) == -1)
tst_resm(TWARN, "error post semaphore: %s",
strerror(errno));
/* Read the status, no zombies! */
wait(NULL);
err_free_sem:
free_sem(sem, MAX_SEMS);
err_free_pages:
free_shared_pages(pages, TEST_PAGES);
}
#else
tst_resm(TCONF, "move_pages support not found.");
#endif
cleanup();
tst_exit();
}
/*
* setup() - performs all ONE TIME setup for this test
*/
void setup(void)
{
struct passwd *ltpuser;
tst_require_root();
tst_sig(FORK, DEF_HANDLER, cleanup);
check_config(TEST_NODES);
if ((ltpuser = getpwnam("nobody")) == NULL) {
tst_brkm(TBROK, NULL, "'nobody' user not present");
}
if (seteuid(ltpuser->pw_uid) == -1) {
tst_brkm(TBROK, NULL, "setting uid to %d failed",
ltpuser->pw_uid);
}
/* Pause if that option was specified
* TEST_PAUSE contains the code to fork the test with the -c option.
*/
TEST_PAUSE;
}
/*
* cleanup() - performs all ONE TIME cleanup for this test at completion
*/
void cleanup(void)
{
} |
package com.spongzi.train.business.controller.admin;
import com.spongzi.train.business.req.StationQueryReq;
import com.spongzi.train.business.req.StationSaveReq;
import com.spongzi.train.business.resp.StationQueryResp;
import com.spongzi.train.business.service.StationService;
import com.spongzi.train.business.service.TrainSeatService;
import com.spongzi.train.common.resp.CommonResp;
import com.spongzi.train.common.resp.PageResp;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/admin/station")
public class StationAdminController {
@Resource
private StationService stationService;
@Resource
private TrainSeatService trainSeatService;
@PostMapping("/save")
public CommonResp<Object> save(@Valid @RequestBody StationSaveReq req) {
stationService.save(req);
return CommonResp.builder().build();
}
@GetMapping("/query-list")
public CommonResp<PageResp<StationQueryResp>> queryList(@Valid StationQueryReq req) {
PageResp<StationQueryResp> list = stationService.queryList(req);
return CommonResp.<PageResp<StationQueryResp>>builder().content(list).build();
}
@DeleteMapping("/delete/{id}")
public CommonResp<Object> delete(@PathVariable Long id) {
stationService.delete(id);
return CommonResp.builder().build();
}
@GetMapping("/query-all")
public CommonResp<List<StationQueryResp>> queryAll() {
return CommonResp.<List<StationQueryResp>>builder()
.content(stationService.queryAll())
.build();
}
@GetMapping("/gen-seat/{trainCode}")
public CommonResp<Object> genSeat(@PathVariable String trainCode) {
trainSeatService.genTrainSeat(trainCode);
return CommonResp.builder()
.message("生成座位成功!")
.build();
}
} |
package com.suihan74.hatena.service
import com.suihan74.hatena.HatenaClient
import com.suihan74.hatena.model.bookmark.BookmarkResult
import java.time.LocalDateTime
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
/**
* ブクマ情報をHTMLから取得する
*/
internal suspend fun getBookmarkImpl(
url: String,
eid: Long,
user: String,
generalService: GeneralService
) : BookmarkResult? {
// サインインしていないクライアントでも取得できればprivateではないと判断する
val private =
if (generalService != HatenaClient.generalService) {
HatenaClient.generalService.get(url).code() != 200
}
else false
return runCatching {
generalService.getHtml(url) { doc ->
// ブクマされていない or アクセスできない
if (doc.getElementsByTag("html").first()!!.attr("data-page-scope") != "EntryComment") {
return@getHtml null
}
doc.getElementsByClass("comment-body").first()?.let { body ->
val comment = body.getElementsByClass("comment-body-text").text().orEmpty()
val tags =
body.getElementsByClass("comment-body-tags").first()
?.getElementsByTag("li")
?.map { it.wholeText() }
?: emptyList()
val commentRaw = tags.joinToString(separator = "", postfix = comment) { "[$it]" }
val dateTimeFormatter = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm")
val timestampStr = body.getElementsByClass("comment-body-date").first()!!.wholeText()
val timestamp =
OffsetDateTime.of(
LocalDateTime.parse(timestampStr, dateTimeFormatter),
ZoneOffset.ofHours(9)
).toInstant()
BookmarkResult(
user = user,
comment = comment,
tags = tags,
timestamp = timestamp,
userIconUrl = HatenaClient.user.getUserIconUrl(user),
commentRaw = commentRaw,
permalink = url,
eid = eid,
private = private
)
}
}
}.getOrNull()
} |
<template>
<div class="input-container">
<div class="input-group">
<label class="input-label">Имя:</label>
<input class="text-input" v-model="nameValue" placeholder="Имя">
</div>
<div class="input-group">
<label class="input-label">Фамилия:</label>
<input class="text-input" v-model="lastNameValue" placeholder="Фамилия">
</div>
</div>
<div class="selected-input">
<div class="input-group centered">
<label class="input-label">Режим налогооблажения:</label>
<select class="dropdown larger-dropdown" v-model="selectedOption">
<option value="Упрощённый">Упрощённый</option>
<option value="Общеустановленный">Общеустановленный</option>
</select>
</div>
</div>
<div class="input-document">
<div class="input-group">
<label class="input-label">ИИН:</label>
<input class="text-input larger-dropdown" v-model="iinValue" @input="validateNumber" placeholder="ИИН" maxlength="12" minlength="12">
</div>
</div>
<div class="input-income">
<div class="input-group">
<label class="input-label">Ваш доход за полгода:</label>
<input class="text-input larger-dropdown" v-model="incomeValue" @input="validateNumber" v-bind:incomeValue="someValue" placeholder="Доход" min="1" max="150000000">
</div>
</div>
<div class="submit-class">
<button class="submit-btn" @click="sendData">Рассчитать</button>
</div>
</template>
<script>
export default {
data() {
return {
nameValue: '',
lastNameValue: '',
selectedOption: 'Общеустановленный',
iinValue: '',
incomeValue: ''
};
},
methods: {
validateNumber() {
this.iinValue = this.iinValue.replace(/\D/g, '');
},sendData() {
const validIIN = this.iinValue.length === 12;
const validIncome = this.incomeValue > 0 && this.incomeValue <= 150000000;
const validName = this.nameValue.trim().length > 0;
const validLastName = this.lastNameValue.trim().length > 0;
const isValidData = validIIN && validIncome && validName && validLastName;
if (isValidData) {
this.$store.dispatch('incomeData', this.incomeValue);
this.$store.commit('updateFormData', {
name: this.nameValue,
lastName: this.lastNameValue,
selectedOption: this.selectedOption,
iin: this.iinValue,
income: this.incomeValue
});
this.$router.push('/nalog');
} else {
if (!validName) {
alert('Введите имя');
} else if (!validLastName) {
alert('Введите фамилию');
} else if (!validIIN) {
alert('ИИН должен состоять из 12 цифр');
} else {
alert('Доход должен быть больше 0 и не превышать 150000000');
}
}
},
}
};
</script>
<style src="./InputComponent.styles.css">
</style> |
<!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>Tablas en HTML</title>
<link rel="stylesheet" href="css/estilos.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=Roboto:wght@100&display=swap" rel="stylesheet">
</head>
<body>
<table>
<caption>Listado de personas</caption>
<tr>
<!--Cabeceros
<th colspan="2">Nombre</th>-->
<th>Nombre</th>
<th>Apellido</th>
<th>Email</th>
</tr>
<tr>
<!--Datos-->
<td>Juan</td>
<td>Perez</td>
<!--<td rowspan="2">Jperez@mail.com</td>-->
<td>Jperez@mail.com</td>
</tr>
<tr>
<!--Datos-->
<td>Maria</td>
<td>Lara</td>
<td>Mlara@mail.com</td>
</tr>
<tr>
<!--Datos-->
<td>Carlos</td>
<td>Apa</td>
<td>Capa@mail.com</td>
</tr>
<tr>
<!--Datos-->
<td>Carla</td>
<td>Esperanza</td>
<td>CEsperanza@mail.com</td>
</tr>
</table>
<!--
colspan: Celdas
rowspan: Renglones
-->
</body>
</html> |
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source,
// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
// SPDX - License - Identifier: GPL - 3.0 +
#pragma once
#include <atomic>
#include <mutex>
namespace Mantid {
namespace Kernel {
/** Thread-safety check
* Checks the workspace to ensure it is suitable for multithreaded access.
* NULL workspaces are assumed suitable
* @param workspace pointer to workspace to verify.
* @return Whether workspace is threadsafe.
*/
template <typename Arg>
inline typename std::enable_if<std::is_pointer<Arg>::value, bool>::type threadSafe(Arg workspace) {
return !workspace || workspace->threadSafe();
}
/** Thread-safety check
* Checks the workspace to ensure it is suitable for multithreaded access.
* NULL workspaces are assumed suitable
* @param workspace pointer to workspace to verify.
* @param others pointers to all other workspaces which need to be checked.
* @return whether workspace is threadsafe.
*/
template <typename Arg, typename... Args>
inline typename std::enable_if<std::is_pointer<Arg>::value, bool>::type threadSafe(Arg workspace, Args &&...others) {
return (!workspace || workspace->threadSafe()) && threadSafe(std::forward<Args>(others)...);
}
/** Thread-safety check
* Checks the workspace to ensure it is suitable for multithreaded access.
* @param workspace reference to workspace to verify.
* @return Whether workspace is threadsafe.
*/
template <typename Arg>
inline typename std::enable_if<!std::is_pointer<Arg>::value, bool>::type threadSafe(const Arg &workspace) {
return workspace.threadSafe();
}
/** Thread-safety check
* Checks the workspace to ensure it is suitable for multithreaded access.
* @param workspace reference to workspace to verify.
* @param others references or pointers to all other workspaces which need to be
* checked.
* @return whether workspace is threadsafe.
*/
template <typename Arg, typename... Args>
inline typename std::enable_if<!std::is_pointer<Arg>::value, bool>::type threadSafe(const Arg &workspace,
Args &&...others) {
return workspace.threadSafe() && threadSafe(std::forward<Args>(others)...);
}
/** Uses std::compare_exchange_weak to update the atomic value f = op(f, d)
* Used to improve parallel scaling in algorithms MDNormDirectSC and MDNormSCD
* @param f atomic variable being updated
* @param d second element in binary operation
* @param op binary operation on elements f and d
*/
template <typename T, typename BinaryOp> void AtomicOp(std::atomic<T> &f, T d, BinaryOp op) {
T old = f.load();
T desired;
do {
desired = op(old, d);
} while (!f.compare_exchange_weak(old, desired));
}
} // namespace Kernel
} // namespace Mantid
// The syntax used to define a pragma within a macro is different on windows and
// GCC
#ifdef _MSC_VER
#define PRAGMA __pragma
#define PARALLEL_SET_CONFIG_THREADS
#else //_MSC_VER
#define PRAGMA(x) _Pragma(#x)
#define PARALLEL_SET_CONFIG_THREADS \
setMaxCoresToConfig(); \
PARALLEL_SET_DYNAMIC(false);
#endif //_MSC_VER
/** Begins a block to skip processing is the algorithm has been interupted
* Note the end of the block if not defined that must be added by including
* PARALLEL_END_INTERRUPT_REGION at the end of the loop
*/
#define PARALLEL_START_INTERRUPT_REGION \
if (!m_parallelException && !m_cancel) { \
try {
/** Ends a block to skip processing is the algorithm has been interupted
* Note the start of the block if not defined that must be added by including
* PARALLEL_START_INTERRUPT_REGION at the start of the loop
*/
#define PARALLEL_END_INTERRUPT_REGION \
} /* End of try block in PARALLEL_START_INTERRUPT_REGION */ \
catch (std::exception & ex) { \
if (!m_parallelException) { \
m_parallelException = true; \
g_log.error() << this->name() << ": " << ex.what() << "\n"; \
} \
} \
catch (...) { \
m_parallelException = true; \
} \
} // End of if block in PARALLEL_START_INTERRUPT_REGION
/** Adds a check after a Parallel region to see if it was interupted
*/
#define PARALLEL_CHECK_INTERRUPT_REGION \
if (m_parallelException) { \
g_log.debug("Exception thrown in parallel region"); \
throw std::runtime_error(this->name() + ": error (see log)"); \
} \
interruption_point();
// _OPENMP is automatically defined if openMP support is enabled in the
// compiler.
#ifdef _OPENMP
#include "MantidKernel/ConfigService.h"
#include <omp.h>
/** Includes code to add OpenMP commands to run the next for loop in parallel.
* This includes an arbirary check: condition.
* "condition" must evaluate to TRUE in order for the
* code to be executed in parallel
*/
#define PARALLEL_FOR_IF(condition) \
PARALLEL_SET_CONFIG_THREADS \
PRAGMA(omp parallel for if (condition) )
/** Includes code to add OpenMP commands to run the next for loop in parallel.
* This includes no checks to see if workspaces are suitable
* and therefore should not be used in any loops that access workspaces.
*/
#define PARALLEL_FOR_NO_WSP_CHECK() \
PARALLEL_SET_CONFIG_THREADS \
PRAGMA(omp parallel for)
/** Includes code to add OpenMP commands to run the next for loop in parallel.
* and declare the variables to be firstprivate.
* This includes no checks to see if workspaces are suitable
* and therefore should not be used in any loops that access workspace.
*/
#define PARALLEL_FOR_NOWS_CHECK_FIRSTPRIVATE(variable) \
PARALLEL_SET_CONFIG_THREADS \
PRAGMA(omp parallel for firstprivate(variable) )
#define PARALLEL_FOR_NO_WSP_CHECK_FIRSTPRIVATE2(variable1, variable2) \
PARALLEL_SET_CONFIG_THREADS \
PRAGMA(omp parallel for firstprivate(variable1, variable2) )
/** Ensures that the next execution line or block is only executed if
* there are multple threads execting in this region
*/
#define IF_PARALLEL if (omp_get_num_threads() > 1)
/** Ensures that the next execution line or block is only executed if
* there is only one thread in operation
*/
#define IF_NOT_PARALLEL if (omp_get_num_threads() == 1)
/** Specifies that the next code line or block will only allow one thread
* through at a time
*/
#define PARALLEL_CRITICAL(name) PRAGMA(omp critical(name))
/** Allows only one thread at a time to write to a specific memory location
*/
#define PARALLEL_ATOMIC PRAGMA(omp atomic)
#define PARALLEL_SET_NUM_THREADS(MaxCores) omp_set_num_threads(MaxCores);
/** A value that indicates if the number of threads available in subsequent
* parallel region
* can be adjusted by the runtime. If nonzero, the runtime can adjust the
* number of threads,
* if zero, the runtime will not dynamically adjust the number of threads.
*/
#define PARALLEL_SET_DYNAMIC(val) omp_set_dynamic(val)
#define PARALLEL_NUMBER_OF_THREADS omp_get_num_threads()
#define PARALLEL_GET_MAX_THREADS omp_get_max_threads()
#define PARALLEL_THREAD_NUMBER omp_get_thread_num()
#define PARALLEL PRAGMA(omp parallel)
#define PARALLEL_SECTIONS PRAGMA(omp sections nowait)
#define PARALLEL_SECTION PRAGMA(omp section)
inline void setMaxCoresToConfig() {
const auto maxCores = Mantid::Kernel::ConfigService::Instance().getValue<int>("MultiThreaded.MaxCores");
if (maxCores.get_value_or(0) > 0) {
PARALLEL_SET_NUM_THREADS(maxCores.get());
}
}
/** General purpose define for OpenMP, becomes the equivalent of
* #pragma omp EXPRESSION
* (if your compiler supports OpenMP)
*/
#define PRAGMA_OMP(expression) PRAGMA(omp expression)
#else //_OPENMP
/// Empty definitions - to enable set your complier to enable openMP
#define PARALLEL_FOR_IF(condition)
#define PARALLEL_FOR_NO_WSP_CHECK()
#define PARALLEL_FOR_NOWS_CHECK_FIRSTPRIVATE(variable)
#define PARALLEL_FOR_NO_WSP_CHECK_FIRSTPRIVATE2(variable1, variable2)
#define IF_PARALLEL if (false)
#define IF_NOT_PARALLEL
#define PARALLEL_CRITICAL(name)
#define PARALLEL_ATOMIC
#define PARALLEL_THREAD_NUMBER 0
#define PARALLEL_SET_NUM_THREADS(MaxCores)
#define PARALLEL_SET_DYNAMIC(val)
#define PARALLEL_NUMBER_OF_THREADS 1
#define PARALLEL_GET_MAX_THREADS 1
#define PARALLEL
#define PARALLEL_SECTIONS
#define PARALLEL_SECTION
#define PRAGMA_OMP(expression)
#endif //_OPENMP |
package com.echain.web.shiro;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
//import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.SerializationUtils;
import com.echain.service.common.RedisUtil;
public class RedisSessionDao extends AbstractSessionDAO {
private static Logger logger = LoggerFactory.getLogger(RedisSessionDao.class);
/**
* 过期时间 分钟
*/
private int expire;
@Resource
private RedisUtil redisUtil;
@Override
protected Serializable doCreate(Session session) {
Serializable sessionId = this.generateSessionId(session);
this.assignSessionId(session, sessionId);
this.saveSession(session);
return sessionId;
}
@Override
protected Session doReadSession(Serializable sessionId) {
if (sessionId == null) {
logger.error("session id is null");
return null;
}
logger.debug("Read Redis.SessionId="
+ new String(getKey(ShiroRedisConstant.SHIRO_REDIS_SESSION_PRE, sessionId.toString())));
logger.info("Session.classLoader {}", Session.class.getClassLoader().toString());
logger.info("SimpleSession.classLoader {}", SimpleSession.class.getClassLoader().toString());
Session session = (SimpleSession) SerializationUtils.deserialize(
redisUtil.getCache(getKey(ShiroRedisConstant.SHIRO_REDIS_SESSION_PRE, sessionId.toString())));
return session;
}
@Override
public void update(Session session) throws UnknownSessionException {
this.saveSession(session);
}
int i = 0;
public void saveSession(Session session) {
if (session == null || session.getId() == null) {
logger.error("session or session id is null");
return;
}
session.setTimeout(expire * 1000 * 60);
int timeout = expire * 60;
// 保存用户会话
redisUtil.setEx(this.getKey(ShiroRedisConstant.SHIRO_REDIS_SESSION_PRE, session.getId().toString()),
SerializationUtils.serialize(session), timeout);
// 获取用户id
String uid = getUserId(session);
if (StringUtils.isNotBlank(uid)) {
// 保存用户会话对应的UID
try {
redisUtil.setEx(this.getKey(ShiroRedisConstant.SHIRO_SESSION_PRE, session.getId().toString()), uid,
timeout, TimeUnit.SECONDS);
// 保存在线UID
redisUtil.setEx(this.getKey(ShiroRedisConstant.UID_PRE, uid), ("online" + (i++)), timeout,
TimeUnit.SECONDS);
} catch (Exception ex) {
logger.error("getBytes error:" + ex.getMessage());
}
}
}
public String getUserId(Session session) {
SimplePrincipalCollection pricipal = (SimplePrincipalCollection) session
.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY");
if (null != pricipal) {
return pricipal.getPrimaryPrincipal().toString();
}
return null;
}
public String getKey(String prefix, String keyStr) {
return prefix + keyStr;
}
@Override
public void delete(Session session) {
if (session == null || session.getId() == null) {
logger.error("session or session id is null");
return;
}
// 删除用户会话
redisUtil.delete(this.getKey(ShiroRedisConstant.SHIRO_REDIS_SESSION_PRE, session.getId().toString()));
// 获取缓存的用户会话对应的UID
String uid = redisUtil.get(this.getKey(ShiroRedisConstant.SHIRO_SESSION_PRE, session.getId().toString()));
// 删除用户会话sessionid对应的uid
redisUtil.delete(this.getKey(ShiroRedisConstant.SHIRO_SESSION_PRE, session.getId().toString()));
// 删除在线uid
redisUtil.delete(this.getKey(ShiroRedisConstant.UID_PRE, uid));
// 删除用户缓存的角色
redisUtil.delete(this.getKey(ShiroRedisConstant.ROLE_PRE, uid));
// 删除用户缓存的权限
redisUtil.delete(this.getKey(ShiroRedisConstant.PERMISSION_PRE, uid));
}
@Override
public Collection<Session> getActiveSessions() {
Set<Session> sessions = new HashSet<>();
Set<String> keys = redisUtil.keys(ShiroRedisConstant.SHIRO_REDIS_SESSION_PRE + "*");
if (keys != null && keys.size() > 0) {
for (String key : keys) {
Session s = (Session) SerializationUtils.deserialize(redisUtil.getCache(key));
sessions.add(s);
}
}
return sessions;
}
/**
* 当前用户是否在线
*
* @param uid 用户id
* @return
*/
public boolean isOnLine(String uid) {
String value = redisUtil.get(ShiroRedisConstant.UID_PRE + uid);
return StringUtils.isNotBlank(value);
// Set<String> keys = redisUtil.keys(ShiroRedisConstant.UID_PRE + uid);
// if (keys != null && keys.size() > 0) {
// return true;
// }
// return false;
}
public void setExpire(int expire) {
this.expire = expire;
}
} |
import { useFetch } from "../hooks/useFetch"
import { RootObjectPokemons } from "../interfaces/pokemons.interface"
import { PokeCard } from "./PokeCard"
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
export const PokeGrid = () => {
const { data, error, loading } = useFetch<RootObjectPokemons>("https://pokeapi.co/api/v2/pokemon/")
if (loading) {
return <div>Loading...</div>
} else if (error) {
return <div>{error.message}</div>
} else {
return (
<>
<Container className="text-center">
<Row className="align-items-center justify-content-center">
{data?.results.map((pokemon, index) => (
<Col key={index} lg='4' md='6' sm='12' className="text-center">
<PokeCard url={pokemon.url} />
</Col>
))}
</Row>
</Container>
</>
)
}
} |
---
permalink: upgrade/concept_upgrade_methods.html
sidebar: sidebar
keywords: upgrade, methods, andu, ndu, automated, automatic, system manager, cli, nondisruptive, disruptive
summary: アップグレード方法は構成によって異なります。 可能な場合は、 System Manager を使用した自動無停止アップグレード( ANDU )を推奨します。
---
= ONTAPソフトウェアのアップグレード方法
:allow-uri-read:
:icons: font
:imagesdir: ../media/
[role="lead"]
[System Manage]を使用して、ONTAPソフトウェアの自動アップグレードを実行できます。または、ONTAPのコマンドラインインターフェイス(CLI)を使用して、自動アップグレードまたは手動アップグレードを実行することもできます。ONTAPをアップグレードする方法は、構成、現在のONTAPのバージョン、およびクラスタ内のノード数によって異なります。NetAppでは、別のアプローチが必要な構成でないかぎり、System Managerを使用して自動アップグレードを実行することを推奨しています。たとえば、ONTAP 9.3以降を実行している4ノードのMetroCluster構成では、System Managerを使用して自動アップグレード(自動無停止アップグレードまたはANDUと呼ばれることもあります)を実行する必要があります。8ノードのMetroCluster構成でONTAP 9.2以前を実行している場合は、CLIを使用して手動アップグレードを実行する必要があります。
アップグレードは、ローリングアップグレードプロセスまたはバッチアップグレードプロセスを使用して実行できます。どちらも無停止で実行できます。
.ONTAPローリングアップグレード
ローリングアップグレードプロセスでは、ノードをオフラインにしてアップグレードし、その間ノードのストレージをパートナーにテイクオーバーします。アップグレードが完了すると、パートナーノードから元の所有者ノードに制御がギブバックされ、パートナーノードで同じ処理が実行されます。HA ペアのそれぞれについて、すべての HA ペアがターゲットリリースに切り替わるまで順番にアップグレードを行います。8ノード未満のクラスタでは、ローリングアップグレードプロセスがデフォルトです。
.ONTAPノバッチアップグレード
バッチアップグレードプロセスでは、クラスタが複数のHAペアを含む複数のバッチに分割されます。最初のバッチで半数のノードをアップグレードし、続けてそれぞれの HA パートナーをアップグレードします。その後、残りのバッチについても処理が順番に繰り返されます。バッチアップグレードプロセスは、8ノード以上のクラスタのデフォルトです。
自動アップグレードの場合、ONTAPはターゲットONTAPイメージを各ノードに自動的にインストールし、クラスタの無停止アップグレードが可能なことを確認するためにクラスタコンポーネントを検証してから、ノード数に基づいてバッチアップグレードまたはローリングアップグレードをバックグラウンドで実行します。手動アップグレードの場合、クラスタ内の各ノードをアップグレードする準備ができていることを管理者が手動で確認してから、ローリングアップグレードを実行します。
== 設定に基づく推奨されるONTAPアップグレード方式
お使いの構成でサポートされているアップグレード方法は、推奨される使用方法の順に記載されています。
[cols="4"]
|===
| 設定 | ONTAPバージョン | ノードの数 | 推奨されるアップグレード方式
| 標準 | 9.0以降 | 2以上 a|
* xref:task_upgrade_andu_sm.html[System Manager を使用した自動無停止アップグレード]
* xref:task_upgrade_andu_cli.html[CLI を使用した自動無停止アップグレード]
| 標準 | 9.0以降 | シングル | xref:task_upgrade_disruptive_automated_cli.html[自動停止機能]
| MetroCluster | 9.3以降 | 8 a|
* xref:task_upgrade_andu_cli.html[CLI を使用した自動無停止アップグレード]
* xref:task_updating_a_four_or_eight_node_mcc.html[CLIを使用した4ノードまたは8ノードMetroClusterの手動による無停止化]
| MetroCluster | 9.3以降 | 2/4 a|
* xref:task_upgrade_andu_sm.html[System Manager を使用した自動無停止アップグレード]
* xref:task_upgrade_andu_cli.html[CLI を使用した自動無停止アップグレード]
| MetroCluster | 9.2 以前 | 4、8 | xref:task_updating_a_four_or_eight_node_mcc.html[CLIを使用した4ノードまたは8ノードMetroClusterの手動による無停止化]
| MetroCluster | 9.2 以前 | 2. | xref:task_updating_a_two_node_metrocluster_configuration_in_ontap_9_2_and_earlier.html[CLIを使用した2ノードMetroClusterの手動無停止アップグレード]
|===
設定に関係なく、すべてのパッチアップグレードではSystem Managerを使用したANDUのアップグレードが推奨されます。
NOTE: A xref:task_updating_an_ontap_cluster_disruptively.html[手動による停止を伴うアップグレード] 任意の構成で実行できます。 ただし、停止を伴うアップグレードを実行するには、アップグレード中にクラスタをオフラインにする必要があります。SAN 環境を使用している場合は、停止を伴うアップグレードを実行する前に、すべての SAN クライアントをシャットダウンまたは一時停止できるように準備しておく必要があります。停止を伴うアップグレードは、 ONTAP CLI を使用して実行します。 |
import './Valute.scss'
import { Button } from '@mui/material'
import { useStore } from 'context/Provider'
type Props = {
onCurrencyChange: (newCurrency: string) => void
}
const currencies = ['USD', 'EUR', 'UAH', 'ZLT']
const Valute: React.FC<Props> = ({ onCurrencyChange }) => {
const { currency, setCurrency } = useStore()
const handleClick = (c: string) => {
setCurrency(c)
}
return (
<div className="valutes">
{currencies.map((c) => (
<Button
key={c}
variant={c === currency ? 'contained' : 'text'}
onClick={() => handleClick(c)}
>
{c}
</Button>
))}
</div>
)
}
export default Valute |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:get/get.dart';
import 'package:login/Screens/login.dart';
import 'package:login/Components/my_button.dart';
import 'package:login/Screens/web/web_start.dart';
import 'package:login/Screens/register.dart';
import 'package:login/Services/auth_service.dart';
import 'package:lottie/lottie.dart';
import 'package:login/Screens/create_account/create_account.dart';
class Start extends StatefulWidget {
const Start({super.key});
@override
State<Start> createState() => _StartState();
}
class _StartState extends State<Start> {
ValueNotifier<bool> _signInPressed = ValueNotifier(false);
ValueNotifier<bool> _downAnimation = ValueNotifier(false);
void signInWithGoogle() async {
await AuthService().signInWithGoogle();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, contraints) {
if (contraints.maxWidth < 500) {
return WillPopScope(
onWillPop: () async {
_signInPressed.value = false;
_downAnimation.value = true;
await Future.delayed(300.ms);
return false;
},
child: Scaffold(
backgroundColor: Colors.grey[300],
body: SafeArea(
child: Column(
children: [
Flexible(
flex: 4,
fit: FlexFit.tight,
child: Image.asset('assets/background.png')),
Flexible(
flex: 1,
fit: FlexFit.tight,
child: Container(),
),
Expanded(
flex: 7,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: AnimatedBuilder(
animation: _signInPressed,
builder: (context, Widget? child) {
if (_signInPressed.value == false) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
const SizedBox(
height: 51,
),
Container(
constraints: BoxConstraints(
maxHeight: 275, maxWidth: 275),
child: Lottie.asset("assets/people.json"),
),
MyButton(
padding: 15,
text: "CREATE ACCOUNT",
onTap: () => Get.to(
() => CreateAccount(),
transition: Transition.rightToLeft,
duration: Duration(milliseconds: 200),
),
),
SizedBox(height: 15),
MyButton(
padding: 15,
text: "SIGN IN",
onTap: () => _signInPressed.value =
!_signInPressed.value,
color: Colors.white,
textColor: Colors.black,
),
],
);
} else {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
constraints: BoxConstraints(
maxHeight: 275, maxWidth: 275),
child: Lottie.asset("assets/people.json"),
).animate().slideY(begin: 0.1854),
IntegratedButton(
text: "SIGN IN WITH APPLE",
onTap: () => Get.to(
() => Register(),
transition: Transition.upToDown,
duration: Duration(milliseconds: 200),
),
iconRoute: "assets/apple.png",
color: Colors.white,
textColor: Colors.black,
).animate().slideY(begin: 1.8).fadeIn(),
SizedBox(height: 7),
IntegratedButton(
text: "SIGN IN WITH GOOGLE",
onTap: () => signInWithGoogle(),
color: Colors.white,
textColor: Colors.black,
iconRoute: "assets/google.png",
).animate().slideY(begin: 0.9).fadeIn(),
SizedBox(height: 7),
IntegratedButton(
iconRoute: "assets/email.png",
text: "SIGN IN WITH EMAIL",
onTap: () => Get.to(
() => Login(),
transition: Transition.downToUp,
duration: Duration(milliseconds: 200),
),
color: Colors.white,
textColor: Colors.black,
),
],
);
}
},
)),
),
],
),
),
),
);
} else {
return webStart();
}
},
);
}
} |
import React, { useEffect } from "react";
import WorkoutDetailComponent from "../components/WorkoutDetailComponent";
import WorkoutForm from "../components/WorkoutForm";
import { useWorkoutContext } from "../hooks/useWorkoutsContext";
const Home = () => {
const { workouts, dispatch } = useWorkoutContext();
useEffect(() => {
const fetchWorkout = async () => {
const response = await fetch("/api/workouts");
const json = await response.json();
if (response.ok) dispatch({ type: "SET_WORKOUTS", payload: json });
};
fetchWorkout();
}, [dispatch]);
return (
<div className="home">
<div className="workouts">
{workouts &&
workouts?.map((workout) => (
<WorkoutDetailComponent workout={workout} key={workout._id} />
))}
</div>
<WorkoutForm />
</div>
);
};
export default Home; |
# Build a stock portfolio management system
#
# Example:
# | stock | shares | share price | total |
# | IBM | 100 | 90 USD | 9000 USD |
# | BMW | 10 | 75 EUR | 750 EUR |
#
# Initial test cases:
#
# [*] 5 USD x 2 == 10 USD
# [ ] 5 EUR x 2 == 10 EUR
# [ ] 5 SGD / 2 = 2.5 SGD
# [ ] 5 USD + 2 USD == 7 USD
# [ ] 5 EUR - 2 EUR == 3 EUR
# [ ] 5 USD + 10 EUR = 16 USD (EUR/USD = 1.1)
import unittest
from money import Money, InvalidCurrency
class TestMoney(unittest.TestCase):
def test_invalid_currency(self):
with self.assertRaises(InvalidCurrency):
money = Money(1, "FOO")
def testMultiply(self):
fiveUSD = Money(5, "USD")
expected = Money(10, "USD")
self.assertEqual(expected, fiveUSD.times(2))
if __name__ == '__main__':
unittest.main() |
import { Expect, Equal } from "@type-challenges/utils";
type arr1 = ["a", "b", "c"];
type arr2 = [3, 2, 1];
type arr3 = [];
type head1 = First<arr1>; // expected to be 'a'
type head2 = First<arr2>; // expected to be 3
type head3 = First<arr3>; // expected to be never
type First<T> = T extends [infer P, ...infer Rest] ? P : never;
type test1 = Expect<Equal<head1, "a">>;
type test2 = Expect<Equal<head2, 3>>;
type test3 = Expect<Equal<head3, never>>; |
# Title One Example
## Title Two Example
### Title Three Example
Command | Syntax | Description
--|--|--
Vanilla Photo Mode | No |
Hotsampling | Yes |
DSR | Yes |
Custom Aspect Ratios | No |
Reshade | Yes (No depth buffer) |
Ansel | No |
DirectX versions | DirectX 11 | testing!
<div class="figure">
<iframe width="854 " height="480" src="https://www.youtube.com/embed/lpUcGNLmdig" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
How to install and use the Universal Unity Freecam
=========
## Link to a video with an image
<p align="center">
<a href="https://youtu.be/I6igj-u1qlk/" target="_blank">
<img src="https://img.youtube.com/vi/I6igj-u1qlk/hqdefault.jpg">
</a>
</p>
*This is a subtitle, [this article](https://learn.unity.com/tutorial/memory-management-in-unity#5c7f8528edbc2a002053b59b) covers the difference between the two types. Basically a difference in scripting.*
* Launch the game and use the Task Manager to check if your game is 32-bit or 64-bit (if it is 32-bit it will have "32 bit" next to the program name).
{.shadowed .autosize}
* Close the game. If it's 32-bit, copy the content from BepInEx_x86.zip into the game's installation folder (specifically in the same folder as the games .exe), or the content from BepInEx_x64.zip if it's 64-bit.
* Start the game again.
* Close the game and look inside the `BepInEx` folder. You should see that new folders were created.
* Open `LogOutput.log` and check for a line that gives you the Unity version of the game, like
`[Info : BepInEx] Running under Unity v2019.1.10.15730669`
* Note down the version, then open the config folder and edit the `BepInEx.cfg` file.
* In the `[Preloader.Entrypoint]` section change `Type` to what their corresponding Unity version pints out in the table below:
* Install the plugins you want by copying them into the `BepInEx\plugins` folder.
- **vtrvrxiv.freecamplugin.dll**
- The freecam compatibility section is very important. Many games require fiddling with the mouse hacksection for these inputs to be detected.
- There is a special section that defines hotkeys for moving the on screen camera menu with the arrow keys. This is a last resort for games that completely prevent mouse movement. You would need to use the arrow keys to move the feature you want to toggle to the center of the screen and then mouse click on it.
- **vtrvrxiv.CursorMode.dll / vtrvrxiv.CursorMode_obsolete.dll**
- Provides options for making the mouse cursor visible and unlocking it. Some games lock the cursor to the center of the screen which prevents it from interacting with the camera menu.
- The plugin is not recommended for general use and should only be used if you experience the issue mentioned above.
- **vtrvrxiv.TimeScaleController.dll**
- Can slow down or speed up game time.
- Depending on the game can cause extreme frame rate issues.
## This is a link of useful links
- [BepInEx Documentation](https://docs.bepinex.dev/master/articles/user_guide/installation/index.html) - Extensive installation, configuration and troubleshooting site
- [MelonLoader Documentation](https://melonwiki.xyz/#/README) - Info about installation, configuration and more
## Mono Default Camera Controls
Keybind | Description
-- | --
`Backspace` |Open / Close the camera menu
`Z` | Rest camera to default (hold when clicking on camera)
`i` | Move camera forward
`k` | Move camera backward
`j` | Move camera left
`l` | Move camera right
`o` | Move camera up
`u` | Move camera down
`NumPad 8` | Rotate camera forward
`NumPad 2` | Rotate camera backward
`NumPad 4` | Rotate camera left
`NumPad 6` | Rotate camera right
`NumPad 9` | Rotate camera up
`NumPad 7` | Rotate camera down
`Left Control` | Slow down the camera movement
`Left Shift` | Speed up the camera movement
@tabs
@tab First Tab
This is the text for the first tab. It's nothing special
@alert tip
This is a tip! It will be displayed in a tip alert box!
@end
@alert important
This is an important text, it will be displayed in a warning/important alert box!
@end
@alert info
This is an info text, it will be displayed in an info alert box!
@end
@alert warning
This is a warning text, it will be displayed in a warning alert box!
@end
@alert danger
This is a dangerous text, it will be displayed in a danger alert box!
@end
As you can see, it can deal with newlines as well.
@end
@tab Second Tab
Now, the second tab however is very interesting. At least let's pretend it is!
@end
@endtabs |
import { Component, Input, OnInit } from '@angular/core';
import { CiteI } from '../../models/Cite';
import { Cites } from '../../services/Cites';
import { Title } from '@angular/platform-browser';
import { Device } from '../../tools/Device';
import { BasePaginatedComponent } from '../common/BasePaginatedComponent';
import { PagerComponent } from '../pager/pager.component';
import { NgIf, NgPlural, NgPluralCase, NgFor } from '@angular/common';
import { BehaviorSubject, filter, switchMap } from 'rxjs';
@Component({
selector: 'app-list-cites-by-authors',
template: `
<div class="container mb-36">
<h1
*ngIf="author"
[ngPlural]="cites.length"
class="text-3xl font-bold text-stone-900 mb-2"
>
<ng-template ngPluralCase="=0"
>Aucune citation de "{{ author }}" </ng-template
>
<ng-template ngPluralCase="=1"
>{{ cites.length }} citation de "{{ author }}": </ng-template
>
<ng-template ngPluralCase="other"
>{{ cites.length }} citations de "{{ author }}": </ng-template
>
</h1>
<ul class="list-none">
<li
*ngFor="let item of paginatedCites; trackBy: trackByCiteId"
class="p-1"
>
<cite>”{{ item.getCite() }}”</cite>
</li>
</ul>
</div>
<div class="container">
<div class="w-full">
<section
class="block fixed inset-x-0 bottom-10 z-10 bg-white"
id="bottom-navigation"
>
<app-pager
[list]="cites"
[options]="{ itemPerPage: getItemsPerPage() }"
(paginatedList$)="setPaginatedList($event)"
></app-pager>
</section>
</div>
</div>
`,
styles: [],
providers: [Device],
standalone: true,
imports: [NgIf, NgPlural, NgPluralCase, NgFor, PagerComponent],
})
export class ListCitesByAuthorsComponent
extends BasePaginatedComponent
implements OnInit
{
@Input({ required: true }) author: string;
cites: CiteI[] = [];
paginatedCites: CiteI[] = [];
constructor(
public citeService: Cites,
protected title: Title,
protected device: Device
) {
super();
this.title.setTitle('Citations - Liste des citations');
this.itemsPerPage = 10;
if (device.isMobile()) {
this.itemsPerPage = 4;
}
}
ngOnInit(): void {
this.citeService
.searchByAuthor(this.author)
.subscribe((cites) => this.fillCites(cites));
}
protected fillCites(citesList: CiteI[]): void {
this.cites = [];
this.paginatedCites = [];
citesList.forEach((cite, index) => {
this.cites.push(cite);
});
this.paginatedCites = this.cites.slice(0, this.itemsPerPage);
}
protected trackByCiteId(index, cite: CiteI): number {
return cite.getId();
}
setPaginatedList(ev: CiteI[]): void {
this.paginatedCites = ev;
}
} |
import {TasksType} from "../App";
import {v1} from "uuid";
import {AddTodolistACType, RemoveTodoListACType} from "./todolisrs-reducer";
type TasksReducerType = RemoveTaskACType
| AddTaskACType
| ChangeTaskStatusACType
| ChangeTaskTitleACType
| AddTodolistACType
| RemoveTodoListACType
export const tasksReducer = (state: TasksType, action: TasksReducerType): TasksType => {
switch (action.type) {
case 'REMOVE-TASK': {
return {
...state,
[action.payload.todolistId]:
state[action.payload.todolistId]
.filter(el => el.id !== action.payload.id)
}
}
case "ADD-TASK": {
return {
...state,
[action.payload.todolistId]:
[
{id: v1(), title: action.payload.newTaskTitle, isDone: false},
...state[action.payload.todolistId]
]
}
}
case "CHANGE-TASK": {
return {
...state,
[action.payload.todolistId]:
state[action.payload.todolistId].map(el => el.id === action.payload.id
? {...el, isDone: action.payload.isDone}
: el)
}
}
case "CHANGE-TITLE": {
return {
...state,
[action.payload.todolistId]:
state[action.payload.todolistId].map(el => el.id === action.payload.id
? {...el, title: action.payload.newTitle}
: el)
}
}
case 'ADD-TODOLIST': {
return {
...state,
[action.payload.todolistId]: []
}
}
case "REMOVE-TODOLIST": {
const {[action.payload.todolistId]: [], ...rest} = state
return rest
}
default:
return state
}
}
export type RemoveTaskACType = ReturnType<typeof removeTaskAC>
export const removeTaskAC = (todolistId: string, id: string) => {
return {
type: 'REMOVE-TASK',
payload: {
todolistId,
id
}
} as const
}
export type AddTaskACType = ReturnType<typeof addTaskAC>
export const addTaskAC = (todolistId: string, newTaskTitle: string) => {
return {
type: 'ADD-TASK',
payload: {
todolistId,
newTaskTitle
}
} as const
}
export type ChangeTaskStatusACType = ReturnType<typeof changeTaskStatusAC>
export const changeTaskStatusAC = (todolistId: string, id: string, isDone: boolean) => {
return {
type: 'CHANGE-TASK',
payload: {
todolistId,
id,
isDone
}
} as const
}
export type ChangeTaskTitleACType = ReturnType<typeof changeTaskTitleAC>
export const changeTaskTitleAC = (todolistId: string, id: string, newTitle: string) => {
return {
type: 'CHANGE-TITLE',
payload: {
todolistId,
id,
newTitle
}
} as const
} |
#include "main.h"
#include <stdio.h>
#include <stdlib.h>
/**
* _calloc - function that allocates memory for an array using malloc
* @nmemb: elements
* @size: size
* Return: returns pointer or NULL
*/
void *_calloc(unsigned int nmemb, unsigned int size)
{
unsigned int i;
unsigned int prod;
char *ptr;
if (nmemb == 0 || size == 0)
return (NULL);
prod = size * nmemb;
ptr = malloc(prod);
if (ptr == NULL)
return (NULL);
i = 0;
while (i < prod)
{
ptr[i] = 0;
i++;
}
return (ptr);
} |
import React, { Component } from 'react';
import TaskEditor from './TaskEditor';
import TaskList from './TaskList';
// import createTask from '../../utils/create-task';
import Filter from './Filter';
import { v4 as uuidv4 } from 'uuid';
export default class Tasks extends Component {
state = {
tasks: [],
filter: '',
};
componentDidMount() {
// console.log('componentDidMount...');
// let tasks = localStorage.getItem('tasks');
// console.log(tasks);
// if (tasks) {
// this.setState({
// tasks: JSON.parse(tasks),
// });
// }
}
componentDidUpdate(prevProps, prevState) {
// console.log('prevProps', prevProps);
// console.log(this.props);
// console.log('prevState', prevState);
// console.log(this.state);
if (prevState.tasks !== this.setState.tasks) {
console.log('Save to ls...');
localStorage.setItem('tasks', JSON.stringify(this.state.tasks));
}
}
addTask = text => {
const task = {
id: uuidv4(),
text,
completed: false,
};
this.setState((prevState, props) => {
return {
tasks: [...prevState.tasks, task],
};
});
};
removeTask = taskId => {
this.setState((prevState, props) => ({
tasks: prevState.tasks.filter(({ id }) => id !== taskId),
}));
};
updateCompleted = taskId => {
this.setState(prevState => {
return {
tasks: prevState.tasks.map(task => {
if (task.id === taskId) {
return {
...task,
completed: !task.completed,
};
}
return task;
}),
};
});
};
changeFilter = filter => {
this.setState({ filter });
};
getVisibleTasks = () => {
let { tasks, filter } = this.state;
return tasks.filter(task => task.text.includes(filter));
};
render() {
let { tasks, filter } = this.state;
let visibleTasks = this.getVisibleTasks();
let fullname = this.state.firstName + ' ' + this.state.lastName;
return (
<>
<h1>{fullname}</h1>
<TaskEditor onAddTask={this.addTask} />
{visibleTasks.length > 0 && (
<Filter value={filter} onchangeFilter={this.changeFilter} />
)}
{tasks.length > 0 && (
<TaskList
// tasks={tasks}
tasks={visibleTasks}
onRemoveTask={this.removeTask}
onUpdateTask={this.updateCompleted}
/>
)}
</>
);
}
} |
# RiverTrack: Streamlining River Flow Rate Monitoring
This site, targeted towards fishing enthusiasts, will showcase real-time data correlating to rivers in the US. Data will come from the Water Web Services Tool provided by the United States Geological Survey (USGS). Users will be able to save rivers to a collection for easy monitoring. Given the app’s focus on anglers, implemented validation will indicate whether or not a river’s flow conditions are optimal for fishing at any given moment.
While exploring potential topics for this project, I was reminded of previous work I had done for a water users association here in Utah. There are a few realistic applications for river data, but my inspiration for this project was my Dad’s love of flyfishing. When I mentioned that I was thinking about incorporating a river data API into my project, he practically begged me to make a “fishing buddy” app for flyfishing fanatics like him to monitor the flow of their favorite rivers.
I want to build two pages for this project: a Home page introducing the user to the site, and an Exploration page showing a list of rivers for users to select as favorites.
---
## Nov 17
- [x] Set up the initial HTML pages (Home, Explore Rivers, User Favorites)
- [x] Establish links (anchor tags) for citing USGS.
- [x] Figures/images on the home page for visual appeal.
- [x] Plan CSS styling and mockup elements (this includes color scheme, margin/padding, and border radius)
- [x] Set up basic page layout with nav, footer, etc.
- [x] Incorporate asides for helpful tips.
- [x] **HTML form**. A place for users to submit a request for a river to monitor. Will include text, number, select, reset, and submit inputs.
- [x] **Search bar** in the exploration page(text input for filtering)
- [x] **Search results table.** Table will show river name, general location, and average flow rate. (Use nth child styling for variation among rows, and hover effects--including transitions--to change row color & show focus).
- [x] **API Call**. Call from USGS API and access the data (async await/promises).
---
## Nov 24
- [x] **Populate the starting table.**
- [x] **Stylize table.** Use nth child and hover.
- [x] **Filter functions and event listeners.** Using data from the API, set up filter functions and event listeners to populate the table (access DOM elements, add/remove event listeners).
- [x] **Structure/Organization**. Establish files in appropriate folders (ui, domain, svc)
- [x] **Read querystring.** (Based on a given streamflow range).
---
## Dec 1
- [x] Let users specify collection to view (home page).
- [x] **Local Storage**. Use local storage to save the names of collections that user has made.
- [x] **Drag/Drop**. User should be able to drag/drop rivers from the table into their favorites list in the side bar.
- [x] **Infrastructure.** Create a C# minimal API to store/retrieve users' saved collections.
---
## Dec 8
- [ ] Fill in the "About This Service" paragraphs.
- [ ] Add ol and dl.
- [x] Style form elements and other inputs.
- [x] Finish validation (replace alerts with messages on the DOM).
- [x] Finish up infrastructure requirements.
- [ ] Revisit difficult topics/bugs.
---
## Dec 13 - Final Presentation |
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" xmlns:spring="http://www.springframework.org/tags">
<head>
<title>Infra Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<!-- para que sea responsive desde el celu-->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script type="text/javascript" th:src="@{/webjars//jquery/3.4.1/jquery.min.js}"></script>
<script type="text/javascript" th:src="@{/webjars/popper.js/1.14.3/umd/popper.min.js}"></script>
<script type="text/javascript" th:src="@{/webjars/bootstrap/4.3.1/js/bootstrap.min.js}"></script>
<link rel="stylesheet" type="text/css" th:href="@{/webjars/font-awesome/5.8.1/css/all.min.css}"/>
<link rel="stylesheet" type="text/css" th:href="@{/webjars/bootstrap/4.3.1/css/bootstrap.min.css}"/>
<link rel="stylesheet" type="text/css"
th:href="@{/webjars/mdbootstrap-bootstrap-material-design/4.8.8/css/mdb.min.css}"/>
<link rel="stylesheet" type="text/css" th:href="@{/css/responsive.css}"/>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h5 class="card-header info-color white-text text-center py-4">
<strong th:text="'Servidor ' + ${serverName} + '!'"/>
</h5>
<div class="card-body text-center border border-light">
<div class="col">
<p th:text="'Hits: ' + ${hits}"/>
<p th:text="'HttpSession ID: ' + ${sessionId}"/>
<p th:text="'Session Type: ' + ${sessionType}"/>
</div>
<div class="col">
<hr/>
</div>
<div class="col">
<h5>Memory Info</h5>
<p th:text="'Free: ' + ${free}"/>
<p th:text="'Allocated: ' + ${allocated}"/>
<p th:text="'Max: ' + ${max}"/>
<p th:text="'Total free: ' + ${total}"/>
</div>
<div class="col">
<a href="/"
class="btn btn-outline-info btn-rounded btn-block z-depth-0 my-4 waves-effect">
Hit
</a>
<a href="/leak"
class="btn btn-outline-info btn-rounded btn-block z-depth-0 my-4 waves-effect">
Leak
</a>
<a href="/stress"
class="btn btn-outline-info btn-rounded btn-block z-depth-0 my-4 waves-effect">
Stress
</a>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript" th:src="@{/webjars/mdbootstrap-bootstrap-material-design/4.8.8/js/mdb.min.js}"></script>
</html> |
/* ******************************************** */
/* */
/* \\ /`/`` */
/* ~\o o_ 0 0\ */
/* / \__) (u ); _ _ */
/* / \/ \/ / \ \/ \/ \ */
/* /( . . ) ( )\ */
/* / \_____/ \_______/ \ */
/* [] [] [[] [[] *. */
/* []] []] [[] [[] */
/* */
/* ************************************ nuo *** */
#include "iostream"
#include "sstream"
#define S printf("--\n")
template<typename T>
void PS(const T& t) // put string
{
std::cout << t << '\n';
}
template<typename T>
std::string PSS(const T& t) // same operation using sstream
{
std::stringstream ss;
ss << t;
return ss.str() ;
}
int main()
{
S;
PS("Hello, World!");
PS(1024);
PS(3.14159);
S;
std::cout << PSS("Hello, World!")<<'\n';
std::cout << PSS(512) << '\n';
std::cout << PSS(3.14) << '\n';
S;
} |
+++
title = "How to document and blog on github pages"
description = "How to setup your own documentation hub"
date = 2024-02-23T00:00:00+06:00
updated = 2024-02-23T00:00:00+06:00
draft = false
template = "blog/page.html"
[extra]
lead = "This is a meta post about how to document"
+++
# Taking note
Rocking it like the 90s, static web sites are easier to host and maintain.
[Github](https://pages.github.com/) provides free hosting, stepping in for geocities.
I tend to take notes in [markdown](https://www.markdownguide.org/basic-syntax/), even if I'm just using notepad. It's pretty intuitive syntax.
For simplicity I chose [Zola](https://www.getzola.org/) for the static website generator. It is a single executable with no dependencies, and has github actions supported. The project isn't a snob about supporting Windows.
# Github hosting
## Create repo on github
[Follow the guide](https://pages.github.com/).
Additionally I created an orphaned branch that the gh-pages will be published too.
```
git checkout --orphan gh-pages
git reset --hard
git commit --allow-empty -m "init gh-pages branch"
git push origin gh-pages
git checkout main
```
```Command line```
# Zola
## Windows Installation
I just [downloaded the release zip](https://github.com/getzola/zola/releases), and then added the folder I extracted to the path so I could use the command from any terminal window.
## Adidok theme
I installed this via a submodule. Assuming your main repo has a "docs" sub directory where you are keeping your markdown, from the root of the repo run something like this to install
```
git submodule add https://github.com/aaranxu/adidoks.git docs/themes/adidoks
```
### Customize Adidok
This required a little more reading of the manual. Anything in the template can be overidden if the same content is found in your own content folder. This includes the html templates. To remove the hero list on the index page required changes to the index.html template.
## Build and test website
To build, make sure you are in the docs directory. Then run the zola command: ```zola build```
To test on the local machine only (and you can make live content changes here too) run ```zola serve```
## Zola github action
[Zola github pages documentation](https://www.getzola.org/documentation/deployment/github-pages/)
You may look in the ```.github/workflows``` directory to see the docs.yml Zola publishing workflow based on those instructions.
## Content creation
Create [markdown](https://www.markdownguide.org/basic-syntax/) files in the ```docs``` sub-directory to be included in that section of the website, and the ```blog``` sub-directory for the blog section. Pay attention to the "front matter" in the markdown docs.
For content creation getting the markdown right is probably the biggest hassle over just taking notes normally with Markdown.
Zola adds "[shotcodes](https://www.getzola.org/documentation/content/shortcodes/)" to its flavor of markdown. |
package fa.training.fjb04.ims.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum Department {
IT(0, "IT"),
HR(1, "HR"),
FINANCE(2, "Finance"),
COMMUNICATION(3, "Communication"),
MARKETING(4, "Marketing"),
ACCOUNTING(5, "Accounting");
private final int code;
private final String name;
public static Department fromCode(Integer code) {
for (Department department : Department.values()) {
if (department.code == code) {
return department;
}
}
throw new IllegalArgumentException("No constant with name " + code + " found in department enum");
}
public static Department fromValue(String value) {
for (Department department : Department.values()) {
if (department.name.equals(value)) {
return department;
}
}
throw new IllegalArgumentException("No constant with value " + value + " found in department enum");
}
} |
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../../../../environments/environment';
import { map, catchError, tap } from 'rxjs/operators';
import { RespData } from '../../../interfaces/shared/ws-data';
import { UiMessagingService } from '../../../../@core/backend/services/shared/ui-messaging.service';
import { Constants } from '../../../../@shared/utils/constants';
import { Logger } from '../../../../@shared/utils/logger';
import { ApiError } from './api-error';
@Injectable()
export class BaseApi {
constructor(
private http: HttpClient,
private uiMessagingService: UiMessagingService
) {}
get apiUrl(): string {
return environment.apiUrl;
}
get apiUrlMock(): string {
return environment.apiUrlMock;
}
// checks for specific API errors, logs and throws OWN to prevent 'next' calls in .subscribe(...)
checkApiError(apiResponse: RespData): any {
if (apiResponse && apiResponse.status && apiResponse.status.err) {
if (apiResponse.status.code === Constants.API_STATUS_ERROR) {
this.uiMessagingService.addErrorStatus(apiResponse.status.err);
this.uiMessagingService.showError(apiResponse.status.err); // TODO: Why explicit show needed?
throw new ApiError(apiResponse.status.err);
} else if (apiResponse.status.code === Constants.API_STATUS_WARN) {
this.uiMessagingService.addWarningStatus(
apiResponse.status.msg
);
this.uiMessagingService.showWarn(apiResponse.status.msg);
} else {
this.uiMessagingService.addSuccessStatus(
apiResponse.status.msg
);
//this.uiMessagingService.showSuccess(apiResponse.status.msg);
}
}
}
// returns actual data from api response
mapApiResponse(apiResponse: RespData): any {
if (!apiResponse.status && !apiResponse.data) {
// TODO: Did not meet the standard format
return apiResponse;
} else {
return apiResponse.data;
}
}
mapArchiveApiResponse(apiResponse: RespData): boolean {
if (apiResponse.status && !apiResponse.status.err) {
// TODO: No error returned
return true;
} else {
return false;
}
}
mapApiError(err: HttpErrorResponse): any {
this.uiMessagingService.addErrorStatus(err.message);
this.uiMessagingService.showError(err.message);
return {};
}
// one place ot describe how we handle API errors
private handleApiError = catchError((err: any) => {
this.mapApiError(err);
Logger.fatal(err);
throw new ApiError('Server Side Issue. Please contact support');
});
get(endpoint: string): Observable<any> {
let apiurl: any;
if (
endpoint.startsWith('admin') ||
endpoint.startsWith('selfcare') ||
endpoint.startsWith('appointment') ||
endpoint.startsWith('class') ||
endpoint.startsWith('site') ||
endpoint.startsWith('service') ||
endpoint.startsWith('summary') ||
endpoint.startsWith('dashboard/') ||
endpoint.startsWith('client') ||
endpoint.startsWith('staff') ||
endpoint.startsWith('appts') ||
endpoint.startsWith('form')
) {
apiurl = this.apiUrl;
} else {
apiurl = this.apiUrlMock;
}
return this.http.get(`${apiurl}/${endpoint}`, {}).pipe(
this.handleApiError,
tap((result: any) => this.checkApiError(result)),
map((result: RespData) => this.mapApiResponse(result))
);
}
post(endpoint: string, data: any): Observable<any> {
return this.http.post(`${this.apiUrl}/${endpoint}`, data, {}).pipe(
this.handleApiError,
tap((result: any) => this.checkApiError(result)),
map((result: RespData) => this.mapApiResponse(result))
);
}
archive(endpoint: string): Observable<any> {
return this.http.delete(`${this.apiUrl}/${endpoint}`, {}).pipe(
this.handleApiError,
tap((result: any) => this.checkApiError(result)),
map((result: RespData) => this.mapArchiveApiResponse(result))
);
}
} |
from enum import Enum
from typing import Optional
from pydantic import BaseModel
# princing from https://openai.com/pricing (OCT 2023)
class GPT_Modules(str, Enum):
gpt_3_5_turbo = 'gpt-3.5-turbo' # $0.0015 / 1K tokens $0.002 / 1K tokens
gpt_3_5_turbo_16k = 'gpt-3.5-turbo-16k' # $0.003 / 1K tokens $0.004 / 1K tokens
gpt_4 = 'gpt-4' # $0.03 / 1K tokens $0.06 / 1K tokens
#gpt_4_32k = 'gpt-4-32k' # $0.06 / 1K tokens $0.12 / 1K tokens
gpt_4_1106_preview = 'gpt-4-1106-preview' # todo: (DC in 6 Nov 2023) latest models launched today
gpt_4_vision_preview = 'gpt-4-vision-preview' # todo: add pricing of these new models and update the prices for the older models
class GPT_History(BaseModel):
question : str
answer : str
DEFAULT_GPT_ENGINE = GPT_Modules.gpt_3_5_turbo
DEFAULT_USER_PROMPT = 'Hi'
DEFAULT_TEMPERATURE = 0.0
DEFAULT_SEED = 42
class GPT_Prompt_Simple(BaseModel):
model : GPT_Modules = DEFAULT_GPT_ENGINE
user_prompt : str = DEFAULT_USER_PROMPT
images : list[str] = []
temperature : float = DEFAULT_TEMPERATURE
seed : int = DEFAULT_SEED
max_tokens : Optional[int] = None
class GPT_Prompt_With_System(GPT_Prompt_Simple):
system_prompts: list[str]
class GPT_Prompt_With_System_And_History(GPT_Prompt_With_System):
histories : list[GPT_History]
class GPT_Answer(BaseModel):
model : Optional[str] = None
answer: str |
import { ThemeProvider } from 'styled-components';
import type { AppProps } from 'next/app';
import GlobalStyles from './global';
import { darkTheme, lightTheme } from '@config/themes/themes';
import { useTheme } from '@hooks/use-theme';
const MyApp = ({ Component, pageProps }: AppProps) => {
const [theme] = useTheme();
return (
<ThemeProvider theme={theme === 'dark' ? darkTheme : lightTheme}>
<GlobalStyles />
<Component {...pageProps} />
</ThemeProvider>
);
};
export default MyApp; |
# -*- coding: utf-8 -*-
##
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## CDS Indico 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 CDS Indico; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
import unittest
import shutil
import sys
from MaKaC.common.Configuration import Config
from MaKaC.consoleScripts.installBase import modifyOnDiskIndicoConfOption
class TestConfiguration(unittest.TestCase):
def testGetInstanceShouldWork(self):
self.config = Config.getInstance()
def testDynamicFindersShouldWork(self):
self.testGetInstanceShouldWork()
self.config.getHtdocsDir()
self.config.getVersion()
def testSmtpUseTLS(self):
self.testGetInstanceShouldWork()
modifyOnDiskIndicoConfOption('etc/indico.conf.local', 'SmtpUseTLS', 'no')
self.config.forceReload()
self.assertEquals(False, self.config.getSmtpUseTLS())
modifyOnDiskIndicoConfOption('etc/indico.conf.local', 'SmtpUseTLS', 'yes')
self.config.forceReload()
self.assertEquals(True, self.config.getSmtpUseTLS())
def testReloadShoulShowNewIndicoConfValuesIfConfMoved(self):
self.testGetInstanceShouldWork()
orig = file('indico/MaKaC/common/MaKaCConfig.py').read()
new = orig.replace('indico_conf = ""', 'indico_conf = "etc/indico2.conf"')
file('indico/MaKaC/common/MaKaCConfig.py', 'w').write(new)
try:
shutil.move('etc/indico.conf.local', 'etc/indico2.conf')
self.config.forceReload()
self.config.getHtdocsDir()
finally:
file('indico/MaKaC/common/MaKaCConfig.py', 'w').write(orig)
shutil.move('etc/indico2.conf', 'etc/indico.conf.local')
def testReloadShoulShowNewIndicoConfValuesIfConfChanged(self):
self.testGetInstanceShouldWork()
orig = file('etc/indico.conf.local').read()
file('etc/indico.conf.local', 'w').write(orig.replace('BaseURL = "http://localhost/"',
'BaseURL = "http://localhost2/"'))
try:
self.config.forceReload()
self.assertEqual('http://localhost2/', self.config.getBaseURL())
finally:
file('etc/indico.conf.local', 'w').write(orig.replace('BaseURL = "http://localhost2/"',
'BaseURL = "http://localhost/"')) |
from Classes.image import convert_img
from Classes.eventhandler import EventHandler
from Widgets.button import Button
from Widgets.titlebar import TitleBar
from pygame import display, event, quit, NOFRAME
from pygame.time import Clock
from pygame._sdl2.video import Window
from win32api import GetMonitorInfo, MonitorFromPoint
"""
Icons by:
icon by <a target="_blank" href="https://icons8.com">Icons8</a>
"""
def get_monitor_size():
monitor_info = GetMonitorInfo(MonitorFromPoint((0,0)))
work_area = monitor_info.get("Work")
return work_area[2], work_area[3]
class App:
def __init__(self,
size: tuple[int, int] = (700, 700),
fps: int = 60,
bg_img_path: str = r'Assets/Backgrounds/bg_9.jpg',
):
self.size = size
self.width, self.height = self.size
self.screen = display.set_mode(size, NOFRAME)
self.clock = Clock()
self.fps = fps
self.desktop_size = get_monitor_size()
self.window = Window.from_display_module()
self.widgets = []
self.update_list = []
self.bg_img_path = bg_img_path
self.bg_img = convert_img(self.bg_img_path, self.size)
self.bg_rect = self.screen.blit(self.bg_img, (0, 0))
self.add_buttons()
self.add_title_bar()
self.event_handler = EventHandler(self)
def add_buttons(self):
close_btn = Button(self, self.screen, width=50, height=40, x=50, y=0, anchor=2, command=quit, image_path=r'Assets\Buttons\close_btn_0.png')
win_btn = Button(self, self.screen, width=50, height=40, x=100, y=0, anchor=2, command=self.win_max_min, image_path=r'Assets\Buttons\maximize_btn_0.png')
min_btn = Button(self, self.screen, width=50, height=40, x=150, y=0, anchor=2, command=self.minimize, image_path=r'Assets\Buttons\minimize_btn_0.png')
def add_title_bar(self):
title_bar = TitleBar(
self, self.screen, width=lambda: self.width-150, height=lambda: 40, x=0, y=0, anchor=1, resizeable=True
)
def win_max_min(self, spawn=(200, 100)):
if not self.is_maximized():
self.size = self.desktop_size[0], self.desktop_size[1] - 1
self.window.position = 0, 0
self.screen = display.set_mode(self.size, NOFRAME)
else:
self.size = 700, 700
self.window.position = spawn
self.screen = display.set_mode(self.size, NOFRAME)
self.width, self.height = self.size
self.bg_img = convert_img(self.bg_img_path, self.size)
self.bg_rect = self.screen.blit(self.bg_img, (0, 0))
self.reindent()
def minimize(self):
display.iconify()
def restore(self):
display.flip()
def reindent(self):
for widget in self.widgets: widget.reindent()
display.flip()
def update(self):
display.update(self.update_list)
self.update_list.clear()
def is_maximized(self):
return not self.size[0] < self.desktop_size[0]
def run(self):
display.flip()
while 1:
self.clock.tick(self.fps)
self.event_handler.handle(event.get())
self.update() |
from enum import Enum
from pydantic import BaseModel
from typing import Optional, List
class Modality(Enum):
VIDEO = "video"
IMAGE = "image"
AUDIO = "audio"
TEXT = "text"
class ConfigsRequest(BaseModel):
modality: Optional[Modality] = "text"
model: Optional[str] = "sentence-transformers/all-MiniLM-L6-v2"
class ConfigsResponse(BaseModel):
dimensions: int
token_size: int
class EmbeddingRequest(BaseModel):
input: str
modality: Optional[Modality] = "text"
model: Optional[str] = "sentence-transformers/all-MiniLM-L6-v2"
class EmbeddingResponse(BaseModel):
embedding: List[float] |
<!--Copyright © XcodeHw 适用于[License](https://github.com/chenzomi12/AISystem)版权许可-->
# ESPNet 系列
本节将会介绍 ESPNet 系列,该网络主要应用在高分辨率图像下的语义分割,在计算内存占用、功耗方面都非常高效,重点介绍一种高效的空间金字塔卷积模块(ESP Module);而在 ESPNet V2 上则是会更进一步给大家呈现如何利用分组卷积核,深度空洞分离卷积学习巨大有效感受野,进一步降低浮点计算量和参数量。
## ESPNet V1 模型
**ESPNet V1**:应用在高分辨图像下的语义分割,在计算、内存占用、功耗方面都非常高效。主要贡献在于基于传统卷积模块,提出高效空间金子塔卷积模块(ESP Module),有助于减少模型运算量和内存、功率消耗,来提升终端设备适用性,方便部署到移动端。
### ESP 模块
基于卷积因子分解的原则,ESP(Efficient spatial pyramid)模块将标准卷积分解成 point-wise 卷积和空洞卷积金字塔(spatial pyramid of dilated convolutions)。point-wise 卷积将输入的特征映射到低维特征空间,即采用 K 个 1x1xM 的小卷积核对输入的特征进行卷积操作,1x1 卷积的作用其实就是为了降低维度,这样就可以减少参数。空洞卷积金字塔使用 K 组空洞卷积的同时下采样得到低维特征,这种分解方法能够大量减少 ESP 模块的参数和内存,并且保证了较大的感受野(如下图 a 所示)。

上图 (b) 展示了 ESP 模块采用的减少-分裂-转换-合并策略。下面来计算下一共包含的参数,其实在效果上,以这种轻量级的网络作为 backbone 效果肯定不如那些参数量大的网络模型,比如 Resnet,但是在运行速度上有很大优势。
如上图所示,对 ESP 模块的第一部分来说,$d$ 个 $1\times 1\times M$ 的卷积核,将 M 维的输入特征降至 d 维。此时参数为:$M*N/K$,第二部分参数量为 $K*n^{2}*(N/K)^{2}$,和标准卷积结构相比,参数数量降低很多。
为了减少计算量,又引入了一个简单的超参数 K,它的作用是统一收缩网络中各个 ESP 模块的特征映射维数。Reduce 对于给定 K,ESP 模块首先通过逐点卷积将特征映射从 m 维空间缩减到 $N/K$ 维空间(上图 a 中的步骤 1)。通过 Split 将低维特征映射拆分到 K 个并行分支上。
然后每个分支使用 $2^{k-1},k=1,...,k-1$ 给出的 $n\times n$ 个扩张速率不同的卷积核同时处理这些特征映射(上图 a 中的步骤 2)。最后将 K 个并行扩展卷积核的输出连接起来,产生一个 n 维输出特征图。
下面代码使用 PyTorch 来实现具体的 ESP 模块:
```python
class ESPModule(nn.Module):
def __init__(self, in_channels, out_channels, K=5, ks=3, stride=1,act_type='prelu',):
super(ESPModule, self).__init__()
self.K = K
self.stride = stride
self.use_skip = (in_channels == out_channels) and (stride == 1)
channel_kn = out_channels // K
channel_k1 = out_channels - (K -1) * channel_kn
self.perfect_divisor = channel_k1 == channel_kn
if self.perfect_divisor:
self.conv_kn = conv1x1(in_channels, channel_kn, stride)
else:
self.conv_kn = conv1x1(in_channels, channel_kn, stride)
self.conv_k1 = conv1x1(in_channels, channel_k1, stride)
self.layers = nn.ModuleList()
for k in range(1, K+1):
dt = 2**(k-1) # dilation
channel = channel_k1 if k == 1 else channel_kn
self.layers.append(ConvBNAct(channel, channel, ks, 1, dt, act_type=act_type))
def forward(self, x):
if self.use_skip:
residual = x
transform_feats = []
if self.perfect_divisor:
x = self.conv_kn(x) # Reduce
for i in range(self.K):
transform_feats.append(self.layers[i](x)) # Split --> Transform
for j in range(1, self.K):
transform_feats[j] += transform_feats[j-1] # Merge: Sum
else:
x1 = self.conv_k1(x) # Reduce
xn = self.conv_kn(x) # Reduce
transform_feats.append(self.layers[0](x1)) # Split --> Transform
for i in range(1, self.K):
transform_feats.append(self.layers[i](xn)) # Split --> Transform
for j in range(2, self.K):
transform_feats[j] += transform_feats[j-1] # Merge: Sum
x = torch.cat(transform_feats, dim=1) # Merge: Concat
if self.use_skip:
x += residual
return x
```
### HFF 特性
虽然将扩张卷积的输出拼接在一起会给 ESP 模块带来一个较大的有效感受野,但也会引入不必要的棋盘或网格假象,如下图所示。

上图(a)举例说明一个网格伪像,其中单个活动像素(红色)与膨胀率 r = 2 的 3×3 膨胀卷积核卷积。
上图(b)具有和不具有层次特征融合(Hierarchical feature fusion,HFF)的 ESP 模块特征图可视化。ESP 中的 HFF 消除了网格伪影。彩色观看效果最佳。
为了解决 ESP 中的网格问题,使用不同膨胀率的核获得的特征映射在拼接之前会进行层次化添加(上图 b 中的 HFF)。该解决方案简单有效,且不会增加 ESP 模块的复杂性,这与现有方法不同,现有方法通过使用膨胀率较小的卷积核学习更多参数来消除网格误差[Dilated residual networks,Understanding convolution for semantic segmentation]。为了改善网络内部的梯度流动,ESP 模块的输入和输出特征映射使用元素求和[Deep residual learning for image recognition]进行组合。
### 网络结构与实现
ESPNet 使用 ESP 模块学习卷积核以及下采样操作,除了第一层是标准的大步卷积。所有层(卷积和 ESP 模块)后面都有一个批归一化和一个 PReLU 非线性,除了最后一个点卷积,它既没有批归一化,也没有非线性。最后一层输入 softmax 进行像素级分类。
ESPNet 的不同变体如下图所示。第一个变体,ESPNet-A(图 a),是一种标准网络,它以 RGB 图像作为输入,并使用 ESP 模块学习不同空间层次的表示,以产生一个分割掩码。第二种 ESP - b(图 b)通过在之前的跨步 ESP 模块和之前的 ESP 模块之间共享特征映射,改善了 ESPNet-A 内部的信息流。第三种变体,ESPNet-C(图 c),加强了 ESPNet-B 内部的输入图像,以进一步改善信息的流动。这三种变量产生的输出的空间维度是输入图像的 1 / 8。第四种变体,ESPNet(图 d),在 ESPNet- c 中添加了一个轻量级解码器(使用 reduceupsample-merge 的原理构建),输出与输入图像相同空间分辨率的分割 mask。

从 ESPNet- a 到 ESPNet 的路径。红色和绿色色框分别代表负责下采样和上采样操作的模块。空间级别的 l 在(a)中的每个模块的左侧。本文将每个模块表示为(#输入通道,#输出通道)。这里,conv-n 表示 n × n 卷积。
为了在不改变网络拓扑结构的情况下构建具有较深计算效率的边缘设备网络,超参数α控制网络的深度;ESP 模块在空间层次 l 上重复 $α_{l}$ 次。在更高的空间层次(l = 0 和 l = 1),cnn 需要更多的内存,因为这些层次的特征图的空间维数较高。为了节省内存,ESP 和卷积模块都不会在这些空间级别上重复。
## ESPNet V2 模型
**ESPNet V2**:是由 ESPNet V1 改进来的,一种轻量级、能耗高效、通用的卷积神经网络,利用分组卷积核深度空洞分离卷积学习巨大有效感受野,进一步降低浮点计算量和参数量。同时在图像分类、目标检测、语义分割等任务上检验了模型效果。
ESPNet V2 与 V1 版本相比,其特点如下:
1. 将原来 ESPNet 的 point-wise convolutions 替换为 group point-wise convolutions;
2. 将原来 ESPNet 的 dilated convolutions 替换为 depth-wise dilated convolution;
3. HFF 加在 depth-wise dilated separable convolutions 和 point-wise (or 1 × 1)卷积之间,去除 gridding artifacts;
4. 使用 group point-wise convolution 替换 K 个 point-wise convolutions;
5. 加入平均池化(average pooling ),将输入图片信息加入 EESP 中;
6. 使用级联(concatenation)取代对应元素加法操作(element-wise addition operation )
### DDConv 模块
深度分离空洞卷积(Depth-wise dilated separable convolution,DDConv)分两步:
- 对每个输入通道执行空洞率为 r 的 DDConv,从有效感受野学习代表性特征。
- 标准 1x1 卷积学习 DDConv 输出的线性组合特征。
深度分离空洞卷积与其他卷积的参数量与感受野对比如下表所示。
| Convolution type | Parameters | Eff.receptive field |
| ---- | - | ---- |
| Standard |$n^{2}c\hat{c}$|$n\times n$ |
| Group |$\frac{n^{2}c\hat{c}}{g}$|$n\times n$|
| Depth-wise separable |$n^{2}c+c\hat{c}$|$n\times n$|
| Depth-wise dilated separable |$n^{2}c+c\hat{c}$|$n_{r}\times n_{r}$|
### EESP 模块
EESP 模块结构如下图,图 b 中相比于 ESPNet,输入层采用分组卷积,DDConv+Conv1x1 取代标准空洞卷积,依然采用 HFF 的融合方式,(c)是(b)的等价模式。当输入通道数 M=240,g=K=4, d=M/K=60,EESP 比 ESP 少 7 倍的参数。

描述了一个新的网络模块 EESP,它利用深度可分离扩张和组逐点卷积设计,专为边缘设备而设计。该模块受 ESPNet 架构的启发,基于 ESP 模块构建,使用了减少-分割-变换-合并的策略。通过组逐点和深度可分离扩张卷积,该模块的计算复杂度得到了显著的降低。进一步,描述了一种带有捷径连接到输入图像的分层 EESP 模块,以更有效地学习多尺度的表示。
如上图中 b 所示,能够降低 $\frac{Md+n^{2}d^{2}K}{\frac{Md}{g}+(n^{2}+d)dK}$ 倍计算复杂度,K 为空洞卷积金字塔层数。考虑到单独计算 K 个 point-wise 卷积等同于单个分组数为 K 的 point-wise 分组卷积,而分组卷积的在实现上更高效,于是改进为上图 c 的最终结构。
```python
class EESP(nn.Module):
'''
按照 REDUCE ---> SPLIT ---> TRANSFORM --> MERGE
'''
def __init__(self, nIn, nOut, stride=1, k=4, r_lim=7, down_method='esp'):
super().__init__()
self.stride = stride
n = int(nOut / k)
n1 = nOut - (k - 1) * n
assert down_method in ['avg', 'esp']
assert n == n1, "n(={}) and n1(={}) should be equal for Depth-wise Convolution ".format(n, n1)
self.proj_1x1 = CBR(nIn, n, 1, stride=1, groups=k)
#3x3 核的膨胀率和感受野之间的映射
map_receptive_ksize = {3: 1, 5: 2, 7: 3, 9: 4, 11: 5, 13: 6, 15: 7, 17: 8}
self.k_sizes = list()
for i in range(k):
ksize = int(3 + 2 * i)
# 达到感受野极限后,回落到 3x3,膨胀率为 1 的基础卷积
ksize = ksize if ksize <= r_lim else 3
self.k_sizes.append(ksize)
#根据感受野对这些核大小进行排序(升序)
#这使我们能够忽略分层中具有相同有效感受野的核(在我们的例子中为 3×3)
# 特征融合,因为 3x3 感受野的核不具有网格伪影。
self.k_sizes.sort()
self.spp_dw = nn.ModuleList()
for i in range(k):
d_rate = map_receptive_ksize[self.k_sizes[i]]
self.spp_dw.append(CDilated(n, n, kSize=3, stride=stride, groups=n, d=d_rate))
self.conv_1x1_exp = CB(nOut, nOut, 1, 1, groups=k)
self.br_after_cat = BR(nOut)
self.module_act = nn.PReLU(nOut)
self.downAvg = True if down_method == 'avg' else False
def forward(self, input):
# Reduce --> 将高维特征映射投影到低维空间
output1 = self.proj_1x1(input)
output = [self.spp_dw[0](output1)]
# 计算每个分支的输出并分层融合它们
# i.e. Split --> Transform --> HFF
for k in range(1, len(self.spp_dw)):
out_k = self.spp_dw[k](output1)
# HFF
#我们不组合具有相同感受野的分支(在我们的例子中是 3x3)
out_k = out_k + output[k - 1]
#融合后应用批量定额,然后添加到列表中
output.append(out_k)
# Merge
expanded = self.conv_1x1_exp(
self.br_after_cat(
torch.cat(output, 1)
)
)
del output
# 如果下采样,则返回连接的向量
# 因为下采样功能会将其与 avg 合并。合并特征图,然后对其进行阈值处理
if self.stride == 2 and self.downAvg:
return expanded
# 如果输入向量和连接向量的维数相同,则将它们相加 (RESIDUAL LINK)
if expanded.size() == input.size():
expanded = expanded + input
# 使用激活函数对特征图进行阈值处理 (PReLU in this case)
return self.module_act(expanded)
```
### Strided EESP 模块
为了在多尺度下能够有效地学习特征,对上图 1c 的网络做了四点改动(如下图所示):
1.对 DDConv 添加 stride 属性。
2.右边的 shortcut 中带了平均池化操作,实现维度匹配。
3.将相加的特征融合方式替换为 concat 形式,增加特征的维度。
4.融合原始输入图像的下采样信息,使得特征信息更加丰富。具体做法是先将图像下采样到与特征图的尺寸相同的尺寸,然后使用第一个卷积,一个标准的 3×3 卷积,用于学习空间表示。再使用第二个卷积,一个逐点卷积,用于学习输入之间的线性组合,并将其投影到高维空间。

```python
class DownSampler(nn.Module):
'''
具有两个并行分支的下采样功能:平均池和步长为 2 的 EESP 块。然后,使用激活函数将这些分支的输出特征图连接起来并进行阈值处理,以产生最终输出。
'''
def __init__(self, nin, nout, k=4, r_lim=9, reinf=True):
super().__init__()
nout_new = nout - nin
self.eesp = EESP(nin, nout_new, stride=2, k=k, r_lim=r_lim, down_method='avg')
self.avg = nn.AvgPool2d(kernel_size=3, padding=1, stride=2)
if reinf:
self.inp_reinf = nn.Sequential(
CBR(config_inp_reinf, config_inp_reinf, 3, 1),
CB(config_inp_reinf, nout, 1, 1)
)
self.act = nn.PReLU(nout)
def forward(self, input, input2=None):
avg_out = self.avg(input)
eesp_out = self.eesp(input)
output = torch.cat([avg_out, eesp_out], 1)
if input2 is not None:
w1 = avg_out.size(2)
while True:
input2 = F.avg_pool2d(input2, kernel_size=3, padding=1, stride=2)
w2 = input2.size(2)
if w2 == w1:
break
output = output + self.inp_reinf(input2)
return self.act(output)
```
## 小结与思考
- ESPNet V1 模型专注于高分辨率图像的语义分割任务,通过引入高效的空间金字塔卷积模块(ESP Module),显著降低了模型的运算量和内存功耗,提升了在终端设备上的适用性。
- ESP Module 利用逐点卷积和空洞卷积金字塔减少参数量和内存消耗,同时通过层次化特征融合(HFF)解决卷积输出的棋盘格效应,保持了较大的感受野和有效的特征学习。
- ESPNet V2 在 V1 的基础上进一步优化,采用分组卷积和深度分离卷积学习更大的有效感受野,减少浮点计算量和参数量,同时通过级联和平均池化融合多尺度特征,提升了模型在不同视觉任务上的性能和通用性。
## 本节视频
<iframe src="https://player.bilibili.com/player.html?bvid=BV1DK411k7qt&as_wide=1&high_quality=1&danmaku=0&t=30&autoplay=0" width="100%" height="500" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe> |
import { SeeBoardsRequest } from './SeeBoardsRequest';
import { SeeBoardsPresenter } from './SeeBoardsPresenter';
import { SeeBoardsResponse } from './SeeBoardsResponse';
import { FieldErrors } from '../../lib/types';
import Validator from 'validatorjs';
import { Member, MemberRepository } from '../../entities/Member';
import { Board, BoardRepository } from '../../entities/Board';
Validator.useLang('fr');
export class SeeBoardsUseCase {
constructor(
private memberRepository: MemberRepository,
private boardRepository: BoardRepository
) {}
async execute(
request: SeeBoardsRequest,
presenter: SeeBoardsPresenter
): Promise<void> {
let errors: FieldErrors = null;
let boards: Board[] | null = null;
let member: Member | null | undefined;
if (request.memberId) {
member = await this.memberRepository.getMemberById(
request.memberId
);
}
if (null === member) {
errors = {
memberId: ["Il n'existe aucun utilisateur ayant cet Id"]
};
} else {
boards = member
? await this.boardRepository.getAllBoardsWhereMemberIsPresentOrWherePublic(
member.id
)
: await this.boardRepository.getAllPublicBoards();
}
presenter.present(new SeeBoardsResponse(boards, errors));
}
} |
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1> Funções </h1>
<script>
// declaracao de funcao
function ola() {
document.write("Olá mundo")
}
ola()
//expressao de funcao
const ola2 = function () {
document.write("Olá mundo de function expression")
}
ola2()
//arrow functions
const ola3 = () => {
console.log("Olá mundo de arrow funcions")
}
ola3()
//retorno de valores
function obtainDiaSemana() {
return new Date().getDay()
}
let dia = obtainDiaSemana()
console.log(dia)
function somar(n1 = 0, n2 = 0 ) {
//let _n1 = n1 || 0
//let _n2 = n2 || 0
return n1 + n2
}
let soma = somar(3, 5)
console.log(soma)
console.log(somar())
</script>
</body>
</html> |
## ---------------------------------------------------------------------------
## See the NOTICE file distributed with this work for additional
## information regarding copyright ownership.
##
## This is free software; you can redistribute it and/or modify it
## under the terms of the GNU Lesser General Public License as
## published by the Free Software Foundation; either version 2.1 of
## the License, or (at your option) any later version.
##
## This software is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with this software; if not, write to the Free
## Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
## 02110-1301 USA, or see the FSF site: http://www.fsf.org.
## ---------------------------------------------------------------------------
#**
This page starts the password reset procedure. It works according to the next algorithm:
1. Display a form requesting the username
2. When receiving the username via form submission, generate a random verification string which is stored (as a hash) inside a ResetPasswordRequestClass object attached to the user's profile page. If no such object exists, it is created, but an existing object will be reused, meaning that at most one password reset request can be active at a moment.
3. Send an email to the address configured in the user's profile, containing a link to the second step of the password reset procedure.
URL parameters:
u = user account sent in the form
*###
##
##
#template("register_macros.vm")
#macro(resetPasswordBoxStart $panelClass)
#if ("$!panelClass" == "")
#set ($panelClass = "default")
#end
<div class="centered panel panel-$panelClass xwikimessage panel-body">
<div class="panel-heading">
<div class="panel-title">$services.localization.render('xe.admin.passwordReset.title')</div>
</div>
<div class="panel-body">
#end
#macro(displayResetPasswordException)
#set ($causeException = $exception.cause)
#if ($causeException.class == 'class org.xwiki.security.authentication.api.ResetPasswordException'
&& $causeException.cause == $causeException)
<div class="xwikirenderingerror">
$escapetool.xml($causeException.message)
</div>
#else
#displayException($escapetool.xml($causeException.message))
#end
#end
#set ($userName = "$!request.get('u')")
#set ($validationString = "$!request.get('v')")
## First step, display the form requesting the username
#if (($userName == '' && $validationString == ''))
#resetPasswordBoxStart("default")
$services.localization.render('xe.admin.passwordReset.instructions')
<form method="post" action="$services.security.authentication.getAuthenticationURL('reset', $NULL)" class="xformInline" id="resetPasswordForm">
<div>
<input type="hidden" name="form_token" value="$!{services.csrf.getToken()}" />
<label for="u">$services.localization.render('xe.admin.passwordReset.username.label')</label>
<input type="text" id="u" name="u"/>
<span class="buttonwrapper">
<input type="submit" value="$services.localization.render('xe.admin.passwordReset.submit')" class="button"/>
</span>
</div>
</form>
#elseif ($userName != '' && $validationString == '')
#if (!$services.csrf.isTokenValid($request.form_token))
#resetPasswordBoxStart("danger")
$services.localization.render('xe.admin.passwordReset.error.csrf')
#else
#try()
#set ($email = $services.security.authentication.requestResetPassword($userName))
#end
#if ("$!exception" != '')
#resetPasswordBoxStart("warning")
#displayResetPasswordException()
#else
#resetPasswordBoxStart("default")
$services.localization.render('xe.admin.passwordReset.emailSent', ["$email"])
#end
#end
<div>
<a href="$services.security.authentication.getAuthenticationURL('reset', $NULL)">$services.localization.render('xe.admin.passwordReset.error.retry')</a> |
<a href="$xwiki.getURL('XWiki.ForgotUsername')">$services.localization.render('xe.admin.passwordReset.error.recoverUsername')</a> |
<a href="$xwiki.getURL('XWiki.XWikiLogin', 'login')">$services.localization.render('xe.admin.passwordReset.login')</a>
</div>
#else
##
##
#**
* Displays the password reset form.
* @param message An optional message to display, for example if the sent password is empty.
* @param u The user account (full document name), which needs to be preserved.
* @param v The validation string, which will be checked again upon receiving the form.
*###
#macro(displayForm $message $validationString)
#if ($message != '')
#resetPasswordBoxStart('warning')
$message
#else
#resetPasswordBoxStart('default')
#end
## Load the configuration from a seperate document.
#loadConfig('XWiki.RegistrationConfig')
#set ($passwordFields = [])
#definePasswordFields($passwordFields, 'p', 'p2', $passwordOptions)
<form action="$services.security.authentication.getAuthenticationURL('reset', $NULL)" method="post" id="resetPasswordStep2Form" class="xform third">
<div class="hidden">
<input type="hidden" name="form_token" value="$!{services.csrf.getToken()}" />
<input type="hidden" name="u" value="$!escapetool.xml($userName)"/>
<input type="hidden" name="v" value="$!escapetool.xml($validationString)"/>
</div>
## A null $request is passed as parameter, since we won't display inserted passwords after a request with error.
#generateHtml($passwordFields, $NULL)
<div class="buttons">
<span class="buttonwrapper"><input type="submit" value="$services.localization.render('xe.admin.passwordReset.step2.submit')" class="button"/></span>
</div>
</form>
#end
#set ($password = "$!request.p")
#set ($password2 = "$!request.p2")
#if (!$request.getParameterMap().containsKey('p'))
#try()
#set ($newValidationString = $services.security.authentication.checkVerificationCode($userName, $validationString))
#end
#if ("$!exception" != '')
#resetPasswordBoxStart("danger")
#displayResetPasswordException()
<a href="$services.security.authentication.getAuthenticationURL('reset', $NULL)">$services.localization.render('xe.admin.passwordReset.step2.backToStep1')</a>
#else
#displayForm('' $newValidationString)
#end
#elseif (!$services.csrf.isTokenValid($request.form_token))
#resetPasswordBoxStart("danger")
$request.form_token
$services.localization.render('xe.admin.passwordReset.error.csrf')
#else
#validateFields($passwordFields, $request)
#if (!$allFieldsValid)
#displayForm($stringtool.join($allFieldsErrors, "<br/>") $validationString)
#else
#try()
#set($discard = $services.security.authentication.resetPassword($userName, $validationString, $password))
#end
#if ("$!exception" != '')
#resetPasswordBoxStart("danger")
#displayResetPasswordException()
<a href="$services.security.authentication.getAuthenticationURL('reset', $NULL)">$services.localization.render('xe.admin.passwordReset.step2.backToStep1')</a>
#else
#resetPasswordBoxStart("success")
$services.localization.render('xe.admin.passwordReset.step2.success')
<a href="$xwiki.getURL('XWiki.XWikiLogin', 'login')">$services.localization.render('xe.admin.passwordReset.step2.login')</a>
#end
#end
#end
#set ($newValidationString = '')
#set ($validationString = '')
#set ($password = '')
#set ($password2 = '')
#end
#xwikimessageboxend() |
Program: N4 MRI Bias Field Correction
Language: C++
Date: $Date: 2012-28-12 14:00:00 +0100 (Fri, 28 Dec 2012) $
Version: $Revision: 1 $
Author: $Sebastien Tourbier$
Copyright (c) 2017 Medical Image Analysis Laboratory (MIAL), Lausanne
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#include "itkImage.h"
#include "itkShrinkImageFilter.h"
#include <itkN4BiasFieldCorrectionImageFilter.h>
#include <iostream>
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkEuler3DTransform.h"
#include "itkResampleImageFilter.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "mialsrtkN4BiasFieldCorrection.h"
mialsrtkN4BiasFieldCorrection::mialsrtkN4BiasFieldCorrection(const char* const _inputFile, const char* const _maskFile, const char* const _outputFile, const char* const _outputBiasFile)
{
inputFile = _inputFile;
maskFile = _maskFile;
outputFile = _outputFile;
outputBiasFile = _outputBiasFile;
ShrinkFactor = 4;
}
mialsrtkN4BiasFieldCorrection::~mialsrtkN4BiasFieldCorrection()
{
}
bool mialsrtkN4BiasFieldCorrection::runN4BiasFieldCorrection()
{
const unsigned int dimension = 3;
typedef float InputPixelType;
typedef float OutputPixelType;
typedef float MaskPixelType;
typedef itk::Image<InputPixelType, dimension> InputImageType;
typedef itk::Image<OutputPixelType, dimension> OutputImageType;
typedef itk::Image<MaskPixelType, dimension> MaskType;
typedef itk::ImageFileReader<InputImageType> ReaderType;
typedef itk::ImageFileWriter<OutputImageType> WriterType;
typedef itk::ImageFileReader<MaskType> MaskReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inputFile);
try
{
reader->Update();
}
catch (itk::ExceptionObject &err)
{
throw "error opening inputImage";
return false;
}
InputImageType::Pointer inputImage = reader->GetOutput();
MaskReaderType::Pointer maskReader = MaskReaderType::New();
maskReader->SetFileName(maskFile);
try
{
maskReader->Update();
}
catch (itk::ExceptionObject &err)
{
throw "error opening maskImage";
return false;
}
typedef itk::ResampleImageFilter<MaskType,MaskType> ResampleImageMaskFilterType;
typedef itk::NearestNeighborInterpolateImageFunction<MaskType> NNInterpolatorType;
ResampleImageMaskFilterType::Pointer maskUpsampler = ResampleImageMaskFilterType::New();
NNInterpolatorType::Pointer nnInterpolator = NNInterpolatorType::New();
typedef itk::Euler3DTransform<double> Euler3DTransformType;
Euler3DTransformType::Pointer idTransform = Euler3DTransformType::New();
idTransform->SetIdentity();
maskUpsampler -> SetInterpolator(nnInterpolator);
maskUpsampler -> SetInput(maskReader->GetOutput());
maskUpsampler -> SetTransform(idTransform);
maskUpsampler -> SetOutputParametersFromImage(inputImage.GetPointer());
maskUpsampler -> SetOutputSpacing(inputImage->GetSpacing());
maskUpsampler -> SetSize(inputImage->GetLargestPossibleRegion().GetSize());
maskUpsampler -> Update();
MaskType::Pointer maskImage = maskUpsampler->GetOutput();
typedef itk::ShrinkImageFilter<InputImageType, InputImageType> ShrinkerType;
ShrinkerType::Pointer shrinker = ShrinkerType::New();
shrinker->SetInput(inputImage);
shrinker->SetShrinkFactors(ShrinkFactor);
shrinker->Update();
shrinker->UpdateLargestPossibleRegion();
typedef itk::ShrinkImageFilter<MaskType, MaskType> MaskShrinkerType;
MaskShrinkerType::Pointer maskShrinker = MaskShrinkerType::New();
maskShrinker->SetInput(maskImage);
maskShrinker->SetShrinkFactors(ShrinkFactor);
maskShrinker->Update();
maskShrinker->UpdateLargestPossibleRegion();
typedef itk::N4BiasFieldCorrectionImageFilter<InputImageType,MaskType,InputImageType> CorrecterType;
CorrecterType::Pointer correcter = CorrecterType::New();
correcter->SetInput1(shrinker->GetOutput());
correcter->SetMaskImage(maskShrinker->GetOutput());
correcter->SetMaskLabel(1);
unsigned int NumberOfFittingLevels = 3;
unsigned int NumberOfHistogramBins = 200;
//With B-spline grid res. = [1, 1, 1]
CorrecterType::ArrayType NumberOfControlPoints(NumberOfFittingLevels);
NumberOfControlPoints[0] = NumberOfFittingLevels+1;
NumberOfControlPoints[1] = NumberOfFittingLevels+1;
NumberOfControlPoints[2] = NumberOfFittingLevels+1;
CorrecterType::VariableSizeArrayType maximumNumberOfIterations(NumberOfFittingLevels);
maximumNumberOfIterations[0] = 50;
maximumNumberOfIterations[1] = 40;
maximumNumberOfIterations[2] = 30;
float WienerFilterNoise = 0.01;
float FullWidthAtHalfMaximum = 0.15;
float ConvergenceThreshold = 0.0001;
correcter->SetMaximumNumberOfIterations(maximumNumberOfIterations);
correcter->SetNumberOfFittingLevels(NumberOfFittingLevels);
correcter->SetNumberOfControlPoints(NumberOfControlPoints);
correcter->SetWienerFilterNoise(WienerFilterNoise);
correcter->SetBiasFieldFullWidthAtHalfMaximum(FullWidthAtHalfMaximum);
correcter->SetConvergenceThreshold(ConvergenceThreshold);
correcter->SetNumberOfHistogramBins(NumberOfHistogramBins);
correcter->Update();
typedef CorrecterType::BiasFieldControlPointLatticeType PointType;
typedef CorrecterType::ScalarImageType ScalarImageType;
typedef itk::BSplineControlPointImageFilter<PointType, ScalarImageType> BSplinerType;
BSplinerType::Pointer bspliner = BSplinerType::New();
bspliner->SetInput( correcter->GetLogBiasFieldControlPointLattice() );
bspliner->SetSplineOrder( correcter->GetSplineOrder() );
bspliner->SetSize( inputImage->GetLargestPossibleRegion().GetSize() );
bspliner->SetOrigin( inputImage->GetOrigin() );
bspliner->SetDirection( inputImage->GetDirection() );
bspliner->SetSpacing( inputImage->GetSpacing() );
bspliner->Update();
InputImageType::Pointer logField = InputImageType::New();
logField->SetOrigin(bspliner->GetOutput()->GetOrigin());
logField->SetSpacing(bspliner->GetOutput()->GetSpacing());
logField->SetRegions(bspliner->GetOutput()->GetLargestPossibleRegion().GetSize());
logField->SetDirection(bspliner->GetOutput()->GetDirection());
logField->Allocate();
itk::ImageRegionIterator<ScalarImageType> ItB(bspliner->GetOutput(),bspliner->GetOutput()->GetLargestPossibleRegion());
itk::ImageRegionIterator<InputImageType> ItF(logField,logField->GetLargestPossibleRegion());
for(ItB.GoToBegin(), ItF.GoToBegin(); !ItB.IsAtEnd(); ++ItB, ++ItF)
{
ItF.Set( ItB.Get()[0] );
}
typedef itk::ExpImageFilter<InputImageType, InputImageType>
ExpFilterType;
ExpFilterType::Pointer expFilter = ExpFilterType::New();
expFilter->SetInput( logField );
expFilter->Update();
typedef itk::DivideImageFilter<InputImageType, InputImageType, InputImageType> DividerType;
DividerType::Pointer divider = DividerType::New();
divider->SetInput1( inputImage );
divider->SetInput2( expFilter->GetOutput() );
divider->Update();
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outputFile);
writer->SetInput(divider->GetOutput());
try
{
writer->Update();
}
catch (itk::ExceptionObject &err)
{
throw "error writing outputImage";
return false;
}
WriterType::Pointer fieldWriter = WriterType::New();
fieldWriter->SetFileName(outputBiasFile);
fieldWriter->SetInput(logField);
try
{
fieldWriter->Update();
}
catch (itk::ExceptionObject &err)
{
throw "error writing output BiasField";
return false;
}
return true;
} |
/*
* Lisans bilgisi icin lutfen proje ana dizinindeki zemberek2-lisans.txt dosyasini okuyunuz.
*/
package net.zemberek.islemler;
import static net.zemberek.tr.yapi.ek.TurkceEkAdlari.*;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.zemberek.TemelTest;
import net.zemberek.TestUtils;
import net.zemberek.bilgi.kokler.KokAdayiBulucu;
import net.zemberek.bilgi.kokler.Sozluk;
import net.zemberek.islemler.cozumleme.CozumlemeSeviyesi;
import net.zemberek.islemler.cozumleme.KesinHDKiyaslayici;
import net.zemberek.islemler.cozumleme.StandartCozumleyici;
import net.zemberek.yapi.Alfabe;
import net.zemberek.yapi.Kelime;
import net.zemberek.yapi.KelimeTipi;
import net.zemberek.yapi.Kok;
import net.zemberek.yapi.ek.Ek;
import org.junit.Before;
import org.junit.Test;
/**
*/
public class TestKelimeUretici extends TemelTest {
private KelimeUretici kelimeUretici;
private StandartCozumleyici cozumleyici;
private Sozluk kokler;
@Before
public void once() throws IOException {
super.once();
kelimeUretici = new KelimeUretici(alfabe, dilBilgisi.ekler(), dilBilgisi.cozumlemeYardimcisi());
//Normal denetleyici-cozumleyici olusumu
KokAdayiBulucu kokBulucu = dilBilgisi.kokler().kokBulucuFactory().kesinKokBulucu();
cozumleyici = new StandartCozumleyici(kokBulucu, new KesinHDKiyaslayici(), alfabe, dilBilgisi.ekler(), dilBilgisi.cozumlemeYardimcisi());
kokler = dilBilgisi.kokler();
}
private Ek ek(String ad) {
return dilBilgisi.ekler().ek(ad);
}
private List<Ek> ekListesi(String... ekAdlari) {
List<Ek> ekler = new ArrayList<Ek>();
for (String s : ekAdlari)
ekler.add(dilBilgisi.ekler().ek(s));
return ekler;
}
@Test
public void testKelimeUret() {
Kok kok = kokler.kokBul("sabret", KelimeTipi.FIIL);
List<Ek> ekler = ekListesi(FIIL_YETENEK_EBIL, FIIL_GELECEKZAMAN_ECEK, FIIL_KISI_BIZ);
assertEquals("sabredebilece\u011fiz", kelimeUretici.kelimeUret(kok, ekler));
kok = kokler.kokBul("armut", KelimeTipi.ISIM);
ekler = ekListesi(ISIM_SAHIPLIK_BIZ_IMIZ, ISIM_TANIMLAMA_DIR);
assertEquals("armudumuzdur", kelimeUretici.kelimeUret(kok, ekler));
Kelime almanyada = cozumleyici.cozumle("Almanya'da", CozumlemeSeviyesi.TEK_KOK)[0];
assertEquals("Almanya'da", kelimeUretici.kelimeUret(almanyada.kok(), almanyada.ekler()));
kok = kokler.kokBul("sabret", KelimeTipi.FIIL);
ekler = ekListesi(FIIL_YETENEK_EBIL, FIIL_GELECEKZAMAN_ECEK, FIIL_KISI_BIZ);
assertEquals("sabredebilece\u011fiz", kelimeUretici.kelimeUret(kok, ekler));
kok = kokler.kokBul("et", KelimeTipi.FIIL);
ekler = ekListesi(FIIL_GELECEKZAMAN_ECEK);
assertEquals("edecek", kelimeUretici.kelimeUret(kok, ekler));
kok = kokler.kokBul("et", KelimeTipi.FIIL);
ekler = ekListesi(FIIL_KOK, FIIL_OLUMSUZLUK_ME);
assertEquals("etme", kelimeUretici.kelimeUret(kok, ekler));
}
private static String I = String.valueOf(Alfabe.CHAR_ii);
@Test
public void testKelimeUretRasgeleDiziliEk() {
Kok kok = kokler.kokBul("armut", KelimeTipi.ISIM);
List<Ek> ekler = ekListesi(ISIM_YONELME_E, ISIM_TANIMLAMA_DIR, ISIM_SAHIPLIK_BIZ_IMIZ);
assertEquals("armudumuzad" + I + "r", kelimeUretici.sirasizEklerleUret(kok, ekler));
kok = kokler.kokBul("sabret", KelimeTipi.FIIL);
ekler = ekListesi(FIIL_GELECEKZAMAN_ECEK, FIIL_YETENEK_EBIL, FIIL_KOK, FIIL_KISI_BIZ);
assertEquals("sabredebilece\u011fiz", kelimeUretici.sirasizEklerleUret(kok, ekler));
}
/**
* fonksiyonel olusum testi. hepsi-dogru.txt dosyasindaki kelimeleri cozumleyip geri olusturur.
*
* @throws java.io.IOException io hatasi durumunda..
*/
@Test
public void testCozGeriOlustur() throws IOException {
List<String> kelimeler = TestUtils.satirlariOku("kaynaklar/tr/test/hepsi-dogru.txt");
for (String s : kelimeler) {
Kelime[] cozumler = cozumleyici.cozumle(s, CozumlemeSeviyesi.TEK_KOK);
for (Kelime kelime : cozumler) {
String uretilen = kelimeUretici.kelimeUret(kelime.kok(), kelime.ekler());
assertEquals("cozumlenen:" + s + ", olusan:" + uretilen + " ile ayni degil", s, uretilen);
}
}
}
@Test
public void testYumusama() {
String kelime = "uyutuyor";
Kelime[] kelimeler = cozumleyici.cozumle(kelime, CozumlemeSeviyesi.TUM_KOKLER);
for (Kelime kel : kelimeler) {
String uretilen = kelimeUretici.kelimeUret(kel.kok(), kel.ekler());
System.out.println(uretilen);
assertEquals(uretilen, kelime);
}
}
@Test
public void testEkAyristirma() {
String l1[] = {"kedi", "le", "r", "im"};
String l2[] = {"kedi", "ler", "im"};
Kelime[] cozumler = cozumleyici.cozumle("kedilerim", CozumlemeSeviyesi.TEK_KOK);
for (Kelime kel : cozumler) {
if (kel.ekSayisi() == 4)
assertEquals(l1, kelimeUretici.ayristir(kel));
else
assertEquals(l2, kelimeUretici.ayristir(kel));
}
}
@Test
public void testEkAyristir() {
Kelime[] cozumler = cozumleyici.cozumle("yedeklemeden", CozumlemeSeviyesi.TEK_KOK);
for (Kelime kel : cozumler) {
String[] ayrim = kelimeUretici.ayristir(kel);
System.out.println(Arrays.toString(ayrim));
}
}
} |
# Rendering
오늘은 렌더링에 관해 작성을 해 보려고 한다.
### 웹 렌더링 정의
브라우저 화면에 그려지는 과정
## 렌더링 과정
1. 클라이언트는 서버로부터 HTML 문서를 다운로드 받아 파싱해
DOM(Document Object Model) 트리를 생성
\*\* DOM : 웹 페이지의 구조
\*\* DOM TREE : DOM을 트리 구조로 표현한 것
2. CSS를 다운로드해 파싱 : CSSOM을 생성한다.
3. 렌더 트리 생성 : DOM트리와 CSSOM 트리를 결합해 렌더 트리(Render Tree)를 생성
4. 레이아웃 : 렌더 트리를 기반으로 위치와 크기를 계산해 배치를 하고
5. 페인트 : 레이아웃 정보를 기반으로 화면에 요소를 그리게 된다.
## SPA
SPA(Single Page Application)은 서버로부터 하나의 HTML 페이지만 받아오고 이후에는 동적으로 페이지를 업데이트하는 방식
( 처음 한번 페이지 전체를 로딩한 후 필요한 데이터만을 서버로부터 비동기적으로 요청 )
## MPA
여러 페이지로 구성된 웹 어플리케이션으로 페이지의 링크를 클릭할때 마다 다른 페이지를 로드하는 방식
## CSR
클라이언트 측에서 동적으로 페이지를 렌더링을 하는 방식
- 장점으로는 서버에 대한 부하를 줄일 수 있고 초기 로딩 이후 빠른 웹사이트 렌더링이 가능
- 검색 엔진 최적화(SEO)에 제약이 있고, 초기 로딩 속도가 느리다는 단점이 있습니다.
## SSR
서버에서 렌더링 하는 방식으로 서버로부터 완전하게 만들어진 HTML 파일을 받아와 화면에 보여준다.
- 초기 속도가 빠르고 검색 엔진 최적화에 유리합니다.
- 서버에 부하가 있고, 깜빡임 현상이 있을 수 있다.
## SSG
빌드 시점에 HTML을 만들고 매 요청마다 `HTML을 재사용`
- 동적인 콘텐츠 처리가 어려우며, 업데이트가 빈번한 사이트에는 적합하지 않음
## ISR
정적 생성된 페이지를 빌드한 후에도 해당 페이지를 필요에 따라 재생성하는 기술
## 배운점
CSR SSR은 정말 많이 나오는 지식으로 이번 TIL로 다시 공부하면서 배운게
SPA와 CSR의 관계에 대해 좀 더 자세하게 알게 되었다. 사실 헷갈렸던게
CSR, SPA와 같은건지, SSR, MPA하고 같은건지 좀 헷갈렸는데 이번에 다시 공부하고 배우면서 알게 되었다.
```
SPA, MPA는 페이지를 하나만 쓰는지, 여러개 쓰는지의 차이
CSR, SSR은 렌더링을 어디서 하냐의 차이
SSR과 SSG에 가장 큰 차이점은 HTML 파일이 언제 생성되느냐의 시점 차이
```
```
next에서 fetch 사용
CSR : 'use client;'
SSR : fetch('https://...', { cache: 'no-store' }
SSG : fetch('https://...', { cache: 'force-cache' }
ISR : fetch('https://...', { next: { revalidate: 10} })
```
참조) https://velog.io/@minw0_o/Nextjs%EC%97%90%EC%84%9C%EC%9D%98-%EB%A0%8C%EB%8D%94%EB%A7%81-%EB%B0%A9%EC%8B%9D-CSR-vs-SSR-vs-SSG-vs-ISR |
import { useEffect, useRef, useState } from "react";
import { Link, useLocation } from "react-router-dom";
import tw, { styled } from "twin.macro";
import SheetMobile from "../pages/Blog/Component/SheetMobile";
const ulStyles = tw`
bg-background-main
[> li]:(rounded-2xl px-5 transition-all border-b-[rgba(255, 255, 255, 0.1)] text-primary-mainColor relative border-b hover:pl-10 hover:bg-secondary-mainColor duration-300 py-1.5)
[> li > a]:(block pl-9 rounded-2xl hover:text-background-main text-[0.85rem] p-3 uppercase font-bold)
[> li > a > span]:( mr-[0.5rem])`;
const menuStyle = tw`
[> i]:(hover:cursor-pointer flex items-center justify-center bg-primary-mainColor lg:p-2 lg:px-3 xs:p-1 xs:px-2 text-background-main rounded text-sm)
`;
const MenuComponent = styled.div<{ open: boolean }>(({ open }) => [
tw`flex fixed left-0 z-50 top-0 h-full duration-300 ease-in-out w-64 pt-3 flex-col translate-x-[-100%] bg-background-main shadow-lg`, // Add base styles first
open && tw`translate-x-[0%] duration-300 ease-in-out`, // Then add conditional styles
]);
const LiNavMobile = styled.li<{ isActive: boolean }>(({ isActive }) => [
tw`flex w-full`, // Add base styles first
isActive &&
tw`bg-secondary-mainColor
[> a]:(text-background-main)`, // Then add conditional styles
]);
const arrayLinks = [
{
icon: <i className='fas fa-home'></i>,
title: "Home",
url: ["/", "/second", "/team"],
link: "#",
},
{
icon: <i className='fas fa-address-card'></i>,
title: "About",
url: [],
link: "/about",
},
{
icon: <i className='fas fa-cog'></i>,
title: "Service",
url: [],
link: "/service",
},
{
icon: <i className='fas fa-address-book'></i>,
title: "Gallery",
url: [],
link: "/gallery",
},
{
icon: <i className='fa-solid fa-book'></i>,
title: "Blog",
url: [],
link: "/blog",
},
{
icon: <i className='fa-regular fa-address-book'></i>,
title: "Contact",
url: [],
link: "/contact",
},
];
function NavMobile() {
const location = useLocation();
const locationName = location.pathname;
const [open, setOpen] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
setOpen(false);
}
};
// Thêm sự kiện click vào document
document.addEventListener("click", handleClickOutside);
// Cleanup: loại bỏ sự kiện khi component bị unmount
return () => {
document.removeEventListener("click", handleClickOutside);
};
}, []);
return (
<div
ref={menuRef}
tw='md:hidden xs:flex relative justify-between w-full flex-row'
>
<button
onClick={() => setOpen(!open)}
tw='bg-none border-none'
css={menuStyle}
>
<i className='fa-solid fa-bars '></i>
</button>
{locationName === "/blog" && <SheetMobile />}
<MenuComponent open={open}>
<button
onClick={() => setOpen(!open)}
className='absolute right-2 top-1'
>
<i className='fa-solid fa-xmark close-icon'></i>
</button>
<div className='mb-2 mt-2'>
<img
tw='w-32'
style={{ marginLeft: "3.3rem" }}
src={window.location.origin + "/logo.png"}
alt=''
/>
</div>
<ul css={ulStyles} tw=''>
{arrayLinks.map((link, index: number) => {
return (
<LiNavMobile
key={index}
isActive={
locationName == link.link || link.url.includes(locationName)
}
className='group'
>
<Link to={link.link}>
<span>{link.icon}</span>
{link.title}
</Link>
{link?.url[0] === "/" && (
<ul
css={ulStyles}
tw='absolute top-0 left-full hidden group-hover:block w-full h-fit shadow-lg rounded-2xl'
>
<LiNavMobile isActive={locationName == "/"}>
<Link to={"/"}>
<span>
<i className='fas fa-home'></i>
</span>
Overview
</Link>
</LiNavMobile>
<LiNavMobile isActive={locationName == "/second"}>
<Link to={"/second"}>
<span>
<i className='fas fa-home'></i>
</span>
Advice
</Link>
</LiNavMobile>
<LiNavMobile isActive={locationName == "/team"}>
<Link to={"/team"}>
<span>
<i className='fas fa-home'></i>
</span>
Team
</Link>
</LiNavMobile>
</ul>
)}
</LiNavMobile>
);
})}
</ul>
</MenuComponent>
</div>
);
}
export default NavMobile; |
import React from 'react'
import styled from 'styled-components'
import logo from '../../../../assets/images/logo.png'
const Container = styled.div`
background: ${props => props.theme.palette.primary.dark};
display: flex;
flex-direction: column;
padding: 30px 40px;
min-height: 200px;
`
const LogoWrapper = styled.div`
width: 100%;
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
`
const ContainerList = styled.div`
`
const ListWrapper = styled.div`
display: flex;
flex-direction: row;
`
const LogoImage = styled.img`
max-width: 100px;
width: 100%;
cursor: pointer;
`
const TextFooter = styled.p`
color: #49a5e6;
margin-right: 20px;
font-size: 18px;
`
const Footer = () => {
const list01 = [
{ name: "Aviso Legal"},
{ name: "Cláusulas Generales de Contratación"},
{ name: "Mapa del Sitio"},
]
const list02 = [
{ name: "Libro de Reclamaciones"},
{ name: "Llámanos (01) 595-0000"},
]
return (
<Container>
<LogoWrapper>
<LogoImage src={logo}/>
</LogoWrapper>
<ContainerList>
<ListWrapper>
{list01.map(item => (
<TextFooter key={item.name}>{item.name}</TextFooter>
))}
</ListWrapper>
<ListWrapper>
{list02.map(item => (
<TextFooter>{item.name}</TextFooter>
))}
</ListWrapper>
</ContainerList>
</Container>
)
}
export default Footer |
/**
* @license
* Visual Blocks Editor
*
* Copyright 2018 Google Inc.
* https://developers.google.com/blockly/
*
* 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.
*/
/**
* @fileoverview Abstract class for events fired as a result of actions in
* Blockly's editor.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Events.Abstract');
goog.require('Blockly.Events');
goog.require('goog.array');
goog.require('goog.math.Coordinate');
/**
* Abstract class for an event.
* @constructor
*/
Blockly.Events.Abstract = function() {
/**
* The workspace identifier for this event.
* @type {string|undefined}
*/
this.workspaceId = undefined;
/**
* The event group id for the group this event belongs to. Groups define
* events that should be treated as an single action from the user's
* perspective, and should be undone together.
* @type {string}
*/
this.group = Blockly.Events.group_;
/**
* Sets whether the event should be added to the undo stack.
* @type {boolean}
*/
this.recordUndo = Blockly.Events.recordUndo;
};
/**
* Encode the event as JSON.
* @return {!Object} JSON representation.
*/
Blockly.Events.Abstract.prototype.toJson = function() {
var json = {
'type': this.type
};
if (this.group) {
json['group'] = this.group;
}
return json;
};
/**
* Decode the JSON event.
* @param {!Object} json JSON representation.
*/
Blockly.Events.Abstract.prototype.fromJson = function(json) {
this.group = json['group'];
};
/**
* Does this event record any change of state?
* By default we assume events are non-null. Subclasses may override to
* indicate that they do not change state.
* @return {boolean} False if something changed.
*/
Blockly.Events.Abstract.prototype.isNull = function() {
return false;
};
/**
* Run an event.
* @param {boolean} _forward True if run forward, false if run backward (undo).
*/
Blockly.Events.Abstract.prototype.run = function(_forward) {
// Defined by subclasses.
};
/**
* Get workspace the event belongs to.
* @return {Blockly.Workspace} The workspace the event belongs to.
* @throws {Error} if workspace is null.
* @protected
*/
Blockly.Events.Abstract.prototype.getEventWorkspace_ = function() {
var workspace = Blockly.Workspace.getById(this.workspaceId);
if (!workspace) {
throw Error('Workspace is null. Event must have been generated from real' +
' Blockly events.');
}
return workspace;
}; |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login And Register</title>
<link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col" >
<h1 class="display-6">Register</h1>
<form:form action="/register" method="post" modelAttribute="newUser">
<div class="g-col-3 g-start-2">
<form:label path="userName" class="col-sm-2 col-form-label">User Name :</form:label>
<div class="col-sm-10">
<form:input type="text" class="form-control" path="userName" />
</div>
<form:errors class="text-danger" path="userName" />
<form:label path="email" class="col-sm-2 col-form-label">Email :</form:label>
<div class="col-sm-10">
<form:input type="email" class="form-control" path="email" />
</div>
<form:errors class="text-danger" path="email" />
<form:label path="password" class="col-sm-2 col-form-label">Password :</form:label>
<form:errors class="text-danger" path="password" />
<div class="col-sm-10">
<form:input type="password" class="form-control" path="password" />
</div>
<form:label path="confirm" class="col-sm-2 col-form-label">Confirm password: </form:label>
<form:errors class="text-danger" path="confirm" />
<div class="col-sm-10">
<form:input type="password" class="form-control" path="confirm" />
</div>
<input type="submit" class="btn btn-primary" value="sign in" />
</div>
</form:form>
</div>
<div class="col" >
<h1 class="display-6">Login</h1>
<form:form action ="/login" method="post" modelAttribute="newLogin">
<form:label path="email" class="col-sm-2 col-form-label">Email</form:label>
<form:errors class="text-danger" path="email" />
<div class="col-sm-10">
<form:input type="email" class="form-control" path="email" />
</div>
<form:label path="password" class="col-sm-2 col-form-label">Password</form:label>
<div class="col-sm-10">
<form:input type="password" class="form-control" path="password" />
</div>
<form:errors class="text-danger" path="password" />
<input type="submit" class="btn btn-primary" value="login"/>
</form:form >
</div>
</div>
</div>
</body>
</html> |
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Todo } from 'src/app/models/todo';
import { TodoService } from 'src/app/services/todo.service';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
@Component({
selector: 'app-create',
templateUrl: './create.component.html',
styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {
myControl = new FormControl();
options: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable<string[]> | undefined;
todo: Todo= {
titulo:'',
descricao:'',
datafinalizar:new Date(),
finalizado:false
}
constructor(private router:Router, private service: TodoService) { }
ngOnInit(): void {
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value)),
);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.toLowerCase().includes(filterValue));
}
create(): void{
this.formataData();
this.service.create(this.todo).subscribe((resposta)=>{
this.service.message('Todo Criado com Sucesso');
this.router.navigate(['']);
}, err =>{
this.service.message('Todo Criado sem Sucesso - FALHA');
this.router.navigate(['']);
})
}
cancelar():void{
this.router.navigate([''])
}
formataData(): void{
let data = new Date (this.todo.datafinalizar)
this.todo.datafinalizar = `${data.getDate()}/${data.getMonth() +1 }/${data.getFullYear()}`
}
} |
import { createContext, useEffect, useState } from "react";
import PropTypes from "prop-types";
import {
GithubAuthProvider,
createUserWithEmailAndPassword,
onAuthStateChanged,
signInWithEmailAndPassword,
signInWithPopup,
signOut,
} from "firebase/auth";
import { GoogleAuthProvider } from "firebase/auth";
import auth from "../Firebase/Firebase.config";
// import axios from "axios";
export const AuthContext = createContext(null);
const googleProvider = new GoogleAuthProvider();
const githubProvider = new GithubAuthProvider();
const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const googleUsers = () => {
setLoading(true);
return signInWithPopup(auth, googleProvider);
};
const githubUsers = () => {
setLoading(true);
return signInWithPopup(auth, githubProvider);
};
const createUsers = (email, password) => {
setLoading(true);
return createUserWithEmailAndPassword(auth, email, password);
};
const LoginUsers = (email, password) => {
setLoading(true);
return signInWithEmailAndPassword(auth, email, password);
};
const logoutUsers = () => {
setLoading(true);
return signOut(auth);
};
useEffect(() => {
const unSubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
setLoading(false);
// if (currentUser) {
// const userLogin = {email: currentUser.email}
// axios
// .post("https://food-server-3xcp7p4qu-suhans-projects.vercel.app/jwt", userLogin, {withCredentials: true})
// .then((res) => {
// console.log(res.data);
// });
// }
});
return () => {
unSubscribe();
};
}, []);
const authInfo = {
user,
googleUsers,
githubUsers,
createUsers,
LoginUsers,
logoutUsers,
loading,
//resetPassword,
};
return (
<AuthContext.Provider value={authInfo}>{children}</AuthContext.Provider>
);
};
export default AuthProvider;
AuthProvider.propTypes = {
children: PropTypes.object,
}; |
package com.wdbyte.os.process;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
/**
* 输出日志到指定文件
* @author https://www.wdbyte.com
*/
public class ProcessBuilderTest4 {
private static String BASE_DIR = "/Users/darcy/git/JavaNotes/core-java-modules/core-java-os/src/main/java/com/wdbyte/os/process";
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.directory(new File(BASE_DIR));
processBuilder.command("/bin/bash", "-c", "ls -l");
File logFile = new File(BASE_DIR + "/process_log.txt");
// 输出到日志文件
processBuilder.redirectOutput(logFile);
// 追加日志到文件
// processBuilder.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile));
// 是否输出ERROR日志到文件
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
long pid = process.pid();
int exitCode = process.waitFor();
System.out.println("pid:" + pid);
System.out.println("exitCode:" + exitCode);
// 读取日志
Files.lines(logFile.toPath()).forEach(System.out::println);
}
} |
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.listen(port, () => {
console.log("Server running on port 3000!!");
});
let todos = [];
const getSpecificTodo = (arr, index) => {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === index) {
return i;
}
}
return -1;
};
const deleteSpecificTodo = (arr, index) => {
todos = arr.filter((x) => x.id !== index);
};
app.get("/", (req, res) => {
res.send({
name: "Server-1",
role: "todo",
});
});
app.get("/todo", (req, res) => {
if (todos.length !== 0) {
console.log(todos);
res.status(200).json(todos);
} else {
res.status(404).json({
status: "No todo found!",
});
}
});
app.get("/todo/:id", (req, res) => {
const specificTodo = getSpecificTodo(todos, parseInt(req.params.id));
if (specificTodo !== -1) {
console.log(todos);
res.status(200).json(todos[specificTodo]);
} else {
res.status(404).json({
status: "No todo found!",
});
}
});
app.post("/todo", (req, res) => {
const newTodo = {
id: Math.floor(Math.random() * 100),
title: req.body.title,
description: req.body.description,
completed: true,
};
todos.push(newTodo);
console.log(todos);
res.status(201).json({ message: "Todo was created!", id: newTodo.id });
});
app.put("/todo/:id", (req, res) => {
const specificTodo = getSpecificTodo(todos, parseInt(req.params.id));
if (specificTodo !== -1) {
todos[specificTodo].title = req.body.title;
todos[specificTodo].completed = req.body.completed;
console.log(todos);
res.status(200).json({
message: "Todo was found and updated!",
});
} else {
res.status(404).json({
message: "Todo not found!",
});
}
});
app.delete("/todo/:id", (req, res) => {
const specificTodo = getSpecificTodo(todos, parseInt(req.params.id));
if (specificTodo !== -1) {
deleteSpecificTodo(todos, todos[specificTodo].id);
console.log(todos);
res.json({
message: "Todo Deleted Succesfully!",
});
} else {
res.status(404).json({
message: "Todo not found!",
});
}
}); |
<?php
namespace App\Http\Controllers\Custom;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Project;
use App\Models\Service;
use App\Models\ProjectImgs;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
class ProjectController extends Controller
{
/**
* View Project.
*/
public function ViewProjects()
{
// $projects = Project::all();
$projects = Project::orderBy('created_at', 'desc')->get();
return view('admin.project.view_projects', compact('projects'));
} //End Method
/**
* Create Project.
*/
public function CreateProject()
{
return view('admin.project.create_project');
} //End Method
/**
* Save Project.
*/
public function SaveProject(Request $request)
{
$request->validate([
'image' => 'required',
'name' => 'required',
'category' => 'required',
],[
'image.required' => 'Project image is required',
'name.required' => 'Project name is required',
'category.required' => 'Project category is required',
]);
$max_no = ProjectImgs::max('order');
$order = $max_no + 1;
// $images = $request->has('images');
$details = isset($request->details);
$images = $request->file('images');
$image = $request->file('image');
if($images && $details) {
// echo('Images and details present!');
// exit();
if($image) {
$width = 1144;
$height = 1300;
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
$img = $img->resize($width, $height);
$img->save('uploads/projects/'.$name_gen);
$save_url = 'uploads/projects/'.$name_gen;
}
$project = Project::create([
'image' => $save_url,
'name' => $request->name,
'category' => $request->category,
'location' => $request->location,
'year' => $request->year,
'details' => $request->details,
]);
foreach( $images as $image) {
if($image) {
$width = 600;
$height = 600;
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
$img = $img->resize($width, $height);
$img->save('uploads/projects/details/'.$name_gen);
$save_urls = 'uploads/projects/details/'.$name_gen;
}
ProjectImgs::insert([
'project_id' => $project->id,
'order' => $order,
'image' => $save_urls,
]);
}// End of the foreach
$notification = array(
'message' => 'Project saved',
);
return redirect()->route('view.projects')->with($notification);
} elseif($images && !$details) {
// echo('Image, no details!');
// exit();
if($image) {
$width = 1144;
$height = 1300;
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
$img = $img->resize($width, $height);
$img->save('uploads/projects/'.$name_gen);
$save_url = 'uploads/projects/'.$name_gen;
}
$project = Project::create([
'order' => $order,
'image' => $save_url,
'name' => $request->name,
'category' => $request->category,
'location' => $request->location,
'year' => $request->year,
]);
foreach( $images as $image) {
if($image) {
$width = 600;
$height = 600;
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
$img = $img->resize($width, $height);
$img->save('uploads/projects/details/'.$name_gen);
$save_urls = 'uploads/projects/details/'.$name_gen;
}
ProjectImgs::insert([
'project_id' => $project->id,
'order' => $order,
'image' => $save_urls,
]);
}// End of the foreach
$notification = array(
'message' => 'Project saved',
// 'message' => 'Project saved, no details',
);
return redirect()->route('view.projects')->with($notification);
} elseif(!$images && $details) {
// echo('Details, no image!');
// exit();
if($image) {
$width = 1144;
$height = 1300;
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
$img = $img->resize($width, $height);
$img->save('uploads/projects/'.$name_gen);
$save_url = 'uploads/projects/'.$name_gen;
}
$project = Project::create([
'order' => $order,
'image' => $save_url,
'name' => $request->name,
'category' => $request->category,
'location' => $request->location,
'year' => $request->year,
'details' => $request->details,
]);
$notification = array(
'message' => 'Project saved',
// 'message' => 'Project details saved, no image',
);
return redirect()->route('view.projects')->with($notification);
} else {
// echo('No details, no image!');
// exit();
if($image) {
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
$img = $img->resize(1600, 1128);
$img->save('uploads/projects/'.$name_gen);
$save_url = 'uploads/projects/'.$name_gen;
}
$project = Project::create([
'image' => $save_url,
'name' => $request->name,
'category' => $request->category,
'location' => $request->location,
'year' => $request->year,
]);
$notification = array(
'message' => 'Project saved',
// 'message' => 'No image, no details',
);
return redirect()->route('view.projects')->with($notification);
}
} // End Method |-------------------
/**
* Edit Project.
*/
public function EditProject($id)
{
$project = Project::findOrFail($id);
$projectImages = $project->images->sortBy('order');
return view('admin.project.edit_project', compact('project'), compact('projectImages'));
} // End Method |-------------------
/**
* Edit Project Images.
*/
public function EditProjectImages($id)
{
$project = Project::findOrFail($id);
$projectImages = $project->images->sortBy('order');
return view('admin.project.edit_project_imgs', compact('project'), compact('projectImages'));
} // End Method |-------------------
/**
* Update resource in storage.
*/
public function UpdateProjectImages(Request $request)
{
$id = $request->id;
$image = $request->file('image');
if($image){
$project_imgs = ProjectImgs::findOrFail($id);
$delImg = $project_imgs->image;
try {
if(file_exists($delImg)){
unlink($delImg);
}
} catch (Exception $e) {
Log::error("Error deleting old image: " . $e->getMessage());
}
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
// $img = $img->resize(200, 140);
// $img->toJpeg(80)->save('upload/hero_images/'.$name_gen);
$img->save('uploads/projects/details/'.$name_gen);
$save_url = 'uploads/projects/details/'.$name_gen;
ProjectImgs::findOrFail($id)->update([
'image' => $save_url,
]);
$notification = array(
'message' => 'Project image updated',
);
return redirect()->back()->with($notification);
} else {
ProjectImgs::findOrFail($id)->update([
'caption' => $request->caption,
]);
$notification = array(
'message' => 'Image Update',
);
return redirect()->back()->with($notification);
}
} //End Method
/**
* Sort Project.
*/
public function SortProject(Request $request)
{
$order = $request->input('order');
foreach ($order as $index => $projectId) {
Project::where('id', $projectId)->update(['order' => $index + 1]);
}
$notification = array(
'message' => 'Project sorted',
);
return redirect()->back()->with($notification);
} // End Method
/**
* Sort Project.
*/
public function SortProjectImgs(Request $request)
{
$order = $request->input('order');
foreach ($order as $index => $projectId) {
ProjectImgs::where('id', $projectId)->update(['order' => $index + 1]);
}
$notification = array(
'message' => 'Project images sorted',
);
return redirect()->back()->with($notification);
} // End Method
/**
* Delete Project image.
*/
public function DeleteProjectImg($id)
{
$image = ProjectImgs::findOrFail($id);
$delImg = $image->image;
try {
if(file_exists($delImg)){
unlink($delImg);
}
} catch (Exception $e) {
Log::error("Error deleting old image: " . $e->getMessage());
}
ProjectImgs::findOrFail($id)->delete();
$notification = array(
'message' => 'Image deleted',
);
return redirect()->back()->with($notification);
} //End Method
/**
* Save Project Image.
*/
public function SaveProjectImg(Request $request)
{
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg',
],[
'image.required' => 'icon in PNG/JPG is required',
]);
$order = 0;
$id = $request->project_id;
$image = $request->file('image');
if($image) {
$width = 600;
$height = 600;
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
$img = $img->resize($width, $height);
$img->save('uploads/projects/details/'.$name_gen);
$save_url = 'uploads/projects/details/'.$name_gen;
}
ProjectImgs::insert([
'order' => $order,
'project_id' => $id,
'image' => $save_url,
'caption' => $request->caption,
]);
$notification = array(
'message' => 'Image saved',
);
return redirect()->back()->with($notification);
} //End Method
/**
* Update resource in storage.
*/
public function UpdateProject(Request $request)
{
$id = $request->id;
$order = 0;
$image = $request->file('image');
$images = $request->file('images');
if($image && $images) {
$project = Project::findOrFail($id);
$delImg = $project->image;
try {
if(file_exists($delImg)) {
unlink($delImg);
}
} catch (Exception $e) {
Log::error("Error deleting old image: " . $e->getMessage());
}
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
$sizedImg = $img->resize(200, 140);
// $sizedImg->toJpeg(80)->save('upload/hero_images/'.$name_gen);
$sizedImg->save('uploads/projects/'.$name_gen);
$save_url = 'uploads/projects/'.$name_gen;
foreach( $images as $image) {
if($image) {
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
$img->save('uploads/projects/details/'.$name_gen);
$save_urls = 'uploads/projects/details/'.$name_gen;
}
ProjectImgs::insert([
'project_id' => $id,
'order' => $order,
'image' => $save_urls,
]);
}// End of the foreach
Project::findOrFail($id)->update([
'name' => $request->name,
'category' => $request->category,
'location' => $request->location,
'year' => $request->year,
'details' => $request->details,
'image' => $save_url,
]);
$notification = array(
'message' => 'Project updated',
);
return redirect()->back()->with($notification);
} elseif($image && !$images) {
// No Images just an image
$project = Project::findOrFail($id);
$delImg = $project->image;
try {
if(file_exists($delImg)){
unlink($delImg);
}
} catch (Exception $e) {
Log::error("Error deleting old image: " . $e->getMessage());
}
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
$sizedImg = $img->resize(200, 140);
// $sizedImg->toJpeg(80)->save('upload/hero_images/'.$name_gen);
$sizedImg->save('uploads/projects/'.$name_gen);
$save_url = 'uploads/projects/'.$name_gen;
Project::findOrFail($id)->update([
'name' => $request->name,
'category' => $request->category,
'location' => $request->location,
'year' => $request->year,
'details' => $request->details,
'image' => $save_url,
]);
$notification = array(
'message' => 'Project updated',
);
return redirect()->back()->with($notification);
} elseif(!$image && $images) {
// No image but there are images
Project::findOrFail($id)->update([
'name' => $request->name,
'category' => $request->category,
'location' => $request->location,
'year' => $request->year,
'details' => $request->details,
]);
foreach( $images as $image) {
if($image) {
$manager = new ImageManager(new Driver());
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
$img = $manager->read($image);
$img->save('uploads/projects/details/'.$name_gen);
$save_urls = 'uploads/projects/details/'.$name_gen;
}
ProjectImgs::insert([
'project_id' => $id,
'order' => $order,
'image' => $save_urls,
]);
}// End of the foreach
$notification = array(
'message' => 'Project updated',
);
return redirect()->back()->with($notification);
} else {
Project::findOrFail($id)->update([
'name' => $request->name,
'category' => $request->category,
'location' => $request->location,
'year' => $request->year,
'details' => $request->details,
]);
$notification = array(
'message' => 'Project updated',
);
return redirect()->back()->with($notification);
}
} //End Method
/**
* Delete Project.
*/
public function DeleteProject($id)
{
$images = ProjectImgs::where('project_id', $id)->get();
foreach($images as $image) {
unlink(public_path($image->image));
}
ProjectImgs::where('project_id', $id)->delete();
$project = Project::findOrFail($id);
$delImg = $project->image;
try {
if(file_exists($delImg)){
unlink($delImg);
}
} catch (Exception $e) {
Log::error("Error deleting old image: " . $e->getMessage());
}
Project::findOrFail($id)->delete();
$notification = array(
'message' => 'Project deleted',
);
return redirect()->route('view.projects')->with($notification);
} //End Method
/**
* Project page(Non-admin page).
*/
public function ProjectPage()
{
return view('frontend.project.projects');
} //End Method |-------------------
/**
* Project Details page(Non-admin page).
*/
public function ProjectDetailedPage($id)
{
$project = Project::findOrFail($id);
$projectImages = $project->images->sortBy('order');
$previousProject = Project::where('id', '<', $project->id)->where('details', '!=', '')->orderBy('id', 'desc')->first();
$nextProject = Project::where('id', '>', $project->id)->where('details', '!=', '')->orderBy('id', 'asc')->first();
return view('frontend.project.project_detailed', compact('project', 'projectImages', 'previousProject', 'nextProject'));
} //End Method |-------------------
} |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
# Load the training data
train_data = pd.read_csv('train.csv')
# Select features and target variable
features = train_data.drop(['Outcome', 'ID'], axis = 1)
target = train_data['Outcome']
# Split the data into training and validation sets
X_train, X_val, y_train, y_val = train_test_split(features, target, test_size = 0.2, random_state = 40)
# Train a machine learning model
model = LogisticRegression()
model.fit(X_train, y_train)
# Make predictions on the test set
test_data = pd.read_csv('diabetes_test.csv')
test_features = test_data.drop('ID', axis = 1)
# Make predictions
predictions = model.predict(test_features)
# Create a DataFrame with ID and predicted columns
result_df = pd.DataFrame({'ID': test_data['ID'], 'predicted': predictions})
# Save the result to predictions.csv
result_df.to_csv('predictions.csv', index=False) |
import React, {
forwardRef,
Suspense,
useMemo,
useRef,
} from 'react';
import { Vector3 } from 'three';
import { TextGeometry } from 'three/addons/geometries/TextGeometry';
import { FontLoader } from 'three/examples/jsm/loaders/FontLoader';
import mathFont
from '@compai/font-noto-sans-math/data/typefaces/normal-400.json';
import {
CatmullRomLine,
OrbitControls,
} from '@react-three/drei';
import {
Canvas,
extend,
useThree,
} from '@react-three/fiber';
extend({ TextGeometry });
const width = 100;
const height = 120;
const origin = new Vector3(0, 0, 0);
const SPHERE_RADIUS = 1;
const xAxis = new Vector3(SPHERE_RADIUS, 0, 0);
const yAxis = new Vector3(0, SPHERE_RADIUS, 0);
const zAxis = new Vector3(0, 0, SPHERE_RADIUS);
const negZAxis = new Vector3(0, 0, -SPHERE_RADIUS);
export default function ({ data = [[], [], []], time }) {
return (
<div style={{ width, height, margin: 'auto' }}>
<Canvas
orthographic
camera={{
zoom: 35,
position: [5, 5, 5],
near: 1,
far: 100,
top: 5,
bottom: -5,
right: 5,
left: -5,
up: [0, 0, 1],
}}
>
<Suspense fallback={null}>
<BlochSphere data={data} time={time} />
</Suspense>
</Canvas>
</div>
);
}
function BlochSphere({ data, time }) {
const ref = useRef();
const blochVectorRef = useRef();
const vector = useMemo(() => {
const [x, y, z] = data?.map((axis) => axis.at(time)) ?? [0, 0, 0];
return { x, y, z };
}, [data, time]);
const vertices = useMemo(
() =>
{const arr = Array.from({ length: data?.[0].slice(0, time).length }, (_, i) => [
data[0][i],
data[1][i],
data[2][i],
])
return arr.length ? arr : []
},
[data, time]
);
return (
<>
<ambientLight />
<pointLight position={[10, 10, 10]} />
{!!(vertices.length > 2) && <CatmullRomLine
points={vertices}
curveType="chordal"
closed={false}
color="orange"
lineWidth={1}
tension={0}
segments={vertices.length-1}
/>}
<mesh position={[0, 0, 0]} ref={ref}>
<BlochVector
x={vector.x}
y={vector.y}
z={vector.z}
ref={blochVectorRef}
/>
<sphereGeometry args={[SPHERE_RADIUS, 32, 16]} />
<ThreeDimAxis />
<meshLambertMaterial
color={"#aaaaaa"}
transparent={true}
opacity={0.5}
/>
</mesh>
<OrbitControls enablePan={false} enableZoom={false} />
</>
);
}
const BlochVector = forwardRef(({ x, y, z }, ref) => {
const vector = new Vector3(x, y, z);
return vector.length() ? (
<arrowHelper
ref={ref}
args={[vector, origin, vector.length(), 0xff0000, 0.25, 0.25]}
/>
) : (
[]
);
});
const ThreeDimAxis = () => {
const axisArrowArgs = [
origin,
1.2 * SPHERE_RADIUS,
0xefefef,
0.1 * SPHERE_RADIUS,
0.1 * SPHERE_RADIUS,
];
const xAxisLabel = new Vector3(1.25*SPHERE_RADIUS, 0, 0);
const yAxisLabel = new Vector3(0, 1.25*SPHERE_RADIUS, 0);
const zAxisLabel = new Vector3(0, 0, 1.25*SPHERE_RADIUS);
const negZAxisLabel = new Vector3(0, 0, -1.25*SPHERE_RADIUS);
return (
<>
<arrowHelper args={[xAxis, ...axisArrowArgs]} />
<arrowHelper args={[yAxis, ...axisArrowArgs]} />
<arrowHelper args={[zAxis, ...axisArrowArgs]} />
<arrowHelper args={[negZAxis, ...axisArrowArgs]} />
<AxisLabel label={"|0⟩"} position={zAxisLabel} />
<AxisLabel label={"|1⟩"} position={negZAxisLabel} />
<AxisLabel label={"x"} position={xAxisLabel} />
<AxisLabel label={"y"} position={yAxisLabel} />
</>
);
};
const AxisLabel = ({ label, position }) => {
const axisRef = useRef();
const { camera } = useThree();
const mathRegular = new FontLoader().parse(mathFont);
return (
<mesh position={position} ref={axisRef} quaternion={camera.quaternion}>
<textGeometry
args={[label, { font: mathRegular, size: 0.3, height: 0.01 }]}
/>
<meshStandardMaterial attach="material" color={"#efefef"} />
</mesh>
);
}; |
import { Suspense } from 'react'
import { useSetRecoilState } from 'recoil'
import { searchKeyWordState } from 'states/search'
import { useMount } from 'react-use'
import Loader from 'components/Loader'
import TopCoinCardList from './TopPriceCoinCardList'
import CoinTickerList from './CoinTickerList'
import HomeTab from './HomeTab'
import SearchForm from 'components/SearchForm'
import styles from './home.module.scss'
const HomePage = () => {
const setKeyWord = useSetRecoilState(searchKeyWordState)
useMount(() => {
setKeyWord('')
})
return (
<div className={styles.homeContainer}>
<Suspense fallback={<Loader />}>
<div className={styles.searchContainer}>
<SearchForm />
</div>
<HomeTab />
<TopCoinCardList />
<CoinTickerList />
</Suspense>
</div>
)
}
export default HomePage |
<?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('documents', function (Blueprint $table) {
$table->id();
$table->foreignId('semester_id')->constrained('semesters')->onDelete('cascade')->onUpdate('cascade');
$table->foreignId('instructors_id')->constrained('instructors')->onDelete('cascade')->onUpdate('cascade');
$table->foreignId('subject_id')->constrained('subjects')->onDelete('cascade')->onUpdate('cascade');
$table->foreignId('department_id')->constrained('departments')->onDelete('cascade')->onUpdate('cascade');
$table->foreignId('year_id')->constrained('departments')->onDelete('cascade')->onUpdate('cascade');
$table->string('file_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('documents');
}
}; |
// <copyright file="IOwnerRepository.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace CarRental.Repository
{
using System;
using CarRental.Data;
/// <summary>
/// IOwnerRepository interface.
/// </summary>
public interface IOwnerRepository : IRepository<Owner>
{
/// <summary>
/// Adds a new <see cref="Contractor"/> to the Contractor table by reaching Data Layer.
/// </summary>
/// <param name="firstName">Owner's first name.</param>
/// <param name="lastName">Owner's last name.</param>
/// <param name="birthDate">Owner's birth date.</param>
/// <param name="phoneNumber">Owner's phone number.</param>
/// <param name="rentalCompany">Owner's rental company.</param>
/// <param name="location">Owner's, location.</param>
void Add(string firstName, string lastName, DateTime birthDate, string phoneNumber, string rentalCompany, string location);
/// <summary>
/// Gets the Owner object by ID.
/// </summary>
/// <param name="id">ID.</param>
/// <returns>Owner by id.</returns>
new Owner GetOne(int id);
// void Set(int id, Owner newOwner);
}
} |
import { memo } from 'react';
interface GravesProps {
amount?: number;
innerRadius: number;
outerRadius: number;
shadows?: boolean;
}
const GravesEl = (props: GravesProps) => {
const { amount = 5, innerRadius, outerRadius, shadows = false } = props;
const dist = outerRadius - innerRadius;
const graveGeometry = <boxGeometry args={[0.6, 0.8, 0.2]} />;
const graveMaterial = <meshStandardMaterial color='#b2b6b1' />;
const graves: JSX.Element[] = [];
for (let i = 0; i < amount; i++) {
const angle = Math.random() * Math.PI * 2; // Random angle
const radius = innerRadius + Math.random() * dist; // Random radius
const x = Math.cos(angle) * radius;
const z = Math.sin(angle) * radius;
const grave = (
<mesh
position={[x, 0.3, z]}
key={i}
rotation-y={(Math.random() - 0.5) * 0.5}
rotation-z={(Math.random() - 0.5) * 0.5}
castShadow={shadows}>
{graveGeometry}
{graveMaterial}
</mesh>
);
graves.push(grave);
}
return <group>{graves}</group>;
};
export const Graves = memo(GravesEl); |
import { DetalleProducto } from "./DetalleProducto";
export class Factura{
id: number=null;
cliente: string=null;
porcentajeIva: number=0.0;
productos: DetalleProducto[]=new Array();
constructor(){
}
getImporteTotalSinIva():number{
let importeTotalSinIva:number=0.0;
this.productos.forEach(detalleProducto =>{
importeTotalSinIva+=detalleProducto.importeUnitario*detalleProducto.unidades;
});
return importeTotalSinIva;
}
getStringImporteTotalSinIva():string{
let cantidad:number=this.getImporteTotalSinIva();
let cadena:string=new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR' }).format(cantidad);
return cadena;
}
getImporteIva():number{
let importeIva:number=0.0;
importeIva=this.getImporteTotalSinIva()*this.porcentajeIva/100;
return importeIva;
}
getImporteTotalConIva():number{
let importeTotalConIva:number=0.0;
importeTotalConIva=this.getImporteTotalSinIva()+this.getImporteIva();
return importeTotalConIva;
}
getStringImporteTotalConIva():string{
let cantidad:number=this.getImporteTotalConIva();
let cadena:string=new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR' }).format(cantidad);
return cadena;
}
public static createFromJsonObject(jsonObject: any): Factura {
let factura: Factura = new Factura();
factura.id=jsonObject['id'];
factura.cliente=jsonObject['cliente'];
factura.porcentajeIva=jsonObject['porcentajeIva'];
jsonObject.productos.forEach(detalleProductoJson => {
let detalleProducto:DetalleProducto=new DetalleProducto();
detalleProducto.descripcion=detalleProductoJson['descripcion'];
detalleProducto.unidades=detalleProductoJson['unidades'];
detalleProducto.importeUnitario=detalleProductoJson['importeUnitario'];
factura.productos.push(detalleProducto);
});
return factura;
}
} |
<?php
use App\Http\Controllers\admin\auth\LoginController;
use App\Http\Controllers\admin\auth\RegistrationController;
use App\Http\Controllers\admin\CategoryController;
use App\Http\Controllers\admin\ProductController;
use App\Http\Controllers\admin\SubCategoryController;
use App\Http\Controllers\admin\ChildSubCategoryController;
use App\Http\Controllers\admin\HomeController;
use App\Http\Controllers\admin\ProductApprovalController;
use App\Http\Controllers\admin\SellerController;
use App\Http\Controllers\admin\RolePermissionController;
use App\Http\Controllers\admin\LogisticController;
use App\Http\Controllers\admin\BannerImagesController;
use App\Http\Controllers\admin\MarketingController;
use App\Http\Controllers\admin\PaymentController;
use App\Http\Controllers\admin\ReferralController;
use App\Http\Controllers\admin\SliderImageController;
use App\Http\Controllers\admin\UserController;
use App\Http\Controllers\admin\WalletController;
use App\Http\Controllers\AdminOrderController;
use App\Http\Controllers\SupportController;
use App\Http\Controllers\HsnCodeController;
use Illuminate\Support\Facades\Route;
use App\Models\Category;
/*
|--------------------------------------------------------------------------
| Admin Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::post('upload-products', [ProductController::class, 'uploadProducts'])->name('upload-products');
Route::get('test', function() {
return view('testfile');
});
Route::get('download-excel-sheet/{id}', [CategoryController::class, 'downloadCategory']);
Route::prefix('admin')->name('admin.')->group(function () {
Route::middleware(['guest:admin', 'PreventBackHistory'])->group(function () {
Route::get('register', [RegistrationController::class, 'index'])->name('register');
Route::get('login', [LoginController::class, 'index'])->name('login');
Route::post('register', [RegistrationController::class, 'adminRegister'])->name('admin-register');
Route::post('login', [LoginController::class, 'adminValidate'])->name('admin-login');
});
Route::middleware(['auth:admin', 'PreventBackHistory'])->group(function () {
Route::get('dashboard', [HomeController::class, 'index'])->name('dashboard');
Route::get('logout', [LoginController::class, 'logout'])->name('logout');
Route::prefix('category')->name('category.')->group(function () {
Route::get('/', [CategoryController::class, 'index'])->name('index');
Route::get('/list', [CategoryController::class, 'list'])->name('list');
Route::post('main/create', [CategoryController::class, 'store'])->name('store');
Route::get('edit/{id}', [CategoryController::class, 'edit'])->name('edit');
Route::post('update/{id}', [CategoryController::class, 'update'])->name('update');
Route::get('delete/{id}', [CategoryController::class, 'delete'])->name('delete');
// Route::post('sub/create', [CategoryController::class, 'categorySubCreate'])->name('sub.create');
// Route::get('create', [CategoryController::class, 'create'])->name('create');
// Route::get('get-categories', [CategoryController::class, 'getCategories'])->name('getCategories');
// Route::get('edit/{id}', [CategoryController::class, 'edit'])->name('edit');
// Route::post('update/{id}', [CategoryController::class, 'update'])->name('update');
// Route::get('delete/{id}', [CategoryController::class, 'delete'])->name('delete');
// Route::post('sub1/create', [CategoryController::class, 'categorySub1Create'])->name('sub1.create');
// Route::get('subcategory', [CategoryController::class, 'subcategory'])->name('subcategory');
// Route::get('subcategory1', [CategoryController::class, 'subcategory1'])->name('subcategory1');
// Route::get('tree/{id}', [CategoryController::class, 'tree'])->name('tree');
});
Route::prefix('subcategory')->name('subcategory.')->group(function () {
Route::get('/', [SubCategoryController::class, 'index'])->name('index');
Route::get('/list', [SubCategoryController::class, 'list'])->name('list');
Route::post('main/create', [SubCategoryController::class, 'store'])->name('store');
Route::get('edit/{id}', [SubCategoryController::class, 'edit'])->name('edit');
Route::post('update/{id}', [SubCategoryController::class, 'update'])->name('update');
Route::get('delete/{id}', [SubCategoryController::class, 'delete'])->name('delete');
});
Route::prefix('childsubcategory')->name('childsubcategory.')->group(function () {
Route::get('/', [ChildSubCategoryController::class, 'index'])->name('index');
Route::get('/list', [ChildSubCategoryController::class, 'list'])->name('list');
Route::post('main/create', [ChildSubCategoryController::class, 'store'])->name('store');
Route::get('edit/{id}', [ChildSubCategoryController::class, 'edit'])->name('edit');
Route::post('update/{id}', [ChildSubCategoryController::class, 'update'])->name('update');
Route::get('delete/{id}', [ChildSubCategoryController::class, 'delete'])->name('delete');
});
Route::prefix('banner-image')->name('bannerImage.')->group(function () {
Route::get('/', [BannerImagesController::class, 'index'])->name('index');
Route::get('/list', [BannerImagesController::class, 'list'])->name('list');
Route::post('main/create', [BannerImagesController::class, 'store'])->name('store');
Route::get('edit/{id}', [BannerImagesController::class, 'edit'])->name('edit');
Route::post('update/{id}', [BannerImagesController::class, 'update'])->name('update');
Route::get('delete/{id}', [BannerImagesController::class, 'delete'])->name('delete');
});
Route::prefix('hsn')->name('hsn.')->group(function () {
Route::get('/', [ChildSubCategoryController::class, 'index'])->name('index');
Route::get('create', [ChildSubCategoryController::class, 'create'])->name('create');
Route::post('store', [ChildSubCategoryController::class, 'store'])->name('store');
Route::get('edit/{id}', [ChildSubCategoryController::class, 'edit'])->name('edit');
Route::post('update/{id}', [ChildSubCategoryController::class, 'update'])->name('update');
Route::get('delete/{id}', [ChildSubCategoryController::class, 'delete'])->name('delete');
});
Route::prefix('hsncode')->name('hsncode.')->group(function () {
Route::get('/', [HsnCodeController::class, 'index'])->name('index');
Route::post('store', [HsnCodeController::class, 'store'])->name('store');
Route::get('edit/{id}', [HsnCodeController::class, 'show'])->name('edit');
Route::post('update/{id}', [HsnCodeController::class, 'update'])->name('update');
Route::get('delete/{id}', [HsnCodeController::class, 'destroy'])->name('delete');
});
Route::prefix('user')->name('user.')->group(function () {
Route::get('/', [UserController::class, 'index'])->name('index');
});
Route::prefix('marketing')->name('marketing.')->group(function () {
Route::get('/', [MarketingController::class, 'index'])->name('index');
});
Route::prefix('payment')->name('payment.')->group(function () {
Route::get('/', [PaymentController::class, 'index'])->name('index');
});
Route::prefix('wallet')->name('wallet.')->group(function () {
Route::get('/', [WalletController::class, 'index'])->name('index');
});
Route::prefix('referral')->name('referral.')->group(function () {
Route::get('/', [ReferralController::class, 'index'])->name('index');
});
Route::prefix('slider')->name('slider.')->group(function () {
Route::get('/', [SliderImageController::class, 'index'])->name('index');
Route::get('/index-ajax', [SliderImageController::class, 'indexAjax'])->name('indexAjax');
Route::post('store', [SliderImageController::class, 'store'])->name('store');
Route::post('update', [SliderImageController::class, 'update'])->name('update');
Route::get('/edit/{id}', [SliderImageController::class, 'edit'])->name('edit');
Route::get('/delete/{id}', [SliderImageController::class, 'delete'])->name('delete');
});
Route::group(['prefix' => 'product_approval', 'as' => 'product_approval.'], function () {
Route::get('/single_product_listing', [ProductApprovalController::class, 'index'])->name('index');
Route::get('/bulk_product_approval', [ProductApprovalController::class, 'bulk_product_approval'])->name('bulk_product_approval');
Route::post('store', [ProductController::class, 'store'])->name('store');
Route::get('qc_process', [ProductApprovalController::class, 'qcProcess'])->name('qcProcess');
Route::post('qc_process', [ProductApprovalController::class, 'qcProcessSubmit'])->name('qcProcess.submit');
Route::get('qc_error', [ProductApprovalController::class, 'qcError'])->name('qcError');
Route::get('qc_failed', [ProductApprovalController::class, 'qcFailed'])->name('qcFailed');
Route::get('qc_pass', [ProductApprovalController::class, 'qcPass'])->name('qcPass');
Route::post('qcPendingToProgress', [ProductApprovalController::class, 'qcPendingToProgress'])->name('qcPendingToProgress');
});
Route::group(['prefix' => 'order', 'as' => 'order.'], function () {
Route::get('/', [AdminOrderController::class, 'index'])->name('index');
});
Route::group(['prefix' => 'seller', 'as' => 'seller.'], function () {
Route::get('list', [SellerController::class, 'list'])->name('list');
Route::get('approval', [SellerController::class, 'approvedSeller'])->name('approval');
Route::get('/hold-seller', [SellerController::class, 'holdSeller'])->name('hold-seller');
Route::get('/un-hold-seller', [SellerController::class, 'unHoldSeller'])->name('un-hold-seller');
Route::get('render-sellers', [SellerController::class, 'holdSellerAjax'])->name('render_sellers');
Route::get('states-cities', [SellerController::class, 'statesCities'])->name('states_cities');
Route::post('/seller-hold', [SellerController::class, 'sellerHold'])->name('seller-hold');
Route::post('/seller-un-hold', [SellerController::class, 'sellerUnHold'])->name('seller-un-hold');
Route::post('/account-search', [SellerController::class, 'searchSellerAccounts'])->name('account-search');
Route::post('/seller-search-bar', [SellerController::class, 'searchBarSellerAccounts'])->name('seller-search-bar');
});
Route::group(['prefix' => 'role', 'as' => 'role.'], function () {
Route::get('/', [RolePermissionController::class, 'index'])->name('index');
Route::get('create', [RolePermissionController::class, 'create'])->name('create');
Route::post('store', [RolePermissionController::class, 'store'])->name('store');
Route::get('edit/{id}', [RolePermissionController::class, 'edit'])->name('edit');
Route::post('update', [RolePermissionController::class, 'update'])->name('update');
Route::delete('destroy', [RolePermissionController::class, 'destroy'])->name('destroy');
Route::get('create_permission', [RolePermissionController::class, 'createPermission'])->name('createPermission');
});
Route::group(['prefix' => 'support', 'as' => 'support.'], function () {
Route::get('/', [SupportController::class, 'admin'])->name('index');
Route::post('send-message', [SupportController::class, 'sendMessageAdmin'])->name('message.send-message');
Route::post('seller/info', [SupportController::class, 'SellerInfo'])->name('seller.info');
});
Route::group(['prefix' => 'logistic', 'as' => 'logistic.'], function () {
Route::get('/', [LogisticController::class, 'panding_payment'])->name('panding-payment');
Route::get('completed-payment', [LogisticController::class, 'completed_payment'])->name('completed-payment');
});
// Route::group(['prefix' => 'hsn', 'as' => 'hsn.'], function () {
// Route::post('/', [HsnCodeController::class, 'store'])->name('store');
// });
});
}); |
import { FC } from "react";
import TestItem from "./TestItem";
import { TestListProps } from "../types";
import Button from "./Button";
const headers = ["name", "type", "status", "site"];
const TestList: FC<TestListProps> = ({
tests,
handleSort,
sortDirection,
sortMethod,
handleResetButton,
}) => {
return (
<div className="dashboard-list-container">
{tests.length > 0 ? (
<table className="dashboard-list">
<thead>
<tr>
{headers.map((item) => (
<th
key={item}
colSpan={item === "SITE" ? 2 : 1}
onClick={() => {
handleSort(item);
}}
tabIndex={0}
>
<div>
{item}
{sortMethod === item && (
<svg
style={{
transform:
sortDirection === "asc" ? "rotate(180deg)" : "",
}}
width="7"
height="4"
viewBox="0 0 7 4"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M0 3.50001L3.13529 0.364716L3.5 7.15256e-06L3.86471 0.364716L7 3.50001L6.63529 3.86472L3.5 0.729424L0.364708 3.86472L0 3.50001Z"
fill="#999999"
/>
</svg>
)}
</div>
</th>
))}
</tr>
</thead>
<tbody>
{tests.map((item) => (
<TestItem key={item.id} {...item} />
))}
</tbody>
</table>
) : (
<div className="not-match">
<p>Your search did not match any results.</p>
<Button isGray={false} handleClick={handleResetButton}>
Reset
</Button>
</div>
)}
</div>
);
};
export default TestList; |
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserModule } from '../user/user.module';
import { User } from '../entities/user.entity';
import { LocalStrategy } from './strategies/local.strategy';
import { JwtModule } from '@nestjs/jwt';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtStrategy } from './strategies/jwt.strategy';
@Module({
imports: [
TypeOrmModule.forFeature([User]),
UserModule,
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
return {
secret: configService.get<string>('JWT_SECRET'),
signOptions: {
expiresIn: configService.get<string>('JWT_EXPIRATION_TIME'),
},
};
},
}),
],
controllers: [AuthController],
providers: [AuthService, LocalStrategy, JwtStrategy],
})
export class AuthModule {} |
---
id: 63ee352b0d8d4841c3a7091c
videoId: LGQuIIv2RVA
title: Основи CSS. Запитання C
challengeType: 15
dashedName: css-foundations-question-c
---
# --description--
Що робити, якщо у вас є дві групи елементів, які мають спільні оголошення стилів?
```css
.read {
color: white;
background-color: black;
/* several unique declarations */
}
.unread {
color: white;
background-color: black;
/* several unique declarations */
}
```
Обидва селектори (`.read` та `.unread`) мають спільні оголошення `color: white;` та `background-color: black;`, але окрім них вони мають декілька власних унікальних оголошень. Щоб зменшити повторення, ви можете згрупувати ці два селектори разом у вигляді списку, розділеного комами:
```css
.read,
.unread {
color: white;
background-color: black;
}
.read {
/* several unique declarations */
}
.unread {
/* several unique declarations */
}
```
Обидва наведені вище приклади (з групуванням і без нього) матимуть однаковий результат, але другий приклад зменшує повтори оголошень та полегшує одночасне редагування `color` чи `background-color` для обох класів.
# --question--
## --text--
Як би ви застосували одне правило до двох різних селекторів: `.red-box` та `.yellow-box`?
## --answers--
```css
.red-box,
.yellow-box {
width: 25px;
height: 25px;
}
```
---
```css
.red-box {
width: 25px;
height: 25px;
}
.yellow-box {
width: 25px;
height: 25px;
}
```
---
```css
.red-box {
width: 25px;
.yellow-box {
height: 25px;
}
}
```
## --video-solution--
1 |
import MySQLdb._exceptions
from django.shortcuts import render, redirect
# Create your views here.
from .models import PollingUnit, AnnouncedPuResult, LGA, State, Ward
from django.db.models import Sum
def polling_unit_result(request, polling_unit_id):
polling_unit = PollingUnit.objects.get(id=polling_unit_id)
results = AnnouncedPuResult.objects.filter(polling_unit=polling_unit)
return render(request, 'election_results/polling_unit_result.html',
{'polling_unit': polling_unit})
def lga_summed_results(request):
lgas = LGA.objects.all()
selected_lga = request.GET.get('lga', None)
if selected_lga:
polling_units = PollingUnit.objects.filter(ward__lga__id=selected_lga)
results = AnnouncedPuResult.objects.filter(polling_unit__in=polling_units) \
.values('party') \
.annotate(total_score=Sum('score'))
selected_lga_name = LGA.objects.get(id=selected_lga).name
else:
results = []
selected_lga_name = None
return render(request, 'election_results/lga_summed_results.html',
{'lgas': lgas, 'results': results, 'selected_lga': selected_lga,
'selected_lga_name': selected_lga_name})
def add_polling_unit_result(request):
states = State.objects.all()
if request.method == 'POST':
state_id = request.POST.get('state')
lga_id = request.POST.get('lga')
ward_id = request.POST.get('ward')
polling_unit_name = request.POST.get('polling_unit')
party = request.POST.get('party')
score = request.POST.get('score')
try:
state = State.objects.get(id=state_id)
lga = LGA.objects.get(id=lga_id)
ward = Ward.objects.get(id=ward_id)
polling_unit, created = PollingUnit.objects.get_or_create(name=polling_unit_name, ward=ward)
AnnouncedPuResult.objects.create(polling_unit=polling_unit, party=party, score=score)
# Redirect to a success page or perform any other desired action
return redirect('success_page')
except MySQLdb._exceptions.IntegrityError:
error_message = "Result for this party already exists for the selected polling unit."
else:
error_message = None
return render(request, 'election_results/add_polling_unit_result.html',
{'states': states, 'error_message': error_message}) |
/**
* ***************************************************************************** Turnstone Biologics
* Confidential
*
* <p>2018 Turnstone Biologics All Rights Reserved.
*
* <p>This file is subject to the terms and conditions defined in file 'license.txt', which is part
* of this source code package.
*
* <p>Contributors : Turnstone Biologics - General Release
* ****************************************************************************
*/
package com.occulue.europeanstandards.commongridmodelexchangestandard.dynamicsprofile.standardmodels.turbinegovernordynamics.projector;
import com.occulue.api.*;
import com.occulue.entity.*;
import com.occulue.europeanstandards.commongridmodelexchangestandard.dynamicsprofile.standardmodels.turbinegovernordynamics.repository.*;
import com.occulue.exception.*;
import java.util.*;
import java.util.logging.Logger;
import org.axonframework.eventhandling.EventHandler;
import org.axonframework.queryhandling.QueryHandler;
import org.axonframework.queryhandling.QueryUpdateEmitter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Projector for GovHydro3 as outlined for the CQRS pattern. All event handling and query handling
* related to GovHydro3 are invoked here and dispersed as an event to be handled elsewhere.
*
* <p>Commands are handled by GovHydro3Aggregate
*
* @author your_name_here
*/
// @ProcessingGroup("govHydro3")
@Component("govHydro3-projector")
public class GovHydro3Projector extends GovHydro3EntityProjector {
// core constructor
public GovHydro3Projector(GovHydro3Repository repository, QueryUpdateEmitter queryUpdateEmitter) {
super(repository);
this.queryUpdateEmitter = queryUpdateEmitter;
}
/*
* @param event CreateGovHydro3Event
*/
@EventHandler(payloadType = CreateGovHydro3Event.class)
public void handle(CreateGovHydro3Event event) {
LOGGER.info("handling CreateGovHydro3Event - " + event);
GovHydro3 entity = new GovHydro3();
entity.setGovHydro3Id(event.getGovHydro3Id());
// ------------------------------------------
// persist a new one
// ------------------------------------------
create(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UpdateGovHydro3Event
*/
@EventHandler(payloadType = UpdateGovHydro3Event.class)
public void handle(UpdateGovHydro3Event event) {
LOGGER.info("handling UpdateGovHydro3Event - " + event);
GovHydro3 entity = new GovHydro3();
entity.setGovHydro3Id(event.getGovHydro3Id());
entity.setAt(event.getAt());
entity.setDb1(event.getDb1());
entity.setDb2(event.getDb2());
entity.setDturb(event.getDturb());
entity.setEps(event.getEps());
entity.setGovernorControl(event.getGovernorControl());
entity.setGv1(event.getGv1());
entity.setGv2(event.getGv2());
entity.setGv3(event.getGv3());
entity.setGv4(event.getGv4());
entity.setGv5(event.getGv5());
entity.setGv6(event.getGv6());
entity.setH0(event.getH0());
entity.setK1(event.getK1());
entity.setK2(event.getK2());
entity.setKg(event.getKg());
entity.setKi(event.getKi());
entity.setMwbase(event.getMwbase());
entity.setPgv1(event.getPgv1());
entity.setPgv2(event.getPgv2());
entity.setPgv3(event.getPgv3());
entity.setPgv4(event.getPgv4());
entity.setPgv5(event.getPgv5());
entity.setPgv6(event.getPgv6());
entity.setPmax(event.getPmax());
entity.setPmin(event.getPmin());
entity.setQnl(event.getQnl());
entity.setRelec(event.getRelec());
entity.setRgate(event.getRgate());
entity.setTd(event.getTd());
entity.setTf(event.getTf());
entity.setTp(event.getTp());
entity.setTt(event.getTt());
entity.setTw(event.getTw());
entity.setVelcl(event.getVelcl());
entity.setVelop(event.getVelop());
// ------------------------------------------
// save with an existing instance
// ------------------------------------------
update(entity);
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event DeleteGovHydro3Event
*/
@EventHandler(payloadType = DeleteGovHydro3Event.class)
public void handle(DeleteGovHydro3Event event) {
LOGGER.info("handling DeleteGovHydro3Event - " + event);
// ------------------------------------------
// delete delegation
// ------------------------------------------
GovHydro3 entity = delete(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignAtToGovHydro3Event
*/
@EventHandler(payloadType = AssignAtToGovHydro3Event.class)
public void handle(AssignAtToGovHydro3Event event) {
LOGGER.info("handling AssignAtToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignAt(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignAtFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignAtFromGovHydro3Event.class)
public void handle(UnAssignAtFromGovHydro3Event event) {
LOGGER.info("handling UnAssignAtFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignAt(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignDb1ToGovHydro3Event
*/
@EventHandler(payloadType = AssignDb1ToGovHydro3Event.class)
public void handle(AssignDb1ToGovHydro3Event event) {
LOGGER.info("handling AssignDb1ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignDb1(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignDb1FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignDb1FromGovHydro3Event.class)
public void handle(UnAssignDb1FromGovHydro3Event event) {
LOGGER.info("handling UnAssignDb1FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignDb1(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignDb2ToGovHydro3Event
*/
@EventHandler(payloadType = AssignDb2ToGovHydro3Event.class)
public void handle(AssignDb2ToGovHydro3Event event) {
LOGGER.info("handling AssignDb2ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignDb2(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignDb2FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignDb2FromGovHydro3Event.class)
public void handle(UnAssignDb2FromGovHydro3Event event) {
LOGGER.info("handling UnAssignDb2FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignDb2(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignDturbToGovHydro3Event
*/
@EventHandler(payloadType = AssignDturbToGovHydro3Event.class)
public void handle(AssignDturbToGovHydro3Event event) {
LOGGER.info("handling AssignDturbToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignDturb(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignDturbFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignDturbFromGovHydro3Event.class)
public void handle(UnAssignDturbFromGovHydro3Event event) {
LOGGER.info("handling UnAssignDturbFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignDturb(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignEpsToGovHydro3Event
*/
@EventHandler(payloadType = AssignEpsToGovHydro3Event.class)
public void handle(AssignEpsToGovHydro3Event event) {
LOGGER.info("handling AssignEpsToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignEps(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignEpsFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignEpsFromGovHydro3Event.class)
public void handle(UnAssignEpsFromGovHydro3Event event) {
LOGGER.info("handling UnAssignEpsFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignEps(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignGovernorControlToGovHydro3Event
*/
@EventHandler(payloadType = AssignGovernorControlToGovHydro3Event.class)
public void handle(AssignGovernorControlToGovHydro3Event event) {
LOGGER.info("handling AssignGovernorControlToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignGovernorControl(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignGovernorControlFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignGovernorControlFromGovHydro3Event.class)
public void handle(UnAssignGovernorControlFromGovHydro3Event event) {
LOGGER.info("handling UnAssignGovernorControlFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignGovernorControl(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignGv1ToGovHydro3Event
*/
@EventHandler(payloadType = AssignGv1ToGovHydro3Event.class)
public void handle(AssignGv1ToGovHydro3Event event) {
LOGGER.info("handling AssignGv1ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignGv1(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignGv1FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignGv1FromGovHydro3Event.class)
public void handle(UnAssignGv1FromGovHydro3Event event) {
LOGGER.info("handling UnAssignGv1FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignGv1(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignGv2ToGovHydro3Event
*/
@EventHandler(payloadType = AssignGv2ToGovHydro3Event.class)
public void handle(AssignGv2ToGovHydro3Event event) {
LOGGER.info("handling AssignGv2ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignGv2(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignGv2FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignGv2FromGovHydro3Event.class)
public void handle(UnAssignGv2FromGovHydro3Event event) {
LOGGER.info("handling UnAssignGv2FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignGv2(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignGv3ToGovHydro3Event
*/
@EventHandler(payloadType = AssignGv3ToGovHydro3Event.class)
public void handle(AssignGv3ToGovHydro3Event event) {
LOGGER.info("handling AssignGv3ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignGv3(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignGv3FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignGv3FromGovHydro3Event.class)
public void handle(UnAssignGv3FromGovHydro3Event event) {
LOGGER.info("handling UnAssignGv3FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignGv3(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignGv4ToGovHydro3Event
*/
@EventHandler(payloadType = AssignGv4ToGovHydro3Event.class)
public void handle(AssignGv4ToGovHydro3Event event) {
LOGGER.info("handling AssignGv4ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignGv4(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignGv4FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignGv4FromGovHydro3Event.class)
public void handle(UnAssignGv4FromGovHydro3Event event) {
LOGGER.info("handling UnAssignGv4FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignGv4(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignGv5ToGovHydro3Event
*/
@EventHandler(payloadType = AssignGv5ToGovHydro3Event.class)
public void handle(AssignGv5ToGovHydro3Event event) {
LOGGER.info("handling AssignGv5ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignGv5(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignGv5FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignGv5FromGovHydro3Event.class)
public void handle(UnAssignGv5FromGovHydro3Event event) {
LOGGER.info("handling UnAssignGv5FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignGv5(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignGv6ToGovHydro3Event
*/
@EventHandler(payloadType = AssignGv6ToGovHydro3Event.class)
public void handle(AssignGv6ToGovHydro3Event event) {
LOGGER.info("handling AssignGv6ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignGv6(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignGv6FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignGv6FromGovHydro3Event.class)
public void handle(UnAssignGv6FromGovHydro3Event event) {
LOGGER.info("handling UnAssignGv6FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignGv6(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignH0ToGovHydro3Event
*/
@EventHandler(payloadType = AssignH0ToGovHydro3Event.class)
public void handle(AssignH0ToGovHydro3Event event) {
LOGGER.info("handling AssignH0ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignH0(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignH0FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignH0FromGovHydro3Event.class)
public void handle(UnAssignH0FromGovHydro3Event event) {
LOGGER.info("handling UnAssignH0FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignH0(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignK1ToGovHydro3Event
*/
@EventHandler(payloadType = AssignK1ToGovHydro3Event.class)
public void handle(AssignK1ToGovHydro3Event event) {
LOGGER.info("handling AssignK1ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignK1(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignK1FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignK1FromGovHydro3Event.class)
public void handle(UnAssignK1FromGovHydro3Event event) {
LOGGER.info("handling UnAssignK1FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignK1(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignK2ToGovHydro3Event
*/
@EventHandler(payloadType = AssignK2ToGovHydro3Event.class)
public void handle(AssignK2ToGovHydro3Event event) {
LOGGER.info("handling AssignK2ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignK2(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignK2FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignK2FromGovHydro3Event.class)
public void handle(UnAssignK2FromGovHydro3Event event) {
LOGGER.info("handling UnAssignK2FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignK2(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignKgToGovHydro3Event
*/
@EventHandler(payloadType = AssignKgToGovHydro3Event.class)
public void handle(AssignKgToGovHydro3Event event) {
LOGGER.info("handling AssignKgToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignKg(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignKgFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignKgFromGovHydro3Event.class)
public void handle(UnAssignKgFromGovHydro3Event event) {
LOGGER.info("handling UnAssignKgFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignKg(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignKiToGovHydro3Event
*/
@EventHandler(payloadType = AssignKiToGovHydro3Event.class)
public void handle(AssignKiToGovHydro3Event event) {
LOGGER.info("handling AssignKiToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignKi(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignKiFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignKiFromGovHydro3Event.class)
public void handle(UnAssignKiFromGovHydro3Event event) {
LOGGER.info("handling UnAssignKiFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignKi(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignMwbaseToGovHydro3Event
*/
@EventHandler(payloadType = AssignMwbaseToGovHydro3Event.class)
public void handle(AssignMwbaseToGovHydro3Event event) {
LOGGER.info("handling AssignMwbaseToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignMwbase(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignMwbaseFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignMwbaseFromGovHydro3Event.class)
public void handle(UnAssignMwbaseFromGovHydro3Event event) {
LOGGER.info("handling UnAssignMwbaseFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignMwbase(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignPgv1ToGovHydro3Event
*/
@EventHandler(payloadType = AssignPgv1ToGovHydro3Event.class)
public void handle(AssignPgv1ToGovHydro3Event event) {
LOGGER.info("handling AssignPgv1ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignPgv1(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignPgv1FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignPgv1FromGovHydro3Event.class)
public void handle(UnAssignPgv1FromGovHydro3Event event) {
LOGGER.info("handling UnAssignPgv1FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignPgv1(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignPgv2ToGovHydro3Event
*/
@EventHandler(payloadType = AssignPgv2ToGovHydro3Event.class)
public void handle(AssignPgv2ToGovHydro3Event event) {
LOGGER.info("handling AssignPgv2ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignPgv2(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignPgv2FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignPgv2FromGovHydro3Event.class)
public void handle(UnAssignPgv2FromGovHydro3Event event) {
LOGGER.info("handling UnAssignPgv2FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignPgv2(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignPgv3ToGovHydro3Event
*/
@EventHandler(payloadType = AssignPgv3ToGovHydro3Event.class)
public void handle(AssignPgv3ToGovHydro3Event event) {
LOGGER.info("handling AssignPgv3ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignPgv3(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignPgv3FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignPgv3FromGovHydro3Event.class)
public void handle(UnAssignPgv3FromGovHydro3Event event) {
LOGGER.info("handling UnAssignPgv3FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignPgv3(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignPgv4ToGovHydro3Event
*/
@EventHandler(payloadType = AssignPgv4ToGovHydro3Event.class)
public void handle(AssignPgv4ToGovHydro3Event event) {
LOGGER.info("handling AssignPgv4ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignPgv4(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignPgv4FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignPgv4FromGovHydro3Event.class)
public void handle(UnAssignPgv4FromGovHydro3Event event) {
LOGGER.info("handling UnAssignPgv4FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignPgv4(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignPgv5ToGovHydro3Event
*/
@EventHandler(payloadType = AssignPgv5ToGovHydro3Event.class)
public void handle(AssignPgv5ToGovHydro3Event event) {
LOGGER.info("handling AssignPgv5ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignPgv5(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignPgv5FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignPgv5FromGovHydro3Event.class)
public void handle(UnAssignPgv5FromGovHydro3Event event) {
LOGGER.info("handling UnAssignPgv5FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignPgv5(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignPgv6ToGovHydro3Event
*/
@EventHandler(payloadType = AssignPgv6ToGovHydro3Event.class)
public void handle(AssignPgv6ToGovHydro3Event event) {
LOGGER.info("handling AssignPgv6ToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignPgv6(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignPgv6FromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignPgv6FromGovHydro3Event.class)
public void handle(UnAssignPgv6FromGovHydro3Event event) {
LOGGER.info("handling UnAssignPgv6FromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignPgv6(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignPmaxToGovHydro3Event
*/
@EventHandler(payloadType = AssignPmaxToGovHydro3Event.class)
public void handle(AssignPmaxToGovHydro3Event event) {
LOGGER.info("handling AssignPmaxToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignPmax(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignPmaxFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignPmaxFromGovHydro3Event.class)
public void handle(UnAssignPmaxFromGovHydro3Event event) {
LOGGER.info("handling UnAssignPmaxFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignPmax(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignPminToGovHydro3Event
*/
@EventHandler(payloadType = AssignPminToGovHydro3Event.class)
public void handle(AssignPminToGovHydro3Event event) {
LOGGER.info("handling AssignPminToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignPmin(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignPminFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignPminFromGovHydro3Event.class)
public void handle(UnAssignPminFromGovHydro3Event event) {
LOGGER.info("handling UnAssignPminFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignPmin(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignQnlToGovHydro3Event
*/
@EventHandler(payloadType = AssignQnlToGovHydro3Event.class)
public void handle(AssignQnlToGovHydro3Event event) {
LOGGER.info("handling AssignQnlToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignQnl(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignQnlFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignQnlFromGovHydro3Event.class)
public void handle(UnAssignQnlFromGovHydro3Event event) {
LOGGER.info("handling UnAssignQnlFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignQnl(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignRelecToGovHydro3Event
*/
@EventHandler(payloadType = AssignRelecToGovHydro3Event.class)
public void handle(AssignRelecToGovHydro3Event event) {
LOGGER.info("handling AssignRelecToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignRelec(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignRelecFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignRelecFromGovHydro3Event.class)
public void handle(UnAssignRelecFromGovHydro3Event event) {
LOGGER.info("handling UnAssignRelecFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignRelec(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignRgateToGovHydro3Event
*/
@EventHandler(payloadType = AssignRgateToGovHydro3Event.class)
public void handle(AssignRgateToGovHydro3Event event) {
LOGGER.info("handling AssignRgateToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignRgate(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignRgateFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignRgateFromGovHydro3Event.class)
public void handle(UnAssignRgateFromGovHydro3Event event) {
LOGGER.info("handling UnAssignRgateFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignRgate(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignTdToGovHydro3Event
*/
@EventHandler(payloadType = AssignTdToGovHydro3Event.class)
public void handle(AssignTdToGovHydro3Event event) {
LOGGER.info("handling AssignTdToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignTd(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignTdFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignTdFromGovHydro3Event.class)
public void handle(UnAssignTdFromGovHydro3Event event) {
LOGGER.info("handling UnAssignTdFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignTd(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignTfToGovHydro3Event
*/
@EventHandler(payloadType = AssignTfToGovHydro3Event.class)
public void handle(AssignTfToGovHydro3Event event) {
LOGGER.info("handling AssignTfToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignTf(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignTfFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignTfFromGovHydro3Event.class)
public void handle(UnAssignTfFromGovHydro3Event event) {
LOGGER.info("handling UnAssignTfFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignTf(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignTpToGovHydro3Event
*/
@EventHandler(payloadType = AssignTpToGovHydro3Event.class)
public void handle(AssignTpToGovHydro3Event event) {
LOGGER.info("handling AssignTpToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignTp(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignTpFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignTpFromGovHydro3Event.class)
public void handle(UnAssignTpFromGovHydro3Event event) {
LOGGER.info("handling UnAssignTpFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignTp(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignTtToGovHydro3Event
*/
@EventHandler(payloadType = AssignTtToGovHydro3Event.class)
public void handle(AssignTtToGovHydro3Event event) {
LOGGER.info("handling AssignTtToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignTt(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignTtFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignTtFromGovHydro3Event.class)
public void handle(UnAssignTtFromGovHydro3Event event) {
LOGGER.info("handling UnAssignTtFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignTt(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignTwToGovHydro3Event
*/
@EventHandler(payloadType = AssignTwToGovHydro3Event.class)
public void handle(AssignTwToGovHydro3Event event) {
LOGGER.info("handling AssignTwToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignTw(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignTwFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignTwFromGovHydro3Event.class)
public void handle(UnAssignTwFromGovHydro3Event event) {
LOGGER.info("handling UnAssignTwFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignTw(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignVelclToGovHydro3Event
*/
@EventHandler(payloadType = AssignVelclToGovHydro3Event.class)
public void handle(AssignVelclToGovHydro3Event event) {
LOGGER.info("handling AssignVelclToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignVelcl(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignVelclFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignVelclFromGovHydro3Event.class)
public void handle(UnAssignVelclFromGovHydro3Event event) {
LOGGER.info("handling UnAssignVelclFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignVelcl(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event AssignVelopToGovHydro3Event
*/
@EventHandler(payloadType = AssignVelopToGovHydro3Event.class)
public void handle(AssignVelopToGovHydro3Event event) {
LOGGER.info("handling AssignVelopToGovHydro3Event - " + event);
// ------------------------------------------
// delegate to assignTo
// ------------------------------------------
GovHydro3 entity = assignVelop(event.getGovHydro3Id(), event.getAssignment());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/*
* @param event UnAssignVelopFromGovHydro3Event
*/
@EventHandler(payloadType = UnAssignVelopFromGovHydro3Event.class)
public void handle(UnAssignVelopFromGovHydro3Event event) {
LOGGER.info("handling UnAssignVelopFromGovHydro3Event - " + event);
// ------------------------------------------
// delegate to unAssignFrom
// ------------------------------------------
GovHydro3 entity = unAssignVelop(event.getGovHydro3Id());
// ------------------------------------------
// emit to subscribers that find one
// ------------------------------------------
emitFindGovHydro3(entity);
// ------------------------------------------
// emit to subscribers that find all
// ------------------------------------------
emitFindAllGovHydro3(entity);
}
/**
* Method to retrieve the GovHydro3 via an GovHydro3PrimaryKey.
*
* @param id Long
* @return GovHydro3
* @exception ProcessingException - Thrown if processing any related problems
* @exception IllegalArgumentException
*/
@SuppressWarnings("unused")
@QueryHandler
public GovHydro3 handle(FindGovHydro3Query query)
throws ProcessingException, IllegalArgumentException {
return find(query.getFilter().getGovHydro3Id());
}
/**
* Method to retrieve a collection of all GovHydro3s
*
* @param query FindAllGovHydro3Query
* @return List<GovHydro3>
* @exception ProcessingException Thrown if any problems
*/
@SuppressWarnings("unused")
@QueryHandler
public List<GovHydro3> handle(FindAllGovHydro3Query query) throws ProcessingException {
return findAll(query);
}
/**
* emit to subscription queries of type FindGovHydro3, but only if the id matches
*
* @param entity GovHydro3
*/
protected void emitFindGovHydro3(GovHydro3 entity) {
LOGGER.info("handling emitFindGovHydro3");
queryUpdateEmitter.emit(
FindGovHydro3Query.class,
query -> query.getFilter().getGovHydro3Id().equals(entity.getGovHydro3Id()),
entity);
}
/**
* unconditionally emit to subscription queries of type FindAllGovHydro3
*
* @param entity GovHydro3
*/
protected void emitFindAllGovHydro3(GovHydro3 entity) {
LOGGER.info("handling emitFindAllGovHydro3");
queryUpdateEmitter.emit(FindAllGovHydro3Query.class, query -> true, entity);
}
// --------------------------------------------------
// attributes
// --------------------------------------------------
@Autowired private final QueryUpdateEmitter queryUpdateEmitter;
private static final Logger LOGGER = Logger.getLogger(GovHydro3Projector.class.getName());
} |
"""
A driver for esg_grid.
"""
from pathlib import Path
from typing import List, Optional
from iotaa import asset, task, tasks
from uwtools.config.formats.nml import NMLConfig
from uwtools.drivers.driver import Driver
from uwtools.strings import STR
from uwtools.utils.tasks import file
class ESGGrid(Driver):
"""
A driver for esg_grid.
"""
def __init__(
self,
config: Optional[Path] = None,
dry_run: bool = False,
batch: bool = False,
key_path: Optional[List[str]] = None,
):
"""
The driver.
:param config: Path to config file (read stdin if missing or None).
:param dry_run: Run in dry-run mode?
:param batch: Run component via the batch system?
:param key_path: Keys leading through the config to the driver's configuration block.
"""
super().__init__(config=config, dry_run=dry_run, batch=batch, key_path=key_path)
# Workflow tasks
@task
def namelist_file(self):
"""
The namelist file.
"""
fn = "regional_grid.nml"
yield self._taskname(fn)
path = self._rundir / fn
yield asset(path, path.is_file)
base_file = self._driver_config["namelist"].get("base_file")
yield file(Path(base_file)) if base_file else None
self._create_user_updated_config(
config_class=NMLConfig,
config_values=self._driver_config["namelist"],
path=path,
schema=self._namelist_schema(schema_keys=["$defs", "namelist_content"]),
)
@tasks
def provisioned_run_directory(self):
"""
Run directory provisioned with all required content.
"""
yield self._taskname("provisioned run directory")
yield [
self.namelist_file(),
self.runscript(),
]
@task
def runscript(self):
"""
The runscript.
"""
path = self._runscript_path
yield self._taskname(path.name)
yield asset(path, path.is_file)
yield None
self._write_runscript(path)
# Private helper methods
@property
def _driver_name(self) -> str:
"""
Returns the name of this driver.
"""
return STR.esggrid |
import React from 'react'
import { Link } from 'react-router-dom'
export const HeroCard = ({
id,
superhero,
alter_ego,
first_appearance,
characters
}) => {
return (
<div className="card ms-3">
<div className="row no-gutters">
<div className="col-md-4">
<img
src={`./assets/heroes/${id}.jpg`}
alt={superhero}
className="card-img"
/>
</div>
<div className="col-md-8">
<div className="card-body">
<h5 className="card-title"> {superhero} </h5>
<p className="card-text"> {alter_ego} </p>
{
(alter_ego !== characters) &&
<p className="card-text"> {characters} </p>
}
<p className="card-text">
<small className="text-muted"> {first_appearance} </small>
</p>
<Link to={`./hero/${ id }`} > Show more. </Link>
</div>
</div>
</div>
</div>
)
} |
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="https://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link th:href="@{/styles/styles.css}" rel="stylesheet" type="text/css"/>
<title>Edit Subject</title>
</head>
<body style="padding: 40px">
<div th:replace="~{fragments/header}"></div>
<div class="container-fluid" style="padding: 40px">
<div class="row vertical-center" style="max-width: 700px">
<h2>Edit Subject</h2>
<form th:action="@{/subject/{id}(id=${subjectDto.id})}" th:object="${subjectDto}" th:method="put">
<input type="hidden" th:field="*{id}"/>
<div class="form-group">
<!-- Edit name option for admin-->
<div class="form-group" sec:authorize="hasAuthority('admin')">
<label>Edit Name</label>
<p><input type="text" th:field="*{name}" required pattern="^(?!\s*$).+"
onmouseover="showPopup()" onmouseout="hidePopup()"/></p>
<!-- popup-->
<div id="editSubjectNamePopup" class="popup">
<p>Use 2 or more letters, numbers or symbols, do not leave this field empty or filled with
whitespaces</p>
</div>
<script>
function showPopup() {
var popup = document.getElementById("editSubjectNamePopup");
popup.style.display = "block";
}
function hidePopup() {
var popup = document.getElementById("editSubjectNamePopup");
popup.style.display = "none";
}
</script>
</div>
<!-- Edit name option for professor-->
<div class="form-group" sec:authorize="hasAuthority('professor') && !hasAuthority('admin')">
<label>Name: <span th:text="*{name}"></span></label>
<input type="hidden" th:field="*{name}" th:value="*{name}"/>
</div>
<!-- Edit descr option for admin-->
<div class="form-group" sec:authorize="hasAuthority('admin')">
<label for="comment">Edit Description</label>
<textarea class="form-control" rows="5" id="comment" th:field="*{description}"
placeholder="Type new description here"></textarea>
</div>
<!-- Edit descr option for professor-->
<div class="form-group" sec:authorize="hasAuthority('professor') && !hasAuthority('admin')">
<label>Description: </label>
<p><span th:text="*{description}"></span></p>
<input type="hidden" th:field="*{description}" th:value="*{description}"/>
</div>
<div class="form-group">
<label>Classroom</label>
<div class="form-group">
<select th:field="${subjectDto.classroomDto.name}">
<option th:each="classroom : ${freeClassrooms}" th:value="${classroom.name}"
th:text="${classroom.name}">
</option>
<option th:value="*{classroomDto.name}" th:text="*{classroomDto.name + ' (current)'}"
selected></option>
<option th:value="null" th:text="'(no classroom)'"></option>
</select>
</div>
</div>
<!-- if no free professor available-->
<div th:if="${freeProfessors.isEmpty()}" class="form-group" sec:authorize="hasAuthority('admin')">
<p>Can't find any free professor to assign to this subject</p>
<p th:if="*{userDto != null}">
Current professor: <span th:text="*{userDto.firstName + ' ' + userDto.lastName}"></span>
</p>
<p>Add new user with role 'professor' if you'd change a professor for this subject</p>
</div>
<!-- if a free professor available-->
<div th:if="${!freeProfessors.isEmpty()}" class="form-group" sec:authorize="hasAuthority('admin')">
<label>Professor</label>
<div>
<select th:field="*{userDto.username}">
<option th:each="user : ${freeProfessors}" th:value="${user.username}"
th:text="${user.firstName + ' ' + user.lastName}"></option>
<option th:value="*{userDto.username}"
th:text="*{userDto.firstName + ' ' + userDto.lastName + ' (current)'}"
selected></option>
<option th:value="null" th:text="'(no professor)'"></option>
</select>
</div>
</div>
<!-- Edit professor for the subject option for professor-->
<div th:if="${!freeProfessors.isEmpty()}" class="form-group" sec:authorize="hasAuthority('professor') && !hasAuthority('admin')">
<label>Professor</label>
<div>
<input type="hidden" th:field="*{userDto.username}" th:value="*{userDto.username}">
</div>
</div>
<div>
<p><input type="submit" value="Submit" class="btn btn-success"/></p>
</div>
</div>
</form>
</div>
</div>
</body>
</html> |
import React, { useState, useEffect } from "react";
import styles from "./Filter.module.scss";
import { Select, Button, Link, Input, SuggestComponent } from "components";
import search from "assets/icons/search.svg";
import store from "redux/stores";
import { useSelector } from "react-redux";
import { axiosAPI } from "plugins/axios";
function Filter() {
const city = useSelector((state) => state.city);
const [result, setResult] = useState([]);
const [age, setAge] = useState([]);
const [gender, setGender] = useState([]);
const [cost, setCost] = useState([]);
const [addr, setAddress] = useState("");
const [category, setCategory] = useState("");
const [other, setOther] = useState([]);
const [name, setName] = useState("");
const [fieldWidth, setFieldWidth] = useState("");
const [selectWidth, setSelectWidth] = useState("");
const [prependWidth, setPrependWidth] = useState("");
const getCategories = async () => {
const categories = await axiosAPI.getCategories(city);
setResult(categories);
};
useEffect(() => {
getCategories();
let tab = "all";
if (cost.length === 1) {
tab = cost[0];
}
store.dispatch({ type: "ChangeTab", amount: tab });
let sex = "any";
if (gender.length === 1) {
sex = gender[0];
}
let isInSummer = "";
let inNotSummer = "";
for (let i = 0; i < other.length; i++) {
switch (other[i]) {
case "isInSummer":
isInSummer = true;
break;
case "inNotSummer":
inNotSummer = true;
break;
}
}
store.dispatch({
type: "SetParamsForCatalogue",
amount: {
name,
age,
sex,
addr,
isInSummer,
inNotSummer,
},
});
}, [name, age, gender, cost, addr, other, city]);
const setDynamicWidth = () => {
let windowWidth = window.outerWidth;
if (windowWidth > 1200) {
setFieldWidth("" + windowWidth / 8.8 + "px");
setSelectWidth("" + windowWidth / 8.8 + "px");
} else {
setFieldWidth("175px");
setSelectWidth("195px");
}
if (windowWidth > 1200 && windowWidth < 1400) {
setPrependWidth("" + windowWidth / 55 + "px");
} else {
setPrependWidth("28.75px");
}
};
useEffect(() => {
setDynamicWidth();
function handleWindowResize() {
setDynamicWidth();
}
window.addEventListener("resize", handleWindowResize);
return () => {
window.removeEventListener("resize", handleWindowResize);
};
}, []);
return (
<section className={styles["filter-wrapper"]}>
{prependWidth !== "" ? (
<div>
<section className={styles.filter}>
<Input
border="none"
type="text"
placeholder="Занятие"
prepend={
<img
src="\images\Name.png"
width={prependWidth}
alt="Название"
/>
}
onChange={(e) => setName(e.target.value)}
inputWidth={fieldWidth}
/>
<Select
placeholder="Возраст"
value={age}
options={[
{ text: "1 год", value: "1" },
{ text: "2 года", value: "2" },
{ text: "3 года", value: "3" },
{ text: "4 года", value: "4" },
{ text: "5 лет", value: "5" },
{ text: "6 лет", value: "6" },
{ text: "7 лет", value: "7" },
{ text: "8 лет", value: "8" },
{ text: "9 лет", value: "9" },
{ text: "10 лет", value: "10" },
{ text: "11 лет", value: "11" },
{ text: "12 лет", value: "12" },
{ text: "13 лет", value: "13" },
{ text: "14 лет", value: "14" },
{ text: "15 лет", value: "15" },
{ text: "16 лет", value: "16" },
{ text: "17 лет", value: "17" },
{ text: "18 лет", value: "18" },
{ text: "Старше 18", value: "bigger" },
]}
checkbox
selectWidth={selectWidth}
prepend={
<img src="\images\Age.png" width={prependWidth} alt="Возраст" />
}
zIndex="6"
onChange={(value) => setAge(value)}
/>
<Select
placeholder="Стоимость"
value={cost}
options={[
{ text: "Платные", value: "pay" },
{ text: "Бесплатные", value: "free" },
]}
checkbox
selectWidth={selectWidth}
prepend={
<img
src="\images\Cost.png"
width={prependWidth}
alt="Стоимость"
/>
}
zIndex="5"
onChange={(value) => setCost(value)}
/>
<SuggestComponent
className={styles.suggest}
value={addr}
handler={setAddress}
border={"none"}
placeholder={"Адрес"}
prepend={
<img src="\images\Address.png" height={"25px"} alt="Адрес" />
}
isCitySet={true}
isNotExact={true}
/>
<Select
placeholder="Категории"
value={category}
options={
Array.isArray(result)
? result.map((category) => {
return {
text: category.baseCategory.name,
value: category.baseCategory.name,
};
})
: {}
}
prepend={
<img
src="\images\Categories.png"
width={prependWidth}
alt="Категории"
/>
}
selectWidth={selectWidth}
zIndex="3"
onChange={(value) => setCategory(value)}
/>
<Select
placeholder="Другое"
value={other}
options={[
{ text: "Работает сент-май", value: "inNotSummer" },
{ text: "Работает летом", value: "isInSummer" },
]}
checkbox
selectWidth={selectWidth}
prepend={
<img
src="\images\Other.png"
width={prependWidth}
alt="Другое"
/>
}
zIndex="2"
onChange={(value) => setOther(value)}
/>
</section>
<section className={styles["btn-section"]}>
<Link path={`/catalogue/${city}/${category}`}>
<Button
width="239px"
background="linear-gradient(90deg, #FBA405 -5.91%, #FDC21E 115.61%)"
>
<img
style={{ marginRight: "8px" }}
src={search}
height="20px"
alt="Подобрать"
/>
Подобрать
</Button>
</Link>
</section>
</div>
) : (
<></>
)}
</section>
);
}
export { Filter }; |
package org.code.protocol.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.code.common.RpcRequest;
import org.code.common.RpcResponse;
import org.code.common.constants.MsgType;
import org.code.common.constants.ProtocolConstants;
import org.code.protocol.MsgHeader;
import org.code.protocol.RpcProtocol;
import org.code.protocol.serialization.RpcSerialization;
import org.code.protocol.serialization.SerializationFactory;
import java.util.List;
/**
* The type Rpc decoder.
*/
public class RpcDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
// If the number of readable bytes is less than the length of the protocol header, it means that the entire protocol header has not been received, and returns directly
if (in. readableBytes() < ProtocolConstants. HEADER_TOTAL_LEN) {
return;
}
// Mark the current reading position for easy rollback later
in.markReaderIndex();
// read the magic number field
short magic = in. readShort();
if (magic != ProtocolConstants. MAGIC) {
throw new IllegalArgumentException("magic number is illegal, " + magic);
}
// read the version field
byte version = in. readByte();
// read message type
byte msgType = in. readByte();
// read response status
byte status = in. readByte();
// read request ID
long requestId = in. readLong();
// Get the length of the serialization algorithm
final int len = in. readInt();
if (in. readableBytes() < len) {
in.resetReaderIndex();
return;
}
final byte[] bytes = new byte[len];
in. readBytes(bytes);
final String serialization = new String(bytes);
// read message body length
int dataLength = in. readInt();
// If the number of readable bytes is less than the length of the message body, it means that the entire message body has not been received, roll back and return
if (in. readableBytes() < dataLength) {
// rollback mark position
in.resetReaderIndex();
return;
}
byte[] data = new byte[dataLength];
// read data
in. readBytes(data);
// type of message to be processed
MsgType msgTypeEnum = MsgType.findByType(msgType);
if (msgTypeEnum == null) {
return;
}
// build message header
MsgHeader header = new MsgHeader();
header. setMagic(magic);
header. setVersion(version);
header. setStatus(status);
header.setRequestId(requestId);
header.setMsgType(msgType);
header.setSerializations(bytes);
header.setSerializationLen(len);
header.setMsgLen(dataLength);
// get the serializer
RpcSerialization rpcSerialization = SerializationFactory. get(serialization);
// Process according to the message type (if there are too many message types, you can use strategy + factory mode to manage)
switch (msgTypeEnum) {
// request message
case REQUEST:
RpcRequest request = rpcSerialization.deserialize(data, RpcRequest.class);
if (request != null) {
RpcProtocol<RpcRequest> protocol = new RpcProtocol<>();
protocol. setHeader(header);
protocol.setBody(request);
out. add(protocol);
}
break;
// response message
case RESPONSE:
RpcResponse response = rpcSerialization.deserialize(data, RpcResponse.class);
if (response != null) {
RpcProtocol<RpcResponse> protocol = new RpcProtocol<>();
protocol. setHeader(header);
protocol.setBody(response);
out. add(protocol);
}
break;
}
}
} |
{% extends "plantillaBase.html" %}
{% block tituloPestana %} Menu Principal {% endblock %}
{% block tituloPrincipal %} {% endblock %}
{% block mensaje %}
{% if exito %}
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{exito}}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endif %}
{% if error %}
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{{error}}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endif %}
{% endblock %}
{% block contenido %}
{% load static %}
<form class="form" method="post" enctype="multipart/form-data" action="{% url 'admin' %}" >
{% csrf_token %}
<script src="{% static 'Images/admin.js' %}"></script>
<!--signin-->
<div class="container-fluid">
<div class="row justify-content-center">
<!--signin-->
<div class="col-10 col-md-4 mt-5">
<div class="form-group mb-4">
<h2>Ingresar producto</h2>
<label for="exampleInputEmail1">
Nombre
</label>
<input type="hidden" name="txtId" value="0{{item.id}}">
<input type="text" name="txtNombre" class="txtNombre form-control" value="{{item.nombre}}" placeholder="ej: 'Fallout 2'" style="color: white; background-color: #121212; border-color: cyan; "/>
</div>
<div class="form-group mb-4">
<label for="exampleInputEmail1">
Categoria<br>
</label>
<select name="cmbCategoria" class="txtCategoria form-select form-select-md mb-3" aria-label=".form-select-md example" style="color: white; background-color: #121212; border-color: cyan;">
<option value=0 selected>Seleccione una categoria...</option>
{% for objecto in categoria %}
{% if objecto.activo == 1 %}
<option value="{{objecto.pk}}" {% if objecto.id == item.categoria.id %}selected {% endif %}>{{objecto.nombre}}</option>
{% endif %}
{% endfor%}
</select>
</div>
<div class="form-group mb-3">
<label for="exampleInputPassword1">
Descripcion
</label>
<input type="text" class="txtDescripcion form-control" name="txtDescripcion" value="{{item.descripcion}}" placeholder="ej: Juego muy divertido" id="exampleInputPassword1" style="color: white; background-color: #121212; border-color: cyan;"/>
</div>
</div>
<!--registro-->
<div class="col-10 col-md-4 m-4 mb-5 mt-md-5 ">
<div class="form-group mb-4">
<b></b>
<h2><br></h2>
<label for="exampleInputEmail1">
Stock
</label>
<input name="txtStock" min="0" value="{{item.stock}}" type="number"
class="txtStock form-control form-control" style="color: white; background-color: #121212; border-color: cyan;" />
</div>
<div class="form-group mb-4">
<label for="exampleInputEmail1">
Consola<br>
</label>
<select name="txtConsola" class="txtConsola form-select form-select-md mb-3" aria-label=".form-select-md example" style="color: white; background-color: #121212; border-color: cyan;">
<option value=0 selected>Seleccione una consola...</option>
{% for objecto in consola %}
{% if objecto.activo == 1 %}
<option value="{{objecto.nombre}}" {% if objecto.id == item.consola.id %}selected {% endif %}>{{objecto.nombre}}</option>
{% endif %}
{% endfor%}
</select>
</div>
<div class="form-group mb-4">
<label for="exampleInputEmail1">
Precio
</label>
<input type="text" name="txtPrecio" class="txtPrecio form-control" id="txtEmail" value="{{item.precio}}" placeholder="ej: '29.990'" style="color: white; background-color: #121212; border-color: cyan;"/>
</div>
<div class="form-group mb-4">
<label for="exampleFormControlFile1">Imagen</label>
<input type="file" class="txtImagen form-control-file" name="txtImagen" value="{{item.imagen}}" id="exampleFormControlFile1" style="color: white; background-color: #121212; border-color: cyan;">
<input hidden type="text" class="txtImagen1 form-control-file" name="txtImagen1" value="{{item.imagen}}" id="exampleFormControlFile1" style="color: white; background-color: #121212; border-color: cyan;">
</div>
<input type="button" name="btnEnviar" class="btnEnviar" value="Guardar" style="color: white; background-color: cyan; color: purple; border-color: purple;">
</input>
</div>
</div>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="color: white; background-color: #121212;">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Añadir al carrito</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" >
¿Seguro que desea añadir al carrito?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
<input type="submit" name="btnGuardar" value="Guardar" class="btn btn-primary" style="color: white; background-color: cyan; color: purple; border-color: purple;">
</input>
</div>
</div>
</div>
</div>
</form>
{% endblock %}
{% block listado %}
<table class="table table-responsive table-striped">
<tr>
<th>Imagen URL</th>
<th>Categoria</th>
<th>Nombre</th>
<th>Precio</th>
<th>Descripcion</th>
<th>Consola</th>
<th>Stock</th>
<th>Modificar</th>
<th>Eliminar</th>
</tr>
{% for item in productos %}
<tr>
<td>{{ item.imagen }}</td>
<td>{{ item.categoria.nombre| title }}</td>
<td>{{ item.nombre| capfirst }}</td>
<td>{{ item.precio }}</td>
<td>{{ item.descripcion }}</td>
<td>{{ item.consola }}</td>
<td>{{ item.stock }}</td>
<td><a href="{% url 'buscarProducto' pk=item.id %}" class="btn btn-warning">Modificar</a></td>
<td><a href="{% url 'eliminarProducto' pk=item.id %}" class="btn btn-danger">Eliminar</a></td>
{% endfor %}
</table>
{% endblock %} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.