text
stringlengths
184
4.48M
import apiClient from "../config/apiClient"; import { StatisticForNew, TransactionSum, TransactionSummary } from "../model/Statistic"; import { GameDTO } from "./CartUtils"; export async function fetchNewOrderStatistics(): Promise<StatisticForNew[]> { try { const response = await apiClient.get('/api/transactions/statistics/new-orders'); return response.data.data as StatisticForNew[]; } catch (error) { console.error('Error fetching new order statistics:', error); throw error; } } export async function fetchNewUserStatistics(): Promise<StatisticForNew[]> { try { const response = await apiClient.get('/api/users/statistics/new-users'); return response.data.data as StatisticForNew[]; } catch (error) { console.error('Error fetching new user statistics:', error); throw error; } } export async function fetchTransactionSumStatistic(): Promise<TransactionSum> { try { const response = await apiClient.get('/api/transactions/statistics/sums'); return response.data.data as TransactionSum; } catch (error) { console.error('Error fetching transaction sum statistic', error); throw error; } } export async function fetchTransactionSummaryStatistic(): Promise<TransactionSummary[]> { try { const response = await apiClient.get('/api/transactions/statistics/summary'); return response.data.data as TransactionSummary[]; } catch (error) { console.error('Error fetching transaction sum statistic', error); throw error; } } export async function fetchSortedGames(field: string): Promise<GameDTO[]> { try { const response = await apiClient.get('/api/games/p/sort', { params: { field: field, page: 0, size: 5, } }); return response.data.data as GameDTO[]; } catch (error) { console.error('Error fetching sorted games:', error); throw error; } }
--- # try also 'default' to start simple theme: seriph # random image from a curated Unsplash collection by Anthony # like them? see https://unsplash.com/collections/94734566/slidev # background: https://cover.sli.dev background: /imgs/theme.avif # some information about your slides, markdown enabled title: Blue Shop class: text-center # https://sli.dev/custom/highlighters.html highlighter: shiki # https://sli.dev/guide/drawing drawings: persist: false # slide transition: https://sli.dev/guide/animations#slide-transitions transition: slide-left # enable MDC Syntax: https://sli.dev/guide/syntax#mdc-syntax mdc: true lineNumbers: true --- # Blue Shop <div class="pt-12"> <span @click="$slidev.nav.next" class="px-2 py-1 rounded cursor-pointer" hover="bg-white bg-opacity-10"> Press Space for next page <carbon:arrow-right class="inline"/> </span> </div> <div class="abs-br m-6 flex gap-2"> <button @click="$slidev.nav.openInEditor()" title="Open in Editor" class="text-xl slidev-icon-btn opacity-50 !border-none !hover:text-white"> <carbon:edit /> </button> <a href="https://github.com/jayhanjaelee/blue-shop" target="_blank" alt="GitHub" title="Open in GitHub" class="text-xl slidev-icon-btn opacity-50 !border-none !hover:text-white"> <carbon-logo-github /> </a> </div> <!-- 안녕하세요 코멘트 테스트입니다. --> --- # Blue-Shop 개발 : 이한재 쇼핑몰 웹서비스 개인 프로젝트 <br> ### 기간 : 3/17 ~ 3/25 (약 7일 소요) <br> ### 기술 스택 <br> - php 7.4.33 - code igniter 3 - mysql 8 - javascript, css --- # 발표 순서 1. 프로젝트 설정 2. 기능 시연 3. 기능 구현 <br> # 기능 구현 목록 1. 스타일 2. 회원가입 & 중복 검사 3. 로그인 & 로그아웃 4. 상품 목록 조회 5. 상품 목록 Pagination 6. 단일 상품 조회 7. 상품 구매 8. 상품 검색 --- <div style="display: flex; min-height: 50vh; justify-content: center; align-items: center;"> <h1>프로젝트 설정</h1> </div> --- # apache 설정 ### vhosts.conf ``` <VirtualHost 127.0.0.1:80> ServerName localhost DocumentRoot "/Users/jay/Desktop/Blue-Shop" <Directory "/Users/jay/Desktop/Blue-Shop"> Options Indexes FollowSymLinks AllowOverride all Require local </Directory> </VirtualHost> ``` <br> ### .htaccess ``` RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] ``` --- <div style="display: flex; min-height: 50vh; justify-content: center; align-items: center;"> <h1>기능 구현</h1> </div> --- # 1. 스타일 ### 폴더 구조 <br> ``` static/css ├── layout │   ├── carousel.css │   ├── footer.css │   ├── header.css │   ├── layout.css │   ├── login.css │   ├── new_products_section.css │   ├── product.css │   ├── products.css │   └── register.css ├── reset.css ├── style.css ├── typpograph.css ├── utils.css └── vars.css 2 directories, 14 files ``` --- # style.css ```css {all}{maxHeight:'400px'} @layer reset, typograph, utils; @layer layout; @layer layout.header, layout.carousel, layout.new_products_section, layout.footer; @layer layout.login; @layer layout.register; @layer layout.products; @layer layout.product; @import url("https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"); @import url('https://fonts.googleapis.com/css2?family=Noto+Sans:ital,wght@0,100..900;1,100..900&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Nanum+Gothic:wght@400;700;800&display=swap'); @import url(./vars.css); @import url(./reset.css); @import url(./typpograph.css); @import url(./utils.css); @import url(./layout/layout.css); /* Index Page */ @import url(./layout/header.css); @import url(./layout/carousel.css); @import url(./layout/new_products_section.css); @import url(./layout/footer.css); /* Login Page */ @import url(./layout/login.css); /* Register Page */ @import url(./layout/register.css); /* Products Page */ @import url(./layout/products.css); /* Product Page */ @import url(./layout/product.css); ``` --- # vars.css ### 필요한 색상 변수로 관리 <br> ```css {all}{maxHeight:'400px'} :root { --orange: #FA6230; --lightblue: #D1E8F7; --blue57: #5780E2; --blue31: #3168AD; --blue33: #3361E0; --lightgray: #eaeaea; --lightgray2: #efeaea; --graycd: #cdcbcb; --gray9b: #9B9B9B; --gray55: #555555; --grayb5: #B5B5B5; --graya9: #A9A9A9; --white: #F7F7F7; --darkwhite: #f7f7f7d9; --black33: #333333; } ``` --- # layout #### 마켓컬리 레이아웃 참고 ![figma](/imgs/figma.png) --- # header ```html {all}{maxHeight:'400px'} <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Blue Shop - <?= $title ?></title> <link rel="stylesheet" href="/static/css/style.css"> </head> ``` --- # footer ```html {all}{maxHeight:'400px'} <script src="https://kit.fontawesome.com/bacab07d7b.js" crossorigin="anonymous"></script> <script type="module" src="/static/js/constants.js"></script> <script type="module" src="/static/js/utils.js"></script> <script type="module" src="/static/js/user/logout.js"></script> <?php $path = explode('/', $_SERVER['REQUEST_URI'])[1] ?> <?php if ($path === 'register') { ?> <script type="module" src="/static/js/user/register.js"></script> <?php } ?> <?php if ($path === 'login') { ?> <script type="module" src="/static/js/user/login.js"></script> <?php } ?> <?php if ($path === 'products') { ?> <script type="module" src="/static/js/pagination.js"></script> <?php } ?> <?php if ($path === 'product') { ?> <script type="module" src="/static/js/product.js"></script> <?php } ?> ``` --- # 프로젝트 전체 폴더 구조 controllers, views, models ```sh {all}{maxHeight:'400px'} ./application/controllers ├── Api.php ├── Home.php ├── Login.php ├── Product.php ├── Products.php └── Register.php 1 directory, 6 files ./application/views ├── components │   ├── carousel.php │   ├── pagination.php │   └── search_pagination.php ├── home.php ├── login.php ├── product.php ├── products.php ├── products_by_search.php ├── register.php └── templates ├── footer.php └── header.php 6 directories, 24 files ./application/models ├── product_model.php └── user_model.php 1 directory, 2 files ``` --- # javascript ```sh static/js ├── constants.js ├── pagination.js ├── product.js ├── user │   ├── login.js │   ├── logout.js │   └── register.js └── utils.js 2 directories, 7 files ``` --- # DB Schema ```sql {1-11|13-21|23-29|31-35|37-44|all}{maxHeight:'400px'} -- users CREATE TABLE `users` ( `id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `user_id` varchar(12) UNIQUE NOT NULL, `password` varchar(255) NOT NULL, `name` varchar(6) NOT NULL, `email` varchar(255) UNIQUE NULL, `mobile_phone` varchar(255) UNIQUE NULL, `address` varchar(255) NULL, `point` INT UNSIGNED NULL DEFAULT 200000 ); -- products CREATE TABLE `products` ( `id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(255) NULL, `price` decimal(7,0) NULL, `stock` integer NULL DEFAULT 99, `image` varchar(255) NULL, `category_id` integer NOT NULL ); -- product foreign key ALTER TABLE `products` ADD CONSTRAINT `FK_categories_TO_products_1` FOREIGN KEY ( `category_id` ) REFERENCES `categories` ( `id` ); -- 카테고리 CREATE TABLE `categories` ( `id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(255) NULL ); -- 세션 테이블 CREATE TABLE IF NOT EXISTS `ci_sessions` ( `id` varchar(128) NOT NULL, `ip_address` varchar(45) NOT NULL, `timestamp` int(10) unsigned DEFAULT 0 NOT NULL, `data` blob NOT NULL, KEY `ci_sessions_timestamp` (`timestamp`) ); ``` --- # Router ```php {all}{maxHeight:'400px'} // Custom Routing $route['/'] = 'home'; $route['register'] = 'register'; $route['login'] = 'login'; $route['products'] = 'products'; $route['products/(:num)'] = 'products/getProducts/$1'; $route['product'] = 'product'; $route['product/(:num)'] = 'product/getProduct/$1'; // search results $route['products/search'] = 'products/getProductsBySearch/$1'; $route['products/search/(:num)'] = 'products/getProductsBySearch/$1'; // API $route['api/user/register'] = 'api/register'; $route['api/user/login'] = 'api/login'; $route['api/user/logout'] = 'api/logout'; $route['api/user/check/duplicate'] = 'api/check_duplicate'; $route['api/prouducts'] = 'api/products'; $route['api/prouducts/(:num)'] = 'api/products/$1'; $route['api/products/search'] = 'api/products_search'; $route['api/products/search/(:num)'] = 'api/products_search/$1'; $route['api/product'] = 'api/product'; $route['api/product/(:num)'] = 'api/product/$1'; $route['api/product/buy/(:num)'] = 'api/product_buy/$1'; ``` --- # BS_Controller ```php {1|2|4-8|10-30|32-41|all}{maxHeight:'400px'} class BS_Controller extends CI_Controller { public $pageTitle = 'Home'; public function __construct($_pageTitle) { parent::__construct(); $this->pageTitle = $_pageTitle; $this->load->model('user_model'); } public function render($params = null) { $user_info = null; if ($this->session->userdata('user_id')) { $user_info = $this->user_model->get_insensitive_info($this->session->userdata['user_id']); } // user 정보 session 에서 가져와서 header 에 로그인 정보 보여줌 $this->load->view( 'templates/header', array('title' => $this->pageTitle, 'user_info' => $user_info) ); // params 있으면 view 로드할 때 data binding. if (!empty($params)) { $this->load->view($this->pageTitle, $params); } else { $this->load->view($this->pageTitle); } $this->load->view('templates/footer'); } // view controller 단에서 api 요청하기 위한 메서드 _request($url) protected function _request($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); $response = curl_exec($ch); curl_close($ch); return $response; } } ``` --- <div style="display: flex; min-height: 50vh; justify-content: center; align-items: center;"> <h1>기능 시연</h1> </div> --- # 2. 회원가입 ### API: http://localhost/api/user/register POST ### request body ```json {monaco} { "user_id": "hanjaelee", "password": "1234", "re_password": "1234", "address" : "my address", "email": "jay@hanjaelee.com", "mobile_phone": "01099769307" } ``` ### response ```json {1-5|7-14|all}{maxHeight:'400px'} // 회원가입 성공 200 OK { "status": "success_then_redirect", "message": "회원가입 되었습니다." } // 이미 존재하는 유저 409 conflict { "status": "success", "message": "이미 존재하는 유저입니다.\n다른 아이디를 사용해주세요." } ``` --- # controllers/api.php ### register_post() method ```php {all}{maxHeight:'400px'} public function register_post() { $input_data = $this->_get_user_input(); $user = $this->user_model->get($input_data['user_id']); // 유저 정보 조회 후 존재하면 에러 리턴 if ($user !== null) { return $this->response( res['user_already_exists']['res'], res['user_already_exists']['code'], ); } // input 비밀번호, 비밀번호 확인 검사 if (!check_password($input_data['password'], $input_data['re_password'])) { return $this->response( res['fail_password_check']['res'], res['fail_password_check']['code'], ); } // 비밀번호 일치하면 회원가입 성공 $input_data['password'] = hash_password($input_data['password']); $result = $this->user_model->register($input_data); if (!$result) { return $this->response( res['fail_register']['res'], res['fail_register']['code'] ); } return $this->response( res['success_register']['res'], res['success_register']['code'] ); } ``` --- # 중복검사 ### API: http://localhost/api/user/check/duplicate POST ### request body ```json {monaco}{maxHeight:'400px'} { "user_id": "hanjaelee" } ``` ### response ```json {1-5|7-11|all}{maxHeight:'400px'} // 200 ok { "status": "success", "message": "사용가능한 아이디 입니다." } // 409 conflict { "status": "success", "message": "이미 존재하는 유저입니다.\n다른 아이디를 사용해주세요." } ``` --- # controllers/api.php ### check_duplicate_post() ```php {2-4|6-12|14-18|all}{maxHeight:'400px'} public function check_duplicate_post() { // 유저 조회 $input_data = $this->_get_user_input(); $user = $this->user_model->get_insensitive_info($input_data['user_id']); // 유저가 존재하지 않을 경우 사용가능한 아이디 if (!$user) { return $this->response( res['user_id_available']['res'], res['user_id_available']['code'], ); } // 중복 아이디 return $this->response( res['user_already_exists']['res'], res['user_already_exists']['code'], ); } ``` --- # 3. 로그인 & 로그아웃 ### API: http://localhost/api/user/login GET ### request body ```json {monaco}{maxHeight:'400px'} { "user_id": "hanjaelee", "password": "1234" } ``` ### response ```json {1-5|6-10|12-17|all}{maxHeight:'400px'} // 로그인 성공 200 OK { "status": "success_then_redirect", "message": "로그인 되었습니다." } // 존재하지 않는 사용자 400 Bad Request { "status": "fail", "message": "존재하지 않는 사용자입니다." } // 비밀번호 불일치 401 Unauthorized { "status": "fail", "message": "패스워드가 일치하지 않습니다." } ``` --- # controllers/api.php ### login_post() method ```php {1-5|7-10|12-18|20-25|27-41|all}{maxHeight:'400px'} private function _get_user_input() { // request body 읽는 부분 $data = json_decode(file_get_contents('php://input'), true); return $data; } public function login_post() { $input_data = $this->_get_user_input(); $user = $this->user_model->get($input_data['user_id']); // user id does not exists. if ($user === null) { return $this->response( res['user_not_exists']['res'], res['user_not_exists']['code'], ); } if (!verify_password($input_data['password'], $user->password)) { return $this->response( res['invalid_password']['res'], res['invalid_password']['code'] ); } // session 발급해서 리턴으로 주어야함 $payload = array( 'user_id' => $user->user_id, 'name' => $user->name, 'point' => $user->point, 'logged_in' => true ); // 로그인 성공했을 때 session 설정. $this->session->set_userdata($payload); return $this->response( res['success_login']['res'], res['success_login']['code'] ); } ``` --- # 로그아웃 ### API: http://localhost/api/user/logout GET ### response ```json {all} { "status": "success_then_redirect", "message": "로그아웃 되었습니다." } ``` ### controllers/api.php ```php {2|3-6}{maxHeight:'400px'} public function logout_get() { $this->session->sess_destroy(); return $this->response( res['success_logout']['res'], res['success_logout']['code'], ); } ``` --- # 4. 상품 목록 조회 ### API: localhost/api/products/{page}?category=fashion GET ### request ```txt {monaco}{maxHeight:'400px'} Query Params ?category=fashion ?category=food ?category=digital ``` --- # 상품 목록 조회 response ```json {all}{maxHeight:'450px'} { "products": [ { "id": "1", "name": "fashion item 01", "price": "43700", "stock": "92", "image": "1.avif", "category_id": "1" }, { "id": "2", "name": "fashion item 02", "price": "72700", "stock": "99", "image": "10.avif", "category_id": "1" }, { "id": "3", "name": "fashion item 03", "price": "73500", "stock": "99", "image": "1.avif", "category_id": "1" }, { "id": "4", "name": "fashion item 04", "price": "97400", "stock": "99", "image": "3.avif", "category_id": "1" }, { "id": "5", "name": "유니클로 데님자켓", "price": "25100", "stock": "99", "image": "6.avif", "category_id": "1" }, { "id": "6", "name": "fashion item 06", "price": "98700", "stock": "99", "image": "10.avif", "category_id": "1" } ], "count": "300" } ``` --- # controllers/api.php ### 상품목록 조회 ### categories 상수 ```php {all} define('categories', array( 'fashion' => 1, 'food' => 2, 'digital' => 3, )); ``` ```php {2-9|11-14|16-18|20-26|28-34|all}{maxHeight:'400px'} public function products_get($page = 1) { // 카테고리 유효성 검사 $is_valid_category = in_array($_GET['category'], array_keys(categories), true); if (!$is_valid_category) { return $this->response( res['invalid_category']['res'], res['invalid_category']['code'] ); } // 기본 property 설정 (카테고리 id, limit, offset) $cid = categories[$_GET['category']]; $limit = 6; $offset = ($page - 1) * $limit; // db products 테이블 에서 products, counts 조회 $products = $this->product_model->get_products($cid, $limit, $offset); $count = $this->product_model->get_products_count(array('cid' => $cid)); // 페이지가 더이상 없을 경우 에러리턴 if ($products === null) { return $this->response( res['no_more_products']['res'], res['no_more_products']['code'] ); } // 성공시 producst 배열에 저장하여 리턴 $data = array( 'products' => $products, 'count' => $count->products_count ); return $this->response($data, 200); } ``` --- # 5. 상품 목록 Pagination ### views/components/pagination.php ```php {2-4|6|8-12|14-18|20-25|all}{maxHeight:'450px'} <?php $page_count_at_once = 9; // 한 화면에 보여질 페이지 수 $products_count_at_once = 6; // 한 화면에 보여질 상품 수 $current_page = $this->uri->segment(2); // 현재 페이지 $max_page = ceil($data['count'] / $products_count_at_once); // 최대 페이지 개수 // page_group 어떤 페이지 번호가 속한 그룹의 값 // 1 page group -> 1,2,3,4,5,6,7,8,9 // 2 page group -> 10,11,12,13,14,15,16,17,18,19 // 3 page group -> 20,21,22,23,24,25,26,27,28,29 $page_group = ceil($current_page / $page_count_at_once); // 현재 페이지 그룹 // 한 화면에 보여지는 페이지 중 첫번째 페이지 // 1 page group -> 1 // 2 page group -> 10 // 3 page group -> 20 $first_page = (($page_group - 1) * $page_count_at_once) + 1; // 한 화면에 보여지는 페이지 중 마지막 페이지 // 1 page group -> 9 // 2 page group -> 19 // 3 page group -> 29 $last_page = $page_group * $page_count_at_once; ?> ``` --- # 6. 단일 상품 조회 ### API: http://localhost/api/product/{id} GET ### request url ```txt {monaco} http://localhost/api/product/1 ``` ### response ```json {all}{maxHeight:'400px'} // 200 ok { "id": "1", "name": "fashion item 01", "price": "43700", "stock": "94", "image": "1.avif", "category_id": "1" } ``` --- # controllers/api.php ### product_get() method ```php {2-3|5-11|13-14|all}{maxHeight:'400px'} public function product_get($product_id) { // db products 테이블에서 id 로 상품 조회 $product = $this->product_model->get($product_id); // 상품 존재하지 않을 경우 에러 리턴 if ($product === null) { return $this->response( res['not_exists_product']['res'], res['not_exists_product']['code'], ); } // 성공시 상품 리턴 return $this->response($product, 200); } ``` --- # 7. 상품 구매 ### API: http://localhost/api/product/buy/1 ### cookie ```txt ci_session=5b4ltd1e01021rs7km0cu120j49nc31m; Path=/; HttpOnly; ``` ### request body ```json {monaco}{maxHeight:'400px'} { "product_count": 1, "price": 43700 } ``` ### response ```json {1-5|7-11|all}{maxHeight:'400px'} // 200 ok { "status": "success_then_reload", "message": "상품 구매가 완료되었습니다." } // 400 bad request (포인트 부족) { "status": "fail", "message": "잔여 포인트가 부족합니다." } ``` --- # controllers/api.php ### product_buy_post($product_id) method ```php {2-4|6-10|12-19|21-27|30-36|all}{maxHeight:'400px'} public function product_buy_post($product_id) { // 유저 입력 설정 $input_data = $this->_get_user_input(); $data = $input_data; // 상품 구매가 가능한 포인트가 있는 유저인지 확인하기 위해 users 테이블에서 유저정보 조회 $user_info = $this->user_model->get_insensitive_info($this->session->userdata['user_id']); $data['user_id'] = $user_info->user_id; $data['name'] = $user_info->name; $data['point'] = intval($user_info->point); // 상품 재고 에러 $result = $this->product_model->update_stock($product_id, $data['product_count']); if (!$result) { $this->response( res['no_more_stock']['res'], res['no_more_stock']['code'], ); } // 유저 포인트 에러 $result = $this->user_model->update_point($data['user_id'], $data['price']); if (!$result) { $this->response( res['not_enough_point']['res'], res['not_enough_point']['code'], ); } // success return $this->response( $this->response( res['success_buy_product']['res'], res['success_buy_product']['code'], ) ); } ``` --- # 8. 상품 검색 ### API: http://localhost/api/products/search/{page}?query={query} ```txt Query Params ?query=item 1 ?query=키보드 ?query=갤럭시탭 ``` ### response ```json {all}{maxHeight:'400px'} { "products": [ { "id": "102", "name": "fashion item 102", "price": "18400", "stock": "99", "image": "8.avif", "category_id": "1" }, { "id": "103", "name": "fashion item 103", "price": "11800", "stock": "99", "image": "8.avif", "category_id": "1" }, { "id": "104", "name": "fashion item 104", "price": "92400", "stock": "99", "image": "9.avif", "category_id": "1" }, { "id": "105", "name": "fashion item 105", "price": "87700", "stock": "99", "image": "8.avif", "category_id": "1" }, { "id": "106", "name": "fashion item 106", "price": "13900", "stock": "99", "image": "6.avif", "category_id": "1" }, { "id": "107", "name": "fashion item 107", "price": "67200", "stock": "99", "image": "10.avif", "category_id": "1" } ], "count": "131" } ``` --- # controllers/api.php ### producst_search_get($page) method ```php {2-6|8-11|13-15|17-23|all}{maxHeight:'400px'} public function products_search_get($page = 1) { // query 설정 $query = ''; if (isset($_GET['query'])) { $query = $_GET['query']; } // limit, offset, query 공백 디코딩. $limit = 6; $offset = ($page - 1) * $limit; $query = urldecode($query); // %20 -> whitespace // producst db 에서 조회 $products = $this->product_model->get_products_by_search($query, $limit, $offset); $count = $this->product_model->get_products_count(array("query" => $query)); // 성공시 producst, count 반환 $data = array( 'products' => $products, 'count' => $count->products_count ); return $this->response($data, 200); } ``` --- <div style="display: flex; min-height: 50vh; justify-content: center; align-items: center;"> <h1>감사합니다.</h1> </div> ---
import React, { useState, useEffect } from "react"; import { NavItem } from "reactstrap"; import base_url from "../api/bootapi"; import axios from "axios"; import { toast } from "react-toastify"; import Faculty from "./Faculty"; const AllFaculty = () => { const getAllFaculty = () => { axios.get(`${base_url}/faculty`).then( (response) => { console.log(response.data); toast.success("faculty has been loaded") setFaculty(response.data); }, (error) => { console.log(error); } ); }; useEffect(() => { getAllFaculty(); }, []); const [faculty, setFaculty] = useState([]); // to refreah after delete course const removeFacultyByCode=(facultyId)=>{ setFaculty(faculty.filter((f)=>f.facultyId!=facultyId)); } return ( <div> <h1> All Faculty </h1> {faculty.length > 0 ? faculty.map((item) => ( <Faculty key={item.facultyId} faculty={item} update={removeFacultyByCode} /> )) : "No Faculty!"} </div> ); }; export default AllFaculty;
import psycopg2 from sql_queries import create_table_queries, drop_table_queries def create_database(): """ Creates Sparkify database """ # connect to default database conn = psycopg2.connect("host=127.0.0.1 dbname=studentdb user=student password=student") conn.set_session(autocommit=True) cur = conn.cursor() # create sparkify database with UTF8 encoding cur.execute("DROP DATABASE IF EXISTS sparkifydb") cur.execute("CREATE DATABASE sparkifydb WITH ENCODING 'utf8' TEMPLATE template0") # close connection to default database conn.close() # connect to sparkify database conn = psycopg2.connect("host=127.0.0.1 dbname=sparkifydb user=student password=student") cur = conn.cursor() return cur, conn def drop_tables(cur, conn): """ Drops existing tables. Args: cur: A psycopg2 connection cursor. conn: A psycopg2 connection. Returns: Nothing, but drops existing tables. """ for query in drop_table_queries: cur.execute(query) conn.commit() def create_tables(cur, conn): """ Creates tables inthe database. Args: cur: A psycopg2 connection cursor. conn: A psycopg2 connection. Returns: Nothing, but creates tables necessary for inserting data. """ for query in create_table_queries: cur.execute(query) conn.commit() def main(): """ Obtains cursor and connection, cleans database and creates tables Args: None. Returns: Nothing, but clears the environment before creating new tables. """ """ """ cur, conn = create_database() drop_tables(cur, conn) create_tables(cur, conn) conn.close() if __name__ == "__main__": main()
# README >This is a project to support AP Computer Science Principles (CSP) as well as a UC articulated Data Structures course. It was crafted iteratively starting in 2020 to the present time. The primary purposes are ... - Used as starter code for student projects for `AP CSP 1 and 2` and `Data Structures 1` curriculum. - Used to teach key principles in learning the Python Flask programming environment. - Used as a backend server to service API's in a frontend-to-backend pipeline. Review the `api` folder in the project for endpoints. - Contains a minimal frontend, mostly to support Administrative functionality using the `templates` folder and `Jinja2` to define UIs. - Contains SQL database code in the `model` folder to introduce concepts of persistent data and storage. Perisistence folder is `instance/volumes` for generated SQLite3 db. - Contains capabilities for deployment and has been used with AWS, Ubuntu, Docker, docker-compose, and Nginx to `deploy a WSGI server`. - Contains APIs to support `user authentication and cookies`, a great deal of which was contributed by Aiden Wu a former student in CSP. ## Flask Portfolio Starter Use this project to create a Flask Server. - GitHub link: [flask_2025](https://github.com/nighthawkcoders/flask_2025) - The runtime link is published under the About on the GitHub link. - `Create a template from this repository` if you plan on making GitHub changes. ## The conventional way to get started > Quick steps that can be used with MacOS, WSL Ubuntu, or Ubuntu; this uses Python 3.9 or later as a prerequisite. - Open a Terminal, clone a project and `cd` into the project directory. Use a `different link` and name for `name` for clone to match your repo. ```bash mkdir -p ~/nighthawk; cd ~/nighthawk git clone https://github.com/nighthawkcoders/flask_2025.git cd flask_2025 ``` - Install python dependencies for Flask, etc. ```bash python -m venv venv source venv/bin/activate pip install -r requirements.txt ``` ### Open project in VSCode - Prepare VSCode and run - From Terminal run VSCode ```bash code . ``` - Open Setting: Ctrl-Shift P or Cmd-Shift - Search Python: Select Interpreter. - Match interpreter to `which python` from terminal. - Shourd be ./venv/bin/python - From Extensions Marketplace install `SQLite3 Editor` - Open and view SQL database file `instance/volumes/user_management.db` - Make a local `.env` file in root of project to contain your secret passwords ```shell # User Defaults ADMIN_USER='toby' ADMIN_PASSWORD='123Toby!' DEFAULT_USER='hop' DEFAULT_PASSWORD='123Hop!' ``` - Make the database and init data. ```bash ./scripts/db_init.py ``` - Explore newly created SQL database - Navigate too instance/volumes - View/open `user_management.db` - Loook at `Users` table in viewer - Run the Project - Select/open `main.py` in VSCode - Start with Play button - Play button sub option contains Debug - Click on loop back address in terminal to launch - Output window will contain page to launch http://127.0.0.1:8087 - Login using your secrets ## Idea ### Visual thoughts > The Starter code should be fun and practical. - Organize with Bootstrap menu - Add some color and fun through VANTA Visuals (birds, halo, solar, net) - Show some practical and fun links (HREFs) like Twitter, Git, Youtube - Build a Sample Page (Table) - Show the project-specific links (HREFs) per page ### Files and Directories in this Project The key files and directories in this project are in this online article. [Flask Anatomy](https://nighthawkcoders.github.io/portfolio_2025/flask-anatomy) Or read this entire series of articles starting with the Intro, Anatomy, and more ... [Flask Intro](https://nighthawkcoders.github.io/portfolio_2025/flask-intro) ### Implementation Summary #### July 2024 > Updates for 2024 too 2025 school year. Primary addition is a fully functional backend for JWT login system. - Full support for JWT cookies - The API's for CRUD methods - The model definition User Class and related tables - SQLite and RDS support - Minimal Server side UI in Jinja2 #### July 2023 > Updates for 2023 to 2024 school year. - Update README with File Descriptions (anatomy) - Add JWT and add security features using a SQLite user database - Add migrate.sh to support sqlite schema and data upgrade #### January 2023 > This project focuses on being a Python backend server. Intentions are to only have simple UIs an perhaps some Administrative UIs. #### September 2021 > Basic UI elements were implemented showing server side Flask with Jinja 2 capabilities. - The Project entry point is main.py, this enables the Flask Web App and provides the capability to render templates (HTML files) - The main.py is the Web Server Gateway Interface, essentially it contains an HTTP route and HTML file relationship. The Python code constructs WSGI relationships for index, kangaroos, walruses, and hawkers. - The project structure contains many directories and files. The template directory (containing HTML files) and static directory (containing JS files) are common standards for HTML coding. Static files can be pictures and videos, in this project they are mostly javascript backgrounds. - WSGI templates: index.html, kangaroos.html, ... are aligned with routes in main.py. - Other templates support WSGI templates. The base.html template contains common Head, Style, Body, and Script definitions. WSGI templates often "include" or "extend" these templates. This is a way to reuse code. - The VANTA javascript statics (backgrounds) are shown and defaulted in base.html (birds) but are block-replaced as needed in other templates (solar, net, ...) - The Bootstrap Navbar code is in navbar.html. The base.html code includes navbar.html. The WSGI html files extend base.html files. This is a process of management and correlation to optimize code management. For instance, if the menu changes discovery of navbar.html is easy, one change reflects on all WSGI html files. - Jinja2 variables usage is to isolate data and allow redefinitions of attributes in templates. Observe "{% set variable = %}" syntax for definition and "{{ variable }}" for reference. - The base.html uses a combination of Bootstrap grid styling and custom CSS styling. Grid styling in observation with the "<Col-3>" markers. A Bootstrap Grid has a width of 12, thus four "Col-3" markers could fit on a Grid row. - A key purpose of this project is to embed links to other content. The "href=" definition embeds hyperlinks into the rendered HTML. The base.html file shows usage of "href={{github}}", the "{{github}}" is a Jinja2 variable. Jinja2 variables are pre-processed by Python, a variable swap with value, before being sent to the browser.
import FilterView from '../view/trip-filters.js'; import {render, RenderPosition, replace, remove} from '../utils/render.js'; import {FilterType, UpdateType} from '../const.js'; import dayjs from 'dayjs'; export default class Filter { constructor(filterContainer, filterModel, pointModel) { this._filterContainer = filterContainer; this._filterModel = filterModel; this._pointModel = pointModel; this._currentFilter = null; this._filterComponent = null; this._handleModelEvent = this._handleModelEvent.bind(this); this._handleFilterTypeChange = this._handleFilterTypeChange.bind(this); this._pointModel.addObserver(this._handleModelEvent); this._filterModel.addObserver(this._handleModelEvent); } init() { this._currentFilter = this._filterModel.getFilter(); const filters = this._getFilters(); const prevFilterComponent = this._filterComponent; this._filterComponent = new FilterView(filters, this._currentFilter); this._filterComponent.setFilterTypeChangeHandler(this._handleFilterTypeChange); if (prevFilterComponent === null) { render(this._filterContainer, this._filterComponent, RenderPosition.BEFOREEND); return; } replace(this._filterComponent, prevFilterComponent); remove(prevFilterComponent); } _getFilters() { return [ { type: FilterType.EVERYTHING, name: `EVERYTHING`, noPoints: !this._pointModel.getPoints().length }, { type: FilterType.FUTURE, name: `FUTURE`, noPoints: !this._pointModel.getPoints().some((point) => dayjs().isBefore(point.start)) }, { type: FilterType.PAST, name: `PAST`, noPoints: !this._pointModel.getPoints().some((point) => point.end.isBefore(dayjs())) }, ]; } _handleModelEvent() { this.init(); } _handleFilterTypeChange(filterType) { if (this._currentFilter === filterType) { return; } this._filterModel.setFilter(UpdateType.MAJOR, filterType); } }
package org.example.bo.custom.impl; import org.example.bo.custom.ProgramBO; import org.example.dao.DAOFactory; import org.example.dao.custom.ProgramDAO; import org.example.dto.ProgramDTO; import org.example.entity.Program; import java.util.ArrayList; import java.util.List; public class ProgramBOImpl implements ProgramBO { ProgramDAO programDAO = (ProgramDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOType.PROGRAM); @Override public List<ProgramDTO> getAll() throws Exception { List<ProgramDTO> programDTOList = new ArrayList<>(); List<Program> programList = programDAO.getAll(); for(Program program : programList) { programDTOList.add(new ProgramDTO(program.getProgramId(),program.getProgramName(),program.getDuration(),program.getFee())); } return programDTOList; } @Override public boolean add(ProgramDTO dto) throws Exception { return programDAO.add( new Program(dto.getProgramId(),dto.getProgramName(),dto.getDuration(), dto.getFee(),new ArrayList<>())); } @Override public boolean update(ProgramDTO dto) throws Exception { return programDAO.update( new Program(dto.getProgramId(),dto.getProgramName(),dto.getDuration(), dto.getFee(),new ArrayList<>())); } @Override public boolean exist(String id) throws Exception { return programDAO.exist(id); } @Override public boolean delete(String id) throws Exception { return programDAO.delete(id); } }
import React, {ChangeEvent, useCallback, useEffect, useState} from 'react'; import './modal.css'; import Modal from "@mui/material/Modal"; import AlertBasic from "../display/AlertBasic"; import { numberRegex } from "config/regexConfig"; import { commonAction } from "reducers/common"; import { ticketAction } from "reducers/ticket"; import { authAction } from "reducers/auth"; import { onChangeInput } from "utils/useOnChange"; import returnFalse from "utils/useReturnFalse"; import durationFormat from "utils/useDurationFormat"; import {useAppDispatch, useAppSelector} from "reducers/hooks"; import { checkVerificationCodeService, postVerificationCodeService } from "../../service/CommonService"; import {VerificationModalInputsType, VerificationModalType} from "../../types/componentsType"; const VerificationModal = ({ openPopup, setOpenPopup }: VerificationModalType) => { const postVerificationCode = useAppSelector((state) => state.ticket.postVerificationCode); const checkedPhoneNumber = useAppSelector((state) => state.auth.userPhoneNumber); const timerCount = useAppSelector((state) => state.common.timerCount); const timerActive = useAppSelector((state) => state.common.timerActive); const user = useAppSelector((state) => state.auth.user); const dispatch = useAppDispatch(); const [disabled, setDisabled] = useState(false); const [input, setInput] = useState<VerificationModalInputsType>({ name: user ? user?.name : "", phoneNumber: "", verificationCode: "", }); const { name, phoneNumber, verificationCode } = input; useEffect(() => { if (postVerificationCode) { let redo = setTimeout(() => setDisabled(true), 30000); return () => clearTimeout(redo); } }, [postVerificationCode]) useEffect(() => { if (user?.cellPhoneVerified === false) { dispatch(authAction.setUserPhoneNumber('')); } }, [user]) const clickClosePopup = (event: any, reason: any) => { if (reason && reason === "backdropClick") return; setOpenPopup(false); AlertBasic('인증이 취소되었습니다.', () => { setInput({ name: user ? user?.name : "", phoneNumber: "", verificationCode: "", }); dispatch(ticketAction.postVerification(false)); dispatch(commonAction.setTimerActive(false)); }) }; const getVerificationCode = useCallback((e: ChangeEvent<HTMLButtonElement>) => { e.preventDefault(); setDisabled(false); if (!checkedPhoneNumber) postVerificationCodeService(phoneNumber, name, setOpenPopup, input, setInput, false); else postVerificationCodeService(phoneNumber, name, setOpenPopup, input, setInput, true); }, [name, phoneNumber]); const chkVerificationCode = useCallback((e: ChangeEvent<HTMLButtonElement>) => { e.preventDefault(); if (!checkedPhoneNumber) checkVerificationCodeService(input.verificationCode, input.phoneNumber, setOpenPopup, input, setInput,false); else checkVerificationCodeService(input.verificationCode, input.phoneNumber, setOpenPopup, input, setInput, true); }, [verificationCode]); return ( <Modal open={openPopup} onClose={() => clickClosePopup} > <div className={`popupWrap`}> <div className={`popupContentWrap`}> <h3>휴대폰 번호 인증</h3> <form onSubmit={(e) => returnFalse(e)}> {!checkedPhoneNumber && <label> 성함 <input type={"text"} placeholder={"이름"} name={"name"} defaultValue={input.name} onChange={(e) => onChangeInput(e, input, setInput)} /> </label> } <div className={`phoneContainer`}> 휴대폰 번호 <label> <input type={"text"} placeholder={"01000000000"} name={"phoneNumber"} defaultValue={input.phoneNumber} maxLength={11} minLength={10} onChange={(e) => onChangeInput(e, input, setInput)} /> <button onClick={() => getVerificationCode} className={`btn`} disabled={postVerificationCode ? !disabled : input.name === "" || input.phoneNumber === "" || !numberRegex.test(input.phoneNumber) } > {postVerificationCode ? "재전송" : "인증코드 전송"} </button> </label> <span className={`${input.phoneNumber.length >= 1 && !numberRegex.test(input.phoneNumber) ? "spanInvalid" : "caption" }`}>* 숫자만 입력해주세요.</span> </div> <label> 인증 코드 <input name={"verificationCode"} type={"number"} onChange={(e) => onChangeInput(e, input, setInput)} disabled={!postVerificationCode} placeholder={"인증 코드를 입력해주세요."} /> { timerActive && <span className={"spanCorrect"} style={{ marginTop: '5px' }}>남은시간 {durationFormat(timerCount)}</span>} </label> </form> </div> <div className={`popupBtnWrap`}> <button className={`closeBtn`} onClick={() => clickClosePopup}>취소</button> <button className={`confirmBtn btn`} onClick={() => chkVerificationCode} disabled={input.verificationCode === undefined || input.verificationCode === "" || !postVerificationCode}>인증코드 확인</button> </div> </div> </Modal> ); }; export default VerificationModal;
"use client"; import { formatToUSD } from "@/helpers/format-number"; import { Badge, Breadcrumb, Button, Card, Label, Table, Textarea, TextInput, } from "flowbite-react"; import Image from "next/image"; import Link from "next/link"; import type { FC } from "react"; import { HiDocumentText, HiHome } from "react-icons/hi"; import type { ECommerceBillingPageData } from "./page"; const ECommerceBillingPageContent: FC<ECommerceBillingPageData> = function ({ nextPayment, orderHistory, }) { return ( <> <div className="mb-4 grid grid-cols-1 gap-y-6 px-4 pt-6 xl:grid-cols-2 xl:gap-4 dark:border-gray-700 dark:bg-gray-900"> <div className="col-span-full xl:mb-2"> <Breadcrumb className="mb-5"> <Breadcrumb.Item href="#"> <div className="flex items-center gap-x-3"> <HiHome className="text-xl" /> <span className="dark:text-white">Home</span> </div> </Breadcrumb.Item> <Breadcrumb.Item href="/e-commerce/products"> E-commerce </Breadcrumb.Item> <Breadcrumb.Item>Billing</Breadcrumb.Item> </Breadcrumb> <h1 className="text-xl font-semibold text-gray-900 sm:text-2xl dark:text-white"> Billing </h1> </div> <IntroCard nextPayment={nextPayment} /> <OrderHistoryCard orderHistory={orderHistory} /> </div> <div className="grid grid-cols-1 gap-y-4 px-4"> <GeneralInfoCard /> <CardDetailsCard /> </div> </> ); }; const IntroCard: FC<Pick<ECommerceBillingPageData, "nextPayment">> = function ({ nextPayment, }) { return ( <Card> <Link href="#" className="mb-6 inline-flex items-center text-2xl font-bold dark:text-white" > <Image alt="" width={43} height={44} src={nextPayment.logo} className="mr-4 h-11" /> <span>{nextPayment.service}</span> </Link> <p className="mb-2 text-base font-normal text-gray-500 dark:text-gray-400"> {nextPayment.serviceDescription} </p> <p className="text-sm font-semibold text-gray-900 dark:text-white"> Next payment of ${nextPayment.amount} ({nextPayment.interval}) occurs on&nbsp; {nextPayment.date}. </p> <div className="mt-6 space-y-4 sm:flex sm:space-x-3 sm:space-y-0"> <div> <Link href="#" className="inline-flex w-full items-center justify-center rounded-lg bg-primary-700 px-5 py-2.5 text-center text-sm font-medium text-white hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 sm:w-auto dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800" > <HiDocumentText className="-ml-1 mr-2 h-5 w-5" /> Change Plan </Link> </div> <div> <Link href="#" className="inline-flex w-full items-center justify-center rounded-lg border border-gray-300 bg-white px-5 py-2.5 text-center text-sm font-medium text-gray-900 hover:bg-gray-100 focus:ring-4 focus:ring-primary-300 sm:w-auto dark:border-gray-600 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white dark:focus:ring-gray-700" > Cancel Subscription </Link> </div> </div> </Card> ); }; const OrderHistoryCard: FC<Pick<ECommerceBillingPageData, "orderHistory">> = function ({ orderHistory }) { return ( <Card> <div className="mb-4 flex items-center justify-between"> <h3 className="text-xl font-bold text-gray-900 dark:text-white"> Order History </h3> <div className="shrink-0"> <Link href="#" className="rounded-lg p-2 text-sm font-medium text-primary-700 hover:bg-gray-100 dark:text-primary-500 dark:hover:bg-gray-700" > View all </Link> </div> </div> <div className="flex flex-col"> <div className="overflow-x-auto rounded-lg"> <div className="inline-block min-w-full align-middle"> <div className="overflow-hidden shadow sm:rounded-lg"> <Table striped> <Table.Head className="bg-gray-50 dark:bg-gray-700" theme={{ cell: { base: "p-4 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400", }, }} > <Table.HeadCell>Transaction</Table.HeadCell> <Table.HeadCell>Date &amp; Time</Table.HeadCell> <Table.HeadCell>Amount</Table.HeadCell> <Table.HeadCell>Status</Table.HeadCell> </Table.Head> <Table.Body> {orderHistory.map( ({ transaction, time, amount, status }) => ( <Table.Row key={`${transaction}-${time}`}> <Table.Cell className="whitespace-nowrap p-4 text-sm font-normal text-gray-900 dark:text-white"> {transaction} </Table.Cell> <Table.Cell className="whitespace-nowrap p-4 text-sm font-normal text-gray-500 dark:text-gray-400"> {time} </Table.Cell> <Table.Cell className="whitespace-nowrap p-4 text-sm font-semibold text-gray-900 dark:text-white"> {formatToUSD(amount)} </Table.Cell> <Table.Cell className="flex whitespace-nowrap p-4"> <Badge className="rounded-md font-medium" color={ status === "Completed" ? "success" : "failure" } > {status} </Badge> </Table.Cell> </Table.Row> ), )} </Table.Body> </Table> </div> </div> </div> </div> </Card> ); }; const GeneralInfoCard: FC = function () { return ( <Card> <h3 className="mb-4 text-xl font-bold dark:text-white"> General Information </h3> <form> <div className="mb-6 grid grid-cols-1 gap-6 md:grid-cols-3"> <div className="col-span-1 grid grid-cols-1 gap-y-4"> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="first-name">First Name</Label> <TextInput id="first-name" name="first-name" placeholder="Bonnie" required /> </div> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="organization">Organization</Label> <TextInput id="organization" name="organization" placeholder="Company Name" required /> </div> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="department">Department</Label> <TextInput id="department" name="department" placeholder="Development" required /> </div> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="city">City</Label> <TextInput id="city" name="city" placeholder="e.g. San Francisco" required /> </div> </div> <div className="col-span-1 grid grid-cols-1 gap-y-4"> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="last-name">Last Name</Label> <TextInput id="last-name" name="last-name" placeholder="Green" required /> </div> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="role">Role</Label> <TextInput id="role" name="role" placeholder="React Developer" required /> </div> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="country">Country</Label> <TextInput id="country" name="country" placeholder="United States" required /> </div> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="email">Email</Label> <TextInput id="email" name="email" placeholder="example@company.com" required /> </div> </div> <div className="col-span-1 flex flex-col gap-y-2"> <Label htmlFor="info">Info</Label> <Textarea id="info" name="info" placeholder="Receipt Info (optional)" rows={12} className="h-full" /> </div> </div> <Button color="blue" type="submit"> Update </Button> </form> </Card> ); }; const CardDetailsCard: FC = function () { return ( <Card> <h3 className="mb-4 text-xl font-bold dark:text-white">Card Details</h3> <form> <div className="mb-6 grid grid-cols-1 gap-6 sm:grid-cols-2"> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="full-name">(Full name as displayed on card)*</Label> <TextInput id="full-name" name="full-name" placeholder="Enter your name" required /> </div> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="card-number">Card Number *</Label> <TextInput id="card-number" name="card-number" placeholder="xxxx-xxxx-xxxx-xxxx" required /> </div> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="cvc">CVC *</Label> <TextInput id="cvc" name="cvc" placeholder="•••" required /> </div> <div className="grid grid-cols-1 gap-y-2"> <Label htmlFor="zip">Postal / ZIP code (optional)</Label> <TextInput id="zip" name="zip" placeholder="e.g. 12345" required /> </div> </div> <Button color="blue">Update</Button> </form> </Card> ); }; export default ECommerceBillingPageContent;
import torch import torch.nn as nn import torch.optim as optim import os from my_vit_models import MyViT2D DATA_DIR = "sample_data/2d/" BATCH_SIZE = 8 EPOCHS = 10 LEARNING_RATE = 0.001 PATCH_SIZE = 16 EMBED_DIM = 768 IMAGE_HEIGHT, IMAGE_WIDTH = 900, 600 IN_CHANNELS = 1 # Single 2D variable zeta def load_data(): file_paths = sorted([os.path.join(DATA_DIR, f) for f in os.listdir(DATA_DIR) if f.endswith(".pth")]) dataset = [] for path in file_paths: data = torch.load(path) #print(data.shape) data = data.squeeze(0).permute(2, 0, 1) dataset.append(data) return torch.cat(dataset, dim=0) def main(): #Prepare dataset + load model + optimizer + loss device = torch.device("cuda" if torch.cuda.is_available() else "cpu") data = load_data() data = data.unsqueeze(1) # Add channel dimension -> (batch_size, 1, 900, 600) train_loader = torch.utils.data.DataLoader(data, batch_size=BATCH_SIZE, shuffle=True) model = MyViT2D(in_channels=IN_CHANNELS, embed_dim=EMBED_DIM, image_height=IMAGE_HEIGHT, image_width=IMAGE_WIDTH, patch_size=30) model = model.to(device) criterion = nn.MSELoss() optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE) for epoch in range(EPOCHS): running_loss = 0.0 for inputs in train_loader: inputs = inputs.to(device, dtype=torch.float32) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, inputs) loss.backward() optimizer.step() running_loss += loss.item() print(f"Epoch {epoch+1}/{EPOCHS}, Loss: {running_loss/len(train_loader):.4f}") torch.save(model.state_dict(), "2d_vit.pth") print("Training complete.") if __name__ == "__main__": main()
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <script> /* 上面的代码运行结果完全符合预期,但同时也说明一个问题,在o1中修改了a和fn,而在o2中没有改变,由于数组和函数都是对象,是引用类型,这就说明o1中的属性和方法与o2中的属性与方法虽然同名但却不是一个引用,而是对Obj对象定义的属性和方法的一个复制。 这个对属性来说没有什么问题,但是对于方法来说问题就很大了,因为方法都是在做完全一样的功能,但是却又两份复制,如果一个函数对象有上千和实例方法,那么它的每个实例都要保持一份上千个方法的复制,这显然是不科学的,这可肿么办呢,prototype应运而生。 */ function Obj() { this.a = []; //实例变量 this.fn = function () { //实例方法 } } var o1 = new Obj(); o1.a.push(1); o1.fn = {}; console.log(o1.a); //[1] console.log(typeof o1.fn); //object var o2 = new Obj(); console.log(o2.a); //[] console.log(typeof o2.fn); //function </script> </body> </html>
import { Image, StyleSheet, View, ScrollView } from "react-native"; import ProductList from "../components/product/ProductList"; import { useContext, useEffect, useLayoutEffect, useState } from "react"; import { AuthContext } from "../store/auth-context"; import { getProductById, getProductIdByType } from "../util/http"; function ContentScreen({ navigation, route }) { const [products, setProducts] = useState([]); const authContext = useContext(AuthContext); const type = route.params?.type; const title = route.params?.title; useLayoutEffect(() => { navigation.setOptions({ title: title, // headerRight: ({ tintColor }) => { // return ( // <IconButton // style={{ borderWidth: 0, padding: 8 }} // icon={<Ionicons name="search" size={24} color={tintColor} />} // /> // ); // }, }); }, [navigation]); useEffect(() => { const getData = async () => { try { const productIds = await getProductIdByType(authContext.token, type); const products = []; for (const item of productIds) { try { const temp = await getProductById(authContext.token, item); products.push(temp); } catch (error) { console.log(error.message); } } setProducts(products); } catch (error) { console.log(error.message); } }; getData(); }, []); return ( <View style={styles.container}> <ScrollView> <View style={styles.bannerContainer}> <Image style={styles.image} source={require("../assets/images/PromotionImage.png")} /> </View> <View style={styles.productContainer}> <ProductList items={products} listOptions={{ numColumns: 2, initialNumToRender: 2, scrollEnabled: false, }} itemOptions={{ width: "46%" }} /> </View> </ScrollView> </View> ); } export default ContentScreen; const styles = StyleSheet.create({ container: { flex: 1, }, bannerContainer: { margin: 16, alignItems: "center", }, image: { resizeMode: "stretch", width: "100%", }, productContainer: { flex: 1, }, });
# PHP-REST-API There are many large organizations that provide access to their data to multiple systems. The stock market provides access to live data using APIs. News media also publish their news on multiple platforms using various APIs. You Can book a movie ticket using a website as well as using a mobile app. Both use some kind of APIs to communicate with each other. Social Media websites also use APIs to show your feed data into your website. There are so many uses of APIs in today’s time. In this project we well learn about PHP & REST APIs. REST and other APIs are used to provide communication and interaction between two systems. # What is REST? REST stands for REpresentational State Transfer. It is an architectural style for providing standards between network-based software. REST is a popular standard to create Web services. # REST APIs REST (or RESTful) API is a medium of communication between systems on the Internet. REST APIs works with multiple standards like HTTP, JSON, URL, and XML. REST APIs uses HTTP methods such as GET, HEAD, POST, PUT, DELETE to perform different operations. # JSON JSON stands for JavaScript Object Notation. JSON is a standard file format to transfer data between two applications. JSON data consist of attribute-value pairs rendered inside curly braces. JSON data can store objects, arrays, string, integer etc.
import React from 'react' // utils import Loader from '../loader/Loader'; import Error from '../error/Error'; import { STATUS } from '../../utils/status' import { setIsModalShowing, setModalData } from '../../store/modalSlice' // redux import { useSelector, useDispatch } from 'react-redux'; // compoenents import SingleProduct from '../singleProduct/SingleProduct'; const ProductList = ( {products, status}) => { const dispatch = useDispatch(); const { isModalShowing } = useSelector((state) => state.modal); // handle modal const handleTheModal = (data) => { // console.log(data) dispatch(setModalData(data)); dispatch(setIsModalShowing(true)); }; // loading if(status === STATUS.ERROR) return (<Error />); if(status === STATUS.LOADING) return (<Loader />); return ( <div className='container mx-auto py-5'> {isModalShowing && <SingleProduct /> } <div className="container mx-auto"> <div className="grid grid-cols-1 place-items-center gap-x-8 gap-y-10 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4"> {products.map((product) => ( <div onClick={() => handleTheModal(product)} key={product.id} className="flex h-full flex-col items-center border bg-white text-black cursor-pointer" > <div className=""> <img src={product.images[0]} alt="" className="w-full" /> </div> <div className="my-2 text-xl font-semibold "> {product.category.name} </div> <div className="my-5 text-center"> <h6 className="text-sm">{product.title}</h6> <p className="text-center text-2xl text-green-500"> ${product.price} </p> </div> </div> ))} </div> </div> </div> ) } export default ProductList
const path = require("path"); const fs = require("fs"); const lunr = require("lunr"); const cheerio = require("cheerio"); // Change these constants to suit your needs const HTML_FOLDER = "../docs"; // folder with your HTML files // Valid search fields: "title", "description", "keywords", "body" const SEARCH_FIELDS = ["title", "description", "keywords", "body"]; const EXCLUDE_FILES = []; const MAX_PREVIEW_CHARS = 275; // Number of characters to show for a given search result const OUTPUT_INDEX = "lunr-index.js"; // Index file function isHtml(filename) { lower = filename.toLowerCase(); return lower.endsWith("/index.html") || lower.endsWith("\index.html"); } function findHtml(folder) { if (!fs.existsSync(folder)) { console.log("Could not find folder: ", folder); return; } const files = fs.readdirSync(folder); const htmls = []; for (let i = 0; i < files.length; i++) { const filename = path.join(folder, files[i]); const stat = fs.lstatSync(filename); if (stat.isDirectory()) { const recursed = findHtml(filename); for (let j = 0; j < recursed.length; j++) { recursed[j] = path.join(files[i], recursed[j]).replace(/\\/g, "/"); } htmls.push.apply(htmls, recursed); } else if (isHtml(filename) && !EXCLUDE_FILES.includes(files[i])) { htmls.push(files[i]); } } return htmls; } function readHtml(root, file, fileId) { const filename = path.join(root, file); const txt = fs.readFileSync(filename).toString(); const $ = cheerio.load(txt); let title = $("title").text(); if (typeof title == 'undefined') title = file; let description = $("meta[name=description]").attr("content"); if (typeof description == 'undefined') description = ""; let keywords = $("meta[name=keywords]").attr("content"); if (typeof keywords == 'undefined') keywords = ""; let body = $("body").text(); if (typeof body == 'undefined') body = ""; return { "id": fileId, "link": file, "t": title, "d": description, "k": keywords, "b": body }; } function buildIndex(docs) { return lunr(function () { this.ref('id'); for (let i = 0; i < SEARCH_FIELDS.length; i++) { this.field(SEARCH_FIELDS[i].slice(0, 1)); } docs.forEach(function (doc) { this.add(doc); }, this); }); } function buildPreviews(docs) { const result = {}; for (let i = 0; i < docs.length; i++) { const doc = docs[i]; let preview = doc["d"]; if (preview == "") preview = doc["b"]; if (preview.length > MAX_PREVIEW_CHARS) preview = preview.slice(0, MAX_PREVIEW_CHARS) + " ..."; result[doc["id"]] = { "t": doc["t"], "p": preview, "l": doc["link"] } } return result; } function main() { files = findHtml(HTML_FOLDER); const docs = []; console.log("Building index for these files:"); for (let i = 0; i < files.length; i++) { console.log(" " + files[i]); docs.push(readHtml(HTML_FOLDER, files[i], i)); } const idx = buildIndex(docs); const previews = buildPreviews(docs); const js = ` export default { LUNR_DATA: ${JSON.stringify(idx)}, PREVIEW_LOOKUP: ${JSON.stringify(previews)} }; `; fs.writeFile(OUTPUT_INDEX, js, function (err) { if (err) { return console.log(err); } console.log("Index saved as " + OUTPUT_INDEX); }); } main();
/* eslint-disable react/prop-types */ /* eslint-disable import/no-extraneous-dependencies */ import React, { useEffect, useState } from "react"; import MLContext from "./MLContext"; import { fetchVillas } from "../Services/fetchVillas"; import { fetchYachts } from "../Services/fetchYachts"; function MLProvider({ children }) { const [isFetching, setIsFetching] = useState(false); const [allVillas, setAllVillas] = useState([]); const [allImages, setAllImages] = useState([]); const [allYachts, setAllYachts] = useState([]); useEffect(() => { setIsFetching(true); (async () => { const apiResponse = await fetchVillas(); setAllVillas(apiResponse); setIsFetching(false); })(); }, []); useEffect(() => { setIsFetching(true); (async () => { const apiResponseY = await fetchYachts(); setAllYachts(apiResponseY); setIsFetching(false); })(); }, []); const ContextValue = { isFetching, setIsFetching, allVillas, setAllVillas, allImages, setAllImages, allYachts, setAllYachts, }; return ( <MLContext.Provider value={ContextValue}>{children}</MLContext.Provider> ); } export default MLProvider;
//go:build !main package testutils import ( "github.com/stretchr/testify/require" "testing" "time" ) func WaitUntil(t *testing.T, predicate Predicate) { t.Helper() WaitUntilWithDur(t, predicate, 10*time.Second) } func WaitUntilWithDur(t *testing.T, predicate Predicate, timeout time.Duration) { t.Helper() complete, err := WaitUntilWithError(predicate, timeout, time.Millisecond) require.NoError(t, err) require.True(t, complete, "timed out waiting for predicate") } type Predicate func() (bool, error) func WaitUntilWithError(predicate Predicate, timeout time.Duration, sleepTime time.Duration) (bool, error) { start := time.Now() for { complete, err := predicate() if err != nil { return false, err } if complete { return true, nil } time.Sleep(sleepTime) if time.Since(start) >= timeout { return false, nil } } }
const HttpResponse = require('../helpers/http-response'); const { MissingParamError, InvalidParamError } = require('../../utils/errors'); module.exports = class LoginRouter { constructor({ authUseCase, emailValidator } = {}) { this.authUseCase = authUseCase; this.emailValidator = emailValidator; } async route(httpRequest) { try { const { email, password } = httpRequest.body; if (!email) return HttpResponse.badRequest(new MissingParamError('email')); if (!this.emailValidator.isValid(email)) return HttpResponse.badRequest(new InvalidParamError('email')); if (!password) return HttpResponse.badRequest(new MissingParamError('password')); const accessToken = await this.authUseCase.auth(email, password); return accessToken ? HttpResponse.ok({ accessToken }) : HttpResponse.unauthorized(); } catch { return HttpResponse.serverError(); } } };
// BuildingContext.tsx import React, { createContext, useContext, useState, ReactNode } from "react"; interface BuildingContextProps { children: ReactNode; } interface BuildingContextValues { buildingId: number; setBuildingId: React.Dispatch<React.SetStateAction<number>>; buildingType: string; setBuildingType: React.Dispatch<React.SetStateAction<string>>; buildingName: string; setBuildingName: React.Dispatch<React.SetStateAction<string>>; numFloors: number; setNumFloors: React.Dispatch<React.SetStateAction<number>>; numRoomsPerFloor: number; setNumRoomsPerFloor: React.Dispatch<React.SetStateAction<number>>; } const BuildingContext = createContext<BuildingContextValues | undefined>( undefined ); export function BuildingProvider({ children }: BuildingContextProps) { const [buildingId, setBuildingId] = useState<number>(0); const [buildingType, setBuildingType] = useState<string>(""); const [buildingName, setBuildingName] = useState<string>(""); const [numFloors, setNumFloors] = useState<number>(0); const [numRoomsPerFloor, setNumRoomsPerFloor] = useState<number>(0); const values: BuildingContextValues = { buildingId, setBuildingId, buildingType, setBuildingType, buildingName, setBuildingName, numFloors, setNumFloors, numRoomsPerFloor, setNumRoomsPerFloor, }; return ( <BuildingContext.Provider value={values}> {children} </BuildingContext.Provider> ); } export function useBuildingContext(): BuildingContextValues { const context = useContext(BuildingContext); if (!context) { throw new Error( "useBuildingContext must be used within a BuildingProvider" ); } return context; }
package com.example.car.controller; import static androidx.core.content.ContextCompat.startActivity; import static java.lang.Math.max; import android.content.Context; import android.content.Intent; import com.example.car.activity.MainActivity; import com.example.car.Repository.DiskRepository; import com.example.car.model.Result; import com.example.car.activity.ResultsActivity; import com.example.car.activity.SettingsActivity; import com.example.car.activity.StatisticsActivity; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Objects; import android.os.Handler; public class MainActivityController{ private long startTime; private long endTime; private boolean hasChanged; private boolean hasFinished; private int maxSpeed; private int currentSpeed; private ArrayList<Integer> speedList; private DiskRepository repository; private Context activityContext; private int testSpeed; private double speedConversionCoeff; private int timerTimeMs; boolean isTimerRunning; public MainActivityController(DiskRepository iRepository, Context iActivityContext){ this.repository = iRepository; this.activityContext = iActivityContext; this.speedList = new ArrayList<>(); this.resetSession(); } public void resetSession(){ this.hasChanged = this.hasFinished = false; this.startTime = this.endTime = this.maxSpeed = this.currentSpeed = 0; this.speedConversionCoeff = (double) repository.getTestSpeed() / 100; this.speedList.clear(); this.resetTimer(); this.updateActivitySpeedViews(); this.resetActivityTimerView(); this.testSpeed = repository.getTestSpeed(); } private void updateSpeedVariables(int currentSpeed){ this.currentSpeed = currentSpeed; this.maxSpeed = max(this.maxSpeed, currentSpeed); this.speedList.add(currentSpeed); } public String getMetricUnitString(){ if (Objects.equals(this.repository.getUnit(), "metric")) return " km/h"; return " mph"; } public void startResultsActivity(){ startActivity(this.activityContext, new Intent(this.activityContext, ResultsActivity.class), null); } public void startSettingsActivity(){ startActivity(this.activityContext, new Intent(activityContext, SettingsActivity.class), null); } public void startStatisticsActivity(){ startActivity(this.activityContext, new Intent(activityContext, StatisticsActivity.class), null); } private String getCurrentDateTime() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } private void resetActivityTimerView(){ ((MainActivity) activityContext).updateTimerView("0"); } private void updateActivitySpeedViews(){ ((MainActivity) activityContext).updateSpeedViews(this.currentSpeed, this.speedConversionCoeff); } public void runTimer(){ this.isTimerRunning = true; } public void stopTimer(){ this.isTimerRunning = false; } public void resetTimer(){ this.isTimerRunning = false; this.timerTimeMs = 0; } public void createTimer(){ final Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { if (isTimerRunning) { double seconds = timerTimeMs / 1000.0; ((MainActivity) activityContext).updateTimerView(Double.toString(seconds)); timerTimeMs += 200; } handler.postDelayed(this, 200); } }); } public void onLocationChanged(int locationSpeed){ // speed is given in kn / h if (!this.repository.isMetric()) locationSpeed = (int) (locationSpeed / 1.6093); if (this.currentSpeed != locationSpeed) this.onSpeedChanged(locationSpeed); } private void onSpeedChanged(int currentSpeed){ updateSpeedVariables(currentSpeed); updateActivitySpeedViews(); if (!hasChanged && currentSpeed > 0){ this.hasChanged = true; this.startTime = System.currentTimeMillis(); this.runTimer(); } if (!hasFinished && currentSpeed >= testSpeed){ this.hasFinished = true; this.endTime = System.currentTimeMillis(); this.addResult(); this.startResultsActivity(); this.resetTimer(); } } public void onResetAction(){ this.resetSession(); } private double computeTotalTime(){ return 1.0 * (this.endTime - this.startTime) / 1000; } private void addResult() { this.repository.addEntity(new Result(this.computeTotalTime(), this.maxSpeed, this.getAverageSpeed(), this.getCurrentDateTime())); } private double getAverageSpeed(){ double average = 0; for (int speed : speedList){ average += speed; } return average / speedList.size(); } }
<!DOCTYPE html> <html lang="es"> <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>PorfolioVicky</title> <link rel="stylesheet" href="estilo.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"> </head> <body class="container"> <!--SECCION DE barra de navegación--> <nav class="navbar navbar-dark bg-dark fixed-top"> <div class="container-fluid"> <a class="navbar-brand" href="#">Argentina Programa</a> <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasDarkNavbar" aria-controls="offcanvasDarkNavbar"> <span class="navbar-toggler-icon"></span> </button> <div class="offcanvas offcanvas-end text-bg-dark" tabindex="-1" id="offcanvasDarkNavbar" aria-labelledby="offcanvasDarkNavbarLabel"> <div class="offcanvas-header"> <h5 class="offcanvas-title" id="offcanvasDarkNavbarLabel">Porfolio</h5> <img src="img/usuario.png" alt="usuario"> <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close"></button> </div> <div class="offcanvas-body"> <ul class="navbar-nav justify-content-end flex-grow-1 pe-3"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Inicio</a> </li> <li class="nav-item"> <a class="nav-link" href="#edu">Educacion</a> </li> <li class="nav-item"> <a class="nav-link" href="#exp">Experiencia</a> </li> <li class="nav-item"> <a class="nav-link" href="#ski">Skills</a> </li> <li class="nav-item"> <a class="nav-link" href="#proy">Proyectos</a> </li> </ul> </div> </div> </div> </nav> <div class="Ventana"> <!--SECCION DE INICIO--> <div class="card m-2" style="width: 100%; height: max-content;" id="Inicio"> <div class="cabecera"> </div> <div class="card-body p-1"> <h1 class="card-title text-center" id="Nombre">Victoria Camblor</h1> <ul class="card-text m-3"> <li> <h2>Acerca de</h2> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Assumenda, provident.</p> </li> </ul> <a href="#edu" class="btn btn-sm d-flex justify-content-center"><img class="sm" src="img/flecha-hacia-abajo-para-navegar.png" alt=""></a> </div> </div> <!--SECCION DE EDUCACION--> <div class="card m-2" style="width: 100%; height: max-content;" id="Inicio" > <div class="card-body p-1" id="edu"> <h2 class="card-title text-center" id="Nombre">Educación</h2> <div class="container text-center"> <div class="row row-cols-2"> <div class="col"> <li> <img src="img/card-text.svg" alt=""> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi, consequuntur.</p> </li> </div> <div class="col"> <li> <img src="img/card-text.svg" alt=""> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi, consequuntur.</p> </li> </div> <div class="col"> <li> <img src="img/card-text.svg" alt=""> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi, consequuntur.</p> </li> </div> <div class="col"> <li> <img src="img/card-text.svg" alt=""> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi, consequuntur.</p> </li> </div> </div> </div> <a href="#exp" class="btn btn-sm d-flex justify-content-center"><img class="sm" src="img/flecha-hacia-abajo-para-navegar.png" alt=""></a> </div> </div> <!--SECCION DE EXPERIENCIA--> <div class="card m-2" id="exp" style="width: 100%; height: max-content;" id="Inicio"> <div class="card-body p-1"> <h2 class="card-title text-center" id="Nombre">Experiencia</h2> <div class="container text-center"> <div class="row row-cols-2"> <div class="col"> <li> <img src="img/card-text.svg" alt=""> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi, consequuntur.</p> </li> </div> <div class="col"> <li> <img src="img/card-text.svg" alt=""> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi, consequuntur.</p> </li> </div> <div class="col"> <li> <img src="img/card-text.svg" alt=""> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi, consequuntur.</p> </li> </div> <div class="col"> <li> <img src="img/card-text.svg" alt=""> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi, consequuntur.</p> </li> </div> </div> </div> <a href="#edu" class="btn btn-sm d-flex justify-content-center"><img class="sm" src="img/flecha-hacia-abajo-para-navegar.png" alt=""></a> </div> </div> <!--SECCION DE SKILLS--> <div class="BarraSkills"> <ul> <li> <img src="" alt=""> <h3>titulo de skills</h3> <p>porcentaje</p> <div class="progress"> <div class="progress-bar progress-bar-striped" role="progressbar" aria-label="Default striped example" style="width: 10%" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div> </div> </li> <li> <img src="" alt=""> <h3>titulo de skills</h3> <p>porcentaje</p> <div class="progress"> <div class="progress-bar progress-bar-striped" role="progressbar" aria-label="Default striped example" style="width: 10%" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div> </div> </li> <li> <img src="" alt=""> <h3>titulo de skills</h3> <p>porcentaje</p> <div class="progress"> <div class="progress-bar progress-bar-striped" role="progressbar" aria-label="Default striped example" style="width: 10%" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div> </div> </li> </ul> </div> <div class="Proyectos"> <ul> <li> <h3>Proyecto Uno</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos, eos.</p> <button>Ver proyecto</button> <img src="" alt=""> </li> <li> <h3>Proyecto Dos</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos, eos.</p> <button>Ver proyecto</button> <img src="" alt=""> </li> <li> <h3>Proyecto Tres</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos, eos.</p> <button>Ver proyecto</button> <img src="" alt=""> </li> <li> <h3>Proyecto Cuatro</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos, eos.</p> <button>Ver proyecto</button> <img src="" alt=""> </li> </ul> </div> </div> <script src="script.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script> </body> </html>
import { notification } from '@/utils/message' import classNames from 'classnames' import React from 'react' import { Link } from 'react-router-dom' import { Button } from '../components/Button' import { Input } from '../components/Input' import { PATH } from '../config/path' import { useAsync } from '../hooks/useAsync' import { useForm } from '../hooks/useForm' import { useScrollTop } from '../hooks/useScrollTop' import { userService } from '../services/user.service' import { confirm, minMax, regexp, required } from '../utils/validate' const SignUp = () => { const { execute: signUpService, loading, status } = useAsync(userService.signUp) const { execute: resendEmailService, loading: resendEmailLoading } = useAsync( userService.resendEmail ) useScrollTop() const { values, validate, register, errors } = useForm({ username: [ required('Please enter your email address'), regexp('email', 'Your email address is not in the correct format'), ], name: [ required('Please enter your name'), regexp(/\b([A-ZÀ-ÿ][-,a-z. ']+[ ]*)+/, 'Your name is not in the correct format'), ], password: [ required('Please enter your password'), minMax('Your password must be 8 chars at minimum', 8), regexp('password', 'Your password is not in the correct format'), ], confirmPassword: [required('Please confirm your password again'), confirm('password')], }) async function _onSubmit(event) { try { event.preventDefault() if (validate()) { const form = { username: values.username.toLowerCase(), name: values.name, password: values.password, } const res = await signUpService(form) if (res.success) { notification.success(res.message, 5) } } else { console.log('Validate error') } } catch (err) { console.error(err) if (err.response?.data?.message) { notification.error(err.response.data.message, 5) } } } const _onResendEmail = async (ev) => { ev.preventDefault() console.log(values.username) try { const response = await resendEmailService({ username: values.username.toLowerCase() }) notification.success(response.message) } catch (err) { console.error(err) if (err.response?.data?.message) { notification.error(err.response.data.message) } } } return ( <main id="main"> <div className="auth"> {status === 'success' ? ( <div className="register-success max-w-[690px] my-[150px] mx-auto bg-white"> <div className="contain p-[50px] text-center"> <h1 className="main-title mb-[20px] capitalize">Tạo tài khoản thành công</h1> <p className="mb-[20px]"> <strong>Chào mừng bạn đã trở thành thành viên mới của Spacedev Team.</strong> <br /> Bạn vui lòng kiểm tra email để kích hoạt tài khoản. </p> <a href="#" className={classNames('link inline-block select-none', { 'opacity-50 pointer-events-none': resendEmailLoading, })} disabled onClick={_onResendEmail} > {resendEmailLoading && ( <span className=" inline-block w-[15px] h-[15px] mr-2 border-[3px] border-solid border-b-transparent rounded-[50%] animate-spin"></span> )} Gửi lại email kích hoạt </a> </div> <Link to={PATH.signIn} className="btn main rect w-full"> Đăng nhập </Link> </div> ) : ( <div className="wrap"> <h2 className="title">Đăng ký</h2> <form onSubmit={_onSubmit}> {/* Email */} <Input placeholder="Email" {...register('username')} error={errors.username} /> {/* Name */} <Input placeholder="Họ và tên" {...register('name')} error={errors.name} /> {/* Password */} <Input type="password" placeholder="Mật khẩu" {...register('password')} error={errors.password} /> {/* Confirm password */} <Input type="password" placeholder="Nhập lại mật khẩu" {...register('confirmPassword')} error={errors.confirmPassword} /> <p className="policy"> Bằng việc đăng kí, bạn đã đồng ý <a href="#">Điều khoản bảo mật</a> của Spacedev </p> <Button loading={loading} className="mt-[30px]"> Đăng ký </Button> </form> </div> )} </div> </main> ) } export default SignUp
package com.mygdx.tank.controllers; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.mygdx.tank.AccountService; import com.mygdx.tank.FirebaseDataListener; import com.mygdx.tank.FirebaseInterface; import com.mygdx.tank.model.LeaderboardEntry; import com.mygdx.tank.TankMazeMayhem; import com.mygdx.tank.Views.LeaderboardView; import com.mygdx.tank.model.MenuModel; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class LeaderboardController implements IController{ private final FirebaseInterface firebaseInterface; private final MenuModel model; private final LeaderboardView view; private final TankMazeMayhem game; private final AccountService accountService; public LeaderboardController(MenuModel model, LeaderboardView view, TankMazeMayhem game, AccountService accountService, FirebaseInterface firebaseInterface) { this.model = model; this.view = view; this.game = game; this.accountService = accountService; this.firebaseInterface = firebaseInterface; } @Override public void updateModelView() { // Get leaderboard entries and update the model fetchLeaderboardData(); } @Override public void addListeners() { view.getBackButton().addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { ApplicationController.getInstance(game, accountService).switchToMainMenu(); } }); view.getSettingsButton().addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { ApplicationController.getInstance(game, accountService).switchToSettings(); } }); } @Override public Screen getView() { return view; } private void fetchLeaderboardData() { firebaseInterface.getLeaderboardData(new FirebaseDataListener() { @Override public void onDataReceived(Object data) { handleLeaderboardData((ArrayList<LeaderboardEntry>) data); } @Override public void onError(String errorMessage) { Gdx.app.log("Firebase", "Error fetching leaderboard " + errorMessage); } }); } private void handleLeaderboardData(ArrayList<LeaderboardEntry> entries) { Gdx.app.postRunnable(() -> { Collections.sort(entries, new Comparator<LeaderboardEntry>() { @Override public int compare(LeaderboardEntry o1, LeaderboardEntry o2) { return Integer.compare(o2.getScore(), o1.getScore()); } }); ArrayList<LeaderboardEntry> topFiveEntries = new ArrayList<>(entries.subList(0, Math.min(entries.size(), 5))); model.updateLeaderboard(topFiveEntries); if (model.getLeaderboardEntries() != null && !model.getLeaderboardEntries().isEmpty()) { view.updateView(model); } else { Gdx.app.log("Error", "Leaderboard data is empty or not initialized"); } }); } }
/**************************************************************************** ** $file: amanith/2d/gmulticurve2d.h 0.3.0.0 edited Jan, 30 2006 ** ** 2D Base multicurve segment definition. ** ** ** Copyright (C) 2004-2006 Mazatech Inc. All rights reserved. ** ** This file is part of Amanith Framework. ** ** This file may be distributed and/or modified under the terms of the Q Public License ** as defined by Mazatech Inc. of Italy and appearing in the file ** LICENSE.QPL included in the packaging of this file. ** ** Licensees holding valid Amanith Professional Edition license may use this file in ** accordance with the Amanith Commercial License Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.mazatech.com or email sales@mazatech.com for ** information about Amanith Commercial License Agreements. ** See http://www.amanith.org/ for opensource version, public forums and news. ** ** Contact info@mazatech.com if any conditions of this licensing are ** not clear to you. **********************************************************************/ #ifndef GMULTICURVE2D_H #define GMULTICURVE2D_H /*! \file gmulticurve2d.h \brief Header file for 2D multicurve class. */ #include "amanith/2d/gcurve2d.h" namespace Amanith { // ********************************************************************* // GMultiCurve2D // ********************************************************************* //! GMultiCurve2D static class descriptor. static const GClassID G_MULTICURVE2D_CLASSID = GClassID("GMultiCurve2D", 0x59BA6FA6, 0x62F943B2, 0xA5548655, 0xA4D349D1); /*! \class GMultiCurve2D \brief This class represents a parametric continuous piece-wise 2D curve. The main difference respect to a GCurve2D is that a multicurve is an "homogeneous" piece-wise continuous curve. A multicurve is made of curve traits of the same type, each trait is continuously joined to the previous and next ones. You can think at a multicurve as a key-based curve. At each key point the curve may or may not be globally derivable. But at least it's continuous.\n Some kind of multicurve can be useful for shape design (think for example at Hermite curves used in Inkscape software), others for animation purposes (think for example at TCB curves). */ class G_EXPORT GMultiCurve2D : public GCurve2D { protected: /*! Add a new (key)point for the curve. <b>This method must be implemented by all derived classes</b>. \param Parameter the domain parameter where to add the (key)point. \param NewPoint if not specified (NULL value) the point must be created on curve. In this case the specified domain Parameter must reside completely inside the domain, else an G_OUT_OF_RANGE error must be returned. If Newpoint is specified (non NULL) the point can be created also outside domain range. \param Index the position (internal index) occupied by the created (key)point. \param AlreadyExists this method must write to this flag a G_TRUE value if the point has been created in a domain position already occupied by another (key)point. In this case the already existing point must be overridden by the created point. \return G_NO_ERROR if the function succeeds, an error code must be returned otherwise. */ virtual GError DoAddPoint(const GReal Parameter, const GPoint2 *NewPoint, GUInt32& Index, GBool& AlreadyExists) = 0; /*! Remove a (key)point from the curve. Index is ensured to be valid and we are sure that after removing we'll have (at least) a minimal (2-(key)points made) multi-curve. <b>This method must be implemented by all derived classes</b>. \param Index the index of (key)point to be removed. Note that this value is ensured to be always valid. \return G_NO_ERROR if the function succeeds, an error code must be returned otherwise. */ virtual GError DoRemovePoint(const GUInt32 Index) = 0; //! Cloning function; this implementation do nothing. GError BaseClone(const GElement& Source); /*! Get domain parameter corresponding to specified (key)point index. Index is ensured to be valid. <b>This method must be implemented by all derived classes</b>. \param Index the point index, is ensured to be always valid. \param Parameter the outputted domain parameter, corresponding to the specified (key)point index. \return G_NO_ERROR if the function succeeds, an error code must be returned otherwise. */ virtual GError DoGetPointParameter(const GUInt32 Index, GReal& Parameter) const = 0; /*! Set domain parameter corresponding to specified (key)point index. The final effect is that a (key)point is moved from its domain position to another domain position. <b>This method must be implemented by all derived classes</b>. \param Index the point index, is ensured to be always valid. \param NewParamValue the new domain parameter, where to move the specified (key)point. It must be outside current domain. \param NewIndex the new position (internal index) occupied by the moved (key)point. This method must output this value. \param AlreadyExists this method must write to this flag a G_TRUE value if the point has been moved in a domain position already occupied by another (key)point. In this case the already existing point must be overridden by the moved point. \return G_NO_ERROR if the function succeeds, an error code must be returned otherwise. */ virtual GError DoSetPointParameter(const GUInt32 Index, const GReal NewParamValue, GUInt32& NewIndex, GBool& AlreadyExists) = 0; public: //! Default constructor, constructs and empty curve. GMultiCurve2D(); //! Constructor with kernel specification, constructs and empty curve. GMultiCurve2D(const GElement* Owner); //! Destructor virtual ~GMultiCurve2D(); /*! Get domain parameter corresponding to specified (key)point index. \param Index the point index, must be valid (else an G_OUT_OF_RANGE error will be returned). \param Parameter the outputted domain parameter, corresponding to the specified (key)point index. \return G_NO_ERROR if the function succeeds, an error code otherwise. */ GError PointParameter(const GUInt32 Index, GReal& Parameter) const; /*! Set domain parameter corresponding to specified (key)point index. The final effect is that a (key)point is moved from its domain position to another domain position. \param Index the point index, must be valid (else an G_OUT_OF_RANGE error will be returned). \param NewParamValue the new domain parameter, where to move the specified (key)point. \param NewIndex the new position (internal index) occupied by the moved (key)point. \param AlreadyExists if G_TRUE, it means that the point has been moved to a domain position already occupied by another (key)point. In this case the already existing point will be overridden by the moved point. \return G_NO_ERROR if the function succeeds, an error code otherwise. \note if the specified new domain position is out of current domain range, then the current domain will be update to include the specified domain value. */ GError SetPointParameter(const GUInt32 Index, const GReal NewParamValue, GUInt32& NewIndex, GBool& AlreadyExists); /*! Add point on curve, at the specified domain parameter; in case of successful operation, the inserted point index (into internal array) will be returned. \param Parameter the domain parameter where to add the point on. It must be in the domain range, else an G_OUT_OF_RANGE error code will be returned. \param Index the position (internal index) occupied by the created (key)point. \param AlreadyExists if G_TRUE, it means that the point has been created in a domain position already occupied by another (key)point. In this case the already existing point will be overridden by the created point. \return G_NO_ERROR if the function succeeds, an error code otherwise. */ GError AddPoint(const GReal Parameter, GUInt32& Index, GBool& AlreadyExists); /*! Add a new (key)point, at the specified domain parameter; in case of successful operation, the inserted point index (into internal array) will be returned. \param Parameter the domain parameter where to add the point on. \param Point the geometrical position of the new created point. \param Index the position (internal index) occupied by the created (key)point. \param AlreadyExists if G_TRUE, it means that the point has been created in a domain position already occupied by another (key)point. In this case the already existing point will be overridden by the created point. \return G_NO_ERROR if the function succeeds, an error code otherwise. \note the specified domain value can be outside the current domain; in this case the domain will be updated to include the specified domain value. */ GError AddPoint(const GReal Parameter, const GPoint2& Point, GUInt32& Index, GBool& AlreadyExists); /*! Remove a (key)point from curve. The domain will be updated in the case that the specified point to be removed is first or last one. \param Index the index of the point to be removed. It must be valid, else a G_OUT_OF_RANGE error code will be returned. \note If the curve were made of just 2 (key)points, calling this function will clear the entire curve, because a multicurve must be composed of at least 2 points. */ GError RemovePoint(const GUInt32 Index); /*! Return the curve derivative calculated at specified domain parameter. This method differs from the one of base GCurve2D class in the number of returned values. This is due to the possibility that the curve is continuous but not derivable (in the sense that left and right derivatives are different). \param Order the order of derivative. \param u the domain parameter at witch we wanna evaluate curve derivative. \param LeftDerivative the left derivative. \param RightDerivative the right derivative. \note specified domain parameter is clamped by domain interval; the default behavior is to return LeftDerivative = RightDerivative = Derivative(Order, u). */ virtual void DerivativeLR(const GDerivativeOrder Order, const GReal u, GVector2& LeftDerivative, GVector2& RightDerivative) const { LeftDerivative = RightDerivative = this->Derivative(Order, u); } /*! Return the curve tangent calculated at specified domain parameter. This method differs from the one of base GCurve2D class in the number of returned values. This is due to the possibility that the curve is continuous but not derivable (in the sense that left and right derivatives are different). \param u the domain parameter at witch we wanna evaluate curve tangent(s). \param LeftTangent the left normalized (unit length) tangent vector. \param RightTangent the right normalized (unit length) tangent vector. \note specified domain parameter is clamped by domain interval. */ void TangentLR(const GReal u, GVector2& LeftTangent, GVector2& RightTangent) const; /*! Return the curve normal calculated at specified domain parameter. This method differs from the one of base GCurve2D class in the number of returned values. This is due to the possibility that the curve is continuous but not derivable (in the sense that left and right derivatives are different). \param u the domain parameter at witch we wanna evaluate curve normal(s). \param LeftNormal the left normalized vector perpendicular to the curve (left)tangent. \param RightNormal the right normalized vector perpendicular to the curve (right)tangent. \note specified domain parameter is clamped by domain interval. */ void NormalLR(const GReal u, GVector2& LeftNormal, GVector2& RightNormal) const; /*! Return the curve curvature calculated at specified domain parameter. This method differs from the one of base GCurve2D class in the number of returned values. This is due to the possibility that the curve is continuous but not derivable (in the sense that left and right derivatives are different). \param u the domain parameter at witch we wanna evaluate curve curvature(s). \param LeftCurvature the left curvature. \param RightCurvature the right curvature. \note specified domain parameter is clamped by domain interval. */ void CurvatureLR(const GReal u, GReal& LeftCurvature, GReal& RightCurvature) const; /*! Return the curve speed calculated at specified domain parameter. With 'speed', here's intended the length of the curve's first derivative vector. This method differs from the one of base GCurve2D class in the number of returned values. This is due to the possibility that the curve is continuous but not derivable (in the sense that left and right derivatives are different). \param u the domain parameter at witch we wanna evaluate curve speed(s). \param LeftSpeed the speed corresponding to the left derivative vector. \param RightSpeed the speed corresponding to the right derivative vector. \note specified domain parameter is clamped by domain interval. */ void SpeedLR(const GReal u, GReal& LeftSpeed, GReal& RightSpeed) const; //! Get class descriptor inline const GClassID& ClassID() const { return G_MULTICURVE2D_CLASSID; } //! Get base class (father class) descriptor inline const GClassID& DerivedClassID() const { return G_CURVE2D_CLASSID; } }; // ********************************************************************* // GMultiCurve2DProxy // ********************************************************************* /*! \class GMultiCurve2DProxy \brief This class implements a GMultiCurve2D proxy (provider). This proxy does not override CreateNew() method because we don't wanna make a creation of a GMultiCurve2D class possible (because of pure virtual methods). */ class G_EXPORT GMultiCurve2DProxy : public GElementProxy { public: //! Get class descriptor of elements type "provided" by this proxy. const GClassID& ClassID() const { return G_MULTICURVE2D_CLASSID; } //! Get base class (father class) descriptor of elements type "provided" by this proxy. const GClassID& DerivedClassID() const { return G_CURVE2D_CLASSID; } }; //! Static proxy for GMultiCurve2D class. static const GMultiCurve2DProxy G_MULTICURVE2D_PROXY; }; // end namespace Amanith #endif
import { nftabi } from "@/abi/NFTABI"; import { ConnectButton } from "@rainbow-me/rainbowkit"; import { ethers } from "ethers"; import * as React from "react"; import { useAccount, useProvider, useSigner } from "wagmi"; const Customer = () => { //a fixed nft is minted for demo const provider = useProvider(); const { data: signer } = useSigner(); const { address } = useAccount(); const contract = new ethers.Contract( "0xC103bd111523cf32E303474810D126d1D7Fd18aa", nftabi, signer || provider ); const [tokenid, setTokenId] = React.useState<String>(""); const [productname, setProductName] = React.useState<String>(""); const [productmaterial, setProductMaterial] = React.useState<String>(""); const [productorigin, setProductOrigin] = React.useState<String>(""); const [productStatus, setProductStatus] = React.useState<String>(""); const [productowner, setProductOwner] = React.useState<String>(""); const [rewards, setRewards] = React.useState<String>(""); const mintnft = async () => { try { const tx = await contract.safeMint( "Product 1", "Material 1", "Origin 1", "https://ipfs.io/ipfs/bafybeibnsoufr2renqzsh347nrx54wcubt5lgkeivez63xvivplfwhtpym/metadata.json", { value: ethers.utils.parseUnits("0.1", "ether") } ); const receipt = await tx.wait(); console.log(receipt); } catch (err) { console.log(err); } }; const getProductDetails = async (tokenid: String) => { const contract = new ethers.Contract( "0xC103bd111523cf32E303474810D126d1D7Fd18aa", nftabi, signer || provider ); const tx = await contract._productDetails(tokenid); console.log(tx); setProductName(tx.name); setProductMaterial(tx.material); setProductOrigin(tx.origin); setProductStatus(tx.stage); setProductOwner(String(tx[3]).toLowerCase()); console.log(productowner); }; const confirmDelivery = async () => { const contract = new ethers.Contract( "0xC103bd111523cf32E303474810D126d1D7Fd18aa", nftabi, signer || provider ); const tx = await contract.confirmProductDelivery(tokenid); const receipt = await tx.wait(); console.log(receipt); }; const getrewards = async () => { const contract = new ethers.Contract( "0xC103bd111523cf32E303474810D126d1D7Fd18aa", nftabi, signer || provider ); const tx = await contract.rewardPoints(address); console.log(tx); setRewards(String(ethers.utils.formatEther(tx))); }; React.useEffect(() => { getrewards(); }, [address]); return ( <div className="flex flex-row h-screen w-screen justify-center items-center"> <div className="flex flex-col h-screen w-1/2 justify-center items-center"> <p className="text-4xl font-bold">Mint your purchase here</p> <ConnectButton /> <p className="text-2xl font-bold mt-4">Rewards : {rewards}</p> <button className="bg-blue-600 text-white font-bold py-2 px-4 mx-2 rounded-xl mt-4" onClick={() => mintnft()} > Mint </button> </div> <div className="flex flex-col h-screen w-1/2 justify-center items-center"> <p className="text-4xl font-bold">Track your purchase here</p> <input type="text" placeholder="Enter Product ID" className="border-2 border-blue-600 rounded-xl p-2 mt-4" onChange={(e) => setTokenId(e.target.value)} /> <button className="bg-blue-600 text-white font-bold py-2 px-4 mx-2 rounded-xl mt-4" onClick={() => getProductDetails(tokenid)} > Refresh Status </button> {address?.toString().toLowerCase() === productowner.toString().toLowerCase() ? ( <div className="flex flex-col mt-7"> <p className="text-2xl font-bold">Product Name: {productname}</p> <p className="text-2xl font-bold"> Product Material: {productmaterial} </p> <p className="text-2xl font-bold"> Product Origin: {productorigin} </p> <p className="text-2xl font-bold"> Product Status:{" "} {productStatus == "0" ? "Order Received" : productStatus == "1" ? "Shipped" : productStatus == "2" ? "Out for Delivery" : "Delivered"} </p> {productStatus == "2" ? ( <button className="bg-blue-600 text-white font-bold py-2 px-4 mx-2 rounded-xl mt-4" onClick={() => confirmDelivery()} > Confirm Delivery </button> ) : null} </div> ) : null} </div> </div> ); }; export default Customer;
### **Chapter 2 - On the Job with a Network Manager** #### **1. Who is a Network Manager?** - Network managers encompass various roles with different titles such as network operators, administrators, planners, craft technicians, and help desk representatives. The term "network manager" itself is rarely used but represents the individuals managing network operations and infrastructure. #### **2. Providers of Network Management** - Key players include application providers, equipment vendors, and systems integrators who collectively contribute to the setup, functioning, and optimization of networks. #### **3. A Day in the Life of a Network Manager** - The daily tasks and responsibilities depend heavily on the type of organization (e.g., global or local) and their capability to provide large-scale, highly available services. Network availability is often held to the "five nines" standard (99.999% uptime). - **Network Operators**: Focus on network statistics, user delays, service levels, and reported issues across geographical areas. - **Trouble Tickets and Alarm Messages**: Key responsibilities include handling and diagnosing issues through trouble tickets and system alarms, providing tiered support, and ensuring problem resolution. #### **4. Role Scenarios in Network Management** - **Global Service Providers**: Network operators must manage detailed utilization statistics, diagnose root causes of issues, and resolve service-affecting alarms. - **Medium-Size Network Administrators**: Often work for organizations with branch locations interconnected by Virtual Private Networks (VPNs) managed by Managed Service Providers (MSPs). Tasks include monitoring network health and addressing issues through status views and health displays. - **Internet Data Center Administrators**: These individuals manage complex data center networks involving intranet, extranet, and public web services. Tasks involve setting up VLANs for segregating traffic and ensuring security. #### **5. Tools and Technology Used by Network Managers** - **Craft Terminals**: User-friendly interfaces for interacting with individual network equipment. - **Network Analyzers**: Tools like packet sniffers and traffic analyzers that monitor and interpret network packet flows. - **Collectors and Probes**: Devices that collect and store network data (e.g., NetFlow collectors) and actively trigger network activities to gather data responses. - **Intrusion Detection Systems (IDS)**: Tools for identifying and responding to suspicious network patterns and potential attacks. - **Alarm Management Systems**: Systems to collect and monitor network-generated alarms, ensuring timely responses. #### **6. Workflow and Management Systems** - **Workflow Management Systems**: Include inventory systems, service provisioning tools, service order-management, and billing systems, which streamline network operations and task management. #### **7. Observations from Different Roles** - Pat, Chris, and Sandy represent varied roles in network management, from specialized task groups to comprehensive network planners. Integration between tools significantly affects operator productivity and efficiency, with tasks varying from manual to automated processes. #### **8. Challenges and Operational Considerations** - Tasks in network management often involve complex interactions among many functions. Integration of tools, adherence to operational guidelines, and high-level abstraction in management are vital for productivity and network stability. #### **9. Summary** - The chapter concludes by highlighting the broad infrastructure required for service provider environments and the diverse tasks characterizing medium-sized enterprises. --- This note summarizes the key points from the presentation, providing a comprehensive overview of the roles, tools, and daily tasks associated with network management as described in Chapter 2.
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class BlogRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' => 'required|string|min:3|max:200', 'text' => 'required|string|min:3|max:500', 'image' => 'required_without:video_url|mimes:png,jpg,jpeg', 'video_url' => 'required_without:image', 'user_id' =>'required|numeric' ]; } }
package org.cbh.seckill.dao.cache; import io.protostuff.LinkedBuffer; import io.protostuff.ProtostuffIOUtil; import io.protostuff.runtime.RuntimeSchema; import org.cbh.seckill.entity.Seckill; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; /** * Created by Administrator on 2016/10/24. */ public class RedisDao { private final JedisPool jedisPool; public RedisDao(String host, int port) { this.jedisPool = new JedisPool(host, port); } private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class); public Seckill getSeckill(long seckillId) { try { Jedis jedis = jedisPool.getResource(); try { String key = "seckill:" + seckillId; byte[] bytes = jedis.get(key.getBytes()); if (bytes != null) { Seckill seckill = schema.newMessage(); ProtostuffIOUtil.mergeFrom(bytes, seckill, schema); return seckill; } } finally { jedis.close(); } } catch (Exception e) { e.printStackTrace(); } return null; } public String putSeckill(Seckill seckill) { try { Jedis jedis = jedisPool.getResource(); try { String key = "seckill:" + seckill.getSeckillId(); byte[] bytes = ProtostuffIOUtil.toByteArray(seckill, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE)); int seconds = 60 * 60; String result = jedis.setex(key.getBytes(), seconds, bytes); return result; } finally { jedis.close(); } } catch (Exception e) { e.printStackTrace(); } return null; } }
(** {v Copyright (C) 2017-2018, Colin P Stark and Gavin J Stark. All rights reserved. * * 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. * * @file trajectories.ml * @brief Integration of trajectories using GPU for trace * * Up to date with python of git CS 189bfccdabc3371eafe8bcafa3bdfa8c241e56e4 * Except max_time_per_kernel and initial_size_factor are hardwired * * Note that integrate_trajectories does NOT create seeds - that is up to the client * * v} *) (*a Module abbreviations *) open Globals open Core open Properties module ODM = Owl.Dense.Matrix.Generic module ODN = Owl.Dense.Ndarray.Generic module OS = Owl.Stats (** {1 pv_verbosity functions} *) (** [pv_noisy t] Shortcut to use {!type:Properties.t_props_trace} verbosity for {!val:Properties.pv_noisy} *) let pv_noisy data = Workflow.pv_noisy data.properties.trace.workflow (** [pv_debug t] Shortcut to use {!type:Properties.t_props_trace} verbosity for {!val:Properties.pv_debug} *) let pv_debug data = Workflow.pv_noisy data.properties.trace.workflow (** [pv_info t] Shortcut to use {!type:Properties.t_props_trace} verbosity for {!val:Properties.pv_info} *) let pv_info data = Workflow.pv_info data.properties.trace.workflow (** [pv_verbose t] Shortcut to use {!type:Properties.t_props_trace} verbosity for {!val:Properties.pv_verbose} *) let pv_verbose data = Workflow.pv_verbose data.properties.trace.workflow (** {1 Statics} *) let cl_files = ["rng.cl";"essentials.cl"; "writearray.cl";"updatetraj.cl";"computestep.cl"; "rungekutta.cl";"trajectory.cl";"integratetraj.cl"] let cl_src_path = ["opencl"] (** {1 Chunks} *) (** [t_chunk] *) type t_chunk = { required : bool; (* false if not required to be calculated *) direction : string; downup_index : int; (* 0 for downstream, 1 for upstream - last index into arrays to put results *) downup_sign : float; (* -1. for upstream, +1. for downstream *) chunk_index : int; (* Which chunk number *) seed_offset : int; (* Offset to first seed in chunk *) num_seeds : int; (* Number of seeds in chunk *) } (** [chunk data downstream (n, seed_start, seed_end)] Create a chunk (index {i n}) with the given seeds, for upstream or downstream *) let chunk data downstream (n, seed_start, seed_end) = let (required, direction, downup_index, downup_sign) = if downstream then (data.properties.trace.do_trace_downstream, "Downstream", 0,(+1.)) else data.properties.trace.do_trace_upstream, "Upstream", 1,(-1.) in { required; direction; downup_index; downup_sign; chunk_index=n; seed_offset=seed_start; num_seeds=(seed_end-seed_start) } (** [show_chunk t] Not yet implemented *) let show_chunk t = Printf.printf "Chunk %d\n" t.chunk_index; Printf.printf " %s (required %b, index %d, sign %f)" t.direction t.required t.downup_index t.downup_sign; Printf.printf " from seed %d for %d seeds\n%!" t.seed_offset t.num_seeds (** [generate_chunks data num_seeds chunk_size] Generate a to_do_list of chunks *) let generate_chunks data num_seeds chunk_size = let num_chunks_required = required_units num_seeds chunk_size in let chunks = List.init num_chunks_required (fun i -> (i, i*chunk_size, min ((i+1)*chunk_size) num_seeds)) in let to_do_list = List.fold_left (fun acc nse -> (chunk data true nse)::(chunk data false nse)::acc) [] chunks in to_do_list (** {1 Memory} *) (** t_memory Structure containing the memory and OpenCL buffers for interacting with the integrate_trajectories kernel. *) type t_memory = { uv_array : t_ba_floats; (* padded ROI - vector field array input *) mapping_array : t_ba_ints; (* padded ROI - #streamlines crossing pixel *) chunk_nsteps_array : t_ba_int16s; (* chunk_size - number of steps taken for a streamline from the seed *) chunk_length_array : t_ba_floats; (* chunk_size - streamline length from the seed *) chunk_trajcs_array : t_ba_chars; (* chunk_size * max_traj_length*2 - char path of streamline from the seed *) seeds_buffer : Pocl.t_buffer; uv_buffer : Pocl.t_buffer; mask_buffer : Pocl.t_buffer; mapping_buffer : Pocl.t_buffer; chunk_trajcs_buffer : Pocl.t_buffer; chunk_nsteps_buffer : Pocl.t_buffer; chunk_length_buffer : Pocl.t_buffer; } (** [copy_read pocl] Shortcut for creating an OpenCL buffer that is read-only by the kernel and copied from a big array before execution @return OpenCL buffer *) let copy_read pocl = Pocl.buffer_of_array pocl ~copy:true true false (** [copy_read_write pocl] Shortcut for creating an OpenCL buffer that is read-write by the kernel and copied from a big array before execution @return OpenCL buffer *) let copy_read_write pocl = Pocl.buffer_of_array pocl ~copy:true true true (** [write_only pocl] Shortcut for creating an OpenCL buffer that is write-only by the kernel @return OpenCL buffer *) let write_only pocl = Pocl.buffer_of_array pocl false true (** [memory_create_buffers pocl data seeds chunk_size] Create a t_memory strucure with big arrays and PyOpenCL buffers to allow CPU-GPU data transfer for the integrate_trajectories kernel *) let memory_create_buffers pocl data seeds chunk_size = let max_traj_length = Info.int_of data.info "max_n_steps" in let roi_nx = data.pad_width*2+data.roi_nx in let roi_ny = data.pad_width*2+data.roi_ny in let uv_array = ba_float2d (roi_nx) (roi_ny*2) in let fill_uv x y u v = ODM.set uv_array x (y*2+0) u; ODM.set uv_array x (y*2+1) v; in ODM.iter2i_2d fill_uv data.u_array data.v_array; let mapping_array = ba_int2d (roi_nx) (roi_ny) in ODM.fill mapping_array 0; (* Chunk-sized temporary arrays - use for a work group, then copy to traj_* *) (* Use "bag o' bytes" buffer for huge trajectories array. Write (by GPU) only. *) let chunk_trajcs_array = ba_char2d chunk_size (max_traj_length*2) in let chunk_nsteps_array = ba_int16s chunk_size in let chunk_length_array = ba_floats chunk_size in (* Create OpenCL buffers of the arrays *) let seeds_buffer = copy_read pocl seeds in let mask_buffer = copy_read pocl data.basin_mask_array in let uv_buffer = copy_read pocl uv_array in let mapping_buffer = copy_read_write pocl mapping_array in let chunk_nsteps_buffer = write_only pocl chunk_nsteps_array in let chunk_length_buffer = write_only pocl chunk_length_array in let chunk_trajcs_buffer = write_only pocl chunk_trajcs_array in let show_sizes _ = Printf.printf "Array sizes:\n"; Printf.printf "ROI-type = %d,%d\n" roi_nx roi_ny ; let (x,y) = ODM.shape uv_array in Printf.printf "uv = %d,%d\n" x y; let (x,y) = ODM.shape chunk_trajcs_array in let (num_seeds,_) = ODM.shape seeds in Printf.printf "Streamlines virtual array allocation: %d,%d size %d\n" num_seeds y (num_seeds*y*max_traj_length*2); Printf.printf "Streamlines array allocation per chunk: %d,%d size %d\n%!" x y (ODM.size_in_bytes chunk_trajcs_array) in pv_verbose data show_sizes; { uv_array; mapping_array; chunk_nsteps_array; chunk_length_array; chunk_trajcs_array; seeds_buffer; mask_buffer; uv_buffer; mapping_buffer; chunk_nsteps_buffer; chunk_length_buffer; chunk_trajcs_buffer; } (** [memory_copyback t pocl] Copy back the chunk buffers from the GPU to the big arrays after execution of the integrate_trajectories kernel *) let memory_copyback t pocl = Pocl.copy_buffer_from_gpu pocl ~src:t.chunk_trajcs_buffer ~dst:t.chunk_trajcs_array; Pocl.copy_buffer_from_gpu pocl ~src:t.chunk_nsteps_buffer ~dst:t.chunk_nsteps_array; Pocl.copy_buffer_from_gpu pocl ~src:t.chunk_length_buffer ~dst:t.chunk_length_array; Pocl.finish_queue pocl (** {1 GPU functions} *) (** [gpu_integrate_chunk pocl data memory streamline_lists results cl_kernel_source t] Integrate a chunk of seeds on the GPU - this is a set of consecutive seeds in either upstream or downstream - and aggregate the results *) let gpu_integrate_chunk pocl data memory streamline_lists results cl_kernel_source t = if t.required then ( pv_verbose data (fun _ -> show_chunk t); (* Specify this integration job's parameters and compile *) let grid_scale = Info.float_of data.info "grid_scale" in Info.set data.info "downup_sign" (Info.Float32 t.downup_sign); Info.set data.info "seeds_chunk_offset" (Info.Int t.seed_offset); Info.set_float32 data.info "combo_factor" ((grid_scale *. data.properties.trace.integrator_step_factor) *. t.downup_sign); let compile_options = Pocl.compile_options pocl data.info "integrate_trajectory" in let program = Pocl.compile_program pocl cl_kernel_source compile_options in let kernel = Pocl.get_kernel pocl program "integrate_trajectory" in (* Execute the kernel *) Pocl.kernel_set_arg_buffer pocl kernel 0 memory.seeds_buffer; Pocl.kernel_set_arg_buffer pocl kernel 1 memory.mask_buffer; Pocl.kernel_set_arg_buffer pocl kernel 2 memory.uv_buffer; Pocl.kernel_set_arg_buffer pocl kernel 3 memory.mapping_buffer; Pocl.kernel_set_arg_buffer pocl kernel 4 memory.chunk_trajcs_buffer; Pocl.kernel_set_arg_buffer pocl kernel 5 memory.chunk_nsteps_buffer; Pocl.kernel_set_arg_buffer pocl kernel 6 memory.chunk_length_buffer; let n_work_items = Info.int_of data.info "n_work_items" in let global_size = round_up_to_unit_size t.num_seeds n_work_items in let time_taken = Pocl.adaptive_enqueue_kernel pocl kernel global_size n_work_items in Printf.printf "\n##### Kernel lapsed time: %0.3f secs #####\n" time_taken; memory_copyback memory pocl; (* Compile streamline results *) pv_noisy data (fun _ -> Printf.printf "Building streamlines compressed array for chunk\n%!"); for i=0 to t.num_seeds-1 do (* i is in range 0 to chunk_size-1 *) let seed_downup_index = 2*(i + t.seed_offset) + t.downup_index in let traj_nsteps = ODN.get memory.chunk_nsteps_array [|i|] in let traj_length = ODN.get memory.chunk_length_array [|i|] in let traj_vector n = ODN.get memory.chunk_trajcs_array [|i; n|] in ODN.set results.traj_nsteps_array [|seed_downup_index|] traj_nsteps; ODN.set results.traj_lengths_array [|seed_downup_index|] traj_length; let streamlines_of_seed = Bytes.init (traj_nsteps*2) traj_vector in streamline_lists.(t.downup_index) <- streamlines_of_seed :: ((streamline_lists.(t.downup_index))); done; ) else ( (* chunk was not required *) ) (** [gpu_integrate_trajectories pocl data seeds chunk_size to_do_list] Carry out GPU computations in the chunks on {i to_do_list}. Each chunk is handled with a separate compilation, and results are aggregated. *) let gpu_integrate_trajectories pocl data results seeds chunk_size to_do_list = let memory = memory_create_buffers pocl data seeds chunk_size in let streamline_lists = [| []; []; |] in let cl_kernel_source = Pocl.read_source cl_src_path cl_files in List.iter (fun chunk -> gpu_integrate_chunk pocl data memory streamline_lists results cl_kernel_source chunk) to_do_list; results.streamline_arrays <- [| Array.of_list (List.rev streamline_lists.(0)); Array.of_list (List.rev streamline_lists.(1)); |]; let total_steps = Array.fold_left (fun acc t -> acc+(Bytes.length t)) 0 results.streamline_arrays.(0) in let total_steps = Array.fold_left (fun acc t -> acc+(Bytes.length t)) total_steps results.streamline_arrays.(1) in pv_verbose data (fun _ -> Printf.printf "Total steps in all streamlines %d\n%!" (total_steps/2)); results (** [integrate_trajectories tprops pocl data results seeds] Integrate trajectories both upstream and downstream from the {i seeds} array of unpadded ROI coordinates. Trace each streamline from its corresponding seed point using 2nd-order Runge-Kutta integration of the topographic gradient vector field. @return trace_results *) let get_traj_stats data results num_seeds downup_index = let pixel_size = Info.float_of data.info "pixel_size" in let data_of_seed seed = let seed_downup_index = 2*seed + downup_index in let ln0 = (ODN.get results.traj_lengths_array [|seed_downup_index|]) *. pixel_size in let ln1 = float (ODN.get results.traj_nsteps_array [|seed_downup_index|]) in (ln0, ln1, ln0 /. ln1) in let line_stats = Array.init num_seeds data_of_seed in let lengths = Array.map (fun (x,_,_) -> x) line_stats in let counts = Array.map (fun (_,x,_) -> x) line_stats in let dses = Array.map (fun (_,_,x) -> x) line_stats in {l_mean=OS.mean lengths; l_min=OS.min lengths; l_max=OS.max lengths; c_mean=OS.mean counts; c_min=OS.min counts; c_max=OS.max counts; d_mean=OS.mean dses; d_min=OS.min dses; d_max=OS.max dses; } let show_stats results = let ds_stats = Option.get results.ds_stats in let us_stats = Option.get results.us_stats in Printf.printf " downstream upstream\n"; Printf.printf " min mean max min mean max\n"; Printf.printf "l %11.6f %11.6f %11.6f %11.6f %11.6f %11.6f\n" ds_stats.l_min ds_stats.l_mean ds_stats.l_max us_stats.l_min us_stats.l_mean us_stats.l_max ; Printf.printf "n %11.6f %11.6f %11.6f %11.6f %11.6f %11.6f\n" ds_stats.c_min ds_stats.c_mean ds_stats.c_max us_stats.c_min us_stats.c_mean us_stats.c_max ; Printf.printf "ds%11.6f %11.6f %11.6f %11.6f %11.6f %11.6f\n%!" ds_stats.d_min ds_stats.d_mean ds_stats.d_max us_stats.d_min us_stats.d_mean us_stats.d_max ; () let integrate_trajectories (tprops:t_props_trace) pocl data results seeds = Workflow.workflow_start ~subflow:"integrating trajectories" tprops.workflow; let gpu_traj_memory_limit = Pocl.get_memory_limit pocl in (* max memory permitted to use *) let (num_seeds,_) = ODM.shape seeds in let mem_per_seed = (Info.int_of data.info "max_n_steps") * 2 in (* an approximation *) let work_items_per_warp = Info.int_of data.info "n_work_items" in let max_chunk_size = gpu_traj_memory_limit / mem_per_seed in let max_chunk_size = round_up_to_unit_size max_chunk_size work_items_per_warp in let chunk_size = min (round_up_to_unit_size num_seeds work_items_per_warp) max_chunk_size in let full_traj_memory_request = chunk_size * mem_per_seed in let to_do_list = generate_chunks data num_seeds chunk_size in let num_chunks_required = List.length to_do_list in let show_memory _ = Printf.printf "GPU/OpenCL device global memory limit for streamline trajectories: %d\n" gpu_traj_memory_limit; Printf.printf "GPU/OpenCL device memory required for streamline trajectories: %d\n" full_traj_memory_request; (if num_chunks_required=1 then ( Printf.printf "no need to chunkify\n" ) else ( Printf.printf "need to split into %d chunks (note separation of up/down may impact this)\n" num_chunks_required ) ); Printf.printf "Number of seed points = total number of kernel instances: %d\n" num_seeds; Printf.printf "Max chunk size (given memory constraint, rounding up to num work items): %d\n" max_chunk_size; Printf.printf "Actual chunk size = number of kernel instances per chunk: %d\n" chunk_size; Printf.printf "%!" in pv_verbose data show_memory; gpu_integrate_trajectories pocl data results seeds chunk_size to_do_list; (* Streamline stats *) pv_verbose data (fun _ -> Printf.printf "Computing streamlines statistics\n"); results.ds_stats <- Some (get_traj_stats data results num_seeds 0); results.us_stats <- Some (get_traj_stats data results num_seeds 1); pv_verbose data (fun _ -> show_stats results); Workflow.workflow_end tprops.workflow; results
use advent_of_code::parse_dimensions; advent_of_code::solution!(2); fn calculate_paper(length: i32, width: i32, height: i32) -> i32 { let side1 = length * width; let side2 = width * height; let side3 = height * length; let smallest_side = side1.min(side2).min(side3); 2 * side1 + 2 * side2 + 2 * side3 + smallest_side } fn calculate_ribbon(length: i32, width: i32, height: i32) -> i32 { let mut dimensions = [length, width, height]; dimensions.sort_unstable(); let smallest_side = dimensions[0]; let second_smallest_side = dimensions[1]; let volume = length * width * height; 2 * smallest_side + 2 * second_smallest_side + volume } pub fn part_one(input: &str) -> Option<i32> { let total_paper: i32 = input .lines() .map(|line| match parse_dimensions(line) { Some((l, w, h)) => calculate_paper(l, w, h), None => panic!("Unexpected input"), }) .sum(); Some(total_paper) } pub fn part_two(input: &str) -> Option<i32> { let total_ribbon: i32 = input .lines() .map(|line| match parse_dimensions(line) { Some((l, w, h)) => calculate_ribbon(l, w, h), None => panic!("Unexpected input"), }) .sum(); Some(total_ribbon) } #[cfg(test)] mod tests { use super::*; #[test] fn test_calculate_paper() { assert_eq!(calculate_paper(2, 3, 4), 58); assert_eq!(calculate_paper(1, 1, 10), 43); } #[test] fn test_part_one() { let input = advent_of_code::template::read_file("examples", DAY); assert_eq!(part_one(&input), Some(101)); } #[test] fn test_part_two() { let input = advent_of_code::template::read_file("examples", DAY); assert_eq!(part_two(&input), Some(48)); } }
--- sidebar: sidebar permalink: docs/task_hcc_upgrade_storage_firmware.html summary: 'Dans le cadre de la mise à niveau d"un système NetApp HCI, vous mettez à niveau le firmware associé à vos nœuds de stockage.' keywords: netapp, element, hcc, firmware, storage firmware --- = Mettre à niveau le firmware du stockage :allow-uri-read: [role="lead"] À partir d'Element 12.0 et des services de gestion version 2.14, vous pouvez effectuer des mises à niveau du firmware uniquement sur vos nœuds de stockage H-Series à l'aide de l'interface de contrôle du cloud hybride NetApp et de l'API REST. Cette procédure ne met pas à niveau le logiciel Element et vous permet de mettre à niveau le firmware du stockage en dehors de la version d'un élément majeur. .Ce dont vous avez besoin * *Privilèges d'administrateur* : vous disposez des autorisations d'administrateur du cluster de stockage pour effectuer la mise à niveau. * *Synchronisation de l'heure du système* : vous avez vérifié que l'heure du système sur tous les nœuds est synchronisée et que NTP est correctement configuré pour le cluster de stockage et les nœuds. Chaque nœud doit être configuré avec un serveur de noms DNS dans l'interface utilisateur Web par nœud (`https://[IP address]:442`) sans erreurs de cluster non résolues liées à l'asymétrie du temps. * *Ports système* : si vous utilisez le contrôle du cloud hybride NetApp pour les mises à niveau, vous avez vérifié que les ports nécessaires sont ouverts. Voir link:hci_prereqs_required_network_ports.html["Ports réseau"] pour plus d'informations. * *Nœud de gestion* : pour l'interface utilisateur et l'API de contrôle de cloud hybride NetApp, le nœud de gestion de votre environnement exécute la version 11.3. * *Services de gestion*: Vous avez mis à jour votre bundle de services de gestion à la dernière version. IMPORTANT: Pour les nœuds de stockage H610S exécutant la version 12.0 du logiciel Element, vous devez appliquer le correctif SUST-909 avant de mettre à niveau le pack du firmware du stockage 2.27. Contactez le support NetApp pour obtenir le D-patch avant de procéder à la mise à niveau. Voir link:rn_storage_firmware_2.27.html["Notes de version du pack de firmware de stockage 2.27"]. IMPORTANT: Vous devez effectuer la mise à niveau vers le dernier bundle de services de gestion avant de mettre à niveau le firmware de vos nœuds de stockage. Si vous mettez à jour votre logiciel Element vers la version 12.2, vous avez besoin des services de gestion 2.14.60 ou une version ultérieure pour continuer. * *Cluster Health* : vous avez effectué des vérifications d'intégrité. Voir link:task_hcc_upgrade_element_prechecks.html["Exécutez des vérifications de l'état du stockage Element avant la mise à niveau du stockage"]. * *Mise à jour de BMC pour les nœuds H610S*: Vous avez mis à niveau la version de BMC pour vos nœuds H610S. Voir link:rn_H610S_BMC_3.84.07.html["notes de version et instructions de mise à niveau"]. NOTE: Pour obtenir une matrice complète du micrologiciel et du micrologiciel du pilote pour votre matériel, reportez-vous à link:firmware_driver_versions.html["Versions de firmware prises en charge pour les nœuds de stockage NetApp HCI"]la section . * *Contrat de licence utilisateur final (CLUF)* : à partir des services de gestion 2.20.69, vous devez accepter et enregistrer le CLUF avant d'utiliser l'interface utilisateur ou l'API de contrôle du cloud hybride NetApp pour mettre à niveau le micrologiciel de stockage : + .. Ouvrez l'adresse IP du nœud de gestion dans un navigateur Web : + [listing] ---- https://<ManagementNodeIP> ---- .. Connectez-vous au contrôle de cloud hybride NetApp en fournissant les identifiants de l'administrateur du cluster de stockage. .. Sélectionnez *Upgrade* en haut à droite de l'interface. .. Le CLUF s'affiche. Faites défiler vers le bas, sélectionnez *J'accepte les mises à jour actuelles et futures*, puis sélectionnez *Enregistrer*. .Options de mise à niveau Choisissez l'une des options de mise à niveau du micrologiciel de stockage suivantes : * <<Utilisez l'interface de contrôle du cloud hybride NetApp pour la mise à niveau du firmware du stockage>> * <<Utilisez l'API de contrôle de cloud hybride NetApp pour mettre à niveau le firmware du stockage>> == Utilisez l'interface de contrôle du cloud hybride NetApp pour la mise à niveau du firmware du stockage Vous pouvez utiliser l'interface utilisateur de NetApp Hybrid Cloud Control pour mettre à niveau le firmware des nœuds de stockage dans votre cluster. .Ce dont vous avez besoin * Si votre nœud de gestion n'est pas connecté à Internet, vous avez https://mysupport.netapp.com/site/products/all/details/element-software/downloads-tab/download/62654/Storage_Firmware_Bundle["téléchargez le pack du firmware de stockage"^]. CAUTION: Si vous rencontrez des problèmes lors de la mise à niveau des clusters de stockage à l'aide de NetApp Hybrid Cloud Control et de leurs solutions, consultez le https://kb.netapp.com/Advice_and_Troubleshooting/Hybrid_Cloud_Infrastructure/NetApp_HCI/Potential_issues_and_workarounds_when_running_storage_upgrades_using_NetApp_Hybrid_Cloud_Control["Article de la base de connaissances"^]. TIP: Le processus de mise à niveau prend environ 30 minutes par nœud. .Étapes . Ouvrez l'adresse IP du nœud de gestion dans un navigateur Web : + [listing] ---- https://<ManagementNodeIP> ---- . Connectez-vous au contrôle de cloud hybride NetApp en fournissant les identifiants de l'administrateur du cluster de stockage. . Sélectionnez *Upgrade* en haut à droite de l'interface. . Sur la page *mises à niveau*, sélectionnez *stockage*. + [NOTE] ==== L'onglet *Storage* répertorie les clusters de stockage qui font partie de votre installation. Si un cluster n'est pas accessible via NetApp Hybrid Cloud Control, il ne s'affiche pas sur la page *mises à niveau*. Si vous avez des clusters exécutant Element 12.0 ou une version ultérieure, la version actuelle des packs de firmware est répertoriée pour ces clusters. Si les nœuds d'un cluster ont des versions de micrologiciel différentes ou lorsque la mise à niveau progresse, vous verrez *multiple* dans la colonne *version actuelle du bundle de micrologiciels*. Vous pouvez sélectionner *multiple* pour accéder à la page *Nodes* pour comparer les versions du micrologiciel. Si tous les clusters exécutent des versions Element avant la version 12.0, aucune information concernant les numéros de version des packs de firmware n'apparaît. Ces informations sont également disponibles sur la page *Nodes*. Voir link:task_hcc_nodes.html["Afficher votre inventaire"]. Si le cluster est à jour et/ou qu'aucun package de mise à niveau n'est disponible, les onglets *Element* et *Firmware Only* ne s'affichent pas. Ces onglets ne s'affichent pas également lorsqu'une mise à niveau est en cours. Si l'onglet *Element* est affiché mais pas l'onglet *Firmware Only*, aucun progiciel de microprogramme n'est disponible. ==== . Sélectionnez la flèche de liste déroulante située à côté du cluster que vous mettez à niveau. . Sélectionnez *Parcourir* pour télécharger le package de mise à niveau que vous avez téléchargé. . Attendez la fin du chargement. Une barre de progression indique l'état du téléchargement. + CAUTION: Le téléchargement du fichier sera perdu si vous vous éloignez de la fenêtre du navigateur. + Un message à l'écran s'affiche une fois le fichier téléchargé et validé. La validation peut prendre plusieurs minutes. Si vous ne vous éloignez pas de la fenêtre du navigateur à ce stade, le téléchargement du fichier est conservé. . Sélectionnez *Firmware Only*, puis choisissez parmi les versions de mise à niveau disponibles. . Sélectionnez *commencer la mise à niveau*. + TIP: Le *Statut de mise à niveau* change pendant la mise à niveau pour refléter l'état du processus. Elle change également en réponse aux actions que vous avez effectuées, comme la mise en pause de la mise à niveau, ou si la mise à niveau renvoie une erreur. Voir <<Modifications du statut des mises à niveau>>. + NOTE: Pendant que la mise à niveau est en cours, vous pouvez quitter la page et y revenir plus tard pour continuer à suivre la progression. La page ne met pas à jour dynamiquement l'état et la version actuelle si la ligne du cluster est réduite. La ligne du cluster doit être développée pour mettre à jour la table ou vous pouvez actualiser la page. Vous pouvez télécharger les journaux une fois la mise à niveau terminée. === Modifications du statut des mises à niveau Voici les différents États que la colonne *Upgrade Status* de l'interface utilisateur affiche avant, pendant et après le processus de mise à niveau : [cols="2*"] |=== | État de mise à niveau | Description | À jour | Le cluster a été mis à niveau vers la dernière version d'Element disponible ou le micrologiciel a été mis à niveau vers la dernière version. | Détection impossible | Cet état s'affiche lorsque l'API du service de stockage renvoie un état de mise à niveau qui ne figure pas dans la liste énumérée des États de mise à niveau possibles. | Versions disponibles | Des versions plus récentes du firmware Element et/ou de stockage sont disponibles pour la mise à niveau. | En cours | La mise à niveau est en cours. Une barre de progression indique l'état de la mise à niveau. Les messages à l'écran affichent également les défaillances au niveau du nœud et l'ID de nœud de chaque nœud du cluster au fur et à mesure de la mise à niveau. Vous pouvez contrôler l'état de chaque nœud via l'interface utilisateur Element ou le plug-in NetApp Element pour l'interface utilisateur de vCenter Server. | Mise à niveau en pause | Vous pouvez choisir d'interrompre la mise à niveau. Selon l'état du processus de mise à niveau, l'opération de pause peut réussir ou échouer. Une invite de l'interface utilisateur s'affiche pour vous demander de confirmer l'opération de pause. Pour vérifier que le cluster est bien en place avant d'interrompre une mise à niveau, il peut prendre jusqu'à deux heures pour que l'opération de mise à niveau soit complètement suspendue. Pour reprendre la mise à niveau, sélectionnez *reprendre*. | En pause | Vous avez interrompu la mise à niveau. Sélectionnez *reprendre* pour reprendre le processus. | Erreur | Une erreur s'est produite lors de la mise à niveau. Vous pouvez télécharger le journal des erreurs et l'envoyer au support NetApp. Après avoir résolu l'erreur, vous pouvez revenir à la page et sélectionner *reprendre*. Lorsque vous reprenez la mise à niveau, la barre de progression revient en arrière pendant quelques minutes pendant que le système exécute la vérification de l'état et vérifie l'état actuel de la mise à niveau. |=== == Que se passe-t-il si une mise à niveau échoue avec NetApp Hybrid Cloud Control En cas de panne d'un disque ou d'un nœud lors de la mise à niveau, l'interface d'Element affiche les défaillances de cluster. Le processus de mise à niveau ne se poursuit pas vers le nœud suivant et attend que les pannes du cluster soient résolu. La barre de progression dans l'interface utilisateur indique que la mise à niveau attend la résolution des pannes du cluster. À ce stade, la sélection de *Pause* dans l'interface utilisateur ne fonctionnera pas, car la mise à niveau attend que le cluster fonctionne correctement. Vous devrez faire appel au support NetApp pour résoudre le problème. Le contrôle du cloud hybride NetApp offre une période d'attente prédéfinie de trois heures. Pour ce faire, vous pouvez utiliser l'un des scénarios suivants : * Les pannes de cluster sont résolues dans une fenêtre de trois heures, puis une mise à niveau est rétablie. Vous n'avez pas besoin d'effectuer d'action dans ce scénario. * Le problème persiste après trois heures et l'état de la mise à niveau affiche *erreur* avec une bannière rouge. Vous pouvez reprendre la mise à niveau en sélectionnant *reprendre* après la résolution du problème. * Le support NetApp a déterminé que la mise à niveau doit être provisoirement abandonnée pour prendre une action corrective avant une fenêtre de trois heures. Le support utilisera l'API pour annuler la mise à niveau. CAUTION: L'abandon de la mise à niveau du cluster pendant la mise à jour d'un nœud peut entraîner le retrait non normal des disques du nœud. Si la suppression des disques n'est pas normale, le support NetApp implique une intervention manuelle de chaque fois que vous ajoutez des disques lors d'une mise à niveau. Il est possible que le nœud mette plus de temps à effectuer des mises à jour de firmware ou à effectuer des activités de synchronisation post-mise à jour. Si la progression de la mise à niveau semble bloquée, contactez le support NetApp pour obtenir de l'aide. == Utilisez l'API de contrôle de cloud hybride NetApp pour mettre à niveau le firmware du stockage Vous pouvez utiliser des API pour mettre à niveau les nœuds de stockage d'un cluster vers la version la plus récente du logiciel Element. Vous pouvez utiliser l'outil d'automatisation de votre choix pour exécuter les API. Le workflow d'API documenté ici utilise l'interface d'API REST disponible sur le nœud de gestion, par exemple. .Étapes . Téléchargez le dernier pack de mise à niveau du micrologiciel de stockage sur un périphérique accessible au nœud de gestion ; accédez au https://mysupport.netapp.com/site/products/all/details/element-software/downloads-tab/download/62654/Storage_Firmware_Bundle["Page de bundle du firmware du stockage du logiciel Element"^] et téléchargez la dernière image du micrologiciel de stockage. . Téléchargez le pack de mise à niveau du firmware de stockage sur le nœud de gestion : + .. Ouvrez l'interface de l'API REST du nœud de gestion sur le nœud de gestion : + [listing] ---- https://<ManagementNodeIP>/package-repository/1/ ---- .. Sélectionnez *Authorise* et procédez comme suit : + ... Saisissez le nom d'utilisateur et le mot de passe du cluster. ... Entrez l'ID client comme `mnode-client`. ... Sélectionnez *Autoriser* pour démarrer une session. ... Fermez la fenêtre d'autorisation. .. Dans l'interface utilisateur de l'API REST, sélectionnez *POST /packages*. .. Sélectionnez *essayez-le*. .. Sélectionnez *Parcourir* et sélectionnez le package de mise à niveau. .. Sélectionnez *Exécuter* pour lancer le téléchargement. .. A partir de la réponse, copiez et enregistrez l'ID de package (`"id"`) pour l'utiliser ultérieurement. . Vérifiez l'état du chargement. + .. Dans l'interface utilisateur de l'API REST, sélectionnez *GET​ /packages​/{ID}​/status*. .. Sélectionnez *essayez-le*. .. Saisissez l'ID du progiciel de micrologiciel que vous avez copié à l'étape précédente dans *ID*. .. Sélectionnez *Exécuter* pour lancer la demande d'état. + La réponse indique `state` que `SUCCESS` lorsque vous avez terminé. . Identifiez l'ID de ressource d'installation : + .. Ouvrez l'interface de l'API REST du nœud de gestion sur le nœud de gestion : + [listing] ---- https://<ManagementNodeIP>/inventory/1/ ---- .. Sélectionnez *Authorise* et procédez comme suit : + ... Saisissez le nom d'utilisateur et le mot de passe du cluster. ... Entrez l'ID client comme `mnode-client`. ... Sélectionnez *Autoriser* pour démarrer une session. ... Fermez la fenêtre d'autorisation. .. Dans l'interface utilisateur de l'API REST, sélectionnez *OBTENIR /installations*. .. Sélectionnez *essayez-le*. .. Sélectionnez *Exécuter*. .. Dans la réponse, copiez l'ID de ressource d'installation (`id`). + [listing, subs="+quotes"] ---- *"id": "abcd01e2-xx00-4ccf-11ee-11f111xx9a0b",* "management": { "errors": [], "inventory": { "authoritativeClusterMvip": "10.111.111.111", "bundleVersion": "2.14.19", "managementIp": "10.111.111.111", "version": "1.4.12" ---- .. Dans l'interface utilisateur de l'API REST, sélectionnez *GET /installations/{ID}*. .. Sélectionnez *essayez-le*. .. Collez l'ID de ressource d'installation dans le champ *ID*. .. Sélectionnez *Exécuter*. .. Dans la réponse, copiez et enregistrez l'ID du (`"id"`cluster de stockage ) du cluster que vous envisagez de mettre à niveau pour pouvoir l'utiliser ultérieurement. + [listing, subs="+quotes"] ---- "storage": { "errors": [], "inventory": { "clusters": [ { "clusterUuid": "a1bd1111-4f1e-46zz-ab6f-0a1111b1111x", *"id": "a1bd1111-4f1e-46zz-ab6f-a1a1a111b012",* ---- . Exécutez la mise à niveau du micrologiciel de stockage : + .. Ouvrez l'interface de l'API REST de stockage sur le nœud de gestion : + [listing] ---- https://<ManagementNodeIP>/storage/1/ ---- .. Sélectionnez *Authorise* et procédez comme suit : + ... Saisissez le nom d'utilisateur et le mot de passe du cluster. ... Entrez l'ID client comme `mnode-client`. ... Sélectionnez *Autoriser* pour démarrer une session. ... Fermez la fenêtre. .. Sélectionnez *POST /mises à niveau*. .. Sélectionnez *essayez-le*. .. Saisissez l'ID du package de mise à niveau dans le champ des paramètres. .. Saisissez l'ID de cluster de stockage dans le champ paramètre. .. Sélectionnez *Exécuter* pour lancer la mise à niveau. + La réponse doit indiquer l'état `initializing` : + [listing, subs="+quotes"] ---- { "_links": { "collection": "https://localhost:442/storage/upgrades", "self": "https://localhost:442/storage/upgrades/3fa85f64-1111-4562-b3fc-2c963f66abc1", "log": https://localhost:442/storage/upgrades/3fa85f64-1111-4562-b3fc-2c963f66abc1/log }, "storageId": "114f14a4-1a1a-11e9-9088-6c0b84e200b4", "upgradeId": "334f14a4-1a1a-11e9-1055-6c0b84e2001b4", "packageId": "774f14a4-1a1a-11e9-8888-6c0b84e200b4", "config": {}, *"state": "initializing",* "status": { "availableActions": [ "string" ], "message": "string", "nodeDetails": [ { "message": "string", "step": "NodePreStart", "nodeID": 0, "numAttempt": 0 } ], "percent": 0, "step": "ClusterPreStart", "timestamp": "2020-04-21T22:10:57.057Z", "failedHealthChecks": [ { "checkID": 0, "name": "string", "displayName": "string", "passed": true, "kb": "string", "description": "string", "remedy": "string", "severity": "string", "data": {}, "nodeID": 0 } ] }, "taskId": "123f14a4-1a1a-11e9-7777-6c0b84e123b2", "dateCompleted": "2020-04-21T22:10:57.057Z", "dateCreated": "2020-04-21T22:10:57.057Z" } ---- .. Copiez l'ID de mise à niveau (`"upgradeId"`) qui fait partie de la réponse. . Vérifier la progression et les résultats de la mise à niveau : + .. Sélectionnez *GET ​/upgrades/{upseId}*. .. Sélectionnez *essayez-le*. .. Saisissez l'ID de mise à niveau de l'étape précédente dans *mise à niveau Id*. .. Sélectionnez *Exécuter*. .. Procédez de l'une des manières suivantes en cas de problème ou d'exigence spéciale lors de la mise à niveau : + [cols="2*"] |=== | Option | Étapes | Vous devez corriger les problèmes d'intégrité du cluster dus à `failedHealthChecks` un message dans le corps de réponse. a| ... Consultez l'article de la base de connaissances spécifique répertorié pour chaque problème ou effectuez la solution spécifiée. ... Si vous spécifiez une base de connaissances, suivez la procédure décrite dans l'article correspondant de la base de connaissances. ... Après avoir résolu les problèmes de cluster, réauthentifier si nécessaire et sélectionner *PUT ​/upgrades/{upseId}*. ... Sélectionnez *essayez-le*. ... Saisissez l'ID de mise à niveau de l'étape précédente dans *mise à niveau Id*. ... Saisissez `"action":"resume"` le corps de la demande. + [listing] ---- { "action": "resume" } ---- ... Sélectionnez *Exécuter*. | Vous devez interrompre la mise à niveau, car la fenêtre de maintenance se ferme ou pour une autre raison. a| ... Réauthentifier si nécessaire et sélectionner *PUT ​/upgrades/{upseId}*. ... Sélectionnez *essayez-le*. ... Saisissez l'ID de mise à niveau de l'étape précédente dans *mise à niveau Id*. ... Saisissez `"action":"pause"` le corps de la demande. + [listing] ---- { "action": "pause" } ---- ... Sélectionnez *Exécuter*. |=== .. Exécutez l'API *GET ​/upgrades/{upseId}* plusieurs fois, selon les besoins, jusqu'à ce que le processus soit terminé. + Pendant la mise à niveau, le `status` indique `running` si aucune erreur n'est détectée. Lors de la mise à niveau de chaque nœud, la `step` valeur devient `NodeFinished`. + La mise à niveau s'est terminée avec succès lorsque la `percent` valeur est `100` et `state` indique `finished`. [discrete] == Trouvez plus d'informations * https://docs.netapp.com/us-en/vcp/index.html["Plug-in NetApp Element pour vCenter Server"^] * https://www.netapp.com/hybrid-cloud/hci-documentation/["Page Ressources NetApp HCI"^]
import { Flex, Input, Table, TableCaption, TableContainer, Tbody, Text, Tfoot, Th, Thead, Tr, } from "@chakra-ui/react"; import { parseCookies } from "nookies"; import { useMemo, useState } from "react"; import { TableContentClient } from "../../components/TableContentClient"; import { useColors } from "../../hooks/useColors"; import { setupAPIClient } from "../../services/api"; import { withSSRAuth } from "../../utils/withSSRAuth"; // type ClientProps = { // rut: string; // name: string; // lastName: string; // email: string; // created_at: string; // }; export default function client({ appointmentData }) { const { colors } = useColors(); const [search, setSearch] = useState(""); const clientFiltered = useMemo(() => { const lowerSearch = search.toLowerCase(); return appointmentData?.filter((clients) => clients.client.name.toLowerCase().includes(lowerSearch) ); }, [search, appointmentData]); return ( <Flex flex="1" w={[ "calc(100vw - 50px)", "calc(100vw - 50px)", "calc(100vw - 50px)", "calc(100vw - 250px)", ]} align="top" justify="center" bg={colors.bg} color={colors.color} > <TableContainer w="80%"> <Text color={colors.color} mb="8px"> Cliente: </Text> <Input onChange={(event) => setSearch(event.target.value)} placeholder="Buscar" size="sm" w="30%" minW="200px" /> <Table w="100%" variant="striped"> <TableCaption>Tabla de clientes</TableCaption> <Thead> <Tr> <Th>Rut</Th> <Th>Nombre</Th> <Th>Apellido</Th> <Th>Estado</Th> <Th></Th> </Tr> </Thead> <Tbody color={colors.color}> {clientFiltered?.map((clients) => ( <TableContentClient key={clients.client.rut} rut={clients.client.rut} name={clients.client.name} lastName={clients.client.lastName} state={clients.state} email={clients.client.email} /> ))} </Tbody> <Tfoot> <Tr> <Th>Rut</Th> <Th>Nombre</Th> <Th>Apellido</Th> <Th>Estado</Th> <Th></Th> </Tr> </Tfoot> </Table> </TableContainer> </Flex> ); } export const getServerSideProps = withSSRAuth( async (ctx) => { try { const apiClient = setupAPIClient(ctx); // const response = await apiClient.get("/me"); // const user = { // name: response.data.name, // lastName: response.data.lastName, // email: response.data.email, // }; const cookies = parseCookies(ctx); const rutNutritionist = cookies["rut"]; const responseAppointment = await apiClient.get( `/appointments/${rutNutritionist}` ); const appointmentData = responseAppointment?.data; return { props: { appointmentData, }, }; } catch (err) { return { props: { appointmentData: [], }, }; } }, { roles: "nutritionist", } );
import { XMarkIcon } from "@heroicons/react/20/solid"; import { useEffect, useRef, useState } from "react"; export default function SearchInput({ userSearch = "", onSearch = () => {}, onInput = () => {} }) { const [search, setSearch] = useState(userSearch); const inputRef = useRef(null) const handleSearch = e => { setSearch(e.target.value.trim()) } const clearSearch = () => { setSearch("") onSearch("") inputRef.current.focus() } useEffect(() => { onInput(search) const debounce = setTimeout(() => { if(search) { onSearch(search) } }, 900) return () => clearTimeout(debounce) }, [search]) return ( <div className="relative"> <input ref={inputRef} type="text" className="!h-9 !border-none focus:outline-none focus:ring-0 w-full pr-8 pl-3" placeholder="Search" value={search} onChange={handleSearch} /> { search ? ( <button onClick={clearSearch} className="absolute right-1 hover:bg-gray-200/50 p-0.5 rounded-full top-[1.05rem] -translate-y-1/2"> <XMarkIcon className="w-5 h-5" /> </button> ) : ("") } </div> ); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> class Gempa { constructor(lokasi, skala) { this.lokasi = lokasi; this.skala = skala; } statusGempa() { let dampak = ""; if (this.skala < 2) { dampak = "Tidak Terasa"; } if (this.skala >= 2 && this.skala < 4) { dampak = "Bangunan Retak-Retak"; } if (this.skala >= 4 && this.skala < 6) { dampak = "Bangunan Roboh"; } if (this.skala >= 6) { dampak = "Bangunan Roboh & Berpotensi Tsunami"; } document.write(` Peringatan Gempa!!! <br/>Tempat: ${this.lokasi} <br/>Skala: ${this.skala} <br/>Dampak: ${dampak} <hr> `) } } const gempa1Lokasi1 = new Gempa("Planet Jupiter", 1); const gempa1Lokasi2 = new Gempa("Planet Saturnus", 1); gempa1Lokasi1.statusGempa(); gempa1Lokasi2.statusGempa(); const gempa2Lokasi1 = new Gempa("Planet Jupiter", 2); const gempa2Lokasi2 = new Gempa("Planet Saturnus", 3); gempa2Lokasi1.statusGempa(); gempa2Lokasi2.statusGempa(); const gempa3Lokasi1 = new Gempa("Planet Jupiter", 4); const gempa3Lokasi2 = new Gempa("Planet Saturnus", 5); gempa3Lokasi1.statusGempa(); gempa3Lokasi2.statusGempa(); const gempa4Lokasi1 = new Gempa("Planet Jupiter", 6); const gempa4Lokasi2 = new Gempa("Planet Saturnus", 8); gempa4Lokasi1.statusGempa(); gempa4Lokasi2.statusGempa(); </script> </body> </html>
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateServiceTransactionTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('service_transactions', function (Blueprint $table) { $table->id(); $table->string('user_id'); $table->string('status'); $table->string('address'); $table->string('type'); $table->string('kind'); $table->text('desc'); $table->string('last_time'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('service_transactions'); } }
from airflow import DAG from airflow.operators.python_operator import PythonOperator from airflow.hooks.base_hook import BaseHook from airflow.providers.postgres.hooks.postgres import PostgresHook from datetime import datetime, timedelta from faker import Faker import random # Initialize Faker fake = Faker() def generate_random_uber_data(): # Generate random data using Faker ride_id = fake.uuid4() pickup_location = f"{fake.latitude()}, {fake.longitude()}" dropoff_location = f"{fake.latitude()}, {fake.longitude()}" pickup_time = fake.date_time_this_year() dropoff_time = pickup_time + timedelta(minutes=random.randint(5, 30)) # Simulate ride duration date_collected = pickup_time.date() driver_name = fake.name() passenger_name = fake.name() fare_amount = round(random.uniform(10.0, 100.0), 2) # Simulate fare amount between $10 and $100 ride_duration = round((dropoff_time - pickup_time).total_seconds() / 60, 2) # Duration in minutes # Return the generated data return { 'ride_id': ride_id, 'pickup_location': pickup_location, 'dropoff_location': dropoff_location, 'pickup_time': pickup_time, 'dropoff_time': dropoff_time, 'date_collected': date_collected, 'driver_name': driver_name, 'passenger_name': passenger_name, 'fare_amount': fare_amount, 'ride_duration': ride_duration, } def create_table_if_not_exists(): hook = PostgresHook(postgres_conn_id='postgres') conn = hook.get_conn() cur = conn.cursor() create_table_query = """ CREATE TABLE IF NOT EXISTS uber_data ( id SERIAL PRIMARY KEY, ride_id VARCHAR(255), pickup_location VARCHAR(255), dropoff_location VARCHAR(255), pickup_time TIMESTAMP, dropoff_time TIMESTAMP, date_collected DATE, driver_name VARCHAR(255), passenger_name VARCHAR(255), fare_amount DECIMAL(10, 2), ride_duration DECIMAL(10, 2) ) """ cur.execute(create_table_query) conn.commit() cur.close() conn.close() def insert_data_into_postgres(**kwargs): # Retrieve the data from the task instance data = kwargs['ti'].xcom_pull(task_ids='generate_data') # Connect to PostgreSQL hook = PostgresHook(postgres_conn_id='postgres') conn = hook.get_conn() cur = conn.cursor() # Insert data into PostgreSQL insert_query = """ INSERT INTO uber_data ( ride_id, pickup_location, dropoff_location, pickup_time, dropoff_time, date_collected, driver_name, passenger_name, fare_amount, ride_duration ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ cur.execute(insert_query, ( data['ride_id'], data['pickup_location'], data['dropoff_location'], data['pickup_time'], data['dropoff_time'], data['date_collected'], data['driver_name'], data['passenger_name'], data['fare_amount'], data['ride_duration'] )) conn.commit() cur.close() conn.close() # Define the default arguments # Define default arguments for the DAG default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': datetime(2024, 9, 1, 0, 0), # Specific start date and time 'retries': 1, 'retry_delay': timedelta(minutes=5), } # Define the DAG dag = DAG( 'fetch_and_insert_uber_data', default_args=default_args, description='Fetch random Uber data, create table if not exists, and insert into PostgreSQL', schedule_interval='* * * * *', # Run every minute catchup=False, # Avoid backfilling if not needed ) # Define the tasks create_table = PythonOperator( task_id='create_table', python_callable=create_table_if_not_exists, dag=dag, ) generate_data = PythonOperator( task_id='generate_data', python_callable=generate_random_uber_data, dag=dag, ) insert_data = PythonOperator( task_id='insert_data', python_callable=insert_data_into_postgres, provide_context=True, dag=dag, ) # Set task dependencies create_table >> generate_data >> insert_data
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:get/get.dart'; import 'package:hirehub/config/Constants.dart'; import 'package:hirehub/models/Job.dart'; class DetailHeader extends StatelessWidget { const DetailHeader({ Key? key, required this.data, }) : super(key: key); final Job data; @override Widget build(BuildContext context) { ScreenUtil.init(context); return Padding( padding: EdgeInsets.symmetric( horizontal: kSpacingUnit * 1, vertical: kSpacingUnit * 1.5, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ GestureDetector( onTap: () => Navigator.pop(context), child: SvgPicture.asset( 'assets/icons/chevron_left_icon.svg', height: 30.sp, width: 30.sp, color: Get.isDarkMode ? Colors.white : Colors.blue, ), ), Text( data.title!, style: kSubTitleTextStyle.copyWith( fontWeight: FontWeight.w600, color: Get.isDarkMode ? Colors.white : Colors.black, ), ), SizedBox(width: 30.sp), ], ), ); } }
// Copyright Crucible Networks Ltd 2023. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "EmergenceAsyncSingleRequestBase.h" #include "HttpModule.h" #include "Interfaces/IHttpRequest.h" #include "ErrorCodeFunctionLibrary.h" #include "Runtime/JsonUtilities/Public/JsonObjectConverter.h" #include "EmergenceInventoryServiceStructs.h" #include "GetDynamicMetadata.generated.h" UCLASS() class EMERGENCE_API UGetDynamicMetadata : public UEmergenceAsyncSingleRequestBase { GENERATED_BODY() public: /** * Gets the dynamic metadata from the Emergence inventory service database. * @param Network Network of the contract we're writing the metadata to. * @param TokenID The Token ID contract we're writing metadata to. * @param Contract The contact that we're writing to. */ UFUNCTION(BlueprintCallable, meta = (BlueprintInternalUseOnly = "true", WorldContext = "WorldContextObject"), Category = "Emergence|Inventory Service") static UGetDynamicMetadata* GetDynamicMetadata(UObject* WorldContextObject, const FString& Network, const FString& Contract, const FString& TokenID); virtual void Activate() override; DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnGetDynamicMetadataCompleted, FString, Response, EErrorCode, StatusCode); UPROPERTY(BlueprintAssignable) FOnGetDynamicMetadataCompleted OnGetDynamicMetadataCompleted; private: void GetDynamicMetadata_HttpRequestComplete(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded); FString Network, Contract, TokenID; };
class Node{ constructor(value){ this.value = value this.left = null this.right = null } } class binarySearchTree{ constructor(){ this.root = null } isEmpty(){ return this.root === null } // Big-O = O(n) (worst case) // Big-O = O(log n) (average case) insert(value){ const node = new Node(value) if(this.isEmpty()){ this.root = node }else{ this.insertNode(this.root,node) } } insertNode(root,node){ if(node.value<root.value){ if(root.left === null){ root.left = node }else{ this.insertNode(root.left,node) } }else{ if(root.right === null){ root.right = node }else{ this.insertNode(root.right,node) } } } // Big-O = O(log n) search(root,value){ if(!root){ return false }else{ if(root.value===value){ return true }else if(value<root.value){ return this.search(root.left,value) }else{ return this.search(root.right,value) } } } isBst(root,min,max){ if(!root){ return true } if(min && root.value <= min || max && root.value >=max){ return false } return this.isBst(root.left,min,root.value) && this.isBst(root.right,root.value,max) } findClosest(root,target){ let closest = root.value while(root){ if(Math.abs(target-closest) > Math.abs(target-root.value)){ closest = root.value } if(target < root.value){ root = root.left }else if (target > root.value){ root = root.right }else{ break } } return closest } preOrder(root){ if(root){ console.log(root.value) this.preOrder(root.left) this.preOrder(root.right) } } inOrder(root){ if(root){ this.inOrder(root.left) console.log(root.value) this.inOrder(root.right) } } postOrder(root){ if(root){ this.postOrder(root.left) this.postOrder(root.right) console.log(root.value) } } levelOrder(){ // Use the optimized queue implementation const queue = [] queue.push(this.root) while(queue.length){ let curr = queue.shift() console.log(curr.value) if(curr.left){ queue.push(curr.left) } if(curr.right){ queue.push(curr.right) } } } min(root){ if(!root.left){ return root.value }else{ return this.min(root.left) } } max(root){ if(!root.right){ return root.value }else{ return this.max(root.right) } } findKthSmallest(k) { let count = 0; let result = null; const inorder = (node) => { if (!node || result !== null) return; inorder(node.left); count++; if (count === k) { result = node.value; return; } inorder(node.right); }; inorder(this.root); return result; } findKthLargest(k) { let count = 0; let result = null; const reverseInorder = (node) => { if (!node || result !== null) return; reverseInorder(node.right); count++; if (count === k) { result = node.value; return; } reverseInorder(node.left); }; reverseInorder(this.root); return result; } // Big O = O(log n) (average case) // Big O = O(n) (worst case) delete(value){ this.root = this.deleteNode(this.root,value) } deleteNode(root,value){ if(root === null){ return root } if(value<root.value){ root.left = this.deleteNode(root.left,value) }else if(value>root.value){ root.right = this.deleteNode(root.right,value) }else{ if(!root.left&&!root.right){ return null } if(!root.left){ return root.right }else if(!root.right){ return root.left } root.value = this.min(root.right) root.right = this.deleteNode(root.right,root.value) } return root } reverse(){ } } const bst = new binarySearchTree() console.log("tree is empty ?",bst.isEmpty()) bst.insert(10) bst.insert(5) bst.insert(15) bst.insert(3) bst.insert(7) bst.levelOrder() // bst.preOrder(bst.root) // console.log("----") // bst.inOrder(bst.root) // console.log("---")- // bst.postOrder(bst.root) // console.log(bst.search(bst.root,10)) // console.log(bst.search(bst.root,20)) console.log(bst.findKthLargest(2)) console.log(bst.findKthSmallest(2))
package funkin; import sys.FileSystem; import base.*; import dependency.FNFSprite; import flixel.FlxBasic; import flixel.FlxCamera; import flixel.FlxG; import flixel.FlxObject; import flixel.FlxSprite; import flixel.FlxState; import flixel.OverlayShader; import flixel.addons.effects.FlxTrail; import flixel.addons.effects.chainable.FlxWaveEffect; import flixel.group.FlxGroup.FlxTypedGroup; import flixel.group.FlxSpriteGroup; import flixel.math.FlxPoint; import flixel.system.FlxSound; import flixel.system.scaleModes.*; import flixel.text.FlxText; import flixel.tweens.FlxEase; import flixel.tweens.FlxTween; import flixel.util.FlxColor; import openfl.Assets; import openfl.display.BlendMode; import openfl.display.GraphicsShader; import openfl.filters.ShaderFilter; import states.PlayState; import funkin.background.*; using StringTools; /** This is the stage class. It sets up everything you need for stages in a more organised and clean manner than the base game. It's not too bad, just very crowded. I'll be adding stages as a separate thing to the weeks, making them not hardcoded to the songs. **/ class Stage extends FlxTypedGroup<FlxBasic> { // public var gfVersion:String = 'gf'; public var curStage:String; var daPixelZoom = PlayState.daPixelZoom; public var foreground:FlxTypedGroup<FlxBasic>; public var layers:FlxTypedGroup<FlxBasic>; public var spawnGirlfriend:Bool = true; public var stageScript:ScriptHandler; public function new(curStage:String = 'unknown', stageDebug:Bool = false) { super(); this.curStage = curStage; if (curStage == null || curStage.length < 1) { switch (CoolUtil.spaceToDash(PlayState.SONG.song.toLowerCase())) { case 'bopeebo' | 'fresh' | 'dadbattle' | 'dad-battle': curStage = 'stage'; case 'spookeez' | 'south' | 'monster': curStage = 'spooky'; case 'pico' | 'philly-nice' | 'philly' | 'blammed': curStage = 'philly'; case 'satin-panties' | 'high' | 'milf': curStage = 'highway'; case 'cocoa' | 'eggnog': curStage = 'mall'; case 'winter-horrorland': curStage = 'mallEvil'; case 'senpai' | 'roses': curStage = 'school'; case 'thorns': curStage = 'schoolEvil'; case 'ugh' | 'guns' | 'stress': curStage = 'military'; default: curStage = 'unknown'; } } if (!stageDebug) PlayState.curStage = PlayState.SONG.stage; // to apply to foreground use foreground.add(); instead of add(); foreground = new FlxTypedGroup<FlxBasic>(); layers = new FlxTypedGroup<FlxBasic>(); // switch (curStage) { default: curStage = 'unknown'; PlayState.defaultCamZoom = 0.9; } callStageScript(); } // return the girlfriend's type public function returnGFtype(curStage) { switch (curStage) { case 'highway': gfVersion = 'gf-car'; case 'mall' | 'mallEvil': gfVersion = 'gf-christmas'; case 'school' | 'schoolEvil': gfVersion = 'gf-pixel'; case 'military': if (PlayState.SONG.song.toLowerCase() == 'stress') gfVersion = 'pico-speaker'; else gfVersion = 'gf-tankmen'; default: gfVersion = 'gf'; } return gfVersion; } public function dadPosition(curStage:String, boyfriend:Character, gf:Character, dad:Character, camPos:FlxPoint):Void { callFunc('dadPosition', [boyfriend, gf, dad, camPos]); } public function repositionPlayers(curStage:String, boyfriend:Character, gf:Character, dad:Character) { callFunc('repositionPlayers', [boyfriend, gf, dad]); } public function stageUpdate(curBeat:Int, boyfriend:Character, gf:Character, dad:Character) { callFunc('updateStage', [curBeat, boyfriend, gf, dad]); } public function stageUpdateSteps(curStep:Int, boyfriend:Character, gf:Character, dad:Character) { callFunc('updateStageSteps', [curStep, boyfriend, gf, dad]); } public function stageUpdateConstant(elapsed:Float, boyfriend:Character, gf:Character, dad:Character) { callFunc('updateStageConst', [elapsed, boyfriend, gf, dad]); } override public function add(Object:FlxBasic):FlxBasic { if (Init.trueSettings.get('Disable Antialiasing') && Std.isOfType(Object, FlxSprite)) cast(Object, FlxSprite).antialiasing = false; return super.add(Object); } function callStageScript() { var paths:Array<String> = [ Paths.getPreloadPath('stages/$curStage/$curStage.hx'), Paths.getPreloadPath('stages/$curStage/$curStage.hxs') ]; for (path in paths) { if (FileSystem.exists(path)) stageScript = new ScriptHandler(path); } setVar('add', this.add); setVar('kill', this.kill); setVar('remove', this.remove); setVar('destroy', this.destroy); setVar('foreground', foreground); setVar('layers', layers); setVar('gfVersion', gfVersion); setVar('game', PlayState.contents); setVar('spawnGirlfriend', function(blah:Bool) { spawnGirlfriend = blah; }); setVar('BackgroundDancer', BackgroundDancer); setVar('BackgroundGirls', BackgroundGirls); setVar('TankmenBG', TankmenBG); callFunc('generateStage', []); } public function callFunc(key:String, args:Array<Dynamic>) { if (stageScript == null) return null; else return stageScript.call(key, args); } public function setVar(key:String, value:Dynamic) { if (stageScript == null) return null; else return stageScript.set(key, value); } }
using NetDot; using System.Globalization; namespace NetDotTests { public class DotNotationSerializationTests { [Fact] public void NullSerializesToEmptyString() { var text = DotNotation.Serialize(null); Assert.Equal("", text); } [Fact] public void CanSerializeSimpleProperties() { var text = DotNotation.Serialize(new { Name = "Felipe", Age = 47 }); Assert.Equal(""" Name=Felipe Age=47 """, text); } [Fact] public void CanSerializeSimpleNestedProperties() { var text = DotNotation.Serialize(new { Name = "Felipe", Age = 47, Brother = new { Name = "Julio" } }); Assert.Equal(""" Name=Felipe Age=47 Brother.Name=Julio """, text); } [Fact] public void CanSerializeArrayWithValueTypes() { var text = DotNotation.Serialize(new { Items = new object[] { "Felipe", 47 } }); Assert.Equal(""" Items[0]=Felipe Items[1]=47 """, text); } [Fact] public void CanSerializeGenericDictionaryWithValueTypes() { var text = DotNotation.Serialize(new { Items = new Dictionary<string, object> { ["Name"] = "Felipe", ["Age"] =47 } }); Assert.Equal(""" Items[Name]=Felipe Items[Age]=47 """, text); } [Fact] public void CanSerializeArraysWithinArraysWithValueTypes() { var text = DotNotation.Serialize(new { Items = new object[] { "Felipe", 47, new object[] { "Julio", 2 } } }); Assert.Equal(""" Items[0]=Felipe Items[1]=47 Items[2][0]=Julio Items[2][1]=2 """, text); } [Fact] public void CanSerializeDictionariesWithinArraysWithValueTypes() { var text = DotNotation.Serialize(new { Items = new object[] { "Felipe", 47, new Dictionary<string, object> { ["Name"]="Julio", ["Position"]=2 } } }); Assert.Equal(""" Items[0]=Felipe Items[1]=47 Items[2][Name]=Julio Items[2][Position]=2 """, text); } [Fact] public void CanSerializeArraysWithinDictionaries() { var text = DotNotation.Serialize(new { dict = new Dictionary<string, object> { ["Items"] = new object[] { "Felipe", 47 } } }); Assert.Equal(""" dict[Items][0]=Felipe dict[Items][1]=47 """, text); } record Person(string Name, int Age); record Group(Person[] Persons); record Job(string Name, decimal rate); record Employee( string Name, int Age, Group Friends, Group ManagedPeople, Group Supervisors, Job[] Jobs, Dictionary<string, Job> JobTransfers) : Person(Name, Age); [Fact] public void CanSerializeComplexObjectGraphs() { var person1 = new Person("Ricardo", 45); var person2 = new Person("Paulo", 72); var person3 = new Person("Marcelle", 52); var employee = new Employee( Name: "Felipe", Age: 47, Friends: new Group(new[] { person1, person3 }), ManagedPeople: new Group(new[] { person2 }), Supervisors: new Group(new[] { person3 }), Jobs: new[] { new Job("Worker", 20m), new Job("Slave", 1m) }, JobTransfers: new() { ["Night"] = new Job("Bouncer", 15m), } ); var text = DotNotation.Serialize(employee); Assert.Equal(""" Friends.Persons[0].Name=Ricardo Friends.Persons[0].Age=45 Friends.Persons[1].Name=Marcelle Friends.Persons[1].Age=52 ManagedPeople.Persons[0].Name=Paulo ManagedPeople.Persons[0].Age=72 Supervisors.Persons[0].Name=Marcelle Supervisors.Persons[0].Age=52 Jobs[0].Name=Worker Jobs[0].rate=20 Jobs[1].Name=Slave Jobs[1].rate=1 JobTransfers[Night].Name=Bouncer JobTransfers[Night].rate=15 Name=Felipe Age=47 """, text); } [Fact] public void CanChangeKeyValueSeparator() { var text = DotNotation.Serialize(new { Name = "Felipe", Age = 47 }, settings: new DotNotationSettings { KeyValueSeparator = ":" }); Assert.Equal(""" Name:Felipe Age:47 """, text); } [Fact] public void CanAddSpaceBeforeValue() { var text = DotNotation.Serialize(new { Name = "Felipe", Age = 47 }, settings: new DotNotationSettings { KeyValueSeparator = ":", SpacingBeforeValue = " " }); Assert.Equal(""" Name: Felipe Age: 47 """, text); } [Fact] public void CanAddSpaceAfterKey() { var text = DotNotation.Serialize(new { Name = "Felipe", Age = 47 }, settings: new DotNotationSettings { KeyValueSeparator = ":", SpacingBeforeValue = " ", SpacingAfterKey = " ", }); Assert.Equal(""" Name : Felipe Age : 47 """, text); } [Fact] public void CanSeparateItemsWithArbitrarySeparator() { var text = DotNotation.Serialize(new { Name = "Felipe", Age = 47 }, settings: new DotNotationSettings { EntrySeparator = ", " }); Assert.Equal(""" Name=Felipe, Age=47 """, text); } [Fact] public void CanQuoteStrings() { var text = DotNotation.Serialize(new { Name = "Felipe", Age = 47 }, settings: new DotNotationSettings { QuoteStrings = true }); Assert.Equal(""" Name="Felipe" Age=47 """, text); } [Fact] public void CanQuoteValues_WhichOverridesQuoteStrings() { var text = DotNotation.Serialize(new { Name = "Felipe", Age = 47 }, settings: new DotNotationSettings { QuoteValues = true }); Assert.Equal(""" Name="Felipe" Age="47" """, text); } [Fact] public void CanChangeQuoteChar() { var text = DotNotation.Serialize(new { Name = "Felipe", Age = 47 }, settings: new DotNotationSettings { QuoteValues = true, QuoteChar = '_' }); Assert.Equal(""" Name=_Felipe_ Age=_47_ """, text); } [Fact] public void CanChangeDotConnector() { var text = DotNotation.Serialize(new { Person = new { Name = "Felipe", Age = 47 } }, settings: new DotNotationSettings { DotConnector = "_" }); Assert.Equal(""" Person_Name=Felipe Person_Age=47 """, text); } [Fact] public void CanTrimValues() { var text = DotNotation.Serialize(new { Person = new { Name = " Felipe ", Age = 47 } }, settings: new DotNotationSettings { TrimValues = true }); Assert.Equal(""" Person.Name=Felipe Person.Age=47 """, text); } [Fact] public void WithoutTrimmingSpacingIsPreserved() { var text = DotNotation.Serialize(new { Person = new { Name = " Felipe ", Age = 47 } }, settings: new DotNotationSettings { TrimValues = false, QuoteStrings = true }); Assert.Equal(""" Person.Name=" Felipe " Person.Age=47 """, text); } [Fact] public void CanTrimMultipleCharacters() { var text = DotNotation.Serialize(new { Person = new { Name = " Felipe *** ", Age = 47 } }, settings: new DotNotationSettings { TrimValues = true, TrimChars = new[] { ' ', '*' } }); Assert.Equal(""" Person.Name=Felipe Person.Age=47 """, text); } [Fact] public void CanSurroundEntriesWithOpeningAndClosingText() { var text = DotNotation.Serialize(new { Person = new { Name = "Felipe", Age = 47 } }, settings: new DotNotationSettings { SurroundingTexts = ("{ ", " }")}); Assert.Equal(""" { Person.Name=Felipe } { Person.Age=47 } """, text); } [Fact] public void WillUrlEncodeValueIfNeeded() { var text = DotNotation.Serialize(new { Item = "Açúcar Mascavo" }, settings: new() { UrlEncode = true, }); Assert.Equal(""" Item=A%C3%A7%C3%BAcar%20Mascavo """, text); } [Fact] public void WillUrlEncodeKeyIfNeeded() { var text = DotNotation.Serialize(new { Açúcar = "Doce" }, settings: new() { UrlEncode = true, }); Assert.Equal(""" A%C3%A7%C3%BAcar=Doce """, text); } [Fact] public void WillUrlEncodeAddedQuotesIfNeeded() { var text = DotNotation.Serialize(new { Item = "Açúcar Mascavo" }, settings: new() { UrlEncode = true, QuoteStrings = true, }); Assert.Equal(""" Item=%22A%C3%A7%C3%BAcar%20Mascavo%22 """, text); } [Fact] public void BooleansAreSerializedAsLowerCase() { var text = DotNotation.Serialize(new { Bool1 = false, Bool2 = true }); Assert.Equal(""" Bool1=false Bool2=true """, text); } [Fact] public void DateTimesAreSerializedWithDateFormatString() { var fmt = "yyyy'-'MM'-'dd HH':'mm':'ss"; var dt = new DateTime(2023, 03, 31, 08, 30, 15); var text = DotNotation.Serialize(new { dt }, settings: new() { DateFormatString = fmt }); Assert.Equal(""" dt=2023-03-31 08:30:15 """, text); } [Fact] public void DateTimesNullableAreSerializedWithDateFormatString() { var fmt = "yyyy'-'MM'-'dd HH':'mm':'ss"; DateTime? dt = new DateTime(2023, 03, 31, 08, 30, 15); var text = DotNotation.Serialize(new { dt }, settings: new() { DateFormatString = fmt }); Assert.Equal(""" dt=2023-03-31 08:30:15 """, text); } [Fact] public void DateTimeWillRespectCulture() { var fmt = "yyyy/MMMM/dd HH:mm:ss"; var ptbr = CultureInfo.GetCultureInfo("pt-br"); var dt = new DateTime(2023, 03, 31, 08, 30, 15); var text = DotNotation.Serialize(new { dt }, settings: new() { DateFormatString = fmt, Culture = ptbr }); Assert.Equal(""" dt=2023/março/31 08:30:15 """, text); } [Fact] public void DateTimeOffsetsAreSerializedWithDateFormatString() { var fmt = "yyyy'-'MM'-'dd HH':'mm':'ss"; var dt = new DateTimeOffset(2023, 03, 31, 08, 30, 15, TimeSpan.FromHours(-3)); var text = DotNotation.Serialize(new { dt }, settings: new() { DateFormatString = fmt }); Assert.Equal(""" dt=2023-03-31 08:30:15 """, text); } [Fact] public void FloatingPointNumbersUseInvariantCulture() { var text = DotNotation.Serialize(new { n = 1.55 }); Assert.Equal(""" n=1.55 """, text); } [Fact] public void FloatingPointNumbersWillUseSelectedCulture() { var ptbr = CultureInfo.GetCultureInfo("pt-br"); var text = DotNotation.Serialize(new { n = 1.55 }, settings: new() { Culture = ptbr }); Assert.Equal(""" n=1,55 """, text); } [Fact] public void DecimalsUseInvariantCulture() { var text = DotNotation.Serialize(new { n = 1_999_999.55 }); Assert.Equal(""" n=1999999.55 """, text); } [Fact] public void DecimalsWillUseSelectedCulture() { var ptBr = CultureInfo.GetCultureInfo("pt-br"); var text = DotNotation.Serialize(new { n = 1_999_999.55 }, settings: new() { Culture = ptBr }); Assert.Equal(""" n=1999999,55 """, text); } [Fact] public void CanSerializeAsURLQueryString() { var queryString = DotNotation.Serialize(new { page = 10, pageSize = 50, user = new { id = 1, }, token = "my token/123" }, settings: new () { UrlEncode = true, EntrySeparator = "&", }); Assert.Equal("page=10&pageSize=50&user.id=1&token=my%20token%2F123", queryString); } [Fact] public void CanSerializeTwoDimensionalRootArray() { object[,] brothers = { { "felipe", 47 }, { "julio", 45 } }; var text = DotNotation.Serialize(brothers); Assert.Equal(""" [0][0]=felipe [0][1]=47 [1][0]=julio [1][1]=45 """, text); } [Fact] public void CanSerializeTwoDimensionalArray() { object[,] brothers = { { "felipe", 47 }, { "julio", 45 } }; var text = DotNotation.Serialize(new { brothers }); Assert.Equal(""" brothers[0][0]=felipe brothers[0][1]=47 brothers[1][0]=julio brothers[1][1]=45 """, text); } [Fact] public void CanSerializeMultiDimensionalArray() { object[,,] brothers = { { { "felipe", 47 }, { "julio", 45 } }, { { "marcelle", 52 }, { "rafael", 45 } }, { { "leonardo", 48 }, { "rodrigo", 43 } }, }; var text = DotNotation.Serialize(new { brothers }); Assert.Equal(""" brothers[0][0][0]=felipe brothers[0][0][1]=47 brothers[0][1][0]=julio brothers[0][1][1]=45 brothers[1][0][0]=marcelle brothers[1][0][1]=52 brothers[1][1][0]=rafael brothers[1][1][1]=45 brothers[2][0][0]=leonardo brothers[2][0][1]=48 brothers[2][1][0]=rodrigo brothers[2][1][1]=43 """, text); } [Fact] public void CanSerializeJaggedRootArray() { object[][] brothers; brothers = new object[2][]; brothers[0] = new object[] { "felipe", 47 }; brothers[1] = new object[] { "julio", 45, "paula", 43 }; var text = DotNotation.Serialize(brothers); Assert.Equal(""" [0][0]=felipe [0][1]=47 [1][0]=julio [1][1]=45 [1][2]=paula [1][3]=43 """, text); } [Fact] public void CanSerializeRootArray() { object[][] brothers; brothers = new object[2][]; brothers[0] = new object[] { "felipe", 47 }; brothers[1] = new object[] { "julio", 45, "paula", 43 }; var text = DotNotation.Serialize(new { brothers }); Assert.Equal(""" brothers[0][0]=felipe brothers[0][1]=47 brothers[1][0]=julio brothers[1][1]=45 brothers[1][2]=paula brothers[1][3]=43 """, text); } [Fact] public void CanSerializeMultidimensionalArrayInsideArray() { var text = DotNotation.Serialize(new { value = new object[] { "felipe", new object[,] { { 10, 22, "test" }, { 30, 44, "teste2" } } } }); Assert.Equal(""" value[0]=felipe value[1][0][0]=10 value[1][0][1]=22 value[1][0][2]=test value[1][1][0]=30 value[1][1][1]=44 value[1][1][2]=teste2 """, text); } } }
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Links</title> <style> /* # = id . = class : = pseudo-class :: = pseudo-elemento > = children */ body { font-family: Arial, Helvetica, sans-serif; } a { color: red; text-decoration: none; font-weight: 900; } a:visited { color: darkred; } a:hover { text-decoration: underline; color: #000; } a:active { color: yellow; } .especial { background: rgb(255, 140, 140); } .especial::before { content: "🔜"; } .especial::after { content: "🔙"; } </style> </head> <body> <h1>Personalizando Links</h1> <ul> <li><a href="http://github.com/Miguelhttp">Repositório GitHub</a></li> <li><a href="" class="especial">Canal do YouTube</a></li> <li> <a href="https://www.cursoemvideo.com" class="especial" >Site do CursoemVideo</a > </li> </ul> </body> </html>
[![Cookiecutter Plone Addon CI](https://github.com/plone/cookiecutter-plone/actions/workflows/plone_addon.yml/badge.svg)](https://github.com/plone/cookiecutter-plone/actions/workflows/plone_addon.yml) [![Built with Cookiecutter](https://img.shields.io/badge/built%20with-Cookiecutter-ff69b4.svg?logo=cookiecutter)](https://github.com/plone/cookiecutter-plone/) ![GitHub](https://img.shields.io/github/license/plone/cookiecutter-plone) [![Black code style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black) # Cookiecutter Plone Addon Powered by [Cookiecutter](https://github.com/cookiecutter/cookiecutter), [Cookiecutter Plone Addon](https://github.com/plone/cookiecutter-plone/plone_addon) is intended to be used by Plone developers to create new addon packages. ## Getting Started 🏁 ### Prerequisites - **pipx**: A handy tool for installing and running Python applications. ### Installation Guide 🛠️ 1. **pipx** ```shell pip install pipx ``` ### Generate Your Plone Addon 🎉 ```shell pipx run cookiecutter gh:plone/cookiecutter-plone ``` Then select the `Plone Add-on` template. ## Project Generation Options These are all the template options that will be prompted by the [Cookiecutter CLI](https://github.com/cookiecutter/cookiecutter) before generating your project. | Option | Description | Example | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | | `addon_title` | Your addon's human-readable name, capitals and spaces allowed. | **Plone Blog** | | `description` | Describes your addon and gets used in places like ``README.md`` and such. | **Create awesome blogs with Plone.** | | `author` | This is you! The value goes into places like ``LICENSE``, ``setup.py`` and such. | **Our Company** | | `email` | The email address you want to identify yourself in the project. | **email@example.com** | | `github_organization` | Used for GitHub and Docker repositories. | **collective** | | `python_package_name` | Name of the Python package used to configure your project. It needs to be Python-importable, so no dashes, spaces or special characters are allowed. | **collective.blog** | ## Code Quality Assurance 🧐 Your package comes equipped with linters to ensure code quality. Run the following to automatically format your code: ```shell make format ``` ## Internationalization 🌐 Generate translation files with ease: ```shell make i18n ``` ## License 📜 This project is licensed under the [MIT License](/LICENSE). ## Let's Get Building! 🚀 Happy coding!
package config // import ( // "context" // "expendit-server/models" // "go.mongodb.org/mongo-driver/bson" // "go.mongodb.org/mongo-driver/bson/primitive" // "go.mongodb.org/mongo-driver/mongo" // "go.mongodb.org/mongo-driver/mongo/options" // "log" // "os" // "time" // ) // type dbHandler interface { // GetUser(email string) (*models.User, error) // GetUsers() ([]*models.User, error) // CreateUser(user models.User) (*mongo.InsertOneResult, error) // UpdateUser(id string, user models.User) (*mongo.UpdateResult, error) // DeleteUser(id string) (*mongo.DeleteResult, error) // } // type DB struct { // client *mongo.Client // } // func collectionHelper(db *DB) *mongo.Collection { // // Get the collection name // collectionName := "User" // // Access the collection // collection := db.client.Database(os.Getenv("MONGODB_URI")).Collection(collectionName) // // Create index if it doesn't exist // indexModel := mongo.IndexModel{ // Keys: bson.D{{"email", 1}}, // Options: options.Index().SetUnique(true), // } // ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // defer cancel() // _, err := collection.Indexes().CreateOne(ctx, indexModel) // if err != nil { // log.Println("Failed to create index:", err) // } // return collection // } // func NewDBHandler() dbHandler { // LoadEnv() // ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // client, err := mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv("MONGODB_URI"))) // if err != nil { // log.Fatalln(err) // } // // Ping the database to check if it's connected // err = client.Ping(ctx, nil) // if err != nil { // log.Fatalln(err) // } // log.Println("Connected to MongoDB") // return &DB{client: client} // } // func (db *DB) GetUser(email string) (*models.User, error) { // collection := collectionHelper(db) // var user models.User // ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // defer cancel() // // Fetch user by email address // filter := bson.M{"email": email} // err := collection.FindOne(ctx, filter).Decode(&user) // if err != nil { // return nil, err // } // return &user, nil // } // func (db *DB) GetUsers() ([]*models.User, error) { // collection := collectionHelper(db) // var users []*models.User // ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // defer cancel() // cursor, err := collection.Find(ctx, bson.M{}) // if err != nil { // return nil, err // } // defer func(cursor *mongo.Cursor, ctx context.Context) { // err := cursor.Close(ctx) // if err != nil { // log.Println(err) // } // }(cursor, ctx) // for cursor.Next(ctx) { // var user models.User // err := cursor.Decode(&user) // if err != nil { // return nil, err // } // users = append(users, &user) // } // return users, nil // } // func (db *DB) CreateUser(user models.User) (*mongo.InsertOneResult, error) { // collection := collectionHelper(db) // ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // defer cancel() // newUser := models.User{ // Name: user.Name, // Email: user.Email, // Password: user.Password, // } // result, err := collection.InsertOne(ctx, newUser) // if err != nil { // return nil, err // } // return result, nil // } // func (db *DB) UpdateUser(id string, user models.User) (*mongo.UpdateResult, error) { // collection := collectionHelper(db) // ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // defer cancel() // updatedUser := bson.M{ // "name": user.Name, // "email": user.Email, // "password": user.Password, // } // result, err := collection.UpdateOne(ctx, bson.M{"_id": id}, bson.M{"$set": updatedUser}) // if err != nil { // return nil, err // } // return result, nil // } // func (db *DB) DeleteUser(id string) (*mongo.DeleteResult, error) { // collection := collectionHelper(db) // ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // defer cancel() // oid, err := primitive.ObjectIDFromHex(id) // result, err := collection.DeleteOne(ctx, bson.M{"_id": oid}) // if err != nil { // return nil, err // } // return result, nil // }
from django.conf import settings from django.db import models from django.utils import timezone from django.core.exceptions import ValidationError from PIL import Image import os def validate_image_dimensions(image): if image.width != 600 or image.height != 800: raise ValidationError("Image dimensions must be exactly 600 x 800 pixels.") def validate_pdf_extension(value): ext = os.path.splitext(value.name)[1] # Get the file extension valid_extensions = [".pdf"] # List of valid extensions if not ext.lower() in valid_extensions: raise ValidationError("Please upload a PDF file. ") class Product(models.Model): title = models.CharField(max_length=200) price = models.IntegerField() image = models.ImageField( upload_to="your_upload_path", validators=[validate_image_dimensions] ) description = models.CharField(max_length=100) # Optional description sub_title = models.CharField(max_length=200, null=True, default=None) time_spent = models.CharField(max_length=100, default=None) Brochure = models.FileField( upload_to="your_upload_path", validators=[validate_pdf_extension], null=True, default=None, ) About = models.TextField(null=True) Visit = models.TextField(null=True) Tours = models.TextField(null=True) Programs = models.TextField(null=True) Image_bk_1 = models.ImageField( upload_to="your_upload_path", ) Image_bk_2 = models.ImageField( upload_to="your_upload_path", ) Image_bk_3 = models.ImageField( upload_to="your_upload_path", ) is_active = models.BooleanField(default=True) # Control item visibility id = models.AutoField(primary_key=True) published_date = models.DateTimeField(default=timezone.now) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title
from http.server import HTTPServer, BaseHTTPRequestHandler import mimetypes import os import urllib.parse import socketserver import json from datetime import datetime import threading import socket class HttpHandler(BaseHTTPRequestHandler): def do_GET(self): # Перевіряємо, чи шлях запиту є кореневим ('/') if self.path == '/': # Якщо так, обробляємо домашню сторінку self.handle_home() else: # Якщо шлях не кореневий, обробляємо статичний контент self.handle_static() def do_POST(self): # Отримуємо розмір тіла POST-запиту з заголовку Content-Length content_length = int(self.headers['Content-Length']) # Зчитуємо тіло POST-запиту з вхідного потоку та декодуємо його з UTF-8 data = self.rfile.read(content_length).decode('utf-8') # Використовуємо parse_qs для перетворення рядка даних на словник data_dict = urllib.parse.parse_qs(data) # Отримуємо значення 'username' та 'message' username = data_dict.get('username', [''])[0] message = data_dict.get('message', [''])[0] # Отримуємо час отримання повідомлення timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") # Створюємо словник для data.json new_data = { "username": username, "message": message } print(f"Отримано дані з форми: {new_data}") # Отримуємо шлях до файлу data.json json_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'storage', 'data.json') # Перевіряємо, чи існує data.json і завантажуємо наявні дані data_dict_all = {} if os.path.exists(json_path): with open(json_path, 'r') as f: data_dict_all = json.load(f) # Додаємо нові дані до словника data_dict_all[timestamp] = new_data print(f"Нові дані для data.json: {new_data}") # Записуємо оновлений словник даних у data.json with open(json_path, 'w') as f: json.dump(data_dict_all, f, indent=2) # Відправляємо перенаправлення клієнту self.send_response(302) self.send_header('Location', '/') self.end_headers() def send_to_socket_server(self, data_dict): # Надсилання даних на Socket-сервер за допомогою UDP # Створення UDP-сокету try: client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Адреса та порт Socket-сервера server_address = ('localhost', 5000) # Підготовка повідомлення для відправки у форматі JSON з використанням поточного часу message = json.dumps({str(datetime.now()): data_dict}) # Відправка повідомлення на Socket-сервер client_socket.sendto(message.encode(), server_address) except Exception as e: print(f"Error sending data to Socket server: {e}") finally: # Закриття сокету після відправки client_socket.close() def handle_home(self): # Отримання поточної робочої директорії current_directory = os.path.dirname(os.path.abspath(__file__)) # Формування шляху до файлу 'index.html' в поточній директорії index_path = os.path.join(current_directory, 'index.html') # Виклик методу для відправлення HTML-файлу на клієнтську сторону self.send_html_file(index_path) def handle_static(self): # Формування шляху до запитаного статичного файлу на основі шляху в HTTP-запиті file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), self.path[1:]) # Перевірка існування файлу за вказаним шляхом if os.path.exists(file_path): # Відправлення статичного файлу, якщо файл існує self.send_static(file_path) else: # Якщо файл не знайдено, відправлення сторінки з помилкою 404 error_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'error.html') self.send_html_file(error_path, 404) def send_html_file(self, filename, status=200): # Відправлення відповіді з HTTP-статусом та заголовками self.send_response(status) self.send_header('Content-type', 'text/html') self.end_headers() # Відкриття та читання вмісту HTML-файлу with open(filename, 'rb') as fd: # Відправлення вмісту файлу через вихідний потік (self.wfile) self.wfile.write(fd.read()) def send_static(self, file_path): # Встановлення HTTP-статусу 200 для успішного відправлення статичного файлу self.send_response(200) # Визначення MIME-типу файлу mt = mimetypes.guess_type(file_path) # Встановлення заголовка Content-type на основі MIME-типу файлу if mt: self.send_header("Content-type", mt[0]) else: # Якщо MIME-тип не визначено, встановлення заголовка як 'text/plain' self.send_header("Content-type", 'text/plain') # Завершення заголовків перед відправленням вмісту self.end_headers() # Читання та відправлення вмісту файлу через вихідний потік with open(file_path, 'rb') as file: self.wfile.write(file.read()) class SocketServerHandler(socketserver.BaseRequestHandler): def handle(self): # Отримання та виведення даних від HTTP сервера data = self.request[0].decode() print(f"Отримані дані від HTTP сервера: {data}") try: # Розшифрування отриманих даних у форматі JSON data_dict = json.loads(data) # Створення шляху до директорії для зберігання файлу data.json storage_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'storage') if not os.path.exists(storage_directory): os.makedirs(storage_directory) # Формування шляху до файлу data.json json_path = os.path.join(storage_directory, 'data.json') data_dict_all = {} # Перевірка існування файлу data.json та завантаження наявних даних if os.path.exists(json_path): with open(json_path, 'r') as f: data_dict_all = json.load(f) # Додавання нових даних до словника timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") new_data = { "username": data_dict.get("username", ""), "message": data_dict.get("message", "") } data_dict_all[timestamp] = new_data # Виведення нових даних, які будуть записані в data.json print("Нові дані для data.json:") print(new_data) # Запис оновленого словника даних у файл data.json with open(json_path, 'w') as f: json.dump(data_dict_all, f, indent=2) except json.JSONDecodeError as e: print(f"Помилка декодування JSON-даних: {e}") def run_http_server(): # Конфігурація адреси та порту для HTTP сервера server_address = ('', 3000) # Створення екземпляру HTTP сервера з вказаною адресою та обробником http_server = HTTPServer(server_address, HttpHandler) try: # Запуск HTTP сервера та виведення повідомлення про старт print('Starting HTTP server...') http_server.serve_forever() except KeyboardInterrupt: # Обробка переривання з клавіатури та виведення повідомлення про зупинку сервера print('Shutting down HTTP server...') http_server.server_close() def run_socket_server(): # Конфігурація адреси та порту для Socket сервера socket_server_address = ('', 5000) # Створення екземпляру UDP сервера з вказаною адресою та обробником (SocketServerHandler) socket_server = socketserver.UDPServer(socket_server_address, SocketServerHandler) try: # Запуск Socket сервера та виведення повідомлення про старт print('Starting Socket server...') socket_server.serve_forever() except KeyboardInterrupt: # Обробка переривання з клавіатури та виведення повідомлення про зупинку сервера print('Shutting down Socket server...') socket_server.server_close() if __name__ == '__main__': # Створення окремого потоку для запуску HTTP сервера http_server_thread = threading.Thread(target=run_http_server) # Створення окремого потоку для запуску Socket сервера socket_server_thread = threading.Thread(target=run_socket_server) # Запуск потоків для HTTP та Socket серверів http_server_thread.start() socket_server_thread.start() # Очікування завершення виконання потоків http_server_thread.join() socket_server_thread.join()
# Actor Del <!-- @name: Actor Del @description: @tags: @categories: \--> Delete an Actor. When an actor is deleted, it no longer appears on the screen and all its events, animations and controls are deleted. ## Syntaxes > **Actor Del** \<string\> ->Ex: Actor Del "magic" > **Actor Del** index ->Ex: Actor Del 10 > **Actor Del** "*" > **Actor Del** "group$_name" (using the name of the Group\$ Actor parameter, used to regroup several actors together) Note: The use of () is also accepted > **Actor Del** (\<string\>) ->Ex: Actor Del ("magic") > **Actor Del** ( index ) ->Ex: Actor Del (10) > **Actor Del** ( "*" ) > **Actor Del** ( "group$_name" ) ## Parameters |**Parameter**|**Type**|**Description**| |---|---|---| |**`Index`**|index or string|Index or string of the Actor.If "*" is used, all the actors will been removed. | <BR> ## Example **Example:** ```basic Actor 1, Image$="magic" Actor 2, Image$="lucie", X=200 Actor "magic", Image$="magicfly", X=400 wait input Actor del 1 Actor del (2) Actor del "magic" ``` ```basic Actor "background", Image$="forest" Actor "ground", Image$="ground", Group$="g2", Y=900 Actor 1, Image$="magic", Group$="g1", X=100, Y=300 Actor 2, Image$="magicfly", Group$="g2", X=500, Y=300 Actor "front", Image$="magic", Group$="g2", X=1000, Y=300 // now let|;s delete the Actors or the groups of Actors wait input Actor Del "background" : Print "-deleting the background Actor" wait input //wait for a key or a mouse press Actor Del "ground" : Print "-deleting the ground Actor (that belongs to the g2 group)" wait input Actor Del "g1" : Print "-deleting the g1 group (made only of the 1 Actor)" wait input Actor Del "g2" : Print "-deleting the g2 group (with ground already deleted)" ``` <p align="center"><img valign="middle" width="76px" src="https://doc.aoz.studio/assets/images/en/image001.png" /></p> <!--stackedit_data: eyJoaXN0b3J5IjpbLTExNjM0ODI5OTldfQ== -->
//SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {IbcUtils} from "@open-ibc/vibc-core-smart-contracts/contracts/libs/IbcUtils.sol"; import "./base/CustomChanIbcApp.sol"; /** * @title PermissionedChannels * @dev PermissionedChannels builds on top of CustomChanIbcApp to limit channels that can be opened, and also provides modifiers that only permissioned contracts can be called. */ abstract contract PermissionedChannels is CustomChanIbcApp { mapping(string => bool) approvedAddresses; bytes32 channel; modifier onlyApprovedCounterParty(string calldata counterParty) { require(approvedAddresses[counterParty], "PermissionedChannels: Sender not approved"); _; } modifier onlyValidChannel(bytes32 callingChannelId) { require(callingChannelId == channel, "PermissionedChannels: Invalid channel"); _; } // We have to check the counterparty here since this is the first step that has been triggered on this chain function onChanOpenTry( ChannelOrder ordering, string[] memory connectionHops, bytes32 channelId, string calldata counterPartyPortId, bytes32 counterpartyChannelId, string calldata counterpartyVersion ) external override onlyIbcDispatcher onlyApprovedCounterParty(counterPartyPortId) returns (string memory selectedVersion) { return _connectChannel(channelId, counterpartyChannelId, counterpartyVersion); } // We don't have to check for counterPartyPortId here since dispatcher would only call this method if we initiated the channel handshake from a previous transaction function onChanOpenAck(bytes32 channelId, bytes32 counterpartyChannelId, string calldata counterpartyVersion) external override onlyIbcDispatcher { _setChannel(channelId); _connectChannel(channelId, counterpartyChannelId, counterpartyVersion); } // We don't have to check for counterPartyPortId here since dispatcher would only call this method since it was already validated in channeOpenTry function onChanOpenConfirm(bytes32 channelId) external override onlyIbcDispatcher { _setChannel(channelId); } /** * @dev Approves a counterparty address to interact with the contract. This should be called after both XTransfer Contracts are deployed on each chain to approve the counterparty contract from both chains. * @param counterPartyPortPrefix The port prefix of the counterparty chain you are communicating with * @param counterParty The address of the counterparty contract to approve. * @notice Only approved counterparties can open a channel with this dapp. */ function approveCounterParty(string memory counterPartyPortPrefix, address counterParty) external onlyOwner { approvedAddresses[IbcUtils.addressToPortId(counterPartyPortPrefix, counterParty)] = true; } function _setChannel(bytes32 channelId) internal { channel = channelId; } } contract XTransfer is PermissionedChannels, ERC20 { uint64 constant TIMEOUT = 1000; constructor(IbcDispatcher _dispatcher, string memory name, string memory symbol) CustomChanIbcApp(_dispatcher) ERC20(name, symbol) {} /** * @dev Deposits the caller's balance to the contract, which burns tokens so that they can be minted on a counterparty chain * @param balance The amount of tokens to move to the counterparty chain * @param gasLimits An array containing two gas limit values: * - gasLimits[0] for `recvPacket` fees * - gasLimits[1] for `ackPacket` fees. * @param gasPrices An array containing two gas price values: * - gasPrices[0] for `recvPacket` fees, for the dest chain * - gasPrices[1] for `ackPacket` fees, for the src chain */ function deposit(uint256 balance, uint256[2] memory gasLimits, uint256[2] memory gasPrices) external payable { _burn(msg.sender, balance); bytes memory payload = abi.encode(msg.sender, balance); uint64 timeoutTimestamp = uint64((block.timestamp + TIMEOUT) * 1000000000); uint64 sequence = dispatcher.sendPacket(channel, payload, timeoutTimestamp); _depositSendPacketFee(dispatcher, channel, sequence, gasLimits, gasPrices); } /* * @notice mint tokens on the destination chain */ function onRecvPacket(IbcPacket memory packet) external override onlyIbcDispatcher onlyValidChannel(packet.dest.channelId) returns (AckPacket memory ackPacket, bool skipAck) { // Mint the tokens on the destination chain, since this could only be triggered if tokens were burned on src chain. (address receiver, uint256 amountBurned) = abi.decode(packet.data, (address, uint256)); _mint(receiver, amountBurned); // Return true in ack packet, since we don't really need an ack and are done with our flow now. return (AckPacket(true, abi.encode(receiver, amountBurned)), true); } /** * Once a packet has been acked, we remove the timeout to */ function onAcknowledgementPacket(IbcPacket calldata, AckPacket calldata ack) external override onlyIbcDispatcher {} /** * @dev Packet lifecycle callback that implements packet receipt logic and return and acknowledgement packet. * MUST be overriden by the inheriting contract. * NOT SUPPORTED YET * @param packet the IBC packet encoded by the counterparty and relayed by the relayer */ function onTimeoutPacket(IbcPacket calldata packet) external override onlyIbcDispatcher {} }
/* * $Id$ * * Copyright (c) 2019-2024, CIAD Laboratory, Universite de Technologie de Belfort Montbeliard * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package fr.utbm.ciad.labmanager.views.components.addons.converters; import java.util.regex.Pattern; import com.vaadin.flow.data.binder.Result; import com.vaadin.flow.data.binder.ValueContext; import com.vaadin.flow.data.converter.Converter; /** A converter that is removing the spaces at the ends of the input string and replacing any keyword separator by a coma character. * * @author $Author: sgalland$ * @version $Name$ $Revision$ $Date$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 4.0 */ public class StringToKeywordsConverter implements Converter<String, String> { private static final long serialVersionUID = 2062988250883892074L; private static Pattern SEPARATORS = Pattern.compile("\\s*[,;:_.]\\s*"); //$NON-NLS-1$ private static final String DEFAULT_SEPARATOR = ","; //$NON-NLS-1$ @Override public Result<String> convertToModel(String value, ValueContext context) { if (value == null) { return Result.ok(""); //$NON-NLS-1$ } final var matcher = SEPARATORS.matcher(value.trim()); final var result = matcher.replaceAll(DEFAULT_SEPARATOR + " "); //$NON-NLS-1$ return Result.ok(result); } @Override public String convertToPresentation(String value, ValueContext context) { if (value == null) { return ""; //$NON-NLS-1$ } return value.trim(); } }
package ormtable_test import ( "context" "fmt" "testing" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/protojson" "github.com/regen-network/gocuke" "gotest.tools/v3/assert" "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "github.com/cosmos/cosmos-sdk/orm/testing/ormtest" ) func TestSave(t *testing.T) { gocuke.NewRunner(t, &suite{}).Path("../../features/table/saving.feature").Run() } type suite struct { gocuke.TestingT table ormtable.Table ctx context.Context err error } func (s *suite) Before() { var err error s.table, err = ormtable.Build(ormtable.Options{ MessageType: (&testpb.SimpleExample{}).ProtoReflect().Type(), }) assert.NilError(s, err) s.ctx = ormtable.WrapContextDefault(ormtest.NewMemoryBackend()) } func (s *suite) AnExistingEntity(docString gocuke.DocString) { existing := s.simpleExampleFromDocString(docString) assert.NilError(s, s.table.Insert(s.ctx, existing)) } func (s suite) simpleExampleFromDocString(docString gocuke.DocString) *testpb.SimpleExample { ex := &testpb.SimpleExample{} assert.NilError(s, protojson.Unmarshal([]byte(docString.Content), ex)) return ex } func (s *suite) IInsert(a gocuke.DocString) { ex := s.simpleExampleFromDocString(a) s.err = s.table.Insert(s.ctx, ex) } func (s *suite) IUpdate(a gocuke.DocString) { ex := s.simpleExampleFromDocString(a) s.err = s.table.Update(s.ctx, ex) } func (s *suite) ExpectAError(a string) { assert.ErrorContains(s, s.err, a) } func (s *suite) ExpectGrpcErrorCode(a string) { var code codes.Code assert.NilError(s, code.UnmarshalJSON([]byte(fmt.Sprintf("%q", a)))) assert.Equal(s, code, status.Code(s.err)) }
import { useState, useEffect } from "react"; import { useDrop } from "react-dnd"; import { Folder } from "../types/Folder"; export const FolderIcon: React.FC<{ folder: Folder; onSelect: (id: string) => void; onRename: (id: string, newName: string) => void; onDelete: (id: string) => void; onMoveBookmark: (bookmarkId: string, folderId: string) => void; }> = ({ folder, onSelect, onRename, onDelete, onMoveBookmark }) => { const [isEditing, setIsEditing] = useState(false); const [folderName, setFolderName] = useState(folder.name); const [showContextMenu, setShowContextMenu] = useState(false); const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0, }); const handleRename = () => { onRename(folder.id, folderName); setIsEditing(false); setShowContextMenu(false); }; const [{ isOver }, drop] = useDrop(() => ({ accept: "bookmark", drop: (item: { id: string }) => onMoveBookmark(item.id, folder.id), collect: (monitor) => ({ isOver: !!monitor.isOver(), }), })); const handleContextMenu = (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); setShowContextMenu(true); setContextMenuPosition({ x: e.pageX, y: e.pageY }); }; useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (showContextMenu) { setShowContextMenu(false); } }; document.addEventListener("click", handleClickOutside); return () => { document.removeEventListener("click", handleClickOutside); }; }, [showContextMenu]); return ( <div ref={drop} className={`w-24 h-24 m-2 flex flex-col items-center justify-center cursor-pointer rounded relative ${ isOver ? "bg-gray-700" : "hover:bg-gray-800" }`} onClick={() => !isEditing && onSelect(folder.id)} onContextMenu={handleContextMenu} > <div className="w-16 h-16 bg-gray-700 flex items-center justify-center rounded"> <span className="text-4xl">📁</span> </div> {isEditing ? ( <input type="text" value={folderName} onChange={(e) => setFolderName(e.target.value)} onBlur={handleRename} onKeyPress={(e) => e.key === "Enter" && handleRename()} className="w-full text-center mt-1 text-xs bg-gray-800 text-gray-300" autoFocus /> ) : ( <span className="text-md mt-1 text-center text-white shadow-sm overflow-hidden"> {folder.name} </span> )} {showContextMenu && ( <div className="fixed bg-white border border-gray-300 shadow-md rounded-md py-2 z-50" style={{ top: contextMenuPosition.y, left: contextMenuPosition.x }} > <button onClick={(e) => { e.stopPropagation(); setIsEditing(true); setShowContextMenu(false); }} className="block w-full text-left px-4 py-2 hover:bg-gray-100" > Rename </button> <button onClick={(e) => { e.stopPropagation(); onDelete(folder.id); setShowContextMenu(false); }} className="block w-full text-left px-4 py-2 hover:bg-gray-100" > Delete </button> </div> )} </div> ); };
import React from "react"; import {useState, useEffect} from "react"; import {useRouter} from "next/router"; export default function Detail() { //detail product by id product const [data, setData] = useState({}); const [loading, setLoading] = useState(true) const [error, setError] = useState(false) const router = useRouter() const { id } = router.query const handleDetailProduct = async (id) => { try { const res = await fetch(`/api/produk/${id}`) const json = await res.json() setData(json.data) setLoading(false) } catch (error) { setError(true) setLoading(false) } } useEffect(() => { if (id) { handleDetailProduct(id) } }, [id]) return ( <div className="container-fluid py-5" id="detail"> <div className="row px-xl-5"> <div className="col-lg-5 pb-5"> <div className="border"> <img className="w-50 h-50 text-center mx-auto justify-content-center" src={data.product_img} alt="" /> </div> </div> <div className="col-lg-7 pb-5"> <h3 className="font-weight-semi-bold">{data.product_name}</h3> <h3 className="font-weight-semi-bold mb-4">Rp.{data.product_price}</h3> <p className="mb-4"> {data.product_desc} </p> <a href="/"> <button className="btn btn-primary px-3"> <i className="fa fa-back mr-1" /> Kembali </button> </a> <div className="d-flex pt-2"> <p className="text-dark font-weight-medium mb-0 mr-2">Share on:</p> <div className="d-inline-flex"> <a className="text-dark px-2" href> <i className="fab fa-facebook-f" /> </a> <a className="text-dark px-2" href> <i className="fab fa-twitter" /> </a> <a className="text-dark px-2" href> <i className="fab fa-linkedin-in" /> </a> <a className="text-dark px-2" href> <i className="fab fa-pinterest" /> </a> </div> </div> </div> </div> </div> ); }
import React, { FormEvent, useEffect, useState } from 'react' import './FeedbackForm.sass' import NameSurname from '../Name_Surname/NameSurname' import Email from '../Email/Email' import Number from '../Number/Number' import DateOfBirth from '../DateOfBirth/DateOfBirth' import Message from '../Message/Message' import { FieldData, FormStatus } from '../../types' import FormContext from '../../context/form.context' interface Feedback{ [key: string]: string } interface ServerResponse { status: 'error' | 'success' message: string } const FeedbackForm = () => { const [serverResponse, setServerResponse] = useState<ServerResponse | undefined>() const [formData, setFormData] = useState<Map<string, FieldData>>(new Map()) const [formStatus, setFormStatus] = useState<FormStatus>(FormStatus.Init) const updateField = (data: FieldData) =>{ setFormData(prevState => { const newMap: Map<string, FieldData> = new Map(Array.from(prevState)) newMap.set(data.name, data) return newMap }) } const clearForm = () => { setFormData(new Map()) } useEffect(()=>{ const data = Array.from(formData) if (data.some(e=>e[1].error || !e[1].data)) { return setFormStatus(FormStatus.Error) } setFormStatus(FormStatus.Correct) }, [formData]) const sendForm = async (e: FormEvent<HTMLFormElement>) =>{ e.preventDefault() setFormStatus(FormStatus.Sending) const data = Array.from(formData) let feedbackData: Feedback = {} if(data.some(value=>value[1].error || !value[1].data)){ return } data.forEach(e=>{ feedbackData[e[0]] = e[1].data }) // let response = await fetch('https://my-json-server.typicode.com/anaistat/test_server/statuses', { // method: 'POST', // headers: { // 'Content-type': 'application/json; charset=UTF-8' // }, // body: JSON.stringify(feedbackData) // }) // Фэйковый сервер не работает с POST запросом, поэтому я написала GET для обработки статусов ответов let response = await fetch('https://my-json-server.typicode.com/anaistat/test_server/statuses', { method: 'GET' }) let result: ServerResponse[] = await response.json() setServerResponse(result[0]) } useEffect(()=>{ if(formStatus === FormStatus.Init || formStatus === FormStatus.Sending){ setServerResponse(undefined) } }, [formStatus]) const ServerMessage = () => { const styles = ['server-response'] if (serverResponse) { styles.push(serverResponse.status === 'error'? 'server-response--error' : 'server-response--success') } return <p className={styles.join(' ')}>{ serverResponse?.message }</p> } return ( <FormContext.Provider value={ { updateField, formStatus } }> <form className='feedback-form' onSubmit={sendForm}> <NameSurname name='name-surname'/> <Email name='email'/> <Number name='number'/> <DateOfBirth name='date-of-birth'/> <Message name='message'/> <button className='send-form' disabled={(formStatus !== FormStatus.Correct && formStatus !== FormStatus.Success)}>Send</button> <ServerMessage/> </form> </FormContext.Provider> ) } export default FeedbackForm
"use client"; export const colorSchemes = [ "default", "stone", "red", "pink", "orange", "green", "blue", "yellow", "violet", ] as const; type ColorSchemeType = (typeof colorSchemes)[number]; export default function useColorScheme( defaultValue: ColorSchemeType = "default", ) { if (typeof window !== "undefined") { const colorScheme = localStorage.getItem("color-scheme") ?? defaultValue; if ( colorScheme !== null && colorSchemes.includes(colorScheme as any) && document.documentElement?.getAttribute("data-color-scheme") !== colorScheme ) { document.documentElement?.setAttribute("data-color-scheme", colorScheme); } const setColorScheme = (value: ColorSchemeType) => { document.documentElement?.setAttribute("data-color-scheme", value); localStorage.setItem("color-scheme", value); }; return { colorScheme: colorScheme as ColorSchemeType, setColorScheme, }; } return { colorScheme: undefined, setColorScheme: undefined, }; }
// hashmaps3.rs // A list of scores (one per line) of a soccer match is given. Each line // is of the form : // <team_1_name>,<v[0].to_string()>,<team_1_goals>,<team_2_goals> // Example: England,France,4,2 (England scored 4 goals, France 2). // You have to build a scores table containing the name of the team, goals // the team scored, and goals the team conceded. One approach to build // the scores table is to use a Hashmap. The solution is partially // written to use a Hashmap, complete it to pass the test. // Make me pass the tests! // Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a hint. use std::collections::HashMap; // A structure to store team name and its goal details. struct Team { name: String, goals_scored: u8, goals_conceded: u8, } fn build_Team(name: String, goals_scored: u8, goals_conceded: u8) -> Team { Team { name, goals_scored, goals_conceded, } } fn build_scores_table(results: String) -> HashMap<String, Team> { // The name of the team is the key and its associated struct is the value. let mut scores: HashMap<String, Team> = HashMap::new(); for r in results.lines() { let v: Vec<&str> = r.split(',').collect(); let team_1_name = v[0].to_string(); // let v[2].parse().unwrap(): u8 = v[2].parse().unwrap(); // let v[0].to_string() = v[1].to_string(); // let v[3].parse().unwrap(): u8 = v[3].parse().unwrap(); // TODO: Populate the scores table with details extracted from the // current line. Keep in mind that goals scored by team_1 // will be number of goals conceded from team_2, and similarly // goals scored by team_2 will be the number of goals conceded by // team_1. let team1 = build_Team ( v[0].to_string(), v[2].parse().unwrap(), v[3].parse().unwrap(), ); let team11 = build_Team ( v[0].to_string(), 0, 0, ); let team111 = build_Team ( v[0].to_string(), v[2].parse().unwrap(), v[3].parse().unwrap(), ); let team2 = build_Team ( v[1].to_string(), v[3].parse().unwrap(), v[2].parse().unwrap(), ); let team22 = build_Team ( v[1].to_string(), 0, 0, ); let team222 = build_Team ( v[1].to_string(), v[3].parse().unwrap(), v[2].parse().unwrap(), ); let count1 = scores.entry(team1.name).or_insert(team11); (*count1).goals_scored += team111.goals_scored; (*count1).goals_conceded += team111.goals_conceded; let count2 = scores.entry(team2.name).or_insert(team22); (*count2).goals_scored += team222.goals_scored; (*count2).goals_conceded += team222.goals_conceded; } scores } #[cfg(test)] mod tests { use super::*; fn get_results() -> String { let results = "".to_string() + "England,France,4,2\n" + "France,Italy,3,1\n" + "Poland,Spain,2,0\n" + "Germany,England,2,1\n"; results } #[test] fn build_scores() { let scores = build_scores_table(get_results()); let mut keys: Vec<&String> = scores.keys().collect(); keys.sort(); assert_eq!( keys, vec!["England", "France", "Germany", "Italy", "Poland", "Spain"] ); } #[test] fn validate_team_score_1() { let scores = build_scores_table(get_results()); let team = scores.get("England").unwrap(); assert_eq!(team.goals_scored, 5); assert_eq!(team.goals_conceded, 4); } #[test] fn validate_team_score_2() { let scores = build_scores_table(get_results()); let team = scores.get("Spain").unwrap(); assert_eq!(team.goals_scored, 0); assert_eq!(team.goals_conceded, 2); } }
const images = ["src/images/banner1.png", "src/images/banner2.png", "src/images/banner3.png"]; document.addEventListener("DOMContentLoaded", function () { initSlider(); resultRequest(); nextLoadBooks(); toggleCategoryBooks(); }); function initSlider() { let sliderImages = document.querySelector(".container-slider"); let sliderDots = document.querySelector(".container-dots"); let intervalSlider = 2000; initImages(); initDots(); initAutoplay(); function initImages() { images.forEach((image, index) => { let imageDiv = `<div class='img n${index} ${index === 0 ? 'active' : ''}' style='background-image:url(${images[index]});' data-index='${index}'></div>`; sliderImages.innerHTML += imageDiv; }); } function initDots() { images.forEach((image, index) => { let dots = `<div class="dot n${index} ${index === 0 ? "active" : ""}" data-index="${index}"></div>`; sliderDots.innerHTML += dots; }); sliderDots.querySelectorAll(".dot").forEach(dot => { dot.addEventListener("click", function () { moveSlider(this.dataset.index); }) }); } function initAutoplay() { setInterval(() => { let curNumber = +sliderImages.querySelector('.active').dataset.index; let nextNumber = curNumber === images.length - 1 ? 0 : curNumber + 1; moveSlider(nextNumber); }, intervalSlider) } function moveSlider(num) { sliderImages.querySelector(".active").classList.remove("active"); sliderImages.querySelector(".n" + num).classList.add("active"); sliderDots.querySelector(".active").classList.remove("active"); sliderDots.querySelector(".n" + num).classList.add("active"); } } const showCaseBooks = document.querySelector(".case-books"); const btnLoadMore = document.querySelector(".btn_load-more"); const linkCategoryBooks = document.querySelectorAll(".category-books_item"); let querySubject = "subject:"; let startIndex = 0; let nextLoadCat; function nextLoadBooks() { // по клику отображаем следующие 6 книг btnLoadMore.addEventListener("click", () => { startIndex += 6; linkCategoryBooks.forEach(item => { if (item.classList.contains("active")) { nextLoadCat = item.innerText; }; }); querySubject = `${nextLoadCat}`; resultRequest(); }); }; function toggleCategoryBooks() { // переключаем категории в блоке категорий linkCategoryBooks.forEach(item => { let targetCategory = item; item.addEventListener("click", () => { removeActiveCategory(); targetCategory.classList.add("active"); if (item.classList.contains("active")) { nextLoadCat = item.innerText; }; showCaseBooks.innerHTML = ""; querySubject = `${nextLoadCat}`; numBooks = 0; resultRequest(); }); }); }; function removeActiveCategory() { // убираем класс active с категории linkCategoryBooks.forEach(item => { if (item.classList.contains("active")) { item.classList.remove("active"); }; }); }; function initRequest() { return fetch(`https://www.googleapis.com/books/v1/volumes?q=subject:${querySubject}&key=AIzaSyC8YBwRI2UO8lk5k4S31Z77MyGZr_Lu_bI&printType=books&startIndex=${startIndex}&maxResults=6&langRestrict='ru'`) .then((response) => { const result = response.json(); return result; }) .then((data) => { return data }) .catch(() => { console.log("error") }); }; async function resultRequest() { const data = await initRequest(); const dataItems = data.items; console.log(dataItems) drawBooks(dataItems); addToCart(); }; function drawBooks(dataItems) { dataItems.forEach(item => { let books = `<div class="book-position"> <img class="${item.volumeInfo?.imageLinks?.thumbnail ? "book-position_image" : "book-position_image-none"}" src="${item.volumeInfo?.imageLinks?.thumbnail}" alt="foto book"> <div class="book-position_info"> <h2 class="book-position_info-author">${item.volumeInfo?.authors}</h2> <h2 class="book-position_info-title">${item.volumeInfo?.title}</h2> <div class="${item.volumeInfo?.averageRating ? "rating-block" : "rating-block-none"}"> <div class="${item.volumeInfo?.averageRating ? "rating-block_stars" : ""}"> <div class="${item.volumeInfo?.averageRating === 1 ? "rating-block_stars__one" : ""}"> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__grey"></div> <div class="rating-block_stars__grey"></div> <div class="rating-block_stars__grey"></div> <div class="rating-block_stars__grey"></div> </div> <div class="${item.volumeInfo?.averageRating === 2 ? "rating-block_stars__two" : ""}"> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__grey"></div> <div class="rating-block_stars__grey"></div> <div class="rating-block_stars__grey"></div> </div> <div class="${item.volumeInfo?.averageRating === 3 ? "rating-block_stars__three" : ""}"> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__grey"></div> <div class="rating-block_stars__grey"></div> </div> <div class="${item.volumeInfo?.averageRating === 4 ? "rating-block_stars__four" : ""}"> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__grey"></div> </div> <div class="${item.volumeInfo?.averageRating === 5 ? "rating-block_stars__five" : ""}"> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__yellow"></div> <div class="rating-block_stars__yellow"></div> </div> </div> <h2 class="${item.volumeInfo?.ratingsCount ? "rating-block_count" : "rating-block_count-none"}">${item.volumeInfo?.ratingsCount} review</h2> </div> <h2 class="${item.volumeInfo?.description ? "book-position_info-description" : "book-position_info-description-none"}">${item.volumeInfo?.description}</h2> <h2 class="${item.saleInfo?.retailPrice?.amount ? "book-position_info-sale" : "book-position_info-sale-none"}">&#36; ${item.saleInfo?.retailPrice?.amount}</h2> <button class="btn_buy-now" type="button" data-btnbuy="${item.id}">buy now</button> </div> </div>`; showCaseBooks.innerHTML += books; }); }; let numBooks = 0; function addToCart() { let buttonsBuyNow = document.querySelectorAll(".btn_buy-now"); buttonsBuyNow.forEach((item) => { let buttonBuy = item; item.addEventListener("click", () => { let countBooks = document.querySelector(".nav_info_num"); buttonBuy.classList.toggle("btn_in_the_cart") if (buttonBuy.classList.contains("btn_in_the_cart")) { buttonBuy.innerText = "In the cart"; numBooks += 1; countBooks.innerText = numBooks; if (countBooks.innerText > 0) countBooks.classList.add("active"); } else { buttonBuy.innerText = "buy now"; numBooks -= 1; countBooks.innerText = numBooks; if (countBooks.innerText == 0) countBooks.classList.remove("active"); }; }); }); };
--- pubDatetime: 2021-12-08T10:00:00Z title: 80 thói quen nhỏ giúp thay đổi cuộc sống của bạn description: 80 thói quen nhỏ giúp thay đổi cuộc sống của bạn có thể không nghĩ rằng những thay đổi nhỏ sẽ ảnh hưởng lớn đến cuộc sống của bạn, nhưng bạn đã nhầm. Hãy thử những thói quen vi mô này ngay hôm nay. featured: true image: https://data.nhavantuonglai.com/image/illustrations/cover-nhavantuonglai-com-0649.jpg tags: - viet lach - nghien cuu khoa hoc - tam ly hoc - hanh vi hoc --- _80 thói quen nhỏ giúp thay đổi cuộc sống của bạn có thể không nghĩ rằng những thay đổi nhỏ sẽ ảnh hưởng lớn đến cuộc sống của bạn, nhưng bạn đã nhầm. Hãy thử những thói quen vi mô này ngay hôm nay._ Một điều nhỏ bé bạn có thể làm mỗi ngày để thay đổi cuộc sống của bạn tốt hơn là gì? Bạn có thể nghĩ rằng một thay đổi nhỏ như vậy sẽ không tạo ra nhiều sự khác biệt, nhưng không có gì có thể xa hơn sự thật. Khi nói đến việc tạo ra những thay đổi lâu dài trong cuộc sống của chúng ta, đó là những điều nhỏ nhặt có giá trị. Và đó là tất cả những gì về thói quen vi mô. Để giúp bạn, chúng tôi đã tổng hợp danh sách những thói quen vi mô tốt nhất mà bạn nên thực hành. Xây dựng chúng từ từ vào thói quen của bạn, và chẳng mấy chốc bạn sẽ nhận thấy những cải tiến nhỏ nhưng rõ rệt cho cuộc sống của bạn. Danh sách 80 thói quen nhỏ giúp thay đổi cuộc sống của bạn: ## Khám phá loại cuộc sống bạn muốn Xác định mục tiêu của bạn. Bạn muốn đạt được điều gì trong cuộc sống? Ưu tiên của bạn là gì? Lập kế hoạch. Một khi bạn biết những gì bạn muốn, hãy tìm ra cách để đạt được điều đó. Hãy hành động. Bắt đầu làm việc hướng tới mục tiêu của bạn ngay hôm nay. Theo dõi tiến trình của bạn. Theo dõi những gì bạn đang làm và nó diễn ra như thế nào bằng cách viết mọi thứ ra. Thực hiện một lời hứa với chính mình. Viết ra một lời thề trong đó bạn thề sẽ hành động hướng tới mục tiêu của mình và không bao giờ bỏ cuộc. ## Xóa bỏ những trở ngại tinh thần trên con đường của bạn Hãy tránh xa con đường của riêng bạn. Đừng để nỗi sợ hãi ngăn cản bạn bắt đầu và đạt được mục tiêu của mình. Hãy tự tin rằng bạn sẽ hoàn thành những gì bạn đặt ra. Nhận thức được những lời bào chữa mà bạn tự nói với mình như một vỏ bọc cho sự trì hoãn và lười biếng. Cứ làm đi! Đừng suy nghĩ quá nhiều về mọi thứ; Chỉ cần thực hiện bước đầu tiên và tiếp tục từ đó. Ngừng so sánh bản thân với người khác và bắt đầu sống cuộc sống của riêng bạn. ## Bắt đầu nói _có_ thường xuyên hơn Nói có thường xuyên hơn. Khi ai đó yêu cầu bạn làm điều gì đó, hãy nói có! Đảm nhận những thử thách mới. Hãy nhớ rằng, một thói quen mới dễ giữ hơn nhiều so với thói quen bạn đã thực hiện trong nhiều năm. Cho phép bản thân thành công ở một cái gì đó mới. Học hỏi từ sự từ chối và chỉ trích bằng cách sải bước và lắng nghe những gì người khác nói khi bạn đang bị thử thách hoặc thử thách theo một cách nào đó. Đừng nói không cho đến khi bạn nghĩ về những gì bạn đang nói không. ## Rèn luyện trí não của bạn Hãy suy nghĩ tích cực. Khẳng định là tuyệt vời để lặp lại những tuyên bố tích cực cho chính mình khi bạn cần một chút cổ vũ hoặc động lực. Sử dụng các kỹ thuật hình dung để tưởng tượng bạn đạt được mục tiêu của mình. Giải quyết vấn đề của bạn bằng cách suy nghĩ về chúng trước khi hành động hoặc nói. Thử thách bản thân để học một cái gì đó mới mỗi ngày. Dành thời gian cho bản thân để thư giãn và nạp lại năng lượng. ## Bắt đầu ăn uống tốt hơn Bắt đầu ăn uống tốt hơn bằng cách lên kế hoạch cho bữa ăn của bạn và suy nghĩ về việc bạn đang ăn bao nhiêu. Hạn chế đồ ăn nhẹ có hàm lượng calo cao như thanh kẹo có đường, bánh ngọt và khoai tây chiên một lần một tuần hoặc một lần mỗi ngày nếu bạn không thể cưỡng lại chúng. Làm cho nó dễ dàng cho chính mình bằng cách giữ thực phẩm lành mạnh xung quanh nhà và tại nơi làm việc. Uống nhiều nước hơn. Nó rất tốt cho làn da, mái tóc và sức khỏe tổng thể của bạn. Tránh ăn khuya. Cố gắng ăn chủ yếu là thực phẩm nguyên chất, chưa qua chế biến. Ăn sáng mỗi ngày để bắt đầu ngày mới của bạn đúng cách. Cắt giảm các loại thịt chế biến sẵn như thịt bò, thịt lợn và thịt gà. ## Di chuyển Hãy di chuyển chỉ một chút mỗi ngày bằng cách đi bộ hoặc đi xe đạp đến nơi làm việc. Bắt đầu với những mục tiêu nhỏ mà bạn dễ dàng đạt được, vì vậy bạn sẽ có thời gian dễ dàng hơn để đạt được những mục tiêu tiếp theo. Thiết lập cho mình thành công bằng cách tạo ra một lịch trình tập thể dục _vừa phải._ Duy trì động lực với các video tập luyện, danh sách phát nhạc hoặc podcast giúp bạn tràn đầy năng lượng và hào hứng để di chuyển nhiều hơn. Đừng đổ mồ hôi cho những thứ nhỏ nhặt; Chỉ cần làm hết sức mình và đừng lo lắng về điều đó nếu bạn không thể thực hiện mọi đại diện hoặc bộ của mọi bài tập một cách hoàn hảo. Hãy chắc chắn rằng bạn đang nâng tạ đó là thách thức cho bạn. Hãy nghỉ ngơi khi bạn cần, và đừng cảm thấy tội lỗi về điều đó. Ăn mừng những thành tựu của bạn trên đường đi, bất kể chúng có vẻ nhỏ như thế nào. ## Sắp xếp khoa học Dọn dẹp không gian của bạn để sắp xếp. Luôn cập nhật mọi thứ bằng cách dọn dẹp và dọn dẹp bản thân suốt cả ngày. Giữ một lịch trình cho chính bạn liệt kê những điều bạn cần hoặc muốn làm mỗi ngày trong tuần và đánh dấu chúng khi chúng hoàn thành. Tải công cụ lập kế hoạch, lịch hoặc ứng dụng để theo dõi các cuộc hẹn, thời hạn và sự kiện của bạn. Lập danh sách những thứ bạn cần mua tại cửa hàng tạp hóa, vì vậy bạn không phải mất thời gian suy nghĩ về nó sau này. Sắp xếp quần áo của bạn theo màu sắc, loại hoặc mùa để mặc quần áo vào buổi sáng dễ dàng hơn. Tạo một danh sách _việc cần làm_ vào cuối mỗi ngày liệt kê mọi thứ bạn đã hoàn thành. Loại bỏ sự lộn xộn để làm cho ngôi nhà của bạn thoải mái và tiện dụng hơn. Hình thành thói quen tốt bằng cách tuân theo một thói quen dễ dàng để bạn tuân thủ. Sắp xếp những suy nghĩ và ý tưởng của bạn bằng cách viết chúng ra một tạp chí hoặc sổ ghi chép. Hãy tạo thói quen làm một việc mỗi ngày để giúp bạn tiến gần hơn đến mục tiêu của mình. Loại bỏ phiền nhiễu khỏi môi trường của bạn để bạn có thể tập trung vào nhiệm vụ trong tầm tay. Sử dụng nhãn và thư mục để giữ cho giấy tờ của bạn được sắp xếp và sắp xếp. Dọn giường của bạn vào đầu mỗi ngày. Bạn sẽ ngạc nhiên về sự khác biệt mà nó tạo ra. Dành thời gian mỗi ngày để giải quyết các nhiệm vụ mà bạn đã trì hoãn. ## Bắt đầu tiết kiệm tiền Ngừng lãng phí tiền vào những thứ bạn không cần. Tạo ngân sách để bạn có thể thấy chính xác tiền của mình sẽ đi đâu mỗi tháng. Sử dụng tiền mặt thay vì thẻ tín dụng để hạn chế chi tiêu của bạn, đặc biệt nếu nó không nằm trong ngân sách. Hãy tự cho mình một khoản trợ cấp chi phí giải trí mỗi tuần hoặc mỗi tháng để không bội chi. Đặt mục tiêu tiết kiệm được một khoản tiền nhất định mỗi tháng hoặc mỗi năm. Bán những thứ bạn không sử dụng hoặc không cần nữa để kiếm thêm tiền. Đầu tư tiền của bạn theo cách sẽ giúp nó phát triển theo thời gian. So sánh giá trước khi bạn mua bất cứ thứ gì để đảm bảo bạn nhận được một thỏa thuận công bằng. ## Xây dựng các mối quan hệ và kỹ năng xã hội mạnh mẽ hơn Hãy cố gắng giao tiếp với những người bạn không biết rõ. Mỉm cười với mọi người, ngay cả khi bạn không biết họ. Đôi khi nói chuyện với người lạ; Nó có thể là một cách tuyệt vời để làm quen với những người mới và kết bạn mới. Đề nghị giúp đỡ ai đó nếu họ trông giống như đang gặp khó khăn. Dành thời gian để lắng nghe người khác và chú ý đến những gì họ đang nói. Cố gắng hiểu biết hơn và ít phán xét hơn. Dành thời gian với những người khiến bạn cảm thấy tốt về bản thân. Hãy từ bỏ những mối quan hệ độc hại hoặc cạn kiệt. Xin lỗi nếu bạn đã làm tổn thương cảm xúc của ai đó hoặc phạm sai lầm. Yêu cầu những gì bạn muốn và cần trong các mối quan hệ của bạn mà không bị đòi hỏi, có quyền hoặc gánh nặng. Hãy ý thức về những gì bạn nói với người khác để họ không cảm thấy bị bạn hạ thấp hoặc hạ thấp. ## Dành thời gian cho những người bạn yêu thương. Cố gắng lên kế hoạch cho ít nhất một chuyến đi chơi vui vẻ mỗi tháng với bạn bè hoặc gia đình của bạn. Giới thiệu bản thân với những người xung quanh thay vì chờ đợi họ đến với bạn. ## Chăm sóc công nghệ của bạn Sao lưu các tệp máy tính của bạn thường xuyên để bạn không bị mất thông tin quan trọng nếu có điều gì đó xảy ra với thiết bị của mình. Xóa các chương trình và ứng dụng bạn không sử dụng nữa để giải phóng dung lượng điện thoại hoặc máy tính. Luôn cập nhật hệ điều hành và phần mềm của bạn để bảo vệ bạn khỏi các mối đe dọa bảo mật. Tắt thông báo, để bạn không bị phân tâm bởi mọi buzz hoặc ding theo cách của bạn. Tìm hiểu lượng dữ liệu bạn đang sử dụng trên gói điện thoại di động của mình và giảm dữ liệu đó nếu cần thiết để tránh dư thừa. Hủy đăng ký nhận email làm lộn xộn hộp thư đến của bạn mà bạn không bao giờ đọc, đặc biệt là spam. Hãy cảnh giác với các trò gian lận trực tuyến và các nỗ lực lừa đảo, đồng thời tự bảo vệ mình bằng cách hoài nghi về những gì bạn thấy website. Thay đổi cuộc sống của bạn tốt hơn có vẻ khó khăn, nhưng điều quan trọng cần nhớ là bạn có thể tạo ra sự khác biệt bằng cách thực hiện các bước nhỏ, có thể quản lý được. Bằng cách thực hiện một số thói quen vi mô này vào thói quen hàng ngày của bạn, bạn sẽ trên đường đến một cuộc sống hạnh phúc và khỏe mạnh hơn. Vì vậy, hãy bắt đầu ngay hôm nay và xem những bước nhỏ này có thể tạo ra sự khác biệt như thế nào. Bạn đã tiến một bước gần hơn đến việc thay đổi cuộc sống của mình. <figure><img src="https://data.nhavantuonglai.com/image/illustrations/cover-nhavantuonglai-com-0614.jpg" alt="nhavantuonglai" title="nhavantuonglai" height=100% width=100%><figcaption><p></p></figcaption></figure>
# GraphQL | Node.js | MongoDB:用用户模型和 auth 设置一个基本服务器 > 原文:<https://medium.com/geekculture/graphql-node-js-mongodb-set-up-a-basic-server-with-user-model-and-auth-d05ed4d5a864?source=collection_archive---------13-----------------------> 在这个教程里(我有史以来第一次!有多紧张😮),我将向您展示如何设置一个基本的 **Node.js** 服务器,通过 **GraphQL** 公开存储在 **MongoDB** 数据库中的用户模型。我们还将在此基础上增加一些测试和验证工具! * [要求](#acbd) * [先于一切](#5de7) * [依赖关系](#78b9) * [用户模型](#40b2) * [认证服务](#7d91) * [graphql 模式](#8bc3) * [graphql 解析器](#a43f) * [测试](#262c) [与解析器](#d41e) [与服务](#4efd) * [app.js](#5094) * [游乐场](#0f69) ![](img/070f8977c44e2a654dae96e389711c1e.png) The beautiful tools we’ll be using in this tutorial # 要求 * 在你的机器上安装并运行 [MongoDB](https://docs.mongodb.com/manual/installation/) * 安装 [Node.js](https://nodejs.org/en/download/) (转到版本 14 或更高版本,因为我使用了版本 13 及以下版本不支持的可选链接) * 对 javascript 和 node 有一些了解 # 在所有人之前 你会在[这个公共回购](https://gitlab.com/steeveox/base-mongo-node-graphql-server)上找到完整的服务器。 如果您想在这个过程中自己构建它,那么创建一个新的文件夹,并根据您希望哪个包管理器来设置项目,键入`yarn init`或`npm init`。 说到包,让我们从安装本教程中需要的所有依赖项开始! (但在此之前,让我们快速看一下这个项目一旦启动并运行将由哪些文件夹和文件组成) ![](img/eb54c2a7326de5911478b8e727e415b5.png) # 属国 下面是所有项目依赖项的列表,以及我们将使用它们的目的(我使用`yarn`来管理包,但是没有什么可以阻止你使用这个好的 ol’`npm`): *开发依赖关系* * `jest`:将用于测试,很容易设置,允许并行测试并提供一个简洁的 API * 将用于在本地运行我们的服务器,一旦启动,它将监视文件的变化,并在保存项目中的任何修改后重新启动 * `@shelf/jest-mongodb`:将提供使用 MongoDB 运行测试所需的所有配置 `yarn add jest jest-cli nodemon @shelf/jest-mongodb --dev` *依赖关系* * `bcrypt`:将用于散列和加盐我们的用户密码。它可靠、易用,自 1999 年以来,世界各地的开发者都在使用它,没有任何抱怨 * `dotenv`:将用于从`.env`文件**中加载环境变量到`process.env`中,你永远不会提交**,这样你就可以将你的秘密从代码中分离出来 * `jsonwebtoken`:将用于生成和解析我们的用户 jwt * `mongoose`:将用于连接和交互我们的 MongoDB 数据库 * 所有的肉。一个易于使用的 GraphQL 服务器,需要最少的配置,基于`apollo-server`,它本身是生成自文档化 GraphQL APIs 的最佳工具 `yarn add bcrypt dotenv jsonwebtoken mongoose graphql-yoga` # 用户模型 如果您还不知道(如果您愿意使用它,我希望您知道),MongoDB 是一个非关系的、面向文档的数据库。它存储文档,比通常的关系数据库灵活得多。如果你想进一步了解这个特殊的话题,MongoDB 团队写了一篇关于它的文章:[https://www.mongodb.com/non-relational-database](https://www.mongodb.com/non-relational-database) 在`models/user.js`中,我们将定义我们的用户模型。模型负责从数据库中创建和读取文档。 `models/user.js` 这里没什么特别的。我们需要`mongoose`,为我们的数据库使用创建一个新的模式,并为我们的每个用户文档的属性设置参数。然后我们以名称`User`将其导出。 # 授权服务 auth 服务将用于管理与身份验证相关的一切,从散列密码到解析 jwt。 `services/auth.service.js` `services/auth.service.js` 让我们一个方法一个方法地分解它: * `hashPassword`:用于哈希密码。与可以逆转的加密相反,从散列的字符串中获取原始字符串几乎是不可能的。`salt`是一个随机字符串,在哈希过程中添加到密码中以增加安全性。`saltRounds`使算法更慢,使其更安全,因为它也增加了攻击者等待破解散列密码的时间。 * `matchPasswords`:使用`bcrypt`比较法,将用户提供的密码与数据库中的密码进行比较。 * `generateJwt`:用于生成一个 json web 令牌,以便在用户登录后对其进行身份验证。我们向它传递可能对应用程序使用有用的用户数据、用于签署您的令牌的秘密字符串(该字符串必须是您的应用程序独有的)以及它将处于活动状态的延迟时间。 *关于 app secret 的一个注意事项:如果你看一下公共存储库,你会发现一个* `*.env.example*` *文件,而不是本文开头显示的项目树结构中的* `*.env*` *文件。如前所述,* `*.dotenv*` *库允许我们检索存储在该文件中的环境变量。这不是故意的。秘密越随机越复杂越好。我通过使用 Node.js 中包含的* `*crypto*` *lib 来生成 mine,为此,我在一个节点控制台中运行以下命令(只需在终端中键入 Node 来打开它):* `require('crypto').randomBytes(64).toString('hex')` * `getJwtPayload`:用于从 jwt 中检索用户数据。 * `getUserId`:用于从令牌中检索用户 Id,或者从传入请求中检索`authorization`头。 # GRAPHQL 模式 GraphQL 模式描述了连接到它的客户机可用的类型、查询和变化。它是使用[模式定义语言](https://www.prisma.io/blog/graphql-sdl-schema-definition-language-6755bcb9ce51)构建的。它用于文档和数据验证目的。与 REST APIs 相反,GraphQL API 公开了一个端点来操作数据。突变和查询是你与它交互的两种方式。 `graphql/schema/user.js` `graphql/schema/user.js` `Query` : GraphQL 对象,包含所有用于获取数据的方法。这里我们将实现两个简单的方法来检查用户的数据。它只是为了指导的目的而实现的,因为这些信息已经在 jwt 中了。 `Mutation` : GraphQL 对象,包含用于写操作(post、put、delete)的所有方法。在这里,用户将能够使用`signup`创建一个用户,并使用`login`进行认证。如果你不熟悉打字,让我们快速分解一下`login`原型: -所有参数(电子邮件、用户名和密码)都是字符串 -无论如何都只需要密码,因此`!` -电子邮件和用户名是不需要的,因为用户将被允许向我们提供任何一个,解析器将负责确保其中一个或另一个确实被提供了 `User`:描述用户在我们公开的 API 中的样子。我们在这里输入密码,这样当你在**游乐场**玩的时候,你就可以看到密码被散列后的样子了(稍后会有更多的介绍)。但是,在刺激的情况下,你不应该暴露它。您应该理解的是,MongoDB 中用于文档存储的`User`模型和 GraphQL `User`类型不必相同。您可以添加未存储在数据库中的动态属性,这些属性将在解析器中计算。 是的,解决者。我第二次谈论他们,但是他们是什么? # GRAPHQL 解析器 GraphQL 解析器是用于实现查询或变异背后的逻辑的实际函数。每个查询和每个变异都应该有一个。 `graphql/resolvers/users/users.js` `graphql/resolvers/users/users.js` `Query`: * getUsers:不需要任何认证。在这里,您可以看到一个简单的查询是如何工作的,这样您就可以检索您将使用`signup`变异创建的用户的 id。 * getUser:这个更有趣。它需要三个参数: _:用于在解析器之间将数据从父对象传递到子对象的`root`对象。我用得不多,但如果你想了解更多,paypal 团队写了一篇关于解析器的好文章:[https://medium . com/paypal-tech/graphql-resolvers-best-practices-CD 36 fdbcef 55](/paypal-tech/graphql-resolvers-best-practices-cd36fdbcef55) -{ id }:客户端传递给 graph QL 的 args。 -context:我们在 GraphQL 服务器实例化期间覆盖的一个对象,将从用户的 jwt 中检索到的 userId 添加到该对象中。 如果没有`userId`出现在上下文中,这意味着用户没有通过身份验证,所以我们抛出。如果用户的 id 与请求的 id 不同,我们会抛出,因为您应该只能请求自己的数据。这就是我们如何保护需要认证的解析器。 `Mutation`: * 注册:用于创建新用户。它使用我们之前在`auth.service`中实现的散列方法。 * 登录:如果没有提供`username`或`email`,则抛出。成功登录后,生成一个返回给用户的 jwt。 # 测试 在这个小项目中有两种测试方法。 ## 使用解析器 所有数据库操作都发生在解析器中。在一个完美的世界中,它将被分离在另一个层中,并且可能存在于[库](https://deviq.com/design-patterns/repository-pattern)中,但是对于这样大小的应用程序,解析器处理 db 逻辑是完全可以接受的。我们与数据库交互的事实意味着我们的测试需要一些额外的设置,因此有了`graphql/resolvers/`中的`test-setup.js`文件。 `graphql/resolvers/test-setup.js` 对于每个测试套件(也就是说,对于每个测试文件),我们将连接到不同的数据库。异步运行每个测试文件,它允许我们确保不同的测试套件不会共享同一个数据库。 我们导出了带有一个`databaseName`参数的`setupDB`函数,这个参数显然是测试套件的 db 的名称。然后我们使用一些`jest`钩子来: * 在运行任何东西之前,连接到测试套件数据库 * 在每次测试后清理每个集合(MongoDB 相当于表),所以我们从每个新集合清理一个 DB 开始 * 完成所有测试后,删除所有集合并关闭数据库连接 我们现在可以在每个测试套件中使用这个配置。让我们看看它在`graphql/resolvers/users/users.spec.js`里是什么样子的 `graphql/resolvers/users/users.spec.js` 你会注意到开头使用了`setupDB`。我不会描述每个测试做了什么,因为它是不言自明的。正如您所看到的,`Jest`语法非常直观: `describe`描述了我们将要测试的方法 `it`定义一个新的测试,将测试名称作为第一个参数(它应该尽可能精确地描述您实际测试的内容),将包含您的测试逻辑的回调作为第二个参数 `expect`是实际测试,断言无论如何必须为真。当然,您可以在一个测试中做出多个断言。 ## 带服务 基本上,我们的服务处理在代码的不同部分有用的逻辑,并且是幂等的:这意味着给定相同的输入,我们的服务方法之一的输出将总是相同的。 `services/auth.service.spec.js` `services/auth.service.spec.js` 我用的`genericToken` const 是一个 jwt 我用以下秘密签名的:' 864 c0a 4 f 6640 Fe 0307 E4 cddd 178 a 33 B2 ba 2 e 00487 AC 0 b 636 cc 3c 5 ab 360 e 0481355 e 9563 a 15 ceea 2 ff 35 c 9948 FD 2c 094 f 067 b 03 e 77 C4 a40 a 75 f 29 a9 CB 220 de '。如果您想让它开箱即用,只需在. env.example 文件中填充`TOKEN_SECRET`变量,您应该将该文件重命名为`.env`。或者,您可以用自己的令牌生成自己的 jwt。也就是说,**您的项目中应该有一个** `**.env**` **文件,并带有一个** `**TOKEN_SECRET**`文件,这样测试套件才能工作。 要运行所有的测试套件,只需在项目的根目录下键入以下命令:`npx jest` # APP。射流研究… 现在,我们的小系统的每个部分都已经就绪,我们只需要实例化我们的 GraphQL 服务器,这样我们就可以向世界公开我们的 API 了! `app.js` app.js 我们需要来自 graphql-yoga 的`GraphQLServer`和用于连接数据库的`Mongoose`。`auth-service`将允许我们将`authorization`头中的`userId`添加到`context`对象中,正如我们之前看到的,所有解析器都可以访问该对象(`graphql-yoga`从`apollo-server`继承了`req`对象,而`apollo-server`又从`express`继承了它)。 `typeDefs`是我们将向客户公开的模式,而`resolvers`是我们的解析器。这两者都是创建 GraphQL 服务器所必需的。为了便于导入,可以在`graphql/resolvers` & `graphql/schema`中找到一个`index.js`文件。它们的内容非常简单: `graphql/resolvers/index.js` ``` const User = require('./users/users') module.exports = [ User ] ``` `graphql/schema/index.js` ``` const User = require('./user') module.exports = [ User ] ``` 然后,我们在上下文中使用我们的 auth 服务添加我们的`userId`,我们尝试连接到数据库,如果我们这样做了,我们实例化我们的小服务器! 只需将以下内容添加到`package.json`中,您就可以开始了! ``` "scripts": { "start": "nodemon app.js"}, ``` # 操场 现在您已经设置好了,您所要做的就是在终端中的项目根目录下键入`yarn start`。你可以在以下网址找到[阿波罗游乐场](https://www.apollographql.com/docs/apollo-server/testing/graphql-playground/):`localhost:3000/graphql` 它应该是这样的: ![](img/5f3b1114229eb9d1c6f07e7ae38a407a.png) 在右边,您会发现所有自动生成的文档都在`DOCS`和`SCHEMA`选项卡后面。 在底部,单击`HTTP HEADERS`将允许您设置`authorization`标题,通过键入以下命令来尝试和验证使用`getUser`查询: ``` { "authorization": "Bearer YOUR_JWT" } ``` 你是否应该用…你自己的 jwt 来代替`YOUR_JWT`,这是通过使用登录变异得到的。 在游戏区的左边,您可以测试您的突变和查询,然后单击中间的大 PLAY 按钮,看看您的解析器在右边返回了什么。 要测试一个查询/方法,开始输入`q`或`m`,你会看到 playground 为你提供了一个甜蜜的自动完成功能。在选择了是否要获取数据或写入数据库之后,打开括号,键入`ctrl` + `space`以查看所有可用的方法。 例如,创建一个带有`signup`突变的新用户如下所示: ``` mutation { signup(email: "[a](mailto:juju@gmail.com)nemail@gmail.com", username: "some cool name", password: "plop") } ``` 要获取数据,还必须指定要从解析器中检索什么数据。假设您创建了 5 个用户,并希望检索他们的 id 和电子邮件,它看起来像这样: ``` query { getUsers{ email id } } ``` `getUsers`没有任何参数,所以在调用它之后,你只需要打开括号,描述你感兴趣的属性。 我想就这样了,伙计们!希望这篇教程对你有所帮助。如有问题或建议,请随时评论:)
package br.com.cambuy.uai.characters.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import br.com.cambuy.characters.domain.useCase.GetCharactersUseCase import br.com.cambuy.uai.core.navigation.UaiWarsScreen import br.com.cambuy.uai.design_system.StateOfUi import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class CharactersViewModel @Inject constructor( private val getCharactersUseCase: GetCharactersUseCase ) : ViewModel() { private val _state = MutableStateFlow(CharactersState()) val state = _state.asStateFlow() private val _uiEvent = Channel<CharactersUiEvent>() val uiEvent = _uiEvent.receiveAsFlow() fun onEvent(event: CharactersEvent) { viewModelScope.launch { when (event) { is CharactersEvent.NavigateToCharactersDetail -> navigateTo( UaiWarsScreen.CharactersDetailScreen( event.id ) ) is CharactersEvent.FetchListOfCharacters -> fetchListOfCharacters(event.textSearch) } } } private fun navigateTo(route: UaiWarsScreen) { viewModelScope.launch { _uiEvent.send(CharactersUiEvent.NavigateTo(route)) } } private fun fetchListOfCharacters(textSearch: String) { viewModelScope.launch(Dispatchers.IO) { updateStateOfUi(StateOfUi.Loading) runCatching { val data = getCharactersUseCase(textSearch) updateStateOfUi(StateOfUi.View) _state.update { it.copy(listOfCharacters = data) } }.getOrElse { updateStateOfUi(StateOfUi.Error { fetchListOfCharacters(textSearch) }) } } } private fun updateStateOfUi(stateOfUi: StateOfUi) { _state.update { it.copy(stateOfUi = stateOfUi) } } }
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Task> */ class TaskFactory extends Factory { /** * Define the model's default state. * * @return array<string, mixed> */ public function definition(): array { return [ 'name' => fake()->name(), 'description' => fake()->realText(), 'due_date' => fake()->dateTimeBetween('now', '+1 year'), 'status' => fake()->randomElement(['pending', 'in_progress', 'completed']), 'image_path' => fake()->imageUrl(), 'assigned_to_user_id' => 1, 'priority' => fake()->randomElement(['low', 'medium', 'high']), 'created_by' => 1, 'updated_by' => 1, 'created_at' => time(), 'updated_at' => time(), ]; } }
<?php use App\Models\User; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('memberships', function (Blueprint $table) { $table->id(); $table->foreignIdFor(User::class) ->constrained() ->cascadeOnDelete() ->cascadeOnUpdate(); $table->enum('plan_type', ['free', 'premium'])->default('free'); // free, premium $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('memberships'); } };
pragma solidity ^0.6.12; import "Bitacora.sol"; import "Resource.sol"; // SPDX-License-Identifier: jclopezpimentel contract User{ //privates address user; //user address address father; //father address string typeu; mapping (address=> bool) exists; // existing resources mapping (Resource => Resource) resources; Bitacora bitacora; // user's bitacora //public methods constructor(address nuser_, string memory typeuser) public{ user = nuser_; //assigning who is the new user typeu = typeuser; father = msg.sender; //assigning who is the father /* userStruct memory nuserS = userStruct(nuser_,"Admor",nuser_); users[nuser_] = nuserS; */ string memory log = "Creating user"; bitacora = new Bitacora(log); } function getOwner() public view returns(address){ return user; } function addResource(string memory resourceDescription) public{ require(msg.sender == user); //only the user can execute this function Resource resource = new Resource(resourceDescription); //address addResource = resource.getAddress(resource); resources[resource] = resource; string memory log = "Creating user"; bitacora.addLog(log); } function getTypeUser() public view returns(string memory){ return typeu; } function getBitacora() public view returns(Bitacora){ require(msg.sender == user); //only the owner can execute this function return (bitacora); } }
import random import numpy as np import pytest from flaky import flaky from dowhy.gcm.independence_test import approx_kernel_based, kernel_based @flaky(max_runs=5) def test_given_categorical_conditionally_independent_data_when_perform_kernel_based_test_then_not_reject(): x, y, z = _generate_categorical_data() assert kernel_based(x, y, z) > 0.05 @flaky(max_runs=5) def test_given_categorical_conditionally_dependent_data_when_perform_kernel_based_test_then_reject(): x, y, z = _generate_categorical_data() assert kernel_based(x, z, y) < 0.05 @flaky(max_runs=2) def test_given_random_seed_when_perform_conditional_kernel_based_test_then_return_deterministic_result( _preserve_random_generator_state, ): z = np.random.randn(1000, 1) x = np.exp(z + np.random.rand(1000, 1)) y = np.exp(z + np.random.rand(1000, 1)) assert kernel_based( x, z, y, max_num_samples_run=5, bootstrap_num_runs=2, p_value_adjust_func=np.mean, use_bootstrap=True ) != kernel_based( x, z, y, max_num_samples_run=5, bootstrap_num_runs=2, p_value_adjust_func=np.mean, use_bootstrap=True ) np.random.seed(0) result_1 = kernel_based( x, z, y, max_num_samples_run=5, bootstrap_num_runs=2, p_value_adjust_func=np.mean, use_bootstrap=True ) np.random.seed(0) result_2 = kernel_based( x, z, y, max_num_samples_run=5, bootstrap_num_runs=2, p_value_adjust_func=np.mean, use_bootstrap=True ) assert result_1 == result_2 @flaky(max_runs=5) def test_given_categorical_independent_data_when_perform_kernel_based_test_then_not_reject(): x = np.random.normal(0, 1, 1000) y = (np.random.choice(2, 1000) == 1).astype(str) assert kernel_based(x, y) > 0.05 @flaky(max_runs=5) def test_given_categorical_dependent_data_when_perform_kernel_based_test_then_reject(): x = np.random.normal(0, 1, 1000) y = [] for v in x: if v > 0: y.append(0) else: y.append(1) y = np.array(y).astype(str) assert kernel_based(x, y) < 0.05 @flaky(max_runs=2) def test_given_random_seed_when_perform_pairwise_kernel_based_test_then_return_deterministic_result( _preserve_random_generator_state, ): x = np.random.randn(1000, 1) y = x + np.random.randn(1000, 1) assert kernel_based( x, y, max_num_samples_run=10, bootstrap_num_runs=2, p_value_adjust_func=np.mean, use_bootstrap=True ) != kernel_based( x, y, max_num_samples_run=10, bootstrap_num_runs=2, p_value_adjust_func=np.mean, use_bootstrap=True ) np.random.seed(0) result_1 = kernel_based( x, y, max_num_samples_run=10, bootstrap_num_runs=2, p_value_adjust_func=np.mean, use_bootstrap=True ) np.random.seed(0) result_2 = kernel_based( x, y, max_num_samples_run=10, bootstrap_num_runs=2, p_value_adjust_func=np.mean, use_bootstrap=True ) assert result_1 == result_2 def test_given_constant_inputs_when_perform_kernel_based_test_then_returns_non_nan_value(): assert kernel_based(np.random.normal(0, 1, (1000, 2)), np.array([5] * 1000)) != np.nan @flaky(max_runs=5) def test_given_continuous_conditionally_independent_data_when_perform_approx_kernel_based_test_then_not_reject(): z = np.random.randn(5000, 1) x = np.exp(z + np.random.rand(5000, 1)) y = np.exp(z + np.random.rand(5000, 1)) assert ( approx_kernel_based(x, y, z, num_random_features_X=10, num_random_features_Y=10, num_random_features_Z=10) > 0.05 ) @flaky(max_runs=5) def test_given_continuous_conditionally_dependent_data_when_perform_approx_kernel_based_test_then_reject(): z = np.random.randn(1000, 1) w = np.random.randn(1000, 1) x = np.exp(z + np.random.rand(1000, 1)) y = np.exp(z + np.random.rand(1000, 1)) assert 0.05 > approx_kernel_based(x, y, w) @flaky(max_runs=5) def test_given_categorical_conditionally_independent_data_when_perform_approx_kernel_based_test_then_not_reject(): x, y, z = _generate_categorical_data() assert approx_kernel_based(x, y, z) > 0.05 @flaky(max_runs=5) def test_given_categorical_conditionally_dependent_data_when_perform_approx_kernel_based_test_then_reject(): x, y, z = _generate_categorical_data() assert approx_kernel_based(x, z, y) < 0.05 @flaky(max_runs=2) def test_given_random_seed_when_perform_conditional_approx_kernel_based_test_then_return_deterministic_result( _preserve_random_generator_state, ): z = np.random.randn(1000, 1) x = np.exp(z + np.random.rand(1000, 1)) y = np.exp(z + np.random.rand(1000, 1)) assert approx_kernel_based( x, z, y, num_random_features_X=1, num_random_features_Y=1, num_random_features_Z=1, bootstrap_num_samples=5, bootstrap_num_runs=10, p_value_adjust_func=np.mean, use_bootstrap=True, ) != approx_kernel_based( x, z, y, num_random_features_X=1, num_random_features_Y=1, num_random_features_Z=1, bootstrap_num_samples=5, bootstrap_num_runs=10, p_value_adjust_func=np.mean, use_bootstrap=True, ) np.random.seed(0) result_1 = approx_kernel_based( x, z, y, num_random_features_X=1, num_random_features_Y=1, num_random_features_Z=1, bootstrap_num_samples=5, bootstrap_num_runs=10, p_value_adjust_func=np.mean, use_bootstrap=True, ) np.random.seed(0) result_2 = approx_kernel_based( x, z, y, num_random_features_X=1, num_random_features_Y=1, num_random_features_Z=1, bootstrap_num_samples=5, bootstrap_num_runs=10, p_value_adjust_func=np.mean, use_bootstrap=True, ) assert result_1 == result_2 @flaky(max_runs=5) def test_given_continuous_independent_data_when_perform_approx_kernel_based_test_then_not_reject(): x = np.random.randn(1000, 1) y = np.exp(np.random.rand(1000, 1)) assert approx_kernel_based(x, y) > 0.05 @flaky(max_runs=5) def test_given_continuous_dependent_data_when_perform_approx_kernel_based_test_then_reject(): z = np.random.randn(1000, 1) x = np.exp(z + np.random.rand(1000, 1)) y = np.exp(z + np.random.rand(1000, 1)) assert approx_kernel_based(x, y) < 0.05 @flaky(max_runs=5) def test_given_categorical_independent_data_when_perform_approx_kernel_based_test_then_not_reject(): x = np.random.normal(0, 1, 1000) y = np.random.choice(2, 1000).astype(str) y[y == "0"] = "Class 1" y[y == "1"] = "Class 2" assert approx_kernel_based(x, y) > 0.05 @flaky(max_runs=5) def test_given_categorical_dependent_data_when_perform_approx_kernel_based_test_then_reject(): x = np.random.normal(0, 1, 1000) y = [] for v in x: if v > 0: y.append("Class 1") else: y.append("Class 2") y = np.array(y).astype(str) assert approx_kernel_based(x, y) < 0.05 @flaky(max_runs=3) def test_given_random_seed_when_perform_pairwise_approx_kernel_based_test_then_return_deterministic_result( _preserve_random_generator_state, ): w = np.random.randn(100, 1) x = w + np.random.rand(100, 1) assert approx_kernel_based( x, w, num_random_features_X=1, num_random_features_Y=1, bootstrap_num_samples=5, bootstrap_num_runs=10, p_value_adjust_func=np.mean, use_bootstrap=True, ) != approx_kernel_based( x, w, num_random_features_X=1, num_random_features_Y=1, bootstrap_num_samples=5, bootstrap_num_runs=10, p_value_adjust_func=np.mean, use_bootstrap=True, ) np.random.seed(0) result_1 = approx_kernel_based( x, w, num_random_features_X=1, num_random_features_Y=1, bootstrap_num_samples=5, bootstrap_num_runs=10, p_value_adjust_func=np.mean, use_bootstrap=True, ) np.random.seed(0) result_2 = approx_kernel_based( x, w, num_random_features_X=1, num_random_features_Y=1, bootstrap_num_samples=5, bootstrap_num_runs=10, p_value_adjust_func=np.mean, use_bootstrap=True, ) assert result_1 == result_2 def test_given_constant_data_when_perform_kernel_based_test_then_returns_expected_result(): assert kernel_based(np.zeros(100), np.random.normal(0, 1, 100)) == 1.0 assert kernel_based(np.zeros(100), np.random.normal(0, 1, 100), np.random.normal(0, 1, 100)) == 1.0 assert not np.isnan(kernel_based(np.random.normal(0, 1, 100), np.random.normal(0, 1, 100), np.zeros(100))) def test_given_constant_data_when_perform_approx_kernel_based_test_then_returns_expected_result(): assert approx_kernel_based(np.zeros(100), np.random.normal(0, 1, 100)) == 1.0 assert approx_kernel_based(np.zeros(100), np.random.normal(0, 1, 100), np.random.normal(0, 1, 100)) == 1.0 assert not np.isnan(approx_kernel_based(np.random.normal(0, 1, 100), np.random.normal(0, 1, 100), np.zeros(100))) def test_given_almost_constant_data_when_perform_kernel_based_test_then_does_not_return_nans(): almost_const = np.concatenate((np.ones(1), np.zeros(99)), axis=0) assert not np.isnan( kernel_based(almost_const, np.random.normal(0, 1, 100), bootstrap_num_runs=2, max_num_samples_run=10) ) assert not np.isnan( kernel_based( almost_const, np.random.normal(0, 1, 100), np.random.normal(0, 1, 100), bootstrap_num_runs=2, max_num_samples_run=10, ) ) assert not np.isnan( kernel_based( np.random.normal(0, 1, 100), np.random.normal(0, 1, 100), almost_const, bootstrap_num_runs=2, max_num_samples_run=10, ) ) def test_given_data_with_boolean_and_object_type_when_kernel_based_then_does_not_raise_error(): kernel_based( np.array([1, 2, 3, 4, 5, 6], dtype=object), np.array([[1, False], [2, True], [3, False], [4, False], [5, True], [6, True]], dtype=object), np.array([False, True, False, False, True, True], dtype=object), ) def _generate_categorical_data(num_samples=1000): x = np.random.normal(0, 1, num_samples) z = [] for v in x: if v > 0: z.append(0) else: z.append(1) y = z + np.random.randn(len(z)) z = np.array(z).astype(str) z[z == "0"] = "Class 1" z[z == "1"] = "Class 2" return x, y, z @pytest.fixture def _preserve_random_generator_state(): numpy_state = np.random.get_state() random_state = random.getstate() yield np.random.set_state(numpy_state) random.setstate(random_state)
using System.Linq.Expressions; using Ardalis.Specification; using Microsoft.EntityFrameworkCore; using MobyLabWebProgramming.Core.DataTransferObjects; using MobyLabWebProgramming.Core.Entities; namespace MobyLabWebProgramming.Core.Specifications; /// <summary> /// This is a specification to filter the user entities and map it to and UserDTO object via the constructors. /// Note how the constructors call the base class's constructors. Also, this is a sealed class, meaning it cannot be further derived. /// </summary> public sealed class SCartProjectionSpec : BaseSpec<SCartProjectionSpec, ShopCart, CartDTO> { /// <summary> /// This is the projection/mapping expression to be used by the base class to get UserDTO object from the database. /// </summary> protected override Expression<Func<ShopCart, CartDTO>> Spec => e => new() { Id = e.Id, Price = e.Price, Count = e.Count, UserId = e.UserId }; public SCartProjectionSpec(bool orderByCreatedAt = true) : base(orderByCreatedAt) { } public SCartProjectionSpec(Guid id) : base(id) { } public SCartProjectionSpec(Guid id,Guid UserId) { if (id == UserId) { } Query.Where(e => e.UserId == UserId); } public SCartProjectionSpec(Guid UserId,bool state) { if (state == true) { Query.Where(e => e.UserId == UserId && e.InUse == state); } else { Query.Where(e => e.UserId == UserId); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using Microsoft.AspNetCore.Http; using Nop.Core; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Payments; using Nop.Core.Http.Extensions; using Nop.Core.Infrastructure; using Nop.Services.Catalog; using Nop.Services.Customers; using Nop.Services.Orders; namespace Nop.Services.Payments { /// <summary> /// Payment service /// </summary> public partial class PaymentService : IPaymentService { #region Fields private readonly ICustomerService _customerService; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IPaymentPluginManager _paymentPluginManager; private readonly PaymentSettings _paymentSettings; private readonly ShoppingCartSettings _shoppingCartSettings; #endregion #region Ctor public PaymentService(ICustomerService customerService, IHttpContextAccessor httpContextAccessor, IPaymentPluginManager paymentPluginManager, PaymentSettings paymentSettings, ShoppingCartSettings shoppingCartSettings) { _customerService = customerService; _httpContextAccessor = httpContextAccessor; _paymentPluginManager = paymentPluginManager; _paymentSettings = paymentSettings; _shoppingCartSettings = shoppingCartSettings; } #endregion #region Methods /// <summary> /// Process a payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the process payment result /// </returns> public virtual async Task<ProcessPaymentResult> ProcessPaymentAsync(ProcessPaymentRequest processPaymentRequest) { if (processPaymentRequest.OrderTotal == decimal.Zero) { var result = new ProcessPaymentResult { NewPaymentStatus = PaymentStatus.Paid }; return result; } //We should strip out any white space or dash in the CC number entered. if (!string.IsNullOrWhiteSpace(processPaymentRequest.CreditCardNumber)) { processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace(" ", string.Empty); processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace("-", string.Empty); } var customer = await _customerService.GetCustomerByIdAsync(processPaymentRequest.CustomerId); var paymentMethod = await _paymentPluginManager .LoadPluginBySystemNameAsync(processPaymentRequest.PaymentMethodSystemName, customer, processPaymentRequest.StoreId) ?? throw new NopException("Payment method couldn't be loaded"); return await paymentMethod.ProcessPaymentAsync(processPaymentRequest); } /// <summary> /// Post process payment (used by payment gateways that require redirecting to a third-party URL) /// </summary> /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param> /// <returns>A task that represents the asynchronous operation</returns> public virtual async Task PostProcessPaymentAsync(PostProcessPaymentRequest postProcessPaymentRequest) { //already paid or order.OrderTotal == decimal.Zero if (postProcessPaymentRequest.Order.PaymentStatus == PaymentStatus.Paid) return; var customer = await _customerService.GetCustomerByIdAsync(postProcessPaymentRequest.Order.CustomerId); var paymentMethod = await _paymentPluginManager .LoadPluginBySystemNameAsync(postProcessPaymentRequest.Order.PaymentMethodSystemName, customer, postProcessPaymentRequest.Order.StoreId) ?? throw new NopException("Payment method couldn't be loaded"); await paymentMethod.PostProcessPaymentAsync(postProcessPaymentRequest); } /// <summary> /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods) /// </summary> /// <param name="order">Order</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the result /// </returns> public virtual async Task<bool> CanRePostProcessPaymentAsync(Order order) { if (order == null) throw new ArgumentNullException(nameof(order)); if (!_paymentSettings.AllowRePostingPayments) return false; var customer = await _customerService.GetCustomerByIdAsync(order.CustomerId); var paymentMethod = await _paymentPluginManager.LoadPluginBySystemNameAsync(order.PaymentMethodSystemName, customer, order.StoreId); if (paymentMethod == null) return false; //Payment method couldn't be loaded (for example, was uninstalled) if (paymentMethod.PaymentMethodType != PaymentMethodType.Redirection) return false; //this option is available only for redirection payment methods if (order.Deleted) return false; //do not allow for deleted orders if (order.OrderStatus == OrderStatus.Cancelled) return false; //do not allow for cancelled orders if (order.PaymentStatus != PaymentStatus.Pending) return false; //payment status should be Pending return await paymentMethod.CanRePostProcessPaymentAsync(order); } /// <summary> /// Gets an additional handling fee of a payment method /// </summary> /// <param name="cart">Shopping cart</param> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the additional handling fee /// </returns> public virtual async Task<decimal> GetAdditionalHandlingFeeAsync(IList<ShoppingCartItem> cart, string paymentMethodSystemName) { if (string.IsNullOrEmpty(paymentMethodSystemName)) return decimal.Zero; var customer = await _customerService.GetCustomerByIdAsync(cart.FirstOrDefault()?.CustomerId ?? 0); var paymentMethod = await _paymentPluginManager.LoadPluginBySystemNameAsync(paymentMethodSystemName, customer, cart.FirstOrDefault()?.StoreId ?? 0); if (paymentMethod == null) return decimal.Zero; var result = await paymentMethod.GetAdditionalHandlingFeeAsync(cart); if (result < decimal.Zero) result = decimal.Zero; if (!_shoppingCartSettings.RoundPricesDuringCalculation) return result; var priceCalculationService = EngineContext.Current.Resolve<IPriceCalculationService>(); result = await priceCalculationService.RoundPriceAsync(result); return result; } /// <summary> /// Gets a value indicating whether capture is supported by payment method /// </summary> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains a value indicating whether capture is supported /// </returns> public virtual async Task<bool> SupportCaptureAsync(string paymentMethodSystemName) { var paymentMethod = await _paymentPluginManager.LoadPluginBySystemNameAsync(paymentMethodSystemName); if (paymentMethod == null) return false; return paymentMethod.SupportCapture; } /// <summary> /// Captures payment /// </summary> /// <param name="capturePaymentRequest">Capture payment request</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the capture payment result /// </returns> public virtual async Task<CapturePaymentResult> CaptureAsync(CapturePaymentRequest capturePaymentRequest) { var paymentMethod = await _paymentPluginManager.LoadPluginBySystemNameAsync(capturePaymentRequest.Order.PaymentMethodSystemName) ?? throw new NopException("Payment method couldn't be loaded"); return await paymentMethod.CaptureAsync(capturePaymentRequest); } /// <summary> /// Gets a value indicating whether partial refund is supported by payment method /// </summary> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains a value indicating whether partial refund is supported /// </returns> public virtual async Task<bool> SupportPartiallyRefundAsync(string paymentMethodSystemName) { var paymentMethod = await _paymentPluginManager.LoadPluginBySystemNameAsync(paymentMethodSystemName); if (paymentMethod == null) return false; return paymentMethod.SupportPartiallyRefund; } /// <summary> /// Gets a value indicating whether refund is supported by payment method /// </summary> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains a value indicating whether refund is supported /// </returns> public virtual async Task<bool> SupportRefundAsync(string paymentMethodSystemName) { var paymentMethod = await _paymentPluginManager.LoadPluginBySystemNameAsync(paymentMethodSystemName); if (paymentMethod == null) return false; return paymentMethod.SupportRefund; } /// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the result /// </returns> public virtual async Task<RefundPaymentResult> RefundAsync(RefundPaymentRequest refundPaymentRequest) { var paymentMethod = await _paymentPluginManager.LoadPluginBySystemNameAsync(refundPaymentRequest.Order.PaymentMethodSystemName) ?? throw new NopException("Payment method couldn't be loaded"); return await paymentMethod.RefundAsync(refundPaymentRequest); } /// <summary> /// Gets a value indicating whether void is supported by payment method /// </summary> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains a value indicating whether void is supported /// </returns> public virtual async Task<bool> SupportVoidAsync(string paymentMethodSystemName) { var paymentMethod = await _paymentPluginManager.LoadPluginBySystemNameAsync(paymentMethodSystemName); if (paymentMethod == null) return false; return paymentMethod.SupportVoid; } /// <summary> /// Voids a payment /// </summary> /// <param name="voidPaymentRequest">Request</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the result /// </returns> public virtual async Task<VoidPaymentResult> VoidAsync(VoidPaymentRequest voidPaymentRequest) { var paymentMethod = await _paymentPluginManager.LoadPluginBySystemNameAsync(voidPaymentRequest.Order.PaymentMethodSystemName) ?? throw new NopException("Payment method couldn't be loaded"); return await paymentMethod.VoidAsync(voidPaymentRequest); } /// <summary> /// Gets a recurring payment type of payment method /// </summary> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains a recurring payment type of payment method /// </returns> public virtual async Task<RecurringPaymentType> GetRecurringPaymentTypeAsync(string paymentMethodSystemName) { var paymentMethod = await _paymentPluginManager.LoadPluginBySystemNameAsync(paymentMethodSystemName); if (paymentMethod == null) return RecurringPaymentType.NotSupported; return paymentMethod.RecurringPaymentType; } /// <summary> /// Process recurring payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the process payment result /// </returns> public virtual async Task<ProcessPaymentResult> ProcessRecurringPaymentAsync(ProcessPaymentRequest processPaymentRequest) { if (processPaymentRequest.OrderTotal == decimal.Zero) { var result = new ProcessPaymentResult { NewPaymentStatus = PaymentStatus.Paid }; return result; } var customer = await _customerService.GetCustomerByIdAsync(processPaymentRequest.CustomerId); var paymentMethod = await _paymentPluginManager .LoadPluginBySystemNameAsync(processPaymentRequest.PaymentMethodSystemName, customer, processPaymentRequest.StoreId) ?? throw new NopException("Payment method couldn't be loaded"); return await paymentMethod.ProcessRecurringPaymentAsync(processPaymentRequest); } /// <summary> /// Cancels a recurring payment /// </summary> /// <param name="cancelPaymentRequest">Request</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the result /// </returns> public virtual async Task<CancelRecurringPaymentResult> CancelRecurringPaymentAsync(CancelRecurringPaymentRequest cancelPaymentRequest) { if (cancelPaymentRequest.Order.OrderTotal == decimal.Zero) return new CancelRecurringPaymentResult(); var paymentMethod = await _paymentPluginManager.LoadPluginBySystemNameAsync(cancelPaymentRequest.Order.PaymentMethodSystemName) ?? throw new NopException("Payment method couldn't be loaded"); return await paymentMethod.CancelRecurringPaymentAsync(cancelPaymentRequest); } /// <summary> /// Gets masked credit card number /// </summary> /// <param name="creditCardNumber">Credit card number</param> /// <returns>Masked credit card number</returns> public virtual string GetMaskedCreditCardNumber(string creditCardNumber) { if (string.IsNullOrEmpty(creditCardNumber)) return string.Empty; if (creditCardNumber.Length <= 4) return creditCardNumber; var last4 = creditCardNumber[(creditCardNumber.Length - 4)..creditCardNumber.Length]; var maskedChars = string.Empty; for (var i = 0; i < creditCardNumber.Length - 4; i++) { maskedChars += "*"; } return maskedChars + last4; } /// <summary> /// Calculate payment method fee /// </summary> /// <param name="cart">Shopping cart</param> /// <param name="fee">Fee value</param> /// <param name="usePercentage">Is fee amount specified as percentage or fixed value?</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the result /// </returns> public virtual async Task<decimal> CalculateAdditionalFeeAsync(IList<ShoppingCartItem> cart, decimal fee, bool usePercentage) { if (fee <= 0) return fee; decimal result; if (usePercentage) { //percentage var orderTotalCalculationService = EngineContext.Current.Resolve<IOrderTotalCalculationService>(); var orderTotalWithoutPaymentFee = (await orderTotalCalculationService.GetShoppingCartTotalAsync(cart, usePaymentMethodAdditionalFee: false)).shoppingCartTotal ?? 0; result = (decimal)((float)orderTotalWithoutPaymentFee * (float)fee / 100f); } else { //fixed value result = fee; } return result; } /// <summary> /// Serialize CustomValues of ProcessPaymentRequest /// </summary> /// <param name="request">Request</param> /// <returns>Serialized CustomValues</returns> public virtual string SerializeCustomValues(ProcessPaymentRequest request) { if (request == null) throw new ArgumentNullException(nameof(request)); if (!request.CustomValues.Any()) return null; //XmlSerializer won't serialize objects that implement IDictionary by default. //http://msdn.microsoft.com/en-us/magazine/cc164135.aspx //also see http://ropox.ru/tag/ixmlserializable/ (Russian language) var ds = new DictionarySerializer(request.CustomValues); var xs = new XmlSerializer(typeof(DictionarySerializer)); using var textWriter = new StringWriter(); using (var xmlWriter = XmlWriter.Create(textWriter)) { xs.Serialize(xmlWriter, ds); } var result = textWriter.ToString(); return result; } /// <summary> /// Deserialize CustomValues of Order /// </summary> /// <param name="order">Order</param> /// <returns>Serialized CustomValues CustomValues</returns> public virtual Dictionary<string, object> DeserializeCustomValues(Order order) { if (order == null) throw new ArgumentNullException(nameof(order)); if (string.IsNullOrWhiteSpace(order.CustomValuesXml)) return new Dictionary<string, object>(); var serializer = new XmlSerializer(typeof(DictionarySerializer)); using var textReader = new StringReader(order.CustomValuesXml); using var xmlReader = XmlReader.Create(textReader); if (serializer.Deserialize(xmlReader) is DictionarySerializer ds) return ds.Dictionary; return new Dictionary<string, object>(); } /// <summary> /// Generate an order GUID /// </summary> /// <param name="processPaymentRequest">Process payment request</param> public virtual void GenerateOrderGuid(ProcessPaymentRequest processPaymentRequest) { if (processPaymentRequest == null) return; //we should use the same GUID for multiple payment attempts //this way a payment gateway can prevent security issues such as credit card brute-force attacks //in order to avoid any possible limitations by payment gateway we reset GUID periodically var previousPaymentRequest = _httpContextAccessor.HttpContext.Session.Get<ProcessPaymentRequest>("OrderPaymentInfo"); if (_paymentSettings.RegenerateOrderGuidInterval > 0 && previousPaymentRequest != null && previousPaymentRequest.OrderGuidGeneratedOnUtc.HasValue) { var interval = DateTime.UtcNow - previousPaymentRequest.OrderGuidGeneratedOnUtc.Value; if (interval.TotalSeconds < _paymentSettings.RegenerateOrderGuidInterval) { processPaymentRequest.OrderGuid = previousPaymentRequest.OrderGuid; processPaymentRequest.OrderGuidGeneratedOnUtc = previousPaymentRequest.OrderGuidGeneratedOnUtc; } } if (processPaymentRequest.OrderGuid == Guid.Empty) { processPaymentRequest.OrderGuid = Guid.NewGuid(); processPaymentRequest.OrderGuidGeneratedOnUtc = DateTime.UtcNow; } } #endregion } }
#pragma once #include <json.hpp> #include <imgui/imgui.h> #include <stdint.h> using nlohmann::json; namespace bandplan { struct Band_t { std::string name; std::string type; double start; double end; }; void to_json(json& j, const Band_t& b); void from_json(const json& j, Band_t& b); struct BandPlan_t { std::string name; std::string countryName; std::string countryCode; std::string authorName; std::string authorURL; std::vector<Band_t> bands; }; void to_json(json& j, const BandPlan_t& b); void from_json(const json& j, BandPlan_t& b); struct BandPlanColor_t { uint32_t colorValue; uint32_t transColorValue; }; void to_json(json& j, const BandPlanColor_t& ct); void from_json(const json& j, BandPlanColor_t& ct); void loadBandPlan(std::string path); void loadFromDir(std::string path); void loadColorTable(json table); extern std::map<std::string, BandPlan_t> bandplans; extern std::vector<std::string> bandplanNames; extern std::string bandplanNameTxt; extern std::map<std::string, BandPlanColor_t> colorTable; };
import React, { Component } from "react"; interface CardProps { title: string; // tailwind css color titleColor?: string; IconComponent: React.ComponentType<any>; bodyText: string | undefined; } export const InformationCard: React.FC<CardProps> = ({ title, titleColor = "text-black", bodyText, IconComponent: Icon = () => <></>, }) => { return ( <> <div className="rounded-2xl bg-white p-6 shadow-xl shadow-gray-300"> <div className={`${titleColor} mb-3 min-w-[300px] text-xl font-bold`}> <div className="inline-flex items-center gap-2"> <Icon className="" /> <span>{title}</span> </div> </div> <div> <span className="text-lg font-normal text-black"> {bodyText || <div className="flex flex-col gap-3"> <div className="bg-slate-300 h-5 rounded-lg w-96 inline-block animate-pulse" /> <div className="bg-slate-300 h-5 rounded-lg w-48 inline-block animate-pulse" /> </div>} </span> </div> </div> </> ); };
// EditPrompt.tsx import React, { useRef, useEffect, useState } from 'react'; import './EditPrompt.css'; import { getUserPrompt, setSuggestedPostsPrompt } from '../../services/PostsService'; import { isAuthenticated } from '../../services/LoginData'; import { useNavigate } from 'react-router-dom'; import { Button } from 'react-bootstrap'; import ErrorDialog from '../ErrorDialogComponent/ErrorDialog'; const EditPrompt: React.FC = () => { const [showErrorDialog, setShowErrorDialog] = useState(false); // Error dialog state const [errorMessage, setErrorMessage] = useState(""); // Error message state const textareaRef = useRef<HTMLTextAreaElement>(null); const navigate = useNavigate(); useEffect(() => { init() .then(() => { getUserPrompt() .then((prompt) => { // Set the prompt in the textarea textareaRef.current!.value = prompt.result; adjustTextareaHeight(); }) .catch(() => { setErrorMessage("There was an error fetching the prompt. You can use your own imigintion and write your own prompt ;)"); setShowErrorDialog(true); }); }); }, []); const adjustTextareaHeight = () => { if (textareaRef.current) { requestAnimationFrame(() => { const currentHeight = textareaRef.current!.style.height ? parseInt(textareaRef.current!.style.height) : 0; const scrollHeight = textareaRef.current!.scrollHeight; if (!currentHeight || scrollHeight > currentHeight) { textareaRef.current!.style.height = `${textareaRef.current!.scrollHeight}px`; } }); } }; const init = async () => { const isUserAuthenticated = await isAuthenticated(); if (!isUserAuthenticated) { navigate('/login'); return; } } const handleGeneratePosts = async () => { setSuggestedPostsPrompt(textareaRef.current!.value); navigate('/dashboard'); } return ( <div className="bg-dark edit-prompt-container"> <h1>Edit Prompt</h1> <textarea ref={textareaRef} onChange={adjustTextareaHeight} className="form-control prompt-textarea" rows={10} /> <Button type="submit" className="btn btn-primary generate-posts-button" onClick={handleGeneratePosts} > Generate Posts </Button> <ErrorDialog // Include the error dialog here show={showErrorDialog} onHide={() => setShowErrorDialog(false)} errorMessage={errorMessage} /> </div> ); }; export default EditPrompt;
/* eslint-disable @typescript-eslint/ban-ts-comment */ import { test, describe, assertType } from 'vitest' import { assertString, assertNotString } from '.' describe('assertString type tests', () => { test('guard definite types', () => { const targetString = 'string' as string | object assertString(targetString) assertType<string>(targetString) }) test('guard definite types 2', () => { const targetConstString = 'string' as 'string' | object assertString(targetConstString) assertType<'string'>(targetConstString) }) test('guard definite types 3', () => { const targetConstString = '3' as `${number}` | number assertString(targetConstString) assertType<`${number}`>(targetConstString) }) test('guard unknown types', () => { const targetUnknown = 'string' as unknown assertString(targetUnknown) assertType<string>(targetUnknown) }) }) describe('assertNotString type tests', () => { test('guard definite types', () => { const targetString = 'string' as string | object assertNotString(targetString) assertType<object>(targetString) }) test('guard definite types 2', () => { const targetConstString = 'string' as 'string' | object assertNotString(targetConstString) assertType<object>(targetConstString) }) test('guard definite types 3', () => { const targetConstString = '3' as `${number}` | number assertNotString(targetConstString) assertType<number>(targetConstString) }) test('guard unknown types', () => { const targetUnknown = 'string' as unknown assertNotString(targetUnknown) assertType<unknown>(targetUnknown) }) })
package it.unipi.iot.coap.CO2; import org.eclipse.californium.core.CoapClient; import org.eclipse.californium.core.CoapHandler; import org.eclipse.californium.core.CoapResponse; import org.eclipse.californium.core.coap.MediaTypeRegistry; import it.unipi.iot.configuration.ConfigurationParameters; import it.unipi.iot.log.Colors; /** * * This class extends the CoapClient class. <br> It provides the methods to: <br> * - compute a new level of Co2 <br> * - activate the dispenser <br> * - change the CO2 dispensed * * @author Fabi8997 * */ public class CO2Dispenser extends CoapClient { private static final String LOG = "[" + Colors.ANSI_CYAN + "Smart Aquarium " + Colors.ANSI_RESET + "]"; private static final String LOG_ERROR = "[" + Colors.ANSI_RED + "Smart Aquarium " + Colors.ANSI_RESET + " ]"; //Status float co2DispenserTankLevel; boolean co2DispenserTankFlowActive; private float currentVariation; private float currentCO2; float minLevel; //TODO Define the threshold private static float THRESHOLD = (float) 2; private static float HIGH_VARIATION_THRESHOLD = 5; /** * Class constructor. * * @param ipAddress of the URI * @param configurationParameters configuration parameters */ public CO2Dispenser(String ipAddress, ConfigurationParameters configurationParameters) { super("coap://[" + ipAddress + "]/"+configurationParameters.co2DispenserTopic+"/tank"); this.minLevel = configurationParameters.minCO2tankLevel; this.co2DispenserTankFlowActive = false; //Initialize current variation, this is needed to know how much must be increase or decrease the PH value this.currentVariation = 0; //Set to 0 so the new value is over the threshold always this.currentCO2 = 0; //Set the initial level of CO2 to be dispensed based on the optimal values computeNewCO2(configurationParameters.pHOptimalValue, configurationParameters.kHOptimalValue, configurationParameters.temperatureOptimalValue); } /** * Compute the new value of CO2 using the formula better explained in the documentation. <br> * The new value depends on the three other measures observed by the sensors.<br> * The new value is accepted only if it is up to a certain threshold read from the configuration file. This * is done in order to not change too frequently the CO2 dispensed but at the same time keeping its value inside a * safe interval for the aquarium life. * * @param pH value observed from the PH sensor * @param kH value observed from the KH sensor * @param temperature observed from the temperature sensor */ public void computeNewCO2(float pH, float kH, float temperature) { float PKa = (float) (((3404.71)/(temperature + 273.15)) + (0.032786*(temperature + 273.15) - 14.8435)); float newCO2 = (float) (15.69692*kH*Math.pow(10, PKa - pH)); currentVariation = Math.abs(newCO2 - currentCO2); if (currentVariation > THRESHOLD){ currentCO2 = newCO2; this.setCO2Dispensed(); } } /** * Activates the flow using the initial CO2 value to be dispensed. */ public void startDispenser() { setCO2Dispensed(); activateFlow(); } /** * Send a put request to activate the flow of CO2, the post variable set is mode = on.<br> * The put request is handled by a CoapHandler that onLoad changes the value of the flag to check the flow status, * while onError \\TODO. * */ public void activateFlow() { //send put mode on this.put(new CoapHandler() { @Override public void onLoad(CoapResponse response) { if (response != null) { if(!response.isSuccess()) { System.out.println(LOG + " Put operation failed [device: CO2Dispenser]."); }else { System.out.println(LOG + " CO2 dispenser [ mode = "+Colors.ANSI_GREEN+"on"+Colors.ANSI_RESET+" ]."); //Set the flag to signal that the flow is active co2DispenserTankFlowActive = true; } } } public void onError() { System.out.println(LOG_ERROR + " Put operation failed [device: CO2Dispenser]."); } }, "mode=on", MediaTypeRegistry.TEXT_PLAIN); } /** * Send a put request to change the value of CO2 dispensed, the post variable set is value = currentCO2.<br> * The put request is handled by a CoapHandler. * */ public void setCO2Dispensed() { //send put mode on this.put(new CoapHandler() { @Override public void onLoad(CoapResponse response) { if (response != null) { if(!response.isSuccess()) { System.out.println(LOG + " Put operation failed [device: CO2Dispenser]."); }else { System.out.println(LOG + " Changed CO2 dispensed [ value = "+Colors.ANSI_GREEN+String.format("%.2f",currentCO2)+Colors.ANSI_RESET+" ]."); } } } public void onError() { System.out.println(LOG_ERROR + " Put operation failed [device: CO2Dispenser]."); } }, "value="+String.format("%.2f",currentCO2), MediaTypeRegistry.TEXT_PLAIN); } /** * Send a put request to stop the flow of CO2, the post variable set is mode = off.<br> * The put request is handled by a CoapHandler that onLoad changes the value of the flag to check the flow status, * while onError \\TODO. * */ public void stopFlow() { //send put mode off this.put(new CoapHandler() { @Override public void onLoad(CoapResponse response) { if (response != null) { if(!response.isSuccess()) { System.out.println(LOG + " Put operation failed [device: CO2Dispenser]."); }else { System.out.println(LOG + " CO2 dispenser [ mode = "+Colors.ANSI_RED+"off"+Colors.ANSI_RESET+" ]."); //Set the flag to signal that the flow is active co2DispenserTankFlowActive = false; } } } public void onError() { System.out.println(LOG_ERROR + " Put operation failed [device: CO2Dispenser]."); } }, "mode=off", MediaTypeRegistry.TEXT_PLAIN); } public boolean isHighVariation() { return currentVariation > HIGH_VARIATION_THRESHOLD; } public float getCurrentCO2() { return currentCO2; } public float getCurrentVariation() { return currentVariation; } public boolean isCo2DispenserTankFlowActive() { return co2DispenserTankFlowActive; } public boolean toBeFilled() { return (this.co2DispenserTankLevel <= this.minLevel); } public void setCo2DispenserTankFlowActive(boolean co2DispenserTankFlowActive) { this.co2DispenserTankFlowActive = co2DispenserTankFlowActive; } public float getCo2DispenserTankLevel() { return co2DispenserTankLevel; } public void setCo2DispenserTankLevel(float co2DispenserTankLevel) { this.co2DispenserTankLevel = co2DispenserTankLevel; } /** * Stop the flow of CO2 and stop the device. */ public void stop() { this.stopFlow(); this.delete(); } }
package main import "fmt" //在Golang中,如果一个struct嵌套了另一个匿名结构体, //那么这个结构体可以直接访问匿名结构体的字段和方法,从而实现了继承特性。 type Animal struct { Age int Weight float32 } func (an *Animal) Shout() { fmt.Println("喊叫") } func (an *Animal) ShowInfo() { fmt.Printf("动物的年龄是:%v,动物的体重是:%v\n", an.Age, an.Weight) } type Cat struct { //为了复用性,体现继承思维,嵌入匿名结构体:将Animal中的字段和方法都达到复用 Animal //结构体的匿名字段可以是基本数据类型 int //结构体的字段可以是结构体类型的。(组合模式) ear Ear } type Ear struct { Shape string Color string } // 对Cat绑定特有的方法: func (c *Cat) catchMouse() { fmt.Println("抓老鼠") } func (c *Cat) Shout() { fmt.Println("喵喵叫") } func main() { cat := &Cat{} // cat.Age ---> cat对应的结构体中找是否有Age字段,如果有直接使用,如果没有就去找嵌入的结构体类型中的Age cat.Age = 3 cat.Weight = 10.6 // 如希望访问匿名结构体的字段和方法,可以通过匿名结构体名来区分。 cat.Animal.Shout() cat.Shout() cat.ShowInfo() cat.catchMouse() fmt.Println("结构体中类型为基本数据类型的匿名字段:", cat.int) // 嵌套匿名结构体后,也可以在创建结构体变量(实例)时,直接指定各个匿名结构体字段的值 cat2 := Cat{ Animal{ Weight: 9, Age: 8, }, 3, Ear{ Shape: "尖尖的", Color: "白色", }, } cat2.ShowInfo() fmt.Println(cat2.ear.Shape) }
// Dart imports import 'dart:io'; // Flutter imports import 'package:firebase_storage/firebase_storage.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; // File imports import '../../providers/user_profile_provider.dart'; import '../../models/user_profile.dart'; import 'firestore_keys.dart'; class DBUserProfile { // CLOUD FIRESTORE ACCESS METHODS // Pulls the Firebase user's user profile from Firestore and uses the passed in provider // to update displays througout the app. // // Returns true if data was fetched and set in provider; false otherwise static Future<bool> fetchUserProfileAndSyncProvider( UserProfileProvider userProfileProvider) async { // Initialize success variable bool success = false; // Get Firebase instance var db = FirebaseFirestore.instance; if (FirebaseAuth.instance.currentUser != null) { // Get the authenticated firebase user final FirebaseAuth auth = FirebaseAuth.instance; final User? user = auth.currentUser; // If no user logged in, return; otherwise continue if (user == null) { return false; } String uid = user.uid; // Try to get the user's data from firestore try { // This code does a one-time read of the database object //var ref = await db.collection(FS_COL_SA_USER_PROFILES).doc(uid).get(); // if (ref.exists) { // Map<String, dynamic>? data = ref.data()!; // UserProfile userProfile = populateUserProfileFromFirestoreObject(data); // // Use the provider to update the profile with new data // userProfileProvider.updateUserProfile(userProfile); // success = true; // } // This code sets up a listener to do a one-time read, and then it executes // again every time the document changes db.collection(FS_COL_SA_USER_PROFILES).doc(uid).snapshots().listen((docRef) { if (docRef.exists) { Map<String, dynamic>? data = docRef.data()!; UserProfile userProfile = populateUserProfileFromFirestoreObject(data); // Use the provider to update the profile with new data userProfileProvider.updateUserProfile(userProfile); success = true; } }); } catch (e) { print("Encountered problem loading user profile from firestore: ${e.toString()}"); userProfileProvider.wipe(); } } // Return status return await Future.value(success); } // Writes the provided user profile to the database static Future<bool> writeUserProfile(UserProfile userProfile) async { // Initialize success variable bool success = false; // Get Firebase instance var db = FirebaseFirestore.instance; if (FirebaseAuth.instance.currentUser != null) { // Get the authenticated firebase user final FirebaseAuth auth = FirebaseAuth.instance; final User? user = auth.currentUser; // If no user logged in, return; otherwise continue if (user == null) { return false; } String uid = user.uid; // Try to get the user's data from firestore try { // Attempt to write data await db .collection(FS_COL_SA_USER_PROFILES) .doc(uid) .set(userProfile.toJsonForDb(), SetOptions(merge: true)); success = true; } catch (e) { print("Encountered problem writing user profile to firestore: ${e.toString()}"); success = false; } } // Return status return success; } // Creates a new User profile and populates using the JSON object passed in as parameter static UserProfile populateUserProfileFromFirestoreObject(Map<String, dynamic> data) { String userEmail = FirebaseAuth.instance.currentUser!.email ?? ""; UserProfile userProfile = UserProfile.fromJsonDbObject(data, userEmail); return userProfile; } // CLOUD STORAGE ACCESS METHODS // Pulls the Firebase user's user profile image from Cloud Storage and uses the passed in // provider to update displays througout the app. // // Returns true if image data was fetched and set in provider; false otherwise static Future<bool> fetchUserProfileImageAndSyncProvider( UserProfileProvider userProfileProvider) async { // Initialize success variable bool success = false; // Try to download the image try { // Get logged-in user's uid if (FirebaseAuth.instance.currentUser == null) { return false; } String uid = FirebaseAuth.instance.currentUser!.uid; // Get a Google Storage reference to the profile picture final ref = FirebaseStorage.instance.ref().child('users/$uid/profile_picture/userProfilePicture.jpg'); var url = await ref.getDownloadURL(); userProfileProvider.userImage = NetworkImage(url); success = true; } catch (e) { // If ref is bad/incomplete, set to local image userProfileProvider.userImage = GENERIC_IMAGE; } // Return status return await Future.value(success); } // Uplads the user profile image to Google Cloud Storage static Future<bool> uploadNewUserProfileImage( File imageFile, UserProfileProvider userProfileProvider) async { // Initialize success variable bool success = false; try { // Get logged-in user's uid if (FirebaseAuth.instance.currentUser == null) { return false; } String uid = FirebaseAuth.instance.currentUser!.uid; // Get a reference to the logged-in user's profile pic and upload the new picture final gcsPath = 'users/$uid/profile_picture/userProfilePicture.jpg'; final ref = FirebaseStorage.instance.ref().child(gcsPath); await ref.putFile(imageFile); success = true; } catch (e) { success = false; } return success; } }
import React from 'react'; import styled from 'styled-components'; import { lighten } from 'polished'; const StyledInput = styled.input` display: flex; align-items: center; width: 93%; height: 93%; margin: 5px 0; font-size: 1rem; padding: 10px; border: 1px solid #ccc; border-radius: 4px; transition: border-color 0.3s, box-shadow 0.3s; cursor: pointer; &:hover { border-color: ${lighten(0.2, '#ccc')}; box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); } &:focus { border-color: #0078d4; box-shadow: 0 0 5px rgba(0, 120, 212, 0.5); outline: none; } `; const TextInput = ({ value = '', onChange }) => { return ( <StyledInput type="text" value={value} onChange={(e) => onChange(e.target.value)} autoFocus /> ); }; export default TextInput;
import type { GetStaticProps } from "next"; import { type NextPage } from "next"; import Head from "next/head"; import { PageLayout } from "~/components/layout"; import { PostView } from "~/components/postview"; import { generateSSGHelper } from "~/server/api/helpers/ssgHelper"; import { api } from "~/utils/api"; const SinglePostPage: NextPage<{ postId: string }> = (props) => { const { data: fullPost } = api.posts.getPostById.useQuery({ id: props.postId, }); if (!fullPost) return <div>404</div>; return ( <> <Head> <title>{`${fullPost.author.username ?? ""} on Rent a Dev: "${ fullPost.post.content || "" }"`}</title> </Head> <PageLayout> <PostView {...fullPost} /> </PageLayout> </> ); }; export const getStaticProps: GetStaticProps = async (context) => { const ssg = generateSSGHelper(); const postId = context.params?.id; if (typeof postId !== "string") throw new Error("no slug"); await ssg.posts.getPostById.prefetch({ id: postId }); return { props: { trpcState: ssg.dehydrate(), postId, }, }; }; export const getStaticPaths = () => { return { paths: [], fallback: "blocking" }; }; export default SinglePostPage;
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.serveFetchReflections = void 0; const modifyDateString_1 = require("../../../../common/modules/date/modifyDateString"); const dbFetchEntries_1 = require("../../../db/entry/dbFetchEntries"); function serveFetchReflections(req, res) { return __awaiter(this, void 0, void 0, function* () { const { userParmId } = req; const { today } = req.query; try { const weekAgo = (0, modifyDateString_1.modifyDateString)(today, -7); const weekAgoReflection = yield makeReflection(req.mongoose, userParmId, "One Week Ago", weekAgo); const monthAgo = (0, modifyDateString_1.modifyDateString)(today, -30); const monthAgoReflection = yield makeReflection(req.mongoose, userParmId, "One Month Ago", monthAgo); const yearAgo = (0, modifyDateString_1.modifyDateStringYear)(today, -1); const yearAgoReflection = yield makeReflection(req.mongoose, userParmId, "One Year Ago", yearAgo); // make reflections const reflections = [ weekAgoReflection, monthAgoReflection, yearAgoReflection, ]; return res.json({ reflections, }); } catch (error) { return res.status(500).json({ message: "Something went wrong", }); } }); } exports.serveFetchReflections = serveFetchReflections; function makeReflection(mongoose, userParmId, title, date) { return __awaiter(this, void 0, void 0, function* () { const entries = yield (0, dbFetchEntries_1.dbFetchEntries)(mongoose, userParmId, { date, draft: false, }); return { title, date, entries: entries.map((entry) => ({ id: entry.id, date: entry.date, body: entry.body, })), }; }); }
import spotipy from spotipy.oauth2 import SpotifyClientCredentials, SpotifyOAuth import json # Ruta al archivo de credenciales CREDENTIALS_FILE = "spotify_credentials.json" def load_credentials(): """ Carga las credenciales de Spotify desde un archivo JSON. Si el archivo no existe o está vacío, devuelve None. """ try: with open(CREDENTIALS_FILE, "r") as file: credentials = json.load(file) return credentials except FileNotFoundError: print("Archivo de credenciales no encontrado. Configure las credenciales primero.") return None except json.JSONDecodeError: print("El archivo de credenciales está mal formado.") return None # Cargar credenciales desde el archivo credentials = load_credentials() if credentials: client_id = credentials["SPOTIFY_CLIENT_ID"] client_secret = credentials["SPOTIFY_CLIENT_SECRET"] redirect_uri = credentials["SPOTIFY_REDIRECT_URI"] # Autenticación basada en la aplicación client_credentials_manager = SpotifyClientCredentials( client_id=client_id, client_secret=client_secret ) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) # Autenticación basada en el usuario user_auth_manager = SpotifyOAuth( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope="user-read-private user-top-read playlist-read-private user-library-read user-follow-read playlist-modify-public playlist-modify-private" ) sp_user = spotipy.Spotify(auth_manager=user_auth_manager) else: sp = None sp_user = None def get_popular_songs(): """ Obtiene canciones populares de un género específico, en este caso pop. """ if not sp: return ["Error: Spotify no está configurado correctamente."] resultados = sp.search(q='genre:"pop"', type='track', limit=10) canciones = [f'{track["name"]} by {track["artists"][0]["name"]}' for track in resultados['tracks']['items']] return canciones def get_user_profile(): """ Obtiene el perfil básico del usuario autenticado. """ if not sp_user: return {"error": "Spotify no está configurado correctamente."} try: user_profile = sp_user.current_user() return { "name": user_profile.get("display_name", "Desconocido"), "id": user_profile.get("id", "No disponible"), "email": user_profile.get("email", "No disponible"), "country": user_profile.get("country", "No disponible"), "product": user_profile.get("product", "No disponible"), "followers": user_profile.get("followers", {}).get("total", 0), } except Exception as e: return {"error": f"Error al obtener el perfil: {str(e)}"} def get_top_artists(): """ Obtiene los artistas más escuchados del usuario autenticado. """ if not sp_user: return {"error": "Spotify no está configurado correctamente."} try: top_artists = sp_user.current_user_top_artists(limit=5) return [artist["name"] for artist in top_artists["items"]] except Exception as e: return {"error": str(e)} def get_playlists(query, limit=2, property='id'): """ Obtiene playlists según una query. """ if not sp: return ["Error: Spotify no está configurado correctamente."] resultados = sp.search(q=query, type='playlist', limit=limit) playlists = [playlist[property] for playlist in resultados['playlists']['items'] if playlist is not None ] return playlists def get_playlists_items(playlist_id, limit=10, property='id'): """ Obtiene las canciones en una playlist """ if not sp: return ["Error: Spotify no está configurado correctamente."] resultados = sp.playlist_tracks(playlist_id=playlist_id, limit=limit) songs = [song['track'][property] for song in resultados['items'] if song is not None and song['track'] is not None] return songs def get_song(song_id): """ Obtiene una propiedad de una playlist dado su id """ if not sp: return ["Error: Spotify no está configurado correctamente."] resultados = sp.track(track_id=song_id) return resultados def song_save_by_user(song_id): """ Obtiene si el usuario tiene guardada una canción o no """ if not sp_user: return ["Error: La cuenta de spotify no está configurada correctamente."] return sp_user.current_user_saved_tracks_contains(tracks=[song_id])[0] def artist_followed_by_user(artist_id): """ Obtiene si el usuario sigue a un artista o no """ if not sp_user: return ["Error: La cuenta de spotify no está configurada correctamente."] return sp_user.current_user_following_artists(ids=[artist_id])[0] def create_playlist(songs, title, description): """ Crea una playlist """ if not isinstance(title,str) or len(title)<1: title = "Nueva playlist" if not isinstance(description,str) or len(description)<1: description = "" if not sp_user: return ["Error: La cuenta de spotify no está configurada correctamente."] playlist = sp_user.user_playlist_create(user=sp_user.current_user()['id'],name=title, description=description) sp_user.playlist_add_items(playlist['id'], songs) return 0
using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using transactionApi; using transactionApi.Models; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authentication.JwtBearer; using System.Text; using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); // In ConfigureServices method of Startup.cs builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" }); }); // In Configure method of Startup.cs builder.Services.AddRazorPages(); builder.Services.AddScoped<UserServices>(); builder.Services.AddDbContext<Context>(options => { options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")); }); builder.Configuration.AddJsonFile("appsettings.json"); builder.Services.AddAuthorization(options => { options.AddPolicy("RequireLoggedIn", policy => { // Require the user to be authenticated policy.RequireAuthenticatedUser(); }); }); builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { var jwtSecret = builder.Configuration.GetValue<string>("Jwt:SecretKey"); options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "rilak", ValidAudience = "rilak", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret)) }; }); var app = builder.Build(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API V1"); }); using (var scope = app.Services.CreateScope()) { var userService = scope.ServiceProvider.GetRequiredService<UserServices>(); var username = "rilakn"; // Replace with an actual username var token = userService.GenerateJwtToken(username); // Do something with the token, e.g., store it securely } app.MapControllers(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); app.UseCors(options => { options.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => endpoints.MapRazorPages()); app.UseHttpsRedirection(); app.MapControllers(); app.Run();
# Import necessary modules import omero import os from tqdm import tqdm import json from scripts import idr_funs from idr import connection data_sizes = list(map(int,[1e5,1e6,5e5])) def get_hcs(): # breakpoint() conn = connection("idr.openmicroscopy.org") screens = conn.getObjects('Screen') filtered_screens = [] for screen in screens: # Get all the map annotation associated with the screen map_anns = [ann for ann in screen.listAnnotations() if isinstance(ann, omero.gateway.MapAnnotationWrapper)] # Filter based on the map annotation values for ann in map_anns: values = dict(ann.getValue()) if values.get('Organism') == 'Homo sapiens' and values.get('Study Type') == 'high content screen': filtered_screens.append(screen.name) conn.close() return filtered_screens screen_names = get_hcs() def expand_from_metadata(wildcards): # breakpoint() # checkpoint_output = checkpoints.get_hcs_screens.get(**wildcards).output.screen_names checkpoint_output = checkpoints.get_image_metadata.get(**wildcards).output.metadata with open(checkpoint_output) as f: metadata = json.load(f) input_files = [] for image_id, zct in tqdm(metadata.items()): input_files.extend( expand( "results/{{screen_name}}/{image_id}/{z}_{c}_{t}.ome.ngff", image_id=image_id, z=range(zct["z"]), c=range(zct["c"]), t=range(zct["t"]), ) ) return input_files def expand_from_screens(wildcards): checkpoint_output = (checkpoints.get_hcs_screens.get(**wildcards).output.screen_names) with open(checkpoint_output) as f: screen_names = list(json.load(f)) return expand("results/{screen_name}/image_ids.json",screen_name=screen_names) def get_organism_screenids(session, organism, idr_base_url="https://idr.openmicroscopy.org"): screen_id_list = [] qs = {"base": idr_base_url, "key": "organism", "value": organism} screens_projects_url = "{base}/mapr/api/{key}/?value={value}" url = screens_projects_url.format(**qs) sr = session.get(url) sr.raise_for_status() for s in sr.json()["screens"]: screen_id_list.append(str(s["id"])) return screen_id_list rule all: input: "results/screen_names.json", "results/image_ids.json", expand("results/{screen_name}/downloaded.flag",screen_name=screen_names) checkpoint get_hcs_screens: # input: # screen_names=expand_from_screens output: screen_names="results/screen_names.json", run: screen_names = get_hcs() # breakpoint() with open(output.screen_names, "w") as f: json.dump(screen_names, f) rule download_all_images_per_screen: input: metadata=expand_from_metadata output: flag=touch("results/{screen_name}/downloaded.flag") rule collate_image_ids: input: screen_names="results/screen_names.json", json=expand_from_screens output: json="results/image_ids.json" shell: "jq -s . {input.json} > {output.json}" rule reduce_image_set: input: image_ids="results/image_ids.json", output: subset="results/{data_size}_image_ids.json" shell: "jq -n --argjson size {wildcards.data_size} '[inputs] | flatten | .[range(0; $size | tonumber)]' {input.image_ids} > {output.subset}" rule generate_image_ids: output: image_ids=touch("results/{screen_name}/image_ids.json"), resources: mem_mb=16000, run: conn = connection("idr.openmicroscopy.org") # image_ids = get_image_ids screen = conn.getObject('Screen', attributes={'name': wildcards.screen_name}) # screens = conn.getObject('Screen', attributes={'name': wildcards.screen_name}) print("Getting plates") plates = idr_funs.get_omero_children(screen) print("Getting wells") wells = idr_funs.get_children_from_list_of_objects(plates) print("Getting imageids") well_sampler = idr_funs.get_children_from_list_of_objects(wells) # breakpoint() # print("Getting plates") image_ids = [x.image().id for x in well_sampler] with open(output.image_ids, "w") as f: json.dump(image_ids, f) # with open(output.image_ids, "w") as f: # f.write("\n".join(str(x) for x in image_ids)) print("generate_image_ids: Done") conn._closeSession() def expand_wildcards_from_checkpoint(wildcards): checkpoint_output = checkpoints.generate_image_ids.get(**wildcards).output.image_ids with open(checkpoint_output) as f: image_ids = [x.strip() for x in f.readlines()] print("Done") return image_ids checkpoint get_image_metadata: input: json="results/{screen_name}/image_ids.json", image_ids="results/{screen_name}/image_ids.json", output: metadata="results/{screen_name}/metadata.json", script: "scripts/get_image_metadata.py" rule download_images: resources: mem_mb=1000, input: metadata="results/{screen_name}/metadata.json", output: tiff="results/{screen_name}/{image_id}/{z}_{c}_{t}.tiff", script: "scripts/download_images.py" rule convert_tiff_to_ngff: input: tiff="results/{screen_name}/{image_id}/{z}_{c}_{t}.tiff", output: ngff=directory("results/{screen_name}/{image_id}/{z}_{c}_{t}.ome.ngff"), shell: """ bioformats2raw {input.tiff} {output.ngff} """ # def expand_from_metadata(wildcards): # checkpoint_output = checkpoints.get_image_metadata.get(**wildcards).output.metadata # with open(checkpoint_output) as f: # metadata = json.load(f) # input_files = [] # for image_id, zct in tqdm(metadata.items()): # z_values = range(zct["z"]) # c_values = range(zct["c"]) # t_values = range(zct["t"]) # input_files.extend( # expand( # "results/{image_id}/{z}_{c}_{t}.tiff", # image_id=image_id, # z=z_values, # c=c_values, # t=t_values, # ) # ) # return input_files[0:10]
local Matrix = require('matrix') describe('matrix', function() it('should allow rows to be extracted', function() local matrix = Matrix('1 2 3\n4 5 6\n7 8 9') assert.same({ 1, 2, 3 }, matrix.row(1)) assert.same({ 4, 5, 6 }, matrix.row(2)) assert.same({ 7, 8, 9 }, matrix.row(3)) end) it('should allow columns to be extracted', function() local matrix = Matrix('1 2 3\n4 5 6\n7 8 9') assert.same({ 1, 4, 7 }, matrix.column(1)) assert.same({ 2, 5, 8 }, matrix.column(2)) assert.same({ 3, 6, 9 }, matrix.column(3)) end) it('should support values of varying sizes', function() local matrix = Matrix('1 2 3\n4 12345 6\n7 8 9') assert.same({ 4, 12345, 6 }, matrix.row(2)) assert.same({ 2, 12345, 8 }, matrix.column(2)) end) it('should support matrices of varying sizes', function() local matrix = Matrix('1 2\n3 4\n5 6') assert.same({ 3, 4 }, matrix.row(2)) assert.same({ 2, 4, 6 }, matrix.column(2)) end) end)
import styles from "../../../../../styles/Dashboard/dashboard.module.css"; import TableStyles from "../../../../../styles/Dashboard/Tables.module.css"; import { usePageSize } from "../../../../../comps/Dashboard/Inputs"; import { BtnEdit, BtnNewDelete, BtnShow, BtnTables, MagicLinkIcon } from "../../../../../comps/Buttons"; import SafqaTable from "../../../../../comps/common/SafqaTable"; import { deleteCity, getCities } from "../../../../../store/slices/citySlice"; import { useRef } from "react"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; import { Space } from "antd"; import AddIcon from "@mui/icons-material/Add"; import VerticalAlignBottomIcon from "@mui/icons-material/VerticalAlignBottom"; import AdminAddressNav from "../../../../../comps/admin/address/AdminAddressNav"; import { useEffect } from "react"; const City = () => { const [t, i18n] = useTranslation(); const { language } = i18n; const dispatch = useDispatch(); const tableRef = useRef() const { SelectPageSize, pageSize } = usePageSize(5); const { cities, isLoading, deleteLoading, success, api_errors } = useSelector(state => state.city); const columns = [ { title: t("dashboard.name_En"), dataIndex: 'name_en', key: 'name_en', }, { title: t("dashboard.name_Ar"), dataIndex: 'name_ar', key: 'name_ar', }, { title: t("dashboard.country"), dataIndex: language == 'en' ? ['country', 'name_en'] : ['country', 'name_ar'], key: ['country', 'name_en'], }, { title: language == 'en' ? 'Actions' : 'أجراءات', dataIndex: '', key: 'x', render: (_, city) => <Space> {/* <BtnShow href={`../../dashboard/admin/address/city/${city.id}`} /> */} <BtnEdit href={`/dashboard/admin/address/city/update/${city.id}`} /> <BtnNewDelete title={city[language == 'en' ? "name_en" : "name_ar"]} item={city} handleDelete={deleteCity} isLoading={deleteLoading} success={success} error={api_errors} /> </Space> }, ] useEffect(() => { dispatch(getCities()); }, [dispatch]) return ( <div className="col-xl-9 col-lg-9 col-md-12 col-sm-12 mb-5"> <div className={styles.container}> <AdminAddressNav /> <div className={`mt-2 mb-4 ${language == "ar" && "me-3 ms-4"}`} dir={language == "ar" ? "rtl" : "ltr"}> <div className={`rounded-2 ${language == "en" && "me-4"} ${TableStyles.info}`}> <MagicLinkIcon url="/dashboard/admin/address/city/create" style={TableStyles.bgBlue} icon={<AddIcon />} name={t("dashboard.create_new")} /> {/* <MagicLinkIcon url="/dashboard" style={TableStyles.bgBlue} icon={<VerticalAlignBottomIcon />} name={t("dashboard.import")} /> */} <br /> <div className={`safqa-scroll-x d-flex ${language == "ar" && "me-2"}`}> <BtnTables getItems={getCities} data={cities} columns={columns} filename="cities" tableRef={tableRef} /> <SelectPageSize /> </div> <div className="w-100 mt-2" ref={tableRef}> <SafqaTable dataSource={cities} columns={columns} loading={isLoading} pageSize={pageSize} /> </div> </div> </div> </div> </div> ); }; export default City;
package org.xmlprocessing_exercise; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import org.xmlprocessing_exercise.service.*; @Component public class CommandLineRunnerImpl implements CommandLineRunner { private final SupplierService supplierService; private final PartService partService; private final CarService carService; private final CustomerService customerService; private final SaleService saleService; public CommandLineRunnerImpl(SupplierService supplierService, PartService partService, CarService carService, CustomerService customerService, SaleService saleService) { this.supplierService = supplierService; this.partService = partService; this.carService = carService; this.customerService = customerService; this.saleService = saleService; } @Override public void run(String... args) throws Exception { this.supplierService.seedSupplier(); this.partService.seedParts(); this.carService.seedCars(); this.customerService.seedCustomers(); this.saleService.seedSales(); // this.customerService.exportOrderedCustomers(); // this.carService.exportToyotaCars(); // this.supplierService.exportLocalSuppliers(); // this.carService.exportCarsAndParts(); // this.customerService.exportCustomersWithBoughtCars(); this.saleService.exportSales(); } }
package parameters; import java.lang.reflect.Field; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static processing.core.PConstants.ADD; public final class Parameters { public static final long SEED = 1968539008; public static final int WIDTH = 2000; public static final int HEIGHT = 2000; public static final int MARGIN = 200; public static final float CHANCE_OF_NEW_SQUARE = .95f; public static final float WIDTH_EXPONENT = .6f; public static final float SIZE_EXPONENT = .6f; public static final float NOISE_SCALE = 1 / 200f; public static final float NOISE_Z_OFFSET_SQUARE = .5f; public static final float NOISE_Z_OFFSET_PYRAMID = .25f; public static final int BLEND_MODE = ADD; public static final Color BACKGROUND_COLOR = new Color("232B36"); public static final Color FILL_COLOR_1 = new Color(196); public static final Color FILL_COLOR_2 = new Color(128); public static final Color FILL_COLOR_3 = new Color(32); public static final Color FILL_COLOR_4 = new Color(32); /** * Helper method to extract the constants in order to save them to a json file * * @return a Map of the constants (name -> value) */ public static Map<String, ?> toJsonMap() throws IllegalAccessException { Map<String, Object> map = new HashMap<>(); Field[] declaredFields = Parameters.class.getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); map.put(field.getName(), field.get(Parameters.class)); } return Collections.singletonMap(Parameters.class.getSimpleName(), map); } public record Color(float red, float green, float blue, float alpha) { public Color(float red, float green, float blue) { this(red, green, blue, 255); } public Color(float grayscale, float alpha) { this(grayscale, grayscale, grayscale, alpha); } public Color(float grayscale) { this(grayscale, 255); } public Color(String hexCode) { this(decode(hexCode)); } public Color(Color color) { this(color.red, color.green, color.blue, color.alpha); } public static Color decode(String hexCode) { return switch (hexCode.length()) { case 2 -> new Color(Integer.valueOf(hexCode, 16)); case 4 -> new Color(Integer.valueOf(hexCode.substring(0, 2), 16), Integer.valueOf(hexCode.substring(2, 4), 16)); case 6 -> new Color(Integer.valueOf(hexCode.substring(0, 2), 16), Integer.valueOf(hexCode.substring(2, 4), 16), Integer.valueOf(hexCode.substring(4, 6), 16)); case 8 -> new Color(Integer.valueOf(hexCode.substring(0, 2), 16), Integer.valueOf(hexCode.substring(2, 4), 16), Integer.valueOf(hexCode.substring(4, 6), 16), Integer.valueOf(hexCode.substring(6, 8), 16)); default -> throw new IllegalArgumentException(); }; } } }
import { createReducer } from "@reduxjs/toolkit"; const initialState = { isLoading: true, adminOrderLoading: false, orders: [], adminOrders: [], error: null, }; export const orderReducer = createReducer(initialState, (builder) => { builder .addCase('getAllOrdersUserRequest', (state) => { state.isLoading = true; }) .addCase('getAllOrdersUserSuccess', (state, action) => { state.isLoading = false; state.orders = action.payload; }) .addCase('getAllOrdersUserFailed', (state, action) => { state.isLoading = false; state.error = action.payload; }) .addCase('getAllOrdersShopRequest', (state) => { state.isLoading = true; }) .addCase('getAllOrdersShopSuccess', (state, action) => { state.isLoading = false; state.orders = action.payload; }) .addCase('getAllOrdersShopFailed', (state, action) => { state.isLoading = false; state.error = action.payload; }) .addCase('adminAllOrdersRequest', (state) => { state.adminOrderLoading = true; }) .addCase('adminAllOrdersSuccess', (state, action) => { state.adminOrderLoading = false; state.adminOrders = action.payload; }) .addCase('adminAllOrdersFailed', (state, action) => { state.adminOrderLoading = false; state.error = action.payload; }) .addCase('clearErrors', (state) => { state.error = null; }); }); export default orderReducer;
(** This module contains interfaces for use within the application. @Author David Hoyle @Version 1.302 @Date 02 Jan 2022 @license DGH Debugging Tools is a RAD Studio plug-in to provide additional functionality in the RAD Studio IDE when debugging. Copyright (C) 2020 David Hoyle (https://github.com/DGH2112/Debugging-Tools/) 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 **) Unit DebuggingTools.Interfaces; Interface Uses DebuggingTools.Types; Type (** An interface for loading and save options from the Options frame. **) IDDTOptions = Interface ['{2C30AC8E-9C54-4544-A6AD-394DA361341F}'] Procedure LoadOptions(Const CheckOptions : TDDTChecks; Const strCodeSiteMsg : String); Procedure SaveOptions(Var CheckOptions : TDDTChecks; Var strCodeSiteMsg : String); End; (** An interface for the Plug-in Options **) IDDTPluginOptions = Interface ['{C0C072B8-4F4C-4EE1-938A-333FF7BCE881}'] Function GetCodeSiteTemplate : String; Procedure SetCodeSiteTemplate(Const strCodeSiteTemplate : String); Function GetCheckOptions : TDDTChecks; Procedure SetCheckOptions(Const setCheckOptions : TDDTChecks); Procedure LoadSettings; Procedure SaveSettings; (** This property gets and sets the CodeSite template that is used to fill the breakpoint evaluation expression. @precon None. @postcon Gets and sets the CodeSite template that is used to fill the breakpoint evaluation expression. @return a String **) Property CodeSiteTemplate : String Read GetCodeSiteTemplate Write SetCodeSiteTemplate; (** This property gets and sets the check options that is used to fill the breakpoint. @precon None. @postcon Gets and sets the check options that is used to fill the breakpoint. @return a TDDTChecks **) Property CheckOptions : TDDTChecks Read GetCheckOptions Write SetCheckOptions; End; Implementation End.
/** * @file Duplicates in Array * @brief You are given an array ‘ARR’ of size ‘N’ containing each number between 1 and ‘N’ - 1 at least once. There is a single integer value that is present in the array twice. Your task is to find the duplicate integer value present in the array. * @link https://www.codingninjas.com/codestudio/problems/duplicate-in-array_893397 * @author Suyash Purwar (github.com/suyash-purwar) * @date 16-06-2023 */ #include <iostream> #include <vector> #include <algorithm> using std::cout; using std::endl; using std::vector; using std::sort; class Solution { public: // Method 1 - Sort the vector and check if any adjacent elements are same. If yes, return that element. // TC: O(nlogn + n) // SC: O(1) int findDuplicate1(vector<int>& nums) { sort(nums.begin(), nums.end()); // O(nlogn) for (int i = 1; i < nums.size(); i++) { // O(n) if (nums[i-1] == nums[i]) return nums[i]; } return -1; } // Method 2 - Hashing // TC: O(2n) // SC: O(n) int findDuplicate2(vector<int> &nums) { vector<int> hash(nums.size(), 0); for (int n: nums) hash[n]++; for (int i = 0; i < hash.size(); i++) { if (hash[i] == 2) return i; } return -1; } // Method 3 (Optimal) // TC: O(n) // SC: O(1) int findDuplicate3(vector<int>& nums) { int n = nums.size()-1; int sum = 0; for (auto i: nums) { sum += i; } return sum - (n*(n+1))/2; } // Method 4 (Optimal) // TC: O(n) // SC: O(1) int findDuplicate4(vector<int>& nums) { int ans = 0; for (int i = 0; i < nums.size(); i++) { ans ^= (nums[i] ^ i); } return ans; } }; int main() { vector<int> arr = {1, 2, 3, 3}; Solution sol; cout << sol.findDuplicate3(arr); return 0; }
<?php /* * This file is part of the Klipper package. * * (c) François Pluchino <francois.pluchino@klipper.dev> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Klipper\Component\Security\Tests\Authorization\Expression; use Klipper\Component\Security\Authorization\Expression\IsBasicAuthProvider; use PHPUnit\Framework\TestCase; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Component\Security\Core\User\UserInterface; /** * @author François Pluchino <francois.pluchino@klipper.dev> * * @internal */ final class IsBasicAuthProviderTest extends TestCase { public function testIsBasicAuth(): void { $user = $this->getMockBuilder(UserInterface::class)->getMock(); $token = new UsernamePasswordToken($user, 'test', ['ROLE_USER']); $trustResolver = new AuthenticationTrustResolver(); $expressionLanguage = new ExpressionLanguage(null, [new IsBasicAuthProvider()]); $variables = [ 'token' => $token, 'trust_resolver' => $trustResolver, ]; static::assertTrue($expressionLanguage->evaluate('is_basic_auth()', $variables)); $compiled = '$token && $token instanceof \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken && $trust_resolver->isAuthenticated($token)'; static::assertEquals($compiled, $expressionLanguage->compile('is_basic_auth()')); } }
package com.griotold.bankshop.web; import com.fasterxml.jackson.databind.ObjectMapper; import com.griotold.bankshop.config.dummy.DummyObject; import com.griotold.bankshop.domain.user.UserRepository; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.transaction.annotation.Transactional; import static com.griotold.bankshop.dto.user.UserReqDto.JoinReqDto; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Slf4j @ActiveProfiles("test") @Sql("classpath:db/teardown.sql") @AutoConfigureMockMvc @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) class UserControllerTest extends DummyObject { @Autowired private MockMvc mvc; @Autowired private ObjectMapper om; @Autowired private UserRepository userRepository; @BeforeEach public void setUp() { dataSetting(); } private void dataSetting() { userRepository.save(newUser("griotold", "고리오영감")); } @Test @DisplayName("회원가입 성공") void join_success_test() throws Exception{ // given JoinReqDto joinReqDto = new JoinReqDto(); joinReqDto.setUsername("love"); joinReqDto.setPassword("1234"); joinReqDto.setEmail("love@nate.com"); joinReqDto.setFullName("러브"); joinReqDto.setAddress("믿음시 소망구 인내동 456번지"); String requestBody = om.writeValueAsString(joinReqDto); // when ResultActions resultActions = mvc.perform(post("/api/join") .content(requestBody) .contentType(MediaType.APPLICATION_JSON)); String responseBody = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("responseBody = " + responseBody); // then resultActions.andExpect(status().isCreated()); } @Test @DisplayName("회원가입 실패 - 이미 있는 username") void join_fail_test() throws Exception { // given JoinReqDto joinReqDto = new JoinReqDto(); joinReqDto.setUsername("griotold"); joinReqDto.setPassword("1234"); joinReqDto.setEmail("griotold@nate.com"); joinReqDto.setFullName("고리오영감"); joinReqDto.setAddress("행복시 희망구 사랑동 123번지"); String requestBody = om.writeValueAsString(joinReqDto); // when ResultActions resultActions = mvc.perform(post("/api/join") .content(requestBody) .contentType(MediaType.APPLICATION_JSON)); String responseBody = resultActions.andReturn().getResponse().getContentAsString(); // then resultActions.andExpect(status().isBadRequest()); } @Test @DisplayName("정규표현식 체크 - 이메일 형식") void regExp_test() throws Exception{ // given JoinReqDto joinReqDto = new JoinReqDto(); joinReqDto.setUsername("kandela"); joinReqDto.setPassword("5678"); joinReqDto.setEmail("kandela123"); joinReqDto.setFullName("칸델라"); joinReqDto.setAddress("세종시 에코구 전등동 456번지"); String requestBody = om.writeValueAsString(joinReqDto); // when ResultActions resultActions = mvc.perform(post("/api/join") .content(requestBody) .contentType(MediaType.APPLICATION_JSON)); String responseBody = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("responseBody = " + responseBody); // then resultActions.andExpect(status().isBadRequest()); } }
import React, { useEffect, useState } from 'react' import { useParams } from 'react-router-dom' import { toast } from "react-toastify"; const JobDetail = () => { const params = useParams(); const {jobId} = params; console.log(jobId) const [jobDetail, setJobDetail] = useState({}) const fetchJobs = async()=>{ const myJob = await fetch(`http://localhost:3000/job/api/get-jobdetail/${jobId}`, {credentials: "include"}); const res = await myJob.json(); setJobDetail(res.jobDetail) } useEffect(()=>{ fetchJobs() }, []) const ApplyForJob = async(e)=>{ e.preventDefault(); const myJob = await fetch(`http://localhost:3000/user/api/apply-job/${jobId}`, {credentials: "include"}); const res = await myJob.json(); if(res.status){ toast.success(res.message) }else{ toast.error(res.message) } } return ( // <!-- Job Details Page --> <div id="job-details" className="container mx-auto my-8 bg-white p-6 rounded shadow"> <h2 className="text-2xl font-bold">Job Title: {jobDetail.jobTitle}</h2> <p className="mt-2 text-gray-600">Company: Tech Corp</p> <p className="text-gray-600">Location: {jobDetail.location}</p> <p className="text-gray-600">Salary: {jobDetail.salary}</p> <h3 className="mt-4 text-xl font-semibold">Job Description:</h3> <p className="mt-2 text-gray-600">{jobDetail.jobDesc}</p> <button onClick={ApplyForJob} className="bg-blue-600 text-white px-4 py-2 rounded mt-4">Apply Now</button> </div> ) } export default JobDetail
import { newSpecPage } from '@stencil/core/testing'; import { IconUserPlus } from '../user-plus'; import { createElement, UserPlus } from 'lucide'; describe('icon-user-plus', () => { it('renders', async () => { const page = await newSpecPage({ components: [IconUserPlus], html: `<icon-user-plus></icon-user-plus>`, }); const svg = createElement(UserPlus); expect(page.root).toEqualHtml(` <icon-user-plus class="st-lucide-icon" innerhtml="${svg.outerHTML.replaceAll('"', '&quot;')}"> ${svg.outerHTML} </icon-user-plus> `); }); it('forwards one-word props to svg', async () => { const page = await newSpecPage({ components: [IconUserPlus], html: `<icon-user-plus stroke="blue"></icon-user-plus>`, }); const svg = createElement(UserPlus); svg.setAttribute('stroke', 'blue'); expect(page.root).toEqualHtml(` <icon-user-plus class="st-lucide-icon" innerhtml="${svg.outerHTML.replaceAll('"', '&quot;')}" stroke="blue"> ${svg.outerHTML} </icon-user-plus> `); }); it('forwards dashed props to svg', async () => { const page = await newSpecPage({ components: [IconUserPlus], html: `<icon-user-plus stroke-width="2"></icon-user-plus>`, }); const svg = createElement(UserPlus); svg.setAttribute('stroke-width', 2); expect(page.root).toEqualHtml(` <icon-user-plus class="st-lucide-icon" innerhtml="${svg.outerHTML.replaceAll('"', '&quot;')}" stroke-width="2"> ${svg.outerHTML} </icon-user-plus> `); }); });
//Copyright 2020 Ellucian Company L.P. and its affiliates. using System; using System.Collections.Generic; using System.Linq; using Ellucian.Colleague.Domain.Student.Entities; using Ellucian.Colleague.Domain.Student.Repositories; using Ellucian.Colleague.Domain.Repositories; using Ellucian.Web.Adapters; using Ellucian.Web.Dependency; using Ellucian.Web.Security; using slf4net; using System.Threading.Tasks; using Ellucian.Colleague.Coordination.Base.Services; using Ellucian.Colleague.Domain.Base.Repositories; namespace Ellucian.Colleague.Coordination.Student.Services { [RegisterType] public class AdmissionApplicationInfluencesService : BaseCoordinationService, IAdmissionApplicationInfluencesService { private readonly IStudentReferenceDataRepository _referenceDataRepository; public AdmissionApplicationInfluencesService( IStudentReferenceDataRepository referenceDataRepository, IAdapterRegistry adapterRegistry, ICurrentUserFactory currentUserFactory, IRoleRepository roleRepository, IConfigurationRepository configurationRepository, ILogger logger) : base(adapterRegistry, currentUserFactory, roleRepository, logger, configurationRepository: configurationRepository) { _referenceDataRepository = referenceDataRepository; } /// <remarks>FOR USE WITH ELLUCIAN EEDM</remarks> /// <summary> /// Gets all admission-application-influences /// </summary> /// <returns>Collection of AdmissionApplicationInfluences DTO objects</returns> public async Task<IEnumerable<Ellucian.Colleague.Dtos.AdmissionApplicationInfluences>> GetAdmissionApplicationInfluencesAsync(bool bypassCache = false) { var admissionApplicationInfluencesCollection = new List<Ellucian.Colleague.Dtos.AdmissionApplicationInfluences>(); var admissionApplicationInfluencesEntities = await _referenceDataRepository.GetApplicationInfluencesAsync(bypassCache); if (admissionApplicationInfluencesEntities != null && admissionApplicationInfluencesEntities.Any()) { foreach (var admissionApplicationInfluences in admissionApplicationInfluencesEntities) { admissionApplicationInfluencesCollection.Add(ConvertAdmissionApplicationInfluencesEntityToDto(admissionApplicationInfluences)); } if (IntegrationApiException != null) { throw IntegrationApiException; } } return admissionApplicationInfluencesCollection; } /// <remarks>FOR USE WITH ELLUCIAN EEDM</remarks> /// <summary> /// Get a AdmissionApplicationInfluences from its GUID /// </summary> /// <returns>AdmissionApplicationInfluences DTO object</returns> public async Task<Ellucian.Colleague.Dtos.AdmissionApplicationInfluences> GetAdmissionApplicationInfluencesByGuidAsync(string guid, bool bypassCache = true) { try { return ConvertAdmissionApplicationInfluencesEntityToDto((await _referenceDataRepository.GetApplicationInfluencesAsync(bypassCache)).Where(r => r.Guid == guid).First()); } catch (KeyNotFoundException ex) { throw new KeyNotFoundException(string.Format("No admission application influence was found for GUID '{0}'", guid), ex); } catch (InvalidOperationException ex) { throw new KeyNotFoundException(string.Format("No admission application influence was found for GUID '{0}'", guid), ex); } } /// <remarks>FOR USE WITH ELLUCIAN EEDM</remarks> /// <summary> /// Converts a ApplInfluences domain entity to its corresponding AdmissionApplicationInfluences DTO /// </summary> /// <param name="source">ApplInfluences domain entity</param> /// <returns>AdmissionApplicationInfluences DTO</returns> private Ellucian.Colleague.Dtos.AdmissionApplicationInfluences ConvertAdmissionApplicationInfluencesEntityToDto(ApplicationInfluence source) { var admissionApplicationInfluences = new Ellucian.Colleague.Dtos.AdmissionApplicationInfluences(); admissionApplicationInfluences.Id = source.Guid; admissionApplicationInfluences.Code = source.Code; admissionApplicationInfluences.Title = source.Description; admissionApplicationInfluences.Description = null; return admissionApplicationInfluences; } } }
import React from 'react' import './testimonials.css' import AVTR1 from '../../assets/avatar1.jpg' import AVTR2 from '../../assets/avatar2.jpg' import AVTR3 from '../../assets/avatar3.jpg' import AVTR4 from '../../assets/avatar4.jpg' // import Swiper core and required modules import {Pagination} from 'swiper'; import { Swiper, SwiperSlide } from 'swiper/react'; // Import Swiper styles import 'swiper/css'; import 'swiper/css/pagination'; const data = [ { avatar: AVTR1, name: 'proxym-IT', review: "This post summarizes my approach to preparing for and delivering performance reviews that are fair, build trust and motivate people." }, { avatar: AVTR2, name: 'ISimm', review: "This post summarizes my approach to preparing for and delivering performance reviews that are fair, build trust and motivate people." }, { avatar: AVTR3, name: 'Esprit', review: "This post summarizes my approach to preparing for and delivering performance reviews that are fair, build trust and motivate people." }, { avatar: AVTR4, name: 'Esprit', review: "This post summarizes my approach to preparing for and delivering performance reviews that are fair, build trust and motivate people." }, ] const Testimonials = () => { return ( <section id='testimonials'> <h5>Review from clients</h5> <h2>Testimonials</h2> <Swiper className='container testimonials__container' // install Swiper modules modules={[Pagination]} spaceBetween={40} slidesPerView={1} pagination={{ clickable: true }} > { data.map(({avatar, name, review}, index) => { return ( <SwiperSlide className='testimonial'> <div className='client__avatar'> <img src={avatar}/> </div> <h5 className='client__name'>{name}</h5> <small className='client__review'> {review} </small> </SwiperSlide> ) }) } </Swiper> </section> ) } export default Testimonials
\subsection{Active Reinforcement Learning} \lezione{Lezione 17}{25/11/2024} In questo caso, a differenza della passiva, non viene data alcuna policy da valutare; l'agente deve scoprire da solo la policy ottima in un ambiente totalmente sconosciuto (all'inizio). \subsubsection{Active Adaptive Dynamic Programming} Questa versione attiva dell'ADP, \textbf{model based} consiste nel stimare il modello del mondo in qualche modo per poi poter applicare gli algoritmi di programmazione dinamica che abbiamo studiato (value iteration o policy iteration). Possiamo utilizzare diversi approcci: \paragraph{Approccio Naive.}Inizialmente si dà all'agente una policy molto banale $\pi_e$ per esplorare il mondo e, con l'esperienza appresa, costruire il modello $\langle \widehat{P},\widehat{R} \rangle$ e infine applicarci su un algoritmo di Dynamic Programming. Il principale \textbf{problema} è che l'esperienza ottenuta, e quindi il modello del mondo, sarà \textbf{fortemente influenzato} dalla policy $\pi_e$ che abbiamo fornito, per cui alcuni stati potrebbero non venir mai scoperti. \paragraph{Approccio Random.}Piuttosto che fornire una policy banale, l'agente deve esplorare l'ambiente eseguendo \textbf{azioni casuali}. In questa maniera siamo sicuri che, in un tempo sufficientemente grande, l'agente \textbf{esplori tutte possibilità}. Il principale \textbf{problema} di quest'approccio è che anche quando l'agente ha una stima del mondo molto affidabile, questo continuerà a eseguire azioni random, per cui non massimizzerà mai i reward (\textbf{massima exploration, minima exploitation}). In particolare, nostro obiettivo è di minimizzare il \textbf{regret}, ossia la differenza tra il reward ottenuto e la policy di riferimento. \paragraph{Approccio Greedy.} Ad ogni iterazione, con la policy ottima calcolata sul modello del mondo esplorato al passo precedente, esploro il mondo. Con l'esperienza ottenuta, calcolo una nuova stima del modello e calcolo la policy ottima da usare al prossimo passo. Sebbene l'approccio converga ad una policy, non è detto che la policy ottenuta sia ottima, perchè l'agente è \textbf{greedy}, ossia ricerca sempre \textbf{l'ottimo locale}, cioè l'ottimo circoscritto al modello del mondo appena osservato. \paragraph{Approccio $\varepsilon-$Greedy.} Con questa variante, dato un $0 \leq \varepsilon \leq 1$, ad ogni iterazione si esplora tramite la \textbf{policy ottima} con probabilità $\varepsilon$ o esploro tramite \textbf{azioni random} con probabilità $1 - \varepsilon$. Anche in questo caso, una volta stimato $\langle \widehat{P},\widehat{R} \rangle$, si calcola la policy ottima e si riparte. Quest'approccio garantisce di convergere, ma molto lentamente, poichè anche dopo molte iterazioni (e quindi con stime affidabili del modello), l'agente continuerà ad eseguire azioni random con probabilità $1 -\varepsilon$. Potremmo, come avevamo fatto per il TD Learning, far diminuire $\epsilon$ in funzione delle iterazioni $k$. \paragraph{Approccio con Funzione di Esplorazione.} Piuttosto che scegliere con una certa probabilità l'azione random e con la sua complementare l'azione ottima, potremmo incorporare entrambe costruendo una policy che deve ottimizzare la \textbf{combinazione di exploration e exploitation}. In questo caso, le azioni con buoni reward vengono ancora predilette, tuttavia vengono dati dei \textbf{bonus} agli stati \textbf{poco esplorati}; è come se l'agente fosse curioso di esplorarli, curiosità che col tempo decrescerà. La modellazione matematica della \textit{"curiosità"} è espressa dalla \textbf{funzoone di esplorazione} $f(u,n)$: \begin{equation} f(u,n) = u + \frac{v^+}{1 + n} \end{equation} Dove: \begin{itemize} \item $u$ è il reward dello stato \item $n$ è il numero di visite di quello stato \item $v^+$ è un parametro positivo per bilanciare \textbf{exploration/exploitation} \end{itemize} Man mano che $n$ cresce, il termine $\frac{v^+}{1 + n}$ decresce, per cui, all'infinito, la funzione di esplorazione dello stato convergerà al reward dello stesso stato. Con la funzione di esplorazione il \textbf{Bellman Update} sarà: \begin{equation} V_{k + 1}(s) \leftarrow \max_a \{f(\underbrace{\sum_{s'} \widehat{P}(s' | s,a)\left[\widehat{R}(s,a,s') + \gamma V_k(s')\right]}_{Q(s,a)}, \#(s,a))\} \end{equation} Dunque, man mano che $\#(s,a)$ aumenta, $f(Q(s,a),\#(s,a))$ converge a $Q(s,a)$. \subsubsection{Q-Learning} Un'altra classe di algoritmi è la \textbf{Active Model-Free Learning}. A differenza dell'Active ADP, quest'approccio all' Active Reinforcement Learning punta \textbf{solo} a trovare la policy ottima e non a stimare il mondo, ossia vuole calcolare: \begin{equation} \pi^* = \arg \max_a Q(s,a) \end{equation} L'algoritmo principe di questa classe di algoritmi è il \textbf{Q-Learning}: \paragraph{Algoritmo Q-Learning} \begin{enumerate} \item Allo stato $s$, l'agente osserva $s$ e, se non l'ha mai visitato, prima inizializza $\#(s,a) = 0$ $ Q(s,a) = 0$ $ \forall a$. In questo caso scelgo $a$ in maniera arbitraria. \item Eseguo $a$, registro il reward della transizione $R(s \xrightarrow{a} s')$ e incremento $\#(s,a) = 0$. A questo punto possiamo correggere la stima di Q: \begin{equation} \label{eq: stimaQ} z = R + \gamma \max_{a'}Q(s',a') \end{equation} \item Se $s'$ non è stato mai osservato prima, inizializzo tutto ($\#(s,a) = 0$ $ Q(s,a) = 0$ $ \forall a$) \item Faccio Update di $Q(s,a)$ sulla base di quanto osservato in questa maniera: \begin{equation} Q(s,a) \leftarrow Q(s,a) + \underbrace{\alpha(\#(s,a))}_{\text{learning rate}}(\underbrace{z - Q(s,a)}_{\text{correzione}}) \end{equation} \item Riparto dalla (2) \end{enumerate} Anche in questo caso dovremmo adottare un $\alpha$ in funzione del numero di iterazioni per far si che all'inizio prevalga l'exploration e verso la fine l'exploitation. Dobbiamo ora puntare l'attenzione su $z$: la sua definizione è \textit{il reward di a + il reward massimo ottenibile allo stato s' raggiunto tramite a}. Questo \textit{sguardo in avanti} rappresenta la parte peculiare di questo algoritmo, perchè stiamo valutando l'azione sapendo che al prossimo stato eseguiremo l'azione ottima, che non è necessariamente prescritta dalla policy che abbiamo calcolato. Per questo motivo, il q-learning è anche detto \textbf{Metodo Off-Policy.} \paragraph{Scelta prossima azione} Tra le tante possibilità, possima implementare la scelta della prossima azione con la \textbf{funzione di esplorazione}, cioè scegliendo l'azione che massimizza la $f$: \begin{equation} a \leftarrow \arg \max_a' f(Q(s',a'), \#(s',a')) \end{equation} Il punto di forza di Q-Learning è che è un metodo off-policy, ossia un'azione la scegliamo ipotizzando che da quel momento in poi sceglieremo sempre quella che massimizza il reward. Quindi update e prossima azione sono \textbf{indipendenti}. \subsection{SARSA} Se il Q-Learning è un algoritmo d'apprendimento off-policy, cioè che per funzionare deve effettuare una fase d'addestramento e poi può lavorare, il SARSA, essendo un algoritmo \textbf{On-Policy}, cerca sempre l'ottimo al momento dell'esplorazione, senza alcun addestramento precedente. L'\textbf{update} è il seguente: \begin{equation} Q(s,a) \leftarrow Q(s,a) + \alpha(\#(s,a))(R + \gamma Q(a',s') - Q(s,a)) \end{equation} Quindi la grande differenza è che, se i metodi off-policy cercano sempre di agiure con l'ipotesi di fare successivamente \textbf{sempre ottime} (anche se tali azioni non vengono scelte, magari perchè l'agente ha bisogno di esplorare), i metodi on-policy possono solo considerare le azioni che massimizzano la funzione d'esplorazione (e quindi le azioni possono non essere ottime). \subsection{Convergenza dell'Active RL} Possiamo dire per qualsiasi algoritmo di Active Reinforcement Learning, che la convergenza all'ottimo si raggiunge solo se si soddisfano 2 condizioni: \begin{itemize} \item Infinite Exploration \item Greedy in the Limit \end{itemize} \paragraph{Infinite Exploration(IE).}L'avevamo già incontrato per verificare la convergenza del TD Learning. Se la \textit{learning rate} dell'algoritmo soddisfa la IE, allora per $t\to +\infty$ l'agente avrà esplorato tutte le coppie <stato,azione> infinite volte. Le condizioni sono: \begin{gather*} \sum_{n = 1}^{+\infty} \alpha(n) = +\infty\\ \sum_{n = 1}^{+\infty} \alpha^2(n) < \infty \end{gather*} \paragraph{Greedy in the Limit(GL).}Una volta che le $Q(s,a)$ si sono stabilizzate per ogni coppia <stato,azione> è necessario che l'algoritmo scelga sempre l'azione ottima e non azioni random, altrimenti non si converge alla policy ottima. Dunque, per $t \to \infty$ $\pi^* = \pi_\text{greedy}$. In definitiva, un algoritmo \textit{"funziona"} se è solo se rispetta le GLIE. Riporto ora un esempio: \paragraph{Boltzman Exploration.}Questa funzione di esplorazione si presenta nella seguente forma: \begin{equation} \pi_e(s) \sim P(a | s) = \frac{e^{\frac{Q_t(s,a)}{\tau}}}{\sum_{b} e^{\frac{Q_t(s,b)}{\tau}}} \end{equation} Dove $\tau$ è detta \textbf{temperatura}; analizziamo i vari casi: \begin{itemize} \item Per temperature \textbf{molto alte}: gli esponenti tenderanno a 0, per cui la funzione corrisponderà a: \begin{equation} \pi_e(s) = \frac{1}{\sum_{b}} \end{equation} Ossia la distribuzione del \textbf{uniforme discreto} (esploro a caso) \item per temperature \textbf{molto basse}: gli esponenti cresceranno all'infinito; il valore che non viene annullato è quello che ha il $Q(s,a)$ più alto, per cui ci sarà il $100\%$ di probabilità di scegliere quella mossa. \end{itemize} Facendo partire l'algoritmo con temperature molto alte e abbassandole man mano, si può dimostrare che vengono rispettate sia la IE che la GL. \subsection{Limiti del Reinforcement Learning} Il limite che tutti gli algoritmi di Reinforcement Learning condividono è la \textbf{quantità di esplorazione prima di convergere all'ottimo}, oltre al fatto di tenere in memoria una rappresentazione almeno delle tabelle di $Q(s,a)$ o di $V(s,a)$. Per uno spazio degli stati superiori a $10^6$, il RL è \textbf{impraticabile}. Sono necessari allora dei modi per \textbf{generalizzare} a partire da un training set molto ridotto, in modo da poter applicare quest'esperienza per molti altri \textit{input} che l'agente non ha mai visto. L'argomento è così importante che esiste una grande branca dell'Intelligenza Artificiale detta \textbf{Machine Learning}. \subsection{Generalizzare in Reinforcement Learning} Per generalizzare in questo contesto potremmo usare uno strumento che avevamo già usato in passato per MINIMAX, ossia le \textbf{feature}. Possiamo infatti \textbf{assumere} che una \textbf{action value function} sia rappresentabile che combinazione lineare di feature, ossia: \begin{equation} Q(s,a) = \theta_0 + \theta_1f_1(s,a) + \dots + \theta_nf_n(s,a) \end{equation} Dove le varie feature stimano la Q in base ad una particolare caratteristica della coppia <stato,azione> (NB: spesso la Q non è rappresentabile in questa maniera, ma pensarla così ci permette di semplificare molti calcoli). Quindi, dati: \begin{itemize} \item un vettore $x_i = \langle f_1(s,a), \dots, f_n(s,a)\rangle $ di feature all'i-esima transizione \item L'esperienza $z_i$ all'iesima transizione \end{itemize} L'agente deve risolvere un problema di \textbf{regressione lineare} in modo da \textit{adattare} il vettore di feature all'output atteso dell'esperienza. Quest'approccio al Reinforcement Learning è detto \textbf{Supervised Learning}.
import { Order } from "../database/model/model"; import OkxDAO from "../integration/okx-dao"; import { OrdersSide } from "../utils/enums"; export default class OkxService { okxDAO: OkxDAO; fee: number; spread: number; expiration: number; constructor() { this.okxDAO = new OkxDAO(); this.fee = Number(process.env.BELO_FEE!); this.spread = Number(process.env.BELO_SPREAD!); this.expiration = Number(process.env.EXPIRATION_MS!) } addFees (price: number) { price += price * this.spread; price += price * this.fee; return price; } calculatePrice (orders: Array<Array<string>>, volume: number) { let count = 0; let price = 0; for(const order of orders) { if(count < volume) { const partial = count + Number(order[1]); if(partial >= volume) { price += Number(order[0]) * Number(volume - count) / volume; count = volume; } else { count += Number(order[1]); price += Number(order[0]) * Number(order[1]) / volume; } } } return this.addFees(price).toFixed(2); } async getEstimated (pair: string, volume: number, side: OrdersSide) { if(volume <= 0) throw new Error('Volume must be greater than 0') if(side !== OrdersSide.buyer && side !== OrdersSide.seller) throw new Error('Invalid side'); const { asks, bids, error } = await this.okxDAO.getOrders(pair); if(error) throw new Error(error); const price = this.calculatePrice(side === OrdersSide.buyer ? bids : asks, volume); const order = await Order.create({ price, volume, pair, side, date_created: Date.now(), executed: false, }) return { volume, priceEstimated: price, pair, orderId: order.returnId() }; } async swapOrder (orderId: string) { const orderById = await Order.findOne({ where: { id: orderId }}); if(!orderById) throw new Error('Order ID not found'); const { dataValues } = orderById; const isExpired = Number(Date.now()) - Number(dataValues.date_created) > this.expiration; if(isExpired) throw new Error('Order ID expired'); const { pair, volume, side, executed, id } = dataValues; if(executed) throw new Error('Order ID was already executed'); const { code, data } = await this.okxDAO.swap(dataValues); if(code !== '0') throw new Error(data[0].sMsg); const detailSwap = await this.okxDAO.detailSwap(data[0].ordId, pair); const executedPrice = Number(detailSwap.data[0].fillPx); await Order.update({ executed: true }, { where: { id }}); return { idTransaction: data[0].ordId, pair, volume, side, price: this.addFees(executedPrice).toFixed(2), }; } }
#!/bin/bash ruta="$(pwd)" # Localiza ficheros en un directorio que tengan la extensión .sh # y muestra información sobre ellos usando el comando stat # Las opciones utilizadas son: # -type: para buscar por tipo de archivo (f) # -name: para buscar por nombre # -print0: para mostrar los resultados en formato nulo (útil para xargs) # Los resultados encontrados por find son pasados a xargs para # ejecutar el comando stat con cada uno de ellos # La opción -0 de xargs indica que los resultados de find están # en formato nulo (delimitados por \0) find "$ruta" -type f -name "*.sh" -print0 | xargs -0 stat
package kz.techorda.finalTaskNews.models; import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; @Entity @Table(name = "t_posts") @Getter @Setter public class Post extends BaseModel{ @Column(name = "title") private String title; @Column(name = "content", columnDefinition = "TEXT") private String content; @Column(name = "post_time") private String postTime; @ManyToOne private User user; @ManyToOne private NewsCategory newsCategory; @OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE) private List<Comment> comments = new ArrayList<>(); @PrePersist public void prePersist() { LocalDateTime dateTime = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); postTime = dateTime.format(formatter); } }
--- title: New FCP X The Ultimate Guide to Creating Realistic Green Screen Composites date: 2024-05-19T10:32:13.760Z updated: 2024-05-20T10:32:13.760Z tags: - video editing software - video editing categories: - ai - video description: This Article Describes New FCP X The Ultimate Guide to Creating Realistic Green Screen Composites excerpt: This Article Describes New FCP X The Ultimate Guide to Creating Realistic Green Screen Composites keywords: the ultimate guide to calculating screen resolution ratios,fcp x pro tutorials creating realistic green screen effects,the ultimate guide to calculating screen aspect ratios,fcp x the ultimate guide to creating realistic green screen composites,the ultimate guide to compressor settings in fcpx,fcp x visual effects how to create seamless green screen composites,the ultimate guide to green screen software for mac users thumbnail: https://www.lifewire.com/thmb/HNtneePKuJeaZXX7qZjEwvmSz6M=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/Flora_and_Son-f6517d3de531487e89f5e0e99192d13f.jpg --- ## FCP X: The Ultimate Guide to Creating Realistic Green Screen Composites # FCP X: Create a Chroma-Key (Green-screen) Effect ![author avatar](https://images.wondershare.com/filmora/article-images/benjamin-arango-author.jpg) ##### Benjamin Arango Mar 27, 2024• Proven solutions Chroma-key (also called "green screen") effects are a staple in video production. What [FCP X effect](https://tools.techidaily.com/wondershare/filmora/download/)does is allow you to make the background behind an actor transparent so you can place the actor into a different environment than a studio. --- This is a basic tutorial about Apple Final Cut Pro X, professional video editing software. However, if video editing is new to you, consider [Wondershare Filmora for Mac](https://tools.techidaily.com/wondershare/filmora/download/). This is a powerful but easy-to-use tool for users just starting out. Download the free trial version below. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) --- ## Getting Started First, the best thing you can do to improve the quality of your keys is to improve how you shoot them. Here are seven basic production rules: * Actors should be at least 10 feet in front of the green screen. This avoids light from the background "spilling" around their body or shoulders. * In general, don't cast shadows on the green screen. Be very careful shooting feet. * The green background should be as smooth as possible. Paint is always better than fabric; avoid wrinkles and folds. * The green background should be lit smoothly, both from side to side and top to bottom. I try to have the green background display between 40-50% level on the waveform monitor. * There is NO relationship between how the background is lit and how your actors are lit. This article will illustrate that. * Light your background for smoothness. Light your actors for drama. * Don't worry about having the green background fill the frame. It only needs to completely surround the edges of your actors. Garbage mattes are used to get rid of junk around the edges. ## Setting up the Key ![fx chroma 01](https://images.wondershare.com/multimedia/fx-chroma-01.jpg) The green screen image is always placed above the background. You can place either the green screen or background image into the Primary Storyline. I find it easier to put the background in the Primary Storyline, because it makes editing the green screen image easier. But this is purely personal choice. **Step 1: Select the green screen clip** From the **Effects Browser > Keying** category, double-click the **Keyer** effect, which applies it to the selected clip. (You can also drag the effect on top of the clip, if you forgot to select the green-screen clip first.) ![fx chroma 02](https://images.wondershare.com/multimedia/fx-chroma-02.jpg) Don't panic if your image looks weird – we will fix it. ![fx chroma 03](https://images.wondershare.com/multimedia/fx-chroma-03.jpg) Click the **Sample Color** icon. This allows fine-tuning the selection of the background color. ![fx chroma 04](https://images.wondershare.com/multimedia/fx-chroma-04.jpg) In the green-screen image, drag to select a representative section of the background. I try to get close to the face, but not so close that I accidentally select loose hair or skin. Your key should look better immediately. Most of the time, you can probably stop here. But there are three other adjustments that can make your key look even better: * Cleaning up the matte * Edge adjustments * Light wrap ![fx chroma 06](https://images.wondershare.com/multimedia/fx-chroma-06.jpg) Click the **Matte** button to display your key as a white foreground on a black background. ![fx chroma 07](https://images.wondershare.com/multimedia/fx-chroma-07.jpg) Your goal is the make the foreground solid white, which means opaque, and the background solid black, which means transparent. Adjust the **Fill Holes** and **Edge Distance** sliders until your key looks solid. (For REALLY bad keys, you'll need to also adjust Color Selection, mentioned below.) ![fx chroma 05](https://images.wondershare.com/multimedia/fx-chroma-05.jpg) If an edge is too pronounced, or needs help, click the **Edges** icon. ![fx chroma 09](https://images.wondershare.com/multimedia/fx-chroma-09.jpg) **Step 2: Tweaks Video** Then, click and drag a line from the foreground to the background in the Canvas. Drag the midpoint slider (where my cursor is) until the edge looks the best it can. Different video formats make this easy (ProRes), while others (HDV, avchd) make this much harder. Perfection is impossible – do the best you can. ![fx chroma 09a](https://images.wondershare.com/multimedia/fx-chroma-09a.jpg) Final Cut provides four additional tweaks at the bottom of the keyer filter: * Color Selection * Matte Tools * Spill Suppression * Light Wrap The first three are designed to clean up poorly shot keys – read the FCP X Help files to learn how these work. (I used the Color Selection tools to clean up the very dark key I use an example later in this article.) Light wrap, though, is aesthetic. What it does is blend colors from the background into the edges of the foreground, to make the entire key look more "organic," as if the foreground and background were actually in the same space. This is a subtle effect, but very cool. ![fx chroma 10](https://images.wondershare.com/multimedia/fx-chroma-10.jpg) Twirl down Light Wrap and adjust the Amount slider and watch what happens. Drag the other sliders around and see what happens. The nice thing about this setting is that when it looks good to you, it is good. The amount of the effect is totally up to you. Remember, Light Wrap only affects the edges of the foreground and should be used subtly. ![fx chroma 11](https://images.wondershare.com/multimedia/fx-chroma-11.jpg) When you are done, you have a great looking key! ## Clean up the Image with a Garbage Mask ![fx chroma 12](https://images.wondershare.com/multimedia/fx-chroma-12.jpg) Sometimes, however, you don't have, ah, perhaps, the best green-screen image to work with. Here, for example, there are lighting instruments in the foreground, with a very inadequately lit green screen in the background. (Sigh… this is just pitiful.) Once you pull the key – which is film-speak for creating a green-screen shot, as I described above – and get it looking as good as possible, there's one more step: adding a garbage matte to get rid of all the garbage surrounding your actors. ![fx chroma 13](https://images.wondershare.com/multimedia/fx-chroma-13.jpg) Once you get your key looking as good as you can – which in this case isn't all that good – drag the Mask effect (**Effects > Keying > Mask**) on top of the green-screen clip. **NOTE**: The Mask effect should always be added after the Keying effect, so that the Mask is below the Keyer in the Inspector. ![fx chroma 14](https://images.wondershare.com/multimedia/fx-chroma-14.jpg) Then, drag each of the four circles to create a shape such that your foreground image is contained inside it, and everything you want to exclude is outside. Here, for instance, we removed the light stand, the edge of the green background and the tearing at the top of the image. I've found this Mask effect works best when applied to a connected clip. However, the big limitation of the Mask effect is that you only have four points to work with. That's where a free effect comes in, which allows you to create far more flexible shapes with it. It's written by Alex Gollner and is available on his website – alex4d.wordpress.com/fcpx/ – I recommend his effects highly. ## How to Create a Chroma-Key in easier ways? Chroma-key, or green screen, is an essential part of every editor to make all kinds of effects. Is there any way to make this sophisticated procedure easier way? Yes, try Filmora. In version 10.5 for Mac, Filmora added a new feature: AI portrait. It allows you to do a green screen effect with just one click. By adopting AI portrait, you can add those stunning effects in simple steps: How to Remove or Change Video Background in One Step? Or: [How to Add a Shake Effect to your Videos?](https://tools.techidaily.com/wondershare/filmora/download/) ## Conclusion The chroma-key filter in FCP X allows us to create some amazing effects. If you want to use green screen effects more easily, here is [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) for you. You can appaly Chroma-Key effects with just a few click. Have fun playing with it. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/benjamin-arango-author.jpg) Benjamin Arango Benjamin Arango is a writer and a lover of all things video. Follow @Benjamin Arango ##### Benjamin Arango Mar 27, 2024• Proven solutions Chroma-key (also called "green screen") effects are a staple in video production. What [FCP X effect](https://tools.techidaily.com/wondershare/filmora/download/)does is allow you to make the background behind an actor transparent so you can place the actor into a different environment than a studio. --- This is a basic tutorial about Apple Final Cut Pro X, professional video editing software. However, if video editing is new to you, consider [Wondershare Filmora for Mac](https://tools.techidaily.com/wondershare/filmora/download/). This is a powerful but easy-to-use tool for users just starting out. Download the free trial version below. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) --- ## Getting Started First, the best thing you can do to improve the quality of your keys is to improve how you shoot them. Here are seven basic production rules: * Actors should be at least 10 feet in front of the green screen. This avoids light from the background "spilling" around their body or shoulders. * In general, don't cast shadows on the green screen. Be very careful shooting feet. * The green background should be as smooth as possible. Paint is always better than fabric; avoid wrinkles and folds. * The green background should be lit smoothly, both from side to side and top to bottom. I try to have the green background display between 40-50% level on the waveform monitor. * There is NO relationship between how the background is lit and how your actors are lit. This article will illustrate that. * Light your background for smoothness. Light your actors for drama. * Don't worry about having the green background fill the frame. It only needs to completely surround the edges of your actors. Garbage mattes are used to get rid of junk around the edges. ## Setting up the Key ![fx chroma 01](https://images.wondershare.com/multimedia/fx-chroma-01.jpg) The green screen image is always placed above the background. You can place either the green screen or background image into the Primary Storyline. I find it easier to put the background in the Primary Storyline, because it makes editing the green screen image easier. But this is purely personal choice. **Step 1: Select the green screen clip** From the **Effects Browser > Keying** category, double-click the **Keyer** effect, which applies it to the selected clip. (You can also drag the effect on top of the clip, if you forgot to select the green-screen clip first.) ![fx chroma 02](https://images.wondershare.com/multimedia/fx-chroma-02.jpg) Don't panic if your image looks weird – we will fix it. ![fx chroma 03](https://images.wondershare.com/multimedia/fx-chroma-03.jpg) Click the **Sample Color** icon. This allows fine-tuning the selection of the background color. ![fx chroma 04](https://images.wondershare.com/multimedia/fx-chroma-04.jpg) In the green-screen image, drag to select a representative section of the background. I try to get close to the face, but not so close that I accidentally select loose hair or skin. Your key should look better immediately. Most of the time, you can probably stop here. But there are three other adjustments that can make your key look even better: * Cleaning up the matte * Edge adjustments * Light wrap ![fx chroma 06](https://images.wondershare.com/multimedia/fx-chroma-06.jpg) Click the **Matte** button to display your key as a white foreground on a black background. ![fx chroma 07](https://images.wondershare.com/multimedia/fx-chroma-07.jpg) Your goal is the make the foreground solid white, which means opaque, and the background solid black, which means transparent. Adjust the **Fill Holes** and **Edge Distance** sliders until your key looks solid. (For REALLY bad keys, you'll need to also adjust Color Selection, mentioned below.) ![fx chroma 05](https://images.wondershare.com/multimedia/fx-chroma-05.jpg) If an edge is too pronounced, or needs help, click the **Edges** icon. ![fx chroma 09](https://images.wondershare.com/multimedia/fx-chroma-09.jpg) **Step 2: Tweaks Video** Then, click and drag a line from the foreground to the background in the Canvas. Drag the midpoint slider (where my cursor is) until the edge looks the best it can. Different video formats make this easy (ProRes), while others (HDV, avchd) make this much harder. Perfection is impossible – do the best you can. ![fx chroma 09a](https://images.wondershare.com/multimedia/fx-chroma-09a.jpg) Final Cut provides four additional tweaks at the bottom of the keyer filter: * Color Selection * Matte Tools * Spill Suppression * Light Wrap The first three are designed to clean up poorly shot keys – read the FCP X Help files to learn how these work. (I used the Color Selection tools to clean up the very dark key I use an example later in this article.) Light wrap, though, is aesthetic. What it does is blend colors from the background into the edges of the foreground, to make the entire key look more "organic," as if the foreground and background were actually in the same space. This is a subtle effect, but very cool. ![fx chroma 10](https://images.wondershare.com/multimedia/fx-chroma-10.jpg) Twirl down Light Wrap and adjust the Amount slider and watch what happens. Drag the other sliders around and see what happens. The nice thing about this setting is that when it looks good to you, it is good. The amount of the effect is totally up to you. Remember, Light Wrap only affects the edges of the foreground and should be used subtly. ![fx chroma 11](https://images.wondershare.com/multimedia/fx-chroma-11.jpg) When you are done, you have a great looking key! ## Clean up the Image with a Garbage Mask ![fx chroma 12](https://images.wondershare.com/multimedia/fx-chroma-12.jpg) Sometimes, however, you don't have, ah, perhaps, the best green-screen image to work with. Here, for example, there are lighting instruments in the foreground, with a very inadequately lit green screen in the background. (Sigh… this is just pitiful.) Once you pull the key – which is film-speak for creating a green-screen shot, as I described above – and get it looking as good as possible, there's one more step: adding a garbage matte to get rid of all the garbage surrounding your actors. ![fx chroma 13](https://images.wondershare.com/multimedia/fx-chroma-13.jpg) Once you get your key looking as good as you can – which in this case isn't all that good – drag the Mask effect (**Effects > Keying > Mask**) on top of the green-screen clip. **NOTE**: The Mask effect should always be added after the Keying effect, so that the Mask is below the Keyer in the Inspector. ![fx chroma 14](https://images.wondershare.com/multimedia/fx-chroma-14.jpg) Then, drag each of the four circles to create a shape such that your foreground image is contained inside it, and everything you want to exclude is outside. Here, for instance, we removed the light stand, the edge of the green background and the tearing at the top of the image. I've found this Mask effect works best when applied to a connected clip. However, the big limitation of the Mask effect is that you only have four points to work with. That's where a free effect comes in, which allows you to create far more flexible shapes with it. It's written by Alex Gollner and is available on his website – alex4d.wordpress.com/fcpx/ – I recommend his effects highly. ## How to Create a Chroma-Key in easier ways? Chroma-key, or green screen, is an essential part of every editor to make all kinds of effects. Is there any way to make this sophisticated procedure easier way? Yes, try Filmora. In version 10.5 for Mac, Filmora added a new feature: AI portrait. It allows you to do a green screen effect with just one click. By adopting AI portrait, you can add those stunning effects in simple steps: How to Remove or Change Video Background in One Step? Or: [How to Add a Shake Effect to your Videos?](https://tools.techidaily.com/wondershare/filmora/download/) ## Conclusion The chroma-key filter in FCP X allows us to create some amazing effects. If you want to use green screen effects more easily, here is [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) for you. You can appaly Chroma-Key effects with just a few click. Have fun playing with it. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/benjamin-arango-author.jpg) Benjamin Arango Benjamin Arango is a writer and a lover of all things video. Follow @Benjamin Arango ##### Benjamin Arango Mar 27, 2024• Proven solutions Chroma-key (also called "green screen") effects are a staple in video production. What [FCP X effect](https://tools.techidaily.com/wondershare/filmora/download/)does is allow you to make the background behind an actor transparent so you can place the actor into a different environment than a studio. --- This is a basic tutorial about Apple Final Cut Pro X, professional video editing software. However, if video editing is new to you, consider [Wondershare Filmora for Mac](https://tools.techidaily.com/wondershare/filmora/download/). This is a powerful but easy-to-use tool for users just starting out. Download the free trial version below. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) --- ## Getting Started First, the best thing you can do to improve the quality of your keys is to improve how you shoot them. Here are seven basic production rules: * Actors should be at least 10 feet in front of the green screen. This avoids light from the background "spilling" around their body or shoulders. * In general, don't cast shadows on the green screen. Be very careful shooting feet. * The green background should be as smooth as possible. Paint is always better than fabric; avoid wrinkles and folds. * The green background should be lit smoothly, both from side to side and top to bottom. I try to have the green background display between 40-50% level on the waveform monitor. * There is NO relationship between how the background is lit and how your actors are lit. This article will illustrate that. * Light your background for smoothness. Light your actors for drama. * Don't worry about having the green background fill the frame. It only needs to completely surround the edges of your actors. Garbage mattes are used to get rid of junk around the edges. ## Setting up the Key ![fx chroma 01](https://images.wondershare.com/multimedia/fx-chroma-01.jpg) The green screen image is always placed above the background. You can place either the green screen or background image into the Primary Storyline. I find it easier to put the background in the Primary Storyline, because it makes editing the green screen image easier. But this is purely personal choice. **Step 1: Select the green screen clip** From the **Effects Browser > Keying** category, double-click the **Keyer** effect, which applies it to the selected clip. (You can also drag the effect on top of the clip, if you forgot to select the green-screen clip first.) ![fx chroma 02](https://images.wondershare.com/multimedia/fx-chroma-02.jpg) Don't panic if your image looks weird – we will fix it. ![fx chroma 03](https://images.wondershare.com/multimedia/fx-chroma-03.jpg) Click the **Sample Color** icon. This allows fine-tuning the selection of the background color. ![fx chroma 04](https://images.wondershare.com/multimedia/fx-chroma-04.jpg) In the green-screen image, drag to select a representative section of the background. I try to get close to the face, but not so close that I accidentally select loose hair or skin. Your key should look better immediately. Most of the time, you can probably stop here. But there are three other adjustments that can make your key look even better: * Cleaning up the matte * Edge adjustments * Light wrap ![fx chroma 06](https://images.wondershare.com/multimedia/fx-chroma-06.jpg) Click the **Matte** button to display your key as a white foreground on a black background. ![fx chroma 07](https://images.wondershare.com/multimedia/fx-chroma-07.jpg) Your goal is the make the foreground solid white, which means opaque, and the background solid black, which means transparent. Adjust the **Fill Holes** and **Edge Distance** sliders until your key looks solid. (For REALLY bad keys, you'll need to also adjust Color Selection, mentioned below.) ![fx chroma 05](https://images.wondershare.com/multimedia/fx-chroma-05.jpg) If an edge is too pronounced, or needs help, click the **Edges** icon. ![fx chroma 09](https://images.wondershare.com/multimedia/fx-chroma-09.jpg) **Step 2: Tweaks Video** Then, click and drag a line from the foreground to the background in the Canvas. Drag the midpoint slider (where my cursor is) until the edge looks the best it can. Different video formats make this easy (ProRes), while others (HDV, avchd) make this much harder. Perfection is impossible – do the best you can. ![fx chroma 09a](https://images.wondershare.com/multimedia/fx-chroma-09a.jpg) Final Cut provides four additional tweaks at the bottom of the keyer filter: * Color Selection * Matte Tools * Spill Suppression * Light Wrap The first three are designed to clean up poorly shot keys – read the FCP X Help files to learn how these work. (I used the Color Selection tools to clean up the very dark key I use an example later in this article.) Light wrap, though, is aesthetic. What it does is blend colors from the background into the edges of the foreground, to make the entire key look more "organic," as if the foreground and background were actually in the same space. This is a subtle effect, but very cool. ![fx chroma 10](https://images.wondershare.com/multimedia/fx-chroma-10.jpg) Twirl down Light Wrap and adjust the Amount slider and watch what happens. Drag the other sliders around and see what happens. The nice thing about this setting is that when it looks good to you, it is good. The amount of the effect is totally up to you. Remember, Light Wrap only affects the edges of the foreground and should be used subtly. ![fx chroma 11](https://images.wondershare.com/multimedia/fx-chroma-11.jpg) When you are done, you have a great looking key! ## Clean up the Image with a Garbage Mask ![fx chroma 12](https://images.wondershare.com/multimedia/fx-chroma-12.jpg) Sometimes, however, you don't have, ah, perhaps, the best green-screen image to work with. Here, for example, there are lighting instruments in the foreground, with a very inadequately lit green screen in the background. (Sigh… this is just pitiful.) Once you pull the key – which is film-speak for creating a green-screen shot, as I described above – and get it looking as good as possible, there's one more step: adding a garbage matte to get rid of all the garbage surrounding your actors. ![fx chroma 13](https://images.wondershare.com/multimedia/fx-chroma-13.jpg) Once you get your key looking as good as you can – which in this case isn't all that good – drag the Mask effect (**Effects > Keying > Mask**) on top of the green-screen clip. **NOTE**: The Mask effect should always be added after the Keying effect, so that the Mask is below the Keyer in the Inspector. ![fx chroma 14](https://images.wondershare.com/multimedia/fx-chroma-14.jpg) Then, drag each of the four circles to create a shape such that your foreground image is contained inside it, and everything you want to exclude is outside. Here, for instance, we removed the light stand, the edge of the green background and the tearing at the top of the image. I've found this Mask effect works best when applied to a connected clip. However, the big limitation of the Mask effect is that you only have four points to work with. That's where a free effect comes in, which allows you to create far more flexible shapes with it. It's written by Alex Gollner and is available on his website – alex4d.wordpress.com/fcpx/ – I recommend his effects highly. ## How to Create a Chroma-Key in easier ways? Chroma-key, or green screen, is an essential part of every editor to make all kinds of effects. Is there any way to make this sophisticated procedure easier way? Yes, try Filmora. In version 10.5 for Mac, Filmora added a new feature: AI portrait. It allows you to do a green screen effect with just one click. By adopting AI portrait, you can add those stunning effects in simple steps: How to Remove or Change Video Background in One Step? Or: [How to Add a Shake Effect to your Videos?](https://tools.techidaily.com/wondershare/filmora/download/) ## Conclusion The chroma-key filter in FCP X allows us to create some amazing effects. If you want to use green screen effects more easily, here is [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) for you. You can appaly Chroma-Key effects with just a few click. Have fun playing with it. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/benjamin-arango-author.jpg) Benjamin Arango Benjamin Arango is a writer and a lover of all things video. Follow @Benjamin Arango ##### Benjamin Arango Mar 27, 2024• Proven solutions Chroma-key (also called "green screen") effects are a staple in video production. What [FCP X effect](https://tools.techidaily.com/wondershare/filmora/download/)does is allow you to make the background behind an actor transparent so you can place the actor into a different environment than a studio. --- This is a basic tutorial about Apple Final Cut Pro X, professional video editing software. However, if video editing is new to you, consider [Wondershare Filmora for Mac](https://tools.techidaily.com/wondershare/filmora/download/). This is a powerful but easy-to-use tool for users just starting out. Download the free trial version below. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) --- ## Getting Started First, the best thing you can do to improve the quality of your keys is to improve how you shoot them. Here are seven basic production rules: * Actors should be at least 10 feet in front of the green screen. This avoids light from the background "spilling" around their body or shoulders. * In general, don't cast shadows on the green screen. Be very careful shooting feet. * The green background should be as smooth as possible. Paint is always better than fabric; avoid wrinkles and folds. * The green background should be lit smoothly, both from side to side and top to bottom. I try to have the green background display between 40-50% level on the waveform monitor. * There is NO relationship between how the background is lit and how your actors are lit. This article will illustrate that. * Light your background for smoothness. Light your actors for drama. * Don't worry about having the green background fill the frame. It only needs to completely surround the edges of your actors. Garbage mattes are used to get rid of junk around the edges. ## Setting up the Key ![fx chroma 01](https://images.wondershare.com/multimedia/fx-chroma-01.jpg) The green screen image is always placed above the background. You can place either the green screen or background image into the Primary Storyline. I find it easier to put the background in the Primary Storyline, because it makes editing the green screen image easier. But this is purely personal choice. **Step 1: Select the green screen clip** From the **Effects Browser > Keying** category, double-click the **Keyer** effect, which applies it to the selected clip. (You can also drag the effect on top of the clip, if you forgot to select the green-screen clip first.) ![fx chroma 02](https://images.wondershare.com/multimedia/fx-chroma-02.jpg) Don't panic if your image looks weird – we will fix it. ![fx chroma 03](https://images.wondershare.com/multimedia/fx-chroma-03.jpg) Click the **Sample Color** icon. This allows fine-tuning the selection of the background color. ![fx chroma 04](https://images.wondershare.com/multimedia/fx-chroma-04.jpg) In the green-screen image, drag to select a representative section of the background. I try to get close to the face, but not so close that I accidentally select loose hair or skin. Your key should look better immediately. Most of the time, you can probably stop here. But there are three other adjustments that can make your key look even better: * Cleaning up the matte * Edge adjustments * Light wrap ![fx chroma 06](https://images.wondershare.com/multimedia/fx-chroma-06.jpg) Click the **Matte** button to display your key as a white foreground on a black background. ![fx chroma 07](https://images.wondershare.com/multimedia/fx-chroma-07.jpg) Your goal is the make the foreground solid white, which means opaque, and the background solid black, which means transparent. Adjust the **Fill Holes** and **Edge Distance** sliders until your key looks solid. (For REALLY bad keys, you'll need to also adjust Color Selection, mentioned below.) ![fx chroma 05](https://images.wondershare.com/multimedia/fx-chroma-05.jpg) If an edge is too pronounced, or needs help, click the **Edges** icon. ![fx chroma 09](https://images.wondershare.com/multimedia/fx-chroma-09.jpg) **Step 2: Tweaks Video** Then, click and drag a line from the foreground to the background in the Canvas. Drag the midpoint slider (where my cursor is) until the edge looks the best it can. Different video formats make this easy (ProRes), while others (HDV, avchd) make this much harder. Perfection is impossible – do the best you can. ![fx chroma 09a](https://images.wondershare.com/multimedia/fx-chroma-09a.jpg) Final Cut provides four additional tweaks at the bottom of the keyer filter: * Color Selection * Matte Tools * Spill Suppression * Light Wrap The first three are designed to clean up poorly shot keys – read the FCP X Help files to learn how these work. (I used the Color Selection tools to clean up the very dark key I use an example later in this article.) Light wrap, though, is aesthetic. What it does is blend colors from the background into the edges of the foreground, to make the entire key look more "organic," as if the foreground and background were actually in the same space. This is a subtle effect, but very cool. ![fx chroma 10](https://images.wondershare.com/multimedia/fx-chroma-10.jpg) Twirl down Light Wrap and adjust the Amount slider and watch what happens. Drag the other sliders around and see what happens. The nice thing about this setting is that when it looks good to you, it is good. The amount of the effect is totally up to you. Remember, Light Wrap only affects the edges of the foreground and should be used subtly. ![fx chroma 11](https://images.wondershare.com/multimedia/fx-chroma-11.jpg) When you are done, you have a great looking key! ## Clean up the Image with a Garbage Mask ![fx chroma 12](https://images.wondershare.com/multimedia/fx-chroma-12.jpg) Sometimes, however, you don't have, ah, perhaps, the best green-screen image to work with. Here, for example, there are lighting instruments in the foreground, with a very inadequately lit green screen in the background. (Sigh… this is just pitiful.) Once you pull the key – which is film-speak for creating a green-screen shot, as I described above – and get it looking as good as possible, there's one more step: adding a garbage matte to get rid of all the garbage surrounding your actors. ![fx chroma 13](https://images.wondershare.com/multimedia/fx-chroma-13.jpg) Once you get your key looking as good as you can – which in this case isn't all that good – drag the Mask effect (**Effects > Keying > Mask**) on top of the green-screen clip. **NOTE**: The Mask effect should always be added after the Keying effect, so that the Mask is below the Keyer in the Inspector. ![fx chroma 14](https://images.wondershare.com/multimedia/fx-chroma-14.jpg) Then, drag each of the four circles to create a shape such that your foreground image is contained inside it, and everything you want to exclude is outside. Here, for instance, we removed the light stand, the edge of the green background and the tearing at the top of the image. I've found this Mask effect works best when applied to a connected clip. However, the big limitation of the Mask effect is that you only have four points to work with. That's where a free effect comes in, which allows you to create far more flexible shapes with it. It's written by Alex Gollner and is available on his website – alex4d.wordpress.com/fcpx/ – I recommend his effects highly. ## How to Create a Chroma-Key in easier ways? Chroma-key, or green screen, is an essential part of every editor to make all kinds of effects. Is there any way to make this sophisticated procedure easier way? Yes, try Filmora. In version 10.5 for Mac, Filmora added a new feature: AI portrait. It allows you to do a green screen effect with just one click. By adopting AI portrait, you can add those stunning effects in simple steps: How to Remove or Change Video Background in One Step? Or: [How to Add a Shake Effect to your Videos?](https://tools.techidaily.com/wondershare/filmora/download/) ## Conclusion The chroma-key filter in FCP X allows us to create some amazing effects. If you want to use green screen effects more easily, here is [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) for you. You can appaly Chroma-Key effects with just a few click. Have fun playing with it. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/benjamin-arango-author.jpg) Benjamin Arango Benjamin Arango is a writer and a lover of all things video. Follow @Benjamin Arango <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## The Ultimate List of Free MP4 Video Cutter Tools # Top 11 Best Free MP4 Video Cutters ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) ##### Liza Brown Mar 27, 2024• Proven solutions MP4 is a video format mostly used worldwide and it's also the recommended video format if you want to upload a video to YouTube. There are times when you may need to cut your MP4 videos, for example, to cut out the unwanted parts, or to shorten the duration. The article will list top 11 free MP4 cutters for Windows, Mac and online. --- Want a fully-featured product? A commercial product like Wondershare [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a good choice. Besides the video cutting function, this video editing tool also provides various video editing tools. Now you can seamlessly put together video clips, music & text, apply effects to make a professional-looking home movie in minutes. Download and try it out. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) If you want to have an online solution, [Filmora video trimmer](https://tools.techidaily.com/wondershare/filmora/download/) is a free online tool that can help you trim video instantly. You can upload your video from computer and video link with drag-and-drop. It is easy to use with the slider or just input specific start and end times for precise trim. It also supports various importing and exporting video format, including .mp4, .mov, .wemb, .mpeg, .flv. More importantly, the exported video is free of watermark. It is definitely worth a try! --- ## Top 10 Best Free MP4 Video Cutters #### 2\. [Avidemux](http://avidemux-mswin.sourceforge.net/) Avidemux is a free open-source video editing program for Windows, Mac OS X and Linux. It comes with a well selected feature set to get your cutting, filtering and encoding tasks done. It also features a lot of interactive options and step by step guide for using this tool is there. Hence, using this tool is quite easy. ![free mp4 video croppers](https://images.wondershare.com/topic/video-editing/avidemux.jpg "free mp4 video croppers") **Pros:** * Lightweight and fairly simple; * Useful video filters. **Cons:** * Outdated interface; * May drop frames in certain formats; * Can be complicated for beginning users. #### 3\. [Lightworks](http://www.lwks.com/) This is one of the most advanced video editing or cutter tool. It features seamless options though a little complicated for the novice users. However, it is the coolest tool for serving professional purposes. It can handle large file sizes with ease. ![free mp4 video editor](https://images.wondershare.com/images/multimedia/video-editor/lightworks.jpg) **Pros:** * Various video editing options; * High video quality. **Cons:** * It crashes occasionally; * Requires a long learning curve. #### 4\. [VSDC Free Video Editor](http://vsdc-free-video-editor.software.informer.com/) It's a free video editing program which supports various video formats include MP4, AVI, MKV, MPG, WMV, FLV and more. It provides various video filters, transitions, audio effects as well as drawing and selection tools. With it, you can easily cut your MP4 files into different pieces. When the editing done, you can also select the optimized save outputs for a variety of devices, including smart phones and gaming consoles. ![top mp4 video editor](https://images.wondershare.com/images/multimedia/video-editor/vsdc-video-editor.jpg "top mp4 video editor") **Pros:** * Provides various useful filters; * Different output options. **Cons:** * Computer resources (CPU and RAM) are required at a high level. #### 5\. [iMovie](http://www.apple.com/mac/imovie/) The second position of the list will be clinched by iMovie as it is quite similar the Windows Movie Maker, compatible for MAC OS X only. In fact, this software offers a few amazing features which are absent in Windows Movie Maker. With it, you can easily cut video into pieces and edit any part of the video as you like. Truly a powerful and effective tool! File saving and export options are particularly praiseworthy. ![free mp4 video cutters](https://images.wondershare.com/topic/video-editing/imovie.jpg "free mp4 video cutters") **Pros:** * Easy-to-use and efficient; * Useful video editing functions. **Cons:** * The supported video formats are limited. #### 6\. [Free Video Cutter](http://www.freevideocutter.com/) Freemake video Cutter does exactly what its name suggests, and that is cut video. As well as MP4 it can deal with several other video formats, it uses a nice easy to follow interface and is a nice compact package that does the job well. ![Free Video Cutter](https://images.wondershare.com/multimedia/free-video-cutter.jpg) One of the easiest to use, a simple interface and good performance. #### 7\. [Freemake Video Converter](http://www.freemake.com/free%5Fvideo%5Fconverter/) Whilst, as the name suggests, this package was designed for format conversion, it includes a wealth of other abilities, one of which is video cutting, it can also rejoin and merge clips too. As a video converter, it has the largest range of format compatibility in the list and can even burn your finished videos to DVD or Blu-ray for you. The cutting feature is nicely implemented into a clear interface and should be straightforward for anyone to use. ![Freemake Video Converter](https://images.wondershare.com/multimedia/freemake-video-converter.png) An easy to use interface and a comprehensive feature set far beyond just cutting make this a great general video utility package. #### 8\. [Movica](https://sourceforge.net/projects/movica/) This package uses other open source scripting files as the mechanics of doing its job, and is in essence a user interface for those systems. That takes nothing away from it though, the tools it uses are very effective, but in their native form not something most people could take advantage of. In addition to MP4 there are several other video formats available as well as both .wma and .mp3 audio files. ![Movica](https://images.wondershare.com/multimedia/movica1.jpg) A simple interface and a more technical outlook than many, but it works well. #### 9\. [Virtualdub](http://www.virtualdub.org/) A fairly comprehensive editing package, VirtualDub has a nice selection of cutting tools enabling accurate cuts and edits with ease, covering the MP4 format as well as several others, it is a useful tool for those looking for additional features beyond just cutting. Due to the lengthy feature set the interface is a little cluttered and for those that want nothing but a cutter, is perhaps overkill, however, it does the job very well and for many presents a useful selection of video tools. ![Virtualdub](https://images.wondershare.com/multimedia/virtualdub1.png) With plenty of video tools in addition to cutting, VirtualDub presents an attractive, video toolbox for the enthusiast. #### 10\. [Online Video Cutter](https://online-video-cutter.com/) Our final offering is a slightly different take on the video cutter. This is an online offering that requires no downloads or installation, you simply go to the website, upload your video or select a video on the web, cut the video and save the output. It is very simple, although there is the obvious issue with larger files of upload and download time, but for many applications is perhaps the ideal solution. ![Online Video Cutter](https://images.wondershare.com/multimedia/onlinecutter.png) Without the need to install anything, and with a very simple interface, for smaller files is perhaps the perfect solution. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown ##### Liza Brown Mar 27, 2024• Proven solutions MP4 is a video format mostly used worldwide and it's also the recommended video format if you want to upload a video to YouTube. There are times when you may need to cut your MP4 videos, for example, to cut out the unwanted parts, or to shorten the duration. The article will list top 11 free MP4 cutters for Windows, Mac and online. --- Want a fully-featured product? A commercial product like Wondershare [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a good choice. Besides the video cutting function, this video editing tool also provides various video editing tools. Now you can seamlessly put together video clips, music & text, apply effects to make a professional-looking home movie in minutes. Download and try it out. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) If you want to have an online solution, [Filmora video trimmer](https://tools.techidaily.com/wondershare/filmora/download/) is a free online tool that can help you trim video instantly. You can upload your video from computer and video link with drag-and-drop. It is easy to use with the slider or just input specific start and end times for precise trim. It also supports various importing and exporting video format, including .mp4, .mov, .wemb, .mpeg, .flv. More importantly, the exported video is free of watermark. It is definitely worth a try! --- ## Top 10 Best Free MP4 Video Cutters #### 2\. [Avidemux](http://avidemux-mswin.sourceforge.net/) Avidemux is a free open-source video editing program for Windows, Mac OS X and Linux. It comes with a well selected feature set to get your cutting, filtering and encoding tasks done. It also features a lot of interactive options and step by step guide for using this tool is there. Hence, using this tool is quite easy. ![free mp4 video croppers](https://images.wondershare.com/topic/video-editing/avidemux.jpg "free mp4 video croppers") **Pros:** * Lightweight and fairly simple; * Useful video filters. **Cons:** * Outdated interface; * May drop frames in certain formats; * Can be complicated for beginning users. #### 3\. [Lightworks](http://www.lwks.com/) This is one of the most advanced video editing or cutter tool. It features seamless options though a little complicated for the novice users. However, it is the coolest tool for serving professional purposes. It can handle large file sizes with ease. ![free mp4 video editor](https://images.wondershare.com/images/multimedia/video-editor/lightworks.jpg) **Pros:** * Various video editing options; * High video quality. **Cons:** * It crashes occasionally; * Requires a long learning curve. #### 4\. [VSDC Free Video Editor](http://vsdc-free-video-editor.software.informer.com/) It's a free video editing program which supports various video formats include MP4, AVI, MKV, MPG, WMV, FLV and more. It provides various video filters, transitions, audio effects as well as drawing and selection tools. With it, you can easily cut your MP4 files into different pieces. When the editing done, you can also select the optimized save outputs for a variety of devices, including smart phones and gaming consoles. ![top mp4 video editor](https://images.wondershare.com/images/multimedia/video-editor/vsdc-video-editor.jpg "top mp4 video editor") **Pros:** * Provides various useful filters; * Different output options. **Cons:** * Computer resources (CPU and RAM) are required at a high level. #### 5\. [iMovie](http://www.apple.com/mac/imovie/) The second position of the list will be clinched by iMovie as it is quite similar the Windows Movie Maker, compatible for MAC OS X only. In fact, this software offers a few amazing features which are absent in Windows Movie Maker. With it, you can easily cut video into pieces and edit any part of the video as you like. Truly a powerful and effective tool! File saving and export options are particularly praiseworthy. ![free mp4 video cutters](https://images.wondershare.com/topic/video-editing/imovie.jpg "free mp4 video cutters") **Pros:** * Easy-to-use and efficient; * Useful video editing functions. **Cons:** * The supported video formats are limited. #### 6\. [Free Video Cutter](http://www.freevideocutter.com/) Freemake video Cutter does exactly what its name suggests, and that is cut video. As well as MP4 it can deal with several other video formats, it uses a nice easy to follow interface and is a nice compact package that does the job well. ![Free Video Cutter](https://images.wondershare.com/multimedia/free-video-cutter.jpg) One of the easiest to use, a simple interface and good performance. #### 7\. [Freemake Video Converter](http://www.freemake.com/free%5Fvideo%5Fconverter/) Whilst, as the name suggests, this package was designed for format conversion, it includes a wealth of other abilities, one of which is video cutting, it can also rejoin and merge clips too. As a video converter, it has the largest range of format compatibility in the list and can even burn your finished videos to DVD or Blu-ray for you. The cutting feature is nicely implemented into a clear interface and should be straightforward for anyone to use. ![Freemake Video Converter](https://images.wondershare.com/multimedia/freemake-video-converter.png) An easy to use interface and a comprehensive feature set far beyond just cutting make this a great general video utility package. #### 8\. [Movica](https://sourceforge.net/projects/movica/) This package uses other open source scripting files as the mechanics of doing its job, and is in essence a user interface for those systems. That takes nothing away from it though, the tools it uses are very effective, but in their native form not something most people could take advantage of. In addition to MP4 there are several other video formats available as well as both .wma and .mp3 audio files. ![Movica](https://images.wondershare.com/multimedia/movica1.jpg) A simple interface and a more technical outlook than many, but it works well. #### 9\. [Virtualdub](http://www.virtualdub.org/) A fairly comprehensive editing package, VirtualDub has a nice selection of cutting tools enabling accurate cuts and edits with ease, covering the MP4 format as well as several others, it is a useful tool for those looking for additional features beyond just cutting. Due to the lengthy feature set the interface is a little cluttered and for those that want nothing but a cutter, is perhaps overkill, however, it does the job very well and for many presents a useful selection of video tools. ![Virtualdub](https://images.wondershare.com/multimedia/virtualdub1.png) With plenty of video tools in addition to cutting, VirtualDub presents an attractive, video toolbox for the enthusiast. #### 10\. [Online Video Cutter](https://online-video-cutter.com/) Our final offering is a slightly different take on the video cutter. This is an online offering that requires no downloads or installation, you simply go to the website, upload your video or select a video on the web, cut the video and save the output. It is very simple, although there is the obvious issue with larger files of upload and download time, but for many applications is perhaps the ideal solution. ![Online Video Cutter](https://images.wondershare.com/multimedia/onlinecutter.png) Without the need to install anything, and with a very simple interface, for smaller files is perhaps the perfect solution. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown ##### Liza Brown Mar 27, 2024• Proven solutions MP4 is a video format mostly used worldwide and it's also the recommended video format if you want to upload a video to YouTube. There are times when you may need to cut your MP4 videos, for example, to cut out the unwanted parts, or to shorten the duration. The article will list top 11 free MP4 cutters for Windows, Mac and online. --- Want a fully-featured product? A commercial product like Wondershare [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a good choice. Besides the video cutting function, this video editing tool also provides various video editing tools. Now you can seamlessly put together video clips, music & text, apply effects to make a professional-looking home movie in minutes. Download and try it out. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) If you want to have an online solution, [Filmora video trimmer](https://tools.techidaily.com/wondershare/filmora/download/) is a free online tool that can help you trim video instantly. You can upload your video from computer and video link with drag-and-drop. It is easy to use with the slider or just input specific start and end times for precise trim. It also supports various importing and exporting video format, including .mp4, .mov, .wemb, .mpeg, .flv. More importantly, the exported video is free of watermark. It is definitely worth a try! --- ## Top 10 Best Free MP4 Video Cutters #### 2\. [Avidemux](http://avidemux-mswin.sourceforge.net/) Avidemux is a free open-source video editing program for Windows, Mac OS X and Linux. It comes with a well selected feature set to get your cutting, filtering and encoding tasks done. It also features a lot of interactive options and step by step guide for using this tool is there. Hence, using this tool is quite easy. ![free mp4 video croppers](https://images.wondershare.com/topic/video-editing/avidemux.jpg "free mp4 video croppers") **Pros:** * Lightweight and fairly simple; * Useful video filters. **Cons:** * Outdated interface; * May drop frames in certain formats; * Can be complicated for beginning users. #### 3\. [Lightworks](http://www.lwks.com/) This is one of the most advanced video editing or cutter tool. It features seamless options though a little complicated for the novice users. However, it is the coolest tool for serving professional purposes. It can handle large file sizes with ease. ![free mp4 video editor](https://images.wondershare.com/images/multimedia/video-editor/lightworks.jpg) **Pros:** * Various video editing options; * High video quality. **Cons:** * It crashes occasionally; * Requires a long learning curve. #### 4\. [VSDC Free Video Editor](http://vsdc-free-video-editor.software.informer.com/) It's a free video editing program which supports various video formats include MP4, AVI, MKV, MPG, WMV, FLV and more. It provides various video filters, transitions, audio effects as well as drawing and selection tools. With it, you can easily cut your MP4 files into different pieces. When the editing done, you can also select the optimized save outputs for a variety of devices, including smart phones and gaming consoles. ![top mp4 video editor](https://images.wondershare.com/images/multimedia/video-editor/vsdc-video-editor.jpg "top mp4 video editor") **Pros:** * Provides various useful filters; * Different output options. **Cons:** * Computer resources (CPU and RAM) are required at a high level. #### 5\. [iMovie](http://www.apple.com/mac/imovie/) The second position of the list will be clinched by iMovie as it is quite similar the Windows Movie Maker, compatible for MAC OS X only. In fact, this software offers a few amazing features which are absent in Windows Movie Maker. With it, you can easily cut video into pieces and edit any part of the video as you like. Truly a powerful and effective tool! File saving and export options are particularly praiseworthy. ![free mp4 video cutters](https://images.wondershare.com/topic/video-editing/imovie.jpg "free mp4 video cutters") **Pros:** * Easy-to-use and efficient; * Useful video editing functions. **Cons:** * The supported video formats are limited. #### 6\. [Free Video Cutter](http://www.freevideocutter.com/) Freemake video Cutter does exactly what its name suggests, and that is cut video. As well as MP4 it can deal with several other video formats, it uses a nice easy to follow interface and is a nice compact package that does the job well. ![Free Video Cutter](https://images.wondershare.com/multimedia/free-video-cutter.jpg) One of the easiest to use, a simple interface and good performance. #### 7\. [Freemake Video Converter](http://www.freemake.com/free%5Fvideo%5Fconverter/) Whilst, as the name suggests, this package was designed for format conversion, it includes a wealth of other abilities, one of which is video cutting, it can also rejoin and merge clips too. As a video converter, it has the largest range of format compatibility in the list and can even burn your finished videos to DVD or Blu-ray for you. The cutting feature is nicely implemented into a clear interface and should be straightforward for anyone to use. ![Freemake Video Converter](https://images.wondershare.com/multimedia/freemake-video-converter.png) An easy to use interface and a comprehensive feature set far beyond just cutting make this a great general video utility package. #### 8\. [Movica](https://sourceforge.net/projects/movica/) This package uses other open source scripting files as the mechanics of doing its job, and is in essence a user interface for those systems. That takes nothing away from it though, the tools it uses are very effective, but in their native form not something most people could take advantage of. In addition to MP4 there are several other video formats available as well as both .wma and .mp3 audio files. ![Movica](https://images.wondershare.com/multimedia/movica1.jpg) A simple interface and a more technical outlook than many, but it works well. #### 9\. [Virtualdub](http://www.virtualdub.org/) A fairly comprehensive editing package, VirtualDub has a nice selection of cutting tools enabling accurate cuts and edits with ease, covering the MP4 format as well as several others, it is a useful tool for those looking for additional features beyond just cutting. Due to the lengthy feature set the interface is a little cluttered and for those that want nothing but a cutter, is perhaps overkill, however, it does the job very well and for many presents a useful selection of video tools. ![Virtualdub](https://images.wondershare.com/multimedia/virtualdub1.png) With plenty of video tools in addition to cutting, VirtualDub presents an attractive, video toolbox for the enthusiast. #### 10\. [Online Video Cutter](https://online-video-cutter.com/) Our final offering is a slightly different take on the video cutter. This is an online offering that requires no downloads or installation, you simply go to the website, upload your video or select a video on the web, cut the video and save the output. It is very simple, although there is the obvious issue with larger files of upload and download time, but for many applications is perhaps the ideal solution. ![Online Video Cutter](https://images.wondershare.com/multimedia/onlinecutter.png) Without the need to install anything, and with a very simple interface, for smaller files is perhaps the perfect solution. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown ##### Liza Brown Mar 27, 2024• Proven solutions MP4 is a video format mostly used worldwide and it's also the recommended video format if you want to upload a video to YouTube. There are times when you may need to cut your MP4 videos, for example, to cut out the unwanted parts, or to shorten the duration. The article will list top 11 free MP4 cutters for Windows, Mac and online. --- Want a fully-featured product? A commercial product like Wondershare [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a good choice. Besides the video cutting function, this video editing tool also provides various video editing tools. Now you can seamlessly put together video clips, music & text, apply effects to make a professional-looking home movie in minutes. Download and try it out. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) If you want to have an online solution, [Filmora video trimmer](https://tools.techidaily.com/wondershare/filmora/download/) is a free online tool that can help you trim video instantly. You can upload your video from computer and video link with drag-and-drop. It is easy to use with the slider or just input specific start and end times for precise trim. It also supports various importing and exporting video format, including .mp4, .mov, .wemb, .mpeg, .flv. More importantly, the exported video is free of watermark. It is definitely worth a try! --- ## Top 10 Best Free MP4 Video Cutters #### 2\. [Avidemux](http://avidemux-mswin.sourceforge.net/) Avidemux is a free open-source video editing program for Windows, Mac OS X and Linux. It comes with a well selected feature set to get your cutting, filtering and encoding tasks done. It also features a lot of interactive options and step by step guide for using this tool is there. Hence, using this tool is quite easy. ![free mp4 video croppers](https://images.wondershare.com/topic/video-editing/avidemux.jpg "free mp4 video croppers") **Pros:** * Lightweight and fairly simple; * Useful video filters. **Cons:** * Outdated interface; * May drop frames in certain formats; * Can be complicated for beginning users. #### 3\. [Lightworks](http://www.lwks.com/) This is one of the most advanced video editing or cutter tool. It features seamless options though a little complicated for the novice users. However, it is the coolest tool for serving professional purposes. It can handle large file sizes with ease. ![free mp4 video editor](https://images.wondershare.com/images/multimedia/video-editor/lightworks.jpg) **Pros:** * Various video editing options; * High video quality. **Cons:** * It crashes occasionally; * Requires a long learning curve. #### 4\. [VSDC Free Video Editor](http://vsdc-free-video-editor.software.informer.com/) It's a free video editing program which supports various video formats include MP4, AVI, MKV, MPG, WMV, FLV and more. It provides various video filters, transitions, audio effects as well as drawing and selection tools. With it, you can easily cut your MP4 files into different pieces. When the editing done, you can also select the optimized save outputs for a variety of devices, including smart phones and gaming consoles. ![top mp4 video editor](https://images.wondershare.com/images/multimedia/video-editor/vsdc-video-editor.jpg "top mp4 video editor") **Pros:** * Provides various useful filters; * Different output options. **Cons:** * Computer resources (CPU and RAM) are required at a high level. #### 5\. [iMovie](http://www.apple.com/mac/imovie/) The second position of the list will be clinched by iMovie as it is quite similar the Windows Movie Maker, compatible for MAC OS X only. In fact, this software offers a few amazing features which are absent in Windows Movie Maker. With it, you can easily cut video into pieces and edit any part of the video as you like. Truly a powerful and effective tool! File saving and export options are particularly praiseworthy. ![free mp4 video cutters](https://images.wondershare.com/topic/video-editing/imovie.jpg "free mp4 video cutters") **Pros:** * Easy-to-use and efficient; * Useful video editing functions. **Cons:** * The supported video formats are limited. #### 6\. [Free Video Cutter](http://www.freevideocutter.com/) Freemake video Cutter does exactly what its name suggests, and that is cut video. As well as MP4 it can deal with several other video formats, it uses a nice easy to follow interface and is a nice compact package that does the job well. ![Free Video Cutter](https://images.wondershare.com/multimedia/free-video-cutter.jpg) One of the easiest to use, a simple interface and good performance. #### 7\. [Freemake Video Converter](http://www.freemake.com/free%5Fvideo%5Fconverter/) Whilst, as the name suggests, this package was designed for format conversion, it includes a wealth of other abilities, one of which is video cutting, it can also rejoin and merge clips too. As a video converter, it has the largest range of format compatibility in the list and can even burn your finished videos to DVD or Blu-ray for you. The cutting feature is nicely implemented into a clear interface and should be straightforward for anyone to use. ![Freemake Video Converter](https://images.wondershare.com/multimedia/freemake-video-converter.png) An easy to use interface and a comprehensive feature set far beyond just cutting make this a great general video utility package. #### 8\. [Movica](https://sourceforge.net/projects/movica/) This package uses other open source scripting files as the mechanics of doing its job, and is in essence a user interface for those systems. That takes nothing away from it though, the tools it uses are very effective, but in their native form not something most people could take advantage of. In addition to MP4 there are several other video formats available as well as both .wma and .mp3 audio files. ![Movica](https://images.wondershare.com/multimedia/movica1.jpg) A simple interface and a more technical outlook than many, but it works well. #### 9\. [Virtualdub](http://www.virtualdub.org/) A fairly comprehensive editing package, VirtualDub has a nice selection of cutting tools enabling accurate cuts and edits with ease, covering the MP4 format as well as several others, it is a useful tool for those looking for additional features beyond just cutting. Due to the lengthy feature set the interface is a little cluttered and for those that want nothing but a cutter, is perhaps overkill, however, it does the job very well and for many presents a useful selection of video tools. ![Virtualdub](https://images.wondershare.com/multimedia/virtualdub1.png) With plenty of video tools in addition to cutting, VirtualDub presents an attractive, video toolbox for the enthusiast. #### 10\. [Online Video Cutter](https://online-video-cutter.com/) Our final offering is a slightly different take on the video cutter. This is an online offering that requires no downloads or installation, you simply go to the website, upload your video or select a video on the web, cut the video and save the output. It is very simple, although there is the obvious issue with larger files of upload and download time, but for many applications is perhaps the ideal solution. ![Online Video Cutter](https://images.wondershare.com/multimedia/onlinecutter.png) Without the need to install anything, and with a very simple interface, for smaller files is perhaps the perfect solution. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Final Cut Pro Tutorial Collection ##### Final Cut Pro alternative - Wondershare Filmora An easy yet powerful editor Numerous effects to choose from Detailed tutorials provided by official channel [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Videos have become a vital part of any marketing strategy. You need video material to stay alive digitally, whether you're a freelance filmmaker, a blogger, a YouTuber, or a member of a full-time agency. However, if you think making movies and editing them in post-production isn't challenging, you haven't done it with Final Cut Pro X. Video editing is a pain. Mastering non-linear editing software like Final Cut Pro is one of the most challenging, soul-crushing, and time-consuming tasks you can do. But that's why you have us and our comprehensive guide to help you find the best tutorial course on using Final Cut Pro like a pro. After learning from these lessons, you will master the basics and advanced techniques of Final Cut Pro X. Let's get started, beginners and pros! #### In this article 01 [The Best Video Courses For Final Cut Pro in YouTube](#part1) 02 [The Best Websites to Learn Final Cut Pro Basics](#part2) 03 [Is Paid Class of FCPX Worth For Beginners?](#part3) ## Part1: The Best Video Courses For Final Cut Pro in YouTube Finding good Final Cut Pro X tutorials on YouTube may be like looking for a needle in a haystack. Millions of videos on the internet promise to teach Final Cut tips and tricks, but only a handful of them deliver the degree of training you require. Even if you discover competent video editing teachers on YouTube, there's a high chance they won't teach you how to use the particular program function you need. It's incredibly aggravating to spend so much time looking for what you need! But don't lose heart just yet. You can discover a professional video editing instructor that offers a variety of free lessons, tips, and tools for beginners and professionals with a bit of assistance. Check out our top 5 Recommendations to learn Final Cut Pro on YouTube before you waste hours scanning through dozens of videos: ### 1.FCPX Tour – Final Cut Pro Tips from Basic to Advance This isn't a regular tutorial; instead, it's a presentation. On the other hand, this channel physically walks you through capturing footage, transferring it to your timeline, and then starting to edit it. Everything from music to speech to light color grading to a quick exporting procedure is covered in this video. After seeing this tutorial, there's no chance you won't grasp how to edit a video. It's just good, reliable information. ![learn-final-cut-pro-with-fcpx-tour](https://images.wondershare.com/filmora/images/final-cut-pro/learn-final-cut-pro-with-fcpx-tour.jpg) **Why recommend this channle?** • Learn basic to advanced level techniques. • Unique workflow gives subscribers a clear understading about the tutorial. • Practical approach for subscribers to reproduce the work instantly. ### 2.Shutterstock Tutorials – Learn Tips For Beginners It takes some time to become familiar with Final Cut Pro X. However, after you've mastered the fundamentals, you'll be able to complete tasks faster than ever before. Follow this channel for a comprehensive explanation of the best beginner techniques for editing in Final Cut Pro X, whether you're new to editing or need a refresher course. There are a few essential interface explanations as well as some tips and tricks for using the tools. Enjoy! ![the-best-fcpx-tutorial-shutterstock](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-2.jpg) **Why recommend this channle?** • Informative and easy. Best tips for people who are beginners in Final Cut Pro. ### 3.Marcos Rocha – A Heaven for Advanced Techniques Having mastered the basics, let's move on to some advanced workflow ideas. It takes some time to become comfortable enough (when editing) to experiment with keyboard shortcuts and workflow shortcuts. This is the beauty of editing. Watching lessons on this channel will assist you in putting some of these advanced concepts, shortcuts, and tips into practice as they become second nature to you. ![the-best-fcpx-maroos rocha](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-3.jpg) **Why recommend this channle?** • Great for shortcuts, tips, and advanced concepts of FCPX. • Efficient workflow and easy-to-understand videos. • Even beginners can benefit from these tutorials. ### 4.Brad and Donna – Game-Changing Plugins Everyone needs and appreciates free things, whether they're new to FCPX or a professional editor. Your budget will not always be sufficient, and you will frequently find yourselves at a fork in the road when the funds are few. So, the good news for FCPX editors is that there is a slew of free plugins, including overlays, LUTs, flares, and titles, that are very excellent (and don't seem like your dingus friend produced them). You can watch the tutorial course if you want to learn more about these free and paid plugins in all price ranges. ![the-best-fcpx-tutorial-brad-and-donna](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-4.jpg) **Why recommend this channle?** • Informative FCPX videos. • Tips about various effects, color grading, graphics, keyframes, etc. • Posts new content every week. ### 5.Totally Exposed – Complete Guide for Beginners Are you new to Final Cut Pro X and don't know where to start? If you're new to FCPX and want to get started with video editing, you can join this FREE hour-long in-depth training that will get you up and running in no time! ![the-best-fcpx-tutorial-totally-exposed](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-5.jpg) When you're learning from a seasoned expert, it's easy to feel left behind as they go through tools and features you've never heard of. On the other hand, the Totally Exposed channel puts such concerns to rest with one-of-a-kind lessons in which we learn with Neil, a novice who has never used FCP X before. Importing, basic terminologies, cutting clips, and adding music, as well as adding effects, titles, and exporting the finished material, are all covered in this video. It's more of a trawling movie than a fast instruction at over one hour long. However, it's ideal for novice users who want to take things a little more slowly and absorb knowledge over time. **Why recommend this channle?** • Extensive yet still very well-paced for beginners. • Amazing teaching skills. However, all the video tutorials are quite long because FCPX is powerful but not easy to get started with. You can always choose Wondershare Filmora to boost your editing. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later ## Part2: **The Best Websites to Read about Final Cut Pro Basics** If you are looking for the best websites to learn Final Cut Pro basics, then you can visit the following web pages: ### 1.[FCP.co](https://fcp.co/) ![the-best-fcpx-tutorial-fcp-co](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-6.jpg) FCP.co is dedicated to all things video on the Mac, focusing on Final Cut Pro X video editing techniques and lessons. They're continuously updated on the latest FCPX third-party plugins and filters (including many free effects). Unlike Apple's FCPX user forum, this one is quite active and updated frequently. ### 2.[Apple Support Center](https://www.apple.com/final-cut-pro/resources/) ![the-best-fcpx-tutorial-apple-support-center](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-7.jpg) On Apple's official website, the FCPX support community is active. If you have a specific query regarding the application, this is an excellent resource. The emphasis here is less on editing style, and skill since most content focuses on more technical FCPX software/hardware concerns. It's worth mentioning that if you contribute to the community by assisting other users with their problems rather than just asking questions, your editing karma will skyrocket! ### 3.[Reddit](https://www.reddit.com/r/finalcutpro/) ![the-best-fcpx-tutorial-reddit](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-8.jpg) If you want to ask a specific question related to Final Cut Pro, you can post it on Reddit. The active community on Reddit will answer it. You can also read the questions posted by other users to increase your knowledge. ### 4.[FCPX.tv](https://fcpx.tv/) ![the-best-fcpx-tutorial-fcpx-tv](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-9.jpg) FCPX.tv, with its motto "all things Final Cut Pro X," is a one-stop shop for the most up-to-date advice and news on this software. An endless list of Final Cut Pro X requests (for future versions and upgrades), FCPX editing lessons, and documentation of known FCPX issues are just a few of the highlights. If you're an FCPX power editor, this is a must-visit website. ## Part3: Is Paid Class of FCPX Worth For Beginners? The last thing you want to do with your hectic schedule is sitting through hours of aimless video lessons. Buying Final Cut Pro lessons gives you the feel of having a personal trainer working alongside you. You can enroll in FCPX paid courses on Udemy and Coursera. Often a certificate of completion is available for download at the end of the course. However, if you are a beginner, we won't recommend you buy paid courses. There is unlimited free content related to Final Cut Pro available on YouTube and other websites that you can access without spending a penny. When you have to spend too much money and energy on an editing tool, consider if it's really worth it. Rather, you can always choose a much easier yet still powerful editor like Filmora to save your time for better editing. Haven't got FCPX yet? Get your [90-day free trial here](https://tools.techidaily.com/wondershare/filmora/download/) or click below to download Filmora for a try. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmorax boxpng ](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Videos have become a vital part of any marketing strategy. You need video material to stay alive digitally, whether you're a freelance filmmaker, a blogger, a YouTuber, or a member of a full-time agency. However, if you think making movies and editing them in post-production isn't challenging, you haven't done it with Final Cut Pro X. Video editing is a pain. Mastering non-linear editing software like Final Cut Pro is one of the most challenging, soul-crushing, and time-consuming tasks you can do. But that's why you have us and our comprehensive guide to help you find the best tutorial course on using Final Cut Pro like a pro. After learning from these lessons, you will master the basics and advanced techniques of Final Cut Pro X. Let's get started, beginners and pros! #### In this article 01 [The Best Video Courses For Final Cut Pro in YouTube](#part1) 02 [The Best Websites to Learn Final Cut Pro Basics](#part2) 03 [Is Paid Class of FCPX Worth For Beginners?](#part3) ## Part1: The Best Video Courses For Final Cut Pro in YouTube Finding good Final Cut Pro X tutorials on YouTube may be like looking for a needle in a haystack. Millions of videos on the internet promise to teach Final Cut tips and tricks, but only a handful of them deliver the degree of training you require. Even if you discover competent video editing teachers on YouTube, there's a high chance they won't teach you how to use the particular program function you need. It's incredibly aggravating to spend so much time looking for what you need! But don't lose heart just yet. You can discover a professional video editing instructor that offers a variety of free lessons, tips, and tools for beginners and professionals with a bit of assistance. Check out our top 5 Recommendations to learn Final Cut Pro on YouTube before you waste hours scanning through dozens of videos: ### 1.FCPX Tour – Final Cut Pro Tips from Basic to Advance This isn't a regular tutorial; instead, it's a presentation. On the other hand, this channel physically walks you through capturing footage, transferring it to your timeline, and then starting to edit it. Everything from music to speech to light color grading to a quick exporting procedure is covered in this video. After seeing this tutorial, there's no chance you won't grasp how to edit a video. It's just good, reliable information. ![learn-final-cut-pro-with-fcpx-tour](https://images.wondershare.com/filmora/images/final-cut-pro/learn-final-cut-pro-with-fcpx-tour.jpg) **Why recommend this channle?** • Learn basic to advanced level techniques. • Unique workflow gives subscribers a clear understading about the tutorial. • Practical approach for subscribers to reproduce the work instantly. ### 2.Shutterstock Tutorials – Learn Tips For Beginners It takes some time to become familiar with Final Cut Pro X. However, after you've mastered the fundamentals, you'll be able to complete tasks faster than ever before. Follow this channel for a comprehensive explanation of the best beginner techniques for editing in Final Cut Pro X, whether you're new to editing or need a refresher course. There are a few essential interface explanations as well as some tips and tricks for using the tools. Enjoy! ![the-best-fcpx-tutorial-shutterstock](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-2.jpg) **Why recommend this channle?** • Informative and easy. Best tips for people who are beginners in Final Cut Pro. ### 3.Marcos Rocha – A Heaven for Advanced Techniques Having mastered the basics, let's move on to some advanced workflow ideas. It takes some time to become comfortable enough (when editing) to experiment with keyboard shortcuts and workflow shortcuts. This is the beauty of editing. Watching lessons on this channel will assist you in putting some of these advanced concepts, shortcuts, and tips into practice as they become second nature to you. ![the-best-fcpx-maroos rocha](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-3.jpg) **Why recommend this channle?** • Great for shortcuts, tips, and advanced concepts of FCPX. • Efficient workflow and easy-to-understand videos. • Even beginners can benefit from these tutorials. ### 4.Brad and Donna – Game-Changing Plugins Everyone needs and appreciates free things, whether they're new to FCPX or a professional editor. Your budget will not always be sufficient, and you will frequently find yourselves at a fork in the road when the funds are few. So, the good news for FCPX editors is that there is a slew of free plugins, including overlays, LUTs, flares, and titles, that are very excellent (and don't seem like your dingus friend produced them). You can watch the tutorial course if you want to learn more about these free and paid plugins in all price ranges. ![the-best-fcpx-tutorial-brad-and-donna](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-4.jpg) **Why recommend this channle?** • Informative FCPX videos. • Tips about various effects, color grading, graphics, keyframes, etc. • Posts new content every week. ### 5.Totally Exposed – Complete Guide for Beginners Are you new to Final Cut Pro X and don't know where to start? If you're new to FCPX and want to get started with video editing, you can join this FREE hour-long in-depth training that will get you up and running in no time! ![the-best-fcpx-tutorial-totally-exposed](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-5.jpg) When you're learning from a seasoned expert, it's easy to feel left behind as they go through tools and features you've never heard of. On the other hand, the Totally Exposed channel puts such concerns to rest with one-of-a-kind lessons in which we learn with Neil, a novice who has never used FCP X before. Importing, basic terminologies, cutting clips, and adding music, as well as adding effects, titles, and exporting the finished material, are all covered in this video. It's more of a trawling movie than a fast instruction at over one hour long. However, it's ideal for novice users who want to take things a little more slowly and absorb knowledge over time. **Why recommend this channle?** • Extensive yet still very well-paced for beginners. • Amazing teaching skills. However, all the video tutorials are quite long because FCPX is powerful but not easy to get started with. You can always choose Wondershare Filmora to boost your editing. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later ## Part2: **The Best Websites to Read about Final Cut Pro Basics** If you are looking for the best websites to learn Final Cut Pro basics, then you can visit the following web pages: ### 1.[FCP.co](https://fcp.co/) ![the-best-fcpx-tutorial-fcp-co](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-6.jpg) FCP.co is dedicated to all things video on the Mac, focusing on Final Cut Pro X video editing techniques and lessons. They're continuously updated on the latest FCPX third-party plugins and filters (including many free effects). Unlike Apple's FCPX user forum, this one is quite active and updated frequently. ### 2.[Apple Support Center](https://www.apple.com/final-cut-pro/resources/) ![the-best-fcpx-tutorial-apple-support-center](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-7.jpg) On Apple's official website, the FCPX support community is active. If you have a specific query regarding the application, this is an excellent resource. The emphasis here is less on editing style, and skill since most content focuses on more technical FCPX software/hardware concerns. It's worth mentioning that if you contribute to the community by assisting other users with their problems rather than just asking questions, your editing karma will skyrocket! ### 3.[Reddit](https://www.reddit.com/r/finalcutpro/) ![the-best-fcpx-tutorial-reddit](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-8.jpg) If you want to ask a specific question related to Final Cut Pro, you can post it on Reddit. The active community on Reddit will answer it. You can also read the questions posted by other users to increase your knowledge. ### 4.[FCPX.tv](https://fcpx.tv/) ![the-best-fcpx-tutorial-fcpx-tv](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-9.jpg) FCPX.tv, with its motto "all things Final Cut Pro X," is a one-stop shop for the most up-to-date advice and news on this software. An endless list of Final Cut Pro X requests (for future versions and upgrades), FCPX editing lessons, and documentation of known FCPX issues are just a few of the highlights. If you're an FCPX power editor, this is a must-visit website. ## Part3: Is Paid Class of FCPX Worth For Beginners? The last thing you want to do with your hectic schedule is sitting through hours of aimless video lessons. Buying Final Cut Pro lessons gives you the feel of having a personal trainer working alongside you. You can enroll in FCPX paid courses on Udemy and Coursera. Often a certificate of completion is available for download at the end of the course. However, if you are a beginner, we won't recommend you buy paid courses. There is unlimited free content related to Final Cut Pro available on YouTube and other websites that you can access without spending a penny. When you have to spend too much money and energy on an editing tool, consider if it's really worth it. Rather, you can always choose a much easier yet still powerful editor like Filmora to save your time for better editing. Haven't got FCPX yet? Get your [90-day free trial here](https://tools.techidaily.com/wondershare/filmora/download/) or click below to download Filmora for a try. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmorax boxpng ](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Videos have become a vital part of any marketing strategy. You need video material to stay alive digitally, whether you're a freelance filmmaker, a blogger, a YouTuber, or a member of a full-time agency. However, if you think making movies and editing them in post-production isn't challenging, you haven't done it with Final Cut Pro X. Video editing is a pain. Mastering non-linear editing software like Final Cut Pro is one of the most challenging, soul-crushing, and time-consuming tasks you can do. But that's why you have us and our comprehensive guide to help you find the best tutorial course on using Final Cut Pro like a pro. After learning from these lessons, you will master the basics and advanced techniques of Final Cut Pro X. Let's get started, beginners and pros! #### In this article 01 [The Best Video Courses For Final Cut Pro in YouTube](#part1) 02 [The Best Websites to Learn Final Cut Pro Basics](#part2) 03 [Is Paid Class of FCPX Worth For Beginners?](#part3) ## Part1: The Best Video Courses For Final Cut Pro in YouTube Finding good Final Cut Pro X tutorials on YouTube may be like looking for a needle in a haystack. Millions of videos on the internet promise to teach Final Cut tips and tricks, but only a handful of them deliver the degree of training you require. Even if you discover competent video editing teachers on YouTube, there's a high chance they won't teach you how to use the particular program function you need. It's incredibly aggravating to spend so much time looking for what you need! But don't lose heart just yet. You can discover a professional video editing instructor that offers a variety of free lessons, tips, and tools for beginners and professionals with a bit of assistance. Check out our top 5 Recommendations to learn Final Cut Pro on YouTube before you waste hours scanning through dozens of videos: ### 1.FCPX Tour – Final Cut Pro Tips from Basic to Advance This isn't a regular tutorial; instead, it's a presentation. On the other hand, this channel physically walks you through capturing footage, transferring it to your timeline, and then starting to edit it. Everything from music to speech to light color grading to a quick exporting procedure is covered in this video. After seeing this tutorial, there's no chance you won't grasp how to edit a video. It's just good, reliable information. ![learn-final-cut-pro-with-fcpx-tour](https://images.wondershare.com/filmora/images/final-cut-pro/learn-final-cut-pro-with-fcpx-tour.jpg) **Why recommend this channle?** • Learn basic to advanced level techniques. • Unique workflow gives subscribers a clear understading about the tutorial. • Practical approach for subscribers to reproduce the work instantly. ### 2.Shutterstock Tutorials – Learn Tips For Beginners It takes some time to become familiar with Final Cut Pro X. However, after you've mastered the fundamentals, you'll be able to complete tasks faster than ever before. Follow this channel for a comprehensive explanation of the best beginner techniques for editing in Final Cut Pro X, whether you're new to editing or need a refresher course. There are a few essential interface explanations as well as some tips and tricks for using the tools. Enjoy! ![the-best-fcpx-tutorial-shutterstock](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-2.jpg) **Why recommend this channle?** • Informative and easy. Best tips for people who are beginners in Final Cut Pro. ### 3.Marcos Rocha – A Heaven for Advanced Techniques Having mastered the basics, let's move on to some advanced workflow ideas. It takes some time to become comfortable enough (when editing) to experiment with keyboard shortcuts and workflow shortcuts. This is the beauty of editing. Watching lessons on this channel will assist you in putting some of these advanced concepts, shortcuts, and tips into practice as they become second nature to you. ![the-best-fcpx-maroos rocha](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-3.jpg) **Why recommend this channle?** • Great for shortcuts, tips, and advanced concepts of FCPX. • Efficient workflow and easy-to-understand videos. • Even beginners can benefit from these tutorials. ### 4.Brad and Donna – Game-Changing Plugins Everyone needs and appreciates free things, whether they're new to FCPX or a professional editor. Your budget will not always be sufficient, and you will frequently find yourselves at a fork in the road when the funds are few. So, the good news for FCPX editors is that there is a slew of free plugins, including overlays, LUTs, flares, and titles, that are very excellent (and don't seem like your dingus friend produced them). You can watch the tutorial course if you want to learn more about these free and paid plugins in all price ranges. ![the-best-fcpx-tutorial-brad-and-donna](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-4.jpg) **Why recommend this channle?** • Informative FCPX videos. • Tips about various effects, color grading, graphics, keyframes, etc. • Posts new content every week. ### 5.Totally Exposed – Complete Guide for Beginners Are you new to Final Cut Pro X and don't know where to start? If you're new to FCPX and want to get started with video editing, you can join this FREE hour-long in-depth training that will get you up and running in no time! ![the-best-fcpx-tutorial-totally-exposed](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-5.jpg) When you're learning from a seasoned expert, it's easy to feel left behind as they go through tools and features you've never heard of. On the other hand, the Totally Exposed channel puts such concerns to rest with one-of-a-kind lessons in which we learn with Neil, a novice who has never used FCP X before. Importing, basic terminologies, cutting clips, and adding music, as well as adding effects, titles, and exporting the finished material, are all covered in this video. It's more of a trawling movie than a fast instruction at over one hour long. However, it's ideal for novice users who want to take things a little more slowly and absorb knowledge over time. **Why recommend this channle?** • Extensive yet still very well-paced for beginners. • Amazing teaching skills. However, all the video tutorials are quite long because FCPX is powerful but not easy to get started with. You can always choose Wondershare Filmora to boost your editing. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later ## Part2: **The Best Websites to Read about Final Cut Pro Basics** If you are looking for the best websites to learn Final Cut Pro basics, then you can visit the following web pages: ### 1.[FCP.co](https://fcp.co/) ![the-best-fcpx-tutorial-fcp-co](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-6.jpg) FCP.co is dedicated to all things video on the Mac, focusing on Final Cut Pro X video editing techniques and lessons. They're continuously updated on the latest FCPX third-party plugins and filters (including many free effects). Unlike Apple's FCPX user forum, this one is quite active and updated frequently. ### 2.[Apple Support Center](https://www.apple.com/final-cut-pro/resources/) ![the-best-fcpx-tutorial-apple-support-center](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-7.jpg) On Apple's official website, the FCPX support community is active. If you have a specific query regarding the application, this is an excellent resource. The emphasis here is less on editing style, and skill since most content focuses on more technical FCPX software/hardware concerns. It's worth mentioning that if you contribute to the community by assisting other users with their problems rather than just asking questions, your editing karma will skyrocket! ### 3.[Reddit](https://www.reddit.com/r/finalcutpro/) ![the-best-fcpx-tutorial-reddit](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-8.jpg) If you want to ask a specific question related to Final Cut Pro, you can post it on Reddit. The active community on Reddit will answer it. You can also read the questions posted by other users to increase your knowledge. ### 4.[FCPX.tv](https://fcpx.tv/) ![the-best-fcpx-tutorial-fcpx-tv](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-9.jpg) FCPX.tv, with its motto "all things Final Cut Pro X," is a one-stop shop for the most up-to-date advice and news on this software. An endless list of Final Cut Pro X requests (for future versions and upgrades), FCPX editing lessons, and documentation of known FCPX issues are just a few of the highlights. If you're an FCPX power editor, this is a must-visit website. ## Part3: Is Paid Class of FCPX Worth For Beginners? The last thing you want to do with your hectic schedule is sitting through hours of aimless video lessons. Buying Final Cut Pro lessons gives you the feel of having a personal trainer working alongside you. You can enroll in FCPX paid courses on Udemy and Coursera. Often a certificate of completion is available for download at the end of the course. However, if you are a beginner, we won't recommend you buy paid courses. There is unlimited free content related to Final Cut Pro available on YouTube and other websites that you can access without spending a penny. When you have to spend too much money and energy on an editing tool, consider if it's really worth it. Rather, you can always choose a much easier yet still powerful editor like Filmora to save your time for better editing. Haven't got FCPX yet? Get your [90-day free trial here](https://tools.techidaily.com/wondershare/filmora/download/) or click below to download Filmora for a try. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmorax boxpng ](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Videos have become a vital part of any marketing strategy. You need video material to stay alive digitally, whether you're a freelance filmmaker, a blogger, a YouTuber, or a member of a full-time agency. However, if you think making movies and editing them in post-production isn't challenging, you haven't done it with Final Cut Pro X. Video editing is a pain. Mastering non-linear editing software like Final Cut Pro is one of the most challenging, soul-crushing, and time-consuming tasks you can do. But that's why you have us and our comprehensive guide to help you find the best tutorial course on using Final Cut Pro like a pro. After learning from these lessons, you will master the basics and advanced techniques of Final Cut Pro X. Let's get started, beginners and pros! #### In this article 01 [The Best Video Courses For Final Cut Pro in YouTube](#part1) 02 [The Best Websites to Learn Final Cut Pro Basics](#part2) 03 [Is Paid Class of FCPX Worth For Beginners?](#part3) ## Part1: The Best Video Courses For Final Cut Pro in YouTube Finding good Final Cut Pro X tutorials on YouTube may be like looking for a needle in a haystack. Millions of videos on the internet promise to teach Final Cut tips and tricks, but only a handful of them deliver the degree of training you require. Even if you discover competent video editing teachers on YouTube, there's a high chance they won't teach you how to use the particular program function you need. It's incredibly aggravating to spend so much time looking for what you need! But don't lose heart just yet. You can discover a professional video editing instructor that offers a variety of free lessons, tips, and tools for beginners and professionals with a bit of assistance. Check out our top 5 Recommendations to learn Final Cut Pro on YouTube before you waste hours scanning through dozens of videos: ### 1.FCPX Tour – Final Cut Pro Tips from Basic to Advance This isn't a regular tutorial; instead, it's a presentation. On the other hand, this channel physically walks you through capturing footage, transferring it to your timeline, and then starting to edit it. Everything from music to speech to light color grading to a quick exporting procedure is covered in this video. After seeing this tutorial, there's no chance you won't grasp how to edit a video. It's just good, reliable information. ![learn-final-cut-pro-with-fcpx-tour](https://images.wondershare.com/filmora/images/final-cut-pro/learn-final-cut-pro-with-fcpx-tour.jpg) **Why recommend this channle?** • Learn basic to advanced level techniques. • Unique workflow gives subscribers a clear understading about the tutorial. • Practical approach for subscribers to reproduce the work instantly. ### 2.Shutterstock Tutorials – Learn Tips For Beginners It takes some time to become familiar with Final Cut Pro X. However, after you've mastered the fundamentals, you'll be able to complete tasks faster than ever before. Follow this channel for a comprehensive explanation of the best beginner techniques for editing in Final Cut Pro X, whether you're new to editing or need a refresher course. There are a few essential interface explanations as well as some tips and tricks for using the tools. Enjoy! ![the-best-fcpx-tutorial-shutterstock](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-2.jpg) **Why recommend this channle?** • Informative and easy. Best tips for people who are beginners in Final Cut Pro. ### 3.Marcos Rocha – A Heaven for Advanced Techniques Having mastered the basics, let's move on to some advanced workflow ideas. It takes some time to become comfortable enough (when editing) to experiment with keyboard shortcuts and workflow shortcuts. This is the beauty of editing. Watching lessons on this channel will assist you in putting some of these advanced concepts, shortcuts, and tips into practice as they become second nature to you. ![the-best-fcpx-maroos rocha](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-3.jpg) **Why recommend this channle?** • Great for shortcuts, tips, and advanced concepts of FCPX. • Efficient workflow and easy-to-understand videos. • Even beginners can benefit from these tutorials. ### 4.Brad and Donna – Game-Changing Plugins Everyone needs and appreciates free things, whether they're new to FCPX or a professional editor. Your budget will not always be sufficient, and you will frequently find yourselves at a fork in the road when the funds are few. So, the good news for FCPX editors is that there is a slew of free plugins, including overlays, LUTs, flares, and titles, that are very excellent (and don't seem like your dingus friend produced them). You can watch the tutorial course if you want to learn more about these free and paid plugins in all price ranges. ![the-best-fcpx-tutorial-brad-and-donna](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-4.jpg) **Why recommend this channle?** • Informative FCPX videos. • Tips about various effects, color grading, graphics, keyframes, etc. • Posts new content every week. ### 5.Totally Exposed – Complete Guide for Beginners Are you new to Final Cut Pro X and don't know where to start? If you're new to FCPX and want to get started with video editing, you can join this FREE hour-long in-depth training that will get you up and running in no time! ![the-best-fcpx-tutorial-totally-exposed](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-5.jpg) When you're learning from a seasoned expert, it's easy to feel left behind as they go through tools and features you've never heard of. On the other hand, the Totally Exposed channel puts such concerns to rest with one-of-a-kind lessons in which we learn with Neil, a novice who has never used FCP X before. Importing, basic terminologies, cutting clips, and adding music, as well as adding effects, titles, and exporting the finished material, are all covered in this video. It's more of a trawling movie than a fast instruction at over one hour long. However, it's ideal for novice users who want to take things a little more slowly and absorb knowledge over time. **Why recommend this channle?** • Extensive yet still very well-paced for beginners. • Amazing teaching skills. However, all the video tutorials are quite long because FCPX is powerful but not easy to get started with. You can always choose Wondershare Filmora to boost your editing. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later (64-bit) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.12 or later ## Part2: **The Best Websites to Read about Final Cut Pro Basics** If you are looking for the best websites to learn Final Cut Pro basics, then you can visit the following web pages: ### 1.[FCP.co](https://fcp.co/) ![the-best-fcpx-tutorial-fcp-co](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-6.jpg) FCP.co is dedicated to all things video on the Mac, focusing on Final Cut Pro X video editing techniques and lessons. They're continuously updated on the latest FCPX third-party plugins and filters (including many free effects). Unlike Apple's FCPX user forum, this one is quite active and updated frequently. ### 2.[Apple Support Center](https://www.apple.com/final-cut-pro/resources/) ![the-best-fcpx-tutorial-apple-support-center](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-7.jpg) On Apple's official website, the FCPX support community is active. If you have a specific query regarding the application, this is an excellent resource. The emphasis here is less on editing style, and skill since most content focuses on more technical FCPX software/hardware concerns. It's worth mentioning that if you contribute to the community by assisting other users with their problems rather than just asking questions, your editing karma will skyrocket! ### 3.[Reddit](https://www.reddit.com/r/finalcutpro/) ![the-best-fcpx-tutorial-reddit](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-8.jpg) If you want to ask a specific question related to Final Cut Pro, you can post it on Reddit. The active community on Reddit will answer it. You can also read the questions posted by other users to increase your knowledge. ### 4.[FCPX.tv](https://fcpx.tv/) ![the-best-fcpx-tutorial-fcpx-tv](https://images.wondershare.com/filmora/images/final-cut-pro/the-best-fcpx-tutorial-9.jpg) FCPX.tv, with its motto "all things Final Cut Pro X," is a one-stop shop for the most up-to-date advice and news on this software. An endless list of Final Cut Pro X requests (for future versions and upgrades), FCPX editing lessons, and documentation of known FCPX issues are just a few of the highlights. If you're an FCPX power editor, this is a must-visit website. ## Part3: Is Paid Class of FCPX Worth For Beginners? The last thing you want to do with your hectic schedule is sitting through hours of aimless video lessons. Buying Final Cut Pro lessons gives you the feel of having a personal trainer working alongside you. You can enroll in FCPX paid courses on Udemy and Coursera. Often a certificate of completion is available for download at the end of the course. However, if you are a beginner, we won't recommend you buy paid courses. There is unlimited free content related to Final Cut Pro available on YouTube and other websites that you can access without spending a penny. When you have to spend too much money and energy on an editing tool, consider if it's really worth it. Rather, you can always choose a much easier yet still powerful editor like Filmora to save your time for better editing. Haven't got FCPX yet? Get your [90-day free trial here](https://tools.techidaily.com/wondershare/filmora/download/) or click below to download Filmora for a try. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmorax boxpng ](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Best Video Brighten Apps [Android and iPhone] ##### Adjust Video Color and Brightness Easily Wondershare Filmora is one of the most popular [video editing software for YouTubers](https://tools.techidaily.com/wondershare/filmora/download/), which allows video creators to adjust video color in an easier way with its auto-enhance, color match and LUTs. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) When photographing with an iPhone or Android device, you may encounter a variety of lighting issues. If you record them in a dim setting, you may find that your movies are excessively dark or of low quality. Recording in low-light conditions may result in a too gloomy video to see clearly and may potentially degrade video quality. In such cases, utilizing video brightening software on an iPhone or Android might be one of the greatest ways to brighten a video. In addition, we've compiled a list of **Video Brightening Editor App** programs for you on this page. Carefully read the information below to learn more about their characteristics, supported operating systems, and more! #### In this article 01 [Best Video Editing Apps to Edit Brightness on iPhone and Android](#part1) 02 [How to Brighten a Video on Your iPhone Before or While Recording](#part2) ## Part 1: Best Video Editing Apps to Edit Brightness on iPhone and Android Brightness is important in a clip, whether you realize it or not. Viewers would not sit through a dark video in which they can't see anything. You need the right amount of brightness in your film to make it more engaging and eye-catching. And the apps we've looked at below can help you do just that. ### 1\. [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is a video brightening editing tool made specifically for cellphones. It's simple to use, and even beginners can use it to edit films. Filmora enhances the video's brightness, making it crisper and more vivid. This application's features include capturing clips, cutting them, adding background music, applying overlays and effects, and more. This popular program also supports Ultra HD resolution. Filmora includes several powerful tools that enable you to put even the most unique and creative ideas into action. You may make movies, work on music videos, and share the finished products with your pals. This software saves you time while still providing entertainment! To brighten a video, simply get the app on your phone and install it. Launch the app and select the "+" button to add the video you wish to modify. By clicking on the 5-second mark in the menu settings, you may alter the video's brightness. Click on the "Export" button to save the altered video for later use. ### 2\. [Capcut](https://www.capcut.net/) Number second on our list is the Capcut video editor that users have grown absolutely fond of. After testing both the Android and iOS versions of CapCut, we discovered that the software is extremely user-friendly and provides many useful features tailored to TikTok users. Split-screen, vintage, humorous, dreamy, party, and so on are just a few of the various effects available. Those effects add new components to your video, giving it the appearance of being professionally edited. You'll discover sub-categories of effects inside each of these categories, allowing you to fine-tune your changes to obtain the precise one that's suitable for that clip. To brighten a video, simply tap on the "+" feature in the new Project tab. Import your video. Head over to the Edit section and apply Brightness from the Adjustment section. ### 3\. iMovie For iPhone and iPad owners, iMovie is the app of choice. YouTubers who wish to edit videos on their phones often use the iOS video editing software. It combines a user-friendly interface with fast performance, ensuring that visual content is never compromised while using a free video editor. It offers 4K and multi-track editing, a variety of filters, and the ability to incorporate free music that adapts to the duration of a film. To master the iMovie learning curve, you don't need to be an expert in video processing. iMovie's theme library is one of the most prominent features. Each choice includes music, transitions, and text overlays, allowing you to save time and effort when editing. ### 4\. [InShot](https://inshot.com/) InShot provides all of the options you'll need to improve the quality of your recordings with the brighten video software. Because this is an all-encompassing software, it gives a lot of flexibility and features. InShot will assist you with creating movies, flipping and rotating film, adjusting music playback speed, and applying filters. Thanks to many handy features, this video brightness editor tool will make your video editing experience pleasurable and productive. Select the New option from the video menu to alter the brightness. Next, from your Android phone's gallery, choose the video you would like to brighten up. Now click on the green circle with the checkmark and then on the Filter choice whenever a new screen appears. Change the brightness of the clip using the Brightness function from the filter by moving the sliders. ### 5\. [Videoleap](https://videoleapapp.com/) Videoleap is a fantastic Android and iPhone brightening app. You can improve the brightness of a video captured in low-light circumstances with the aid of its filter pack. You may also utilize a wide range of premium and free services to edit your film further. For expert video editors, Videoleap has several useful features. Keyframe animations, layered editing, chromakey combinations, and other capabilities are among them. Standard operations, such as editing films and generating clips, are simple enough for beginners to utilize. When you click on the menu option, simply adjust the Brightness and another criterion. With this tool, Instagram users can simply create high-quality stories and other streaming videos. The Videoleap brightness video program adds amazing video and audio effects, filters film emulators, and creates stunning videos, among other things. ### 6\. [BeeCut](https://beecut.com/) BeeCut is another brightening video editing program with several unique features. It allows you to add filters, messages, and music to films and modify volume, trim, and rotate clips. You may also use this program to brighten and improve the color palette of movies. It features a user-friendly design and is quite simple to operate. The absence of sophisticated settings will appeal to beginners, who will be pleased to edit or make short video clips with just a few clicks. BeeCut can generate movies in a variety of resolutions, however high-quality films take longer to load. Simply launch BeeCut after installing it on your phone. To upload a video, launch the app and click the "+" symbol. Now choose whatever aspect ratio you like and wait a few seconds for your file to upload. To brighten the video, go to Filters and pick the "Brightness" option. ### 7\. [Filmmaker Pro](https://www.filmmakerproapp.com/) Filmmaker Pro is among the best video brightening program for both skilled and new users. With a wide range of helpful features and a large number of tools, this program can rival even costly video editing applications. The extensive capability enables you to generate high-quality content that will attract a lot of attention. Filmmaker Pro allows you to create Hollywood-style films and share photos through social networking sites. To brighten a video, go to the 'Add Project' tab and select a video to modify. The video will show in a timeline, where you may alter it by pressing it. For android video brightness, choose 'Adjust.' Brighten a dark video in Android by moving on a slider from the left side to ride by clicking on 'Brightness.' And that's all there is to it. ### 8\. [Magisto](https://www.magisto.com/) The Magisto brighten video software uses Artificial Intelligence to identify the greatest sections of your video. Object stabilization, fantastic filters, and dazzling effects are among the ways used to improve the footage. Consequently, you'll be able to create visually appealing videos that draw in a large number of visitors. Owing to artificial intelligence, the Magisto video brightness editing software lets you make professional-quality films fast and effortlessly. It can edit your video files accurately and add fantastic graphics, effects, filters, and music to create a captivating tale. To lighten a video, open the application and choose one. Next should be tapped. Adjust the parameters for Brightness until the video is optimal. Save the video and exit the program. ### 9\. [VivaVideo](https://vivavideo.tv/) VivaVideo is a free video editing software for Android and iOS devices that allows you to edit or develop new videos. It uses a special video editing tool to make a fresh and unique video for free on your smartphone. This application is a professional-level video lighting editor that can enhance any movie by adding effects, trimming, splitting, transitions, and more. It has a filter option that allows you to modify the video's brightness, contrast saturation, and warmth. You may combine numerous photographs and videos to create a mix that appears better in the final video, in addition to brightness adjustment. Once you've got the video, go to Filters, Adjust, and choose the clip you wish to alter. You may adjust the video's visual characteristics here, such as brightness and contrast. You can even crop a video to make it seem better. ### 10\. [Chromic](https://apps.apple.com/us/app/chromic-video-filters-editor/id724295125) Chromic is a video brightening program that provides customers with a wide range of professional filters to enhance their movies substantially. The program comes with a strong image processing engine that allows it to create vivid, unique videos. Chromic will elevate your video editing skills to new heights. Use this useful tool to give all of your video recordings a unique flair. Even the darkest film may be brightened with Chromic. ![chromic video filters editor](https://images.wondershare.com/filmora/article-images/chromic-video-filters-editor.jpg) To brighten the video, on your smartphone, open the Chromic Video Editor. To add a video to the display, choose it. Adjust the brightness of the video by tapping on the Sun symbol. While you're at it, you may also change the colors and other settings. ## Part 2: How to Brighten a Video on Your iPhone Before or While Recording A gloomy video isn't fun to watch, but it's frequently difficult to know in the present if the video you're capturing is too dull to see clearly. Brightening an iPhone video can help you see the activity on-screen and make it more appealing if you share it on social media or post it to a website. Because the iPhone's built-in camera app does not enable you to brighten films after they have been recorded, you should always try to light a video before you begin recording. **Step 1:** Switch to video mode by opening the camera app and swiping left. Touch the screen to bring up a box with a sun-shaped symbol. **Step 2**: Move your fingers upward on the iPhone screen to brighten the scene when you begin filming. This may be done at any moment while the video is being recorded. **Conclusion** There are a ton of **Video Brightening Editor Apps** that will make brightening the videos after filming quite easy for you. Long gone are the days when you had to re-film now and again until you would get that one final shot that has every color adjustment aspect fit to perfection. With the advent of amazing software such as those covered in this article, brightening a dark video has never been easier! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) When photographing with an iPhone or Android device, you may encounter a variety of lighting issues. If you record them in a dim setting, you may find that your movies are excessively dark or of low quality. Recording in low-light conditions may result in a too gloomy video to see clearly and may potentially degrade video quality. In such cases, utilizing video brightening software on an iPhone or Android might be one of the greatest ways to brighten a video. In addition, we've compiled a list of **Video Brightening Editor App** programs for you on this page. Carefully read the information below to learn more about their characteristics, supported operating systems, and more! #### In this article 01 [Best Video Editing Apps to Edit Brightness on iPhone and Android](#part1) 02 [How to Brighten a Video on Your iPhone Before or While Recording](#part2) ## Part 1: Best Video Editing Apps to Edit Brightness on iPhone and Android Brightness is important in a clip, whether you realize it or not. Viewers would not sit through a dark video in which they can't see anything. You need the right amount of brightness in your film to make it more engaging and eye-catching. And the apps we've looked at below can help you do just that. ### 1\. [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is a video brightening editing tool made specifically for cellphones. It's simple to use, and even beginners can use it to edit films. Filmora enhances the video's brightness, making it crisper and more vivid. This application's features include capturing clips, cutting them, adding background music, applying overlays and effects, and more. This popular program also supports Ultra HD resolution. Filmora includes several powerful tools that enable you to put even the most unique and creative ideas into action. You may make movies, work on music videos, and share the finished products with your pals. This software saves you time while still providing entertainment! To brighten a video, simply get the app on your phone and install it. Launch the app and select the "+" button to add the video you wish to modify. By clicking on the 5-second mark in the menu settings, you may alter the video's brightness. Click on the "Export" button to save the altered video for later use. ### 2\. [Capcut](https://www.capcut.net/) Number second on our list is the Capcut video editor that users have grown absolutely fond of. After testing both the Android and iOS versions of CapCut, we discovered that the software is extremely user-friendly and provides many useful features tailored to TikTok users. Split-screen, vintage, humorous, dreamy, party, and so on are just a few of the various effects available. Those effects add new components to your video, giving it the appearance of being professionally edited. You'll discover sub-categories of effects inside each of these categories, allowing you to fine-tune your changes to obtain the precise one that's suitable for that clip. To brighten a video, simply tap on the "+" feature in the new Project tab. Import your video. Head over to the Edit section and apply Brightness from the Adjustment section. ### 3\. iMovie For iPhone and iPad owners, iMovie is the app of choice. YouTubers who wish to edit videos on their phones often use the iOS video editing software. It combines a user-friendly interface with fast performance, ensuring that visual content is never compromised while using a free video editor. It offers 4K and multi-track editing, a variety of filters, and the ability to incorporate free music that adapts to the duration of a film. To master the iMovie learning curve, you don't need to be an expert in video processing. iMovie's theme library is one of the most prominent features. Each choice includes music, transitions, and text overlays, allowing you to save time and effort when editing. ### 4\. [InShot](https://inshot.com/) InShot provides all of the options you'll need to improve the quality of your recordings with the brighten video software. Because this is an all-encompassing software, it gives a lot of flexibility and features. InShot will assist you with creating movies, flipping and rotating film, adjusting music playback speed, and applying filters. Thanks to many handy features, this video brightness editor tool will make your video editing experience pleasurable and productive. Select the New option from the video menu to alter the brightness. Next, from your Android phone's gallery, choose the video you would like to brighten up. Now click on the green circle with the checkmark and then on the Filter choice whenever a new screen appears. Change the brightness of the clip using the Brightness function from the filter by moving the sliders. ### 5\. [Videoleap](https://videoleapapp.com/) Videoleap is a fantastic Android and iPhone brightening app. You can improve the brightness of a video captured in low-light circumstances with the aid of its filter pack. You may also utilize a wide range of premium and free services to edit your film further. For expert video editors, Videoleap has several useful features. Keyframe animations, layered editing, chromakey combinations, and other capabilities are among them. Standard operations, such as editing films and generating clips, are simple enough for beginners to utilize. When you click on the menu option, simply adjust the Brightness and another criterion. With this tool, Instagram users can simply create high-quality stories and other streaming videos. The Videoleap brightness video program adds amazing video and audio effects, filters film emulators, and creates stunning videos, among other things. ### 6\. [BeeCut](https://beecut.com/) BeeCut is another brightening video editing program with several unique features. It allows you to add filters, messages, and music to films and modify volume, trim, and rotate clips. You may also use this program to brighten and improve the color palette of movies. It features a user-friendly design and is quite simple to operate. The absence of sophisticated settings will appeal to beginners, who will be pleased to edit or make short video clips with just a few clicks. BeeCut can generate movies in a variety of resolutions, however high-quality films take longer to load. Simply launch BeeCut after installing it on your phone. To upload a video, launch the app and click the "+" symbol. Now choose whatever aspect ratio you like and wait a few seconds for your file to upload. To brighten the video, go to Filters and pick the "Brightness" option. ### 7\. [Filmmaker Pro](https://www.filmmakerproapp.com/) Filmmaker Pro is among the best video brightening program for both skilled and new users. With a wide range of helpful features and a large number of tools, this program can rival even costly video editing applications. The extensive capability enables you to generate high-quality content that will attract a lot of attention. Filmmaker Pro allows you to create Hollywood-style films and share photos through social networking sites. To brighten a video, go to the 'Add Project' tab and select a video to modify. The video will show in a timeline, where you may alter it by pressing it. For android video brightness, choose 'Adjust.' Brighten a dark video in Android by moving on a slider from the left side to ride by clicking on 'Brightness.' And that's all there is to it. ### 8\. [Magisto](https://www.magisto.com/) The Magisto brighten video software uses Artificial Intelligence to identify the greatest sections of your video. Object stabilization, fantastic filters, and dazzling effects are among the ways used to improve the footage. Consequently, you'll be able to create visually appealing videos that draw in a large number of visitors. Owing to artificial intelligence, the Magisto video brightness editing software lets you make professional-quality films fast and effortlessly. It can edit your video files accurately and add fantastic graphics, effects, filters, and music to create a captivating tale. To lighten a video, open the application and choose one. Next should be tapped. Adjust the parameters for Brightness until the video is optimal. Save the video and exit the program. ### 9\. [VivaVideo](https://vivavideo.tv/) VivaVideo is a free video editing software for Android and iOS devices that allows you to edit or develop new videos. It uses a special video editing tool to make a fresh and unique video for free on your smartphone. This application is a professional-level video lighting editor that can enhance any movie by adding effects, trimming, splitting, transitions, and more. It has a filter option that allows you to modify the video's brightness, contrast saturation, and warmth. You may combine numerous photographs and videos to create a mix that appears better in the final video, in addition to brightness adjustment. Once you've got the video, go to Filters, Adjust, and choose the clip you wish to alter. You may adjust the video's visual characteristics here, such as brightness and contrast. You can even crop a video to make it seem better. ### 10\. [Chromic](https://apps.apple.com/us/app/chromic-video-filters-editor/id724295125) Chromic is a video brightening program that provides customers with a wide range of professional filters to enhance their movies substantially. The program comes with a strong image processing engine that allows it to create vivid, unique videos. Chromic will elevate your video editing skills to new heights. Use this useful tool to give all of your video recordings a unique flair. Even the darkest film may be brightened with Chromic. ![chromic video filters editor](https://images.wondershare.com/filmora/article-images/chromic-video-filters-editor.jpg) To brighten the video, on your smartphone, open the Chromic Video Editor. To add a video to the display, choose it. Adjust the brightness of the video by tapping on the Sun symbol. While you're at it, you may also change the colors and other settings. ## Part 2: How to Brighten a Video on Your iPhone Before or While Recording A gloomy video isn't fun to watch, but it's frequently difficult to know in the present if the video you're capturing is too dull to see clearly. Brightening an iPhone video can help you see the activity on-screen and make it more appealing if you share it on social media or post it to a website. Because the iPhone's built-in camera app does not enable you to brighten films after they have been recorded, you should always try to light a video before you begin recording. **Step 1:** Switch to video mode by opening the camera app and swiping left. Touch the screen to bring up a box with a sun-shaped symbol. **Step 2**: Move your fingers upward on the iPhone screen to brighten the scene when you begin filming. This may be done at any moment while the video is being recorded. **Conclusion** There are a ton of **Video Brightening Editor Apps** that will make brightening the videos after filming quite easy for you. Long gone are the days when you had to re-film now and again until you would get that one final shot that has every color adjustment aspect fit to perfection. With the advent of amazing software such as those covered in this article, brightening a dark video has never been easier! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) When photographing with an iPhone or Android device, you may encounter a variety of lighting issues. If you record them in a dim setting, you may find that your movies are excessively dark or of low quality. Recording in low-light conditions may result in a too gloomy video to see clearly and may potentially degrade video quality. In such cases, utilizing video brightening software on an iPhone or Android might be one of the greatest ways to brighten a video. In addition, we've compiled a list of **Video Brightening Editor App** programs for you on this page. Carefully read the information below to learn more about their characteristics, supported operating systems, and more! #### In this article 01 [Best Video Editing Apps to Edit Brightness on iPhone and Android](#part1) 02 [How to Brighten a Video on Your iPhone Before or While Recording](#part2) ## Part 1: Best Video Editing Apps to Edit Brightness on iPhone and Android Brightness is important in a clip, whether you realize it or not. Viewers would not sit through a dark video in which they can't see anything. You need the right amount of brightness in your film to make it more engaging and eye-catching. And the apps we've looked at below can help you do just that. ### 1\. [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is a video brightening editing tool made specifically for cellphones. It's simple to use, and even beginners can use it to edit films. Filmora enhances the video's brightness, making it crisper and more vivid. This application's features include capturing clips, cutting them, adding background music, applying overlays and effects, and more. This popular program also supports Ultra HD resolution. Filmora includes several powerful tools that enable you to put even the most unique and creative ideas into action. You may make movies, work on music videos, and share the finished products with your pals. This software saves you time while still providing entertainment! To brighten a video, simply get the app on your phone and install it. Launch the app and select the "+" button to add the video you wish to modify. By clicking on the 5-second mark in the menu settings, you may alter the video's brightness. Click on the "Export" button to save the altered video for later use. ### 2\. [Capcut](https://www.capcut.net/) Number second on our list is the Capcut video editor that users have grown absolutely fond of. After testing both the Android and iOS versions of CapCut, we discovered that the software is extremely user-friendly and provides many useful features tailored to TikTok users. Split-screen, vintage, humorous, dreamy, party, and so on are just a few of the various effects available. Those effects add new components to your video, giving it the appearance of being professionally edited. You'll discover sub-categories of effects inside each of these categories, allowing you to fine-tune your changes to obtain the precise one that's suitable for that clip. To brighten a video, simply tap on the "+" feature in the new Project tab. Import your video. Head over to the Edit section and apply Brightness from the Adjustment section. ### 3\. iMovie For iPhone and iPad owners, iMovie is the app of choice. YouTubers who wish to edit videos on their phones often use the iOS video editing software. It combines a user-friendly interface with fast performance, ensuring that visual content is never compromised while using a free video editor. It offers 4K and multi-track editing, a variety of filters, and the ability to incorporate free music that adapts to the duration of a film. To master the iMovie learning curve, you don't need to be an expert in video processing. iMovie's theme library is one of the most prominent features. Each choice includes music, transitions, and text overlays, allowing you to save time and effort when editing. ### 4\. [InShot](https://inshot.com/) InShot provides all of the options you'll need to improve the quality of your recordings with the brighten video software. Because this is an all-encompassing software, it gives a lot of flexibility and features. InShot will assist you with creating movies, flipping and rotating film, adjusting music playback speed, and applying filters. Thanks to many handy features, this video brightness editor tool will make your video editing experience pleasurable and productive. Select the New option from the video menu to alter the brightness. Next, from your Android phone's gallery, choose the video you would like to brighten up. Now click on the green circle with the checkmark and then on the Filter choice whenever a new screen appears. Change the brightness of the clip using the Brightness function from the filter by moving the sliders. ### 5\. [Videoleap](https://videoleapapp.com/) Videoleap is a fantastic Android and iPhone brightening app. You can improve the brightness of a video captured in low-light circumstances with the aid of its filter pack. You may also utilize a wide range of premium and free services to edit your film further. For expert video editors, Videoleap has several useful features. Keyframe animations, layered editing, chromakey combinations, and other capabilities are among them. Standard operations, such as editing films and generating clips, are simple enough for beginners to utilize. When you click on the menu option, simply adjust the Brightness and another criterion. With this tool, Instagram users can simply create high-quality stories and other streaming videos. The Videoleap brightness video program adds amazing video and audio effects, filters film emulators, and creates stunning videos, among other things. ### 6\. [BeeCut](https://beecut.com/) BeeCut is another brightening video editing program with several unique features. It allows you to add filters, messages, and music to films and modify volume, trim, and rotate clips. You may also use this program to brighten and improve the color palette of movies. It features a user-friendly design and is quite simple to operate. The absence of sophisticated settings will appeal to beginners, who will be pleased to edit or make short video clips with just a few clicks. BeeCut can generate movies in a variety of resolutions, however high-quality films take longer to load. Simply launch BeeCut after installing it on your phone. To upload a video, launch the app and click the "+" symbol. Now choose whatever aspect ratio you like and wait a few seconds for your file to upload. To brighten the video, go to Filters and pick the "Brightness" option. ### 7\. [Filmmaker Pro](https://www.filmmakerproapp.com/) Filmmaker Pro is among the best video brightening program for both skilled and new users. With a wide range of helpful features and a large number of tools, this program can rival even costly video editing applications. The extensive capability enables you to generate high-quality content that will attract a lot of attention. Filmmaker Pro allows you to create Hollywood-style films and share photos through social networking sites. To brighten a video, go to the 'Add Project' tab and select a video to modify. The video will show in a timeline, where you may alter it by pressing it. For android video brightness, choose 'Adjust.' Brighten a dark video in Android by moving on a slider from the left side to ride by clicking on 'Brightness.' And that's all there is to it. ### 8\. [Magisto](https://www.magisto.com/) The Magisto brighten video software uses Artificial Intelligence to identify the greatest sections of your video. Object stabilization, fantastic filters, and dazzling effects are among the ways used to improve the footage. Consequently, you'll be able to create visually appealing videos that draw in a large number of visitors. Owing to artificial intelligence, the Magisto video brightness editing software lets you make professional-quality films fast and effortlessly. It can edit your video files accurately and add fantastic graphics, effects, filters, and music to create a captivating tale. To lighten a video, open the application and choose one. Next should be tapped. Adjust the parameters for Brightness until the video is optimal. Save the video and exit the program. ### 9\. [VivaVideo](https://vivavideo.tv/) VivaVideo is a free video editing software for Android and iOS devices that allows you to edit or develop new videos. It uses a special video editing tool to make a fresh and unique video for free on your smartphone. This application is a professional-level video lighting editor that can enhance any movie by adding effects, trimming, splitting, transitions, and more. It has a filter option that allows you to modify the video's brightness, contrast saturation, and warmth. You may combine numerous photographs and videos to create a mix that appears better in the final video, in addition to brightness adjustment. Once you've got the video, go to Filters, Adjust, and choose the clip you wish to alter. You may adjust the video's visual characteristics here, such as brightness and contrast. You can even crop a video to make it seem better. ### 10\. [Chromic](https://apps.apple.com/us/app/chromic-video-filters-editor/id724295125) Chromic is a video brightening program that provides customers with a wide range of professional filters to enhance their movies substantially. The program comes with a strong image processing engine that allows it to create vivid, unique videos. Chromic will elevate your video editing skills to new heights. Use this useful tool to give all of your video recordings a unique flair. Even the darkest film may be brightened with Chromic. ![chromic video filters editor](https://images.wondershare.com/filmora/article-images/chromic-video-filters-editor.jpg) To brighten the video, on your smartphone, open the Chromic Video Editor. To add a video to the display, choose it. Adjust the brightness of the video by tapping on the Sun symbol. While you're at it, you may also change the colors and other settings. ## Part 2: How to Brighten a Video on Your iPhone Before or While Recording A gloomy video isn't fun to watch, but it's frequently difficult to know in the present if the video you're capturing is too dull to see clearly. Brightening an iPhone video can help you see the activity on-screen and make it more appealing if you share it on social media or post it to a website. Because the iPhone's built-in camera app does not enable you to brighten films after they have been recorded, you should always try to light a video before you begin recording. **Step 1:** Switch to video mode by opening the camera app and swiping left. Touch the screen to bring up a box with a sun-shaped symbol. **Step 2**: Move your fingers upward on the iPhone screen to brighten the scene when you begin filming. This may be done at any moment while the video is being recorded. **Conclusion** There are a ton of **Video Brightening Editor Apps** that will make brightening the videos after filming quite easy for you. Long gone are the days when you had to re-film now and again until you would get that one final shot that has every color adjustment aspect fit to perfection. With the advent of amazing software such as those covered in this article, brightening a dark video has never been easier! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) When photographing with an iPhone or Android device, you may encounter a variety of lighting issues. If you record them in a dim setting, you may find that your movies are excessively dark or of low quality. Recording in low-light conditions may result in a too gloomy video to see clearly and may potentially degrade video quality. In such cases, utilizing video brightening software on an iPhone or Android might be one of the greatest ways to brighten a video. In addition, we've compiled a list of **Video Brightening Editor App** programs for you on this page. Carefully read the information below to learn more about their characteristics, supported operating systems, and more! #### In this article 01 [Best Video Editing Apps to Edit Brightness on iPhone and Android](#part1) 02 [How to Brighten a Video on Your iPhone Before or While Recording](#part2) ## Part 1: Best Video Editing Apps to Edit Brightness on iPhone and Android Brightness is important in a clip, whether you realize it or not. Viewers would not sit through a dark video in which they can't see anything. You need the right amount of brightness in your film to make it more engaging and eye-catching. And the apps we've looked at below can help you do just that. ### 1\. [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is a video brightening editing tool made specifically for cellphones. It's simple to use, and even beginners can use it to edit films. Filmora enhances the video's brightness, making it crisper and more vivid. This application's features include capturing clips, cutting them, adding background music, applying overlays and effects, and more. This popular program also supports Ultra HD resolution. Filmora includes several powerful tools that enable you to put even the most unique and creative ideas into action. You may make movies, work on music videos, and share the finished products with your pals. This software saves you time while still providing entertainment! To brighten a video, simply get the app on your phone and install it. Launch the app and select the "+" button to add the video you wish to modify. By clicking on the 5-second mark in the menu settings, you may alter the video's brightness. Click on the "Export" button to save the altered video for later use. ### 2\. [Capcut](https://www.capcut.net/) Number second on our list is the Capcut video editor that users have grown absolutely fond of. After testing both the Android and iOS versions of CapCut, we discovered that the software is extremely user-friendly and provides many useful features tailored to TikTok users. Split-screen, vintage, humorous, dreamy, party, and so on are just a few of the various effects available. Those effects add new components to your video, giving it the appearance of being professionally edited. You'll discover sub-categories of effects inside each of these categories, allowing you to fine-tune your changes to obtain the precise one that's suitable for that clip. To brighten a video, simply tap on the "+" feature in the new Project tab. Import your video. Head over to the Edit section and apply Brightness from the Adjustment section. ### 3\. iMovie For iPhone and iPad owners, iMovie is the app of choice. YouTubers who wish to edit videos on their phones often use the iOS video editing software. It combines a user-friendly interface with fast performance, ensuring that visual content is never compromised while using a free video editor. It offers 4K and multi-track editing, a variety of filters, and the ability to incorporate free music that adapts to the duration of a film. To master the iMovie learning curve, you don't need to be an expert in video processing. iMovie's theme library is one of the most prominent features. Each choice includes music, transitions, and text overlays, allowing you to save time and effort when editing. ### 4\. [InShot](https://inshot.com/) InShot provides all of the options you'll need to improve the quality of your recordings with the brighten video software. Because this is an all-encompassing software, it gives a lot of flexibility and features. InShot will assist you with creating movies, flipping and rotating film, adjusting music playback speed, and applying filters. Thanks to many handy features, this video brightness editor tool will make your video editing experience pleasurable and productive. Select the New option from the video menu to alter the brightness. Next, from your Android phone's gallery, choose the video you would like to brighten up. Now click on the green circle with the checkmark and then on the Filter choice whenever a new screen appears. Change the brightness of the clip using the Brightness function from the filter by moving the sliders. ### 5\. [Videoleap](https://videoleapapp.com/) Videoleap is a fantastic Android and iPhone brightening app. You can improve the brightness of a video captured in low-light circumstances with the aid of its filter pack. You may also utilize a wide range of premium and free services to edit your film further. For expert video editors, Videoleap has several useful features. Keyframe animations, layered editing, chromakey combinations, and other capabilities are among them. Standard operations, such as editing films and generating clips, are simple enough for beginners to utilize. When you click on the menu option, simply adjust the Brightness and another criterion. With this tool, Instagram users can simply create high-quality stories and other streaming videos. The Videoleap brightness video program adds amazing video and audio effects, filters film emulators, and creates stunning videos, among other things. ### 6\. [BeeCut](https://beecut.com/) BeeCut is another brightening video editing program with several unique features. It allows you to add filters, messages, and music to films and modify volume, trim, and rotate clips. You may also use this program to brighten and improve the color palette of movies. It features a user-friendly design and is quite simple to operate. The absence of sophisticated settings will appeal to beginners, who will be pleased to edit or make short video clips with just a few clicks. BeeCut can generate movies in a variety of resolutions, however high-quality films take longer to load. Simply launch BeeCut after installing it on your phone. To upload a video, launch the app and click the "+" symbol. Now choose whatever aspect ratio you like and wait a few seconds for your file to upload. To brighten the video, go to Filters and pick the "Brightness" option. ### 7\. [Filmmaker Pro](https://www.filmmakerproapp.com/) Filmmaker Pro is among the best video brightening program for both skilled and new users. With a wide range of helpful features and a large number of tools, this program can rival even costly video editing applications. The extensive capability enables you to generate high-quality content that will attract a lot of attention. Filmmaker Pro allows you to create Hollywood-style films and share photos through social networking sites. To brighten a video, go to the 'Add Project' tab and select a video to modify. The video will show in a timeline, where you may alter it by pressing it. For android video brightness, choose 'Adjust.' Brighten a dark video in Android by moving on a slider from the left side to ride by clicking on 'Brightness.' And that's all there is to it. ### 8\. [Magisto](https://www.magisto.com/) The Magisto brighten video software uses Artificial Intelligence to identify the greatest sections of your video. Object stabilization, fantastic filters, and dazzling effects are among the ways used to improve the footage. Consequently, you'll be able to create visually appealing videos that draw in a large number of visitors. Owing to artificial intelligence, the Magisto video brightness editing software lets you make professional-quality films fast and effortlessly. It can edit your video files accurately and add fantastic graphics, effects, filters, and music to create a captivating tale. To lighten a video, open the application and choose one. Next should be tapped. Adjust the parameters for Brightness until the video is optimal. Save the video and exit the program. ### 9\. [VivaVideo](https://vivavideo.tv/) VivaVideo is a free video editing software for Android and iOS devices that allows you to edit or develop new videos. It uses a special video editing tool to make a fresh and unique video for free on your smartphone. This application is a professional-level video lighting editor that can enhance any movie by adding effects, trimming, splitting, transitions, and more. It has a filter option that allows you to modify the video's brightness, contrast saturation, and warmth. You may combine numerous photographs and videos to create a mix that appears better in the final video, in addition to brightness adjustment. Once you've got the video, go to Filters, Adjust, and choose the clip you wish to alter. You may adjust the video's visual characteristics here, such as brightness and contrast. You can even crop a video to make it seem better. ### 10\. [Chromic](https://apps.apple.com/us/app/chromic-video-filters-editor/id724295125) Chromic is a video brightening program that provides customers with a wide range of professional filters to enhance their movies substantially. The program comes with a strong image processing engine that allows it to create vivid, unique videos. Chromic will elevate your video editing skills to new heights. Use this useful tool to give all of your video recordings a unique flair. Even the darkest film may be brightened with Chromic. ![chromic video filters editor](https://images.wondershare.com/filmora/article-images/chromic-video-filters-editor.jpg) To brighten the video, on your smartphone, open the Chromic Video Editor. To add a video to the display, choose it. Adjust the brightness of the video by tapping on the Sun symbol. While you're at it, you may also change the colors and other settings. ## Part 2: How to Brighten a Video on Your iPhone Before or While Recording A gloomy video isn't fun to watch, but it's frequently difficult to know in the present if the video you're capturing is too dull to see clearly. Brightening an iPhone video can help you see the activity on-screen and make it more appealing if you share it on social media or post it to a website. Because the iPhone's built-in camera app does not enable you to brighten films after they have been recorded, you should always try to light a video before you begin recording. **Step 1:** Switch to video mode by opening the camera app and swiping left. Touch the screen to bring up a box with a sun-shaped symbol. **Step 2**: Move your fingers upward on the iPhone screen to brighten the scene when you begin filming. This may be done at any moment while the video is being recorded. **Conclusion** There are a ton of **Video Brightening Editor Apps** that will make brightening the videos after filming quite easy for you. Long gone are the days when you had to re-film now and again until you would get that one final shot that has every color adjustment aspect fit to perfection. With the advent of amazing software such as those covered in this article, brightening a dark video has never been easier! <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://smart-video-creator.techidaily.com/new-in-2024-introductory-video-editing-software-a-beginners-guide/"><u>New In 2024, Introductory Video Editing Software A Beginners Guide</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/2024-approved-filmora-free-trial-vs-torrent-which-one-is-safe-and-legit/"><u>2024 Approved Filmora Free Trial vs Torrent Which One Is Safe and Legit?</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-fcp-x-visual-effects-how-to-create-seamless-green-screen-composites-for-2024/"><u>New FCP X Visual Effects How to Create Seamless Green Screen Composites for 2024</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/2024-approved-best-free-video-watermarking-tools-top-picks/"><u>2024 Approved Best Free Video Watermarking Tools Top Picks</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/updated-in-2024-moviemaster-for-macos/"><u>Updated In 2024, MovieMaster for macOS</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-12-audio-converters-that-will-change-your-music-experience-forever/"><u>New 12 Audio Converters That Will Change Your Music Experience Forever</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-from-script-to-screen-a-kids-guide-to-movie-making-for-2024/"><u>New From Script to Screen A Kids Guide to Movie Making for 2024</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/updated-2024-approved-missing-imovie-on-android-here-are-10-fantastic-alternatives/"><u>Updated 2024 Approved Missing iMovie on Android? Here Are 10 Fantastic Alternatives</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-in-2024-10-essential-online-waveform-generators-for-audio-enthusiasts/"><u>New In 2024, 10 Essential Online Waveform Generators for Audio Enthusiasts</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/download-facebook-audio-as-mp3-with-these-top-online-tools-for-2024/"><u>Download Facebook Audio as MP3 with These Top Online Tools for 2024</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/in-2024-quick-fix-how-to-adjust-video-dimensions-with-ease/"><u>In 2024, Quick Fix How to Adjust Video Dimensions with Ease</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/updated-join-videos-without-restrictions-7-best-watermark-free-apps/"><u>Updated Join Videos Without Restrictions 7 Best Watermark-Free Apps</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/2024-approved-unlock-the-power-of-green-screen-top-10-free-apps-for-android-and-ios/"><u>2024 Approved Unlock the Power of Green Screen Top 10 Free Apps for Android & iOS</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-in-2024-the-top-free-wmv-video-assembly-software/"><u>New In 2024, The Top Free WMV Video Assembly Software</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/updated-2024-approved-discover-the-best-3d-animation-makers-for-stunning-videos/"><u>Updated 2024 Approved Discover the Best 3D Animation Makers for Stunning Videos</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/updated-2024-approved-video-editing-essentials-how-to-speed-up-clips-in-quicktime-player-windowsmac/"><u>Updated 2024 Approved Video Editing Essentials How to Speed Up Clips in QuickTime Player Windows/Mac</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/updated-download-edit-and-share-the-complete-online-video-editing-course-for-2024/"><u>Updated Download, Edit, and Share The Complete Online Video Editing Course for 2024</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/in-2024-shake-it-off-how-to-fix-unstable-video-in-after-effects/"><u>In 2024, Shake It Off How to Fix Unstable Video in After Effects</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/updated-top-video-smoothening-apps-for-mobile-devices-for-2024/"><u>Updated Top Video Smoothening Apps for Mobile Devices for 2024</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-improve-your-videos-audio-quality-removing-background-noise-in-fcpx/"><u>New Improve Your Videos Audio Quality Removing Background Noise in FCPX</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/2024-approved-the-ultimate-list-10-timecode-calculators-for-film-and-video-pros/"><u>2024 Approved The Ultimate List 10 Timecode Calculators for Film and Video Pros</u></a></li> <li><a href="https://ai-live-streaming.techidaily.com/in-2024-a-detailed-guide-to-stream-to-instagram-with-an-rtmp/"><u>In 2024, A Detailed Guide To Stream to Instagram With an RTMP</u></a></li> <li><a href="https://location-social.techidaily.com/change-location-on-yik-yak-for-your-motorola-moto-g73-5g-to-enjoy-more-fun-drfone-by-drfone-virtual-android/"><u>Change Location on Yik Yak For your Motorola Moto G73 5G to Enjoy More Fun | Dr.fone</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/new-how-to-make-animation-talk-explained-with-easy-steps/"><u>New How To Make Animation Talk? Explained with Easy Steps</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-change-country-on-app-store-for-apple-iphone-xs-with-7-methods-drfone-by-drfone-ios/"><u>How To Change Country on App Store for Apple iPhone XS With 7 Methods | Dr.fone</u></a></li> <li><a href="https://howto.techidaily.com/authentication-error-occurred-on-oppo-k11x-here-are-10-proven-fixes-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Authentication Error Occurred on Oppo K11x? Here Are 10 Proven Fixes | Dr.fone</u></a></li> <li><a href="https://ai-video-translation.techidaily.com/the-best-ai-translator-to-translate-videos-online-for-2024/"><u>The Best AI Translator to Translate Videos Online for 2024</u></a></li> <li><a href="https://activate-lock.techidaily.com/in-2024-how-to-bypass-activation-lock-on-apple-watch-or-apple-iphone-15-by-drfone-ios/"><u>In 2024, How To Bypass Activation Lock On Apple Watch Or Apple iPhone 15?</u></a></li> <li><a href="https://change-location.techidaily.com/how-to-use-ispoofer-on-vivo-t2x-5g-drfone-by-drfone-virtual-android/"><u>How to use iSpoofer on Vivo T2x 5G? | Dr.fone</u></a></li> <li><a href="https://techidaily.com/is-your-honor-magic5-ultimate-working-too-slow-heres-how-you-can-hard-reset-it-drfone-by-drfone-reset-android-reset-android/"><u>Is your Honor Magic5 Ultimate working too slow? Heres how you can hard reset it | Dr.fone</u></a></li> <li><a href="https://pokemon-go-android.techidaily.com/in-2024-planning-to-use-a-pokemon-go-joystick-on-honor-magic5-ultimate-drfone-by-drfone-virtual-android/"><u>In 2024, Planning to Use a Pokemon Go Joystick on Honor Magic5 Ultimate? | Dr.fone</u></a></li> <li><a href="https://ios-pokemon-go.techidaily.com/unova-stone-pokemon-go-evolution-list-and-how-catch-them-for-apple-iphone-xr-drfone-by-drfone-virtual-ios/"><u>Unova Stone Pokémon Go Evolution List and How Catch Them For Apple iPhone XR | Dr.fone</u></a></li> <li><a href="https://ai-editing-video.techidaily.com/everything-that-you-need-to-know-about-video-montages-ideas-techniqu-for-2024/"><u>Everything That You Need to Know About Video Montages- Ideas, Techniqu for 2024</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-forgot-locked-iphone-7-plus-password-learn-the-best-methods-to-unlock-drfone-by-drfone-ios/"><u>In 2024, Forgot Locked iPhone 7 Plus Password? Learn the Best Methods To Unlock | Dr.fone</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-how-to-do-tecno-camon-20-premier-5g-screen-sharing-drfone-by-drfone-android/"><u>In 2024, How To Do Tecno Camon 20 Premier 5G Screen Sharing | Dr.fone</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-guide-to-mirror-your-nokia-c12-plus-to-other-android-devices-drfone-by-drfone-android/"><u>In 2024, Guide to Mirror Your Nokia C12 Plus to Other Android devices | Dr.fone</u></a></li> <li><a href="https://howto.techidaily.com/8-solutions-to-solve-youtube-app-crashing-on-oppo-a79-5g-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>8 Solutions to Solve YouTube App Crashing on Oppo A79 5G | Dr.fone</u></a></li> </ul></div>
import mongoose from "mongoose"; import { IUserType } from "../types/user"; import { UserTypes } from "../enums/user"; const Schema = mongoose.Schema; const userSchema = new Schema( { name: { maxlength: 255, minlength: 5, required: true, trim: true, type: String, }, email: { lowercase: true, maxlength: 255, minlength: 5, required: true, trim: true, type: String, unique: true, }, password: { trim: true, required: true, type: String, }, phone: { required: true, type: String, }, type: { required: true, enum: UserTypes, type: String, }, }, { timestamps: true } ); userSchema.set("toJSON", { virtuals: true }); export default mongoose.model<IUserType>("User", userSchema);
<script lang="ts" setup> import type { FormError, FormSubmitEvent } from '#ui/types'; import { type PersistedCategory, useCategoryStore } from '~/store/category'; import { type PersistedProject, useProjectStore } from '~/store/project'; import { getNameFromExtendableListItem } from '~/utils/getNameFromExtendableListItem'; import AppContainer from '~/components/shared/AppContainer.vue'; const props = defineProps< | { resource: 'category'; initValue: PersistedCategory; } | { resource: 'project'; initValue: PersistedProject; } >(); function decomposeNameToParentAndExplicit( item: | { category: string; } | { project: string; }, ): { parentName: string; explicitName: string; } { const [explicitName, parentName] = getNameFromExtendableListItem( props.resource, item, ) .split(':') .reverse(); return { parentName, explicitName }; } interface EditState { id: string; parentName: string; explicitName: string; color?: string; } const state = ref<EditState>({ id: props.initValue.id, ...decomposeNameToParentAndExplicit(props.initValue), ...(props.resource === 'category' ? { color: props.initValue.color ?? 'transparent' } : {}), }); const isRoot = computed<boolean>(() => { const [explicitName, parentName] = getNameFromExtendableListItem( props.resource, props.initValue, ); return !parentName && Boolean(explicitName); }); const hasChildren = computed<boolean>(() => { switch (props.resource) { case 'project': { const projectStore = useProjectStore(); return 'project' in props.initValue ? Boolean(projectStore.getSubProjects(props.initValue.project).length) : false; } case 'category': { const categoryStore = useCategoryStore(); return 'category' in props.initValue ? Boolean( categoryStore.getSubCategories(props.initValue.category).length, ) : false; } default: return false; } }); function composeName( state: Pick<EditState, 'parentName' | 'explicitName'>, ): string { if (state.explicitName.includes(':')) throw new Error(`Category name cant contain ":" character`); if (!state.parentName) { return state.explicitName; } else { if (state.parentName.includes(':')) throw new Error(`Parent category name cant contain ":" character`); return `${state.parentName}:${state.explicitName}`; } } const validate = (state: EditState): FormError[] => { const errors = []; if (!state.explicitName) { errors.push({ path: 'explicit-name', message: 'Required' }); } else if (state.explicitName.includes(':')) errors.push({ path: 'explicit-name', message: `Category name cant contain ":" character`, }); return errors; }; const router = useRouter(); function submit(event: FormSubmitEvent<EditState>) { if (props.resource === 'category') { const categoryStore = useCategoryStore(); categoryStore.update(state.value.id, { color: event.data.color ?? 'transparent', category: composeName(event.data), }); router.push('/categories'); } else { const projectStore = useProjectStore(); projectStore.update(state.value.id, { project: composeName(event.data), }); router.push('/projects'); } } const possibleParentItems = computed<PersistedProject[] | PersistedCategory[]>( () => { switch (props.resource) { case 'project': { const projectStore = useProjectStore(); return projectStore.rootProjects.filter( (p) => p.project !== state.value.explicitName && p.id !== state.value.id, ); } case 'category': { const categoryStore = useCategoryStore(); return categoryStore.rootCategories.filter( (p) => p.category !== state.value.explicitName && p.id !== state.value.id, ); } } }, ); function cancel() { router.back(); } </script> <template> <AppContainer class="my-10"> <UCard class="h-screen"> <UForm :state="state" :validate="validate" @submit="submit"> <UFormGroup label="Name" name="explicit-name"> <UInput v-model="state.explicitName" /> </UFormGroup> <UFormGroup label="Parent Category" name="parent-name"> <USelectMenu v-model="state.parentName" :disabled="isRoot && hasChildren" :option-attribute="resource" :options="possibleParentItems" :value-attribute="resource" /> </UFormGroup> <UFormGroup v-if="resource === 'category'" label="Color" name="color"> <input v-model="state.color" class="w-full h-8 border-0" type="color" /> </UFormGroup> <div class="grid grid-cols-2 gap-6"> <UButton class="mt-4 justify-center" color="gray" @click="cancel"> Cancel </UButton> <UButton class="mt-4 justify-center" color="gray" type="submit"> Save </UButton> </div> </UForm> </UCard> </AppContainer> </template> <style scoped></style>
import { Pipe, PipeTransform } from '@angular/core'; import * as _ from 'underscore' @Pipe({ name: 'sort' }) export class SortPipe implements PipeTransform { transform(value: any[], arg?: string, tDato?: string): any { if (!value) return []; if (arg) { switch (tDato) { case 'cCarro': switch (arg) { case "up": return _.sortBy(value, function (dato) { return dato.propietario }); case "down": return _.sortBy(value, function (dato) { return dato.propietario }).reverse(); case "default": return value; } break; case 'cProducto': switch (arg) { case "up": return _.sortBy(value, function (dato) { return dato.nombre }); case "down": return _.sortBy(value, function (dato) { return dato.nombre }).reverse(); case "default": return value; } break; case 'cOrdenES': switch (arg) { case "default": return value; case "up-N": return _.sortBy(value, function (dato) { return dato.persona.nombreP }); case "down-N": return _.sortBy(value, function (dato) { return dato.persona.nombreP }).reverse(); case "up-G": return _.sortBy(value, function (dato) { var split = dato.numDocumentacion.split(": "); return Number(split[1]); }); case "down-G": return _.sortBy(value, function (dato) { var split = dato.numDocumentacion.split(": "); return Number(split[1]); }).reverse(); } break; case 'cPersonal': switch (arg) { case "up": return _.sortBy(value, function (dato) { return dato.nombreP }); case "down": return _.sortBy(value, function (dato) { return dato.nombreP }).reverse(); case "default": return value; } break; case 'cProductoB': switch (arg) { case "default": return value; case "n-up": return _.sortBy(value, function (dato) { return dato.nombre }); case "n-down": return _.sortBy(value, function (dato) { return dato.nombre }).reverse(); case "ct-up": return _.sortBy(value, function (dato) { return dato.categoria }); case "ct-down": return _.sortBy(value, function (dato) { return dato.categoria }).reverse(); case "pv-up": return _.sortBy(value, function (dato) { return dato.proveedor }); case "pv-down": return _.sortBy(value, function (dato) { return dato.proveedor }).reverse(); case "m-up": return _.sortBy(value, function (dato) { return dato.marca }); case "m-down": return _.sortBy(value, function (dato) { return dato.marca }).reverse(); case "pstandar-up": return _.sortBy(value, function (dato) { return dato.precioStandar }); case "pstandar-down": return _.sortBy(value, function (dato) { return dato.precioStandar }).reverse(); case "pnacional-up": return _.sortBy(value, function (dato) { return dato.precioNacional }); case "pnacional-down": return _.sortBy(value, function (dato) { return dato.precioNacional }).reverse(); case "pventa-up": return _.sortBy(value, function (dato) { return dato.precioVenta }); case "pventa-down": return _.sortBy(value, function (dato) { return dato.precioVenta }).reverse(); } break; case 'cProveedor': switch (arg) { case "up": return _.sortBy(value, function (dato) { return dato.proveedor }); case "down": return _.sortBy(value, function (dato) { return dato.proveedor }).reverse(); } break; case 'cBalde': switch (arg) { case "default": return value; case "num-up": return _.sortBy(value, function (dato) { return dato.numBalde }); case "num-down": return _.sortBy(value, function (dato) { return dato.numBalde }).reverse(); case "est-up": return _.sortBy(value, function (dato) { return dato.estadoBalde }); case "est-down": return _.sortBy(value, function (dato) { return dato.estadoBalde }).reverse(); } break; case 'cOrdenEC': switch (arg) { case "default": return value; case "up-F": return _.sortBy(value, function (dato) { return dato.factura }); case "down-F": return _.sortBy(value, function (dato) { return dato.factura }).reverse(); case "up-P": return _.sortBy(value, function (dato) { return dato.proveedor }); case "down-P": return _.sortBy(value, function (dato) { return dato.proveedor }).reverse(); case "up-B": return _.sortBy(value, function (dato) { return dato.listPcomprasO[0].destinoBodega }); case "down-B": return _.sortBy(value, function (dato) { return dato.listPcomprasO[0].destinoBodega }).reverse(); } break; case 'cOrdenTrabajoI': switch (arg) { case "default": return value; case "up-I": return _.sortBy(value, function (dato) { return dato.numOrdenSecuencial }); case "down-I": return _.sortBy(value, function (dato) { return dato.numOrdenSecuencial }).reverse(); case "up-B": return _.sortBy(value, function (dato) { return dato.bodega }); case "down-B": return _.sortBy(value, function (dato) { return dato.bodega }).reverse(); case "up-E": return _.sortBy(value, function (dato) { return dato.estadoProceso }); case "down-E": return _.sortBy(value, function (dato) { return dato.estadoProceso }).reverse(); } break; case 'cConsultaMedic': switch (arg) { case "default": return value; case "up-I": return _.sortBy(value, function (dato) { return dato.numOrdenSecuencial }); case "down-I": return _.sortBy(value, function (dato) { return dato.numOrdenSecuencial }).reverse(); case "up-B": return _.sortBy(value, function (dato) { return dato.bodegaOrigen }); case "down-B": return _.sortBy(value, function (dato) { return dato.bodegaOrigen }).reverse(); case "up-P": return _.sortBy(value, function (dato) { return dato.paciente }); case "down-P": return _.sortBy(value, function (dato) { return dato.paciente }).reverse(); } break; case 'cAtencionMedic': switch (arg) { case "default": return value; case "up-E": return _.sortBy(value, function (dato) { return dato.enfermedadCIE10 }); case "down-E": return _.sortBy(value, function (dato) { return dato.enfermedadCIE10 }).reverse(); case "up-P": return _.sortBy(value, function (dato) { return dato.pacienteMedic.empleado }); case "down-P": return _.sortBy(value, function (dato) { return dato.pacienteMedic.empleado }).reverse(); } break; case 'cAccidenteMedic': switch (arg) { case "default": return value; case "up-C": return _.sortBy(value, function (dato) { return dato.causaAccidente }); case "down-C": return _.sortBy(value, function (dato) { return dato.causaAccidente }).reverse(); } break; case 'cPermisoMedic': switch (arg) { case "default": return value; case "up-E": return _.sortBy(value, function (dato) { return dato.enfermedadCIE10 }); case "down-E": return _.sortBy(value, function (dato) { return dato.enfermedadCIE10 }).reverse(); case "up-P": return _.sortBy(value, function (dato) { return dato.pacienteMedic.empleado }); case "down-P": return _.sortBy(value, function (dato) { return dato.pacienteMedic.empleado }).reverse(); case "up-T": return _.sortBy(value, function (dato) { return dato.tipoPermiso }); case "down-T": return _.sortBy(value, function (dato) { return dato.tipoPermiso }).reverse(); } break; case 'cReportGeneralMedic': switch (arg) { case "default": return value; case "up-E": return _.sortBy(value, function (dato) { return dato.objNameG }); case "down-E": return _.sortBy(value, function (dato) { return dato.objNameG }).reverse(); case "up-C": return _.sortBy(value, function (dato) { return dato.contadorOcurrencia }); case "down-C": return _.sortBy(value, function (dato) { return dato.contadorOcurrencia }).reverse(); } break; case 'cOrdenPedido': switch (arg) { case "default": return value; case "up-T": return _.sortBy(value, function (dato) { return dato.tipoPedido }); case "down-T": return _.sortBy(value, function (dato) { return dato.tipoPedido }).reverse(); case "up-P": return _.sortBy(value, function (dato) { return dato.proveedor }); case "down-P": return _.sortBy(value, function (dato) { return dato.proveedor }).reverse(); case "up-B": return _.sortBy(value, function (dato) { return dato.barco }); case "down-B": return _.sortBy(value, function (dato) { return dato.barco }).reverse(); case "up-S": return _.sortBy(value, function (dato) { return dato.strNumSecuencial }); case "down-S": return _.sortBy(value, function (dato) { return dato.strNumSecuencial }).reverse(); case "up-E": return _.sortBy(value, function (dato) { return dato.empresa }); case "down-E": return _.sortBy(value, function (dato) { return dato.empresa }).reverse(); case "up-F": return _.sortBy(value, function (dato) { return dato.fechaPedido }); case "down-F": return _.sortBy(value, function (dato) { return dato.fechaPedido }).reverse(); } break; case 'cBodega': switch (arg) { case "default": return value; case "up-T": return _.sortBy(value, function (dato) { return dato.tipoBodega }); case "down-T": return _.sortBy(value, function (dato) { return dato.tipoBodega }).reverse(); case "up-N": return _.sortBy(value, function (dato) { return dato.nombreBodega }); case "down-N": return _.sortBy(value, function (dato) { return dato.nombreBodega }).reverse(); } break; } } else return value; } }
/** * Feb-16-2014 * @author Ivoryhe * Spiral Matrix II * * Given an integer n, generate a square matrix filled with * elements from 1 to n2 in spiral order. * * For example, * Given n = 3, * You should return the following matrix: * [ * [ 1, 2, 3 ], * [ 8, 9, 4 ], * [ 7, 6, 5 ] * ] */ public class Solution { public int[][] generateMatrix(int n) { int[][] matrix = new int[n][n]; if(n <=0) {return matrix;} int step = 0; if(n == 1){ step = 1; } else{ step = n-1; } int circle = (n+1)/2 - 1; int count = 1; int max = n*n; for(int i=0; i<=circle; i++){ int j=i; //top while(j<step+i && count<=max){ matrix[i][j] = count; count++; j++; } //right j=i; while(j<step+i && count<=max){ matrix[j][n-1-i] = count; count++; j++; } //down j=i; while(j<step+i && count<=max){ matrix[n-1-i][n-1-j] = count; count++; j++; } //left j=i; while(j<step+i && count<=max){ matrix[n-1-j][i] = count; count++; j++; } step = step -1; if(step == 1){ step = 1; } else{ step = step-1; } } return matrix; } }