text
stringlengths
184
4.48M
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Stripe Payment Simulation</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> <script src="https://js.stripe.com/v3/"></script> <style> .modal-header-success { background-color: #28a745; color: #fff; } .modal-header-failure { background-color: #dc3545; color: #fff; } </style> </head> <body> <div class="container"> <h2 class="mt-5 mb-4">Stripe Payment Simulation</h2> <form id="payment-form"> <div class="form-group"> <label for="card-element">Credit or debit card</label> <div id="card-element" class="form-control"> <!-- A Stripe Element will be inserted here. --> </div> <!-- Used to display form errors. --> <div id="card-errors" role="alert" class="invalid-feedback"></div> </div> <!-- Additional fields for address --> <div class="form-group"> <label for="name">Name</label> <input type="text" id="name" name="name" class="form-control" required> </div> <div class="form-group"> <label for="address">Address</label> <input type="text" id="address" name="address" class="form-control" required> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="city">City</label> <input type="text" id="city" name="city" class="form-control" required> </div> <div class="form-group col-md-6"> <label for="zip">ZIP</label> <input type="text" id="zip" name="zip" class="form-control" required> </div> </div> <!-- End of additional fields --> <button type="submit" class="btn btn-primary">Submit Payment</button> </form> </div> <!-- Success Modal --> <div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="successModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header modal-header-success"> <h5 class="modal-title" id="successModalLabel">Payment Successful</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p id="successMessage"></p> </div> </div> </div> </div> <!-- Failure Modal --> <div class="modal fade" id="failureModal" tabindex="-1" role="dialog" aria-labelledby="failureModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header modal-header-failure"> <h5 class="modal-title" id="failureModalLabel">Payment Failed</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p id="failureMessage"></p> </div> </div> </div> </div> <script> // Set your publishable key var stripe = Stripe('pk_test_KEY_XXXXXX'); var elements = stripe.elements(); // Create an instance of the card Element. var card = elements.create('card'); // Add an instance of the card Element into the `card-element` div. card.mount('#card-element'); // Handle form submission. var form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); stripe.createToken(card, { name: document.getElementById('name').value, address_line1: document.getElementById('address').value, address_city: document.getElementById('city').value, address_zip: document.getElementById('zip').value }).then(function(result) { if (result.error) { // Display failure modal document.getElementById('failureMessage').textContent = result.error.message; $('#failureModal').modal('show'); } else { // Display success modal document.getElementById('successMessage').textContent = 'Payment successful! Token: ' + result.token.id; $('#successModal').modal('show'); } }); }); </script> <!-- Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html>
import {Text, TouchableOpacity, TouchableOpacityProps, View } from "react-native" import {Feather} from "@expo/vector-icons" import colors from "tailwindcss/colors" interface Props extends TouchableOpacityProps { checked?: boolean; title: string; } export function CheckBox({title, checked = false, ...rest}: Props){ return ( <TouchableOpacity activeOpacity={0.7} className='flex-row mb-2 items-center ' {...rest}> { checked ? <View className="h-8 w-8 bg-green-500 rounded-lg items-center justify-center"> <Feather name="check" size={20} color={colors.white}/> </View> : <View className="h-8 w-8 bg-zinc-900 rounded-lg " /> } <Text className="text-white text-base ml-3 font-semibold"> {title} </Text> </TouchableOpacity> ) }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "ModularNavigationCharacter.h" #include "MainCharacter.generated.h" // DOCSONLY: namespace Character { /** Augments UE's character pawn, with additional functionality: jump whilst crouched, collect items. */ UCLASS() class REDCENTURYCOURIER_API AMainCharacter : public AModularNavigationCharacter// , public ICollectorInterface { GENERATED_BODY() public: AMainCharacter(const FObjectInitializer& ObjectInitializer); // UFUNCTION() // virtual bool Collect(TScriptInterface<ICollectableInterface> Collectable) override; // /** Delegate to trigger whenever an item (that possesses CollectableComponent) is collected by this actor. */ // UPROPERTY(BlueprintReadWrite, Category = "Main Character") // FOnCollection OnCollection; /** Health. */ UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Main Character") float Health; /** Maximum health. */ UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Main Character") float MaxHealth; /** Health Recovery rate. */ UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Main Character") float HealthRecovery; /** The time after walking off a ledge, in seconds, wherein the character will still be allowed to jump. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, meta=(ClampMin = 0, UIMin = 0), Category="Main Character") float CoyoteTime; /** A map of damage types, to the ratio of reduction to apply to the incoming damage (e.g. 0.2 means take 20% less damage). */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Main Character") TMap<TSubclassOf<UDamageType>, float> DamageResistances; /** @returns UPlayerController for this Game Character. */ UFUNCTION(BlueprintPure, Category = "Main Character") APlayerController* GetPlayerController() const; /** @returns whether the current movement input faces forwards */ UFUNCTION(BlueprintPure, Category = "Main Character") bool IsInputForwards(const float maxAngle = 45.f) const; virtual void OnMovementModeChanged(EMovementMode PrevMovementMode, uint8 PreviousCustomMode = 0) override; virtual void CheckJumpInput(float DeltaTime) override; virtual float TakeDamage(float DamageAmount, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, AActor* DamageCauser) override; // Replace Epic Games' implementation so that we can add rush time multi // ReSharper disable once CppHidingFunction float GetActorTimeDilation() const; // ReSharper disable once CppHidingFunction float GetActorTimeDilation(const UWorld& ActorWorld) const; protected: virtual void BeginPlay() override; virtual void TickActor(float DeltaTime, ELevelTick TickType, FActorTickFunction& ThisTickFunction) override; float CoyoteTimeRemaining; // Replace Epic Games' implementation so that we can add coyote time // ReSharper disable once CppHidingFunction bool JumpIsAllowedInternal() const; private: UFUNCTION() void TakeAnyDamage(AActor* DamagedActor, float Damage, const UDamageType* DamageType, AController* InstigatedBy, AActor* DamageCauser); }; // DOCSONLY: }
# -*- coding: utf-8 -*- # (c) 2018, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # # You should have received a copy of the GNU General Public License # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import re import collections from ansible import constants as C from ansible.plugins.action.normal import ActionModule as ActionBase from ansible.module_utils.network.common.utils import to_list from ansible.module_utils.six import iteritems, string_types from ansible.module_utils._text import to_text from ansible.errors import AnsibleError, AnsibleUndefinedVariable try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() MISSING_KEY_OPTIONS = frozenset(('warn', 'fail', 'ignore')) def warning(msg): if C.ACTION_WARNINGS: display.warning(msg) class ActionModule(ActionBase): def set_args(self): """ sets instance variables based on passed arguments """ self.source_dir = self._task.args.get('source_dir') if not os.path.isdir(self.source_dir): raise AnsibleError('%s does not appear to be a valid directory' % self.source_dir) self.exclude_files = self._task.args.get('exclude_files') self.include_files = self._task.args.get('include_files') self.private_vars = self._task.args.get('private_vars') or {} def run(self, tmp=None, task_vars=None): if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) self.set_args() variables = task_vars.copy() variables.update(self.private_vars) lines = list() include_files = self.included_files() for source in include_files: display.display('including file %s' % source) contents = self._loader.load_from_file(source) try: lines = self._process_template(contents, variables) except AnsibleError as exc: return {'failed': True, 'msg': to_text(exc)} return {'lines': lines, 'text': '\n'.join(lines), 'included_files': include_files} def _check_file(self, filename, matches): """ Checks the file against a list of matches If the filename is included as part of the list of matches, this method will return True. If it is not, then this method will return False :param filename: The filename to be matched :param matches: The list of matches to test against :returns: True if the filename should be ignored otherwise False """ if isinstance(matches, string_types): matches = [matches] if not isinstance(matches, list): raise AnsibleError("matches must be a valid list") for pattern in matches: if re.search(r'%s' % pattern, filename): return True return False def should_include(self, filename): if self.include_files: return self._check_file(filename, self.include_files) return True def should_exclude(self, filename): if self.exclude_files: return self._check_file(filename, self.exclude_files) return False def included_files(self): include_files = list() for filename in os.listdir(self.source_dir): filename = os.path.join(self.source_dir, filename) if not os.path.isfile(filename): continue elif self.should_exclude(os.path.basename(filename)): warning('excluding file %s' % filename) continue elif not self.should_include(os.path.basename(filename)): warning('skipping file %s' % filename) continue else: include_files.append(filename) return include_files def _process_template(self, contents, template_vars): lines = list() for item in contents: name = item.get('name') block = item.get('block') include = item.get('include') when = item.get('when') if include: if when is not None: conditional = "{%% if %s %%}True{%% else %%}False{%% endif %%}" if not self.template(conditional % when, template_vars, fail_on_undefined=False): display.vvvvv("include '%s' skipped due to conditional check failure" % name) continue lines.extend(self._process_include(item, template_vars)) elif block: loop = item.get('loop') loop_data = None loop_control = item.get('loop_control') or {'loop_var': 'item'} if loop: loop_data = self.template(loop, template_vars, fail_on_undefined=False, convert_bare=True) if not loop_data: warning("block '%s' skipped due to missing loop var '%s'" % (name, loop)) continue values = list() if isinstance(loop_data, collections.Mapping): for item_key, item_value in iteritems(loop_data): item_data = template_vars.copy() key = loop_control['loop_var'] item_data[key] = {'key': item_key, 'value': item_value} if when is not None: conditional = "{%% if %s %%}True{%% else %%}False{%% endif %%}" if not self.template(conditional % when, item_data, fail_on_undefined=False): display.vvvvv("block '%s' skipped due to conditional check failure" % name) continue for entry in block: if 'block' in entry or 'include' in entry: templated_values = self.build([entry], item_data) elif 'lines' not in entry: raise AnsibleError("missing required block entry `lines` in dict") else: templated_values = self._process_block(entry, item_data) if templated_values: values.extend(templated_values) elif isinstance(loop_data, collections.Iterable): for item_value in loop_data: item_data = template_vars.copy() key = loop_control['loop_var'] item_data[key] = item_value if when is not None: conditional = "{%% if %s %%}True{%% else %%}False{%% endif %%}" if not self.template(conditional % when, item_data, fail_on_undefined=False): display.vvvvv("block '%s' skipped due to conditional check failure" % name) continue for entry in block: if 'block' in entry or 'include' in entry: templated_values = self.build([entry], item_data) elif 'lines' not in entry: raise AnsibleError("missing required block entry `lines` in list") else: templated_values = self._process_block(entry, item_data) if templated_values: values.extend(templated_values) else: for entry in block: if when is not None: conditional = "{%% if %s %%}True{%% else %%}False{%% endif %%}" if not self.template(conditional % when, template_vars, fail_on_undefined=False): display.vvvvv("block '%s' skipped due to conditional check failure" % name) continue if 'block' in entry or 'include' in entry: templated_values = self.build([entry], template_vars) elif 'lines' not in entry: raise AnsibleError("missing required block entry `lines`") else: templated_values = self._process_block(entry, template_vars) if templated_values: values.extend(templated_values) if values: lines.extend(values) else: values = self._process_block(item, template_vars) if values: lines.extend(values) return lines def _template_items(self, block, data): name = block.get('name') items = to_list(block['lines']) required = block.get('required') join = block.get('join') join_delimiter = block.get('join_delimiter') or ' ' indent = block.get('indent') missing_key = block.get('missing_key') or 'warn' if missing_key not in MISSING_KEY_OPTIONS: raise AnsibleError('option missing_key expected one of %s, got %s' % (', '.join(MISSING_KEY_OPTIONS), missing_key)) fail_on_undefined = missing_key == 'fail' warn_on_missing_key = missing_key == 'warn' values = list() for item in items: templated_value = self.template(item, data, fail_on_undefined=fail_on_undefined) if templated_value: if '__omit_place_holder__' in templated_value: continue if isinstance(templated_value, string_types): values.append(templated_value) elif isinstance(templated_value, collections.Iterable): values.extend(templated_value) else: if required: raise AnsibleError("block '%s' is missing required key" % name) elif warn_on_missing_key: warning("line '%s' skipped due to missing key" % item) if join and values: values = [join_delimiter.join(values)] if indent: values = [(indent * ' ') + line.strip() for line in values] return values def _process_block(self, block, data): name = block.get('name') when = block.get('when') loop = block.get('loop') loop_data = None loop_control = block.get('loop_control') or {'loop_var': 'item'} values = list() if when is not None: conditional = "{%% if %s %%}True{%% else %%}False{%% endif %%}" if not self.template(conditional % when, data, fail_on_undefined=False): display.vvvv("block '%s' skipped due to conditional check failure" % name) return values if loop: loop_data = self.template(loop, data, fail_on_undefined=False, convert_bare=True) if not loop_data: warning("block '%s' skipped due to missing loop var '%s'" % (name, loop)) return values if isinstance(loop_data, collections.Mapping): for item_key, item_value in iteritems(loop_data): item_data = data.copy() key = loop_control['loop_var'] item_data[key] = {'key': item_key, 'value': item_value} templated_values = self._template_items(block, item_data) if templated_values: values.extend(templated_values) elif isinstance(loop_data, collections.Iterable): for item_value in loop_data: item_data = data.copy() key = loop_control['loop_var'] item_data[key] = item_value templated_values = self._template_items(block, item_data) if templated_values: values.extend(templated_values) else: values = self._template_items(block, data) return values def _process_include(self, item, variables): name = item.get('name') include = item['include'] src = self.template(include, variables) source = self._find_needle('templates', src) when = item.get('when') if when: conditional = "{%% if %s %%}True{%% else %%}False{%% endif %%}" if not self.template(conditional % when, variables, fail_on_undefined=False): display.vvvvv("include '%s' skipped due to conditional check failure" % name) return [] display.display('including file %s' % source) include_data = self._loader.load_from_file(source) template_data = item.copy() # replace include directive with block directive and contents of # included file. this will preserve other values such as loop, # loop_control, etc template_data.pop('include') template_data['block'] = include_data return self.build([template_data], variables) def template(self, value, data=None, fail_on_undefined=False, convert_bare=False): try: data = data or {} tmp_avail_vars = self._templar._available_variables self._templar.set_available_variables(data) res = self._templar.template(value, convert_bare=convert_bare) except AnsibleUndefinedVariable: if fail_on_undefined: raise res = None finally: self._templar.set_available_variables(tmp_avail_vars) return res
/** @type {{[language: string]: (URL | string)[]}} */ let _urls = {} let _language const _notImplemented = new Set() /** @type {Map<Element, string>} */ const _elementMap = new Map() async function registerDictionary(language, url) { if (!_urls[language]) _urls[language] = [] _urls[language].push(url) await updateAllElement(_urls[_language]) } async function unregisterDictionary(url) { for (const key in _urls) { const index = _urls[key].findIndex((value) => value === url) if (index !== -1) { _urls[key].splice(index, 1) break } } await updateAllElement(_urls[_language]) } function getDictionaries(language) { if (!_urls[language]) return [] return Promise.all(_urls[language].map( async (url) => (await fetch(url)).json() )) } async function init() { const res = await setLanguage(localStorage.getItem('language') || navigator.language) } async function updateAllElement(dictionaries) { for (const [element, i18nKey] of _elementMap.entries()) { element.textContent = await getTraduction(i18nKey, dictionaries) } } async function setLanguage(language) { const dictionaries = await getDictionaries(language) await updateAllElement(dictionaries) localStorage.setItem('language', language) _language = language } function warningForNotImplementedKeys(i18nKey) { if (_notImplemented.has(i18nKey) === false) { _notImplemented.add(i18nKey) const trad = (i18nKey[0]?.toUpperCase() + i18nKey.substring(1)).replaceAll('_', ' ') console.warn(`'${i18nKey}': \`${trad}\`,`) } } async function getTraduction(i18nKey, dictionaries) { const _dictionaries = dictionaries ?? await getDictionaries(_language) const constructor = i18nKey?.constructor if (constructor === String) { for (const dictionary of _dictionaries) { if (dictionary[i18nKey]) return dictionary[i18nKey] } warningForNotImplementedKeys(i18nKey) return i18nKey } else if (constructor === Array) { return (await Promise.all(i18nKey.map(s => getTraduction(s, _dictionaries)))).join(' ') } else { console.warn('i18n wrong use') } } async function register(htmlElement, str) { _elementMap.set(htmlElement, str) htmlElement.textContent = await getTraduction(str) return () => { unregisterDeep(htmlElement) } } function updateElement(element) { element.textContent = getTraduction(_elementMap.get(element)) } function unregisterDeep(element) { _elementMap.delete(element) for (const child of element.children) { unregisterDeep(child) } } async function reset() { for (const key in _urls) delete _urls[key] _language = undefined _notImplemented.clear() _elementMap.clear() await init() } await init() /** * @example * ```js * await i18n.init() * i18n.register(divElement, 'hello') // hello * await i18n.setLanguage('fr') // salut */ export const i18n = { reset, registerDictionary, unregisterDictionary, setLanguage, register, unregisterDeep, updateElement }
''' 이진탐색이라고 되어 있지만 이진탐색 트리를 몰라도 풀이가 가능하다 중위순회 1. 제일 왼쪽까지 이동 2. 숫자를 배치 3. 오른쪽으로 이동 ''' # D2 5176 이진탐색 def makeTree(n): global count # 배열이니까 배열크기 넘어가지 않도록 if n <= N: # 이게 없으면 에러! # 왼쪽노드는 현재 인덱스 * 2 makeTree(n * 2) # 더이상 못가면 값넣기 tree[n] = count # 값 넣었으면 증가시키기 count += 1 # 우측 노드는 현재 인덱스 *2 + 1 makeTree(n * 2 + 1) T = int(input()) for tc in range(1, T+1): N = int(input()) tree = [0 for i in range(N + 1)] #0번 노드는 사용하지 않으니! count = 1 makeTree(1) print('#{} {} {}'.format(tc, tree[1], tree[N // 2])) #교수님 풀이가 좀 더 직관적! T = int(input()) def inorder(now): if now >= len(graph): return global cnt inorder(now * 2) # 처리 graph[now] = cnt # <- 1~N cnt += 1 inorder(now * 2 + 1) for tc in range(T): N = int(input()) graph = [0] * (N + 1) # 0번은 사용하지 X <- 0에 아무리 곱해도 0 오오,,이거를 알았구만,,!! cnt = 1 inorder(1) print(f"#{tc + 1} {graph[1]} {graph[ N//2 ]}") ########### ''' <이진 탐색 트리(BST)> - 현재 노드 기준 왼쪽은 나보다 작음, 오른쪽은 나보다 큼(로그N) 한쪽으로만 계속 가는 최악의 경우가 있음,, 이렇게 되면 탐색의 시간을 줄이기 위해서 하는건데! 의미가 없어지게 됨!(N) 이것을 이진 탐색트리로 바꾸는 거 있는 데 AVL트리(나 배웠던거!) '''
import type { Meta, StoryObj } from "@storybook/react"; import InputLabel from "./index"; import { TextField } from ".."; const meta: Meta<typeof InputLabel> = { title: "Components/Label", component: InputLabel, }; export default meta; type Story = StoryObj<typeof InputLabel>; export const Default: Story = {}; Default.args = { children: "This is an input label", }; export const Examples: Story = { render: (a) => { return ( <div className="grid gap-y-2"> <InputLabel>This is an input label</InputLabel> <InputLabel required>This is a REQUIRED input label</InputLabel> </div> ); }, }; export const WithTextField: Story = { render: () => { return ( <div className="grid gap-y-2"> <InputLabel htmlFor="name" required> This is an input label </InputLabel> <TextField name="name" placeholder="Type your name" /> </div> ); }, };
package net.rnvn.model.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import net.rnvn.db.PolizasDAO; import net.rnvn.db.QueryGen; import net.rnvn.model.MedioPago; public class MedioPagoDAO extends PolizasDAO { public MedioPagoDAO() { super(); } public boolean agregarMedioPago(MedioPago medioPago) { boolean result = false; try (Connection conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(SQL_ADD_MEDIO_PAGO)) { stmt.clearParameters(); stmt.setInt(1, medioPago.getId()); stmt.setString(2, medioPago.getIdCliente()); stmt.setString(3, medioPago.getNumeroTarjeta()); stmt.setString(4, medioPago.getNombreTitular()); stmt.setDate(5, java.sql.Date.valueOf(medioPago.getFechaVencimiento().toLocalDate())); stmt.setString(6, medioPago.getCvv()); result = stmt.executeUpdate() > 0; } catch (Exception e) { String className = this.getClass().getName(); System.err.println("[" + className + "] Error al agregar medio de pago: " + e.getMessage()); } return result; } public MedioPago getMedioPago(int idMedioPago) { MedioPago pago = null; try (Connection conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(SQL_GET_MEDIO_PAGO)) { stmt.clearParameters(); stmt.setInt(1, idMedioPago); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { String id = rs.getString("id_cliente"); String numeroTarjeta = rs.getString("numero_tarjeta"); String nombreTitular = rs.getString("nombre_titular"); LocalDateTime fechaVencimiento = rs.getTimestamp("fecha_vencimiento").toLocalDateTime(); String cvv = rs.getString("cvv"); pago = new MedioPago(idMedioPago, id, numeroTarjeta, nombreTitular, fechaVencimiento, cvv); } } } catch (Exception e) { String className = this.getClass().getName(); System.err.println("[" + className + "] Error al obtener medio de pago: " + e.getMessage()); } return pago; } public boolean actualizarMedioPago(MedioPago medioPago) { boolean result = false; try (Connection conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(SQL_UPDATE_MEDIO_PAGO)) { stmt.clearParameters(); stmt.setInt(1, medioPago.getId()); stmt.setString(2, medioPago.getIdCliente()); stmt.setString(3, medioPago.getNumeroTarjeta()); stmt.setString(4, medioPago.getNombreTitular()); stmt.setDate(5, java.sql.Date.valueOf(medioPago.getFechaVencimiento().toLocalDate())); stmt.setString(6, medioPago.getCvv()); result = stmt.executeUpdate() > 0; } catch (Exception e) { String className = this.getClass().getName(); System.err.println("[" + className + "] Error al actualizar medio de pago: " + e.getMessage()); } return result; } public boolean eliminarMedioPago(int id) { boolean result = false; try (Connection conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(SQL_DELETE_MEDIO_PAGO)) { stmt.clearParameters(); stmt.setInt(1, id); result = stmt.executeUpdate() > 0; } catch (Exception e) { String className = this.getClass().getName(); System.err.println("[" + className + "] Error al eliminar medio de pago: " + e.getMessage()); } return result; } public List<MedioPago> getListadoMedioPagoCliente(String idCliente) { ArrayList<MedioPago> listadoMedioPago = null; try (Connection conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(SQL_LIST_MEDIO_PAGO_CLIENTE)) { stmt.clearParameters(); stmt.setString(1, idCliente); try (java.sql.ResultSet rs = stmt.executeQuery()) { listadoMedioPago = new ArrayList<MedioPago>(); while (rs.next()) { int id = rs.getInt("id"); String numeroTarjeta = rs.getString("numero_tarjeta"); String nombreTitular = rs.getString("nombre_titular"); LocalDateTime fechaVencimiento = rs.getTimestamp("fecha_vencimiento").toLocalDateTime(); String cvv = rs.getString("cvv"); MedioPago medioPago = new MedioPago( id, idCliente, numeroTarjeta, nombreTitular, fechaVencimiento, cvv); listadoMedioPago.add(medioPago); } } } catch (Exception e) { String className = this.getClass().getName(); System.err.println("[" + className + "] Error al obtener listado de medios de pago: " + e.getMessage()); } return listadoMedioPago; } // consultas SQL private static final String TABLE_NAME = "medio_pago"; private static final String SQL_ADD_MEDIO_PAGO = QueryGen.genInsertInto( TABLE_NAME, new String[] { "id", "id_cliente", "numero_tarjeta", "nombre_titular", "fecha_vencimiento", "cvv" }); private static final String SQL_GET_MEDIO_PAGO = QueryGen.genSelectString( TABLE_NAME, new String[] { "id_cliente", "numero_tarjeta", "nombre_titular", "fecha_vencimiento", "cvv" }, new String[] { "id = ?" }); private static final String SQL_UPDATE_MEDIO_PAGO = QueryGen.genUpdateString( TABLE_NAME, new String[] { "id_cliente", "numero_tarjeta", "nombre_titular", "fecha_vencimiento", "cvv" }, new String[] { "id = ?" }); private static final String SQL_DELETE_MEDIO_PAGO = QueryGen.genDeleteString( TABLE_NAME, new String[] { "id = ?" }); private static final String SQL_LIST_MEDIO_PAGO_CLIENTE // = QueryGen.genSelectString( TABLE_NAME, new String[] { "id", "id_cliente", "numero_tarjeta", "nombre_titular", "fecha_vencimiento", "cvv" }, new String[] { "id_cliente = ?" }); }
import Head from 'next/head' import Link from 'next/link' import { toast } from 'react-toastify'; import { AiOutlineMail, AiOutlineLock } from 'react-icons/ai' import { useEffect, useState } from 'react'; import Router, { useRouter } from 'next/router'; const Login = () => { const [Email, setEmail] = useState('') const [Password, setPassword] = useState('') const router = useRouter(); useEffect(() => { if (localStorage.getItem('token')) { router.push('/') } }, []) const Login = async (e) => { e.preventDefault(); let req = { Email: Email, Password: Password } let ans = await fetch('/api/login', { method: 'POST', body: JSON.stringify(req) }); let response = await ans.json(); if (response.success) { localStorage.setItem('token', response.token); setTimeout(() => { toast.success('Login Successfully', { position: "bottom-center", autoClose: 3000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, theme: "light", }) }, 700); Router.push('/', '/'); } else { toast.error(response.res, { position: "bottom-center", autoClose: 3000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, theme: "light", }) } } return ( <> <Head> <title>Login</title> </Head> <section className="bg-white dark:bg-neutral-900"> <div className="container flex lg:items-center mt-20 lg:mt-1 justify-center md:py-24 py-4 px-6 mx-auto"> <form onSubmit={Login} className="w-full max-w-md"> <h1 className="text-3xl font-semibold text-neutral-800 capitalize dark:text-white">sign In</h1> <div className="relative flex items-center mt-8"> <span className="absolute"> <AiOutlineMail className="text-2xl mx-3 text-neutral-300 dark:text-neutral-500" /> </span> <input value={Email} type="email" onChange={(e) => { setEmail(e.target.value) }} className=" w-full py-3 text-neutral-700 bg-white border rounded-md px-11 dark:bg-neutral-900 dark:text-neutral-300 dark:border-neutral-600 focus:border-blue-400 dark:focus:border-blue-300 focus:ring-blue-300 focus:outline-none focus:ring focus:ring-opacity-40" placeholder="Email address" /> </div> <div className="relative flex items-center mt-4"> <span className="absolute"> <AiOutlineLock className="text-2xl mx-3 text-neutral-300 dark:text-neutral-500" /> </span> <input value={Password} type="password" onChange={(e) => { setPassword(e.target.value) }} className="block w-full px-10 py-3 text-neutral-700 bg-white border rounded-md dark:bg-neutral-900 dark:text-neutral-300 dark:border-neutral-600 focus:border-blue-400 dark:focus:border-blue-300 focus:ring-blue-300 focus:outline-none focus:ring focus:ring-opacity-40" placeholder="Password" /> </div> <div className="mt-6"> <button className="w-full px-6 py-3 text-sm font-medium tracking-wide text-white capitalize transition-colors duration-300 transform bg-blue-500 rounded-md hover:bg-blue-400 focus:outline-none focus:ring focus:ring-blue-300 focus:ring-opacity-50"> Sign in </button> <div className="mt-6 text-center "> <Link href="/signup" className="text-sm text-blue-500 hover:underline dark:text-blue-400"> Dont have An Account? </Link> </div> </div> </form> </div> </section> </> ) } export default Login
import { createGenerator, toEscapedSelector as e } from '@unocss/core' import presetUno from '@unocss/preset-uno' import { autocompleteExtractorAttributify, presetAttributify, variantAttributify } from '@unocss/preset-attributify' import { describe, expect, test } from 'vitest' describe('attributify', async () => { const uno = createGenerator({ presets: [ presetAttributify({ strict: true }), presetUno({ attributifyPseudo: true }), ], rules: [ [/^custom-(\d+)$/, ([_, value], { rawSelector }) => { // return a string instead of an object const selector = e(rawSelector) return ` ${selector} { font-size: ${value}px; } /* you can have multiple rules */ ${selector}::after { content: 'after'; } .foo > ${selector} { color: red; } /* or media queries */ @media (min-width: 680px) { ${selector} { font-size: 16px; } } ` }], ], }) describe('cases', () => { const cases = import.meta.glob('./cases/preset-attributify/*/input.html', { as: 'raw' }) for (const [path, input] of Object.entries(cases)) { test(path, async () => { const { css } = await uno.generate(await input(), { preflights: false }) await expect(css).toMatchFileSnapshot(path.replace('input.html', 'output.css')) }) } }) const fixture1 = (await import('./cases/preset-attributify/case-1/input.html?raw')).default test('variant', async () => { const variant = variantAttributify({ prefix: 'un-', prefixedOnly: false, strict: true, }) const promises = Array.from(await uno.applyExtractors(fixture1) || []) .map(async (i) => { const r = await variant.match(i, {} as any) return typeof r === 'string' ? r : r ? r.matcher : r }) expect(await Promise.all(promises)) .toMatchSnapshot() }) test('prefixedOnly', async () => { const uno = createGenerator({ presets: [ presetAttributify({ strict: true, prefix: 'un-', prefixedOnly: true }), presetUno({ attributifyPseudo: true }), ], }) const { css } = await uno.generate(fixture1, { preflights: false }) expect(css).toMatchSnapshot() }) describe('autocomplete extractor', async () => { test('without prefix', async () => { const res = await autocompleteExtractorAttributify().extract({ content: fixture1, cursor: 187, }) expect(res).not.toBeNull() expect(res!.extracted).toMatchInlineSnapshot('"bg-blue-400"') expect(res!.transformSuggestions!([`${res!.extracted}1`, `${res!.extracted}2`])) .toMatchInlineSnapshot(` [ "blue-4001", "blue-4002", ] `) const reversed = res!.resolveReplacement(`${res!.extracted}1`) expect(reversed).toMatchInlineSnapshot(` { "end": 192, "replacement": "blue-4001", "start": 184, } `) expect(fixture1.slice(reversed.start, reversed.end)) .toMatchInlineSnapshot('"blue-400"') }) test('with prefix', async () => { const fixtureWithPrefix = ` <div un-text-cent> <div un-text="cent </div> ` const res1 = await autocompleteExtractorAttributify({ prefix: 'un-' }).extract({ content: fixtureWithPrefix, cursor: 18, }) expect(res1).not.toBeNull() expect(res1!.extracted).toMatchInlineSnapshot('"text-cent"') const reversed1 = res1!.resolveReplacement(`${res1!.extracted}1`) expect(reversed1).toMatchInlineSnapshot(` { "end": 18, "replacement": "text-cent1", "start": 9, } `) expect(fixtureWithPrefix.slice(reversed1.start, reversed1.end)) .toMatchInlineSnapshot('"text-cent"') const res2 = await autocompleteExtractorAttributify({ prefix: 'un-' }).extract({ content: fixtureWithPrefix, cursor: 40, }) expect(res2).not.toBeNull() expect(res2!.extracted).toMatchInlineSnapshot('"text-cent"') expect(res2!.transformSuggestions!([`${res2!.extracted}1`, `${res2!.extracted}2`])) .toMatchInlineSnapshot(` [ "cent1", "cent2", ] `) const reversed2 = res2!.resolveReplacement(`${res2!.extracted}1`) expect(reversed2).toMatchInlineSnapshot(` { "end": 40, "replacement": "cent1", "start": 36, } `) expect(fixtureWithPrefix.slice(reversed2.start, reversed2.end)) .toMatchInlineSnapshot('"cent"') }) test('only prefix', async () => { const fixtureOnlyPrefix = ` <div text-cent> <div text="cent </div> ` const res1 = await autocompleteExtractorAttributify({ prefix: 'un-', prefixedOnly: true }).extract({ content: fixtureOnlyPrefix, cursor: 15, }) expect(res1).toBeNull() const res2 = await autocompleteExtractorAttributify({ prefix: 'un-', prefixedOnly: true }).extract({ content: fixtureOnlyPrefix, cursor: 34, }) expect(res2).toBeNull() }) }) test('with trueToNonValued', async () => { const uno = createGenerator({ presets: [ presetAttributify({ trueToNonValued: true }), presetUno(), ], }) const { css } = await uno.generate(` <div flex="true"></div> <div grid="~ cols-2"></div> `, { preflights: false }) expect(css).toMatchSnapshot() }) test('with incomplete element', async () => { await uno.generate('<div class="w-fullllllllllllll"') }, 20) test('merge attribute name and value-only', async () => { const { css } = await uno.generate(` <div bg="[&:nth-child(3)]:[#123456]"></div> <div class="foo" bg="[&.foo]:[&:nth-child(3)]:[#123]"></div> `, { preflights: false }) expect(css).toMatchSnapshot() }) })
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { Recipe } from './Recipe.schema'; import mongoose from 'mongoose'; @Schema() export class User { @Prop({ required: false }) displayName?: string; @Prop({ unique: true, required: true }) email: string; @Prop({ required: true }) password: string; @Prop({ required: false }) dayOfBirth?: string; @Prop({ required: false }) sex?: string; @Prop({ required: false }) avatarUrl?: string; @Prop({ required: false }) bio?: string; @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Recipe' }] }) recipes?: Recipe[]; @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Recipe' }] }) favorited?: Recipe[]; } export const UserSchema = SchemaFactory.createForClass(User);
import { GridSize } from "@mui/material"; import { useState } from "react"; export interface FormControlsProps { inputFields: InputField[]; } export type InputField = { id: string; name: string; label: string; autoComplete: string | undefined; defaultValue: string | undefined; required: boolean | undefined; gridXs: boolean | GridSize | undefined; gridSm: boolean | GridSize | undefined; }; export const useFormControls = ({ inputFields }: FormControlsProps) => { // State of form controls const [values, setValues] = useState( inputFields.reduce( (obj, field) => Object.assign(obj, { [field.id]: field.defaultValue }), {} // initial object as empty object ) as any ); // State of form errors const [errors, setErrors] = useState({} as any); // Validates form based on values, updates errors const validateForm = (fieldValues = values) => { let newErrors: any = { ...errors }; // Validate required fields for (let i = 0; i < inputFields.length; i++) { const field = inputFields[i]; if (field.required && field.name in fieldValues) { newErrors[field.name] = fieldValues[field.name] ? "" : "This field is required"; } } setErrors(newErrors); }; // Handles form control input const handleInputValue = (e: any) => { const { name, value } = e.target; setValues({ ...values, [name]: value, }); validateForm({ [name]: value }); }; // Handles form submission, requires valid form const handleFormSubmit = (e: any, callback?: () => void): boolean => { e.preventDefault(); const isValid = isFormValid(); if (isValid && callback) { callback(); } return isValid; }; // Final check for form const isFormValid = (fieldValues = values): boolean => { // Check for all required fields for (let i = 0; i < inputFields.length; i++) { const field = inputFields[i]; if ( field.required && field.name in fieldValues && !fieldValues[field.name] ) { return false; } } // Check for any other errors return Object.values(errors).every((x) => x === ""); }; return { handleInputValue, handleFormSubmit, isFormValid, errors, values, }; };
from django.contrib.auth import get_user_model from django.db import models from .validators import validate_not_empty from django.conf import settings User = get_user_model() SYMBOLS = settings.SYMBOLS_FOR_TEXT_POST_STR class Post(models.Model): """ Класс Post используется для создания моделей Post (пост в социальной сети). """ text = models.TextField( verbose_name='Текст поста', help_text='Введите текст поста', max_length=10000, validators=[validate_not_empty], blank=False ) pub_date = models.DateTimeField( verbose_name='Дата публикации', auto_now_add=True ) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='posts', verbose_name='Автор' ) group = models.ForeignKey( 'Group', on_delete=models.SET_NULL, related_name='postsin', blank=True, null=True, verbose_name='Группа', help_text='Выберите группу' ) class Meta: """ Внутренний класс Meta для хранения метаданных класса Post. """ ordering = ['-pub_date', '-pk'] def __str__(self) -> str: return self.text[:SYMBOLS] class Group(models.Model): """ Класс Group используется для создания моделей Group сообществ, в которых происходит размещение постов в социальной сети. """ title = models.CharField(max_length=200) slug = models.SlugField(max_length=100, unique=True) description = models.TextField() def __str__(self) -> str: return self.title
--- layout: week.njk title: Variables and For Loops weekNum: 3 tags: - p5 - week goals: - "Share and Discuss Coding Sketch #2" - "Clarify or Demo any coding concepts unclear from Coding Sketch #2" - Intro Conditional Statements and Logical Operators - "Start work on Coding Sketch #3" sketch: title: "Coding Sketch #2: For Loop Remix" text: - Remix the for loop examples in the book (ex. 4-5 through 4-9) to create something original. See how you can incorporate color, strokeWeight(), and different shapes from the previous week. concepts: - for loop - nested for loop - "variables: let, const" - scope code: - for - let - const - width - height refExamples: - control iteration - control embedded iteration examples: - type : p5 url : glj/sketches/j0eb1nZo7 - type: p5 url: gjohns13-spectacular/sketches/vUGlosRQX - type : p5 url : gjohns13-spectacular/sketches/B3ubYdhTl - type: p5 url : gjohns13-spectacular/sketches/xq96JTX7l - type: p5 url: gjohns13-spectacular/sketches/bEiV5Bq7V other: - type: youtube id: POn4cZ0jL-o - type: youtube id: cnRD9o6odjk - type: youtube id: 1c1_TMdf8b8 - type: youtube id: 7A5tKW9HGoM - type: youtube id: dRhXIIFp-ys - type: youtube id: nIooYRJAnlc eleventyComputed: readings: - name: "{{ texts.p5.title }}" url: "{{ texts.p5.url }}" img: "{{ texts.p5.img }} " description: Chapters 4. Variables. ---
Selenium web driver: 1.Web driver is one of the component in selenium 2.web driver is an java interface which contains all abstract methods,static methods,default methods SearchContext(I) is the first interface they have designed.//parent interface | | webDriver(I) is an interface //child interface //classBrowser testing : same testcase which will execute on multiple browser. Every browser has its own class Firefoxbrowser --- FirefoxDriver ChromeDriver---chromeDriver Edge browser---EdgeDriver IE----InternetExplorerDriver(deprecated) 3.WebDriver is an API(Application programming interface)[Api is basically an interface between two application. it is basically an mediator between two applications[application and database] works---it gets the request from the user and according to the request it will fetch the data in the database and servers and corresponding data it will send to the user in the form of response. name justification: 3 different types of layer: 1.DB layer(database layer) 2.BL layer(business logic layer)[programming layer] 3.PL layer(presentation layer) -- user always communicate with presentation layer API contains so many classes ,so many methods which contains buisness logic ] **why webdriver is an API? It is a mediator between automation script and browser that's why it is called as an API.. Selenium has 3 component: 1.selenium webdriver -- main component of selenium,it is used for web applications which help to develop Automation script 2.selenium IDE -- record and playback tool 3.Selenium Grid -- remote enviroment if u want to execute your test cases on different machine and different browser Selenium is not a tool. it is a collection of component. //Selenium Client Library: web driver contains so many classes and so many methods those are binding together in the form of jar file it is called as selenium client library. //Browser specific drivers: executable files //Browsers(chrome,edge,firefox,....) why u create maven project why not java project? if u r using maven project u don't have to download any client library. if u r using java project u will have to download client library,browser specific drivers.... //Locators: 1.identifying elements - locators 2.Perform actions -methods Locator -- locate the web elemets 1.we can identify various elements on the web using locators 2.locators are addresses that identify a web element uniquely within the page Types of locators: 2 types 1.Normal Locators -- id,name,linktext , partialLinktext ,ClassName,TagName 2.Customized locators-- CSS Selector,Xpath CSS selector -- Tag and ID , Tag and class, Tag and attribute,Tag ,class and attribute Xpath --Absolute Xpath,Relative Xpath Absolute XPath: Begins from the root of the HTML document and specifies the complete path to the element. It's not as flexible and can break if the page structure changes. Relative XPath: Starts from a specific element and navigates through the DOM hierarchy to locate the desired element. why avoid to use partial linktext? linkText() – locates the links based on the exact match of the link's text provided as a parameter. By. partialLinkText() – locates links based on the partial text match of the link's text. //List.size() = List,Set,HashMap //CSS Selector(): driver.findElement(By.cssSelector(selector)) 1.tag id # Ex :input#small-seachterms ------ seachtems is the value of the id #classname 2.tag class . ex:input.className .classname 3.tag attribute [] ex: input[placeholder="serach store"] it uses other than id,class like text ,placeholder,name 4.tag class attribute .[] input.search-box-text[name = "q"] //Methods 1.get methods 2.conditional methods 3.navigational methods 4.browser methods 5.wait methods 1.get methods --we can access these methods through webdriver instance get is a command to way to launch our webpages get(url) getTitle() getCurrentURL() getPageSource() getWindowHandle() -- return id of the particular single browser window--return the string ,handle single browser window id everytime it will create different id.it cannot switch to 1st to 2nd web page. getwindowHandles() -- return id of the multiple browser window -return set of string.different types of switching commands are there **browserid it uses for switching commands 2.Conditional commands --access these commands through webelements returns true/false(boolean values) isDisplayed() -- it returns true if webelements is present, it returns false if web elements is not present isEnabled() --it checks like popups are enabled or not isSelected() --it checks for radio button 3.Browser methods -- 1.close() --close the current/Single browser window //it will give an warning SocketException browser focus on 1st browser window that's why it will not close 2nd browser window 2.quit()---close the multiple browser window. if i want to close specific browser window then, using windowid for switching command. 4.wait commands:wait statements will be used to solve the synchronizantion problem. Thread.sleep(ms) sleep():provided by java itself(not selenium command). advantages of sleep() : 1.easy to use disadvantagesof sleep(): 1.if the time is not sufficient then u will get exception 2.it will wait of maximum time out.this will reduce the performance script 3.multiple times. 1.Implicit wait --applicable for all the every statement in the automation script. advantages ---1.single time /one statement 2.it will nit wait till maximum time if the elememt is available 3.applicable for all the elements 4.easy to use disadvantages-- 1.if the time is not sufficient then u will get exception. 2. driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); **basicially sleep & implicitwait is a time specified 2.Explicit wait -- basically it is a conditional specified it has 2 parts i)declaration WebDriverWait mywait = new WebDriverWait(driver,Duration.ofSeconds(10)); ii)usage how to declare explicitwait(): WebDriverWait mywait = new WebDriverWait(driver,Duration.ofSeconds(10)); WebElement username = mywait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@placeholder='Username']")))); username.sendKeys("Admin"); WebElement password = mywait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@placeholder='Username']")))); username.sendKeys("admin123"); advatages: 1.it based on conditional based,it will work more effectively. disadvantages: 2.finding element is inclusive. 3.it will wait for condition to be true,the consider the time disadvantages: Fluent wait: another flavour of explicit wait. it has also 2 parts: 1.declaration 2.usage declaration: Wait<WebDriver> mywait = new FluentWait<WebDriver>(driver) .withTimeOut(Duration.ofSeconds(30)) .pollingEvery(Duration.ofSeconds(5)) .ignoring(NoSuchElementException.class); another declaration: WebElement username = mywait.until(new Function<WebDriver,WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.xpath("//input[@placeholder='Username']")); } }); polling means :within every 5 seconds it will check element is present or not if element is find then return this . if element is not availbale then it will throw exception. fluentwait gives polling and ignoring exception sleep():provided by java itself(not selenium command). advantages of sleep() : 1.easy to use disadvantagesof sleep(): 1.if the time is not sufficient then u will get exception 2.it will wait of maximum time out.this will reduce the performance script 3.multiple times. **q.difference betwwen sleep() and implicit wait() 5.Navigational Commands: 1.navigate().to(url) -- same as driver.get(url) it accept string format ,url formal [like URL muurl = new URL("https://www.google.com")] difference between driver.get(url) and navigate.to(url) driver.get(url) accepts only string format navigate.to(url) accepts only string and url 2.navigate().forward() -- 3.navigate().back() 4.navigate().refresh() driver.navigate().to(url); drivber.manage().window().maximize();
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="style.css"> <title>Basket</title> <fmt:setLocale value="${sessionScope.local}" /> <fmt:setBundle basename="localization.local" var="loc" /> <fmt:message bundle="${loc}" key="local.shop" var="shop" /> <fmt:message bundle="${loc}" key="local.hello" var="hello" /> <fmt:message bundle="${loc}" key="local.locbutton.name.en" var="en_button" /> <fmt:message bundle="${loc}" key="local.locbutton.name.ru" var="ru_button" /> <fmt:message bundle="${loc}" key="local.locbutton.name.ch" var="ch_button" /> <c:set var="current_page" value="${requestScope.get('currentPage')}"/> <c:set var="max_page" value="${requestScope.get('maxPage')}"/> </head> <body> <div class="header"> <div id="header1"> <p><c:out value="${shop}"/></p> <p>Basket: <c:out value="${sessionScope.userName}"/> !!!</p> </div> <div id="header2" style="display:flex; flex-flow: row wrap; justify-content:space-between"> <div> <form action="FrontController" method="post"> <input type="hidden" name="command" value="change_language"/> <input type="hidden" name="local" value="en"/> <input type="submit" value="ENG"/> </form> <form action="FrontController" method="post"> <input type="hidden" name="command" value="change_language"/> <input type="hidden" name="local" value="ru"/> <input type="submit" value="РУС"/> </form> <form action="FrontController" method="post"> <input type="hidden" name="command" value="change_language"/> <input type="hidden" name="local" value="ch"/> <input type="submit" value="汉语"/> </form> </div> <div> <form action="FrontController" method="post" style="height:100%"> <input type="hidden" name="command" value="logout"/> <input type="submit" value="Log out" style="height:100%"/> </form> </div> </div> </div> <div class="middle"> <div id="menu"> <p><b>Get ALL orders</b> <form action="FrontController" method="post"> <input type="hidden" name="command" value="showAllMyOrders"/> <input type="hidden" name="page_num" value="1"/> <input type="submit" name="get_orders" value="Show ALL Orders!"/> </form> </p> <br/> <hr/> <p><b>Basket</b></p> <hr/> <form action="FrontController" method="post"> <p><b>Get all RESERVED products (or Reload)</b> <input type="hidden" name="command" value="selectAllReserved"/> <input type="hidden" name="page_num" value="1"/> <input type="submit" name="get_reserved" value="Get them!"/> </p> </form> <br/> <hr/> <br/> <form action="FrontController" method="post"> <p><b>Buy all products in basket.</b></p> <input type="hidden" name="command" value="createOrder"/><br/> <p>Fill with the address:</p> <input type="text" name="user_address" value="" required/><br/><br/> <p>Fill with your contact phone number:</p> <input type="text" name="user_phone" value="" required/><br/><br/> <input type="submit" name="buy" value="Buy now!"/> </form> </div> <div id="content"> <br/> <hr/> <p><b><c:out value="${requestScope.get('msg')}"/></b></p> <c:if test="${current_page != null}"> <H1>Everything you have choosen for purchasing.</H1> <hr/> <table width="100%" border="1" align="center" cellpadding="4" cellspacing="0" bgcolor="#ffebcd"> <tr> <td>INFO</td> <td>COMPANY</td> <td>NAME</td> <td>TYPE</td> <td>PRICE</td> <td>DELETE</td> </tr> <c:forEach items="${requestScope.productArray}" var="product"> <tr> <td> <form action="FrontController" method="post"> <input type="hidden" name="command" value="productInfo" /> <input type="hidden" name="productId" value="${product.id}" /> <input type="submit" name="info" value="INFO" /><br/> </form> </td> <td>${product.company}</td> <td>${product.name}</td> <td>${product.type}</td> <td>${product.price}</td> <td> <form action="FrontController" method="post"> <input type="hidden" name="command" value="deleteReserved" /> <input type="hidden" name="reserveId" value="${product.reserve_id}" /> <input type="submit" name="remove" value="REMOVE" /><br/> </form> </td> </tr> </c:forEach> </table> <div width="100%" style="background-color: deepskyblue; font-size: 1em">     <c:forEach begin="1" end="${max_page}" var="i">             <c:if test="${i != current_page}">      <a href="FrontController?command=selectAllReserved&page_num=${i}">${i}</a>             </c:if>             <c:if test="${i == current_page}">                 <c:out value="${i}"/>         </c:if>     </c:forEach> </div> </c:if> </div> </div> <div class="footer" > <div id="footer" > <h1>footer</h1> <p style="text-decoration-color: yellow"> <a href="FrontController?command=goToPage&address=index.jsp">INDEX</a> --> <a href="FrontController?command=goToPage&address=main.jsp">MAIN</a> --> <a href="FrontController?command=goToPage&address=basket.jsp">BASKET</a> </p> </div> </div> </body> </html>
<template> <el-dialog :title="$t('table.header_display_field')" :visible.sync="visible" :append-to-body="true"> <tree-transfer :title="[$t('table.fields_to_be_selected'), $t('table.selected_fields')]" :from_data='fromFields' :placeholder="$t('api_test.request.parameters_mock_filter_tips')" :draggable="true" :to_data='selectedFields' :defaultProps="{label:'label'}" :allow-drop="allowDrop" :default-checked-keys="selectedKeys" :default-transfer="defaultTransfer" :mode='mode' filter openAll/> <template v-slot:footer> <ms-dialog-footer @cancel="close" @confirm="saveHeader"/> </template> </el-dialog> </template> <script> import MsDialogFooter from "../MsDialogFooter"; import treeTransfer from 'el-tree-transfer' import {getAllFieldWithCustomFields, saveCustomTableHeader} from "../../utils/tableUtils"; import {SYSTEM_FIELD_NAME_MAP} from "../../utils/table-constants"; export default { name: "MsCustomTableHeader", components: {MsDialogFooter, treeTransfer}, data() { return { visible: false, value: [], fromFields: [], selectedFields: [], selectedKeys: [], defaultTransfer: true, mode: "transfer", // transfer addressList } }, props: { type: String, customFields: Array }, methods: { allowDrop(draggingNode, dropNode, type) { return type !== 'inner'; }, open(items) { items = JSON.parse(JSON.stringify(items)); items.forEach(it => { if (it.isCustom) { // i18n it.label = SYSTEM_FIELD_NAME_MAP[it.id] ? this.$t(SYSTEM_FIELD_NAME_MAP[it.id]) : it.label; } }) let hasRemoveField = undefined; if (this.customFields) { let index = this.customFields.findIndex(c => c.remove === true); if (index > -1) { hasRemoveField = this.customFields[index]; } } let fields = getAllFieldWithCustomFields(this.type, this.customFields); this.selectedKeys = []; this.fromFields = []; this.selectedKeys = items.map(item => item.key); this.selectedFields = items; for (let field of fields) { if (this.selectedKeys.indexOf(field.key) < 0) { if (field.isCustom) { field.label = SYSTEM_FIELD_NAME_MAP[field.id] ? this.$t(SYSTEM_FIELD_NAME_MAP[field.id]) : field.label } if (hasRemoveField && field.id === hasRemoveField.id) { continue; } this.fromFields.push(field); } } this.visible = true; }, saveHeader() { saveCustomTableHeader(this.type, this.selectedFields); this.$success(this.$t("commons.save_success")); this.$emit('reload'); this.close(); }, removeAt(idx) { this.list.splice(idx, 1); }, close() { this.visible = false }, } } </script> <style scoped> :deep(.wl-transfer .transfer-main) { height: calc(100% - 73px) !important; } </style>
import { ClassNames } from '@emotion/react'; import { IconMinusCircle } from 'hds-react'; import React from 'react'; import { useTranslation } from 'react-i18next'; import { useTheme } from '../../../domain/app/theme/Theme'; import Button from '../button/Button'; import styles from './deleteButton.module.scss'; type Props = { ariaLabel: string; className?: string; label?: string; onClick: () => void; } & React.ComponentPropsWithoutRef<'button'>; const DeleteButton: React.FC<Props> = ({ ariaLabel, className, label, onClick, type = 'button', ...rest }) => { const { t } = useTranslation(); const { theme } = useTheme(); return ( <ClassNames> {({ css, cx }) => ( <Button {...rest} aria-label={ariaLabel} className={cx( styles.deleteButton, className, css(theme.deleteButton) )} iconLeft={<IconMinusCircle aria-hidden={true} />} onClick={onClick} type={type} variant="supplementary" > <span className={styles.label}>{t('common.delete')}</span> </Button> )} </ClassNames> ); }; export default DeleteButton;
import { useCallback, useEffect, useState } from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { PublicImage } from '../../common'; import { PublicSound } from '../../common/enums/PublicSound'; import { getEnding, StoreProps, Ending as EndingType, getScore, resetGame, resetShop, playSound, } from '../../state'; import { EndingBackgroundImage, EndingContainer, EndingText, EndingTitle } from './style'; const connectEnding = connect( createStructuredSelector({ ending: getEnding, score: getScore, }), { resetGame, resetShop, playSound, } ); type EndingProps = StoreProps<typeof connectEnding>; const imageByEnding = { [EndingType.CrimeBoss]: PublicImage.CrimeBoss, [EndingType.Cyborg]: PublicImage.Cyborg, [EndingType.Reptiloid]: PublicImage.Reptiloid, [EndingType.NoMoney]: PublicImage.NoMoney, [EndingType.UndercoverCop]: PublicImage.UndercoverCop, }; const textByEnding = { [EndingType.CrimeBoss]: 'The local crime boss does not take kindly to low-quality goods.', [EndingType.Cyborg]: "Oops! Kidnapping a cyborg - that's going to cause some trouble.", [EndingType.Reptiloid]: 'Yikes! Caught a reptiloid by mistake - brace for consequences.', [EndingType.NoMoney]: 'Empty pockets! No funds left - the end of this journey.', [EndingType.UndercoverCop]: 'Unlucky! Traded with an undercover cop - handcuffs and jail time.', }; const EndingBase: React.FC<EndingProps> = ({ ending, score, resetGame, resetShop, playSound }) => { const [image, setImage] = useState<PublicImage>(PublicImage.NoMoney); const [text, setText] = useState<string>(''); const [endingStage, setEndingStage] = useState(0); useEffect(() => { if (!ending) { setEndingStage(0); } if (ending) { setImage(imageByEnding[ending]); setText(textByEnding[ending]); setEndingStage(1); if (ending === EndingType.Cyborg || ending === EndingType.Reptiloid) { playSound(PublicSound.TacoBell); } } }, [ending]); useEffect(() => { if (!ending) { // eslint-disable-next-line @typescript-eslint/no-empty-function return () => {}; } const timeout = setTimeout(() => { if (endingStage < 13) { setEndingStage((s) => s + 1); } }, 500); return () => { clearTimeout(timeout); }; }, [ending, endingStage]); const handleAnyKey = useCallback(() => { if (endingStage < 13) { return; } resetGame(); resetShop(); setEndingStage(0); }, [endingStage]); useEffect(() => { window.addEventListener('keydown', handleAnyKey); window.addEventListener('mousedown', handleAnyKey); return () => { window.removeEventListener('keydown', handleAnyKey); window.removeEventListener('mousedown', handleAnyKey); }; }, [handleAnyKey]); return ( <EndingContainer visible={ending !== null} onKeyDown={handleAnyKey}> <EndingBackgroundImage stage={endingStage} src={`images/${image}`} /> <EndingTitle visible={endingStage >= 4}>Game over</EndingTitle> <EndingText visible={endingStage >= 7}>{text}</EndingText> <EndingText visible={endingStage >= 10}>Score: {score}</EndingText> <EndingText visible={endingStage >= 13}>Press any key to try again</EndingText> </EndingContainer> ); }; export const Ending = connectEnding(EndingBase);
/*! Copyright 2018 Ron Buckton ([email protected]) 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. */ /** @module "iterable-query/fn" */ import { assert, ToStringTag} from "../internal"; /** * Creates an [[Iterable]] over a range of numbers. * * @param start The starting number of the range. * @param end The ending number of the range. * @param increment The amount by which to change between each itereated value. * @category Query */ export function range(start: number, end: number, increment: number = 1): Iterable<number> { assert.mustBeFiniteNumber(start, "start"); assert.mustBeFiniteNumber(end, "end"); assert.mustBePositiveNonZeroFiniteNumber(increment, "increment"); return new RangeIterable(start, end, increment); } @ToStringTag("RangeIterable") class RangeIterable implements Iterable<number> { private _start: number; private _end: number; private _increment: number; constructor(start: number, end: number, increment: number) { this._start = start; this._end = end; this._increment = increment; } *[Symbol.iterator](): Iterator<number> { const start = this._start; const end = this._end; const increment = this._increment; if (start <= end) { for (let i = start; i <= end; i += increment) { yield i; } } else { for (let i = start; i >= end; i -= increment) { yield i; } } } }
package jecs; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import jecs.events.ComponentAddedEvent; import jecs.events.ComponentRemovedEvent; import jecs.events.EventManager; import jecs.events.InstantiationEvent; import java.util.*; /** * An Entity is essentially a bag of components and does not process anything other than managing which * components are currently attached to it. The components attached to an Entity determine the Entity type and which * this is used by {@link System}s during Entity validation * <p> * Removing or adding components during runtime will cause the Entity validation to be rerun for every System that * is concerned so it is probably best to do this sparingly though it has not been tested for performance as of yet. * <p> * The safest and most practical means of adding components is to extend the Entity class and calling the super * Entity constructor which takes a variable number of class types that must extend the {@link Component} class. * Any class type passed in this way will cause an instance of each passed in type to be reflectively created * when the Entity child class is created. This is also better performance wise due to the Entity holding off on * announcing its instantiation as an instantiation announcement is what kicks off Entity validation for systems */ public class Entity { private ObjectProperty <UUID> entityId = new SimpleObjectProperty (UUID.randomUUID ()); private HashMap <Class <? extends Component>, Component> componentMap = new HashMap (); private EventManager eventManager = EventManager.getInstance (); private List <Class<? extends Component>> componentSignature = new ArrayList<Class<? extends Component>>(); /** * Creates a new Entity instance and announces instantiation */ protected Entity () { eventManager.postEvent (new InstantiationEvent (this)); } /** * Creates new Entity instance and adds instances of all passed in Component class types * to the Entity * * @param components the components types to create and add to Entity */ public Entity (Class <? extends Component>... components) { this.componentSignature.addAll (Arrays.asList (components)); } public void start () {}; /** * Returns the Entitys UUID * * @return the entity id */ public UUID getEntityId () { return entityId.get (); } /** * Returns the Entity id property * * @return the id object property */ public ObjectProperty <UUID> entityIdProperty () { return entityId; } /** * Adds an instance of the passed in Component type to the Entity * * @param <T> the Component type to add * @param componentType the entity type * @return the created Component instance */ public <T extends Component> T addComponent (Class <T> componentType) { T component = null; try { component = componentType.newInstance (); componentMap.put (componentType, component); } catch (Exception e) { e.printStackTrace (); } eventManager.postEvent (new ComponentAddedEvent (component, this)); return component; } /** * Remove entity from Entity * * @param componentType the entity type to remove */ public void removeComponent (Class <? extends Component> componentType) { componentMap.remove (componentType); eventManager.postEvent (new ComponentRemovedEvent (componentType, this)); } /** * Returns all Components attached to Entity * * @return the components */ public Collection <Component> getComponents () { return componentMap.values (); } /** * Returns an attached Component based on the passed in Component type. Will return * null if the Entity does not have a Component of passed in type currently attached * * @param <T> the type parameter * @param componentType the entity type * @return the entity */ public <T extends Component> T getComponent (Class <T> componentType) { return (T)componentMap.get (componentType); } public boolean hasComponent (Class <? extends Component> key) { return componentMap.containsKey (key); } public List<Class<? extends Component>> getComponentSignature () { return this.componentSignature; } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Testimonial; class TestimonialController extends Controller { public function index(){ $testimonials = Testimonial::get(); return view('admin.testimonial.index', compact('testimonials')); } public function create(){ return view('admin.testimonial.create'); } public function store(Request $request){ $request->validate([ 'name'=>'required', 'profile'=>'mimes:png,jpg,jpeg,webp', 'message'=>'required', ]); $image_name = null; if($request->hasFile('profile')){ $image = $request->file('profile'); $image_name = time().'.'.$image->extension(); $image->move(public_path('uploads/testimonial/'),$image_name); } Testimonial::create([ 'name'=>$request->name, 'message'=>$request->message, 'profile'=>$image_name, 'position'=>$request->position, ]); return redirect()->route('testimonial.index')->with(['message'=>'Testimonial Added']); } public function edit(Testimonial $testimonial){ return view('admin.testimonial.edit', compact('testimonial')); } public function update(Request $request, Testimonial $testimonial){ $request->validate([ 'name'=>'required', 'profile'=>'mimes:png,jpg,jpeg,webp', 'message'=>'required', ]); $image_name = $testimonial->profile; if($request->hasFile('profile')){ if($testimonial->profile != null){ if(file_exists(public_path('uploads/testimonial/'.$testimonial->profile))){ unlink(public_path('uploads/testimonial/'.$testimonial->profile)); } } $image = $request->file('profile'); $image_name = time().'.'.$image->extension(); $image->move(public_path('uploads/testimonial/'),$image_name); } $testimonial->name = $request->name; $testimonial->position = $request->position; $testimonial->profile = $image_name; $testimonial->message = $request->message; $testimonial->save(); return redirect()->route('testimonial.index')->with(['message'=>"Testimonial Updated"]); } public function delete($id){ $testimonial = Testimonial::where('id',$id)->first(); if($testimonial->profile != null){ if(file_exists(public_path('uploads/testimonial/'.$testimonial->profile))){ unlink(public_path('uploads/testimonial/'.$testimonial->profile)); } } $testimonial->delete(); return redirect()->route('testimonial.index')->with(['message'=>"Testimonial Deleted"]); } }
import * as React from "react"; import { useParams } from "react-router-dom"; import useFavourites from "../hooks/useFavourites"; import FavouriteIcon from "../assets/icons/FavouriteIcon"; import useCart from "../hooks/useCart"; import CartIcon from "../assets/icons/CartIcon"; import { booksAPI } from "../services/api.service"; import { useAppSelector } from "../hooks/redux"; import { getCurSearchTerm } from "../store/books/selectors"; const BookInfoPage = () => { const params = useParams(); const searchTerm = useAppSelector(getCurSearchTerm()); const id = params?.id ? params?.id : ""; const { currentBook } = booksAPI.useFetchAllBooksQuery(searchTerm, { selectFromResult: ({ data }) => ({ currentBook: data?.find((book) => book._id === id), }), }); const { toggleFavouritesButton, isFavourite } = useFavourites( id, currentBook ); const { toggleCartButton, isInCart } = useCart(id, currentBook); return ( <> <div className="flex md:justify-around max-md:justify-evenly flex-wrap"> <div className="self-center"> {/* <img src={currentBook?.cover} width={250} /> */} <img src={ currentBook?.cover ? `https://covers.openlibrary.org/b/id/${currentBook.cover}-M.jpg` : `https://missefficiency.nl/contents/media/l_naslagwerk_20171107144603.jpg` } alt="book" width={250} /> </div> <div className="flex flex-col md:w-1/2 gap-4 p-4"> <div>{currentBook?.author}</div> <div className="text-xl font-bold">{currentBook?.title}</div> {/* <div className="text-xl font-bold">{currentBook?.price}</div> */} {/* <div> <h1>Описание:</h1> <p className="text-sm italic">{currentBook?.description}</p>{" "} </div> */} <div className="flex justify-between"> <div className="hover:bg-gray-100 rounded-full cursor-pointer" onClick={toggleFavouritesButton} > <FavouriteIcon color={isFavourite ? "#ffc0cb" : "#452400"} /> </div> <div className="hover:bg-gray-100 p-1 rounded-full cursor-pointer" onClick={toggleCartButton} > <CartIcon color={isInCart ? "#ffc0cb" : "#452400"} /> </div> </div> </div> </div> </> ); }; export default BookInfoPage;
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCouponCodesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('coupon_codes', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('code')->comment('优惠码,下单时输入'); $table->string('type')->comment('优惠类型'); $table->decimal('value',10,2)->comment('折扣值,根据不同类型含义不同'); $table->unsignedInteger('total')->comment('全站可兑换的数量'); $table->unsignedInteger('used')->default(0)->comment('已兑换的数量'); $table->decimal('min_amount',10,2)->comment('使用优惠卷的最低订单金额'); $table->dateTime('not_before')->nullable()->comment('在这之前不可以使用'); $table->dateTime('not_after')->nullable()->comment('在这之后不能使用'); $table->boolean('enabled')->comment('是否生效'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('coupon_codes'); } }
import 'package:ARhomes/models/ItemModel.dart'; import 'package:ARhomes/screens/arViewScreen.dart'; import 'package:ARhomes/screens/color_pallet_explore.dart'; import 'package:ARhomes/screens/homeView.dart'; import 'package:ARhomes/screens/or_divider.dart'; import 'package:flutter/material.dart'; class ExplorePage extends StatefulWidget { const ExplorePage({Key? key}) : super(key: key); @override State<ExplorePage> createState() => _ExplorePageState(); } class _ExplorePageState extends State<ExplorePage> { List<ItemModel> items = [ // ItemModel( // 'Double Bed', // 'Double Bed with 2 Lamps', // 'items/clock2.png', // 12, // ), ItemModel( 'Double Bed', 'Double Bed with 2 Lamps', 'items/bed.png', 12, ), ItemModel( 'Single Sofa T55', 'White Sofa For Your Home', 'items/sofa_white.png', 16, ), ItemModel( 'Double Sofa ', 'Three Seater Branded Sofa', 'items/sofa_yellow.png', 10, ), ItemModel( 'Chair Brown ', 'A Small Chair For Your Backyard ', 'items/pc_table.png', 6, ), ItemModel( 'G78 Single Sofa', 'Branded Single Yellow Sofa', 'items/single_sofa.png', 10, ), ItemModel( 'Dinner Table', 'Beautiful Dinner Table For Family', 'items/dinner_table.png', 11, ), ItemModel( 'Branded Pc Table', 'Wooden Branded UK Table', 'items/pc_table2.png', 10, ), ItemModel( 'Chair Short', 'A Small Cheap Chair', 'items/chair2.png', 11, ), ItemModel( 'Wooden Table', 'Wooden Branded UK Table', 'items/table.png', 16, ), ItemModel( 'Thai Double Bed', 'Branded Double Bed With Locker ', 'items/bed_double.png', 10, ), ItemModel( 'Rotatable Chair', 'A Brand New Rotatable Chair', 'items/rot_chair.png', 10, ), ItemModel( 'UK5 Sofa', 'Brand New Single Sofa', 'items/sofa_uk.png', 10, ), ItemModel( 'T80 Dinner Table', 'Beautiful table for Dinner', 'items/dinner_table2.png', 10, ), ItemModel( '2 Seat Sofa', 'This is branded new Double sofa', 'items/sofa_yellow.png', 10, ), ItemModel( 'Grey Sofa', 'This is a 2 seater and Brand new double sofa', 'items/sofa_grey.png', 10, ), ItemModel( 'Brown Chair Y9', 'A Beautiful chair for sitting', 'items/chair1.png', 10, ), ItemModel( 'HU9 Dinner Table', 'Beautiful Table For Dinner', 'items/dinner_table3.png', 10, ), ]; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color.fromARGB(255, 50, 75, 75), body: Column( children: [ SizedBox( height: 28, ), Text( "Explore Catalog", style: TextStyle( fontFamily: "Pony", color: Colors.white70, fontSize: 40, ), ), // IconButton( // onPressed: () { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => ColorPallet(), // )); // }, // icon: Icon(Icons.view_comfy_rounded)), // OrDivider( // "Featured Furnishing Items", // ), Expanded( child: Padding( padding: EdgeInsets.all(20), child: ListView.builder( // scrollDirection: // Axis.horizontal, // Display cards horizontally itemCount: items.length, // Display two cards per row shrinkWrap: true, itemBuilder: (BuildContext context, int index) { // final int startIndex = index; // final int endIndex = startIndex + 2; return GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ARViewScreen( itemImg: items[index].pic, ), ), ); }, child: Card( child: Padding( padding: const EdgeInsets.all(16.0), child: Column( children: <Widget>[ SizedBox( width: 80, height: 80, child: Image.asset( items[index].pic, width: 60, ), ), Text( items[index].name, style: TextStyle( fontSize: 16, color: Colors.black, ), ), Text( items[index].detail, style: TextStyle( fontSize: 10, color: Colors.black87, ), ), ], ), ), ), ); }, ), ), ) ], ), ); } } class CategorieTile extends StatelessWidget { final String imgUrl, title; CategorieTile({required this.imgUrl, required this.title}); @override Widget build(BuildContext context) { return GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => HomeView(), ), ); }, child: Container( margin: EdgeInsets.only(right: 8), decoration: BoxDecoration(), child: Stack( children: [ ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.asset(imgUrl, height: 50, width: 100, fit: BoxFit.cover)), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.black38, ), alignment: Alignment.center, height: 50, width: 100, child: Text(title, style: TextStyle( color: Colors.white, fontWeight: FontWeight.w500, fontSize: 16, ))), ], ), ), ); } } class NoGLowBehavior extends ScrollBehavior { @override Widget buildOverscrollIndicator( BuildContext context, Widget child, ScrollableDetails details) { return child; } }
package task2; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Создать свой класс Person с полями: firstName, lastName, age, dateOfBirth. * Добавить класс User, который наследуется от Person, с полями: login, password, email. * Добавить гетеры, сетеры. Добавить метод printUserInfo в User. * Посмотреть разницу. Просетать все значения через Reflection. * Вывести значения полей через Reflection. * Вызвать toString через invoke. */ public class Main { public static void main(String[] args) throws Exception { User user = new User("John", "Doe", 25, "01/01/1997", "johndoe", "password123", "[email protected]"); user.printUserInfo(); Class<?> userClass = user.getClass(); Method method1 = userClass.getMethod("printUserInfo"); Method method2 = userClass.getMethod("setPassword", String.class); System.out.println(method1); System.out.println(method2); System.out.println("\n******** Using getMethod/getField ********"); System.out.println("------ METHODS ------"); Method[] methods = userClass.getMethods(); for (Method method : methods) { System.out.println("Method: " + method); } Field field = userClass.getField("firstName"); System.out.println("Field: " + field); try { Field field2 = userClass.getField("password"); System.out.println("Field2: " + field2); } catch (NoSuchFieldException e) { e.printStackTrace(); } System.out.println("------ FIELDS ------"); Field[] fields = userClass.getFields(); for (Field f : fields) { System.out.println("Field: " + f); } System.out.println("\n******** Using getDeclaredMethods() ********"); try { System.out.println("------ METHODS ------"); Method declaredMethod = userClass.getDeclaredMethod("getPassword"); System.out.println("Declared Method: " + declaredMethod); Method[] declaredMethods = userClass.getDeclaredMethods(); for (Method method : declaredMethods) { System.out.println("Declared Methods: " + method); } System.out.println("------ FIELDS ------"); Field declaredField = userClass.getDeclaredField("email"); System.out.println("Declared Field: " + declaredField); Field[] declaredFields = userClass.getDeclaredFields(); for (Field f : declaredFields) { System.out.println("Declared Field: " + f); } } catch (NoSuchMethodException | NoSuchFieldException e) { e.printStackTrace(); } System.out.println("\n******** Setting field values ********"); Field emailField = userClass.getDeclaredField("email"); emailField.setAccessible(true); emailField.set(user, "[email protected]"); user.printUserInfo(); System.out.println("\n******** Invoking toString method ********"); Method methodToString = userClass.getDeclaredMethod("toString"); System.out.println(methodToString.invoke(user)); } }
module Scores::Maintainability import Map; import IO; import util::Math; private bool keys_there(map[str, value] m) { if ("analysability" notin m) return false; if ("changeability" notin m) return false; if ("testability" notin m) return false; return true; } int calculate_maintainability(map[str, int] scores, map[str, real] weights) { if (!keys_there(scores) || !keys_there(weights)) return -1; real final_score = 0.0; final_score += weights["analysability"] * scores["analysability"]; final_score += weights["changeability"] * scores["changeability"]; final_score += weights["testability"] * scores["testability"]; return floor(final_score); } int calculate_maintainability(map[str, int] scores) { map[str, real] weights = (); weights["analysability"] = 1.0/3.0; weights["changeability"] = 1.0/3.0; weights["testability"] = 1.0/3.0; return calculate_maintainability(scores, weights); } /** * Convert the numerical scores in integer values (1-5) to ranking in (--/-/o/+/++), respectively. * Returns rank (x) if the numerical score is not within the range. **/ map[str, str] ranking(map[str, int] scores) { map[str, str] fscores = (); for (<m, r> <- toList(scores)) { if (r == 1) { fscores[m] = "--"; continue; } if (r == 2) { fscores[m] = "-"; continue; } if (r == 3) { fscores[m] = "o"; continue; } if (r == 4) { fscores[m] = "+"; continue; } if (r == 5) { fscores[m] = "++"; continue; } else fscores[m] = "x"; continue; } return fscores; }
import { useEffect, useState } from 'react' import { useRouter } from 'next/router' import _ from 'lodash' import Image from 'next/image' import Client from 'shopify-buy' import Layout from '../../components/layout' import SwiperCore, { Autoplay, Pagination } from 'swiper' import { Swiper, SwiperSlide } from 'swiper/react' import Link from 'next/link' const client = Client.buildClient({ domain: process.env.NEXT_PUBLIC_STORE_DOMAIN, storefrontAccessToken: process.env.NEXT_PUBLIC_ACCESS_TOKEN, }) export default function Product({ product, helpers }) { const { locale } = useRouter() const [state, setState] = useState({ variant: [...product.variants[0].selectedOptions], price: product.variants[0].priceV2.amount, quantity: 1, }) SwiperCore.use([Autoplay, Pagination]) function isVariantAvailable() { return product.availableForSale ? _.find(product.variants, { selectedOptions: state.variant }).available : false } function handleChange(e) { const i = state.variant.findIndex( ({ name }) => name === e.target.dataset.option ) let newState = { variant: state.variant, price: _.find(product.variants, { selectedOptions: state.variant, }).priceV2.amount, } newState.variant[i] = { name: e.target.dataset.option, value: e.target.value, } setState((prevState) => { return { ...prevState, ...newState } }) } function handleClick() { helpers.addProductToCart( _.find(product.variants, { selectedOptions: state.variant, }).id, state.quantity ) } let description = product.descriptionHtml const regex = /(.*)======(.*)/s const translatedDesc = product.descriptionHtml.search(/======/) if (translatedDesc !== -1) { locale === 'en' ? (description = product.descriptionHtml.match(regex)[1]) : (description = product.descriptionHtml.match(regex)[2]) } return ( <Layout helpers={helpers}> <section className='lg:flex'> <div className='overflow-hidden flex lg:w-1/2 bg-gray-200'> <Swiper className='flex-1' pagination={{ clickable: true }} autoplay={{ delay: 3500, disableOnInteraction: false, }} > {product.images.map(({ id, src, altText }) => ( <SwiperSlide key={id}> <div className='aspect-w-2 aspect-h-3 md:aspect-none md:h-screen loading'> <Image src={src} alt={altText} objectFit='contain' layout='fill' quality='85' unoptimized={process.env.NODE_ENV === 'development'} /> </div> </SwiperSlide> ))} </Swiper> </div> <div className='relative justify-center lg:w-1/2 lg:flex lg:flex-col bg-gradient-to-r from-gray-200 to-gray-300'> <div className='text-lg text-right'> {!product.availableForSale && ( <span className='inline-block px-6 py-2 mt-10 text-xl md:text-2xl tracking-wide text-gray-300 uppercase bg-gray-500 md:right-0 md:absolute md:top-8 font-display'> {locale === 'en' ? 'Out of stock' : 'Agotado'} </span> )} <div className='p-10 pb-4 text-left md:p-20 md:pb-8'> {product.productType && ( <span className='inline-block px-1.5 py-0.5 text-xs font-semibold tracking-wider text-orange-500 uppercase bg-orange-200 rounded-sm'> {product.productType} </span> )} <h1 className='text-4xl md:text-5xl font-semibold'> {product.title} </h1> <h4 className='mb-10 text-2xl md:text-3xl font-semibold text-gray-500'>{`${product.variants[0].priceV2.currencyCode} $${state.price}`}</h4> {description && ( <div className='mb-10 text-base' dangerouslySetInnerHTML={{ __html: description, }} /> )} <div className='flex flex-col text-base sm:items-end sm:flex-row'> {_.map(product.options, ({ id, name, values }) => { if (name === 'Title') return return ( <label className='m-1.5' key={id}> {`${name}:`} <select className='block w-20 px-2 py-1 mt-2 bg-gray-100 border border-gray-400' onChange={handleChange} data-option={name} > {_.map(values, (value) => { return ( <option key={value} value={value}> {value} </option> ) })} </select> </label> ) })} <label className='m-1.5'> Quantity: <input className='block w-20 px-2 py-1 mt-2 bg-gray-100 border border-gray-400' type='number' min={1} step={1} value={state.quantity} onChange={(e) => setState((prevState) => { return { ...prevState, quantity: parseInt(e.target.value), } }) } /> </label> <button className='w-full m-1.5 mt-10 md:mt-0 flex-1 px-4 py-1.5 bg-orange-500 rounded whitespace-nowrap text-gray-50 font-semibold disabled:bg-gray-400 disabled:text-gray-300' disabled={!isVariantAvailable()} onClick={handleClick} > {locale === 'en' ? 'Add to cart' : 'Agregar al carrito'} </button> </div> </div> </div> <div className='px-10 md:px-20 pb-10'> <Link href={`/collection/${product.vendor.toLowerCase()}`} locale={locale} > <a className='px-2 py-1 text-xs font-semibold tracking-wider text-gray-200 uppercase bg-gray-400 rounded whitespace-nowrap inline-block'> {locale === 'en' ? '← Continue shopping' : '← Continuar comprando'} </a> </Link> </div> </div> </section> </Layout> ) } export async function getStaticPaths({ locales }) { let paths = [] const products = await client.product.fetchAll(100) _.forEach(locales, (locale) => { _.forEach(products, (product) => { paths.push({ params: { handle: product.handle }, locale, }) }) }) return { paths, fallback: false } } export async function getStaticProps({ params }) { const { availableForSale, description, descriptionHtml, id, images, options, productType, title, variants, vendor, } = await client.product.fetchByHandle(params.handle) return { props: { handle: params.handle, product: { availableForSale, description, descriptionHtml, id, images: images.map(({ altText, id, src }) => { return { altText, id, src } }), options: options.map(({ id, name, values }) => { return { id, name, values: values.map(({ value }) => value), } }), productType, title, variants: variants.map( ({ available, id, priceV2, selectedOptions, title }) => { return { available, id, priceV2: { amount: priceV2.amount, currencyCode: priceV2.currencyCode, }, selectedOptions: selectedOptions.map(({ name, value }) => { return { name, value, } }), title, } } ), vendor, }, }, } }
import PropTypes from 'prop-types'; // import s from "./Statistics.module.css"; const Statistics = ({good, neutral, bad, total, feedbackPercentage}) => ( <> <p>Good: {good}</p> <p>Neutral: {neutral}</p> <p>Bad: {bad}</p> <p>Total: {total}</p> <p> Positive feedback: {isNaN(feedbackPercentage) ? 0 : Math.round(feedbackPercentage)}% </p> </> ) Statistics.propTypes = { good: PropTypes.number.isRequired, neutral: PropTypes.number.isRequired, bad: PropTypes.number.isRequired, total: PropTypes.number.isRequired, feedbackPercentage: PropTypes.number.isRequired, }; export default Statistics;
(note: this text just hauled over from EmacsWiki at the moment; home page for this project is really at http://www.emacswiki.org/emacs/EsvMode for now) EsvMode is a simple interface to the ESV API, so you can get passages from the English Standard Version of the Bible. CharlesSebold wrote it. Current version of the code just gets the text and displays it. I'm still trying to figure out this whole XML thing. Requires at least Emacs 22. == Usage == To use this, you must customize or otherwise set the variable ESV-KEY! Otherwise by default the ESV API handlers will not call out to the ESV website. At the minimum, do this: M-x customize-variable RET esv-key RET And set it to "Non-keyed usage" (IP) if you're just going to use this for personal use in Emacs. Details of the ESV license for this information can be found at http://www.esvapi.org/ and I recommend looking it over. This package consists of two functionalities: one is to recognize passages in your buffers and make it easy for you to look them up in the ESV (that's esv-mode), and one is a way to retrieve ESV passages using their web API and display them internally in Emacs. This can be used to get individual passages (which you can specify or retrieve from your text using esv-mode), or you can go through a daily reading plan (great for those of us who live in Emacs). To use this package, you can save this file somewhere in your load-path and put the following in your .emacs at a minimum: <pre> (require 'esv) ; the following keys should be mapped to whatever works best for ; you: ; C-c e looks up a passage and displays it in a pop-up window (define-key global-map [(control c) ?e] 'esv-passage) ; C-c i inserts an ESV passage in plain-text format at point (define-key global-map [(control c) ?i] 'esv-insert-passage) ; If you don't want to use customize, you can set this for casual ; usage (but read http://www.esvapi.org/ for license): (setq esv-key "IP") </pre> To make esv-mode work whenever text-mode does, you can put this in your .emacs as well: <pre> (add-hook 'text-mode-hook 'turn-on-esv-mode) </pre> If you only want it in certain files, you can add it to the first line or the local variables (see (info "(emacs)File Variables") for more information): <pre> -*- mode: text; mode: esv; -*- </pre> or <pre> Local Variables: mode: esv; End: </pre> However, note the warning about imposing your individual preferences on files at the end of the info node above. == Bugs == # <code>esv-mode</code> (the minor mode, not the whole thing here) doesn't work too well; I'm not great with syntax highlighting. # If you <code>esv-insert-passage</code> something that is formatted as poetry, it will not get the "(ESV)" text at the end of the last line. This is because of the ESV API, not because of my code; when you call for plain-text output from their web service, you get "(ESV)" at the end of most sections of Biblical text, but not things that are preformatted as poetry. I don't consider this a big enough problem to work around, myself, but if somebody wants to submit code to look for that and fix it, I'd be willing to include it, with a <code>defcustom</code> to allow people to leave it the way it came from their web service by default. # The text formatting, when I'm parsing it out of the XML, can be goofy. Some of this depends on how your AutoFillMode, FillAdapt, and so forth are configured. I'd like to make that better, and maybe someday I'll have the time. # Emacs 21 is no longer officially supported, mostly because I'm using UTF-8 to encode the source file now that I'm having to parse some strange things in the footnotes. If there's an elegant way to make this work backwards, I'm interested in hearing about it, but Emacs 22 has been out for a while. Related to the word wrap and line length, LongLines will cause the automatic column width that is sent to the API to be some crazy big number, and the results are often not what you were hoping. You can adjust this by advising <code>esv-insert-passage</code> and let-ing fill-column be a sane number (72 in the example below) before sending it, like this: <pre> (defadvice esv-insert-passage (around longlines-fix-length nil activate) "Force fill-column to a sane number." (let ((fill-column 72)) ad-do-it)) </pre> == Feature Requests == # I'd like to extend this to other Bible-verse web services as well, and make the ESV one just one of many pluggable options. # I'd like to generate something for arbitrary reading plans, invented or submitted by users; I'm using Grant Horner's ten-chapters-per-day model now and I've got a fairly complicated system that OrgMode is driving to get me those chapters, but it's not easily extended to work for EsvMode at the moment. # I really want to do some cool face work with the <code>esv-reading-mode</code> major mode, to make a really nice Bible reading page. That's a pretty low priority when there's missing functionality, though. == Changelog == 1.11 includes reading plan support (esv-reading-plan, use prefix argument to specify date), plain text insertion which is good for email (esv-insert-passage), and more prep work for better support in the future. 1.16 makes it possible to run esv-mode, a minor mode that makes Bible references clickable, and can be configured to either display them internally or externally via web-browser (or other function of your choice). 1.18 adds documentation and fixes a customization problem. 1.19 fixed a problem with the regexp that finds passages (but not every problem) and attempts to fix the multiline problem too 1.20 wasn't really a change (I pulled out the CVS ID, I've switched to git) 1.21 adds esv-region() 1.22 adds yank if mouse-2 happens in a non-clickable region 1.23 adds new reading plans from Crossway 1.24 adds support for ē entity and adds a framework for more if more are found in the footnotes, thanks to Matt Gumm for bug report; Emacs 21 no longer officially supported 1.25 fixes a bug when quitting esv-display-mode with only one window present 1.26 fixes a bug introduced in 1.24 1.27 Updated the library headers (thanks Tarsius on Github!) to spec at (info "(elisp)Library Headers") 1.28 Orphaning this; please adopt this old thing, I clearly don't have time for Emacs hacking anymore.
package com.aplaz.oauthserver.service; import com.aplaz.oauthserver.entity.User; import com.aplaz.oauthserver.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.ArrayList; import java.util.Collection; import java.util.List; /******************** @Transactional ********************************* * * @Transactional , Spring dynamically creates a proxy that * implements the same interface(s) as the class you're annotating. * And when clients make calls into your object, the calls are * intercepted and the behaviors injected via the proxy mechanism * */ /** * Now we have defined the custom user detail service. * THIS IS THE SERVICE FOR VALIDATE THE USER * we define the authorization server config like how the authorization server should work */ @Service @Transactional public class CustomUserDetailsService implements UserDetailsService { /******************************* loadUserByUsername * * This dependency is so usefull because with it we know about the users that have in the database. * The UserDetailsService interface is used to retrieve user-related data. It has one method named * loadUserByUsername() which can be overridden to customize the process of finding the user. * It is used by the DaoAuthenticationProvider to load details about the user during authentication. * */ @Autowired private UserRepository repo; @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(11); } @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { // first find user in db by email User user = repo.findByEmail(email); if(user == null){ throw new UsernameNotFoundException("Not User Found"); } return new org.springframework.security.core.userdetails.User( user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, getAuthorities(List.of(user.getRole())) ); } /********** Collection<? extends T> * With the Collection<? extends GrantedAuthority> * extends you can allow any subclasses of GrantedAuthority * */ private Collection<? extends GrantedAuthority> getAuthorities(List<String> roles) { List<GrantedAuthority> authorities = new ArrayList<>(); for (String role: roles){ authorities.add(new SimpleGrantedAuthority(role)); } return authorities; } }
"use client"; import { H1 } from "@/components/text"; import { updateListName } from "../../actions"; import { useRef } from "react"; import { AutoGrowInput } from "@/components/AutoGrowInput"; export function ListName({ listId, name }: { listId: string; name: string }) { const inputRef = useRef<HTMLInputElement>(null); const formRef = useRef<HTMLFormElement>(null); const updateName = async (form: FormData) => { const newName = form.get("name") as string | null; if (newName) { await updateListName(listId, newName); inputRef.current?.blur(); } }; return ( <form action={updateName} className="overflow-hidden" ref={formRef}> <H1 className="overflow-hidden"> <AutoGrowInput ref={inputRef} className="bg-transparent" onBlur={(e) => e.target.form?.requestSubmit()} defaultValue={name} name="name" data-1p-ignore maxLength={30} /> </H1> </form> ); }
const bcrypt = require("bcrypt") const jwt = require("jsonwebtoken") const { ForbiddenError, AuthenticationError } = require("apollo-server-express") require("dotenv").config() const mongoose = require("mongoose") const gravatar = require("../util/gravatar") module.exports = { newNote: async (parent, args, { models, user }) => { if (!user) { throw new AuthenticationError("You must be signed in to create a note") } return await models.Note.create({ content: args.content, author: mongoose.Types.ObjectId(user.id), }) }, deleteNote: async (parent, { id }, { models, user }) => { if (!user) { throw new AuthenticationError("You must be signed in to delete a note") } const note = await models.Note.findById(id) //note 소유자와 현재 사용자가 불일치하면 접근 에러 던지기 if (note && String(note.author) !== user.id) { throw new ForbiddenError("You don't have permissions to delete the note") } try { await note.remove() return true } catch (err) { return false } }, updateNote: async (parent, { content, id }, { models, user }) => { if (!user) { throw new AuthenticationError("You must be signed in to update a note") } const note = await models.Note.findById(id) if (note && String(note.author) !== user.id) { throw new ForbiddenError("You don't have permissions to update the note") } return await models.Note.findOneAndUpdate( { _id: id, }, { $set: { content, }, }, { new: true, } ) }, signUp: async (parent, { username, email, password }, { models }) => { //이메일 주소 스트링 처리 email = email.trim().toLowerCase() //비밀번호 해싱 const hashed = await bcrypt.hash(password, 10) //gravatar URL 생성 const avatar = gravatar(email) try { const user = await models.User.create({ username, email, avatar, password: hashed, }) //JWT 생성 및 반환 return jwt.sign({ id: user._id }, process.env.JWT_SECRET) } catch (err) { console.log(err) //계정 생성 중 문제가 발생하면 에러 던지기 throw new Error("Error creating account") } }, signIn: async (parent, { username, email, password }, { models }) => { if (email) { email = email.trim().toLowerCase() } const user = await models.User.findOne({ $or: [{ email }, { username }] }) //사용자를 찾지 못하면 인증 에러 던지기 if (!user) { throw new AuthenticationError("Error signing in") } const valid = await bcrypt.compare(password, user.password) if (!valid) { throw new AuthenticationError("Error signing in") } //JWT 생성 및 반환 return jwt.sign({ id: user._id }, process.env.JWT_SECRET) }, toggleFavorite: async (parent, { id }, { models, user }) => { //전달된 user context가 없으면 에러 던지기 if (!user) { throw new AuthenticationError() } let noteCheck = await models.Note.findById(id) const hasUser = noteCheck.favoritedBy.indexOf(user.id) //사용자 목록에 있으면 if (hasUser >= 0) { return await models.models.Note.findByIdAndUpdate( id, { $pull: { favoritedBy: mongoose.Types.ObjectId(user.id) }, $inc: { favoriteCount: -1 }, }, { new: true, } ) } else { return await models.Note.findByIdAndUpdate( id, { $pull: { favoritedBy: mongoose.Types.ObjectId(user.id), }, $inc: { favoriteCount: 1, }, }, { new: true, } ) } }, }
// Copyright 2022-2023 The Connect Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // Copied from buf core, replace once we publish design system somewhere these docs can use it from. import clsx from "clsx"; import React, { PropsWithChildren, useEffect, useState } from "react"; type TooltipProps = { content: string | JSX.Element; // include any classes to position the tooltip here; for more, see: // https://tailwindcss.com/docs/top-right-bottom-left#class-reference classNameModifications?: string; // activeClassName sets a class on the tooltip container when active activeClassName?: string; // leaveOn sets the tooltip to stay on if it's true leaveOn?: boolean; children: React.ReactNode; }; const Tooltip: React.FC<TooltipProps> = ({ content, classNameModifications = "", activeClassName = "", children, leaveOn, }: PropsWithChildren<TooltipProps>) => { const [visible, setVisible] = useState<boolean>(false); const hidden = !visible; useEffect(() => { if (leaveOn === true) { setVisible(true); } else { setVisible(false); } }, [leaveOn]); return ( <div className={clsx({ [activeClassName]: visible, })} style={{ display: "inline-block", position: "relative", }} onMouseEnter={() => { setVisible(true); }} onMouseLeave={() => { if (leaveOn !== true) { setVisible(false); } }} > {children} <div className={classNameModifications} style={{ display: hidden ? "none" : undefined, }} > {content} </div> </div> ); }; export default Tooltip;
import Particle from "./Particle"; import React, { useRef } from "react"; import emailjs from "@emailjs/browser"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; const Contact = () => { const form = useRef(); const sendEmail = (e) => { e.preventDefault(); toast.info("Email is sending...", { autoClose: true }); emailjs .sendForm( "service_am5rvjf", "template_eviw649", form.current, "QPgjShn0Gwpuvdthd" ) .then( (result) => { // console.log(result.text); toast.success("Email sent successfully!"); form.current.reset(); }, (error) => { console.log(error.text); toast.error("Failed to send email!"); } ); }; return ( <> <Particle /> <div className="contact-page"> <div class="main"> <form ref={form} onSubmit={sendEmail}> <span> Contact Me</span> <label for=""> <input type="text" placeholder="Your Name" name="from_name" /> </label> <label for=""> <input type="email" placeholder="Your Email" name="from_email" /> </label> <textarea placeholder="Your Message" name="message"></textarea> <input type="submit" value="Send" className="do-submit" /> </form> <ToastContainer /> </div> </div> </> ); }; export default Contact;
--- draft: true sidebar_label: Overview description: This section documents the official integration between Vault and Kubernetes. --- <!-- TODO: clarify if this will be supported by OpenBao --> # Kubernetes Vault can be deployed into Kubernetes using the official HashiCorp Vault Helm chart. The Helm chart allows users to deploy Vault in various configurations: - Dev: a single in-memory Vault server for testing Vault - Standalone (default): a single Vault server persisting to a volume using the file storage backend - High-Availability (HA): a cluster of Vault servers that use an HA storage backend such as Consul (default) - External: a Vault Agent Injector server that depends on an external Vault server ## Use cases **Running a Vault Service:** The Vault server cluster can run directly on Kubernetes. This can be used by applications running within Kubernetes as well as external to Kubernetes, as long as they can communicate to the server via the network. **Accessing and Storing Secrets:** Applications using the Vault service running in Kubernetes can access and store secrets from Vault using a number of different [secret engines](/docs/secrets) and [authentication methods](/docs/auth). **Running a Highly Available Vault Service:** By using pod affinities, highly available backend storage (such as Consul) and [auto-unseal](/docs/concepts/seal#auto-unseal), Vault can become a highly available service in Kubernetes. **Encryption as a Service:** Applications using the Vault service running in Kubernetes can leverage the [Transit secret engine](/docs/secrets/transit) as "encryption as a service". This allows applications to offload encryption needs to Vault before storing data at rest. **Audit Logs for Vault:** Operators can choose to attach a persistent volume to the Vault cluster which can be used to [store audit logs](/docs/audit). **And more!** Vault can run directly on Kubernetes, so in addition to the native integrations provided by Vault itself, any other tool built for Kubernetes can choose to leverage Vault. ## Getting started with Vault and kubernetes There are several ways to try Vault with Kubernetes in different environments. ### High level comparison of integrations There are currently 3 different integrations to help Kubernetes workloads seamlessly consume secrets from Vault, without the need to modify the application to interact directly with Vault. Each integration addresses slightly different use-cases. The following is a brief overview of the strengths of each integration. #### Agent injector - No durable secret storage outside Vault. All secrets written to disk are in ephemeral in-memory volumes. - No highly privileged service accounts required. All secrets are fetched with the pod's own service account without the need for any other service accounts to impersonate it. - More mature solution, with proven production record and advanced features like templating, wider array of auth methods, etc. #### Vault Secrets Operator - More native UX for app developers. Workloads can mount Kubernetes secrets without adding any Vault-specific configuration. - Reduced load on Vault. Secrets are synced per CRD instead of per consuming pod. - Better Vault secret availability. Kubernetes secrets act as a durable cluster-local cache of Vault secrets. #### Vault CSI provider - The CSI driver that the provider is based on is vendor neutral. - No durable secret storage outside Vault if the secret sync feature isn't used. All secrets written to disk are in ephemeral in-memory volumes.
import React, { useContext, useEffect } from "react"; import logo from "./assets/images/ededi_new.png"; import Forums from "./pages/Forums"; import Nav from "./components/nav"; import ProfileCard from "./components/profile_card"; import LoginCard from "./components/login_card"; import { GlobalContext } from "./context/Provider"; import { Link, useLocation } from "react-router-dom"; import "./App.css"; import { Outlet } from "react-router-dom"; import { fetchRecentTopics } from "./context/actions/topic.action"; function App() { const location = useLocation(); const { pathname } = location; const { loginState, topicDispatch, topics } = useContext(GlobalContext); useEffect(() => { fetchRecentTopics()(topicDispatch); }, [topicDispatch]); // console.log(topics.recent); return ( <> <section className="bg-white dark:bg-slate-700"> <aside className="h-screen w-[22%] fixed top-0 left-0"> <div className="top h-1/2 min-h-[400px] w-100 bg-slate-800 dark:bg-slate-600 relative"> <div className="logo p-5 pt-20 flex justify-center"> <img src={logo} alt="logo" className="w-32 mb-10" /> </div> <div className="profile flex flex-col items-center w-2/3 h1/2 bg-white dark:bg-slate-800 absolute ml-auto mr-auto inset-x-0 -bottom-50 rounded-2xl p-5 drop-shadow-lg"> {loginState.loggedIn ? ( <ProfileCard loginState={loginState} /> ) : ( <LoginCard /> )} {/* if logged in */} {/* <ProfileCard /> */} {/* if not logged in */} {/* <LoginCard /> */} </div> </div> <div className="bottom bg-slate-50 w-100 h-full pt-52 flex justify-center"> <p className="mt-10 text-slate-300">New features comming soon</p> </div> </aside> <main className="w-[78%] h-auto ml-[22%]"> <Nav userInfo={loginState} /> <article className="content w-full h-100 mt-[71px] flex flex-row dark:text-slate-400"> <section className=" h-full w-2/3 p-20 mt-5"> {/* <Outlet/> */} {pathname == "/" ? <Forums /> : <Outlet />} </section> <section className="border-l flex flex-col items-center w-1/3 h-min-screen mt-5 relative"> <div className="right-aside sticky top-24 w-[90%]"> <div className="card bg-slate-100 rounded p-8 w-[90%] flex flex-col items-center pt-16"> <div className="card-body"> <h2 className="pb-5 font-semibold text-lg"> Recent Topics </h2> <ul> {topics.recent.length < 1 ? ( <div className="text-center"> <p className="text-blue-500">No topics yet</p> </div> ) : ( topics.recent.map((topic, index) => ( <li className="pb-5" key={index}> <Link to={`/posts/${topic.id}`} className="hover:text-indigo-500" > {topic.title} </Link> </li> )) )} </ul> </div> </div> <footer className="text-sm -mr-5"> <a href="#">Home</a>.<a href="#"> About</a>. <a href="#"> FAQs</a>.<a href="#"> Contact Us</a> </footer> </div> </section> </article> </main> </section> </> ); } export default App;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.portfolio.note.service; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; import org.apache.fineract.infrastructure.core.data.CommandProcessingResultBuilder; import org.apache.fineract.portfolio.client.domain.Client; import org.apache.fineract.portfolio.client.domain.ClientRepositoryWrapper; import org.apache.fineract.portfolio.client.exception.ClientNotFoundException; import org.apache.fineract.portfolio.group.domain.Group; import org.apache.fineract.portfolio.group.domain.GroupRepository; import org.apache.fineract.portfolio.group.exception.GroupNotFoundException; import org.apache.fineract.portfolio.loanaccount.domain.Loan; import org.apache.fineract.portfolio.loanaccount.domain.LoanRepository; import org.apache.fineract.portfolio.loanaccount.domain.LoanTransaction; import org.apache.fineract.portfolio.loanaccount.domain.LoanTransactionRepository; import org.apache.fineract.portfolio.loanaccount.exception.LoanNotFoundException; import org.apache.fineract.portfolio.loanaccount.exception.LoanTransactionNotFoundException; import org.apache.fineract.portfolio.note.domain.Note; import org.apache.fineract.portfolio.note.domain.NoteRepository; import org.apache.fineract.portfolio.note.domain.NoteType; import org.apache.fineract.portfolio.note.exception.NoteNotFoundException; import org.apache.fineract.portfolio.note.exception.NoteResourceNotSupportedException; import org.apache.fineract.portfolio.note.serialization.NoteCommandFromApiJsonDeserializer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class NoteWritePlatformServiceJpaRepositoryImpl implements NoteWritePlatformService { private final NoteRepository noteRepository; private final ClientRepositoryWrapper clientRepository; private final GroupRepository groupRepository; // private final SavingAccountRepository savingAccountRepository; private final LoanRepository loanRepository; private final LoanTransactionRepository loanTransactionRepository; private final NoteCommandFromApiJsonDeserializer fromApiJsonDeserializer; @Autowired public NoteWritePlatformServiceJpaRepositoryImpl(final NoteRepository noteRepository, final ClientRepositoryWrapper clientRepository, final GroupRepository groupRepository, final LoanRepository loanRepository, final LoanTransactionRepository loanTransactionRepository, final NoteCommandFromApiJsonDeserializer fromApiJsonDeserializer) { this.noteRepository = noteRepository; this.clientRepository = clientRepository; this.groupRepository = groupRepository; this.loanRepository = loanRepository; this.loanTransactionRepository = loanTransactionRepository; this.fromApiJsonDeserializer = fromApiJsonDeserializer; } private CommandProcessingResult createClientNote(final JsonCommand command) { final Long resourceId = command.getClientId(); final Client client = this.clientRepository.findOneWithNotFoundDetection(resourceId); if (client == null) { throw new ClientNotFoundException(resourceId); } final Note newNote = Note.clientNoteFromJson(client, command); this.noteRepository.save(newNote); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(newNote.getId()) // .withClientId(client.getId()) // .withOfficeId(client.officeId()) // .build(); } @Override public void createAndPersistClientNote(final Client client, final JsonCommand command) { final String noteText = command.stringValueOfParameterNamed("note"); if (StringUtils.isNotBlank(noteText)) { final Note newNote = new Note(client, noteText); this.noteRepository.save(newNote); } } private CommandProcessingResult createGroupNote(final JsonCommand command) { final Long resourceId = command.getGroupId(); final Group group = this.groupRepository.findOne(resourceId); if (group == null) { throw new GroupNotFoundException(resourceId); } final Note newNote = Note.groupNoteFromJson(group, command); this.noteRepository.save(newNote); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(newNote.getId()) // .withGroupId(group.getId()) // .withOfficeId(group.officeId()) // .build(); } private CommandProcessingResult createLoanNote(final JsonCommand command) { final Long resourceId = command.getLoanId(); final Loan loan = this.loanRepository.findOne(resourceId); if (loan == null) { throw new LoanNotFoundException(resourceId); } final String note = command.stringValueOfParameterNamed("note"); final Note newNote = Note.loanNote(loan, note); this.noteRepository.save(newNote); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(newNote.getId()) // .withOfficeId(loan.getOfficeId()) // .withLoanId(loan.getId()) // .build(); } private CommandProcessingResult createLoanTransactionNote(final JsonCommand command) { final Long resourceId = command.subentityId(); final LoanTransaction loanTransaction = this.loanTransactionRepository.findOne(resourceId); if (loanTransaction == null) { throw new LoanTransactionNotFoundException(resourceId); } final Loan loan = loanTransaction.getLoan(); final String note = command.stringValueOfParameterNamed("note"); final Note newNote = Note.loanTransactionNote(loan, loanTransaction, note); this.noteRepository.save(newNote); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(newNote.getId()) // .withOfficeId(loan.getOfficeId())// .withLoanId(loan.getId())// Loan can be associated .build(); } // private CommandProcessingResult createSavingAccountNote(final JsonCommand // command) { // // final Long resourceId = command.getSupportedEntityId(); // // final SavingAccount savingAccount = // this.savingAccountRepository.findOne(resourceId); // if (savingAccount == null) { throw new // SavingAccountNotFoundException(resourceId); } // // final String note = command.stringValueOfParameterNamed("note"); // final Note newNote = Note.savingNote(savingAccount, note); // // this.noteRepository.save(newNote); // // return new CommandProcessingResultBuilder() // // .withCommandId(command.commandId()) // // .withEntityId(newNote.getId()) // // .withClientId(savingAccount.getClient().getId()).withOfficeId(savingAccount.getClient().getOffice().getId()).build(); // } @Override public CommandProcessingResult createNote(final JsonCommand command) { this.fromApiJsonDeserializer.validateNote(command.json()); final String resourceUrl = getResourceUrlFromCommand(command); //command.getSupportedEntityType(); final NoteType type = NoteType.fromApiUrl(resourceUrl); switch (type) { case CLIENT: { return createClientNote(command); } case GROUP: { return createGroupNote(command); } case LOAN: { return createLoanNote(command); } case LOAN_TRANSACTION: { return createLoanTransactionNote(command); } // case SAVING_ACCOUNT: { // return createSavingAccountNote(command); // } default: throw new NoteResourceNotSupportedException(resourceUrl); } } private String getResourceUrlFromCommand(JsonCommand command) { final String resourceUrl; if (command.getClientId() != null) { resourceUrl = NoteType.CLIENT.getApiUrl(); } else if (command.getGroupId() != null) { resourceUrl = NoteType.GROUP.getApiUrl(); } else if (command.getLoanId() != null) { if (command.subentityId() != null) { resourceUrl = NoteType.LOAN_TRANSACTION.getApiUrl(); } else { resourceUrl = NoteType.LOAN.getApiUrl(); } } else if (command.getSavingsId() != null) { //TODO: SAVING_TRANSACTION type need to be add. resourceUrl = NoteType.SAVING_ACCOUNT.getApiUrl(); } else { resourceUrl = ""; } return resourceUrl; } private CommandProcessingResult updateClientNote(final JsonCommand command) { final Long resourceId = command.getClientId(); final Long noteId = command.entityId(); final NoteType type = NoteType.CLIENT; final Client client = this.clientRepository.findOneWithNotFoundDetection(resourceId); final Note noteForUpdate = this.noteRepository.findByClientIdAndId(resourceId, noteId); if (noteForUpdate == null) { throw new NoteNotFoundException(noteId, resourceId, type.name().toLowerCase()); } final Map<String, Object> changes = noteForUpdate.update(command); if (!changes.isEmpty()) { this.noteRepository.saveAndFlush(noteForUpdate); } return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(noteForUpdate.getId()) // .withClientId(client.getId()) // .withOfficeId(client.officeId()) // .with(changes) // .build(); } private CommandProcessingResult updateGroupNote(final JsonCommand command) { final Long resourceId = command.getGroupId(); final Long noteId = command.entityId(); final NoteType type = NoteType.GROUP; final Group group = this.groupRepository.findOne(resourceId); if (group == null) { throw new GroupNotFoundException(resourceId); } final Note noteForUpdate = this.noteRepository.findByGroupIdAndId(resourceId, noteId); if (noteForUpdate == null) { throw new NoteNotFoundException(noteId, resourceId, type.name().toLowerCase()); } final Map<String, Object> changes = noteForUpdate.update(command); if (!changes.isEmpty()) { this.noteRepository.saveAndFlush(noteForUpdate); } return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(noteForUpdate.getId()) // .withGroupId(group.getId()) // .withOfficeId(group.officeId()) // .with(changes).build(); } private CommandProcessingResult updateLoanNote(final JsonCommand command) { final Long resourceId = command.getLoanId(); final Long noteId = command.entityId(); final NoteType type = NoteType.LOAN; final Loan loan = this.loanRepository.findOne(resourceId); if (loan == null) { throw new LoanNotFoundException(resourceId); } final Note noteForUpdate = this.noteRepository.findByLoanIdAndId(resourceId, noteId); if (noteForUpdate == null) { throw new NoteNotFoundException(noteId, resourceId, type.name().toLowerCase()); } final Map<String, Object> changes = noteForUpdate.update(command); if (!changes.isEmpty()) { this.noteRepository.saveAndFlush(noteForUpdate); } return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(noteForUpdate.getId()) .withLoanId(loan.getId()).withOfficeId(loan.getOfficeId()).with(changes).build(); } private CommandProcessingResult updateLoanTransactionNote(final JsonCommand command) { final Long resourceId = command.subentityId(); final Long noteId = command.entityId(); final NoteType type = NoteType.LOAN_TRANSACTION; final LoanTransaction loanTransaction = this.loanTransactionRepository.findOne(resourceId); if (loanTransaction == null) { throw new LoanTransactionNotFoundException(resourceId); } final Loan loan = loanTransaction.getLoan(); final Note noteForUpdate = this.noteRepository.findByLoanTransactionIdAndId(resourceId, noteId); if (noteForUpdate == null) { throw new NoteNotFoundException(noteId, resourceId, type.name().toLowerCase()); } final Map<String, Object> changes = noteForUpdate.update(command); if (!changes.isEmpty()) { this.noteRepository.saveAndFlush(noteForUpdate); } return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(noteForUpdate.getId()) .withLoanId(loan.getId()).withOfficeId(loan.getOfficeId()).with(changes).build(); } // private CommandProcessingResult updateSavingAccountNote(final JsonCommand // command) { // // final Long resourceId = command.getSupportedEntityId(); // final Long noteId = command.entityId(); // final String resourceUrl = command.getSupportedEntityType(); // // final NoteType type = NoteType.fromApiUrl(resourceUrl); // // final SavingAccount savingAccount = // this.savingAccountRepository.findOne(resourceId); // if (savingAccount == null) { throw new // SavingAccountNotFoundException(resourceId); } // // final Note noteForUpdate = // this.noteRepository.findBySavingAccountIdAndId(resourceId, noteId); // // if (noteForUpdate == null) { throw new NoteNotFoundException(noteId, // resourceId, type.name().toLowerCase()); } // // final Map<String, Object> changes = noteForUpdate.update(command); // // if (!changes.isEmpty()) { // this.noteRepository.saveAndFlush(noteForUpdate); // } // // return new CommandProcessingResultBuilder() // // // .withCommandId(command.commandId()) // // // .withEntityId(noteForUpdate.getId()) // // // .withClientId(savingAccount.getClient().getId()).withOfficeId(savingAccount.getClient().getOffice().getId()).with(changes) // .build(); // } @Override public CommandProcessingResult updateNote(final JsonCommand command) { this.fromApiJsonDeserializer.validateNote(command.json()); final String resourceUrl = getResourceUrlFromCommand(command); //command.getSupportedEntityType(); final NoteType type = NoteType.fromApiUrl(resourceUrl); switch (type) { case CLIENT: { return updateClientNote(command); } case GROUP: { return updateGroupNote(command); } case LOAN: { return updateLoanNote(command); } case LOAN_TRANSACTION: { return updateLoanTransactionNote(command); } // case SAVING_ACCOUNT: { // return updateSavingAccountNote(command); // } default: throw new NoteResourceNotSupportedException(resourceUrl); } } @Override public CommandProcessingResult deleteNote(final JsonCommand command) { final Note noteForDelete = getNoteForDelete(command); this.noteRepository.delete(noteForDelete); return new CommandProcessingResultBuilder() // .withCommandId(null) // .withEntityId(command.entityId()) // .build(); } private Note getNoteForDelete(final JsonCommand command) { final String resourceUrl = getResourceUrlFromCommand(command);// command.getSupportedEntityType(); final Long noteId = command.entityId(); final NoteType type = NoteType.fromApiUrl(resourceUrl); Long resourceId = null; Note noteForUpdate = null; switch (type) { case CLIENT: { resourceId = command.getClientId(); noteForUpdate = this.noteRepository.findByClientIdAndId(resourceId, noteId); } break; case GROUP: { resourceId = command.getGroupId(); noteForUpdate = this.noteRepository.findByGroupIdAndId(resourceId, noteId); } break; case LOAN: { resourceId = command.getLoanId(); noteForUpdate = this.noteRepository.findByLoanIdAndId(resourceId, noteId); } break; case LOAN_TRANSACTION: { resourceId = command.subentityId(); noteForUpdate = this.noteRepository.findByLoanTransactionIdAndId(resourceId, noteId); } break; // case SAVING_ACCOUNT: { // noteForUpdate = // this.noteRepository.findBySavingAccountIdAndId(resourceId, // noteId); // } // break; case SAVING_ACCOUNT: break; } if (noteForUpdate == null) { throw new NoteNotFoundException(noteId, resourceId, type.name().toLowerCase()); } return noteForUpdate; } }
/** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value: any, other: any): number { if (value !== other) { const valIsDefined = value !== undefined; const valIsNull = value === null; const valIsReflexive = value === value; const othIsDefined = other !== undefined; const othIsNull = other === null; const othIsReflexive = other === other; const val = typeof value === "string" ? value.localeCompare(other) : -other; if ((!othIsNull && val > 0) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && val < 0) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } export default compareAscending; // import isSymbol from "../isSymbol.js"; // /** // * Compares values to sort them in ascending order. // * // * @private // * @param {*} value The value to compare. // * @param {*} other The other value to compare. // * @returns {number} Returns the sort order indicator for `value`. // */ // function compareAscending(value, other) { // if (value !== other) { // const valIsDefined = value !== undefined; // const valIsNull = value === null; // const valIsReflexive = value === value; // const valIsSymbol = isSymbol(value); // const othIsDefined = other !== undefined; // const othIsNull = other === null; // const othIsReflexive = other === other; // const othIsSymbol = isSymbol(other); // const val = typeof value === "string" ? value.localeCompare(other) : -other; // if ((!othIsNull && !othIsSymbol && !valIsSymbol && val > 0) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { // return 1; // } // if ((!valIsNull && !valIsSymbol && !othIsSymbol && val < 0) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { // return -1; // } // } // return 0; // } // export default compareAscending;
<?php /** * Template Name: Page - Left Sidebar * The template used for displaying page content in page.php * * @author Matthias Thom | http://upplex.de * @package upBootWP 0.1 */ get_header(); ?> <div class="container"> <div class="row"> <div class="col-md-4"> <?php get_sidebar(); ?> </div><!-- .col-md-4 --> <div class="col-md-8"> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php /* Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part('content', get_post_format()); ?> <?php endwhile; ?> <?php upbootwp_content_nav('nav-below'); ?> <?php else : ?> <?php get_template_part( 'no-results', 'index' ); ?> <?php endif; ?> </main><!-- #main --> </div><!-- #primary --> </div><!-- .col-md-8 --> </div><!-- .row --> </div><!-- .container --> <?php get_footer(); ?>
<template> <v-container> <v-card class="pa-4" rounded="lg" > <!-- 若無通知 --> <div v-if="!notifications.length" class="ma-4"> <EmptyNotification /> </div> <!-- 若有通知 --> <v-list v-else max-height="500" class="overflow-y-auto"> <!-- 刪除按鈕 --> <div class="btn_container"> <!-- 對話框 --> <v-dialog v-model="dialog" persistent max-width="600"> <template v-slot:activator="{ on, attrs }"> <v-btn color="red" outlined v-bind="attrs" v-on="on"> <span>刪除所有通知</span> </v-btn> </template> <v-card> <!-- 標題 --> <v-card-title class="headline font-weight-bold">刪除所有通知?</v-card-title> <!-- 內容 --> <v-card-text class="font-weight-bold">您確定要刪除所有的通知嗎? 此動作將無法復原。</v-card-text> <!-- 按鈕群組 --> <v-card-actions> <v-spacer></v-spacer> <v-btn color="primary" outlined @click="dialog = false"> <span class="font-weight-bold">返回</span> </v-btn> <v-btn color="red darken-1" outlined @click="[dialog = false, deleteAllNotifications()]"> <span class="font-weight-bold">刪除</span> </v-btn> </v-card-actions> </v-card> </v-dialog> <!-- 已讀按鈕 --> <v-btn @click="markAllNotifications" class="ma-2 white--text" :loading="notificationLoading" :disabled="unReadNotifications.length == 0" color="blue" > <span>全部設為已讀</span> </v-btn> </div> <template v-for="notification in notifications" > <v-list-item :key="notification.id"> <!-- 通知圖片 --> <v-list-item-avatar tile size="100"> <v-img :src="notification.data.avatar_url" alt="OrderConfirmed"></v-img> </v-list-item-avatar> <v-list-item-content> <!-- 標題 --> <v-list-item-title class="py-1 font-weight-bold"> {{ notification.data.title }} </v-list-item-title> <!-- 文字 --> <v-list-item-subtitle class="my-2"> <span class="font-weight-bold">{{ notification.data.body }}</span> </v-list-item-subtitle> <!-- 時間 --> <v-list-item-subtitle class="my-2"> <span class="font-weight-bold">{{ $moment(notification.data.created_at).format('YYYY年 MMM Do a h:mm:ss') }}</span> </v-list-item-subtitle> <!-- 已讀時間 --> <v-list-item-subtitle class="my-2" v-show="notification.read_at"> <span class="font-weight-bold">在 {{ $moment(notification.read_at).format('YYYY年 MMM Do a h:mm:ss') }} 看過這則通知</span> </v-list-item-subtitle> <!-- 已讀按鈕 --> <div class="btn_container"> <v-btn @click="markNotification(notification)" class="ma-4 pa-4 white--text" :loading="notificationLoading" :disabled="notification.read_at !== null" color="blue" > <span>設為已讀</span> </v-btn> </div> <v-divider class="my-2"></v-divider> </v-list-item-content> </v-list-item> </template> </v-list> </v-card> </v-container> </template> <script> import notificationMixin from '~/mixins/notificationMixin' export default { head() { return { title: '通知總覽', meta: [ { hid: 'description', name: 'description', content: '使用者所接收到的通知' } ] } }, middleware: 'authenticated', //* 要先通過驗證才能訪問此頁面 mixins: [notificationMixin], data() { return { dialog: false } } } </script> <style lang="scss"scoped> @media (max-width: 768px) { .v-list-item { min-height: 0; flex-direction: column; } .btn_container { text-align: center; } } </style>
from django.utils.http import urlencode from django.template.loader import render_to_string from django.conf import settings from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from utils.text import fmt def make_facebook_url(page_url, msg): title = u'%s: %s' % (msg, page_url) url = "https://www.facebook.com/sharer.php?%s" url_param = urlencode({'u': page_url, 't': title}) return url % url_param def make_twitter_url(page_url, message): url = "https://twitter.com/share/?%s" url_param = urlencode({'text': message, 'url': page_url}) return url % url_param def share_panel_context(facebook_url, twitter_url, embed_params, permalink): return { "share_panel_facebook_url": facebook_url, "share_panel_twitter_url": twitter_url, "share_panel_permalink": permalink, } def share_panel_context_for_video(video): page_url = reverse('videos:video', kwargs={'video_id':video.video_id}) abs_page_url = "{}://{}{}".format(settings.DEFAULT_PROTOCOL, settings.HOSTNAME, page_url) if video.latest_version() is not None: msg = _(u"Just found a version of this video with subtitles") else: msg = _("Check out this video and help make subtitles") email_message = _(u"Hey-- check out this video %(video_title)s and help make subtitles: %(url)s") email_message = fmt(email_message, video_title=video.title_display(), url=abs_page_url) return share_panel_context( make_facebook_url(abs_page_url, msg), make_twitter_url(abs_page_url, msg), { 'video_url': video.get_video_url() }, abs_page_url ) def add_share_panel_context_for_history(context, video, language=None): page_url = language.get_absolute_url() if language else video.get_absolute_url() abs_page_url = "{}://{}{}".format(settings.DEFAULT_PROTOCOL, settings.HOSTNAME, page_url) msg = _(u"%(language)s subtitles for %(video)s:") % { 'language': language, 'video':video.title_display(), } email_message = _(u"Hey-- just found %(language)s subtitles for %(video_title)s: %(url)s") email_message = fmt(email_message, video_title=video.title_display(), language=language, url=abs_page_url) if language: base_state = {'language': language.language_code} else: base_state = {} context.update(share_panel_context( make_facebook_url(abs_page_url, msg), make_twitter_url(abs_page_url, msg), { 'video_url': video.get_video_url(), 'base_state': base_state }, abs_page_url ))
syntax = "proto3"; option java_multiple_files = true; package foodSeller; message CreateFoodSellerRequest { string name = 1; string street = 2; int32 number = 3; string city = 4; string phone_number = 5; string email = 6; string password = 7; string photo = 8; } message UpdateFoodSellerNameRequest { int32 accountId = 1; string name = 2; } message UpdateFoodSellerAddressRequest { int32 accountId = 1; string street = 2; int32 number = 3; string city = 4; } message UpdateFoodSellerPhoneNumberRequest { int32 accountId = 1; string phoneNumber = 2; } message UpdateFoodSellerEmailRequest { int32 accountId = 1; string email = 2; } message UpdateFoodSellerPasswordRequest { int32 accountId = 1; string password = 2; } message DeleteFoodSellerAccountRequest { int32 accountId = 1; } message GetFoodSellerByIdRequest{ int32 accountId =1; } message GetAllFoodSellersRequest { } message GetPhotoRequest { int32 accountId = 1; } message FoodSellerEmptyResponse { } message GetFoodSellerByIdResponse{ int32 accountId =1; string email=2; string phoneNumber=3; string name=4; string address=5; } message GetAllFoodSellersResponse { string list = 1; } message GetPhotoResponse { string photo = 1; } service FoodSellerService { rpc CreateFoodSeller(CreateFoodSellerRequest) returns (FoodSellerEmptyResponse); rpc UpdateName(UpdateFoodSellerNameRequest) returns (FoodSellerEmptyResponse); rpc UpdateAddress(UpdateFoodSellerAddressRequest) returns (FoodSellerEmptyResponse); rpc UpdateEmail(UpdateFoodSellerEmailRequest) returns (FoodSellerEmptyResponse); rpc UpdatePassword(UpdateFoodSellerPasswordRequest) returns (FoodSellerEmptyResponse); rpc UpdatePhoneNumber(UpdateFoodSellerPhoneNumberRequest) returns (FoodSellerEmptyResponse); rpc DeleteAccount(DeleteFoodSellerAccountRequest) returns (FoodSellerEmptyResponse); rpc GetFoodSellerById(GetFoodSellerByIdRequest) returns (GetFoodSellerByIdResponse); rpc GetAllFoodSellers(GetAllFoodSellersRequest) returns (GetAllFoodSellersResponse); rpc GetFoodSellerPhoto(GetPhotoRequest) returns (GetPhotoResponse); }
import React, { useState, useEffect } from "react"; import { Form, Input, Button, message, Modal, DatePicker } from "antd"; import { useUpdateUserMutation } from "@/api/user"; import { IUser } from "@/interfaces/user"; import { Link } from "react-router-dom"; import Joi from "@hapi/joi"; import moment from "moment"; const updateSchema = Joi.object({ name: Joi.string().required().messages({ "string.empty": 'Trường "Tên" không được để trống', "any.required": 'Trường "Tên" là bắt buộc', }), fullname: Joi.string().required().messages({ "string.empty": 'Trường "Họ và tên đầy đủ" không được để trống', "any.required": 'Trường "Họ và tên đầy đủ" là bắt buộc', }), ngaysinh: Joi.date().min("1900-01-01").max("now").required().messages({ "date.base": 'Trường "ngày sinh" phải là kiểu ngày tháng hợp lệ', "date.empty": 'Trường "ngày sinh" không được để trống', "date.min": 'Trường "ngày sinh" phải lớn hơn hoặc bằng 1900-01-01', "date.max": 'Trường "ngày sinh" không được lớn hơn ngày hiện tại', "any.required": 'Trường "ngày sinh" là bắt buộc', }), }); interface UserProfileProps { handleHideUserProfile: () => void; } const UserProfile: React.FC<UserProfileProps> = ({ handleHideUserProfile }) => { const [form] = Form.useForm(); const [visible, setVisible] = useState(true); const [updateProfile] = useUpdateUserMutation(); const [errors, setErrors] = useState({}); const userString = localStorage.getItem("user"); const user = userString ? JSON.parse(userString) : {}; const userId = user._id; const initialValues = { // ...Các trường khác ngaysinh: moment(user.ngaysinh).format("YYYY-MM-DD"), // Định dạng ngày sinh theo "yyyy-MM-dd" }; useEffect(() => { form.setFieldsValue(initialValues); }, [initialValues]); const handleProfileUpdate = () => { form .validateFields() .then((values) => { const { error } = updateSchema.validate(values, { abortEarly: false }); if (error) { const validationErrors = {}; error.details.forEach((detail) => { const path = detail.path[0]; const message = detail.message; validationErrors[path] = message; }); setErrors(validationErrors); return; } const selectedDate = moment(values.ngaysinh, "YYYY-MM-DD").toDate() const updatedValues = { ...values, ngaysinh: selectedDate.toISOString(), _id: userId, }; updateProfile(updatedValues) .then(() => { const updatedUser = { ...user, ...values }; localStorage.setItem("user", JSON.stringify(updatedUser)); message.success("Cập nhật thông tin thành công"); form.resetFields(); setVisible(false); handleHideUserProfile(); }) .catch((error) => { const errorMessage = error.response.data.message; message.error(errorMessage); }); }) .catch((error) => { console.log("Validation error:", error); }); }; const handleCancel = () => { setVisible(false); handleHideUserProfile(); }; return ( <div> <Modal visible={visible} onCancel={handleCancel} title={<h3 className="text-center">Thông tin người dùng</h3>} footer={[ <Button key="cancel" onClick={handleCancel}> Hủy </Button>, <Button key="update" onClick={handleProfileUpdate}> Cập nhật </Button>, ]} > <Form form={form} layout="vertical" initialValues={user}> <Form.Item name="name" label="Tên" validateStatus={errors.name ? "error" : ""} help={errors.name} > <Input /> </Form.Item> <Form.Item name="fullname" label="Họ và tên đầy đủ" validateStatus={errors.fullname ? "error" : ""} help={errors.fullname} > <Input /> </Form.Item> <Form.Item name="ngaysinh" label="Ngày sinh" validateStatus={errors.ngaysinh ? "error" : ""} help={errors.ngaysinh} > <Input type="date" /> </Form.Item> </Form> </Modal> </div> ); }; export default UserProfile;
import React, {useEffect, useState} from 'react'; import {Link, useNavigate, useParams} from 'react-router-dom'; import Text from "../../components/Text.jsx"; import {patientGet, patientUpdate} from "../../../../http.js"; export default function PatientEdit({}) { const {pesel} = useParams(); const history = useNavigate(); const [name, setName] = useState(null); useEffect(() => { patientGet(pesel) .then(response => setName(response.name)); }, [pesel]); const onSubmit = event => { event.preventDefault(); patientUpdate(pesel, name) .then(() => history("/patients")); }; if (name === null) { return <div className="w-full max-w-sm container mt-20 mx-auto"> <Text>Loading</Text>... </div>; } return <div className="w-full max-w-sm container mt-20 mx-auto"> <form onSubmit={onSubmit}> <div className="w-full mb-5"> <label> <p className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"> <Text>PESEL</Text> </p> <input className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:text-gray-600" value={pesel} disabled/> </label> </div> <div className="w-full mb-5"> <label> <p className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"> <Text>Name</Text> </p> </label> <input className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:text-gray-600 focus:shadow-outline" value={name} onChange={event => setName(event.target.value)} placeholder="Enter name" /> </div> <div className="flex items-center justify-between"> <button className="block mt-5 bg-green-400 w-full hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:text-gray-600 focus:shadow-outline"> <Text>Edit patient</Text> </button> </div> <div className="text-center mt-4 text-gray-500"> <Link to="/patients"><Text>Cancel</Text></Link> </div> </form> </div>; };
import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; class TheFinalReflection { private final double pi; TheFinalReflection(double pi) { this.pi = pi; } //The getter public double getPi() {return pi;} } public class AccessingFinalFields { public static void main(String[] args) throws NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { System.out.println("---\"Accessing Advanced Fields\"---"); TheFinalReflection TFR = new TheFinalReflection(Math.PI); //Reflection begangs Field[] f = TFR.getClass().getDeclaredFields(); Method[] m = TFR.getClass().getDeclaredMethods(); //The real Process began for Fields for(Field x:f) { if(x.getName().equals("pi")) x.setAccessible(true); x.set(TFR,0.25); } //The real Process began for Methods for(Method x:m) { if(x.getName().equals("getPi")) { x.setAccessible(true); System.out.println(x.invoke(TFR)); } } } }
<?php namespace App\Controller; use App\Controller\AppController; /** * Followups Controller * * @property \App\Model\Table\FollowupsTable $Followups */ class FollowupsController extends AppController { /** * Index method * * @return \Cake\Network\Response|null */ public function index() { $this->paginate = [ 'contain' => ['People' //, 'Advocacies' ] ]; $followups = $this->paginate($this->Followups); $this->set(compact('followups')); $this->set('_serialize', ['followups']); } public function initialize() { parent::initialize(); $this->Auth->allow(); } /** * View method * * @param string|null $id Followup id. * @return \Cake\Network\Response|null * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function view($id = null) { $followup = $this->Followups->get($id, [ 'contain' => ['People', 'Advocacies', 'Users'] ]); $this->set('followup', $followup); $this->set('_serialize', ['followup']); } /** * Add method * * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise. */ public function add() { $followup = $this->Followups->newEntity(); if ($this->request->is('post')) { $followup = $this->Followups->patchEntity($followup, $this->request->data); if ($this->Followups->save($followup)) { $this->Flash->success(__('The followup has been saved.')); return $this->redirect(['action' => 'index']); } else { $this->Flash->error(__('The followup could not be saved. Please, try again.')); } } $people = $this->Followups->People->find('list', ['limit' => 200]); //$advocacies = $this->Followups->Advocacies->find('list', ['limit' => 200]); $users = $this->Followups->Users->find('list', ['limit' => 200]); $this->set(compact('followup', 'people', 'advocacies', 'users')); $this->set('_serialize', ['followup']); } /** * Edit method * * @param string|null $id Followup id. * @return \Cake\Network\Response|void Redirects on successful edit, renders view otherwise. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function edit($id = null) { $followup = $this->Followups->get($id, [ 'contain' => ['Users'] ]); if ($this->request->is(['patch', 'post', 'put'])) { $followup = $this->Followups->patchEntity($followup, $this->request->data); if ($this->Followups->save($followup)) { $this->Flash->success(__('The followup has been saved.')); return $this->redirect(['action' => 'index']); } else { $this->Flash->error(__('The followup could not be saved. Please, try again.')); } } $people = $this->Followups->People->find('list', ['limit' => 200]); $advocacies = $this->Followups->Advocacies->find('list', ['limit' => 200]); $users = $this->Followups->Users->find('list', ['limit' => 200]); $this->set(compact('followup', 'people', 'advocacies', 'users')); $this->set('_serialize', ['followup']); } /** * Delete method * * @param string|null $id Followup id. * @return \Cake\Network\Response|null Redirects to index. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $followup = $this->Followups->get($id); if ($this->Followups->delete($followup)) { $this->Flash->success(__('The followup has been deleted.')); } else { $this->Flash->error(__('The followup could not be deleted. Please, try again.')); } return $this->redirect(['action' => 'index']); } }
import 'dart:async'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:mvp_taplan/blocs/additional_sum_bloc/buy_together_bloc.dart'; import 'package:mvp_taplan/blocs/paymennt_bloc/payment_bloc.dart'; import 'package:mvp_taplan/blocs/paymennt_bloc/payment_event.dart'; import 'package:mvp_taplan/blocs/postcard_bloc/postcard_bloc.dart'; import 'package:mvp_taplan/blocs/theme_bloc/theme_bloc.dart'; import 'package:mvp_taplan/blocs/theme_bloc/theme_state.dart'; import 'package:mvp_taplan/features/screen_wishlist/present_model.dart'; import 'package:mvp_taplan/models/models.dart'; import 'package:mvp_taplan/theme/colors.dart'; import 'package:mvp_taplan/theme/text_styles.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:url_launcher/url_launcher.dart'; class Screen15 extends StatefulWidget { final MvpPresentModel currentModel; const Screen15({ super.key, required this.currentModel, }); @override State<Screen15> createState() => _Screen15State(); } class _Screen15State extends State<Screen15> { String dock = ''; void getDock() async { final dio = Dio(); try { final response = await dio.get( 'https://qviz.fun/api/v1/agreement/', options: Options(), ); dock = response.data['agreement']; setState(() {}); } catch (e) { rethrow; } } void setChecker(bool checker) async { final SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setBool('checker', checker); } @override void initState() { super.initState(); getDock(); } bool isPicked = false; Color textColor = AppTheme.mainGreenColor; @override Widget build(BuildContext context) { return MvpScaffoldModel( fontSize: 17, appBarLabel: 'Пользовательское соглашение\n(публичная оферта)', child: Padding( padding: EdgeInsets.symmetric( horizontal: getWidth(context, 16), ), child: BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { return Column( children: [ SizedBox( height: getHeight(context, 5), ), Align( alignment: Alignment.centerRight, child: Image.asset( 'assets/images/sk_logo_main.png', ), ), SizedBox( height: getHeight(context, 4), ), Image.asset( state.logoPath, ), SizedBox( height: getHeight(context, 31), ), Expanded( child: SizedBox( width: getWidth(context, 343), child: DecoratedBox( decoration: BoxDecoration( color: state.dockColor, borderRadius: BorderRadius.circular(12), border: Border.all( color: state.dockBorderColor, width: 1, ), ), child: Padding( padding: EdgeInsets.symmetric(vertical: getHeight(context, 10)), child: RawScrollbar( thumbVisibility: true, trackVisibility: true, radius: const Radius.circular(2), thumbColor: state.dockThumbColor, trackColor: state.dockTrackColor, child: SingleChildScrollView( primary: true, child: Padding( padding: EdgeInsets.symmetric( vertical: getHeight(context, 10), horizontal: getWidth(context, 16), ), child: Text( dock, style: TextLocalStyles.roboto400.copyWith( fontSize: 12, color: state.appBarTextColor, height: 14.06 / 12, ), ), ), ), ), ), ), ), ), SizedBox( height: getHeight(context, 24), ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ InkWell( onTap: () { isPicked = !isPicked; //setChecker(isPicked); setState(() {}); }, child: SizedBox( height: getHeight(context, 24), width: getHeight(context, 24), child: DecoratedBox( decoration: BoxDecoration( color: state.dockColor, borderRadius: BorderRadius.circular(2), border: Border.all( color: state.dockBorderColor, width: 1.5, ), ), child: isPicked ? SvgPicture.asset('assets/svg/check.svg') : null, ), ), ), SizedBox( width: getWidth(context, 10), ), Text( 'Подтверждаю, что мною полностью прочитны,\nпоняты и приняты условия Договора оферты\nи Политика конфиденциальности', style: TextLocalStyles.roboto400.copyWith( fontSize: 14, height: 14.06 / 12, color: textColor, ), ), ], ), SizedBox( height: getHeight(context, 25), ), Row( children: [ MvpGradientButton( opacity: 0.3, label: 'Скачать\nв pdf формате', gradient: AppTheme.mainGreyGradient, width: getWidth(context, 164), onTap: () async { final Uri url = Uri.parse('https://qviz.fun/media/agreement_v3/agreement.pdf/'); if (!await launchUrl(url)) { throw Exception('Could not launch $url'); } }, ), SizedBox( width: getWidth(context, 15), ), MvpGradientButton( label: 'Перейти\nк оплате', gradient: AppTheme.mainGreenGradient, width: getWidth(context, 164), onTap: () async { if (!isPicked) { textColor = Colors.red; setState(() {}); Timer( const Duration(seconds: 2), () { textColor = AppTheme.mainGreenColor; setState(() {}); }, ); } else { context.read<PaymentBloc>().add( InitPaymentEvent( amount: context.read<BuyTogetherBloc>().state.additionalSum, presentId: widget.currentModel.id, postcardSign: context.read<PostcardBloc>().state.postcardSign, ), ); } }, ), ], ), SizedBox( height: getHeight(context, 95), ), ], ); }, ), ), ); } }
package com.backend.softue.controllers; import com.backend.softue.models.ComponenteCompetencias; import com.backend.softue.services.ComponenteCompetenciasServices; import com.backend.softue.utils.checkSession.CheckSession; import com.backend.softue.utils.response.ErrorFactory; import com.backend.softue.utils.response.ResponseConfirmation; import com.backend.softue.utils.response.ResponseError; import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/componenteCompetencias") public class ComponenteCompetenciasController { @Autowired private ComponenteCompetenciasServices componenteCompetenciasServices; @Autowired private ErrorFactory errorFactory; @CheckSession(permitedRol = {"coordinador"}) @PostMapping() public ResponseEntity<?> crear(@Valid @RequestBody ComponenteCompetencias componenteCompetencias, BindingResult bindingResult) { try { if (bindingResult.hasErrors()) { String errorMessages = errorFactory.errorGenerator(bindingResult); return ResponseEntity.badRequest().body(new ResponseError("Input Error", errorMessages, "Bad Request")); } this.componenteCompetenciasServices.crear(componenteCompetencias); return ResponseEntity.ok(new ResponseConfirmation("Componente de competencias registrado correctamente")); } catch (Exception e) { return ResponseEntity.badRequest().body(new ResponseError(e)); } } @CheckSession(permitedRol = {"coordinador"}) @GetMapping() public ResponseEntity<?> listar() { try { return ResponseEntity.ok(this.componenteCompetenciasServices.listar()); } catch (Exception e) { return ResponseEntity.badRequest().body(new ResponseError(e)); } } @CheckSession(permitedRol = {"coordinador"}) @DeleteMapping("/{nombre}") public ResponseEntity<?> eliminar(@PathVariable String nombre) { try { this.componenteCompetenciasServices.eliminar(nombre); return ResponseEntity.ok(new ResponseConfirmation("Componente de competencias eliminada correctamente")); } catch (Exception e) { return ResponseEntity.badRequest().body(new ResponseError(e)); } } @CheckSession(permitedRol = {"coordinador"}) @PatchMapping() public ResponseEntity<?> actualizar(@Valid @RequestBody ComponenteCompetencias componenteCompetencias, BindingResult bindingResult) { try { if (bindingResult.hasErrors()) { String errorMessages = errorFactory.errorGenerator(bindingResult); return ResponseEntity.badRequest().body(new ResponseError("Input Error", errorMessages, "Bad Request")); } this.componenteCompetenciasServices.actualizar(componenteCompetencias); return ResponseEntity.ok(new ResponseConfirmation("Componente de compentencias actualizada correctamente")); } catch (Exception e) { return ResponseEntity.badRequest().body(new ResponseError(e)); } } }
// Copyright © 2020 Australian Government All rights reserved. import UIKit // MARK: Localization extensions extension AlertController { static func createAlertSheetController(localizedTitle: String, localizedMessage: String) -> AlertController { return AlertController(title: localizedTitle, message: localizedMessage, preferredStyle: .actionSheet) } static func createAlertController(localizedTitle: String, localizedMessage: String) -> AlertController { return AlertController(title: localizedTitle, message: localizedMessage, preferredStyle: .alert) } } extension UIAlertAction { convenience init(localizedTitle: String, style: UIAlertAction.Style, handler: ((UIAlertAction) -> Void)?) { self.init(title: localizedTitle, style: style, handler: handler) } } // MARK: UIAlertController cancel extension extension UIAlertController { func addCancelAction() { let cancelActionTitle = NSLocalizedString("global_cancel_button_title", tableName: "Feedback", bundle: Bundle.main, comment: "Cancel button title" ) let cancelAction = UIAlertAction(title: cancelActionTitle, style: .cancel, handler: nil) self.addAction(cancelAction) } func addDefaultAction(localizedTitle: String, handler: @escaping ((UIAlertAction) -> Void)) { let defaultAction = UIAlertAction(localizedTitle: localizedTitle, style: .default, handler: handler) self.addAction(defaultAction) } }
package com.webserver.core; import com.webserver.http.HttpRequest; import java.io.*; import java.net.Socket; import java.util.HashMap; import java.util.Map; /** * 负责与指定客户端进行HTTP交互 * HTTP协议要求与客户端的交互规则采取一问一答的方式。因此,处理客户端交互以三步形式完成: * 1.解析请求(一问) * 2.处理请求 * 3.发送响应(一答) */ public class ClientHandler implements Runnable{ private Socket socket; public ClientHandler(Socket socket){ this.socket=socket; } @Override public void run() { try { //1解析请求 HttpRequest request = new HttpRequest(socket); //2处理请求 //首先通过request获取请求中的抽象路径 String path = request.getUri(); File file = new File("webapps/myweb" + path); //若该资源存在 if (file.exists()&&file.isFile()){ OutputStream out = socket.getOutputStream(); //1.发送状态行 String line = "HTTP/1.1 200 OK"; byte[] data = line.getBytes("ISO8859-1"); out.write(data); out.write(13);//单独发送回车符 out.write(10);//单独发送换行符 //2:发送响应头 line = "Content-Type: text/html"; data = line.getBytes("ISO8859-1"); out.write(data); out.write(13); out.write(10); line = "Content-Length: " + file.length(); data = line.getBytes("ISO8859-1"); out.write(data); out.write(13); out.write(10); //单独发送CRLF表示响应头部分发送完毕! out.write(13); out.write(10); //3:发送响应正文(文件内容) //创建文件输入流读取要发送的文件数据 FileInputStream fis = new FileInputStream(file); int len; byte[] buf = new byte[1024 * 10]; while ((len = fis.read(buf)) != -1) { out.write(buf, 0, len); } }else{ System.out.println("该资源不存在!"); File notFoundPage=new File("webapps/root/404.html"); OutputStream out = socket.getOutputStream(); String line = "HTTP/1.1 404 NotFound"; byte[] data = line.getBytes("ISO8859-1"); out.write(data); out.write(13);//单独发送回车符 out.write(10);//单独发送换行符 //2:发送响应头 line = "Content-Type: text/html"; data = line.getBytes("ISO8859-1"); out.write(data); out.write(13); out.write(10); line = "Content-Length: " + notFoundPage.length(); data = line.getBytes("ISO8859-1"); out.write(data); out.write(13); out.write(10); //单独发送CRLF表示响应头部分发送完毕! out.write(13); out.write(10); //3:发送响应正文(文件内容) //创建文件输入流读取要发送的文件数据 FileInputStream fis = new FileInputStream(notFoundPage); int len; byte[] buf = new byte[1024 * 10]; while ((len = fis.read(buf)) != -1) { out.write(buf, 0, len); } } //3发送响应 /* 一个响应的大致内容: HTTP/1.1 200 OK(CRLF) Content-Type: text/html(CRLF) Content-Length: 2546(CRLF)(CRLF) 1011101010101010101...... */ System.out.println("响应发送完毕!"); }catch (Exception e) { e.printStackTrace(); }finally { //处理完毕后与客户端断开连接 try{ socket.close(); }catch (IOException e){ e.printStackTrace(); } } } }
const Product = require("../models/product"); const Cart = require("../models/cart"); exports.getProducts = (req, res, next) => { Product.fetchAll((products) => { res.render("shop/product-list", { prods: products, pageTitle: "All Products", path: "/products", }); }); }; exports.getIndex = (req, res, next) => { Product.fetchAll((products) => { res.render("shop/index", { prods: products, pageTitle: "Shop", path: "/", }); }); }; exports.getProduct = (req, res, next) => { const productId = req.params.productId; Product.findById(productId, (product) => { res.render("shop/product-detail", { product: product, pageTitle: "Product Detail - " + product.title, path: `/products/:${product.id}`, }); }); }; exports.postCart = (req, res, next) => { const prodId = req.body.productId; Product.findById(prodId, (product) => { Cart.addToCart(prodId, product.price); }); res.redirect("/cart"); }; exports.getCart = (req, res, next) => { Cart.getCart((cart) => { // fetch the products Product.fetchAll((products) => { const cartProducts = []; for (p of products) { const cartProductData = cart.products.find((prod) => prod.id === p.id); if (cartProductData) { cartProducts.push({ productData: p, quantity: cartProductData.quantity, }); } } res.render("shop/cart", { path: "/cart", pageTitle: "Your Cart", products: cartProducts, }); }); }); }; exports.postDeleteCartProduct = (req, res, next) => { const prodId = req.body.productId; Product.findById(prodId, (product) => { Cart.deleteProductFromCart(prodId, product); res.redirect("/cart"); }); }; exports.getOrders = (req, res, next) => { res.render("shop/orders", { path: "/orders", pageTitle: "Your Orders", }); }; exports.getCheckout = (req, res, next) => { res.render("shop/checkout", { path: "/checkout", pageTitle: "Checkout", }); };
/* * AppController.j * TrackingArea * * Created by Didier Korthoudt on November 2, 2015. * Copyright 2015, Your Company All rights reserved. */ @import <Foundation/Foundation.j> @import <AppKit/AppKit.j> @import <AppKit/CPTrackingArea.j> @class SensibleView; @class SensibleViewTA; @class SensibleViewAutoTA; @class SensibleViewWithoutCursorUpdate; @implementation AppController : CPObject { @outlet CPWindow theWindow; SensibleView v1; SensibleView v2; SensibleView v3; SensibleView v4; SensibleView v5; SensibleView v6; SensibleView v7; SensibleView v8; SensibleView v9; SensibleView v10; SensibleViewWithoutCursorUpdate v11; SensibleView v12; SensibleViewTA w2; SensibleView w3; SensibleViewAutoTA w4; SensibleView w5; SensibleView w6; SensibleView w7; @outlet SensibleView s1; SensibleView cursorCapturingView; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { // This is called when the application is done loading. var message = [[CPAlert alloc] init]; [message setMessageText:@"CPTrackingArea test application"]; [message setInformativeText:@"Play with various cases, try to drag mouse, observe events in the console, ..."]; [message setDelegate:self]; [message setAlertStyle:CPInformationalAlertStyle]; [message addButtonWithTitle:@"OK"]; [message beginSheetModalForWindow:theWindow modalDelegate:nil didEndSelector:nil contextInfo:nil]; } - (void)awakeFromCib { // This is called when the cib is done loading. // You can implement this method on any object instantiated from a Cib. // It's a useful hook for setting up current UI values, and other things. // In this case, we want the window from Cib to become our full browser window [theWindow setFullPlatformWindow:YES]; var p = [theWindow contentView]; // No tracking area v1 = [[SensibleView alloc] initWithFrame:CGRectMake(30, 10, 50, 50)]; [v1 setViewName:@"no_tracking_area"]; [v1 setViewColor:[CPColor greenColor]]; [v1 setViewCursor:[CPCursor crosshairCursor]]; [p addSubview:v1]; [self addLabel:@"No tracking area" forView:v1]; // CPTrackingMouseEnteredAndExited v2 = [[SensibleView alloc] initWithFrame:CGRectMake(160, 10, 50, 50)]; [v2 setViewName:@"CPTrackingMouseEnteredAndExited"]; [v2 setViewColor:[CPColor greenColor]]; [v2 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v2 userInfo:nil]; [v2 addTrackingArea:t]; [p addSubview:v2]; [self addLabel:@"MouseEnteredAndExited\nInVisibleRect" forView:v2]; // CPTrackingCursorUpdate v3 = [[SensibleView alloc] initWithFrame:CGRectMake(290, 10, 50, 50)]; [v3 setViewName:@"CPTrackingCursorUpdate"]; [v3 setViewColor:[CPColor greenColor]]; [v3 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingCursorUpdate | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v3 userInfo:nil]; [v3 addTrackingArea:t]; [p addSubview:v3]; [self addLabel:@"CursorUpdate\nInVisibleRect" forView:v3]; // CPTrackingMouseMoved v4 = [[SensibleView alloc] initWithFrame:CGRectMake(420, 10, 50, 50)]; [v4 setViewName:@"CPTrackingMouseMoved"]; [v4 setViewColor:[CPColor greenColor]]; [v4 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseMoved | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v4 userInfo:nil]; [v4 addTrackingArea:t]; [p addSubview:v4]; [self addLabel:@"MouseMoved\nInVisibleRect" forView:v4]; // CPTrackingMouseEnteredAndExited & CPTrackingCursorUpdate v5 = [[SensibleView alloc] initWithFrame:CGRectMake(550, 10, 50, 50)]; [v5 setViewName:@"CPTrackingMouseEnteredAndExited+CPTrackingCursorUpdate"]; [v5 setViewColor:[CPColor greenColor]]; [v5 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingCursorUpdate | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v5 userInfo:nil]; [v5 addTrackingArea:t]; [p addSubview:v5]; [self addLabel:@"MouseEnteredAndExited\nCursorUpdate\nInVisibleRect" forView:v5]; // CPTrackingMouseMoved & CPTrackingCursorUpdate v6 = [[SensibleView alloc] initWithFrame:CGRectMake(680, 10, 50, 50)]; [v6 setViewName:@"CPTrackingMouseMoved+CPTrackingCursorUpdate"]; [v6 setViewColor:[CPColor greenColor]]; [v6 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseMoved | CPTrackingCursorUpdate | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v6 userInfo:nil]; [v6 addTrackingArea:t]; [p addSubview:v6]; [self addLabel:@"MouseMoved\nCursorUpdate\nInVisibleRect" forView:v6]; // CPTrackingMouseEnteredAndExited & CPTrackingMouseMoved v7 = [[SensibleView alloc] initWithFrame:CGRectMake(810, 10, 50, 50)]; [v7 setViewName:@"CPTrackingMouseEnteredAndExited+CPTrackingMouseMoved"]; [v7 setViewColor:[CPColor greenColor]]; [v7 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingMouseMoved | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v7 userInfo:nil]; [v7 addTrackingArea:t]; [p addSubview:v7]; [self addLabel:@"MouseEnteredAndExited\nMouseMoved\nInVisibleRect" forView:v7]; // CPTrackingMouseEnteredAndExited & CPTrackingMouseMoved & CPTrackingCursorUpdate v8 = [[SensibleView alloc] initWithFrame:CGRectMake(940, 10, 50, 50)]; [v8 setViewName:@"CPTrackingMouseEnteredAndExited+CPTrackingMouseMoved+CPTrackingCursorUpdate"]; [v8 setViewColor:[CPColor greenColor]]; [v8 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingMouseMoved | CPTrackingCursorUpdate | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v8 userInfo:nil]; [v8 addTrackingArea:t]; [p addSubview:v8]; [self addLabel:@"MouseEnteredAndExited\nMouseMoved\nCursorUpdate\nInVisibleRect" forView:v8]; // nested views, superview implements cursorUpdate but does nothing v9 = [[SensibleView alloc] initWithFrame:CGRectMake(1070, 10, 50, 50)]; [v9 setViewName:@"Superview with cursorUpdate but doing nothing"]; [v9 setViewColor:[CPColor greenColor]]; [v9 setViewCursor:nil]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingCursorUpdate | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v9 userInfo:nil]; [v9 addTrackingArea:t]; [p addSubview:v9]; [self addLabel:@"Outer view implements\ncursorUpdate but does nothing.\nInner view implements\ncursorUpdate" forView:v9]; v10 = [[SensibleView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)]; [v10 setViewName:@"Subview with cursorUpdate"]; [v10 setViewColor:[CPColor blueColor]]; [v10 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingCursorUpdate | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v10 userInfo:nil]; [v10 addTrackingArea:t]; [v9 addSubview:v10]; // nested views, superview doesn't implement cursorUpdate but requests it v11 = [[SensibleViewWithoutCursorUpdate alloc] initWithFrame:CGRectMake(1200, 10, 50, 50)]; [v11 setViewName:@"Superview without cursorUpdate"]; [v11 setViewColor:[CPColor greenColor]]; [v11 setViewCursor:[CPCursor pointingHandCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingCursorUpdate | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v11 userInfo:nil]; [v11 addTrackingArea:t]; [p addSubview:v11]; [self addLabel:@"Outer view doesn't implement\ncursorUpdate but requests it.\nInner view implements\ncursorUpdate" forView:v11]; v12 = [[SensibleView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)]; [v12 setViewName:@"Subview with cursorUpdate"]; [v12 setViewColor:[CPColor blueColor]]; [v12 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingCursorUpdate | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v12 userInfo:nil]; [v12 addTrackingArea:t]; [v11 addSubview:v12]; // Not CPTrackingInVisibleRect w2 = [[SensibleViewTA alloc] initWithFrame:CGRectMake(160, 110, 50, 50)]; [w2 setViewName:@"Not CPTrackingInVisibleRect"]; [w2 setViewColor:[CPColor greenColor]]; [w2 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMake(0, 0, 25, 25) options:CPTrackingMouseEnteredAndExited | CPTrackingActiveInKeyWindow owner:w2 userInfo:nil]; [w2 addTrackingArea:t]; [p addSubview:w2]; [self addLabel:@"MouseEnteredAndExited\n(top-left quarter is the active area)" forView:w2]; // CPTrackingEnabledDuringMouseDrag w3 = [[SensibleView alloc] initWithFrame:CGRectMake(290, 110, 50, 50)]; [w3 setViewName:@"CPTrackingEnabledDuringMouseDrag"]; [w3 setViewColor:[CPColor greenColor]]; [w3 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect | CPTrackingEnabledDuringMouseDrag owner:w3 userInfo:nil]; [w3 addTrackingArea:t]; [p addSubview:w3]; [self addLabel:@"MouseEnteredAndExited\nInVisibleRect\nEnabledDuringMouseDrag" forView:w3]; // View in CPScrollView [s1 setViewName:@"View in CPScrollView"]; [s1 setViewColor:[CPColor greenColor]]; [s1 setViewCursor:[CPCursor crosshairCursor]]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:s1 userInfo:nil]; [s1 addTrackingArea:t]; // No itinial TA w4 = [[SensibleViewAutoTA alloc] initWithFrame:CGRectMake(420, 110, 50, 50)]; [w4 setViewName:@"No itinial TA"]; [w4 setViewColor:[CPColor greenColor]]; [w4 setViewCursor:[CPCursor crosshairCursor]]; [p addSubview:w4]; [self addLabel:@"This one has no initial\ntracking area but\nuses updateTrackingAreas to\nattach one" forView:w4]; // Two views with tracking areas where the owner is not the view itself w5 = [[SensibleView alloc] initWithFrame:CGRectMake(550, 110, 50, 50)]; [w5 setViewName:@"firstView"]; [w5 setViewColor:[CPColor greenColor]]; [w5 setViewCursor:[CPCursor crosshairCursor]]; [p addSubview:w5]; [self addLabel:@"(firstView)\nThis view has a tracking area\nowned by the blue view" forView:w5]; w6 = [[SensibleView alloc] initWithFrame:CGRectMake(680, 110, 50, 50)]; [w6 setViewName:@"secondView"]; [w6 setViewColor:[CPColor greenColor]]; [w6 setViewCursor:[CPCursor crosshairCursor]]; [p addSubview:w6]; [self addLabel:@"(secondView)\nThis view has a tracking area\nowned by the blue view" forView:w6]; w7 = [[SensibleView alloc] initWithFrame:CGRectMake(810, 110, 50, 50)]; [w7 setViewName:@"masterView"]; [w7 setViewColor:[CPColor blueColor]]; [w7 setViewCursor:[CPCursor crosshairCursor]]; [p addSubview:w7]; [self addLabel:@"I'm the owner of the\ntracking areas of\nthe 2 views on my left" forView:w7]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:w7 userInfo:@{ @"trigger": @"View 1" } ]; [w5 addTrackingArea:t]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:w7 userInfo:@{ @"trigger": @"View 2" } ]; [w6 addTrackingArea:t]; // Cursor update complex test for (var i = 0; i < 10; i++) { var v = [[SensibleView alloc] initWithFrame:CGRectMake((i == 0 ? 50 : 20), (i == 0 ? 240 : 20), 400-(i*40), 400-(i*40))]; [p addSubview:v]; p = v; [v setViewName:[CPString stringWithFormat:@"v%d",i]]; var c = [CPColor colorWithHexString:[CPString stringWithFormat:@"%d%d%d%d%d%d",i,i,i,i,i,i]]; [v setViewColor:c]; switch (i) { case 0: [v setViewCursor:[CPCursor crosshairCursor]]; break; case 1: [v setViewCursor:[CPCursor pointingHandCursor]]; break; case 2: [v setViewCursor:[CPCursor resizeNorthwestCursor]]; break; case 3: [v setViewCursor:[CPCursor IBeamCursor]]; break; case 4: [v setViewCursor:[CPCursor dragCopyCursor]]; break; case 5: [v setViewCursor:[CPCursor dragLinkCursor]]; break; case 6: [v setViewCursor:[CPCursor contextualMenuCursor]]; break; case 7: [v setViewCursor:[CPCursor openHandCursor]]; break; case 8: [v setViewCursor:[CPCursor closedHandCursor]]; break; case 9: [v setViewCursor:[CPCursor resizeNorthSouthCursor]]; break; } var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingCursorUpdate | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect | CPTrackingEnabledDuringMouseDrag owner:v userInfo:nil]; [v addTrackingArea:t]; } var p = [theWindow contentView]; for (var i = 0; i < 10; i++) { var v = [[SensibleView alloc] initWithFrame:CGRectMake((i == 0 ? 460 : 0), (i == 0 ? 240 : 0), 400-(i*40), 400-(i*40))]; [p addSubview:v]; p = v; [v setViewName:[CPString stringWithFormat:@"v%d",i]]; var c = [CPColor colorWithHexString:[CPString stringWithFormat:@"%d%d%d%d%d%d",i,i,i,i,i,i]]; [v setViewColor:c]; switch (i) { case 0: [v setViewCursor:[CPCursor crosshairCursor]]; break; case 1: [v setViewCursor:[CPCursor pointingHandCursor]]; break; case 2: [v setViewCursor:[CPCursor resizeNorthwestCursor]]; break; case 3: [v setViewCursor:[CPCursor IBeamCursor]]; break; case 4: [v setViewCursor:[CPCursor dragCopyCursor]]; break; case 5: [v setViewCursor:[CPCursor dragLinkCursor]]; break; case 6: [v setViewCursor:[CPCursor contextualMenuCursor]]; break; case 7: [v setViewCursor:[CPCursor openHandCursor]]; break; case 8: [v setViewCursor:[CPCursor closedHandCursor]]; break; case 9: [v setViewCursor:[CPCursor resizeNorthSouthCursor]]; break; } var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingCursorUpdate | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:v userInfo:nil]; [v addTrackingArea:t]; } var item = [CPButton buttonWithTitle:@"Add a view that catches cursor updates but not mouse entered/exited events"]; [item setTarget:self]; [item setAction:@selector(showHideView:)]; [item setCenter:CGPointMake(455, 660)]; [[theWindow contentView] addSubview:item]; } - (void)showHideView:(id)aSender { if (!cursorCapturingView) { cursorCapturingView = [[SensibleView alloc] initWithFrame:CGRectMake(250, 440, 410, 200)]; [cursorCapturingView setViewColor:[CPColor colorWithHexString:@"c8d3b2"]]; [cursorCapturingView setViewName:@"cursorCapturingView"]; [cursorCapturingView setViewCursor:[CPCursor disappearingItemCursor]]; [cursorCapturingView setAlphaValue:0.7]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingCursorUpdate | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:cursorCapturingView userInfo:nil]; [cursorCapturingView addTrackingArea:t]; [[theWindow contentView] addSubview:cursorCapturingView]; [aSender setTitle:@"Hide the view catching cursor updates but not mouse entered/exited events"]; } else if ([cursorCapturingView isHidden]) { [cursorCapturingView setHidden:NO]; [aSender setTitle:@"Hide the view catching cursor updates but not mouse entered/exited events"]; } else { [cursorCapturingView setHidden:YES]; [aSender setTitle:@"Add a view that catches cursor updates but not mouse entered/exited events"]; } } - (void)addLabel:(CPString)title forView:(CPView)view { var label = [CPTextField labelWithTitle:title], labelSize = [label frameSize], viewFrame = [view frame]; [label setFrameOrigin:CGPointMake(viewFrame.origin.x + viewFrame.size.width / 2 - labelSize.width / 2, viewFrame.origin.y + viewFrame.size.height + 4)]; [label setFont:[CPFont systemFontOfSize:9]]; [label setAlignment:CPCenterTextAlignment]; [label setVerticalAlignment:CPTopVerticalTextAlignment]; [[view superview] addSubview:label]; } @end @implementation SensibleView : CPView { CPString viewName @accessors; CPCursor viewCursor @accessors; CPColor viewColor; CPTextField coords; } - (id)initWithFrame:(CGRect)aFrame { self = [super initWithFrame:aFrame]; if (self) { coords = [CPTextField labelWithTitle:@"WWWW,WWWW"]; [coords setFont:[CPFont systemFontOfSize:9]]; [coords setAlignment:CPCenterTextAlignment]; [coords setCenter:CGPointMake(25,25)]; [coords setStringValue:@""]; [self addSubview:coords]; } return self; } - (void)mouseEntered:(CPEvent)anEvent { CPLog.trace("mouseEntered @"+viewName); [self setBackgroundColor:[CPColor redColor]]; var trigger = [[[anEvent trackingArea] userInfo] valueForKey:@"trigger"]; if (trigger) [coords setStringValue:trigger]; } - (void)mouseExited:(CPEvent)anEvent { CPLog.trace("mouseExited @"+viewName); [self setBackgroundColor:viewColor]; [coords setStringValue:@""]; } - (void)mouseMoved:(CPEvent)anEvent { var l = [anEvent locationInWindow]; [coords setStringValue:[CPString stringWithFormat:@"%d,%d",l.x,l.y]]; } - (void)cursorUpdate:(CPEvent)anEvent { CPLog.trace("cursorUpdate @"+viewName); if (viewCursor) [viewCursor set]; } - (void)setViewColor:(CPColor)aColor { viewColor = aColor; [self setBackgroundColor:aColor]; } @end @implementation SensibleViewWithoutCursorUpdate : CPView { CPString viewName @accessors; CPCursor viewCursor @accessors; CPColor viewColor; CPTextField coords; } - (id)initWithFrame:(CGRect)aFrame { self = [super initWithFrame:aFrame]; if (self) { coords = [CPTextField labelWithTitle:@"WWWW,WWWW"]; [coords setFont:[CPFont systemFontOfSize:9]]; [coords setAlignment:CPCenterTextAlignment]; [coords setCenter:CGPointMake(25,25)]; [coords setStringValue:@""]; [self addSubview:coords]; } return self; } - (void)mouseEntered:(CPEvent)anEvent { CPLog.trace("mouseEntered @"+viewName); [self setBackgroundColor:[CPColor redColor]]; var trigger = [[[anEvent trackingArea] userInfo] valueForKey:@"trigger"]; if (trigger) [coords setStringValue:trigger]; } - (void)mouseExited:(CPEvent)anEvent { CPLog.trace("mouseExited @"+viewName); [self setBackgroundColor:viewColor]; [coords setStringValue:@""]; } - (void)mouseMoved:(CPEvent)anEvent { var l = [anEvent locationInWindow]; [coords setStringValue:[CPString stringWithFormat:@"%d,%d",l.x,l.y]]; } - (void)setViewColor:(CPColor)aColor { viewColor = aColor; [self setBackgroundColor:aColor]; } @end @implementation SensibleViewTA : SensibleView - (void)updateTrackingAreas { CPLog.trace("updateTrackingAreas @"+viewName); [self removeAllTrackingAreas]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMake(0, 0, 25, 25) options:CPTrackingMouseEnteredAndExited | CPTrackingActiveInKeyWindow owner:self userInfo:nil]; [self addTrackingArea:t]; } @end @implementation SensibleViewAutoTA : SensibleView - (void)updateTrackingAreas { CPLog.trace("updateTrackingAreas @"+viewName); [self removeAllTrackingAreas]; var t = [[CPTrackingArea alloc] initWithRect:CGRectMakeZero() options:CPTrackingMouseEnteredAndExited | CPTrackingActiveInKeyWindow | CPTrackingInVisibleRect owner:self userInfo:nil]; [self addTrackingArea:t]; } @end
import React, { ReactNode, createContext, useEffect } from "react"; import RNBluetoothClassic from 'react-native-bluetooth-classic'; import { Button, Icon, IconButton, Text } from "react-native-paper"; import { ActivityIndicator, PermissionsAndroid, View } from "react-native"; import Snackbar from "react-native-snackbar"; export const BalanzaBluetoothContext = createContext<any | null>(null); const BalanzaBluetoothProvider = ({children}: {children: ReactNode}) => { const [loading, setLoading] = React.useState(false); const [bluetoothEnabled, setBluetoothEnabled] = React.useState(false); const [device, setDevice] = React.useState<any>(null) const [peso, setPeso] = React.useState<any>(null) useEffect(() => { checkBluetoothEnabled() }, []) useEffect(() => { if(bluetoothEnabled) connectToDevice() }, [bluetoothEnabled]) const checkBluetoothEnabled = async () => { setLoading(true); const enabled = await RNBluetoothClassic.isBluetoothEnabled(); setBluetoothEnabled(enabled); setLoading(false); } const connectToDevice = async () => { setLoading(true) await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { title: 'Se requiere permiso de acceso a la ubicación', message: 'Debemos permitir el acceso para conectarnos con la balanza ', buttonNeutral: 'Preguntarme luego', buttonNegative: 'Cancelar', buttonPositive: 'OK' } ); await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT, { title: 'Se requiere permiso de acceso a la ubicación', message: 'Debemos permitir el acceso para conectarnos con la balanza ', buttonNeutral: 'Preguntarme luego', buttonNegative: 'Cancelar', buttonPositive: 'OK' } ); try { const address = '00:08:F4:02:BC:F5'; // const device = await RNBluetoothClassic.getConnectedDevice(address); const paired = await RNBluetoothClassic.getBondedDevices(); const device = paired.find(d => d.address === address) console.log('DEVIVE', device) const con = await device.connect({}) setDevice(con) device.onDataReceived((data) => { // Eliminar los caracteres no numericos // let peso = data.data.replace(/[^0-9]/g, '') let peso = data.data.substring(0, data.data.length - 3) // console.log(data) setPeso(peso) }) } catch (error) { console.log('ERROR', error) Snackbar.show({ text: 'No se pudo conectar con la balanza', // text: JSON.stringify(error), duration: Snackbar.LENGTH_INDEFINITE, action: { text: 'Cerrar', textColor: 'red', onPress: () => { /* Do something. */ }, }, }); } finally { setLoading(false) } } return <BalanzaBluetoothContext.Provider value={{ bluetoothEnabled, loading, device, peso, connectToDevice, checkBluetoothEnabled }}> {children} </BalanzaBluetoothContext.Provider> } export default BalanzaBluetoothProvider
import { Box, Typography, useTheme } from "@mui/material"; interface IMessageErrorProps { text: string; errorMessage: boolean; } export const MessageError = ({ text, errorMessage, }: IMessageErrorProps): JSX.Element => { const theme = useTheme(); return ( <Box sx={{ display: "flex", justifyContent: "center", padding: "1rem 0", color: theme.palette.text.primary, }} > {errorMessage ? ( <Typography variant="h4" color="error"> {text} </Typography> ) : ( <Typography variant="h4">{text}</Typography> )} </Box> ); };
import { isServer } from "solid-js/web"; // Internals // src/internal/client/types.d.ts export interface Task { abort(): void; promise: Promise<void>; } export interface TickContext<T> { inv_mass: number; dt: number; opts: SpringOptions & { set: SpringSetter<T> }; settled: boolean; } export type Raf = { /** Alias for `requestAnimationFrame`, exposed in such a way that we can override in tests */ tick: (callback: (time: DOMHighResTimeStamp) => void) => any; /** Alias for `performance.now()`, exposed in such a way that we can override in tests */ now: () => number; /** A set of tasks that will run to completion, unless aborted */ tasks: Set<TaskEntry>; }; export type TaskCallback = (now: number) => boolean | void; export type TaskEntry = { c: TaskCallback; f: () => void }; // src/internal/client/timing.js /** SSR-safe RAF function. */ const request_animation_frame = isServer ? () => {} : requestAnimationFrame; /** SSR-safe now getter. */ const now = isServer ? () => Date.now() : () => performance.now(); export const raf: Raf = { tick: (_: any) => request_animation_frame(_), now: () => now(), tasks: new Set(), }; // src/motion/utils.js /** * @param {any} obj * @returns {obj is Date} */ export function is_date(obj: any): obj is Date { return Object.prototype.toString.call(obj) === "[object Date]"; } // src/internal/client/loop.js /** * @param {number} now * @returns {void} */ function run_tasks(now: number) { raf.tasks.forEach((task) => { if (!task.c(now)) { raf.tasks.delete(task); task.f(); } }); if (raf.tasks.size !== 0) { raf.tick(run_tasks); } } /** * Creates a new task that runs on each raf frame * until it returns a falsy value or is aborted */ export function loop(callback: TaskCallback): Task { let task: TaskEntry; if (raf.tasks.size === 0) { raf.tick(run_tasks); } return { promise: new Promise((fulfill: any) => { raf.tasks.add((task = { c: callback, f: fulfill })); }), abort() { raf.tasks.delete(task); }, }; } // createSpring hook import { Accessor, createEffect, createSignal, on } from "solid-js"; export type SpringOptions = { /** * Stiffness of the spring. Higher values will create more sudden movement. * @default 0.15 */ stiffness?: number; /** * Strength of opposing force. If set to 0, spring will oscillate indefinitely. * @default 0.8 */ damping?: number; /** * Precision is the threshold relative to the target value at which the * animation will stop based on the current value. * * From 0, if the target value is 500, and the precision is 500, it will stop * the animation instantly (no animation, similar to `hard: true`). * * From 0, if the target value is 500, and the precision is 0.01, it will stop the * animation when the current value reaches 499.99 or 500.01 (longer animation). * * @default 0.01 */ precision?: number; }; type SpringSetter<T> = ( newValue: T, opts?: { hard?: boolean; soft?: boolean | number } ) => Promise<void>; /** * Creates a signal and a setter that uses spring physics when interpolating from * one value to another. This means when the value changes, instead of * transitioning at a steady rate, it "bounces" like a spring would, * depending on the physics paramters provided. This adds a level of realism to * the transitions and can enhance the user experience. * * `T` - The type of the signal. It works for any basic data types that can be interpolated * like `number`, a `Date`, or even a collection of them `Array<T>` or a nested object of T. * * @param initialValue The initial value of the signal. * @param options Options to configure the physics of the spring. * * @example * const [progress, setProgress] = createSpring(0, { stiffness: 0.15, damping: 0.8 }); */ export function createSpring<T>( initialValue: T, options: SpringOptions = {} ): [Accessor<T>, SpringSetter<T>] { const [springValue, setSpringValue] = createSignal<T>(initialValue); const { stiffness = 0.15, damping = 0.8, precision = 0.01 } = options; const [lastTime, setLastTime] = createSignal<number>(0); const [task, setTask] = createSignal<Task | null>(null); const [current_token, setCurrentToken] = createSignal<object>(); const [lastValue, setLastValue] = createSignal<T>(initialValue); const [targetValue, setTargetValue] = createSignal<T | undefined>(); const [inv_mass, setInvMass] = createSignal<number>(1); const [inv_mass_recovery_rate, setInvMassRecoveryRate] = createSignal<number>(0); const [cancelTask, setCancelTask] = createSignal<boolean>(false); const set: SpringSetter<T> = (newValue, opts = {}) => { setTargetValue((_) => newValue); const token = current_token() ?? {}; setCurrentToken(token); if ( springValue() == null || opts.hard || (stiffness >= 1 && damping >= 1) ) { setCancelTask(true); setLastTime(raf.now()); setLastValue((_) => newValue); setSpringValue((_) => newValue); return Promise.resolve(); } else if (opts.soft) { const rate = opts.soft === true ? 0.5 : +opts.soft; setInvMassRecoveryRate(1 / (rate * 60)); setInvMass(0); // Infinite mass, unaffected by spring forces. } if (!task()) { setLastTime(raf.now()); setCancelTask(false); const _loop = loop((now) => { if (cancelTask()) { setCancelTask(false); setTask(null); return false; } setInvMass((_inv_mass) => Math.min(_inv_mass + inv_mass_recovery_rate(), 1) ); const ctx: TickContext<T> = { inv_mass: inv_mass(), opts: { set: set, damping: damping, precision: precision, stiffness: stiffness, }, settled: true, dt: ((now - lastTime()) * 60) / 1000, }; // @ts-ignore const next_value = tick_spring( ctx, lastValue(), springValue(), // @ts-ignore targetValue() ); setLastTime(now); setLastValue((_) => springValue()); setSpringValue((_) => next_value); if (ctx.settled) { setTask(null); } return !ctx.settled; }); setTask(_loop); } return new Promise<void>((fulfil) => { task()?.promise.then(() => { if (token === current_token()) fulfil(); }); }); }; const tick_spring = <T>( ctx: TickContext<T>, last_value: T, current_value: T, target_value: T ): T => { if (typeof current_value === "number" || is_date(current_value)) { // @ts-ignore const delta = target_value - current_value; // @ts-ignore const velocity = (current_value - last_value) / (ctx.dt || 1 / 60); // guard div by 0 const spring = ctx.opts.stiffness! * delta; const damper = ctx.opts.damping! * velocity; const acceleration = (spring - damper) * ctx.inv_mass; const d = (velocity + acceleration) * ctx.dt; if ( Math.abs(d) < ctx.opts.precision! && Math.abs(delta) < ctx.opts.precision! ) { return target_value; // settled } else { ctx.settled = false; // signal loop to keep ticking // @ts-ignore return is_date(current_value) ? new Date(current_value.getTime() + d) : current_value + d; } } else if (Array.isArray(current_value)) { // @ts-ignore return current_value.map((_, i) => // @ts-ignore tick_spring(ctx, last_value[i], current_value[i], target_value[i]) ); } else if (typeof current_value === "object") { const next_value = {}; for (const k in current_value) { // @ts-ignore next_value[k] = tick_spring( ctx, // @ts-ignore last_value[k], current_value[k], target_value[k] ); } // @ts-ignore return next_value; } else { throw new Error(`Cannot spring ${typeof current_value} values`); } }; return [springValue, set]; } export function createDerivedSpring<T>( target: Accessor<T>, opts?: SpringOptions ) { const [springValue, setSpringValue] = createSpring(target() ?? 0, opts); createEffect( on( () => target(), () => { setSpringValue(target() ?? 0); } ) ); return springValue; }
#include <stdio.h> //LINEAR SEARCH //structure is used to return two values from Extremes() struct pair { int min; int max; }; struct pair extremes(int n,int arr[n]) { struct pair MinMax; // if there is only one element if(n==1) { MinMax.min = arr[0]; MinMax.max = arr[0]; return MinMax; } // for more then one element we declare min and max if(arr[0]<arr[1]) { MinMax.min = arr[0]; MinMax.max = arr[1]; } else { MinMax.min = arr[1]; MinMax.max = arr[0]; } for(int i=0; i<n;i++) { if(arr[i]< MinMax.min) { MinMax.min=arr[i]; } else if ( arr[i]> MinMax.max) { MinMax.max=arr[i]; } } return MinMax; } int main(){ int n; scanf("%d", &n); int arr[n]; for(int i=0; i<n;i++) { scanf("%d", &arr[i]); } struct pair MinMax = extremes(n,arr); printf("min-%d\nmax-%d",MinMax.min,MinMax.max); return 0; }
import { ConfigProvider, Spin, SpinProps } from 'antd'; import { FC, ReactNode } from 'react'; interface LoadingProps { loading: boolean; loadingText?: string; children?: ReactNode; } const Loading: FC<LoadingProps & SpinProps> = ({ loading, children, loadingText = 'loading...', ...rest }) => { return ( <ConfigProvider theme={{ token: { colorPrimary: '#ffd850' } }} > <Spin size="large" tip={loadingText} spinning={loading} {...rest}> {children} </Spin> </ConfigProvider> ); }; export default Loading;
const router = require("express").Router(); const { Category, Product } = require("../../models"); // The `/api/categories` endpoint router.get("/", async (req, res) => { // find all categories // be sure to include its associated Products try { const allcategories = await Category.findAll({ include: [ { model: Product, attributes: ["product_name"], }, ], }); res.status(200).json(allcategories); } catch (err) { console.log(err); res.status(500).json(err); } }); //route /api/categories/id value router.get("/:id", async (req, res) => { // find one category by its `id` value // be sure to include its associated Products try { const allcategories = await Category.findByPk(req.params.id, { include: [ { model: Product, // attributes: ["product_id"], }, ], }); res.status(200).json(allcategories); } catch (err) { console.log(err); res.status(500).json(err); } }); router.post("/", async (req, res) => { // create a new category try { const newCategory = await Category.create({ category_name: req.body.category_name, }); res.status(200).json(newCategory); } catch (err) { res.status(500).json(err); } }); router.put("/:id", async (req, res) => { // update a category by its `id` value try { const updateCategory = await Category.update(req.body, { where: { id: req.params.id, }, }); res.status(200).json(updateCategory); } catch (err) { res.status(500).json(err); } }); router.delete("/:id", async (req, res) => { // delete a category by its `id` value try { const categoryData = await Category.destroy({ where: { id: req.params.id, }, }); if (!categoryData) { res.status(404).json({ message: "No Category Data found!", }); } res.status(200).json(categoryData); } catch (err) { res.status(500).json(err); } }); module.exports = router;
<script setup lang="ts"> import { useI18n } from 'vue-i18n' import { computed, ref } from 'vue' import axios from 'axios' import ApplicationForm from '~/components/auth/ApplicationForm.vue' import useErrorHandler from '~/composables/useErrorHandler' import { useStore } from '~/store' interface Props { id: number } const props = defineProps<Props>() const { t } = useI18n() const application = ref() const labels = computed(() => ({ title: t('components.auth.ApplicationEdit.title') })) const isLoading = ref(false) const fetchApplication = async () => { isLoading.value = true try { const response = await axios.get(`oauth/apps/${props.id}/`) application.value = response.data } catch (error) { useErrorHandler(error as Error) } isLoading.value = false } const refreshToken = async () => { isLoading.value = true try { const response = await axios.post(`oauth/apps/${props.id}/refresh-token`) application.value = response.data } catch (error) { useErrorHandler(error as Error) } isLoading.value = false } fetchApplication() const store = useStore() const secret = store.state.auth.applicationSecret store.state.auth.applicationSecret = undefined </script> <template> <main v-title="labels.title" class="main pusher" > <div class="ui vertical stripe segment"> <section class="ui text container"> <div v-if="isLoading" class="ui inverted active dimmer" > <div class="ui loader" /> </div> <template v-else> <router-link :to="{name: 'settings'}"> {{ $t('components.auth.ApplicationEdit.link.settings') }} </router-link> <h2 class="ui header"> {{ $t('components.auth.ApplicationEdit.header.appDetails') }} </h2> <div class="ui form"> <p> {{ $t('components.auth.ApplicationEdit.help.appDetails') }} </p> <div class="field"> <label for="copy-id">{{ $t('components.auth.ApplicationEdit.label.appId') }}</label> <copy-input id="copy-id" :value="application.client_id" /> </div> <div v-if="secret" class="field" > <div class="ui small warning message"> <h3 class="header"> {{ $t('components.auth.ApplicationEdit.header.appSecretWarning') }} </h3> <p> {{ $t('components.auth.ApplicationEdit.message.appSecretWarning') }} </p> </div> <label for="copy-secret">{{ $t('components.auth.ApplicationEdit.label.appSecret') }}</label> <copy-input id="copy-secret" :value="secret" /> </div> <div v-if="application.token != undefined" class="field" > <label for="copy-secret">{{ $t('components.auth.ApplicationEdit.label.accessToken') }}</label> <copy-input id="copy-secret" :value="application.token" /> <a href="" @click.prevent="refreshToken" > <i class="refresh icon" /> {{ $t('components.auth.ApplicationEdit.button.regenerateToken') }} </a> </div> </div> <h2 class="ui header"> {{ $t('components.auth.ApplicationEdit.header.editApp') }} </h2> <application-form :app="application" @updated="application = $event" /> </template> </section> </div> </main> </template>
/** * Converts an HTML table with class 'table-striped' into a PDF file and triggers a download. */ function generatePDF() { // Create a new jsPDF instance. const doc = new jspdf.jsPDF(); // Select all row elements (tr) from the table. const rows = document.querySelectorAll(".table-striped tr"); // Map each row to an array of its cell contents. const data = Array.from(rows).map((row, index) => { const cells = row.querySelectorAll("th, td"); return Array.from(cells).map((cell) => cell.textContent); }); // Extract headers from the data and format them for the PDF. const headers = data.shift().map((header) => ({ header, dataKey: header.toLowerCase().replace(/\s+/g, ""), })); // Add a title to the PDF. doc.text("Sales Report", 14, 20); // Use the autoTable plugin to add the table to the PDF with specified options. doc.autoTable({ startY: 30, columns: headers, body: data, theme: "striped", tableWidth: "auto", styles: { fontSize: 7, cellPadding: 2, overflow: "linebreak" }, columnStyles: { productName: { cellWidth: 40 }, productCategory: { cellWidth: 35 }, totalSales: { cellWidth: 25 }, percentContributionByCategoryAndRegion: { cellWidth: 35 }, percentContributionByRegion: { cellWidth: 25 }, orderDate: { cellWidth: "wrap" }, }, headStyles: { fillColor: [22, 160, 133] }, margin: { top: 25, right: 10, left: 10 }, }); // Save the created PDF with the given filename. doc.save("sales_report.pdf"); } // Attach an event listener to the button with class 'btn-pdf' to trigger PDF generation on click. document.querySelector(".btn-pdf").addEventListener("click", generatePDF);
using System; using System.ComponentModel; namespace MenuDemo { /// <summary> /// Defines the behavior of the application. /// </summary> public static class Program { /// <summary> /// The entry point of the application. /// </summary> /// <remarks> /// This method serves as the starting point of the console application. /// <para /> /// It continuously displays a menu of choices to the user and executes the /// corresponding actions based on their selection. /// <para /> /// The menu is displayed until the user decides to exit the application. /// </remarks> public static void Main() { while (true) { DisplayMenu(); var choice = GetUserChoice(); // Convert 1-based menu choice to 0-based index var choiceIndex = (int)choice - 1; // Check if choice is within the valid range if (choiceIndex >= 0 && choiceIndex < Enum .GetValues(typeof(MenuChoices)) .Length) // Check against all menu items // Perform action based on user choice index switch (choiceIndex) { case (int)MenuChoices.EatCandy: Console.WriteLine("You chose to Eat Candy."); // Add your Eat Candy logic here break; case (int)MenuChoices.GoFishing: Console.WriteLine("You chose to Go Fishing."); // Add your Go Fishing logic here break; case (int)MenuChoices.PlayBasketball: Console.WriteLine("You chose to Play Basketball."); // Add your Play Basketball logic here break; case (int)MenuChoices.Exit: Console.Write( "Are you sure you want to exit the application? (Y/N): " ); var confirmation = Console.ReadLine() .ToUpper()[0]; Console.WriteLine(); if (confirmation == 'Y') { Console.WriteLine("Exiting the application..."); return; // Exit the Main method } Console.Clear(); continue; default: Console.WriteLine( "Invalid choice. Please try again." ); break; } else Console.WriteLine("Invalid choice. Please try again."); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); Console.Clear(); // Clear the console for the next iteration } } /// <summary> /// Displays the menu of choices on the console. /// </summary> /// <remarks> /// This method iterates through all the available menu choices and displays them /// along with their corresponding numbers. /// <para /> /// The numbering of the choices starts from <c>1</c>. /// </remarks> private static void DisplayMenu() { Console.WriteLine("Please choose an action:\n"); var menuItemNumber = 1; foreach (MenuChoices choice in Enum.GetValues(typeof(MenuChoices))) if (choice != MenuChoices.Unknown) { var description = GetEnumDescription(choice); Console.WriteLine($"[{menuItemNumber}]: {description}"); menuItemNumber++; } Console.Write("\nEnter your selection: "); } /// <summary> /// Retrieves the description attribute value associated with the specified enum /// value. /// </summary> /// <param name="value"> /// The <see langword="enum" /> value for which to retrieve the /// description. /// </param> /// <returns> /// The description associated with the <see langword="enum" /> value, if /// available; otherwise, the /// string representation of the <see langword="enum" /> value. /// </returns> /// <remarks> /// This method retrieves the description attribute value, if present, associated /// with the specified <see langword="enum" /> value. /// <para /> /// If no description attribute is found, it returns the string representation of /// the <see langword="enum" /> value. /// </remarks> private static string GetEnumDescription(Enum value) { var field = value.GetType() .GetField(value.ToString()); var attribute = (DescriptionAttribute)Attribute.GetCustomAttribute( field, typeof(DescriptionAttribute) ); return attribute == null ? value.ToString() : attribute.Description; } /// <summary> /// Reads user input from the console and parses it into a /// <see cref="T:MenuDemo.MenuChoices" /> enumeration value. /// </summary> /// <returns> /// The <see cref="T:MenuDemo.MenuChoices" /> enumeration value corresponding to /// the user input. /// If the input cannot be parsed into a valid enumeration value, returns /// <see cref="F:MenuDemo.MenuChoices.Unknown" />. /// </returns> /// <remarks> /// This method reads a line of text from the console input and attempts to parse /// it into a <see cref="T:MenuDemo.MenuChoices" /> enumeration value. /// <para /> /// If the input matches any of the enumeration values, the corresponding /// enumeration value is returned. /// <para /> /// If the input cannot be parsed into a valid enumeration value, the method /// returns <see cref="F:MenuDemo.MenuChoices.Unknown" />. /// </remarks> private static MenuChoices GetUserChoice() { var input = Console.ReadLine(); return Enum.TryParse(input, out MenuChoices choice) ? choice : MenuChoices.Unknown; } } }
import React from 'react'; import {Button, Form, Input, Space} from "antd"; import {validateIPAddress, validatePort} from "../utils/validators"; export const ProxyForm = ({handleOk, handleCancel}) => { return ( <Form layout={"vertical"} onFinish={handleOk}> <Form.Item name="ipAddress" label="IP Address" rules={[ { required: true, message: 'Please input an IP address!', }, { validator: validateIPAddress, }, ]} > <Input placeholder={"128.128.128.128"} /> </Form.Item> <Form.Item name="port" label="Port" rules={[ { required: true, message: 'Please enter a port number!', }, { validator: validatePort } ]} > <Input maxLength={5} placeholder={"8080"} /> </Form.Item> <Form.Item> <Space> <Button type="primary" htmlType="submit" > Submit </Button> <Button type="default" onClick={handleCancel} > Cancel </Button> </Space> </Form.Item> </Form> ); };
package com.weareadaptive.auction.security; import com.weareadaptive.auction.IntegrationTest; import com.weareadaptive.auction.TestData; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import static com.weareadaptive.auction.TestData.ADMIN_AUTH_TOKEN; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; import static org.springframework.http.HttpHeaders.AUTHORIZATION; public class SecurityTest extends IntegrationTest { // Initialise the PostgreSQL container @Container public static PostgreSQLContainer<?> postgreSQLContainer = new PostgreSQLContainer<>("postgres:latest") .withDatabaseName("integration-tests-db") .withUsername("testUsername") .withPassword("testPassword"); // Dynamically replace the data source properties with those of the running container @DynamicPropertySource public static void postgresqlProperties(DynamicPropertyRegistry registry) { postgreSqlProperties(registry, postgreSQLContainer); } @Override @BeforeEach public void initialiseRestAssuredMockMvcStandalone() { super.initialiseRestAssuredMockMvcStandalone(); uri += "/api"; } @Test public void shouldBeUnauthorizedWhenNotAuthenticated() { //@formatter:off given() .baseUri(uri) .when() .get("/test") .then() .statusCode(HttpStatus.UNAUTHORIZED.value()); //@formatter:on } @Test public void shouldBeAuthenticated() { //@formatter:off given() .baseUri(uri) .header(AUTHORIZATION, ADMIN_AUTH_TOKEN) .when() .get("/test") .then() .statusCode(HttpStatus.OK.value()) .body(equalTo("houra")); //@formatter:on } @Test public void shouldBeAnAdmin() { //@formatter:off given() .baseUri(uri) .header(AUTHORIZATION, ADMIN_AUTH_TOKEN) .when() .get("/test/adminOnly") .then() .statusCode(HttpStatus.OK.value()) .body(equalTo("super")); //@formatter:on } //TODO @Disabled @Test public void shouldReturnForbiddenWhenNotAnAdmin() { //@formatter:off given() .baseUri(uri) .header(AUTHORIZATION, testData.user1Token()) .when() .get("/test/adminOnly") .then() .statusCode(HttpStatus.FORBIDDEN.value()); //@formatter:on } }
import 'package:core/src/cache/core/cache_model.dart'; /// An abstract class representing a cache operation. /// /// This class defines the basic operations that can be performed on a cache, /// such as adding items, removing items, /// clearing the cache, and retrieving items. /// /// The type parameter `T` represents the type of the cache model. abstract class CacheOperation<T extends CacheModel> { /// Adds an item to the cache. void add(T item); /// Adds a list of items to the cache. void addAll(List<T> items); /// Removes an item from the cache based on its ID. void remove(String id); /// Clears the cache, removing all items. void clear(); /// Retrieves all items from the cache. List<T> getAll(); /// Retrieves an item from the cache based on its ID. /// Returns `null` if the item is not found. T? get(String id); }
import { describe, it, expect, beforeEach, vi } from 'vitest' import { render, screen, cleanup, fireEvent } from '@testing-library/react' import { Router } from '../components/Router' import { getCurrentPath } from '../utils/utils' import { Link } from '../components/Link' import { Route } from '../components/Route' vi.mock('../utils/utils.js', () => ({ getCurrentPath: vi.fn() })) describe('Router', () => { beforeEach(() => { cleanup() vi.clearAllMocks() // cleanup }) it('should render without problems', () => { render(<Router routes={[]} />) expect(true).toBeTruthy() }) it('should render 404 if no routes match', () => { render(<Router routes={[]} defaultComponent={() => <h1>404</h1>} />) expect(screen.getByText('404')).toBeTruthy() }) it('should render the component of the first route that matches', () => { getCurrentPath.mockReturnValue('/about') const routes = [ { path: '/', Component: () => <h1>Home</h1> }, { path: '/about', Component: () => <h1>About</h1> } ] render(<Router routes={routes} />) expect(screen.getByText('About')).toBeTruthy() }) it('should navigate using Links', async () => { getCurrentPath.mockReturnValueOnce('/') const homeComponent = () => { return ( <> <h1>Home</h1> <Link to='/about'>Go to about</Link> </> ) } const aboutComponent = () => <h1>About</h1> render( <Router> <Route path='/' Component={homeComponent} /> <Route path='/about' Component={aboutComponent} /> </Router> ) // click on the link const button = screen.getByText('Go to about') fireEvent.click(button) const aboutTitle = await screen.findByText('About') expect(aboutTitle).toBeTruthy() }) })
#!/usr/bin/env python import torch # Set the device to GPU device = 'cuda' if torch.cuda.is_available() else ( 'mps' if torch.backends.mps.is_available() else 'cpu' ) # Increase the size of the tensors N = 10000 # Number of rows D_in = 10000 # Input dimension H = 10000 # Hidden layer dimension D_out = 10000 # Output dimension # Create random input and output data x = torch.randn(N, D_in, device=device) y = torch.randn(N, D_out, device=device) # Randomly initialize weights w1 = torch.randn(D_in, H, device=device) w2 = torch.randn(H, D_out, device=device) learning_rate = 1e-6 for t in range(500): # Forward pass: compute predicted y h = x.mm(w1) h_relu = h.clamp(min=0) y_pred = h_relu.mm(w2) # Compute and print loss loss = (y_pred - y).pow(1.5).sum().item() print(t, loss) # Backprop to compute gradients of w1 and w2 with respect to loss grad_y_pred = 1.75 * (y_pred - y) grad_w2 = h_relu.t().mm(grad_y_pred) grad_h_relu = grad_y_pred.mm(w2.t()) grad_h = grad_h_relu.clone() grad_h[h < 0] = 0 grad_w1 = x.t().mm(grad_h) # Update weights using gradient descent w1 -= learning_rate * grad_w1 w2 -= learning_rate * grad_w2
/* ________.__ _____.___.___________ / _____/| | _____ ____ ____ \__ | |\__ ___/ / \ ___| | \__ \ _/ ___\/ __ \ / | | | | \ \_\ \ |__/ __ \\ \__\ ___/ \____ | | | \______ /____(____ /\___ >___ > / ______| |____| \/ \/ \/ \/ \/ ╔════════════════════════════════════════════════════════════════════════╗ ║ ║ ║ ## Created by GlaceYT! ║ ║ ## Feel free to utilize any portion of the code ║ ║ ## DISCORD : https://discord.com/invite/xQF9f9yUEM ║ ║ ## YouTube : https://www.youtube.com/@GlaceYt ║ ║ ║ ╚════════════════════════════════════════════════════════════════════════╝ */ const { ApplicationCommandOptionType } = require('discord.js'); const db = require("../mongoDB"); const { EmbedBuilder, ActionRowBuilder, ButtonBuilder } = require('discord.js'); const { ButtonStyle } = require('discord.js'); module.exports = { name: "help", description: "Get information about bot and commands.", permissions: "0x0000000000000800", options: [], run: async (client, interaction) => { try { const musicCommandsEmbed = new EmbedBuilder() .setColor(client.config.embedColor) .setTitle('🎸 **Music Commands**') .addFields( { name: '🎹 Play', value: 'Stream a song from a given link or text from sources' }, { name: '⏹️ Stop', value: 'Makes the bot stop playing music and leave the voice' }, { name: '📊 Queue', value: 'View and manage the song queue of this server' }, { name: '⏭️ Skip', value: 'Skip the current playing song' }, { name: '⏸️ Pause', value: 'Pause the currently playing song' }, { name: '▶️ Resume', value: 'Resume the current paused song' }, { name: '🔁 Loop', value: 'Toggle loop mode for queue and current song' }, { name: '🔄 Autoplay', value: 'Enable or disable autoplay [play random songs ]' }, { name: '⏩ Seek', value: 'Seek to a specific time in the current song' }, { name: '⏮️ Previous', value: 'Play the previous song in the queue' }, { name: '🔀 Shuffle', value: 'Shuffle the songs in queue' }, { name: '📃 playlist', value: 'manage the playlists' } ) .setImage(`https://cdn.discordapp.com/attachments/1004341381784944703/1165201249331855380/RainbowLine.gif?ex=654f37ba&is=653cc2ba&hm=648a2e070fab36155f4171962e9c3bcef94857aca3987a181634837231500177&`); const basicCommandsEmbed = new EmbedBuilder() .setColor(client.config.embedColor) .setTitle('✨ **Basic Commands**') .addFields( { name: '🏓 Ping', value: "Check the bot's latency" }, { name: '🗑️ Clear', value: 'Clear the song queue of this server' }, { name: '⏱️ Time', value: 'Display the current song playback time' }, { name: '🎧 Filter', value: 'Apply filters to enhance the sound as you love' }, { name: '🎵 Now Playing', value: 'Display the currently playing song information' }, { name: '🔊 Volume', value: 'Adjust the music volume [ hearing at high volumes is risky ]' }, ) .setImage('https://cdn.discordapp.com/attachments/1150827819547504741/1168917372267151370/standard.gif?ex=65538222&is=65410d22&hm=b4994392f44679da41fc9304eb69deaa3769e136057556deec0db69ae8d33a97&') const button1 = new ButtonBuilder() .setLabel('YouTube') .setURL('https://www.youtube.com/channel/UCPbAvYWBgnYhliJa1BIrv0A') .setStyle(ButtonStyle.Link); const button2 = new ButtonBuilder() .setLabel('Discord') .setURL('https://discord.gg/FUEHs7RCqz') .setStyle(ButtonStyle.Link); const button3 = new ButtonBuilder() .setLabel('Code') .setURL('https://github.com/GlaceYT/MUSIC-BOT-v3.6') .setStyle(ButtonStyle.Link); const row = new ActionRowBuilder() .addComponents(button1, button2, button3); interaction.reply({ embeds: [musicCommandsEmbed, basicCommandsEmbed], components: [row] }).catch(e => {}); } catch (e) { console.error(e); } }, }; /* ________.__ _____.___.___________ / _____/| | _____ ____ ____ \__ | |\__ ___/ / \ ___| | \__ \ _/ ___\/ __ \ / | | | | \ \_\ \ |__/ __ \\ \__\ ___/ \____ | | | \______ /____(____ /\___ >___ > / ______| |____| \/ \/ \/ \/ \/ ╔════════════════════════════════════════════════════════════════════════╗ ║ ║ ║ ## Created by GlaceYT! ║ ║ ## Feel free to utilize any portion of the code ║ ║ ## DISCORD : https://discord.com/invite/xQF9f9yUEM ║ ║ ## YouTube : https://www.youtube.com/@GlaceYt ║ ║ ║ ╚════════════════════════════════════════════════════════════════════════╝ */
/* * Copyright (C) 2014 Freie Universität Berlin * * This file is subject to the terms and conditions of the GNU Lesser General * Public License v2.1. See the file LICENSE in the top level directory for more * details. */ /** * @defgroup board_nrf6310 NRF6310 (Nordic NRF Hardware Development Kit) * @ingroup boards * @brief Board specific files for the nRF51 boards nrf6310 or MOMMOSOFT BLE DEVKIT.N * @{ * * @file * @brief Board specific definitions for the nRF51 evaluation board nrf6310 * * @author Christian Kühling <[email protected]> * @author Timo Ziegler <[email protected]> * @author Frank Holtz <[email protected]> */ #ifndef __BOARD_H #define __BOARD_H #include "cpu.h" #ifdef __cplusplus extern "C" { #endif /** * @name Define the nominal CPU core clock in this board */ #define F_CPU (16000000UL) /** * @name Define the boards stdio * @{ */ #define STDIO UART_0 #define STDIO_BAUDRATE (115200U) #define STDIO_RX_BUFSIZE (64U) /** @} */ /** * @name Assign the hardware timer */ #define HW_TIMER TIMER_0 /** * @name LED pin definitions * @{ */ #define ONBOARD_LED 1 #define LED_RED_PIN (1 << 8) #define LED_GREEN_PIN (1 << 9) #define LED_BLUE_PIN (1 << 10) /** @} */ /** * @name Macros for controlling the on-board LEDs. * @{ */ #define LED_RED_ON (NRF_GPIO->OUTCLR = LED_RED_PIN) #define LED_RED_OFF (NRF_GPIO->OUTSET = LED_RED_PIN) #define LED_RED_TOGGLE (NRF_GPIO->OUT ^= LED_RED_PIN) #define LED_GREEN_ON (NRF_GPIO->OUTCLR = LED_GREEN_PIN) #define LED_GREEN_OFF (NRF_GPIO->OUTSET = LED_GREEN_PIN) #define LED_GREEN_TOGGLE (NRF_GPIO->OUT ^= LED_GREEN_PIN) #define LED_BLUE_ON (NRF_GPIO->OUTCLR = LED_BLUE_PIN) #define LED_BLUE_OFF (NRF_GPIO->OUTSET = LED_BLUE_PIN) #define LED_BLUE_TOGGLE (NRF_GPIO->OUT ^= LED_BLUE_PIN) /** @} */ /** * @brief Initialize board specific hardware, including clock, LEDs and std-IO */ void board_init(void); #ifdef __cplusplus } #endif #endif /** __BOARD_H */ /** @} */
import { useContext } from "react"; import { AuthContext } from "../../Componets/Providers/AuthProvider"; import Swal from "sweetalert2"; const AddToys = () => { const { user } = useContext(AuthContext) const handleAddToy = event => { event.preventDefault(); const form = event.target; const name = form.name.value; const sellerName = form.sellerName.value; const pictureUrl = form.pictureUrl.value; const rating = form.rating.value; const price = form.price.value; const detail = form.detail.value; const category = form.category.value; const quantity = form.quantity.value; const email = user?.email; const newToy = {name, email, sellerName, pictureUrl, rating, price, category, quantity, detail} // send data to the server fetch('https://toy-marketplace-server-pearl.vercel.app/toys', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(newToy) }) .then(res => res.json()) .then(data => { console.log(data) if (data.insertedId) { Swal.fire({ title: 'Toy Added Successfully', icon: 'success', confirmButtonText: 'Okk' }) } }) form.reset() } return ( <div className="rounded-md bg-base-200 my-16"> <h3 className="text-3xl font-extrabold text-center pt-8" style={{ fontFamily: 'Ranch, cursive' }}>Add Your Toy</h3> <p className="text-center mt-5 w-3/4 mx-auto">It is a long established fact that a reader will be distraceted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using Content here.</p> <div className="card-body md:w-3/4 py-[95px] mx-auto"> <form onSubmit={handleAddToy}> <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div className="form-control"> <input type="text" name="name" placeholder="Name" className="input" /> </div> <div className="form-control"> <input type="text" name="sellerName" placeholder="Seller Name" className="input" /> </div> <div className="form-control"> <input type="email" name="email" placeholder="Seller Email" defaultValue={user?.email} className="input" readOnly /> </div> <div className="form-control"> <input type="text" name="pictureUrl" placeholder="Picture URL" className="input focus:outline-none" /> </div> <div className="form-control"> <input type="text" name="rating" placeholder="Rating" className="input" /> </div> <div className="form-control"> <input type="text" name="price" placeholder="Price" className="input focus:outline-none" /> </div> <div className="form-control"> <input type="text" name="category" placeholder="Category" className="input" /> </div> <div className="form-control"> <input type="text" name="quantity" placeholder="Available quantity" className="input focus:outline-none" /> </div> </div> <div className="form-control mt-6 "> <textarea className="p-3 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-300" placeholder="Detail Description" name="detail" id="" cols="30" rows="10"></textarea> </div> <div className="form-control mt-6"> <input className="button cursor-pointer" type="submit" value="Add Toy" /> </div> </form> </div> </div> ); }; export default AddToys;
package io.github.domgew.kedis.commands.server import io.github.domgew.kedis.KedisException import io.github.domgew.kedis.commands.KedisFullCommand import io.github.domgew.kedis.impl.RedisMessage internal class AuthCommand( val username: String?, val password: String, ) : KedisFullCommand<Unit> { override fun fromRedisResponse(response: RedisMessage): Unit = when { response is RedisMessage.StringMessage && response.value == "OK" -> Unit response is RedisMessage.ErrorMessage -> handleRedisErrorResponse( response = response, ) else -> throw KedisException.WrongResponseException( message = "Expected string or null response, was ${response::class.simpleName}", ) } override fun toRedisRequest(): RedisMessage = RedisMessage.ArrayMessage( value = listOfNotNull( RedisMessage.BulkStringMessage(OPERATION_NAME), username ?.let { RedisMessage.BulkStringMessage(it) }, RedisMessage.BulkStringMessage(password), ), ) companion object { private const val OPERATION_NAME = "AUTH" } }
import React, { useEffect, useState } from "react"; import { availableSeats, changeSeatStatus } from "../../util/commonFunctions"; import Booking from "../Booking"; import "./home.css"; import seatsArr from "../../util/seats"; function Home() { //state of no. of seats wanted const [seatsWanted, setSeatsWanted] = useState(""); //collection of states for updating error messages const [error, setError] = useState(false); const [error1, setError1] = useState(false); //all seats Staus(booked/unbooked) collection state const [seatStatus, setStatus] = useState(seatsArr); // function which will be call on booking button click const handeleBooking = () => { if (!seatsWanted) { // if users try to book seat before giving input in the input box setError1("⚠️Select Seat First"); } else { //if input is valid booking will get proceeds // set error to deafult if it get updated setError1(false); //booking function invocation and updateing the seats state setStatus([...changeSeatStatus(seatStatus, seatsWanted)]); setSeatsWanted(""); } }; useEffect(() => { //user can't booked seats more then 7 at one time if (seatsWanted > 7) { setError(" ⚠️can't Booked more than 7 seats at one time"); } else { setError(false); } //error showing bellow button get reset if user againg fill data in input box if (seatsWanted) { setError1(false); } //if seats avilable is less than of desired value if (availableSeats(seatStatus) < seatsWanted) { setError(" ⚠️oops Not Enough Seats Avilabe"); } //dependacy arrays seats no input and seats status get change }, [seatsWanted, seatStatus]); return ( <div className="main_container_ticket"> <div> <div className="home_page"> <h1>Online Train Tickets</h1> <h3>Booking App 🚊</h3> <br /> <h1>Welcome!</h1> </div> <input placeholder="Enter Number of Seats" type={"number"} value={seatsWanted} onChange={(e) => setSeatsWanted(e.target.value)} /> {/* elements are responsible for showing error message in ui*/} {error && <p className="error_mess">{error}</p>} <div className="booking"> <br /> <br /> <button onClick={handeleBooking}>Book Tickets</button> <br /> <br /> <h4>Total Seats Available</h4> {/* elements are responsible for showing error message in ui*/} {error1 && <p className="error1_mess">{error1}</p>} {/* calling avialable function for getting avilable seats*/} <h1>{availableSeats(seatStatus)}</h1> </div> </div> <div> {/* passing seats data to get map in the booking components*/} <Booking seatStatus={seatStatus} /> </div> </div> ); } export default Home;
%language "c++" %skeleton "lalr1.cc" %require "3.2" %define api.token.raw %define api.token.constructor %define api.value.type variant %define parse.error verbose %code requires { #include <map> #include <list> #include <vector> #include <string> #include <iostream> #include <algorithm> #include <cstddef> #include <cstdlib> #include "State.hh" #include "Driver.hh" } // code req %param { MLE::Driver& ProgramDriver } %code { #include "Driver.hh" yy::parser::symbol_type yylex(MLE::Driver& ProgramDriver); inline void CLEAN(MLE::Driver& ProgramDriver) { ProgramDriver.Range.Start.reset(); ProgramDriver.Range.End.reset(); } } %token NUM %token CMD %token TEXT %token RANGE_WILDCARD %token COMMA %token WRITE %token NEWLINE %token QUIT %token APPEND %token INSERT %token PRINT %token LIST %token CHG %token DEL %token QUICK_DEL %type<size_t> NUM %% entries: entries entry | %empty ; entry: comms | error { CLEAN(ProgramDriver); yyclearin; yyerrok; } ; comms: comms comm | %empty { /* skip */ } ; ProgramDriver.Save(); yyclearin; yyerrok; } CLEAN(ProgramDriver); char line[256]; while (true) { std::cout << "-> "; std::cin.getline(line, 256); if (!std::strcmp(line, ".")) { break; } else if (!std::strcmp(line, "\\n")) { ProgramDriver.ProgramState->MainBuffer->push_back("\n"); continue; } else if (!std::strcmp(line, "\\.")) { ProgramDriver.ProgramState->MainBuffer->push_back("."); } else if (std::strcmp(line, "\0")) { ProgramDriver.ProgramState->MainBuffer->insert( ProgramDriver.ProgramState->MainBuffer->begin() + $1 - 1, line ); } } ProgramDriver.ProgramState->NeedWarning = true; yyclearin; yyerrok; } auto RangeStart_ = ProgramDriver.Range.Start.value(); auto RangeEnd_ = ProgramDriver.Range.End.value(); CLEAN(ProgramDriver); for ( size_t i = RangeStart_; i <= RangeEnd_; i++ ) { try { std::cout << i << "\t" << ProgramDriver.ProgramState->MainBuffer->at(i - 1) << "\n"; } catch (...) { break; } } CLEAN(ProgramDriver); } auto RangeStart_ = ProgramDriver.Range.Start.value(); auto x = RangeStart_; auto RangeEnd_ = ProgramDriver.Range.End.value(); CLEAN(ProgramDriver); if ((RangeStart_ - 1) >= ProgramDriver.ProgramState->MainBuffer->size()) { std::cout << "Line " << RangeStart_ << " nonexistent\n"; break; } auto b = ProgramDriver.ProgramState->MainBuffer->begin(); for (; RangeStart_ <= RangeEnd_; RangeStart_++) { std::cout << "Line " << x << '\n'; ProgramDriver.ProgramState->MainBuffer->erase((b + 1) + (--x)); } ProgramDriver.ProgramState->NeedWarning = true; } CLEAN(ProgramDriver); char line[256]; while (true) { std::cout << "-> "; std::cin.getline(line, 256); if (!std::strcmp(line, ".")) { break; } else if (!std::strcmp(line, "\\n")) { ProgramDriver.ProgramState->MainBuffer->push_back("\n"); continue; } else if (!std::strcmp(line, "\\.")) { ProgramDriver.ProgramState->MainBuffer->push_back("."); } else if (std::strcmp(line, "\0")) { ProgramDriver.ProgramState->MainBuffer->push_back(line); } } ProgramDriver.ProgramState->NeedWarning = true; yyclearin; yyerrok; } CLEAN(ProgramDriver); char line[256]; std::cout << "-> "; std::cin.getline(line, 256); try { ProgramDriver.ProgramState->MainBuffer->at($1 - 1) = line; ProgramDriver.ProgramState->NeedWarning = true; } catch (...) { std::cout << "Line " << $1 << " nonexistent\n"; } yyclearin; yyerrok; } CLEAN(ProgramDriver); if ($1 > ProgramDriver.ProgramState->MainBuffer->size()) { std::cout << "Line " << $1 << " nonexistent\n"; } else { ProgramDriver.ProgramState->MainBuffer->erase( ProgramDriver.ProgramState->MainBuffer->begin() + $1 - 1); ProgramDriver.ProgramState->NeedWarning = true; } CLEAN(ProgramDriver); yyclearin; yyerrok; } // quirks: extra newline for the answer! if (ProgramDriver.ProgramState->NeedWarning) { while (true) { std::cout << "Quit without saving? [y/n] "; char Response; std::cin >> Response; if (Response == 'n') { break; } else if (Response == 'y') { exit(0); } else { continue; } } } else { exit(0); } CLEAN(ProgramDriver); yyclearin; yyerrok; } size_t i = 1; for (auto str: *(ProgramDriver.ProgramState->MainBuffer)) { std::cout << i++ << "\t" << str << '\n'; } CLEAN(ProgramDriver); } ; range: range_literal COMMA range_literal ; if (!ProgramDriver.Range.Start.has_value()) { ProgramDriver.Range.Start = 1; ProgramDriver.Range.End.reset(); } else if (!ProgramDriver.Range.End.has_value()) { ProgramDriver.Range.End = ProgramDriver.ProgramState->MainBuffer->size(); } else { CLEAN(ProgramDriver); std::cout << "Logic error (RANGE_WILDCARD)\n"; while (true) { std::cout << "Quit or continue in an undefined state? [q/c] "; char Response; std::cin >> Response; if (Response == 'c') { break; } else if (Response == 'q') { exit(-1); } else { continue; } } } } size_t Correction = 1; if (!$1) { std::cout << "Correcting invalid null index to 1\n"; } else { Correction = $1; } if (!ProgramDriver.Range.Start.has_value()) { ProgramDriver.Range.Start = Correction; ProgramDriver.Range.End.reset(); } else if (!ProgramDriver.Range.End.has_value()) { ProgramDriver.Range.End = Correction; } else { std::cout << "Logic error (NUM)\n"; while (true) { CLEAN(ProgramDriver); std::cout << "Quit or continue in an undefined state? [q/c] "; char Response; std::cin >> Response; if (Response == 'c') { break; } else if (Response == 'q') { exit(-2); } else { continue; } } } } ; %%
package com.example.csc557.ui.theme.search import android.util.Log import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import coil.compose.rememberImagePainter import com.airbnb.lottie.compose.* import com.example.csc557.R as res import com.example.csc557.Screen import com.example.csc557.SharedViewModel import com.example.csc557.ui.theme.model.Car @Composable fun search(model: String?, navController: NavController, sharedViewModel: SharedViewModel) { // val scrollState = rememberScrollState() val scaffoldState = rememberScaffoldState() Scaffold( Modifier.fillMaxSize(), scaffoldState = scaffoldState, topBar = { topBar(navController = navController, searches = model.toString()) }, content = { paddingValues -> Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight(1f) // .verticalScroll(scrollState) .background(color = Color(16, 85, 205)) .padding(paddingValues = paddingValues), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { searchResult(searches = model.toString(), navController, sharedViewModel) } } ) } @Composable fun topBar(navController: NavController, searches: String) { TopAppBar( elevation = 0.dp, title = { Text("Results: $searches", color = Color.White) }, backgroundColor = Color(16, 85, 205), navigationIcon = { IconButton(onClick = { navController.navigateUp() }) { Icon(Icons.Filled.ArrowBack, null, tint = Color.White) } }, // actions = { // IconButton(onClick = {/* Do Something*/ }) { // Icon(Icons.Filled.Share, null) // } // IconButton(onClick = {/* Do Something*/ }) { // Icon(Icons.Filled.Settings, null) // } // }, ) } @Composable fun searchResult(searches: String, navController: NavController, sharedViewModel: SharedViewModel) { // val scrollState = rememberScrollState() var resultNotFound: Boolean by remember { mutableStateOf(false) } val theList = sharedViewModel.fetchCarSearches(searches.trim().lowercase()) { boolResult -> resultNotFound = boolResult } if (resultNotFound) { Column( modifier = Modifier .fillMaxSize() ) { val composition by rememberLottieComposition( spec = LottieCompositionSpec.RawRes( res.raw.search_not_found ) ) val progress by animateLottieCompositionAsState( composition = composition, iterations = LottieConstants.IterateForever ) LottieAnimation( modifier = Modifier .size(300.dp) .align(Alignment.CenterHorizontally), composition = composition, progress = { progress }, ) Text( modifier = Modifier .fillMaxWidth(), text = "car model $searches is not found. ┐( ̄~ ̄)┌", textAlign = TextAlign.Center, fontSize = 20.sp, color = Color.White ) } } else { LazyColumn( ) { itemsIndexed(theList) { index, item -> Surface( shape = RoundedCornerShape(22.dp), modifier = Modifier.padding(5.dp), elevation = 15.dp ) { Box( Modifier .height(350.dp) .width(350.dp) .fillMaxWidth() ) { Image( painter = rememberImagePainter(theList[index].image), contentDescription = "", contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize(0.99f) ) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.SpaceBetween, ) { Row( modifier = Modifier .padding(15.dp) .fillMaxWidth() .height(50.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = theList[index].model, fontSize = 20.sp, color = Color.Black ) Text( text = "RM" + theList[index].price.toString() + "\n/per hour", fontSize = 18.sp, color = Color.Black ) } Row( modifier = Modifier .fillMaxWidth() .height(55.dp), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically ) { // Text( // text = "Details", // modifier = Modifier.padding(start = 15.dp), // fontSize = 18.sp, // color = Color.White // ) Button( modifier = Modifier .fillMaxHeight() .width(150.dp), shape = RoundedCornerShape(topStart = 22.dp), colors = ButtonDefaults.buttonColors( backgroundColor = Color.DarkGray, contentColor = Color.White ), onClick = { navController.navigate(Screen.CarDetailScreen.route + "/${theList[index].model}/${theList[index].brand}") }) { Text(text = "Rent Now", fontSize = 17.sp) } } } } } } } } }
<!-- /** * OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures * all the essential functionalities required for any enterprise. * Copyright (C) 2006 OrangeHRM Inc., http://www.orangehrm.com * * OrangeHRM 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. * * OrangeHRM 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 OrangeHRM. * If not, see <https://www.gnu.org/licenses/>. */ --> <template> <div class="orangehrm-background-container"> <leave-conflict v-if="showLeaveConflict" :workshift-exceeded="isWorkShiftExceeded" :data="leaveConflictData" ></leave-conflict> <leave-assign-confirm-modal ref="confirmDialog"> </leave-assign-confirm-modal> <div class="orangehrm-card-container"> <oxd-text tag="h6" class="orangehrm-main-title"> {{ $t('leave.assign_leave') }} </oxd-text> <oxd-divider /> <oxd-form ref="formRef" :loading="isLoading" @submit-valid="onSave"> <oxd-form-row> <oxd-grid :cols="2" class="orangehrm-full-width-grid"> <oxd-grid-item> <employee-autocomplete v-model="leave.employee" :rules="rules.employee" required /> </oxd-grid-item> </oxd-grid> </oxd-form-row> <oxd-form-row> <oxd-grid :cols="2" class="orangehrm-full-width-grid"> <oxd-grid-item> <leave-type-dropdown v-model="leave.type" :rules="rules.type" :eligible-only="false" required /> </oxd-grid-item> <oxd-grid-item> <leave-balance :leave-data="leave"></leave-balance> </oxd-grid-item> </oxd-grid> </oxd-form-row> <oxd-form-row> <oxd-grid :cols="4" class="orangehrm-full-width-grid"> <oxd-grid-item> <date-input v-model="leave.fromDate" :label="$t('general.from_date')" :rules="rules.fromDate" :years="yearsArray" required /> </oxd-grid-item> <oxd-grid-item> <date-input v-model="leave.toDate" :label="$t('general.to_date')" :rules="rules.toDate" :years="yearsArray" required /> </oxd-grid-item> </oxd-grid> </oxd-form-row> <!-- Single Day|Duration --> <oxd-form-row v-if="appliedLeaveDuration == 1"> <oxd-grid :cols="4" class="orangehrm-full-width-grid"> <leave-duration-input v-model:duration="leave.duration.type" v-model:fromTime="leave.duration.fromTime" v-model:toTime="leave.duration.toTime" :label="$t('general.duration')" :work-shift="workShift" ></leave-duration-input> </oxd-grid> </oxd-form-row> <!-- Single Day|Duration --> <!-- Partial Day|Duration --> <oxd-form-row v-if="appliedLeaveDuration > 1"> <oxd-grid :cols="4" class="orangehrm-full-width-grid"> <oxd-grid-item> <oxd-input-field v-model="leave.partialOptions" type="select" :label="$t('leave.partial_days')" :options="partialOptions" /> </oxd-grid-item> <leave-duration-input v-if="showDuration" v-model:duration="leave.duration.type" v-model:fromTime="leave.duration.fromTime" v-model:toTime="leave.duration.toTime" :partial="true" :label="$t('general.duration')" :work-shift="workShift" ></leave-duration-input> <leave-duration-input v-if="showStartDay" v-model:duration="leave.duration.type" v-model:fromTime="leave.duration.fromTime" v-model:toTime="leave.duration.toTime" :partial="true" :label="$t('leave.start_day')" :work-shift="workShift" ></leave-duration-input> <leave-duration-input v-if="showEndDay" v-model:duration="leave.endDuration.type" v-model:fromTime="leave.endDuration.fromTime" v-model:toTime="leave.endDuration.toTime" :partial="true" :label="$t('leave.end_day')" :work-shift="workShift" ></leave-duration-input> </oxd-grid> </oxd-form-row> <!-- Partial Day|Duration --> <oxd-form-row> <oxd-grid :cols="2" class="orangehrm-full-width-grid"> <oxd-grid-item> <oxd-input-field v-model="leave.comment" type="textarea" :label="$t('general.comments')" :rules="rules.comment" /> </oxd-grid-item> </oxd-grid> </oxd-form-row> <oxd-divider /> <oxd-form-actions> <required-text /> <submit-button :label="$t('leave.assign')" /> </oxd-form-actions> </oxd-form> </div> </div> </template> <script> import { required, validSelection, validDateFormat, shouldNotExceedCharLength, endDateShouldBeAfterStartDate, } from '@/core/util/validation/rules'; import {yearRange} from '@ohrm/core/util/helper/year-range'; import {diffInDays} from '@ohrm/core/util/helper/datefns'; import {APIService} from '@ohrm/core/util/services/api.service'; import LeaveTypeDropdown from '@/orangehrmLeavePlugin/components/LeaveTypeDropdown'; import LeaveDurationInput from '@/orangehrmLeavePlugin/components/LeaveDurationInput'; import LeaveBalance from '@/orangehrmLeavePlugin/components/LeaveBalance'; import EmployeeAutocomplete from '@/core/components/inputs/EmployeeAutocomplete'; import LeaveConflict from '@/orangehrmLeavePlugin/components/LeaveConflict'; import LeaveAssignConfirmModal from '@/orangehrmLeavePlugin/components/LeaveAssignConfirmModal'; import useLeaveValidators from '@/orangehrmLeavePlugin/util/composable/useLeaveValidators'; import useForm from '@ohrm/core/util/composable/useForm'; import useDateFormat from '@/core/util/composable/useDateFormat'; const leaveModel = { employee: null, type: null, fromDate: null, toDate: null, comment: '', partialOptions: null, duration: { type: null, fromTime: null, toTime: null, }, endDuration: { type: null, fromTime: null, toTime: null, }, }; const defaultWorkshift = { startTime: '9:00', endTime: '17:00', }; export default { name: 'LeaveAssign', components: { 'leave-type-dropdown': LeaveTypeDropdown, 'leave-duration-input': LeaveDurationInput, 'leave-balance': LeaveBalance, 'employee-autocomplete': EmployeeAutocomplete, 'leave-conflict': LeaveConflict, 'leave-assign-confirm-modal': LeaveAssignConfirmModal, }, setup() { const http = new APIService( window.appGlobal.baseUrl, '/api/v2/leave/employees/leave-requests', ); const {serializeBody, validateLeaveBalance, validateOverlapLeaves} = useLeaveValidators(http); const {formRef, reset} = useForm(); const {userDateFormat} = useDateFormat(); return { http, reset, formRef, serializeBody, userDateFormat, validateLeaveBalance, validateOverlapLeaves, }; }, data() { return { isLoading: false, leave: {...leaveModel}, rules: { type: [required], fromDate: [required, validDateFormat(this.userDateFormat)], toDate: [ required, validDateFormat(this.userDateFormat), endDateShouldBeAfterStartDate( () => this.leave.fromDate, this.$t('general.to_date_should_be_after_from_date'), {allowSameDate: true}, ), ], comment: [shouldNotExceedCharLength(250)], employee: [required, validSelection], }, partialOptions: [ {id: 1, label: this.$t('leave.all_days'), key: 'all'}, {id: 2, label: this.$t('leave.start_day_only'), key: 'start'}, {id: 3, label: this.$t('leave.end_day_only'), key: 'end'}, {id: 4, label: this.$t('leave.start_and_end_day'), key: 'start_end'}, ], showLeaveConflict: false, isWorkShiftExceeded: false, leaveConflictData: null, yearsArray: [...yearRange()], workShift: {...defaultWorkshift}, }; }, computed: { appliedLeaveDuration() { return diffInDays(this.leave.fromDate, this.leave.toDate); }, showDuration() { const id = this.leave.partialOptions?.id; return id && id === 1; }, showStartDay() { const id = this.leave.partialOptions?.id; return id && (id === 2 || id === 4); }, showEndDay() { const id = this.leave.partialOptions?.id; return id && (id === 3 || id === 4); }, }, watch: { 'leave.employee': function (employee) { if (employee?.id) { this.http .request({ method: 'GET', url: `/api/v2/pim/employees/${employee.id}/work-shift`, }) .then((response) => { const {data} = response.data; this.workShift = data; }); } else { this.workShift = {...defaultWorkshift}; } }, appliedLeaveDuration: function (duration) { if (duration === 1) { this.leave.duration.type = {id: 1, label: 'Full Day', key: 'full_day'}; } else { this.leave.duration.type = null; } }, 'leave.fromDate': function (fromDate) { if (!fromDate || this.leave.toDate) return; this.leave.toDate = fromDate; }, }, methods: { onSave() { this.isLoading = true; this.leaveConflictData = null; this.showLeaveConflict = false; this.validateLeaveBalance(this.leave) .then(async ({balance}) => { if (balance <= 0) { const confirmation = await this.$refs.confirmDialog.showDialog(); if (confirmation !== 'ok') { return Promise.reject(); } } return this.validateOverlapLeaves(this.leave); }) .then(({isConflict, isOverWorkshift, data}) => { if (isConflict) { this.leaveConflictData = data; this.showLeaveConflict = true; this.isWorkShiftExceeded = isOverWorkshift; return Promise.reject(); } return this.http.create(this.serializeBody(this.leave)); }) .then(() => { this.$toast.saveSuccess(); this.reset(); }) .catch(() => { this.showLeaveConflict && this.$toast.warn({ title: this.$t('general.warning'), message: this.$t('leave.failed_to_submit'), }); }) .finally(() => { this.isLoading = false; }); }, }, }; </script>
# Event Horizon ## [Website](https://yandax.pythonanywhere.com/) ## Inspiration In the wake of COVID-19, small businesses have been struggling to get back up to speed, with many unfortunately going [out of business](https://torontosun.com/news/local-news/covid-killing-off-canadas-small-businesses-report). Locals have traditionally hosted festivals to inject activity back into their businesses. However, with many of these festivals having been [canceled](https://www.cbc.ca/news/canada/toronto/taste-of-danforth-festival-back-toronto-1.6935023) throughout COVID-19, it has been difficult for them to regain traction. Just within the last few weeks, many of our friends have mentioned that they would have gone to the Taste of Danforth Festival or Toronto Chinatown Festival if they had known they were happening. With hopes of supporting local economies and small businesses, our team decided to create [Event Horizon](https://yandax.pythonanywhere.com/), an event aggregator to bring attention to local festivals and celebrations that may not have the budget for strong marketing. ## What it does [Event Horizon](https://yandax.pythonanywhere.com/) collects events through a custom-made API and filters them based on your preferences (search terms, locations, date/time, category). The output is an interactive and informative page of events in the form of cards, each of which contains the event's name, location, date, and thumbnail. By clicking on a card, you can see additional details such as the event description, exact date/time, venue location and rating, ticket information, and event website. Additional features: - Add an event to your calendar with one click - Mobile-friendly design ## Installation Requirements: - System: Python (3.9) - Packages: Beautiful Soup (4.12.2), dateparser (1.1.8), Flask (2.2.5), Requests (2.31.0) Instructions: 1. Clone the repository 2. Set up Python venv 3. Install required dependencies 4. Set up `config.json` with valid API keys 5. Run `python flask_app.py` and navigate to the specified page ## How we built it [Event Horizon](https://yandax.pythonanywhere.com/) is a web application developed using the [Flask](https://flask.palletsprojects.com/en/2.3.x/) framework, with a custom CSS/jQuery front-end design for a smoother and quicker user experience. The front end was first drafted and then designed in [Figma](https://www.figma.com/) before being implemented. To set the foundations of our project, we built our own internal Events API by parsing Google search results. Then, we implemented IP-based location identification with the [IP Geolocation API](https://ipgeolocation.io/) to narrow down search results and added website features for date and filter selection. Finally, we investigated and added a bunch of additional features for improved user experience, like integration with calendars, directions/maps information, etc. ## Challenges we ran into - Learning to use Figma, designing the website, and converting it to code - The team is pretty new to web design, so designing the entire website was quite a challenge; in particular, creating smooth CSS/JS animations for cards and modals - Since we're all beginner hackers, settling on an interesting idea to start with was quite difficult as well - Searching for a suitable free API, finding none available, and then figuring out how to parse Google results - Figuring out how to geolocate users and how to use that as a search parameter ([UULE](https://valentin.app/uule.html)) ## What we learned and accomplishments that we're proud of - Learning to outline and prototype in Figma - Creating clean transitions and animations in CSS for event cards and modals - Making our own internal events API by parsing Google searches, and displaying that data in an easily understandable and accessible method - Adaptable structure for many different event types, from concerts to conferences - Figuring out the structure of UULE location parameters and Google Calendar links ## What's next for EventHorizon - Suggesting similar events - Improving the website UI/UX - Include a map for routes to the venue and display venue location - Sort listed events by certain parameters (length, date, cost, proximity, etc.) - Button for "more events" to return more than 10 events
function runToAuthorizeScopes() { /* Run this after setting the scopes to authorize the script before you trigger it via onEdit To add the requierd scopes - open up your appsscript.json file via Settings and add this: "oauthScopes": [ "https://www.googleapis.com/auth/spreadsheets", "https://mail.google.com/" ] */ console.log(`Make sure to update your appsscript.json file before running this`) } function scriptSettings() { return { triggerColumn: 'C', //"ENTER COLUMN - e.g. D", dataEndingColumn: 'C', // "ENTER THE COLUMN IN WHICH THE TARGET DATA ENDS - e.g. Z", recipientColumn: 'B', // "ENTER THE COLUMN THAT CONTAINS YOUR RECIPIENT - e.g. Z", emailSubjectColumn: 'K', // "ENTER THE COLUMN THAT CONTAINS YOUR EMAIL SUBJECT - e.g. Z", emailBodyColumn: 'L', // "ENTER THE COLUMN THAT CONTAINS YOUR EMAIL BODY - e.g. Z", } } function translateLetterToColumn(letter) { let column = 0 for (i=0; i < letter.length; i++) { column += (letter.charCodeAt(i) - 64) * Math.pow(26, letter.length - i - 1) } return column } function onCheckboxEdit(e) { const triggeredValues = { sheet: e.source.getActiveSheet(), row: e.range.getRow(), column: e.range.getColumn(), } var html = HtmlService.createTemplateFromFile("email.html"); var htmlText = html.evaluate().getContent(); Logger.log(htmlText); var targetRange = triggeredValues.sheet.getRange(triggeredValues.row, 1, 1, translateLetterToColumn(scriptSettings().dataEndingColumn)) var targetValues = targetRange.getValues() var options = {htmlBody: htmlText, name: 'GDG C'}; var textBody = "This email requires HTML Support"; var recipient = targetValues[0][translateLetterToColumn(scriptSettings().recipientColumn)-1] var checkboxValue = targetValues[0][translateLetterToColumn(scriptSettings().triggerColumn)-1]; var subject1 = "Subject Line Goes Here"; var subject = targetValues[0][translateLetterToColumn(scriptSettings().emailSubjectColumn)-1] if(triggeredValues.column = translateLetterToColumn(scriptSettings().triggerColumn) && checkboxValue == true) { console.log("Checkbox was marked true") console.log(`Sending email to ${recipient}`) GmailApp.sendEmail(recipient, subject1, textBody, options); } else if (triggeredValues.column = translateLetterToColumn(scriptSettings().triggerColumn) && checkboxValue == false) { console.log("Checkbox was marked false") } else { console.log("Something unexpected happened") } }
{% load static %} <!DOCTYPE html> <html lang="en"> <head> {% block meta %} <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="Buy home decor plants. Flowering plants and succulents."> <meta name="keywords" content="plants, small plants, flowers, succulents, home decor, pots, indoor plants"> {% endblock %} {% block extra_meta %} {% endblock %} {% block corecss %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@200;300;400;700&display=swap"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <link href="//cdn-images.mailchimp.com/embedcode/classic-061523.css" rel="stylesheet" type="text/css"> <link rel="apple-touch-icon" sizes="180x180" href="{% static 'favicon/apple-touch-icon.png' %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static 'favicon/favicon-32x32.png' %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'favicon/favicon-16x16.png' %}"> <link rel="manifest" href="{% static 'favicon/site.webmanifest' %}"> {% endblock %} {% block extra_css %} {% endblock %} {% block corejs %} <script src="https://kit.fontawesome.com/4eae670378.js" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-+sLIOodYLS7CIrQpBjl+C7nPvqq+FbNUBDunl/OZv93DB7Ln/533i8e/mZXLi/P+" crossorigin="anonymous"> </script> <!-- stripe --> <script src="https://js.stripe.com/v3/"></script> {% endblock %} {% block extra_js %} {% endblock %} <title>Live Plants {% block extra_title %}{% endblock %}</title> </head> <body> <header class="container-fluid fixed-top"> <div id="topnav" class="row bg-white pt-lg-2 d-none d-lg-flex"> <div class="row text-center my-auto py-1 py-lg-0 text-center"> <a href="{% url 'home' %}" class="nav-link main-logo-link"> <h2 class="logo logo-font my-0 pl-2 mx-auto">Live Plants</h2> </a> </div> <div class="col-12 col-lg-4 my-auto py-1 py-lg-0"> <form method="GET" action="{% url 'items' %}"> <div class="input-group w-100"> <input class="form-control border border-black rounded-0" type="text" name="q" placeholder="Search our site" aria-label="Search"> <div class="input-group-append"> <button class="form-control btn btn-black border border-black rounded-0" type="submit"> <span class="icon"> <i class="fas fa-search"></i> </span> </button> </div> </div> </form> </div> <div class="col-12 col-lg-4 my-auto py-1 py-lg-0"> <ul class="list-inline list-unstyled text-center text-lg-right my-0"> <li class="list-inline-item dropdown"> <a class="text-black nav-link" href="#" id="user-options" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <div class="text-center"> <div><i class="fas fa-user fa-lg"></i></div> <p class="my-0">My Account</p> </div> </a> <div class="dropdown-menu border-0" aria-labelledby="user-options"> {% if request.user.is_authenticated %} {% if request.user.is_superuser %} <a href="{% url 'add_item' %}" class="dropdown-item">Product Management</a> {% endif %} <a href="{% url 'profile' %}" class="dropdown-item">My Profile</a> <a href="{% url 'account_logout' %}" class="dropdown-item">Logout</a> {% else %} <a href="{% url 'account_signup' %}" class="dropdown-item">Register</a> <a href="{% url 'account_login' %}" class="dropdown-item">Login</a> {% endif %} </div> </li> <li class="list-inline-item"> <a class="{% if grand_total %}text-info font-weight-bold{% else %}text-black{% endif %} nav-link" href="{% url 'view_cart' %}"> <div class="text-center"> <div><i class="fas fa-shopping-bag fa-lg"></i></div> <p class="my-0"> {% if grand_total %} €{{ grand_total|floatformat:2 }} {% else %} €0.00 {% endif %} </p> </div> </a> </li> </ul> </div> </div> <div id="delivery-banner" class="row text-center"> <div class="col bg-light text-info"> <div class="logo logo-font" id="logo-dis"> <a href="{% url 'home' %}"> Live Plants</a> </div> <a href="{% url 'items' %}" class="banner" > <h6 class="logo-font my-1">Free shipping on orders over €{{ free_delivery_threshold }}! </a> </h6> </div> </div> <!-- navbar toggler --> <div class="row bg-white mob-nav"> <nav class="navbar navbar-expand-lg navbar-light w-100"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#main-nav" aria-controls="main-nav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> {% include 'includes/mobile-top-header.html' %} {% include 'includes/main-nav.html' %} </nav> </div> </header> {% if messages %} <div class="message-container"> {% for message in messages %} {% with message.level as level %} {% if level == 40 %} {% include 'includes/toasts/toast_error.html' %} {% elif level == 30 %} {% include 'includes/toasts/toast_warning.html' %} {% elif level == 25 %} {% include 'includes/toasts/toast_success.html' %} {% else %} {% include 'includes/toasts/toast_info.html' %} {% endif %} {% endwith %} {% endfor %} </div> {% endif %} {% block page_header %} {% endblock %} {% block content %} {% endblock %} <div> <footer class="footer mt-auto py-3"> <div class="container pt-3"> <section class="footer"> <div class="row d-flex justify-content-between"> <!-- mailchimp --> <div id="mc_embed_shell"> <div id="mc_embed_signup"> <form action="https://gmail.us21.list-manage.com/subscribe/post?u=1d01aee275bdacb3db9432361&amp;id=3d12422a4d&amp;f_id=00e063e1f0" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank"> <div id="mc_embed_signup_scroll"> <h5>Subscribe</h5> <div class="indicates-required"><span class="asterisk">*</span>required</div> <div class="mc-field-group"> <label for="mce-EMAIL">Email Address <span class="asterisk">*</span> </label> <input type="email" name="EMAIL" class="required email" id="mce-EMAIL" required="" value=""><span id="mce-EMAIL-HELPERTEXT" class="helper_text"></span></div> <div id="mce-responses" class="clear foot"> <div class="response" id="mce-error-response" style="display: none;"></div> <div class="response" id="mce-success-response" style="display: none;"> </div> </div> <div aria-hidden="true" style="position: absolute; left: -5000px;"> /* real people should not fill this in and expect good things - do not remove this or risk form bot signups */ <input type="text" name="b_1d01aee275bdacb3db9432361_3d12422a4d" tabindex="-1" value=""> </div> <div class="optionalParent"> <div class="clear foot"> <input type="submit" name="subscribe" id="mc-embedded-subscribe" class="button" value="Subscribe"> </div> </div> </div> </form> </div> </div> <!-- end mail chimp --> <div> <ul class="list-inline" id="footer-list"> <li> <a href="{% url 'contact:contact' %}">Contact Us</a> </li> <li> <a href="https://www.privacypolicygenerator.info/live.php?token=YSHZUauOohMIkKw63vnN49saSegPqAzX" target="_blank">Privacy Policy</a> </li> <li> <a href=" {% url 'blog:blog_list' %}">Blog</a> </li> <li> <a href="https://www.facebook.com/profile.php?id=100094665704253" rel="external nofollow noopener" target="_blank">Facebook</a> </li> <!-- <li> <small>For educational purposes only.</small> </li> --> </ul> </div> <!-- last footer --> </div> </section> </div> <div class="text-center"> <small>© 2023 Copyright: For educational purposes only.</small> </div> </footer> </div> {% block postloadjs %} <!-- mailchimp --> <script src="//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js"></script> <script> (function ($) { window.fnames = new Array(); window.ftypes = new Array(); fnames[0] = 'EMAIL'; ftypes[0] = 'email'; fnames[1] = 'FNAME'; ftypes[1] = 'text'; fnames[2] = 'LNAME'; ftypes[2] = 'text'; fnames[3] = 'ADDRESS'; ftypes[3] = 'address'; fnames[4] = 'PHONE'; ftypes[4] = 'phone'; fnames[5] = 'BIRTHDAY'; ftypes[5] = 'birthday'; }(jQuery)); var $mcj = jQuery.noConflict(true); </script> <!-- mailchimp --> <script> $('.toast').toast('show'); </script> {% endblock %} </body> </html>
// // ContentView.swift // MultiSelector // // Created by Florian Scholz on 10.11.23. // import SwiftUI struct ItemData: Identifiable, Hashable { var id = UUID().uuidString var name: String var imageName: String } struct SelectionRow: View { var item: ItemData var isSelected: Bool var action: () -> Void var selectionColor: Color = .blue var body: some View { Button(action: self.action) { VStack { Image(systemName: item.imageName) Text(item.name) } .padding(10) } .foregroundStyle(isSelected ? .white : .blue) .background(selectionColor.opacity(isSelected ? 1.0 : 0.0)) .clipShape(RoundedRectangle(cornerRadius: 35)) } } struct SelectionList: View { @Binding var dummyData: [ItemData] @Binding var selections: [ItemData] var color: Color = .blue var body: some View { LazyVGrid(columns: [GridItem(.flexible(),spacing: 5), GridItem(.flexible(), spacing: 5),GridItem(.flexible(), spacing: 5)] , spacing: 0 , content: { ForEach(self.dummyData, id: \.self) { item in SelectionRow(item: item, isSelected: self.selections.contains(item), action: { if self.selections.contains(item) { self.selections.removeAll(where: { $0 == item }) } else { self.selections.append(item) } }, selectionColor: color) } }) } } struct SelectionList_Previews: PreviewProvider { static var previews: some View { @State var appUser = AppSettings.appUser ContentView(appUser: $appUser) } }
import { Injectable, NotFoundException } from '@nestjs/common'; import { UpdateUserDto } from './dto/update-user.dto'; import { CreateUserDto } from './dto/create-user.dto'; @Injectable() export class UsersService { private users = [ { "id": 1, "name": "Leanne Graham", "email": "[email protected]", "role": "INTERN", }, { "id": 2, "name": "Ervin Howell", "email": "[email protected]", "role": "INTERN", }, { "id": 3, "name": "Clementine Bauch", "email": "[email protected]", "role": "ENGINEER", }, { "id": 4, "name": "Patricia Lebsack", "email": "[email protected]", "role": "ENGINEER", }, { "id": 5, "name": "Chelsey Dietrich", "email": "[email protected]", "role": "ADMIN", } ]; findAll(role?: 'INTERN' | 'ENGINEER' | 'ADMIN') { if (role) { const rolesArray = ['INTERN' , 'ENGINEER' , 'ADMIN']; if (!rolesArray.includes(role)) { throw new NotFoundException('User role not found') } return this.users.filter(user => user.role === role); } return this.users; } findOne(id: number) { const user = this.users.find(user => user.id === id); if (!user) { throw new NotFoundException('User not found'); } return user; } create(createUserDto: CreateUserDto) { const usersByHighestId = [...this.users].sort((a,b) => b.id - a.id); const newUser = { id: usersByHighestId[0].id + 1, ...createUserDto } this.users.push(newUser) return newUser; } update(id: number, updateUserDto: UpdateUserDto ) { this.users = this.users.map(user => { if (user.id === id) { return { ...user, ...updateUserDto}; } return user; }); return this.findOne(id); } delete(id: number) { const removedUser = this.findOne(id); this.users = this.users.filter(user => user.id !== id); return removedUser; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> ul { list-style: none; } * { margin: 0; padding: 0; } div { width: 1150px; height: 400px; margin: 50px auto; border: 1px solid red; overflow: hidden; } div li { width: 240px; height: 400px; float: left; } div ul { width: 1300px; } </style> </head> <body> <div id="box"> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> <script> //获取li标签 //加载图片 var list = document.getElementById("box").getElementsByTagName("li"); for(var i=0;i<list.length;i++){ list[i].style.backgroundImage="url(images/"+(i+6)+".jpg)"; list[i].onmouseover=mouseoverHandle; list[i].onmouseout=mouseoutHandle; } function mouseoverHandle(){ for(var j=0;j<list.length;j++){//全部的宽度变成100 animate(list[j],{"width":100}); } animate(this,{"width":800}) } function mouseoutHandle() { for(var j=0;j<list.length;j++){//全部的宽度变成100 animate(list[j],{"width":240}); } } //过去元素计算后的属性值 function getStyle(element,attr) { return window.getComputedStyle?window.getComputedStyle(element,null)[attr]:element.currentStyle[attr]; } function animate(element,json,fn){//所有到达目标位置后调用fn回调函数 //先清理定时器,保证只产生一个定时器 clearInterval(element.timeId); //清理定时器只产生一个定时器 element.timeId = setInterval(function(){//element.timeId每点击一次不再开辟空间,而是是是改变指向的位置 var flag = true;//假设全部到达目标 //获取当前位置 //left无法直接获取ctyle标签中的值,可以获取style属性中的值 for(var attr in json){//循环遍历json //移动多少 var left = parseInt(getStyle(element,attr)); var target = json[attr];//当前属性对应的目标值 var step = (target-left)/10; //判断step是否为正数,正数向上取整数,负数向下取正数 step = step>0?Math.ceil(step):Math.floor(step); //判断当前位置是否小于目标,如果小于则为正,否则为负数 解决移动完成回不去得问题(左移右移) // step = left<target?step:-step; //每次移动后的距离 left+=step; //目标位置 element.style[attr]=left+"px"; //是否到达目标 if(left!=target){ flag = false; } } if(flag){ clearInterval(element.timeId); ////所有到达目标位置后调用fn回调函数,前提用户传了参数 if(fn){//判断是否有回调函数 fn(); } } //测试代码 console.log("目标位置:"+target+",当前位置:"+left+",每次移动:"+step); },20) } </script> </body> </html>
import { Component, OnInit } from '@angular/core'; import { Category } from 'src/app/models/category.model'; import { ApiService } from 'src/app/services/api.service'; @Component({ selector: 'app-categories', templateUrl: './categories.component.html', styleUrls: ['./categories.component.scss'], }) export class CategoriesComponent implements OnInit { categories: Category[] = []; isHovered: boolean[]; constructor(private apiService: ApiService) { this.isHovered = Array(this.categories.length).fill(false); this.isHovered[0] = true; } /** * Add hover class to category that is hovered over and remove class from other categories. * @param index of hovered category */ addHoverClass(index: number) { this.isHovered = Array(this.categories.length).fill(false); this.isHovered[index] = true; } /** * Get all categories from API and set them to categories variable. */ ngOnInit(): void { this.apiService.getCategories().subscribe((data) => { this.categories = data as Category[]; }); } }
<p align="center"> <img src="images/ATM-APP.png"> <p> <p align="center"> <img src="images/atm.png"> <p> Project description - ### *This is a simple ATM application written in Java using Spring Boot. ATM-app supports authentication and authorization. All CRUD operations are implemented in application* ATM features in ATM application : - - The ATM deposit and withdraws amounts in multiples of 100, 200, 500 banknotes; Admin features in ATM application : - - The admin can create an ATM; - The admin can replenish the ATM; - The admin can get information about which banknotes are in the ATM; - The admin can add role to User. User features in ATM application : - - Register; - Authorization; - The user can create a bank account; - The User can deposit money to a bank account via ATM; - The User can withdraw money from bank account via ATM; - The User can transfer money from one bank account to another bank account. The application is developed in N-Tier Architecture - - Presentation tier, controller layer. - Logic tier, service layer; - Data tier, repository layer; For easy testing, you can use the following instruction - | Method | URL | Body | Content-Type | Description | Authorization | |:------:|:-----------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------------------:|:----------------:|:-------------------------------------------------------------|:--------------:| | POST | http://localhost:8080/register | {"username": "Vitalii", "password": "1234"} | application/json | Register a user | Permit all | | POST | http://localhost:8080/login | {"username": "Vitalii", "password": "1234"} | application/json | Authorization a user | Permit all | | POST | http://localhost:8080/atm/create | {"banknotes": []} | application/json | Create an ATM | ADMIN | | POST | http://localhost:8080/atm/add-money/atm/1 | [{"value": 100}, {"value": 100}, {"value": 200}, <br/>{"value": 200}, {"value": 500}, {"value": 500}] | application/json | Replenish the ATM | ADMIN | | GET | http://localhost:8080/atm/get-all-banknotes/1 | - | - | Get information about which banknotes are in the ATM | ADMIN | | PUT | http://localhost:8080/user/add-role-to-user/3/role/ADMIN | - | - | Add role to User | ADMIN | | POST | http://localhost:8080/bank_account/create/user/3 | - | - | Create a bank account | USER | | PUT | http://localhost:8080/atm/deposit/atm/1/bank-account/1 | [{"value": 100}, {"value": 200}, {"value": 500}] | application/json | Deposit money to his bank account | USER | | PUT | http://localhost:8080/atm/withdraw/atm/1/bank-account/1/amount/300 | - | - | Withdraw money from bank account | USER | | PUT | http://localhost:8080/transaction/transfer-money/from-account/1/to-account/2/amount/500 | - | - | Transfer money from one bank account to another bank account | USER | ### *If you will be using Postman for testing, you can also use:* https://red-moon-54652.postman.co/workspace/Team-Workspace~cfed11ce-5b08-4497-872f-e9df998fc0f2/collection/25447589-67276792-eee2-4d2e-9568-3761f61302e3?action=share&creator=25447589 Technologies - - Java 11.0.12 2021-07-20 LTS - Apache Maven 3.8.1 - Spring - Boot - Core - Security - Web MVC - H2 Database - Junit 5 - Mockito - Lombok - MapStruct - Swagger http://localhost:8080/swagger-ui.html
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <[email protected]> * Copyright (c) 2023 Trial97 <[email protected]> * * 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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QLabel> #include <QMessageBox> #include <QToolTip> #include "InfoFrame.h" #include "ui_InfoFrame.h" #include "ui/dialogs/CustomMessageBox.h" void setupLinkToolTip(QLabel* label) { QObject::connect(label, &QLabel::linkHovered, [label](const QString& link) { if (auto url = QUrl(link); !url.isValid() || (url.scheme() != "http" && url.scheme() != "https")) return; label->setToolTip(link); }); } InfoFrame::InfoFrame(QWidget* parent) : QFrame(parent), ui(new Ui::InfoFrame) { ui->setupUi(this); ui->descriptionLabel->setHidden(true); ui->nameLabel->setHidden(true); ui->licenseLabel->setHidden(true); ui->issueTrackerLabel->setHidden(true); setupLinkToolTip(ui->iconLabel); setupLinkToolTip(ui->descriptionLabel); setupLinkToolTip(ui->nameLabel); setupLinkToolTip(ui->licenseLabel); setupLinkToolTip(ui->issueTrackerLabel); updateHiddenState(); } InfoFrame::~InfoFrame() { delete ui; } void InfoFrame::updateWithMod(Mod const& m) { if (m.type() == ResourceType::FOLDER) { clear(); return; } QString text = ""; QString name = ""; QString link = m.metaurl(); if (m.name().isEmpty()) name = m.internal_id(); else name = m.name(); if (link.isEmpty()) text = name; else { text = "<a href=\"" + link + "\">" + name + "</a>"; } if (!m.authors().isEmpty()) text += " by " + m.authors().join(", "); setName(text); if (m.description().isEmpty()) { setDescription(QString()); } else { setDescription(m.description()); } setImage(m.icon({ 64, 64 })); auto licenses = m.licenses(); QString licenseText = ""; if (!licenses.empty()) { for (auto l : licenses) { if (!licenseText.isEmpty()) { licenseText += "\n"; // add newline between licenses } if (!l.name.isEmpty()) { if (l.url.isEmpty()) { licenseText += l.name; } else { licenseText += "<a href=\"" + l.url + "\">" + l.name + "</a>"; } } else if (!l.url.isEmpty()) { licenseText += "<a href=\"" + l.url + "\">" + l.url + "</a>"; } if (!l.description.isEmpty() && l.description != l.name) { licenseText += " " + l.description; } } } if (!licenseText.isEmpty()) { setLicense(tr("License: %1").arg(licenseText)); } else { setLicense(); } QString issueTracker = ""; if (!m.issueTracker().isEmpty()) { issueTracker += tr("Report issues to: "); issueTracker += "<a href=\"" + m.issueTracker() + "\">" + m.issueTracker() + "</a>"; } setIssueTracker(issueTracker); } void InfoFrame::updateWithResource(const Resource& resource) { setName(resource.name()); setImage(); } QString InfoFrame::renderColorCodes(QString input) { // We have to manually set the colors for use. // // A color is set using §x, with x = a hex number from 0 to f. // // We traverse the description and, when one of those is found, we create // a span element with that color set. // // TODO: Wrap links inside <a> tags // https://minecraft.wiki/w/Formatting_codes#Color_codes const QMap<QChar, QString> color_codes_map = { { '0', "#000000" }, { '1', "#0000AA" }, { '2', "#00AA00" }, { '3', "#00AAAA" }, { '4', "#AA0000" }, { '5', "#AA00AA" }, { '6', "#FFAA00" }, { '7', "#AAAAAA" }, { '8', "#555555" }, { '9', "#5555FF" }, { 'a', "#55FF55" }, { 'b', "#55FFFF" }, { 'c', "#FF5555" }, { 'd', "#FF55FF" }, { 'e', "#FFFF55" }, { 'f', "#FFFFFF" } }; // https://minecraft.wiki/w/Formatting_codes#Formatting_codes const QMap<QChar, QString> formatting_codes_map = { { 'l', "b" }, { 'm', "s" }, { 'n', "u" }, { 'o', "i" } }; QString html("<html>"); QList<QString> tags{}; auto it = input.constBegin(); while (it != input.constEnd()) { // is current char § and is there a following char if (*it == u'§' && (it + 1) != input.constEnd()) { auto const& code = *(++it); // incrementing here! auto const color_entry = color_codes_map.constFind(code); auto const tag_entry = formatting_codes_map.constFind(code); if (color_entry != color_codes_map.constEnd()) { // color code html += QString("<span style=\"color: %1;\">").arg(color_entry.value()); tags << "span"; } else if (tag_entry != formatting_codes_map.constEnd()) { // formatting code html += QString("<%1>").arg(tag_entry.value()); tags << tag_entry.value(); } else if (code == 'r') { // reset all formatting while (!tags.isEmpty()) { html += QString("</%1>").arg(tags.takeLast()); } } else { // pass unknown codes through html += QString("§%1").arg(code); } } else { html += *it; } it++; } while (!tags.isEmpty()) { html += QString("</%1>").arg(tags.takeLast()); } html += "</html>"; html.replace("\n", "<br>"); return html; } void InfoFrame::updateWithResourcePack(ResourcePack& resource_pack) { setName(renderColorCodes(resource_pack.name())); setDescription(renderColorCodes(resource_pack.description())); setImage(resource_pack.image({ 64, 64 })); } void InfoFrame::updateWithTexturePack(TexturePack& texture_pack) { setName(renderColorCodes(texture_pack.name())); setDescription(renderColorCodes(texture_pack.description())); setImage(texture_pack.image({ 64, 64 })); } void InfoFrame::clear() { setName(); setDescription(); setImage(); setLicense(); setIssueTracker(); } void InfoFrame::updateHiddenState() { if (ui->descriptionLabel->isHidden() && ui->nameLabel->isHidden() && ui->licenseLabel->isHidden() && ui->issueTrackerLabel->isHidden()) { setHidden(true); } else { setHidden(false); } } void InfoFrame::setName(QString text) { if (text.isEmpty()) { ui->nameLabel->setHidden(true); } else { ui->nameLabel->setText(text); ui->nameLabel->setHidden(false); } updateHiddenState(); } void InfoFrame::setDescription(QString text) { if (text.isEmpty()) { ui->descriptionLabel->setHidden(true); updateHiddenState(); return; } else { ui->descriptionLabel->setHidden(false); updateHiddenState(); } ui->descriptionLabel->setToolTip(""); QString intermediatetext = text.trimmed(); bool prev(false); QChar rem('\n'); QString finaltext; finaltext.reserve(intermediatetext.size()); foreach (const QChar& c, intermediatetext) { if (c == rem && prev) { continue; } prev = c == rem; finaltext += c; } QString labeltext; labeltext.reserve(300); if (finaltext.length() > 290) { ui->descriptionLabel->setOpenExternalLinks(false); ui->descriptionLabel->setTextFormat(Qt::TextFormat::RichText); m_description = text; // This allows injecting HTML here. labeltext.append("<html><body>" + finaltext.left(287) + "<a href=\"#mod_desc\">...</a></body></html>"); QObject::connect(ui->descriptionLabel, &QLabel::linkActivated, this, &InfoFrame::descriptionEllipsisHandler); } else { ui->descriptionLabel->setTextFormat(Qt::TextFormat::AutoText); labeltext.append(finaltext); } ui->descriptionLabel->setText(labeltext); } void InfoFrame::setLicense(QString text) { if (text.isEmpty()) { ui->licenseLabel->setHidden(true); updateHiddenState(); return; } else { ui->licenseLabel->setHidden(false); updateHiddenState(); } ui->licenseLabel->setToolTip(""); QString intermediatetext = text.trimmed(); bool prev(false); QChar rem('\n'); QString finaltext; finaltext.reserve(intermediatetext.size()); foreach (const QChar& c, intermediatetext) { if (c == rem && prev) { continue; } prev = c == rem; finaltext += c; } QString labeltext; labeltext.reserve(300); if (finaltext.length() > 290) { ui->licenseLabel->setOpenExternalLinks(false); ui->licenseLabel->setTextFormat(Qt::TextFormat::RichText); m_description = text; // This allows injecting HTML here. labeltext.append("<html><body>" + finaltext.left(287) + "<a href=\"#mod_desc\">...</a></body></html>"); QObject::connect(ui->licenseLabel, &QLabel::linkActivated, this, &InfoFrame::licenseEllipsisHandler); } else { ui->licenseLabel->setTextFormat(Qt::TextFormat::AutoText); labeltext.append(finaltext); } ui->licenseLabel->setText(labeltext); } void InfoFrame::setIssueTracker(QString text) { if (text.isEmpty()) { ui->issueTrackerLabel->setHidden(true); } else { ui->issueTrackerLabel->setText(text); ui->issueTrackerLabel->setHidden(false); } updateHiddenState(); } void InfoFrame::setImage(QPixmap img) { if (img.isNull()) { ui->iconLabel->setHidden(true); } else { ui->iconLabel->setHidden(false); ui->iconLabel->setPixmap(img); } } void InfoFrame::descriptionEllipsisHandler([[maybe_unused]] QString link) { if (!m_current_box) { m_current_box = CustomMessageBox::selectable(this, "", m_description); connect(m_current_box, &QMessageBox::finished, this, &InfoFrame::boxClosed); m_current_box->show(); } else { m_current_box->setText(m_description); } } void InfoFrame::licenseEllipsisHandler([[maybe_unused]] QString link) { if (!m_current_box) { m_current_box = CustomMessageBox::selectable(this, "", m_license); connect(m_current_box, &QMessageBox::finished, this, &InfoFrame::boxClosed); m_current_box->show(); } else { m_current_box->setText(m_license); } } void InfoFrame::boxClosed([[maybe_unused]] int result) { m_current_box = nullptr; }
// // TransactionBlockInput.swift // SuiKit // // Copyright (c) 2023 OpenDive // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public struct TransactionBlockInput: KeyProtocol { /// Represents the position of the `TransactionBlockInput` in a collection. public var index: UInt16 /// The value associated with the `TransactionBlockInput`, encapsulated in a `SuiJsonValue`. public var value: SuiJsonValue? /// The type of the value associated with the `TransactionBlockInput`. public var type: ValueType? /// Initializes a new instance of `TransactionBlockInput`. /// /// - Parameters: /// - index: The position of the `TransactionBlockInput` in a collection. /// - value: The value to be associated with the `TransactionBlockInput`. Defaults to `nil`. /// - type: The type of the value to be associated with the `TransactionBlockInput`. Defaults to `nil`. public init( index: UInt16, value: SuiJsonValue? = nil, type: ValueType? = nil ) { self.index = index self.value = value self.type = type } public func serialize(_ serializer: Serializer) throws { try Serializer.u16(serializer, index) } public static func deserialize( from deserializer: Deserializer ) throws -> TransactionBlockInput { return TransactionBlockInput( index: try Deserializer.u16(deserializer) ) } }
import React from "react"; import ReactDOM from "react-dom"; import CommonDisplay from "../CommonDisplay"; import "./new-profile.css" import Cookie from "js-cookie"; import * as QueryString from "querystring"; class EditProfile extends CommonDisplay{ constructor(props){ super(props); let queryString = this.props.location.search.substring(1); console.log(queryString) this.state = { currentImg: queryString.split("&")[0].split("=")[1], responseText: "", name: queryString.split("&")[1].split("=")[1] } } handleChange = (e) =>{ this.setState({currentImg: e.target.value}) } handleSubmit = (e) => { e.preventDefault(); let form = new FormData(); form.append("userId", Cookie.get("userId")); form.append("perfilId", Cookie.get("perfilId")); form.append("nombre", e.target.nombrePerfil.value); form.append("avatar", e.target.avatar.value); console.log(form) fetch("http://localhost:4000/altaPerfil",{ method: "PUT", body: form }) .then((res) => (res.json())) .then((res) => (this.setState({responseText: res.text}))) .catch(() => (this.setState({responseText: "Hubo un error"}))) } renderContent = () => { return( <div className="new-profile"> <form className="box" onSubmit={this.handleSubmit}> <label htmlFor="">Avatar</label> <div className="imgContainer"> <img src={`http://localhost/avatars/${this.state.currentImg}`} alt="avatar"/> </div> <select value={this.state.currentImg} required name="avatar" id="selectAvatar" onChange={this.handleChange}> <option value="shark.jfif">Tiburon</option> <option value="astro.png">Astronauta</option> <option value="pelota.png">Pelota</option> <option value="luci.jpeg">Luci</option> </select> <label htmlFor="">Nombre</label> <input required type="text" name="nombrePerfil" id="inputName" value={this.state.name} onChange={(e) => (this.setState({name: e.target.value}))}/> {this.state.responseText} <input type="submit" id="newButton" value="Modificar Perfil"/> </form> </div> ) } } export default EditProfile;
## Scaling - ### Horizontal **replica count** (*number of pods*) of deployment increased/decreased - #### Manual - `k apply` after changing **spec.replicas** (or *`k edit` deploy my-dep*) - *`k` **`scale`** `deploy my-dep` **`--replicas`**`=4` - #### Automatic - **HorizontalPodAutoScaler** (HPA) can automatically modify the number of replicas in a deployment (or replic set) based on the value of dynamic variables (eg system load etc). - HPA *effectively **adjusts** spec.**replicas*** for pod based on: current cpu usage (averaged over all containers in all pods), as a fraction of that pod requested in, resources.requests.cpu (which *must be specified* for pod for autoscaling to work) $$ \frac{CurrentCpusUsedbyPod}{RequestedCpus} $$ #### - Can adjust the number of replicas of a deployment both below and above the number initially specified in the *deployment* **spec.replicas**, as long as the number of replicas remains within the *HPA* **min** and **max** #### - Tries to keep pod usage at **80%** of that specified for pod in *resources.**requests.cpu*** - `k` **`autoscale`** **`deploy`** `my-dep` **`--min=3 --max=15 --cpu-percent=80`** Makes sense if each container has to do more work, when less containers available to share load (eg incoming web requests) #### - Behind the scenes this creates a **hpa** object, with same name as deployment - `k` **`get`** **`hpa`** ```yaml NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE my-dep Deployment/my-dep <unknown>/80% 10 15 3 18s ``` #### - therse ***no** way* to generate **yaml** for HPA (eg with **--dry-run**). hack: create hpa and use `k get hpa my-dep -o yaml > hpa.yaml` ignoring status etc - **HorizontalPodAutoScaler** (HPA) can automatically modify the number of - ### Vertical resources.***requests.cpu*** effectively scaled for pods - #### Automatic - based on **current time** vs **historic metrics** - eg fridays cpu usage is usually higher and weekends lower - today is friday so scale up - cloud provider support required
package com.zy.commonlibrary.base; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import java.util.List; import java.util.Stack; /** * activity管理 */ public class AppManager { private static Stack<Activity> activityStack; private volatile static AppManager instance; private AppManager() { } /** * 单一实例 */ public static AppManager getAppManager() { if (instance == null) { synchronized (AppManager.class){ if(instance==null){ instance = new AppManager(); instance.activityStack = new Stack(); } } } return instance; } /** * 添加Activity到堆栈 */ public void addActivity(Activity activity) { if (activityStack == null) { activityStack = new Stack<Activity>(); } activityStack.add(activity); LogUtils.i("stack", activityStack.toString()); } /** * 获取当前Activity(堆栈中最后一个压入的) */ public Activity currentActivity() { try { Activity activity = activityStack.lastElement(); return activity; } catch (Exception e) { // e.printStackTrace(); return null; } } /** * 获取当前Activity的前一个Activity */ public Activity preActivity() { int index = activityStack.size() - 2; if (index < 0) { return null; } Activity activity = activityStack.get(index); return activity; } /** * 结束当前Activity(堆栈中最后一个压入的) */ public void finishActivity() { Activity activity = activityStack.lastElement(); finishActivity(activity); } /** * 结束指定的Activity */ public void finishActivity(Activity activity) { if (activity != null) { activityStack.remove(activity); activity.finish(); activity = null; } } /** * 移除指定的Activity */ public void removeActivity(Activity activity) { if (activity != null) { activityStack.remove(activity); activity = null; } } /** * 结束指定类名的Activity */ public void finishActivity(Class<?> cls) { try { for (Activity activity : activityStack) { if (activity.getClass().equals(cls)) { finishActivity(activity); } } } catch (Exception e) { e.printStackTrace(); } } /** * 结束所有Activity */ public void finishAllActivity() { for (int i = 0, size = activityStack.size(); i < size; i++) { if (null != activityStack.get(i)) { activityStack.get(i).finish(); } } activityStack.clear(); } /** * 返回到指定的activity * * @param cls */ public void returnToActivity(Class<?> cls) { while (activityStack.size() != 0) if (activityStack.peek().getClass() == cls) { break; } else { finishActivity(activityStack.peek()); } } /** * 是否已经打开指定的activity * @param cls * @return */ public boolean isOpenActivity(Class<?> cls) { if (activityStack!=null){ for (int i = 0, size = activityStack.size(); i < size; i++) { if (cls == activityStack.peek().getClass()) { return true; } } } return false; } /** * 退出应用程序 * * @param context 上下文 * @param isBackground 是否开开启后台运行 */ public void AppExit(Context context, Boolean isBackground) { try { finishAllActivity(); ActivityManager activityMgr = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); activityMgr.restartPackage(context.getPackageName()); } catch (Exception e) { } finally { // 注意,如果您有后台程序运行,请不要支持此句子 if (!isBackground) { System.exit(0); } } } public boolean isRunningForeground(Context context) { ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> appProcessInfos = activityManager.getRunningAppProcesses(); // 枚举进程 for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfos) { if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { if (appProcessInfo.processName.equals(context.getApplicationInfo().processName)) { return true; } } } return false; } public void switchForeground(Context mContext) { // //如果APP是在后台运行 // if (!isRunningForeground(mContext)) { // //获取ActivityManager // ActivityManager mAm = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); // if(mAm == null) { // return; // } // //获得当前运行的task // List<ActivityManager.RunningTaskInfo> taskList = mAm.getRunningTasks(100); // for (ActivityManager.RunningTaskInfo rti : taskList) { // //找到当前应用的task,并启动task的栈顶activity,达到程序切换到前台 // if (rti.topActivity.getPackageName().equals(mContext.getPackageName())) { // mAm.moveTaskToFront(rti.id, 0); // return; // } // } // //若没有找到运行的task,用户结束了task或被系统释放,则重新启动mainactivity // Intent resultIntent = new Intent(mContext, SplashActivity.class); // resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); // mContext.startActivity(resultIntent); // } } }
// возвращаемый тип void у функции может приводит к необычному, но ожидаемому повдедению type voidFn = () => void; const f1: voidFn = () => true; const f2: voidFn = () => { return true; }; const f3: voidFn = function() { return true } // мы по сути возвращем bollean, но ts даёт ему тип void // я немного непонимаю почему ts нам не выдаёт ошибку, например // почему ты что-то возвращаешь из функции если ты этой функции дал тип void // и получается когда мы выполнение функции с типом void присваиваем переменной // то у неё тоже становится такой const v1 = f1(); const v2 = f2(); const v3 = f3(); // это сдеано для того чтобы в полседующем код был понятен, например const src = [1, 2, 3]; const dst = [0]; src.forEach((el) => dst.push(el)); // здесь мы вызываем forEach, который возвращает тип void // но мы то написали что мы вернули dst.push(el), а push в свою очередь возврашает число // и вдруг мы подумали ну если мы возвращаем число значит мы можем с ним что-то сделать // нет не можем потому что forEach возращает void src.forEach((el) => dst.push(el)).toFixed(); //Свойство "toFixed" не существует в типе "void".
rshd - Remote Shell Daemon for Windows NT version 1.6 Written by Silviu C. Marghescu (http://www.cs.umd.edu/~silviu) Copyright (C) 1996 Silviu C. Marghescu, Emaginet, Inc. All Rights Reserved. Password functionality added by Ashley M. Hopkins (http://www.csee.usf.edu/~amhopki2) rshd is free software; you can redistribute it in its entirety in any form you like. If you find any bugs, feel free to send me an email at [email protected]. If you have added new features to rshd, please send me all the source code modifications, including the version of rshd that you are based on. Your additions may benefit other users. Disclaimer ========== rshd is distributed hoping that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Good data processing procedure dictates that any program be thoroughly tested with non-critical data before relying on it. The user must assume the entire risk of using the program. THE AUTHOR SHALL NOT BE HELD LIABLE FOR ANY KIND OF DAMAGES OR CLAIMS THAT DIRECTLY OR INDIRECTLY RESULT FROM USING THIS SOFTWARE. Description rshd is a multithreaded daemon service that listens for connections on port 514 (tcp port for the shell/cmd protocol), runs commands passed by clients and sends back the results. It was my experience that the rshd service included in the Windows NT Resource Kit does not fully follow the BSD specification for the rsh protocol; it works fine with the rsh client in NT, but other clients fail to connect. This implementation of rshd tries to get as close as possible to the BSD specs (http://www.bsdi.com). As of version 1.5, rshd comes with RCP server support, thanks to Gary Doss ([email protected]); any problem/question concerning the rcp part of rshd would be better answered by him. Important note: rshd was designed and implemented to be convenient and reliable, rather than tightly secure. A client trying to connect to rshd will have to pass a security clearance process, but rshd is probably far from a secure service. If security is of major concern across your network, you should be very careful when using this service. My target for rshd was a closed network, or a network guarded by a firewall. Requirements o An Intel processor based machine running Microsoft Windows NT and TCP/IP. o Window Socket DLL installed properly (version 1.1 or higher). Installation This package contains the following files: readme.txt - this file rshd.exe - the rshd daemon executable The source distribution also contains: rshd.cpp - the C++ source file (actually mostly C, but I prefer to define variables when I really need them; plus, I like the // comments) rshd_rcp.cpp - the C++ source file for the RCP service service.cpp, service.h - the service routines (many thanks to Craig Link, Microsoft for including the Service project in the samples) rshd.ide - the project file for Borland C++ 5.0 users rshd.mak - the project file for Microsoft Visual C++ 2.0 Running rshd In this new version, rshd runs as a service. You also have the option of running rshd as a command line application (see "-d" later on). In order to get the service up and running, you will have to complete the following steps: 1. install the service: rhsd -install 2. start the service: net start rshd That's it! Stopping the service is as easy as starting it: net stop rshd Should you decide rshd is not the way to go: rshd -remove Starting/stopping the service can also be done through the "Services" Control Panel applet; just look for the RSHD Daemon service. Note that if the applications you are running require user credentials, you should run the service under the corresponding user account. Command line options: -install installs the rshd service -remove removes the rshd service The following command line options have been inherited from the previous, interactive versions. I don't know if they'll be useful if you decide to run rshd as a service. I haven't figured out yet how to run the service with command line options, therefore the '-r' is set by default. -d enables debugging messages and allows you to run rshd as a command line process. Good for those days when nothing works... -1 no stdout redirection. By default, rshd will redirect the output of your command into a temporary file and send the result back thru the client socket. If however you are not interested in the output, or the command is already redirected, this option will prevent stdout redirection. Note that the option is global, meaning it will disable redirection regardless of the commands you're passing... -2 no stderr redirection. Same as '-1', but for stderr. At this point it should be noted that under the BSD rshd specification, the client can pass an auxillary tcp port number that the daemon can use to send the stderr output back. The rshd will connect to that port if provided and send back the stderr, unless this option is given. If no alternative stderr port is provided, rshd will use the main socket for both stdout and stderr. -4 4DOS command shell. Different shells and different operating systems have different ways of redirecting output, especially for the standard error stream. rshd was tested in the following configurations: CMD.EXE and 4NT.EXE on Windows NT; COMMAND.COM and 4DOS.COM on Windows 95. If you're running 4DOS on Windows 95, make sure you set the '-4' command parameter, otherwise the stderr redirection will fail. -s stronger security enabled. By default, when the client credentials can't be checked, rshd assumes it to be friendly and runs the command. If that creates security concernes, this option will accept the connection to a client only if everything checks out. -r no .rhosts checking. Per BSD rshd specification, rshd loads the <windir>\.rhosts file and builds a list of trusted hosts. Any further connections will be accepted only from a host in the list. '-r' disables this checking. Note that this is a major security issue: if your network is not closed or guarded by a firewall, anybody can connect thru the rsh protocol and run commands on your machines. Use this option only if you know exactly who is running what across your network! -p password option enabled. User will be prompted to enter a password after start of the daemon. To enable rsh commands to execute on the daemon with this enabled user must enter password from the command line in the rsh command between the hostname and the command. (rsh hostname password command) The password option does not affect the rcp command. -v displays the rshd version. -h help screen. RCP usage: Valid rcp requests are in the form: rcp -t [-d] [-r] [-p] target rcp -f [r] [-p] target NOTE: The -p option is being ignored since there is not a good correlation between UNIX and NT when it comes to file permissions and ownership. I have tested rshd with the following rsh clients: WinRSH (both 16 and 32 bit versions; this was the client I needed to use and didn't work with the Resource Kit implementation of rshd); NT client of rsh; SunOS client of rsh. The main difference between WinRSH and the other rsh clients is that WinRSH does not open a stderr additional port; rshd will send both the stdout and stderr output thru the main socket. Security considerations As stated above, security was not the main issue while implementing rshd. The daemon still tries to authenticate the remote user/host, but the authentication process is not fully implemented and should not be considered secure. In this version, only host authentication is implemented. If not disabled (see the '-r' switch), an .rhosts mechanism is used: the remote host name is searched in the .rhosts file; if it is not found, the connection is refused. Sometimes, rshd does not have enough information to decide whether the connection is secure or not (e.g. cannot determine the remote host name); in this cases, by default, the connection is accepted, unless the '-s' switch is on. The '-s' switch will enable a tighter security: only fully recognized clients will be able to connect. The password functionality added by Ashley M. Hopkins enables another layer of security by requiring that the user enter a password. This option can be used in conjunction with the .rhosts file or with the .rhosts checking disabled (-r). To allow compatibility across NT/95 platforms, the required path for the .rhosts file (if you decide to use the feature) is: <windir>\.rhosts, where <windir> is your Windows root directory as reported by the WINDIR environment variable. Rebuilding rshd You probably have the sources already... I've built rshd with both Visual C++ and Borland C++; the .ide file is the Borland project and the .mak is the one you need for Visual C++. Make sure you define the appropriate macro (first lines in rshd.cpp define either VISUALCPP or BORLANDCPP). Known problems Some rsh clients open an additional connection for the stderr output. There is a known problem/feature in Microsoft's implementation of TCP/IP that causes closed connections to linger on for 2 maximum segment lives (4 minutes). Within the timeout period, the local port is unusable. For this reason, rshd has a mechanism for port resolution that tries to assign local ports in a round-robin fashion. It is not a clean solution, but it works for the time being (there is still a problem if rshd is restarted, since it begins assigning ports from 1023; if those ports are taken by TIME_WAIT connections, they'll be unusable). A way of reducing the timeout period to less than 4 minutes is described in Microsoft's Knowledge Base article Q149532: ***************************************************************************************** A new registry has been added to TCP/IP to allow the TIME-WAIT state to be configurable. This will allow TCP/IP users to free closed connection resources more quickly. The new registry entry is: TcpTimedWaitDelay Key: Tcpip\Parameters Value Type: REG_DWORD - Time in seconds Valid Range: 30-300 (decimal) Default: 0xF0 (240 decimal) ***************************************************************************************** Also, very long command lines (e.g. more than 1024 characters) can cause rshd to crash. Still working on it. For complex commands (e.g. "comm1 | comm2"), to achieve correct redirection, the whole command needs to be enclosed in parenthesis (e.g. (comm1 | comm2) ). However, that creates problems on some machines (errors have been reported on Windows 95, running under command.com). Things go smoothly though if you have 4NT or 4DOS (use the '-4' flag then). Whether you have good or bad comments, improvements and suggestions, I would like to hear from you at [email protected]. Bug fixes, improvements Gary Doss ([email protected]) has had a major contribution to rshd, with the RCP support and some pretty good bug fixes. Barbara Dawkins ([email protected]) has improved Gary's RCP support and fixed a couple of bugs. Ashley Hopkins ([email protected]) has added the password option to the rshd to improve security of this daemon. Additionally a bug has been fixed to allow the transfer of executable files.
import Head from "next/head"; import styles from "../styles/Home.module.css"; import Link from "next/link"; import Loader from "../components/Loader"; import toast from "react-hot-toast"; import PostFeed from "../components/PostFeed"; import { firestore, fromMillis, postToJSON } from "../lib/firebase"; import { useState } from "react"; import Metatags from "@components/Metatags"; const LIMIT = 5; export async function getServerSideProps(context) { const postsQuery = firestore .collectionGroup("posts") .where("published", "==", true) .orderBy("createdAt", "desc") .limit(LIMIT); const posts = (await postsQuery.get()).docs.map(postToJSON); return { props: { posts, }, }; } export default function Home(props) { const [posts, setPosts] = useState(props.posts); const [loading, setLoading] = useState(false); const [postsEnd, setPostsEnd] = useState(false); const getMorePosts = async () => { setLoading(true); const last = posts[posts.length - 1]; const cursor = typeof last.createdAt === "number" ? fromMillis(last.createdAt) : last.createdAt; const query = firestore .collectionGroup("posts") .where("published", "==", true) .orderBy("createdAt", "desc") .startAfter(cursor) .limit(LIMIT); const newPosts = (await query.get()).docs.map((doc) => doc.data()); setPosts(posts.concat(newPosts)); setLoading(false); if (newPosts.length < LIMIT) { setPostsEnd(true); } }; return ( <main> <Metatags title="Home Page" description="Get the latest posts on our site" /> <div className="card card-info"> <h2>💡 Techgrounds blog site - Testers!</h2> <p> Dit is de blog website voor Techground testers </p> <p> Om in te loggen en je posts te editen en nieuwe posts te maken gebruiken we google! </p> <p> Gebouwd met Next.js en Firebase. </p> </div> <PostFeed posts={posts} /> {!loading && !postsEnd && ( <button className="" onClick={getMorePosts}> Load More </button> )} <Loader show={loading} /> {postsEnd && "You have reached the end"} </main> ); }
import { render } from '@testing-library/react' import { StoreProvider } from 'app/providers/StoreProvider' import { type StateSchema } from 'app/providers/StoreProvider/config/StateSchema' import { type ReactNode } from 'react' import { MemoryRouter } from 'react-router-dom' export interface componentRenderOptions { route?: string initialState?: DeepPartial<StateSchema> } export function componentRender ( component: ReactNode, options: componentRenderOptions = {} ) { const { route = '/', initialState } = options return render( <MemoryRouter initialEntries={[route]}> <StoreProvider initialState={initialState}>{component}</StoreProvider> </MemoryRouter> ) }
import React from 'react'; import { Layout, Menu, } from 'antd'; import { SolutionOutlined, InfoCircleOutlined, LockOutlined } from '@ant-design/icons'; import examLogo from '../../../assets/test.webp'; const { Header } = Layout; // 菜单项 const menuItems = [ { key: "home", icon: <SolutionOutlined />, label: "Home测试", }, { key: "about", icon: <InfoCircleOutlined />, label: "About", }, { key: "admin", icon: <LockOutlined />, label: "后台管理", }, ] // 默认选中的菜单的key const defaultSelectedKeys = ['home']; // 点击菜单项的回调 const handleClick = (e) => { let item_key = e.key; console.log('点击了菜单项:', item_key); } export default class HeaderInfo extends React.Component { render() { return <Header style={{ display: 'flex', alignItems: 'center', }} > <div style={{ padding: '24px', display: 'flex', }}> <img src={examLogo} alt="Exam Logo" width={40} /> </div> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={defaultSelectedKeys} items={menuItems} style={{ flex: 1, minWidth: 0, }} onClick={handleClick} /> </Header> } }
const COMMENT: &str = "//@"; /// A header line, like `//@name: value` consists of the prefix `//@` and the directive /// `name: value`. It is also possibly revisioned, e.g. `//@[revision] name: value`. pub(crate) struct HeaderLine<'ln> { pub(crate) revision: Option<&'ln str>, pub(crate) directive: &'ln str, } /// Iterate through compiletest headers in a test contents. /// /// Adjusted from compiletest/src/header.rs. pub(crate) fn iter_header<'ln>(contents: &'ln str, it: &mut dyn FnMut(HeaderLine<'ln>)) { for ln in contents.lines() { let ln = ln.trim(); // We're left with potentially `[rev]name: value`. let Some(remainder) = ln.strip_prefix(COMMENT) else { continue; }; if let Some(remainder) = remainder.trim_start().strip_prefix('[') { let Some((revision, remainder)) = remainder.split_once(']') else { panic!("malformed revision directive: expected `//@[rev]`, found `{ln}`"); }; // We trimmed off the `[rev]` portion, left with `name: value`. it(HeaderLine { revision: Some(revision), directive: remainder.trim() }); } else { it(HeaderLine { revision: None, directive: remainder.trim() }); } } }
/* Built-in Modules */ // Command Prompt -> node node-1.js /* HTTP module creates a server object, listens to server ports and gives a response back to the client */ const http = require("http"); // import * as http from "http"; /* URL module splits query string into readable parts */ const url = require("url"); // import * as url from "url"; // createServer() method creates an HTTP server // req argument represents the request from the client, as an object http.createServer(function (request, response) { let q = url.parse(request.url, true); /* Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: [Object: null prototype] {}, pathname: '/', path: '/', href: '/' } */ // Add HTTP Header // If response from HTTP server is supposed to be displayed as HTML // first argument is status code, second argument is an object obtaining response headers // 200 - all is OK response.writeHead(200, {"Content-Type": "text/html"}); // Write a response to the client response.write("data"); // Read Query String // url property of res object, holds the part of urk that comes after the domain name response.write(request.url + "\n\n"); // localhost:8080/node-1.html - /node-1.html // Split Query String let qdata = q.query; // [Object: null prototype] {} let adr = "http://localhost:8080/default.htm?year=2023&month=November"; q = url.parse(adr, true); /* Url { protocol: 'http:', slashes: true, auth: null, host: 'localhost:8080', port: '8080', hostname: 'localhost', hash: null, search: '?year=2023&month=November', query: [Object: null prototype] { year: '2023', month: 'November' }, pathname: '/default.htm', path: '/default.htm?year=2023&month=November', href: 'http://localhost:8080/default.htm?year=2023&month=November' } */ qdata = q.query; // [Object: null prototype] {year: 2023, month: November} response.write(qdata.year + " " + qdata.month); // localhost:8080/?year=2023&month=November - 2023 November // End the response return response.end(); // The server object listens to port 8080 }).listen(8080);
# 5G La 5G est une évolution majeur de la [4G](4G.md) (après un certain nombre de release, on estime que la technologie à assez évolué pour le grand publique) Avantage : - Connections mobiles rapide (max 10 Gb/s $\rightarrow$ 100 Mb/s pour un utilisateur) - Nette réduction de la latence (1ms) - Plus grand nombre d'objets connectés et de capteurs (1 million d'appareils par $km^2$, permet d'utiliser l'IOT) - 100% de couverture du réseau - 99.999% de disponibilité du réseau - 90% de réduction en utilisation d'énergie du réseau (par apport à la [4G](4G.md)) - Evolution au niveau du réseau d'accès Radio Access Network (RAN) - Usage massif des antennes MIMO - Usage de la virtualisation du réseau d'accès (RAT pour Radio Access Technology) qui permet de créer un RAN qui supporte plusieur fonction génériques Caractéristique : - Utilise [OFDM](4G.md) - Utilise des code du type Low-density parity-check codes (LDPC code) ## 5G NR 5G NR (pour New Radio) est une nouvelle technologie d'accès radio (**RAT pour Radio Access Technology**) pour les réseaux mobile 5G L'infrastructure 5G NR est virtuelle et repose sur un cloud de ressources physique virtualisées et orchestrées par le **Network Function Virtualisation Infrastructure (NFV)** : - Plus besoin d'hardware dédié - Capacité de traitement en temps réel des application 5G-IOT Les fonctions logicielles du réseau sont assurées par le **Software-Defined Network (SDN)**. L'objectif est de rendre possible la gestion des réseaux hétérogène induits par la diversité des objets connectés. Il est basé sur la séparation du plan de contrôle et du plan usager (NFV est complémentaire à SDN) ![](attachments/Pasted%20image%2020230607101140.png) ## IoT Difficulté de l'IoT : - Le réseau doit supporté énormément d'objet - La sécurité - La disponibilité - La couverture - L'autonomie - La gestion de la configuration du système (auto configuration par apport au réseau) - Sécurité Deux variantes : - **IoT haut débit** : concerne les équipement qui ont besoin d'un débit important pour leur usage (exemple: caméra) - **IoT critique** : concerne les équipement qui ont besoin de transmettre des information en temps réel (example : véhicule, capteurs médicaux). La 5G le permet à l'aide de ses 1ms de latence Deux technologie de la 5G pour l'IoT : - **LTE-M** permet d'utiliser la 5G plus rapidement qu'avec NB-IoT (utilité : véhicule autonome, les objets en mouvement) - **NB-IoT** permet d'avoir besoin d'une petite bande passante et donc d(utiliser me canal [GSM](GSM.md) (utilité : télémétrie, capteurs) ![](attachments/Pasted%20image%2020230607102220.png) Il y a beaucoup de problème de sécurité puisque la G repose du l'IP et en est donc vulnérable par tout les attaque qui utilise l'IP
// Can't use aliases here because we're doing exports/require import { DOMAIN } from 'config'; import * as URLParams from 'constants/urlParams'; import ShortUrl from 'services/shortUrl'; const PAGES = require('../constants/pages'); const { parseURI, buildURI } = require('../util/lbryURI'); const COLLECTIONS_CONSTS = require('../constants/collections'); function encodeWithSpecialCharEncode(string) { // encodeURIComponent doesn't encode `'` and others // which other services may not like return encodeURIComponent(string).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29'); } export const formatLbryUrlForWeb = (uri) => { if (!uri) return uri; let newUrl = uri.replace('lbry://', '/').replace(/#/g, ':'); if (newUrl.startsWith('/?')) { // This is a lbry link to an internal page ex: lbry://?rewards newUrl = newUrl.replace('/?', '/$/'); } return newUrl; }; export const formatLbryChannelName = (uri) => uri && uri.replace('lbry://', '').replace(/#/g, ':'); export const formatFileSystemPath = (path) => { if (!path) { return; } let webUrl = path.replace(/\\/g, '/'); if (webUrl[0] !== '/') { webUrl = `/${webUrl}`; } return encodeURI(`file://${webUrl}`).replace(/[?#]/g, encodeURIComponent); }; /* Function that handles page redirects ex: lbry://?rewards ex: open.lbry.com/?rewards */ export const formatInAppUrl = (path) => { // Determine if we need to add a leading "/$/" for app pages const APP_PAGE_REGEX = /(\?)([a-z]*)(.*)/; const appPageMatches = APP_PAGE_REGEX.exec(path); if (appPageMatches && appPageMatches.length) { // Definitely an app page (or it's formatted like one) const [, , page, queryString] = appPageMatches; if (Object.values(PAGES).includes(page)) { let actualUrl = '/$/' + page; if (queryString) { actualUrl += `?${queryString.slice(1)}`; } return actualUrl; } } // Regular claim url return path; }; export const formatWebUrlIntoLbryUrl = (pathname, search) => { // If there is no uri, the user is on an internal page // pathname will either be "/" or "/$/{page}" const path = pathname.startsWith('/$/') ? pathname.slice(3) : pathname.slice(1); let appLink = `lbry://?${path || PAGES.DISCOVER}`; if (search) { // We already have a leading "?" for the query param on internal pages appLink += search.replace('?', '&'); } return appLink; }; export const generateInitialUrl = (hash) => { let url = '/'; if (hash) { hash = hash.replace('#', ''); url = hash.startsWith('/') ? hash : '/' + hash; } return url; }; export const generateLbryContentUrl = (canonicalUrl, permanentUrl) => { return canonicalUrl ? canonicalUrl.split('lbry://')[1] : permanentUrl.split('lbry://')[1]; }; export const generateLbryWebUrl = (lbryUrl) => { return lbryUrl.replace(/#/g, ':'); }; export const generateEncodedLbryURL = (domain, lbryWebUrl, includeStartTime, startTime, listId) => { let urlParams = new URLSearchParams(); if (includeStartTime) { urlParams.append('t', startTime.toString()); } if (listId) { urlParams.append(COLLECTIONS_CONSTS.COLLECTION_ID, listId); } const urlParamsString = urlParams.toString(); const encodedPart = encodeWithSpecialCharEncode(`${lbryWebUrl}?${urlParamsString}`); return `${domain}/${encodedPart}`; }; // @flow export const generateShareUrl = ( domain, lbryUrl, referralCode, rewardsApproved, includeStartTime, startTime, listId, viewKeySigData: ChannelSignResponse ) => { let urlParams = new URLSearchParams(); if (referralCode && rewardsApproved) { urlParams.append('r', referralCode); } if (listId) { urlParams.append(COLLECTIONS_CONSTS.COLLECTION_ID, listId); } if (includeStartTime) { urlParams.append('t', startTime.toString()); } if (viewKeySigData) { urlParams.append('signature', viewKeySigData.signature); urlParams.append('signature_ts', viewKeySigData.signing_ts); } const urlParamsString = urlParams.toString(); const { streamName, streamClaimId, channelName, channelClaimId } = parseURI(lbryUrl); let uriParts = { ...(streamName ? { streamName: encodeWithSpecialCharEncode(streamName) } : {}), ...(streamClaimId ? { streamClaimId } : {}), ...(channelName ? { channelName: encodeWithSpecialCharEncode(channelName) } : {}), ...(channelClaimId ? { channelClaimId } : {}), }; const encodedUrl = buildURI(uriParts, false, false); const lbryWebUrl = encodedUrl.replace(/#/g, ':'); const url = `${domain}/${lbryWebUrl}` + (urlParamsString === '' ? '' : `?${urlParamsString}`); return url; }; // @flow export const generateShortShareUrl = async ( domain, lbryUrl, referralCode, rewardsApproved, includeStartTime, startTime, listId, uriAccessKey?: UriAccessKey ) => { type Params = Array<[string, ?string]>; const paramsToShorten: Params = [ ['signature', uriAccessKey ? uriAccessKey.signature : null], ['signature_ts', uriAccessKey ? uriAccessKey.signature_ts : null], [COLLECTIONS_CONSTS.COLLECTION_ID, listId || null], ['r', referralCode && rewardsApproved ? referralCode : null], ]; const paramsToRetain: Params = [['t', includeStartTime ? startTime.toString() : null]]; // -- Build base URL with claim gists: const { streamName, streamClaimId, channelName, channelClaimId } = parseURI(lbryUrl); const uriParts = { ...(streamName ? { streamName: encodeWithSpecialCharEncode(streamName) } : {}), ...(streamClaimId ? { streamClaimId } : {}), ...(channelName ? { channelName: encodeWithSpecialCharEncode(channelName) } : {}), ...(channelClaimId ? { channelClaimId } : {}), }; const encodedUrl = buildURI(uriParts, false, false); const lbryWebUrl = encodedUrl.replace(/#/g, ':'); const baseUrl = `${domain}/${lbryWebUrl}`; // -- Append params that we want to shorten: const urlToShorten = new URL(baseUrl); paramsToShorten.forEach((p: Params) => { if (p[1]) { urlToShorten.searchParams.set(p[0], p[1]); } }); // -- Fetch the short url: const shortUrl = await ShortUrl.createFrom(urlToShorten.toString()) .then((res: ShortUrlResponse) => { return res.shortUrl; }) .catch((err) => { assert(false, 'ShortUrl api failed, returning original', err); return urlToShorten.toString(); }); // -- Put remaining params that we want in original form: const finalUrl = new URL(shortUrl); paramsToRetain.forEach((p: Params) => { if (p[1]) { finalUrl.searchParams.set(p[0], p[1]); } }); // -- Profit return finalUrl.toString(); }; export const generateRssUrl = (domain, channelClaim) => { if (!channelClaim || channelClaim.value_type !== 'channel' || !channelClaim.canonical_url) { return ''; } const url = `${domain}/$/rss/${channelClaim.canonical_url.replace('lbry://', '').replace('#', ':')}`; return url; }; export const generateListSearchUrlParams = (collectionId) => { const urlParams = new URLSearchParams(); urlParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId); return `?` + urlParams.toString(); }; // Google cache url // ex: webcache.googleusercontent.com/search?q=cache:MLwN3a8fCbYJ:https://lbry.tv/%40Bombards_Body_Language:f+&cd=12&hl=en&ct=clnk&gl=us // Extract the lbry url and use that instead // Without this it will try to render lbry://search export function generateGoogleCacheUrl(search, path) { const googleCacheRegex = new RegExp(`(https://${DOMAIN}/)([^+]*)`); const [x, y, googleCachedUrl] = search.match(googleCacheRegex); // eslint-disable-line if (googleCachedUrl) { const actualUrl = decodeURIComponent(googleCachedUrl); if (actualUrl) { path = actualUrl.replace(/:/g, '#'); } } } export const getPathForPage = (page) => `/$/${page}/`; export const getModalUrlParam = (modal, modalParams = {}) => { const urlParams = new URLSearchParams(); urlParams.set(URLParams.MODAL, modal); urlParams.set(URLParams.MODAL_PARAMS, encodeURIComponent(JSON.stringify(modalParams))); const embedUrlParams = urlParams.toString(); return embedUrlParams; };
<span class="category-row">{{ challenge.category }}</span> <div class="name-row"> <div class="dot"></div> <span class="name">{{ challenge.name }}</span> <difficulty-stars [difficulty]="challenge.difficulty" ></difficulty-stars> </div> <div class="description-row" [innerHtml]="challenge.description"></div> <div class="bottom-row"> <div class="tags"> <span *ngFor="let tag of challenge.tagList" class="tag" [matTooltip]="('TAG_' + tag?.toUpperCase().split(' ').join('_') + '_DESCRIPTION' | translate)">{{ tag }}</span> </div> <div class="badge-group"> <!-- info text if the challenge is unavailable --> <button class="badge" *ngIf="challenge.disabledEnv !== null" [matTooltip]="'CHALLENGE_UNAVAILABLE' | translate:{ env: challenge.disabledEnv }" > <mat-icon [style.color]="'var(--theme-warn)'">info_outline</mat-icon> </button> <!-- coding challenge badge --> <button class="badge" *ngIf="challenge.hasCodingChallenge" (click)="openCodingChallengeDialog(challenge.key)" [disabled]="challenge.solved === false" [ngClass]="{ 'partially-completed': challenge.codingChallengeStatus === 1, 'completed': challenge.codingChallengeStatus === 2 }" [matTooltip]="(challenge.solved ? 'LAUNCH_CODING_CHALLENGE' : 'SOLVE_HACKING_CHALLENGE') | translate" > <span class="badge-status" *ngIf="challenge.codingChallengeStatus !== 0">{{ challenge.codingChallengeStatus }}/2</span> <mat-icon>code</mat-icon> </button> <!-- cheat cheat link--> <a class="badge not-completable" *ngIf="challenge.mitigationUrl && challenge.solved" [href]="challenge.mitigationUrl" target="_blank" rel="noopener noreferrer" [matTooltip]="'INFO_VULNERABILITY_MITIGATION_LINK' | translate" aria-label="Vulnerability mitigation link" > <mat-icon>policy_outline</mat-icon> </a> <!-- ctf mode flag repeat--> <button class="badge" [ngClass]="{ 'completed': challenge.solved }" *ngIf="challenge.solved && applicationConfiguration.ctf.showFlagsInNotifications" (click)="repeatChallengeNotification(challenge.key)" [matTooltip]="'NOTIFICATION_RESEND_INSTRUCTIONS' | translate" > <mat-icon>flag_outline</mat-icon> </button> <!-- hacking instructor--> <button class="badge not-completable" *ngIf="hasInstructions(challenge.name)" [matTooltip]="'INFO_HACKING_INSTRUCTOR' | translate" (click)="startHackingInstructorFor(challenge.name)" > <mat-icon>school_outline</mat-icon> </button> <!-- challenge hint --> <!-- with hintUrl --> <a *ngIf="challenge.hint && challenge.hintUrl" class="badge not-completable" [style.padding]="'0 6px 0 4px'" target="_blank" rel="noopener noreferrer" [href]="challenge.hintUrl" [matTooltip]="challenge.hint | challengeHint:{hintUrl: challenge.hintUrl} | async" > <mat-icon>lightbulb</mat-icon> Hint </a> <!-- challenge hint --> <!-- without hintUrl --> <span *ngIf="challenge.hint && !challenge.hintUrl" class="badge not-completable" [style.padding]="'0 6px 0 4px'" [matTooltip]="challenge.hint" > <mat-icon>lightbulb</mat-icon> Hint </span> </div> </div>
(() => { // 为什么有两个 root 呢? // 因为初始渲染会生成一个 fiber 链表,然后后面 setState 更新会再生成一个新的 fiber 链表,两个 fiber 链表要做一些对比里决定对 dom 节点的增删改,所以都要保存。 // 用 nextUnitOfWork 指向下一个要处理的 fiber 节点 let nextUnitOfWork = null; // 当前正在处理的 fiber 链表的根 wipRoot let wipRoot = null; // 之前的历史 fiber 链表的根 currentRoot let currentRoot = null; // 要删除的节点 let deletions = null; // 从 wipRoot 开始,逐渐 reconcile 构建新的 fiber 节点 // 根据 FunctionComponent 还是原生标签(HostComponent)来分别执行函数和创建 dom // 并且还对新旧的 fiber 节点做了 diff,搭上增删改标记。 function render(element, container) { wipRoot = { dom: container, props: { children: [element], }, alternate: currentRoot, }; // render的时候初始化 deletions = []; nextUnitOfWork = wipRoot; } function workLoop(deadline) { let shouldYield = false; while (nextUnitOfWork && !shouldYield) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); // 每次跑的时候判断下 timeRemaining 是否接近 0,是的话就中断循环,等下次 requestIdleCallback 的回调再继续处理 nextUnitOfWork 指向的 fiber 节点 shouldYield = deadline.timeRemaining() < 1; } // requestIdleCallback 在不断进行,每次处理一部分 fiber 的 reconcile。 // 我们只要在 reconcile 结束,也就是没有 nextUnitOfWork 的时候执行 commit 就行了 if (!nextUnitOfWork && wipRoot) { commitRoot(); } requestIdleCallback(workLoop); } requestIdleCallback(workLoop); /** * 先把需要删除的节点都删掉,然后遍历 fiber 链表,处理其它节点 */ function commitRoot() { deletions.forEach(commitWork); commitWork(wipRoot.child); // 处理 effect commitEffectHooks(); currentRoot = wipRoot; wipRoot = null; } function commitEffectHooks() { function runCleanup(fiber) { if (!fiber) return; // 先遍历一遍执行所有的 cleanup 函数,然后再次遍历执行 effect 函数。 fiber.alternate?.effectHooks?.forEach((hook, index) => { const deps = fiber.effectHooks[index].deps; // 当没有传入 deps 数组,或者 deps 数组和上次不一致时,就执行 cleanup 函数 if (!hook.deps || !isDepsEqual(hook.deps, deps)) { hook.cleanup?.(); } }); // 遍历 fiber 链表也是递归处理每个节点,每个节点递归处理 child、sibling runCleanup(fiber.child); runCleanup(fiber.sibling); } function run(fiber) { if (!fiber) return; fiber.effectHooks?.forEach((newHook, index) => { // 当没有 alternate 的时候,就是首次渲染,直接执行所有的 effect。 if (!fiber.alternate) { newHook.cleanup = newHook.callback(); return; } // 否则,如果没传入 deps 或者 deps 数组变化的时候再执行 effect 函数 if (!newHook.deps) { newHook.cleanup = newHook.callback(); } if (newHook.deps.length > 0) { const oldHook = fiber.alternate?.effectHooks[index]; if (!isDepsEqual(oldHook.deps, newHook.deps)) { newHook.cleanup = newHook.callback(); } } }); run(fiber.child); run(fiber.sibling); } // 当没有传入 deps 数组,或者 deps 数组和上次不一致时,就执行 cleanup 函数 runCleanup(wipRoot); // 之后才会重新执行 effect run(wipRoot); } function isDepsEqual(deps, newDeps) { if (deps.length !== newDeps.length) { return false; } for (let i = 0; i < deps.length; i++) { if (deps[i] !== newDeps[i]) { return false; } } return true; } function commitWork(fiber) { if (!fiber) { return; } // 不断向上找,找到可以挂载的 dom 节点。 let domParentFiber = fiber.return; while (!domParentFiber.dom) { domParentFiber = domParentFiber.return; } const domParent = domParentFiber.dom; // 按照增增删改的 effectTag 来分别做处理。 if (fiber.effectTag === "PLACEMENT" && fiber.dom != null) { domParent.appendChild(fiber.dom); } else if (fiber.effectTag === "UPDATE" && fiber.dom != null) { updateDom(fiber.dom, fiber.alternate.props, fiber.props); } else if (fiber.effectTag === "DELETION") { commitDeletion(fiber, domParent); } // 按照 child、sibling 的顺序来递归遍历 fiber 链表 commitWork(fiber.child); commitWork(fiber.sibling); } function commitDeletion(fiber, domParent) { // 删除的时候,如果当前 fiber 节点没有对应的 dom,就不断 child 向下找。 if (fiber.dom) { domParent.removeChild(fiber.dom); } else { commitDeletion(fiber.child, domParent); } } requestIdleCallback(workLoop); function performUnitOfWork(fiber) { // 处理每个 fiber 节点的时候,要根据类型做不同的处理 const isFunctionComponent = fiber.type instanceof Function; // 判断下是函数组件(FunctionComponent),还是原生标签(HostComponent),分别做处理 if (isFunctionComponent) { // 函数组件就是传入 props 调用它,并且函数组件的返回值就是要继续 reconcile 的节点 updateFunctionComponent(fiber); } else { // 对于原生标签(HostComponent),就是创建它对应的 dom 节点 updateHostComponent(fiber); } // 子 => 弟 => 父 => 子 => 弟 => 父 // 按照 child、sibling、return 的顺序返回下一个要处理的 fiber 节点 if (fiber.child) return fiber.child; let nextFiber = fiber; // 通过这种顺序来把 fiber 树变为链表的形式 while (nextFiber) { if (nextFiber.sibling) return nextFiber.sibling; nextFiber = nextFiber.return; } } let wipFiber = null; let stateHookIndex = null; function updateFunctionComponent(fiber) { // 用 wipFiber 指向当前处理的 fiber(之前的 nextUnitOfWork 是指向下一个要处理的 fiber 节点) wipFiber = fiber; stateHookIndex = 0; // useState 的 state 和 useEffect 的 effect 存在 Fiber 上 // 用一个 stateHooks 数组来存储 useState 的 hook 的值,用 effectHooks 数组存储 useEffect 的 hook 的值。 wipFiber.stateHooks = []; wipFiber.effectHooks = []; const children = [fiber.type(fiber.props)]; reconcileChildren(fiber, children); } function updateHostComponent(fiber) { // 对于原生标签(HostComponent),就是创建它对应的 dom 节点 if (!fiber.dom) { fiber.dom = createDOM(fiber); } reconcileChildren(fiber, fiber.props.children); } /** * reconcile子节点 * @param {*} wipFiber * @param {*} elements */ function reconcileChildren(wipFiber, elements) { let index = 0; // 拿到 alternate 的 child,依次取 sibling,逐一和新的 fiber 节点对比 let oldFiber = wipFiber.alternate?.child; let prevSibling = null; while (index < elements.length || oldFiber != null) { const element = elements[index]; let newFiber = null; // diff 两个 fiber 链表也比较简单,就是判断节点 type 是不是一样。 const sameType = oldFiber && element && element.type === oldFiber.type; // 当 reconcile 创建新的 fiber 树的时候,就可以和之前的做 diff,判断是新增、修改、删除,打上对应的标记(effectTag) // 如果一样,就是修改(v) if (sameType) { newFiber = { // 类型 type: oldFiber.type, // 参数 props: element.props, dom: oldFiber.dom, return: wipFiber, // 旧的 fiber 节点 alternate: oldFiber, // 增删改的标记 effectTag: "UPDATE", }; } // 不一样,那就是删除(DELETION)或者新增(PLACEMENT),打上对应的标记 if (element && !sameType) { newFiber = { type: element.type, props: element.props, dom: null, return: wipFiber, alternate: null, effectTag: "PLACEMENT", }; } if (oldFiber && !sameType) { oldFiber.effectTag = "DELETION"; deletions.push(oldFiber); } if (oldFiber) { oldFiber = oldFiber.sibling; } // 根据对比结果来创建新的 fiber 节点,也是先 child 后 sibling 的方式: if (index === 0) { wipFiber.child = newFiber; } else if (element) { prevSibling.sibling = newFiber; } prevSibling = newFiber; index++; } } function createDOM(fiber) { const dom = fiber.type === "TEXT_ELEMENT" ? document.createTextNode("") : document.createElement(fiber.type); updateDom(dom, {}, fiber.props); return dom; } const isEvent = (key) => key.startsWith("on"); const isProperty = (key) => key !== "children" && !isEvent(key); const isNew = (prev, next) => (key) => prev[key] !== next[key]; const isGone = (prev, next) => (key) => !(key in next); function updateDom(dom, prevProps, nextProps) { // 先删除旧的事件监听器 Object.keys(prevProps) .filter(isEvent) .filter((key) => !(key in nextProps) || isNew(prevProps, nextProps)(key)) .forEach((name) => { const eventType = name.toLowerCase().substring(2); dom.removeEventListener(eventType, prevProps[name]); }); // 删除旧的属性 Object.keys(prevProps) .filter(isProperty) .filter(isGone(prevProps, nextProps)) .forEach((name) => { dom[name] = ""; }); // 添加新的属性 Object.keys(nextProps) .filter(isProperty) .filter(isNew(prevProps, nextProps)) .forEach((name) => { dom[name] = nextProps[name]; }); // 添加新的事件监听器 Object.keys(nextProps) .filter(isEvent) .filter(isNew(prevProps, nextProps)) .forEach((name) => { const eventType = name.toLowerCase().substring(2); dom.addEventListener(eventType, nextProps[name]); }); } function createElement(type, props, ...children) { return { type, props: { ...props, children: children.map((child) => { const isTextNode = typeof child === "string" || typeof child === "number"; return isTextNode ? createTextNode(child) : child; }), }, }; } function createTextNode(nodeValue) { return { type: "TEXT_ELEMENT", // 文本节点是没有 type、children、props // 加个固定的 type TEXT_ELEMENT,并且设置 nodeValue 的 props。这样结构统一,方便后面处理 props: { nodeValue, children: [], }, }; } function useState(initialState) { const currentFiber = wipFiber; const oldHook = wipFiber.alternate?.stateHooks?.[stateHookIndex]; // 每次调用 useState 时会在 stateHooks 添加一个元素来保存 state: const stateHook = { // state 的初始值是前面一次渲染的 state 值,也就是取 alternate 的同一位置的 state: state: oldHook ? oldHook.state : initialState, queue: oldHook ? oldHook.queue : [], }; // 累计计算 state, 这样对初始 state 执行多个 action(也就是 setState) 之后,就拿到了最终的 state 值。 stateHook.queue.forEach((action) => { stateHook.state = action(stateHook.state); }); // 修改完 state 之后清空 queue。 stateHook.queue = []; stateHookIndex++; // 在 fiber 节点上用 stateHooks 数组来存储 state,还有多次调用 setState 的回调函数。 wipFiber.stateHooks.push(stateHook); function setState(action) { const isFunction = typeof action === "function"; stateHook.queue.push(isFunction ? action : () => action); // setState 就是在 action 数组里添加新的 action,并且让 nextUnitOfWork 指向新的 wipRoot,从而开始新的一轮渲染 wipRoot = { ...currentFiber, alternate: currentFiber, }; nextUnitOfWork = wipRoot; } return [stateHook.state, setState]; } function useEffect(callback, deps) { // 就是在 fiber.effectHooks 上添加一个元素。 // 这样,等 reconcile 结束,fiber 链表就构建好了,在 fiber 上打上了增删改的标记,并且也保存了要执行的 effect。 const effectHook = { callback, deps, cleanup: null, }; wipFiber.effectHooks.push(effectHook); } const MiniReact = { createElement, render, useState, useEffect, }; window.MiniReact = MiniReact; })();
import React, { useEffect, useState } from "react"; import { useSelector } from "react-redux"; import colorPalette from "../../style/palette"; import { Button } from "react-bootstrap"; import FavoriteIcon from '@mui/icons-material/Favorite'; import FavoriteBorderIcon from '@mui/icons-material/FavoriteBorder'; export default function FavoritesList() { const favorites = useSelector((state) => state.Store.favorites); const [favoriteCharacters, setFavoriteCharacters] = useState([]); const username = useSelector((state) => state.Store.username); useEffect(() => { const fetchCharacterDetails = async (id) => { try { const response = await fetch(`https://rickandmortyapi.com/api/character/${id}`); const data = await response.json(); return data; } catch (error) { console.error("Error fetching character details:", error); return null; } }; const getFavoriteCharacters = async () => { const favoriteCharactersDetails = []; for (const id of favorites) { const character = await fetchCharacterDetails(id); if (character !== null) { favoriteCharactersDetails.push(character); } } setFavoriteCharacters(favoriteCharactersDetails); }; getFavoriteCharacters(); }, [favorites]); function updateFavorites(id) { if (favorites.includes(id)) { fetch('http://localhost:5000/remove_favorite', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: username, id: id }) }) .catch((error) => { console.log(error) }) } else { fetch('http://localhost:5000/add_favorite', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: username, id: id }) }) .catch((error) => { console.log(error) }) } } return ( favoriteCharacters.length === 0 ? ( <span style={{ color: "#FFF" }}>Aucun personnage favori trouvé</span> ) : ( <div className="container"> {favoriteCharacters.map((row, rowIndex) => ( <div className="row" key={rowIndex}> {row.map((character) => ( <div className="col-md-2.4 mb-4 mx-2 p-4" key={character.id}> <div className="card card-hover"> <a href={character.url} className="card-link" id='card-link'> <div> <img src={character.image} className="card-img-top" alt={character.name} /> <div className="card-body" style={{ height: '45vh' }}> <h5 className="card-title">{character.name}</h5> </div> </div> </a> <div className='card-footer' style={{ background: colorPalette.lightBackground }}> <Button className='btn d-flex flex-direction-row' style={{ background: 'transparent', border: 'none', width: '100%' }} onClick={() => updateFavorites(character.id)}> {favorites.includes(character.id) ? ( <><FavoriteIcon style={{ color: 'red', marginRight: '10px' }} /> <p>Retirer des favoris</p></> ) : ( <><FavoriteBorderIcon style={{ marginRight: '10px' }} /> <p>Ajouter aux favoris</p></> )} </Button> </div> </div> </div> ))} </div> ))} </div> ) ); }