text
stringlengths
184
4.48M
package pl.niewadzj.moneyExchange.api.currencyAccount; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import pl.niewadzj.moneyExchange.api.currencyAccount.interfaces.CurrencyAccountController; import pl.niewadzj.moneyExchange.api.currencyAccount.interfaces.CurrencyAccountService; import pl.niewadzj.moneyExchange.api.currencyAccount.records.BalanceResponse; import pl.niewadzj.moneyExchange.api.currencyAccount.records.CurrencyAccountResponse; import pl.niewadzj.moneyExchange.api.currencyAccount.records.TransactionRequest; import pl.niewadzj.moneyExchange.entities.user.User; import static pl.niewadzj.moneyExchange.api.currencyAccount.constants.CurrencyAccountMappings.ACTIVATE_ACCOUNT_MAPPING; import static pl.niewadzj.moneyExchange.api.currencyAccount.constants.CurrencyAccountMappings.CURRENCY_ACCOUNT_MAPPING; import static pl.niewadzj.moneyExchange.api.currencyAccount.constants.CurrencyAccountMappings.DEPOSIT_MAPPING; import static pl.niewadzj.moneyExchange.api.currencyAccount.constants.CurrencyAccountMappings.GET_CURRENCY_ACCOUNT; import static pl.niewadzj.moneyExchange.api.currencyAccount.constants.CurrencyAccountMappings.SUSPEND_ACCOUNT_MAPPING; import static pl.niewadzj.moneyExchange.api.currencyAccount.constants.CurrencyAccountMappings.WITHDRAW_MAPPING; @Slf4j @RestController @RequiredArgsConstructor @RequestMapping(CURRENCY_ACCOUNT_MAPPING) public class CurrencyAccountControllerImpl implements CurrencyAccountController { private final CurrencyAccountService currencyAccountService; @Override @PutMapping(DEPOSIT_MAPPING) public final BalanceResponse depositToAccount(@RequestBody @Valid TransactionRequest transactionRequest, @AuthenticationPrincipal User user) { return currencyAccountService.depositToAccount(transactionRequest, user); } @Override @PutMapping(WITHDRAW_MAPPING) public final BalanceResponse withdrawFromAccount(@RequestBody @Valid TransactionRequest transactionRequest, @AuthenticationPrincipal User user) { return currencyAccountService.withdrawFromAccount(transactionRequest, user); } @Override @GetMapping(GET_CURRENCY_ACCOUNT) public final CurrencyAccountResponse getCurrencyAccountByCurrencyId(@RequestParam Long currencyId, @AuthenticationPrincipal User user) { return currencyAccountService.getCurrencyAccountByCurrencyId(currencyId, user); } @Override @PatchMapping(SUSPEND_ACCOUNT_MAPPING) public final void suspendCurrencyAccount(@RequestParam Long currencyId, @AuthenticationPrincipal User user) { currencyAccountService.suspendCurrencyAccount(currencyId, user); } @Override @PatchMapping(ACTIVATE_ACCOUNT_MAPPING) public final void activateCurrencyAccount(@RequestParam Long currencyId, @AuthenticationPrincipal User user) { currencyAccountService.activateCurrencyAccount(currencyId, user); } }
package sectional.springsectional.aop; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; @Slf4j @Aspect @RequiredArgsConstructor public class AspectTransactionController { private final PlatformTransactionManager manager; @Around("args()") public void targetObject() { } @Around("execution(* sectional.springsectional.mvc.PostServiceImpl.*(..))") public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { TransactionStatus tx = manager.getTransaction(new DefaultTransactionDefinition()); //외부 트랜잭션 try { //save result = true : commit //save result = false : rollBack log.info("트랜잭션 시작 = {}" ,joinPoint.getSignature()); Object proceed = joinPoint.proceed(); log.info("커밋 = {}" ,joinPoint.getSignature()); this.manager.commit(tx); return proceed; } catch (RuntimeException e) { log.info("롤백 = {}" ,e.getMessage()); this.manager.rollback(tx); throw e; } } }
import SideMenuAccountItem, { type SideMenuAccountItemProps } from './side-menu-account-item'; import { Meta, StoryObj } from '@storybook/react'; import { action } from '@storybook/addon-actions'; export default { title: 'components/common/SideMenuAccountItem', component: SideMenuAccountItem, } as Meta<typeof SideMenuAccountItem>; export const Default: StoryObj<SideMenuAccountItemProps> = { args: { selected: false, account: { accountId: '1', name: 'Account 1', address: 'Address1', balance: '123,992.09 GNOT', type: 'HD_WALLET', }, changeAccount: action('changeAccount'), moveGnoscan: action('moveGnoscan'), moveAccountDetail: action('moveAccountDetail'), }, }; export const Ledger: StoryObj<SideMenuAccountItemProps> = { args: { account: { accountId: '1', name: 'Account 1', address: 'Address1', balance: '123,992.09 GNOT', type: 'LEDGER', }, changeAccount: action('changeAccount'), moveGnoscan: action('moveGnoscan'), moveAccountDetail: action('moveAccountDetail'), }, }; export const Import: StoryObj<SideMenuAccountItemProps> = { args: { account: { accountId: '1', name: 'Account 1', address: 'Address1', balance: '123,992.09 GNOT', type: 'PRIVATE_KEY', }, changeAccount: action('changeAccount'), moveGnoscan: action('moveGnoscan'), moveAccountDetail: action('moveAccountDetail'), }, }; export const Google: StoryObj<SideMenuAccountItemProps> = { args: { account: { accountId: '1', name: 'Account 1', address: 'Address1', balance: '123,992.09 GNOT', type: 'WEB3_AUTH', }, changeAccount: action('changeAccount'), moveGnoscan: action('moveGnoscan'), moveAccountDetail: action('moveAccountDetail'), }, };
# week 1 # gm1 checkpoint system and lives 7 # bh1 scrolling background 4/3 - add extension # bh2 destroy some rock obstacles - edit tilemap then code 3 # bh3 animate lava tiles 2/3 # week 2 # gm2 moving platforms 6 place on tilemap # bh4 sharks that swin across the screen 6 # bh5 new level 4 - make tilemap # bh6 level save 1/2 # week 3 # gm3 shrimp that patrols 9 # bh7 animate enemy dying and falling off 3 # bh8 ladder 5 # bh9 collectables - assets, tilemap, func, edit load, collect 5 @namespace class SpriteKind: enemy_projectile = SpriteKind.create() moving_platform = SpriteKind.create() platform_hitbox = SpriteKind.create() floating_enemy = SpriteKind.create() # gm3 patrolling_enemy = SpriteKind.create() # /gm3 # bh7 if you did not do bh3 effect = SpriteKind.create() # /bh7 # sprites shrimp = sprites.create(assets.image("shrimp right"), SpriteKind.player) shrimp.ay = 325 scene.camera_follow_sprite(shrimp) characterAnimations.run_frames(shrimp, [assets.image("shrimp right")], 1, characterAnimations.rule(Predicate.FACING_RIGHT)) characterAnimations.run_frames(shrimp, [assets.image("shrimp left")], 1, characterAnimations.rule(Predicate.FACING_LEFT)) # variables levels = [ assets.tilemap("level 1"), assets.tilemap("level 2"), assets.tilemap("level 3"), assets.tilemap("level 4") ] level = 3 jump_count = 2 facing_right = True # setup scene.set_background_image(assets.image("background")) scroller.scroll_background_with_camera(scroller.CameraScrollMode.ONLY_HORIZONTAL) info.set_life(3) def animate_lava(): sprites.destroy_all_sprites_of_kind(SpriteKind.effect) for lava_tile in tiles.get_tiles_by_type(assets.tile("lava")): effect_sprite = sprites.create(image.create(1, 1), SpriteKind.effect) tiles.place_on_tile(effect_sprite, lava_tile) effect_sprite.y -= 8 effect_sprite.start_effect(effects.bubbles) def make_moving_platforms(): for moving_platform_tile in tiles.get_tiles_by_type(assets.tile("moving platform")): moving_platform = sprites.create(assets.tile("moving platform"), SpriteKind.moving_platform) tiles.place_on_tile(moving_platform, moving_platform_tile) tiles.set_tile_at(moving_platform_tile,image.create(16, 16)) moving_platform.set_flag(SpriteFlag.BOUNCE_ON_WALL, True) moving_platform.vx = 30 hitbox = sprites.create(image.create(16, 4), SpriteKind.platform_hitbox) sprites.set_data_sprite(hitbox, "platform", moving_platform) hitbox.image.fill(1) hitbox.set_flag(SpriteFlag.INVISIBLE, True) def load_save(): global level if game.ask("Would you like to load your previous game?"): if database.exists_key("level"): level = database.get_number_value("level") else: game.splash("No save file found") load_save() # bh9 def spawn_coins(): sprites.destroy_all_sprites_of_kind(SpriteKind.food) for coin_spawn in tiles.get_tiles_by_type(assets.tile("coin spawn")): coin = sprites.create(assets.image("coin"), SpriteKind.food) tiles.place_on_tile(coin, coin_spawn) tiles.set_tile_at(coin_spawn, image.create(16, 16)) # /bh9 # gm3 def make_crabs(): sprites.all_of_kind(SpriteKind.patrolling_enemy) for crab_spawn in tiles.get_tiles_by_type(assets.tile("enemy crab spawn")): crab = sprites.create(assets.image("enemy crab"), SpriteKind.patrolling_enemy) crab.set_flag(SpriteFlag.BOUNCE_ON_WALL, True) crab.vx = 50 tiles.place_on_tile(crab, crab_spawn) tiles.set_tile_at(crab_spawn, image.create(16, 16)) # /gm3 def load_level(): shrimp.set_velocity(0, 0) scene.set_tile_map_level(levels[level - 1]) tiles.place_on_random_tile(shrimp, assets.tile("player spawn")) tiles.set_tile_at(shrimp.tilemap_location(), assets.tile("checkpoint collected")) sprites.destroy_all_sprites_of_kind(SpriteKind.enemy) for urchin_tile in tiles.get_tiles_by_type(assets.tile("enemy spawn")): urchin = sprites.create(assets.image("urchin"), SpriteKind.enemy) tiles.place_on_tile(urchin, urchin_tile) tiles.set_tile_at(urchin_tile, image.create(16, 16)) animate_lava() make_moving_platforms() database.set_number_value("level", level) # gm3 make_crabs() # /gm3 # bh9 spawn_coins() # /bh9 load_level() def player_fire(): proj = sprites.create_projectile_from_sprite(assets.image("shockwave"), shrimp, 0, 0) proj.scale = 0.5 if facing_right: proj.vx = 200 animation.run_image_animation(shrimp, assets.animation("attack right"), 100, False) else: proj.vx = -200 proj.image.flip_x() animation.run_image_animation(shrimp, assets.animation("attack left"), 100, False) def throttle_fire(): timer.throttle("player fire", 300, player_fire) controller.A.on_event(ControllerButtonEvent.PRESSED, throttle_fire) def jump(): global jump_count if jump_count < 1: shrimp.vy = -155 jump_count += 1 controller.up.on_event(ControllerButtonEvent.PRESSED, jump) def take_damage(): info.change_life_by(-1) shrimp.set_velocity(0, 0) tiles.place_on_random_tile(shrimp, assets.tile("checkpoint collected")) def hit(shrimp, spine): timer.throttle("take damage", 1000, take_damage) # sprites.on_overlap(SpriteKind.player, SpriteKind.enemy_projectile, hit) # sprites.on_overlap(SpriteKind.player, SpriteKind.floating_enemy, hit) # gm3 # sprites.on_overlap(SpriteKind.player, SpriteKind.patrolling_enemy, hit) # /gm3 # bh9 def get_coin(shrimp, coin): info.change_score_by(500) music.power_up.play() coin.destroy() sprites.on_overlap(SpriteKind.player, SpriteKind.food, get_coin) # /bh9 def hit_lava(shrimp, location): timer.throttle("take damage", 1000, take_damage) scene.on_overlap_tile(SpriteKind.player, assets.tile("lava"), hit_lava) # bh8 def use_ladder(shrimp, location): shrimp.vy = 0 if controller.up.is_pressed(): shrimp.vy = -50 elif controller.down.is_pressed(): shrimp.vy = 50 scene.on_overlap_tile(SpriteKind.player, assets.tile("ladder"), use_ladder) # /bh8 def reach_checkpoint(shrimp, checkpoint): for checkpoint_collected in tiles.get_tiles_by_type(assets.tile("checkpoint collected")): tiles.set_tile_at(checkpoint_collected, image.create(16, 16)) tiles.set_tile_at(checkpoint, assets.tile("checkpoint collected")) scene.on_overlap_tile(SpriteKind.player, assets.tile("checkpoint uncollected"), reach_checkpoint) def hit_wall(proj, location): if tiles.tile_image_at_location(location).equals(assets.tile("breakable rock")): tiles.set_tile_at(location, image.create(16, 16)) tiles.set_wall_at(location, False) effect_sprite = sprites.create(assets.tile("breakable rock")) tiles.place_on_tile(effect_sprite, location) effect_sprite.destroy(effects.disintegrate, 500) scene.on_hit_wall(SpriteKind.projectile, hit_wall) def next_level(): global level if level == len(levels): game.over(True) level += 1 load_level() scene.on_overlap_tile(SpriteKind.player, assets.tile("level end"), next_level) # bh7 def enemy_animate(enemy: Sprite): enemy.image.flip_y() for colour in range(1, 16): enemy.image.replace(colour, 1) enemy.set_kind(SpriteKind.effect) enemy.set_flag(SpriteFlag.GHOST, True) enemy.set_flag(SpriteFlag.AUTO_DESTROY, True) enemy.ay = 325 enemy.vy = -100 # /bh7 def enemy_hit(proj, enemy): info.change_score_by(10) proj.destroy() # bh7 # enemy.destroy() enemy_animate(enemy) # /bh7 sprites.on_overlap(SpriteKind.projectile, SpriteKind.enemy, enemy_hit) sprites.on_overlap(SpriteKind.projectile, SpriteKind.floating_enemy, enemy_hit) # gm3 sprites.on_overlap(SpriteKind.projectile, SpriteKind.patrolling_enemy, enemy_hit) # /gm3 def urchin_fire(urchin): for vx in range(-100, 101, 100): for vy in range(-100, 101, 100): if vx != 0 or vy != 0: spine = sprites.create_projectile_from_sprite(assets.image("spine"), urchin, vx, vy) spine.set_kind(SpriteKind.enemy_projectile) angle = spriteutils.radians_to_degrees(spriteutils.heading(spine) ) transformSprites.rotate_sprite(spine, angle) def urchin_behaviour(): for urchin in sprites.all_of_kind(SpriteKind.enemy): urchin_fire(urchin) game.on_update_interval(3000, urchin_behaviour) def shark_spawn(): shark = sprites.create(assets.image("shark"), SpriteKind.floating_enemy) if randint(1, 2) == 1: shark.image.flip_x() shark.right = 1 shark.vx = 50 else: shark.left = (tilesAdvanced.get_tilemap_width() * 16) - 1 shark.vx = -50 if spriteutils.distance_between(shark, shrimp) < 120: shark.destroy() shark_spawn shark.y = shrimp.y sprites.set_data_number(shark, "start y", shark.y) shark.set_flag(SpriteFlag.GHOST_THROUGH_WALLS, True) game.on_update_interval(1000, shark_spawn) def shark_behaviour(): for shark in sprites.all_of_kind(SpriteKind.floating_enemy): if shark.left > tilesAdvanced.get_tilemap_width() * 16 or shark.right < 0: shark.destroy() start_y = sprites.read_data_number(shark, "start y") shark.y = (Math.sin(shark.x / 20) * 20) + start_y def x_movement(): global facing_right if controller.left.is_pressed(): shrimp.vx -= 8 facing_right = False elif controller.right.is_pressed(): shrimp.vx += 8 facing_right = True shrimp.vx *= 0.9 def y_movement(): global jump_count if shrimp.is_hitting_tile(CollisionDirection.BOTTOM): jump_count = 0 # bh8 def check_on_ladder(): if tiles.tile_at_location_equals(shrimp.tilemap_location(), assets.tile("ladder")): shrimp.ay = 0 else: shrimp.ay = 325 # /bh8 # gm3 def crab_behaviour(): if len(sprites.all_of_kind(SpriteKind.patrolling_enemy)) < 1: return for crab in sprites.all_of_kind(SpriteKind.patrolling_enemy): location = crab.tilemap_location() tile_infront = tiles.get_tile_location(location.col, location.row + 1) if not tiles.tile_at_location_is_wall(tile_infront): crab.vx *= -1 crab.image.flip_x() # /gm3 def hit_moving_platform(shrimp, platform): if Math.abs(platform.x - shrimp.x) > Math.abs(platform.y - shrimp.y): shrimp.vx = 0 while shrimp.overlaps_with(platform): shrimp.x -= Math.sign(platform.x - shrimp.x) pause(0) else: shrimp.vy = 0 while shrimp.overlaps_with(platform): shrimp.y -= Math.sign(platform.y - shrimp.y) pause(0) sprites.on_overlap(SpriteKind.player, SpriteKind.moving_platform, hit_moving_platform) def use_moving_platform(): global jump_count for hitbox in sprites.all_of_kind(SpriteKind.platform_hitbox): platform = sprites.read_data_sprite(hitbox, "platform") hitbox.set_position(platform.x, platform.top - 2) if shrimp.overlaps_with(hitbox): jump_count = 0 fps = 1000 / spriteutils.get_delta_time() shrimp.x += platform.vx / fps shrimp.ay = 0 return shrimp.ay = 325 def tick(): x_movement() y_movement() use_moving_platform() shark_behaviour() # gm3 crab_behaviour() # /gm3 # bh8 check_on_ladder() # /bh8 game.on_update(tick)
import 'dart:math'; class Solution { int search(List<int> nums, int target) { final minPoint = findMin(nums); final left = binarySearch(nums, target, 0, minPoint - 1); final right = binarySearch(nums, target, minPoint, nums.length - 1); return max(left, right); } int findMin(List<int> nums) { var left = 0; var right = nums.length - 1; if (nums.length == 1) return 0; while (left < right) { final mid = ((left + right) / 2).floor(); if (nums[mid] > nums[right]) { left = mid + 1; } else { right = mid; } } return left; } int binarySearch(List<int> nums, target, left, right) { while (left <= right) { final mid = ((left + right) / 2).floor(); if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; } }
#include "PolyACalculator.h" #include "utils/sequence_utils.h" #include <edlib.h> #include <spdlog/spdlog.h> #include <algorithm> #include <array> #include <cmath> #include <limits> #include <utility> namespace { struct SignalAnchorInfo { // Is the strand in forward or reverse direction. bool is_fwd_strand = true; // The start or end anchor for the polyA/T signal // depending on whether the strand is forward or // reverse. int signal_anchor = -1; // Number of additional A/T bases in the polyA // stretch from the adapter. int trailing_adapter_bases = 0; }; const int kMaxTailLength = 750; // This algorithm walks through the signal in windows. For each window // the avg and stdev of the signal is computed. If the stdev is below // an empirically determined threshold, and consecutive windows have // similar avg and stdev, then those windows are considered to be part // of the polyA tail. std::pair<int, int> determine_signal_bounds(int signal_anchor, bool fwd, const dorado::SimplexRead& read, int num_samples_per_base, bool is_rna) { const c10::Half* signal = static_cast<c10::Half*>(read.read_common.raw_data.data_ptr()); int signal_len = read.read_common.get_raw_data_samples(); auto calc_stats = [&](int s, int e) -> std::pair<float, float> { float avg = 0; for (int i = s; i < e; i++) { avg += signal[i]; } avg = avg / (e - s); float var = 0; for (int i = s; i < e; i++) { var += (signal[i] - avg) * (signal[i] - avg); } var = var / (e - s); return {avg, std::sqrt(var)}; }; std::vector<std::pair<int, int>> intervals; std::pair<float, float> last_interval_stats; // Maximum variance between consecutive values to be // considered part of the same interval. const float kVar = 0.35f; // Determine the outer boundary of the signal space to // consider based on the anchor. const int kSpread = num_samples_per_base * kMaxTailLength; // Maximum gap between intervals that can be combined. const int kMaxSampleGap = num_samples_per_base * 3; // Minimum size of intervals considered for merge. const int kMinIntervalSizeForMerge = 10 * num_samples_per_base; // Floor for average signal value of poly tail. const float kMinAvgVal = (is_rna ? 0.0 : -3.0); int left_end = is_rna ? std::max(0, signal_anchor - 50) : std::max(0, signal_anchor - kSpread); int right_end = std::min(signal_len, signal_anchor + kSpread); spdlog::debug("Bounds left {}, right {}", left_end, right_end); const int kStride = 3; for (int s = left_end; s < right_end; s += kStride) { int e = std::min(s + kMaxSampleGap, right_end); auto [avg, stdev] = calc_stats(s, e); if (stdev < kVar) { // If a new interval overlaps with the previous interval, just extend // the previous interval. if (intervals.size() > 1 && intervals.back().second >= s && std::abs(avg - last_interval_stats.first) < 0.2 && (avg > kMinAvgVal)) { auto& last = intervals.back(); last.second = e; } else { // Attempt to merge the most recent interval and the one before // that if the gap between the intervals is small and both of the // intervals are longer than some threshold. if (intervals.size() > 2) { auto& last = intervals.back(); auto& second_last = intervals[intervals.size() - 2]; if ((last.first - second_last.second < kMaxSampleGap) && (last.second - last.first > kMinIntervalSizeForMerge) && (second_last.second - second_last.first > kMinIntervalSizeForMerge)) { second_last.second = last.second; intervals.pop_back(); } } intervals.push_back({s, e}); } last_interval_stats = {avg, stdev}; } } std::string int_str = ""; for (const auto& in : intervals) { int_str += std::to_string(in.first) + "-" + std::to_string(in.second) + ", "; } spdlog::debug("found intervals {}", int_str); std::vector<std::pair<int, int>> filtered_intervals; std::copy_if(intervals.begin(), intervals.end(), std::back_inserter(filtered_intervals), [&](auto& i) { int interval_size = i.second - i.first; // Filter out any small intervals. if (interval_size < (num_samples_per_base * 5)) { return false; } // Only keep intervals that are close-ish to the signal anchor. return (fwd ? std::abs(signal_anchor - i.second) < interval_size : std::abs(signal_anchor - i.first) < interval_size) || (i.first <= signal_anchor) && (signal_anchor <= i.second); }); int_str = ""; for (auto in : filtered_intervals) { int_str += std::to_string(in.first) + "-" + std::to_string(in.second) + ", "; } spdlog::debug("filtered intervals {}", int_str); if (filtered_intervals.empty()) { spdlog::debug("Anchor {} No range within anchor proximity found", signal_anchor); return {0, 0}; } // Choose the longest interval. If there is a tie for the longest interval, // choose the one that is closest to the anchor. auto best_interval = std::max_element(filtered_intervals.begin(), filtered_intervals.end(), [&](auto& l, auto& r) { auto l_size = l.second - l.first; auto r_size = r.second - r.first; if (l_size != r_size) { return l_size < r_size; } else { if (fwd) { return std::abs(l.second - signal_anchor) < std::abs(r.second - signal_anchor); } else { return std::abs(l.first - signal_anchor) < std::abs(r.first - signal_anchor); } } }); spdlog::debug("Anchor {} Range {} {}", signal_anchor, best_interval->first, best_interval->second); return *best_interval; } // Estimate the number of samples per base. For RNA, use the last 100 bases // to get a measure of samples/base. For DNA, just taking the average across // the whole read gives a decent estimate. int estimate_samples_per_base(const dorado::SimplexRead& read, bool is_rna) { size_t num_bases = read.read_common.seq.length(); if (is_rna && num_bases > 250) { const auto stride = read.read_common.model_stride; const auto seq_to_sig_map = dorado::utils::moves_to_map(read.read_common.moves, stride, read.read_common.get_raw_data_samples(), num_bases + 1); // Use last 100bp to estimate samples / base. size_t signal_len = seq_to_sig_map[num_bases] - seq_to_sig_map[num_bases - 100]; return std::floor(static_cast<float>(signal_len) / 100); } float num_samples_per_base = static_cast<float>(read.read_common.get_raw_data_samples()) / num_bases; // The estimate is not rounded because this calculation generally overestimates // the samples per base. Rounding down gives better results than rounding to nearest. return std::floor(num_samples_per_base); } // In order to find the approximate location of the start/end (anchor) of the polyA // cDNA tail, the adapter ends are aligned to the reads to find the breakpoint // between the read and the adapter. Adapter alignment also helps determine // the strand direction. This function returns a struct with the strand direction, // the approximate anchor for the tail, and if there needs to be an adjustment // made to the final polyA tail count based on the adapter sequence (e.g. because // the adapter itself contains several As). SignalAnchorInfo determine_signal_anchor_and_strand_cdna(const dorado::SimplexRead& read) { const std::string SSP = "TTTCTGTTGGTGCTGATATTGCTTT"; const std::string SSP_rc = dorado::utils::reverse_complement(SSP); const std::string VNP = "ACTTGCCTGTCGCTCTATCTTCAGAGGAGAGTCCGCCGCCCGCAAGTTTT"; const std::string VNP_rc = dorado::utils::reverse_complement(VNP); int trailing_Ts = dorado::utils::count_trailing_chars(VNP, 'T'); const int kWindowSize = 150; std::string read_top = read.read_common.seq.substr(0, kWindowSize); auto bottom_start = std::max(0, (int)read.read_common.seq.length() - kWindowSize); std::string read_bottom = read.read_common.seq.substr(bottom_start, kWindowSize); EdlibAlignConfig align_config = edlibDefaultAlignConfig(); align_config.task = EDLIB_TASK_LOC; align_config.mode = EDLIB_MODE_HW; // Check for forward strand. EdlibAlignResult top_v1 = edlibAlign(SSP.data(), SSP.length(), read_top.data(), read_top.length(), align_config); EdlibAlignResult bottom_v1 = edlibAlign(VNP_rc.data(), VNP_rc.length(), read_bottom.data(), read_bottom.length(), align_config); int dist_v1 = top_v1.editDistance + bottom_v1.editDistance; // Check for reverse strand. EdlibAlignResult top_v2 = edlibAlign(VNP.data(), VNP.length(), read_top.data(), read_top.length(), align_config); EdlibAlignResult bottom_v2 = edlibAlign(SSP_rc.data(), SSP_rc.length(), read_bottom.data(), read_bottom.length(), align_config); int dist_v2 = top_v2.editDistance + bottom_v2.editDistance; spdlog::debug("v1 dist {}, v2 dist {}", dist_v1, dist_v2); bool fwd = dist_v1 < dist_v2; bool proceed = std::min(dist_v1, dist_v2) < 30 && std::abs(dist_v1 - dist_v2) > 10; SignalAnchorInfo result = {false, -1, trailing_Ts}; if (proceed) { int start = 0, end = 0; int base_anchor = 0; if (fwd) { base_anchor = bottom_start + bottom_v1.startLocations[0]; } else { base_anchor = top_v2.endLocations[0]; } const auto stride = read.read_common.model_stride; const auto seq_to_sig_map = dorado::utils::moves_to_map( read.read_common.moves, stride, read.read_common.get_raw_data_samples(), read.read_common.seq.size() + 1); int signal_anchor = seq_to_sig_map[base_anchor]; result = {fwd, signal_anchor, trailing_Ts}; } else { spdlog::debug("{} primer edit distance too high {}", read.read_common.read_id, std::min(dist_v1, dist_v2)); } edlibFreeAlignResult(top_v1); edlibFreeAlignResult(bottom_v1); edlibFreeAlignResult(top_v2); edlibFreeAlignResult(bottom_v2); return result; } // Since the adapter in RNA is still DNA, the basecall quality of the adapter is poor because we // infer with a model trained on RNA data. So finding a match of the adapter sequence in the RNA sequence // doesn't work well. Instead, the raw signal is traversed to find a point // where there's a jump in the median signal value, which is indicative of the // transition from the DNA adapter to the RNA signal. The polyA will start right // at that juncture. This function returns a struct with the strand // direction (which is always reverse for dRNA), the signal anchor and the number of bases // to omit from the tail length estimation due to any adapter effects. SignalAnchorInfo determine_signal_anchor_and_strand_drna( const dorado::SimplexRead& read, dorado::PolyACalculator::ModelType model_type) { static const std::unordered_map<dorado::PolyACalculator::ModelType, int> kOffsetMap = { {dorado::PolyACalculator::ModelType::RNA002, 5000}, {dorado::PolyACalculator::ModelType::RNA004, 1000}}; static const std::unordered_map<dorado::PolyACalculator::ModelType, int> kMaxSignalPosMap = { {dorado::PolyACalculator::ModelType::RNA002, 10000}, {dorado::PolyACalculator::ModelType::RNA004, 5000}}; const int kWindowSize = 250; const int kStride = 50; const int kOffset = kOffsetMap.at(model_type); const int kMaxSignalPos = kMaxSignalPosMap.at(model_type); const float kMinMedianForRNASignal = 0.f; const float kMinMedianDiff = 1.f; int bp = -1; int signal_len = read.read_common.get_raw_data_samples(); auto sig_fp32 = read.read_common.raw_data.to(torch::kFloat); float last_median = 0.f; for (int i = kOffset; i < std::min(signal_len / 2, kMaxSignalPos); i += kStride) { auto slice = sig_fp32.slice(0, std::max(0, i - kWindowSize / 2), std::min(signal_len, i + kWindowSize / 2)); float median = slice.median().item<float>(); if (median > kMinMedianForRNASignal) { float diff = median - last_median; if (diff > kMinMedianDiff) { bp = i; break; } } last_median = median; } spdlog::debug("Approx break point {}", bp); if (bp > 0) { return SignalAnchorInfo{false, bp, 0}; } else { return SignalAnchorInfo{false, -1, 0}; } } } // namespace namespace dorado { void PolyACalculator::worker_thread() { torch::InferenceMode inference_mode_guard; Message message; while (get_input_message(message)) { // If this message isn't a read, just forward it to the sink. if (!std::holds_alternative<SimplexReadPtr>(message)) { send_message_to_sink(std::move(message)); continue; } // If this message isn't a read, we'll get a bad_variant_access exception. auto read = std::get<SimplexReadPtr>(std::move(message)); // Determine the strand direction, approximate base space anchor for the tail, and whether // the final length needs to be adjusted depending on the adapter sequence. auto [fwd, signal_anchor, trailing_Ts] = m_is_rna ? determine_signal_anchor_and_strand_drna(*read, m_model_type) : determine_signal_anchor_and_strand_cdna(*read); if (signal_anchor >= 0) { spdlog::debug("Strand {}; poly A/T signal anchor {}", fwd ? '+' : '-', signal_anchor); auto num_samples_per_base = estimate_samples_per_base(*read, m_is_rna); // Walk through signal auto [signal_start, signal_end] = determine_signal_bounds( signal_anchor, fwd, *read, num_samples_per_base, m_is_rna); int num_bases = std::round(static_cast<float>(signal_end - signal_start) / num_samples_per_base) - trailing_Ts; if (num_bases > 0 && num_bases < kMaxTailLength) { spdlog::debug( "{} PolyA bases {}, signal anchor {} Signal range is {} {}, " "samples/base {} trim {}", read->read_common.read_id, num_bases, signal_anchor, signal_start, signal_end, num_samples_per_base, read->read_common.num_trimmed_samples); // Set tail length property in the read. read->read_common.rna_poly_tail_length = num_bases; // Update debug stats. total_tail_lengths_called += num_bases; ++num_called; if (spdlog::get_level() == spdlog::level::debug) { std::lock_guard<std::mutex> lock(m_mutex); tail_length_counts[num_bases]++; } } else { spdlog::debug( "{} PolyA bases {}, signal anchor {} Signal range is {}, " "samples/base {}, trim {}", read->read_common.read_id, num_bases, signal_anchor, signal_start, signal_end, num_samples_per_base, read->read_common.num_trimmed_samples); num_not_called++; } } else { num_not_called++; } send_message_to_sink(std::move(read)); } } PolyACalculator::PolyACalculator(size_t num_worker_threads, PolyACalculator::ModelType model_type, size_t max_reads) : MessageSink(max_reads), m_num_worker_threads(num_worker_threads), m_is_rna(model_type == ModelType::RNA004 || model_type == ModelType::RNA002), m_model_type(model_type) { start_threads(); } void PolyACalculator::start_threads() { for (size_t i = 0; i < m_num_worker_threads; i++) { m_workers.push_back( std::make_unique<std::thread>(std::thread(&PolyACalculator::worker_thread, this))); } } void PolyACalculator::terminate_impl() { terminate_input_queue(); for (auto& m : m_workers) { if (m->joinable()) { m->join(); } } m_workers.clear(); spdlog::debug("Total called {}, not called {}, avg tail length {}", num_called.load(), num_not_called.load(), num_called.load() > 0 ? total_tail_lengths_called.load() / num_called.load() : 0); // Visualize a distribution of the tail lengths called. static bool done = false; if (!done && spdlog::get_level() == spdlog::level::debug) { int max_val = -1; for (auto [k, v] : tail_length_counts) { max_val = std::max(v, max_val); } int factor = std::max(1, 1 + max_val / 100); for (auto [k, v] : tail_length_counts) { spdlog::debug("{} : {}", k, std::string(v / factor, '*')); } done = true; } } void PolyACalculator::restart() { restart_input_queue(); start_threads(); } stats::NamedStats PolyACalculator::sample_stats() const { stats::NamedStats stats = stats::from_obj(m_work_queue); stats["reads_not_estimated"] = num_not_called.load(); stats["reads_estimated"] = num_called.load(); stats["average_tail_length"] = num_called.load() > 0 ? total_tail_lengths_called.load() / num_called.load() : 0; return stats; } PolyACalculator::ModelType PolyACalculator::get_model_type(const std::string& model_name) { if (model_name.find("rna004") != std::string::npos) { return PolyACalculator::ModelType::RNA004; } else if (model_name.find("rna002") != std::string::npos) { return PolyACalculator::ModelType::RNA002; } else if (model_name.find("dna") != std::string::npos) { return PolyACalculator::ModelType::DNA; } else { throw std::runtime_error("Could not determine model type for " + model_name); } } } // namespace dorado
<template> <div class="home" style="width: 60%; margin-left: 20%"> <img alt="Vue logo" src="../assets/logo.png" /> <!-- <HelloWorld msg="Welcome to Your Vue.js App"/> --> <p>{{ res }}</p> <input v-model="text" /> <button @click="send()">发送</button> </div> </template> <script> // @ is an alias to /src import HelloWorld from "@/components/HelloWorld.vue"; import axios from "axios"; export default { name: "Home", components: { HelloWorld, }, data() { return { text: "请输入...", res: "canny-chat-res", }; }, methods: { send() { let endpoint = "http://url:5000/api/chat"; // 指向您的后端 API 的 URL let body = { messages: [{ role: "user", content: this.text }], // 根据您的需求自定义请求体的内容 }; this.res = "请求中,请稍后..."; let self = this; // axios.defaults.headers.common["Access-Control-Allow-Origin"] = "*"; // axios.defaults.headers.common["Access-Control-Allow-Methods"] = // "GET, POST, OPTIONS"; // axios.defaults.headers.common["Access-Control-Allow-Headers"] = // "Content-Type, Authorization"; // axios.defaults.headers.common["Access-Control-Allow-Credentials"] = // "true"; // axios.defaults.headers.common["Cache-Control"] = "no-cache"; // axios.defaults.headers.common["Pragma"] = "no-cache"; // axios.defaults.headers.common["Expires"] = "0"; // 使用axios库发送请求 axios .post(endpoint, body, { withCredentials: true }) .then((response) => { // 在此处处理来自后端的响应结果 console.log(response.data); self.res = response.data.choices[0].message.content; }) .catch((error) => { // 处理请求错误 console.error("请求错误:", error); self.res = "请求错误"; }); }, }, // methods: { // send() { // let endpoint = "https://api.openai.com/v1/chat/completions"; // let headers = { // "Content-Type": "application/json", // Authorization: // process.env.VUE_APP_APIKEY, // 将YOUR_API_KEY替换为您自己的ChatGPT API密钥 // }; // let body = { // model: "gpt-3.5-turbo", // messages: [{ role: "user", content: this.text }], // // 根据您的需求自定义请求体的内容 // }; // this.res = "请求中,请稍后..." // let self = this; // // 使用axios库发送请求 // axios // .post(endpoint, body, { headers: headers }) // .then((response) => { // // 在此处处理来自ChatGPT API的响应结果 // console.log(response.data); // self.res = response.data.choices[0].message.content; // }) // .catch((error) => { // // 处理请求错误 // console.error("请求错误:", error); // self.res = "请求错误" // }); // }, // }, }; </script>
<template> <div class="login"> <div class="loginidex"> <div> <el-card class="logincard"> <div class="text"> <el-text class="title">登陆</el-text> </div> <el-card class="userinfo"> <el-input v-model="userinfo.name" placeholder="请输入用户名"/> <el-input v-model="userinfo.password" type="password" placeholder="请输入密码" show-password /> </el-card> <div class="login-btn"> <el-button type="primary" plain @click="dologin()" class="btn">登录</el-button> <div class="btn"> <el-button text @click="dialogFormVisible = true"> 忘记密码 </el-button> <el-dialog v-model="dialogFormVisible" title="忘记密码"> <el-form :model="form"> <el-form-item label="用户名" :label-width="formLabelWidth"> <el-input v-model="form.name" autocomplete="off"/> </el-form-item> <el-form-item label="邮箱" :label-width="formLabelWidth"> <el-input v-model="form.name" autocomplete="off"/> </el-form-item> </el-form> <template #footer> <span class="dialog-footer"> <el-button @click="dialogFormVisible = false">取消</el-button> <el-button type="primary" @click="forgotpwd"> 确认 </el-button> </span> </template> </el-dialog> </div> </div> </el-card> </div> </div> </div> </template> <style scoped> .loginidex { display: flex; flex-direction: column; width: 300px; height: 500px; margin-top: 10%; } .login-btn { display: flex; margin-left: 10px; justify-content: space-between; } .btn { margin-top: 20px; align-items: center; } .login { display: flex; flex-direction: column; align-items: center; height: 100%; width: 100%; } .title { font-size: 30px; display: flex; flex-direction: column; align-items: center; margin-top: 30px; } .userinfo{ margin-top: 100px; border: 1px solid var(--el-border-color); } .logincard { height: 400px; border: 2px solid var(--el-border-color); background-image: url(../../public/images/clouds-blue-sky-light-31912398.jpg); } </style> <script lang="ts" setup> import axios from 'axios'; import {reactive, ref} from 'vue' import router from '../router/index.js' import { ElMessage } from 'element-plus' const dialogTableVisible = ref(false) const dialogFormVisible = ref(false) const formLabelWidth = '140px' const forgotpwd = () => { console.log("密码已发送邮箱") } const form = reactive({ name: '', email: '', }) const userinfo = reactive({ name: "", password: "", }) const dologin = () => { axios.post('http://192.168.0.117:8081/login', { username: userinfo.name, password: userinfo.password }).then((res) => { if (res.data.code === 1000) { console.log("登陆成功") localStorage.setItem("loginResult", JSON.stringify(res.data)); router.push({path: '/'}) } else { ElMessage.error('用户名密码错误') console.log(res.data.message) } }).catch(function (error) { console.log("错误信息", error) ElMessage.error('用户名密码错误') }); } </script>
import Foundation // トークンの種類を表す列挙型 enum TokenKind { case punct(String) case number(Int) case eof } // トークンの構造体 struct Token { let kind: TokenKind let start: String.Index let end: String.Index } // トークン化エラーのレポートとプログラムの終了 func error(_ message: String) -> Never { fputs(message + "\n", stderr) exit(1) } // トークンが指定された文字列と一致するかを確認 func equal(_ token: Token, to string: String, in input: String) -> Bool { return input[token.start..<token.end] == string } // 数字のトークンから値を取得 func getNumber(from token: Token) -> Int { if case .number(let value) = token.kind { return value } error("Expected a number") } // 新しいトークンを生成 func newToken(kind: TokenKind, start: String.Index, end: String.Index) -> Token { return Token(kind: kind, start: start, end: end) } // 文字列をトークンに分解 func tokenize(_ input: String) -> [Token] { var tokens = [Token]() var index = input.startIndex func skipWhitespace() { while index < input.endIndex, input[index].isWhitespace { index = input.index(after: index) } } while index < input.endIndex { skipWhitespace() if index == input.endIndex { break } // 数字のトークン if input[index].isNumber { let start = index var value = 0 while index < input.endIndex, let digit = input[index].wholeNumberValue { value = value * 10 + digit index = input.index(after: index) } tokens.append(newToken(kind: .number(value), start: start, end: index)) continue } // 演算子のトークン if "+-".contains(input[index]) { let start = index index = input.index(after: index) tokens.append(newToken(kind: .punct(String(input[start])), start: start, end: index)) continue } error("Invalid token") } tokens.append(newToken(kind: .eof, start: index, end: index)) return tokens } // コマンドライン引数のチェック guard CommandLine.arguments.count == 2 else { error("\(CommandLine.arguments[0]): invalid number of arguments") } // 入力文字列をトークン化 let input = CommandLine.arguments[1] let tokens = tokenize(input) var index = 0 func nextToken() -> Token { defer { index += 1 } return tokens[index] } // アセンブリコードの生成 print(" .globl main") print("main:") // 最初のトークンは数値である必要があります var token = nextToken() print(" mov $\(getNumber(from: token)), %rax") // + または - の後に続く数値を処理 while index < tokens.count - 1 { token = nextToken() switch token.kind { case .punct("+"): let value = getNumber(from: nextToken()) print(" add $\(value), %rax") case .punct("-"): let value = getNumber(from: nextToken()) print(" sub $\(value), %rax") case .eof: break default: error("Unexpected token") } } print(" ret")
import React from 'react' import Box from "@mui/material/Box"; import IconButton from "@mui/material/IconButton"; import Typography from "@mui/material/Typography"; import MenuIcon from "@mui/icons-material/Menu"; import CarRentalIcon from "@mui/icons-material/EventAvailableSharp"; import { Toolbar } from '@mui/material'; const DrawerHeader = ({click, variant, children}) => { return ( <Toolbar disableGutters sx={{ paddingLeft: '16px', paddingRight: '16px'}}> <IconButton size="large" edge="start" color="385f97" aria-label="open drawer" onClick={click} > <MenuIcon style={{ color: '#385f97' }}/> </IconButton> <Box sx={{ display: variant ==='relative' ? { xs: "none", md: "flex" }: 'flex', mr: 1 }}> <CarRentalIcon fontSize="large" style={{ color: '#385f97' }}/> <Typography variant="h6" noWrap component="a" href="/" sx={{ ml: 1, mr: 2, fontFamily: "monospace", fontWeight: 700, letterSpacing: ".1rem", textDecoration: "none", color: "#385f97" }} > Lesure </Typography> </Box> {children} </Toolbar> ) } export default DrawerHeader
const { model, Schema } = require("mongoose"); const { STATUS_ORDER } = require("../constants/status"); const DOCUMENT_NAME = "Order"; const COLLECTION_NAME = "Orders"; const orderSchema = new Schema( { order_user: { type: Schema.Types.ObjectId, ref: "User", required: true }, order_checkout: { type: Object, default: {} }, order_note: String, /** * order_checkout :{ * totalPrice, * totalApplyDiscount * feeShip * } */ order_shop: { type: Schema.Types.ObjectId, ref: "Shop", required: true }, order_shipping: { type: Object, default: {} }, order_payment: { type: Object, default: {} }, // kiểu thanh toán order_products: { type: [ { price: { type: Number, required: true }, product: { type: Schema.Types.ObjectId, ref: "Product", required: true, }, quantity: { type: Number, required: true }, }, ], required: true, }, //shop_order_ids_new order_trackingNumber: { type: String, default: "#00001" }, order_status: { type: String, enum: [ STATUS_ORDER.PENDING, STATUS_ORDER.CONFIRMED, STATUS_ORDER.SHIPPED, STATUS_ORDER.CANCELLED, STATUS_ORDER.DELIVERED, ], default: STATUS_ORDER.PENDING, }, order_isPaid: { type: Boolean, defautl: false }, order_paidAt: Date, order_isDelivered: { type: Boolean, default: false, }, order_deliveredAt: Date, }, { collection: COLLECTION_NAME, timestamps: true, } ); module.exports = model(DOCUMENT_NAME, orderSchema);
import cx from 'classnames'; import { useFormik } from 'formik'; import Head from 'next/head'; import { useRouter } from 'next/router'; import { useEffect, useRef, useState } from 'react'; import { FaDownload, FaPlus } from 'react-icons/fa'; import { AccessControl } from '../app-state/accessControl'; import API_PATHS from '../constants/apiPaths'; import { BACKEND_ADMIN_CONTROL } from '../constants/policies'; import useCourseSessionBulkUpload from '../hooks/useCourseSessionBulkUpload'; import { centralHttp } from '../http'; import UploadApi from '../http/upload.api'; import useTranslation from '../i18n/useTranslation'; import { AdminLayout } from '../layouts/admin.layout'; import { CourseCategoryKey, courseValidationSchema, getCourseOutlineInitialObj, ICourse, } from '../models/course'; import { Language } from '../models/language'; import Button from '../ui-kit/Button'; import { ContentDisclosure } from '../ui-kit/ContentDisclosure'; import ErrorMessages from '../ui-kit/ErrorMessage'; import FileUploadButton from '../ui-kit/FileUploadButton'; import SuccessMessage from '../ui-kit/SuccessMessage'; import { SystemError } from '../ui-kit/SystemError'; import { getErrorMessages } from '../utils/error'; import CourseForm from './CourseForm'; import CourseOutlineForm from './CourseOutlineForm'; import { setCourseOutlineForm } from './utils'; const CourseDetailPage = () => { const api = UploadApi; const { t } = useTranslation(); const router = useRouter(); const { id } = router.query; const [errors, setErrors] = useState([]); const [openTab, setOpenTab] = useState(1); const [categoryKey, setCategoryKey] = useState(''); const [course, setCourse] = useState<ICourse<Language>>(null); const [successTitle, setSuccessTitle] = useState(''); const [isUploadingFile, setIsUploadingFile] = useState(false); const { downloadTemplate, processFile } = useCourseSessionBulkUpload(); const scrollRef = useRef(null); const executeScroll = () => scrollRef.current.scrollIntoView(); const [errorOnLoad, setErrorOnLoad] = useState<Error | undefined>(); const getCourse = async (courseId: string) => { setErrorOnLoad(undefined); const { data } = await centralHttp.get( API_PATHS.ADMIN_COURSE_DETAIL.replace(':id', courseId), ); setCourse(data.data); setCategoryKey(data.data.category.key); await formik.setValues(data.data); data.data.courseOutlines.forEach((co, index) => { const subCategoryKey = co.category?.key || ''; setCourseOutlineForm(formik, index, co, subCategoryKey); }); }; useEffect(() => { if (id) { getCourse(id as string).catch((err) => { setErrorOnLoad(err); }); } }, [id]); const handleSubmit = async (data: ICourse<Language>) => { if ( categoryKey === CourseCategoryKey.LEARNING_EVENT && data.courseOutlines.find((co) => co.courseSessions.length < 1) ) { setErrors(['Please select sessions for Learning Event type course.']); executeScroll(); return; } const payload = { ...data, courseOutlines: data.courseOutlines.map((co) => ({ ...co, mediaPlaylist: co.mediaPlaylist.map((mp) => mp.id), })), }; try { if (formik.values.imageFile) { const key = await api.uploadCourseImageToS3(formik.values.imageFile); formik.setFieldValue('imageKey', key); payload.imageKey = key; } if ( formik.values.courseOutlines.find( (item) => item.outlineType === 'scorm', ) ) { let files = []; formik.values.courseOutlines .filter((o) => o.outlineType === 'scorm') .forEach((outline) => { files = [...files, ...outline.learningContentFiles]; }); const result = await api.getSCORMPresign(files.map((f) => f.name)); const urls = result.data.reduce( (obj, cur) => ({ ...obj, [cur.key]: cur.url }), {}, ); const promises = files.map((file) => { return api.uploadFileToS3(urls[file.name], file); }); await Promise.all(promises); } setErrors([]); setSuccessTitle(''); await centralHttp.put( API_PATHS.ADMIN_COURSE_DETAIL.replace(':id', id as string), payload, ); formik.setFieldValue('courseOutlines', []); await getCourse(id as string); setSuccessTitle('Updated successfully!'); } catch (err) { const errors = getErrorMessages(err); setErrors(errors); } finally { executeScroll(); } }; const handleError = (error) => { const msgs = getErrorMessages(error); setErrors(msgs); }; const formik = useFormik<ICourse<Language>>({ initialValues: { id: '', title: course?.title || { nameEn: '', nameTh: '' }, tagLine: course?.tagLine || { nameEn: '', nameTh: '' }, categoryId: '', durationMinutes: 0, durationHours: 0, durationDays: 0, durationWeeks: 0, durationMonths: 0, availableLanguage: '', description: { nameEn: '', nameTh: '' }, learningObjective: { nameEn: '', nameTh: '' }, courseTarget: { nameEn: '', nameTh: '' }, tagIds: [], materialIds: [], topicIds: [], courseOutlines: [], status: '', isPublic: true, imageFile: null, imageKey: '', }, validationSchema: courseValidationSchema, onSubmit: handleSubmit, }); const onAddCourseOutline = () => { formik.setFieldValue('courseOutlines', [ ...formik.values.courseOutlines, getCourseOutlineInitialObj(), ]); }; const onRemoveCourseOutline = (i: number) => { if (formik.values.courseOutlines.length > 1) { const arr = [...formik.values.courseOutlines]; arr.splice(i, 1); formik.setFieldValue('courseOutlines', arr); } }; if (id && errorOnLoad) { return ( <AdminLayout> <Head> <title>{t('adminCourseDetailPage.title')}</title> </Head> <SystemError error={errorOnLoad} resetError={() => getCourse(id as string).catch(setErrorOnLoad)} /> </AdminLayout> ); } if (!formik?.values?.id) { return null; } // eslint-disable-next-line @typescript-eslint/no-explicit-any const handleFileChange = async (e: any, files: FileList) => { try { setErrors([]); setSuccessTitle(''); setIsUploadingFile(true); const uploadedCourseSessions = await processFile(e, files); for await (const ucs of uploadedCourseSessions) { const formikCourseOutlines = formik.values.courseOutlines; const coIndex = formikCourseOutlines.findIndex( (co) => co.id === ucs.courseOutlineId, ); if (coIndex === -1) { throw `Invalid Course Outline Id: ${ucs.courseOutlineId}`; } await formik.setFieldValue( `courseOutlines[${coIndex}].courseSessions`, [ ...formikCourseOutlines[coIndex].courseSessions, ...uploadedCourseSessions.filter( (u) => u.courseOutlineId === formikCourseOutlines[coIndex].id, ), ], ); } setSuccessTitle('Uploaded successfully!'); } catch (err) { handleError(err); } finally { e.target.value = null; executeScroll(); setIsUploadingFile(false); } }; return ( <AccessControl policyNames={[ BACKEND_ADMIN_CONTROL.ACCESS_ADMIN_PORTAL, BACKEND_ADMIN_CONTROL.ACCESS_COURSE_MANAGEMENT, ]} > <AdminLayout> <Head> <title>{t('adminCourseDetailPage.title')}</title> </Head> <div className="mx-auto mt-4 flex w-full flex-1 flex-col justify-start text-center" ref={scrollRef} > <div className="mb-8"> <h4 className="text-hero-desktop"> {t('adminCourseDetailPage.title')} </h4> </div> <ErrorMessages messages={errors} onClearAction={() => setErrors([])} /> <SuccessMessage title={successTitle} onClearAction={() => setSuccessTitle('')} /> <div className="mx-auto w-278"> <ul className="mb-0 flex list-none flex-row flex-wrap pt-3 pb-4" role="tablist" > <li className="-mb-px mr-2 flex-auto text-center"> <a className={cx( 'block rounded px-5 py-3 text-caption font-bold uppercase leading-normal shadow-lg', openTab === 1 ? ' bg-brand-secondary text-white' : ' bg-white text-brand-secondary', )} onClick={(e) => { e.preventDefault(); setOpenTab(1); }} data-toggle="tab" role="tablist" > Course Info </a> </li> <li className="-mb-px mr-2 flex-auto text-center"> <a className={cx( 'block rounded px-5 py-3 text-caption font-bold uppercase leading-normal shadow-lg', openTab === 2 && formik.values.categoryId ? ' bg-brand-secondary text-white' : ' bg-white text-brand-secondary', !formik.values.categoryId ? 'cursor-not-allowed bg-gray-600 text-white' : '', )} onClick={(e) => { if (!formik.values.categoryId) { return; } e.preventDefault(); setOpenTab(2); }} data-toggle="tab" role="tablist" > Course Outlines </a> </li> </ul> <div className="relative mb-6 flex w-full min-w-0 flex-col break-words rounded shadow-lg"> {openTab === 2 && formik.values?.courseOutlines[0]?.id && categoryKey === CourseCategoryKey.LEARNING_EVENT ? ( <div className="mx-3 mt-4 flex items-end justify-end"> <div className="mx-1"> <FileUploadButton variant="primary" disabled={isUploadingFile} btnText="Bulk upload sessions" onChange={(e) => handleFileChange(e, e.target.files)} accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" /> </div> <div className="mx-1"> <Button size="medium" variant="primary" type="button" iconLeft={ <FaDownload className="text-grey-400 mr-2 h-5 w-5" aria-hidden="true" /> } onClick={() => downloadTemplate( formik.values.courseOutlines.map((co) => ({ ...co, course: { title: formik.values.title, } as ICourse<Language>, })), ) } > Download sessions template </Button> </div> </div> ) : null} <div className="flex-auto px-4 py-5"> <form onSubmit={formik.handleSubmit} autoComplete="off"> <div className="tab-content tab-space mb-6"> <div className={openTab === 1 ? 'block' : 'hidden'} id="link1" > <CourseForm formik={formik} courseMain={course} setCategoryKey={setCategoryKey} /> </div> <div className={cx('mb-6', openTab === 2 ? 'block' : 'hidden')} id="link2" > {formik.values.courseOutlines.map((co, index) => ( <ContentDisclosure key={`outline-form-${index}`} title={ co.part && co.title?.nameEn ? `${co.part}: ${co.title.nameEn}` : `${`Outline ${index + 1}`}` } defaultOpen={co.id === undefined} > <CourseOutlineForm key={`${co.id}`} formik={formik} index={index} courseOutlineMain={course.courseOutlines.find( (cco) => cco.id === co.id, )} categoryKey={categoryKey} onRemoveCourseOutline={onRemoveCourseOutline} /> </ContentDisclosure> ))} </div> {openTab === 2 ? ( <div className="flex w-full flex-row items-end justify-end"> <div className="w-1/3 text-right"> <Button size="medium" variant="secondary" type="button" iconLeft={ <FaPlus className="text-grey-400 mr-2 h-5 w-5" aria-hidden="true" /> } onClick={onAddCourseOutline} > Add another course outline </Button> </div> </div> ) : null} </div> <Button size="medium" variant="primary" type="submit" disabled={!formik.isValid || formik.isSubmitting} > Save course </Button> </form> </div> </div> </div> </div> </AdminLayout> </AccessControl> ); }; export default CourseDetailPage;
#include "main.h" /** * _strncat - concatenates n bytes from a string to another * @dest: destination string * @src: source string * @n: number of bytes of str to concatenate * * Return: a pointer to the resulting string dest */ char *_strncat(char *dest, char *src, int n) { int c, j; c = 0; j = 0; while (dest[c] != '\0') c++; while (src[j] != '\0' && j < n) { dest[c] = src[j]; c++; j++; } dest[c] = '\0'; return (dest); }
// Copyright 2023 The Cross-Media Measurement 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. package org.wfanet.measurement.duchy.daemon.mill.liquidlegionsv2.crypto import com.google.common.truth.Truth.assertThat import com.google.protobuf.ByteString import java.nio.file.Paths import kotlin.test.assertEquals import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.anysketch.SketchKt import org.wfanet.anysketch.crypto.CombineElGamalPublicKeysResponse import org.wfanet.anysketch.crypto.EncryptSketchRequest.DestroyedRegisterStrategy.FLAGGED_KEY import org.wfanet.anysketch.crypto.EncryptSketchResponse import org.wfanet.anysketch.crypto.SketchEncrypterAdapter import org.wfanet.anysketch.crypto.combineElGamalPublicKeysRequest import org.wfanet.anysketch.crypto.encryptSketchRequest import org.wfanet.anysketch.sketch import org.wfanet.estimation.Estimators import org.wfanet.measurement.common.loadLibrary import org.wfanet.measurement.duchy.daemon.utils.toAnySketchElGamalPublicKey import org.wfanet.measurement.duchy.daemon.utils.toCmmsElGamalPublicKey import org.wfanet.measurement.internal.duchy.protocol.CompleteReachOnlyExecutionPhaseAtAggregatorResponse import org.wfanet.measurement.internal.duchy.protocol.CompleteReachOnlyExecutionPhaseResponse import org.wfanet.measurement.internal.duchy.protocol.CompleteReachOnlyInitializationPhaseResponse import org.wfanet.measurement.internal.duchy.protocol.CompleteReachOnlySetupPhaseResponse import org.wfanet.measurement.internal.duchy.protocol.completeReachOnlyExecutionPhaseAtAggregatorRequest import org.wfanet.measurement.internal.duchy.protocol.completeReachOnlyExecutionPhaseRequest import org.wfanet.measurement.internal.duchy.protocol.completeReachOnlyInitializationPhaseRequest import org.wfanet.measurement.internal.duchy.protocol.completeReachOnlySetupPhaseRequest import org.wfanet.measurement.internal.duchy.protocol.liquidLegionsSketchParameters import org.wfanet.measurement.internal.duchy.protocol.reachonlyliquidlegionsv2.ReachOnlyLiquidLegionsV2EncryptionUtility @RunWith(JUnit4::class) class ReachOnlyLiquidLegionsV2EncryptionUtilityTest { // Helper function to go through the entire Liquid Legions V2 protocol using the input data. // The final relative_frequency_distribution map are returned. private fun goThroughEntireMpcProtocol( encrypted_sketch: ByteString ): CompleteReachOnlyExecutionPhaseAtAggregatorResponse { // Setup phase at Duchy 1 (NON_AGGREGATOR). Duchy 1 receives all the sketches. val completeReachOnlySetupPhaseRequest1 = completeReachOnlySetupPhaseRequest { combinedRegisterVector = encrypted_sketch curveId = CURVE_ID compositeElGamalPublicKey = CLIENT_EL_GAMAL_KEYS parallelism = PARALLELISM } val completeReachOnlySetupPhaseResponse1 = CompleteReachOnlySetupPhaseResponse.parseFrom( ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlySetupPhase( completeReachOnlySetupPhaseRequest1.toByteArray() ) ) // Setup phase at Duchy 2 (NON_AGGREGATOR). Duchy 2 does not receive any sketche. val completeReachOnlySetupPhaseRequest2 = completeReachOnlySetupPhaseRequest { curveId = CURVE_ID compositeElGamalPublicKey = CLIENT_EL_GAMAL_KEYS parallelism = PARALLELISM } val completeReachOnlySetupPhaseResponse2 = CompleteReachOnlySetupPhaseResponse.parseFrom( ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlySetupPhase( completeReachOnlySetupPhaseRequest2.toByteArray() ) ) // Setup phase at Duchy 3 (AGGREGATOR). Aggregator receives the combined register vector and // the concatenated excessive noise ciphertexts. val completeReachOnlySetupPhaseRequest3 = completeReachOnlySetupPhaseRequest { combinedRegisterVector = completeReachOnlySetupPhaseResponse1.combinedRegisterVector.concat( completeReachOnlySetupPhaseResponse2.combinedRegisterVector ) curveId = CURVE_ID compositeElGamalPublicKey = CLIENT_EL_GAMAL_KEYS serializedExcessiveNoiseCiphertext = completeReachOnlySetupPhaseResponse1.serializedExcessiveNoiseCiphertext.concat( completeReachOnlySetupPhaseResponse2.serializedExcessiveNoiseCiphertext ) parallelism = PARALLELISM } val completeReachOnlySetupPhaseResponse3 = CompleteReachOnlySetupPhaseResponse.parseFrom( ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlySetupPhase( completeReachOnlySetupPhaseRequest3.toByteArray() ) ) // Execution phase at duchy 1 (non-aggregator). val completeReachOnlyExecutionPhaseRequest1 = completeReachOnlyExecutionPhaseRequest { combinedRegisterVector = completeReachOnlySetupPhaseResponse3.combinedRegisterVector localElGamalKeyPair = DUCHY_1_EL_GAMAL_KEYS curveId = CURVE_ID serializedExcessiveNoiseCiphertext = completeReachOnlySetupPhaseResponse3.serializedExcessiveNoiseCiphertext parallelism = PARALLELISM } val completeReachOnlyExecutionPhaseResponse1 = CompleteReachOnlyExecutionPhaseResponse.parseFrom( ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlyExecutionPhase( completeReachOnlyExecutionPhaseRequest1.toByteArray() ) ) // Execution phase at duchy 2 (non-aggregator). val completeReachOnlyExecutionPhaseRequest2 = completeReachOnlyExecutionPhaseRequest { combinedRegisterVector = completeReachOnlyExecutionPhaseResponse1.combinedRegisterVector localElGamalKeyPair = DUCHY_2_EL_GAMAL_KEYS curveId = CURVE_ID serializedExcessiveNoiseCiphertext = completeReachOnlyExecutionPhaseResponse1.serializedExcessiveNoiseCiphertext parallelism = PARALLELISM } val completeReachOnlyExecutionPhaseResponse2 = CompleteReachOnlyExecutionPhaseResponse.parseFrom( ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlyExecutionPhase( completeReachOnlyExecutionPhaseRequest2.toByteArray() ) ) // Execution phase at duchy 3 (aggregator). val completeReachOnlyExecutionPhaseAtAggregatorRequest = completeReachOnlyExecutionPhaseAtAggregatorRequest { combinedRegisterVector = completeReachOnlyExecutionPhaseResponse2.combinedRegisterVector localElGamalKeyPair = DUCHY_3_EL_GAMAL_KEYS curveId = CURVE_ID serializedExcessiveNoiseCiphertext = completeReachOnlyExecutionPhaseResponse2.serializedExcessiveNoiseCiphertext parallelism = PARALLELISM sketchParameters = liquidLegionsSketchParameters { decayRate = DECAY_RATE size = LIQUID_LEGIONS_SIZE } vidSamplingIntervalWidth = VID_SAMPLING_INTERVAL_WIDTH parallelism = PARALLELISM } return CompleteReachOnlyExecutionPhaseAtAggregatorResponse.parseFrom( ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlyExecutionPhaseAtAggregator( completeReachOnlyExecutionPhaseAtAggregatorRequest.toByteArray() ) ) } @Test fun endToEnd_basicBehavior() { val rawSketch = sketch { registers += SketchKt.register { index = 1L } registers += SketchKt.register { index = 2L } registers += SketchKt.register { index = 2L } registers += SketchKt.register { index = 3L } registers += SketchKt.register { index = 4L } } val request = encryptSketchRequest { sketch = rawSketch curveId = CURVE_ID maximumValue = MAX_COUNTER_VALUE elGamalKeys = CLIENT_EL_GAMAL_KEYS.toAnySketchElGamalPublicKey() destroyedRegisterStrategy = FLAGGED_KEY } val response = EncryptSketchResponse.parseFrom(SketchEncrypterAdapter.EncryptSketch(request.toByteArray())) val encryptedSketch = response.encryptedSketch val result = goThroughEntireMpcProtocol(encryptedSketch).reach val expectedResult = Estimators.EstimateCardinalityLiquidLegions( DECAY_RATE, LIQUID_LEGIONS_SIZE, 4, VID_SAMPLING_INTERVAL_WIDTH.toDouble() ) assertEquals(expectedResult, result) } @Test fun `completeReachOnlySetupPhase fails with invalid request message`() { val exception = assertFailsWith(RuntimeException::class) { ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlySetupPhase( "something not a proto".toByteArray() ) } assertThat(exception).hasMessageThat().contains("Failed to parse") } @Test fun `completeReachOnlyExecutionPhase fails with invalid request message`() { val exception = assertFailsWith(RuntimeException::class) { ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlyExecutionPhase( "something not a proto".toByteArray() ) } assertThat(exception).hasMessageThat().contains("Failed to parse") } @Test fun `completeReachOnlyExecutionPhaseAtAggregator fails with invalid request message`() { val exception = assertFailsWith(RuntimeException::class) { ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlyExecutionPhaseAtAggregator( "something not a proto".toByteArray() ) } assertThat(exception).hasMessageThat().contains("Failed to parse") } companion object { init { loadLibrary( "reach_only_liquid_legions_v2_encryption_utility", Paths.get("wfa_measurement_system/src/main/swig/protocol/reachonlyliquidlegionsv2") ) loadLibrary( "sketch_encrypter_adapter", Paths.get("any_sketch_java/src/main/java/org/wfanet/anysketch/crypto") ) loadLibrary("estimators", Paths.get("any_sketch_java/src/main/java/org/wfanet/estimation")) } private const val DECAY_RATE = 12.0 private const val LIQUID_LEGIONS_SIZE = 100_000L private const val MAXIMUM_FREQUENCY = 10 private const val VID_SAMPLING_INTERVAL_WIDTH = 0.5f private const val CURVE_ID = 415L // NID_X9_62_prime256v1 private const val PARALLELISM = 3 private const val MAX_COUNTER_VALUE = 10 private val COMPLETE_INITIALIZATION_REQUEST = completeReachOnlyInitializationPhaseRequest { curveId = CURVE_ID } private val DUCHY_1_EL_GAMAL_KEYS = CompleteReachOnlyInitializationPhaseResponse.parseFrom( ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlyInitializationPhase( COMPLETE_INITIALIZATION_REQUEST.toByteArray() ) ) .elGamalKeyPair private val DUCHY_2_EL_GAMAL_KEYS = CompleteReachOnlyInitializationPhaseResponse.parseFrom( ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlyInitializationPhase( COMPLETE_INITIALIZATION_REQUEST.toByteArray() ) ) .elGamalKeyPair private val DUCHY_3_EL_GAMAL_KEYS = CompleteReachOnlyInitializationPhaseResponse.parseFrom( ReachOnlyLiquidLegionsV2EncryptionUtility.completeReachOnlyInitializationPhase( COMPLETE_INITIALIZATION_REQUEST.toByteArray() ) ) .elGamalKeyPair private val CLIENT_EL_GAMAL_KEYS = CombineElGamalPublicKeysResponse.parseFrom( SketchEncrypterAdapter.CombineElGamalPublicKeys( combineElGamalPublicKeysRequest { curveId = CURVE_ID elGamalKeys += DUCHY_1_EL_GAMAL_KEYS.publicKey.toAnySketchElGamalPublicKey() elGamalKeys += DUCHY_2_EL_GAMAL_KEYS.publicKey.toAnySketchElGamalPublicKey() elGamalKeys += DUCHY_3_EL_GAMAL_KEYS.publicKey.toAnySketchElGamalPublicKey() } .toByteArray() ) ) .elGamalKeys .toCmmsElGamalPublicKey() private val DUCHY_2_3_COMBINED_EL_GAMAL_KEYS = CombineElGamalPublicKeysResponse.parseFrom( SketchEncrypterAdapter.CombineElGamalPublicKeys( combineElGamalPublicKeysRequest { curveId = CURVE_ID elGamalKeys += DUCHY_2_EL_GAMAL_KEYS.publicKey.toAnySketchElGamalPublicKey() elGamalKeys += DUCHY_3_EL_GAMAL_KEYS.publicKey.toAnySketchElGamalPublicKey() } .toByteArray() ) ) .elGamalKeys .toCmmsElGamalPublicKey() } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Personal Portfolio</title> <script src="https://kit.fontawesome.com/81f1467af6.js" crossorigin="anonymous" ></script> <link rel="stylesheet" href="styles/style.css" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Work+Sans&display=swap" rel="stylesheet" /> </head> <body> <header class="header"> <h1 class="banner-title">All Thinks Are Possible If You believe</h1> <p class="banner-description"> There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words </p> <button class="btn-primary">Contact Us</button> </header> <!-- My Failure section --> <section class="my-failure"> <div class="failure-content"> <img class="person" src="images/person.png" alt="" /> <div class="failure-items"> <h2 class="failure-title">My failures of previous year</h2> <p class="failure-description"> Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock. </p> <ul> <li> <i class="fa-solid fa-check" style="color: rgb(6, 255, 85)"></i> Contrary to popular belief, is not simply. </li> <li> <i class="fa-solid fa-check" style="color: rgb(6, 255, 85)"></i> Contrary to popular belief. </li> <li> <i class="fa-solid fa-check" style="color: rgb(6, 255, 85)"></i> Contrary to popular , is not simply. </li> <li> <i class="fa-solid fa-check" style="color: rgb(6, 255, 85)"></i> Contrary to popular belief, is not simply. </li> <li> <i class="fa-solid fa-check" style="color: rgb(6, 255, 85)"></i> Contrary to popular simply. </li> </ul> </div> </div> </section> <!-- My Plan section --> <section class="my-plan"> <h2 class="my-plan-title">My Plans</h2> <div class="my-plan-info-container"> <div class="my-plan-content"> <img src="images/icons/web.png" alt="" /> <h3 class="my-plan-skill">Web Development</h3> <p class="my-plan-description">I want to start</p> </div> <div class="my-plan-content"> <img src="images/icons/js.png" alt="" /> <h3 class="my-plan-skill">Javascript</h3> <p class="my-plan-description">I want to learn</p> </div> <div class="my-plan-content"> <img src="images/icons/smoke.png" alt="" /> <h3 class="my-plan-skill">Smoking Habit</h3> <p class="my-plan-description">I want to end</p> </div> <div class="my-plan-content"> <img src="images/icons/ecom.png" alt="" /> <h3 class="my-plan-skill">ecommerce</h3> <p class="my-plan-description">I want to develop</p> </div> </div> </section> <!-- My Recent Work --> <section class="my-recent-work"> <div class="my-recent-work-container"> <div class="recent-work-info"> <h2 class="recent-work-title">MY RECENT WORKS</h2> <p class="recent-work-description"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </div> <div class="recent-work-sample"> <div class="design"> <img class="work-image" src="work images/bg-banner.jpg" alt="" /> <img class="work-image" src="work images/port02.jpg" alt="" /> <img class="work-image" src="work images/port03.jpg" alt="" /> <img class="work-image" src="work images/port04.jpg" alt="" /> <img class="work-image" src="work images/port05.jpg" alt="" /> <img class="work-image" src="work images/port06.jpg" alt="" /> </div> </div> </section> <!-- Call Now section--> <section class="call-now"> <div class="call-now-container"> <h2 class="section-title">Always keep a positive mindset</h2> <button class="btn-primary-2">Call Now</button> </div> </section> <!-- footer section --> <footer class="footer"> <div class="future"> <h3 class="future-title">Future</h3> <p class="future-description">There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words</p> <p class="email-info">Email : [email protected]</p> <p class="email-info">+80 4572345347</p> <div class="footer-img"> <img src="images/icons/fb.png" alt="facebook"> <img src="images/icons/twitter.png" alt="twitter"> <img src="images/icons/youtube.png" alt="youtube"> </div> </div> <div class="subscribe"> <h3 class="subscribe-title">Subscribe</h3> <input type="Email" id="email" placeholder="Enter Your Email"> <button class="btn-third">Subscribe</button> </div> </footer> </body> </html>
from pathlib import Path from typing import List, Optional from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_core.documents import Document from logger import get_logger from models.databases.supabase.supabase import SupabaseDB from models.settings import get_supabase_db from modules.brain.service.brain_vector_service import BrainVectorService from packages.files.file import compute_sha1_from_content from pydantic import BaseModel logger = get_logger(__name__) class File(BaseModel): file_name: str tmp_file_path: Path bytes_content: bytes file_size: int file_extension: str chunk_size: int = 400 chunk_overlap: int = 100 documents: List[Document] = [] file_sha1: Optional[str] = None vectors_ids: Optional[list] = [] def __init__(self, **data): super().__init__(**data) data["file_sha1"] = compute_sha1_from_content(data["bytes_content"]) @property def supabase_db(self) -> SupabaseDB: return get_supabase_db() def compute_documents(self, loader_class): """ Compute the documents from the file Args: loader_class (class): The class of the loader to use to load the file """ logger.info(f"Computing documents from file {self.file_name}") loader = loader_class(self.tmp_file_path) documents = loader.load() text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder( chunk_size=self.chunk_size, chunk_overlap=self.chunk_overlap ) self.documents = text_splitter.split_documents(documents) def set_file_vectors_ids(self): """ Set the vectors_ids property with the ids of the vectors that are associated with the file in the vectors table """ self.vectors_ids = self.supabase_db.get_vectors_by_file_sha1( self.file_sha1 ).data def file_already_exists(self): """ Check if file already exists in vectors table """ self.set_file_vectors_ids() # if the file does not exist in vectors then no need to go check in brains_vectors if len(self.vectors_ids) == 0: # pyright: ignore reportPrivateUsage=none return False return True def file_already_exists_in_brain(self, brain_id): """ Check if file already exists in a brain Args: brain_id (str): Brain id """ response = self.supabase_db.get_brain_vectors_by_brain_id_and_file_sha1( brain_id, self.file_sha1 # type: ignore ) if len(response.data) == 0: return False return True def file_is_empty(self): """ Check if file is empty by checking if the file pointer is at the beginning of the file """ return self.file_size < 1 # pyright: ignore reportPrivateUsage=none def link_file_to_brain(self, brain_id): self.set_file_vectors_ids() if self.vectors_ids is None: return brain_vector_service = BrainVectorService(brain_id) for vector_id in self.vectors_ids: # pyright: ignore reportPrivateUsage=none brain_vector_service.create_brain_vector(vector_id["id"], self.file_sha1)
<?php namespace Drupal\Tests\test_helpers_example\Kernel; use Drupal\Core\Datetime\Entity\DateFormat; use Drupal\node\Entity\Node; use Drupal\node\Entity\NodeType; use Drupal\Tests\field\Kernel\FieldKernelTestBase; use Drupal\test_helpers_example\Controller\TestHelpersExampleController; use Drupal\user\Entity\User; /** * @coversDefaultClass \Drupal\test_helpers_example\Controller\TestHelpersExampleController * @group test_helpers_example */ class TestHelpersExampleControllerKernelClassicTest extends FieldKernelTestBase { /** * {@inheritdoc} */ protected static $modules = ['node', 'user', 'test_helpers_example']; /** * {@inheritdoc} */ protected function setUp(): void { parent::setUp(); $this->installEntitySchema('node'); $this->installEntitySchema('user'); } /** * Tests articlesList() function. */ public function testArticlesList() { \Drupal::service('config.factory')->getEditable('test_helpers_example.settings') ->set('articles_to_display', 1)->save(); DateFormat::load('medium')->setPattern('d.m.Y')->save(); $user1 = User::create(['name' => 'Alice']); $user1->save(); NodeType::create(['type' => 'article'])->save(); // Putting coding standards ignore flag to suppress warnings until the // https://www.drupal.org/project/coder/issues/3185082 is fixed. // @codingStandardsIgnoreStart Node::create(['type' => 'article', 'title' => 'A1', 'status' => 1, 'uid' => $user1->id(), 'created' => 1672574400])->save(); Node::create(['type' => 'article', 'title' => 'A2', 'status' => 1, 'uid' => $user1->id(), 'created' => 1672660800])->save(); Node::create(['type' => 'page', 'title' => 'P1', 'status' => 1, 'uid' => $user1->id(), 'created' => 1672747200])->save(); Node::create(['type' => 'article', 'title' => 'A3', 'status' => 0, 'uid' => $user1->id(), 'created' => 1672833600])->save(); // @codingStandardsIgnoreEnd $controller = new TestHelpersExampleController( $this->container->get('config.factory'), $this->container->get('entity_type.manager'), $this->container->get('date.formatter'), ); $result = $controller->articlesList(); $this->assertCount(1, $result['#items']); $this->assertEquals('A2 (02.01.2023 by Alice)', $result['#items'][0]->getText()); $this->assertContains('node_list:article', $result['#cache']['tags']); } }
@extends('layouts.app') @section('content') <div class="container register-container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header text-center px-4 py-3"> <h5 class="mb-0">Register your account and join BoolBnB</h5> </div> <div class="card-body p-5"> @include('partials.errors') <form method="POST" action="{{ route('register') }}"> @csrf {{-- Name --}} <div class="form-group row mb-4"> <label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label> <div class="col-md-6"> <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}" autocomplete="name" autofocus maxlength="25" minlength="3" placeholder="Type your name"> <!-- <small class="text-muted">Add your name min: 3 | max: 25 characters</small> --> @error('name') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> {{-- Surname --}} <div class="form-group row mb-4"> <label for="surname" class="col-md-4 col-form-label text-md-right">{{ __('Surname') }}</label> <div class="col-md-6"> <input id="surname" type="text" class="form-control @error('surname') is-invalid @enderror" name="surname" value="{{ old('surname') }}" autocomplete="surname" autofocus maxlength="25" minlength="3" placeholder="Type your surname"> <!-- <small class="text-muted">Add your surname min: 3 | max: 25 characters</small> --> @error('surname') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> {{-- Date of birth --}} <div class="form-group row mb-4"> <label for="date_of_birth" class="col-md-4 col-form-label text-md-right">{{ __('Date of birth') }}</label> <div class="col-md-6"> <input id="date_of_birth" type="date" class="form-control @error('date_of_birth') is-invalid @enderror" name="date_of_birth" value="{{ old('date_of_birth') }}" autocomplete="date_of_birth" autofocus min="1900-01-01" max="{{ now()->subYears(18)->toDateString('d/m/Y') }}"> <small class="text-muted">Choose your date of birth</small> @error('date_of_birth') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> @error('date_of_birth') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> {{-- Email --}} <div class="form-group row mb-4"> <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address *') }}</label> <div class="col-md-6"> <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" placeholder="Type your e-mail address"> <!-- <small class="text-muted">Add your email address</small> --> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> {{-- Password --}} <div class="form-group row mb-4"> <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password *') }}</label> <div class="col-md-6"> <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="new-password" minlength="8" placeholder="*******"> <small class="text-muted">Password must be min 8 characters</small> @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row mb-4"> <label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password *') }}</label> <div class="col-md-6"> <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password" minlength="8" placeholder="*******"> <small class="text-muted">Please type again your password</small> </div> </div> <div class="form-group row mb-0"> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn text-white w-100"> REGISTER </button> </div> </div> <small class="text-muted fst-italic fw-bold">Fields marked with * are required</small> </form> </div> </div> </div> </div> </div> @endsection
import kotlin.math.abs import kotlin.math.min import kotlin.math.sqrt import kotlin.random.Random typealias Point = Vector typealias Color = Vector data class Vector(var x: Double, var y: Double, var z: Double) { constructor() : this(0.0, 0.0, 0.0) operator fun unaryMinus() = Vector(-x, -y, -z) operator fun plus(vector: Vector) = Vector(x + vector.x, y + vector.y, z + vector.z) operator fun minus(vector: Vector) = Vector(x - vector.x, y - vector.y, z - vector.z) operator fun times(vector: Vector) = Vector(x * vector.x, y * vector.y, z * vector.z) operator fun times(times: Double) = Vector(x * times, y * times, z * times) operator fun div(times: Double) = Vector(x / times, y / times, z / times) operator fun plusAssign(vector: Vector) { this.x += vector.x this.y += vector.y this.z += vector.z } operator fun timesAssign(vector: Vector) { this.x *= vector.x this.y *= vector.y this.z *= vector.z } operator fun divAssign(factor: Double) { this.x /= factor this.y /= factor this.z /= factor } infix fun dot(vector: Vector) = x * vector.x + y * vector.y + z * vector.z infix fun cross(vector: Vector) = Vector(y * vector.z - z * vector.y, z * vector.x - x * vector.z, x * vector.y - y * vector.x) fun lengthSquared() = x * x + y * y + z * z fun length() = sqrt(lengthSquared()) fun unit() = this / length() fun reflect(normal: Vector) = this - 2.0 * (this dot normal) * normal fun refract(normal: Vector, factor: Double): Vector { val cosTheta = min(-this dot normal, 1.0) val rPrep = factor * (this + cosTheta * normal) val rParallel = -sqrt(abs(1.0 - rPrep.lengthSquared())) * normal return rPrep + rParallel } fun nearZero() = abs(x) < 1e-8 && abs(y) < 1e-8 && abs(z) < 1e-8 fun toVectorString() = "$x $y $z" fun toColorString(): String { val color = clamp(this, 0.0, 0.999) return "${(255.999 * color.x).toInt()} ${(255.999 * color.y).toInt()} ${(255.999 * color.z).toInt()}" } companion object { @JvmStatic fun randomInUnitDisk(): Vector { while (true) { val vector = Vector(Random.nextDouble(), Random.nextDouble(), 0.0) if (vector.lengthSquared() < 1) return vector } } @JvmStatic fun randomInHemisphere(normal: Vector): Vector { val inUnitSphere = randomInUnitSphere() return if (inUnitSphere dot normal > 0.0) inUnitSphere else -inUnitSphere } @JvmStatic fun randomUnitVector() = randomInUnitSphere().unit() @JvmStatic fun randomInUnitSphere(): Vector { while (true) { val vector = random(-1.0, 1.0) if (vector.lengthSquared() < 1) return vector } } @JvmStatic fun random(min: Double, max: Double) = Vector(Random.nextDouble(min, max), Random.nextDouble(min, max), Random.nextDouble(min, max)) @JvmStatic fun random() = Vector(Random.nextDouble(), Random.nextDouble(), Random.nextDouble()) @JvmStatic private fun clamp(x: Double, min: Double, max: Double) = if (x < min) min else if (x > max) max else x @JvmStatic private fun clamp(vector: Vector, min: Double, max: Double) = Vector(clamp(vector.x, min, max), clamp(vector.y, min, max), clamp(vector.z, min, max)) } } operator fun Double.times(vector: Vector) = vector * this
import './App.css'; import React, {createContext, useEffect, useState} from 'react'; import Main from "../Main/Main"; import {BrowserRouter, Route, Routes} from "react-router-dom"; import Login from "../Login/Login"; import Register from "../Register/Register"; import Profile from "../Profile/Profile"; import Movies from "../Movies/Movies"; import SavedMovies from "../SavedMovies/SavedMovies"; import Page404 from "../Page404/Page404"; import {ProtectedRoute} from "../ProtectedRoute/ProtectedRoute"; import Popup from '../Popup/Popup'; import InfoTooltip from "../InfoTooltip/InfoTooltip"; import {getProfile} from "../../utils/Api/MainApi"; // начинаю последний этап export const CurrentUserContext = createContext(); const initialStateUser = {name: '', email: ''} function App() { const [user, setUser] = useState(initialStateUser); const [logedId, setLogedId] = useState(true); //хуки для карточек и фильмов const [cards, setCards] = useState([]) const [films, setFilms] = useState([]) const [saveMoviesStore, setSaveMoviesStore] = useState([]); const [findeSaveMoviesStore, setFindeSaveMoviesStore] = useState([]); //состояния для попап const [popupOpen, setPopupOpen] = useState(false) const [popupMessage, setPopupMessage] = useState(""); const [searchText, setSearchText] = useState('') const [isInfoMessage, setInfoMessage] = useState(null); const closePopup = () => { setPopupOpen(false); setPopupMessage(""); }; const closePopupHello = () => { setPopupOpen(false); setPopupMessage(""); }; const openPopup = (message) => { setPopupMessage(message); setPopupOpen(true); }; useEffect(() => { if(!localStorage.getItem("token") || localStorage.getItem("token") === ''){ setLogedId(false) } else { getProfile() .then(data=>{ if(data.message){ localStorage.removeItem("token") setLogedId(false) window.location.reload(); } }) .catch(error => { console.error('Ошибка при обработке getProfile ', error) }) } }, []); const searchHandler = (text, name) =>{ if(name === 'MoviesSearch'){ const settings = localStorage.getItem(`settings_${name}`) if(settings){ const obj = JSON.parse(settings); obj.searchText = text; localStorage.setItem(`settings_${name}`, JSON.stringify(obj)) } else { localStorage.setItem(`settings_${name}`, `{"searchText": "${text}", "shortSwich": ${false}}`) } } setSearchText(text) } function closePopupsOnOutsideClick(evt) { const target = evt.target; const checkSelector = (selector) => target.classList.contains(selector); if (checkSelector('popup_opened') || checkSelector('popup__close')) { closePopupHello(); } setInfoMessage(null) } function handleShowInfoMessage(message) { setInfoMessage(message); } return ( <BrowserRouter> <CurrentUserContext.Provider value={{setInfoMessage, saveMoviesStore, setSaveMoviesStore, findeSaveMoviesStore, setFindeSaveMoviesStore, user, setUser, logedId, setLogedId, cards, setCards, films, setFilms, openPopup, setSearchText, closePopupHello}}> <div className='app'> <Routes> <Route exact path="/" element={<Main/>}/> <Route exact path="/signin" element={ <ProtectedRoute logedId={!logedId}> <Login handleShowInfoMessage={handleShowInfoMessage} /> </ProtectedRoute> } /> <Route exact path="/signup" element={ <ProtectedRoute logedId={!logedId}> <Register /> </ProtectedRoute> } /> <Route exact path="/profile" element={ <ProtectedRoute logedId={logedId}> <Profile/> </ProtectedRoute> } /> <Route exact path="/Movies" element={ <ProtectedRoute logedId={logedId}> <Movies searchText={searchText} searchHandler={searchHandler}/> </ProtectedRoute> } /> <Route exact path="/saved-movies" element={ <ProtectedRoute logedId={logedId}> <SavedMovies searchText={searchText} searchHandler={searchHandler}/> </ProtectedRoute> } /> <Route exact path="*" element={<Page404/>}/> </Routes> <Popup popupOpen={popupOpen} popupMessage={popupMessage} closePopup={closePopup} /> <InfoTooltip message={isInfoMessage} onClick={closePopupHello} closePopupsOnOutsideClick={closePopupsOnOutsideClick} /> </div> </CurrentUserContext.Provider> </BrowserRouter> ); } export default App;
/** * @file JsonSerializer.h * @author Thomas Saquet, Florent Poinsaut * @date * @brief File containing example of doxygen usage for quick reference. * * Alert - API is a part of the Alert software * Copyright (C) 2013-2017 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef JSONSERIALIZER_H #define JSONSERIALIZER_H #include <boost/algorithm/string.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <Wt/WDateTime> #include <Wt/Dbo/Dbo> #include <Wt/Auth/Dbo/AuthInfo> #include <Wt/WLogger> #include <tools/Session.h> namespace Wt { namespace Dbo { class JsonSerializer { public: JsonSerializer(Session& s); virtual ~JsonSerializer(); static std::string transformFieldName(const std::string& fieldName); static std::string transformTableName(const std::string& fieldTable); static std::string getTrigramFromTableName(const std::string& tableName); template <class V> void act(Wt::Dbo::FieldRef<V> field) { // std::cout << "In act(Wt::Dbo::FieldRef<V> field) - " << field.name() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; // std::cout << "V is: " << typeid(V).name() << std::endl; m_currentElem->put(transformFieldName(field.name()), field.value()); // std::cout << "Out act(Wt::Dbo::FieldRef<V> field) - " << field.name() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; } // When the field is WDateTime or WString, field added as std::string to add quotes " " in json void act(Wt::Dbo::FieldRef<Wt::WDateTime> field) { // std::cout << "In act(Wt::Dbo::FieldRef<Wt::WDateTime> field)) - " << field.name() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; m_currentElem->put<std::string>(transformFieldName(field.name()), field.value().toString().toUTF8()); // std::cout << "Out act(Wt::Dbo::FieldRef<Wt::WDateTime> field)) - " << field.name() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; } void act(Wt::Dbo::FieldRef<Wt::WString> field) { // std::cout << "In act(Wt::Dbo::FieldRef<Wt::WString> field)) - " << field.name() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; m_currentElem->put<std::string>(transformFieldName(field.name()), field.value().toUTF8()); // std::cout << "Out act(Wt::Dbo::FieldRef<Wt::WString> field)) - " << field.name() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; } void act(Wt::Dbo::FieldRef<boost::optional<Wt::WString>> field) { // std::cout << "In act(Wt::Dbo::FieldRef<boost::optional<Wt::WString>> field)) - " << field.name() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; std::string value; if (field.value()) { value = field.value().get().toUTF8(); } else { value = ""; } m_currentElem->put<std::string>(transformFieldName(field.name()), value); // std::cout << "Out act(Wt::Dbo::FieldRef<boost::optional<Wt::WString>> field)) - " << field.name() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; } template <class V> void actId(V& value, const std::string& name, int& size) { field(*this, value, name, size); } template <class V> void actPtr(Wt::Dbo::PtrRef< V> field) { // std::cout << "In actPtr(Wt::Dbo::PtrRef< V> field) - " << m_session.tableName<V>() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; if (m_rank < m_maxRank) { m_rank++; processSerialize(field.value()); m_rank--; } else if (m_rank == m_maxRank) { processSerialize(field.value()); } // std::cout << "Out actPtr(Wt::Dbo::PtrRef< V> field) - " << m_session.tableName<V>() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; } template<class S> void actPtr(Wt::Dbo::PtrRef< Wt::Auth::Dbo::AuthInfo<S >> field) { Wt::log("debug") << "[JsonSerializer] - actPtr(Wt::Dbo::PtrRef< Wt::Auth::Dbo::AuthInfo<S >> field)"; } template <class V> void actWeakPtr(WeakPtrRef<V> field) { Wt::log("debug") << "[JsonSerializer] - actWeakPtr(WeakPtrRef<V> field)"; } template <class V> void actCollection(const Wt::Dbo::CollectionRef<V> & collec) { // std::cout << "In actCollection(const Wt::Dbo::CollectionRef< V> & collec) - " << m_session.tableName<V>() << " - size: " << collec.value().size() << " rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; // FIXME i'm famous ! // Si cette méthode est appelée de manière récursive, m_joinTableContainer est partargé. // Ceci a pour conséquence, que si un objet apparait dans une collection de rang > 0 // il ne sera présent que dans le 1er objet de la collection. if (std::find(m_joinTableContainer.begin(), m_joinTableContainer.end(), collec.joinName()) == m_joinTableContainer.end()) { m_joinTableContainer.push_back(collec.joinName()); std::string tableName = ""; std::string fieldIdName = ""; std::string deleteCondition = ""; if (boost::starts_with(collec.joinName(), TABLE_JOINT_PREFIX SEP)) { tableName = collec.joinName(); fieldIdName = m_parentTableName + SEP + getTrigramFromTableName(m_parentTableName) + ID; deleteCondition = ""; } else { tableName = boost::lexical_cast<std::string>(m_session.tableName<V>()); fieldIdName = collec.joinName() + SEP + getTrigramFromTableName(m_parentTableName) + ID; deleteCondition = "AND \"" + getTrigramFromTableName(boost::lexical_cast<std::string>(m_session.tableName<V>())) + SEP "DELETE\" IS NULL"; } const long long i = m_session.query<long long>( " SELECT COUNT(1)" " FROM \"" + tableName + "\"" " WHERE" " \"" + fieldIdName + "\" = " + boost::lexical_cast<std::string>(m_currentElem->get<long long>("id")) + " " + deleteCondition ); m_currentElem->put<long long>(transformTableName(m_session.tableName<V>()) + "s", i); } // std::cout << "Out actCollection(const Wt::Dbo::CollectionRef< V> & collec) - " << m_session.tableName<V>() << " - size: " << collec.value().size() << " rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; } void actCollection(const Wt::Dbo::CollectionRef<Echoes::Dbo::Syslog> & collec) { Wt::log("debug") << "[JsonSerializer] - actCollection(const Wt::Dbo::CollectionRef<Echoes::Dbo::Syslog> & collec)"; } // We do not want to display AuthInfo to our users. template<class S> void actCollection(const Wt::Dbo::CollectionRef< Wt::Auth::Dbo::AuthInfo<S >> &collec) { Wt::log("debug") << "[JsonSerializer] - actCollection(const Wt::Dbo::CollectionRef< Wt::Auth::Dbo::AuthInfo<S >> &collec)"; } template <class C> void processSerialize(C& c) { // std::cout << "In processSerialize(C& c) - " << m_session.tableName<C>() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; const_cast<C&> (c).persist(*this); // std::cout << "Out processSerialize(C& c) - " << m_session.tableName<C>() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; } template <class C> void processSerialize(Wt::Dbo::ptr< C> & c) { // std::cout << "In processSerialize(Wt::Dbo::ptr< C> & c) - " << m_session.tableName<C>() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; if (m_rank <= m_maxRank) { if (c) { if (c->deleteTag.isNull()) { boost::property_tree::ptree elem; boost::property_tree::ptree *previousElem; std::string previousParentTableName; if (m_currentElem != &m_root || m_rank > 0) { if (!m_isCollection || m_rank > 1) { previousElem = m_currentElem; m_currentElem = &elem; previousParentTableName = m_parentTableName; } } m_rank++; m_currentElem->put("id", c.id()); if (m_rank <= m_maxRank) { m_parentTableName = m_session.tableName<C>(); const_cast<C&> (*c).persist(*this); } m_rank--; if (m_currentElem != &m_root || m_rank > 0) { if (!m_isCollection || m_rank > 1) { m_currentElem = previousElem; m_currentElem->put_child(transformTableName(m_session.tableName<C>()), elem); m_parentTableName = previousParentTableName; } } } else { m_currentElem->put(transformTableName(m_session.tableName<C>()), "{}"); } } else { m_currentElem->put(transformTableName(m_session.tableName<C>()), "{}"); } } // std::cout << "Out processSerialize(Wt::Dbo::ptr< C> & c) - " << m_session.tableName<C>() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; } template<class S> // We do not want to display AuthInfo to our users. void processSerialize(Wt::Dbo::ptr< Wt::Auth::Dbo::AuthInfo<S >> &c) { Wt::log("debug") << "[JsonSerializer] - processSerialize(Wt::Dbo::ptr< Wt::Auth::Dbo::AuthInfo<S >> &c)"; } // WARNING: hack to create an array on root of JSON // boost::property_tree::json_parser::write_json doesn't handle array for root // boost version: 1.53 template <class C> void processSerialize(Wt::Dbo::collection< Wt::Dbo::ptr<C>>& cs) { // std::cout << "In processSerialize(Wt::Dbo::collection< Wt::Dbo::ptr< C> >& cs) - " << m_session.tableName<C>() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; long unsigned int i = 0; m_ss << "[\n"; m_rank++; for (auto& c : cs) { processSerialize(c); if (!m_currentElem->empty()) { try { boost::property_tree::json_parser::write_json(m_ss, *m_currentElem); } catch (boost::property_tree::json_parser::json_parser_error const &e) { Wt::log("error") << "[JsonSerializer] - " << e.message(); } m_result = m_ss.str(); if (i < cs.size() - 1) { std::string tmp = m_ss.str().erase(m_ss.str().size() - 1); m_ss.str(""); m_ss.clear(); m_ss << tmp; m_ss << ",\n"; } } m_currentElem->clear(); m_joinTableContainer.clear(); ++i; } // FIXME (or not.) // When the last elem is "deleted" (echoes way) a ',' remains before the final brackett // Should be removed if it exists // We will fix this the day we have a problem which should not happen. m_rank--; m_ss << "]\n"; // std::cout << "Out processSerialize(Wt::Dbo::collection< Wt::Dbo::ptr< C> >& cs) - " << m_session.tableName<C>() << " - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; } template<class S> // We do not want to display AuthInfo to our users. void processSerialize(Wt::Dbo::collection< Wt::Dbo::ptr< Wt::Auth::Dbo::AuthInfo<S >> >& cs) { Wt::log("debug") << "[JsonSerializer] - processSerialize(Wt::Dbo::collection< Wt::Dbo::ptr< Wt::Auth::Dbo::AuthInfo<S >> >& cs)"; } template <class C> void serialize(C& c) { m_rank = 0; // std::cout << "In serialize(C& c) - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; m_joinTableContainer.clear(); processSerialize(c); try { boost::property_tree::json_parser::write_json(m_ss, m_root); } catch (boost::property_tree::json_parser::json_parser_error const &e) { Wt::log("error") << "[JsonSerializer] - " << e.message(); } m_result = m_ss.str(); // std::cout << "Out serialize(C& c) - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; } // WARNING: hack to create an array on root of JSON // boost::property_tree::json_parser::write_json doesn't handle array for root // boost version: 1.53 template <class C> void serialize(Wt::Dbo::collection< Wt::Dbo::ptr< C> >& cs) { m_rank = 0; m_isCollection = true; // std::cout << "In serialize(Wt::Dbo::collection< Wt::Dbo::ptr< C> >& cs) - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; m_joinTableContainer.clear(); processSerialize(cs); m_result = m_ss.str(); // std::cout << "Out serialize(Wt::Dbo::collection< Wt::Dbo::ptr< C> >& cs) - rank: " << boost::lexical_cast<std::string>(m_rank) << std::endl; } std::string getResult(); void print(); Session *session(); private: std::ostream& m_out; std::stringstream m_ss; Session& m_session; std::string m_result; boost::property_tree::ptree m_root; boost::property_tree::ptree *m_currentElem; const unsigned short m_maxRank; bool m_isCollection; std::string m_parentTableName; static std::vector<std::string> m_joinTableContainer; static unsigned short m_rank; }; }} #endif /* JSONSERIALIZER_H */
import 'package:fitness_app/common_widget/round_gradient_button.dart'; import 'package:fitness_app/view/dashboard/dashboardScreen.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../widgets/app_colors.dart'; class WelcomeScreen extends StatelessWidget { static String routeName = "/WelcomeScreen"; const WelcomeScreen({super.key}); @override Widget build(BuildContext context) { var media = MediaQuery.of(context).size; return Scaffold( backgroundColor: AppColors.whiteColor, body: SafeArea( child: Padding( padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 25), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: [ Image.asset("assets/images/welcome_promo.png",width: media.width*0.75,fit: BoxFit.fitWidth,), SizedBox( height: media.width*0.05, ), const Text( "Welcome, Stefani", style: TextStyle( color: AppColors.blackColor, fontSize: 20, fontWeight: FontWeight.w700, ), ), SizedBox( height: media.width*0.01, ), const Text( "You are all set now, let's reach your\ngoals together with us", textAlign: TextAlign.center, style: TextStyle( color: AppColors.grayColor, fontSize: 12, fontWeight: FontWeight.w400, fontFamily: "Poppins", ), ), const Spacer(), RoundGradientButton( title: "Go To Home", onPressed: (){ Navigator.pushNamed(context, DashboardScreen.routeName); }), ], ), ), ), ); } }
import os import cv2 from skimage.metrics import structural_similarity def ssim(frame1, frame2): """Calculate Structural Similarity (SSIM) between two frames""" frame1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY) frame2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY) frame1 = cv2.resize(frame1, (512, 512)) frame2 = cv2.resize(frame2, (512, 512)) return structural_similarity(frame1, frame2) def read_frames(video_path, size=1000): cap = cv2.VideoCapture(video_path) if not cap.isOpened(): print("Error opening video file") return while True: frames = [] for _ in range(size): ret, frame = cap.read() if not ret: break frames.append(frame) if not frames: break yield frames cap.release() def slice_frames(frames,ssim_threshold): start = 0 end = start + 1 total_length = len(frames) borders = [] while end != total_length: left = end right = total_length - 1 while left != right: mid = int((left + right)/2) ssim_val = ssim(frames[start], frames[mid]) if ssim_val > ssim_threshold: # indicating that the same scene left = mid + 1 else: right = mid borders.append(left) start = left end = start + 1 return borders def frames_to_video(video_path, borders, output_path): cap = cv2.VideoCapture(video_path) if not cap.isOpened(): print("Error opening video file") return fps = int(cap.get(cv2.CAP_PROP_FPS)) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fourcc = cv2.VideoWriter_fourcc(*'mp4v') video_writer = None segment_count = 1 frame_count = 0 current_border = 0 while True: ret, frame = cap.read() frame_count += 1 if not ret: break if current_border < len(borders) and frame_count > borders[current_border]: if video_writer: video_writer.release() segment_path = os.path.join(output_path, f"segment_{segment_count}.mp4") video_writer = cv2.VideoWriter(segment_path, fourcc, fps, (width, height)) segment_count += 1 current_border += 1 if video_writer: video_writer.write(frame) else: segment_path = os.path.join(output_path, f"segment_{segment_count}.mp4") video_writer = cv2.VideoWriter(segment_path, fourcc, fps, (width, height)) segment_count += 1 current_border += 1 if video_writer: video_writer.release() cap.release() def segment_scenes(video_path, read_size, min_interval, ssim_threshold, output_path): last_frame = None # Used to determine if two segments are connected generator = read_frames(video_path, read_size) final_borders = [] offset = 0 for frames in generator: first_frame = frames[0] print(f"Read {len(frames)} frames over") borders = slice_frames(frames, ssim_threshold) # Check if the last frame of the previous segment is similar to the first frame of the current segment if last_frame is not None and ssim(first_frame, last_frame) >= ssim_threshold: final_borders.pop() final_borders.extend(b + offset for b in borders) offset += read_size last_frame = frames[-1] last = 0 filtered_borders = [] # Filter borders based on the minimum interval for item in final_borders: if item - last < min_interval: continue else: last = item filtered_borders.append(item) print(filtered_borders) frames_to_video(video_path, filtered_borders, output_path) if __name__ == '__main__': read_size = 500 min_interval = 100 # Set the minimum interval value ssim_threshold = 0.50 # Set the threshold for SSIM video_path = "test_input/test.mp4" output_path = "test_output" segment_scenes(video_path, read_size, min_interval, ssim_threshold, output_path)
import { RequestType } from "../../infrastructure/constant/RequestType"; import { config } from "../../application/variable/Config"; import type { RequestTypeImpl } from "../../interface/RequestTypeImpl"; interface Object { type: RequestTypeImpl; name: string; path: string; cache: boolean; class: string; access: string; method: string; callback?: string | string[]; } /** * @class * @memberof domain.parser */ export class RequestParser { /** * @description routing.jsonに設定されたrequestsを返却します。 * クラスターの指定があった場合は返却する配列にマージして返却 * Returns requests set in routing.json. * If a cluster is specified, it is merged into the array to be returned * * @param {string} name * @return {array} * @method * @public */ execute (name: string): Object[] { if (!config || !config.routing) { return []; } const routing: any = config.routing[name]; if (!routing || !routing.requests) { return []; } const requests: Object[] = []; for (let idx = 0; idx < routing.requests.length; idx++) { const object: Object = routing.requests[idx]; if (object.type !== RequestType.CLUSTER) { requests.push(object); continue; } const results: Object[] = new RequestParser().execute(object.path); for (let idx = 0; idx < results.length; ++idx) { requests.push(results[idx]); } } return requests; } }
document.getElementById('input-form').addEventListener('submit', function(event) { event.preventDefault(); // Get form data const formData = new FormData(event.target); const city = formData.get('city'); const totalFunding = parseFloat(formData.get('total-funding')); const yearFounded = parseInt(formData.get('year-founded')); const debtFinancing = parseFloat(formData.get('debt-financing')); const ventureFunding = parseFloat(formData.get('venture-funding')); const seedFunding = parseFloat(formData.get('seed-funding')); const angelFunding = parseFloat(formData.get('angel-funding')); const grant = parseFloat(formData.get('grant')); const convertibleNote = parseFloat(formData.get('convertible-note')); const privateEquity = parseFloat(formData.get('private-equity')); const undisclosedFunding = parseFloat(formData.get('undisclosed-funding')); const market = formData.get('market'); const country = formData.get('country'); const fundingRounds = parseInt(formData.get('funding-rounds')); const firstFundingDate = formData.get('first-funding-date'); const lastFundingDate = formData.get('last-funding-date'); const firstFundingReceived = parseFloat(formData.get('first-funding-received')); const secondFundingReceived = parseFloat(formData.get('second-funding-received')); const thirdFundingReceived = parseFloat(formData.get('third-funding-received')); const fourthFundingReceived = parseFloat(formData.get('fourth-funding-received')); const fifthFundingReceived = parseFloat(formData.get('fifth-funding-received')); const sixthFundingReceived = parseFloat(formData.get('sixth-funding-received')); // Mapping dictionaries const marketMapping = { "Software": 562, "Biotechnology": 53, "Mobile": 380, "Curated Web": 137, "Enterprise Software": 211, "Health Care": 273, "E-Commerce": 180, "Hardware + Software": 272, "Advertising": 7, "Clean Technology": 82, "Health and Wellness": 276 }; const cityMapping = { "San Francisco": 1486, "New York": 1148, "Palo Alto": 1216, "Austin": 81, "Seattle": 1540, "Mountain View": 1106, "Chicago": 313, "Los Angeles": 935, "Boston": 170, "Vancouver": 1754 }; const countryMapping = { "USA": 1, "Canada": 0 }; // Prepare data for prediction const predictionData = { "city": cityMapping[city], "total_funding": totalFunding, "year_founded": yearFounded, "debt_financing": debtFinancing, "venture_funding": ventureFunding, "seed_funding": seedFunding, "angel_funding": angelFunding, "grant": grant, "convertible_note": convertibleNote, "private_equity": privateEquity, "undisclosed_funding": undisclosedFunding, "market": marketMapping[market], "country_code": countryMapping[country], "funding_rounds": fundingRounds, "first_funding_date": firstFundingDate, "last_funding_date": lastFundingDate, "first_funding_received": firstFundingReceived, "second_funding_received": secondFundingReceived, "third_funding_received": thirdFundingReceived, "fourth_funding_received": fourthFundingReceived, "fifth_funding_received": fifthFundingReceived, "sixth_funding_received": sixthFundingReceived }; // Call model API (replace MODEL_ENDPOINT_URL with the actual endpoint URL) const MODEL_ENDPOINT_URL = 'log_reg.pkl'; fetch(MODEL_ENDPOINT_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(predictionData) }) .then(response => response.json()) .then(data => { // Display prediction result if (data.prediction === 1) { alert("Based on the analysis, the model predicts that the startup may face challenges and could potentially close down in the future. While this prediction serves as a cautionary note, it's essential to reassess strategies and explore opportunities for improvement to mitigate risks and enhance the chances of success."); } else if (data.prediction === 0) { alert("Great news! According to the analysis, the model predicts that the startup is positioned for success. Remember to stay agile and adaptive to capitalize on opportunities and maintain growth."); } }) .catch(error => { console.error('Error:', error); alert("An error occurred while processing your request. Please try again later."); }); });
package com.almostreliable.lib.datagen.recipe; import com.almostreliable.lib.item.IngredientStack; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.ItemLike; import java.util.Set; /** * An abstraction for an item or an ingredient inside a datagen recipe. * <p> * Can be used to add all kinds of item or ingredient components to {@link FinishedRecipe}s. */ public interface RecipeComponent { static RecipeComponent of(ResourceLocation id, int count) { return new RecipeComponent() { @Override public JsonElement toJson() { JsonObject json = new JsonObject(); json.addProperty("item", id.toString()); if (count > 1) json.addProperty("count", count); return json; } @Override public Set<String> getModIds() { return Set.of(id.getNamespace()); } }; } static RecipeComponent of(ResourceLocation id) { return of(id, 1); } static RecipeComponent of(String rawId, int count) { if (!rawId.startsWith("#")) return of(new ResourceLocation(rawId), count); return new RecipeComponent() { @Override public JsonElement toJson() { JsonObject json = new JsonObject(); json.addProperty("tag", rawId.substring(1)); if (count > 1) json.addProperty("count", count); return json; } @Override public Set<String> getModIds() { return Set.of(rawId.substring(1, rawId.indexOf(':'))); } }; } static RecipeComponent of(String rawId) { return of(rawId, 1); } static RecipeComponent of(Ingredient ingredient, int count) { return IngredientStack.of(ingredient, count); } static RecipeComponent of(Ingredient ingredient) { return IngredientStack.of(ingredient); } static RecipeComponent of(ItemStack stack, int count) { return IngredientStack.of(stack, count); } static RecipeComponent of(ItemStack stack) { return IngredientStack.of(stack); } static RecipeComponent of(ItemLike itemLike, int count) { return IngredientStack.of(itemLike, count); } static RecipeComponent of(ItemLike itemLike) { return IngredientStack.of(itemLike); } static RecipeComponent of(TagKey<Item> itemTag, int count) { return IngredientStack.of(itemTag, count); } static RecipeComponent of(TagKey<Item> itemTag) { return IngredientStack.of(itemTag); } JsonElement toJson(); Set<String> getModIds(); }
import React, { useEffect, useState } from 'react' import Navbar from './Navbar' import Footer from './Footer' import { UserAuth } from '../contexts/AuthContext' import { db } from '../firebase' import { updateDoc, doc, onSnapshot } from 'firebase/firestore' import { Link } from 'react-router-dom' const Account = () => { const { user } = UserAuth(); const [saved, setSaved] = useState([]); useEffect(() => { onSnapshot(doc(db, 'users', `${user?.email}`), (doc) => { setSaved(doc.data()?.wishlist); }) }, [user?.email]) const productRef = doc(db, 'users', `${user?.email}`) const handleDelete = async (passedID) =>{ try { const result = saved.filter((item) => item.id !== passedID) await updateDoc(productRef, { wishlist : result }) } catch (error) { console.log(error); } } return ( <> <Navbar /> <div className="bg-gray-100 text-black h-auto font-f2 p-4"> <div className="md:flex md:space-x-10 items-center"> <h1 className="text-4xl underline underline-offset-8 decoration-purple-400">Wishlist</h1> <h1 className="my-2 ">Welcome: <span className='font-bold'>{user?.email}</span> </h1> <Link to='/cart'><button className='text-xl bg-purple-400 text-white px-4 py-1 rounded-xl shadow-xl '>Go to Cart</button></Link> </div> <div className="md:grid md:grid-cols-2 xl:grid-cols-3 gap-8 py-10 flex flex-col items-center"> {saved.map((item) => { return <div className='w-[400px] h-[350px] bg-white rounded-2xl shadow-xl'> <img className=' mt-4 w-[200px] h-[200px] object-contain mx-auto' src={item?.image} alt="" /> <h1 className="text-xs mt-7 text-center tracking-wider">{item?.title} <span className='font-bold ml-2 text-xl block '>${item?.price} </span> <button onClick={()=>{handleDelete(item?.id)}} className="bg-purple-400 mb-4 px-3 py-1 text-white rounded-xl shadow-2xl font-bold font-f2 tracking-widest hover:scale-105 duration-300">Remove</button> </h1> </div> })} </div> </div> <Footer /> </> ) } export default Account
/* Copyright (c) 2014 Marco Martin <[email protected]> Copyright (c) 2014 Vishesh Handa <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _KCM_SEARCH_H #define _KCM_SEARCH_H #include <KConfig> #include <KConfigGroup> #include <Plasma/Package> #include <KQuickAddons/ConfigModule> class QStandardItemModel; class KCMSplashScreen : public KQuickAddons::ConfigModule { Q_OBJECT Q_PROPERTY(QStandardItemModel *splashModel READ splashModel CONSTANT) Q_PROPERTY(QString selectedPlugin READ selectedPlugin WRITE setSelectedPlugin NOTIFY selectedPluginChanged) public: enum Roles { PluginNameRole = Qt::UserRole +1, ScreenhotRole }; KCMSplashScreen(QObject* parent, const QVariantList& args); QList<Plasma::Package> availablePackages(const QString &component); QStandardItemModel *splashModel(); QString selectedPlugin() const; void setSelectedPlugin(const QString &plugin); public Q_SLOTS: void load(); void save(); void defaults(); void test(const QString &plugin); Q_SIGNALS: void selectedPluginChanged(); private: QStandardItemModel *m_model; Plasma::Package m_package; QString m_selectedPlugin; KConfig m_config; KConfigGroup m_configGroup; }; #endif
/* eslint-disable no-unused-vars */ import React, { useState } from "react"; import ImageProductOne from "../images/image-product-1.png"; import ImageProductTwo from "../images/image-product-2.jpg"; import ImageProductThree from "../images/image-product-3.jpg"; import ImageProductFour from "../images/image-product-4.jpg"; import ImageProduct1 from "../images/image-product-1-thumbnail.jpeg"; import ImageProduct2 from "../images/image-product-2-thumbnail.webp"; import ImageProduct3 from "../images/image-product-3-thumbnail.jpg"; import ImageProduct4 from "../images/image-product-4-thumbnail.webp"; import { Figure, Image } from "react-bootstrap"; function LargeScreenSlide() { const [displayedImage, setDisplayedImage] = useState(""); const handleClick = (image) => { setDisplayedImage(image); }; const thumbnails = [ { src: ImageProduct1, alt: "Thumbnail 1", mainImage: ImageProductOne }, { src: ImageProduct2, alt: "Thumbnail 2", mainImage: ImageProductTwo }, { src: ImageProduct3, alt: "Thumbnail 3", mainImage: ImageProductThree }, { src: ImageProduct4, alt: "Thumbnail 4", mainImage: ImageProductFour }, ]; return ( <> <div className=" d-none d-lg-block"> <Image src={displayedImage || ImageProductOne} className="rounded-3" width={430} /> <br /> <Figure className="d-flex gap-4"> {thumbnails.map((thumbnail, index) => ( <Figure.Image key={index} className="rounded-2" style={{ cursor: "pointer" }} width={90} alt={thumbnail.alt} src={thumbnail.src} onClick={() => handleClick(thumbnail.mainImage)} /> ))} </Figure> </div> </> ); } export default LargeScreenSlide;
# Software Engineering Lab 3: Unity Simulation Welcome to our Unity project used in simulating the RL environment our agent will be trained on in order to learn to fold a piece of fabric. The project itself consists of a number of components, separated using different namespaces. For the interaction between Unity and our Python reinforcement learning environment, we're using the [Unity ML Agents framework (Release 12)](https://github.com/Unity-Technologies/ml-agents). ## Global project structure The project is separated globally in two main namespaces: - [SoftBody](/api/SoftBody.html) which implements the physics of our piece of textile, either using a CPU based integrator or using a GPU based implementation (which was spun-out into [SoftBody.Gpu](/api/SoftBody.Gpu.html)). - [RigidBody](/api/RigidBody.html) which implements the ML Agents logic driving our Baxter robot's behaviour in Unity and some additional features used in its interaction with the surroundings (e.g. [Magnetic Grippers](/api/RigidBody.BaxterHandGrab.html)). Some smaller namespaces contain tests and configuration functionality. ## Explore the API reference For full details we refer you to the [API reference](/api/Configuration.html) included in this documentation site.
<h3>Add Hotel Room</h3> <form action="hotel/add_room.php" method="POST"> <div class="form-group"> <label for="roomDescription">Description</label> <input type="text" class="form-control" id="roomDescription" name="roomDescription" required> </div> <div class="form-group"> <label for="roomCondition">Condition</label> <select class="form-control" id="roomCondition" name="roomCondition" required> <option value="Good">Good</option> <option value="Decent">Decent</option> <option value="Unusable">Unusable</option> </select> </div> <div class="form-group"> <label for="roomImageLink">Image Link</label> <input type="text" class="form-control" id="roomImageLink" name="roomImageLink" required> </div> <button type="submit" class="btn btn-primary">+ Add</button> </form> <?php include '../utils/connect.php'; // Check if form is submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { // Check if all necessary POST variables are set if(isset($_POST['roomDescription']) && isset($_POST['roomCondition']) && isset($_POST['roomImageLink'])) { // Retrieve and sanitize form inputs $roomDescription = pg_escape_string($conn, $_POST['roomDescription']); $roomCondition = pg_escape_string($conn, $_POST['roomCondition']); $roomImageLink = pg_escape_string($conn, $_POST['roomImageLink']); // Prepare and execute query $query = "INSERT INTO hotel_room (description, condition, image_link) VALUES ($1, $2, $3)"; $result = pg_prepare($conn, "insert_hotel_room", $query); $result = pg_execute($conn, "insert_hotel_room", array($roomDescription, $roomCondition, $roomImageLink)); if ($result) { header("Location: ../Dashboard.php?p=hotel/hotelManager"); exit(); } else { echo "Error: Could not add the room."; } } else { echo "Error: Missing form data."; } } ?>
/* * Copyright 2020-2023 IEXEC BLOCKCHAIN TECH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.iexec.commons.poco.tee; import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.*; @Value @Builder @AllArgsConstructor @NoArgsConstructor(force = true, access = AccessLevel.PRIVATE) public class TeeEnclaveConfiguration { @JsonAlias("provider") TeeFramework framework; String version; String entrypoint; long heapSize; String fingerprint; public static TeeEnclaveConfiguration buildEnclaveConfigurationFromJsonString(String jsonString) throws JsonProcessingException { return new ObjectMapper() .readValue(jsonString, TeeEnclaveConfiguration.class); } public String toJsonString() throws JsonProcessingException { return new ObjectMapper().writeValueAsString(this); } @JsonIgnore public TeeEnclaveConfigurationValidator getValidator() { return new TeeEnclaveConfigurationValidator(this); } }
<div class="mainContent"> <div class="subLContent"> <div class="header"> Categoies </div> <div *ngFor="let cat of categories; let index = index" class="element"> <!-- <span [ngClass]="{ selectedCat: selectedCatId === cat.Id }" (click)="selectedCatId = cat.Id" >{{ cat.name }}</span > --> <a [routerLink]="['/home/' + index]" routerLinkActive="active" [ngClass]="{ 'navigate-active': selectedCatIndex == index }" >{{ cat.name }}</a > </div> <div class="addButton"> <input type="text" [(ngModel)]="newCategory" style="width:80px;" /> <button (click)="addCategory()" [disabled]="!newCategory">Add</button> </div> </div> <div class="subRContent"> <div class="header"> To Do List </div> <div *ngFor="let task of tasks; let index = index" class="element flexContainerForTask" > <div> <input type="checkbox" [(ngModel)]="task.isCompleted" /> </div> <div> <span [ngClass]="{ strikeText: task.isCompleted }">{{ task.name }}</span> </div> <div> <!-- <span (click)="deleteTask(index)">delete</span> --> <img src="assets/img/delete.png" alt="delete" (click)="deleteTask(index)" class="imageButton" title="delete" /> </div> </div> <div class="addButton"> <input type="text" [(ngModel)]="newTask" style="width:80px;" /> <button (click)="addTask()" [disabled]="!newTask">Add</button> </div> </div> </div>
import { CommonModule } from '@angular/common'; import { Component } from '@angular/core'; import { Router, RouterLink, RouterModule, RouterOutlet, } from '@angular/router'; import { HousingService } from '../housing.service'; import { Listing } from '../listing'; import { FormControl, FormGroup, ReactiveFormsModule, Validators, } from '@angular/forms'; @Component({ selector: 'app-add-listing', standalone: true, imports: [ CommonModule, RouterModule, RouterLink, RouterOutlet, ReactiveFormsModule, ], templateUrl: './add-listing.component.html', styleUrl: './add-listing.component.css', }) export class AddListingComponent { listings: Listing[] | undefined; addForm: FormGroup = new FormGroup({ name: new FormControl('', Validators.required), city: new FormControl('', Validators.required), photo: new FormControl('', Validators.required), price: new FormControl('', [Validators.required, Validators.min(1)]), wifi: new FormControl(''), laundry: new FormControl(''), }); constructor( private housing: HousingService, private router: Router, ) {} ngOnInit() {} updateImagePreview() { let photoControl = this.addForm.get('photo'); if (photoControl) { photoControl.updateValueAndValidity(); } } onSubmit() { if (this.addForm.valid) { const name = this.addForm.value.name; const city = this.addForm.value.city; const photo = this.addForm.value.photo; const price = this.addForm.value.price; const wifi = this.addForm.value.wifi; const laundry = this.addForm.value.laundry; this.housing.addListing(name, city, photo, price, wifi, laundry); this.router.navigate(['/edit']); } } }
import { ExtendedRoutesConfig, ExtendedSpecConfig, generateRoutes, generateSpec } from 'tsoa' import { getEnv } from '../src/utils/get-env' const HOST = getEnv('HOST', 'string', 'localhost') const PORT = getEnv('PORT', 'number', 9000) const globalOp = { entryFile: 'src/main.ts', controllerPathGlobs: ['src/controllers/*-controller.ts'], basePath: '/v1', } const specOptions: ExtendedSpecConfig = { ...globalOp, specVersion: 3, host: `${HOST}:${PORT}`, schemes: [HOST === 'localhost' ? 'http' : 'https'], outputDirectory: 'generated/tsoa/spec', noImplicitAdditionalProperties: 'silently-remove-extras', } const routeOptions: ExtendedRoutesConfig = { ...globalOp, routesDir: 'generated/tsoa', noImplicitAdditionalProperties: 'ignore', } export const GenerateTsoaRoutesAndSpec = async (): Promise<void> => { await generateSpec(specOptions) console.info('Generate OpenApi Spec: Done') await generateRoutes(routeOptions) console.info('Generate Routes: Done') }
@page "/student/save" @page "/student/save/{Id:int}" @inherits Bases.StudentInfo.StudentSaveBase @if(Id == null) { <h3>Add New Student</h3> } else { <h3>Edit @student.Name</h3> } <br /> <hr /> <a href="student/list" class="btn btn-info">Back</a> <EditForm Model="@student" OnValidSubmit="HandleValidSubmit"> <DataAnnotationsValidator/> <ValidationSummary/> <div class="form-group row"> <label for="Name" class="col-sm-3 col-form-label"> Name </label> <div class="col-sm-9"> <InputText id="Name" class="form-control" placeholder="Name" @bind-Value="student.Name" /> <ValidationMessage For="@(() => student.Name)"/> </div> </div> <div class="form-group row"> <label for="MotherName" class="col-sm-3 col-form-label"> Mother Name </label> <div class="col-sm-9"> <InputText id="MotherName" class="form-control" placeholder="Mother Name" @bind-Value="student.MotherName" /> <ValidationMessage For="@(() => student.MotherName)"/> </div> </div> <div class="form-group row"> <label for="FatherName" class="col-sm-3 col-form-label"> Father Name </label> <div class="col-sm-9"> <InputText id="FatherName" class="form-control" placeholder="Father Name" @bind-Value="student.FatherName" /> <ValidationMessage For="@(() => student.FatherName)"/> </div> </div> <div class="form-group row"> <label for="Nationality" class="col-sm-3 col-form-label"> Nationality </label> <div class="col-sm-9"> <InputText id="Nationality" class="form-control" placeholder="Nationality" @bind-Value="student.Nationality" /> <ValidationMessage For="@(() => student.Nationality)"/> </div> </div> <div class="form-group row"> <label for="DateOfBirth" class="col-sm-3 col-form-label"> Date of Birth </label> <div class="col-sm-9"> <InputDate id="DateOfBirth" class="form-control" placeholder="Date of Birth" @bind-Value="student.DateOfBirth" /> <ValidationMessage For="@(() => student.DateOfBirth)"/> </div> </div> <div class="form-group row"> <label for="Class" class="col-sm-3 col-form-label"> Class </label> <div class="col-sm-9"> <InputSelect id="Class" class="form-control" placeholder="Class" @bind-Value="student.ClassId" > <option value="">Select Any</option> @foreach (var classStandard in classes) { <option value="@classStandard.Id">@classStandard.Name</option> } </InputSelect> </div> </div> <div class="form-group row"> <label for="EnrollDate" class="col-sm-3 col-form-label"> Enroll Date </label> <div class="col-sm-9"> <InputDate id="EnrollDate" class="form-control" placeholder="Enroll Date" @bind-Value="student.EnrollDate" /> <ValidationMessage For="@(() => student.EnrollDate)"/> </div> </div> <button class="btn btn-primary" type="submit">Submit</button> </EditForm> @code { }
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, catchError, of, throwError } from 'rxjs'; import { Country } from '../interfaces/Country.interface'; import { City } from '../interfaces/City.interface'; import { Weather } from '../interfaces/Weather.interface'; import { Exchange } from '../interfaces/Exchange.interface'; @Injectable({ providedIn: 'root', }) export class DataService { private baseUrl: string = 'http://localhost:8000/api'; constructor(private http: HttpClient) {} getQueryHistory(country_id: number): Observable<any> { return this.http.get(`${this.baseUrl}/queries_history/${country_id}`); } postQueryHistory(data: any): Observable<any> { return this.http.post(`${this.baseUrl}/save_history`, data); } getCountries(): Observable<Country[]> { return this.http.get<Country[]>(`${this.baseUrl}/get-all-countries`).pipe( catchError((error) => { console.error('Error fetching countries:', error); return of([]); }) ); } getExchangeByCountry(country_id: number): Observable<Exchange> { return this.http .get<Exchange>(`${this.baseUrl}/currency/${country_id}`) .pipe( catchError((error) => { console.error('Error fetching exchange:', error); return throwError(() => new Error('Error fetching exchange')); }) ); } getCitiesByCountry(country_id: number): Observable<City> { return this.http .get<City>(`${this.baseUrl}/countries/${country_id}/cities`) .pipe( catchError((error) => { console.error('Error fetching cities:', error); return throwError(() => new Error('Error fetching cities')); }) ); } getWeatherByCityName(city_name: string): Observable<Weather[]> { return this.http .get<Weather[]>(`${this.baseUrl}/weather/${city_name}`) .pipe( catchError((error) => { console.error('Error fetching the weather:', error); return of([]); }) ); } }
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org" lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <style> .indent { margin-left: 30px; margin-right: 30px; margin-top: 20px; } </style> <title>Информация о команде</title> </head> <body> <div th:replace="general :: page-header"> </div> <div class="indent"> <div id="teamInfo"> <h4 th:text="${team.getName()}"></h4> <p th:if="${team.getName() != null}" th:text="'Название: ' + ${team.getName()}"></p> <p th:if="${team.getCoach() != null}" th:text="'Тренер: ' + ${team.getCoach()}"></p> <p>Текущий состав команды:&nbsp <table class="table table-bordered table-warning" id="currentPlayers"> <thead class="thead-dark"> <tr> <th scope="col"> Имя игрока</th> <th scope="col"> Дата рождения</th> </tr> </thead> <tbody> <tr th:if="${teamPlayers.isEmpty()}"> <td><span>Состав отсутствует.</span></td> </tr> <tr th:each="player : ${teamPlayers}"> <td> <a th:href="'sportsman?sportsmanId=' + ${player.getId()}"> <span th:text="${player.getName()}"> </span></a> </td> <td><span th:text="${player.getBirth_date()}"> </span></td> </tr> </tbody> </table> </p><br> <p>История участия в соревнованиях:&nbsp <table class="table table-bordered table-warning" id="compHistory"> <thead class="thead-dark"> <tr> <th scope="col"> Команда противника</th> <th scope="col"> Турнир</th> <th scope="col"> Дата</th> <th scope="col"> Счет</th> </tr> </thead> <tbody> <tr th:if="${teamOpponents.isEmpty()}"> <td><span>История соревнований отсутствует.</span></td> </tr> <tr th:each="team_competition : ${teamOpponents}"> <td><a th:href="'/team?teamId=' + ${team_competition.getTeam().getId()}" th:text="${team_competition.getTeam().getName()}"></a></td> <td><a th:href="'/competition?competitionId=' + ${team_competition.getCompetition().getId()}" th:text="${team_competition.getCompetition().getTournament()}"></a></td> <td><span th:text="${team_competition.getCompetition().getComp_date()}"></span></td> <td><span th:text="${team_competition.getCompetition().getScore()}"></span></td> </tr> </tbody> </table> </p> </div> <!--edit delete order button group--> <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups"> <div class="btn-group mr-2" role="group" aria-label="First group"> <form style="margin-right: 30px" method="get" th:action="'/editTeam'"> <input type="hidden" name="teamId" th:value="${team.getId()}"> <button id="editButton" type="submit" class="btn btn-secondary">Редактировать информацию о команде</button> </form> <form method="post" action="/removeTeam"> <input type="hidden" name="teamId" th:value="${team.getId()}"/> <button id="deleteButton" type="submit" class="btn btn-secondary">Удалить команду из базы</button> </form> </div> </div> <!--end of button group--> </div> <div th:replace="general :: site-script"></div> </body> </html>
var express = require('express'); var router = express.Router(); var promocionesModel = require('../../models/promocionesModel'); var util = require('util'); var cloudinary = require('cloudinary').v2; const uploader = util.promisify(cloudinary.uploader.upload); const destroy = util.promisify(cloudinary.uploader.destroy); /* GET home page. */ router.get('/', async function(req, res, next) { var promociones = await promocionesModel.getPromociones(); promociones = promociones.map(promocion => { if (promocion.img_id) { const imagen = cloudinary.image(promocion.img_id, { width:200, height:200, crop:'fill' }); return { ...promocion, imagen } }else { return { ...promocion, imagen: '' } } }); res.render('admin/promociones' , { layout:'admin/layout', usuario: req.session.nombre, promociones }); }); router.get ('/agregar' , (req , res , next) =>{ res.render('admin/agregar', { layout : 'admin/layout' }) }) router.post ('/agregar' , async (req , res , next) =>{ try{ var img_id =''; if(req.files && Object.keys(req.files).length > 0) { imagen = req.files.imagen; img_id = (await uploader(imagen.tempFilePath)).public_id; } if (req.body.titulo != "" & req.body.subtitulo != "" && req.body.cuerpo !=""){ await promocionesModel.insertarPromocion({ ...req.body, img_id }); res.redirect('/admin/promociones') }else { res.render('admin/agregar',{ layout: 'admin/layout', error: true, message: 'Todos los campos son requeridos' }) } }catch (error){ res.render('admin/agregar', { layout: 'admin/layout', error: true, message: 'No se cargó la información' }) } res.render('admin/agregar', { layout : 'admin/layout' }) }) router.get ('/eliminar/:id' , async (req,res,next) =>{ var id = req.params.id; let promocion = await promocionesModel.getPromocionById(id); if(promocion.img_id) { await (destroy(promocion.img_id)) } await promocionesModel.borrarPromocionesById(id); res.redirect('/admin/promociones'); }); router.get ('/editar/:id' , async (req,res,next) =>{ var id = req.params.id; var promocion = await promocionesModel.getPromocionById(id); res.render('admin/editar' , { layout : 'admin/layout', promocion }) }) router.post ('/editar' , async (req,res,next) => { try { let img_id = req.body.img_original ; let borrar_img_anterior = false; if (req.body.img_delete === "1"){ img_id = null; borrar_img_anterior= true; }else { if (req.files && Object.keys(req.files).length > 0){ imagen = req.files.imagen; img_id = (await uploader (imagen.tempFilePath)).public_id; borrar_img_anterior = true; } } if (borrar_img_anterior && req.body.img_original ) { await (destroy(req.body.img_original)); } var obj = { titulo : req.body.titulo, subtitulo :req.body.subtitulo, cuerpo : req.body.cuerpo, img_id } await promocionesModel.editarPromocionById(obj, req.body.id); res.redirect('/admin/promociones'); } catch (error) { res.render ('admin/editar', { layout : 'admin/layout', error : true, message : ' No se editó la promocion' }) } }) module.exports = router;
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Model; use App\Models\Document; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Document> */ class DocumentFactory extends Factory { /** * Define the model's default state. * * @return array<string, mixed> */ public function definition(): array { return [ // ]; } /** * Overloads the create method of Factory * * @param (callable(array<string, mixed>): array<string, mixed>)|array<string, mixed> $attributes * @param \Illuminate\Database\Eloquent\Model|null $parent * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model|TModel>|\Illuminate\Database\Eloquent\Model|TModel */ public function create($attributes = [], ?Model $parent = null) { # Ensure that raw_text is base64 encoded upon creation if (isset($attributes['raw_text'])) { if (base64_encode(base64_decode($attributes['raw_text'], true)) !== $attributes['raw_text']) { $attributes['raw_text'] = base64_encode($attributes['raw_text']); } } return parent::create($attributes, $parent); } }
window.onload = () => { let search = document.getElementById("usernameForm"); search.addEventListener("submit", searchUser); } const searchUser = (event) => { event.preventDefault(); let nameInput = event.target.querySelector("#usernameInput").value; let response; fetch('https://api.github.com/users/' + nameInput) .then(res => res.json())//response type .then(data => { response = data; loadInfo(response); }); } const loadInfo = async (data) => { let profileTable = document.querySelector("#profileTable"); //get references let avatar = profileTable.querySelector("#avatar") let name = profileTable.querySelector("#name"); let username = profileTable.querySelector("#username"); let email = profileTable.querySelector("#email"); let location = profileTable.querySelector("#location"); let gists = profileTable.querySelector("#gists"); avatar.setAttribute("src", validateData(data["avatar_url"])) name.textContent = "Name: " + validateData(data["name"]); username.textContent = "Username: " + validateData(data["login"]); email.textContent = "Email: " + validateData(data["email"]); location.textContent = "Location: " + validateData(data["location"]); gists.textContent = "Number of Gists: " + validateData(data["public_gists"]); let repos; await fetch(data["repos_url"]) .then(res => res.json())//response type .then(data => { repos = data; }); let userRepos = document.querySelector("#userRepos") if(repos.length > 5) { userRepos.style.overflow = "scroll"; userRepos.style.maxHeight = "90vh"; } else { userRepos.style.overflow = "visible"; userRepos.style.maxHeight = "none"; } let reposTable = document.querySelector("#reposTable"); reposTable.firstElementChild.textContent = '' reposTable.firstElementChild.innerHTML = repos.map(repo => { return "<tr><td>" + "<p>Name: " + validateData(repo["name"]) + "</p>" + "<p>Description: " + validateData(repo["description"]) + "</p>" + "</td></tr>" }).join(""); } const validateData = (data) => { if(data === null || data === undefined) { return "" } else { return data; } } const validateInputs = (inputs) => { if(inputs.nameInput === '' || inputs.phoneNoInput === '' || inputs.emailInput === '') { showInputError("fields should not be empty"); return false; } //validate name let onlyLettersAndWhitespace = /[^A-Z ]/gi; if(onlyLettersAndWhitespace.test(inputs.nameInput)) { showInputError("name should contain only Alphabets and Space"); return false; } if(inputs.nameInput.length > 20) { showInputError("name should be less than or equal to 20 characters in length"); return false; } //validate mobile number let onlyNumbers = /[^0-9]/gi; if(onlyNumbers.test(inputs.phoneNoInput)) { showInputError("phone number should contain only numbers"); return false; } if(inputs.phoneNoInput.length !== 10) { showInputError("phone number should be 10 digits in length"); return false; } //validate email let emailRegExp = /^((?!\.)[\w-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/gim; if(!emailRegExp.test(inputs.emailInput)) { showInputError("incorrect email format") return false; } if(inputs.emailInput.length >= 40) { showInputError("email should be less than 40 characters in length"); return false; } return true } const showInputError = (text) => { let error = document.getElementById("error").firstElementChild; error.innerHTML = "Error: " + text; } let sorted = false; const sortTableByName = (event) => { let contacts = tableToArray(); const compareByName = (a, b) => { return a.nameInput.localeCompare(b.nameInput) } sorted ? contacts.reverse() : contacts.sort(compareByName); sorted = !sorted; loadTable(contacts); } const filterTableByPhoneNo = (event) => { let searchInput = event.target.value; let contacts = sessionStorage.getItem("contacts"); contacts = JSON.parse(contacts); console.log(searchInput); console.log(contacts) let filtered = contacts.filter(contact => { return contact.phoneNoInput.includes(searchInput); }) filtered.length === 0 ? showNoResult() : hideNoResult(); loadTable(filtered); } const tableToArray = () => { let contacts = []; document .querySelectorAll("tbody tr") .forEach(tr => { let contact = {nameInput: '', phoneNoInput: '', emailInput: ''}; tr.childNodes.forEach( td => { switch (td.cellIndex) { case 0: { contact.nameInput = td.innerText; return; } case 1: { contact.phoneNoInput = td.innerText; return; } case 2: { contact.emailInput = td.innerText; contacts.push(contact); return; } } }) }); return contacts; }
using BindOpen.Kernel.Data; using BindOpen.Kernel.Logging.Tests; using NUnit.Framework; using System.IO; using System.Linq; namespace BindOpen.Kernel.Logging { [TestFixture, Order(400)] public class IOTests { private readonly string _filePath_xml = GlobalVariables.WorkingFolder + "Log.xml"; private readonly string _filePath_json = GlobalVariables.WorkingFolder + "Log.json"; private IBdoCompleteLog _log = null; private dynamic _testData; [OneTimeSetUp] public void OneTimeSetUp() { _testData = new { itemNumber = 1000 }; } private void Test(IBdoCompleteLog log) { Assert.That(log.Errors(false).Count() == _testData.itemNumber, string.Format("Bad insertion of errors ({0} expected; {1} found)", _testData.itemNumber, _log.Errors().Count())); Assert.That(log.Exceptions().Count() == _testData.itemNumber, string.Format("Bad insertion of exceptions ({0} expected; {1} found)", _testData.itemNumber, _log.Exceptions().Count())); Assert.That(log.Messages().Count() == _testData.itemNumber, string.Format("Bad insertion of messages ({0} expected; {1} found)", _testData.itemNumber, _log.Messages().Count())); Assert.That(log.Warnings().Count() == _testData.itemNumber, string.Format("Bad insertion of warnings ({0} expected; {1} found)", _testData.itemNumber, _log.Warnings().Count())); Assert.That(log.Children().Count() == _testData.itemNumber, string.Format("Bad insertion of sub logs ({0} expected; {1} found)", _testData.itemNumber, _log.Children().Count())); } [Test, Order(1)] public void CreateTest() { _log = BdoLogging.NewLog() .WithDetail( BdoData.NewMeta("string", DataValueTypes.Text, "stringValue"), BdoData.NewMeta("int", DataValueTypes.Integer, 1500) ); for (int i = 0; i < _testData.itemNumber; i++) { _log.AddError("Error" + i); _log.AddException("Exception" + i); _log.AddMessage("Message" + i); _log.AddWarning("Warning" + i); _log.AddChild(BdoLogging.NewLog() .WithTitle("Child" + i) .AddError("Child_Error" + i + "_1") ); } Test(_log); } // Xml [Test, Order(2)] public void SaveXmlTest() { if (_log == null) { CreateTest(); } var log = BdoLogging.NewLog(); _log.ToDto()?.SaveXml(_filePath_xml, log); string xml = string.Empty; if (log.HasErrorsOrExceptions()) { xml = ". Result was '" + log.ToDto().ToXml() + "'"; } Assert.That(!log.HasErrorsOrExceptions(), "Log saving failed" + xml); } [Test, Order(3)] public void LoadXmlTest() { if (_log == null || !File.Exists(_filePath_xml)) { SaveXmlTest(); } BdoLog log = BdoLogging.NewLog(); _log = XmlHelper.LoadXml<LogDto>(_filePath_xml, log: log).ToPoco(); string xml = string.Empty; if (log.HasErrorsOrExceptions()) { xml = ". Result was '" + log.ToDto().ToXml() + "'"; } Assert.That(_log.HasErrorsOrExceptions(), "Error while loading log" + xml); Test(_log); } // Json [Test, Order(2)] public void SaveJsonTest() { if (_log == null) { CreateTest(); } var log = BdoLogging.NewLog(); _log.ToDto()?.SaveJson(_filePath_json, log); string xml = string.Empty; if (log.HasErrorsOrExceptions()) { xml = ". Result was '" + log.ToDto().ToJson() + "'"; } Assert.That(!log.HasErrorsOrExceptions(), "Log saving failed" + xml); } [Test, Order(3)] public void LoadJsonTest() { if (_log == null || !File.Exists(_filePath_json)) { SaveJsonTest(); } BdoLog log = BdoLogging.NewLog(); _log = JsonHelper.LoadJson<LogDto>(_filePath_json, log: log).ToPoco(); string xml = string.Empty; if (log.HasErrorsOrExceptions()) { xml = ". Result was '" + log.ToDto().ToJson() + "'"; } Assert.That(_log.HasErrorsOrExceptions(), "Error while loading log" + xml); Test(_log); } } }
package com.zimbra.cs.service.util; import com.zimbra.common.util.StringUtil; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; /** * Utility class for parsing Content-Disposition headers following RFC-6266 specifications. This * class provides methods to extract filenames from Content-Disposition header values. */ public class ContentDispositionParser { /** Private constructor to prevent instantiation. This class should be used as a utility class. */ private ContentDispositionParser() {} /** * RFC-6266 compliant filename extraction helper method. Returns the filename from the given * Content-Disposition header value following RFC-6266 specifications. Preference to the extended * version of the filename {@code filename*=UTF-8''utf8EncodedFile} is given. If the extended * filename is not specified in the content-disposition header, then the ASCII valued filename is * returned. If that is also not specified, an empty string is returned. * * @param contentDisposition A {@link String} value of the Content-Disposition header. * @return The filename from the given Content-Disposition header or an empty string if not found. */ public static String getFileNameFromContentDisposition(final String contentDisposition) { String fileName = ""; if (!StringUtil.isNullOrEmpty(contentDisposition)) { final String dispositionItemsDelimiter = ";"; for (String dispositionItem : contentDisposition.split(dispositionItemsDelimiter)) { fileName = getAsciiFileNameFromDispositionItem(fileName, dispositionItem); fileName = getExtendedFilenameFromDispositionItem(fileName, dispositionItem); } } return fileName; } /** * Returns the filename from the given disposition item. * * @param defaultValue The fallback filename if the filename is not specified in the disposition * item. * @param dispositionItem The disposition item. * @return The filename. */ private static String getAsciiFileNameFromDispositionItem( final String defaultValue, final String dispositionItem) { String newFileName = defaultValue; if (dispositionItem.trim().toLowerCase().startsWith("filename=")) { final String[] keyValue = dispositionItem.split("="); if (keyValue.length >= 2) { newFileName = keyValue[1].trim().replace("\"", ""); } } return newFileName; } /** * Returns the extended filename from the given disposition item. * * @param defaultValue The fallback filename if the filename is not specified in the disposition * item. * @param dispositionItem The disposition item. * @return The filename. */ private static String getExtendedFilenameFromDispositionItem( final String defaultValue, final String dispositionItem) { String newFileName = defaultValue; if (dispositionItem.trim().toLowerCase().startsWith("filename*=")) { final String[] keyValue = dispositionItem.split("="); final String value = keyValue[1].trim(); final String delimiter = "utf-8''"; if (value.toLowerCase().startsWith(delimiter)) { newFileName = URLDecoder.decode(value.substring(delimiter.length()), StandardCharsets.UTF_8); } } return newFileName; } }
<template lang="pug"> .applications TableDisplaySettings( :sort_select_items="sort_select_items" @input_search="onSearchInput( { $event } )" @sort_select_change="handlers().onSortSelectChange( { $event } )" ) .table-applications .table-list-style v-data-table( :headers="headers" :items="tasks" class="applications-table" item-key="uuid" :item-class="rowClass" show-select hide-default-footer hide-default-header ) template( v-slot:item.name="{ item }" ) div span.request-i span( class="color-black" ) {{ item.name }} template( v-slot:item.payment="{ item }" ) v-tooltip( v-if="!item.payment.value" top color="#E4F1FA" ) template( v-slot:activator="{ on, attrs }" ) .payment( v-bind="attrs" v-on="on" ) .wrapper span.value {{ `${ item.payment.value || '0' } р. / смена` }} span.tooltip-text Табель не заполнен .payment( v-else v-bind="attrs" v-on="on" ) .wrapper span.value {{ `${ item.payment.value || '0' } р. / смена` }} template( v-slot:item.object="{ item }" ) {{ item.object.name }} template( v-slot:item.date="{ item }" ) {{ helpers().parseDate( { date : item.created_at } ) }} template( v-slot:item.actions="{ item }" ) div( class="d-flex justify-end" ) v-menu( bottom rounded="10" offset-y nudge-bottom="10" ) template( v-slot:activator="{ on }" ) v-btn.icon( v-on="on" class="mix-edit-btn" ) v-icon mdi-dots-vertical v-card v-list-item-content( class="justify-start" ) div( class="mx-auto text-left" ) nuxt-link( :to="'/tasks/'+ item.uuid +'/edit/'" ) span Редактировать </template> <script> import { mapState, mapActions, mapGetters, mapMutations } from 'vuex'; import { CONTRACTOR, EMPLOYEE } from '@/constants/'; import _ from 'lodash'; export default { components : {}, props : { user_type : { type : String, required : true, }, }, computed : { ...mapGetters( 'contractors', [ 'contractor', ] ), tasks () { switch ( this.user_type ) { case CONTRACTOR : return this.$store.getters[ 'contractors/contractorTasks' ]; case EMPLOYEE : return this.$store.getters[ 'employee_id/employee_id_tasks' ]; default : return {}; } }, }, data () { return { headers : [ {text: 'name', value: 'name', width: '16px'}, {text: 'payment', value: 'payment'}, {text: 'object', value: 'object'}, {text: 'date', value: 'date', }, {text: 'actions', value: 'actions', sortable: false}, ], sort_select_items : [ { uuid : 'uuid_date_up', name : 'Дата по возрастанию', sort : 'asc', order : 'created_at', }, { uuid : 'uuid_date_down', name : 'Дата по убыванию', sort : 'desc', order : 'created_at', }, // { // uuid : 'uuid_payment_up', // name : 'Цена по возрастанию', // sort : 'asc', // order : 'payment', // }, // { // uuid : 'uuid_payment_down', // name : 'Цена по убыванию', // sort : 'desc', // order : 'payment', // }, ], searchParams : {}, } }, methods : { ...mapActions( 'contractors', [ 'getContractorTasks' ] ), getters () { return {} }, setters () { return {} }, handlers () { return { onSortSelectChange : ( payload = {} ) => { let selectedOption = this.sort_select_items.find( item => item.uuid === payload.$event ); console.log( "onSortSelectChange", payload, selectedOption ); // DELETE switch ( this.user_type ) { case CONTRACTOR : this.searchParams = { ...this.searchParams, order : selectedOption.order, sort : selectedOption[ 'sort' ], } this.getContractorTasks( { uuid : this.contractor.uuid, params : this.searchParams, } ); break; case EMPLOYEE : break; } }, } }, helpers () { return { /** * * @param { object } params * { * date : '2021-12-23T12:59:03.000000Z' * } */ parseDate : ( payload = {} ) => { let splitedPayloadDate = payload.date.split( 'T' ); let date = splitedPayloadDate[ 0 ].split( '-' ); let time = splitedPayloadDate[ 1 ].split( '.' )[ 0 ].split( ':' ); let result = `${ date[ 2 ] }.${ date[ 1 ] }.${ date[ 0 ] } ${ time[ 0 ] }:${ time[ 1 ] }`; return result; }, } }, init (){}, bindActions (){}, rowClass( item ) { const rowClass = 'applications-row'; return rowClass;; }, onSearchInput : _.debounce( function( payload = {} ) { console.log( "onSearchInput", payload ); // DELETE switch ( this.user_type ) { case CONTRACTOR : this.searchParams = { ...this.searchParams, search : payload.$event, } this.getContractorTasks( { uuid : this.contractor.uuid, params : this.searchParams, } ); break; case EMPLOYEE : break; } }, 400 ), } } </script> <style lang="scss"> /* OBJECTS STYLES START */ .applications-table { background-color : unset !important; .v-data-table__empty-wrapper { background-color : #FFFFFF; } .applications-row { background-color : #FFFFFF !important; .color-black { position : relative; } } } .payment { display : flex; flex-direction : row; flex-wrap : nowrap; align-content : center; justify-content : center; align-items : center; background : #E4F1FA; border-radius : 6px; padding : 7px 8px; .wrapper { display : flex; flex-direction : column; flex-wrap : nowrap; align-content : center; justify-content : center; align-items : center; .value { font-style : normal; font-weight : bold; font-size : 14px; line-height : 125%; letter-spacing : 0.01em; color : #0082DE; white-space : nowrap; } } } .tooltip-text { font-style: normal; font-weight: bold; font-size: 14px; line-height: 125%; letter-spacing: 0.01em; color: #0082DE; white-space: nowrap; } /* OBJECTS STYLES END */ </style>
import { useEffect, useState } from 'react' import { KTSVG } from '../../../../_metronic/helpers' import { useForm } from "react-hook-form"; import { yupResolver } from "@hookform/resolvers/yup"; import * as yup from "yup"; import { ContributorModel, UpdateRoleContributorMutation, optionsRoles } from '../core/_models'; import { SelectValueNameInput } from '../../utils/forms/SelectValueNameInput'; import { AlertDangerNotification, AlertSuccessNotification, capitalizeFirstLetter } from '../../utils'; interface Props { setOpenModal: any, contributor: ContributorModel | any } const schema = yup .object({ role: yup.string().required(), }) .required(); export const ContributorUpdateFormModal: React.FC<Props> = ({ setOpenModal, contributor }) => { const [loading, setLoading] = useState(false) const [hasErrors, setHasErrors] = useState<boolean | string | undefined>(undefined) const { register, handleSubmit, setValue, formState: { errors, isSubmitted, isDirty, isValid } } = useForm<any>({ resolver: yupResolver(schema), mode: "onChange" }); useEffect(() => { if (contributor) { const fields = ['role']; fields?.forEach((field: any) => setValue(field, contributor[field]?.name)); } }, [contributor,setValue]); const saveMutation = UpdateRoleContributorMutation({ onSuccess: () => { setOpenModal(false) setHasErrors(false); setLoading(false) }, }); const onSubmit = async (data: any) => { setLoading(true); setHasErrors(undefined) try { await saveMutation.mutateAsync({ ...data, contributorId: String(contributor?.id) }) AlertSuccessNotification({ text: 'Role update successfully', className: 'info', position: 'center', }) } catch (error: any) { AlertDangerNotification({ text: `${error?.response?.data?.message}`, className: 'info', position: 'center' }) } }; return ( <> <div className='modal fade show d-block' id='kt_modal_1' role='dialog' tabIndex={-1} aria-modal='true' > {/* begin::Modal dialog */} <div className='modal-dialog modal-dialog-centered mw-600px'> {/* begin::Modal content */} <div className='modal-content'> <div className="modal-header pb-0 border-0 justify-content-end"> <div onClick={() => { setOpenModal(false) }} className="btn btn-icon btn-sm btn-active-light-primary ms-2" data-bs-dismiss="modal"> <KTSVG path="/media/icons/duotune/arrows/arr061.svg" className="svg-icon svg-icon-2x" /> </div> </div> <form className="form fv-plugins-bootstrap5 fv-plugins-framework" onSubmit={handleSubmit(onSubmit)}> {/* begin::Modal body */} <div className='mx-5 mx-xl-15 my-7'> <div className="d-flex flex-stack py-4 border-bottom border-gray-300 border-bottom-dashed"> <div className="d-flex align-items-center"> {contributor?.profile?.image ? <div className="symbol symbol-35px symbol-circle"> <img src={contributor?.profile?.image} alt={`${contributor?.profile?.firstName} ${contributor?.profile?.lastName}`} className="symbol symbol-35px symbol-circle" /> </div> : <div className="symbol symbol-35px symbol-circle" title={`${contributor?.profile?.firstName} ${contributor?.profile?.lastName}`}> <span className={`symbol-label fw-bold bg-light-${contributor?.profile?.color} text-${contributor?.profile?.color}`}> {capitalizeFirstLetter(String(contributor?.profile?.lastName), String(contributor?.profile?.firstName))} </span> </div> } <div className="ms-5"> <a href={void (0)} className="fs-5 fw-bold text-gray-900 text-hover-primary mb-2"> {contributor?.profile?.lastName} {contributor?.profile?.firstName} </a> <div className="fw-semibold text-muted">{contributor?.profile?.email}</div> </div> </div> </div> </div> <div className='mx-5 mx-xl-15 my-7'> <div className="fv-row fv-plugins-icon-container"> <SelectValueNameInput dataItem={optionsRoles} className="form-control" labelFlex="Role" register={register} errors={errors} inputName="role" validation={{ required: true }} isRequired={true} isValueInt={false} required="required" /> </div> </div> {/* end::Modal body */} <div className="modal-footer flex-center"> <button type="button" onClick={() => { setOpenModal(false) }} className="btn btn-light me-3">Cancel</button> <button type='submit' className='btn btn-lg btn-primary fw-bolder' disabled={loading || !isDirty || !isValid || isSubmitted} > {!loading && <span className='indicator-label'>Submit</span>} {loading && ( <span className='indicator-progress' style={{ display: 'block' }}> Please wait... <span className='spinner-border spinner-border-sm align-middle ms-2'></span> </span> )} </button> </div> </form> </div> {/* end::Modal content */} </div> {/* end::Modal dialog */} </div> {/* begin::Modal Backdrop */} <div className='modal-backdrop fade show'></div> {/* end::Modal Backdrop */} </> ) }
import { FC, useState } from 'react' import classes from './Layout.module.scss' import editBtn from '../../assets/icons/edit.svg' import ToggleIcon from '../../assets/icons/nav-toggle.svg' import quitBtn from '../../assets/icons/quit.svg' import SettingsIcon from '../../assets/icons/settings.svg' import testAvatar from '../../assets/icons/test-avatar.png' import clsx from 'clsx' import { Route, Routes } from 'react-router-dom' import { ExtendedUser } from '../../App' import Navigation from '../../components/navigation/Navigation' import HabitsPage from '../../pages/habits/Habits' import NotesPage from '../../pages/notes/Notes' import NotePage from '../../pages/notes/components/note/Note' import ProjectsPage from '../../pages/projects/Projects' import ProjectPage from '../../pages/projects/components/project/Project' import TimerPage from '../../pages/timer/Timer' import TimerSettings from '../../pages/timer/components/timer-settings/TimerSettings' import { logoutUser } from '../../services/logoutService' import Modal from '../modal/Modal' interface ILayoutProps { user: ExtendedUser } const Layout: FC<ILayoutProps> = ({ user }) => { const [isNavigationVisible, setIsNavigationVisible] = useState(true) const [isSettingsModalOpened, setIsSettingsModalOpened] = useState(false) function toggleNavigationVisibility() { setIsNavigationVisible(prev => !prev) } function toggleModalVisibility() { setIsSettingsModalOpened(true) } return ( <div className={classes.layout}> <aside className={clsx(classes.sidebar, !isNavigationVisible && 'hidden')} > <img className={classes.logo} src='/logo.png' alt='logo' /> <Navigation /> <img className={classes.brain} src='/brain.svg' alt='brain image' /> </aside> <Routes> <Route path='/' element={<NotesPage />} /> <Route path='/note/:noteId' element={<NotePage />} /> <Route path='/habits' element={<HabitsPage />} /> <Route path='/timer' element={<TimerPage />} /> <Route path='/timer/settings' element={<TimerSettings />} /> <Route path='/projects' element={<ProjectsPage />} /> <Route path='/project/:id' element={<ProjectPage />} /> </Routes> <button className={clsx(classes.toggleButton, !isNavigationVisible && 'closed')} onClick={toggleNavigationVisibility} > <img src={ToggleIcon} alt='toggle navigation visibility' /> </button> <button className={classes.settingsButton} onClick={toggleModalVisibility} > <img src={SettingsIcon} alt='settings' /> </button> {isSettingsModalOpened && ( <Modal setIsSettingsModalOpened={setIsSettingsModalOpened} isSettingsModalOpened={isSettingsModalOpened} > <div className={classes.modalBody} onClick={e => e.stopPropagation()}> <button className={classes.quitButton}> <img src={quitBtn} alt='quit button' onClick={() => logoutUser()} /> </button> <img className={classes.avatar} src={testAvatar} alt='avatar' /> <div className={classes.userName}> <h6>{user.name}</h6> <button className={classes.editBtn}> <img src={editBtn} alt='edit button' /> </button> </div> <div className={classes.userEmail}> <a href='mailto:[email protected]'>{user.email}</a> <button className={classes.editBtn}> <img src={editBtn} alt='edit button' /> </button> </div> <div className={classes.themeButtons}> <button className={classes.themeLightButton}>Light</button> <button className={classes.themeDarkButton}>Dark</button> </div> <a className={classes.projectLink} href='#'> Link to project's github </a> </div> </Modal> )} </div> ) } export default Layout
@extends('layout') @section('metaTitle', 'Key areas') @section('metaDesc', preg_replace( "/\r|\n/", "", strip_tags('TEKTELIC is a premier provider of Best-in-Class IoT Gateways and Devices. Utilizing the LoRaWAN® technology, TEKTELIC prides itself on building hardware designed for Carrier-Grade performance, reliability, scalability.') )) @section('content') <div class="page-header"> <div class="container"> {{ Breadcrumbs::render('key-areas') }} <div class="page-headings"> @if(isset($heading) && !empty($heading->title)) <h1 class="page-title">{{$heading->title}}</h1> @else <h1 class="page-title"><?= \App\Models\StaticTextLang::t("Key areas",'key_area'); ?></h1> @endif </div> </div> </div> <div class="page-body"> <div class="container"> <div class="keyareas-list"> @foreach ($key_areas as $key_area) <div class="keyareas-list-item" data-aos="fade-up" data-aos-duration="1000" data-aos-delay="50"> <article class="keyarea-card-article"> <a class="keyarea-card-image" href="{{url('key-areas',['slug' => $key_area->slug])}}"> <svg class="keyarea-card-placeholder" width="340" height="207" viewBox="0 0 340 207" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect width="340" height="207" fill="none"/> </svg> <img class="image" src="{{asset(\App\Helpers\Helper::getImgSrc($key_area->keyArea->image))}}" alt="{{ $key_area->alt }}" title="{{ $key_area->pic_title }}"/> </a> <div class="keyarea-card-content"> <a class="keyarea-card-inner" href="{{url('key-areas',['slug' => $key_area->slug])}}"> <h2 class="keyarea-card-title">{{ $key_area->title }}</h2> <div class="keyarea-card-excerpt">{!! \Illuminate\Support\Str::limit(strip_tags($key_area->text), 230, $end='') !!}</div> <span class="learn-more-link"><span><?= \App\Models\StaticTextLang::t("Click to learn more",'key_area'); ?></span></span> </a> </div> </article> </div> @endforeach </div> </div> </div> @include('layouts.contact-us', ['entity' => $seo_block]) @endsection @section('footer') @endsection()
<?php namespace App\Http\Controllers\Assets; use App\DataTransferObjects\Assets\AssetData; use App\Excels\Assets\Asset as AssetsAsset; use App\Helpers\CarbonHelper; use App\Helpers\Helper; use App\Http\Controllers\Controller; use App\Http\Requests\Assets\AssetRequest; use App\Http\Requests\Assets\ImportRequest; use App\Imports\Assets\AssetImport; use App\Models\Assets\Asset; use App\Models\Masters\Lifetime; use App\Services\Assets\AssetDepreciationService; use App\Services\Assets\AssetService; use App\Services\GlobalService; use App\Services\Masters\ActivityService; use App\Services\Masters\ConditionService; use App\Services\Masters\LeasingService; use App\Services\Masters\LifetimeService; use App\Services\Masters\SubClusterService; use App\Services\Masters\UnitService; use App\Services\Masters\UomService; use Illuminate\Http\Request; use Illuminate\Support\Facades\Bus; use Maatwebsite\Excel\Facades\Excel; use Yajra\DataTables\Facades\DataTables; class AssetMasterController extends Controller { public function __construct( private AssetService $service, private AssetDepreciationService $assetDepreciationService, ) { } public function index() { // dd($this->service->allNotElastic()->first()); return view('assets.asset.index', [ 'uoms' => UomService::dataForSelect(), 'subClusters' => SubClusterService::dataForSelect(), 'units' => UnitService::dataForSelect(), 'lifetimes' => LifetimeService::dataForSelect(), 'activities' => ActivityService::dataForSelect(), 'conditions' => ConditionService::dataForSelect(), 'dealers' => GlobalService::vendorForSelect(), 'leasings' => LeasingService::dataForSelect(), 'projects' => GlobalService::getProjects(), 'employees' => GlobalService::getEmployees(['nik', 'nama_karyawan'])->toCollection() ]); } public function datatablePG(Request $request) { return DataTables::collection($this->service->allNotElastic()) ->editColumn('kode', function ($asset) { return $asset->kode; }) ->editColumn('kode_unit', function ($asset) { return $asset->assetUnit?->kode; }) ->editColumn('unit_model', function ($asset) { return $asset->assetUnit?->unit?->model; }) ->editColumn('unit_type', function ($asset) { return $asset->assetUnit?->type; }) ->editColumn('asset_location', function ($asset) { return $asset->project?->project; }) ->editColumn('pic', function ($asset) { return $asset->employee?->nama_karyawan ?? $asset->pic; }) ->editColumn('action', function ($asset) { $key = $asset->getKey(); $kode = $asset->kode; return view('assets.asset.action', compact('key', 'kode'))->render(); }) ->rawColumns(['action']) ->make(); } public function datatable(Request $request) { return DataTables::collection($this->service->all($request->get('search'))) ->editColumn('kode', function ($asset) { return $asset->_source->kode; }) ->editColumn('kode_unit', function ($asset) { return $asset->_source->asset_unit?->kode; }) ->editColumn('unit_model', function ($asset) { return $asset->_source->asset_unit?->unit?->model; }) ->editColumn('unit_type', function ($asset) { return $asset->_source->asset_unit?->type; }) ->editColumn('asset_location', function ($asset) { return $asset->_source->project?->project; }) ->editColumn('pic', function ($asset) { return $asset->_source->employee?->nama_karyawan ?? $asset->_source->pic; }) ->editColumn('action', function ($asset) { $key = $asset->_source->id; $kode = $asset->_source->kode; return view('assets.asset.action', compact('key', 'kode'))->render(); }) ->rawColumns(['action']) ->make(); } public function show($kode) { return view('assets.asset.show', [ 'asset' => AssetData::from($this->service->getByKode($kode)), ]); } public function showScan($kode) { return view('assets.asset.show-scan', [ 'asset' => AssetData::from($this->service->getByKode($kode)), ]); } public function store(AssetRequest $request) { try { $this->service->updateOrCreate($request); return response()->json([ 'message' => 'Berhasil disimpan' ]); } catch (\Throwable $th) { throw $th; } } public function edit($id) { try { return response()->json($this->service->getDataForEdit($id)); } catch (\Throwable $th) { throw $th; } } public function destroy(Asset $asset) { try { $this->service->delete($asset); return response()->json([ 'message' => 'Berhasil dihapus' ]); } catch (\Throwable $th) { throw $th; } } public function import(ImportRequest $request) { try { $results = Excel::toArray(new AssetImport, $request->file('file')); $batch = $this->service->import(isset($results[0]) ? $results[0] : []); return response()->json($batch); } catch (\Throwable $th) { throw $th; } } public function batch(Request $request) { try { $batch = Bus::findBatch($request->id); return $batch; } catch (\Throwable $th) { throw $th; } } public function bulk() { try { return $this->service->startBulk(); } catch (\Throwable $th) { throw $th; } } public function format() { return response()->download((new AssetsAsset)->generate()); } public function depreciation(Request $request) { try { $lifetime_id = $request->get('lifetime_id'); $price = $request->get('price'); $nilaiSisa = $request->get('nilai_sisa'); $date = $request->get('date'); if (!$lifetime_id || !$price || !$date) { return response()->json([]); } $request->validate([ 'date' => ['date'], ]); $lifetime = Lifetime::query()->find($lifetime_id); $depresiasi = $this->assetDepreciationService->generate($lifetime?->masa_pakai, CarbonHelper::convertDate($date), Helper::resetRupiah($price), Helper::resetRupiah($nilaiSisa)); return response()->json($depresiasi); } catch (\Throwable $th) { throw $th; } } public function nextIdAssetUnit($id) { try { return response()->json([ 'id' => $this->service->nextIdAssetUnitById($id) ]); } catch (\Throwable $th) { throw $th; } } }
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; class LocalMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $local = null; if(Auth::check() && !Session::has('locale')) { $local = $request->user()->local; Session::put('locale',$local); } if($request->has('local')) { $local = $request->get('local'); Session::put('locale',$local); } $local = Session::get('locale'); if($local === null)$local = config('app.fallback_locale'); App::setLocale($local); return $next($request); } }
from synthesizer.preprocess import preprocess_dataset from synthesizer.hparams import hparams from utils.argutils import print_args from pathlib import Path import argparse if __name__ == "__main__": parser = argparse.ArgumentParser( description="Procesa archivos de audio de conjuntos de datos, los codifica como espectrogramas mel " "y los escribe en el disco. Los archivos de audio también se guardan para ser utilizados por el " "vocoder durante el entrenamiento.", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("datasets_root", type=Path, help=\ "Ruta al directorio que contiene tus conjuntos de datos de LibriSpeech/TTS.") parser.add_argument("-o", "--out_dir", type=Path, default=argparse.SUPPRESS, help=\ "Ruta al directorio de salida que contendrá los espectrogramas mel, los archivos de audio y los " "incrustados. Por defecto, es <datasets_root>/SV2TTS/synthesizer/") parser.add_argument("-n", "--n_processes", type=int, default=None, help=\ "Número de procesos en paralelo.") parser.add_argument("-s", "--skip_existing", action="store_true", help=\ "Si se deben sobrescribir los archivos existentes con el mismo nombre. Útil si la preprocesamiento fue " "interrumpido.") parser.add_argument("--hparams", type=str, default="", help=\ "Anulaciones de hiperparámetros como una lista de pares de nombre y valor separados por comas") parser.add_argument("--no_trim", action="store_true", help=\ "Procesar audio sin recortar silencios (no recomendado).") parser.add_argument("--no_alignments", action="store_true", help=\ "Usar esta opción cuando el conjunto de datos no incluye alineaciones " "(se utilizan para dividir archivos de audio largos en subutterancias).") parser.add_argument("--datasets_name", type=str, default="/home/oscar/Documents/AudioCloning/VoiceCloneNet/Wav", help=\ "Nombre del directorio del conjunto de datos a procesar.") parser.add_argument("--subfolders", type=str, default="train-clean-100, train-clean-360", help=\ "Lista de subdirectorios separados por comas para procesar dentro del directorio de tu conjunto de datos.") args = parser.parse_args() # Procesar los argumentos if not hasattr(args, "out_dir"): args.out_dir = args.datasets_root.joinpath("SV2TTS", "synthesizer") # Crear directorios assert args.datasets_root.exists() args.out_dir.mkdir(exist_ok=True, parents=True) # Verificar la disponibilidad de webrtcvad if not args.no_trim: try: import webrtcvad except: raise ModuleNotFoundError("Paquete 'webrtcvad' no encontrado. Este paquete permite " "la eliminación de ruido y es recomendado. Por favor, instálalo e intenta de nuevo. Si la instalación falla, " "usa --no_trim para deshabilitar este mensaje de error.") del args.no_trim # Preprocesar el conjunto de datos print_args(args, parser) args.hparams = hparams.parse(args.hparams) preprocess_dataset(**vars(args))
import { Router, Response, Request } from 'express'; import { PrismaClient } from '@prisma/client'; const router = Router(); const prisma = new PrismaClient(); //GET /test/add/[address] router.get('/add/:address', (req: Request, res: Response) => { createUser(req.params.address) .then((result) => { res.json({ msg: 'success' }); }) .catch((error) => { if (error.code === 'P2002') { res.json({ msg: 'unique constraint' }); } else { res.json({ msg: 'add: error' }); } }); }); // GET /test/userList router.get('/userList', (req: Request, res: Response) => { allUsers() .then((result) => { res.json(result); }) .catch(() => { res.json({ msg: 'userList: error' }); }); }); // GET /test/user/[id] router.get('/user/:id', (req: Request, res: Response) => { findUser(req.params.id) .then((result) => { res.json(result); }) .catch((error) => { res.json({ msg: 'list: error' }); }); }); // POST /test/update router.post('/update', (req: Request, res: Response) => { updateUserName(req.body) .then((result) => { res.json({ msg: 'update: success' }); }) .catch((error) => { res.json({ msg: 'update: error' }); }); }); //GET /test/delete router.get('/delete', (req: Request, res: Response) => { deletePost() .then((result) => { res.json({ msg: 'delete: success' }); }) .catch((error) => { res.json({ msg: 'delete: error' }); }); }); const createUser = async (address: string) => { const cUser = await prisma.user.create({ data: { name: 'tester', email: address, posts: { create: { title: 'Hello World' }, }, profile: { create: { bio: 'prisma' }, }, }, }); return cUser; }; const allUsers = async () => { const allUsers = await prisma.user.findMany({ //include: 関連するレコードを含める include: { posts: true, profile: true, }, }); return allUsers; }; const findUser = async (userId: string) => { if (isNaN(parseInt(userId))) return; const user = await prisma.user.findUnique({ where: { id: Number(userId), }, include: { posts: true, profile: true, }, }); return user; }; const updateUserName = async (param: test) => { const result = await prisma.user.update({ where: { id: param.id, }, data: { name: param.newName, }, }); return result; }; const deletePost = async () => { //delete all const del = await prisma.post.deleteMany({}); /* const del = await prisma.post.deleteMany({ where: { title: { contains: 'Hello World', }, }, }); */ return del; }; type test = { id: number; newName: string; }; export default router;
package com.example.zelda.scene; import com.example.zelda.engine.GObject; import com.example.zelda.engine.Game; import com.example.zelda.engine.Scene; import com.example.zelda.items.GuiHeart; import com.example.zelda.items.GuiRupee; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.Rectangle; import java.util.ArrayList; /** * A specialised Scene object for the Zelda game. * * @author maartenhus */ public abstract class ZeldaScene extends Scene { protected final ArrayList<Rectangle> exits = new ArrayList<>(); private boolean adjust = false; private final int xSensitivity; private final int ySensitivity; public ZeldaScene(Game game, String img, String sceneName) { super(game, img, sceneName); xSensitivity = game.getWidth() / 2; ySensitivity = game.getHeight() / 2; sprite.setSprite(new Rectangle(0, 0, game.getWidth(), game.getHeight())); GuiHeart.clear(); for (int i = 0; i < 5; i++) { var heart = new GuiHeart(game, (game.getWidth() - 130) + i * 12, 50); gameObjects.add(heart); } var rupee = new GuiRupee(game, 100, game.getHeight() / 11); gameObjects.add(rupee); } @Override public void handleInput() { super.handleInput(); checkLinkIsInExit(); if (game.getLink().moveInput()) { adjust = true; } if (adjust) { var stateString = game.getLink().getStateString(); if (!stateString.equals("SwordState") && !stateString.equals("BowState")) { adjustScene(game.getLink().getX(), game.getLink().getY()); } } inputHook(); } public void inputHook() { } private void checkLinkIsInExit() { for (Rectangle exit : exits) { if (exit.intersects(game.getLink().getRectangle())) { handleSwitchScene(exit); } } } public void adjustScene(int moveToX, int moveToY) { int mod = MOD; if (moveToX > (sprite.getWidth() - xSensitivity)) { int newX = sprite.getX() + mod; if ((newX + sprite.getWidth()) <= sprite.getImageWidth()) { game.getLink().setX(game.getLink().getX() - mod); modShapes(-mod, 0); sprite.setX(newX); } } if (moveToX < xSensitivity) { int newX = sprite.getX() - mod; if (newX > 0) { game.getLink().setX(game.getLink().getX() + mod); modShapes(mod, 0); sprite.setX(newX); } } if (moveToY > (sprite.getHeight() - ySensitivity)) { int newY = sprite.getY() + mod; if ((newY + sprite.getHeight()) <= sprite.getImageHeight()) { game.getLink().setY(game.getLink().getY() - mod); modShapes(0, -mod); sprite.setY(newY); } } if (moveToY < ySensitivity) { int newY = sprite.getY() - mod; if (newY > 0) { game.getLink().setY(game.getLink().getY() + mod); modShapes(0, mod); sprite.setY(newY); } } } @Override public void modShapes(int modX, int modY) { for (Polygon poly : solids) { poly.translate(modX, modY); } for (Rectangle rect : exits) { rect.translate(modX, modY); } for (GObject obj : gameObjects) { if (obj.isScreenAdjust()) { obj.setXHardCore(obj.getX() + modX); obj.setYHardCore(obj.getY() + modY); } } } @Override public void draw(Graphics2D g2) { super.draw(g2); g2.setColor(Color.white); var f = new Font("Serif", Font.BOLD, 12); g2.setFont(f); g2.drawString("-- LIFE --", game.getWidth() - 122, game.getHeight() / 9); g2.drawString(String.valueOf(game.getLink().getRupee()), 102, game.getHeight() / 7); } public ArrayList<Rectangle> getExits() { return exits; } public abstract void handleSwitchScene(Rectangle exit); public abstract void handleSwitchScene(String entrance); }
# -*- coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Copyright (c) 2012 dput authors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """ Implementation regarding configuration files & their internal representation to the dput profile code. """ import abc class AbstractConfig(object): """ Abstract Configuration Object. All concrete configuration implementations must subclass this object. Basically, all subclasses are bootstrapped in the same-ish way: * preload * get_defaults * set defaults """ __metaclass__ = abc.ABCMeta def __init__(self, configs): self.preload(configs) self.path = ' '.join(configs) @abc.abstractmethod def set_replacements(self, replacements): """ """ pass # XXX: DOCUMENT ME. @abc.abstractmethod def get_defaults(self): """ Get the defaults that concrete configs get overlaid on top of. In theory, this is set during the bootstrapping process. """ pass @abc.abstractmethod def get_config(self, name, ignore_errors=False): """ Get a configuration block. What this means is generally up to the implementation. However, please keep things sane and only return sensual upload target blocks. """ pass @abc.abstractmethod def get_config_blocks(self): """ Get a list of all configuration blocks. Strings in a list. """ pass @abc.abstractmethod def preload(self, replacements): """ Load all configuration blocks. """ pass
#!/bin/bash # NFS health monitor plugin for Nagios # # Written by : Steve Bosek ([email protected]) # Release : 1.0rc4 # Creation date : 8 May 2009 # Revision date : 7 Oct 2012 # Package : BU Plugins # Description : Nagios plugin (script) to NFS health monitor (NFS server and/or client side). # With this plugin you can define client or server NFS side, RPC services which must be checked, # add or exclude NFS mountpoints and add or ignore file which contain the information on filesystems # on Linux and AIX plateforms # # # This script has been designed and written on Linux plateform. # # Usage : ./check_nfs_health.sh -i <server|client> -s <list rpc services> -a <add nfs mountpoint> -x <exclude nfs mountpoints> -f <add|ignore> # # Check NFS client-side : # check_nfs_health.sh -i client -s default -a none -x none -f add # check_nfs_health.sh -i client -s portmapper,nlockmgr -a /backup,/nfs_share -x /mouth_share -f add # # Check NFS basic client-side : # check_nfs_health.sh -i client -s default -a /backup,/nfs_share -x none -f ignore # # ----------------------------------------------------------------------------------------- # # TODO : - Performance Data (client-side and server-side) : nfsd_cpu, nfsd_used_threads, io_read, io_write, ... # - Solaris, HP-UX, MAC OSX support # - My atrocious English. Help Me ! ;-D # # # # HISTORY : # Release | Date | Authors | Description # --------------+---------------+-----------------------+---------------------------------- # 1.0rc1 | 12.05.2009 | Steve Bosek | Previous version # 1.0rc2 | 15.05.2009 | Steve Bosek | Add AIX Support (bash shell) # Add parameter [-f <add|ignore>] to ignore the file which # contains the information on filesystems: /etc/fstab,.. # 1.0rc3 | 19.05.2009 | Steve Bosek | Add Solaris support (bash shell) # # 1.0rc4 | 10.07.2012 | Austin Murphy | Strip client checks # | Strip performance checks # | Strip mountpoint checks # | Move reporting to end # | Use nagios codes from utils.sh # | added rquotad to services # | fixed FAULT_SERVICES_STATUS # Paths to commands used in this script PATH=$PATH:/usr/sbin:/usr/bin # Plugin variable description PROGNAME=$(basename $0) PROGPATH=$(echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,') REVISION="Revision 1.0rc3" AUTHOR="(c) 2009 Steve Bosek ([email protected])" . $PROGPATH/../utils.sh # Functions plugin usage print_revision() { echo "$PROGNAME $REVISION $AUTHOR" } print_usage() { echo "Usage: $PROGNAME -s <default|list NFS services> -i <client|server> -a <add nfs mountpoints> -x <exclude nfs mountpoints> -f <add|ignore>" echo "" echo "-h Show this page" echo "-v Script version" echo "-s List separate with comma of NFS dependent services. Look rpcinfo -p" echo " Default NFS server-side : nfs,mountd,portmapper,nlockmgr" } print_help() { print_revision echo "" print_usage echo "" exit 0 } # ----------------------------------------------------------------------------------------- # Default variable if not define in script command parameter # ----------------------------------------------------------------------------------------- NFS_SERVER_SERVICES=${NFS_SERVER_SERVICES:="nfs mountd portmapper nlockmgr rquotad"} NFS_SERVICES="default" NFS_SIDE="server" # ------------------------------------------------------------------------------------- # Grab the command line arguments # -------------------------------------------------------------------------------------- while [ $# -gt 0 ]; do case "$1" in -h | --help) print_help exit $STATE_OK ;; -v | --version) print_revision exit $STATE_OK ;; -s | --services) shift NFS_SERVICES=$1 ;; *) echo "Unknown argument: $1" print_usage exit $STATE_UNKNOWN ;; esac shift done # ----------------------------------------------------------------------------------------- # Check if NFS services are running # ----------------------------------------------------------------------------------------- if [ "$NFS_SERVICES" = "default" ]; then NFS_SERVICES=$NFS_SERVER_SERVICES else NFS_SERVICES=$(echo $NFS_SERVICES | sed 's/,/ /g') fi for i in ${NFS_SERVICES}; do NFS_SERVICES_STATUS=$(rpcinfo -p | grep -w ${i} | wc -l) if [ $NFS_SERVICES_STATUS -eq 0 ]; then FAULT_SERVICES_STATUS=$(echo "$FAULT_SERVICES_STATUS $i") fi done # ----------------------------------------------------------------------------------------- # Check if exported directories exist # ----------------------------------------------------------------------------------------- NFS_EXPORTS=`showmount -e 2>/dev/null | awk '{ print $1 }' | sed "1,1d" | tr -s "\n" " "` # Check exportfs for i in ${NFS_EXPORTS[@]}; do if [ ! -d $i ]; then FAULT_ARRAY=( ${FAULT_ARRAY[@]} $i ) fi done # ----------------------------------------------------------------------------------------- # Report status # ----------------------------------------------------------------------------------------- # NFS services are NOT running if [ ${#FAULT_SERVICES_STATUS[@]} != 0 ]; then echo "NFS CRITICAL : NFS services not running: ${FAULT_SERVICES_STATUS[@]} " exit $STATE_CRITICAL # No directories exported elif [ -z "$NFS_EXPORTS" ]; then echo "NFS UNKNOWN : NFS no export(s) " exit $STATE_UNKNOWN # Exported directory does not exist elif [ ${#FAULT_ARRAY[@]} != 0 ]; then echo "NFS CRITICAL : NFS export(s) missing: ${FAULT_ARRAY[@]}" exit $STATE_CRITICAL # all OK else echo "NFS OK : NFS services: ${NFS_SERVICES[@]}, export(s): ${NFS_EXPORTS[@]}" exit $STATE_OK fi
package com.persival.realestatemanagerkotlin.data.local_database.property_with_photos_and_pois import androidx.room.Embedded import androidx.room.Relation import com.persival.realestatemanagerkotlin.data.local_database.photo.PhotoEntity import com.persival.realestatemanagerkotlin.data.local_database.point_of_interest.PointOfInterestEntity import com.persival.realestatemanagerkotlin.data.local_database.property.PropertyEntity data class PropertyWithPhotosAndPoisEntity( @Embedded val property: PropertyEntity, @Relation( parentColumn = "id", entityColumn = "propertyId" ) val photos: List<PhotoEntity>, @Relation( parentColumn = "id", entityColumn = "propertyId" ) val pointsOfInterest: List<PointOfInterestEntity>, )
const { Usuario, Producto, Categoria } = require("../models"); const {ObjectId} = require("mongoose").Types; const coleccionesPermitidas = [ "categoria", "productos", "roles", "usuarios", ]; const buscarCategorias = async (termino,res)=>{ const isMongoId = ObjectId.isValid(termino); if(isMongoId){ const categoria = await Categoria.findById(termino); res.json({ results: (categoria) ? [categoria] : [] }); } const regex = new RegExp(termino,"i"); const categorias = await Categoria.find({nombre: regex, estado: true}); res.json({count: categorias.length, results: categorias}); } const buscarProductos = async (termino,res)=>{ const isMongoId = ObjectId.isValid(termino); if(isMongoId){ const producto = await Producto.findById(termino).populate("categoria","nombre"); res.json({ results: (producto) ? [producto] : [] }); } const regex = new RegExp(termino,"i"); const productos = await Producto.find({nombre: regex, estado: true}).populate("categoria","nombre"); res.json({count: productos.length, results: productos}); } const buscarUsuarios = async (termino,res)=>{ const isMongoId = ObjectId.isValid(termino); if(isMongoId){ const usuario = await Usuario.findById(termino); res.json({ results: (usuario) ? [usuario] : [] }); } const regex = new RegExp(termino,"i"); const usuarios = await Usuario.find({ $or: [{nombre: regex},{correo: regex}], $and: [{estado: true}] }); res.json({count: usuarios.length, results: usuarios}); } const buscar = async (req,res)=>{ const {coleccion,termino} = req.params; if(!coleccionesPermitidas.includes(coleccion)){ return res.status(400).json({msg: `Las colecciones permitidas son: ${coleccionesPermitidas}`}); } switch(coleccion){ case "categoria": await buscarCategorias(termino,res); break; case "productos": await buscarProductos(termino,res); break; case "usuarios": await buscarUsuarios(termino,res); break; default: res.status(500).json({msg: `No existe esta busqueda`}); } } module.exports = { buscar }
package io.github.ilnurnasybullin.math.mip; import io.github.ilnurnasybullin.math.simplex.FunctionType; import io.github.ilnurnasybullin.math.simplex.Simplex; import io.github.ilnurnasybullin.math.simplex.SimplexAnswer; import java.util.concurrent.locks.ReentrantLock; class SingleAnswerAccumulator implements AnswersAccumulator<SimplexAnswer> { /** * Объект для блокировки к доступу (записи) некоторых ресурсов ({@link #recordValue}, {@link #answer}) */ private final ReentrantLock lock = new ReentrantLock(); /** * Тип целевой функции. Необходим для выбора более оптимального значений функций из 2 предложенных (f<sub>1</sub> &lt * f<sub>2</sub>). При f &rarr min более оптимальное значение - f<sub>1</sub>, при f &rarr max - f<sub>2</sub> */ private final FunctionType functionType; /** * Рекордное значение (наиболее оптимальное значение). До тех пор, пока не вычислено - его значение null. */ private volatile Double recordValue; private volatile SimplexAnswer answer; SingleAnswerAccumulator(FunctionType functionType) { this.functionType = functionType; } @Override public boolean hasBetterThan(SimplexAnswer answer) { double fx = answer.fx(); Double localRecordValue; lock.lock(); localRecordValue = recordValue; lock.unlock(); if (localRecordValue == null) { return false; } if (isApproximateEqual(fx, localRecordValue)) { return true; } return functionType == FunctionType.MAX ? fx <= localRecordValue : fx >= localRecordValue; } private boolean isApproximateEqual(double x1, double x2) { return isApproximateEqual(x1, x2, Simplex.EPSILON); } private boolean isApproximateEqual(double x1, double x2, double epsilon) { return Math.abs(x1 - x2) < epsilon; } @Override public boolean tryPutAnswer(SimplexAnswer answer) { double fx = answer.fx(); try { lock.lock(); if (recordValue == null || functionType == FunctionType.MAX && fx > recordValue || functionType == FunctionType.MIN && fx < recordValue ) { updateResult(answer); return true; } } finally { lock.unlock(); } return false; } private void updateResult(SimplexAnswer answer) { this.answer = answer; recordValue = answer.fx(); } @Override public SimplexAnswer answer() { return answer; } }
#Region Movement ;~ Description: Move to a location. Func Move($aX, $aY, $aRandom = 50) ;returns true if successful If GetAgentExists(-2) Then DllStructSetData($mMove, 2, $aX + Random(-$aRandom, $aRandom)) DllStructSetData($mMove, 3, $aY + Random(-$aRandom, $aRandom)) Enqueue($mMovePtr, 16) Return True Else Return False EndIf EndFunc ;==>Move ;~ Description: Move to a location and wait until you reach it. Func MoveTo($aX, $aY, $aRandom = 50) Local $lBlocked = 0 Local $lMe Local $lMapLoading = GetMapLoading(), $lMapLoadingOld Local $lDestX = $aX + Random(-$aRandom, $aRandom) Local $lDestY = $aY + Random(-$aRandom, $aRandom) Move($lDestX, $lDestY, 0) Do Sleep(100) $lMe = GetAgentByID(-2) If DllStructGetData($lMe, 'HP') <= 0 Then ExitLoop $lMapLoadingOld = $lMapLoading $lMapLoading = GetMapLoading() If $lMapLoading <> $lMapLoadingOld Then ExitLoop If DllStructGetData($lMe, 'MoveX') == 0 And DllStructGetData($lMe, 'MoveY') == 0 Then $lBlocked += 1 $lDestX = $aX + Random(-$aRandom, $aRandom) $lDestY = $aY + Random(-$aRandom, $aRandom) Move($lDestX, $lDestY, 0) EndIf Until ComputeDistance(DllStructGetData($lMe, 'X'), DllStructGetData($lMe, 'Y'), $lDestX, $lDestY) < 25 Or $lBlocked > 14 EndFunc ;==>MoveTo ;~ Description: Run to or follow a player. Func GoPlayer($aAgent) Local $lAgentID If IsDllStruct($aAgent) = 0 Then $lAgentID = ConvertID($aAgent) Else $lAgentID = DllStructGetData($aAgent, 'ID') EndIf Return SendPacket(0x8, $HEADER_AGENT_FOLLOW , $lAgentID) EndFunc ;==>GoPlayer ;~ Description: Talk to an NPC Func GoNPC($aAgent) Local $lAgentID If IsDllStruct($aAgent) = 0 Then $lAgentID = ConvertID($aAgent) Else $lAgentID = DllStructGetData($aAgent, 'ID') EndIf Return SendPacket(0xC, $HEADER_NPC_TALK, $lAgentID) EndFunc ;==>GoNPC ;~ Description: Talks to NPC and waits until you reach them. Func GoToNPC($aAgent) If Not IsDllStruct($aAgent) Then $aAgent = GetAgentByID($aAgent) Local $lMe Local $lBlocked = 0 Local $lMapLoading = GetMapLoading(), $lMapLoadingOld Move(DllStructGetData($aAgent, 'X'), DllStructGetData($aAgent, 'Y'), 100) Sleep(100) GoNPC($aAgent) Do Sleep(100) $lMe = GetAgentByID(-2) If DllStructGetData($lMe, 'HP') <= 0 Then ExitLoop $lMapLoadingOld = $lMapLoading $lMapLoading = GetMapLoading() If $lMapLoading <> $lMapLoadingOld Then ExitLoop If DllStructGetData($lMe, 'MoveX') == 0 And DllStructGetData($lMe, 'MoveY') == 0 Then $lBlocked += 1 Move(DllStructGetData($aAgent, 'X'), DllStructGetData($aAgent, 'Y'), 100) Sleep(100) GoNPC($aAgent) EndIf Until ComputeDistance(DllStructGetData($lMe, 'X'), DllStructGetData($lMe, 'Y'), DllStructGetData($aAgent, 'X'), DllStructGetData($aAgent, 'Y')) < 250 Or $lBlocked > 14 Sleep(GetPing() + Random(1500, 2000, 1)) EndFunc ;==>GoToNPC ;~ Description: Run to a signpost. Func GoSignpost($aAgent) Local $lAgentID If IsDllStruct($aAgent) = 0 Then $lAgentID = ConvertID($aAgent) Else $lAgentID = DllStructGetData($aAgent, 'ID') EndIf Return SendPacket(0xC, $HEADER_SIGNPOST_RUN, $lAgentID, 0) EndFunc ;==>GoSignpost ;~ Description: Go to signpost and waits until you reach it. Func GoToSignpost($aAgent) If Not IsDllStruct($aAgent) Then $aAgent = GetAgentByID($aAgent) Local $lMe Local $lBlocked = 0 Local $lMapLoading = GetMapLoading(), $lMapLoadingOld Move(DllStructGetData($aAgent, 'X'), DllStructGetData($aAgent, 'Y'), 100) Sleep(100) GoSignpost($aAgent) Do Sleep(100) $lMe = GetAgentByID(-2) If DllStructGetData($lMe, 'HP') <= 0 Then ExitLoop $lMapLoadingOld = $lMapLoading $lMapLoading = GetMapLoading() If $lMapLoading <> $lMapLoadingOld Then ExitLoop If DllStructGetData($lMe, 'MoveX') == 0 And DllStructGetData($lMe, 'MoveY') == 0 Then $lBlocked += 1 Move(DllStructGetData($aAgent, 'X'), DllStructGetData($aAgent, 'Y'), 100) Sleep(100) GoSignpost($aAgent) EndIf Until ComputeDistance(DllStructGetData($lMe, 'X'), DllStructGetData($lMe, 'Y'), DllStructGetData($aAgent, 'X'), DllStructGetData($aAgent, 'Y')) < 250 Or $lBlocked > 14 Sleep(GetPing() + Random(1500, 2000, 1)) EndFunc ;==>GoToSignpost Func GoNearestNPCToCoords($x, $y) Local $guy, $Me Do RndSleep(250) $guy = GetNearestNPCToCoords($x, $y) Until DllStructGetData($guy, 'Id') <> 0 ChangeTarget($guy) RndSleep(250) GoNPC($guy) RndSleep(250) Do RndSleep(500) Move(DllStructGetData($guy, 'X'), DllStructGetData($guy, 'Y'), 40) RndSleep(500) GoNPC($guy) RndSleep(250) $Me = GetAgentByID(-2) Until ComputeDistance(DllStructGetData($Me, 'X'), DllStructGetData($Me, 'Y'), DllStructGetData($guy, 'X'), DllStructGetData($guy, 'Y')) < 250 RndSleep(1000) EndFunc ;==>GoNearestNPCToCoords ;~ Description: Attack an agent. Func Attack($aAgent, $aCallTarget = False) Local $lAgentID If IsDllStruct($aAgent) = 0 Then $lAgentID = ConvertID($aAgent) Else $lAgentID = DllStructGetData($aAgent, 'ID') EndIf Return SendPacket(0xC, $HEADER_ATTACK_AGENT, $lAgentID, $aCallTarget) EndFunc ;==>Attack ;~ Description: Turn character to the left. Func TurnLeft($aTurn) If $aTurn Then Return PerformAction(0xA2, 0x1E) Else Return PerformAction(0xA2, 0x20) EndIf EndFunc ;==>TurnLeft ;~ Description: Turn character to the right. Func TurnRight($aTurn) If $aTurn Then Return PerformAction(0xA3, 0x1E) Else Return PerformAction(0xA3, 0x20) EndIf EndFunc ;==>TurnRight ;~ Description: Move backwards. Func MoveBackward($aMove) If $aMove Then Return PerformAction(0xAC, 0x1E) Else Return PerformAction(0xAC, 0x20) EndIf EndFunc ;==>MoveBackward ;~ Description: Run forwards. Func MoveForward($aMove) If $aMove Then Return PerformAction(0xAD, 0x1E) Else Return PerformAction(0xAD, 0x20) EndIf EndFunc ;==>MoveForward ;~ Description: Strafe to the left. Func StrafeLeft($aStrafe) If $aStrafe Then Return PerformAction(0x91, 0x1E) Else Return PerformAction(0x91, 0x20) EndIf EndFunc ;==>StrafeLeft ;~ Description: Strafe to the right. Func StrafeRight($aStrafe) If $aStrafe Then Return PerformAction(0x92, 0x1E) Else Return PerformAction(0x92, 0x20) EndIf EndFunc ;==>StrafeRight ;~ Description: Auto-run. Func ToggleAutoRun() Return PerformAction(0xB7, 0x1E) EndFunc ;==>ToggleAutoRun ;~ Description: Turn around. Func ReverseDirection() Return PerformAction(0xB1, 0x1E) EndFunc ;==>ReverseDirection #EndRegion Movement
<!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title>wh.gg</title> <meta content="" name="description"> <meta content="" name="keywords"> <!-- Favicons --> <link href="{% static 'summoner_dashboard/img/wh.ico' %}" rel="icon"> <link href="{% static 'summoner_dashboard/img/apple-touch-icon.png' %}" rel="apple-touch-icon"> <!-- Google Fonts --> <link href="https://fonts.gstatic.com" rel="preconnect"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Righteous&display=swap" rel="stylesheet"> <!-- Vendor CSS Files --> <link href="{% static 'summoner_dashboard/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'summoner_dashboard/vendor/bootstrap-icons/bootstrap-icons.css' %}" rel="stylesheet"> <link href="{% static 'summoner_dashboard/vendor/boxicons/css/boxicons.min.css' %}" rel="stylesheet"> <link href="{% static 'summoner_dashboard/vendor/quill/quill.snow.css' %}" rel="stylesheet"> <link href="{% static 'summoner_dashboard/vendor/quill/quill.bubble.css' %}" rel="stylesheet"> <link href="{% static 'summoner_dashboard/vendor/remixicon/remixicon.css' %}" rel="stylesheet"> <link href="{% static 'summoner_dashboard/vendor/simple-datatables/style.css' %}" rel="stylesheet"> <!-- Template Main CSS File --> <link href="{% static 'summoner_dashboard/css/style.css' %}" rel="stylesheet"> * Template Name: NiceAdmin * Updated: Mar 09 2023 with Bootstrap v5.2.3 * Template URL: https://bootstrapmade.com/nice-admin-bootstrap-admin-html-template/ * Author: BootstrapMade.com * License: https://bootstrapmade.com/license/ </head> <> <!-- ======= Header ======= --> <header id="header" class="header fixed-top d-flex align-items-center"> <div class="d-flex align-items-center justify-content-between"> <a href="" class="logo d-flex align-items-center"> <!-- <img src="/static/img/test-logo.png" alt=""> --> <span class="d-none d-lg-block">wh.gg</span> </a> <i class="bi bi-list toggle-sidebar-btn"></i> <div class="search-bar"> <form id="search-form" class="search-form d-flex align-items-center" onsubmit="event.preventDefault(); redirectToSummonerInfo();"> <input type="text" id="summoner-name-input" placeholder="Search" title="Enter summoner name"> <button type="submit" title="Search"><i class="bi bi-search"></i></button> </form> </div> <script> function redirectToSummonerInfo() { var summonerName = document.getElementById('summoner-name-input').value; window.location.href = "/summoners/euw1/" + summonerName; } </script> </div> </div><!-- End Logo --> </header><!-- End Header --> <!-- ======= Sidebar ======= --> <aside id="sidebar" class="sidebar"> <ul class="sidebar-nav" id="sidebar-nav"> <li class="nav-item"> <a class="nav-link" href=""> <span>Home</span> </a> </li><!-- End Dashboard Nav --> <li class="nav-item"> <a class="nav-link collapsed" href=""> <span>Tier List</span> </a> </li><!-- End Profile Page Nav --> <li class="nav-item"> <a class="nav-link collapsed" href=""> <span>Champions</span> </a> </li><!-- End F.A.Q Page Nav --> <li class="nav-item"> <a class="nav-link collapsed" href=""> <span>Leaderboards</span> </a> </li><!-- End Contact Page Nav --> </ul> </aside><!-- End Sidebar--> <main id="main" class="main"> <section class="section dashboard"> <div class="row"> <!-- Left side columns --> <div class="col-lg-8"> <div class="row"> <!-- Summoner Card --> <div class="col-xxl-4 col-xl-12"> <div class="card info-card customers-card"> <div class="card-body"> <h5 class="card-title"> | Profile</h5> <div class="d-flex align-items-center"> <div class="card-icon rounded-circle d-flex align-items-center justify-content-center"> <img src="{% static 'img/profileicon/' %}{{ summoner_data.profile_icon_id }}.png" alt="" class="img-icon"> </div> <div class="ps-3"> <h6>{{ summoner_name }}</h6> <button class="update-button" id="update-button">Update</button> <script> document.addEventListener('DOMContentLoaded', function () { const updateButton = document.getElementById('update-button'); const summonerInfoUrl = "{% url 'summoner_dashboard:summoner_info' summoner_name=summoner_name %}"; updateButton.addEventListener('click', function (event) { event.preventDefault(); // Redirige a la URL actual con la región y el nombre del invocador window.location.href = summonerInfoUrl; }); }); </script> </div> </div> </div> </div> </div><!-- End Summoner Card --> <!-- Ranked Solo Card --> <div class="col-xxl-4 col-md-6"> <div class="card info-card sales-card"> <div class="card-body"> <h5 class="card-title"> | Ranked Solo</h5> <div class="d-flex align-items-center"> <div class="card-icon rounded-circle d-flex align-items-center justify-content-center"> <img src="{% static 'img/'|add:summoner_data.soloq.rank.split.0|add:'.webp' %}" alt="master" class="img-icon"> </div> <div class="ps-3"> <h6>{{ summoner_data.soloq.rank }}</h6> <span class="text-success small pt-1 fw-bold">{{ summoner_data.soloq.lp }}</span> <span class="text-muted small pt-2 ps-1">LP</span> </div> </div> </div> </div> </div><!-- End Ranked Solo Card --> <!-- Revenue Card --> <div class="col-xxl-4 col-md-6"> <div class="card info-card revenue-card"> <div class="card-body"> <h5 class="card-title"> | Ranked Flex </h5> <div class="d-flex align-items-center"> <div class="card-icon rounded-circle d-flex align-items-center justify-content-center"> <img src="{% static 'img/'|add:summoner_data.flex.rank.split.0|add:'.webp' %}" alt="master" class="img-icon"> </div> <div class="ps-3"> <h6>{{ summoner_data.flex.rank }}</h6> <span class="text-success small pt-1 fw-bold">{{ summoner_data.flex.lp }}</span> <span class="text-muted small pt-2 ps-1">LP</span> </div> </div> </div> </div> </div><!-- End Revenue Card --> <!-- Recent Games --> <div class="col-12"> <div class="card top-selling overflow-auto"> <div class="card-body pr-25 pl-25"> <h5 class="card-title center-text"> | Recent Games</h5> <!-- Cards --> {% for match in recent_matches %} <div class="card"> <div class="card-header"> <span class="game-type">{{ match.game_type }}</span> <img src="{% static 'img/champion/' %}{{ match.champion_name }}.png" alt="Champion icon" class="champ-icon"> <div class="game-runes"> <img src="{% static 'img/spells/' %}{{ match.summoner_spell_ids.0 }}.png" alt="spell-1" class="rune-icon"> <img src="{% static 'img/spells/' %}{{ match.summoner_spell_ids.1 }}.png" alt="spell-2" class="rune-icon"> </div> <div class="game-score"> <span class="kda">{{ match.kills }} / {{ match.deaths }} / {{ match.assists }}</span> <span class="kda-ratio">{{ match.kda_ratio }}:1 KDA</span> <span class="cs cs-center">{{ match.cs }} CS</span> </div> <div class="game-items"> {% for item_id in match.item_ids %} <div class="item-icon"> {% if item_id != 0 %} <img src="{% static 'img/item/' %}{{ item_id }}.png" alt="" class="item-icon"> {% endif %} </div> {% endfor %} </div> {% if match.win %} <span class="game-result">Victory</span> {% else %} <span class="game-result defeat">Defeat</span> {% endif %} </div> <div class="card-header justify-content-center"> <div class="participant-column"> {% for champ_name in match.participant_champion_names|slice:":5" %} <div class="participant-icon"> <img src="{% static 'img/champion/'|add:champ_name|add:'.png' %}" alt="{{ champ_name }}" class="participant-icon"> </div> {% endfor %} </div> <div class="participant-column"> {% for participant_name in match.participant_summoner_names|slice:":5" %} <span class="participant-name">{{ participant_name }}</span> {% endfor %} </div> <div class="participant-column pl-100"> {% for champ_name in match.participant_champion_names|slice:"5:" %} <div class="participant-icon"> <img src="{% static 'img/champion/'|add:champ_name|add:'.png' %}" alt="{{ champ_name }}" class="participant-icon"> </div> {% endfor %} </div> <div class="participant-column"> {% for participant_name in match.participant_summoner_names|slice:"5:" %} <span class="participant-name">{{ participant_name }}</span> {% endfor %} </div> </div> </div> {% endfor %} </div> </div> </div><!-- End Recent Games --> </div> </div><!-- End Left side columns --> <!-- Right side columns --> <div class="col-lg-4"> <!-- Roles chart --> <div class="card"> <div class="card-body pb-2"> <h5 class="card-title"> | Roles</h5> <div style="display: none;"> <span id="top-count">{{ role_data.TOP }}</span> <span id="jungle-count">{{ role_data.JUNGLE }}</span> <span id="mid-count">{{ role_data.MIDDLE }}</span> <span id="bottom-count">{{ role_data.BOTTOM }}</span> <span id="support-count">{{ role_data.UTILITY }}</span> </div> <div id="trafficChart" style="min-height: 150px;" class="echart"></div> <script> document.addEventListener("DOMContentLoaded", () => { let role_counts = { 'Top': parseInt(document.getElementById("top-count").textContent, 10), 'Jungle': parseInt(document.getElementById("jungle-count").textContent, 10), 'Mid': parseInt(document.getElementById("mid-count").textContent, 10), 'Bottom': parseInt(document.getElementById("bottom-count").textContent, 10), 'Support': parseInt(document.getElementById("support-count").textContent, 10) }; echarts.init(document.querySelector("#trafficChart")).setOption({ tooltip: { trigger: 'item' }, legend: { orient: 'vertical', left: '0', top: 'middle', itemWidth: 30, textStyle: { fontSize: 10 } }, series: [{ name: '', type: 'pie', radius: ['40%', '70%'], center: ['65%', '50%'], avoidLabelOverlap: false, label: { show: false, position: 'center' }, emphasis: { label: { show: true, fontSize: '18', fontWeight: 'bold' } }, labelLine: { show: false }, data: [{ value: role_counts["Top"], name: 'Top' }, { value: role_counts["Jungle"], name: 'Jungle' }, { value: role_counts["Mid"], name: 'Mid' }, { value: role_counts["Bottom"], name: 'Bottom' }, { value: role_counts["Support"], name: 'Support' } ] }] }); }); </script> </div> </div><!-- End Roles chart--> <!-- Champion Stats --> <div class="card"> <div class="card-body pb-0"> <h5 class="card-title "> | Champion Stats</h5> {% if champions_played %} {% for champion in champions_played %} <hr> <div class="card-body"> <div class="row"> <div class="col"> <img class="champ-img" src="{% static 'img/champion/'|add:champion.champion_name|add:'.png' %}" alt=""> </div> <div class="col"> <span class="champ-name">{{ champion.champion_name }}</span> </div> <div class="col stats-wrapper"> <span class="kda1">{{ champion.kda }}:1 KDA</span> <span class="kda-ratio">{{ champion.kills }} / {{ champion.deaths }} / {{ champion.assists }}</span> </div> <div class="col stats-wrapper"> <span class="win-rate">{{ champion.wr }}%</span> <span class="games-played">{{ champion.games_played }} games</span> </div> </div> </div> {% endfor %} <hr> {% endif %} </div> </div><!-- End Champion Stats--> </div><!-- End Right side columns --> </div> </section> </main><!-- End #main --> <!-- ======= Footer ======= --> <footer id="footer" class="footer"> <div class="copyright"> &copy; Copyright <strong><span>NiceAdmin</span></strong>. All Rights Reserved </div> <div class="credits"> Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a> </div> </footer> </<!-- End Footer --> <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a> <!-- Vendor JS Files --> <script src="{% static 'vendor/apexcharts/apexcharts.min.js' %}"></script> <script src="{% static 'vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <script src="{% static 'vendor/chart.js/chart.umd.js' %}"></script> <script src="{% static 'vendor/echarts/echarts.min.js' %}"></script> <script src="{% static 'vendor/quill/quill.min.js' %}"></script> <script src="{% static 'vendor/simple-datatables/simple-datatables.js' %}"></script> <script src="{% static 'vendor/tinymce/tinymce.min.js' %}"></script> <script src="{% static 'vendor/php-email-form/validate.js' %}"></script> <!-- Template Main JS File --> <script src="{% static 'js/main.js' %}"></script> </body> </html>
package org.fawry.Week5.DesignPattern3.Task3.singletonLogger; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.time.LocalDateTime; public class logger { private static logger instance; FileWriter fileWriter; private logger() { File file = new File("./src/main/java/org/fawry/Week5/DesignPattern3/Task3/log.txt"); try { file.createNewFile(); fileWriter = new FileWriter(file); } catch (IOException e) { System.out.println(e.getMessage()); } } public static logger getInstance() { if (instance == null) { synchronized (logger.class) { if (instance == null) { instance = new logger(); } } } return instance; } public void logSmoke() { System.out.println("Log smoke...."); try { fileWriter.write(LocalDateTime.now() + ":smoke detected\n"); fileWriter.flush(); } catch (IOException e) { System.out.println(e.getMessage()); } } public void logMotion() { System.out.println("Log motion...."); try { fileWriter.write(LocalDateTime.now() + ":motion detected\n"); fileWriter.flush(); } catch (IOException e) { System.out.println(e.getMessage()); } } }
'use client'; import * as z from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; import { useForm } from 'react-hook-form'; import axios from 'axios'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/components/ui/dialog'; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from '@/components/ui/form'; import { Input } from '@/components/ui/input'; import { Button } from '@/components/ui/button'; import FileUpload from '@/components/file-upload'; import { useRouter } from 'next/navigation'; import { useModal } from '@/hooks/use-modal-store'; import { useEffect, useState, useTransition } from 'react'; import { useCurrentUser } from '@/hooks/use-current-user'; import { settings } from '@/actions/settings'; import { useSession } from 'next-auth/react'; import { Switch } from '../ui/switch'; import { FormError } from '../form-error'; import { FormSuccess } from '../form-success'; import { Gender } from '@prisma/client'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select'; import { Textarea } from '../ui/textarea'; const formSchema = z.object({ bannerImage: z.optional(z.string()), description: z.optional(z.string()), status: z.optional(z.string()), gender: z.enum([Gender.MALE, Gender.FEMALE, Gender.SECRET]), }); const ProfileModal = () => { const [error, setError] = useState<string | undefined>(); const [success, setSuccess] = useState<string | undefined>(); const [isPending, startTransition] = useTransition(); const { update } = useSession(); const { isOpen, onClose, type, data } = useModal(); const router = useRouter(); const user = useCurrentUser(); const isModalOpen = isOpen && type === 'profile'; const form = useForm({ resolver: zodResolver(formSchema), defaultValues: { bannerImage: '', description: '', status: '', gender: user?.gender || Gender.SECRET, }, }); useEffect(() => { if (user?.gender) { form.setValue('gender', user.gender); } if (user?.bannerImage) { form.setValue('bannerImage', user.bannerImage); } if (user?.description) { form.setValue('description', user.description); } if (user?.status) { form.setValue('status', user.status); } }, [form, isOpen, user?.bannerImage, user?.description, user?.gender, user?.status]); const isLoading = form.formState.isSubmitting; const onSubmit = (values: z.infer<typeof formSchema>) => { setError(''); setSuccess(''); startTransition(() => { settings(values) .then((data) => { if (data.error) { setError(data.error); } if (data.success) { update(); router.refresh(); setSuccess(data.success); } }) .catch(() => setError('Something went wrong!')); }); }; const handleClose = () => { setError(''); setSuccess(''); form.reset(); onClose(); }; return ( <Dialog open={isModalOpen} onOpenChange={handleClose}> <DialogContent className=" bg-white text-black p-0 overflow-hidden"> <DialogHeader className=" pt-8 px-6 "> <DialogTitle className=" text-2xl text-center font-bold "> Edit Profile </DialogTitle> <DialogDescription className=" text-center text-zinc-500 "> Here you can edit your profile. </DialogDescription> </DialogHeader> <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8"> <div className=" space-y-8 px-6 "> <FormField control={form.control} name="status" render={({ field }) => ( <FormItem> <FormLabel className=" uppercase text-xs font-bold text-zinc-500 dark:text-secondary/70 "> Status </FormLabel> <FormControl> <Input disabled={isPending} className=" bg-zinc-300/50 border-0 focus-visible:ring-0 text-black focus-visible:ring-offset-0 " placeholder="Looking for inspiration..." {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <div className=" flex items-center "> <FormField control={form.control} name="bannerImage" render={({ field }) => ( <FormItem> <FormLabel className=" uppercase text-xs font-bold text-zinc-500 dark:text-secondary/70 "> Banner Image </FormLabel> <FormControl> <FileUpload endpoint="bannerImage" value={field.value} onChange={field.onChange} /> </FormControl> </FormItem> )} /> </div> <FormField control={form.control} name="gender" render={({ field }) => ( <FormItem> <FormLabel className=" uppercase text-xs font-bold text-zinc-500 dark:text-secondary/70 "> Gender </FormLabel> <Select disabled={isPending} onValueChange={field.onChange} defaultValue={field.value}> <FormControl className=' bg-zinc-300/50 border-0 focus-visible:ring-0 focus-visible:ring-offset-0 text-zinc-500 dark:text-secondary/70 "'> <SelectTrigger> <SelectValue placeholder="Select a role" /> </SelectTrigger> </FormControl> <SelectContent> <SelectItem value={Gender.MALE}>Male</SelectItem> <SelectItem value={Gender.FEMALE}>Female</SelectItem> <SelectItem value={Gender.SECRET}>Secret</SelectItem> </SelectContent> </Select> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="description" render={({ field }) => ( <FormItem> <FormLabel className=" uppercase text-xs font-bold text-zinc-500 dark:text-secondary/70 "> Description </FormLabel> <FormControl> <Textarea rows={4} disabled={isPending} className=" resize-none bg-zinc-300/50 border-0 focus-visible:ring-0 text-black focus-visible:ring-offset-0 " placeholder="An expert on caffeine science and a repository of unnecessary facts." {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> </div> <DialogFooter className=" bg-gray-100 px-6 py-4 "> <FormError message={error} /> <FormSuccess message={success} /> <Button variant={'primary'} disabled={isLoading}> Save </Button> </DialogFooter> </form> </Form> </DialogContent> </Dialog> ); }; export default ProfileModal;
// final welcome = welcomeFromJson(jsonString); import 'dart:convert'; Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str)); String welcomeToJson(Welcome data) => json.encode(data.toJson()); class Welcome { List<Value> value; Welcome({ required this.value, }); factory Welcome.fromJson(Map<String, dynamic> json) => Welcome( value: List<Value>.from(json["value"].map((x) => Value.fromJson(x))), ); Map<String, dynamic> toJson() => { "value": List<dynamic>.from(value.map((x) => x.toJson())), }; } class Value { List<Joining> joining; List<Transaction> transaction; List<Joining> team; List<Joining> tax; Value({ required this.joining, required this.transaction, required this.team, required this.tax, }); factory Value.fromJson(Map<String, dynamic> json) => Value( joining: List<Joining>.from(json["joining"].map((x) => Joining.fromJson(x))), transaction: List<Transaction>.from(json["transaction"].map((x) => Transaction.fromJson(x))), team: List<Joining>.from(json["team"].map((x) => Joining.fromJson(x))), tax: List<Joining>.from(json["tax"].map((x) => Joining.fromJson(x))), ); Map<String, dynamic> toJson() => { "joining": List<dynamic>.from(joining.map((x) => x.toJson())), "transaction": List<dynamic>.from(transaction.map((x) => x.toJson())), "team": List<dynamic>.from(team.map((x) => x.toJson())), "tax": List<dynamic>.from(tax.map((x) => x.toJson())), }; } class Joining { String title; String size; String url; Joining({ required this.title, required this.size, required this.url, }); factory Joining.fromJson(Map<String, dynamic> json) => Joining( title: json["title"], size: json["size"], url: json["url"], ); Map<String, dynamic> toJson() => { "title": title, "size": size, "url": url, }; } class Transaction { String address; int transactionId; String date; String dateType; List<Document> documents; Transaction({ required this.address, required this.transactionId, required this.documents, required this.date, required this.dateType }); factory Transaction.fromJson(Map<String, dynamic> json) => Transaction( address: json["address"], transactionId: json["transactionId"], date: json["transaction_date"], dateType: json["date_type"], documents: List<Document>.from(json["documents"].map((x) => Document.fromJson(x))), ); Map<String, dynamic> toJson() => { "address": address, "transactionId": transactionId, "transaction_date": date, "date_type": dateType, "documents": List<dynamic>.from(documents.map((x) => x.toJson())), }; } class Document { Title title; CheckListName checkListName; DateTime date; Status status; String url; Document({ required this.title, required this.checkListName, required this.date, required this.status, required this.url, }); factory Document.fromJson(Map<String, dynamic> json) => Document( title: titleValues.map[json["title"]]!, checkListName: checkListNameValues.map[json["checkListName"]]!, date: DateTime.parse(json["date"]), status: statusValues.map[json["status"]]!, url: json["url"], ); Map<String, dynamic> toJson() => { "title": titleValues, "checkListName": checkListNameValues.reverse[checkListName], "date": date.toIso8601String(), "status": statusValues.reverse[status], "url": url, }; } enum CheckListName { DEMO_NAME } final checkListNameValues = EnumValues({ "Demo Name": CheckListName.DEMO_NAME }); enum Status { APPROVED, UNAPPROVED } final statusValues = EnumValues({ "Approved": Status.APPROVED, "Unapproved": Status.UNAPPROVED }); enum Title { LICENSE_DOCUMENT_PDF } final titleValues = EnumValues({ "License Document.pdf":Title.LICENSE_DOCUMENT_PDF }); class EnumValues<T> { Map<String, T> map; late Map<String, T> reverseMap; EnumValues(this.map); Map<String, T> get reverse { reverseMap = map.map((k, v) => MapEntry(k, v)); return reverseMap; } }
import tkinter as tk from ast import main from tkinter import * from tkinter import messagebox as mess from tkcalendar import DateEntry from datetime import date from mysql.connector import Error import mysql.connector import pyzbar import numpy as np import cv2 from pymysql import* import xlwt import pandas.io.sql as sql from tkinter import font as tkFont import datetime import time global e1,e2,e3,e4,Name,Subject,Class,db_table_name,new_date,message,root def ok(): global db_table_name Subject=e1.get() Name=e2.get() Class=e3.get() Date=e4.get() new_date=Date.replace('/','_') new_name=Name.replace(' ','_') new_subject=Subject.replace(' ','_') new_class=Class.replace(' ','_') db_table_name = new_subject+"_"+new_name+"_"+new_class+"_"+new_date if Name=='Select Faculty' or Subject=='Select Subject' or Class=='Select Class': message.set("Enter full details") else: main() def main(): try: connection = mysql.connector.connect(host='localhost',database='qr',user='root',password='') if connection.is_connected(): cursor = connection.cursor() except Error as e: print("Error while connecting to MySQL", e) try: cursor.execute( "CREATE TABLE " + db_table_name + " (Id INT AUTO_INCREMENT, Enrollment VARCHAR(12),Name VARCHAR(30),PRIMARY KEY( Id ))") except mysql.connector.Error as error: print("Failed to create table in MySQL: {}".format(error)) cap = cv2.VideoCapture(0) cap.set(3, 1280) cap.set(4, 1024) font = cv2.FONT_HERSHEY_SIMPLEX while (cap.isOpened()): ret, frame = cap.read() im = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) data = pyzbar.decode(im) for i in data: points = i.polygon # If the points do not form a quad, find convex hull if len(points) > 4: hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32)) hull = list(map(tuple, np.squeeze(hull))) else: hull = points; n = len(hull) # Draw the convext hull for j in range(0, n): cv2.line(frame, hull[j], hull[(j + 1) % n], (0, 255, 0), 4) barCode = str(i.data) enrollment = barCode[2:14] name = barCode[14:-1] cv2.putText(frame, name, (i.rect.left, i.rect.top), font, 1, (255, 60,), 2, cv2.LINE_AA) cursor.execute("select Enrollment from " + db_table_name + " where Enrollment=%s", (enrollment,)) record = cursor.fetchone() if not record: cursor.execute("INSERT INTO " + db_table_name + "(Enrollment,Name) VALUES (%s,%s)", (enrollment, name)) connection.commit() cv2.imshow('frame', frame) key = cv2.waitKey(1) if key & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() if connection.is_connected(): df = sql.read_sql('select * from ' + db_table_name + "", connection) df.to_excel(db_table_name + '.xls') cursor.close() connection.close() print("Successfully complete") root.destroy() def tick(): time_string = time.strftime('%d-%m-%Y | %I:%M:%S %p') clock.config(text=time_string) clock.after(200, tick) def contact(): mess._show(title='Contact us', message="Please contact us on : [email protected] ") def about(): mess._show(title='About', message="Created by ashish parmar") # root window root = tk.Tk() root.geometry('555x480') root.title('Attandance System') root.resizable(0, 0) root.configure(bg='LightBlue2') helv12 = tkFont.Font(family='Helvetica', size=11) menubar = tk.Menu(root, relief='ridge') filemenu = tk.Menu(menubar, tearoff=0) filemenu.add_command(label='Contact Us', command=contact) filemenu.add_command(label='About', command=about) filemenu.add_command(label='Exit', command=root.destroy) menubar.add_cascade(label='Help', font=('times', 29, ' bold '), menu=filemenu) b = Label(root, text="QR Code Based Attendance System", font=("Helvetica", 15)) b.config(background='LightBlue2', foreground='blue') b.grid(columnspan=2, row=0, padx=7, pady=7) clock = tk.Label(root, bg="LightBlue2", height=2, font=('times', 14, ' bold ')) clock.grid(columnspan=2, row=1) tick() # configure the grid root.columnconfigure(0, weight=1) root.columnconfigure(1, weight=2) # subject subject = ttk.Label(root, text="Subject :", font=("Helvetica", 12)) subject.config(background="LightBlue2") subject.grid(column=0, row=2, padx=5, pady=20) e1 = StringVar() e1.set("Select Subject") x = OptionMenu(root, e1, "Java", "Python", "OS", "IP", "Maths", "DCN", "NEN", "CPI") x.config(bg="DeepSkyBlue2", font=helv12) x['menu'].config(bg="LightSteelBlue2", font=helv12) x.grid(column=1, row=2, padx=50, sticky=tk.EW) # username name = ttk.Label(root, text="Faculty Name :", font=("Helvetica", 12)) name.config(background='LightBlue2') name.grid(column=0, row=3, padx=5, pady=20) e2 = StringVar() e2.set("Select Faculty") x = OptionMenu(root, e2, "Snehal Sathwara", "Jasmin Jasani", "Paresh Tanna", "Nikunj Vadher", "Neha Chauhan", "Shivangi Patel", "Alpa Makwana", "Sweta Patel", "Hiren Kathiriya", "Ankit Pandya", "Purvangi Butani", "Mahesh Parasaniya", "Dushyant Joshi") x.config(bg="DeepSkyBlue2", font=helv12) x['menu'].config(bg="LightSteelBlue2", font=helv12) x.grid(column=1, row=3, padx=50, sticky=tk.EW) # class Class = ttk.Label(root, text="Class :", font=("Helvetica", 12)) Class.config(background='LightBlue2') Class.grid(column=0, row=4, padx=5, pady=20) e3 = StringVar() e3.set("Select Class") x = OptionMenu(root, e3, "4CEA", "4CEB", "4CEC") x.config(bg="DeepSkyBlue2", font=helv12) x['menu'].config(bg="LightSteelBlue2", font=helv12) x.grid(column=1, row=4, padx=50, sticky=tk.EW) # date today = date.today() y = int(today.strftime("%y")) m = int(today.strftime("%m")) d = int(today.strftime("%d")) date = tk.Label(root, text="Date :", font=("Helvetica", 12)) date.config(background='LightBlue2') date.grid(column=0, row=5, padx=5, pady=20) e4 = DateEntry(root, width=12, year=y, month=m, day=d, background='deep sky blue', borderwidth=2, font=helv12, date_pattern="dd/mm/yy") e4.grid(column=1, row=5, padx=50, sticky=tk.EW) # Take Attendance button message = StringVar() b = Label(root, text="", font=("Helvetica", 11), textvariable=message) b.config(background='LightBlue2', foreground='red') b.grid(columnspan=2, padx=7, pady=7) button = tk.Button(root, text="Take Attendance", bg='DeepSkyBlue2', command=ok, font=helv12) button.grid(columnspan=2, padx=5, pady=5) root.configure(menu=menubar) root.mainloop()
package com.example.newappdi.api_calling.DI import com.example.newappdi.api_calling.DI.Network.APICallServices import com.example.newappdi.api_calling.DI.Network.ErrorResponse import com.example.newappdi.api_calling.DI.Network.Response import com.example.newappdi.api_calling.DI.Network.SuccessResponse import com.example.newappdi.api_calling.model.AppMainData import javax.inject.Inject class APIRespository @Inject constructor(@BaseUrl2Retrofit val apiCallServices: APICallServices) { suspend fun getData(): Response<AppMainData> { return try { val response = apiCallServices.getData() SuccessResponse(response) } catch (ee: Exception) { ErrorResponse("", ee) } } /* * I have read the content of the page "Kotlin's Flow, ChannelFlow, and CallbackFlow Made Easy" by Elye on Medium. Here's a summary of the key points: **The article explains the differences and use cases for three Kotlin flow types:** 1. **Flow**: The basic reactive stream for asynchronous data processing. Best for linear data streams with operations like mapping, filtering, etc. 2. **ChannelFlow**: A flow with a buffer, allowing concurrent data emission and reception. Ideal for situations where data arrives faster than it's processed. 3. **CallbackFlow**: A flow built from callbacks, useful when you need to push data from outside the flow's scope. Offers more flexibility but can be less predictable. **The article highlights the following benefits of using these flow types:** * Improved code readability and maintainability compared to traditional callbacks. * Easier handling of asynchronous data processing and cancellation. * Increased flexibility and composability for building complex data pipelines. **The author provides practical examples and code snippets for each flow type, making the concepts easy to understand.** They also discuss common pitfalls and best practices for using these flows effectively. Overall, the article provides a valuable resource for developers who want to learn more about Kotlin flows and how to leverage them effectively in their projects. **Do you have any specific questions about the content or want me to delve deeper into any particular aspects of the article?** I'm happy to assist you further! * */ }
import GithubService from "@/services/GithubService"; import { useCallback, useEffect, useState } from "react"; interface userGithubIssueByIdProps { id: number; body: string; updated_at: string; title: string; html_url: string; comments: number; user: { login: string; } } export function useGetUserGithubIssueById({ id }: { id: number }) { const [userGithubIssue, setUserGithubIssue] = useState<userGithubIssueByIdProps>({ id: 0, body: "", updated_at: "", title: "", html_url: "", comments: 0, user: { login: "" } }); const [loading, setLoading] = useState(false); const getUserGithubIssues = useCallback(async () => { try { setLoading(true) const data = await GithubService.getUserGithubIssueById({ id }) setUserGithubIssue(data); } catch (error) { console.log(error) } setLoading(false) }, [id]); useEffect(() => { getUserGithubIssues() }, [getUserGithubIssues]); return { userGithubIssue, loading } }
6/8 <!DOCTYPE html> <html> <head> <title> Practice makes perfect! </title> <link type='text/css' rel='stylesheet' href='style.css'/> </head> <body> <p> <!-- Your code here --> <?php //creating a class class Dog { //creating publics public $numLegs = 4 ; public $name; //creating constructior and declaring it public function __construct($name){ $this->name =$name ; } //creating a fucntion greeting public function bark(){ return "Woof!"; } public function greet(){ return "My name is " . $this->name ; } } //two instances $dog1 = new Dog("Barker"); $dog2 = new Dog("Amigo"); echo $dog2->greet(); echo $dog1->bark(); ?> </p> </body> </html>
package handler import ( "log" "net/http" "time" "github.com/labstack/echo-contrib/session" "github.com/labstack/echo/v4" "github.com/RaivoKinne/Friends/internal/database" "github.com/RaivoKinne/Friends/internal/database/model" "github.com/RaivoKinne/Friends/utils" "github.com/RaivoKinne/Friends/web/templates/post" ) func PostPageHandler(c echo.Context) error { db, err := database.Connect() if err != nil { log.Fatal(err) } posts, err := utils.FetchPosts(db) if err != nil { log.Fatal(err) } defer db.Close() sess, err := session.Get("session", c) if err != nil { log.Println("Error getting session:", err) return err } userId, ok := sess.Values["UserId"].(int) if !ok { log.Println("User ID is nil or not of type int") } return utils.Render(c, post.Index(posts, userId)) } func PostHandler(c echo.Context) error { sess, err := session.Get("session", c) if err != nil { log.Println("Error getting session:", err) return err } if auth, ok := sess.Values["Authenticated"].(bool); !ok || !auth { log.Println("User is not authenticated") return c.Redirect(http.StatusFound, "/") } userId, ok := sess.Values["UserId"].(int) if !ok { log.Println("User ID is nil or not of type int") return c.Redirect(http.StatusFound, "/") } post := &model.Post{ UserID: userId, Content: c.FormValue("content"), CreatedAt: time.Now().UTC(), } db, err := database.Connect() if err != nil { log.Println("Error connecting to the database:", err) return err } defer db.Close() _, err = db.Exec(`CREATE TABLE IF NOT EXISTS posts ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT, content VARCHAR(255), created_at DATETIME, FOREIGN KEY (user_id) REFERENCES users(id) )`) if err != nil { log.Println("Error creating messages table:", err) return err } stmt, err := db.Prepare("INSERT INTO posts (user_id, content, created_at) VALUES (?, ?, ?)") if err != nil { log.Println("Error preparing statement:", err) return err } defer stmt.Close() _, err = stmt.Exec(post.UserID, post.Content, post.CreatedAt) if err != nil { log.Println("Error inserting message into the database:", err) return err } return c.Redirect(302, "/posts") } func DeletePostHandler(c echo.Context) error { sess, err := session.Get("session", c) if err != nil { log.Println("Error getting session:", err) return err } if auth, ok := sess.Values["Authenticated"].(bool); !ok || !auth { log.Println("User is not authenticated") return c.Redirect(http.StatusFound, "/") } userId, ok := sess.Values["UserId"].(int) if !ok { log.Println("User ID is nil or not of type int") return c.Redirect(http.StatusFound, "/") } db, err := database.Connect() if err != nil { log.Println("Error connecting to the database:", err) return err } defer db.Close() stmt, err := db.Prepare("DELETE FROM posts WHERE id = ? AND user_id = ?") if err != nil { log.Println("Error preparing statement:", err) return err } defer stmt.Close() _, err = stmt.Exec(c.Param("id"), userId) if err != nil { log.Println("Error deleting post:", err) return err } return c.Redirect(http.StatusFound, "/posts") }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import {MatButtonModule} from '@angular/material/button'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatInputModule} from '@angular/material/input'; import {MatDividerModule} from '@angular/material/divider'; import {MatSelectModule} from '@angular/material/select'; import {MatIconModule} from '@angular/material/icon'; import {MatTabsModule} from '@angular/material/tabs'; import { MatSnackBarModule } from '@angular/material/snack-bar'; import { ReactiveFormsModule } from '@angular/forms'; import { LoginComponent } from './components/login/login.component'; import { RouterModule } from '@angular/router'; import { TipoDePedidosComponent } from './components/tipo-de-pedidos/tipo-de-pedidos.component'; import { PedidoNoAdheridoComponent } from './components/pedido-no-adherido/pedido-no-adherido.component'; import { PagoComponent } from './components/pago/pago.component'; import { FormsModule } from '@angular/forms'; import { Servicios } from './services'; import { Componentes } from './components'; import { DetallesPedidoComponent } from './components/detalles-pedido/detalles-pedido.component'; import { PedidoConfirmadoComponent } from './components/pedido-confirmado/pedido-confirmado.component'; import {MatCardModule} from '@angular/material/card'; import {MatDatepickerModule} from '@angular/material/datepicker'; import {MatNativeDateModule} from '@angular/material/core'; import {NgxMatDatetimePickerModule, NgxMatNativeDateModule } from '@angular-material-components/datetime-picker'; import {MatTooltipModule} from '@angular/material/tooltip'; @NgModule({ declarations: [ AppComponent, ...Componentes ], imports: [ BrowserModule, BrowserAnimationsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatDividerModule, MatSelectModule, MatIconModule, MatTabsModule, MatSnackBarModule, NgxMatNativeDateModule, ReactiveFormsModule, MatCardModule, MatDatepickerModule, MatNativeDateModule, NgxMatDatetimePickerModule, MatTooltipModule, FormsModule, RouterModule.forRoot([ {path: 'login', component: LoginComponent}, {path: 'tipo-de-pedido', component: TipoDePedidosComponent}, {path: 'pedido-no-adherido', component: PedidoNoAdheridoComponent}, {path: 'pago', component: PagoComponent}, {path: 'detalles-pedido', component: DetallesPedidoComponent}, {path: 'pedido-confirmado', component: PedidoConfirmadoComponent}, {path: '', redirectTo: '/login', pathMatch: 'full'}, ]), ], providers: [...Servicios ], bootstrap: [AppComponent] }) export class AppModule { }
import React, { useState } from "react"; import classNames from "classnames"; import { Outlet, useLocation, useNavigate } from "react-router"; import { useSelector } from "react-redux"; import { FormattedMessage } from "react-intl"; import { NavLink } from "react-router-dom"; import { AnimatedLogo } from "../AnimatedLogo"; import { Pictogram } from "../Pictogram"; import { LanguageButtons } from "../LanguageButtons"; import { pictogramData } from "../Pictogram/PictogramData"; import { setAccountInfo } from "../../redux/actions/userActions"; import { useTypedDispatch } from "../../redux/store/store"; import { selectAvatar, selectUserName, } from "../../redux/selectors/userSelectors"; import { Button } from "../../uikit/Button"; import { BurgerMenuIcon, CloseBurgerMenu, Logout } from "../Icons"; import { Sidebar } from "../../pages/PersonalCabinet/Sidebar"; import { deleteCookie, getCookie } from "../../utils/cookieHandlers"; import defaultAvatar from "../../uikit/static/avatar.png"; import { Container } from "../Container"; import "./headerStyles.css"; export const pathsWithDarkBackground = ["/", "/registration", "/recovery"]; export const Header = () => { const { pathname } = useLocation(); const token = getCookie("token"); const avatar = useSelector(selectAvatar); const userName = useSelector(selectUserName); const dispatch = useTypedDispatch(); const navigate = useNavigate(); const [isBurgerMenuOpen, setIsBurgerMenuOpen] = useState(false); const handleLogout = () => { dispatch(setAccountInfo(null)); deleteCookie("token"); navigate("/"); setIsBurgerMenuOpen(false); }; const handleClick = () => { setIsBurgerMenuOpen(false); }; const handleBurgerMenuClick = () => { setIsBurgerMenuOpen(!isBurgerMenuOpen); }; return ( <Container> <div className={classNames("header-wrapper", { light: !pathsWithDarkBackground.includes(pathname), })} > <div className="header-animated-logo"> <AnimatedLogo /> </div> <ul className={classNames( "header-wrapper_pictogram", isBurgerMenuOpen && "header-wrapper_pictogram_active" )} > {pictogramData.map((pict) => ( <Pictogram componentIcon={pict.componentIcon} text={pict.text} key={pict.id} link={pict.link} closeBurgerMenu={handleClick} /> ))} </ul> {!pathsWithDarkBackground.includes(pathname) && token && ( <div className={classNames( "user-login-block", isBurgerMenuOpen && "user-login-block_active" )} > {userName && ( <div className="user-login-avatar-wrapper"> <img className="user-login-avatar" src={ avatar ? `data:image/jpg;base64,${avatar}` : defaultAvatar } alt="avatar" width="32" height="32" /> <NavLink className="user-login-block-link" to="/cabinet/personal-info" onClick={handleClick} > {userName} </NavLink> </div> )} <Button className="user-login-btn" onClick={handleLogout}> <> <Logout className="user-logout-icon" /> <FormattedMessage id="logout" /> </> </Button> </div> )} <LanguageButtons /> <Button onClick={handleBurgerMenuClick}> {!isBurgerMenuOpen ? ( <BurgerMenuIcon className="header-burger-menu" /> ) : ( <CloseBurgerMenu className="close-burger-menu-icon" /> )} </Button> </div> <Outlet /> {isBurgerMenuOpen && ( <Sidebar isBurgerMenuOpen={isBurgerMenuOpen} closeBurgerMenu={handleClick} /> )} </Container> ); };
const { response } = require("@hapi/hapi/lib/validation"); const { nanoid } = require('nanoid'); const books = require('./books'); // Menambahkan Buku const addBook = (request, h) => { const { name, year, author, summary, publisher, pageCount, readPage, reading, } = request.payload; if (!name) { const response = h.response({ status: 'fail', message: 'Gagal menambahkan buku. Mohon isi nama buku', }); response.code(400); return response; } if (readPage > pageCount) { const response = h.response({ status: 'fail', message: 'Gagal menambahkan buku. readPage tidak boleh lebih besar dari pageCount', }); response.code(400); return response; } const id = nanoid(16); const insertedAt = new Date().toISOString(); const updatedAt = insertedAt; const finished = pageCount === readPage; const newBook = { id, name, year, author, summary, publisher, pageCount, readPage, finished, reading, insertedAt, updatedAt }; books.push(newBook); const isSuccess = books.filter((book) => book.id === id).length > 0; if (isSuccess) { const response = h.response({ status: 'success', message: 'Buku berhasil ditambahkan', data: { bookId: id, }, }); response.code(201); return response; } const response = h.response({ status: 'error', message: 'Buku gagal ditambahkan', }); response.code(500); return response; }; // Menampilkan seluruh buku const getAllBook = (request, h) => { const { name, reading, finished } = request.query; if (!name && !reading && !finished){ const response = h.response({ status: 'success', data:{ books: books.map((book) => ({ id: book.id, name: book.name, publisher: book.publisher, })), }, }); response.code(200); return response; } if (name){ const filterBooksName = books.filter((book) => { const nameRegex = new RegExp(name, 'gi'); return nameRegex.test(book.name); }); const response = h.response({ status: 'success', data:{ book: filterBooksName.map((book) => ({ id: book.id, name: book.name, publisher: book.publisher, })), }, }); response.code(200); return response; } if (reading){ const filterBooksReading = book.filter( (book) => Number(book.reading) === Number(reading), ); const response = h.response({ status: 'success', data:{ books: filterBooksReading.map((book) => ({ id: book.id, name: book.name, publisher: book.publisher, })), }, }); response.code(200); return response; } const filterBooksFinished = books.filter( (book) => Number(book.finished) === Number(finished), ); const response = h.response({ status: 'success', data:{ books: filterBooksFinished.map((book) => ({ id: book.id, name: book.name, publisher: book.publisher, })), }, }); response.code(200); return response; }; // Menampilkan buku dengan ID const getBookById = (request, h) => { const { bookId } = request.params; const book = books.filter((book) => book.id == bookId)[0]; if (book === undefined) { const response = h.response({ status: "fail", message: "Buku tidak ditemukan", }); response.code(404); return response; } else { const response = h.response({ status: "success", data: { book, }, }); response.code(200); return response; } }; // Mengubah data buku const editBookById = (request, h) => { const { bookId } = request.params; const { name, year, author, summary, publisher, pageCount, readPage, reading } = request.payload; const finished = pageCount === readPage; const updateAt = new Date().toISOString; if(!name){ const response = h.response({ status: 'fail', message: 'Gagal memperbarui buku. Mohon isi nama buku', }); response.code(400); return response; } if (readPage > pageCount){ const response = h.response({ status: 'fail', message: 'Gagal memperbarui buku. readPage tidak boleh lebih besar dari pageCount', }); response.code(400); return response; } const index = books.findIndex((book) => book.id === bookId); if (index !== -1){ books[index] ={ name, year, author, summary, publisher, pageCount, readPage, reading, finished, updateAt, }; const response = h.response({ status: 'success', message: 'Buku berhasil diperbarui', }); response.code(200); return response; } const response = h.response({ status: 'fail', message: 'Gagal memperbarui buku. Id tidak ditemukan', }); response.code(404); return response; }; //Menghapus buku const deleteBookById = (request, h) => { const { bookId } = request.params; const index = books.findIndex((book) => book.id === bookId); if (index !== -1) { books.splice(index, 1); const response = h.response({ status: 'success', message: 'Buku berhasil dihapus', }); response.code(200); return response; } const response = h.response({ status: 'fail', message: 'Buku gagal dihapus. Id tidak ditemukan', }); response.code(404); return response; }; module.exports = { addBook, getAllBook, getBookById, editBookById, deleteBookById, };
<template> <div id="app"> <list-images :photos="photos" @select="selectIndex"/> <slider :photos="photos" :index="index"/> </div> </template> <script> import ListImages from './components/ListImages.vue' import Slider from './components/Slider.vue' export default { data () { return { photos: ['https://images.unsplash.com/photo-1589009602500-c5137f420e80?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=600&ixlib=rb-1.2.1&q=80&w=800', 'https://images.unsplash.com/photo-1587725544257-9ae9f910ae8a?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=600&ixlib=rb-1.2.1&q=80&w=800', 'https://images.unsplash.com/photo-1586953805370-9300364ab6f7?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=600&ixlib=rb-1.2.1&q=80&w=800'], index: 0 } }, components: { ListImages, Slider }, methods: { selectIndex(index){ this.index = index }, changeIndex(){ if(this.index + 1 >= this.photos.length){ this.index = 0 } else{ this.index += 1 } } }, created() { setInterval(this.changeIndex, 2000) } } </script> <style> * { box-sizing: border-box; } #app { width: 1100px; text-align: center; margin-top: 60px; display: flex; } </style>
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # class Solution: # def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int: # if not root: # return 0 # if not root.left and not root.right: # return 1 # left = self.count_left(root.left, 1) # right = self.count_right(root.right, 1) # return left + right # def count_left(self, root, c1): # if not root: # return 0 # while root: # if root.left: # c1 *= 2 # root = root.left # continue # if root.right: # c1 = c1*2 - 1 # root = root.right # return c1 # def count_right(self, root, c1): # if not root: # return 0 # while root: # if root.right: # c1 *= 2 # root = root.right # continue # if root.left: # c1 = c1*2 - 1 # root = root.left # return c1 class Solution: def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int: if not root: return 0 queue = deque([(root, 0)]) # store nodes along with their positions max_width = 0 while queue: level_length = len(queue) _, first = queue[0] for i in range(level_length): node, col_index = queue.popleft() if node.left: queue.append((node.left, 2*col_index)) if node.right: queue.append((node.right, 2*col_index + 1)) max_width = max(max_width, col_index - first + 1) return max_width
import { useAddress, useSDK } from "@thirdweb-dev/react"; import { useWeb3Context } from "context/web3Context"; import { BigNumber } from "ethers"; import { useQuery, UseQueryOptions } from "react-query"; export type Balance = { symbol: string; value: BigNumber; name: string; decimals: number; displayValue: string; }; export default function useWalletBalance( address: string | undefined, options?: Omit< UseQueryOptions<Balance, unknown, Balance, "wallet-balance">, "queryKey" | "queryFn" > ) { const sdk = useSDK(); const fetchBalance = async () => await sdk!.wallet.balance(); return useQuery("wallet-balance", fetchBalance, { enabled: !!address && !!sdk, ...options, }); }
import CGPIOD public enum MonitorType { case continuus case event } public enum GPIOError: Error { case openChipFailure case getLineFailure case lineRequestInputFailure case streamFailure case getValueFailed case triedReadingFromOutputPin } public enum GPIODirection { case input(MonitorType) case output } enum ActiveState { case high case low case unknown init(_ rawValue: Int32) { switch rawValue { case Int32(GPIOD_LINE_ACTIVE_STATE_HIGH): self = .high case Int32(GPIOD_LINE_ACTIVE_STATE_LOW): self = .low default: self = .unknown } } } enum BiasType { case pullUp case pullDown case disable case asIs case unknown init(_ rawValue: Int32) { switch rawValue { case Int32(GPIOD_LINE_BIAS_PULL_UP): self = .pullUp case Int32(GPIOD_LINE_BIAS_PULL_DOWN): self = .pullDown case Int32(GPIOD_LINE_BIAS_DISABLE): self = .disable case Int32(GPIOD_LINE_BIAS_AS_IS): self = .asIs default: self = .unknown } } } public enum EventType { case risingEdge case fallingEdge case bothEdges case timeout case unknown init(ctxless: Int32) { switch ctxless { case Int32(GPIOD_CTXLESS_EVENT_CB_RISING_EDGE): self = .risingEdge case Int32(GPIOD_CTXLESS_EVENT_CB_FALLING_EDGE): self = .fallingEdge case Int32(GPIOD_CTXLESS_EVENT_CB_TIMEOUT): self = .timeout default: self = .unknown } } init(lineEvent: Int32) { switch lineEvent { case Int32(GPIOD_LINE_EVENT_RISING_EDGE): self = .risingEdge case Int32(GPIOD_LINE_EVENT_FALLING_EDGE): self = .fallingEdge default: self = .unknown } } }
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #if WITH_VERSE_VM || defined(__INTELLISENSE__) #include "Containers/StringFwd.h" #include "HAL/Platform.h" #include "Misc/EnumClassFlags.h" class FString; namespace Verse { struct FAllocationContext; struct VCell; struct VEmergentType; struct VInt; struct VRestValue; struct VValue; struct FCellFormatter { virtual ~FCellFormatter() {} // Format the cell into a string. Where possible, use a string builder and the Append method below virtual FString ToString(FAllocationContext Context, VCell& Cell) const = 0; // Format the cell into an existing string builder. virtual void Append(FStringBuilderBase& Builder, FAllocationContext Context, VCell& Cell) const = 0; }; enum class ECellFormatterMode : uint8 { EnableToString = 1 << 0, ///< First try to use the ToString method to format the cell EnableVisitor = 1 << 1, ///< Second try to use the VisitReferences to format the cell (Warning, ATM this doesn't handle circular references) IncludeCellNames = 1 << 2, ///< Wrap the value of the cell with the debug name of the cell FormatAddresses = 1 << 3, ///< Format addresses when enabled, otherwise use a constant string for unit testing UniqueAddresses = 1 << 4, ///< Add the address of UniqueString or UniqueStringSet to the output }; ENUM_CLASS_FLAGS(ECellFormatterMode); struct FDefaultCellFormatter : FCellFormatter { static constexpr ECellFormatterMode DefaultMode = ECellFormatterMode::EnableToString | ECellFormatterMode::IncludeCellNames | ECellFormatterMode::UniqueAddresses | ECellFormatterMode::FormatAddresses; FDefaultCellFormatter(ECellFormatterMode InMode = DefaultMode) : Mode(InMode) { } // FCellFormatter implementation COREUOBJECT_API virtual FString ToString(FAllocationContext Context, VCell& Cell) const override; COREUOBJECT_API virtual void Append(FStringBuilderBase& Builder, FAllocationContext Context, VCell& Cell) const override; protected: // This helper method appends the cell to the string builder but without any of the debugging address text. // This allows such things as unit tests to override Append to provide stable strings to compare. COREUOBJECT_API virtual bool TryAppend(FStringBuilderBase& Builder, FAllocationContext Context, VCell& Cell) const; void BeginCell(FStringBuilderBase& Builder, VCell& Cell) const; void EndCell(FStringBuilderBase& Builder) const; void AppendAddress(FStringBuilderBase& Builder, const void* Address) const; ECellFormatterMode Mode; }; COREUOBJECT_API FString ToString(const VInt& Int); COREUOBJECT_API FString ToString(FAllocationContext Context, const FCellFormatter& Formatter, const VValue& Value); COREUOBJECT_API FString ToString(FAllocationContext Context, const FCellFormatter& Formatter, const VRestValue& Value); COREUOBJECT_API void ToString(FStringBuilderBase& Builder, FAllocationContext Context, const FCellFormatter& Formatter, const VValue& Value); COREUOBJECT_API void ToString(FStringBuilderBase& Builder, FAllocationContext Context, const FCellFormatter& Formatter, const VRestValue& Value); } // namespace Verse #endif // WITH_VERSE_VM
// SPDX-License-Identifier: MIT // Compatible with OpenZeppelin Contracts ^5.0.0 pragma solidity ^0.8.20; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract OnePieceNFT is ERC721, ERC721URIStorage, Ownable { uint256 private _nextTokenId; constructor() ERC721("OnePieceNFT", "ONF") Ownable(msg.sender) {} function safeMint(address to, string memory uri) public onlyOwner returns (uint256){ uint256 tokenId = _nextTokenId++; _safeMint(to, tokenId); _setTokenURI(tokenId, uri); return tokenId; } function mint(string memory uri) external returns (uint256){ uint256 tokenId = _nextTokenId++; _safeMint(msg.sender, tokenId); _setTokenURI(tokenId, uri); return tokenId; } // The following functions are overrides required by Solidity. function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721URIStorage) returns (bool) { return super.supportsInterface(interfaceId); } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OrderService = void 0; const tslib_1 = require("tslib"); const node_binance_api_1 = tslib_1.__importDefault(require("node-binance-api")); const Order_1 = tslib_1.__importDefault(require("../schemas/Order")); class OrderService { constructor() { this.log = require("log-beautify"); this.binance = new node_binance_api_1.default().options({ APIKEY: process.env.API_KEY, APISECRET: process.env.API_SECRET }); this.profitRate = 0.0262713; this.lossRate = 0.0082713; this.startAmount = 30; } closeOrder(orderItem, earn, price, symbols) { return tslib_1.__awaiter(this, void 0, void 0, function* () { let mySymbol = symbols.find((s) => s.symbol === orderItem.symbol); let myCoin = orderItem.symbol.replace('USDT', ''); this.binance.openOrders(orderItem.symbol, (errorOpenDoors, openOrders, symbol) => { let mainTrade = openOrders.find((tr) => tr.orderId.toString() === orderItem.orderId); if (!mainTrade) { this.binance.balance((errorBalance, balances) => { var _a, _b, _c, _d, _e; if (errorBalance) console.error(errorBalance.body); if (!errorBalance) { let newPrice = (_b = (price.split('.').length > 0 && (mySymbol === null || mySymbol === void 0 ? void 0 : mySymbol.priceDecimal) > 0 && price.split('.')[0] + '.' + price.split('.')[1].substr(0, parseInt((_a = mySymbol === null || mySymbol === void 0 ? void 0 : mySymbol.priceDecimal) !== null && _a !== void 0 ? _a : 0)))) !== null && _b !== void 0 ? _b : price; let coinsAvailable = (_c = balances[myCoin]) === null || _c === void 0 ? void 0 : _c.available; let quantity = (_d = orderItem.quantity) !== null && _d !== void 0 ? _d : 0; if (orderItem.quantity > coinsAvailable) { if (coinsAvailable > 0) { quantity = coinsAvailable; } } if (coinsAvailable > orderItem.quantity) { if (((parseFloat(coinsAvailable) - parseFloat(orderItem.quantity)) * parseFloat(newPrice)) < (this.startAmount / 2)) { quantity = coinsAvailable; } } let newQuantity = (mySymbol === null || mySymbol === void 0 ? void 0 : mySymbol.quantityDecimal) > 0 ? quantity.split('.').length > 0 && quantity.split('.')[0] + '.' + quantity.split('.')[1].substr(0, parseInt((_e = mySymbol === null || mySymbol === void 0 ? void 0 : mySymbol.quantityDecimal) !== null && _e !== void 0 ? _e : 0)) : parseInt(quantity); console.log('realQuantity =>', quantity, coinsAvailable, myCoin, orderItem.quantity); this.binance.sell(orderItem.symbol, newQuantity, newPrice, { type: 'LIMIT' }, (errorSell, response) => tslib_1.__awaiter(this, void 0, void 0, function* () { if (errorSell) { console.log('ERRO AO VENDER', errorSell.body); } ; if (!errorSell) { console.info("VENDIDO: " + response.orderId, earn); yield this.createNewOrder(orderItem.symbol, price, orderItem.quantity, 'SELL', 'CLOSE', 0, response.orderId, this.profitRate, this.lossRate); yield Order_1.default.findOneAndUpdate({ _id: orderItem._id, }, { $set: { status: 'FINISH', earn: earn.toString() } }); } })); } }); } }); }); } setStopOrder(orderItem) { return tslib_1.__awaiter(this, void 0, void 0, function* () { yield Order_1.default.findOneAndUpdate({ _id: orderItem._id }, { $set: { sendStop: true } }); }); } setProfitOrder(orderItem) { return tslib_1.__awaiter(this, void 0, void 0, function* () { yield Order_1.default.findOneAndUpdate({ _id: orderItem._id }, { $set: { sendProfit: true } }); }); } verifyOpenOrders(symbol, price, lastCandle, symbols) { return tslib_1.__awaiter(this, void 0, void 0, function* () { var openOrders = yield Order_1.default.find({ status: 'OPEN', symbol }); yield Promise.all(openOrders.map((orderItem) => tslib_1.__awaiter(this, void 0, void 0, function* () { this.binance.openOrders(symbol, (errorOpenDoors, openOrderss, symbol) => tslib_1.__awaiter(this, void 0, void 0, function* () { let mainTrade = JSON.parse(JSON.stringify(openOrderss)).find((tr) => tr.orderId.toString() === orderItem.orderId); if (!mainTrade) { yield Order_1.default.findOneAndUpdate({ _id: orderItem._id }, { $set: { active: true } }); } })); }))); var activeOrders = yield Order_1.default.find({ status: 'OPEN', symbol, active: true }); var floatingEarn = 0; var floatingLoss = 0; yield Promise.all(activeOrders.map((orderItem) => tslib_1.__awaiter(this, void 0, void 0, function* () { var _a, _b; let priceBuy = orderItem.price * orderItem.quantity; let priceNow = price * orderItem.quantity; let earnF = priceNow - priceBuy; let objetivo = (orderItem.price * orderItem.quantity) * 1.015; let trailingStop = yield this.trailingStopLoss(orderItem, earnF, price, lastCandle, symbols); var localLoss = 0; var localEarn = 0; if (trailingStop.next) { if (earnF > 0) { floatingEarn += earnF; localEarn = earnF; } if (earnF < 0) { localLoss = earnF; floatingLoss += earnF; if (price <= orderItem.price && orderItem.martinGale < 3) { let maxMartinLoss = 0.005; let maxLoss = (orderItem.price - (maxMartinLoss * orderItem.price)); let originalPrice = orderItem.price * orderItem.quantity; let takeLoss = (originalPrice) - (originalPrice * maxMartinLoss); let atualPrice = (price * orderItem.quantity); let mySymbol = symbols.find((s) => s.symbol === symbol); let quantity = (this.startAmount / price).toString(); let newQuantity = (mySymbol === null || mySymbol === void 0 ? void 0 : mySymbol.quantityDecimal) > 0 ? (quantity.split('.').length > 1 && quantity.split('.')[0] + '.' + quantity.split('.')[1].substr(0, parseInt((_a = mySymbol === null || mySymbol === void 0 ? void 0 : mySymbol.quantityDecimal) !== null && _a !== void 0 ? _a : quantity.toFixed()))) : parseInt(quantity); let newPrice = price.split('.').length > 1 ? price.split('.')[0] + '.' + price.split('.')[1].substr(0, parseInt((_b = mySymbol === null || mySymbol === void 0 ? void 0 : mySymbol.priceDecimal) !== null && _b !== void 0 ? _b : 0)) : price; let warningLoss = (orderItem.price - 0.005 * orderItem.price); if (price <= warningLoss) this.log.warn('MAX LOSS ', maxLoss, 'BUY AT ', orderItem.price); if (atualPrice <= takeLoss) { let martinSignal = orderItem.martinSignal + 1; if (martinSignal >= 20) { this.log.error(`MAX LOSS REACHEAD ${takeLoss} OPENING MARTINGALE ${orderItem.martinGale + 1}`); this.binance.buy(symbol, newQuantity, newPrice, { type: 'LIMIT' }, (error, response) => tslib_1.__awaiter(this, void 0, void 0, function* () { if (error) console.log(error); if (!error) { console.info("Martingale! " + response.orderId); yield Order_1.default.findOneAndUpdate({ _id: orderItem._id, }, { $set: { martinGale: 99, martinSignal: 0 } }); yield this.createNewOrder(symbol, price, response.origQty, 'BUY', 'OPEN', 99, response.orderId, this.profitRate, this.lossRate); } })); } else { yield Order_1.default.findOneAndUpdate({ _id: orderItem._id, }, { $set: { martinSignal } }); } } } ; } ; if (localEarn > 0) { this.log.success(`[${symbol}]`, 'START:', priceBuy.toFixed(3), 'POSITION RESULT', (earnF + priceBuy).toFixed(3), 'GOAL', objetivo.toFixed(3), `WIN: ${localEarn.toFixed(3)}USDT - LOSS: ${localLoss.toFixed(3)}USDT`); } else { this.log.error(`[${symbol}]`, 'START:', priceBuy.toFixed(3), 'POSITION RESULT', (earnF + priceBuy).toFixed(3), 'GOAL', objetivo.toFixed(3), `WIN: ${localEarn.toFixed(3)}USDT - LOSS: ${localLoss.toFixed(3)}USDT`); } } }))); return { openOrders, floatingLoss, floatingEarn }; }); } calculateRates(originalPrice, profitRate, lossRate) { let binanceTax = (originalPrice / 1000) * 2; let takeProfit = (originalPrice + (originalPrice * profitRate)) + binanceTax; let stopLoss = (originalPrice - (originalPrice * lossRate)) + binanceTax; return { takeProfit, stopLoss }; } createNewOrder(currency, price, quantity = 4, order = 'SELL', status = 'OPEN', martingale = 0, orderId, profitRate, lossRate) { return tslib_1.__awaiter(this, void 0, void 0, function* () { let originalPrice = price * quantity; let { takeProfit, stopLoss } = this.calculateRates(originalPrice, profitRate, lossRate); yield Order_1.default.create({ symbol: currency, time: new Date().getTime(), price: price.toString(), quantity: quantity.toString(), status, order: order, orderId: orderId, martinGale: martingale, originalPrice, takeProfit, stopLoss }); }); } trailingStopLoss(orderItem, earnF, price, lastCandle, symbols) { return tslib_1.__awaiter(this, void 0, void 0, function* () { let next = true; let { originalPrice, stopLoss, takeProfit } = orderItem; let binanceTax = (originalPrice / 1000) * 2.5; let atualPrice = (price * orderItem.quantity); let balance = atualPrice - originalPrice; if (balance >= binanceTax) { let update = this.calculateRates(atualPrice, this.profitRate, 0.002713); if (update.stopLoss > stopLoss) { yield Order_1.default.findOneAndUpdate({ _id: orderItem._id }, { $set: { stopLoss: update.stopLoss.toString() } }); stopLoss = update.stopLoss; } } if (atualPrice >= takeProfit) { next = false; yield this.closeOrder(orderItem, balance.toString(), price, symbols); } if (atualPrice <= stopLoss) { next = false; yield this.closeOrder(orderItem, balance.toString(), price, symbols); } if (price >= (lastCandle === null || lastCandle === void 0 ? void 0 : lastCandle.high) && balance >= binanceTax && balance >= 0.1) { next = false; yield this.closeOrder(orderItem, balance.toString(), price, symbols); } return { next }; }); } } exports.OrderService = OrderService; //# sourceMappingURL=OrderService.js.map
# JavaPlayground Description: Welcome to JavaPrograms, your comprehensive repository of Java programs for learning and practicing Java programming! This repository is dedicated to providing a diverse collection of Java programs covering essential concepts, algorithms, and data structures. Whether you're a beginner seeking to grasp the basics or an experienced developer looking to sharpen your skills, JavaPrograms offers a wide range of programs to cater to your learning needs. Contents: Fundamental Programs: Explore basic Java programs that introduce fundamental programming concepts such as variables, loops, conditionals, classes and functions/methods. Problem-Solving Exercises: Challenge yourself with problem-solving exercises and programming puzzles designed to enhance your Java programming skills and problem-solving abilities. Java Language Features: Experiment with Java language features, syntax, and constructs through practical examples and exercises. How to Use: Clone or download this repository to your local machine. Browse the contents of the repository to find Java programs that align with your learning objectives or interests. Open the Java files in your preferred Java development environment or text editor. Study the code, understand the logic and algorithms, and experiment with modifying the programs to deepen your understanding. Compile and run the Java programs using standard Java development tools (e.g., JDK, IDEs) to see the output and observe the program behavior. Contribution: JavaPrograms encourages contributions from the Java community! If you have additional Java programs to share, improvements to existing programs, or corrections to make, feel free to fork this repository, make your changes, and submit a pull request. Together, we can create a valuable resource for Java learners and enthusiasts worldwide. Start your Java programming journey today with JavaPrograms and embark on a path of continuous learning and exploration in the world of Java programming!
package com.gitee.usl.kernel.queue; import cn.hutool.core.util.IdUtil; import com.gitee.usl.kernel.configure.Configuration; import com.googlecode.aviator.Expression; import java.util.StringJoiner; /** * 编译事件 * * @author hongda.li */ public class CompileEvent { private final String eventId; private String content; private Expression expression; private Configuration configuration; public CompileEvent() { // 雪花ID作为唯一ID this.eventId = IdUtil.getSnowflakeNextIdStr(); } public String getEventId() { return eventId; } public String getContent() { return content; } public CompileEvent setContent(String content) { this.content = content; return this; } public Expression getExpression() { return expression; } public CompileEvent setExpression(Expression expression) { this.expression = expression; return this; } public Configuration getConfiguration() { return configuration; } public CompileEvent setConfiguration(Configuration configuration) { this.configuration = configuration; return this; } @Override public String toString() { return new StringJoiner(", ", CompileEvent.class.getSimpleName() + "[", "]") .add("eventId='" + eventId + "'") .add("content='" + content + "'") .add("expression=" + expression) .add("configuration=" + configuration) .toString(); } }
// 藏书编目 catalog 路由模组 const express = require('express') const router = express.Router() // 导入控制器模块 const book_controller = require('../controllers/bookController') const author_controller = require('../controllers/authorController') const genre_controller = require('../controllers/genreController') const book_instance_controller = require('../controllers/bookinstanceController') // 藏书路由 // GET 获取藏书编目主页 router.get('/', book_controller.index) // GET 请求添加新的藏书。注意此项必须位于显示藏书的路由(使用了id)之前 router.get('/book/create', book_controller.book_create_get) router.post('/book/create', book_controller.book_create_post) // GET 请求删除藏书 router.get('/book/:id/delete', book_controller.book_delete_get) // POST 请求删除藏书 router.post('/book/:id/delete', book_controller.book_delete_post) // GET 请求更新藏书 router.get('/book/:id/update', book_controller.book_update_get) // POST 请求更新藏书 router.post('/book/:id/update', book_controller.book_update_post) // GET 请求藏书 router.get('/book/:id', book_controller.book_detail) // GET 请求完整藏书列表 router.get('/books', book_controller.book_list) /** */ // GET 请求添加新的藏书副本 router.get( '/bookinstance/create', book_instance_controller.book_instance_create_get ) // POST 请求添加新的藏书副本 router.post( '/bookinstance/create', book_instance_controller.book_instance_create_post ) // GET 请求删除藏书副本 router.get( '/bookinstance/:id/delete', book_instance_controller.book_instance_delete_get ) // POST 请求删除藏书副本 router.post( '/bookinstance/:id/delete', book_instance_controller.book_instance_delete_post ) // GET 请求更新藏书副本 router.get( '/bookinstance/:id/update', book_instance_controller.book_instance_update_get ) // POST 请求更新藏书副本 router.post( '/bookinstance/:id/update', book_instance_controller.book_instance_update_post ) // GET 请求藏书副本详情 router.get('/bookinstance/:id', book_instance_controller.book_instance_detail) // GET 请求获取藏书副本完整列表 router.get('/bookinstances', book_instance_controller.book_instance_list) /** */ // GET 请求添加新的藏书种类 router.get('/genre/create', genre_controller.genre_create_get) // POST 请求添加新的藏书种类 router.post('/genre/create', genre_controller.genre_create_post) // GET 请求删除藏书种类 router.get('/genre/:id/delete', genre_controller.genre_delete_get) // POST 请求删除藏书种类 router.post('/genre/:id/delete', genre_controller.genre_delete_post) // GET 请求更新藏书种类 router.get('/genre/:id/update', genre_controller.genre_update_get) // POST 请求更新藏书种类 router.post('/genre/:id/update', genre_controller.genre_update_post) // GET 请求藏书种类详情 router.get('/genre/:id', genre_controller.genre_detail) // GET 请求获取藏书种类完整列表 router.get('/genres', genre_controller.genre_list) /** */ // GET 请求添加新的作者 router.get('/author/create', author_controller.author_create_get) // POST 请求添加新的作者 router.post('/author/create', author_controller.author_create_post) // GET 请求删除作者 router.get('/author/:id/delete', author_controller.author_delete_get) // POST 请求删除作者 router.post('/author/:id/delete', author_controller.author_delete_post) // GET 请求更新作者 router.get('/author/:id/update', author_controller.author_update_get) // POST 请求更新作者 router.post('/author/:id/update', author_controller.author_update_post) // GET 请求作者详情 router.get('/author/:id', author_controller.author_detail) // GET 请求获取作者完整列表 router.get('/authors', author_controller.author_list) module.exports = router
<template> <div> <p style="font-style: normal; font-weight: 400; font-size: 14px; line-height: 14px; color: #686868; margin-bottom: 12px;" > Có thể nhập tối đa 03 loại đính kèm khai báo điện tử </p> <el-form label-position="top" label-width="100px" :model="formModel" size="mini" :rules="formModel" ref="formModel" > <el-row :gutter="20"> <el-col :span="16"> <div class="border-el-table" style="vertical-align: middle" > <el-row :gutter="20" class="text-center table-header-edit"> <el-col :span="1" style="word-break: break-word;"> STT </el-col> <el-col :span="11" style="word-break: break-word;"> Phân loại đính kèm </el-col> <el-col :span="11" style="word-break: break-word;"> Số đính kèm </el-col> </el-row> </div> <div v-if="!formModel.electronicAttachment || formModel.electronicAttachment.length === 0" class="el-table__empty-block" style="height: 100%; width: 100%;" > <span class="el-table__empty-text">Không có dữ liệu</span> </div> <el-form v-else ref="formToKhaiTriGia" :model="formModel" :rules="ruleFormDinhKemKhaiBao" style="padding-top: 0px" size="mini" label-width="0px" label-position="top" > <el-row v-for="(value, index) in formModel.electronicAttachment" :key="index" :gutter="10" class="border-bot" style="padding: 15px 0 0 0; margin-top: 0px;" > <el-col :span="1" style="padding-top: 5px"> {{ index + 1 }} </el-col> <input-select :rules="ruleFormDinhKemKhaiBao.classificationElectronicAttachment" style="margin-top: -1.4em; " :prop="'electronicAttachment[' + index + '].classificationElectronicAttachment'" label=" " :v-model.sync="formModel.electronicAttachment[index].classificationElectronicAttachment" :list-option-select="listHq" :number-gird-responsive="11" > </input-select> <input-text :rules="ruleFormDinhKemKhaiBao.electronicAttachmentNo" style="margin-top: -1.4em" label=" " :prop="'electronicAttachment[' + index + '].electronicAttachmentNo'" :v-model.sync="formModel.electronicAttachment[index].electronicAttachmentNo" maxlength="21" :number-gird-responsive="11" ></input-text> <el-col :span="1" class="text-center"> <el-tooltip :open-delay="400" content="Xóa" effect="light" placement="top"> <div class="custom-delete-button" style="font-size: medium"> <el-button size="mini" icon="el-icon-error" @click="delItem(formModel.electronicAttachment, index, validateDinhKem)" /> </div> </el-tooltip> </el-col> </el-row> <div class="EmptyBox20"></div> </el-form> <div class="text-left"> <el-button type="primary" size="mini" plain :disabled="formModel.electronicAttachment.length >= 3" icon="el-icon-circle-plus-outline" @click="addNewItem(formModel.electronicAttachment, DEFAULT_VALUE_DINH_KEM_KHAI_BAO, 'formModel', )" > <span>Thêm loại đính kèm</span> </el-button> </div> <div class="EmptyBox20"></div> </el-col> </el-row> </el-form> </div> </template> <script> import inputText from "@/components/InputEtc/input-text.vue"; import inputSelect from "@/components/InputEtc/input-select.vue"; import {listHq} from "@/untils/listCategory"; import {addNewItem, delItem, validateField} from "@/untils/untils"; import {numberRule, requiredRule} from "@/untils/validate"; const DEFAULT_VALUE_DINH_KEM_KHAI_BAO = { giayPhepMa: '', giayPhepNgay: '', giayPhepNgayCap: '', giayPhepNgayHh: '', giayPhepNguoiCap: '', giayPhepNoiCap: '', giayPhepSo: '', giayPhepTen: '' } export default { name: "step-dinh-kem-khai-bao-dien-tu", components: { inputText, inputSelect }, data() { return { formModel: { electronicAttachment: [] }, ruleFormDinhKemKhaiBao: { electronicAttachmentNo: [requiredRule('Số đính kèm'), numberRule('Số đính kèm')], classificationElectronicAttachment: [requiredRule('Phân loại đính kèm'), { validator: this.validateDuplicatePlDinhKemDt, trigger: ['change', 'blur'] }] }, listHq: listHq, DEFAULT_VALUE_DINH_KEM_KHAI_BAO, methods: { addNewItem, delItem, validateDinhKem(i) { if (this.formModel.electronicAttachment[i].electronicAttachmentNo) validateField('formModel', 'electronicAttachment[' + i + '].electronicAttachmentNo') }, validateDuplicatePlDinhKemDt(info, value, callback) { this.validateDuplicateMa(info, value, callback, this.formModel.electronicAttachment, 'electronicAttachment', 'classificationElectronicAttachment', 'Phân loại đính kèm') }, }, } }, methods: { delItem, addNewItem, validateDinhKem(i) { if (this.formModel.electronicAttachment[i].electronicAttachmentNo) this.validateField('formModel', 'electronicAttachment[' + i + '].electronicAttachmentNo') }, }, } </script> <style scoped> .el-form-item__label::before { content: ''; } .el-form-item__label::after { content: ''; } </style>
package usecase import ( "github.com/Kimoto-Norihiro/scholar-manager/model" "github.com/Kimoto-Norihiro/scholar-manager/repository" "github.com/go-playground/validator/v10" ) type InternationalConferenceEvaluationUsecase struct { repository repository.IInternationalConferenceEvaluationRepository validate *validator.Validate } func NewInternationalConferenceEvaluationUsecase(r repository.IInternationalConferenceEvaluationRepository) *InternationalConferenceEvaluationUsecase { return &InternationalConferenceEvaluationUsecase{ repository: r, validate: validator.New(), } } func (u *InternationalConferenceEvaluationUsecase) CreateInternationalConferenceEvaluation(m model.InternationalConferenceEvaluation) error { err := u.validate.Struct(m) if err != nil { return err } return u.repository.CreateInternationalConferenceEvaluation(m) } func (u *InternationalConferenceEvaluationUsecase) ListInternationalConferenceEvaluations() ([]model.InternationalConferenceEvaluation, error) { return u.repository.ListInternationalConferenceEvaluations() } func (u *InternationalConferenceEvaluationUsecase) UpdateInternationalConferenceEvaluation(m model.InternationalConferenceEvaluation) error { err := u.validate.Struct(m) if err != nil { return err } return u.repository.UpdateInternationalConferenceEvaluation(m) } func (u *InternationalConferenceEvaluationUsecase) GetInternationalConferenceEvaluationByInternationalConferenceIDAndYear(internationalConferenceID int, year int) (model.InternationalConferenceEvaluation, error) { return u.repository.GetInternationalConferenceEvaluationByInternationalConferenceIDAndYear(internationalConferenceID, year) } func (u *InternationalConferenceEvaluationUsecase) DeleteInternationalConferenceEvaluation(internationalConferenceID int, year int) error { return u.repository.DeleteInternationalConferenceEvaluation(internationalConferenceID, year) }
class StudentManagementSystem: def __init__(self): self.students = {} def add_student(self, student_id, name, grade): if student_id not in self.students: self.students[student_id] = {'Name': name, 'Grade': grade} print(f"Student {name} added successfully.") else: print("Student ID already exists. Please choose a different ID.") def remove_student(self, student_id): if student_id in self.students: del self.students[student_id] print("Student removed successfully.") else: print("Student ID not found.") def display_students(self): if not self.students: print("No students in the system.") else: print("Student Management System:") print("---------------------------") for student_id, details in self.students.items(): print(f"ID: {student_id}, Name: {details['Name']}, Grade: {details['Grade']}") print("---------------------------") # Example usage: if __name__ == "__main__": sms = StudentManagementSystem() while True: print("\nStudent Management System Menu:") print("1. Add Student") print("2. Remove Student") print("3. Display Students") print("4. Exit") choice = input("Enter your choice (1-4): ") if choice == '1': student_id = input("Enter Student ID: ") name = input("Enter Student Name: ") grade = input("Enter Student Grade: ") sms.add_student(student_id, name, grade) elif choice == '2': student_id = input("Enter Student ID to remove: ") sms.remove_student(student_id) elif choice == '3': sms.display_students() elif choice == '4': print("Exiting Student Management System. Goodbye!") break else: print("Invalid choice. Please enter a number between 1 and 4.")
#[repr(u8)] #[derive(Clone, Copy)] enum Dir { Left = 1, Right = 2, Up = 4, Down = 8, } impl Dir { fn x_increment(&self) -> i32 { match self { Dir::Up => -1, Dir::Down => 1, _ => 0, } } fn y_increment(&self) -> i32 { match self { Dir::Left => -1, Dir::Right => 1, _ => 0, } } } #[derive(Clone, Copy)] struct Beam { x: i32, y: i32, dir: Dir, } fn is_valid_beam(curr: &Beam, grid: &Vec<Vec<char>>) -> bool { curr.x >= 0 && curr.x < grid.len() as i32 && curr.y >= 0 && curr.y < grid[0].len() as i32 } fn get_next_beams(curr: &Beam, grid: &[Vec<char>]) -> Vec<Beam> { let element = grid[curr.x as usize][curr.y as usize]; let new_dirs = match (element, curr.dir) { ('.', _) | ('-', Dir::Left | Dir::Right) | ('|', Dir::Down | Dir::Up) => vec![curr.dir], ('/', Dir::Right) | ('\\', Dir::Left) => vec![Dir::Up], ('/', Dir::Down) | ('\\', Dir::Up) => vec![Dir::Left], ('/', Dir::Up) | ('\\', Dir::Down) => vec![Dir::Right], ('/', Dir::Left) | ('\\', Dir::Right) => vec![Dir::Down], ('|', Dir::Left | Dir::Right) => vec![Dir::Up, Dir::Down], ('-', Dir::Up | Dir::Down) => vec![Dir::Left, Dir::Right], _ => unreachable!(), }; new_dirs .iter() .map(|new_dir| Beam { x: curr.x + new_dir.x_increment(), y: curr.y + new_dir.y_increment(), dir: *new_dir, }) .collect::<Vec<_>>() } fn simulate_beam(grid: &Vec<Vec<char>>, starting_beam: &Beam) -> usize { let mut energized_grid = vec![vec![0; grid[0].len()]; grid.len()]; let mut queue = vec![*starting_beam]; while let Some(beam) = queue.pop() { if is_valid_beam(&beam, grid) && energized_grid[beam.x as usize][beam.y as usize] & beam.dir as u8 == 0 { queue.append(&mut get_next_beams(&beam, grid)); energized_grid[beam.x as usize][beam.y as usize] |= beam.dir as u8; } } energized_grid.iter().fold(0, |acc, row| { acc + row.iter().filter(|&&cell| cell != 0).count() }) } fn main() { let grid = include_str!("../../input/day16") .lines() .map(|line| line.chars().collect::<Vec<_>>()) .collect::<Vec<_>>(); let p1 = simulate_beam( &grid, &Beam { x: 0, y: 0, dir: Dir::Right, }, ); println!("p1: {p1:?}"); // grid.len() == grid[0].len() let starting_beams = (0..grid.len()) .flat_map(|i| { [ Beam { x: i as i32, y: 0, dir: Dir::Right, }, Beam { x: i as i32, y: grid[0].len() as i32 - 1, dir: Dir::Left, }, Beam { x: 0, y: i as i32, dir: Dir::Down, }, Beam { x: grid.len() as i32 - 1, y: i as i32, dir: Dir::Up, }, ] }) .collect::<Vec<_>>(); let max_energized = starting_beams .iter() .map(|s| simulate_beam(&grid, s)) .max() .unwrap(); println!("p2: {max_energized:?}"); }
package XindusAssignment.WishlistManagement.DTOs.ResponseDTOs; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * WishlistItemResponseDto represents the response DTO for a wishlist item. */ @NoArgsConstructor @AllArgsConstructor @Data public class WishlistItemResponseDto { /** * The unique identifier of the wishlist item. */ private int id; /** * The name of the wishlist item. */ private String name; /** * The description of the wishlist item. */ private String description; /** * The price of the wishlist item. */ private double price; /** * The user information associated with the wishlist item. */ private UserResponseDto userInfo; }
import { Ages } from '../enums'; import { selectAgeAchievements, selectPlayer, selectPlayerBoard, selectPlayerHand, selectPlayerScore, } from '../state/selectors'; import { checkIfPlayerCanAchieve } from '../utils/achievements'; import { calculateTotalTopCardsOnBoard } from '../utils/board'; import noop from '../utils/noop'; import { useDrawCard } from './dogma-actions/use-draw-card'; import { useMeldCard } from './dogma-actions/use-meld-card'; import { useRemoveCardFromHand } from './dogma-actions/use-remove-card-from-hand'; import { useAppSelector } from './use-app-selector'; import { usePlayerTakesAction } from './use-player-takes-action'; const BASE_ACTION_OPTIONS = { canAchieve: false, canDogma: false, canDraw: false, canMeld: false, drawAction: noop, meldAction: noop, }; export const useActionOptions = ({ player }: { player: string }) => { const playerData = useAppSelector(state => selectPlayer(state, player)); const playerAge = (playerData?.age as Ages) ?? Ages.ONE; const playerScore = useAppSelector(state => selectPlayerScore(state, player)); const ageAchievements = useAppSelector(selectAgeAchievements); const playerHand = useAppSelector(state => selectPlayerHand(state, player)); const playerBoard = useAppSelector(state => selectPlayerBoard(state, player)); const playerDrawAction = usePlayerTakesAction(player, useDrawCard); const playerMeldAction = usePlayerTakesAction(player, useRemoveCardFromHand, useMeldCard); if (!player) { return { ...BASE_ACTION_OPTIONS, }; } const canDogma = calculateTotalTopCardsOnBoard(playerBoard) > 0; const canMeld = playerHand.length > 0; const canAchieve = checkIfPlayerCanAchieve({ ageAchievements, playerAge, playerScore, }); return { ...BASE_ACTION_OPTIONS, canAchieve, canDogma, canDraw: true, canMeld, drawAction: playerDrawAction, meldAction: playerMeldAction, }; };
/** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { Translate } from 'react-redux-i18n' import { navigateTo2Fa } from 'redux/ui/navigation' import PropTypes from 'prop-types' import Button from 'components/common/ui/Button/Button' import './TwoFAWarningWidget.scss' import { prefix } from './lang' function mapDispatchToProps (dispatch) { return { handleGoTo2FA: () => dispatch(navigateTo2Fa()), } } @connect(null, mapDispatchToProps) export default class TwoFAWarningWidget extends PureComponent { static propTypes = { handleGoTo2FA: PropTypes.func, } render () { return ( <div styleName='header-container'> <div styleName='wallet-list-container'> <div styleName='wallet-container'> <div styleName='token-container'> <div styleName='subIcon'> <div styleName='icon' className='chronobank-icon'>security</div> </div> <div styleName='token-icon'> <div styleName='imageIcon' className='chronobank-icon'>wallet-circle</div> </div> </div> <div styleName='content-container'> <div styleName='title'><Translate value={`${prefix}.title`} /></div> <div styleName='text'><Translate value={`${prefix}.message`} /></div> <div styleName='actions-container'> <div styleName='action'> <Button disabled={false} type='submit' label={<Translate value={`${prefix}.button`} />} onClick={this.props.handleGoTo2FA} /> </div> </div> </div> </div> </div> </div> ) } }
function prompt { $location = $executionContext.SessionState.Path.CurrentLocation.path #detect .git folder if (Test-Path .git) { #change the pointer to bright green $pointer = "$($PSStyle.Foreground.BrightGreen)$([char]::ConvertFromUtf32(0x25B6))$($PSStyle.Reset)" } else { $pointer = [char]::ConvertFromUtf32(0x25B6) } #Some code to shorten long paths in the prompt #what is the maximum length of the path before you begin truncating? [int]$len = $Host.UI.RawUI.MaxWindowSize.width / 3 #33 if ($location.length -gt $len) { $diff = ($location.length - $len) #split on the path delimiter which might be different on non-Windows platforms $dsc = [system.io.path]::DirectorySeparatorChar #escape the separator character to treat it as a literal #filter out any blank entries which might happen if the path ends with the delimiter $split = $location -split "\$($dsc)" | Where-Object { $_ -match '\S+' } #reconstruct a shorted path if ($split.count -gt 2) { $here = "{0}$dsc{1}...$dsc{2}" -f $split[0], ($split[1][0..$diff] -join ''), $split[-1] } else { #I'm in a long top-level folder name $here = "{0}$dsc{1}..." -f $split[0], ($split[1][0..$diff] -join '') } } else { #length is ok so use the current location $here = $location } $dt = Get-Date -Format 'dd MMM HH:mm tt' Write-Host "[$($PSStyle.Foreground.FromRgb(255,215,0))$($PSStyle.Italic)$dt$($PSStyle.ItalicOff)] " -NoNewline #use truncated long path Write-Host "$($PSStyle.Bold)PS$($PSVersionTable.PSversion.major).$($PSVersionTable.PSversion.minor)$($PSStyle.BoldOff) $($PSStyle.Background.blue)$here$($PSStyle.Reset)$($pointer * ($nestedPromptLevel + 1))" -NoNewline Write-Output ' ' }
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] before_action :require_user, only: [:edit, :update, :destroy] before_action :same_user, only: [:edit, :update, :destroy] def index @users = User.paginate(page: params[:page], per_page: 3) end def new @user = User.new end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id flash[:notice] = "Welcome #{@user.username} to the Alpha Blog, you have successfully sign up your account! " redirect_to articles_path else render :new, status: :unprocessable_entity end end def destroy @user.destroy session[:user_id] = nil if @user == current_user flash[:notice] = "Account and all associated articles successfully deleted." redirect_to articles_path end def edit end def update if @user.update(user_params) flash[:notice] = "Your account information was successfully updated. " redirect_to user_path else redner :edit, status: :unprocessable_entity end end def show @articles = @user.articles.paginate(page: params[:page], per_page: 3) end private def user_params params.require(:user).permit(:username, :email, :password) end def set_user @user = User.find(params[:id]) end def same_user if current_user != @user && !current_user.admin? flash[:alert] = "You can only edit or delete your own account. " redirect_to @user end end end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> <link rel="stylesheet" href="assets/css/login.css"> <link href='https://unpkg.com/[email protected]/css/boxicons.min.css' rel='stylesheet'> <link href="https://cdn.jsdelivr.net/npm/[email protected]/fonts/remixicon.css" rel="stylesheet"> <script type="module" src="assets/js/register.js"></script> </head> <body> <div class="wrapper"> <form action=""> <h1>Cadastro</h1> <div class="input-box"> <input type="text" placeholder="E-mail" id="email" required> <i class='ri-mail-line'></i> </div> <div class="input-box"> <input type="text" placeholder="Nome" required> <i class='bx bxs-user'></i> </div> <div class="input-box"> <input type="password" placeholder="Senha" id="password" required> <i class='bx bxs-lock-alt' ></i> </div> <button id="submit" type="submit" class="btn">Registre-se</button> <div class="register-link"> <p>Já tem uma conta? <a href="login.html">Logar</a></p> </div> </form> </div> <script> // Import the functions you need from the SDKs you need import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-analytics.js"; import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/10.7.2/firebase-auth.js"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "AIzaSyDzvVWVOVcJ0qevAqwDzSnT-Smwf74EVyU", authDomain: "caixa-f89aa.firebaseapp.com", projectId: "caixa-f89aa", storageBucket: "caixa-f89aa.appspot.com", messagingSenderId: "913843692581", appId: "1:913843692581:web:c527f5fcdebb9c7a634bcc", measurementId: "G-R5X4EQMW6M" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); const email = document.getElementById('email').value; const password = document.getElementById('password').value; const submit = document.getElementById('submit').value; submit.addEventListener("click", function (event){ event.preventDefault() const email = document.getElementById('email').value; const password = document.getElementById('password').value; createUserWithEmailAndPassword(auth, email, password) .then((userCredential) => { const user = userCredential.user; alert("criando conta") }) .catch((error) => { const errorCode = error.code; const errorMessage = error.message; alert("erro") }); }) </script> </body> </html>
import React from 'react'; import { Link } from 'react-router-dom'; import { useSelector, useDispatch } from 'react-redux'; import { signOutUserStart } from './../../redux/User/user.actions'; import './stylesHead.scss'; import Logo from './../../assets/logo-payoneer.jpg'; const mapState = ({ user }) => ({ currentUser: user.currentUser }); const Header = props => { //access to dispatch const dispatch = useDispatch(); const { currentUser } = useSelector(mapState); const signOut = () => { dispatch(signOutUserStart()); }; return ( <header className="header"> <div className="wrap"> <div className="logo"> <Link to="/"> <img src={Logo} alt="logo" /> </Link> </div> <div className="callToActions"> {/* if user is loged in */} { currentUser && ( <ul> <li> <Link to="/dashboard"> My Account </Link> </li> <li> <span onClick={() => signOut()}> LogOut </span> </li> </ul> )} {/* if user is not loged in */} { !currentUser && ( <ul> <li> <Link to="/registration"> Register </Link> </li> <li> <Link to="/login"> Login </Link> </li> </ul> )} </div> </div> </header> ); }; Header.defaultProps = { currentUser: null }; export default Header;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Latest compiled and minified Bootstrap 3.3.7 CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="/css/style.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Sofia"> <link href="https://fonts.googleapis.com/css2?family=Quicksand&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@300&family=Quicksand&display=swap" rel="stylesheet"> <script src="https://kit.fontawesome.com/d6049e74e4.js" crossorigin="anonymous"></script> <meta property="og:title" content="Nae Jewerly" /> <meta property="og:url" content="https://naejewerly.herokuapp.com/" /> <meta property="og:image" content="images/naepic.png" /> <title>Home</title> </head> <body> <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="2000"> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="item active"> <div class="notif">Free Shipping on all orders over $50</div> </div> <div class="item"> <div class="notif">Shop our <a href="/gifts">Holiday Collection</a></div> </div> </div> </div> <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <!-- Collect the nav links, forms, and other content for toggling --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">nae</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav" id="mainlink"> <li>{{#navLink "/"}}HOME{{/navLink}}</li> <li>{{#navLink "/shop"}}SHOP{{/navLink}}</li> </ul> {{#if session.user}} <form class="navbar-form navbar-right"> <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" id="userMenu" data-toggle="dropdown"> <span class="glyphicon glyphicon-user"></span>&nbsp;&nbsp;{{session.user.userName}}&nbsp;&nbsp;<span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="userMenu"> <li><a href="/userHistory">User History</a></li> <li><a href="/logout">Log Out</a></li> </ul> </div> </form> <ul class="nav navbar-nav navbar-right"> {{#navLink "/images"}}Images{{/navLink}} {{#navLink "/employees"}}Employees{{/navLink}} {{#navLink "/departments"}}Departments{{/navLink}} </ul> {{else}} <form class="navbar-form navbar-right"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search"> <div class="input-group-btn"> <button class="btn btn-default" type="submit"> <i class="glyphicon glyphicon-search"></i> </button> </div> </div> <i class="fas fa-shopping-cart"></i> </form> {{/if}} </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> {{{body}}} <footer class="text-center"> <p>&copy; copyright </p> <p>All rights reserved by Natalie Vu</p> </footer> </div> <!-- Latest compiled and minified jQuery 3.2.1 JavaScript --> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="crossorigin="anonymous"></script> <!-- Latest compiled and minified Bootstrap 3.3.7 JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </body> </html>
#ifndef QUICKSWITCHBUTTON_H #define QUICKSWITCHBUTTON_H #include <QLabel> namespace dcc { class QuickSwitchButton : public QLabel { Q_OBJECT public: explicit QuickSwitchButton(const int index, const QString &iconName, QWidget *parent = 0); Q_PROPERTY(QString themeName READ themeName WRITE setThemeName) QString themeName() const; void setThemeName(const QString &themeName); bool checked() const { return m_checked; } signals: void hovered(const int index) const; void clicked(const int index) const; void checkedChanged(const bool checked) const; public slots: void setChecked(const bool checked); void setCheckable(const bool checkable); void setSelected(const bool selected); void setBackgroundVisible(const bool visible); protected: void mouseReleaseEvent(QMouseEvent *e); void enterEvent(QEvent *e); void paintEvent(QPaintEvent *e); private: QPixmap normalPixmap() const; QPixmap hoverPixmap() const; QPixmap pressedPixmap() const; private: const int m_index; bool m_selected; bool m_checked; bool m_checkable; bool m_showBackground; QString m_themeName; const QString m_iconName; }; } #endif //
import HTTP from "@/common/http"; const resource = "events"; function createParams(query, sort) { const params = new URLSearchParams(); if (query) { for (let i = 0; i < query.length; i++) { params.append(query[i].name, query[i].value); } } if (sort) params.append("sort", sort); return params.toString(); } async function find(url, query, sort) { const paramsStr = createParams(query, sort); if (paramsStr) url += "?" + paramsStr; const response = await HTTP.get(url); return response.data; } export default { async findAll(query, sort) { return find(resource, query, sort); }, async findPublishedUpcoming(query, sort) { return find(`${resource}/upcoming`, query, sort); }, async findPublishedPast(query, sort) { return find(`${resource}/past`, query, sort); }, async findUnreviewed(query, sort) { return find(`${resource}/unreviewed`, query, sort); }, async findRejected(query, sort) { return find(`${resource}/rejected`, query, sort); }, async findOne(id) { const event = (await HTTP.get(`${resource}/${id}`)).data; return event; }, async save(event) { if (event.id) { return (await HTTP.put(`${resource}/${event.id}`, event)).data; } else { return (await HTTP.post(`${resource}`, event)).data; } }, async delete(id) { return (await HTTP.delete(`${resource}/${id}`)).data; }, async saveEventImage(id, file) { const formData = new FormData(); formData.append("file", file); return ( await HTTP.post(`${resource}/${id}/image`, formData, { headers: { "Content-Type": "multipart/form-data", }, }) ).data; }, async deleteEventImage(idEvent, idImage) { return (await HTTP.delete(`${resource}/${idEvent}/image/${idImage}`)).data; }, };
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/customer.css"> <title>Desafio Modulo 02</title> </head> <body> <header> <h1>Curiosidades de Tecnologia</h1> <p>Tudo aquilo que você sempre quis saber sobre o mundo <br> Tech, em um único lugar</p> <nav> <ul> <a href="#">Home</a> <a href="#">Notícias</a> <a href="#">Curiosidades</a> <a href="#">Fale Conosco</a> </ul> </nav> </header> <main> <section> <h2>História do Mascote do Android</h2> <main> <section> <article> <h1>História do Mascote do Android</h1> <p> Provavelmente você sabe que o sistema operacional Android, mantido pelo Google é um dos mais utilizados para dispositivos móveis em todo o mundo. Mas tavez você não saiba que o seu simpático mascote tem um nome e uma história muito curiosa? Pois acompanhe esse artigo para aprender muita coisa sobre esse robozinho. </p> <h2>A primeira versão</h2> <p> A primeira tentativa de criar um mascote surgiu em 2007 e veio de um desenvolvedor chamado Dan Morrill. Ele conta que abriu o Inkscape (software livre para vetorização de imagens) e criou sua própria versão de robô. O objetivo era apenas personificar o sistema apenas para a a sua equipe, não existia nenhuma solicitação da empresa para a criação de um mascote. </p> <img src="img/dan-droids.png" alt="Vários Androids"> <p> Essa primeira versão bizarra até foi batizada em homenagem ao seu criador: seriam os Dandroids. </p> <h2>Surge um novo mascote</h2> <p> A ideia de ter um mascote foi amadurecendo e a missão foi passada para uma profissional da área. A ilustradora Russa Irina Blok, também funcionária do Google, ficou com a missão de representar o pequeno robô de uma maneira mais agradável. </p> <img src="img/irina-blok.jpg" alt="Imagem mulher"> <p> A ideia principal da Irina era representar tudo graficamente com poucos traços e de forma mais chapada. O desenho também deveria gerar identificação rápida com quem o olha. Surgiu então o Bugdroid, o novo mascote do Android. </p> <img class="img-centralizada" src="img/bugdroid.png" alt="Android Com Pessoa"> <p> A principal inspiração para os traços do novo Bugdroid veio daqueles bonequinhos que ilustram portas de banheiro para indicar o gênero de cada porta. Conta a lenda que a artista estava criando em sua mesa no escritório do Google e olhou para o lado dos banheiros e a identificação foi imediata: simples, limpo, objetivo. </p> <div class="video"> <iframe width="750" height="350" src="https://www.youtube.com/embed/APq1NA0kae8" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> <div class="texto-segundario"> <h3>Quer aprender mais? </h3> <p> Outro assunto curioso em relação ao Android é que cada versão sempre foi nomeada em homenagem a um doce, em ordem alfabética a partir da versão 1.5 até a 9.0. </p> <ul class="list-01"> <li> &#10004; 1.5 - Cupcake</li> <li> &#10004; 1.6 - Donut</li> <li> &#10004;3.0 - Eclair</li> <li> &#10004;2.2 - Froyo</li> <li> &#10004; 2.3 - Gingerbread</li> <li> &#10004; 3.0 - Honeycomb</li> <li> &#10004; 4.0 - Ice Cream Sandwich</li> </ul> <ul class="list-02"> <li> &#10004; 4.1 - Jelly Bean</li> <li> &#10004; KitKat </li> <li> &#10004; 5.0 - Lolipop</li> <li> &#10004; 6.0 - Marshmallow</li> <li> &#10004; 7.0 - Nougat</li> <li> &#10004; 8.0 - Oreo</li> <li> &#10004; 9.0 - Pie</li> </ul> </p> </p> <p> Infelizmente, o Android Q não existiu, pois o Google resolveu pôr fim a essa divertida prática e começou a usar numerações, o que deu origem ao Android 10. </p> <p> Acesse aqui o site Android History para conhecer a sequência das versões "adocicadas" e o que cada uma trouxe para o sistema Android. </p> </div> <div class="paragrafo-final"> <p> Então é isso! Espero que você tenha gostado do nosso artigo com essa curiosidade sobre o sistema Android e seu simpático mascote. </p> </div> </article> </section> </main> <footer> <h3>Site criado por Gustavo Guanabara para o CursoemVideo.</h3> </footer> </body> </html>
//! 与「浮点处理」有关的实用工具 use crate::macro_once; /// 「0-1」实数 /// 📌通过特征为浮点数添加「0-1 限制」方法 /// * 📝而非直接`impl FloatPrecision`:孤儿规则 pub trait ZeroOneFloat { /// 判断是否在范围内 fn is_in_01(&self) -> bool; /// 尝试验证「0-1」合法性 /// * 🎯不会引发panic,而是返回一个[`Result`] /// * 🚩在范围内⇒`Some(&自身)` /// * 🚩在范围外⇒`Err(错误信息)` /// * 📝不能直接使用`Result<Self, _>`:其编译时大小未知 fn try_validate_01(&self) -> Result<&Self, &str> { match self.is_in_01() { true => Ok(self), false => Err("「0-1」区间外的值(建议:`0<x<1`)"), } } /// 验证「0-1」合法性 /// * 📌只使用不可变借用:仅需比较,并且`Self`大小未知 /// * ⚠️若不在范围内,则产生panic /// * 🚩复用`try_validate_01`的消息 fn validate_01(&self) -> &Self { // * 📝这里直接使用`unwrap`即可:报错信息会写「called `Result::unwrap()` on an `Err` value: ...」 self.try_validate_01().unwrap() } } macro_once! { /// 批量实现「0-1」实数 /// * 🚩【2024-03-18 21:32:40】现在使用**宏**而非依赖「默认精度」超参数 /// * 📌减少重复代码,即便实际上只需实现两个类型 macro impl_zero_one_float($($t:tt)*) {$( /// 实现 impl ZeroOneFloat for $t { fn is_in_01(&self) -> bool { // * 📝Clippy:可以使用「区间包含」而非「条件组合」 // * 📝↓下边的`=`是「小于等于」「包含右边界」的意思 (0.0..=1.0).contains(self) } } )*} // 直接实现 f32 f64 } /// 单元测试/「0-1」实数 #[cfg(test)] mod tests_01_float { use super::*; use crate::{fail_tests, macro_once, show}; #[test] fn test_01_float_valid() { macro_once! { /// 辅助用测试宏/成功测试 /// /// ! 📝`, $(,)?`这里的「,」代表的不是「分隔表达式」,而是「模式中的`,`」 /// * 故应去除这前边的「,」 // 📝使用的时候,圆括号、方括号、花括号均可 macro test_valid($($num:expr),* $(,)?) { $( let v = $num.validate_01(); assert_eq!(*v, $num); show!($num.validate_01()); )* } // 从0.1到1.0 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 } } macro_once! { /// 辅助用测试宏/失败测试 /// /// ! 📝`, $(,)?`这里的「,」代表的不是「分隔表达式」,而是「模式中的`,`」 /// * 故应去除这前边的「,」 macro test_all_invalid($($name:ident => $num:expr),* $(,)?) { // 直接用`fail_tests!`生成失败测试 fail_tests!{ $( $name ($num.validate_01()); )* } } // 大数 fail_1_1 => 2.0, fail_3_0 => 3.0, fail_10_0 => 10.0, // 负数 fail_n_0_1 => -0.1, fail_n_0_2 => -0.2, fail_n_2_0 => -2.0, } }
import React, { useEffect, useState } from 'react' import { db } from "./firebase"; import "./Orders.css" import Order from "./Order"; import { useStateValue } from './StateProvider'; function Orders() { const[{ basket, user },dispatch] = useStateValue(); const [orders,setOrders] = useState([]); // 7:50:19 useEffect(()=>{ if(user){ db .collection('users') .doc(user?.uid) .collection("orders") .orderBy("created","desc") .onSnapshot(snapshot =>{ setOrders(snapshot.docs.map(doc => ({ id: doc.id, data: doc.data() }))) }) } else { setOrders([]); } },[user]) return ( <div className="orders"> <h1>Your Orders</h1> <div className="orders__order"> {orders?.map(order=>( <Order order={order}/> ))} </div> </div> ) } export default Orders
<template> <div class="min-h-full flex flex-col justify-center py-12 sm:px-6 lg:px-8"> <div class="sm:mx-auto sm:w-full sm:max-w-md"> <h2 class="mt-6 text-center text-4xl font-medium text-gray-900"> Inicia sesión </h2> </div> <div class="mt-8 sm:mx-auto sm:w-full sm:max-w-md"> <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10"> <form class="space-y-6" action="#" method="POST"> <Input name="email" placeholder="Email" v-model="email" label="Email" /> <Input name="password" v-model="password" label="Password" type="password" /> <div> <button @click.prevent="signIn" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-teal-600 hover:bg-teal-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"> Iniciar sesión </button> </div> <div class="relative flex justify-center text-sm"> <span class="px-2 bg-white text-gray-500"> ¿No tienes una cuenta? <router-link to="/" class="font-medium text-teal-600 hover:text-teal-500">Regístrate</router-link> </span> </div> </form> </div> </div> </div> </template> <script lang="ts"> import { defineComponent, ref } from "vue"; import Input from "@/components/Input.vue" import { key } from '@/store'; import { useStore } from "vuex"; export default defineComponent({ name: "SignIn", components: { Input }, setup: () => { let email = ref("") let password = ref("") const store = useStore(key) const signIn = () => { store.dispatch('login', { email: email.value, password: password.value, }) } return { email, password, signIn, } } }) </script>
(* Lecture 11b *) (* 1. If expressions are just matches. The compiler can actually replace if expressions with match expressions. if e0 then e1 else e2 becomes match e0 with true -> e1 | false -> e2 because type bool = true | false Equivalent to the ' condition ? (statement to be executed if true) : (statement to be executed if false) ' syntax in other imperative languages. 2. Option is a built in datatype. type 'a option = None | Some of 'a (* Useful when a NULL value has to be returned *) - None and Some are constructors - 'a means "any type" let string_of_intopt(x: int option) = match x with None -> "" Some(i) -> string_of_int(i) Example: a = max(lst), print(a+1); lst = []. This would cause a NPE in runtime. But, in OCaml, encapsulating a inside an Option constructor gives us the option to return a None value instead, diverting the NPE problem entirely. For instance, if lst is an empty list, OCaml will return a result of None. Doing so, the compiler will know that a None type carries no data at all, and therefore, will not even attempt to execute traverse the list to compute a = max(lst) and print(a+1), as lst will have to carry some data in the first place for such operations to be valid. This way, OCaml interdicts and blocks off any entry points that cause exceptions in runtime before even going into runtime. All of this happens at compile time. Other imperative languages can only figure this out at runtime. 3. List is another built-in datatype. type 'a list = Nil | Cons of 'a * 'a list let rec append (xs: 'a list) (ys: 'a list) = match xs with [] -> ys | x::xs' -> x :: (append xs' ys) OCaml uses [], ::, @ instead as syntactic sugar for Nil, Cons, and append *) let rec max_lst (lst: int list) : int option = match lst with [] -> None | h::t -> match max_lst t with None -> Some h | Some a -> Some (max a h) let lst = [] (* 4. Let expressions are pattern matches. The syntax on the LHS of = in a let expression is really a pattern: let p = e - (Variables are just one kind of pattern) Implies it's possible to do this let [x1; x2] = lst; [x1; x2] is a pattern that an "object" must have to be considered an instance of lst *) (* 5. Function arguments are patterns A function argument can also be a pattern - Match against the argument in a function call: let f p = e Examples: *) let sum_triple (x, y, z) = x + y + z (* 'a: generic type, aka alpha; can be used instead of explicit parameter type declarations similar to generics in Java and templates in C++. In C++ auto a = ... is used to infer the type of a automatically. Meanwhile, in Java, automatic type inference is not allowed. OCaml actively uses and encourages type inference by default. *) let rec len (xs: 'a list) = match xs with [] -> 0 | _::xs' -> 1 + len xs' (* Example: type 'a t = C1 [of t1] | C2 [of t2] | ... | Cn of [tn] type 'a option = None | Some of a *)
import React from "react"; import styles from "./Hotel.module.scss"; import { AiOutlineClose } from "react-icons/ai"; import { HiMinusCircle, HiPlusCircle } from "react-icons/hi"; import Button from "../common/Button"; import { useGlobalContext } from "../../context/useGlobal"; type PeopleProps = { setShow: React.Dispatch<React.SetStateAction<string>>; }; const PeopleCount: React.FC<PeopleProps> = ({ setShow }) => { const value = useGlobalContext(); return ( <div className={styles["people-main"]}> <div className={styles["price-head"]}> <h4>Accommodation</h4> <AiOutlineClose size={18} color={"var(--main-font-color)"} cursor="pointer" onClick={() => setShow("")} /> </div> <div className={styles["people-wrap"]}> <div className={styles["people-sub"]}> <h4>Adult</h4> <div className={styles["people-sub2"]}> <HiMinusCircle size={16} color={"var(--main-font-color)"} cursor="pointer" onClick={() => { if (value?.peopleData.adult === 1) return; value?.setPeopleData({ ...value?.peopleData, adult: value?.peopleData.adult - 1, }); }} /> <p>{value?.peopleData.adult}</p> <HiPlusCircle size={16} color={"var(--main-font-color)"} cursor="pointer" onClick={() => value?.setPeopleData({ ...value?.peopleData, adult: value?.peopleData.adult + 1, }) } /> </div> </div> <div className={styles["people-sub"]}> <h4>Children</h4> <div className={styles["people-sub2"]}> <HiMinusCircle size={16} color={"var(--main-font-color)"} cursor="pointer" onClick={() => { if (value?.peopleData.children === 0) return; value?.setPeopleData({ ...value?.peopleData, children: value?.peopleData.children - 1, }); }} /> <p>{value?.peopleData.children}</p> <HiPlusCircle size={16} color={"var(--main-font-color)"} cursor="pointer" onClick={() => value?.setPeopleData({ ...value?.peopleData, children: value?.peopleData.children + 1, }) } /> </div> </div> <div className={styles["people-sub"]}> <h4>Room</h4> <div className={styles["people-sub2"]}> <HiMinusCircle size={16} color={"var(--main-font-color)"} cursor="pointer" onClick={() => { if (value?.peopleData.room === 1) return; value?.setPeopleData({ ...value?.peopleData, room: value?.peopleData.room - 1, }); }} /> <p>{value?.peopleData.room}</p> <HiPlusCircle size={16} color={"var(--main-font-color)"} cursor="pointer" onClick={() => value?.setPeopleData({ ...value?.peopleData, room: value?.peopleData.room + 1, }) } /> </div> </div> </div> <Button buttonName="Submit" onClick={() => setShow("")} className={styles["price-button"]} /> </div> ); }; export default PeopleCount;