text
stringlengths
184
4.48M
import Avatar from '../components/avatar' import DateFormatter from '../components/date-formatter' import CoverImage from './cover-image' import Link from 'next/link' export default function PostPreview({ id, title, coverImage, date, excerpt }: { id: string title: string, coverImage: string, date: string, excerpt: string, }): JSX.Element | null { return ( <div> <div className="mb-5"> <CoverImage id={id} title={title} src={coverImage} height={328} width={556} /> </div> <div className="mx-5 md:mx-0"> <h3 className="text-3xl mb-3 leading-snug"> <Link href={`/posts/${id}`}> <a className="hover:underline">{title}</a> </Link> </h3> <div className="text-lg mb-4"> <DateFormatter dateString={date} /> </div> <p className="text-lg leading-relaxed mb-4">{excerpt}</p> </div> </div> ) }
const pokeApi = {} //Simplificar o modelo da pokeApi function convertPokeApiDetailToPokemon(pokeDetail) { const pokemon = new Pokemon() pokemon.name = pokeDetail.name pokemon.number = pokeDetail.id const types = pokeDetail.types.map((typeSlot) => typeSlot.type.name) //Array destruct const [type] = types pokemon.types = types pokemon.type = type pokemon.photo = pokeDetail.sprites.other.dream_world.front_default return pokemon } pokeApi.getPokemonDetail = (pokemon) => { return fetch(pokemon.url) .then((response) => response.json()) .then(convertPokeApiDetailToPokemon) } pokeApi.getPokemons = (offset = 0, limit = 5) => { const url = `https://pokeapi.co/api/v2/pokemon?offset=${offset}&limit=${limit}`; return fetch(url) //Converter http response para JSON .then((response) => response.json()) //Utilizar apenas results do JSON .then((jsonBody) => jsonBody.results) //Mapear lista de pokemons para lista de requisições .then((pokemons) => pokemons.map(pokeApi.getPokemonDetail)) //Aguardar toda a lista de requisições terminar .then((detailRequests) => Promise.all((detailRequests))) //Utilizar uma lista de detalhes dos pokemons .then((pokemonsDetails) => pokemonsDetails) } Promise.all([ fetch('https://pokeapi.co/api/v2/pokemon/1'), fetch('https://pokeapi.co/api/v2/pokemon/2'), fetch('https://pokeapi.co/api/v2/pokemon/3'), fetch('https://pokeapi.co/api/v2/pokemon/4') ]).then((results)=>{ console.log(results) })
#ifndef TINYLANG_BACK_TAC_CODEGEN_TMGEN_H_ #define TINYLANG_BACK_TAC_CODEGEN_TMGEN_H_ #include <ostream> #include <list> #include <utility> #include <string_view> #include "back/tac/codegen/tinymips.h" namespace tinylang::back::tac { class TinyMIPSAsmGen { public: TinyMIPSAsmGen() { Reset(); } // reset internal state void Reset() { asms_.clear(); is_reordered_ = false; } // push a new assembly template <typename... Args> void PushAsm(Args &&... args) { asms_.emplace_back(std::forward<Args>(args)...); } // push 'nop' pseudo instruction void PushNop(); // push a label void PushLabel(std::string_view label); // push 'move' pseudo instruction void PushMove(TinyMIPSReg dest, TinyMIPSReg src); // push 'li' pseudo instruction void PushLoadImm(TinyMIPSReg dest, std::uint32_t imm); // push 'la' pseudo instruction void PushLoadImm(TinyMIPSReg dest, std::string_view imm_str); // push a new branch instruction void PushBranch(TinyMIPSReg cond, std::string_view label); // push a new jump instruction void PushJump(std::string_view label); // push a new jump instruction void PushJump(TinyMIPSReg dest); // dump assembly code to stream void Dump(std::ostream &os, std::string_view indent); private: // reorder all jumps (make delay slots) void ReorderJump(); std::list<TinyMIPSAsm> asms_; bool is_reordered_; }; } // namespace tinylang::back::tac #endif // TINYLANG_BACK_TAC_CODEGEN_TMGEN_H_
<template> <v-sheet class="rounded-lg back my-10 pa-10"> <v-form ref="search"> <v-container> <v-row> <v-col> <v-combobox v-model="departure" :rules="departureRules" :items="departures" no-data-text="Рейсов нет" validate-on-blur open-on-clear color="#ce6f61" dark :menu-props="{ offsetY: true, transition: 'scale-transition', }" label="Откуда" item-color="#00131a" ></v-combobox> </v-col> <v-col> <v-combobox v-model="arrival" :rules="arrivalRules" :items="arrivals" no-data-text="Рейсов нет" validate-on-blur open-on-clear color="#ce6f61" dark :menu-props="{ offsetY: true, transition: 'scale-transition', }" label="Куда" item-color="#00131a" ></v-combobox> </v-col> <v-col> <v-menu v-model="datepickerMenu" :close-on-content-click="false" transition="scale-transition" offset-y min-width="auto" > <template v-slot:activator="{ on, attrs }"> <v-text-field v-model="date" :rules="datepickerRules" label="Дата" validate-on-blur readonly dark required color="#ce6f61" v-bind="attrs" v-on="on" ></v-text-field> </template> <v-date-picker v-model="date" no-title scrollable locale="ru" color="#ce6f61" :min="new Date().toISOString().substr(0, 10)" > <v-spacer></v-spacer> <v-btn text color="#ce6f61" @click="datepickerMenu = false"> ОК </v-btn> </v-date-picker> </v-menu> </v-col> </v-row> <v-row> <v-col class="text-center"> <v-btn color="#ce6f61" outlined elevation="10" @click="search"> Найти </v-btn> </v-col> </v-row> </v-container> </v-form> </v-sheet> </template> <script> export default { name: "SearchForm", data: () => ({ departure: "", departures: [], departureRules: [(v) => !!v || "Место вылета обязательно!"], arrival: "", arrivals: [], arrivalRules: [(v) => !!v || "Место прибытия обязательно!"], date: (new Date()).toISOString().substring(0, 10), datepickerMenu: false, datepickerRules: [(v) => !!v || "Дата вылета обязательна!"], }), async mounted() { let query = `/Ticket/Cities` let resp = await this.$axios.get(query) try { this.departures = resp.data.departures this.arrivals = resp.data.arrivals } catch { } }, methods: { search() { if (this.$refs.search.validate()) { this.$emit("search", { departure: this.departure, arrival: this.arrival, date: this.date, }) } }, }, }; </script> <style scoped> .back { position: relative; left: 50%; max-width: 1100px; background-image: linear-gradient(rgba(0, 19, 26, 0.6), rgba(0, 19, 26, 0.6)), url("/form-back.jpg"); transform: translateX(-50%); } </style> <style> .v-menu__content::-webkit-scrollbar { width: 0px; } </style>
/** * This is version 2 of the gx.ui.Table class. It simplifies the class * by removing the hidden thead element and do not calculate the thead sizes * with javascript. * * It contains massive rework by splitting .addData() into * createRow, updateRow, removeRow. * * Fixing HUGE performance issues (do not bind "click" event handler to EVERY CELL by default). * * Therefore the API to gx.ui.SimpleTable is broken. * * * @class gx.ui.Table * @description Creates a dynamic select box, which dynamically loads the contents from a remote URL. * @extends gx.ui.Container * @implements gx.util.Console * * @event click Fired when click a row. * */ gx.ui.SimpleTable = new Class({ Implements: [Options, Events], options: { 'cols': [], 'structure' : function (row, index) { return [ row.col1, { 'label': row.col2, 'className': row.col2class } ]; }, 'tableCss': 'table table-striped table-hover', 'fireRowClick': false // data: [] }, initialize: function (display, options) { this.setOptions(options); this.build(display); this.buildCols(this.options.cols); }, /** * @method build * @description Builds the core components */ build: function (display) { this._display = {}; var rootElmt = this._display.root = typeOf(display) === 'element' ? display : new Element('table'); if ( rootElmt.get('tag') === 'table' ) { this._display.table = rootElmt; } else { this._display.table = new Element('table'); rootElmt.adopt(this._display.table); } this._display.table.addClass(this.options.tableCss); this._display.tbody = new Element('tbody'); this._display.thead = new Element('thead'); this._display.table.adopt( this._display.thead, this._display.tbody ); }, /** * @method buildCols * @description Builds the columns * @param {array} cols An array of columns */ buildCols: function (cols) { var tr = new Element('tr'); this._display.thead.empty(); this._display.thead.adopt(tr); cols.each(function (col) { var th = new Element('th', { 'class': '' }); if ( col.properties ) th.set(col.properties); switch ( typeOf(col.label) ) { case 'object' : th.adopt(__(col.label)); break; case 'element': th.adopt(col.label); break; default: th.set('html', col.label); break; } tr.adopt(th); }); }, /** * @method setData * @description Sets the list data. Calls empty() and then addData(data) * @param {array} data The list data to set * @returns Returns this instance (for method chaining). * @type gx.ui.Table */ setData: function (data) { this.empty(); return this.addData(data); }, /** * @method addData * @description Adds the specified data to the table * @param {array} data The data to add * @returns Returns this instance (for method chaining). * @type gx.ui.Table */ addData: function (data) { data.each(function (row, index) { this.addRow(row, index); }.bind(this)); }, createRow: function(row, index) { var root = this; var cols = root.options.structure(row, index, root); var rowProperties = {}; if ( cols.row && cols.properties ) { Object.merge(rowProperties, cols.properties); cols = cols.row; } var tr = new Element('tr', rowProperties); for ( var i = 0, l = cols.length; i < l; i++ ) { var col = cols[i]; var td = new Element('td'); switch (typeOf(col)) { case 'object' : var label = col.label; if ( label instanceof Element ) td.adopt(label); else td.set('html', label); col = Object.clone(col); if ( col.className ) td.addClass(col.className); delete col.label; delete col.className; td.set(col); break; case 'element': td.adopt(col); break; default: td.set('html', col); break; } tr.adopt(td); } // BAD, this event should be added to "table" tag handled with // event propagation, however. This requires index management of the // data rows. Therefore stay with this for now. if ( this.options.fireRowClick === true ) { tr.addEvent('click', function() { root.fireEvent('click', [row, index]); }); } return tr; }, addRow: function(obj, index) { var tr = this.createRow(obj, index); this._display.tbody.adopt(tr); return tr; }, updateRow: function(obj, index) { var replaceTr; var tbody = this._display.tbody; if ( typeof tbody.childNodes !== 'undefined' ) replaceTr = tbody.childNodes[index]; else replaceTr = tbody.getChildren()[index]; var tr = this.createRow(obj, index); tr.replaces(replaceTr); return tr; }, removeRow: function(index) { var row; var tbody = this._display.tbody; if ( typeof tbody.childNodes !== 'undefined' ) row = tbody.childNodes[index]; else row = tbody.getChildren()[index]; if ( row ) $(row).destroy(); }, getRows: function() { return this._display.tbody.childNodes; }, /** * @method empty * @description Clears the table body * @returns Returns this instance (for method chaining). * @type gx.ui.Table */ empty: function () { this._display.tbody.empty(); }, toElement: function() { return this._display.root; } });
use super::type_support::FieldRef; use crate::{ _impl::arrow::datatypes::{DataType, Field, TimeUnit, UnionMode}, internal::{ error::{error, fail, Error, Result}, schema::{ GenericDataType, GenericField, GenericTimeUnit, SchemaLike, Sealed, SerdeArrowSchema, Strategy, STRATEGY_KEY, }, }, }; /// Support for arrow types (*requires one of the `arrow-*` features*) impl SerdeArrowSchema { /// Build a new Schema object from fields pub fn from_arrow_fields(fields: &[Field]) -> Result<Self> { Ok(Self { fields: fields .iter() .map(GenericField::try_from) .collect::<Result<_>>()?, }) } /// This method is deprecated. Use /// [`to_arrow_fields`][SerdeArrowSchema::to_arrow_fields] instead: /// /// ```rust /// # fn main() -> serde_arrow::_impl::PanicOnError<()> { /// # use serde_arrow::schema::{SerdeArrowSchema, SchemaLike, TracingOptions}; /// # #[derive(serde::Deserialize)] /// # struct Item { a: u32 } /// # let schema = SerdeArrowSchema::from_type::<Item>(TracingOptions::default()).unwrap(); /// # let fields = /// schema.to_arrow_fields()? /// # ; /// # Ok(()) /// # } /// ``` #[deprecated = "The method `get_arrow_fields` is deprecated. Use `to_arrow_fields` instead"] pub fn get_arrow_fields(&self) -> Result<Vec<Field>> { self.to_arrow_fields() } /// Build a vec of fields from a Schema object pub fn to_arrow_fields(&self) -> Result<Vec<Field>> { self.fields.iter().map(Field::try_from).collect() } } impl TryFrom<SerdeArrowSchema> for Vec<Field> { type Error = Error; fn try_from(value: SerdeArrowSchema) -> Result<Self> { value.to_arrow_fields() } } impl Sealed for Vec<Field> {} /// Schema support for `Vec<arrow::datatype::Field>` (*requires one of the /// `arrow-*` features*) impl SchemaLike for Vec<Field> { fn from_value<T: serde::Serialize>(value: &T) -> Result<Self> { SerdeArrowSchema::from_value(value)?.to_arrow_fields() } fn from_type<'de, T: serde::Deserialize<'de>>( options: crate::schema::TracingOptions, ) -> Result<Self> { SerdeArrowSchema::from_type::<T>(options)?.to_arrow_fields() } fn from_samples<T: serde::Serialize>( samples: &T, options: crate::schema::TracingOptions, ) -> Result<Self> { SerdeArrowSchema::from_samples(samples, options)?.to_arrow_fields() } } impl TryFrom<&DataType> for GenericDataType { type Error = Error; fn try_from(value: &DataType) -> Result<GenericDataType> { match value { DataType::Boolean => Ok(GenericDataType::Bool), DataType::Null => Ok(GenericDataType::Null), DataType::Int8 => Ok(GenericDataType::I8), DataType::Int16 => Ok(GenericDataType::I16), DataType::Int32 => Ok(GenericDataType::I32), DataType::Int64 => Ok(GenericDataType::I64), DataType::UInt8 => Ok(GenericDataType::U8), DataType::UInt16 => Ok(GenericDataType::U16), DataType::UInt32 => Ok(GenericDataType::U32), DataType::UInt64 => Ok(GenericDataType::U64), DataType::Float16 => Ok(GenericDataType::F16), DataType::Float32 => Ok(GenericDataType::F32), DataType::Float64 => Ok(GenericDataType::F64), DataType::Utf8 => Ok(GenericDataType::Utf8), DataType::LargeUtf8 => Ok(GenericDataType::LargeUtf8), DataType::Date64 => Ok(GenericDataType::Date64), DataType::Timestamp(TimeUnit::Second, tz) => Ok(GenericDataType::Timestamp( GenericTimeUnit::Second, tz.as_ref().map(|s| s.to_string()), )), DataType::Timestamp(TimeUnit::Millisecond, tz) => Ok(GenericDataType::Timestamp( GenericTimeUnit::Millisecond, tz.as_ref().map(|s| s.to_string()), )), DataType::Timestamp(TimeUnit::Microsecond, tz) => Ok(GenericDataType::Timestamp( GenericTimeUnit::Microsecond, tz.as_ref().map(|s| s.to_string()), )), DataType::Timestamp(TimeUnit::Nanosecond, tz) => Ok(GenericDataType::Timestamp( GenericTimeUnit::Nanosecond, tz.as_ref().map(|s| s.to_string()), )), _ => fail!("Only primitive data types can be converted to GenericDataType"), } } } impl TryFrom<&Field> for GenericField { type Error = Error; fn try_from(field: &Field) -> Result<Self> { let strategy: Option<Strategy> = match field.metadata().get(STRATEGY_KEY) { Some(strategy_str) => Some(strategy_str.parse::<Strategy>()?), None => None, }; let name = field.name().to_owned(); let nullable = field.is_nullable(); let mut children = Vec::<GenericField>::new(); let data_type = match field.data_type() { DataType::List(field) => { children.push(GenericField::try_from(field.as_ref())?); GenericDataType::List } DataType::LargeList(field) => { children.push(field.as_ref().try_into()?); GenericDataType::LargeList } DataType::Struct(fields) => { for field in fields { children.push(field.as_field_ref().try_into()?); } GenericDataType::Struct } DataType::Map(field, _) => { children.push(field.as_ref().try_into()?); GenericDataType::Map } DataType::Union(fields, mode) => { if !matches!(mode, UnionMode::Dense) { fail!("Only dense unions are supported at the moment"); } for (pos, (idx, field)) in fields.iter().enumerate() { if pos as i8 != idx { fail!("Union types with explicit field indices are not supported"); } children.push(field.as_ref().try_into()?); } GenericDataType::Union } DataType::Dictionary(key_type, value_type) => { children.push(GenericField::new("", key_type.as_ref().try_into()?, false)); children.push(GenericField::new( "", value_type.as_ref().try_into()?, false, )); GenericDataType::Dictionary } dt => dt.try_into()?, }; let field = GenericField { data_type, name, strategy, children, nullable, }; field.validate()?; Ok(field) } } impl TryFrom<&GenericField> for Field { type Error = Error; fn try_from(value: &GenericField) -> Result<Self> { let data_type = match &value.data_type { GenericDataType::Null => DataType::Null, GenericDataType::Bool => DataType::Boolean, GenericDataType::I8 => DataType::Int8, GenericDataType::I16 => DataType::Int16, GenericDataType::I32 => DataType::Int32, GenericDataType::I64 => DataType::Int64, GenericDataType::U8 => DataType::UInt8, GenericDataType::U16 => DataType::UInt16, GenericDataType::U32 => DataType::UInt32, GenericDataType::U64 => DataType::UInt64, GenericDataType::F16 => DataType::Float16, GenericDataType::F32 => DataType::Float32, GenericDataType::F64 => DataType::Float64, GenericDataType::Date64 => DataType::Date64, GenericDataType::Utf8 => DataType::Utf8, GenericDataType::LargeUtf8 => DataType::LargeUtf8, GenericDataType::List => DataType::List( Box::<Field>::new( value .children .get(0) .ok_or_else(|| error!("List must a single child"))? .try_into()?, ) .into(), ), GenericDataType::LargeList => DataType::LargeList( Box::<Field>::new( value .children .get(0) .ok_or_else(|| error!("List must a single child"))? .try_into()?, ) .into(), ), GenericDataType::Struct => DataType::Struct( value .children .iter() .map(Field::try_from) .collect::<Result<_>>()?, ), GenericDataType::Map => { let element_field: Field = value .children .get(0) .ok_or_else(|| error!("Map must a single child"))? .try_into()?; DataType::Map(Box::new(element_field).into(), false) } #[cfg(not(feature = "arrow-36"))] GenericDataType::Union => { let mut fields = Vec::new(); for (idx, field) in value.children.iter().enumerate() { fields.push((idx as i8, std::sync::Arc::new(Field::try_from(field)?))); } DataType::Union(fields.into_iter().collect(), UnionMode::Dense) } #[cfg(feature = "arrow-36")] GenericDataType::Union => DataType::Union( value .children .iter() .map(Field::try_from) .collect::<Result<Vec<_>>>()?, (0..value.children.len()) .into_iter() .map(|v| v as i8) .collect(), UnionMode::Dense, ), GenericDataType::Dictionary => { let key_field = value .children .get(0) .ok_or_else(|| error!("Dictionary must a two children"))?; let val_field: Field = value .children .get(1) .ok_or_else(|| error!("Dictionary must a two children"))? .try_into()?; let key_type = match &key_field.data_type { GenericDataType::U8 => DataType::UInt8, GenericDataType::U16 => DataType::UInt16, GenericDataType::U32 => DataType::UInt32, GenericDataType::U64 => DataType::UInt64, GenericDataType::I8 => DataType::Int8, GenericDataType::I16 => DataType::Int16, GenericDataType::I32 => DataType::Int32, GenericDataType::I64 => DataType::Int64, _ => fail!("Invalid key type for dictionary"), }; DataType::Dictionary(Box::new(key_type), Box::new(val_field.data_type().clone())) } GenericDataType::Timestamp(GenericTimeUnit::Second, tz) => { DataType::Timestamp(TimeUnit::Second, tz.clone().map(|s| s.into())) } GenericDataType::Timestamp(GenericTimeUnit::Millisecond, tz) => { DataType::Timestamp(TimeUnit::Millisecond, tz.clone().map(|s| s.into())) } GenericDataType::Timestamp(GenericTimeUnit::Microsecond, tz) => { DataType::Timestamp(TimeUnit::Microsecond, tz.clone().map(|s| s.into())) } GenericDataType::Timestamp(GenericTimeUnit::Nanosecond, tz) => { DataType::Timestamp(TimeUnit::Nanosecond, tz.clone().map(|s| s.into())) } }; let mut field = Field::new(&value.name, data_type, value.nullable); if let Some(strategy) = value.strategy.as_ref() { field.set_metadata(strategy.clone().into()); } Ok(field) } }
#include <iostream> #include <iomanip> #include <string> #include <fstream> #include <vector> using namespace std; const string file_name = "clients.txt"; enum en_main_menu { en_quick_withdraw = 1, en_withdraw = 2, en_deposit = 3, en_check_balance = 4, en_logout = 5 }; struct st_client_data { string account_number; string pin_code; string name; string phone; double account_balance = 0; bool mark_for_delete = false; }; st_client_data current_client; void show_main_menu(); void login(); st_client_data convert_line_data_to_record(string line, string delim); string read_string(string message) { string sentence; cout << message << endl; getline(cin >> ws, sentence); return sentence; } int read_amount(string message) { int amount = -1; while (amount < 0) { cout << message; cin >> amount; } return amount; } short read_withdraw_option() { short option = 0; cout << "\nChoose option to withdraw [1 - 8]: "; cin >> option; return option; } bool is_client_exist(string account_number, string file_name) { string line; st_client_data client_data; fstream file; file.open(file_name, ios::in); while (getline(file, line)) { client_data = convert_line_data_to_record(line, "#//#"); if (client_data.account_number == account_number) { file.close(); return true; } } file.close(); return false; } string convert_record_to_line(st_client_data client_data, string delim = "#//#") { return (client_data.account_number + delim + client_data.pin_code + delim + client_data.name + delim + client_data.phone + delim + to_string(client_data.account_balance)); } vector<string> split_string(string sentence, string delim = " ") { vector <string> words; short pos = 0; string word; while ((pos = sentence.find(delim)) != std::string::npos) { word = sentence.substr(0, pos); if (word != "") words.push_back(word); sentence.erase(0, pos + delim.length()); } if (sentence != "") words.push_back(sentence); return words; } st_client_data convert_line_data_to_record(string line, string delim = "#//#") { vector <string> line_data = split_string(line, delim); st_client_data client_data; client_data.account_number = line_data.at(0); client_data.pin_code = line_data.at(1); client_data.name = line_data.at(2); client_data.phone = line_data.at(3); client_data.account_balance = stod(line_data.at(4)); return client_data; } void add_data_line_to_file(string file_name, string line_data) { fstream file; file.open(file_name, ios::out | ios::app); while (file.is_open()) { file << line_data << endl; file.close(); } } vector<st_client_data> read_clients_data_from_file(string file_name) { vector<st_client_data> v_clients_data; string line; st_client_data client_data; fstream file; file.open(file_name, ios::in); while (getline(file, line)) { client_data = convert_line_data_to_record(line); v_clients_data.push_back(client_data); } file.close(); return v_clients_data; } bool find_client_by_account_number(string account_number, vector<st_client_data> v_clients_data, st_client_data& client) { for (st_client_data& c : v_clients_data) { if (c.account_number == account_number) { client = c; return true; } } return false; } void save_client_data_to_file(string file_name, vector<st_client_data> v_clients_data) { fstream file; string line_data; file.open(file_name, ios::out); if (file.is_open()) { for (st_client_data client : v_clients_data) { if (client.mark_for_delete == false) { line_data = convert_record_to_line(client); file << line_data << endl; } } file.close(); } } short read_menu_option() { short option = 0; cout << "Choose what you want to do: "; cin >> option; return option; } void go_back_to_main_menu() { cout << "\n\nPress any key to go back to main menu..."; system("pause>0"); show_main_menu(); } void show_exit_screen() { cout << "\n-----------------------------------\n"; cout << "\tExit Program\n"; cout << "-----------------------------------\n"; } bool deposit(string account_number, int amount, vector <st_client_data>& v_clients_data) { char answer = 'n'; cout << "Are you sure you want to make this operation[Y/N]? "; cin >> answer; if (tolower(answer) == 'y') { for (st_client_data& c : v_clients_data) { if (c.account_number == account_number) { if (tolower(answer) == 'y') { c.account_balance += amount; current_client.account_balance = c.account_balance; cout << "\nOperation is done Successfully.\n"; cout << "\nYour balance is " << c.account_balance; save_client_data_to_file(file_name, v_clients_data); return true; } } } } return false; } void show_deposit_screen() { cout << "\n-----------------------------------\n"; cout << "\tDeposit Screen\n"; cout << "-----------------------------------\n"; vector <st_client_data> v_clients_data = read_clients_data_from_file(file_name); int amount = read_amount("Enter amount to deposit: "); deposit(current_client.account_number, amount, v_clients_data); } int get_quick_withdraw_amount(short quick_option) { switch (quick_option) { case 1: return 20; case 2: return 50; case 3: return 100; case 4: return 200; case 5: return 400; case 6: return 600; case 7: return 800; case 8: return 1000; default: return 0; } } void show_quick_withdraw_screen() { cout << "\n-----------------------------------\n"; cout << "\tQuick Withdraw Screen\n"; cout << "-----------------------------------\n"; cout << "\t[1] 20 \t\t[2] 50" << endl; cout << "\t[3] 100 \t[4] 200" << endl; cout << "\t[5] 400 \t[6] 600" << endl; cout << "\t[7] 800 \t[8] 1000" << endl; cout << "-----------------------------------\n"; vector <st_client_data> v_clients_data = read_clients_data_from_file(file_name); cout << "\nYour balance is " << current_client.account_balance; int amount = get_quick_withdraw_amount(read_withdraw_option()); if (amount < current_client.account_balance) deposit(current_client.account_number, -amount, v_clients_data); else cout << "The amount exceeds the current balance.\n"; } void show_withdraw_screen() { cout << "\n-----------------------------------\n"; cout << "\tWithdraw Screen\n"; cout << "-----------------------------------\n"; vector <st_client_data> v_clients_data = read_clients_data_from_file(file_name); cout << "\nYour balance is " << current_client.account_balance << endl; int amount = read_amount("\nEnter amount to withdraw: "); if (amount < current_client.account_balance) deposit(current_client.account_number, -amount, v_clients_data); else cout << "The amount exceeds the current balance.\n"; } void show_check_balance() { cout << "\n-----------------------------------\n"; cout << "\tBalance Screen\n"; cout << "-----------------------------------\n"; cout << "\n\n\Balance = " << current_client.account_balance << endl << endl; } void perform_menu_option(en_main_menu option) { switch (option) { case en_main_menu::en_quick_withdraw: system("cls"); show_quick_withdraw_screen(); go_back_to_main_menu(); break; case en_main_menu::en_withdraw: system("cls"); show_withdraw_screen(); go_back_to_main_menu(); break; case en_main_menu::en_deposit: system("cls"); show_deposit_screen(); go_back_to_main_menu(); break; case en_main_menu::en_check_balance: system("cls"); show_check_balance(); go_back_to_main_menu(); break; case en_main_menu::en_logout: system("cls"); login(); break; } } void show_main_menu() { system("cls"); cout << "\tATM Main Menu Screen\n"; cout << "\t[1] Quick Withdraw.\n"; cout << "\t[2] Withdraw.\n"; cout << "\t[3] Deposit.\n"; cout << "\t[4] Check Balance.\n"; cout << "\t[5] Logout.\n"; perform_menu_option((en_main_menu)read_menu_option()); } bool find_user_by_account_number_pincode(string account_number, string pincode, st_client_data& client) { vector <st_client_data> v_clients = read_clients_data_from_file(file_name); for (st_client_data c : v_clients) { if (c.account_number == account_number && c.pin_code == pincode) { client = c; return true; } } return false; } bool load_client_data(string account_number, string pincode) { if (find_user_by_account_number_pincode(account_number, pincode, current_client)) return true; else return false; } void login() { bool login_failed = false; string account_number, pincode; do { system("cls"); cout << "\n-----------------------------------\n"; cout << "\tLogin Screen\n"; cout << "-----------------------------------\n"; if (login_failed) cout << "\nInvaid Username/Password.\n\n"; cout << "Enter account number: "; getline(cin >> ws, account_number); cout << "Enter pincode: "; cin >> pincode; login_failed = !load_client_data(account_number, pincode); } while (login_failed); show_main_menu(); } int main() { cout << left; login(); system("pause>0"); return 0; }
import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from "@angular/common/http"; import { Observable } from "rxjs"; import { map } from "rxjs/operators"; import { appConfig as c } from 'app/core/config/app.config' import { Defeito, DefeitoData, DefeitoParameters } from '../types/defeito.types'; @Injectable({ providedIn: 'root' }) export class DefeitoService { constructor(private http: HttpClient) { } obterPorParametros(parameters: DefeitoParameters): Observable<DefeitoData> { let params = new HttpParams(); Object.keys(parameters).forEach(key => { if (parameters[key] !== undefined && parameters[key] !== null) params = params.append(key, String(parameters[key])); }); return this.http.get<DefeitoData>(`${c.api}/Defeito`, { params: params }).pipe( map((data) => data) ) } obterPorCodigo(codDefeito: number): Observable<Defeito> { const url = `${c.api}/Defeito/${codDefeito}`; return this.http.get<Defeito>(url).pipe( map((obj) => obj) ); } criar(defeito: Defeito): Observable<Defeito> { return this.http.post<Defeito>(`${c.api}/Defeito`, defeito).pipe( map((obj) => obj) ); } atualizar(defeito: Defeito): Observable<Defeito> { const url = `${c.api}/Defeito`; return this.http.put<Defeito>(url, defeito).pipe( map((obj) => obj) ); } deletar(codDefeito: number): Observable<Defeito> { const url = `${c.api}/Defeito/${codDefeito}`; return this.http.delete<Defeito>(url).pipe( map((obj) => obj) ); } }
import java.util.ArrayList; public class Boat { private String name; private int size; private Position position; private String direction; private ArrayList<Position> HitPositions=new ArrayList<Position>(); private ArrayList<Position> BoatPositions = new ArrayList<Position>(); Boat (String ship, Position startPosition, String directionofBoat){ BoatPositions.add(startPosition); name=ship; if(name.substring(0,1).equalsIgnoreCase("A")){ size=5; }else if(name.substring(0,1).equalsIgnoreCase("B")){ size=4; }else if (name.substring(0,1).equalsIgnoreCase("C")|| name.substring(0,1).equalsIgnoreCase("S")){ size= 3; }else{ size= 2; } position=startPosition; direction=directionofBoat.toLowerCase(); int row = startPosition.rowIndex(); int column = startPosition.columnIndex(); if (direction.equals("vertical")){ for (int b=row; b<=size+row-2; b++){ Position A = new Position (b+1, startPosition.columnIndex() ); BoatPositions.add(A); } }else if (direction.equals("horizontal")){ for (int c=column; c<=size+column-2; c++){ Position A = new Position (startPosition.rowIndex(), c+1); BoatPositions.add(A); } } } public String name(){ return name; } public char abbreviation(){ char ab=name.charAt(0); return ab; } public int size(){ return size; } public boolean isHit(Position hitHere){ String position = hitHere.toString(); for (Object pos: HitPositions){ String onBoat = pos.toString(); if(onBoat.compareTo(position)==0){ return true; } } return false; } public boolean onBoat (Position hitThis){ String position = hitThis.toString(); for (Object pos: BoatPositions){ String onBoat = pos.toString(); if(onBoat.compareTo(position)==0){ return true; } } return false; } public void hit (Position hitThis){ if(onBoat(hitThis)){ HitPositions.add(hitThis); } } public boolean sunk(){ for (Object pos: BoatPositions){ if (isHit((Position) pos)){ }else{ return false; } } return true; } public Position position (){ return position; } public String direction (){ return direction; } }
import { Link, useParams } from "react-router-dom"; import Header from "../components/Header"; import { useEffect, useState } from "react"; import { useConnection } from "@arweave-wallet-kit/react"; import { dryrun } from "@permaweb/aoconnect"; import ReactQuill from "react-quill"; import "react-quill/dist/quill.bubble.css"; const ViewPost = () => { const { postId } = useParams(); const { connected } = useConnection(); const processId = "5iK7nXtoUMWNCDtiOpwf75_ppw0v4LwusumyqiQdPq8"; const [isFetching, setIsFetching] = useState(false); const [postContent, setPostContent] = useState(); const syncAllPosts = async () => { if (!connected) { return; } try { const result = await dryrun({ process: processId, data: "", tags: [ { name: "Action", value: "Get" }, { name: "Post-Id", value: postId }, ], anchor: "1234", }); console.log("Dry run result", result); const filteredResult = JSON.parse(result.Messages[0].Data); console.log("Filtered result", filteredResult); setPostContent(filteredResult[0]); } catch (error) { console.log(error); } // setIsFetching(false); }; useEffect(() => { setIsFetching(true); syncAllPosts(); setIsFetching(false); }, [connected]); return ( <main> <Header /> {postContent && ( <div style={styles.parentDiv}> <h2 style={styles.postHeading}>{postContent.Title}</h2> <p style={styles.postContent}>{postContent.Author}</p> <p style={styles.postContent}>{postContent.ID}</p> <Link to="/view" style={styles.postLink}> <button style={styles.button}>Back</button> </Link> <hr style={styles.horizontalRule} /> <ReactQuill value={postContent.Body} readOnly theme="bubble" /> </div> )} </main> ); }; export default ViewPost; const styles = { parentDiv: { height: "calc(100vh - 72px)", display: "flex", flexDirection: "column", padding: "40px", }, horizontalRule: { border: 0, clear: "both", display: "block", width: "100%", backgroundColor: "#ccc", height: "1px", }, postHeading: { margin: "0px", padding: "0px", }, postContent: { margin: "0px", padding: "0px", color: "#555", fontSize: "14px", }, button: { padding: "10px 20px", backgroundColor: "#000", color: "#fff", border: "none", borderRadius: "4px", cursor: "pointer", width: "100px", marginTop: "20px", }, postLink: { textDecoration: "none", color: "#fff", }, };
import { useState, useContext } from 'react'; import FormInput from '../form-input/form-input.compotents'; import Button from '../button/button.compotents'; import { singInWithGooglePopup, createUserDocumentFormAuth, signInAuthUserWithEmailAndPassword } from '../../utils/firebase/firebase.utils' import './sign-in-form.styles.scss' const defaultFormFields = { email: '', password: '', } const SignInForm = () => { const [ formFields, setFormFields] = useState(defaultFormFields); const { email, password } = formFields; const resetFormFieles = () => { setFormFields(defaultFormFields) } const signInWithGoogle = async () => { await singInWithGooglePopup(); } const handleSubmit = async (event) => { event.preventDefault() try { const {user} = await signInAuthUserWithEmailAndPassword(email,password); resetFormFieles(); } catch(error){ if (error.code == 'auth/wrong-password'){ alert("incorect password") } console.log(error) } } const handleChange = (event) => { const {name, value} = event.target; setFormFields({...formFields, [name]: value }) } return ( <div className='sign-in-container'> <h2>Aleready have an acount?</h2> <span>sign in with email and passwod</span> <form onSubmit={handleSubmit}> <FormInput label='email' type='email' required onChange={handleChange} name='email' value={email} /> <FormInput label='password' type='password' required onChange={handleChange} name='password' value={password} /> <div className='buttons-container'> <Button type='submit'> sing in </Button> <Button type='button' buttonType='google' onClick={signInWithGoogle}> google sing in </Button> </div> </form> </div> ) } export default SignInForm;
import * as React from 'react'; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableContainer'; import TableHead from '@mui/material/TableHead'; import TableRow from '@mui/material/TableRow'; import parse from 'html-react-parser'; import { Title } from '../../atoms/Title/Title'; const BasicTable = ({ valueTable }) => { const getBmiState = bmi => { if (bmi < 18.5) return '<span style="color: blue;">Niskie</span>'; else if (bmi >= 18.5 && bmi < 25) return '<span style="color: green;">W normie</span>'; else if (bmi >= 25 && bmi < 28) return '<span style="color: yellow;">Zwiększone</span>'; else if (bmi >= 28 && bmi < 32) return '<span style="color: orange;">Wysokie</span>'; else if (bmi >= 32) return '<span style="color: red;">Bardzo wysokie</span>'; else return '<span style="color: black;">Poza zakresem</span>'; }; return ( <div className="Table"> <Title as="h2">Ostatnie wyniki</Title> <TableContainer style={{ boxShadow: '0px 13px 20px 0px #80808029' }}> <Table sx={{ minWidth: 650 }} aria-label="simple table"> <TableHead> <TableRow> <TableCell align="left">Wzrost</TableCell> <TableCell align="left">Waga</TableCell> <TableCell align="left">Data</TableCell> <TableCell align="left">BMI</TableCell> <TableCell align="left">Stan</TableCell> </TableRow> </TableHead> <TableBody style={{ color: 'white' }}> {valueTable .slice(0) .reverse() .map(valueTable => ( <TableRow key={valueTable.rndId} sx={{ '&:last-child td, &:last-child th': { border: 0 } }}> <TableCell align="left">{valueTable.height}</TableCell> <TableCell align="left">{valueTable.weight}</TableCell> <TableCell align="left">{valueTable.date}</TableCell> <TableCell align="left">{valueTable.bmi}</TableCell> <TableCell align="left">{parse(getBmiState(valueTable.bmi))}</TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </div> ); }; export default BasicTable;
/* * Copyright 2020 tkit.org. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tkit.quarkus.test.docker; import io.quarkus.test.common.QuarkusTestResourceLifecycleManager; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors; /** * The docker compose test resource. */ public class DockerComposeTestResource implements QuarkusTestResourceLifecycleManager{ /** * The docker test environment. */ protected DockerTestEnvironment environment; /** * {@inheritDoc} */ @Override public Map<String, String> start() { environment = new DockerTestEnvironment(); environment.start(); return Collections.emptyMap(); } /** * {@inheritDoc} */ @Override public void stop() { environment.stop(); } /** * Inject all {@link DockerComposeService} in the test class. * @param testInstance the test instance */ @Override public void inject(Object testInstance) { List<Field> fields = getDockerComposeServiceFields(testInstance.getClass()); for (Field f : fields) { f.setAccessible(true); try { DockerComposeService s = environment.getService(f.getAnnotation(DockerService.class).value()); f.set(testInstance, s); } catch (Exception e) { throw new IllegalStateException(e); } } } /** * Gets all docker compose fields for the class. * * @param clazz the test class. * @return the corresponding list of fields. */ private static List<Field> getDockerComposeServiceFields(Class<?> clazz) { if (clazz == null) { return Collections.emptyList(); } List<Field> result = new ArrayList<>(getDockerComposeServiceFields(clazz.getSuperclass())); result.addAll( Arrays.stream(clazz.getDeclaredFields()) .filter(f -> DockerComposeService.class.isAssignableFrom(f.getType())) .filter(f -> f.getAnnotation(DockerService.class) != null) .filter(f -> !f.getAnnotation(DockerService.class).value().isEmpty()) .collect(Collectors.toList()) ); return result; } }
<template> <div id="loginbg"> <h2 id="closebut"><i class="bi bi-x-lg" @click="goback()"></i></h2> <div id="logincontainer" class="border"> <div id="logintitle" class="pt-4 ps-4"> <img src="/logo.png" id="lglogo" class="me-4"> <h1 id="loginword" class="fw-bold">LOGIN</h1> </div> <form v-on:submit.prevent="test" class="row mt-3 mb-4"> <div class="col-8 ps-5"> <div class="form-floating"> <input type="text" class="form-control" id="sloganid" name="sloganid" placeholder="" required v-model="sloganid"> <label for="sloganid">아이디</label> </div> <div class="form-floating mt-3"> <input type="password" class="form-control" id="sloganbody" name="sloganbody" placeholder="" required v-model="sloganpw"> <label for="sloganbody">비밀번호</label> </div> </div> <div class="col-4 ps-0 pe-5"> <button type="submit" class="btn w-100 h-100 btn-danger"> <h3 class="fw-bold m-0">LOGIN</h3> </button> </div> </form> </div> </div> </template> <style scoped> #loginbg { position: absolute; top: 0; left: 0; width: 100vw; height: 100vh; background: #ffffff; display: flex; justify-content: center; align-items: center; overflow: hidden; } #closebut { position: absolute; right: 10px; top: 10px; color: black; } #logincontainer { width: 700px; height: fit-content; } #logintitle { display: flex; } #loginword { height: fit-content; } .btn { background-color: rgba(221, 27, 118, .8); color: white; } .btn:hover { background-color: rgba(184, 15, 94, .8); } </style> <script> export default { data() { return { sloganid: '', sloganpw: '' } }, async mounted() { const logo = document.getElementById('lglogo') const word = document.getElementById('loginword') const wordstyle = window.getComputedStyle(word, true) logo.style.height = wordstyle.height await this.logincheck() window.addEventListener('resize', () => { const logo = document.getElementById('lglogo') const word = document.getElementById('loginword') const wordstyle = window.getComputedStyle(word, true) logo.style.height = wordstyle.height }) }, methods: { goback() { this.$router.push('/') }, async basehash(text) { const original = new TextEncoder().encode(text) const hashbytes = await crypto.subtle.digest('SHA-256', original) const hashbase = await btoa(String.fromCharCode.apply(null, new Uint8Array(hashbytes))); return hashbase }, async test() { const data = { id: await this.basehash(this.sloganid), pw: await this.basehash(this.sloganpw) } const lgdata = await fetch('https://www.wpnews.kro.kr/api/login', { method: 'post', headers: { "Content-Type": "application/json", }, body: JSON.stringify(data) }) const lgdatajson = await lgdata.json() if (lgdata.status === 401) { alert('ID나 PW가 틀렸습니다.') this.sloganid = '' this.sloganpw = '' } else if (lgdata.status === 400) { if (lgdatajson.message.includes('id')) alert('ID를 입력해주십시오.') else if (lgdatajson.message.includes('pw')) alert('PW을 입력해주십시오.') } else if (lgdata.status === 500) { alert('서버 내 오류가 발생했습니다.\n잠시 후 다시 이용해주세요') } else if (lgdata.status === 200) { if (lgdatajson.message === 'Login Success') { this.$cookies.set('ssesid', lgdatajson.sessid) this.$cookies.set('reportid', lgdatajson.reportid) this.$router.push('/admin') } else { alert('서버 내 오류가 발생했습니다.\n잠시 후 다시 이용해주세요.') } } else { alert('서버 내 오류가 발생했습니다.\n잠시 후 다시 이용해주세요.') } }, async logincheck() { let sessid = this.$cookies.get('ssesid') if (!sessid) return let response = await fetch('https://www.wpnews.kro.kr/api/session?id=' + sessid) if (response.status == 404) return response = await response.json() if (response.message == 'Session Found!') return this.$router.push('/admin') } } } </script>
package com.yiling.ih.pharmacy.api.impl; import com.yiling.framework.common.exception.BusinessException; import com.yiling.ih.common.ApiResult; import com.yiling.ih.patient.enums.IHErrorCode; import com.yiling.ih.pharmacy.api.IHPharmacyApi; import com.yiling.ih.pharmacy.dto.IHPharmacyDTO; import com.yiling.ih.pharmacy.dto.request.SyncPharmacyRequest; import com.yiling.ih.pharmacy.dto.request.UpdateIHPharmacyStatusRequest; import com.yiling.ih.pharmacy.feign.IHPharmacyFeignClient; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.DubboService; import org.springframework.beans.factory.annotation.Autowired; import java.util.Objects; /** * IH 终端药店服务api * * @author: fan.shen * @date: 2022-11-18 */ @Slf4j @DubboService public class IHPharmacyApiImpl implements IHPharmacyApi { @Autowired private IHPharmacyFeignClient pharmacyFeignClient; @Override public IHPharmacyDTO syncPharmacy(SyncPharmacyRequest request) { ApiResult<IHPharmacyDTO> apiResult = pharmacyFeignClient.syncPharmacy(request); if (!apiResult.success() || Objects.isNull(apiResult.getData())) { log.error("[syncPharmacy]调用IH服务同步终端药店失败"); throw new BusinessException(IHErrorCode.SYNC_PHARMACY_ERROR); } return apiResult.getData(); } @Override public Boolean updatePharmacyStatus(UpdateIHPharmacyStatusRequest request) { ApiResult<Boolean> apiResult = pharmacyFeignClient.updatePharmacyStatus(request); if (!apiResult.success() || Objects.isNull(apiResult.getData())) { log.error("[updatePharmacyStatus]调用IH服务修改终端药店合作状态失败"); throw new BusinessException(IHErrorCode.SYNC_PHARMACY_ERROR); } return apiResult.getData(); } }
#include "lists.h" /** * add_node_end - add a new node at the end of a singly linked list. * @head: pointer to pointer to the head node. * @str: data to be stored in the node. * Return: pointer to the new node. */ list_t *add_node_end(list_t **head, const char *str) { list_t *new; list_t *current; new = malloc(sizeof(list_t)); if (!new) return (NULL); current = *head; new->str = strdup(str); new->len = strlen(str); if (*head == NULL) *head = new; else { while (current->next) current = current->next; current->next = new; } new->next = NULL; return (new); }
/* * Copyright (c) 2007, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.test.jdbc4; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import org.postgresql.test.TestUtil; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * This test-case is only for JDBC4 blob methods. Take a look at * {@link org.postgresql.test.jdbc2.BlobTest} for base tests concerning blobs */ class BlobTest { private Connection conn; @BeforeEach void setUp() throws Exception { conn = TestUtil.openDB(); TestUtil.createTable(conn, "testblob", "id name,lo oid"); conn.setAutoCommit(false); } @AfterEach void tearDown() throws Exception { conn.setAutoCommit(true); try { Statement stmt = conn.createStatement(); try { stmt.execute("SELECT lo_unlink(lo) FROM testblob"); } finally { try { stmt.close(); } catch (Exception e) { } } } finally { TestUtil.dropTable(conn, "testblob"); TestUtil.closeDB(conn); } } @Test void setBlobWithStream() throws Exception { byte[] data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque bibendum dapibus varius." .getBytes("UTF-8"); try ( PreparedStatement insertPS = conn.prepareStatement(TestUtil.insertSQL("testblob", "lo", "?")) ) { insertPS.setBlob(1, new ByteArrayInputStream(data)); insertPS.executeUpdate(); } try (Statement selectStmt = conn.createStatement() ) { try (ResultSet rs = selectStmt.executeQuery(TestUtil.selectSQL("testblob", "lo"))) { assertTrue(rs.next()); Blob actualBlob = rs.getBlob(1); byte[] actualBytes = actualBlob.getBytes(1, (int) actualBlob.length()); assertArrayEquals(data, actualBytes); } } } @Test void setBlobWithStreamAndLength() throws Exception { byte[] fullData = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse placerat tristique tellus, id tempus lectus." .getBytes("UTF-8"); byte[] data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.".getBytes("UTF-8"); try ( PreparedStatement insertPS = conn.prepareStatement(TestUtil.insertSQL("testblob", "lo", "?")) ) { insertPS.setBlob(1, new ByteArrayInputStream(fullData), data.length); insertPS.executeUpdate(); } try ( Statement selectStmt = conn.createStatement() ) { try (ResultSet rs = selectStmt.executeQuery(TestUtil.selectSQL("testblob", "lo"))) { assertTrue(rs.next()); Blob actualBlob = rs.getBlob(1); byte[] actualBytes = actualBlob.getBytes(1, (int) actualBlob.length()); assertArrayEquals(data, actualBytes); } } } @Test void getBinaryStreamWithBoundaries() throws Exception { byte[] data = "Cras vestibulum tellus eu sapien imperdiet ornare.".getBytes("UTF-8"); try ( PreparedStatement insertPS = conn.prepareStatement(TestUtil.insertSQL("testblob", "lo", "?")) ) { insertPS.setBlob(1, new ByteArrayInputStream(data), data.length); insertPS.executeUpdate(); } try ( Statement selectStmt = conn.createStatement() ) { try (ResultSet rs = selectStmt.executeQuery(TestUtil.selectSQL("testblob", "lo"))) { assertTrue(rs.next()); byte[] actualData = new byte[10]; Blob actualBlob = rs.getBlob(1); InputStream stream = actualBlob.getBinaryStream(6, 10); try { stream.read(actualData); assertEquals(-1, stream.read(new byte[1]), "Stream should be at end"); } finally { stream.close(); } assertEquals("vestibulum", new String(actualData, "UTF-8")); } } } @Test void getBinaryStreamWithBoundaries2() throws Exception { byte[] data = "Cras vestibulum tellus eu sapien imperdiet ornare.".getBytes("UTF-8"); try ( PreparedStatement insertPS = conn.prepareStatement(TestUtil.insertSQL("testblob", "lo", "?")) ) { insertPS.setBlob(1, new ByteArrayInputStream(data), data.length); insertPS.executeUpdate(); } try ( Statement selectStmt = conn.createStatement() ) { try (ResultSet rs = selectStmt.executeQuery(TestUtil.selectSQL("testblob", "lo"))) { assertTrue(rs.next()); byte[] actualData = new byte[9]; Blob actualBlob = rs.getBlob(1); try ( InputStream stream = actualBlob.getBinaryStream(6, 10) ) { // read 9 bytes 1 at a time for (int i = 0; i < 9; i++) { actualData[i] = (byte) stream.read(); } /* try to read past the end and make sure we get 1 byte */ assertEquals(1, stream.read(new byte[2]), "There should be 1 byte left"); /* now read one more and we should get an EOF */ assertEquals(-1, stream.read(new byte[1]), "Stream should be at end"); } assertEquals("vestibulu", new String(actualData, "UTF-8")); } } } @Test void free() throws SQLException { try ( Statement stmt = conn.createStatement() ) { stmt.execute("INSERT INTO testblob(lo) VALUES(lo_creat(-1))"); try (ResultSet rs = stmt.executeQuery("SELECT lo FROM testblob")) { assertTrue(rs.next()); Blob blob = rs.getBlob(1); blob.free(); try { blob.length(); fail("Should have thrown an Exception because it was freed."); } catch (SQLException sqle) { // expected } } } } }
/** * @file matriz_dispersa.h * @brief Fichero cabecera del TDA Matriz Dispersa * */ #ifndef _MATRIZ_DISPERSA_ #define _MATRIZ_DISPERSA_ #include "vd.h" #include <iostream> #include <fstream> #include <iterator> #include <cstring> #include <list> using namespace std; /** * @brief T.D.A Tripleta * * Una instancia @e del tipo de datos abstracto @c Tripleta es un objeto * que representa un struct de tripletas formadas por: fila, columna y el valor * asociado de tipo carácter. * * fila, columna, valor * * @author Pablo J. Jiménez Ortiz * @date Noviembre 2017 */ template <class T> struct tripleta{ int fila; /**<fila */ int columna; /**<columna */ T valor; /**<valor */ template<class U> friend ostream &operator<<(ostream &os, tripleta<U> const &t); template<class U> friend istream& operator>>(istream& is, tripleta<U> const &t); /** * @brief Operator = de una Tripleta * @param m tripleta que queremos igualar al objeto implícito * @retval La Tripleta leída en m * @post El objeto implícito de la llamada queda con los valores de la tripleta m recibida * como parámetro */ bool &operator<(tripleta &t){ return ((*this).fila < t.fila and (*this).columna < columna); } void operator=(const tripleta<T> &m){ this->fila = m->fila; this->columna = m->columna; this->valor = m->valor; } }; template<class U> ostream &operator<<(ostream &os, const tripleta<U> &t){ os << t->fila << " " << t->columna << " " << t->valor << endl; } /** * @brief Entrada de una Tripleta desde istream * @param is stream de entrada * @param t Tripleta que recibe el valor * @retval La Tripleta leído en t * @pre La entrada tiene el formato (fila/columna/valor) con \e fila,\e columna y \e valor los valores * de la tripleta t */ template<class U> istream& operator>>(istream& is, tripleta<U> &t){ int fila, columna; U valor; is >> fila >> columna >> valor; t.fila = fila; t.columna = columna; t.valor = valor; return is; } /** * @brief T.D.A Matriz Dispersa * * Una instancia @e del tipo de datos abstracto @c Matriz Dispersa es un objeto * que representa un array 1-d de tripletas formadas por: fila, columna y el valor * asociado de tipo carácter. * * v, valor_por_defecto * * @author Pablo J. Jiménez Ortiz * @date Noviembre 2017 */ template <class T> class Matriz_Dispersa{ private: /** * @page repMatrizDispersa Rep del TDA Matriz Dispersa * @section invConjunto Invariante de la representación * El invariante es que el tipo <T> debe ser de tipo tripleta * * @section faConjunto Funcion de abtracción * * Un objeto válido @e rep del TDA Matriz Dispersa representa al valor * * (rep.v, rep.valor_por_defecto) * */ list<tripleta<T>> v; /**<v */ T valor_por_defecto; /**< valor_por_defecto */ typename list<tripleta<T>>::iterator it; /**<it */ public: class iterator{ private: typename list<tripleta<T>>::iterator it; public: iterator &operator++(){ ++it; return *this; } iterator &operator--(){ --it; return *this; } const tripleta<T> &operator*(){ return *it; } bool &operator!=(iterator t){ return it != t.it; } bool &operator==(iterator t){ return it == t.it; } void advance(int n){ std::advance(it, n); } friend class Matriz_Dispersa<T>; }; class const_iterator{ private: typename list<tripleta<T>>::const_iterator it; public: const_iterator &operator++(){ ++it; return *this; } const_iterator &operator--(){ --it; return *this; } const tripleta<T> &operator*(){ return *it; } bool &operator!=(const_iterator t){ return it != t.it; } bool &operator==(const_iterator t){ return it == t.it; } void advance(int n){ std::advance(it, n); } friend class Matriz_Dispersa<T>; }; iterator begin(){ return v.begin(); } iterator end(){ return v.end(); } const_iterator cbegin(){ return v.cegin(); } const_iterator cend(){ return v.cend(); } /** * @brief Constructor por defecto de la clase. Define el valor por defecto * de nuestra matriz a 0 */ Matriz_Dispersa(): valor_por_defecto(0){} /** * @brief Constructor por defecto de la clase. * @param defecto valor por defecto de nuestra matriz * @return Crea la matriz dispersa con valor por defecto defecto * @pre defecto debe ser de tipo char */ Matriz_Dispersa(T defecto):valor_por_defecto(defecto){} /** * @brief Destructor de la clase * @return Libera la memoria asociada al objeto implícito */ ~Matriz_Dispersa(); typename Matriz_Dispersa<T>::iterator& operator[](int posicion)const; /** * @brief Elemento * @param fil fila en la que se encuentra el elemento que queremos obtener * @param col columna en la que se encuentra el elemento que queremos obtener * @return Devuelve el elemento contenido en la posicion (fil, col) de la matriz */ T getElemento(int fil, int col)const; /** * @brief MayorFila * @return Devuelve la fila mayor contenida en la matriz */ int mayorFila()const; /** * @brief MayorColumna * @return Devuelve la columna mayor contenida en la matriz */ int mayorColumna()const; /** * @brief Size * @return Devuelve el tamaño de la matriz */ int size()const; /** * @brief MenorFila * @return Devuelve la fila menor contenida en la matriz */ int menorFila()const; /** * @brief MenorColumna * @return Devuelve la columna menor contenida en la matriz */ int menorColumna()const; /** * @brief ValorPorDefecto * @return Devuelve el valor por defecto de la matriz */ T ValorPorDefecto()const; /** * @brief CasillasOcupadas * @return Devuelve el número de casillas ocupadas de la matriz */ int casillasOcupadas()const; /** * @brief NumeroFilas * @return Devuelve el número de filas de la matriz */ int numeroFilas()const; /** * @brief NumeroColumnas * @return Devuelve el número de columnas de la matriz */ int numeroColumnas()const; /** * @brief Esta * @return Devuelve el número de filas de la matriz */ bool Esta(int fil, int col)const; /** * @brief Set * @param fil fila en la que se encuentra el elemento de la matriz que quieres cambiar * @param col columna en la que se encuentra el elemento de la matriz que quieres cambiar * @valor valor que quieres introducir en el elemento (fil,col) * @return Asigna al elemento (fil,col) del objeto implícito el * valor recibido como parámetro */ void Set(int fil, int col, T value); /** * @brief Insertar * @param fila fila en la que se encuentra el elemento de la matriz que quieres cambiar * @param columna columna en la que se encuentra el elemento de la matriz que quieres cambiar * @valor tripleta elemento que quieres insertar en la matriz * @return Inserta al elemento (fila,columna) del objeto implícito la tripleta recibida * recibida como parámetro */ void Insertar(tripleta<T> t); /** * @brief Entrada de una Matriz Dispersa desde istream * @param is stream de entrada * @param t Matriz Dispersa que recibe el valor * @retval La Matriz Dispersa leído en t * @pre La entrada tiene el formato (v/valor_por_defecto) con \e v,\e valor_por_defecto los valores * de los elementos de la matriz y el valor por defecto */ friend istream& operator>>(istream& is, Matriz_Dispersa<T> &t){ T defecto; tripleta<T> tri; is >> defecto; Matriz_Dispersa<T> aux(defecto); while(is.good()){ // mientras el flujo esté ok is >> tri; // operator >> de tripleta aux.Insertar(tri); } if(is){ t = aux; } return is; } /** * @brief Salida de una matriz dispersa a ostream * @param os stream de salida * @param t Matriz Dispersa a escribir * @post Se obtiene en \a os la cadena (v/valor_por_defecto) con \e num,den los valores * de los elementos de la matriz y el valor por defecto de las tripletas de \a t */ friend ostream& operator<<(ostream& os, Matriz_Dispersa<T> &t){ for(typename Matriz_Dispersa<T>::iterator ite = t.begin(); ite != t.end(); ite++){ for(int i = 0; i < t.numeroFilas(); i++){ for(int j = 0; j < t.numeroColumnas(); j++){ if(t.Esta(i, j)) os << (*ite).valor << " "; else os << t.ValorPorDefecto() << " "; } os << endl; } } return os; } }; #include "matriz_dispersa.cpp" #endif
import React, { useEffect, useState } from "react"; import { Button, Table } from "antd"; import "./customers.scss"; import { useDispatch, useSelector } from "react-redux"; import { getUsers } from "../../../features/user/userSlice"; const columns = [ { title: "SNo", dataIndex: "key", }, { title: "Name", dataIndex: "name", sorter: (a, b) => a.name.length - b.name.length, }, { title: "Email", dataIndex: "email", sorter: (a, b) => a.email.length - b.email.length, }, { title: "Mobile", dataIndex: "mobile", sorter: (a, b) => a.mobile.length - b.mobile.length, }, ]; const Customers = () => { const dispatch = useDispatch(); useEffect(() => { dispatch(getUsers()); }, []); const userState = useSelector((state) => state.user.user); const data = userState.users ? userState.users.map((user, index) => ({ key: index + 1, name: `${user.firstname} ${user.lastname}`, email: user.email, mobile: user.mobile, })) : []; return ( <div className="customers"> <div className="header"> <h1>Customers</h1> </div> <div className="content"> <Table columns={columns} dataSource={data} /> </div> </div> ); }; export default Customers;
# Awesome RSS reader [![License: MIT][license-img]][license] [![Powered by Python][python-img]][python] [![Code style: black][black-img]][black] [![Ruff][ruff-img]][ruff] [![codecov][codecov-img]][codecov] [![ci][ci-img]][ci] ## API documentation For actual API documentation, please refer to the [swagger][swagger] at [arr.khoroshilov.tech](https://arr.khoroshilov.tech/). ## Getting started Firstly, you'll want to set up your own configuration using a .env file: ```shell cp .env.example .env ``` In the copied `.env` file, set `AUTH_SECRET_KEY` variable to a random string. To generate a random string, you can use the following command: ```shell openssl rand -hex 32 ```` The development server is set to work with the default variables out of the box. However, if needed, you can modify these variables later for a more personalized setup. Run the development server stack: ```shell docker-compose up ``` This will start the development server on port 8000. PostgreSQL instance that comes with the development stack uses the port 5432. This port is exposed on your machine as well. Apply the migrations: ```shell docker-compose exec devserver alembic upgrade head ``` Once done, you'll be able to access the development server at `http://localhost:8000`. ⚠️ Important: The database container running with the dev server is **not persistent**. When you stop the development stack, the data goes away. 💡 If you want your changes to stick around, consider running a separate PostgreSQL instance. You can then adjust the `POSTGRES_DB_DSN` variable accordingly. ## Testing ⚠️ For the test suite to work, it needs PostgreSQL. Ensure the development stack is up and running. Running the test suite is as straightforward as: ```shell pytest ``` ## License Released under the [MIT License](LICENSE.txt). [license-img]: https://img.shields.io/badge/License-MIT-yellow.svg [license]: https://opensource.org/licenses/MIT [python-img]: https://img.shields.io/badge/python-3.11-blue.svg [python]: https://www.python.org/downloads/release/python-3110/ [black-img]: https://img.shields.io/badge/code%20style-black-000000.svg [black]: https://github.com/psf/black [ruff-img]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json [ruff]: https://github.com/astral-sh/ruff [codecov-img]: https://codecov.io/gh/sergei-doing-tests/awesome-rss-reader/branch/main/graph/badge.svg?token=A0JV2BRV23 [codecov]: https://codecov.io/gh/sergei-doing-tests/awesome-rss-reader [ci-img]: http://github.com/sergei-doing-tests/awesome-rss-reader/actions/workflows/ci.yml/badge.svg?branch=main [ci]: http://github.com/sergei-doing-tests/awesome-rss-reader/actions/workflows/ci.yml [swagger]: https://arr.khoroshilov.tech/docs
<template> <view class="normal-login-container"> <view class="logo-content align-center justify-center flex"> <image style="width: 100rpx;height: 100rpx;" :src="globalConfig.appInfo.logo" mode="widthFix"> </image> <text class="title">移动端登录</text> </view> <view class="login-form-content"> <view class="input-item flex align-center"> <view class="iconfont icon-user icon"></view> <input v-model="loginForm.username" class="input" type="text" placeholder="请输入账号" maxlength="30" /> </view> <view class="input-item flex align-center"> <view class="iconfont icon-password icon"></view> <input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" /> </view> <view class="input-item flex align-center" v-if="captchaEnabled"> <view class="iconfont icon-code icon"></view> <input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" /> <image :src="codeUrl" @click="getCode" class="login-code-img"></image> </view> <view class="action-btn"> <button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round">登录</button> </view> </view> <!-- 版本更新提示信息 --> <view v-if="shouldShowUpdateTip" class="update-tip"> 有新的版本可以更新 </view> </view> </template> <script> import { getCodeImg } from "@/api/login"; export default { data() { return { codeUrl: "", captchaEnabled: true, globalConfig: getApp().globalData.config, loginForm: { username: "admin", password: "admin123", code: "", uuid: "", }, shouldShowUpdateTip: false, }; }, created() { this.getCode(); plus.runtime.getProperty(plus.runtime.appid, (res) => { console.log("当前版本"); console.log(res); this.version = res.versionCode; // this.version = 101; }); this.getNewVersion(); }, methods: { // 隐私协议 handlePrivacy() { let site = this.globalConfig.appInfo.agreements[0]; this.$tab.navigateTo( `/pages/common/webview/index?title=${site.title}&url=${site.url}` ); }, // 用户协议 handleUserAgrement() { let site = this.globalConfig.appInfo.agreements[1]; this.$tab.navigateTo( `/pages/common/webview/index?title=${site.title}&url=${site.url}` ); }, // 获取图形验证码 getCode() { getCodeImg().then((res) => { this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled; if (this.captchaEnabled) { this.codeUrl = "data:image/gif;base64," + res.img; this.loginForm.uuid = res.uuid; } }); }, // 登录方法 async handleLogin() { if (this.loginForm.username === "") { this.$modal.msgError("请输入您的账号"); } else if (this.loginForm.password === "") { this.$modal.msgError("请输入您的密码"); } else if (this.loginForm.code === "" && this.captchaEnabled) { this.$modal.msgError("请输入验证码"); } else { this.$modal.loading("登录中,请耐心等待..."); this.pwdLogin(); } }, // 密码登录 async pwdLogin() { this.$store .dispatch("Login", this.loginForm) .then(() => { this.$modal.closeLoading(); this.loginSuccess(); }) .catch(() => { if (this.captchaEnabled) { this.getCode(); } }); }, // 登录成功后,处理函数 loginSuccess(result) { // 设置用户信息 this.$store.dispatch("GetInfo").then((res) => { // this.$tab.reLaunch('/pages/workModel/workModel') this.$tab.reLaunch("/pages/work/index"); }); }, // 获取最新版本 getNewVersion() { let that = this; uni.request({ url: "http://121.199.30.10:19000/appStoreFile/version.json", data: {}, header: {}, method: "GET", success: (res) => { // 如果当前版本小于最新版本,就更改shouldShowUpdateTip if (that.version < res.data.version) { that.shouldShowUpdateTip = true; } }, }); }, }, }; </script> <style lang="scss"> page { background-color: #ffffff; } .normal-login-container { width: 100%; .logo-content { width: 100%; font-size: 21px; text-align: center; padding-top: 15%; image { border-radius: 4px; } .title { margin-left: 10px; } } .login-form-content { text-align: center; margin: 20px auto; margin-top: 15%; width: 80%; .input-item { margin: 20px auto; background-color: #f5f6f7; height: 45px; border-radius: 20px; .icon { font-size: 38rpx; margin-left: 10px; color: #999; } .input { width: 100%; font-size: 14px; line-height: 20px; text-align: left; padding-left: 15px; } } .login-btn { margin-top: 40px; height: 45px; } .xieyi { color: #333; margin-top: 20px; } } .easyinput { width: 100%; } } .login-code-img { height: 45px; } .update-tip { position: fixed; top: 0; left: 0; width: 100%; height: 50px; background-color: #ff0000; color: #ffffff; font-size: 16px; text-align: center; line-height: 50px; } </style>
import Link from "next/link"; import { axiosClient } from "@/utils/axios-client.js"; import { useState } from "react"; import { useRouter } from "next/router"; export default function Register() { const router = useRouter(); const [name, setName] = useState(""); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const handleRegister = async (e) => { e.preventDefault(); try { await axiosClient.post("/api/users", { name, username, password, }); router.push("/login"); } catch (error) { console.error(error); } }; return ( <div style={{ padding: "2rem" }}> <div className="card" style={{ width: "18rem" }}> <div className="card-body"> <form method="POST" onSubmit={(e) => handleRegister(e)}> <div className="mb-3"> <label htmlFor="fullName" className="form-label"> Full name </label> <input type="text" className="form-control" id="fullName" placeholder="Input your full name" value={name} onChange={(e) => setName(e.target.value)} /> </div> <div className="mb-3"> <label htmlFor="username" className="form-label"> Username </label> <input type="text" className="form-control" id="username" placeholder="Input your username" value={username} onChange={(e) => setUsername(e.target.value)} /> </div> <div className="mb-3"> <label htmlFor="password" className="form-label"> Password </label> <input type="password" className="form-control" id="password" placeholder="Input your password" value={password} onChange={(e) => setPassword(e.target.value)} /> </div> <button type="submit" className="btn btn-primary"> Register </button> </form> <p style={{ marginTop: "1rem" }}> <Link href="/login">Click here to login</Link> </p> </div> </div> </div> ); }
<div class="row"> <h1 class="text-center text-primary mt-5">Register </h1> <form *ngIf="registerForm" [formGroup]="registerForm" (ngSubmit)="addregister()" class="offset-md-2 col-md-8 my-5"> <div class="row"> <div> <div class="mb-3"> <label for="name" class="form-label">Company Name</label> <input type="text" class="form-control" id="name" placeholder="Type the name here" formControlName="companyName" [ngClass]="{'is-valid': submitted && !registerForm.get('name')?.errors ,'is-invalid': submitted && registerForm.get('name')?.errors}"> <div class="invalid-feedback" *ngIf="submitted && registerForm.get('name')?.hasError('required')"> Name is required. </div> </div> </div> <div> <div class="mb-3"> <label for="description" class="form-label">Company Description</label> <input type="text" class="form-control" id="description" placeholder="Type the description here" formControlName="companyDescription" [ngClass]="{'is-valid': submitted && !registerForm.get('description')?.errors ,'is-invalid': submitted && registerForm.get('description')?.errors}"> <div class="invalid-feedback" *ngIf="submitted && registerForm.get('description')?.hasError('required')"> Description is required. </div> </div> </div> <div> <div class="mb-3"> <label for="email" class="form-label"> Email</label> <input type="email" class="form-control" id="email" placeholder="Type the email here" formControlName="email" [ngClass]="{'is-valid': submitted && !registerForm.get('email')?.errors ,'is-invalid': submitted && registerForm.get('email')?.errors}"> <div class="invalid-feedback" *ngIf="submitted && registerForm.get('email')?.hasError('required')"> Email is required. </div> </div> </div> <div> <div class="mb-3"> <label for="password" class="form-label">Password</label> <input type="password" class="form-control" id="password" placeholder="Type the password here" formControlName="password" [ngClass]="{'is-valid': submitted && !registerForm.get('password')?.errors ,'is-invalid': submitted && registerForm.get('password')?.errors}"> <div class="invalid-feedback" *ngIf="submitted && registerForm.get('password')?.hasError('required')"> Password is required. </div> </div> </div> </div> <div class="row"> <button type="submit" class="btn btn-success"> <i class="fa fa-save"></i> Creat account </button> </div> </form> </div> <!-- <div class="bg-light min-vh-100 d-flex flex-row align-items-center"> <c-container> <c-row class="justify-content-center"> <c-col lg="7" md="9" xl="6"> <c-card class="mx-4"> <c-card-body class="p-4"> <form cForm *ngIf="registerForm" [formGroup]="registerForm" (ngSubmit)="addregister()" class="offset-md-2 col-md-8 my-5"> <h1>Register</h1> <p class="text-medium-emphasis">Create your account</p> <c-input-group class="mb-3"> <span cInputGroupText> <svg cIcon name="cilUser"></svg> </span> <input autoComplete="companyName" cFormControl placeholder="CompanyName" type="text" class="form-control" id="companyName" formControlName="companyName" [ngClass]="{'is-valid': submitted && !registerForm.get('companyName')?.errors ,'is-invalid': submitted && registerForm.get('companyName')?.errors}"> <div class="invalid-feedback" *ngIf="submitted && registerForm.get('companyName')?.hasError('required')"> Name is required. </div> </c-input-group> <c-input-group class="mb-3"> <span cInputGroupText> <svg cIcon name="cilCommentSquare"></svg> </span> <input autoComplete="companyDescription" cFormControl placeholder="CompanyDescription" type="text" class="form-control" id="companyDescription" formControlName="companyDescription" [ngClass]="{'is-valid': submitted && !registerForm.get('companyDescription')?.errors ,'is-invalid': submitted && registerForm.get('companyDescription')?.errors}"> <div class="invalid-feedback" *ngIf="submitted && registerForm.get('companyDescription')?.hasError('required')"> Description is required. </div> </c-input-group> <c-input-group class="mb-3"> <span cInputGroupText>@</span> <input autoComplete="email" cFormControl placeholder="Email" type="email" class="form-control" id="email" formControlName="email" [ngClass]="{'is-valid': submitted && !registerForm.get('email')?.errors ,'is-invalid': submitted && registerForm.get('email')?.errors}"> <div class="invalid-feedback" *ngIf="submitted && registerForm.get('email')?.hasError('required')"> Email is required. </div> </c-input-group> <c-input-group class="mb-3"> <span cInputGroupText> <svg cIcon name="cilLockLocked"></svg> </span> <input autoComplete="password" cFormControl placeholder="Password" type="password" class="form-control" id="password" formControlName="password" [ngClass]="{'is-valid': submitted && !registerForm.get('password')?.errors ,'is-invalid': submitted && registerForm.get('password')?.errors}"> <div class="invalid-feedback" *ngIf="submitted && registerForm.get('password')?.hasError('required')"> Password is required. </div> </c-input-group> <c-input-group class="mb-4"> <span cInputGroupText> <svg cIcon name="cilContact"></svg> </span> <input autoComplete="role" cFormControl placeholder="Role" type="text" class="form-control" id="role" formControlName="role" [ngClass]="{'is-valid': submitted && !registerForm.get('role')?.errors ,'is-invalid': submitted && registerForm.get('role')?.errors}"> <div class="invalid-feedback" *ngIf="submitted && registerForm.get('role')?.hasError('required')"> Role is required. </div> </c-input-group> <div class="d-grid"> <button cButton color="success">Create Account</button> </div> </form> </c-card-body> </c-card> </c-col> </c-row> </c-container> </div> -->
""" update_uni_dict_internal!(model::LikelihoodModel, uni_row_number::Int, points::PointsAndLogLikelihood) Updates the `interval_points` field of a [`UnivariateConfidenceStruct`](@ref), for the profile related to `uni_row_number` stored at `model.uni_profiles_dict[uni_row_number]`, with the interval points stored in `points`. """ function update_uni_dict_internal!(model::LikelihoodModel, uni_row_number::Int, points::PointsAndLogLikelihood) interval_struct = model.uni_profiles_dict[uni_row_number] model.uni_profiles_dict[uni_row_number] = @set interval_struct.interval_points = points return nothing end # function update_uni_df_internal_points!(model::LikelihoodModel, # uni_row_number::Int, # num_points_in_interval::Int) # # model.uni_profiles_df[uni_row_number, [:not_evaluated_internal_points, :num_points]] .= false, num_points_in_interval+2 # # return nothing # end """ get_points_in_interval_single_row(univariate_optimiser::Function, model::LikelihoodModel, num_points_in_interval::Int, θi::Int, profile_type::AbstractProfileType, θlb_nuisance::AbstractVector{<:Real}, θub_nuisance::AbstractVector{<:Real}, current_interval_points::PointsAndLogLikelihood, additional_width::Real, use_threads::Bool) Method for getting `num_points_in_interval` points inside a confidence interval for parameter `θi`, directly called by [`LikelihoodBasedProfileWiseAnalysis.univariate_confidenceinterval`](@ref) and called via it's other method for [`get_points_in_intervals!`](@ref). Adds `additional_width` outside of the confidence interval, so long as a parameter bound is not reached. If a bound is reached, up until the bound will be considered instead. """ function get_points_in_interval_single_row(univariate_optimiser::Function, model::LikelihoodModel, num_points_in_interval::Int, θi::Int, profile_type::AbstractProfileType, θlb_nuisance::AbstractVector{<:Real}, θub_nuisance::AbstractVector{<:Real}, current_interval_points::PointsAndLogLikelihood, additional_width::Real, optimizationsettings::OptimizationSettings, use_threads::Bool) num_points_in_interval > 0 || throw(DomainError("num_points_in_interval must be a strictly positive integer")) additional_width >= 0 || throw(DomainError("additional_width must be greater than or equal to zero")) boundary_indices = current_interval_points.boundary_col_indices newLb, newUb, initGuess, θranges, ωranges = init_nuisance_parameters(model, θi, θlb_nuisance, θub_nuisance) consistent = get_consistent_tuple(model, 0.0, profile_type, 1) q=(ind=θi, newLb=newLb, newUb=newUb, initGuess=initGuess, θranges=θranges, ωranges=ωranges, consistent=consistent, options=optimizationsettings) point_locations = zeros(0) if additional_width > 0.0 boundary = current_interval_points.points[θi, boundary_indices] boundary_width = diff(boundary)[1] half_add_width = boundary_width * (additional_width / 2.0) interval_to_eval = [max(boundary[1]-half_add_width, model.core.θlb[θi]), min(boundary[2]+half_add_width, model.core.θub[θi])] interval_width = diff(interval_to_eval)[1] additional_widths = [boundary[1]-interval_to_eval[1], interval_to_eval[2]-boundary[2]] points_in_each_interval = [0, num_points_in_interval+2, 0] if additional_widths[1] > 0.0 num_points = convert(Int, max(1.0, round((additional_widths[1]/interval_width)*num_points_in_interval, RoundDown))) points_in_each_interval[1] = num_points append!(point_locations, LinRange(interval_to_eval[1], boundary[1], points_in_each_interval[1]+1)[1:(end-1)] ) end append!(point_locations, LinRange(boundary[1], boundary[2], num_points_in_interval+2) ) if additional_widths[2] > 0.0 num_points = convert(Int, max(1.0, round((additional_widths[2]/interval_width)*num_points_in_interval, RoundDown))) points_in_each_interval[3] = num_points append!(point_locations, LinRange(boundary[2], interval_to_eval[2], points_in_each_interval[3]+1)[2:end] ) end new_boundary_indices = [points_in_each_interval[1]+1, points_in_each_interval[1]+points_in_each_interval[2]] else new_boundary_indices = [1, num_points_in_interval+2] point_locations = LinRange(current_interval_points.points[θi, boundary_indices[1]], current_interval_points.points[θi, boundary_indices[2]], num_points_in_interval+2) end total_points = length(point_locations) ll = zeros(total_points) interval_points = zeros(model.core.num_pars, total_points) ll[new_boundary_indices] .= current_interval_points.ll[boundary_indices] interval_points[:,new_boundary_indices[1]] .= current_interval_points.points[:,boundary_indices[1]] interval_points[:,new_boundary_indices[2]] .= current_interval_points.points[:,boundary_indices[2]] iter_inds = setdiff(1:total_points, new_boundary_indices) ex = use_threads ? ThreadedEx() : ThreadedEx(basesize=length(iter_inds)) let point_locations = point_locations @floop ex for i in iter_inds FLoops.@init ω_opt = zeros(model.core.num_pars-1) p = (ω_opt=ω_opt, q=q, options=model.core.optimizationsettings) ll[i] = univariate_optimiser(point_locations[i], p) variablemapping!(@view(interval_points[:,i]), p.ω_opt, θranges, ωranges) # p.initGuess .= p.ω_opt .* 1.0 end end interval_points[θi,iter_inds] .= point_locations[iter_inds] return PointsAndLogLikelihood(interval_points, ll, new_boundary_indices) end """ get_points_in_interval_single_row(model::LikelihoodModel, uni_row_number::Int, num_points_in_interval::Int, additional_width::Real, θlb_nuisance::AbstractVector{<:Real}, θub_nuisance::AbstractVector{<:Real}, use_threads::Bool, channel::RemoteChannel) Alternate method called by [`get_points_in_intervals!`](@ref). """ function get_points_in_interval_single_row(model::LikelihoodModel, uni_row_number::Int, num_points_in_interval::Int, additional_width::Real, θlb_nuisance::AbstractVector{<:Real}, θub_nuisance::AbstractVector{<:Real}, optimizationsettings::OptimizationSettings, use_threads::Bool, channel::RemoteChannel) try @timeit_debug timer "Univariate points in interval" begin θi = model.uni_profiles_df.θindex[uni_row_number] profile_type = model.uni_profiles_df.profile_type[uni_row_number] univariate_optimiser = get_univariate_opt_func(profile_type) current_interval_points = get_uni_confidence_interval_points(model, uni_row_number) output = get_points_in_interval_single_row(univariate_optimiser, model, num_points_in_interval, θi, profile_type, θlb_nuisance, θub_nuisance, current_interval_points, additional_width, optimizationsettings, use_threads) put!(channel, true) return output end catch @error string("an error occurred when finding the points inside a univariate confidence interval with settings: ", (uni_row_number=uni_row_number, num_points_in_interval=num_points_in_interval, additional_width=additional_width)) for (exc, bt) in current_exceptions() showerror(stdout, exc, bt) println(stdout) println(stdout) end end return nothing end """ get_points_in_intervals!(model::LikelihoodModel, num_points_in_interval::Int; <keyword arguments>) Evaluate and save `num_points_in_interval` linearly spaced points between the confidence intervals of existing univariate profiles that meet the requirements of the univariate method of [`LikelihoodBasedProfileWiseAnalysis.desired_df_subset`](@ref) (see Keyword Arguments), as well as any additional width on the sides of the interval. Modifies `model` in place. # Arguments - `model`: a [`LikelihoodModel`](@ref) containing model information, saved profiles and predictions. - `num_points_in_interval`: an integer number of points to evaluate within the confidence interval. Points are linearly spaced in the interval and have their optimised log-likelihood value recorded (standardised to 0.0 at the MLE point). Useful for plots that visualise the confidence interval or for predictions from univariate profiles. # Keyword Arguments - `additional_width`: a `Real` number greater than or equal to zero. Specifies the additional width to optionally evaluate outside the confidence interval's width. Half of this additional width will be placed on either side of the confidence interval. If the additional width goes outside a bound on the parameter, only up to the bound will be considered. The spacing of points in the additional width will try to match the spacing of points evaluated inside the interval. Useful for plots that visualise the confidence interval as it shows the trend of the log-likelihood profile outside the interval range. Default is `0.0`. - `confidence_levels`: a vector of confidence levels. If empty, all confidence levels of univariate profiles will be considered for finding interval points. Otherwise, only confidence levels in `confidence_levels` will be considered. Default is `Float64[]` (any confidence level). - `dofs`: a vector of integer degrees of freedom used to define the asymptotic threshold for the extremities of a univariate profile. If empty, all degrees of freedom for univariate profiles will be considered for evaluating predictions from. Otherwise, only degrees of freedom in `dofs` will be considered. Default is `Int[]` (any degree of freedom). - `profile_types`: a vector of `AbstractProfileType` structs. If empty, all profile types of univariate profiles are considered. Otherwise, only profiles with matching profile types will be considered. Default is `AbstractProfileType[]` (any profile type). - `θlb_nuisance`: a vector of lower bounds on nuisance parameters, require `θlb_nuisance .≤ model.core.θmle`. Default is `model.core.θlb`. - `θub_nuisance`: a vector of upper bounds on nuisance parameters, require `θub_nuisance .≥ model.core.θmle`. Default is `model.core.θub`. - `not_evaluated_predictions`: a boolean specifying whether to only get points in intervals of profiles that have not had predictions evaluated (true) or for all profiles (false). If `false`, then any existing predictions will be forgotten by the `model` and overwritten the next time predictions are evaluated for each profile. Default is `true`. - `optimizationsettings`: a [`OptimizationSettings`](@ref) containing the optimisation settings used to find optimal values of nuisance parameters for a given interest parameter value. Default is `missing` (will use `model.core.optimizationsettings`). - `show_progress`: boolean variable specifying whether to display progress bars on the percentage of `θs_to_profile` completed and estimated time of completion. Default is `model.show_progress`. - `use_threads`: boolean variable specifying, if the number of workers for distributed computing is not greater than 1 (`!Distributed.nworkers()>1`), to use a parallelised for loop across `Threads.nthreads()` threads to evaluate the interval points. Default is `false`. # Details Interval points and their corresponding log-likelihood values are stored in the `interval_points` field of a [`UnivariateConfidenceStruct`](@ref). These are updated using [`LikelihoodBasedProfileWiseAnalysis.update_uni_dict_internal!`](@ref). Nuisance parameters of each point in univariate interest parameter space are found by maximising the log-likelihood function given by the `profile_type` of the profile. If [`get_points_in_intervals!`](@ref) has already been used on a univariate profile, with the same values of `num_points_in_interval` and `additional_width`, it will not be recomputed for that profile. ## Parallel Computing Implementation If [Distributed.jl](https://docs.julialang.org/en/v1/stdlib/Distributed/) is being used then each set of interval points for distinct interest parameters will be computed in parallel across `Distributed.nworkers()` workers. If it is not being used (`Distributed.nworkers()` is equal to `1`) and `use_threads` is `true` then the interval points of each interest parameter will be computed in parallel across `Threads.nthreads()` threads . It is highly recommended to set `use_threads` to `true` in that situation. ## Iteration Speed Of the Progress Meter An iteration within the progress meter is specified as the time it takes for all internal points within a univariate confidence interval to be found (as well as any outside, if `additional_width` is greater than zero). """ function get_points_in_intervals!(model::LikelihoodModel, num_points_in_interval::Int; additional_width::Real=0.0, confidence_levels::Vector{<:Float64}=Float64[], dofs::Vector{<:Int}=Int[], profile_types::Vector{<:AbstractProfileType}=AbstractProfileType[], θlb_nuisance::AbstractVector{<:Float64}=model.core.θlb, θub_nuisance::AbstractVector{<:Float64}=model.core.θub, not_evaluated_predictions::Bool=true, optimizationsettings::Union{OptimizationSettings,Missing}=missing, show_progress::Bool=model.show_progress, use_threads::Bool=false) function argument_handling() num_points_in_interval > 0 || throw(DomainError("num_points_in_interval must be a strictly positive integer")) additional_width >= 0 || throw(DomainError("additional_width must be greater than or equal to zero")) model.core isa CoreLikelihoodModel || throw(ArgumentError("model does not contain a log-likelihood function. Add it using add_loglikelihood_function!")) length(θlb_nuisance) == model.core.num_pars || throw(ArgumentError("θlb_nuisance must have the same length as the number of model parameters")) length(θub_nuisance) == model.core.num_pars || throw(ArgumentError("θub_nuisance must have the same length as the number of model parameters")) all(θlb_nuisance .≤ model.core.θmle) || throw(DomainError("θlb_nuisance must be less than or equal to model.core.θmle")) all(θub_nuisance .≥ model.core.θmle) || throw(DomainError("θub_nuisance must be greater than or equal to model.core.θmle")) (use_threads && timeit_debug_enabled()) && throw(ArgumentError("use_threads cannot be true when debug timings from TimerOutputs are enabled. Either set use_threads to false or disable debug timings using `LikelihoodBasedProfileWiseAnalysis.TimerOutputs.disable_debug_timings(LikelihoodBasedProfileWiseAnalysis)`")) (use_threads && nworkers() > 1) && throw(ArgumentError("use_threads cannot be true when the number of workers for distributed computing is greater than 1 (`Distributed.nworkers()>1`). Either set use_threads to false or remove these workers using `Distributed.rmprocs(workers())`")) end argument_handling() optimizationsettings = ismissing(optimizationsettings) ? model.core.optimizationsettings : optimizationsettings sub_df = desired_df_subset(model.uni_profiles_df, model.num_uni_profiles, Int[], confidence_levels, dofs, profile_types, for_points_in_interval=(true, num_points_in_interval, additional_width), for_prediction_generation=not_evaluated_predictions) if nrow(sub_df) < 1 return nothing end p = Progress(nrow(sub_df); desc="Computing points in univariate confidence intervals: ", dt=PROGRESS__METER__DT, enabled=show_progress, showspeed=true) channel = RemoteChannel(() -> Channel{Bool}(1)) @sync begin @async while take!(channel) next!(p) end @async begin points_to_add = @distributed (vcat) for i in 1:nrow(sub_df) [(sub_df[i, :row_ind], get_points_in_interval_single_row(model, sub_df[i, :row_ind], num_points_in_interval, additional_width, θlb_nuisance, θub_nuisance, optimizationsettings, use_threads, channel))] end put!(channel, false) for (i, (row_ind, points)) in enumerate(points_to_add) if isnothing(points); continue end update_uni_dict_internal!(model, row_ind, points) end end end sub_df[:, :not_evaluated_internal_points] .= false sub_df[:, :not_evaluated_predictions] .= true sub_df[:, :num_points] .= num_points_in_interval+2 sub_df[:, :additional_width] .= additional_width return nothing end
import "./App.css"; import { AuthContext } from "./context/authContext"; import { LoadingContext } from "./context/loadingContext"; import { useContext } from "react"; import { Routes, Route } from "react-router-dom"; import { useState, useEffect } from "react"; import axios from "axios"; import Home from "./pages/Home"; import Cars from "./pages/Cars"; import Navbar from "./components/Navbar"; import Signup from "./pages/Signup"; import Events from "./pages/Events"; import Login from "./pages/Login"; import Profile from "./pages/Profile"; import Landing from "./pages/Landing"; import Family from "./pages/Family"; import Locations from "./pages/Locations"; function App() { const { getToken, user } = useContext(LoadingContext); return ( <> {!getToken() && ( <> <Routes> <Route path='/' element={<Landing />} /> <Route path='/signup' element={<Signup />} /> <Route path='/login' element={<Login />} /> <Route path='*' element={<Landing />} /> </Routes> </> )} {/* PROTECTED ROUTES */} {getToken() && ( <> <Navbar> <Routes> <Route path='/cars' element={<Cars />} /> <Route path='/events' element={<Events />} /> <Route path='/profile' element={<Profile />} /> <Route path='/family' element={<Family />} /> <Route path='/locations' element={<Locations />} /> <Route path='*' element={<Events />} /> </Routes> </Navbar> </> )} </> ); } export default App;
#include <cs50.h> #include <stdio.h> int main(void) { // declare int variable of height int height; do { height = get_int("Height: "); } while (height < 1 || height > 8); // we should check that height is not less than 1 or greater than 8 for (int row = 0; row < height; row++) // print new line as row { for (int space = height - row - 1; space > 0; space--) // print sapce { printf("."); } for (int hash = 0; hash < row + 1; hash++) // print(#) { printf("#"); } printf("\n"); } }
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger" import { IsBoolean, IsEnum, IsString } from "class-validator" import { MultiverseVersion } from "../../config/constants" export class AssetDto { @ApiProperty({ description: 'Asset name' }) @IsString() name: string @ApiProperty({ description: 'Asset address' }) @IsString() assetAddress: string @ApiProperty({ description: 'Asset id, aka token id' }) @IsString() assetId: string @ApiProperty({ description: 'Asset type, aka token type' }) @IsString() assetType: string @ApiProperty({ description: 'Amount of the asset in ether' }) @IsString() amount: string @ApiProperty({ description: 'Whether the assets are combined and have a balance' }) @IsBoolean() treatAsFungible: boolean @ApiProperty({ description: 'Whether the asset can be exported as a token' }) @IsBoolean() exportable: boolean @ApiProperty({ description: 'Whether to show asset in-game resource/ on-chain resources' }) @IsBoolean() summonable: boolean @ApiProperty({ description: 'Asset will be shown in inventory but not able to be summoned if false' }) @IsBoolean() inventorySummonEnabled: boolean @ApiProperty({ description: 'Recognized Asset Type, MSAMA | TICKET | TEST | PLOT | OFFHAND | WEAPON_SKIN | TEMPORARY_TICKET' }) @IsString() recognizedAssetType: string @ApiProperty({ description: 'Whether the asset is enraptured' }) @IsBoolean() enraptured: boolean @ApiProperty({ description: 'Whether the asset is a gamepass' }) @IsBoolean() gamepass: boolean @ApiPropertyOptional({ description: 'Chain id where asset lives' }) @IsString() chainId: number @ApiProperty({ description: 'Address where the asset can be exported to' }) @IsString() exportAddress: string @ApiProperty({ description: 'Hash of the entry. Needed for exports.' }) @IsString() hash?: string @ApiProperty({ description: 'Hash of the entry. Needed for exports.' }) @IsEnum(MultiverseVersion) multiverseVersion: MultiverseVersion } export class TextureDto { @ApiProperty({ description: 'Skin id from database' }) @IsString() id: string @ApiProperty({ description: 'Asset address' }) @IsString() assetAddress: string @ApiProperty({ description: 'Asset id, aka token id' }) @IsString() assetId: string @ApiProperty({ description: 'Asset type, aka token type' }) @IsString() assetType: string @ApiProperty({ description: 'Texture data' }) @IsString() textureData: string @ApiProperty({ description: 'Texture signature' }) @IsString() textureSignature: string @ApiProperty({ description: 'Whether the skin can be selected.' }) @IsBoolean() selectable: boolean @ApiProperty({ description: 'Name for the skin' }) @IsString() name?: string @ApiProperty({ description: 'Whether the skin is the currently equipped one.' }) @IsBoolean() equipped: boolean } export class ThingsDto { @ApiProperty({ description: 'Textures available', isArray: true }) assets: AssetDto[] @ApiProperty({ description: 'Available textures of the user', isArray: true }) textures: TextureDto[] @ApiProperty({ description: 'In-game resources available to summon', isArray: true }) resources: AssetDto[] }
import "styles/globals.css"; import "@rainbow-me/rainbowkit/styles.css"; import type { AppProps } from "next/app"; import { getDefaultWallets, RainbowKitProvider } from "@rainbow-me/rainbowkit"; import { configureChains, createClient, WagmiConfig } from "wagmi"; import { mainnet, goerli } from "wagmi/chains"; import { publicProvider } from "wagmi/providers/public"; import { Layout } from "components/Layout"; function MyApp({ Component, pageProps }: AppProps) { const { chains, provider } = configureChains( [mainnet, goerli], [publicProvider()] ); const { connectors } = getDefaultWallets({ appName: "My RainbowKit App", chains, }); const wagmiClient = createClient({ autoConnect: true, connectors, provider, }); return ( <WagmiConfig client={wagmiClient}> <RainbowKitProvider chains={chains}> <Layout> <Component {...pageProps} /> </Layout> </RainbowKitProvider> </WagmiConfig> ); } export default MyApp;
<script setup> import { useRouter } from 'vue-router'; import { ref } from 'vue'; import { fetchData } from '../getdata' import 'moment-timezone/builds/moment-timezone-with-data' const router = useRouter(); const title = ref() const des = ref() const category = ref() const pubDate = ref() const pubtime = ref('06:00:00') const clsDate = ref() const clstime = ref('18:00:00') const dis = ref() const data = ref() const dateTimee = ref() const TitleCount = ref(0) const DesCount = ref(0) const apiUrl = import.meta.env.VITE_API_ROOT; const categoryId = () => { let categoryan = category.value; let num = 0; switch (categoryan) { case "ทั่วไป": num = 1; break; case "ทุนการศึกษา": num = 2; break; case "หางาน": num = 3; break; case "ฝึกงาน": num = 4; break; default: num = 0; } category.value = num; return num; } const dataUtc = (dataDate, dataTime) => { if (dataDate !== null && dataDate !== undefined && dataTime !== null && dataTime !== undefined) { const newDatetime = dataDate + ' ' + dataTime const timeformat = new Date(newDatetime) timeformat.toLocaleString('en-GB') dateTimee.value = timeformat dateTimee.value = timeformat return timeformat.toISOString() } else { return null } } const cancelForm = () => { router.push({ name: 'allAnnouncement' }) } const TitleCharacterCount = () => { TitleCount.value = title.value.length; } const DesCharacterCount = () => { DesCount.value = des.value.length; } const datatime = () => { if (!dis.value) { dis.value = 'N'; } else { dis.value = 'Y'; } categoryId(category.value) data.value = { "announcementTitle": title.value, "announcementDescription": des.value, "categoryId": category.value, "publishDate": dataUtc(pubDate.value, pubtime.value), "closeDate": dataUtc(clsDate.value, clstime.value), "announcementDisplay": dis.value } } const addAnnouncement = async () => { datatime() if (title.value === undefined || title.value.trim() === '') { alert('Please Input Title! || Data cannot be blank! '); } else if (des.value === undefined || des.value.trim() === '') { alert('Please Input Description! || Data cannot be blank!'); } else if (category.value === 0) { alert("Please Input Category"); } else if (pubDate.value !== undefined && pubtime.value === undefined) { alert("Please Input Publish Time"); } else if (clsDate.value !== undefined && clstime.value === undefined) { alert("Please Input Close Time"); } const currentTime = new Date().getTime(); const selectedDateTime = new Date(dataUtc(pubDate.value, pubtime.value)).getTime(); const selectedCloseTime = new Date(dataUtc(clsDate.value, clstime.value)).getTime(); if (pubDate.value !== undefined && selectedDateTime < currentTime) { alert("Publish Date cannot be earlier than the current time"); } if (clsDate.value !== undefined && selectedCloseTime < selectedDateTime) { alert("Closed Date cannot be earlier than the current time"); } else { try { const url = `${apiUrl}/api/announcements`; const responseData = await fetchData(url, 'POST', data.value); console.log('Data sent:', data); console.log('Response data:', responseData); router.push({ name: 'allAnnouncement' }) }catch (error) { console.error(error); } // try { // const response = await axios.post(`${x}/api/announcements`, data.value); // console.log(data.value); // console.log(response.data); // router.push({ name: 'allAnnouncement' }) // } catch (error) { // console.error(error); // console.log(category.value) // console.log(error); // } } } </script> <template> <div class="frame1"> <div class="list"> <h1 style="font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;">Announcement Detail: </h1> <div class="Title"> <label for="announcementTitle" class="ann-tt"> <h2 style="font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;">Title</h2> </label> <p id="p9">( {{ TitleCount }}/200 )</p> </div> <input type="text" class="ann-title" name="announcementTitle" required style="width: 99%;" v-model="title" maxlength="200" @input="TitleCharacterCount"><br> <label for="categoryName" class="ann-ct"> <h2 style="font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;">Category</h2> </label> <select name="categoryName" required class="ann-category" v-model="category"> <option value="ทั่วไป">ทั่วไป</option> <option value="ทุนการศึกษา">ทุนการศึกษา</option> <option value="หางาน">หางาน</option> <option value="ฝึกงาน">ฝึกงาน</option> </select><br> <div class="Title"> <label for="announcementDescription"> <h2 style="font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;">Description </h2> </label> <p id="p9">( {{ DesCount }}/10,000 )</p> </div> <textarea class="ann-description" required style="height: 100px; width: 99%; resize: vertical;" v-model="des" maxlength="10000" @input="DesCharacterCount"></textarea><br> <label for="publishDate"> <h2 style="font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;">PublishDate</h2> </label> <div style="display: flex; "> <input type="date" class="ann-publish-date" name="publishdate" style=" height: 20px; margin-right: 10px; " v-model="pubDate"> <input v-if="pubDate === undefined" type="time" class="ann-publish-time" name="publishTime" v-model="pubtime" disabled> <input v-else type="time" class="ann-publish-time" name="publishTime" v-model="pubtime"> </div> <label for="publishDate"> <h2 style="font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;">Close Date</h2> </label> <div style="display: flex; "> <input type="date" class="ann-close-date" name="closeDate" style=" height: 20px; margin-right: 10px; " v-model="clsDate"> <input v-if="clsDate === undefined" type="time" class="ann-closeTime-time" name="closeTime" v-model="clstime" disabled> <input v-else type="time" class="ann-closeTime-time" name="closeTime" v-model="clstime"> </div> <label for="announcementDisplay"> <h2 style="font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif; ">Display</h2> </label> <div style="display: flex; "><input type="checkbox" class="ann-display" name="announcementDisplay" id="Checkbox" style=" margin-right: 10px;" v-model="dis"> <p class="ann-d" style="font-size: 16px; font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;">Check to show this announcement</p> </div> <button type="submit" class="ann-button" @click="addAnnouncement()" style="margin-right: 10px;">Submit</button> <button class="ann-button" @click="cancelForm">Cancel</button> </div> </div> </template> <style scoped> .frame1 { background-color: #e7e7e7; padding: 20px; border-radius: 10px; width: 1350px; height: 850px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .ann-title{ height: 30px; } .ann-title:focus{ border: 3px solid #ccc; outline: none; border-color: #000000; } .ann-title::placeholder { color: #ccc; } .ann-description:focus{ border: 3px solid #ccc; outline: none; border-color: #000000; } .ann-description::placeholder { color: #ccc; } .ann-close-date:focus{ border: 3px solid #ccc; outline: none; border-color: #000000; } .ann-close-time:focus{ border: 3px solid #ccc; outline: none; border-color: #000000; } .ann-publish-date:focus{ border: 3px solid #ccc; outline: none; border-color: #000000; } .ann-publish-time:focus{ border: 3px solid #ccc; outline: none; border-color: #5f9ea0; } button { transition-duration: 500ms; background-color: #353835; border: none; color: white; padding: 8px 16px; text-align: center; text-decoration: none; font-size: 14px; margin: 18px 2px; cursor: pointer; border-radius: 5px; } </style>
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>門庭</title> <meta name="description" content=""> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.0/css/bootstrap-reboot.min.css"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.min.css"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/i18n/jquery.ui.datepicker-ja.min.js"></script> <script type="text/javascript" src="js/jquery.zip2addr.js"></script> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="app"> <montei-header></montei-header> <section class="reserve_form"> <img src="image/niku.jpg" alt=""> <div class="container"> <h2>ご予約フォーム</h2> <form> <table> <tr> <th>お名前</th> <td> <input type="text" class="half" v-model.lazy="name" v-on:change="nameCheck"> <p class="err" v-if="nameErr">記号・数字の使用は不可です。</p> </td> </tr> <tr> <th>お電話番号</th> <td> <input type="tel" class="half" v-model.lazy="tel" v-on:change="telCheck"> <p>※ハイフン不要</p> <p class="err" v-if="telErr">半角数字で入力してください。</p> </td> </tr> <tr> <th>ご住所</th> <td> 〒<input type="tel" class="yuubin" id="zip" onKeyUp="$('#zip').zip2addr('#address');"><br> <input type="text" id="address"> <p>※郵便番号を入力すると自動で町名まで入力されます。</p> </td> </tr> <tr> <th>来店人数</th> <td> 大人: <select v-model="adult" v-on:change="totalPrice"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> 人  子ども: <select v-model="child" v-on:change="totalPrice"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> 人 </td> </tr> <tr> <th>ご予約日時</th> <td> 日付:<input type="text" id="datepicker" class="yuubin" placeholder="年/ 月/ 日" readonly> <br class="pc_off"><span class="pc_off">時間:</span><select v-model="time"> <option value="0">選択してください</option> <option value="17">17:00</option> <option value="18">18:00</option> <option value="19">19:00</option> <option value="20">20:00</option> <option value="21" class="last_time">21:00</option> </select> <!-- test --> <!-- <br> test:<input type="datetime-local" :min="minDate"> --> </td> </tr> <tr> <th>ご予約コース</th> <td> <select v-model="course" v-on:change="totalPrice"> <option value="0">選択してください</option> <option value="3500">門庭厳選コース</option> <option value="5000">門庭贅沢コース</option> <option value="6000">門庭究極の赤身コース</option> <option value="8000">最高峰の極みコース</option> </select> <p>※コース内容のご確認は<a href="index.html#course" target="_blank">こちら</a>。</p> </td> </tr> </table> <div class="sum_box"> <p>お支払予定金額:{{ $filters.number_format(totalPrice()) }}円</p> </div> <button class="conf_btn">ご入力内容確認</button> </form> </div> </section> <montei-footer></montei-footer> </div> <script> // 日付選択 $(function(){ $('#datepicker').datepicker({ // 表示形式 dateFormat:'yy/mm/dd', // 月曜日を選択不可に beforeShowDay: function(date) { if(date.getDay() == 1){ return [false, 'ui-state-disabled']; } else { return [true, '']; } }, // 過去の日付を選択不可に minDate: 0, // 日曜日を選択した場合は、選択できる時間を制限する onSelect: (date) => { let dt = new Date(date) if (dt.getDay() == 0) { $('.last_time').css('display', 'none'); } else { $('.last_time').css('display', 'block'); } } }) }); </script> </body> <script src="js/components/header.js"></script> <script src="js/components/footer.js"></script> <script src="js/form.js"></script> </html>
class scene1 extends Phaser.Scene { constructor(){ super('bootGame'); } //preload preload(){ // this.load.plugin('rexinputtextplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexinputtextplugin.min.js', true); this.load.image("background","assets/images/background.png") // this.load.image("ship","assets/images/ship.png") //change to spritesheet this.load.spritesheet("ship","assets/spritesheets/ship.png",{ frameWidth: 16, frameHeight: 16 }) // this.load.image("ship2","assets/images/ship2.png") this.load.spritesheet("ship2","assets/spritesheets/ship2.png",{ frameWidth: 32, frameHeight: 16 }) // this.load.image("ship3","assets/images/ship3.png") this.load.spritesheet("ship3","assets/spritesheets/ship3.png",{ frameWidth: 32, frameHeight: 32 }) this.load.spritesheet("explosion","assets/spritesheets/explosion.png",{ frameWidth: 16, frameHeight: 16 }) this.load.spritesheet("power-up","assets/spritesheets/power-up.png",{ frameWidth: 16, frameHeight: 16 }) this.load.spritesheet("player","assets/spritesheets/player.png",{ frameWidth: 16, frameHeight: 24 }) this.load.spritesheet("beam","assets/spritesheets/beam.png",{ frameWidth: 16, frameHeight: 16 }) //load bitmap font this.load.bitmapFont("pixelFont","assets/font/font.png",'assets/font/font.xml') //load audio this.load.audio("audio_beam",['assets/sounds/beam.ogg','assets/sounds/beam.mp3']) this.load.audio("audio_explosion",['assets/sounds/explosion.ogg','assets/sounds/explosion.mp3']) this.load.audio("audio_pickup",['assets/sounds/pickup.ogg','assets/sounds/pickup.mp3']) this.load.audio("bgm",['assets/sounds/sci-fi_platformer12.ogg','assets/sounds/sci-fi_platformer12.mp3']) this.load.audio("death",['assets/sounds/mario_death.ogg','assets/sounds/mario_death.mp3']) } create(){ //create text (x, y) this.add.text(20,20,"loading game..."); //jump after finish load this.scene.start('playGame'); //anim this.anims.create({ key: "ship1_anim", frames: this.anims.generateFrameNumbers("ship"), frameRate:20, repeat: -1 //-1 for infinite loops }) this.anims.create({ key: "ship2_anim", frames: this.anims.generateFrameNumbers("ship2"), frameRate:20, repeat: -1 //-1 for infinite loops }) this.anims.create({ key: "ship3_anim", frames: this.anims.generateFrameNumbers("ship3"), frameRate:20, repeat: -1 //-1 for infinite loops }) this.anims.create({ key: "explode_anim", frames: this.anims.generateFrameNumbers("explosion"), frameRate:20, repeat: 0, hideOnComplete:true //dissapear }) this.anims.create({ key: "red", frames: this.anims.generateFrameNumbers('power-up',{ start:0, end:1 }), frameRate:20, repeat: -1 }) this.anims.create({ key: "grey", frames: this.anims.generateFrameNumbers('power-up',{ start:2, end:3 }), frameRate:20, repeat: -1 }) this.anims.create({ key: "thrust", frames: this.anims.generateFrameNumbers('player'), frameRate:20, repeat: -1 }) this.anims.create({ key: "beam_anim", frames: this.anims.generateFrameNumbers('beam'), frameRate:20, repeat: -1 }) } }
# Lattice.py: crystals with boundaries and associated functions for RiflesSO # ------------------------------------------------------------------------------------------------- # A part of RiflesSO project created by Oleg Kharlanov (O.K.), 2024, # for further merging with R.Sundararaman's qimpy project. from typing import Sequence, List, Union, Optional, Tuple from numpy.typing import NDArray import numpy as np import yaml import re from .utils import lcm_list, reduce_to_coprimes, normalize, solve_LDE_3vars_homo, snap_to_rational from . import utils # For re_* RegEx constants from . import units class CrystalLattice: '''Encapsulates a periodic Bravais lattice filling a d-dimensional half-space (d=1,2,3) embedded into the n-dimensional target space (n >= d), as well as the corresponding reciprocal space''' _lattice_vectors: NDArray #: d lattice vectors as columns of a matrix (shape = (n,d)) _reciprocal_vectors: NDArray #: d reciprocal vectors as rows of matrix (shape = (d,n)) def __init__(self, *, lattice_vectors: Sequence[float] = np.identity(3, dtype=float) ): '''Constructs a CrystalLattice object with d given primitive vectors, stored column_wise in lattice_vectors. Note: lattice_vectors.shape = (n, d), n >= d. ''' self.lattice_vectors = lattice_vectors # Also initializes reciprocals def metric_tensor(self) -> NDArray: "Returns a (dxd) matrix g_ab = <e_a|e_b>, where e_a is the lattice vector No.a" return self._lattice_vectors.T.dot(self._lattice_vectors) @property def reciprocal_vectors(self) -> NDArray: "Primitive vectors of the reciprocal vectors stored row-wise, in inverse length units" return self._reciprocal_vectors @reciprocal_vectors.setter def reciprocal_vectors(self, new_vecs): self._reciprocal_vectors = np.array(new_vecs, dtype=float) # Note: if d < n (say, 2D graphene in 3D space), direct inversion of reciprocal_vectors is impossible g = self._reciprocal_vectors.dot(self._reciprocal_vectors.T) self._lattice_vectors = (2 * np.pi) * (self._reciprocal_vectors.T @ np.linalg.inv(g)) @property def lattice_vectors(self) -> NDArray: "Primitive lattice vectors stored column-wise, in length units" return self._lattice_vectors @lattice_vectors.setter def lattice_vectors(self, new_vecs): self._lattice_vectors = np.array(new_vecs, dtype=float) # Note: if d < n (say, 2D graphene in 3D space), direct inversion of lattice_vectors is impossible self._reciprocal_vectors = (2 * np.pi) * np.linalg.inv(self.metric_tensor()) @ self._lattice_vectors.T def crystal_dimension(self) -> int: "Returns d, the dimensionality of the crystal (e.g., 1 for polyacetylene, 2 for graphene, 3 for graphite)" return self._lattice_vectors.shape[1] def target_space_dimension(self) -> int: "Returns n, the dimensionality of space the crystal is embedded into. N.B.: n >= crystal_dimension()" return self._lattice_vectors.shape[0] def fractional_coords_to_real_vector(self, coords: Sequence) -> NDArray[np.float]: "Transforms a list of d coordinates x_i to an nD vector x_i \\vec{e}_i in real space, where \\vec{e}_i are the primitive vectors" return self._lattice_vectors.dot(coords) def fractional_coords_to_reciprocal_vector(self, coords: Sequence) -> NDArray[np.float]: "Transforms a list of d coordinates k_i to an nD vector k_i \\vec{f}_i in the reciprocal space with primitive vectors \\vec{f}_i" return np.dot(coords, self._reciprocal_vectors) def real_vector_to_fractional_coords(self, x: Sequence) -> NDArray[np.float]: '''Transforms an nD vector \\vec{x} in real space into its d coordinates in the primitive vector basis. Note that if d < n and \\vec{x} does not lie in the crystal plane, the out-of-plane coordinates are lost''' return (0.5 / np.pi) * self._reciprocal_vectors.dot(x) def reciprocal_vector_to_fractional_coords(self, k: Sequence) -> NDArray[np.float]: '''Transforms an nD momentum vector \\vec{k} in space into its d coordinates in the reciprocal vector basis. Note that if d < n and \\vec{k} does not lie in the crystal plane, the out-of-plane coordinates are lost. ''' return (0.5 / np.pi) * np.dot(k, self._lattice_vectors) def project_onto_crystal(self, vec: Sequence[float]) -> NDArray[np.float]: "Project an arbitrary vector onto the crystal plane (if it is, e.g. two-dimensional in a 3D space)" if self.target_space_dimension() == self.crystal_dimension(): return np.array(vec) # Essentially nothing to project else: return self.fractional_coords_to_real_vector(self.real_vector_to_fractional_coords(vec)) def load(self, filename: str, format: Union[str, Tuple[str, dict]]) -> None: '''Load the crystal structure from a file `filename`, such as an output file written by a DFT software. `format` can be either a string, such as \"jdftx.dft_outfile\", or a tuple of the form ("file_name", {"param1": param1_value, "param2": param2_value}), with the parameters defining further options, e.g., for parsing a specific section of the file. ''' if format == 'jdftx.dft_outfile': self._load_jdftx_dft_outfile(filename) elif format == 'yaml': with open(filename, 'rt') as f: self.initialize_from_dictionary(f, yaml.SafeLoader) else: raise ValueError(f'CrystalLattice.load() does not support format {format}') def initialize_from_dictionary(self, d: dict): '''Initialize the lattice vectors from a dictionary containing their Cartesian components or other information, such as length units. ''' # Length units for lattice vectors lv_units = d.get('lattice-vectors-units', 'Angstrom') units_error = ValueError('In CrystalLattice.initialize_from_dictionary(): ' + 'lattice-vectors-units should be formatted as <Len> Bohr|Angstrom') units_supported = { 'Angstrom': units.Angstrom, 'Bohr': units.BohrRadius } if not isinstance(lv_units, str): raise units_error if lv_units in units_supported: lv_units = units_supported[lv_units] else: try: lv_units = utils.float_with_units(lv_units, allowed_units=units_supported.keys()) except: raise units_error if 'lattice-vectors.Cartesian' in d: try: lv_components = d['lattice-vectors.Cartesian'] assert(isinstance(lv_components, list)) for lv in lv_components: assert(isinstance(lv, list)) for x in lv: assert(isinstance(x, float) or isinstance(x, int)) self.lattice_vectors = lv_units * np.array(lv_components, dtype=float) except: raise ValueError('In CrystalLattice.initialize_from_dictionary(): ' + 'lattice-vectors.Cartesian should be a nested list of numbers') lv_components = [] for v in ['a', 'b', 'c']: if v + '.Cartesian' in d: if 'lattice-vectors.Cartesian' in d: raise ValueError('In CrystalLattice.initialize_from_dictionary(): ' + f'conflicting lattice-vectors.Cartesian and {v}.Cartesian statements') try: lv_components.append(d[v + '.Cartesian']) if isinstance(lv_components[-1], str): lv_components[-1] = list(float(x) for x in lv_components[-1].split()) else: assert(isinstance(lv_components[-1], list)) for x in lv_components[-1]: assert(isinstance(x, float) or isinstance(x, int)) except: raise ValueError('In CrystalLattice.initialize_from_dictionary(): ' + f'{v}.Cartesian should be a list of numbers') if lv_components != []: self.lattice_vectors = lv_units * np.array(lv_components, dtype=float).T def _load_jdftx_dft_outfile(self, filename: str, occurrence: int = 0): '''A branch of load() function for JDFTx output files of DFT calculations. If occurrence = 0, reads the first occurrence of the lattice vectors in the file and stops; if occurrence = 1, 2, 3, ..., searches uses the corresponding nth set of lattice vectors; if occurrence = -1, uses the last set of the lattice vectors. ''' sep, ws, ow = utils.re_separator('-', 3), utils.re_whitespace, utils.re_opt_whitespace occurred = 0 with open(filename, 'rt') as f: while occurrence == -1 or occurred <= occurrence: ln = utils.find_line_in_file(f, [[sep + ow + 'Initializing the grid' + ow + sep, 'R' + ow + r'\=' ] ], re.IGNORECASE) if ln == None: if occurrence == -1 and occurred > 0: break raise ValueError('In CrystalLattice._load_jdftx_dft_outfile(): cannot find requested lattice vectors in DFT output file') occurred += 1 lattice_vectors = [] while True: ln = f.readline().strip() m = re.match('\\[' + ow + utils.re_real + '(?:' + ws + ')*' + '\\]', ln) if not m: if lattice_vectors == []: raise ValueError('In CrystalLattice._load_jdftx_dft_outfile(): unknown format of lattice vectors in DFT output file') break else: lattice_vectors.append([float(x) * units.BohrRadius for x in ln.split()[1:4]]) self.lattice_vectors = lattice_vectors def __str__(self) -> str: s = 'CrystalLattice(' if not self._lattice_vectors is None: vec_str = [] for i in range(self._lattice_vectors.shape[1]): vec_str.append(['a', 'b', 'c'][i] + '=' + utils.nparr2str(self._lattice_vectors[:,i] / units.Angstrom, prec=2, fmt='fixed') ) s += ', '.join(vec_str) return s + ')' class CrystallineHalfSpace(CrystalLattice): '''Encapsulates a periodic Bravais lattice filling a d-dimensional half-space (d=1,2,3) embedded into the n-dimensional target space (n >= d), as well as the corresponding reciprocal space''' boundary_plane: Union[List[int], NDArray[np.float]] #: either (integer) Miller indices or frac. coords of \vec{n} in the reciprocal basis def __init__(self, *, lattice_vectors: Sequence[float] = np.identity(3, dtype=float), boundary_plane_normal: Optional[NDArray[np.float]] = None, boundary_plane_indices: Optional[List[int]] = None ): '''Constructs a CrystallineHalfSpace object with the following properties: lattice_vectors: a set of column-wise lattice vectors (shape=(n, d), n >= d), boundary_plane_normal: an outward normal vector to the boundary [optional], boundary_plane_indices: Miller indices [h,k,l] of the boundary plane [optional] ''' super().__init__(lattice_vectors=lattice_vectors) if boundary_plane_normal != None: self.boundary_plane = self.reciprocal_vector_to_fractional_coords(boundary_plane_normal) elif boundary_plane_indices != None: self.boundary_plane = reduce_to_coprimes(boundary_plane_indices) else: # [0, 0, 1] for 3D crystals, [0, 1] for 2D ones dim = self.crystal_dimension() if dim == 1: self.boundary_plane = [] else: self.boundary_plane = [0] * dim self.boundary_plane[-1] = 1 def is_boundary_normal_rational(self) -> bool: "Returns True if the crystal boundary is rational, i.e., corresponds to certain Miller indices (hkl)" return isinstance(self.boundary_plane, list) # and list(map(type, self.boundary_plane)) == [int] * len(self.boundary_plane) def boundary_normal(self) -> NDArray[np.float]: "Returns a unit n-dimensional vector describing the outer normal to the crystal boundary" return normalize(self.fractional_coords_to_reciprocal_vector(self.boundary_plane)) def snap_to_rational_boundary(self, delta_normal_max: float = 0.05) -> List[int]: '''Replace the normal vector currently installed to the 'rational' one (hkl), such that max(h,k,l) --> min and |new_normal - current_normal| <= delta_normal_max. Returns the Miller indices of the new normal vector. ''' if self.is_boundary_normal_rational(): return self.boundary_plane # "Dummy" Version 0.1: just round the Miller indices to withion delta_normal_max and then find a common denominator boundary_plane_rounded = [snap_to_rational(n_i, delta_normal_max) for n_i in self.boundary_plane] common_denom = lcm_list([f.denominator for f in boundary_plane_rounded]) self.boundary_plane = [f.numerator * (common_denom // f.denominator) for f in boundary_plane_rounded] return self.boundary_plane def boundary_lattice_vectors(self) -> NDArray: '''Find the shortest real lattice vectors, G in 2D and G_1, G_2 in 3D, that connect the lattice points lying at the boundary. In other words, these vectors are the periods of the boundary of the semi-infinite crystal. Return value: the coordinates of the vectors as rows of a 2D numpy.array[int], e.g. e_1 + 2 e_2 - e_3 corresponds to a row [1,2,-1]. In 1D, an empty set is returned. ''' dim = self.crystal_dimension() if dim == 1: return np.array([], dtype=int) if not self.is_boundary_normal_rational(): raise ValueError('In CrystallineHalfSpace.boundary_lattice_vectors(): result undefined for ' + 'irrational plane slopes. Consider trying to snap_to_rational_boundary() first.') elif dim == 2: h, k = self.boundary_plane xi_coords = np.array([k, -h], dtype=int) # Make the period vector xi form a right-handed basis together with the normal third_direction = np.cross(self._lattice_vectors[:,0], self._lattice_vectors[:,1]) xi_third_direction = np.cross(self.fractional_coords_to_real_vector(xi_coords), self.boundary_normal()) return xi_coords[None,:] if xi_third_direction.dot(third_direction) > 0 else -xi_coords[None,:] elif dim == 3: # Finding the basis vectors \vec{v} in the plane amounts to solving a linear Diophantine equation \vec{v} \cdot \vec{n} = 0 xi_coords, eta_coords = solve_LDE_3vars_homo(*self.boundary_plane) # Make the period vectors xi, eta form a right-handed basis together with the normal xieta_orientation = np.cross(self.fractional_coords_to_real_vector(xi_coords), self.fractional_coords_to_real_vector(eta_coords) ).dot(self.boundary_normal()) return np.array([xi_coords, eta_coords]) if xieta_orientation > 0 else -np.array([xi_coords, eta_coords]) def boundary_potential_kdirection(self) -> np.array: '''Returns a tangent vector to a line in reciprocal space, which is a locus of nonzero matrix elements of the boundary potential. The potential is assumed to be of the form of an increasing function V(\\vec{n} \cdot \\vec{x}), where \\vec{n} is the outward normal to the boundary. The tangent vector is returned as a set of its components in the reciprocal vectors (a.k.a. fractional coordinates). If the boundary plane is given in terms of the Miller indices, a rational vector is retured; otherwise a real-valued one. ''' return np.array(self.boundary_plane) # Just that easy!.. def initialize_from_dictionary(self, d: dict): '''Initialize the lattice vectors from a dictionary containing their Cartesian components or other information, such as length units. ''' super().initialize_from_dictionary(d) if 'boundary_normal.Cartesian' in d: try: n_components = d['boundary_normal.Cartesian'] if isinstance(n_components, str): n_components = list(float(x) for x in n_components.split()) else: assert(isinstance(n_components, list)) for x in n_components: assert(isinstance(x, float) or isinstance(x, int)) self.boundary_plane = utils.normalize(np.array(n_components, dtype=float)) assert(self.boundary_plane.shape[0] == self.crystal_dimension()) except: raise ValueError('In CrystallineHalfSpace.initialize_from_dictionary(): ' + 'boundary_normal.Cartesian should be a list of numbers') if 'Miller_indices' in d: if 'boundary_normal.Cartesian' in d: raise ValueError('In CrystallineHalfSpace.initialize_from_dictionary(): ' + 'conflicting boundary_normal and Miller_indices statements') try: hkl = d['Miller_indices'] if isinstance(hkl, str): hkl = list(int(n) for n in hkl.split()) else: assert(isinstance(hkl, list)) for n in hkl: assert(isinstance(n, int)) self.boundary_plane = list(hkl) assert(len(self.boundary_plane) == self.crystal_dimension()) except: raise ValueError('In CrystallineHalfSpace.initialize_from_dictionary(): ' + 'Miller_indices should be a list of integers') if __name__ == '__main__': lat = CrystalLattice() lat.load('../../jdftx_calculations/graphene/scf_fine.out', 'jdftx.dft_outfile') print(lat.lattice_vectors)
extends Node onready var character: Character = $"../Character" # Initial room (0 in normal game, change for debug) export(int) var start_room_index = 0 func _ready(): # Note that this is run even in release, so we can place character and camera # where we want immediately in case they are not preset correctly in the level _warp_character(start_room_index) # Wait a short time, just enough to load/reload the game if using restart # and so character enters RoomEntrance and triggers camera motion # with no smoothing so it is immediate the first time; # but short enough to guarantee character won't enter next room in that duration) yield(get_tree().create_timer(0.1), "timeout") # Then enable smoothing so camera moves smoothly on further Room Entrances var camera: Camera2D = get_tree().get_nodes_in_group("camera")[0] camera.smoothing_enabled = true # Play intro sequence if starting in first room, as normally # but skip it if debug warping to another room if start_room_index == 0: _play_intro_sequence() func _unhandled_input(event): if OS.has_feature("debug"): if event.is_action_pressed("cheat_restart"): var _err = get_tree().reload_current_scene() elif event.is_action_pressed("go_to_room1"): _warp_character(0) elif event.is_action_pressed("go_to_room2"): _warp_character(1) elif event.is_action_pressed("go_to_room3"): _warp_character(2) elif event.is_action_pressed("go_to_room4"): _warp_character(3) func _warp_character(room_index: int): # room 1 entrance is at 240, 268 and each room has a height of 16*17=272 # for room 1, we want to be after the entrance door in room 1 after it closed # so add offset UP by 16 var target_pos = Vector2(240, 268 - 272 * room_index) if room_index == 0: target_pos.y -= 16 character.global_position = target_pos # to support warping during intro sequence, stop it now stop_intro_sequence() func _play_intro_sequence(): # Light rod on silently for setup var rod = character.rod # pass go_off_after_timer = false so the first flame is infinite # note that the first ignite will rekindle the rod, with timer this time, # thus starting the timer and deactivating infinite flame as we want rod._light_on(false) # Move character lower so it starts outside room # (far enough so his own light disc is not visible on screen at first) character.position += 76.0 * Vector2.DOWN # Take control of character var control = character.control control.control_mode = Enum.ControlMode.SIMULATION # Prevent throwing fireball because player would lose the initial flame # before igniting the first fire pit, causing soft lock control.can_throw_fireball = false # Move up to just enter room control.move_intention = Vector2.UP # In this case, self has same lifetime as Character since Restart will free them all, # so we can pass it as timer owner yield(TimerUtils.create_temp_timer_under(self, 1.5), "timeout") control.move_intention = Vector2.ZERO # Give control back to player stop_intro_sequence() func stop_intro_sequence(): var control = character.control # control may still be null on ready and we have not started playing intro # anyway on first warp, so skip it in this case if control != null: control.control_mode = Enum.ControlMode.PLAYER_INPUT
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:quizzle/features/auth/views/auth_screen.dart'; import 'package:quizzle/firebase_options.dart'; import 'package:sizer/sizer.dart'; import 'package:firebase_core/firebase_core.dart'; import 'core/typedefs.dart'; import 'core/providers.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'dart:developer'; import 'package:flex_color_scheme/flex_color_scheme.dart'; import 'features/home/views/home.dart'; FutureVoid main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); await dotenv.load(fileName: ".env"); runApp( const ProviderScope( child: MyApp(), ), ); } class MyApp extends ConsumerStatefulWidget { const MyApp({super.key}); @override ConsumerState<MyApp> createState() => _MyAppState(); } class _MyAppState extends ConsumerState<MyApp> { late final AppLifecycleListener _listener; @override void initState() { super.initState(); _listener = AppLifecycleListener(onStateChange: (state) { log(state.name); }); } @override Widget build(BuildContext context) { final firebaseAuth = ref.watch(firebaseAuthProvider); return Sizer( builder: (context, _, __) { return MaterialApp( debugShowCheckedModeBanner: false, theme: FlexThemeData.light( scheme: FlexScheme.green, useMaterial3: true, ), home: firebaseAuth.currentUser == null ? const AuthScreen() : const Home(), ); }, ); } }
""" Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follows. Then, get the last value from the input, and output all integers less than or equal to that value. Ex: If the input is: 5 50 60 140 200 75 100 the output is: 50 60 75 The 5 indicates that five integers are in the list, namely 50, 60, 140, 200, and 75. The 100 indicates that the program should output all integers less than or equal to 100, so the program outputs 50, 60, and 75. Such functionality is common on sites like Amazon, where a user can filter results. Utilizing functions will help to make your main very clean and intuitive. The program must define the following two functions: def get_user_values() - read from input the size of the list, the integers in the list, and the threshold value. Return the list of integers and the threshold value. def ints_less_than_or_equal_to_threshold(user_values, upper_threshold) - create a new list that contains values in user_values that are less than or equal to upper_threshold. Return the newly created list. """ # Define your functions here def get_user_values(): num_ints = int(input()) count = 0 user_values = [] while count < num_ints: user_input = input() if user_input == '': break else: user_values.append(user_input) count += 1 upper_threshold = int(input()) return user_values, upper_threshold def ints_less_than_or_equal_to_threshold(user_values, upper_threshold): vals = [] for val in user_values: if int(val) <= upper_threshold: vals.append(val) #print(vals) return vals if __name__ == '__main__': user_values, upper_threshold = get_user_values() res_values = ints_less_than_or_equal_to_threshold(user_values, upper_threshold) for value in res_values: print(value)
"""Provide common variables and configurations for the Regybox application. This module defines common variables and configurations used throughout the Regybox application. It also loads environment variables from a .env file. Variables: LOGGER: The logger instance for the Regybox application. TIMEZONE: The timezone used for date and time calculations. CLASS_TIME: The default class time. CLASS_TYPE: The default class type. EVENT_NAME: The default event name. REGYBOX_USER: The Regybox user, used to create the Regybox website cookie. PHPSESSID: The PHP session ID, used to create the Regybox website cookie. CALENDAR_URL: The URL of the calendar. Note: The module loads environment variables from a .env file using the dotenv package. """ import logging import os from zoneinfo import ZoneInfo from dotenv import find_dotenv, load_dotenv load_dotenv(dotenv_path=find_dotenv(usecwd=True)) logging.basicConfig( format="%(asctime)s %(levelname)s [%(name)s] [%(filename)s:%(lineno)d] - %(message)s", level=logging.INFO, ) LOGGER: logging.Logger = logging.getLogger("REGYBOX") TIMEZONE: ZoneInfo = ZoneInfo("Europe/Lisbon") CLASS_TIME: str = "06:30" CLASS_TYPE: str = "WOD Rato" EVENT_NAME: str = "CrossFit" REGYBOX_USER: str = os.environ["REGYBOX_USER"] PHPSESSID: str = os.environ["PHPSESSID"] CALENDAR_URL: str = os.environ["CALENDAR_URL"]
## Task Last week, the Nautilus DevOps team deployed a redis app on Kubernetes cluster, which was working fine so far. This morning one of the team members was making some changes in this existing setup, but he made some mistakes and the app went down. We need to fix this as soon as possible. Please take a look. The deployment name is redis-deployment. The pods are not in running state right now, so please look into the issue and fix the same. Note: The kubectl utility on jump_host has been configured to work with the kubernetes cluster. ## Solution View the specification of the deployment. ```sh thor@jump_host ~$ kubectl describe deployment redis-deployment Name: redis-deployment Namespace: default CreationTimestamp: Fri, 13 Oct 2023 11:42:34 +0000 Labels: app=redis Annotations: deployment.kubernetes.io/revision: 1 Selector: app=redis Replicas: 1 desired | 1 updated | 1 total | 0 available | 1 unavailable StrategyType: RollingUpdate MinReadySeconds: 0 RollingUpdateStrategy: 25% max unavailable, 25% max surge Pod Template: Labels: app=redis Containers: redis-container: Image: redis:alpin Port: 6379/TCP Host Port: 0/TCP Requests: cpu: 300m Environment: <none> Mounts: /redis-master from config (rw) /redis-master-data from data (rw) Volumes: data: Type: EmptyDir (a temporary directory that shares a pod's lifetime) Medium: SizeLimit: <unset> config: Type: ConfigMap (a volume populated by a ConfigMap) Name: redis-conig Optional: false Conditions: Type Status Reason ---- ------ ------ Available False MinimumReplicasUnavailable Progressing True ReplicaSetUpdated OldReplicaSets: <none> NewReplicaSet: redis-deployment-54cdf4f76d (1/1 replicas created) Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal ScalingReplicaSet 70s deployment-controller Scaled up replica set redis-deployment-54cdf4f76d to 1 ``` And we can see that there is a typo in image name. Instead of `redis:alpin` should be `redis:alpine`. Also we can see that there is another typo in the name of ConfigMap. Should be `redis-config` instead of `redis-conig` To change the image in the container we can use this command: ```sh thor@jump_host ~$ kubectl set image deployment/redis-deployment redis-container=redis:alpine deployment.apps/redis-deployment image updated ``` To change ConfigMap name we can edit the deployment and change name to the correct value. ```sh thor@jump_host ~$ kubectl edit deployment redis-deployment deployment.apps/redis-deployment edited ``` ```yml - configMap: defaultMode: 420 name: redis-config ``` And pod should be now running. ```sh thor@jump_host ~$ kubectl get pods NAME READY STATUS RESTARTS AGE redis-deployment-7c8d4f6ddf-zfh89 1/1 Running 0 4m13s ``` ## References [A visual guide on troubleshooting Kubernetes deployments](https://learnk8s.io/troubleshooting-deployments)
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAdminUserConversationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('admin_user_conversations', function (Blueprint $table) { $table->increments('id'); $table->string('subject')->nullable(); $table->integer('user_id')->nullable(); $table->text('message')->nullable(); $table->timestamps(); $table->enum('type', ['Ticket', 'Dispute', 'Contact'])->nullable(); $table->text('order_number')->nullable(); $table->string('phone')->nullable(); $table->string('email')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('admin_user_conversations'); } }
package com.rca.app.userregistration; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; @WebServlet(name = "RegisterServlet", value = "/register") public class RegisterServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // No implementation for now } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); String userName = req.getParameter("username"); String email = req.getParameter("email"); String password = req.getParameter("password"); String role = req.getParameter("role"); // Validate email and password using RegexValidator boolean isValidEmail = RegexValidator.isValidEmail(email); boolean isValidPassword = RegexValidator.isValidPassword(password); if (!isValidEmail || !isValidPassword) { // Redirect to an error page or display an error message resp.getWriter().println("Invalid email or password format."); return; } // Hashing the password String hashedPassword = PasswordHasher.hashPassword(password); try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/javaUserDb"; String userN = "root"; String pass = ""; try (Connection con = DriverManager.getConnection(url, userN, pass); PreparedStatement ps = con.prepareStatement("INSERT INTO users (userName, email, password, role) VALUES (?,?,?,?)")) { ps.setString(1, userName); ps.setString(2, email); ps.setString(3, hashedPassword); ps.setString(4, role); int rowsAffected = ps.executeUpdate(); if (rowsAffected > 0) { System.out.println("Data inserted successfully!"); // Redirect based on user role if ("admin".equalsIgnoreCase(role)) { // Forward to admin.jsp RequestDispatcher dispatcher = req.getRequestDispatcher("Admin.jsp"); dispatcher.forward(req, resp); } else if ("guest".equalsIgnoreCase(role)) { // Forward to guest.jsp RequestDispatcher dispatcher = req.getRequestDispatcher("Guest.jsp"); dispatcher.forward(req, resp); } } else { System.out.println("Failed to insert data."); } } catch (SQLException e) { // Log or handle the SQL exception appropriately e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); } } catch (ClassNotFoundException e) { // Log or handle the ClassNotFoundException appropriately e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); } } }
import { theme } from "@service/app/theme"; import { renderWithProvider } from "@testing/TestRenderers"; import { expect } from "chai"; import chroma from "chroma-js"; import { assertIsObject } from "primitive-predicates"; import ExtensionTrail from "./ExtensionTrail"; describe("React Integration: Extension Trail", function (): void { let styles: CSSStyleDeclaration; let classNames: string[]; before(function (): void { const { renderResult: { container }, } = renderWithProvider(<ExtensionTrail />); const box = container.querySelector(".extensionTrail"); assertIsObject(box); styles = getComputedStyle(box); classNames = box.className.split(" "); }); it("should have pink background", function (): void { expect(chroma(styles.backgroundColor).hex()).to.equal( chroma(theme.extensionColor).hex() ); }); it("should have flex basis of 0", function (): void { expect(Number(styles.flexBasis.slice(0, -2))).to.equal(0); }); it("should be able to flex grow", function (): void { expect(styles.flexGrow).to.equal("1"); }); it("should have growing class name and not the other variant name", function (): void { expect(classNames) .to.contain("extensionTrailGrow") .and.not.to.contain("extensionTrailFixedSize"); }); });
import axios from "axios"; import { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import BookingWidget from "../BookingWidget"; import PlaceGallery from "../PlaceGallery"; import AddressLink from "../AddressLink"; import Calendar from "../Calendar"; import TimePicker from "../TimePicker"; import { DateTime } from "luxon"; export default function PlacePage() { const { id } = useParams(); const [place, setPlace] = useState(null); const [date, setDate] = useState(new Date().toISOString().split("T")[0]); const [selectedTime, setSelectedTime] = useState(""); const [checkoutTime, setCheckoutTime] = useState(""); const [showCalendar, setShowCalendar] = useState(true); function handleSelectTime(time) { setSelectedTime(time); } function handleCheckoutTime(time) { setCheckoutTime(time); } function handlePhotoClick() { setShowCalendar(false); } function handlePhotoClose() { setShowCalendar(true); } function handleSetDate(newDate) { setDate(newDate); } useEffect(() => { if (!id) { return; } axios.get(`/places/${id}`).then((res) => { setPlace(res.data); }); }, [id]); if (!place) return ""; const today = DateTime.now().startOf("day"); // Create a new Date object using the selected date state const selectedDateObj = DateTime.fromISO(date).startOf("day"); const isTodayOrFutureDate = selectedDateObj >= today; const selectedDateOnly = date.split("T")[0]; return ( <div className="mx-0 mt-4 bg-slate-100 px-8 pt-8 "> <h1 className="text-3xl">{place.title}</h1> <AddressLink>{place.address}</AddressLink> <PlaceGallery place={place} onPhotoClick={handlePhotoClick} onCloseClick={handlePhotoClose} /> <div className="mt-8 mb-8 grid grid-cols-1 gap-8 md:grid-cols-[2fr_1fr]"> <div> <div className="my-2"> <h2 className="text-2xl font-semibold">Description</h2> <div className="my-6">{place.description}</div> </div> <div className=""> Open time: {place.openTime} <br /> Close time: {place.closeTime} <br /> Max number of guests: {place.maxGuests} </div> {showCalendar && ( <div> <Calendar setDate={handleSetDate} /> </div> )} {/* Render TimePicker only if selected date is not in the past */} {isTodayOrFutureDate ? ( <div> <TimePicker onTimeSelect={handleSelectTime} selectedDate={selectedDateObj.toJSDate()} onCheckoutTimeChange={handleCheckoutTime} /> </div> ) : ( <p className="mt-10 text-2xl font-semibold"> You cannot book a place in the past. </p> )} </div> <div> <BookingWidget place={place} selectedTime={selectedTime} checkoutTime={checkoutTime} selectedDate={selectedDateOnly} /> </div> </div> <div className="-mx-8 border-t bg-slate-100 px-8 py-8"> <div> <h2 className="text-2xl font-semibold">Extra info</h2> </div> <div> <div className="mb-4 mt-2 text-sm leading-5 text-gray-700"> {place.extraInfo} </div> </div> </div> </div> ); }
<template> <div class="articleSection"> <h1 class="articleTitle">{{ article.title }}</h1> <div class="articleBrown"> <q-breadcrumbs class="text-pink-8"> <template v-slot:separator> <q-icon size="1.5em" name="chevron_right" color="pink-8" /> </template> <q-breadcrumbs-el label="健康資訊" @click="goBack" class="pointer" /> <q-breadcrumbs-el :label="article.title" /> </q-breadcrumbs> <p class="articleTime"> time: <span>{{ article.date }}</span> </p> </div> <q-card class="articleCard"> <img :src="article.image" class="articleImg" alt="文章圖片" /> <div v-for="(section, index) in article.sections" :key="index" class="articleCardContent"> <p>{{ section.title }}</p> <p v-html="section.content"></p> </div> <div class="articleFrom"> <p>本文出處 : {{ article.from }}</p> </div> <div class="backBtn"><q-btn @click="goBack">回上一頁</q-btn></div> </q-card> </div> </template> <script setup> const route = useRoute() const router = useRouter() const goBack = () => { router.back() } const articles = [ { id: '1', title: '健康喝水原則', date: '2023-10-01', image: '/news/article1.png', from: 'HEHO健康 你喝對了嗎? 遵守4個喝水原則 健康又安心 https://heho.com.tw/archives/10109', sections: [ { title: '原則 1:按身體需求去喝水,別喝過量的水', content: ' 澳洲蒙那許大學首席研究員法雷爾(Michael Farrell)主張「按身體的需求去喝水才是正確的,覺得口渴時再喝水,比按照規定時間去喝水更健康」,而研究證實,過度飲用水後大腦吞咽機制工作量增加了3倍,也會使身體處於水中毒或低納血症的危險中,當血液中的納含量變得異常低時,可能會引起嗜睡、噁心,甚至昏迷的症狀。' }, { content: '在正常的新陳代謝下,每人每天至少要有1000毫升的尿液,才能排除當天所製造的身體廢棄物,只要是尿液顏色清澈、並且每天排尿6至7次,就代表喝水量足夠。醫界有個簡易的算法來推估每個人每天應該飲用的水量,就是體重(公斤)X33=一天所需飲用水的毫升數,大概是1500至2000毫升。' }, { title: '原則 2:喝脫水飲料要喝同量的水,不可用飲料代替水', content: ' 湯汁、飲料、及茶飲等有味道的液體,都不能用來取代喝水。如果喝了含咖啡因、酒精、加糖的脫水飲料,例如咖啡、汽水等碳酸飲料與酒類,就要補充更多的飲水,而補水的原則是「喝一杯脫水飲料,要補回一杯半同等量的純水」。' }, { content: ' 補充脫水飲料的水份,不可以代替原本就需要喝的當日水量。舉例來說,你一天需要2000 毫升的飲水,而你今天喝了一杯100 毫升的咖啡,那你今天就需要喝上2000 +(100 X 1.5 = 150)= 2150 毫升的水量。' }, { title: '原則 3:患特殊疾病者喝水需控制適量', content: ' 心血管疾病患者如果醫師沒有要求限制喝水量,最好在睡前半小時喝150cc的水,早上起床時也要喝水,可稀釋血液濃稠度,降低中風及心肌梗塞的可能性。' }, { content: ' 如出現下肢水腫或短促呼吸時就得減少水分的攝取;如有心肺積水時,甚至要將每日攝取水量控制在500ml以內。因此若有疾病狀況,最好請教醫師再決定是否增減喝水量。而腎功能不好或洗腎的病人,因為腎臟腎絲球過濾功能變差,可以處理的水量變少,攝取水的份量要更加小心。' }, { title: '原則 4:喝好水、暖水,別喝久置的水與冰水', content: ' 我們每天飲水所用的自來水含微量「三鹵甲烷」,雖不至於造成嚴重危害,但若能運用簡單方法在飲用前先去除,就能保障健康。可以自來水煮沸時先將抽油煙機打開,再打開水壺的蓋子、轉小火再煮5至10分鐘,簡單動作就可減少水中的三鹵甲烷,讓你的飲用水變成「好水」。' } ] }, { id: '2', title: '水對人體的重要', date: '2023-10-01', image: '/news/article2.png', from: 'HEHO健康 水有多重要 說給你知道! https://heho.com.tw/archives/11502', sections: [ { content: '水是人體最重要的組成成分,我們體內有60%是水,而大腦就含有75%以上的水量。<br>大腦正不正常,水是關鍵之一,研究證實人體的大腦功能和攝水量有關,尤其是認知和情緒功能。<br>當我們體內缺水時,不管是大人還是小孩,注意力、記憶力、反應速度及正向情緒通通都扣分。' }, { content: '一天當中,我們至少需要7杯水。湯汁、飲料、及茶飲等有味道的液體,都不能取代喝水。<br>如果喝了就要補充更多的飲水,而補水的原則是「喝一杯脫水飲料,要補回一杯半同等量的純水」。' }, { title: '氣泡水和一般水一樣嗎?是不是更健康?', content: ' 答案是否定的。氣泡水不但會讓你感覺更餓,甚至會讓你變胖!所以還是喝水最健康。' }, { content: ' 大部分的人都認為喝熱水比冰水好!但我必須要語重心長的告訴你,熱水亂喝可是不行的哦!<br>國外曾有研究針對長期飲用65度C以上的熱水沖茶喝的民眾做實驗,發現他們罹患食道癌的風險是一般人的8倍,這是因為食道內壁的黏膜在超過65度C時,食道的黏膜就會被燙傷。所以經常喝熱茶、熱湯的人長期下來會讓口腔、食道黏膜產生細胞病變,於是就提高了食道癌的機率,而且溫度越高,罹患的機率就越高。<br>在服用藥物時搭配熱開水,也可能會讓藥效減半,症狀加重,所以還是配溫開水最好!' }, { title: '你或許會疑惑,喝冰水是不是也很不健康?', content: ' 在國外研究文獻顯示在人體實驗中發現喝了3℃冰水後卻可以增加新陳代謝 4.5%,並可持續 60 分鐘,這個實驗證明喝冰水可以「暫時增加」新陳代謝,但是只是喝室溫的冷水,就不會有增加代謝的情形。順帶一提,這項研究理論大人小孩通用。' }, { content: '對於一般健康成人和孩童,喝冰水是可以暫時增加新陳代謝的,對於減重有正面的幫助。但如果你本身有氣喘、心臟病、控制不佳的高血壓,或是中風等等的病史,喝冰水會有誘發疾病發作的可能,請你千萬不要想不開。<br>但還是要注意,在夏天的時候喝冰水,有可能會越喝越渴、越喝越熱。' }, { title: '雖然喝水很健康,但也別過量!', content: '只要是尿液顏色清澈、並且每天排尿6到7次,就代表喝水量足夠。<br>攝取過多水份也會造成痙攣、昏睡,甚至是俗稱的水中毒,會造成大腦細胞膨脹,出現腦水腫的現象,嚴重可致死。這時候病患會感覺到暈眩的不適感,但急救時絕不可讓病患躺下,會加速腦水腫的程度,所以除了要記得補充鹽水外,還要讓病患保持坐姿。' } ] }, { id: '3', title: '喝水的好處', date: '2023-10-01', image: '/news/article3.jpg', from: 'HEHO健康 水喝的夠腦袋靈活、膝蓋不痛!多喝水的 6 大好處 https://heho.com.tw/archives/62367', sections: [ { content: '水可以說是生命的基礎,也是全身關節的潤滑劑,更是神經系統的緩衝劑。人體有70%是水組成的,人體如果喪失10%水分時即會感到不適,開始對身體組織造成損傷,而喪失20~25%時就會對生命帶來危險。因此每天喝到足夠的水分是很重要的,而且只要持續多喝水,它為身體帶來的好處及變化是可以看見的!' }, { title: '多喝水的6大好處' }, { title: '1. 大腦變靈活', content: '水是維持腦部正常功能運作的關鍵之一,它與大腦記憶力、情緒、視覺專注力是有相關的,因為血裡有高達90%是水,而血水承載氧氣進入大腦,只要一缺水,就會缺血,導致腦缺氧。而大腦佔了體內氧氣消耗的20%,有充足的氧氣才能讓腦袋運轉更快、更靈活。' }, { title: '2. 血管更健康', content: ' 多喝水可以幫助降低血液的黏稠度,減少血栓、高血壓以及心血管疾病的發生率。' }, { title: '3. 抗老顯年輕', content: ' 水可以活化細胞、加速身體代謝以及排毒。而且肌膚的彈性也要靠水分來支撐,所以每天喝足夠的水分,就能有助於修復皮膚更顯年輕。' }, { title: '5. 提升抵抗力', content: '水是非常重要的存在,它參與了整個身體的循環,可以幫助人體的細胞與組織想維持正常的生理機能。它可以運送養分、氧氣到各個組織,也可將廢物經由肝臟、腎臟排出體外。當體內的廢物、毒素排出體外後,抵抗力自然就提升。' }, { title: '6. 加速新陳代謝', content: '身體有足夠水分,就能加速體內的新陳代謝、幫助排毒減肥。有研究顯示,水分攝取不足時會導致脂肪堆積,相反的如果有攝取到充足的水分,就能有效減少脂肪堆積在體內。' }, { content: '※小提醒:人體吸收水分是有上限的,所以需要分次飲水。平均來說,人體20分鐘大約能吸收200c.c.的水分,快速、大量的飲水其實是做白工。建議可以將水放在手邊容易取得的位置,想到的時候就喝個幾口。' } ] }, { id: '4', title: '冬天也要補水', date: '2023-10-01', image: '/news/article4.jpg', from: '健康2.0 冬天沒流汗也要多喝水!營養師:小心水喝不夠會中風、關節退化,甚至記憶力衰退 https://health.tvbs.com.tw/medical/330607', sections: [ { content: '天氣冷,許多民眾都會忘記補充水分,或自以為沒流汗就可以不用喝水,但要注意,這樣可是會影響身體健康!營養師林雨薇表示,水喝太少,除了宿便纏身,也會導致許多疾病發生,甚至引發中風、關節退化及記憶力衰退!' }, { title: '不渴也要喝水', content: '林雨薇指出,許多民眾因為不口渴,而忽略補充水分,結果出現尿液特別黃、排便乾硬,講話甚至有口臭等,但其實這些現象都是「身體在告訴你缺水」。但是不渴為什麼要喝水?林雨薇說,人體50至70%是水組成,且人體是一台精密且複雜的儀器,口腔、消化道、血液及呼吸循環系統、新陳代謝相關組織器官等,通通需要通過水為媒介才能新陳代謝,就連肌膚也不例外。若忽略喝水,身體會接二連三發生大小症狀。' }, { content: ' 短時間缺水,可能出現宿便、口臭、濃黃尿。中期則有可能發生肌膚乾燥、皺紋、心悸、中風及尿道炎等。而長期缺水,則可能導致關節退化、記憶力衰退甚至發生尿毒症!' }, { content: ' 林雨薇提醒,許多民眾忙起來,專注力都投入在工作、家庭、生活上,稍不留意,水分就有可能攝取不足,建議養成隨時隨地補充水分習慣,且定期如廁不憋尿的健康生活。' }, { title: '每天應補充1500至2000cc白開水', content: '至於每天要喝多少水才夠?林雨薇說,每天應喝1500至2000cc白開水,以每杯250cc的水為例,即約6至8杯水。若有運動或大量流汗勞力活動時,也應再額外補充水分,有些民眾應身體狀況,不確定自己是否適合喝這麼多水,也可諮詢醫師及營養師。' }, { content: '有些民眾也會擔心水喝太多會水腫,林雨薇說,水腫原因複雜,但容易引起水腫的外在3大因素為「吃太鹹、站太久、穿太緊」。也因此,飲食重口味、腳循環差或血管靜脈曲張、愛穿緊身褲者,要多加留意。另外若罹患心衰竭、腎衰竭、肝衰竭,或是身體營養不良也容易有腫水現象。林說,對於一般健康民眾而言,日常保健飲水不會直接引起病理性水腫,而外在因素引起的水腫情況,通常較為短暫非長期慢性。' }, { content: '※小提醒:人體吸收水分是有上限的,所以需要分次飲水。平均來說,人體20分鐘大約能吸收200c.c.的水分,快速、大量的飲水其實是做白工。建議可以將水放在手邊容易取得的位置,想到的時候就喝個幾口。' } ] }, { id: '5', title: '喝水不只可以保健,還能減肥?', date: '2023-10-01', image: '/news/article5.jpg', from: 'HEHO健康喝水也能瘦!運動營養師小紅教你減肥的喝水公式!https://heho.com.tw/archives/51821', sections: [ { content: '水份攝取量,會依每個人的年齡、體型、性別、體重、工作性質而不同,運動營養師小紅(蘇政瑜)表示,一般人每天的基本喝水建議量,是將自己的體重乘以30(單位:c.c.),就是每天建議的喝水量。舉例來說,一個體重60公斤的人,每天的建議飲水量就是60 × 30 = 1800c.c.。' }, { content: '不過,如果是想要用喝水減肥的人,就需要將自己的體重乘以40,作為每天的基本喝水量。像是60公斤的人,就需要喝到2400c.c.的水。' }, { title: '一次猛灌500c.c.水 反而是做白工', content: '人體吸收水分是有上限的,所以需要分次飲水。「平均來說,人體20分鐘大約能吸收200c.c.的水分,攝取水分的速度不要快於這個。有的人為了達到飲水目標,一次猛灌500c.c.,但是去一下廁所就沒了,」 蘇政瑜指出,快速、大量的飲水其實是做白工。建議可以將水放在手邊容易取得的位置,想到的時候就喝個幾口。' }, { content: ' 至於喝水的時機,蘇政瑜表示,只要不要睡前飲水、影響睡眠就好。目前的營養學教科書上,並沒有特別強調水溫,雖然過去有研究認為喝冰水時身體會消耗更多卡路里,不過其實差別微乎其微,加上中醫不提倡喝冰水,因此蘇政瑜認為,選擇自己喜歡的即可。' }, { title: '如果不喜歡白開水 你還有這些選擇', content: '另外,我們每天吃的食物內就含有很多水分,如飯菜、麵湯、稀飯、蔬果、果汁等等,都內含的水份,都算是喝水。「所以,如果不喜歡喝水,也可以換成無糖、零熱量的飲料,例如黑咖啡、茶或是檸檬汁,」蘇政瑜指出。' }, { content: '對於有運動習慣的人,蘇政瑜建議,至少要在30分鐘前先飲水,如果運動會在一個小時內結束,也不需要在運動間特別補充水分。如果運動期間想喝水,就喝1、2口就好了。' }, { title: '水喝多了會不會有壞處?', content: '有些人擔心,水喝太多會不會造成水中毒?林新醫院腎臟內科主任黃嘉宏表示,在正常的身體狀況下,所謂的水中毒(即低滲透壓性低血鈉),得每日飲水到10公升以上,請民眾不必過於擔心。' }, { content: '不過,腎功能不好或洗腎的病人,因為腎臟腎絲球過濾功能變差,可以處理的水量變少,攝取水份量就要特別加小心。慢性腎臟病有各種不同的原因及嚴重程度,病人應該和腎臟專科醫師討論自己適當的水份及電解質攝取量,以達到適當的體力、血壓、心律、呼吸及沒有水腫為最理想。' } ] }, { id: '6', title: '喝水治百病!?補充水分好健康!', date: '2023-10-01', image: '/news/article6.jpg', from: 'HEHO健康 喝水治百病!補充水分好健康!https://heho.com.tw/archives/72365', sections: [ { content: '常聽人說喝水好健康,喝水到底是對哪裡健康呢?人體有70%是水組成的,身體各個器官與系統都仰賴水分的補給才能維持基礎運作。喝水真的好處多多,這裡列出18個需要你時時補充水分的部位,提醒大家多多喝水。' }, { title: '喝水百病消', content: '1. 大腦<br>補充水分有益於大腦複雜的認知工作與記憶力,並有益於學習能力,改善情緒問題<br><br>2. 腦脊髓液<br>腦脊髓液幾乎都由水分組成,可保護腦部不受外力影響,減輕大腦壓力<br><br>3. 眼睛<br>眼睛結構幾乎由水組成,水分具運送營養及維持眼內壓力的作用<br><br>4. 嘴巴<br>嘴乾也是口臭原因之一,唾液具殺菌作用,能殺死病菌減少口腔異味,而多喝水能刺激唾液分泌<br><br>5. 呼吸道<br>保持呼吸道濕潤能形成屏障,避免外界刺激物干擾,減少過敏、和緩氣喘症狀<br><br>6. 心臟<br>缺水時心跳會跳得比平常快,使人心悸不舒服<br><br>7. 肝臟<br>肝臟需水份才能分解肝醣、儲存能量,無法分解肝醣會影響血糖恆定<br><br>8. 腸胃<br>水份不足會使消化不良或是便秘,可喝點水幫助腸胃蠕動<br><br>9. 脾臟<br>脾臟缺水時會使身體代謝能力下降,長期缺水有可能使脾腫大<br><br>10. 腎臟<br>腎臟若缺水會影響毒素代謝、生成結石、增加泌尿道感染的機率<br><br>11. 脊椎<br>若椎間盤軟骨水份不足,容易彎腰駝背、腰酸背痛<br><br>12. 女性私密處<br>陰道屬於黏膜組織,需水分滋潤,充足水分可減少異味<br><br>13. 皮膚<br>皮膚缺水角質層就會受損,無法發揮對外的屏障能力,產生黯淡、乾燥、敏感、脫皮、粗糙等狀況<br><br>14. 血液<br>血液負責運輸、物質交換,缺水會影響循環,使人疲累。水分不足還會使血液變濃稠,血壓升高<br><br>15. 肌肉<br>水分充足能使肌肉維持電解質平衡,比較不會疲勞<br><br>16. 淋巴結<br>缺水會影響淋巴結過濾和清除掉病原體、排除毒素的能力<br><br>17. 軟骨組織<br>軟骨中的水分能夠減少關節摩擦,並吸收震動。缺水容易磨損軟骨<br><br>18. 新陳代謝<br>缺水會使代謝功能下降,進而影響減重<br><br>' } ] } ] const article = ref({}) article.value = articles.find(a => a.id === route.params.id) </script> <style lang="scss" scoped> @import 'assets/newsContent'; </style>
package com.taggy.training.webservices.handlers.server; import java.util.Map; import java.util.HashMap; import java.util.Collections; import javax.jws.HandlerChain; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.soap.SOAPBinding; @WebService(targetNamespace = "http://quickstart.taggy.com") @SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED) @HandlerChain(file = "serverhandler-chain.xml") public class RabbitCounter { private Map<Integer, Integer> cache = Collections.synchronizedMap(new HashMap<Integer, Integer>()); @WebMethod public int countRabbits(int n) throws FibException { // Throw a fault if n is negative. if (n < 0) throw new FibException("Neg. arg. not allowed.", n + " < 0"); // Easy cases. if (n < 2) return n; // Return cached values if present. if (cache.containsKey(n)) return cache.get(n); if (cache.containsKey(n - 1) && cache.containsKey(n - 2)) { cache.put(n, cache.get(n - 1) + cache.get(n - 2)); return cache.get(n); } // Otherwise, compute from scratch, cache, and return. int fib = 1, prev = 0; for (int i = 2; i <= n; i++) { int temp = fib; fib += prev; prev = temp; } cache.put(n, fib); // cache value for later lookup System.out.println("XXXXXXXXXXXXXXXXXXXXXXXX"); return fib; } }
import styled from "styled-components" import { baseSuissetIntlRegular } from "../../../ui/base" import { Input } from "../../../ui/atoms/Input" import { Button } from "../../../ui/atoms/Button" import { Text } from "../../../ui/atoms/Text" import { ChatContentSkeleton } from "./ChatContentSkeleton" import { ChatMessages } from "./ChatMessages" import { extractLink } from "../utils/linkHandler" import { X } from "../../../assets/icons" import { useEffect, useState } from "react" type ChatContentProps = { chatInputRef: React.RefObject<HTMLInputElement> chat?: ChatType handleCloseChat: () => void handleSendMessage: (chatId: string, message: string) => Promise<void> } & ChatIdProps export const ChatMessage = styled(Text)` overflow-wrap: anywhere; ` export const ChatMessageLink = styled(ChatMessage).attrs({ target: "_blank", rel: "noopener noreferrer", })` color: var(--GREEN-VII); text-decoration: underline; text-decoration-color: var(--GREEN-VII); @media (width > 768px) { &::after { content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="1rem" viewBox="0 -960 960 960" width="1rem" fill="rgb(40, 82, 48)"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h280v80H200v560h560v-280h80v280q0 33-23.5 56.5T760-120H200Zm188-212-56-56 372-372H560v-80h280v280h-80v-144L388-332Z"/></svg>'); position: relative; margin-left: 3px; top: 3px; } } ` const ChatImage = styled.img` max-width: 200px; max-height: 200px; object-fit: cover; ` export const MESSAGE_TEXT_LINK = (MESSAGE_TEXT: string) => { const IMAGE_URL = MESSAGE_TEXT const [isImage, setIsImage] = useState(false) useEffect(() => { const img = new Image() img.onload = () => setIsImage(true) img.onerror = () => setIsImage(false) img.src = IMAGE_URL }, [IMAGE_URL]) if (isImage) { return <ChatImage src={IMAGE_URL} alt="Image" /> } return ( <ChatMessageLink as="a" size="small" type="SFPROMEDIUM" href={isImage ? undefined : extractLink(MESSAGE_TEXT)} > {MESSAGE_TEXT} </ChatMessageLink> ) } export const ChatInput = styled(Input)` border: none; color: var(--WHITE-I); ${baseSuissetIntlRegular} font-weight: 400; letter-spacing: 2px; height: 3rem; width: 100%; background-color: var(--BLACK-I); ` export const SendButton = styled(Button)` height: max-content; ` export const CloseChat = styled(Button)` position: absolute; right: 0; top: 0; &:hover { background-color: var(--RED-I); color: var(--WHITE-I); } ` export function ChatContent({ chat, chatInputRef, handleCloseChat, handleSendMessage, chatId, }: ChatContentProps) { async function handleSendChat(event: React.FormEvent<HTMLFormElement>) { try { event.preventDefault() const chatInput = chatInputRef.current?.value if (!chatInput || !chatId) return await handleSendMessage(chatId, chatInput) chatInputRef.current!.value = "" } catch (error) { throw new Error("Something went wrong") } } if (!chatId) { return ( <ContentContainer> <ChatContentSkeleton /> </ContentContainer> ) } return ( <ContentContainer> <CloseChat onClick={handleCloseChat}> <X /> Fechar </CloseChat> <ChatArea className="flex flex-1 flex-col text-[var(--BLACK-I)] pr-[12%]"> <ChatMessages chat={chat} /> </ChatArea> <form className="flex items-center text-[var(--BLACK-I)] gap-4" onSubmit={handleSendChat} > <ChatInput id="chat-input" name="chat-input" placeholder="Jot something down" ref={chatInputRef} /> <SendButton type="submit">Enviar</SendButton> </form> </ContentContainer> ) } const ContentContainer = styled.div` position: relative; padding-left: calc(2rem - 8px); display: flex; flex: 1; flex-direction: column; padding-bottom: 1rem; @media (max-width: 668px) { display: none; } ` const ChatArea = styled.div` overflow-y: scroll; margin-bottom: 1rem; `
= STAT 29000: Project 9 -- Spring 2021 **Motivation:** In the previous project you worked through some common logic needed to make a good script. By the end of the project `argparse` was (hopefully) a welcome package to be able to use. In this project, we are going to continue to learn about `argparse` and create a CLI for the https://data.whin.org[WHIN Data Portal]. In doing so, not only will we get to practice using `argparse`, but you will also get to learn about using an API to retrieve data. An API (application programming interface) is a common way to retrieve structured data from a company or resource. It is common for large companies like Twitter, Facebook, Google, etc. to make certain data available via API's, so it is important to get some exposure. **Context:** This is the second (of two) projects where we will learn about creating and using Python scripts. **Scope:** python .Learning objectives **** - Write a python script that accepts user inputs and returns something useful. - Interact with an API to retrieve data. **** Make sure to read about, and use the template found xref:templates.adoc[here], and the important information about projects submissions xref:submissions.adoc[here]. == Dataset The following questions will involve retrieving data using an API. Instructions and hints will be provided as we go. == Questions === Question 1 WHIN (Wabash Heartland Innovation Network) has deployed hundreds of weather stations across the region so farmers can use the data collected to become more efficient, save time, and increase yields. WHIN has kindly granted access to 20+ public-facing weather stations for educational purposes. Navigate to https://data.whin.org/data/current-conditions, and click on the "CREATE ACCOUNT" button in the middle of the screen: ![](./images/p9_01.png) Click on "I'm a student or educator": ![](./images/p9_02.png) Enter your information. For "School or Organization" please enter "Purdue University". For "Class or project", please put "The Data Mine Project 9". For the description, please put "We are learning about writing scripts by writing a CLI to fetch data from the WHIN API." Please use your purdue.edu email address. Once complete, click "Next". Carefully read the LICENSE TERMS before accepting, and confirm your email address if needed. Upon completion, navigate here: https://data.whin.org/data/current-conditions Read about the API under "API Usage". An endpoint is the place (in this case the end of a URL (which can be referred to as the URI)) that you can use to access/delete/update/etc. a given resource depending on the HTTP method used. What are the 3 endpoints of this API? Write and run a script called `question01.py` that, when run, tries to print the current listing of the weather stations. Instead of printing what you think it should print, it will print something else. What happened? [source,bash] ---- $HOME/question01.py ---- [TIP] ==== You can use the `requests` library to run the HTTP GET method on the endpoint. For example: ==== [source,python] ---- import requests response = requests.get("https://datamine.purdue.edu/") print(response.json()) ---- [TIP] ==== We want to use our regular course environment, therefore, make sure to use the following shebang: `#!/class/datamine/apps/python/f2020-s2021/env/bin/python` ==== ++++ <iframe class="video" src="https://mediaspace.itap.purdue.edu/id/1_3pwhon32"></iframe> ++++ .Items to submit ==== - List the 3 endpoints for this API. - The entirety of the updated (working) script's content in a Python code chunk with chunk option "eval=F". - Output from running your script with the given examples. ==== === Question 2 In question 1, we quickly realize that we are missing a critical step -- authentication! Recall that authentication is the process of a system understanding _who_ a person is, authorization is the process of telling whether or not somebody (or something) has permissions to access/modify/delete/etc. a resource. When we make GET requests to https://data.whin.org/api/weather/stations, or any other endpoint, the server that returns the data we are trying to access has no clue who we are, which explains the result from question 1. While there are many methods of authentication, WHIN is using Bearer tokens. Navigate https://data.whin.org/account[here]. Take a look at your account info. You should see a large chunk of random numbers and text. This is your bearer token that you can use for authentication. The bearer token is to be sent in the "Authorization" header of the request. For example: [source,python] ---- import requests my_headers = {"Authorization": "Bearer LDFKGHSOIDFRUTRLKJNXDFGT"} response = requests.get("my_url", headers = my_headers) ---- Update your script (as a new script called `question02.py`), and test it out again to see if we get the expected results now. `question02.py` should only print the first 5 results. A couple important notes: - The bearer token should be taken care of like a password. You do NOT want to share this, ever. - There is an inherent risk in saving code like the code shown above. What if you accidentally upload it to GitHub? Then anyone with access could potentially read and use your token. How can we include the token in our code without typing it in our code? The typical way to handle this is to use environment variables and/or a file containing the information that is specifically NOT shared unless necessary. For example, create a file called `.env` in your home directory, with the following contents: [source,txt] ---- MY_BEARER_TOKEN=aslgdkjn304iunglsejkrht09 SOME_OTHER_VARIABLE=some_other_value ---- In this file, replace the "aslgdkj..." part with you actual token and save the file. Then make sure only YOU can read and write to this file by running the following in a terminal: [source,bash] ---- chmod 600 $HOME/.env ---- Now, we can use a package called `dotenv` to load the variables in the `$HOME/.env` file into the environment. We can then use the `os` package to get the environment variables. For example: [source,python] ---- import os from dotenv import load_dotenv # This function will load the .env file variables from the same directory as the script into the environment load_dotenv() # We can now use os.getenv to get the important information without showing anything. # Now, all anybody reading the code sees is "os.getenv('MY_BEARER_TOKEN')" even though that is replaced by the actual # token when the code is run, cool! my_headers = {"Authorization": f"Bearer {os.getenv('MY_BEARER_TOKEN')}"} ---- Update `question02.py` to use `dotenv` and `os.getenv` to get the token from the local `$HOME/.env` file. Test out your script: [source,bash] ---- $HOME/question02.py ---- ++++ <iframe class="video" src="https://mediaspace.itap.purdue.edu/id/1_fotbs2kc"></iframe> ++++ ++++ <iframe class="video" src="https://mediaspace.itap.purdue.edu/id/1_fq0pqm2c"></iframe> ++++ .Items to submit ==== - The entirety of the updated (working) script's content in a Python code chunk with chunk option "eval=F". - Output from running your script with the given example. ==== === Question 3 That's not so bad! We now know how to retrieve data from the API as well as load up variables from our environment rather than insecurely just pasting them in our code, great! A query parameter is (more or less) some extra information added at the end of the endpoint. For example, the following url has a query parameter called `param` and value called `value`: \https://example.com/some_resource?param=value. You could even add more than one query parameter as follows: \https://example.com/some_resource?param=value&second_param=second_value -- as you can see, now we have another parameter called `second_param` with a value of `second_value`. While the query parameters begin with a `?`, each subsequent parameter is added using `&`. Query parameters can be optional or required. API's will sometimes utilize query parameters to filter or fine-tune the returned results. Look at the documentation for the `/api/weather/station-daily` endpoint. Use your newfound knowledge of query parameters to update your script (as a new script called `question03.py`) to retrieve the data for station with id `150` on `2021-01-05`, and print the first 5 results. Test out your script: [source,bash] ---- $HOME/question03.py ---- ++++ <iframe class="video" src="https://mediaspace.itap.purdue.edu/id/1_xjcywy0i"></iframe> ++++ .Items to submit ==== - The entirety of the updated (working) script's content in a Python code chunk with chunk option "eval=F". - Output from running your script with the given example. ==== === Question 4 Excellent, now let's build our CLI. Call the script `whin.py`. Use your knowledge of `requests`, `argparse`, and API's to write a CLI that replicates the behavior shown below. For convenience, only print the first 2 results for all output. [TIP] ==== - In general, there will be 3 commands: `stations`, `daily`, and `cc` (for current condition). - You will want to create a subparser for each command: `stations_parser`, `current_conditions_parser`, and `daily_parser`. - The `daily_parser` will have 2 _position_, _required_ arguments: `station_id` and `date`. - The `current_conditions_parser` will have 2 _optional_ arguments of type `str`: `--center`/`-c` and `--radius`/`-r`. - If only one of `--center` or `--radius` is present, you should use `sys.exit` to print a message saying "Need both center AND radius, or neither.". - To create a subparser, just do the following: [source,python] ---- parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help="possible commands", dest="command") my_subparser = subparsers.add_parser("my_command", help="my help message") my_subparser.add_argument("--my-option", type=str, help="some option") args = parser.parse_args() ---- - Then, you can access which command was run with `args.command` (which in this case would only have 1 possible value of `my_command`), and access any parser or subparsers options with `args`, for example, `args.my_option`. ==== [source,bash] ---- $HOME/whin.py ---- ---- usage: whin.py [-h] {stations,cc,daily} ... positional arguments: {stations,cc,daily} possible commands stations list the stations cc list the most recent data from each weather station daily list data from a given day and station optional arguments: -h, --help show this help message and exit ---- [TIP] ==== A good way to print the help information if no arguments are provided is: [source,python] ---- if len(sys.argv) == 1: parser.print_help() parser.exit() ---- ==== [source,bash] ---- $HOME/whin.py stations -h ---- ---- usage: whin.py stations [-h] optional arguments: -h, --help show this help message and exit ---- [source,bash] ---- $HOME/whin.py cc -h ---- ---- usage: whin.py cc [-h] [-c CENTER] [-r RADIUS] optional arguments: -h, --help show this help message and exit -c CENTER, --center CENTER return results near this center coordinate, given as a latitude,longitude pair -r RADIUS, --radius RADIUS search distance, in meters, from the center ---- [source,bash] ---- $HOME/whin.py cc ---- ---- [{'humidity': 90, 'latitude': 40.93894, 'longitude': -86.47418, 'name': 'WHIN001-PULA001', 'observation_time': '2021-03-16T18:45:00Z', 'pressure': '30.051', 'rain': '0', 'rain_inches_last_hour': '0', 'soil_moist_1': 6, 'soil_moist_2': 11, 'soil_moist_3': 14, 'soil_moist_4': 9, 'soil_temp_1': 42, 'soil_temp_2': 40, 'soil_temp_3': 40, 'soil_temp_4': 41, 'solar_radiation': 203, 'solar_radiation_high': 244, 'station_id': 1, 'temperature': 40, 'temperature_high': 40, 'temperature_low': 40, 'wind_direction_degrees': '337.5', 'wind_gust_direction_degrees': '22.5', 'wind_gust_speed_mph': 6, 'wind_speed_mph': 3}, {'humidity': 88, 'latitude': 40.73083, 'longitude': -86.98467, 'name': 'WHIN003-WHIT001', 'observation_time': '2021-03-16T18:45:00Z', 'pressure': '30.051', 'rain': '0', 'rain_inches_last_hour': '0', 'soil_moist_1': 6, 'soil_moist_2': 5, 'soil_moist_3': 6, 'soil_moist_4': 4, 'soil_temp_1': 40, 'soil_temp_2': 39, 'soil_temp_3': 39, 'soil_temp_4': 40, 'solar_radiation': 156, 'solar_radiation_high': 171, 'station_id': 3, 'temperature': 40, 'temperature_high': 40, 'temperature_low': 39, 'wind_direction_degrees': '337.5', 'wind_gust_direction_degrees': '337.5', 'wind_gust_speed_mph': 8, 'wind_speed_mph': 3}] ---- [IMPORTANT] ==== Your values may be different because they are _current_ conditions. ==== [source,bash] ---- $HOME/whin.py cc --radius=10000 ---- ---- Need both center AND radius, or neither. ---- [source,bash] ---- $HOME/whin.py cc --center=40.4258686,-86.9080654 ---- ---- Need both center AND radius, or neither. ---- [source,bash] ---- $HOME/whin.py cc --center=40.4258686,-86.9080654 --radius=10000 ---- ---- [{'humidity': 86, 'latitude': 40.42919, 'longitude': -86.84547, 'name': 'WHIN008-TIPP005 Chatham Square', 'observation_time': '2021-03-16T18:45:00Z', 'pressure': '30.012', 'rain': '0', 'rain_inches_last_hour': '0', 'soil_moist_1': 5, 'soil_moist_2': 5, 'soil_moist_3': 5, 'soil_moist_4': 5, 'soil_temp_1': 42, 'soil_temp_2': 41, 'soil_temp_3': 41, 'soil_temp_4': 42, 'solar_radiation': 191, 'solar_radiation_high': 220, 'station_id': 8, 'temperature': 42, 'temperature_high': 42, 'temperature_low': 42, 'wind_direction_degrees': '0', 'wind_gust_direction_degrees': '22.5', 'wind_gust_speed_mph': 9, 'wind_speed_mph': 3}, {'humidity': 86, 'latitude': 40.38494, 'longitude': -86.84577, 'name': 'WHIN027-TIPP003 EXT', 'observation_time': '2021-03-16T18:45:00Z', 'pressure': '29.515', 'rain': '0', 'rain_inches_last_hour': '0', 'soil_moist_1': 5, 'soil_moist_2': 4, 'soil_moist_3': 4, 'soil_moist_4': 5, 'soil_temp_1': 43, 'soil_temp_2': 42, 'soil_temp_3': 42, 'soil_temp_4': 42, 'solar_radiation': 221, 'solar_radiation_high': 244, 'station_id': 27, 'temperature': 43, 'temperature_high': 43, 'temperature_low': 43, 'wind_direction_degrees': '337.5', 'wind_gust_direction_degrees': '337.5', 'wind_gust_speed_mph': 6, 'wind_speed_mph': 3}] ---- [source,bash] ---- $HOME/whin.py daily ---- ---- usage: whin.py daily [-h] station_id date whin.py daily: error: too few arguments ---- [source,bash] ---- $HOME/whin.py daily 150 2021-01-05 ---- ---- [{'humidity': 96, 'latitude': 41.00467, 'longitude': -86.68428, 'name': 'WHIN058-PULA007', 'observation_time': '2021-01-05T05:00:00Z', 'pressure': '29.213', 'rain': '0', 'rain_inches_last_hour': '0', 'soil_moist_1': 5, 'soil_moist_2': 6, 'soil_moist_3': 7, 'soil_moist_4': 5, 'soil_temp_1': 33, 'soil_temp_2': 34, 'soil_temp_3': 35, 'soil_temp_4': 35, 'solar_radiation': 0, 'solar_radiation_high': 0, 'station_id': 150, 'temperature': 31, 'temperature_high': 31, 'temperature_low': 31, 'wind_direction_degrees': '270', 'wind_gust_direction_degrees': '292.5', 'wind_gust_speed_mph': 13, 'wind_speed_mph': 8}, {'humidity': 96, 'latitude': 41.00467, 'longitude': -86.68428, 'name': 'WHIN058-PULA007', 'observation_time': '2021-01-05T05:15:00Z', 'pressure': '29.207', 'rain': '1', 'rain_inches_last_hour': '0', 'soil_moist_1': 5, 'soil_moist_2': 6, 'soil_moist_3': 7, 'soil_moist_4': 5, 'soil_temp_1': 33, 'soil_temp_2': 34, 'soil_temp_3': 35, 'soil_temp_4': 35, 'solar_radiation': 0, 'solar_radiation_high': 0, 'station_id': 150, 'temperature': 31, 'temperature_high': 31, 'temperature_low': 31, 'wind_direction_degrees': '270', 'wind_gust_direction_degrees': '292.5', 'wind_gust_speed_mph': 14, 'wind_speed_mph': 9}] ---- ++++ <iframe class="video" src="https://mediaspace.itap.purdue.edu/id/1_rej7d8oo"></iframe> ++++ .Items to submit ==== - The entirety of the updated (working) script's content in a Python code chunk with chunk option "eval=F". - Output from running your script with the given examples. ==== === Question 5 There are a multitude of improvements and/or features that we could add to `whin.py`. Customize your script (as a new script called `question05.py`), to either do something new, or fix a scenario that wasn't covered in question 4. Be sure to include 1-2 sentences that explains exactly what your modification does. Demonstrate the feature by running it in a bash code chunk. .Items to submit ==== - The entirety of the updated (working) script's content in a Python code chunk with chunk option "eval=F". - Output from running your script with the given examples. ====
import PropTypes from 'prop-types'; import './styles/style.css'; import TodoListButtons from '../TodoListButtons'; import { useDispatch, useSelector } from 'react-redux'; import { useRef } from 'react'; // import RegisterImage from '../../assets/images/modify.png'; const todoItem = ({ todoItem }) => { const dispatch = useDispatch(); const focusTest = useRef(); const todoItems = useSelector((state) => state.todoItems); const onModifyBtn = () => { if (todoItem.modify === false) { todoItem.modify = true; setTimeout(() => { focusTest.current.focus(); }, 0); } else { todoItem.modify = false; } dispatch({ type: 'todoReDraw', payload: todoItems }); }; const onDeleteBtn = () => { const newArray = todoItems.filter((item, index) => { if (todoItem.todoIdNumber !== index) { return item; } }); dispatch({ type: 'todoReDraw', payload: newArray }); }; const onModifyInput = (event) => { todoItem.list = event.target.value; }; const onKeyEnter = (event) => { if (event.key === 'Enter') { onModifyBtn(); } }; /* ※ 공백일 시에는 alert 창 띄우기 ※ 기능 참고 : https://velog.io/@dongoc21hj/Project-Retrotodo-ver.1-Preview ※ 리스트 클릭을 하면 수정 인풋 나오기 참고: https://chaelin1211.github.io/study/2021/04/02/todo-project-13.html */ return ( <> <td>0</td> <td> {/* 240503 컴포넌트화 시켜서 useRef 사용하기 */} {todoItem.modify === true ? ( <div> <input type='text' onChange={(event) => onModifyInput(event)} onKeyDown={(event) => onKeyEnter(event)} ref={focusTest} /> </div> ) : ( <div>{todoItem.todoTitle}</div> )} {/* // 240503 컴포넌트화 시켜서 useRef 사용하기 */} </td> <td> {/* 240503 컴포넌트화 시키기 */} {/* <TodoListButtons /> */} {todoItem.modify === true ? ( <button type='submit' className='todo__btn todo__btn-registration btn--bg-success' onClick={onModifyBtn} > 등록 </button> ) : ( <button type='button' className='todo__btn todo__btn-modify btn--bg-primary' onClick={onModifyBtn} > 수정 </button> )} <button type='button' className='todo__btn todo__btn-del btn--bg-danger' onClick={onDeleteBtn} > 삭제 </button> {/* // 240503 컴포넌트화 시키기 */} </td> </> ); }; todoItem.propTypes = { todoItem: PropTypes.object.isRequired, }; export default todoItem;
import { QUESTION, RECORD_TYPE_STR } from '../../../testUtils/dnsStubs.js'; import { Question } from './Question.js'; import { IANA_RR_TYPE_IDS, IANA_RR_TYPE_NAMES } from './ianaRrTypes.js'; import { DnsError } from './DnsError.js'; import { DnsClass } from './ianaClasses.js'; describe('constructor', () => { describe('Name', () => { test('Missing trailing dot should be added', () => { const name = 'example.com'; const question = new Question(name, QUESTION.typeId, QUESTION.classId); expect(question.name).toBe(`${name}.`); }); test('Present trailing dot should be left as is', () => { const name = 'example.com.'; const question = new Question(name, QUESTION.typeId, QUESTION.classId); expect(question.name).toStrictEqual(name); }); }); describe('Type', () => { test('Id should be stored as is', () => { const question = new Question(QUESTION.name, IANA_RR_TYPE_IDS.A, DnsClass.IN); expect(question.typeId).toStrictEqual(IANA_RR_TYPE_IDS.A); }); test('Name should be converted to id', () => { const id = IANA_RR_TYPE_IDS.A; const name = IANA_RR_TYPE_NAMES[id]; const question = new Question(QUESTION.name, name, DnsClass.IN); expect(question.typeId).toStrictEqual(id); }); }); describe('Class', () => { test('IN class should be used by default', () => { const question = new Question(QUESTION.name, IANA_RR_TYPE_IDS.A); expect(question.classId).toStrictEqual(DnsClass.IN); }); test('Id should be stored as is', () => { const question = new Question(QUESTION.name, IANA_RR_TYPE_IDS.A, DnsClass.IN); expect(question.classId).toStrictEqual(DnsClass.IN); }); test('Name should be converted to id', () => { const question = new Question(QUESTION.name, QUESTION.typeId, 'CH'); expect(question.classId).toStrictEqual(DnsClass.CH); }); }); }); describe('key', () => { test('Key should start with name', () => { expect(QUESTION.key).toStartWith(`${QUESTION.name}/`); }); test('Key should end with type id', () => { expect(QUESTION.key).toEndWith(`/${QUESTION.typeId}`); }); }); describe('getTypeName', () => { test('Name should be returned if defined by IANA', () => { expect(QUESTION.getTypeName()).toStrictEqual(RECORD_TYPE_STR); }); test('Error should be thrown if not defined by IANA', () => { const reservedType = 0; const question = QUESTION.shallowCopy({ type: reservedType }); expect(() => question.getTypeName()).toThrowWithMessage( DnsError, `RR type id ${reservedType} is not defined by IANA`, ); }); }); describe('equals', () => { test('Questions with different names should be unequal', () => { const differentQuestion = QUESTION.shallowCopy({ name: `sub.${QUESTION.name}` }); expect(QUESTION.equals(differentQuestion)).toBeFalse(); }); test('Questions with different types should be unequal', () => { const differentQuestion = QUESTION.shallowCopy({ type: QUESTION.typeId + 1 }); expect(QUESTION.equals(differentQuestion)).toBeFalse(); }); test('Questions with different classes should be unequal', () => { const differentQuestion = QUESTION.shallowCopy({ class: QUESTION.classId + 1 }); expect(QUESTION.equals(differentQuestion)).toBeFalse(); }); test('Questions with same attributes should be equal', () => { const equivalentQuestion = QUESTION.shallowCopy({}); expect(QUESTION.equals(equivalentQuestion)).toBeTrue(); }); }); describe('shallowCopy', () => { test('Nothing should be changed if nothing is overridden', () => { const copy = QUESTION.shallowCopy({}); expect(copy.name).toStrictEqual(QUESTION.name); expect(copy.typeId).toStrictEqual(QUESTION.typeId); expect(copy.classId).toStrictEqual(QUESTION.classId); }); test('New name should be used if set', () => { const newName = `sub.${QUESTION.name}`; const copy = QUESTION.shallowCopy({ name: newName }); expect(copy.name).toStrictEqual(newName); expect(copy.typeId).toStrictEqual(QUESTION.typeId); expect(copy.classId).toStrictEqual(QUESTION.classId); }); test('New type should be used if set', () => { const newType = QUESTION.typeId + 1; const copy = QUESTION.shallowCopy({ type: newType }); expect(copy.name).toStrictEqual(QUESTION.name); expect(copy.typeId).toStrictEqual(newType); expect(copy.classId).toStrictEqual(QUESTION.classId); }); test('New class should be used if set', () => { const newClass = QUESTION.classId + 1; const copy = QUESTION.shallowCopy({ class: newClass }); expect(copy.name).toStrictEqual(QUESTION.name); expect(copy.typeId).toStrictEqual(QUESTION.typeId); expect(copy.classId).toStrictEqual(newClass); }); });
@import 'zenponsive-mixins'; /** * Zenponsive – Responsive CSS Grid - Flexbox * @author Malte Müller (acrylian) <info@maltem.de> * @copyright 2016 Malte Müller * @license GPL v3 or later * @version: 1.4.1 */ @import 'zenponsive-base'; /* Main flex wrapper: * @source: https://css-tricks.com/using-flexbox/ -----------------------------------*/ @include main_flexwrapper('flex'); /* The columns without gutter * (12 col grid and 5th) -----------------------------------*/ /* Grid items in case you don't want to use the cols */ @include general_flexboxitem('flex'); @include grid12('', 'flex'); @include grid5('', 'flex'); /* Columns with gutter 2% -----------------------------------*/ @include grid12_gutter(2, '', 'flex'); @include grid5_gutter(2, '', 'flex'); /* Columns with gutter 4% -----------------------------------*/ @include grid12_gutter(4, '', 'flex'); @include grid5_gutter(4, '', 'flex'); /* Responsive breakpoints -----------------------------------*/ /* Bigger desktop */ @media only screen and (max-width: 1280px) { /* No gutter */ @include grid12($break1, 'flex'); @include grid5($break1, 'flex'); /* 2% gutter */ @include grid12_gutter(2, $break1, 'flex'); @include grid5_gutter(2, $break1, 'flex'); /* 4% gutter */ @include grid12_gutter(4, $break1, 'flex'); @include grid5_gutter(4, $break1, 'flex'); /* show hide */ @include show_hide(1280); } /* "Standard" desktop */ @media only screen and (max-width: 960px) { /* No gutter */ @include grid12($break2, 'flex'); @include grid5($break2, 'flex'); /* 2% gutter */ @include grid12_gutter(2, $break2, 'flex'); @include grid5_gutter(2, $break2, 'flex'); /* 4% gutter */ @include grid12_gutter(4, $break2, 'flex'); @include grid5_gutter(4, $break2, 'flex'); /* show hide */ @include show_hide(959); } /* Tablet */ @media only screen and (max-width: 767px) { /* No gutter */ @include grid12($break3, 'flex'); @include grid5($break3, 'flex'); /* 2% gutter */ @include grid12_gutter(2, $break3, 'flex'); @include grid5_gutter(2, $break3, 'flex'); /* 4% gutter */ @include grid12_gutter(4, $break3, 'flex'); @include grid5_gutter(4, $break3, 'flex'); /* show hide */ @include show_hide(767); } /* Mobile */ @media only screen and (max-width: 479px) { /* Full for all incl. gutter items */ .#{$prefix}flex > *[class^='#{$prefix}col'], .#{$prefix}flex.#{$prefix}gutter2 > *[class^='#{$prefix}col'], .#{$prefix}flex.#{$prefix}gutter4 > *[class^='#{$prefix}col'] { -webkit-box-flex: 0 1 100% !important; -moz-box-flex: 0 1 100% !important; -webkit-flex: 0 1 100% !important; -ms-flex: 0 1 100% !important; flex: 0 1 100% !important; width: 100% !important; } /* No gutter */ @include grid12($break4, 'flex'); @include grid5($break4, 'flex'); /* 2% gutter */ @include grid12_gutter(2, $break4, 'flex'); @include grid5_gutter(2, $break4, 'flex'); /* 4% gutter */ @include grid12_gutter(4, $break4, 'flex'); @include grid5_gutter(4, $break4, 'flex'); /* show hide */ @include show_hide(479); }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mmarinel <mmarinel@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/09/27 16:59:30 by mmarinel #+# #+# */ /* Updated: 2022/10/09 17:51:00 by mmarinel ### ########.fr */ /* */ /* ************************************************************************** */ # include "templates.hpp" # include "Awesome.hpp" # include "../colors.hpp" # include <iostream> # include <string> int main ( void ) { { int a = 2; int b = 3; ::swap( a, b ); std::cout << "a = " << a << ", b = " << b << std::endl; std::cout << "min( a, b ) = " << ::min( a, b ) << std::endl; std::cout << "max( a, b ) = " << ::max( a, b ) << std::endl; //*...........................................................*// std::string c = "chaine1"; std::string d = "chaine2"; ::swap(c, d); std::cout << "c = " << c << ", d = " << d << std::endl; std::cout << "min( c, d ) = " << ::min( c, d ) << std::endl; std::cout << "max( c, d ) = " << ::max( c, d ) << std::endl; std::cout << std::endl; } { std::cout << YELLOW << " testing complex types" << RESET << std::endl; Awesome a(2), b(4); swap(a, b); std::cout << "Awesome a = " << a << ", Awesome b = " << b << std::endl; std::cout << "max( a, b ) = " << max(a, b) << std::endl; std::cout << "min( a, b ) = " << min(a, b) << std::endl; std::cout << std::endl; } return 0; }
// 혼자 해결하지 못해서 검색함 var mergeSort = function (array) { if (array.length < 2) { return array; } const mid = Math.floor(array.length / 2); const left = array.slice(0, mid); const right = array.slice(mid); return merge(mergeSort(left), mergeSort(right)); function merge(left, right) { const resultArray = []; let leftIndex = 0; let rightIndex = 0; while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { resultArray.push(left[leftIndex]); leftIndex++; } else { resultArray.push(right[rightIndex]); rightIndex++; } } return resultArray.concat(left.slice(leftIndex), right.slice(rightIndex)); } };
// ignore_for_file: unnecessary_import, library_private_types_in_public_api, library_prefixes, use_super_parameters import 'package:finance_app/controllers/db_helper.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:finance_app/static.dart' as Static; import 'package:flutter/services.dart'; class AddSavingNoGradient extends StatefulWidget { const AddSavingNoGradient({Key? key}) : super(key: key); @override _AddSavingNoGradientState createState() => _AddSavingNoGradientState(); } class _AddSavingNoGradientState extends State<AddSavingNoGradient> { int? amount; String note = "Expence"; int? goalAmount; List<String> months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( toolbarHeight: 0.0, ), backgroundColor: const Color(0xffe2e7ef), // body: ListView( padding: const EdgeInsets.all( 12.0, ), children: [ const Text( "\nAñadir ahorro", textAlign: TextAlign.center, style: TextStyle( fontSize: 32.0, fontWeight: FontWeight.w700, ), ), // const SizedBox( height: 20.0, ), // Row( children: [ Container( decoration: BoxDecoration( color: Static.PrimaryColor, borderRadius: BorderRadius.circular( 16.0, ), ), padding: const EdgeInsets.all( 12.0, ), child: const Icon( Icons.attach_money, size: 24.0, // color: Colors.grey[700], color: Colors.white, ), ), const SizedBox( width: 12.0, ), Expanded( child: TextField( decoration: const InputDecoration( hintText: "0", border: InputBorder.none, ), style: const TextStyle( fontSize: 24.0, ), onChanged: (val) { try { amount = int.parse(val); } catch (e) { // show Error ScaffoldMessenger.of(context).showSnackBar( const SnackBar( backgroundColor: Colors.red, duration: Duration( seconds: 2, ), content: Row( children: [ Icon( Icons.info_outline, color: Colors.white, ), SizedBox( width: 6.0, ), Text( "Introduzca sólo números como importe", style: TextStyle( fontSize: 16.0, ), ), ], ), ), ); } }, inputFormatters: [ FilteringTextInputFormatter.digitsOnly, ], keyboardType: TextInputType.number, // textAlign: TextAlign.center, ), ), ], ), // const SizedBox( height: 20.0, ), // Row( children: [ Container( decoration: BoxDecoration( color: Static.PrimaryColor, borderRadius: BorderRadius.circular( 16.0, ), ), padding: const EdgeInsets.all( 12.0, ), child: const Icon( Icons.description, size: 24.0, // color: Colors.grey[700], color: Colors.white, ), ), const SizedBox( width: 12.0, ), Expanded( child: TextField( decoration: const InputDecoration( hintText: "Nota sobre el ahorro", border: InputBorder.none, ), style: const TextStyle( fontSize: 20.0, ), onChanged: (val) { note = val; }, ), ), ], ), // const SizedBox( height: 20.0, ), // Row( children: [ Container( decoration: BoxDecoration( color: Static.PrimaryColor, borderRadius: BorderRadius.circular( 16.0, ), ), padding: const EdgeInsets.all( 12.0, ), child: const Icon( Icons.attach_money, size: 24.0, // color: Colors.grey[700], color: Colors.white, ), ), const SizedBox( width: 12.0, ), Expanded( child: TextField( decoration: const InputDecoration( hintText: "0", border: InputBorder.none, ), style: const TextStyle( fontSize: 24.0, ), onChanged: (val) { try { goalAmount = int.parse(val); } catch (e) { // show Error ScaffoldMessenger.of(context).showSnackBar( const SnackBar( backgroundColor: Colors.red, duration: Duration( seconds: 2, ), content: Row( children: [ Icon( Icons.info_outline, color: Colors.white, ), SizedBox( width: 6.0, ), Text( "Introduzca sólo números como meta", style: TextStyle( fontSize: 16.0, ), ), ], ), ), ); } }, inputFormatters: [ FilteringTextInputFormatter.digitsOnly, ], keyboardType: TextInputType.number, // textAlign: TextAlign.center, ), ), ], ), // const SizedBox( height: 20.0, ), // SizedBox( height: 50.0, child: ElevatedButton( onPressed: () { if (amount != null || goalAmount != null) { DbHelper dbHelper = DbHelper(); dbHelper.addSaving(amount!, note, goalAmount!); Navigator.of(context).pop(); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: Colors.red[700], content: const Text( "Introduzca un importe o meta válida.", style: TextStyle( fontSize: 16.0, color: Colors.white, ), ), ), ); } }, child: const Text( "Añadir", style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.w600, ), ), ), ), ], ), ); } }
/* eslint-disable @typescript-eslint/no-empty-function */ "use client"; import React, { useState, createContext, Fragment } from "react"; import { Transition } from "@headlessui/react"; import { CheckCircleIcon, XMarkIcon } from "@heroicons/react/24/outline"; interface ToastContextType { showToast: (success: boolean, title: string, subtitle?: string) => void; } export const ToastContext = createContext<ToastContextType>({ showToast: () => {}, }); export const ToastProvider = ({ children }: { children: any }) => { const [showToastState, setShowToastState] = useState(false); const [toastSuccess, setToastSuccess] = useState(true); const [toastTitle, setToastTitle] = useState(""); const [toastSubtitle, setToastSubtitle] = useState(""); const showToast = (success: boolean, title: string, subtitle = "") => { setToastTitle(title); setToastSubtitle(subtitle); if (success) { setToastSuccess(true); } else { setToastSuccess(false); } setShowToastState(true); setTimeout(() => { setShowToastState(false); // count is 0 here }, 3000); }; return ( <ToastContext.Provider value={{ showToast }}> {children} <div className="fixed right-2 top-10 flex w-64 flex-shrink-0" style={{ zIndex: 1000 }} // Needed to be able to show toast over modal > <Transition show={showToastState} as={Fragment} enter="transform ease-out duration-300 transition" enterFrom="translate-y-2 opacity-0 sm:translate-y-0 sm:translate-x-2" enterTo="translate-y-0 opacity-100 sm:translate-x-0" leave="transition ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="pointer-events-auto w-full max-w-sm overflow-hidden rounded-lg bg-white shadow-lg ring-1 ring-black ring-opacity-5"> <div className="p-4"> <div className="flex items-start"> <div className="flex-shrink-0"> {toastSuccess ? ( <CheckCircleIcon className="h-6 w-6 text-green-400" aria-hidden="true" /> ) : ( <XMarkIcon className="h-6 w-6 text-red-400" aria-hidden="true" /> )} </div> <div className="ml-3 w-0 flex-1 pt-0.5"> <p className="text-sm font-medium text-gray-900"> {toastTitle} </p> <p className="mt-1 text-sm text-gray-500">{toastSubtitle}</p> </div> <div className="ml-4 flex flex-shrink-0"> <button type="button" className="inline-flex rounded-md bg-white text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2" onClick={() => { setShowToastState(false); }} > <span className="sr-only">Close</span> <XMarkIcon className="h-5 w-5" aria-hidden="true" /> </button> </div> </div> </div> </div> </Transition> </div> </ToastContext.Provider> ); };
var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); const mongoose = require("mongoose"); const authRoutes = require ('./routes/authRoutes') var indexRouter = require('./index'); const stadiumsRoute = require('./routes/stadiums'); const { checkUser, requireAuth } = require('./middleware/authMiddleware'); //enviroment variables require('dotenv').config() var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); //database connection setup // Import the mongoose module // Mongo DB Connection mongoose.connect(process.env.DB_URI, { dbName: process.env.DB_NAME, user: process.env.DB_USER, pass: process.env.DB_PASS, useNewUrlParser: true, useUnifiedTopology: true }) .then( (res) => console.log('db connected')) .catch((err) => console.log(err)); // Get the default connection const db = mongoose.connection; // Bind connection to error event (to get notification of connection errors) db.on("error", console.error.bind(console, "MongoDB connection error:")); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); //ROUTES app.get('*', checkUser) app.use(indexRouter); app.use(authRoutes); app.use(stadiumsRoute); // app.use(tablesRoute) // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
// // AmmoListView.swift // WeaponsStore // // Created by Evgeniy Lemish on 25.10.2022. // import SwiftUI struct AmmoListView: View { @State private var selectedAmmoIndex = 0 @State private var isPresented = false var body: some View { NavigationView{ ZStack{ Color(.black) //.edgesIgnoringSafeArea(.bottom) .navigationTitle("Bullets") .navigationBarTitleDisplayMode(.inline) .navigationBarItems(trailing: Button(action: { self.isPresented.toggle() }, label:{ Text("Help") } )) .sheet(isPresented: $isPresented, content: { ExtraHelpView() }) VStack{ Spacer() Text ("Scroll in right Bullets to see more".uppercased()) .foregroundColor(.white) .fontWeight(.heavy) .shadow(color: .white, radius: 15) .position(x: 200, y: 100) ScrollView(.horizontal, showsIndicators: false){ HStack(spacing: 10) { ForEach(Ammo.ammoDemo) { ammo in GeometryReader{ proxy in NavigationLink(destination: AmmoDetailsView(ammo: ammo)) { VStack{ Image(ammo.imageBullet) .resizable() .shadow(color: .red, radius: 15) Text(ammo.title) .fontWeight(.heavy) .foregroundColor(.black) .shadow(color: .white, radius: 15) .multilineTextAlignment(.center) } } /* .background(Image(ammo.imageBullet) .resizable() .scaledToFill() .overlay(Color.yellow) .blendMode(.multiply) .blur(radius: 1)) */ .background(Color.yellow) .cornerRadius(25) .frame(width: max(proxy.size.width - proxy.frame(in: .global).midX, proxy.size.width), height: proxy.size.height-50) .padding() .shadow(color: .yellow, radius: 15) .rotation3DEffect(Angle(degrees: Double(proxy.frame(in: .global).midX)/20), axis: (x: -3, y: -4, z: -3)) } .padding(30) .padding(.top, 30) } .position(x: 180, y: 250) .frame(width: 350, height: 400) .padding(.bottom, 250) } } } } } } } struct AmmoListView_Previews: PreviewProvider { static var previews: some View { AmmoListView() } }
import { createPolygon, createPolygonEx } from "../../../common/createPolygon"; export class GameScene extends Phaser.Scene { mainGameObject: any; wheelRight: any; wheelLeft: any; forceMajor = new Phaser.Math.Vector2(0.027, 0); forceMinor = new Phaser.Math.Vector2(0.01, 0); text: Phaser.GameObjects.Text; text2: Phaser.GameObjects.Text; initialTime: number = 0; runNumber: number = 1; lastSetText: number = 0; maxX: number = 0; angularVelocity: number = 0; constructor() { super({ key: "GameScene" }); } private createGroundPoly(points: string, x: number, y: number) { var ground: any = this.add.polygon(0, 0, points, 0x00aa00); var p: any = this.matter.add.gameObject( ground, { shape: { type: 'fromVerts', verts: points, flagInternal: true }, isStatic: true, } ); p.setPosition( x + p.centerOfMass.x, y + p.centerOfMass.y - (p.getBottomLeft().y - p.getTopLeft().y) ); } create(): void { var width: any = this.game.config.width; var height: any = this.game.config.height; this.matter.world.setGravity(0, 1); // this.matter.world.setBounds(0, 0, width, height); this.add.grid( -10, 10, 100000, 100000, 1000, 1000, 0x000000, 0, 0x00ff00, 1, ); var fontSize = 32; this.text = this.add.text(0, 0, "", { fontSize: 32 + 'px', color: 'gray', strokeThickness: 1, }, ); this.text2 = this.add.text(0, 0, "", { fontSize: 32 + 'px', color: 'gray', strokeThickness: 1, }, ); var i: number = 0; var j: number = 0; while (j < 7) { this.createGroundPoly('0 100 1000 100 1000 0 0 0', i++ * 1000, 0 ); ++j; } this.createGroundPoly('0 150 1000 150 1000 0 0 50', i++ * 1000, 0 ); this.createGroundPoly('0 250 1000 250 1000 0 0 100', i++ * 1000, 0 ); this.createGroundPoly('0 400 1000 400 1000 0 0 150', i++ * 1000, 0 ); this.createGroundPoly('0 600 1000 600 1000 0 0 200', i++ * 1000, 0 ); i++; i++; i++; var shift = 180 this.createGroundPoly('0 600 1000 600 1000 200 0 0', i++ * 1000 + shift, 0 ); this.createGroundPoly('0 400 1000 400 1000 150 0 0', i++ * 1000 + shift, 0 ); this.createGroundPoly('0 250 1000 250 1000 100 0 0', i++ * 1000 + shift, 0 ); this.createGroundPoly('0 150 1000 150 1000 50 0 0', i++ * 1000 + shift, 0 ); var j: number = 0; while (j < 7) { this.createGroundPoly('0 100 1000 100 1000 0 0 0', i++ * 1000 + shift, 0 ); ++j; } const density = 0.001 const friction = 0.9 var x: number = 100; var y: number = -500; const wheelSize: number = 20; const wheelAOffset = 140; const wheelBOffset = -110; const wheelYOffset = 10; // let group = this.matter.world.nextGroup(true); var points: string = "" + "0 0" + " " + "0 50" + " " + "200 50" + " " + "200 30" + " " + "50 15" + " " + "20 0" ; this.mainGameObject = createPolygonEx( this, points, x, y, 0x009900, false, { shape: { type: 'fromVerts', verts: points, flagInternal: true }, isStatic: false, friction, density, } ); var circleA = this.add.circle(x + wheelAOffset, y + wheelYOffset, wheelSize, 0x009900); var circleB = this.add.circle(x + wheelBOffset, y + wheelYOffset, wheelSize, 0x009900); this.wheelRight = this.matter.add.gameObject( circleA, { shape: { type: 'circle', radius: wheelSize, flagInternal: true }, friction, density, } ); this.wheelLeft = this.matter.add.gameObject( circleB, { shape: { type: 'circle', radius: wheelSize, flagInternal: true }, friction, density, } ); let axelA = this.matter.add.constraint( this.mainGameObject.body, this.wheelRight.body, 0, 0.2, { pointA: { x: wheelAOffset, y: wheelYOffset } }) let axelB = this.matter.add.constraint( this.mainGameObject.body, this.wheelLeft.body, 0, 0.2, { pointA: { x: wheelBOffset, y: wheelYOffset } }) this.input.on('pointerdown', function (pointer) { var position = new Phaser.Math.Vector2( this.mainGameObject.x - 100, this.mainGameObject.y + 10 ); var force = new Phaser.Math.Vector2(1, 0); this.mainGameObject.applyForceFrom(position, force); }, this); } private vDigit(d: number): string { var result: string = ""; var roundedValue: number = Number(((d / 1000) * 1000).toFixed(0)); if (roundedValue > 0) { result += "+"; } result += roundedValue; return result; } private formatVector(vX: number, vY: number): string { return "<" + this.vDigit(vX) + "," + this.vDigit(-vY) + ">"; } update(time: number, delta: number): void { var t: number = Number( ((time - this.initialTime) / 1000) .toFixed(1) ); this.text.x = this.wheelLeft.x - 220; this.text.y = this.wheelLeft.y - 200; this.text2.x = this.wheelLeft.x; this.text2.y = this.wheelLeft.y - 200; if (time - this.lastSetText > 250) { this.lastSetText = time; this.text.setText("" + "run#" + this.runNumber + " " + "t=" + t.toFixed(0) + "\n" + "v=" + this.formatVector( this.mainGameObject.body.velocity.x, this.mainGameObject.body.velocity.y, ) ); if (this.mainGameObject.body.velocity.x > this.maxX) { this.maxX = this.mainGameObject.body.velocity.x; // console.log("maxX=" + this.maxX.toFixed(0)); } } this.cameras.main.centerOn( this.mainGameObject.x, this.mainGameObject.y ); this.cameras.main.setZoom(0.5); // warming up var t0 = 2; // warm var t1 = 4; // hot var t2 = 6; // thrust: min var t3 = 10; // thrust: MAX var t4 = 15; // thrust: min var t5 = 18; // cooling var t6 = 25; // stop if (t <= t0) { this.t0(); } else if (t > t0 && t <= t1) { this.t1(); } else if (t > t1 && t <= t2) { this.t2(); } else if (t > t2 && t <= t3) { this.t3(); } else if (t > t3 && t <= t4) { this.t4(); } else if (t > t4 && t <= t5) { this.t5(); } else if (t > t5 && t <= t6) { this.t6(); } else { this.initialTime = time; this.runNumber++; this.scene.restart(); } } private t0() { this.text2.setText("" + "engine: cold" + "\n" + "thrust: disengaged" ); } private t1() { this.text2.setText("" + "engine: warm" + "\n" + "thrust: disengaged" ); } private t2() { this.text2.setText("" + "engine: hot" + "\n" + "thrust: disengaged" ); } private t3() { this.thrustMin(); } private t4() { this.thrustMax(); } private t5() { this.thrustMin(); } private t6() { this.text2.setText("" + "engine: cooling" + "\n" + "thrust: disengaged" ); } private thrustMin() { this.text2.setText("" + "engine: hot" + "\n" + "thrust: ENGAGED: min" ); var position = new Phaser.Math.Vector2( this.mainGameObject.x - 100, this.mainGameObject.y + 5 ); this.mainGameObject.applyForceFrom(position, this.forceMinor); } private thrustMax() { this.text2.setText("" + "engine: hot" + "\n" + "thrust: ENGAGED: MAX" ); var position = new Phaser.Math.Vector2( this.mainGameObject.x - 100, this.mainGameObject.y + 5 ); this.mainGameObject.applyForceFrom(position, this.forceMajor); } }
// // CategoryRowView.swift // landmarks // // Created by Alejandro Sanabria on 20/02/23. // import SwiftUI struct CategoryRowView: View { var categoryName: String var items: [Landmark] var body: some View { VStack(alignment: .leading) { Text(categoryName) .font(.headline) .padding(.leading, 12) .padding(.top, 12) ScrollView(.horizontal, showsIndicators: false) { HStack(alignment: .top, spacing: 0) { ForEach(items) { item in NavigationLink { LandmarkDetailView(landmark: item) } label: { CategoryItemView(landmark: item) } } } } .frame(height: 190) } } } struct CategoryRowView_Previews: PreviewProvider { static var landmarks = LandmarkViewModel().landmarks static var previews: some View { CategoryRowView( categoryName: landmarks[0].category.rawValue, items: Array(landmarks.prefix(4))) } }
package com.scorealarm.meeting.rooms.rest import com.google.gson.GsonBuilder import com.scorealarm.meeting.rooms.Config import com.scorealarm.meeting.rooms.models.Meeting import com.scorealarm.meeting.rooms.models.MeetingRoom import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.joda.time.DateTime import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit object RestService { val gson = GsonBuilder() .registerTypeAdapter(DateTime::class.java, DateTimeAdapter()) .create() private val okHttpClient = OkHttpClient.Builder() .addInterceptor { val request = it.request() .newBuilder() .addHeader("authentication", Config.HEADER_AUTH) .build() it.proceed(request) } .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .build() private val api = Retrofit.Builder() .baseUrl(Config.BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .client(okHttpClient) .build() .create(MeetingRoomApi::class.java) fun getMeetingRoomList(): Observable<List<MeetingRoom>> = api.getMeetingRoomList().flatMap { Observable.fromArray(it.meetingRoomList) }.subscribeOn(Schedulers.io()) fun getMeetingListByRoom(meetingRoomId: String): Observable<List<Meeting>> = api.getMeetingsByRoom(meetingRoomId).flatMap { Observable.fromArray(it.meetingList) } .subscribeOn(Schedulers.io()) }
package com.pab.list_view_fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; // Kelas untuk Adapter RecyclerView public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private ArrayList<MyItem> itemList; private OnItemClickListener listener; public MyAdapter(ArrayList<MyItem> itemList, OnItemClickListener listener) { this.itemList = itemList; this.listener = listener; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { MyItem item = itemList.get(position); holder.bind(item); } @Override public int getItemCount() { return itemList.size(); } public interface OnItemClickListener { void onItemClick(MyItem item); } class ViewHolder extends RecyclerView.ViewHolder { private TextView titleTextView; ViewHolder(@NonNull View itemView) { super(itemView); titleTextView = itemView.findViewById(R.id.title_text_view); // Menangani klik item itemView.setOnClickListener(v -> { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION && listener != null) { listener.onItemClick(itemList.get(position)); } }); } void bind(final MyItem item) { titleTextView.setText(item.getTitle()); } } }
import React from "react"; import useVisibility from "../hooks/useVisibility"; import { useTranslation } from "react-i18next"; import styles from "../style"; import { instagram, //logo, logo03T, } from "../assets"; import { footerLinks, //socialMedia } from "../constants"; const Footer = () => { const [ref, isVisible] = useVisibility(); const { t } = useTranslation(); return ( <section ref={ref} className={`${styles.flexCenter} ${styles.paddingY} flex-col ${ isVisible ? "animate-endFadeIn" : "animate-fadeOut" }`} > <div className={`flex justify-center items-center md:flex-row flex-col mb-8 w-full`} > <div className="flex flex-1 flex-col justify-center items-center"> <img loading="lazy" src={logo03T} alt="Makerstar Logo" className="w-[266px] h-[72px] object-contain hidden md:block" /> <p className={`${styles.paragraph} text-center mt-0 xs:w-full w-[280px]`} > {t("footer_text.title")} </p> </div> {/* <div className="flex flex-[1.5] w-full flex-row justify-between flex-wrap md:mt-0 mt-10"> {footerLinks.map((footerLink) => ( <div key={footerLink.id} className="flex flex-col items-center ss:my-0 my-4 min-w-[150px]" > <h4 className="font=poppins font-medium text-[18px] leading-[27px] text-white"> {footerLink.title} </h4> <ul className="list-none mt-4"> {footerLink.links.map((link, index) => ( <li id={link.name} key={link.name} className={`font-poppins font-normal text-[16px] leading-[24px] text-dimWhite hover:text-makerGold hover:tracking-wide duration-200 cursor-pointer ${ index !== footerLink.links.length - 1 ? "mb-4" : "mb-0" }`} > <a href={`${link.link}`}>{link.name}</a> </li> ))} </ul> </div> ))} </div> */} </div> <div className={`w-full flex justify-between items-center md:flex-row flex-col pt-1 border-t-[1px] border-t-[#3F3E45] ${ isVisible ? "animate-endFadeUp" : "opacity-0" }`} > {/* <div className="flex flex-row md:mt-0 mt-6"> {socialMedia.map((social, index) => ( <img key={social.id} src={social.icon} alt={social.id} className={`w-[21px] h-[21px] object-contain cursor-pointer ${ index !== socialMedia.length - 1 ? "mr-6" : "mr-0" } `} /> ))} </div> */} <div className="flex flex-row w-full md:order-1 md:mt-0 mt-6"> {footerLinks.map((footerLink) => ( <div key={footerLink.id} className="w-full items-center justify-center" > <ul className="list-none flex flex-col md:flex-row justify-end items-center "> {footerLink.links.map((link, index) => ( <li id={link.name} key={link.name} className={`font-poppins font-normal text-[12px] leading-[24px] text-dimWhite text-center md:text-left hover:text-makerGold hover:tracking-wide duration-200 cursor-pointer ${ index !== footerLink.links.length - 1 ? "mb-4" : "mb-0" }`} > <a href={`${link.link}`}>{t(link.name)}</a> </li> ))} </ul> </div> ))} </div> <p className="font-poppins font-normal md:text-start text-center text-[12px] leading-[24px] text-dimWhite pt-1 w-full"> {t("footer_text.copyright_one")} &copy;{" "} {t("footer_text.copyright_two")} </p> </div> </section> ); }; export default Footer;
import { FC, memo } from 'react'; import Link from 'next/link'; interface HeaderProps { /** * Title to be displayed within the component. */ title: string; } /** * The Header component displays a page title within an `<h1>` element. * * Usage example: * ```tsx * <Header title="Page Title"/> * ``` * * @component * @param props - The component properties as defined in the `HeaderProps` interface. */ const Header: FC<HeaderProps> = memo(({ title }) => ( <header className='bg-gradient-to-r from-cyan-500 to-blue-500 shadow-md'> <div className='container'> <h1 className='text-white font-bold text-xl md:text-3xl'> <Link href='/'>{title}</Link> </h1> </div> </header> )); Header.displayName = 'Header'; export default Header;
#include <iostream> #include <stdexcept> int divide(int a, int b) { if (b == 0) { throw std::runtime_error("Division by zero!"); } return a / b; } int main() { int num1, num2; std::cout << "Enter two numbers for division: "; std::cin >> num1 >> num2; try { int result = divide(num1, num2); std::cout << "The result is: " << result << std::endl; } catch (const std::exception &e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; }
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "erc721a-upgradeable/contracts/ERC721AUpgradeable.sol"; // ========== Internal imports ========== import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; // ========== Features ========== import "../feature/ContractMetadata.sol"; import "../feature/PlatformFee.sol"; import "../feature/Royalty.sol"; import "../feature/PrimarySale.sol"; import "../feature/Ownable.sol"; import "../feature/DelayedReveal.sol"; import "../feature/LazyMint.sol"; import "../feature/PermissionsEnumerable.sol"; import "../feature/meta-tx/Drop.sol"; import "../feature/interface/ISignatureMintERC721.sol"; contract SignatureDrop is Initializable, ContractMetadata, PlatformFee, Royalty, PrimarySale, Ownable, DelayedReveal, LazyMint, PermissionsEnumerable, Drop, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, ERC721AUpgradeable { using StringsUpgradeable for uint256; State variables bytes32 private constant MODULE_TYPE = bytes32("SignatureDrop"); uint256 private constant VERSION = 1; /// @dev Only transfers to or from TRANSFER_ROLE holders are valid, when transfers are restricted. bytes32 private constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); /// @dev Only MINTER_ROLE holders can sign off on `MintRequest`s and lazy mint tokens. bytes32 private constant MINTER_ROLE = keccak256("MINTER_ROLE"); /// @dev Max bps in the thirdweb system. uint256 private constant MAX_BPS = 10_000; /// @dev The tokenId of the next NFT that will be minted / lazy minted. uint256 public nextTokenIdToMint; /// @dev The address of the contract with signature minting logic. address public sigMint; Events event TokensLazyMinted(uint256 startTokenId, uint256 endTokenId, string baseURI, bytes encryptedBaseURI); event TokenURIRevealed(uint256 index, string revealedURI); event TokensMintedWithSignature( address indexed signer, address indexed mintedTo, uint256 indexed tokenIdMinted, ISignatureMintERC721.MintRequest mintRequest ); Constructor + initializer logic /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _name, string memory _symbol, string memory _contractURI, address[] memory _trustedForwarders, address _saleRecipient, address _royaltyRecipient, uint128 _royaltyBps, uint128 _platformFeeBps, address _platformFeeRecipient, address _signatureMintLogic ) external initializer { // Initialize inherited contracts, most base-like -> most derived. __ReentrancyGuard_init(); __ERC2771Context_init(_trustedForwarders); __ERC721A_init(_name, _symbol); // Revoked at the end of the function. _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); // Initialize this contract's state. sigMint = _signatureMintLogic; setContractURI(_contractURI); setOwner(_defaultAdmin); _setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin); _setupRole(MINTER_ROLE, _defaultAdmin); _setupRole(TRANSFER_ROLE, _defaultAdmin); _setupRole(TRANSFER_ROLE, address(0)); setPlatformFeeInfo(_platformFeeRecipient, _platformFeeBps); setDefaultRoyaltyInfo(_royaltyRecipient, _royaltyBps); setPrimarySaleRecipient(_saleRecipient); _revokeRole(DEFAULT_ADMIN_ROLE, _msgSender()); } Generic contract logic /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { return MODULE_TYPE; } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { return uint8(VERSION); } ERC 165 / 721 / 2981 logic /// @dev Returns the URI for a given tokenId. function tokenURI(uint256 _tokenId) public view override returns (string memory) { uint256 batchId = getBatchId(_tokenId); string memory batchUri = getBaseURI(_tokenId); if (isEncryptedBatch(batchId)) { return string(abi.encodePacked(batchUri, "0")); } else { return string(abi.encodePacked(batchUri, _tokenId.toString())); } } /// @dev See ERC 165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721AUpgradeable) returns (bool) { return super.supportsInterface(interfaceId) || type(IERC2981Upgradeable).interfaceId == interfaceId; } Lazy minting + delayed-reveal logic /** * @dev Lets an account with `MINTER_ROLE` lazy mint 'n' NFTs. * The URIs for each token is the provided `_baseURIForTokens` + `{tokenId}`. */ function lazyMint( uint256 _amount, string calldata _baseURIForTokens, bytes calldata _encryptedBaseURI ) external onlyRole(MINTER_ROLE) returns (uint256 batchId) { uint256 startId = nextTokenIdToMint; (nextTokenIdToMint, batchId) = _batchMint(startId, _amount, _baseURIForTokens); if (_encryptedBaseURI.length != 0) { _setEncryptedBaseURI(batchId, _encryptedBaseURI); } emit TokensLazyMinted(startId, startId + _amount, _baseURIForTokens, _encryptedBaseURI); } /// @dev Lets an account with `MINTER_ROLE` reveal the URI for a batch of 'delayed-reveal' NFTs. function reveal(uint256 _index, bytes calldata _key) external onlyRole(MINTER_ROLE) returns (string memory revealedURI) { uint256 batchId = getBatchIdAtIndex(_index); revealedURI = getRevealURI(batchId, _key); _setBaseURI(batchId, revealedURI); emit TokenURIRevealed(_index, revealedURI); } Claiming lazy minted tokens logic /// @dev Claim lazy minted tokens via signature. function mintWithSignature(ISignatureMintERC721.MintRequest calldata _req, bytes calldata _signature) external payable nonReentrant returns (address signer) { signer = ISignatureMintERC721(sigMint).mintWithSignature(_req, _signature); uint256 tokenIdToMint = _currentIndex; require(tokenIdToMint + _req.quantity <= nextTokenIdToMint, "not enough minted tokens."); // Get receiver of tokens. address receiver = _req.to == address(0) ? msg.sender : _req.to; // Collect price collectPriceOnClaim(_req.quantity, _req.currency, _req.pricePerToken); // Mint tokens. _mint(receiver, _req.quantity); emit TokensMintedWithSignature(signer, receiver, tokenIdToMint, _req); } /// @dev Lets an account claim tokens. function claim( address _receiver, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof, bytes memory _data ) public payable override nonReentrant { super.claim(_receiver, _quantity, _currency, _pricePerToken, _allowlistProof, _data); } /// @dev Verifies that a mint request is signed by an account holding MINTER_ROLE (at the time of the function call). function verify(ISignatureMintERC721.MintRequest calldata _req, bytes calldata _signature) external view returns (bool success, address signer) { return ISignatureMintERC721(sigMint).verify(_req, _signature); } Internal functions /// @dev Runs before every `claim` function call. function _beforeClaim( address, uint256 _quantity, address, uint256, AllowlistProof calldata, bytes memory ) internal view override { require(_currentIndex + _quantity <= nextTokenIdToMint, "not enough minted tokens."); } /// @dev Collects and distributes the primary sale value of NFTs being claimed. function collectPriceOnClaim( uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal override { if (_pricePerToken == 0) { return; } (address platformFeeRecipient, uint16 platformFeeBps) = getPlatformFeeInfo(); uint256 totalPrice = _quantityToClaim * _pricePerToken; uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { require(msg.value == totalPrice, "must send total price."); } CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees); CurrencyTransferLib.transferCurrency( _currency, _msgSender(), primarySaleRecipient(), totalPrice - platformFees ); } /// @dev Transfers the NFTs being claimed. function transferTokensOnClaim(address _to, uint256 _quantityBeingClaimed) internal override returns (uint256 startTokenId) { startTokenId = _currentIndex; _mint(_to, _quantityBeingClaimed); } /// @dev Returns whether platform fee info can be set in the given execution context. function _canSetPlatformFeeInfo() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /// @dev Returns whether primary sale recipient can be set in the given execution context. function _canSetPrimarySaleRecipient() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /// @dev Returns whether owner can be set in the given execution context. function _canSetOwner() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /// @dev Returns whether royalty info can be set in the given execution context. function _canSetRoyaltyInfo() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /// @dev Returns whether contract metadata can be set in the given execution context. function _canSetContractURI() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } Miscellaneous /// @dev Burns `tokenId`. See {ERC721-_burn}. function burn(uint256 tokenId) public virtual { address ownerOfToken = ownerOf(tokenId); //solhint-disable-next-line max-line-length require( _msgSender() == ownerOfToken || isApprovedForAll(ownerOfToken, _msgSender()) || getApproved(tokenId) == _msgSender(), "caller not owner nor approved" ); _burn(tokenId); } /// @dev See {ERC721-_beforeTokenTransfer}. function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual override { super._beforeTokenTransfers(from, to, startTokenId, quantity); // if transfer is restricted on the contract, we still want to allow burning and minting if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "!TRANSFER_ROLE"); } } function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable, ExecutionContext) returns (address sender) { return ERC2771ContextUpgradeable._msgSender(); } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable, ExecutionContext) returns (bytes calldata) { return ERC2771ContextUpgradeable._msgData(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Multicall.sol) pragma solidity ^0.8.0; import "./AddressUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Provides a function to batch together multiple calls in a single external call. * * _Available since v4.1._ */ abstract contract MulticallUpgradeable is Initializable { function __Multicall_init() internal onlyInitializing { } function __Multicall_init_unchained() internal onlyInitializing { } /** * @dev Receives and executes a batch of function calls on this contract. */ function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = _functionDelegateCall(address(this), data[i]); } return results; } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981Upgradeable is IERC165Upgradeable { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // ERC721A Contracts v3.3.0 // Creator: Chiru Labs pragma solidity ^0.8.4; import "./IERC721AUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721AUpgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721AUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721A_init_unchained(name_, symbol_); } function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721AUpgradeable.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner) if(!isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract()) if(!_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement * {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex < end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint(address to, uint256 quantity) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Equivalent to `_burn(tokenId, false)`. */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[42] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (metatx/ERC2771Context.sol) pragma solidity ^0.8.11; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @dev Context variant with ERC2771 support. */ abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable { mapping(address => bool) private _trustedForwarder; function __ERC2771Context_init(address[] memory trustedForwarder) internal onlyInitializing { __Context_init_unchained(); __ERC2771Context_init_unchained(trustedForwarder); } function __ERC2771Context_init_unchained(address[] memory trustedForwarder) internal onlyInitializing { for (uint256 i = 0; i < trustedForwarder.length; i++) { _trustedForwarder[trustedForwarder[i]] = true; } } function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return _trustedForwarder[forwarder]; } function _msgSender() internal view virtual override returns (address sender) { if (isTrustedForwarder(msg.sender)) { // The assembly code is more direct than the Solidity version using `abi.decode`. assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return super._msgSender(); } } function _msgData() internal view virtual override returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; } else { return super._msgData(); } } uint256[49] private __gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // Helper interfaces import { IWETH } from "../interfaces/IWETH.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; library CurrencyTransferLib { using SafeERC20Upgradeable for IERC20Upgradeable; /// @dev The address interpreted as native token of the chain. address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Transfers a given amount of currency. function transferCurrency( address _currency, address _from, address _to, uint256 _amount ) internal { if (_amount == 0) { return; } if (_currency == NATIVE_TOKEN) { safeTransferNativeToken(_to, _amount); } else { safeTransferERC20(_currency, _from, _to, _amount); } } /// @dev Transfers a given amount of currency. (With native token wrapping) function transferCurrencyWithWrapper( address _currency, address _from, address _to, uint256 _amount, address _nativeTokenWrapper ) internal { if (_amount == 0) { return; } if (_currency == NATIVE_TOKEN) { if (_from == address(this)) { // withdraw from weth then transfer withdrawn native token to recipient IWETH(_nativeTokenWrapper).withdraw(_amount); safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper); } else if (_to == address(this)) { // store native currency in weth require(_amount == msg.value, "msg.value != amount"); IWETH(_nativeTokenWrapper).deposit{ value: _amount }(); } else { safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper); } } else { safeTransferERC20(_currency, _from, _to, _amount); } } /// @dev Transfer `amount` of ERC20 token from `from` to `to`. function safeTransferERC20( address _currency, address _from, address _to, uint256 _amount ) internal { if (_from == _to) { return; } if (_from == address(this)) { IERC20Upgradeable(_currency).safeTransfer(_to, _amount); } else { IERC20Upgradeable(_currency).safeTransferFrom(_from, _to, _amount); } } /// @dev Transfers `amount` of native token to `to`. function safeTransferNativeToken(address to, uint256 value) internal { // solhint-disable avoid-low-level-calls // slither-disable-next-line low-level-calls (bool success, ) = to.call{ value: value }(""); require(success, "native token transfer failed"); } /// @dev Transfers `amount` of native token to `to`. (With native token wrapping) function safeTransferNativeTokenWithWrapper( address to, uint256 value, address _nativeTokenWrapper ) internal { // solhint-disable avoid-low-level-calls // slither-disable-next-line low-level-calls (bool success, ) = to.call{ value: value }(""); if (!success) { IWETH(_nativeTokenWrapper).deposit{ value: value }(); IERC20Upgradeable(_nativeTokenWrapper).safeTransfer(to, value); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interface/IContractMetadata.sol"; abstract contract ContractMetadata is IContractMetadata { /// @dev Contract level metadata. string public override contractURI; /// @dev Lets a contract admin set the URI for contract-level metadata. function setContractURI(string memory _uri) public override { require(_canSetContractURI(), "Not authorized"); string memory prevURI = contractURI; contractURI = _uri; emit ContractURIUpdated(prevURI, _uri); } /// @dev Returns whether contract metadata can be set in the given execution context. function _canSetContractURI() internal virtual returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interface/IPlatformFee.sol"; abstract contract PlatformFee is IPlatformFee { /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The % of primary sales collected as platform fees. uint16 private platformFeeBps; /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() public view override returns (address, uint16) { return (platformFeeRecipient, uint16(platformFeeBps)); } /// @dev Lets a contract admin update the platform fee recipient and bps function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) public override { require(_canSetPlatformFeeInfo(), "Not authorized"); require(_platformFeeBps <= 10_000, "Exceeds max bps"); platformFeeBps = uint16(_platformFeeBps); platformFeeRecipient = _platformFeeRecipient; emit PlatformFeeInfoUpdated(_platformFeeRecipient, _platformFeeBps); } /// @dev Returns whether platform fee info can be set in the given execution context. function _canSetPlatformFeeInfo() internal virtual returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interface/IRoyalty.sol"; abstract contract Royalty is IRoyalty { /// @dev The (default) address that receives all royalty value. address private royaltyRecipient; /// @dev The (default) % of a sale to take as royalty (in basis points). uint16 private royaltyBps; /// @dev Token ID => royalty recipient and bps for token mapping(uint256 => RoyaltyInfo) private royaltyInfoForToken; /// @dev Returns the royalty recipient and amount, given a tokenId and sale price. function royaltyInfo(uint256 tokenId, uint256 salePrice) external view virtual override returns (address receiver, uint256 royaltyAmount) { (address recipient, uint256 bps) = getRoyaltyInfoForToken(tokenId); receiver = recipient; royaltyAmount = (salePrice * bps) / 10_000; } /// @dev Returns the royalty recipient and bps for a particular token Id. function getRoyaltyInfoForToken(uint256 _tokenId) public view override returns (address, uint16) { RoyaltyInfo memory royaltyForToken = royaltyInfoForToken[_tokenId]; return royaltyForToken.recipient == address(0) ? (royaltyRecipient, uint16(royaltyBps)) : (royaltyForToken.recipient, uint16(royaltyForToken.bps)); } /// @dev Returns the default royalty recipient and bps. function getDefaultRoyaltyInfo() external view override returns (address, uint16) { return (royaltyRecipient, uint16(royaltyBps)); } /// @dev Lets a contract admin update the default royalty recipient and bps. function setDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps) public override { require(_canSetRoyaltyInfo(), "Not authorized"); require(_royaltyBps <= 10_000, "Exceeds max bps"); royaltyRecipient = _royaltyRecipient; royaltyBps = uint16(_royaltyBps); emit DefaultRoyalty(_royaltyRecipient, _royaltyBps); } /// @dev Lets a contract admin set the royalty recipient and bps for a particular token Id. function setRoyaltyInfoForToken( uint256 _tokenId, address _recipient, uint256 _bps ) external override { require(_canSetRoyaltyInfo(), "Not authorized"); require(_bps <= 10_000, "Exceeds max bps"); royaltyInfoForToken[_tokenId] = RoyaltyInfo({ recipient: _recipient, bps: _bps }); emit RoyaltyForToken(_tokenId, _recipient, _bps); } /// @dev Returns whether royalty info can be set in the given execution context. function _canSetRoyaltyInfo() internal virtual returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interface/IPrimarySale.sol"; abstract contract PrimarySale is IPrimarySale { /// @dev The address that receives all primary sales value. address private recipient; function primarySaleRecipient() public view override returns (address) { return recipient; } /// @dev Lets a contract admin set the recipient for all primary sales. function setPrimarySaleRecipient(address _saleRecipient) public override { require(_canSetPrimarySaleRecipient(), "Not authorized"); recipient = _saleRecipient; emit PrimarySaleRecipientUpdated(_saleRecipient); } /// @dev Returns whether primary sale recipient can be set in the given execution context. function _canSetPrimarySaleRecipient() internal virtual returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interface/IOwnable.sol"; abstract contract Ownable is IOwnable { /// @dev Owner of the contract (purpose: OpenSea compatibility) address public override owner; /// @dev Lets a contract admin set a new owner for the contract. The new owner must be a contract admin. function setOwner(address _newOwner) public override { require(_canSetOwner(), "Not authorized"); address _prevOwner = owner; owner = _newOwner; emit OwnerUpdated(_prevOwner, _newOwner); } /// @dev Returns whether owner can be set in the given execution context. function _canSetOwner() internal virtual returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interface/IDelayedReveal.sol"; abstract contract DelayedReveal is IDelayedReveal { /// @dev Mapping from id of a batch of tokens => to encrypted base URI for the respective batch of tokens. mapping(uint256 => bytes) public encryptedBaseURI; /// @dev Sets the encrypted baseURI for a batch of tokenIds. function _setEncryptedBaseURI(uint256 _batchId, bytes memory _encryptedBaseURI) internal { encryptedBaseURI[_batchId] = _encryptedBaseURI; } /// @dev Returns the decrypted i.e. revealed URI for a batch of tokens. function getRevealURI(uint256 _batchId, bytes calldata _key) public returns (string memory revealedURI) { bytes memory encryptedURI = encryptedBaseURI[_batchId]; require(encryptedURI.length != 0, "nothing to reveal."); revealedURI = string(encryptDecrypt(encryptedURI, _key)); // yash - added this, and removed view mutability delete encryptedBaseURI[_batchId]; } /// @dev See: https://ethereum.stackexchange.com/questions/69825/decrypt-message-on-chain function encryptDecrypt(bytes memory data, bytes calldata key) public pure override returns (bytes memory result) { // Store data length on stack for later use uint256 length = data.length; // solhint-disable-next-line no-inline-assembly assembly { // Set result to free memory pointer result := mload(0x40) // Increase free memory pointer by lenght + 32 mstore(0x40, add(add(result, length), 32)) // Set result length mstore(result, length) } // Iterate over the data stepping by 32 bytes for (uint256 i = 0; i < length; i += 32) { // Generate hash of the key and offset bytes32 hash = keccak256(abi.encodePacked(key, i)); bytes32 chunk; // solhint-disable-next-line no-inline-assembly assembly { // Read 32-bytes data chunk chunk := mload(add(data, add(i, 32))) } // XOR the chunk with hash chunk ^= hash; // solhint-disable-next-line no-inline-assembly assembly { // Write 32-byte encrypted chunk mstore(add(result, add(i, 32)), chunk) } } } /// @dev Returns whether the relvant batch of NFTs is subject to a delayed reveal. function isEncryptedBatch(uint256 _batchId) public view returns (bool) { return encryptedBaseURI[_batchId].length > 0; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interface/ILazyMint.sol"; abstract contract LazyMint is ILazyMint { /// @dev Largest tokenId of each batch of tokens with the same baseURI. uint256[] private batchIds; /// @dev Mapping from id of a batch of tokens => to base URI for the respective batch of tokens. mapping(uint256 => string) private baseURI; /// @dev Returns the number of batches of tokens having the same baseURI. function getBaseURICount() public view returns (uint256) { return batchIds.length; } /// @dev Returns the id for the batch of tokens the given tokenId belongs to. function getBatchIdAtIndex(uint256 _index) public view returns (uint256) { require(_index < getBaseURICount(), "invalid index."); return batchIds[_index]; } /// @dev Returns the id for the batch of tokens the given tokenId belongs to. function getBatchId(uint256 _tokenId) internal view returns (uint256) { uint256 numOfTokenBatches = getBaseURICount(); uint256[] memory indices = batchIds; for (uint256 i = 0; i < numOfTokenBatches; i += 1) { if (_tokenId < indices[i]) { return indices[i]; } } revert("No batch id for token."); } /// @dev Returns the baseURI for a token. The intended metadata URI for the token is baseURI + tokenId. function getBaseURI(uint256 _tokenId) internal view returns (string memory) { uint256 numOfTokenBatches = getBaseURICount(); uint256[] memory indices = batchIds; for (uint256 i = 0; i < numOfTokenBatches; i += 1) { if (_tokenId < indices[i]) { return baseURI[indices[i]]; } } revert("No base URI for token."); } /// @dev Sets the base URI for the batch of tokens with the given batchId. function _setBaseURI(uint256 _batchId, string memory _baseURI) internal { baseURI[_batchId] = _baseURI; } /// @dev Mints a batch of tokenIds and associates a common baseURI to all those Ids. function _batchMint( uint256 _startId, uint256 _amountToMint, string calldata _baseURIForTokens ) internal returns (uint256 nextTokenIdToMint, uint256 batchId) { batchId = _startId + _amountToMint; nextTokenIdToMint = batchId; batchIds.push(batchId); baseURI[batchId] = _baseURIForTokens; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interface/IPermissionsEnumerable.sol"; import "./Permissions.sol"; contract PermissionsEnumerable is IPermissionsEnumerable, Permissions { struct RoleMembers { uint256 index; mapping(uint256 => address) members; mapping(address => uint256) indexOf; } mapping(bytes32 => RoleMembers) private roleMembers; function getRoleMember(bytes32 role, uint256 index) external view override returns (address member) { uint256 currentIndex = roleMembers[role].index; uint256 check; for (uint256 i = 0; i < currentIndex; i += 1) { if (roleMembers[role].members[i] != address(0)) { if (check == index) { member = roleMembers[role].members[i]; } } else { check += 1; } } } function getRoleMemberCount(bytes32 role) external view override returns (uint256 count) { uint256 currentIndex = roleMembers[role].index; for (uint256 i = 0; i < currentIndex; i += 1) { if (roleMembers[role].members[i] != address(0)) { count += 1; } } } function grantRole(bytes32 role, address account) public override(IPermissions, Permissions) { super.grantRole(role, account); _addMember(role, account); } function revokeRole(bytes32 role, address account) public override(IPermissions, Permissions) { super.revokeRole(role, account); _removeMember(role, account); } function renounceRole(bytes32 role, address account) public override(IPermissions, Permissions) { super.renounceRole(role, account); _removeMember(role, account); } function _setupRole(bytes32 role, address account) internal override { super._setupRole(role, account); _addMember(role, account); } function _addMember(bytes32 role, address account) internal { uint256 idx = roleMembers[role].index; roleMembers[role].index += 1; roleMembers[role].members[idx] = account; roleMembers[role].indexOf[account] = idx; } function _removeMember(bytes32 role, address account) internal { uint256 idx = roleMembers[role].indexOf[account]; delete roleMembers[role].members[idx]; delete roleMembers[role].indexOf[account]; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "../interface/IDrop.sol"; import "../../lib/MerkleProof.sol"; import "./ExecutionContext.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/BitMapsUpgradeable.sol"; abstract contract Drop is IDrop, ExecutionContext { using BitMapsUpgradeable for BitMapsUpgradeable.BitMap; State variables /// @dev The active conditions for claiming tokens. ClaimConditionList public claimCondition; Drop logic /// @dev Lets an account claim tokens. function claim( address _receiver, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof, bytes memory _data ) public payable virtual override { _beforeClaim(_receiver, _quantity, _currency, _pricePerToken, _allowlistProof, _data); // bytes32 activeConditionId = conditionId; uint256 activeConditionId = getActiveClaimConditionId(); /** * We make allowlist checks (i.e. verifyClaimMerkleProof) before verifying the claim's general * validity (i.e. verifyClaim) because we give precedence to the check of allow list quantity * restriction over the check of the general claim condition's quantityLimitPerTransaction * restriction. */ // Verify inclusion in allowlist. (bool validMerkleProof, uint256 merkleProofIndex) = verifyClaimMerkleProof( activeConditionId, _msgSender(), _quantity, _allowlistProof ); // Verify claim validity. If not valid, revert. bool toVerifyMaxQuantityPerTransaction = _allowlistProof.maxQuantityInAllowlist == 0; verifyClaim( activeConditionId, _msgSender(), _quantity, _currency, _pricePerToken, toVerifyMaxQuantityPerTransaction ); if (validMerkleProof && _allowlistProof.maxQuantityInAllowlist > 0) { /** * Mark the claimer's use of their position in the allowlist. A spot in an allowlist * can be used only once. */ // usedAllowlistSpot[activeConditionId].set(merkleProofIndex); claimCondition.usedAllowlistSpot[activeConditionId].set(merkleProofIndex); } // Update contract state. // claimCondition.supplyClaimed += _quantity; // lastClaimTimestamp[activeConditionId][_msgSender()] = block.timestamp; claimCondition.conditions[activeConditionId].supplyClaimed += _quantity; claimCondition.lastClaimTimestamp[activeConditionId][_msgSender()] = block.timestamp; // If there's a price, collect price. collectPriceOnClaim(_quantity, _currency, _pricePerToken); // Mint the relevant NFTs to claimer. uint256 startTokenId = transferTokensOnClaim(_receiver, _quantity); emit TokensClaimed(activeConditionId, _msgSender(), _receiver, startTokenId, _quantity); _afterClaim(_receiver, _quantity, _currency, _pricePerToken, _allowlistProof, _data); } /// @dev Lets a contract admin set claim conditions. function setClaimConditions( ClaimCondition[] calldata _conditions, bool _resetClaimEligibility, bytes memory ) external virtual override { uint256 existingStartIndex = claimCondition.currentStartId; uint256 existingPhaseCount = claimCondition.count; /** * `lastClaimTimestamp` and `usedAllowListSpot` are mappings that use a * claim condition's UID as a key. * * If `_resetClaimEligibility == true`, we assign completely new UIDs to the claim * conditions in `_conditions`, effectively resetting the restrictions on claims expressed * by `lastClaimTimestamp` and `usedAllowListSpot`. */ uint256 newStartIndex = existingStartIndex; if (_resetClaimEligibility) { newStartIndex = existingStartIndex + existingPhaseCount; } claimCondition.count = _conditions.length; claimCondition.currentStartId = newStartIndex; uint256 lastConditionStartTimestamp; for (uint256 i = 0; i < _conditions.length; i++) { require(i == 0 || lastConditionStartTimestamp < _conditions[i].startTimestamp, "ST"); uint256 supplyClaimedAlready = claimCondition.conditions[newStartIndex + i].supplyClaimed; require(supplyClaimedAlready <= _conditions[i].maxClaimableSupply, "max supply claimed already"); claimCondition.conditions[newStartIndex + i] = _conditions[i]; claimCondition.conditions[newStartIndex + i].supplyClaimed = supplyClaimedAlready; lastConditionStartTimestamp = _conditions[i].startTimestamp; } /** * Gas refunds (as much as possible) * * If `_resetClaimEligibility == true`, we assign completely new UIDs to the claim * conditions in `_conditions`. So, we delete claim conditions with UID < `newStartIndex`. * * If `_resetClaimEligibility == false`, and there are more existing claim conditions * than in `_conditions`, we delete the existing claim conditions that don't get replaced * by the conditions in `_conditions`. */ if (_resetClaimEligibility) { for (uint256 i = existingStartIndex; i < newStartIndex; i++) { delete claimCondition.conditions[i]; delete claimCondition.usedAllowlistSpot[i]; } } else { if (existingPhaseCount > _conditions.length) { for (uint256 i = _conditions.length; i < existingPhaseCount; i++) { delete claimCondition.conditions[newStartIndex + i]; delete claimCondition.usedAllowlistSpot[newStartIndex + i]; } } } emit ClaimConditionsUpdated(_conditions); } /// @dev Checks a request to claim NFTs against the active claim condition's criteria. function verifyClaim( uint256 _conditionId, address _claimer, uint256 _quantity, address _currency, uint256 _pricePerToken, bool verifyMaxQuantityPerTransaction ) public view { ClaimCondition memory currentClaimPhase = claimCondition.conditions[_conditionId]; require( _currency == currentClaimPhase.currency && _pricePerToken == currentClaimPhase.pricePerToken, "invalid currency or price." ); // If we're checking for an allowlist quantity restriction, ignore the general quantity restriction. require( _quantity > 0 && (!verifyMaxQuantityPerTransaction || _quantity <= currentClaimPhase.quantityLimitPerTransaction), "invalid quantity." ); require( currentClaimPhase.supplyClaimed + _quantity <= currentClaimPhase.maxClaimableSupply, "exceed max claimable supply." ); // uint256 timestampOfLastClaim = lastClaimTimestamp[conditionId][_claimer]; // uint256 timestampOfLastClaim = claimCondition.lastClaimTimestamp[_conditionId][_claimer]; // require( // timestampOfLastClaim == 0 || // block.timestamp >= timestampOfLastClaim + currentClaimPhase.waitTimeInSecondsBetweenClaims, // "cannot claim." // ); (uint256 lastClaimTimestamp, uint256 nextValidClaimTimestamp) = getClaimTimestamp(_conditionId, _claimer); require(lastClaimTimestamp == 0 || block.timestamp >= nextValidClaimTimestamp, "cannot claim."); } /// @dev Checks whether a claimer meets the claim condition's allowlist criteria. function verifyClaimMerkleProof( uint256 _conditionId, address _claimer, uint256 _quantity, AllowlistProof calldata _allowlistProof ) public view returns (bool validMerkleProof, uint256 merkleProofIndex) { ClaimCondition memory currentClaimPhase = claimCondition.conditions[_conditionId]; if (currentClaimPhase.merkleRoot != bytes32(0)) { (validMerkleProof, merkleProofIndex) = MerkleProof.verify( _allowlistProof.proof, currentClaimPhase.merkleRoot, keccak256(abi.encodePacked(_claimer, _allowlistProof.maxQuantityInAllowlist)) ); require(validMerkleProof, "not in whitelist."); // require(!usedAllowlistSpot[conditionId].get(merkleProofIndex), "proof claimed."); require(!claimCondition.usedAllowlistSpot[_conditionId].get(merkleProofIndex), "proof claimed."); require( _allowlistProof.maxQuantityInAllowlist == 0 || _quantity <= _allowlistProof.maxQuantityInAllowlist, "invalid quantity proof." ); } } /// @dev At any given moment, returns the uid for the active claim condition. function getActiveClaimConditionId() public view returns (uint256) { for (uint256 i = claimCondition.currentStartId + claimCondition.count; i > claimCondition.currentStartId; i--) { if (block.timestamp >= claimCondition.conditions[i - 1].startTimestamp) { return i - 1; } } revert("!CONDITION."); } /// @dev Returns the claim condition at the given uid. function getClaimConditionById(uint256 _conditionId) external view returns (ClaimCondition memory condition) { condition = claimCondition.conditions[_conditionId]; } /// @dev Returns the timestamp for when a claimer is eligible for claiming NFTs again. function getClaimTimestamp(uint256 _conditionId, address _claimer) public view returns (uint256 lastClaimTimestamp, uint256 nextValidClaimTimestamp) { lastClaimTimestamp = claimCondition.lastClaimTimestamp[_conditionId][_claimer]; unchecked { nextValidClaimTimestamp = lastClaimTimestamp + claimCondition.conditions[_conditionId].waitTimeInSecondsBetweenClaims; if (nextValidClaimTimestamp < lastClaimTimestamp) { nextValidClaimTimestamp = type(uint256).max; } } } Virtual functions: to be implemented in derived contract /// @dev Runs before every `claim` function call. function _beforeClaim( address _receiver, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof, bytes memory _data ) internal virtual {} /// @dev Runs after every `claim` function call. function _afterClaim( address _receiver, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof, bytes memory _data ) internal virtual {} /// @dev Collects and distributes the primary sale value of NFTs being claimed. function collectPriceOnClaim( uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal virtual; /// @dev Transfers the NFTs being claimed. function transferTokensOnClaim(address _to, uint256 _quantityBeingClaimed) internal virtual returns (uint256 startTokenId); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /** * The 'signature minting' mechanism used in thirdweb Token smart contracts is a way for a contract admin to authorize an external party's * request to mint tokens on the admin's contract. * * At a high level, this means you can authorize some external party to mint tokens on your contract, and specify what exactly will be * minted by that external party. */ interface ISignatureMintERC721 { /** * @notice The body of a request to mint tokens. * * @param to The receiver of the tokens to mint. * @param royaltyRecipient The recipient of the minted token's secondary sales royalties. (Not applicable for ERC20 tokens) * @param royaltyBps The percentage of the minted token's secondary sales to take as royalties. (Not applicable for ERC20 tokens) * @param primarySaleRecipient The recipient of the minted token's primary sales proceeds. * @param uri The metadata URI of the token to mint. (Not applicable for ERC20 tokens) * @param quantity The quantity of tokens to mint. * @param pricePerToken The price to pay per quantity of tokens minted. * @param currency The currency in which to pay the price per token minted. * @param validityStartTimestamp The unix timestamp after which the payload is valid. * @param validityEndTimestamp The unix timestamp at which the payload expires. * @param uid A unique identifier for the payload. */ struct MintRequest { address to; address royaltyRecipient; uint256 royaltyBps; address primarySaleRecipient; string uri; uint256 quantity; uint256 pricePerToken; address currency; uint128 validityStartTimestamp; uint128 validityEndTimestamp; bytes32 uid; } /// @dev Emitted when tokens are minted. event TokensMintedWithSignature( address indexed signer, address indexed mintedTo, uint256 indexed tokenIdMinted, MintRequest mintRequest ); /** * @notice Verifies that a mint request is signed by an account holding * MINTER_ROLE (at the time of the function call). * * @param req The payload / mint request. * @param signature The signature produced by an account signing the mint request. * * returns (success, signer) Result of verification and the recovered address. */ function verify(MintRequest calldata req, bytes calldata signature) external view returns (bool success, address signer); /** * @notice Mints tokens according to the provided mint request. * * @param req The payload / mint request. * @param signature The signature produced by an account signing the mint request. */ function mintWithSignature(MintRequest calldata req, bytes calldata signature) external payable returns (address signer); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165Upgradeable.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // ERC721A Contracts v3.3.0 // Creator: Chiru Labs pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; /** * @dev Interface of an ERC721A compliant contract. */ interface IERC721AUpgradeable is IERC721Upgradeable, IERC721MetadataUpgradeable { /** * The caller must own the token or be an approved operator. */ error ApprovalCallerNotOwnerNorApproved(); /** * The token does not exist. */ error ApprovalQueryForNonexistentToken(); /** * The caller cannot approve to their own address. */ error ApproveToCaller(); /** * The caller cannot approve to the current owner. */ error ApprovalToCurrentOwner(); /** * Cannot query the balance for the zero address. */ error BalanceQueryForZeroAddress(); /** * Cannot mint to the zero address. */ error MintToZeroAddress(); /** * The quantity of tokens minted must be more than zero. */ error MintZeroQuantity(); /** * The token does not exist. */ error OwnerQueryForNonexistentToken(); /** * The caller must own the token or be an approved operator. */ error TransferCallerNotOwnerNorApproved(); /** * The token must be owned by `from`. */ error TransferFromIncorrectOwner(); /** * Cannot safely transfer to a contract that does not implement the ERC721Receiver interface. */ error TransferToNonERC721ReceiverImplementer(); /** * Cannot transfer to the zero address. */ error TransferToZeroAddress(); /** * The token does not exist. */ error URIQueryForNonexistentToken(); // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } /** * @dev Returns the total amount of tokens stored by the contract. * * Burned tokens are calculated here, use `_totalMinted()` if you want to count just minted tokens. */ function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IWETH { function deposit() external payable; function withdraw(uint256 amount) external; function transfer(address to, uint256 value) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IContractMetadata { /// @dev Returns the metadata URI of the contract. function contractURI() external view returns (string memory); /** * @dev Sets contract URI for the storefront-level metadata of the contract. * Only module admin can call this function. */ function setContractURI(string calldata _uri) external; event ContractURIUpdated(string prevURI, string newURI); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IPlatformFee { /// @dev Returns the platform fee bps and recipient. function getPlatformFeeInfo() external view returns (address, uint16); /// @dev Lets a module admin update the fees on primary sales. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external; /// @dev Emitted when fee on primary sales is updated. event PlatformFeeInfoUpdated(address platformFeeRecipient, uint256 platformFeeBps); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IRoyalty { struct RoyaltyInfo { address recipient; uint256 bps; } /// @dev Returns the royalty recipient and fee bps. function getDefaultRoyaltyInfo() external view returns (address, uint16); /// @dev Lets a module admin update the royalty bps and recipient. function setDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps) external; /// @dev Lets a module admin set the royalty recipient for a particular token Id. function setRoyaltyInfoForToken( uint256 tokenId, address recipient, uint256 bps ) external; /// @dev Returns the royalty recipient for a particular token Id. function getRoyaltyInfoForToken(uint256 tokenId) external view returns (address, uint16); /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); /// @dev Emitted when royalty info is updated. event DefaultRoyalty(address newRoyaltyRecipient, uint256 newRoyaltyBps); /// @dev Emitted when royalty recipient for tokenId is set event RoyaltyForToken(uint256 indexed tokenId, address royaltyRecipient, uint256 royaltyBps); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IPrimarySale { /// @dev The adress that receives all primary sales value. function primarySaleRecipient() external view returns (address); /// @dev Lets a module admin set the default recipient of all primary sales. function setPrimarySaleRecipient(address _saleRecipient) external; /// @dev Emitted when a new sale recipient is set. event PrimarySaleRecipientUpdated(address indexed recipient); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IOwnable { /// @dev Returns the owner of the contract. function owner() external view returns (address); /// @dev Lets a module admin set a new owner for the contract. The new owner must be a module admin. function setOwner(address _newOwner) external; /// @dev Emitted when a new Owner is set. event OwnerUpdated(address prevOwner, address newOwner); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IDelayedReveal { function reveal(uint256 identifier, bytes calldata key) external returns (string memory revealedURI); function encryptDecrypt(bytes memory data, bytes calldata key) external pure returns (bytes memory result); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface ILazyMint { function lazyMint( uint256 amount, string calldata baseURIForTokens, bytes calldata encryptedBaseURI ) external returns (uint256 batchId); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IPermissions.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IPermissionsEnumerable is IPermissions { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interface/IPermissions.sol"; import "../lib/Strings.sol"; contract Permissions is IPermissions { mapping(bytes32 => mapping(address => bool)) private _hasRole; mapping(bytes32 => bytes32) private _getRoleAdmin; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; modifier onlyRole(bytes32 role) { _checkRole(role, msg.sender); _; } function hasRole(bytes32 role, address account) public view override returns (bool) { return _hasRole[role][account]; } function hasRoleWithSwitch(bytes32 role, address account) public view returns (bool) { if (!_hasRole[role][address(0)]) { return _hasRole[role][account]; } return true; } function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _getRoleAdmin[role]; } function grantRole(bytes32 role, address account) public virtual override { _checkRole(_getRoleAdmin[role], msg.sender); _setupRole(role, account); } function revokeRole(bytes32 role, address account) public virtual override { _checkRole(_getRoleAdmin[role], msg.sender); _revokeRole(role, account); } function renounceRole(bytes32 role, address account) public virtual override { require(msg.sender == account, "Can only renounce for self"); _revokeRole(role, account); } function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = _getRoleAdmin[role]; _getRoleAdmin[role] = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _setupRole(bytes32 role, address account) internal virtual { _hasRole[role][account] = true; emit RoleGranted(role, account, msg.sender); } function _revokeRole(bytes32 role, address account) internal virtual { delete _hasRole[role][account]; emit RoleRevoked(role, account, msg.sender); } function _checkRole(bytes32 role, address account) internal view virtual { if (!_hasRole[role][account]) { revert( string( abi.encodePacked( "Permissions: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } function _checkRoleWithSwitch(bytes32 role, address account) internal view virtual { if (!hasRoleWithSwitch(role, account)) { revert( string( abi.encodePacked( "Permissions: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IPermissions { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IClaimCondition.sol"; interface IDrop is IClaimCondition { struct AllowlistProof { bytes32[] proof; uint256 maxQuantityInAllowlist; } event TokensClaimed( uint256 indexed claimConditionIndex, address indexed claimer, address indexed receiver, uint256 startTokenId, uint256 quantityClaimed ); event ClaimConditionsUpdated(ClaimCondition[] claimConditions); /** * @notice Lets an account claim a given quantity of NFTs. * * @param receiver The receiver of the NFTs to claim. * @param quantity The quantity of NFTs to claim. * @param currency The currency in which to pay for the claim. * @param pricePerToken The price per token to pay for the claim. * @param allowlistProof The proof of the claimer's inclusion in the merkle root allowlist * of the claim conditions that apply. * @param data Arbitrary bytes data that can be leveraged in the implementation of this interface. */ function claim( address receiver, uint256 quantity, address currency, uint256 pricePerToken, AllowlistProof calldata allowlistProof, bytes memory data ) external payable; /** * @notice Lets a contract admin (account with `DEFAULT_ADMIN_ROLE`) set claim conditions. * * @param phases Claim conditions in ascending order by `startTimestamp`. * * @param resetClaimEligibility Whether to reset `limitLastClaimTimestamp` and `limitMerkleProofClaim` values when setting new * claim conditions. * * @param data Arbitrary bytes data that can be leveraged in the implementation of this interface. */ function setClaimConditions( ClaimCondition[] calldata phases, bool resetClaimEligibility, bytes memory data ) external; } // SPDX-License-Identifier: MIT // Modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/utils/cryptography/MerkleProof.sol // Copied from https://github.com/ensdomains/governance/blob/master/contracts/MerkleProof.sol pragma solidity ^0.8.11; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. * * Source: https://github.com/ensdomains/governance/blob/master/contracts/MerkleProof.sol */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool, uint256) { bytes32 computedHash = leaf; uint256 index = 0; for (uint256 i = 0; i < proof.length; i++) { index *= 2; bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); index += 1; } } // Check if the computed hash (root) is equal to the provided root return (computedHash == root, index); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ExecutionContext { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/BitMaps.sol) pragma solidity ^0.8.0; /** * @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. * Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor]. */ library BitMapsUpgradeable { struct BitMap { mapping(uint256 => uint256) _data; } /** * @dev Returns whether the bit at `index` is set. */ function get(BitMap storage bitmap, uint256 index) internal view returns (bool) { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); return bitmap._data[bucket] & mask != 0; } /** * @dev Sets the bit at `index` to the boolean `value`. */ function setTo( BitMap storage bitmap, uint256 index, bool value ) internal { if (value) { set(bitmap, index); } else { unset(bitmap, index); } } /** * @dev Sets the bit at `index`. */ function set(BitMap storage bitmap, uint256 index) internal { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); bitmap._data[bucket] |= mask; } /** * @dev Unsets the bit at `index`. */ function unset(BitMap storage bitmap, uint256 index) internal { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); bitmap._data[bucket] &= ~mask; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/structs/BitMapsUpgradeable.sol"; /** * Thirdweb's 'Drop' contracts are distribution mechanisms for tokens. * * A contract admin (i.e. a holder of `DEFAULT_ADMIN_ROLE`) can set a series of claim conditions, * ordered by their respective `startTimestamp`. A claim condition defines criteria under which * accounts can mint tokens. Claim conditions can be overwritten or added to by the contract admin. * At any moment, there is only one active claim condition. */ interface IClaimCondition { /** * @notice The criteria that make up a claim condition. * * @param startTimestamp The unix timestamp after which the claim condition applies. * The same claim condition applies until the `startTimestamp` * of the next claim condition. * * @param maxClaimableSupply The maximum total number of tokens that can be claimed under * the claim condition. * * @param supplyClaimed At any given point, the number of tokens that have been claimed * under the claim condition. * * @param quantityLimitPerTransaction The maximum number of tokens that can be claimed in a single * transaction. * * @param waitTimeInSecondsBetweenClaims The least number of seconds an account must wait after claiming * tokens, to be able to claim tokens again. * * @param merkleRoot The allowlist of addresses that can claim tokens under the claim * condition. * * @param pricePerToken The price required to pay per token claimed. * * @param currency The currency in which the `pricePerToken` must be paid. */ struct ClaimCondition { uint256 startTimestamp; uint256 maxClaimableSupply; uint256 supplyClaimed; uint256 quantityLimitPerTransaction; uint256 waitTimeInSecondsBetweenClaims; bytes32 merkleRoot; uint256 pricePerToken; address currency; } /** * @notice The set of all claim conditions, at any given moment. * Claim Phase ID = [currentStartId, currentStartId + length - 1]; * * @param currentStartId The uid for the first claim condition amongst the current set of * claim conditions. The uid for each next claim condition is one * more than the previous claim condition's uid. * * @param count The total number of phases / claim conditions in the list * of claim conditions. * * @param conditions The claim conditions at a given uid. Claim conditions * are ordered in an ascending order by their `startTimestamp`. * * @param lastClaimTimestamp Map from an account and uid for a claim condition, to the last timestamp * at which the account claimed tokens under that claim condition. * * @param usedAllowlistSpot Map from a claim condition uid to whether an address in an allowlist * has already claimed tokens i.e. used their place in the allowlist. */ struct ClaimConditionList { uint256 currentStartId; uint256 count; mapping(uint256 => ClaimCondition) conditions; mapping(uint256 => mapping(address => uint256)) lastClaimTimestamp; mapping(uint256 => BitMapsUpgradeable.BitMap) usedAllowlistSpot; } }
<template> <nav class="my-3" aria-label="Page navigation example"> <ul v-if="pagesIndex !== ''" class="pagination justify-content-center"> <li :class="{ disabled: page.currentPage === 1 }" class="page-item" > <router-link :to="`${currentRoute}/${page.currentPage-1}`" class="page-link">Previous</router-link> </li> <li v-for="pageIndex in pagesIndex" :key="pageIndex.index" class="page-item" > <router-link :to="`${currentRoute}/${pageIndex}`" :class="{ current: page.currentPage === pageIndex }" class="page-link" > {{ pageIndex }} </router-link> </li> <li :class="{ disabled: page.currentPage === page.totalPage }" class="page-item" > <router-link :to="`${currentRoute}/${page.currentPage+1}`" class="page-link">Next</router-link> </li> </ul> </nav> </template> <script> import { ref, watchEffect } from 'vue' import { useRouter } from 'vue-router' export default { name: 'Pagination', props: { pagination: { type: Object } }, setup(props) { const currentRoute = ref(null) const path = useRouter().currentRoute.value.fullPath if (path === '/') { currentRoute.value = '' } else { currentRoute.value = path } const page = ref({ currentPage: props.pagination.currentPage, totalCount: props.pagination.totalCount, perPage: props.pagination.perPage, totalPage: Math.round(props.pagination.totalCount/props.pagination.perPage) }) watchEffect(() => { page.value.currentPage = props.pagination.currentPage }) let pagesIndex = [] for (let i = 1; i <= page.value.totalPage; i++) { pagesIndex.push(i) } return { page, pagesIndex, currentRoute } } } </script> <style> .current { background: #2b60d1; color: #fff; } </style>
const express = require('express'); const axios = require('axios'); const path = require('path'); const app = express(); const port = process.env.PORT || 3000; const apiKey = "YOUR_API_KEY_HERE"; app.use(express.static(path.join(__dirname, 'public'))); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.post('/getWeather', async (req, res) => { try { const city = req.body.city; const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`; const response = await axios.get(url); const data = response.data; console.log("API Response:", data); // Added for debugging res.json({ temperature: data.main.temp, description: data.weather[0].description, city: data.name, }); } catch (error) { res.status(500).json({ message: "Error fetching weather data" }); } }); app.listen(port, () => { console.log(`Server running on port ${port}`); });
import selectorParser from 'postcss-selector-parser'; import postcss, { Root } from 'postcss'; import cssnano from 'cssnano'; const KEYFRAME_RULES = new Set(['keyframes', '-webkit-keyframes', '-moz-keyframes', '-o-keyframes']); async function scopeCss(code: string, styleScopeId: string) { const selectorProcessor = selectorParser(selectors => { for (let i = 0; i < selectors.length; i++) { const scopeSelector = selectorParser.attribute({ attribute: styleScopeId } as any); const selector = selectors.at(i); const groups = selector.split(s => s.type === 'combinator'); for (const group of groups) { let didInsert = false; for (let i = 0; i < group.length; i++) { if (group[i].type === 'tag' || group[i].type === 'root' || group[i].type === 'universal') continue; group.splice(i, 0, scopeSelector); didInsert = true; break; } if (!didInsert) group.push(scopeSelector); } selector.nodes = groups.flat(); } }); const cssProcessor = postcss() .use((root: Root) => { root.walkRules(rule => { if (rule.parent && KEYFRAME_RULES.has((rule.parent as any)?.name ?? '')) return; rule.selectors = rule.selectors.map(selector => selectorProcessor.processSync(selector)); }); }) .use(cssnano); const processed = await cssProcessor.process(code, { from: undefined }); return processed.css; } export { scopeCss };
package main import ( "sort" "strings" ) var CARDS = []byte{'A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2'} var CARD_STRENGTH map[byte]int var CARD_STRENGTH_WJ map[byte]int func init() { CARD_STRENGTH = make(map[byte]int, len(CARDS)) CARD_STRENGTH_WJ = make(map[byte]int, len(CARDS)) for ix, card := range CARDS { CARD_STRENGTH[card] = len(CARDS) - ix if card != 'J' { CARD_STRENGTH_WJ[card] = len(CARDS) - ix } } CARD_STRENGTH_WJ['J'] = 0 } const ( HighCardMask = uint16(0b_000_00_111) OnePairMask = uint16(0b_000_01_000) TwoPairMask = uint16(0b_000_10_000) ThreeMask = uint16(0b_001_00_000) FullHouseMask = uint16(0b_001_01_000) FourMask = uint16(0b_010_00_000) FiveMask = uint16(0b_100_00_000) ) const JOKER_SHIFT = 8 var CNT_SHIFT = [6]int{0, 0, 3, 5, 6, 7} func getHandMask(s string, MOD uint16) uint16 { hasJ := (MOD >> JOKER_SHIFT) > 0 cnts := make(map[byte]int, len(s)) for _, b := range []byte(s) { cnts[b]++ } msk := uint16(0) for b, cnt := range cnts { if hasJ && b == 'J' { msk += uint16(cnt) << JOKER_SHIFT } else { msk += 1 << (CNT_SHIFT[cnt]) } } if hasJ { msk = applyJokerMask(msk) } debugf("s: %s, msk: %011b", s, msk) return msk } const ( NO_JOKER = uint16(0b_1111_1111) WITH_JOKER = uint16(0b_111_1111_1111) ) func cmpHighestCard(A, B string, MOD uint16) bool { hasJ := MOD>>JOKER_SHIFT > 0 aa, bb := []byte(A), []byte(B) for i := 0; i < len(A); i++ { if aa[i] == bb[i] { continue } // TODO: this was supposed to be handled by the MOD mask rather than branch if hasJ { return CARD_STRENGTH_WJ[aa[i]] < CARD_STRENGTH_WJ[bb[i]] } return CARD_STRENGTH[aa[i]] < CARD_STRENGTH[bb[i]] } panic("cards are equal???") } // detects joker bits and adds them up to the highest-ranked group func applyJokerMask(m uint16) uint16 { j := m >> JOKER_SHIFT if j > 0 { m &= NO_JOKER if m&FiveMask > 0 { return m } else if m&FourMask > 0 { m = m&(^FourMask) | FiveMask } else if m&ThreeMask > 0 { m = m&(^ThreeMask) | (ThreeMask << j) } else if m&TwoPairMask > 0 || m&OnePairMask > 0 { pairs := (((m & (OnePairMask | TwoPairMask) >> 3) & 0b11) - 1) << 3 m = m&(^(OnePairMask | TwoPairMask)) | pairs m |= (TwoPairMask << j) } else { // WTF, oleg? delta := uint16(0) if m > 0 { m -= 1 delta = 1 } if j == 1 { m |= OnePairMask } else { m |= (TwoPairMask << (j - 2 + delta)) } } } return m } func cmpCardMask(A, B string, MOD uint16) bool { MA, MB := getHandMask(A, MOD), getHandMask(B, MOD) if MA != MB { return MA < MB } return cmpHighestCard(A, B, MOD) } func getWinnings(cards []string, ranks map[string]int) int { win := 0 for rank, card := range cards { win += (rank + 1) * ranks[card] } return win } func main() { lines := input() debugf("file data: %+v", lines) cards := make([]string, 0, len(lines)) ranks := make(map[string]int) for _, line := range lines { ss := strings.SplitN(line, " ", 2) card, rank := ss[0], parseInt(ss[1]) cards = append(cards, card) ranks[card] = rank } debugf("cards: %+v, ranks: %+v", cards, ranks) sort.Slice(cards, func(i, j int) bool { return cmpCardMask(cards[i], cards[j], NO_JOKER) }) debugf("sorted cards: %+v", cards) win1 := getWinnings(cards, ranks) printf("total winnings 1: %d", win1) sort.Slice(cards, func(i, j int) bool { return cmpCardMask(cards[i], cards[j], WITH_JOKER) }) debugf("sorted cards: %+v", cards) win2 := getWinnings(cards, ranks) printf("total winnings 2: %d", win2) }
package com.cerridan.badmintonscheduler.dialog import android.os.Bundle import android.widget.Toast import android.widget.Toast.LENGTH_LONG import androidx.appcompat.app.AlertDialog import com.cerridan.badmintonscheduler.R import com.cerridan.badmintonscheduler.dagger.DaggerInjector import com.cerridan.badmintonscheduler.manager.PlayerManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import javax.inject.Inject class RemovePlayerFragment : BaseAlertDialogFragment() { companion object { private const val KEY_PLAYER_NAME = "dialog.RemovePlayerFragment/player_name" fun create(playerName: String) = RemovePlayerFragment() .apply { arguments = Bundle().apply { putString(KEY_PLAYER_NAME, playerName) } } } @Inject lateinit var playerManager: PlayerManager init { DaggerInjector.appComponent.inject(this) } override fun onCreateDialog(savedInstanceState: Bundle?) = AlertDialog.Builder(requireContext()) .setTitle(R.string.remove_player_title) .setMessage( resources.getString( R.string.remove_player_message, arguments?.getString(KEY_PLAYER_NAME)!! ) ) .setPositiveButton(R.string.remove_player_confirm, null) .setNegativeButton(R.string.remove_player_cancel, null) .create() override fun onStart(dialog: AlertDialog) { val playerName = arguments?.getString(KEY_PLAYER_NAME)!! dialogScope.launch { positiveButtonClicks .filter { isCancelable } .map { isCancelable = false playerManager.removePlayer(playerName) } .flowOn(Dispatchers.IO) .collect { error -> isCancelable = true if (error.isNotBlank()) { Toast.makeText(dialog.context, error, LENGTH_LONG).show() } else { dismiss() } } } dialogScope.launch { negativeButtonClicks .filter { isCancelable } .collect { dismiss() } } } }
<?php namespace Drupal\json_table\Plugin\Field\FieldType; use Drupal\Core\Field\FieldItemBase; use Drupal\Core\Field\FieldStorageDefinitionInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\TypedData\DataDefinition; /** * Provides a field type of baz. * * @FieldType( * id = "json", * label = @Translation("Json table field"), * default_formatter = "json_formatter", * default_widget = "json_editor_widget", * ) */ class JsonItem extends FieldItemBase { /** * {@inheritdoc} */ public static function schema(FieldStorageDefinitionInterface $field_definition) { return [ // columns contains the values that the field will store 'columns' => [ // List the values that the field will save. This // field will only save a single value, 'value' 'value' => [ 'type' => 'json', 'pgsql_type' => 'json', 'mysql_type' => 'json', 'not null' => FALSE, ], ], ]; } /** * {@inheritdoc} */ public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) { $properties['value'] = DataDefinition::create('string') ->setLabel(t('JSON value')); return $properties; } /** * {@inheritdoc} */ public function isEmpty() { $value = $this->get('value')->getValue(); return $value === NULL || $value === ''; } /** * {@inheritdoc} */ public static function defaultFieldSettings() { return [ // Declare a single setting, 'size', with a default // value of 'large' 'size' => 'big', ] + parent::defaultFieldSettings(); } /** * {@inheritdoc} */ public function fieldSettingsForm(array $form, FormStateInterface $form_state) { $element = []; // The key of the element should be the setting name $element['size'] = [ '#title' => $this->t('Size'), '#type' => 'select', '#options' => [ 'normal' => $this->t('Normal'), 'medium' => $this->t('Medium'), 'big' => $this->t('Big'), ], '#default_value' => $this->getSetting('size'), ]; return $element; } }
import React, { ReactElement, FC, useState } from 'react'; import { Grid, Modal, ModalProps, Icon, Form, Message, } from 'semantic-ui-react'; import { BasePopulatedUser } from 'ssw-common'; import { UserPicture, FieldTag } from '..'; import { titleCase } from '../../utils/helpers'; import { SecondaryButton } from '../ui/SecondaryButton'; import { PrimaryButton } from '../ui/PrimaryButton'; import { approveUser, rejectUser } from '../../api'; import { TagList } from '../list/TagList'; import { useAuth } from '../../contexts'; import './modals.scss'; import './ReviewUser.scss'; interface ReviewUserProps extends ModalProps { user: BasePopulatedUser; setOpen: React.Dispatch<React.SetStateAction<boolean>>; type: 'reject' | 'review'; } export const ReviewUser: FC<ReviewUserProps> = ({ user, open, setOpen, type, ...rest }): ReactElement => { const [onboardReasoning, setOnboardReasoning] = useState(''); const { user: currentUser } = useAuth(); return ( <Modal {...rest} open={open} onClose={() => setOpen(false)} className="review-user-modal" > <Modal.Header className="review-user-header"> {type === 'reject' ? 'View Rejected User' : 'Review User'} </Modal.Header> <Modal.Content scrolling> <Grid divided="vertically"> <Grid.Row columns={2}> <Grid.Column> <div className="user-info"> <UserPicture className="review-user-picture" user={user} /> <div className="user-info-text"> <b>{user.joinedNames}</b> <br /> {user.pronouns.join(', ')} </div> </div> </Grid.Column> <Grid.Column> <div> <Icon name="mail" /> {user.email} </div> <div> <Icon name="phone" /> {user.phone} </div> </Grid.Column> <Grid.Column> <b>Genders:</b> {user.genders.join(', ')} <br /> <b>Races:</b> {user.races.map(titleCase).join(', ')} <br /> <b>Neighborhood:</b> {user.neighborhood} </Grid.Column> </Grid.Row> <Grid.Row columns="4"> <Grid.Column> <b>Role</b> <div> <FieldTag className="role-tag" content={user.role} size="medium" /> </div> </Grid.Column> <Grid.Column> <b>Teams</b> <div> <TagList tags={user.teams} /> </div> </Grid.Column> <Grid.Column width={8}> <b>Topic Interests</b> <div> <TagList tags={user.interests} /> </div> </Grid.Column> </Grid.Row> <Grid.Row columns={1}> <Grid.Column> {type === 'reject' && ( <Message size="small" className="reject-message" header="Rejection Reasoning" warning content={user.onboardReasoning} /> )} <span style={{ color: 'gray' }}> {type === 'reject' ? 'Applied' : 'Registered'} on{' '} {new Date(user.dateJoined).toLocaleDateString()} </span> </Grid.Column> <Grid.Column> <div className="section"> <b>How and why user wants to get involved</b> <br /> {user.involvementResponse} </div> <div className="section"> <b>User's past experience</b> <br /> {user.journalismResponse} </div> {type === 'review' && ( <> <h5> Reasoning <span style={{ color: 'gray' }}>- Optional</span> </h5> <Form.Input fluid value={onboardReasoning} onChange={(e, { value }) => setOnboardReasoning(value)} /> </> )} </Grid.Column> </Grid.Row> </Grid> </Modal.Content> {type === 'review' && ( <Modal.Actions className="review-user-actions"> <PrimaryButton className="approve-button" onClick={() => approveUser(user, currentUser)} content="Approve" /> <SecondaryButton className="decline-button" onClick={() => rejectUser(user, currentUser, onboardReasoning)} content="Decline" border /> </Modal.Actions> )} </Modal> ); };
import React from 'react'; import { Link } from 'react-router-dom'; import { makeStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Tabs from '@material-ui/core/Tabs'; import Tab from '@material-ui/core/Tab'; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, backgroundColor: theme.palette.background.paper, }, })); function NavBar() { const classes = useStyles(); const [value, setValue] = React.useState(0); const handleChange = (event, newValue) => { setValue(newValue); }; return ( <div className={classes.root}> <AppBar position='static'> <Tabs value={value} onChange={handleChange} aria-label='simple tabs example'> <Tab label='Home' component={Link} to='/' /> <Tab label='Calculate' component={Link} to='/calc' /> <Tab label='Count' component={Link} to='/Count' /> <Tab label='Log' component={Link} to='/Log' /> </Tabs> </AppBar> </div> ); } export default NavBar;
import React from 'react'; import { Button, Card, CardHeader, CardBody, CardFooter, Form, Input, InputGroupAddon, InputGroupText, InputGroup, Container, Col, } from 'reactstrap'; import { history } from '../store'; // reactstrap components // core components import ExamplesNavbar from '../components/Navbars/ExamplesNavbar'; import TransparentFooter from '../components/Footers/TransparentFooter'; function LoginPage() { const [firstFocus, setFirstFocus] = React.useState(false); const [lastFocus, setLastFocus] = React.useState(false); React.useEffect(() => { document.body.classList.add('login-page'); document.body.classList.add('sidebar-collapse'); document.documentElement.classList.remove('nav-open'); window.scrollTo(0, 0); document.body.scrollTop = 0; return function cleanup() { document.body.classList.remove('login-page'); document.body.classList.remove('sidebar-collapse'); }; }); return ( <> <ExamplesNavbar /> <div className="page-header clear-filter" filter-color="blue"> <div className="page-header-image" style={{ backgroundImage: `url(${require('assets/img/login.jpg')})`, }} /> <div className="content"> <Container> <Col className="ml-auto mr-auto" md="4"> <Card className="card-login card-plain"> <Form action="" className="form" method=""> <CardHeader className="text-center"> <div className="logo-container"> <img alt="..." src={require('assets/img/now-logo.png')} /> </div> </CardHeader> <CardBody> <InputGroup className={`no-border input-lg${firstFocus ? ' input-group-focus' : ''}`}> <InputGroupAddon addonType="prepend"> <InputGroupText> <i className="now-ui-icons users_circle-08" /> </InputGroupText> </InputGroupAddon> <Input placeholder="First Name..." type="text" onFocus={() => setFirstFocus(true)} onBlur={() => setFirstFocus(false)} /> </InputGroup> <InputGroup className={`no-border input-lg${lastFocus ? ' input-group-focus' : ''}`}> <InputGroupAddon addonType="prepend"> <InputGroupText> <i className="now-ui-icons text_caps-small" /> </InputGroupText> </InputGroupAddon> <Input placeholder="Last Name..." type="text" onFocus={() => setLastFocus(true)} onBlur={() => setLastFocus(false)} /> </InputGroup> </CardBody> <CardFooter className="text-center"> <Button block className="btn-round" color="info" onClick={() => history.push('/dashboard')} size="lg"> Get Started </Button> <div className="pull-left"> <h6> <a className="link" href="#pablo" onClick={e => e.preventDefault()}> Create Account </a> </h6> </div> <div className="pull-right"> <h6> <a className="link" href="#pablo" onClick={e => e.preventDefault()}> Need Help? </a> </h6> </div> </CardFooter> </Form> </Card> </Col> </Container> </div> <TransparentFooter /> </div> </> ); } export default LoginPage;
import "package:firebase_auth/firebase_auth.dart"; import "package:flutter/material.dart"; import "package:flutter_iconly/flutter_iconly.dart"; import "package:grocery_app/consts/firebase_consts.dart"; import "package:grocery_app/screens/auth/login.dart"; import "package:grocery_app/screens/orders/orders_screen.dart"; import "package:grocery_app/screens/viewed_recently/viewed_recently.dart"; import "package:grocery_app/screens/wishlist/wishlist_screen.dart"; import "package:grocery_app/services/global_methods.dart"; import "package:grocery_app/widgets/text_widget.dart"; import "package:provider/provider.dart"; import "../provider/dark_theme_provider.dart"; class UserScreen extends StatefulWidget { const UserScreen({super.key}); @override State<UserScreen> createState() => _UserScreenState(); } class _UserScreenState extends State<UserScreen> { TextEditingController _addressTextController = TextEditingController(text: ""); @override void dispose() { _addressTextController.dispose(); super.dispose(); } final User? user = authInstance.currentUser; @override Widget build(BuildContext context) { final themeState = Provider.of<DarkThemeProvider>(context); final Color color = themeState.getDarkTheme ? Colors.white : Colors.black; return Scaffold( body: Center( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ const SizedBox( height: 15, ), RichText( text: TextSpan( text: 'Hi, ', style: const TextStyle( color: Colors.cyan, fontSize: 27, fontWeight: FontWeight.bold), children: <TextSpan>[ TextSpan( text: 'MyName', style: TextStyle( color: color, fontSize: 25, fontWeight: FontWeight.w600)) ])), TextWidget(text: 'Email@email.com', color: color, textSize: 18), Divider( thickness: 2, ), SizedBox( height: 20, ), _listTiles( title: 'Address 2', subtitle: 'My subtitle', icon: IconlyLight.profile, onPressed: () async { await _showAdressDialog(); }, color: color), _listTiles( title: 'Orders', icon: IconlyLight.bag, onPressed: () { GlobalMethods().navigateTo( ctx: context, routeName: OrdersScreen.routeName); }, color: color), _listTiles( title: 'Wishlist', icon: IconlyLight.heart, onPressed: () { GlobalMethods().navigateTo( ctx: context, routeName: WishlistScreen.routeName); }, color: color), _listTiles( title: 'Viewed', icon: IconlyLight.show, onPressed: () { GlobalMethods().navigateTo( ctx: context, routeName: ViewedRecentlyScreen.routeName); }, color: color), _listTiles( title: 'Forget Password', icon: IconlyLight.unlock, onPressed: () {}, color: color), SwitchListTile( title: TextWidget( text: themeState.getDarkTheme ? 'Dark mode' : 'Light mode', color: color, textSize: 18, ), secondary: Icon(themeState.getDarkTheme ? Icons.dark_mode_outlined : Icons.light_mode_outlined), onChanged: (bool value) { setState(() { themeState.setDarkTheme = value; }); }, value: themeState.getDarkTheme, ), _listTiles( title: user == null ? 'Login' : 'Logout', icon: user == null ? IconlyLight.login : IconlyLight.logout, onPressed: () async { if (user == null) { Navigator.of(context).push( MaterialPageRoute( builder: (context) => const LoginScreen(), ), ); } await GlobalMethods().warningDialog( title: 'Sign out', subtitle: 'Do you wanna sign out?', fct: () async { await authInstance.signOut(); Navigator.of(context).push(MaterialPageRoute( builder: (context) => const LoginScreen())); }, context: context); }, color: color) ], ), )), ), ); } Future<void> _showAdressDialog() async { await showDialog( context: context, builder: (context) { return AlertDialog( title: const Text('Update'), content: TextField( // onChanged: (value) { // //_addressTextController.text; // }, controller: _addressTextController, maxLines: 5, decoration: const InputDecoration(hintText: "Your Adress"), ), actions: [ TextButton( onPressed: () {}, child: const Text('Update'), ), ], ); }); } Widget _listTiles({ required String title, String? subtitle, required IconData icon, required Function onPressed, required Color color, }) { return ListTile( title: TextWidget(text: title, color: color, textSize: 22, isTitle: true), subtitle: TextWidget( text: subtitle == null ? "" : subtitle, color: color, textSize: 18, ), leading: Icon(icon), trailing: const Icon(IconlyLight.arrowRight2), onTap: () { onPressed(); }); } }
<?php namespace Model\Entities; use App\Entity; final class Post extends Entity { private $id; private $topic; private $user; private $creationDate; private $message; public function __construct($data) { $this->hydrate($data); } /** * Get the value of (post) id */ public function getId() { return $this->id; } /** * Set the value of (post) id * * @return self */ public function setId($id) { $this->id = $id; return $this; } /** * Get the value of title */ public function getTopic() { return $this->topic; } /** * Set the value of title * * @return self */ public function setTopic($topic) { $this->topic = $topic; return $this; } /** * Get the value of user */ public function getUser() { return $this->user; } /** * Set the value of user * * @return self */ public function setUser($user) { $this->user = $user; return $this; } public function getCreationDate() { $formattedDate = $this->creationDate->format("l/d/M/Y - H:i:s"); return $formattedDate; } public function setCreationDate($date) { $this->creationDate = new \DateTime($date); return $this; } /** * Get the value of message */ public function getMessage() { return $this->message; } /** * Set the value of message * * @return self */ public function setMessage($message) { $this->message = $message; return $this; } } ?>
import os import json from langchain.chains import ConversationalRetrievalChain from langchain_openai import ChatOpenAI from langchain.embeddings import SentenceTransformerEmbeddings from langchain.memory import ConversationBufferMemory from langchain.vectorstores.faiss import FAISS from langchain.prompts import PromptTemplate from langchain.schema.output_parser import StrOutputParser from langchain_community.document_loaders import DirectoryLoader, Docx2txtLoader import docx2txt ArdTemperatureValue = 5 ArdphValue = 5 Water_Level = 5 ArdConductivityValue = 5 brightness = 5 # Define the application prompt #utiliser les valeurs actuelles : temperature:34, Ph_value:12, water_level:30, conductivity:20, brightness:10, donner des recommandations spécifiques à chaque mesure combined_prompt = """ Utilisez les valeurs actuelles : - Température : {ArdTemperatureValue} degrés Celsius - Ph : {ArdphValue} - Niveau d'eau : {Water_Level} - Conductivité : {ArdConductivityValue} - brightnss: {brightness} ,donner des recommandations spécifiques à chaque mesure. """ user_input = f"temperature={ArdTemperatureValue};Ph_value={ArdphValue};water_level={Water_Level};conductivity={ArdConductivityValue};brightness={brightness}" prompt = combined_prompt.format( ArdTemperatureValue=ArdTemperatureValue, ArdphValue=ArdphValue, Water_Level=Water_Level, ArdConductivityValue=ArdConductivityValue, brightness=brightness ) class DataHandler: def __init__(self): self.docs_dir = "./handbook/" self.persist_dir = "./handbook_faiss" self.embedding =SentenceTransformerEmbeddings(model_name="all-mpnet-base-v2") self.received_data = None self.qa_chain = None # Load or build the FAISS index self.load_or_build_faiss() # Initialize the LLM model and conversation retrieval chain self.llm = ChatOpenAI( api_key='', temperature=0.6 ) self.memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) self.memory.load_memory_variables({}) self.load_or_build_faiss() self.initialize_qa_chain() def load_or_build_faiss(self): if os.path.exists(self.persist_dir): print(f"Loading FAISS index from {self.persist_dir}") self.vectorstore = FAISS.load_local(self.persist_dir, self.embedding, allow_dangerous_deserialization=True) print("Done.") else: print(f"Building FAISS index from documents in {self.docs_dir}") # Code for building FAISS index goes here pass def initialize_qa_chain(self): self.qa_chain = ConversationalRetrievalChain.from_llm( llm=self.llm, memory=self.memory, retriever=self.vectorstore.as_retriever() ) def process_received_data(self, data): self.received_data = data print("Received data:", self.received_data) recommendations = self.generate_recommendations(data) return recommendations def generate_recommendations(self, data): # Créer le modèle de prompt spécifique à chaque mesure if "temperature" in data: temperature_prompt = self.combined_prompt.format(ArdTemperatureValue=data["temperature"], ArdphValue=ArdphValue, Water_Level=Water_Level, ArdConductivityValue=ArdConductivityValue, brightness=brightness) prompt = PromptTemplate(input_variables=["user_input"], temparature=temperature_prompt) elif "Ph_value" in data: ph_prompt = self.combined_prompt.format(ArdTemperatureValue=ArdTemperatureValue, ArdphValue=data["Ph_value"], Water_Level=Water_Level, ArdConductivityValue=ArdConductivityValue, brightness=brightness) prompt = PromptTemplate(input_variables=["user_input"], ph=ph_prompt) elif "water_level"in data: water_prompt = self.combined_prompt.format(ArdTemperatureValue=ArdTemperatureValue, ArdphValue=data, Water_Level=Water_Level["water_level"], ArdConductivityValue=ArdConductivityValue, brightness=brightness) prompt = PromptTemplate(input_variables=["user_input"], water_level=water_prompt) elif "conductivity"in data: conductivity_prompt=self.combined_prompt.format(ArdTemperatureValue=ArdTemperatureValue, ArdphValue=data, Water_Level=Water_Level, ArdConductivityValue=ArdConductivityValue["conductivity"], brightness=brightness) prompt = PromptTemplate(input_variables=["user_input"], conductivity=conductivity_prompt) elif "brightness"in data: self.combined_prompt.format(ArdTemperatureValue=ArdTemperatureValue, ArdphValue=data, Water_Level=Water_Level, ArdConductivityValue=ArdConductivityValue, brightness=brightness["brightness"]) brightness_prompt = PromptTemplate(input_variables=["user_input"], conductivity=brightness_prompt) else: prompt = PromptTemplate(input_variables=["user_input"], ph="") # Utiliser le modèle de prompt pour générer la requête chain = prompt | self.llm | StrOutputParser() response = chain.invoke({"user_input": user_input})["output"] return response def execute(self): while True: user_input = input("Question:.\n>") if user_input == "exit": break else: result = self.qa_chain.invoke({"question": user_input}) response = result["answer"] print("Recommendations:", response) # Main entry point if __name__ == "__main__": main = DataHandler() main.execute()
pub use clap::Parser; use std::path::{Path, PathBuf}; use rand::{distributions::Alphanumeric, Rng}; use colored::Colorize; use filetime::{set_file_mtime, FileTime}; #[derive(Parser)] #[command(author, version, about, long_about = None)] pub struct Cli { pub directory: String, #[arg(short, long, default_value_t = 20, value_parser=length_correct)] pub length: i32, #[arg(short, long)] pub yes: bool, } pub fn length_correct(length: &str) -> Result<i32, String> { let length = length.parse::<i32>().unwrap_or(-1); if length > 0 { Ok(length) } else { Err("Length invalid".to_string()) } } fn get_log_number_to_reach_percent(percent: f64, length: i32) -> f64 { 0.5 *f64::log10(2_f64) + (length as f64) * 0.5 * f64::log10(36_f64)+ 0.5 * f64::log10(f64::log(1_f64 / (1_f64-percent), std::f64::consts::E)) } fn get_directory<'a>(directory_path: &'a str) -> Result<PathBuf,&'a str> { let path: PathBuf = PathBuf::from(directory_path); let is_dir = path.is_dir(); if is_dir { Ok(path) } else { Err("Directory not found") } } fn change_file_name(path: impl AsRef<Path>, name: &str) -> Result<(), &str> { //Get original path name let metadata = std::fs::metadata(path.as_ref()).expect("Unable to read metadata"); let modification_time = FileTime::from_last_modification_time(&metadata); let path = path.as_ref(); let original_path_name = path.to_str().unwrap(); let mut result = path.to_owned(); result.set_file_name(name); //Get filename from result if let Some(ext) = path.extension() { result.set_extension(ext); } std::fs::rename(path, result.clone()).expect("Error renaming file"); set_file_mtime(result.clone(), modification_time).expect("Error maintaining modification time"); println!("{} {} {}", original_path_name, "→".bold().red() ,result.to_str().unwrap()); Ok(()) } pub fn run_parsing(cli: &mut Cli) -> Result<(), Box<dyn std::error::Error>> { let mut response_to_continue = cli.yes; while !response_to_continue { println!("For a 1% chance of a collision, there needs to be 10^{:.2} objects. Change length ({}) or enter yes to continue: ",get_log_number_to_reach_percent(0.01, cli.length),cli.length); let mut response = String::new(); std::io::stdin().read_line(&mut response)?; let response = response.trim(); match response.to_lowercase().as_str() { "yes" | "y" => { response_to_continue = true; continue; }, _ => {} } //Convert response to integer cli.length = match length_correct(response.trim()) { Ok(response) => response, Err(e) => { println!("{}", e); continue; } }; } Ok(()) } pub fn run_randomize(cli: &Cli) -> Result<(), Box<dyn std::error::Error>> { let directory = get_directory(&cli.directory)?; for entry in directory.read_dir()? { if let Ok(entry) = entry { let random_alphanumeric_string = rand::thread_rng() .sample_iter(&Alphanumeric) .take(cli.length.try_into().unwrap()) .map(char::from) .collect::<String>(); change_file_name(entry.path(), random_alphanumeric_string.as_str())?; } } Ok(()) }
package com.xms.day02.PC; import java.util.ArrayList; import java.util.List; /** * @author dpc * @create 2021-06-21 下午 4:46 * 需求: * 资源类 * 生产者:提供资源,从1开始,依次+1 * 消费者:消费资源,删除生产者生产的资源 * 解决方案: * 使用等待唤醒机制 * 1)资源满了,生产者不停抢夺CPU * 解决:让生产者等待,等待消费者消费资源.当资源不满的时候,才允许生产者继续生产 * 2)资源空了,消费者不停抢夺CPU * 解决:让消费者等待,等待生产者生产资源,当有资源的时候,才允许消费者继续消费 * 问题: * 发生了死锁 */ //资源类 class MyList2 { static int n = 1;//共享资源 List<Integer> list = new ArrayList<>(); public static final int MAX_SIZE = 1;//生产上限 // 生产数据 public synchronized void addSource() { // 判断是否达到生产上线 while (list.size() == MAX_SIZE){//满了,等待消费者消费 // 当通过notify唤醒了由wait进入到等待队列中的线程后,当该线程重新抢到CPU时间片后,会执行之前wait后面的操作 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "生产的数据" + n); list.add(n); System.out.println(Thread.currentThread().getName() + "生产后的集合为" + list); n++; // 唤醒线程 this.notify(); } // 消费数据 public synchronized void removeSourse() { // 判断是否资源全部消费 while (list.size() == 0){//没有资源,等待生产者生产 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 有资源消费资源 Integer value = list.remove(0); System.out.println(Thread.currentThread().getName() + "消费的数据为" + value); System.out.println(Thread.currentThread().getName() + "消费后的集合为" + list); // 唤醒线程 this.notify(); } } //生产者任务类 class ProductRunn2 implements Runnable { MyList ml; public ProductRunn2(MyList ml) { this.ml = ml; } @Override public void run() { while (true) { // 生产资源 ml.addSource(); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } } //消费者任务 class CustomerRunn2 implements Runnable { MyList ml; public CustomerRunn2(MyList ml) { this.ml = ml; } @Override public void run() { while (true) { // 消费数据 ml.removeSourse(); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class PCDemo02 { public static void main(String[] args) { // 资源 MyList ml = new MyList(); // 任务 Runnable target1 = new ProductRunn(ml); Runnable target2 = new CustomerRunn(ml); // 生产者 Thread t1 = new Thread(target1, "生产者1号"); Thread t2 = new Thread(target1, "生产者2号"); Thread t3 = new Thread(target1, "生产者3号"); // 消费者 Thread t4 = new Thread(target2, "消费者1号"); t1.start(); t2.start(); t3.start(); t4.start(); } }
import moment from "moment" import IntUser from "../interfaces/user" import IntSession from "../interfaces/session" import IntFollow from "../interfaces/follow" import mongoose from "mongoose" class ClsUser implements IntUser { _id?: string name: string surname: string bio: string nick: string email: string password: string role?: string image?: string created_at?: Date constructor(_id: string = "", name: string = "", surname: string = "", bio: string = "", nick: string = "", email: string = "", password: string = "", role: string = "", image: string = "", created_at: Date = new Date(Date.now())){ this._id = _id; this.name = name; this.surname = surname; this.bio = bio; this.nick = nick; this.email = email; this.password = password; this.role = role; this.image = image; this.created_at = created_at; } } class ClsSession implements IntSession { user: ClsUser iat: number exp: number constructor(user: ClsUser = new ClsUser(), iat: number = moment().unix(), exp: number = moment().add(30, "days").unix()) { this.user = user; this.iat = iat; this.exp = exp; } } class ClsFollow implements IntFollow { _id?: string | undefined user: mongoose.Types.ObjectId | null followed: mongoose.Types.ObjectId | null created_at: Date constructor(_id: string = "", user: mongoose.Types.ObjectId | null = null, followed: mongoose.Types.ObjectId | null = null, created_at: Date = new Date()) { this._id = _id; this.user = user; this.followed = followed; this.created_at = created_at; } } export { ClsUser, ClsSession, ClsFollow }
<!DOCTYPE html> <html> <main> <head> <title>FSD Survey</title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <div> <h1 id="title">Developer Survey</h1> </div> <p id="description"> What are the most frequently utilized tools by a Developer? </p> <form id="survey-form"> <div id="top"> <div class="rowTab"> <div class="labels"> <p>Please provide some basic information</p> <label id="name-label" for="name">Name: </label> </div> <div id="field"> <input autofocus type="text" name="name" id="name" class="input-field" placeholder="Enter your name" required> </div> </div> <br> <div class="rowTab"> <div class="labels"> <label id="email-label" for="email">Email: </label> </div> <div id="field"> <input type="email" name="email" id="email" class="input-field" required placeholder="Enter your Email"> </div> </div> <br> <div class="rowTab"> <div class="labels"> <label id="number-label" for="age">Years of experience: </label> </div> <div id="field"> <input type="number" name="experience" id="number" min="1" max="99" class="input-field" placeholder="Yrs. of experience"> </div> <br> <div class="rowTab"> <div class="labels"> <label for="POS">What is your current development role?</label> </div> <div class="label"> <ul style="list-style: none;"> <li class="radio"><label>Front-end<input name="radio-buttons" value="1" type="radio" class="POS" ></label></li> <li class="radio"><label>Back-end<input name="radio-buttons" value="2" type="radio" class="POS" ></label></li> <li class="radio"><label>Full Stack<input name="radio-buttons" value="3" type="radio" class="POS" ></label></li> <li class="radio"><label>N/A - Not a Developer<input name="radio-buttons" value="3" type="radio" class="POS" ></label></li> </ul> </div> </div> <div class="q1"> <label id="label1" for="operatingSystem">What Operating System do you prefer for development?</label> <select id="dropdown" name="operatingSystem" class="dropdown"> <option disabled value>Select an OS</option> <option value="student">Windows (7, 8, 10)</option> <option value="job">Mac OS</option> <option value="learner">Linux</option> <option value="preferNo">Mobile platform (Android)</option> <option value="other">Other</option> </select> </div> <br> <div class="rowTab"> <div id="labels"> <label for="preferences">What do you consider the most important technologies to learn?: </label> </div> <div id="labels"> <ul id="preferences" style="list-style: none;"> <li class="checkbox"><label><input name="prefer" value="1" type="checkbox" class="userRatings">HTML/CSS</label></li> <li class="checkbox"><input name="prefer" value="2" type="checkbox" class="userRatings">JavaScript</li> <li class="checkbox"><label><input name="prefer" value="3" type="checkbox" class="userRatings">Algorithms</label></li> <li class="checkbox"><label><input name="prefer" value="4" type="checkbox" class="userRatings">Bootstrap</label></li> <li class="checkbox"><label><input name="prefer" value="5" type="checkbox" class="userRatings">jQuery</label></li> <li class="checkbox"><label><input name="prefer" value="6" type="checkbox" class="userRatings">Sass</label></li> <li class="checkbox"><label><input name="prefer" value="7" type="checkbox" class="userRatings">React</label></li> <li class="checkbox"><label><input name="prefer" value="8" type="checkbox" class="userRatings">Redux</label></li> <li class="checkbox"><label><input name="prefer" value="9" type="checkbox" class="userRatings">JSON</label></li> <li class="checkbox"><label><input name="prefer" value="10" type="checkbox" class="userRatings">Ajax</label></li> <li class="checkbox"><label><input name="prefer" value="10" type="checkbox" class="userRatings">Other (please comment below)</label></li> </ul> </div> </div> <div class="rowTab"> <div class="labels"> <label for="comments">Any Comments or Suggestions?</label> </div> <div class="rightTab"> <textarea id="comments" class="input-field" style="height:50px;resize:vertical;" name="comment" placeholder="Enter your comment here..."></textarea> </div> </div> <button id="submit" type="submit">Submit</button> </form> </div> </main> </html>
package br.com.weather.brazil.view.viewmodel import android.app.Application import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import br.com.weather.brazil.data.dto.Weather import br.com.weather.brazil.data.repository.WeatherRepository import br.com.weather.brazil.utils.NetWorkResult import kotlinx.coroutines.launch class WeatherViewModel( private val weatherRepository: WeatherRepository, application: Application ) : BaseViewModel(application) { private val _responseWeather: MutableLiveData<NetWorkResult<Weather>> = MutableLiveData() val responseWeather: LiveData<NetWorkResult<Weather>> = _responseWeather fun getWeather(latitude: Double, longitude: Double) = viewModelScope.launch { weatherRepository.getWeather(context, latitude, longitude).collect { _responseWeather.value = it } } }
const APIURL = "https://api.github.com/users/"; const form = document.getElementById("form"); const search = document.getElementById("search"); const main = document.getElementById("main"); async function getData(username) { try { const { data } = await axios(APIURL + username); createCardUser(data); } catch (err) { if (err.response.status == 404) { createErrorCard("No user find"); } } } function createCardUser(user) { const cardHTML = ` <div class="card"> <div> <img src="${user.avatar_url}" alt="${user.img}" class="avatar" /> </div> <div class="user-info"> <h2>${user.name}</h2> <p>${user.bio}</p> <ul> <li>${user.followers} <strong>Followers</strong></li> <li>${user.following}<strong>Following</strong></li> <li>${user.public_repos} <strong>oRepos</strng></li> </ul> <div id="repos"></div> </div> </div> `; main.innerHTML = cardHTML; } function createErrorCard(msg) { const cardHTML = ` <div class="card"> <h1>${msg}</h1> </div> `; main.innerHTML = cardHTML; } form.addEventListener("submit", (e) => { e.preventDefault(); const user = search.value; if (user) { getData(user); search.value = ""; } });
<ion-header> <ion-navbar> <ion-title>Signup</ion-title> </ion-navbar> </ion-header> <ion-content padding> <form [formGroup]="formGroup" (ngSubmit)="signupUser(); $event.preventDefault()" > <ion-item> <ion-label stacked>Name*</ion-label> <ion-input formControlName="name" type="text"></ion-input> </ion-item> <p class="danger" *ngIf="formGroup.controls.name.dirty && formGroup.controls.name.errors" margin-left > Invalid value! </p> <ion-item> <ion-label stacked>Email</ion-label> <ion-input formControlName="email" type="text"></ion-input> </ion-item> <p class="danger" *ngIf="formGroup.controls.email.dirty && formGroup.controls.email.errors" margin-left > Invalid value! </p> <ion-list radio-group formControlName="type"> <ion-list-header> Client type </ion-list-header> <ion-item> <ion-label>Natural Person</ion-label> <ion-radio checked="false" value="1"></ion-radio> </ion-item> <ion-item> <ion-label>Legal Person</ion-label> <ion-radio checked="false" value="2"></ion-radio> </ion-item> </ion-list> <ion-item> <ion-label stacked>CPF or CNPJ</ion-label> <ion-input formControlName="cpfOrCnpj" type="text"></ion-input> </ion-item> <p class="danger" *ngIf="formGroup.controls.cpfOrCnpj.dirty && formGroup.controls.cpfOrCnpj.errors" margin-left > Invalid value! </p> <ion-item> <ion-label stacked>Password*</ion-label> <ion-input formControlName="password" type="password"></ion-input> </ion-item> <p class="danger" *ngIf="formGroup.controls.password.dirty && formGroup.controls.password.errors" margin-left > Invalid value! </p> <ion-item> <ion-label stacked>Public Place*</ion-label> <ion-input formControlName="publicPlace" type="text"></ion-input> </ion-item> <p class="danger" *ngIf="formGroup.controls.publicPlace.dirty && formGroup.controls.publicPlace.errors" margin-left > Invalid value! </p> <ion-item> <ion-label stacked>Number*</ion-label> <ion-input formControlName="number" type="text"></ion-input> </ion-item> <p class="danger" *ngIf="formGroup.controls.number.dirty && formGroup.controls.number.errors" margin-left > Invalid value! </p> <ion-item> <ion-label stacked>Complement</ion-label> <ion-input formControlName="complement" type="text"></ion-input> </ion-item> <ion-item> <ion-label stacked>District</ion-label> <ion-input formControlName="district" type="text"></ion-input> </ion-item> <ion-item> <ion-label stacked>CEP</ion-label> <ion-input formControlName="cep" type="text"></ion-input> </ion-item> <ion-item> <ion-label stacked>Phone 1*</ion-label> <ion-input formControlName="phone1" type="text"></ion-input> </ion-item> <p class="danger" *ngIf="formGroup.controls.phone1.dirty && formGroup.controls.phone1.errors" margin-left > Invalid value! </p> <ion-item> <ion-label stacked>Phone 2</ion-label> <ion-input formControlName="phone2" type="text"></ion-input> </ion-item> <ion-item> <ion-label stacked>Phone 3</ion-label> <ion-input formControlName="phone3" type="text"></ion-input> </ion-item> <ion-item> <ion-label stacked>State*</ion-label> <ion-select formControlName="stateId" (ionChange)="updateCities()"> <ion-option *ngFor="let state of states; first as f" [value]="state.id" [selected]="f" >{{state.name}}</ion-option > </ion-select> </ion-item> <ion-item> <ion-label stacked>City*</ion-label> <ion-select formControlName="cityId"> <ion-option *ngFor="let city of cities" [value]="city.id" >{{city.name}}</ion-option > </ion-select> </ion-item> <button ion-button block type="submit" [disabled]="formGroup.invalid"> Create account </button> </form> </ion-content>
<template> <div> <el-dialog :visible="true" :width="windowWidth < 768 ? 'calc(100% - 24px)' : '80%'" :title="id ? '费用登记-edit' : 'new-费用登记'" top="10vh" @close="close" > <div> <ExpenseRecordEdit ref="expenseRecordEdit" :id="id" @loadingChange="loadingChange" /> </div> <div slot="footer" class="dialog-footer"> <el-button v-loading="loading" size="mini" @click="resetData">重置</el-button> <el-button v-loading="loading" type="primary" size="mini" @click="save">保存</el-button> </div> </el-dialog> </div> </template> <script> import ExpenseRecordEdit from './../../../components/entity/expense-record/ExpenseRecordEdit' export default { name: 'ExpenseRecordEditPopup', components: { ExpenseRecordEdit }, props: { id: { type: String | Number, default: null } }, data() { return { loading: false } }, computed: { windowWidth() { return this.$store.getters.width } }, created() { }, methods: { close() { this.$emit('close') }, async save() { const formData = await this.$refs.expenseRecordEdit.save() this.$emit('update', formData) }, resetData() { this.$refs.expenseRecordEdit.resetData() }, loadingChange(val) { this.loading = val } } } </script> <style rel="stylesheet/scss" lang="scss" scoped> </style>
// This program was cloned from: https://github.com/RonnyA/nd-120 // License: MIT License module FIFO_testbench; // Parameters parameter DEPTH = 13; // Signals reg rst; reg wr_en; reg rd_en; reg [7:0] data_in; wire [7:0] data_out; wire full; wire empty; // Instantiate the FIFO module FIFO_8BIT #( .DEPTH(DEPTH) ) fifo_inst ( .rst(rst), .wr_en(wr_en), .rd_en(rd_en), .data_in(data_in), .data_out(data_out), .full(full), .empty(empty) ); // Test procedure initial begin $dumpfile("fifo_tb.vcd"); $dumpvars(0, FIFO_testbench); // Initialize signals rst = 1; wr_en = 0; rd_en = 0; data_in = 8'b0; // Apply reset #10 rst = 0; // Write some data into the FIFO #10 data_in = 8'hA5; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'h5A; wr_en = 1; #10 wr_en = 0; // Reset the FIFO #10 rst = 1; // Clear reset signal #10 rst = 0; // Write some more data into the FIFO #10 data_in = 8'hB5; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'h6B; wr_en = 1; #10 wr_en = 0; // Read the data back from the FIFO #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; // Check the full and empty flags #10 $display("Full: %b, Empty: %b", full, empty); // Overflow the FIFO // Write some more data into the FIFO #10 data_in = 8'hF0; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hF1; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hF2; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hF3; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hF4; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hF5; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hF6; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hF7; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hF8; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hF9; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hFA; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hFB; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hFC; wr_en = 1; #10 wr_en = 0; #10 data_in = 8'hFD; wr_en = 1; #10 wr_en = 0; // Check the full and empty flags #10 $display("Full: %b, Empty: %b", full, empty); // Read the data back from the FIFO #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; #10 rd_en = 1; #10 rd_en = 0; // Check the full and empty flags #10 $display("Full: %b, Empty: %b", full, empty); // End of test #10 $finish; end endmodule
/** Title Login.component.ts Author: Professor Krasso Modified By: Manel Phiseme Date Jan 22, 2023 Description login component for NodeBucket app */ // imported statements import { ConfirmDialogComponent } from 'src/app/shared/confirm-dialog/confirm-dialog.component'; import { Component, OnInit } from '@angular/core'; import { TaskService } from 'src/app/shared/services/task.service'; import { CookieService} from 'ngx-cookie-service'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; import {Employee} from '../../shared/models/employee.interface'; import {Item} from '../../shared/models/item.interface'; import {MatDialog} from '@angular/material/dialog'; import {DialogData} from '../../shared/models/dialog-data.interface'; import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { //Declare variables and assignment them to //various interfaces employee: Employee; todo: Item[]; done: Item[]; empId: number; dialogData: DialogData; //This set the requirement for the task inputs taskForm: FormGroup = this.fb.group({ task: [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(35)])] }) constructor(private taskService: TaskService, private cookieService: CookieService, private fb: FormBuilder, private dialog: MatDialog) { this.employee = {} as Employee; this.dialogData = {} as DialogData; this.todo = []; this.done = []; //this assign user id saved in browser cookie to empId this.empId = parseInt(this.cookieService.get('session_user'), 10); //this code use id stored in empID //to find an employee and it's todo and done tasks this.taskService.findAllTasks(this.empId).subscribe({ next: (res:any)=> { this.employee =res; console.log('Response from the findAllTasks service call') console.log(this.employee) }, error: (e:any) => { console.log(e.message); }, complete: () => { this.todo=this.employee.todo; this.done = this.employee.done; console.log('onComplete() method from the home.component.ts file, findAllTasks() service call.') console.log(this.todo); console.log(this.done); } }) } ngOnInit(): void { } //this using the employee id and taskform requirments //to create new tasks createTask(){ /** * variable newTask store task entered from the form */ const newTask = this.taskForm.controls['task'].value; /** * This code check if there's issue with empID and inputed task * before creating it. */ this.taskService.createTask(this.empId, newTask).subscribe({ next: (res:any) => { this.employee = res; console.log('--This is the response from the createTask service call.') console.log(res); }, error: (e:any) =>{ console.log(e.message); }, complete: () => { this.todo = this.employee.todo; this.done = this.employee.done; console.log('--onComplete method from the home.component.ts file, createTask() service call--') console.log(this.todo); console.log(this.done); this.taskForm.controls['task'].setErrors({'incorrect': false}); } }) } /** * THis function delete tasks */ deleteTask(taskId: string){ /** * dialog message to double check with user if they want to delete * tasks */ this.dialogData.header = 'Delete Record Dialog'; this.dialogData.content = 'Are you sure you want to delete this task?'; const dialogRef = this.dialog.open(ConfirmDialogComponent, { data: this.dialogData, disableClose: true }) /** * Action that need to be taken after dialog box is closed */ dialogRef.afterClosed().subscribe({ next: (result) => { console.log(result) /** * this delete task */ if(result === 'confirm'){ this.taskService.deleteTask(this.empId, taskId).subscribe({ next: (res) => { this.employee =res; }, error:(e) => { console.log(e) }, complete: () => { this.todo = this.employee.todo; this.done = this.employee.done; } }) } } }) } /** * THis allow the drag of tasks in the same column up and down or * To another column back and forth */ drop(event: CdkDragDrop<any[]>){ if (event.previousContainer === event.container){ moveItemInArray(event.container.data, event.previousIndex, event.currentIndex); console.log('Item reordered in the same column') this.updateTaskList(this.empId, this.todo, this.done); }else { console.log('Item moved to the other column') transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex) this.updateTaskList(this.empId, this.todo, this.done); } } /** * This code list update the todo list and done list * check if there's any errors with the actions */ updateTaskList(empId: number, todo: Item[], done: Item[]){ // write the code to call the update API //write the code the call the update API this.taskService.updateTask(empId, todo, done).subscribe({ next: (res) => { this.employee =res; }, error: (e) => { console.log(e); }, complete: () => { this.todo = this.employee.todo; this.done = this.employee.done; } }) } }
/* Quinta-feira, 09/02/2023 Das 22:00:00 a 22:22:00 h+|- Duração: 22 minutos ø Array:Métodos Importantes */ const pilotos = ['Vettel', 'Alonso', 'Raikkonem', 'Massa'] pilotos.pop() // Massa quebrou o carro!!! console.log(pilotos)// ['Vettel', 'Alonso', 'Raikkonem' ] pilotos.push('Verstappen') // O push adiciona outro elemento console.log(pilotos) // ['Vettel', 'Alonso', 'Raikkonem', 'Verstappen' ] pilotos.shift() // Remove o primeiro da lista; console.log(pilotos) // ['Alonso', 'Raikkonem', 'Verstappen' ] pilotos.unshift('Hamilton') /// adiciona da primeira posição console.log(pilotos)// ['Hamilton',Alonso', 'Raikkonem', 'Verstappen' ] // splice pode adicionar e remover elementos // adicionar pilotos.splice(2, 0, 'Bottas', 'Massas') console.log(pilotos) // ['Hamilton' 'Alonso', 'Bottas', 'Massas', 'Raikkonem', 'Verstappen' ] // remover pilotos.splice(3, 1) // Massa quebrou :( console.log(pilotos) // ['Hamilton' 'Alonso', 'Bottas', 'Raikkonem', 'Verstappen' ] // Slice -> retorna um novo Array const algunsPilotos1 = pilotos.slice(2) console.log(algunsPilotos1) // ['Bottas', 'Raikkonem', 'Verstappen' ] const algunsPilotos2 = pilotos.slice(1, 4) console.log(algunsPilotos2) // ['Alonso', 'Bottas', 'Raikkonem' ]
<template> <div class="home-page"> <div class="intro text-left ml-3 mr-3"> <p> On April 15, 2021, Mayor Kenney released his <a class="text-link" href="https://www.phila.gov/documents/mayor-kenneys-fiscal-year-2022-budget/" target="blank_" >budget proposal</a > for fiscal year 2022 (FY22) as part of the City’s annual Five Year Financial Plan. While the COVID-19 pandemic is still impacting the City’s finances, the budget proposal includes an overall increase in spending due to an estimated $1.4 billion in federal funding the City is set to receive as part of the American Rescue Plan. Without this federal funding, the City was once again facing a <a class="text-link" target="blank_" href="https://controller.phila.gov/philadelphia-audits/covid19-fiscal-impact-mar-2021/" >large revenue shortfall</a > that would have necessitated significant spending reductions. These cuts would have been in addition to those enacted as part of last year's budget, when the City's <a class="text-link" target="blank_" href="https://controller.phila.gov/philadelphia-audits/interactive-fy21-budget/" >FY21 budget</a > decreased by more than 4 percent as revenues declined as a result of the pandemic's impact on the local economy. </p> <p> With the help of the additional federal funding, the Mayor's budget proposal restores many, but not all, of the pandemic-related spending cuts. To better understand these changes, the City Controller’s Office is releasing a tool to visualize the major changes in the newly released budget relative to budgets from previous years. The tool is intended to serve as a resource for policymakers and Philadelphians alike, bringing necessary transparency to the City’s budgeting process. </p> <h2 class="mb-3">About this tool</h2> <p> The visualization includes budgeted spending data for the <a class="text-link" target="blank_" href="https://www.phila.gov/media/20210414133527/FY22-Budget-in-Brief-Proposed-FINAL.pdf" ><b>FY22 Proposed Budget</b></a >. Users can explore the new budget proposal by comparing to the adopted budgets from the past two fiscal years: </p> <ul class="indented"> <li> <a class="text-link" target="blank_" href="https://www.phila.gov/media/20210709120156/budget-in-brief-FY2021-approved.pdf" ><b>The FY21 Adopted Budget</b></a >: Adopted by City Council in June 2020, this budget includes spending cuts due to the impact of the COVID-19 pandemic; and </li> <li> <a class="text-link" target="blank_" href="https://www.phila.gov/media/20201020113701/budget-in-brief-FY2020-approved.pdf" ><b>The FY20 Adopted Budget</b></a >: Adopted by City Council in June 2019, this budget is the best representation of City spending prior to the COVID-19 pandemic. </li> </ul> <p> Spending changes are broken down by City department as well as the "major class" associated with each type of spending. The City uses seven major classes to classify spending: </p> <ul class="indented"> <li><b>Personal Services</b>: Payroll for City employees;</li> <li> <b>Purchase of Services</b>: Spending on contracts and leases with outside vendors, which includes spending on professional services; </li> <li> <b>Materials/Equip.</b>: Spending on materials, equipment, and other supplies needed by City departments; </li> <li> <b>Debt Service</b>: Fixed payments on previously-issued City debt obligations; </li> <li> <b>Contrib./Indemnities</b>: Spending on educational and nonprofit contributions as well as indemnities (lawsuits against the City). For example, this class includes the City's annual contributions to the School District and Community College of Philadelphia; and </li> <li> <b>Advances & Misc.</b>: In addition to miscellaneous spending, this class includes funding held in reserve to prepare for future recessions or unanticipated expenditures. </li> </ul> <p> In addition to viewing all changes at once, users can group the changes according to department, major class, or spending category. The spending category is a broad label based on the primary function of a department, such as Public Safety; Education; and General Government. Budgeted spending items that are outside the main function of a department may not be reflected in these spending categories. For example, spending on the Philadelphia Cultural Fund was transferred to the Managing Director's Office, which is categorized as "General Government". </p> </div> </div> </template> <script> export default { name: "Home" }; </script> <style scoped> .intro { border-bottom: 2px solid #deedfc; margin-bottom: 40px; } .intro p { text-align: left; } .intro li { text-align: left; } .indented { margin-left: 5rem; } li { margin-bottom: 5px; } @media screen and (max-width: 768px) { .indented { margin-left: 2rem; } } </style>
import { useEffect, useState } from "react"; import { axiosReq } from "../api/axiosDefaults"; import { useLocation } from "react-router-dom"; import { useCurrentUser } from "../contexts/CurrentUserContext"; const useFetchWishlist = (props) => { /** * The useFetchWishlist hook is a custom hook that fetches the wishlist data from the API. * @returns {Array} - The listing id. * @returns {Function} - A function to set the listing id state. * @returns {Number} - The wishlist id. * @returns {Function} - A function to set the wishlist id state. * @returns {String} - The pathname from the location object. * @returns {Boolean} - A boolean indicating whether the current user is the owner of the listing. * @returns {Object} - The current user data. * @returns {Boolean} - A boolean indicating whether the listing has been added to the wishlist. * @returns {Function} - A function to set the added to list state. */ const currentUser = useCurrentUser(); const is_owner = currentUser?.username === props.owner; const { pathname } = useLocation(); const [listingId, setListingId] = useState([]); const [wishlistId, setWishlistId] = useState(null); const [addedToList, setAddedToList] = useState(null); const [mounted, setMounted] = useState(true); useEffect(() => { // let mounted = true; // Fetch the wishlist from the API. const fetchWishlist = async () => { try { const { data } = await axiosReq.get(`/wishlist/`); // Map through the wishlist data and return the listings that match the current user's username. const wishlist = data.results.map( (result) => result.owner === currentUser?.username && result.listings ); // Find the wishlist id that matches the current user's username and the listing id. const wishlistId = data.results.find( (result) => result.listings === props.id && result.owner === currentUser?.username ); if (mounted) { // If the wishlist id exists, set the wishlist id state. if (wishlistId) { setWishlistId(wishlistId?.id); } // If the wishlist id exists and the owner matches the current user's username, set the added to list state to true. if (wishlistId && wishlistId.owner === currentUser?.username) { setAddedToList(true); } setListingId(wishlist); } } catch (err) { // console.log(err); } }; fetchWishlist(); return () => { setMounted(false); }; }, [ pathname, is_owner, currentUser?.username, props.id, addedToList, mounted, ]); return { listingId, setListingId, wishlistId, setWishlistId, pathname, is_owner, currentUser, addedToList, setAddedToList, }; }; export default useFetchWishlist;
#include <iostream> #include <string> using namespace std; struct lcs { int length; int path; // left = 001, up = 010, left-up = 100 lcs() : length(0), path(0) { } lcs(int length, int path) : length(length), path(path) { } }; lcs** LCS(string str1, string str2) { lcs** table = new lcs * [str1.size() + 1]; for (int i = 0; i <= str1.size(); i++) { table[i] = new lcs[str2.size() + 1]; } for (int i = 1; i <= str1.size(); i++) { for (int j = 1; j <= str2.size(); j++) { if (str1[i - 1] == str2[j - 1]) { table[i][j].length = table[i - 1][j - 1].length + 1; table[i][j].path = 0b100; } else if (table[i - 1][j].length >= table[i][j - 1].length) { table[i][j].length = table[i - 1][j].length; table[i][j].path = 0b010; } else { table[i][j].length = table[i][j - 1].length; table[i][j].path = 0b001; } } } return table; } int LCS_length(lcs** table, int m, int n) { return table[m][n].length; } int main() { string str1, str2; cin >> str1 >> str2; lcs** table = LCS(str1, str2); cout << LCS_length(table, str1.size(), str2.size()) << "\n"; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var arr = [2,3,4]; // 위 array에 있는 data를 전부 변수에 담아보자, 쉽게 var [a,b,c] = [2,3,4]; console.log(a); console.log(b); console.log(c); // cf) // var [a,b,c] = arr; --> 이렇게 해도 동일값 출력 </script> <script> // array destructuring 할때 몇개를 빼먹는다면? var arr2 = [2,3]; var [d,e,f = 999] = [2]; // (f = 999) --> data가 안 들어올 경우의 default 변수값 지정 console.log(d); // 2 console.log(e); // undefined console.log(f); // 999 </script> <script> // object에서도 destructuring 문법 사용 가능 var obj = {name : "Kim", age : 30} // object안의 데이터("Kim", 30)들을 뽑아 변수에 담아보자 // cf) name과 age는 데이터가 아니라 '데이터의 이름'이다. // 모양만 맞춰주면 된다. var {name, age = 31} = {name : "Kim", age : 30}; // (age = 31) --> age 변수의 기본값 지정 가능 console.log(name); console.log(age); /* array와 다르게 objcet에서는 위치를 보장해주지 않는다. 즉, var {name, age} = {name : "Kim", age : 30} 이렇게 썼다고 해서 (name = "Kim", age = 30)이라는 값으로 무조건 매칭되는게 아니라는 것이다. 따라서 원하는 변수에 원하는 값을 정확하게 매칭하고 싶으면 '변수명을 key 명과 동일하게 사용해야한다.' 즉, 위치를 맞추는게 아니라 '이름'을 맞춘다고 생각하고 destructuring 문법을 사용하면 된다. */ // cf) // var {name, age} = obj; --> 이렇게 해도 동일값 출력 </script> <script> // object의 key명과 동일한 이름을 변수명으로 사용하기 싫을때(변수의 이름 바꾸기) var obj2 = {name : "Park", age2 : 29} // 나는 (name : "Park")이라는 값을 변수에 저장해서 사용하고 싶지만 // 변수명을 name으로 하기 싫을 때 아래와 같이 변수명을 지정하면 된다. var {name : apple = "Choi", age2 = 999} = {name : "Park", age2 : 29}; // (name : apple = "Choi") --> apple 변수에 default 값 지정 console.log(apple); console.log(age2); var {name : a, age : b} = {name : "Won", age : 35} ; console.log(a); console.log(b); </script> <script> // 반대 : 변수들을 object에 집어넣고 싶은 경우 var name3 = "Kim"; var age3 = 30; // 위의 변수들을 object에 집어넣고 싶으면 어떻게 해야할까? var obj3 = {name3, age3}; // {name3, age3}가 {name3 : name3, age3 : age3}의 일종의 약자라고 생각하면 된다. // object의 key & value 명이 동일하면 위와 같이 줄여쓸 수 있다. // React, vue 같은 곳에서 쓰인다. console.log(obj3); // {name3: 'Kim', age3: 30} </script> <script> // 함수 parameter 변수에서도 destructuring 문법 사용 가능 // 아래 object의 데이터를 argument로 만들고 싶다.(obj4의 name과 age를 argument로 집어넣고 싶다.) var obj4 = {name4 : "Jung", age4 : 33}; function func1({name4, age4}) { // name4와 age4를 parameter로 받는다는 의미 console.log(name4); console.log(age4); } // 함수의 parameter도 변수를 만드는 것과 동일하다고 생각하면 된다. // {name4, age4}는 2개의 변수를 생성한 것과 동일하다. // func1({name4 : "Jung", age4 : 33}) : 그 변수에 각각 "Jung"과 33을 담는 것이다. // 아래 2줄의 결과는 동일하다. func1(obj4); func1({name4 : "Jung", age4 : 33}); </script> <script> // array도 동일하게 적용가능 var testArr = [1,2]; function func2([x, y]) { console.log(x); console.log(y); } // 아래 2줄의 결과는 동일하다. func2(testArr); func2([1,2]); </script> <script> // a와 address와 number라는 변수는 각각 무슨 값을 가지고 있을까? var [number, address] = [ 30, 'seoul' ]; console.log(number); console.log(address); console.log({ address, number }); // {address: 'seoul', number: 30} var {address : a , number = 20 } = { address, number }; console.log(number); // 30 console.log(address); // 'seoul' console.log(a); // 'seoul' </script> <script> // Object에서 데이터를 뽑아서 변수를 만들자 // 키, 몸무게, 상의사이즈, 하의사이즈 정보를 각각 뽑아서 4개의 변수를 만들고 싶다. // * 데이터가 얼마나 복잡하든간에 '좌우 형태를 똑같이 맞추면' destructuring 문법으로 변수를 만들 수 있다. let bodyInfo = { body: { height: 190, weight: 70 }, size: ["상의 Large", "바지 30인치"] }; // 아래의 코드에서 body, size는 key의 명(데이터 명)이지 data가 아니다. // 따라서 따로 console.log()를 이용해 출력할 수도 없다. let { body: { height, weight }, size: [상의, 하의] } = bodyInfo; console.log(height); console.log(weight); console.log(상의); console.log(하의); </script> </body> </html>
import { useState } from 'react'; import s from './Searchbar.module.css'; import { toast } from 'react-toastify'; function Searchbar({ onSubmit }) { const [searchQuery, setSearchQuery] = useState(''); const handleQueryChange = event => { setSearchQuery(event.currentTarget.value.toLowerCase()); }; const handleSubmit = event => { event.preventDefault(); if (searchQuery.trim() === '') { toast.info('Enter your query for searching'); return; } onSubmit(searchQuery); setSearchQuery(''); }; return ( <header className={s.searchbar}> <form className={s.form} onSubmit={handleSubmit}> <button type="submit" className={s.button}> <span className={s.label}>Search</span> </button> <input className={s.input} type="text" autoComplete="off" autoFocus placeholder="Search images and photos" value={searchQuery} onChange={handleQueryChange} /> </form> </header> ); } export default Searchbar;
import R from "ramda"; import React, {Component, PropTypes} from "react"; import withRouter from "react-router/lib/withRouter"; import Helpers from "../../helpers/index"; import Expenses from "./view"; class ExpensesContainer extends Component { constructor (props) { super(props); this.total = 0; this.state = { entries: [], loading: false, page: 0, }; this.onClickExpenseEdit = this.onClickExpenseEdit.bind(this); this.onClickExpenseRemove = this.onClickExpenseRemove.bind(this); this.onEnterWaypoint = this.onEnterWaypoint.bind(this); this.loadDataSuccessCb = this.loadDataSuccessCb.bind(this); this.loadDataFailureCb = this.loadDataFailureCb.bind(this); } componentDidMount () { Helpers.Utils.redirectToLoginIfTokenExpired(this.props.router); this.loadData(this.state.page); } getOffset(page, perPage, total) { let offset = page * perPage; if (page < 0) { return 0; } if (offset >= total) { return this.total; } if (page >= 0 && offset < this.total) { return offset; } } loadData (page) { Helpers.API.getExpenseEntries(Helpers.Constants.perPage, page) .then(response => Helpers.API.successHandler(response, this.props.router, this.loadDataSuccessCb)) .catch(error => Helpers.API.errorHandler(error, this.props.router, this.loadDataFailureCb)); } loadDataSuccessCb (response) { this.total = response.total; this.setState({ entries: R.concat(this.state.entries, response.data), loading: false, }); } loadDataFailureCb () { this.setState({loading: false}); } onEnterWaypoint() { if (this.state.loading) return; this.setState({loading: true}); let page = this.state.page; if (this.getOffset(page, Helpers.Constants.perPage, this.total) < this.total) { this.setState({page: page + 1}); this.loadData(page + 1); } else { this.setState({loading: false}); } } onClickExpenseEdit (expenseId) { this.props.router.push(`edit-entry/${expenseId}`); } onClickExpenseRemove (expenseId) { Helpers.API.removeExpenseEntry(expenseId) .then(response => { Helpers.Utils.redirectToLoginIfTokenExpired(this.props.router); if (response.success) { const index = R.findIndex(expense => expense._id == expenseId, this.state.entries); let entries = this.state.entries; entries = R.remove(index, 1, entries); this.setState({entries}); } }) .catch((error) => { console.log(error); // eslint-disable-line }); } render () { return ( <Expenses entries={this.state.entries} isLoading={this.state.loading} showWaypoint={this.total > this.getOffset(this.state.page, Helpers.Constants.perPage, this.total)} enterWaypoint={this.onEnterWaypoint} updateExpenseEntry={this.onClickExpenseEdit} removeExpenseEntry={this.onClickExpenseRemove} /> ); } } ExpensesContainer.propTypes = { router: PropTypes.object, }; export default withRouter(ExpensesContainer);
import 'package:anime_app/model/popular_movies_response_model.dart'; import 'package:anime_app/model/recent_anime_response_model.dart'; import 'package:anime_app/services/rest_service.dart'; import 'package:flutter/material.dart'; import '../model/movies_trending_response_model.dart'; import '../model/popular_anime_response_model.dart'; import '../model/popular_people_response_model.dart'; import '../model/popular_tvshows_response_model.dart'; class DashboardViewModel extends ChangeNotifier { // List<PopularDataModel> popularDataList = []; List<RecentDataModel> recentDataList = []; List<PopularMoviesData> popularMovieList = []; List<PopularTVShowsData> popularTVShowsList = []; List<PopularPeopleData> popularPeopleList = []; List<TrendingData> moviesTrendingList = []; int currentIndex = 0; List<AnimeDetails> animePopularDataList = []; void oninit() { getRecentData(); getMoviesData(); getPeoplesData(); getTVShowsData(); // getPopularData(); // getYouMightLike(); getMoviesTrendingData(); getAnimePopularData(); } void getMoviesData() async { popularMovieList.clear(); var result = await RestService.popularMovies(); for (int i = 0; i < result.results.length; i++) { popularMovieList.add(result.results[i]); } notifyListeners(); } void getMoviesTrendingData() async { moviesTrendingList.clear(); var result = await RestService.moviesTrendingData(); for (int i = 0; i < result.results.length; i++) { moviesTrendingList.add(result.results[i]); } notifyListeners(); } void getTVShowsData() async { popularTVShowsList.clear(); var result = await RestService.popularTVShows(); for (int i = 0; i < result.results.length; i++) { popularTVShowsList.add(result.results[i]); } notifyListeners(); } void getPeoplesData() async { popularPeopleList.clear(); var result = await RestService.popularPeoples(); for (int i = 0; i < result.results.length; i++) { popularPeopleList.add(result.results[i]); } notifyListeners(); } // void getPopularData() async { // popularDataList.clear(); // var result = await RestService.popularAnime(); // for (int i = 0; i < result.results.length; i++) { // popularDataList.add(result.results[i]); // } // notifyListeners(); // } void getRecentData() async { recentDataList.clear(); var result = await RestService.recentAnime(); for (int i = 0; i < result.results.length; i++) { recentDataList.add(result.results[i]); } notifyListeners(); } // void getYouMightLike() async { // var result = await RestService.youMigthLike(); // youMigthLike = result; // notifyListeners(); // } void getAnimePopularData() async { var result = await RestService.animePopular(); animePopularDataList = result.results; notifyListeners(); } }
/* The ability to combine multiple joins in a single query is a powerful feature of SQL, e.g: SELECT * FROM left_table INNER JOIN right_table ON left_table.id = right_table.id INNER JOIN another_table ON left_table.id = another_table.id; As you can see here it becomes tedious to continually write long table names in joins. This is when it becomes useful to alias each table using the first letter of its name (e.g. countries AS c)! It is standard practice to alias in this way and, if you choose to alias tables or are asked to specifically for an exercise in this course, you should follow this protocol. Now, for each country, you want to get the country name, its region, the fertility rate, and the unemployment rate for both 2010 and 2015. Note that results should work throughout this course with or without table aliasing unless specified differently. */ SELECT c.cde, name, religion, e.year, fertility_rate, unemployemnt_rate FROM countries AS c INNER JOIN populations AS p ON c.code = p.country_code INNER JOIN economies AS e ON c.code = e.code AND e.year = p.year;
/* * ADC_interface.h * * Created on: Oct 23, 2023 * Author: zashr */ #ifndef MCAL_ADC_ADC_INTERFACE_H_ #define MCAL_ADC_ADC_INTERFACE_H_ #include "../../LIB/STD_TYPES.h" /******************************************************************************* * Definitions * *******************************************************************************/ #define ADC_MAXIMUM_VALUE 1023 #define ADC_REF_VOLT_VALUE 5 /************ ADMUX *************/ enum ADMUXRef { AFREF = 0, AVCC = 1, Internal = 3, }; enum ADMUXAdj { LeftAdj = 1, RightAdj = 0, }; enum ADMUXChannel { SingleADC0 = 0, SingleADC1 = 1, SingleADC2 = 2, SingleADC3 = 3, SingleADC4 = 4, SingleADC5 = 5, SingleADC6 = 6, SingleADC7 = 7, PosADC0_10x = 8, PosADC1_10x = 9, //To Be Continued .... :) }; /************ ADCSRA *************/ enum ADCSRAControlBits { ADEN = 7, ADSC = 6, ADATE = 5, ADIF = 4, ADIE = 3, }; enum ADCSRAPre{ Prescaler_2 = 0, Prescaler_4 = 2, Prescaler_8 = 3, Prescaler_16 = 4, Prescaler_32 = 5, Prescaler_64 = 6, Prescaler_128 = 7, }; /************ SFIOR *************/ enum SFIORControlBits { Free = 0, Analog, ExtInt0, Timer0Comp, Timer0Ovr, Timer1Comp, Timer1Ovr, TImer1Cap, }; /* This enum is for function validation, holds the possible states of the ADC */ enum ADC_enuState { ADC_enuNormalState= 0, ADC_enuNullPointerException, }ADC_enuState; // Struct that holds all the enums typedef struct{ enum ADMUXRef ref; enum ADMUXAdj adj; enum ADMUXChannel channel; enum ADCSRAPre adcsraPre; enum SFIORControlBits sfiorControl; }ADC_config; /* Initialization Method*/ void ADC_Init(const ADC_config *config); /* Enables ADC interrupt and takes two arguments: channel number and a pointer to a function that handles the ADC reading. This function configures the ADC to use the specified channel and enables the ADC interrupt. When the ADC conversion is complete, the provided callback function will be called with the ADC reading as an argument. */ void ADC_getDigitalValueAsynchCallBack(u8 channel_num,void (*localPtr)(u16 value)); /* Get ADC value asynchronously with a timeout of 50ms. This function takes the channel number as an argument and returns the ADC reading after pooling for the specified channel. If the ADC conversion does not complete within 50ms, it returns a default or error value. */ u16 ADC_getDigitalValueSynchNonBlocking (u8 channel_num); #endif /* MCAL_ADC_ADC_INTERFACE_H_ */
<template> <v-dialog v-model="dialog" width="535px" persistent> <v-card> <v-card-title style="color: white" class="text-h5 primary" >Return Borrowed Item - {{ form.item_info.name }} <v-spacer></v-spacer> <v-icon color="white" @click="$emit('closeReturnDialog')" >mdi-close</v-icon ></v-card-title > <v-form ref="form" @submit.prevent="returnBorrowedItem"> <v-card-text> <v-alert dense outlined type="error" class="my-3" v-if="input_error"> Invalid quantity please insure that your input data is correct. </v-alert> <h3 class="my-3"> Return Item {{ form.item_info.name }}: {{ returnItemBalance }} </h3> <v-text-field v-model.number="return_form.quantity" solo label="Quantity" clearable hide-details ></v-text-field> </v-card-text> <v-col class="d-flex justify-end" cols="12"> <v-btn type="submit" style="float: right" color="primary" hide-details :disabled="input_error" ><v-icon class="mr-2">mdi-keyboard-return</v-icon> Return</v-btn > </v-col> </v-form> </v-card> </v-dialog> </template> <script> export default { props: { form: { type: Object, default: () => {}, }, returnDialog: { type: Boolean, default: false, }, }, computed: { returnItemBalance() { const balance = this.form.quantity - this.return_form.quantity if (balance >= 0) { return balance } else { return 0 } }, }, data() { return { input_error: false, dialog: false, return_form: { id: null, item_id: null, quantity: 0, }, } }, methods: { returnBorrowedItem() { this.$axios .$post(`return_item/${this.return_form.id}`, this.return_form) .then((response) => { this.$store.commit('SET_SNACKBAR', { snackbar: { status: true, text: 'Item return successfully!', timeout: 5000, color: 'primary', }, }) this.$store.dispatch('callGetCustomers') this.$emit('closeReturnDialog') }) .catch((error) => { this.$store.commit('SET_SNACKBAR', { snackbar: { status: true, text: error.response.data.message, timeout: 5000, color: 'error', }, }) }) .finally(() => { setTimeout(this.$unSetSnackbar, 7000, this.$store) }) }, }, watch: { returnItemBalance(new_val) { const balance = this.form.quantity - this.return_form.quantity if (balance < 0) { this.input_error = true } else { this.input_error = false } }, 'return_form.quantity'(new_val, old_val) { if (new_val === '' || new_val <= 0 || new_val > this.form.quantity || new_val === null) { this.input_error = true } else { this.input_error = false } }, }, created() { this.dialog = this.returnDialog this.return_form.id = Number(this.form.id) this.return_form.item_id = Number(this.form.item_info.id) this.return_form.quantity = Number(this.form.quantity) }, } </script> <style scoped></style>
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Yet Another Pixel Dungeon * Copyright (C) 2015-2019 Considered Hamster * * No Name Yet Pixel Dungeon * Copyright (C) 2018-2019 RavenWolf * * 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 * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.ravenwolf.nnypdcn.items.scrolls; import com.ravenwolf.nnypdcn.actors.buffs.BuffActive; import com.ravenwolf.nnypdcn.actors.buffs.debuffs.Controlled; import com.ravenwolf.nnypdcn.actors.mobs.Wraith; import com.ravenwolf.nnypdcn.visuals.Assets; import com.ravenwolf.nnypdcn.visuals.effects.SpellSprite; import com.watabou.noosa.audio.Sample; import com.watabou.utils.Random; import java.util.ArrayList; public class ScrollOfRaiseDead extends Scroll { { name = "死灵卷轴"; shortName = "Ra"; spellSprite = SpellSprite.SCROLL_RAISEDEAD; spellColour = SpellSprite.COLOUR_DARK; icon=5; } @Override protected void doRead() { ArrayList<Wraith> summoned = Wraith.spawnAround( curUser.magicSkill() / 3, curUser.pos, 2/*Random.IntRange( 3, 4 )*/ ); for( Wraith w : summoned ){ //float duration = Random.Int( 16, 20 ) * ( 110 + curUser.magicSkill() ) / 100; float duration = Random.Int( 10, 16 ) * ( 110 + curUser.magicSkill() ) / 100; Controlled buff = BuffActive.add( w, Controlled.class, duration ); if( buff != null ){ buff.object = curUser.id(); } } Sample.INSTANCE.play(Assets.SND_DEATH); super.doRead(); } @Override public String desc() { return "卷轴下隐藏的邪恶法术允许阅读者与亡灵之物交流,赋予其召唤并控制亡灵的能力。不过要注意的是,它迟早会将獠牙对向自己的主人!" + "\n\n控制效果的持续时间取决于使用者的魔能属性"; } @Override public int price() { return isTypeKnown() ? 100 * quantity : super.price(); } }
@testable import MEGA import XCTest final class EmptyStateViewTests: XCTestCase { var emptyStateImage: UIImage? var emptyStateTitle: String? var emptyStateDescription: String? override func tearDown() { emptyStateImage = nil emptyStateTitle = nil emptyStateDescription = nil } private func validate(emptyStateView: EmptyStateView, image: UIImage, title: String, description: String, isButtonHidden: Bool) throws { emptyStateImage = try? XCTUnwrap(emptyStateView.imageView?.image) XCTAssertTrue(image == emptyStateImage) emptyStateTitle = try? XCTUnwrap(emptyStateView.titleLabel?.text) XCTAssertTrue(title == emptyStateTitle) emptyStateDescription = try? XCTUnwrap(emptyStateView.descriptionLabel?.text) XCTAssertTrue(description == emptyStateDescription) XCTAssertTrue(emptyStateView.button?.isHidden ?? false == isButtonHidden) } func testEmptyState_Favourites() throws { try? validate(emptyStateView: EmptyStateView.create(for: .favourites), image: Asset.Images.EmptyStates.favouritesEmptyState.image, title: Strings.Localizable.noFavourites, description: "", isButtonHidden: true) } func testEmptyState_Photos() { try? validate(emptyStateView: EmptyStateView.create(for: .photos), image: Asset.Images.Home.allPhotosEmptyState.image, title: Strings.Localizable.Home.Images.empty, description: "", isButtonHidden: true) } func testEmptyState_Timeline() { try? validate(emptyStateView: EmptyStateView.create(for: .timeline(image: Asset.Images.EmptyStates.cameraEmptyState.image, title: Strings.Localizable.cameraUploadsEnabled, description: "", buttonTitle: nil)), image: Asset.Images.EmptyStates.cameraEmptyState.image, title: Strings.Localizable.cameraUploadsEnabled, description: "", isButtonHidden: true) } func testEmptyState_Documents() { try? validate(emptyStateView: EmptyStateView.create(for: .documents), image: Asset.Images.Home.documentsEmptyState.image, title: Strings.Localizable.noDocumentsFound, description: "", isButtonHidden: true) } func testEmptyState_Audio() { try? validate(emptyStateView: EmptyStateView.create(for: .audio), image: Asset.Images.Home.audioEmptyState.image, title: Strings.Localizable.noAudioFilesFound, description: "", isButtonHidden: true) } func testEmptyState_Videos() { try? validate(emptyStateView: EmptyStateView.create(for: .videos), image: Asset.Images.Home.videoEmptyState.image, title: Strings.Localizable.noVideosFound, description: "", isButtonHidden: true) } func testEmptyState_Backups() { let isSearchActive = Bool.random() try? validate(emptyStateView: EmptyStateView.create(for: .backups(searchActive: isSearchActive)), image: isSearchActive ? Asset.Images.EmptyStates.searchEmptyState.image : Asset.Images.EmptyStates.folderEmptyState.image, title: isSearchActive ? Strings.Localizable.noResults : Strings.Localizable.Backups.Empty.State.message, description: isSearchActive ? "" : Strings.Localizable.Backups.Empty.State.description, isButtonHidden: true) } }
import {React , useEffect , useState} from 'react' import {Link} from 'react-router-dom' import {jwtDecode} from 'jwt-decode'; const StudentCourses = () => { const [Courses, setCourses] = useState(null); const [studentId, setStudentId] = useState(null); useEffect(() => { getCourses(); }, []); const getCourses = async () => { const token = localStorage.getItem('token'); try { const response = await fetch("http://localhost:8998/api/student/getCourses", { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, }); const data = await response.json(); setCourses(data); // console.log(data) } catch (error) { console.error('Error fetching teacher list:', data.message); } }; if(Courses == null){ return <h1> Loading </h1> } return( <div className="container mx-auto p-4"> <h1 className="text-3xl font-bold mb-4">Courses</h1> {Courses.map(course => ( <Link key={course._id} to={`/student/home/course/${course.CourseId}`} className="text-decoration-none" > <div className="bg-gray-100 p-4 rounded shadow mb-4 cursor-pointer"> <h1 className="text-xl font-semibold mb-2">CourseId: {course.CourseId}</h1> <p className="text-gray-700 rounded-2xl">CourseName: {course.CourseName}</p> </div> </Link> ))} </div> ) } export default StudentCourses
from rest_framework import serializers from .models import Customer, Invoice, Revenue, User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" class RevenueSerializer(serializers.ModelSerializer): class Meta: model = Revenue fields = "__all__" class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = "__all__" class InvoiceSerializer(serializers.ModelSerializer): class Meta: model = Invoice fields = ["id", "amount", "date", "status", "customer_id"] class InvoiceListSerializer(serializers.ModelSerializer): customer = CustomerSerializer(source="customer_id", read_only=True) class Meta: model = Invoice fields = ["id", "customer", "amount", "status", "date"]
--- import { Icon } from "astro-icon"; import HeroImage from "~/components/hero-image.astro"; import type { FooterLink } from "~/types"; const links: FooterLink[] = [ { url: "https://www.linkedin.com/in/alexandre-martinez31000", description: "Mon profil LinkedIn", icon: "mdi:linkedin", }, { url: "https://github.com/zerowww", description: "Mon profil Github", icon: "mdi:github", }, { url: "https://stackoverflow.com/users/10944302/zeroww", description: "Mon profil StackOverflow", icon: "mdi:stack-overflow", }, { url: "mailto: martinez.a.pro@gmail.com", description: "Mon adresse mail", icon: "mdi:alternate-email", }, ]; --- <footer class="relative flex items-center justify-center h-64"> <div class="absolute inset-0 overflow-hidden opacity-40"> <HeroImage /> </div> <ul class="relative grid grid-cols-2 gap-4 sm:grid-cols-4"> { links.map((link) => ( <li> <a class="flex items-center justify-center w-16 h-16 p-4 border-2 border-current rounded-full" href={link.url} > <span class="sr-only">{link.description}</span> <Icon class="h-full" name={link.icon} aria-hidden="true" /> </a> </li> )) } </ul> </footer>