text
stringlengths
184
4.48M
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { DashboardComponent } from './dashboard.component'; import { ProjectComponent } from './projects/projects/projects.component'; import { ProfileComponent } from './Profile/Profile.component'; import { SupportComponent } from './Support/Support.component'; import { ModalModule } from '../_modal'; const routes: Routes = [ { path: '', pathMatch: 'full', redirectTo: 'home' }, { path: 'home', component: DashboardComponent, }, { path: 'projects', component: ProjectComponent, }, { path: 'profile', component: ProfileComponent, }, { path: 'support', component: SupportComponent, }, ]; @NgModule({ imports: [RouterModule.forChild(routes),ModalModule], exports: [RouterModule], }) export class DashboardRoutingModule {}
use itertools::Itertools; use ndarray::Array2; use num_integer::Integer; use std::{ collections::{HashMap, HashSet, VecDeque}, io, }; type Coord = (usize, usize); fn adjacents(y: usize, x: usize, h: usize, w: usize) -> impl Iterator<Item = Coord> { [ if x > 0 { Some((y, x - 1)) } else { None }, if x < w - 1 { Some((y, x + 1)) } else { None }, if y > 0 { Some((y - 1, x)) } else { None }, if y < h - 1 { Some((y + 1, x)) } else { None }, ] .into_iter() .flatten() } fn wrapping_adjacents( y: usize, x: usize, h: usize, w: usize, ) -> impl Iterator<Item = (i32, i32, usize, usize)> { [ if x > 0 { (0, 0, y, x - 1) } else { (0, -1, y, w - 1) }, if x < w - 1 { (0, 0, y, x + 1) } else { (0, 1, y, 0) }, if y > 0 { (0, 0, y - 1, x) } else { (-1, 0, h - 1, x) }, if y < h - 1 { (0, 0, y + 1, x) } else { (1, 0, 0, x) }, ] .into_iter() } fn find_targets( steps_remaining: u8, y: usize, x: usize, grid: &Array2<char>, target_bitmap: &mut Array2<bool>, visited: &mut HashSet<(u8, usize, usize)>, ) { if !visited.insert((steps_remaining, y, x)) { return; } if steps_remaining == 0 { target_bitmap[(y, x)] = true; return; } let (h, w) = grid.dim(); adjacents(y, x, h, w) .filter(|(yy, xx)| grid[(*yy, *xx)] == '.') .for_each(|(yy, xx)| { find_targets(steps_remaining - 1, yy, xx, grid, target_bitmap, visited) }); } fn find_min_pos(ds: &Array2<usize>) -> Vec<(usize, usize)> { ds.indexed_iter().min_set_by_key(|(_, d)| *d).into_iter().map(|(c, _)| c).collect() } fn find_targets_count( steps_remaining: u8, pos: Vec<(usize, usize)>, grid: &Array2<char> ) -> usize { let mut bitmap = Array2::default(grid.dim()); let mut visited = HashSet::new(); for (y, x) in pos.iter().copied() { find_targets(steps_remaining, y, x, grid, &mut bitmap, &mut visited); } bitmap.iter().filter(|x| **x).count() } fn part1(input: &Array2<char>, start: (usize, usize)) -> usize { let mut target_bitmap = Array2::<bool>::default(input.dim()); let mut visited_state = HashSet::new(); find_targets( 64, start.0, start.1, input, &mut target_bitmap, &mut visited_state, ); target_bitmap.iter().filter(|x| **x).count() } fn part2(grid: &Array2<char>, start: (usize, usize)) -> usize { let mut distance_maps = Array2::from_elem((5, 5), Array2::from_elem(grid.dim(), usize::MAX)); let mut q = VecDeque::new(); let (h, w) = grid.dim(); // Calculate distances for 5x5 full squares using BFS for (dy, dx, y, x) in wrapping_adjacents(start.0, start.1, h, w) { q.push_back((dy, dx, y, x, 1)); } while let Some((dy, dx, y, x, dist)) = q.pop_front() { let dm = &mut distance_maps[((dy + 2) as usize, (dx + 2) as usize)]; let d = &mut dm[(y, x)]; if *d <= dist { continue; } *d = dist; let next_coords = wrapping_adjacents(y, x, h, w) .map(|(dyy, dxx, yy, xx)| (dy + dyy, dx + dxx, yy, xx)) .filter(|(dyy, dxx, yy, xx)| { grid[(*yy, *xx)] == '.' && *dyy >= -2 && *dyy <= 2 && *dxx >= -2 && *dxx <= 2 }); for (ddy, ddx, yy, xx) in next_coords { q.push_back((ddy, ddx, yy, xx, dist + 1)); } } for dm in distance_maps.iter_mut() { for (_, d) in dm.indexed_iter_mut() { if d.is_even() { *d = usize::MAX; } } } let filled_even_val = distance_maps[(0, 0)].iter().filter(|x| **x < usize::MAX).count(); let filled_odd_val = distance_maps[(0, 1)].iter().filter(|x| **x < usize::MAX).count(); let min_dist_1_1 = *distance_maps[(1 + 2, 1 + 2)].iter().min().unwrap(); let max_dist_1_1 = *distance_maps[(1+2, 1+2)].iter().filter(|x| **x < usize::MAX).max().unwrap(); let min_dist_1_2 = *distance_maps[(1+2, 2+2)].iter().min().unwrap(); let corner_dist_delta = min_dist_1_2 - min_dist_1_1; let calc_corner_min_dist = |d: usize| (d-2) * corner_dist_delta + min_dist_1_1 + (d-2) / 2 * 2; let calc_corner_max_dist = |d: usize| (d-2) * corner_dist_delta + max_dist_1_1 + (d-1) / 2 * 2; let min_dist_0_1 = *distance_maps[(2, 1 + 2)].iter().min().unwrap(); let max_dist_0_1 = *distance_maps[(2, 1+2)].iter().filter(|x| **x < usize::MAX).max().unwrap(); let min_dist_0_2 = *distance_maps[(2, 2+2)].iter().min().unwrap(); let straight_dist_delta = min_dist_0_2 - min_dist_0_1; let calc_straight_min_dist = |d: usize| (d-1) * straight_dist_delta + min_dist_0_1 + (d-1) / 2 * 2; let calc_straight_max_dist = |d: usize| (d-1) * straight_dist_delta + max_dist_0_1 + (d-1) / 2 * 2; // now we know how to calculate min/max distances for each square // determine how far we get const STEPS: usize = 26501365; let corner_entered_sq_dist = (10..).find(|&d| calc_corner_min_dist(d) > STEPS).unwrap() - 1; let corner_filled_sq_dist = (10..).find(|&d| calc_corner_max_dist(d) > STEPS).unwrap() - 1; let straight_entered_sq_dist = (10..).find(|&d| calc_straight_min_dist(d) > STEPS).unwrap() - 1; let straight_filled_sq_dist = (10..).find(|&d| calc_straight_max_dist(d) > STEPS).unwrap() - 1; assert_eq!(corner_filled_sq_dist, straight_filled_sq_dist); let filled_sq_dist = corner_filled_sq_dist; // Filled squares are easy to calculate, but we must manually check the partial ones. // And I think we must do all 8 directions separately let mut partial_counts = HashMap::new(); for d in filled_sq_dist+1..=straight_entered_sq_dist { let steps: u8 = (STEPS - calc_straight_min_dist(d)).try_into().unwrap(); // top let start_pos = if d.is_even() { find_min_pos(&distance_maps[(0, 2)]) }else { find_min_pos(&distance_maps[(1, 2)]) }; partial_counts.insert((d, -1, 0), find_targets_count(steps, start_pos, grid)); // bottom let start_pos = if d.is_even() { find_min_pos(&distance_maps[(4, 2)]) }else { find_min_pos(&distance_maps[(3, 2)]) }; partial_counts.insert((d, 1, 0), find_targets_count(steps, start_pos, grid)); // left let start_pos = if d.is_even() { find_min_pos(&distance_maps[(2, 0)]) }else { find_min_pos(&distance_maps[(2, 1)]) }; partial_counts.insert((d, 0, -1), find_targets_count(steps, start_pos, grid)); // right let start_pos = if d.is_even() { find_min_pos(&distance_maps[(2, 4)]) }else { find_min_pos(&distance_maps[(2, 3)]) }; partial_counts.insert((d, 0, 1), find_targets_count(steps, start_pos, grid)); } for d in filled_sq_dist+1..=corner_entered_sq_dist { let steps: u8 = (STEPS - calc_corner_min_dist(d)).try_into().unwrap(); // Top left let start_pos = if d.is_even() { find_min_pos(&distance_maps[(1, 1)]) } else { find_min_pos(&distance_maps[(1, 0)]) }; partial_counts.insert((d, -1, -1), find_targets_count(steps, start_pos, grid)); // Bottom left let start_pos = if d.is_even() { find_min_pos(&distance_maps[(3, 1)]) } else { find_min_pos(&distance_maps[(3, 0)]) }; partial_counts.insert((d, 1, -1), find_targets_count(steps, start_pos, grid)); // Bottom right let start_pos = if d.is_even() { find_min_pos(&distance_maps[(3, 3)]) } else { find_min_pos(&distance_maps[(3, 4)]) }; partial_counts.insert((d, 1, 1), find_targets_count(steps, start_pos, grid)); // Top right let start_pos = if d.is_even() { find_min_pos(&distance_maps[(1, 3)]) } else { find_min_pos(&distance_maps[(1, 4)]) }; partial_counts.insert((d, -1, 1), find_targets_count(steps, start_pos, grid)); } assert_eq!(partial_counts.len(), 12); // 1 + 4 * (Sum of 2, 4, 6, ..., n) // Sum of first n even numbers == n* (n+1) let filled_even_sq_count = 1 + 4 * (filled_sq_dist/2)*(filled_sq_dist/2 + 1); //1 + ((2..=filled_sq_dist).step_by(2).sum::<usize>()) * 4; // 4 * (Sum of 1, 3, 5, ..., n) // Sum of n first odd numbers == n^2 let filled_odd_sq_count = (filled_sq_dist.div_ceil(2)).pow(2) * 4; let filled_sum = filled_even_sq_count * filled_even_val + filled_odd_sq_count * filled_odd_val; let partial_sum: usize = partial_counts.into_iter() .map(|((d, y, x), v)| { if y == 0 || x == 0 { v } else { (d-1) * v } }) .sum(); filled_sum + partial_sum } fn find_start(mut arr: Array2<char>) -> ((usize, usize), Array2<char>) { let start = arr.indexed_iter().find(|(_, c)| **c == 'S').unwrap().0; arr[start] = '.'; (start, arr) } fn main() -> io::Result<()> { let input = aoclib::read_input_char_matrix()?; let (start, input) = find_start(input); let p1 = part1(&input, start); println!("Part 1: {}", p1); let p2 = part2(&input, start); println!("Part 2: {}", p2); Ok(()) } #[cfg(test)] mod test { use super::*; #[test] fn test_real_input() { let input = aoclib::read_file_char_matrix(aoclib::get_test_input_file!(21)).unwrap(); let (start, input) = find_start(input); let p1 = part1(&input, start); assert_eq!(p1, 3809); let p2 = part2(&input, start); assert_eq!(p2, 629720570456311); } }
<?xml version="1.0" encoding="UTF-8"?> <refentry xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svg="http://www.w3.org/2000/svg" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:db="http://docbook.org/ns/docbook" xmlns:scilab="http://www.scilab.org" xml:lang="fr" xml:id="do"> <refnamediv> <refname>do</refname> <refpurpose>Mot-clé utilisé pour les boucles</refpurpose> </refnamediv> <refsection> <title>Description</title> <para> Le mot clé <literal>do</literal> peut être utilisé dans une instruction <literal>for</literal> ou <literal>while</literal> pour séparer la définition de la variable de boucle de l'ensemble des instructions. </para> </refsection> <refsection> <title>Exemples</title> <programlisting role="example"><![CDATA[ i = 0 while i<5 do disp("i"); i = i + 1; end ]]></programlisting> <programlisting role="example"><![CDATA[ n=5; for i = 1:n do for j = 1:n do a(i,j) = 1/(i+j-1); end; end ]]></programlisting> </refsection> <refsection role="see also"> <title>Voir aussi</title> <simplelist type="inline"> <member> <link linkend="for">for</link> </member> <member> <link linkend="while">while</link> </member> </simplelist> </refsection> </refentry>
package sugoi.tools; /** * CSV Import-Export Tool * Based on thx.csv * * @author fbarbut<[email protected]> */ class Csv { public var separator :String; var headers : Array<String>; //datas accessible in both forms public var datas : Array<Array<String>>; public var datasAsMap : Array<Map<String,String>>; public var step:Int;//@deprecated public function new() { separator = ","; datas = []; headers = []; } public function setHeaders(_headers){ headers = _headers; } public function addDatas(d:Array<Dynamic>) { datas.push( Lambda.array(Lambda.map(d, function(x) return StringTools.trim(Std.string(x)) )) ); } public function getHeaders(){ return headers; } public function getDatas():Array<Array<String>>{ return datas; } public function isEmpty(){ return datasAsMap == null || datasAsMap.length == 0; } /** * Import CSV / DCSV datas as Maps */ public function importDatasAsMap(d:String):Array<Map<String,String>>{ if (headers.length == 0) throw "CSV headers should be defined"; //separator detection try{ var x = d.split("\n"); if (x[0].split(";").length > x[0].split(",").length) separator = ";"; }catch (e:Dynamic){} //trace(separator); var _datas = new Array<Array<String>>(); if (separator == ","){ _datas = thx.csv.Csv.decode(d); }else{ _datas = thx.csv.DCsv.decode(d); } /*for(line in d.split("\n")){ _datas.push(line.split(separator)); }*/ //removes headers _datas.shift(); //cleaning for ( o in _datas.copy() ) { //remove empty lines if (o == null || o.length <= 1) { _datas.remove(o); continue; } //remove remaining quotes for (i in 0...o.length) { var s = o[i]; if(s.substr(0,1)=="\""){ s = s.substr(1); } if(s.substr(s.length-1,1)=="\""){ s = s.substr(0,s.length-1); } o[i] = s; } //nullify empty fields for (i in 0...o.length) { if (o[i] == "" || o[i] == "null" || o[i]=="NULL") { o[i] = null; continue; } //clean spaces and useless chars o[i] = StringTools.trim(o[i]); o[i] = StringTools.replace(o[i], "\n", ""); o[i] = StringTools.replace(o[i], "\t", ""); o[i] = StringTools.replace(o[i], "\r", ""); } //remove empty lines if (isNullRow(o)) _datas.remove(o); } //cut columns which are out of headers for ( d in _datas){ datas.push( d.copy().splice(0, headers.length) ); } //maps datasAsMap = new Array<Map<String,String>>(); for ( d in datas){ var m = new Map(); for ( h in 0...headers.length){ //nullify var v = d[h]; if ( v == "" || v == "null" || v=="NULL" ) v = null; m[headers[h]] = v; } datasAsMap.push(m); } return datasAsMap; } /** * Import CSV Datas * * @deprecated Use importDatasAsMap instead */ public function importDatas(d:String):Array<Array<String>> { d = StringTools.replace(d, "\r", ""); //vire les \r var data = d.split("\n"); //separator detection if (data[0].split(";").length > data[0].split(",").length) separator = ";"; var out = new Array<Array<String>>(); var rowLen = null; if (headers != null && headers.length > 0) rowLen = headers.length; //fix quoted fields with comas inside : "23 allée des Taupes, 46100 Camboulis" for (d in data) { var x = d.split('"'); for (i in 0...x.length) { if (i % 2 == 1) x[i] = StringTools.replace(x[i], separator, "|"); } d = x.join(""); var row = d.split(separator); if (rowLen != null) row = row.splice(0, rowLen); //no extra columns out.push(row); } for (u in out) { for (i in 0...u.length) { u[i] = StringTools.replace(u[i], "|", separator); } } //cleaning for ( o in out.copy() ) { //remove empty lines if (o == null || o.length <= 1) { out.remove(o); continue; } //nullify empty fields for (i in 0...o.length) { if (o[i] == "" || o[i] == "null" || o[i]=="NULL") { o[i] = null; continue; } //clean spaces and useless chars o[i] = StringTools.trim(o[i]); o[i] = StringTools.replace(o[i], "\n", ""); o[i] = StringTools.replace(o[i], "\t", ""); o[i] = StringTools.replace(o[i], "\r", ""); } //remove empty lines if (isNullRow(o)) out.remove(o); } //remove headers out.shift(); //utf-8 check for ( row in out.copy()) { for ( i in 0...row.length) { var t = row[i]; if (t != "" && t != null) { // try{ // if (!haxe.Utf8.validate(t)) { // t = haxe.Utf8.encode(t); // } // }catch (e:Dynamic) {} row[i] = t; } } } return out; } private function isNullRow(row:Array<String>):Bool{ for (c in row) if (c != null) return false; return true; } /** * Print datas as a CSV file * * @param data * @param headers * @param fileName */ public static function printCsvDataFromObjects(data:Iterable<Dynamic>,headers:Array<String>,fileName:String) { App.current.setTemplate('empty.mtt'); Web.setHeader("Content-type", "text/csv"); Web.setHeader('Content-disposition', 'attachment;filename="$fileName.csv"'); if(App.t==null) { Sys.println(Lambda.map(headers,function(t) return t).join(";")); }else{ Sys.println(Lambda.map(headers,function(t) return App.t._(t)).join(";")); } for (d in data) { var row = []; for ( f in headers){ var v = Reflect.getProperty(d, f); row.push( "\""+(v==null?"":v)+"\""); } Sys.println(row.join(";")); } return true; } /** * Separator is ";" for better compat with french excel users */ public static function printCsvDataFromStringArray(data:Array<Array<String>>,headers:Array<String>,fileName:String) { Web.setHeader("Content-type", "text/csv"); Web.setHeader('Content-disposition', 'attachment;filename="$fileName.csv"'); Sys.println(Lambda.map(headers,function(t) return App.t._(t)).join(";")); for (r in data) { var row = []; for ( v in r ){ row.push( "\""+(v==null?"":v)+"\""); } Sys.println(row.join(";")); } return true; } public static function escape(str:String){ if(str==null) return ""; str = StringTools.replace(str,'"',"'"); str.split("\n").join(" "); str.split("\r").join(" "); str.split("\t").join(" "); return str; } /** * do a "array.shift()" on datas */ public function shift(){ if (datasAsMap != null) datasAsMap.shift(); datas.shift(); } }
import axios from 'axios'; import React, { useState, useEffect,useRef } from 'react'; import { toast } from 'react-toastify'; function Pincode() { const [pin, setPin] = useState(['', '', '', '']); const [userId, setUserId] = useState(''); const inputRefs = useRef([]); useEffect(() => { const storedUserId = sessionStorage.getItem('userId'); if (storedUserId) { setUserId(storedUserId); } }, []); const handleVerify = (e) => { e.preventDefault(); const pinValue = pin.join(''); if (!userId) { toast.error('User ID is missing.'); return; } if (pinValue.length !== 4) { toast.error('Please enter a valid pin code.'); return; } axios.post('http://103.69.196.162:2000/signup/step2', { pin: pinValue, userId: userId }) .then((response) => { if (response.status === 200) { sessionStorage.setItem('userpin', pinValue); toast.success('Pin Set successful!', { position: 'top-center', autoClose: 2000, onClose: () => { window.location.href = '/identitycard'; } }); } else { toast.error('Failed to set pin. Please try again later.'); console.error('Failed to set pin:', response); } }) .catch((error) => { toast.error('Failed to set pin. Please try again later.'); console.error('Failed to set pin:', error); }); }; const handleChange = (index, value) => { const newPin = [...pin]; newPin[index] = value; setPin(newPin); // Move focus to the next input field if value is not empty and it's not the last input field if (value !== '' && index < inputRefs.current.length - 1) { inputRefs.current[index + 1].focus(); } }; return ( <div className="page-header position-relative"> <div className='background-div'></div> <div className="container"> <div className='row h-100'> <div className="col-md-7 content-center bg-white"> <div className="logo-container" style={{ textAlign: 'left' }}> <img src="../assets/images/logo.svg" alt="" /> </div> <div className='center_div'> <div className='row'> <div className='col-md-6 m-auto'> <div className="card-plain"> <h3 className='text-center text-dark'>Set A Pin Code</h3> <p className='text-center text-body my-5'>Enter 04 Digit Code</p> <form className="form" onSubmit={handleVerify}> <div className="content d-flex justify-content-center"> {pin.map((value, index) => ( <input key={index} type="text" className="form-control mb-lg-4 mb-2 py-lg-3 py-2 otp-input" maxLength="1" value={value} onChange={(e) => handleChange(index, e.target.value)} ref={(inputRef) => { inputRefs.current[index] = inputRef; }} /> ))} </div> <div className="footer text-center"> <button type="submit" className="btn btn-primary btn-lg btn-block waves-effect waves-light mb-3" style={{ backgroundColor: '#919296', borderRadius: '16px' }} > Verify </button> </div> </form> </div> </div> </div> </div> </div> <div className='col-md-5 position-relative d-flex align-items-center'> <div className='secat_img'> <img className='img-fluid' src="../assets/images/s_up_img.png" alt="" /> </div> </div> </div> </div> </div> ); } export default Pincode;
class BinaryMaxHeap: def __init__(self): self.heap = [] self.size = 0 def parent(self, ind): return ind//2 def left_child(self, ind): return ind * 2 + 1 def right_child(self, ind): return ind * 2 + 2 def heapify(self, ind): if ind >= self.size: return left = self.left_child(ind) largest = left if left < self.size and self.heap[left] > self.heap[ind] else ind right = self.right_child(ind) largest = right if right < self.size and self.heap[right] > self.heap[largest] else largest if largest != ind: self.heap[ind], self.heap[largest] = self.heap[largest], self.heap[ind] self.heapify(largest) def heapify_up(self, ind): if ind <= 0: return parent = self.parent(ind) if self.heap[parent] < self.heap[ind]: self.heap[parent], self.heap[ind] = self.heap[ind], self.heap[parent] self.heapify_up(parent) def insert(self, val): self.heap.append(val) self.size += 1 self.heapify_up(self.size-1) def delete(self, val): if self.size == 0: return 'Empty' if val not in self.heap: return 'Not found' ind = self.heap.index(val) self.heap[ind], self.heap[-1] = self.heap[-1], self.heap[ind] self.heap.pop() self.size -= 1 self.heapify(ind) def get_max(self): if self.size == 0: return 'Empty' return self.heap[0] def pop_max(self): if self.size == 0: return 'Empty' self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0] out = self.heap.pop() self.size -= 1 self.heapify(0) return out def get_min(self): # max heap so min will be in leaf nodes n = self.size out = float('inf') for i in range(n//2, n): out = min(out, self.heap[i]) return out def increase_val(self, val, new_val): if self.size == 0: return 'Empty' ind = self.heap.index(val) self.heap[ind] = new_val self.heapify_up(ind) def decrease_val(self, val, new_val): if self.size == 0: return 'Empty' ind = self.heap.index(val) self.heap[ind] = new_val self.heapify(ind) def build_from_array(self, array): # O(n) # https://stackoverflow.com/questions/9755721/how-can-building-a-heap-be-on-time-complexity self.heap = array self.size = len(array) for i in range(self.size//2,-1,-1): self.heapify(i) def kth_largest(self, k): # O(klogn ) removed = [] out = None if k > self.size: return out for i in range(k-1): removed.append(self.pop_max()) out = self.pop_max() removed.append(out) for i in removed: self.insert(i) return out def kth_largest_2(self,k): # O(n) prev_size = self.size removed = [] self.size = min(self.size, 2**k-1) for _ in range(k-1): removed.append(self.pop_max()) out = self.get_max() for i in removed: self.insert(i) self.size = prev_size return out def show(self): print(self.heap) class BinaryMinHeap: def __init__(self): self.heap = [] self.size = 0 def parent(self, ind): return ind//2 def left_child(self, ind): return 2*ind + 1 def right_child(self, ind): return 2*ind + 2 def heapify(self, ind): if ind >= self.size: return left = self.left_child(ind) right = self.right_child(ind) if left < self.size and self.heap[left] < self.heap[ind]: smallest = left else: smallest = ind if right < self.size and self.heap[right] < self.heap[smallest]: smallest = right if smallest != ind: self.heap[ind], self.heap[smallest] = self.heap[smallest], self.heap[ind] self.heapify(smallest) def heapify_up(self, ind): if ind == 0: return parent = self.parent(ind) if self.heap[ind] < self.heap[parent]: self.heap[ind], self.heap[parent] = self.heap[parent], self.heap[ind] self.heapify_up(parent) def insert(self, val): self.heap.append(val) self.size += 1 self.heapify_up(self.size-1) def delete(self, val): if self.size == 0: return 'Empty' if val not in self.heap: return 'Not found' ind = self.heap.index(val) self.heap[ind], self.heap[-1] = self.heap[-1], self.heap[ind] self.heap.pop() self.size -= 1 self.heapify(ind) def get_min(self): if self.size == 0: return 'Empty' return self.heap[0] def pop_min(self): if self.size == 0: return 'Empty' self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0] out = self.heap.pop() self.size -= 1 self.heapify(0) return out def get_max(self): # min heap so max will be in leaf nodes n = self.size out = -float('inf') for i in range(n//2, n): out = max(out, self.heap[i]) return out def increase_val(self, val, new_val): if self.size == 0: return 'Empty' ind = self.heap.index(val) self.heap[ind] = new_val self.heapify(ind) def decrease_val(self, val, new_val): if self.size == 0: return 'Empty' ind = self.heap.index(val) self.heap[ind] = new_val self.heapify_up(ind) def build_from_array(self, array): for i in array: self.insert(i) def kth_smallest(self, k): # O(klogn) removed = [] out = None if k > self.size: return out for i in range(k-1): removed.append(self.pop_min()) out = self.pop_min() removed.append(out) for i in removed: self.insert(i) return out def kth_smallest_2(self, k): # O(n) prev_size = self.size removed = [] self.size = min(self.size, 2**k-1) for _ in range(k-1): removed.append(self.pop_min()) out = self.get_min() for i in removed: self.insert(i) self.size = prev_size return out def show(self): print(self.heap) # Test cases for MaxHeap if __name__ == "__main__": # Create a max heap print('max heap\n') max_heap = BinaryMaxHeap() # Edge Test 1: Insert and delete in an empty heap empty_heap = BinaryMaxHeap() print(empty_heap.get_max()) # Expected output: None print(empty_heap.pop_max()) # Expected output: None # Edge Test 2: Insert and delete the only element heap_with_one_element = BinaryMaxHeap() heap_with_one_element.insert(42) print(heap_with_one_element.get_max()) # Expected output: 42 print(heap_with_one_element.pop_max()) # Expected output: 42 # Edge Test 3: Insert duplicate elements heap_with_duplicates = BinaryMaxHeap() heap_with_duplicates.insert(5) heap_with_duplicates.insert(5) heap_with_duplicates.insert(5) heap_with_duplicates.insert(5) print(heap_with_duplicates.get_max()) # Expected output: 5 # Edge Test 4: Insert elements in descending order, then heapify descending_heap = BinaryMaxHeap() descending_heap.insert(5) descending_heap.insert(4) descending_heap.insert(3) descending_heap.insert(2) descending_heap.insert(1) descending_heap.heapify(0) # Heapify the descending order heap print(descending_heap.get_max()) # Expected output: 5 # Edge Test 5: Insert elements in ascending order, then heapify ascending_heap = BinaryMaxHeap() ascending_heap.insert(1) ascending_heap.insert(2) ascending_heap.insert(3) ascending_heap.insert(4) ascending_heap.insert(5) ascending_heap.heapify(0) # Heapify the ascending order heap print(ascending_heap.get_max()) # Expected output: 5 # Edge Test 6: Insert random elements and test heapify random_heap = BinaryMaxHeap() random_heap.insert(9) random_heap.insert(2) random_heap.insert(7) random_heap.insert(4) random_heap.insert(6) random_heap.insert(3) random_heap.heapify(0) # Expected output: 9 print(random_heap.get_max()) # expected: 9 print(random_heap.get_min()) # expected: 2 print(random_heap.kth_largest(3)) # expected: 6 print(random_heap.kth_largest(4)) # expected: 4 print(random_heap.kth_largest_2(3)) # expected: 6 print(random_heap.kth_largest_2(4)) # expected: 4 # tests for min heap --------------------------------- print('\nmin heap\n') min_heap = BinaryMinHeap() # Test insert method min_heap.insert(5) min_heap.insert(9) min_heap.insert(3) min_heap.insert(7) print(min_heap.heap) # Test get_min method print(min_heap.get_min()) # expected: 3 # Test delete method print(min_heap.delete(2)) # expected: None print(min_heap.heap) # Test pop_min method print(min_heap.pop_min()) # expected: 3 print(min_heap.heap) # Test heapify method min_heap.heapify(0) print(min_heap.heap) empty_heap = BinaryMinHeap() print(empty_heap.heap) # Expected output: [] # Edge Test 2: Insert and delete the only element heap_with_one_element = BinaryMinHeap() heap_with_one_element.insert(42) print(heap_with_one_element.heap) # Expected output: [42] print(heap_with_one_element.pop_min()) # Expected output: 42 print(heap_with_one_element.heap) # Expected output: [] # Edge Test 3: Insert duplicate elements heap_with_duplicates = BinaryMinHeap() heap_with_duplicates.insert(5) heap_with_duplicates.insert(5) heap_with_duplicates.insert(5) heap_with_duplicates.insert(5) print(heap_with_duplicates.heap) # Expected output: [5, 5, 5, 5] # Edge Test 4: Insert elements in ascending order, then heapify ascending_heap = BinaryMinHeap() ascending_heap.insert(1) ascending_heap.insert(2) ascending_heap.insert(3) ascending_heap.insert(4) ascending_heap.insert(5) ascending_heap.heapify(0) print(ascending_heap.heap) # Expected output: [1, 2, 3, 4, 5] # Edge Test 5: Insert elements in descending order, then heapify descending_heap = BinaryMinHeap() descending_heap.insert(5) descending_heap.insert(4) descending_heap.insert(3) descending_heap.insert(2) descending_heap.insert(1) descending_heap.heapify(0) print(descending_heap.heap) # Expected output: [1, 2, 3, 5, 4] # Edge Test 6: Insert random elements and test heapify random_heap = BinaryMinHeap() random_heap.insert(9) random_heap.insert(2) random_heap.insert(7) random_heap.insert(4) random_heap.insert(6) random_heap.insert(3) random_heap.heapify(0) print(random_heap.heap) # Expected output: The min heap after heapify print(random_heap.get_max()) # expected: 9 print(random_heap.kth_smallest(3)) # expected: 4 print(random_heap.kth_smallest(4)) # expected: 6 print(random_heap.kth_smallest_2(3)) # expected: 4 print(random_heap.kth_smallest_2(4)) # expected: 6
;;; GNU Guix --- Functional package management for GNU ;;; Copyright © 2013, 2014, 2015 Andreas Enge <[email protected]> ;;; Copyright © 2014 Eric Bavier <[email protected]> ;;; Copyright © 2016 Mark H Weaver <[email protected]> ;;; Copyright © 2016 Efraim Flashner <[email protected]> ;;; ;;; This file is part of GNU Guix. ;;; ;;; GNU Guix 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. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>. (define-module (gnu packages fontutils) #:use-module (gnu packages) #:use-module (gnu packages compression) #:use-module (gnu packages ghostscript) #:use-module (gnu packages perl) #:use-module (gnu packages pkg-config) #:use-module (gnu packages autotools) #:use-module (gnu packages gettext) #:use-module (gnu packages python) #:use-module (gnu packages image) #:use-module (gnu packages glib) #:use-module (gnu packages xorg) #:use-module (gnu packages gtk) #:use-module (gnu packages xml) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix svn-download) #:use-module (guix build-system cmake) #:use-module (guix build-system gnu)) (define-public freetype (package (name "freetype") (version "2.6") (source (origin (method url-fetch) (uri (string-append "mirror://savannah/freetype/freetype-" version ".tar.bz2")) (sha256 (base32 "0zilx15fwcpa8hmcxpc423jwb8ijw4qpq968kh18akvn4j0znsc4")))) (build-system gnu-build-system) (arguments `(#:phases ;; This should not be necessary; reported upstream as ;; https://savannah.nongnu.org/bugs/index.php?44261 (alist-cons-before 'configure 'set-paths (lambda _ (setenv "CONFIG_SHELL" (which "bash"))) %standard-phases))) (synopsis "Font rendering library") (description "Freetype is a library that can be used by applications to access the contents of font files. It provides a uniform interface to access font files. It supports both bitmap and scalable formats, including TrueType, OpenType, Type1, CID, CFF, Windows FON/FNT, X11 PCF, and others. It supports high-speed anti-aliased glyph bitmap generation with 256 gray levels.") (license license:freetype) ; some files have other licenses (home-page "http://www.freetype.org/"))) (define-public fontconfig (package (name "fontconfig") (version "2.11.94") (source (origin (method url-fetch) (uri (string-append "https://www.freedesktop.org/software/fontconfig/release/fontconfig-" version ".tar.bz2")) (sha256 (base32 "1psrl4b4gi4wmbvwwh43lk491wsl8lgvqj146prlcha3vwjc0qyp")))) (build-system gnu-build-system) (propagated-inputs `(("expat" ,expat) ("freetype" ,freetype))) (inputs `(("gs-fonts" ,gs-fonts))) (native-inputs `(("pkg-config" ,pkg-config))) (arguments `(#:configure-flags (list "--with-cache-dir=/var/cache/fontconfig" ;; register gs-fonts as default fonts (string-append "--with-default-fonts=" (assoc-ref %build-inputs "gs-fonts") "/share/fonts") ;; register fonts from user profile ;; TODO: Add /run/current-system/profile/share/fonts and remove ;; the skeleton that works around it from 'default-skeletons'. "--with-add-fonts=~/.guix-profile/share/fonts" ;; python is not actually needed "PYTHON=false") #:phases (modify-phases %standard-phases (replace 'install (lambda _ ;; Don't try to create /var/cache/fontconfig. (zero? (system* "make" "install" "fc_cachedir=$(TMPDIR)" "RUN_FC_CACHE_TEST=false"))))))) (synopsis "Library for configuring and customizing font access") (description "Fontconfig can discover new fonts when installed automatically; perform font name substitution, so that appropriate alternative fonts can be selected if fonts are missing; identify the set of fonts required to completely cover a set of languages; have GUI configuration tools built as it uses an XML-based configuration file; efficiently and quickly find needed fonts among the set of installed fonts; be used in concert with the X Render Extension and FreeType to implement high quality, anti-aliased and subpixel rendered text on a display.") ; The exact license is more X11-style than BSD-style. (license (license:non-copyleft "file://COPYING" "See COPYING in the distribution.")) (home-page "http://www.freedesktop.org/wiki/Software/fontconfig"))) (define-public t1lib (package (name "t1lib") (version "5.1.2") (source (origin (method url-fetch) (uri "ftp://sunsite.unc.edu/pub/Linux/libs/graphics/t1lib-5.1.2.tar.gz") (sha256 (base32 "0nbvjpnmcznib1nlgg8xckrmsw3haa154byds2h90y2g0nsjh4w2")))) (build-system gnu-build-system) (arguments ;; Making the documentation requires latex, but t1lib is also an input ;; for building texlive. `(#:tests? #f ; no test target #:make-flags '("without_doc"))) (synopsis "Library for generating bitmaps from Type 1 fonts") (description "T1lib is a library for generating/rasterising bitmaps from Type 1 fonts. It is based on the code of the X11 rasteriser of the X11 project. The bitmaps created by t1lib are returned in a data structure with type GLYPH. This special GLYPH-type is also used in the X11 window system to describe character bitmaps. It contains the bitmap data as well as some metric information. But t1lib is in itself entirely independent of the X11-system or any other graphical user interface.") (license license:gpl2) (home-page "http://www.t1lib.org/"))) (define-public teckit (package (name "teckit") (version "2.5.4") (source (origin ;; Downloaded tarballs vary with each download, so we use an ;; svn snapshot. The 2.5.4 release seems to be made in r128, ;; but r132 updates additional files to contain the correct ;; version number (r129 to r131 do not concern TRUNK). (method svn-fetch) (uri (svn-reference (url "https://scripts.sil.org/svn-public/teckit/TRUNK") (revision 132))) (file-name (string-append name "-" version)) (sha256 (base32 "1xqkqgw30pb24snh46srmjs2j4zhz2dfi5pf7znia0k34mrpwivz")))) (build-system gnu-build-system) (inputs `(("zlib" ,zlib))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("libtool" ,libtool) ("perl" ,perl))) ; for the tests (arguments `(#:phases (modify-phases %standard-phases (add-after 'unpack 'autogen (lambda _ (zero? (system* "sh" "autogen.sh"))))))) (synopsis "Toolkit for encoding conversions") (description "TECkit is a low-level toolkit intended to be used by other applications that need to perform encoding conversions (e.g., when importing legacy data into a Unicode-based application). The primary component of the TECkit package is therefore a library that performs conversions; this is the \"TECkit engine\". The engine relies on mapping tables in a specific binary format (for which documentation is available); there is a compiler that creates such tables from a human-readable mapping description (a simple text file). To facilitate the development and testing of mapping tables for TECkit, several applications are also included in the current package; these include simple tools for applying conversions to plain-text and Standard Format files, as well as both command-line and simple GUI versions of the TECkit compiler. However, it is not intended that these tools will be the primary means by which end users perform conversions, and they have not been designed, tested, and debugged to the extent that general-purpose applications should be.") (license license:lgpl2.1+) (home-page "http://scripts.sil.org/cms/scripts/page.php?cat_id=teckit"))) (define-public graphite2 (package (name "graphite2") (version "1.3.6") (source (origin (method url-fetch) (uri (string-append "https://github.com/silnrsi/graphite/archive/" version ".tar.gz")) (file-name (string-append name "-" version ".tar.gz")) (sha256 (base32 "1frd9mjaqzvh9gs74ngc43igi53vzjzlwr5chbrs6ii1hc4aa23s")))) (build-system cmake-build-system) (native-inputs `(("python" ,python-2) ; because of "import imap" in tests ("python-fonttools" ,python2-fonttools))) (inputs `(("freetype" ,freetype))) (synopsis "Reimplementation of the SIL Graphite text processing engine") (description "Graphite2 is a reimplementation of the SIL Graphite text processing engine. Graphite is a smart font technology designed to facilitate the process known as shaping. This process takes an input Unicode text string and returns a sequence of positioned glyphids from the font.") (license license:lgpl2.1+) (home-page "https://github.com/silnrsi/graphite"))) (define-public potrace (package (name "potrace") (version "1.11") (source (origin (method url-fetch) (uri (string-append "mirror://sourceforge/potrace/potrace-" version ".tar.gz")) (sha256 (base32 "1bbyl7jgigawmwc8r14znv8lb6lrcxh8zpvynrl6s800dr4yp9as")))) (build-system gnu-build-system) (native-inputs `(("ghostscript" ,ghostscript))) ;for tests (inputs `(("zlib" ,zlib))) (arguments `(#:configure-flags `("--with-libpotrace"))) ; install library and headers (synopsis "Transform bitmaps into vector graphics") (description "Potrace is a tool for tracing a bitmap, which means, transforming a bitmap into a smooth, scalable image. The input is a bitmap (PBM, PGM, PPM, or BMP format), and the default output is an encapsulated PostScript file (EPS). A typical use is to create EPS files from scanned data, such as company or university logos, handwritten notes, etc. The resulting image is not \"jaggy\" like a bitmap, but smooth. It can then be rendered at any resolution.") (license license:gpl2+) (home-page "http://potrace.sourceforge.net/"))) (define-public libotf (package (name "libotf") (version "0.9.13") (source (origin (method url-fetch) (uri (string-append "mirror://savannah/releases/m17n/libotf-" version ".tar.gz")) (sha256 (base32 "0239zvfan56w7vrppriwy77fzb10ag9llaz15nsraps2a2x6di3v")))) (build-system gnu-build-system) (propagated-inputs `(("freetype" ,freetype))) (home-page "http://www.nongnu.org/m17n/") (synopsis "Library for handling OpenType Font") (description "This library can read Open Type Layout Tables from an OTF file. Currently these tables are supported; head, name, cmap, GDEF, GSUB, and GPOS. It can convert a Unicode character sequence to a glyph code sequence by using the above tables.") (license license:lgpl2.0+))) (define-public libspiro (package (name "libspiro") (version "20071029") (source (origin (method url-fetch) (uri (string-append "mirror://sourceforge/libspiro/libspiro/" version "/libspiro_src-" version ".tar.bz2")) (sha256 (base32 "1kylz8pvwnb85yya150r9i6mhbpzx38f32qy523qg3ylgd9b3zhy")))) (build-system gnu-build-system) (arguments `(#:tests? #f)) ;no tests (synopsis "Clothoid to bezier conversion library") (description "Raph Levien's Spiro package as a library. A mechanism for drawing smooth contours with constant curvature at the spline joins.") (license license:gpl2+) (home-page "http://libspiro.sourceforge.net/"))) (define-public libuninameslist (package (name "libuninameslist") (version "0.5.20150701") (source (origin (method url-fetch) (uri (string-append "https://github.com/fontforge/libuninameslist/" "archive/" version ".tar.gz")) (file-name (string-append name "-" version ".tar.gz")) (sha256 (base32 "1j6147l100rppw7axlrkdx0p35fax6bz2zh1xgpg7a3b4pmqaj3v")))) (build-system gnu-build-system) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("libtool" ,libtool))) (arguments `(#:phases (alist-cons-after 'unpack 'bootstrap (lambda _ (zero? (system* "autoreconf" "-vi"))) %standard-phases))) (synopsis "Unicode names and annotation list") (description "LibUniNamesList holds www.unicode.org Nameslist.txt data which can be useful for programs that need Unicode \"Names\", \"Annotations\", and block definitions.") (license license:gpl2) (home-page "https://github.com/fontforge/libuninameslist"))) (define-public fontforge (package (name "fontforge") (version "20150824") (source (origin (method url-fetch) (uri (string-append "https://github.com/fontforge/fontforge/releases/download/" version "/fontforge-" version ".tar.gz")) (sha256 (base32 "0gfcm8yn1d30giqhdwbchnfnspcqypqdzrxlhqhwy1i18wgl0v2v")) (modules '((guix build utils))) (snippet ;; Make builds bit-reproducible by using fixed date strings. '(substitute* "configure" (("^FONTFORGE_MODTIME=.*$") "FONTFORGE_MODTIME=\"1458399002\"\n") (("^FONTFORGE_MODTIME_STR=.*$") "FONTFORGE_MODTIME_STR=\"15:50 CET 19-Mar-2016\"\n") (("^FONTFORGE_VERSIONDATE=.*$") "FONTFORGE_VERSIONDATE=\"20160319\"\n"))))) (build-system gnu-build-system) (native-inputs `(("pkg-config" ,pkg-config))) (inputs `(("cairo" ,cairo) ("fontconfig" ,fontconfig) ;dlopen'd ("freetype" ,freetype) ("gettext" ,gnu-gettext) ("giflib" ,giflib) ;needs giflib 4.* ("glib" ,glib) ;needed for pango detection ("libICE" ,libice) ("libSM" ,libsm) ("libX11" ,libx11) ("libXi" ,libxi) ("libjpeg" ,libjpeg) ("libltdl" ,libltdl) ("libpng" ,libpng) ("libspiro" ,libspiro) ("libtiff" ,libtiff) ("libuninameslist" ,libuninameslist) ("libxft" ,libxft) ("libxml2" ,libxml2) ("pango" ,pango) ("potrace" ,potrace) ("python" ,python) ("zlib" ,zlib))) (arguments '(#:tests? #f #:phases (alist-cons-before 'configure 'patch-configure (lambda* (#:key inputs #:allow-other-keys) (let ((libxml2 (assoc-ref inputs "libxml2")) (cairo (assoc-ref inputs "cairo")) (pango (assoc-ref inputs "pango"))) (substitute* "configure" ;; configure looks for a directory to be present to determine ;; whether libxml2 is available, rather than checking for the ;; library or headers. Point it to the correct directory. (("/usr/include/libxml2") (string-append libxml2 "/include/libxml2")) ;; Similary, the search directories for cairo and pango are ;; hard-coded. (("gww_prefix in.*") (string-append "gww_prefix in " cairo " " pango "\n"))))) (alist-cons-after 'install 'set-library-path (lambda* (#:key inputs outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out")) (potrace (string-append (assoc-ref inputs "potrace") "/bin"))) (wrap-program (string-append out "/bin/fontforge") ;; Fontforge dynamically opens libraries. `("LD_LIBRARY_PATH" ":" prefix ,(map (lambda (input) (string-append (assoc-ref inputs input) "/lib")) '("libtiff" "libjpeg" "libpng" "giflib" "libxml2" "zlib" "libspiro" "freetype" "pango" "cairo" "fontconfig"))) ;; Checks for potrace program at runtime `("PATH" ":" prefix (,potrace))))) %standard-phases)))) (synopsis "Outline font editor") (description "FontForge allows you to create and modify postscript, truetype and opentype fonts. You can save fonts in many different outline formats, and generate bitmaps.") (license license:gpl3+) (home-page "http://fontforge.org/")))
package TTTinternet; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Tic-Tac-Toe: Two-player Graphics version with Simple-OO */ @SuppressWarnings("serial") public class TTTGraphics2P extends JFrame { // Named-constants for the game board // Объявляем константы для игрового поля и инициализируем их public static final int ROWS = 3; // ROWS by COLS cells public static final int COLS = 3; // Задаем количество колонок и строк // Named-constants of the various dimensions used for graphics drawing // Объявляем константы различных размеров используемых для графики public static final int CELL_SIZE = 100; // cell width and height (square) (ширина и высота ячейки (квадрат)) public static final int CANVAS_WIDTH = CELL_SIZE * COLS; // ширина поля (получается произведением ширины клетки на их количество) public static final int CANVAS_HEIGHT = CELL_SIZE * ROWS; //the drawing canvas public static final int GRID_WIDTH = 8; // Ширина линии сетки Grid-line's width public static final int GRID_WIDHT_HALF = GRID_WIDTH / 2; // Половина ширины линии сетки Grid-line's half-width // Symbols (cross/nought) are displayed inside a cell, with padding from border //Символы (крестик / ноль нолик) отображаются внутри ячейки с отступом от границы public static final int CELL_PADDING = CELL_SIZE / 6; // Заполнение клетки public static final int SYMBOL_SIZE = CELL_SIZE - CELL_PADDING * 2; // Размер символа(не очень понятно , получается просто 2/3 размера клетки) width/height public static final int SYMBOL_STROKE_WIDTH = 8; // ширина линии символа (крестик / ноль нолик) pen's stroke width // Use an enumeration (inner class) to represent the various states of the game // Используйте перечисление (внутренний класс) для представления различных состояний игры public enum GameState { PLAYING, DRAW, CROSS_WON, NOUGHT_WON } private GameState currentState; // текущее изровое состояние the current game state // Use an enumeration (inner class) to represent the seeds and cell contents // Используйте перечисление (внутренний класс) для представления заполненности содержимого ячейки public enum Seed { EMPTY, CROSS, NOUGHT } private Seed currentPlayer; // Текущий игрок the current player private Seed[][] board ; // Массив представляющий собой игровое поле Game board of ROWS-by-COLS cells private DrawCanvas canvas; // Отрисовка игрового поля Drawing canvas (JPanel) for the game board private JLabel statusBar; // Индикация состояния Status Bar /** Constructor to setup the game and the GUI components */ // Конструктор для установки игры и GUI компоненты public TTTGraphics2P() { canvas = new DrawCanvas(); // Construct a drawing canvas (a JPanel) canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT)); // The canvas (JPanel) fires a MouseEvent upon mouse-click canvas.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { // mouse-clicked handler int mouseX = e.getX(); int mouseY = e.getY(); // Get the row and column clicked int rowSelected = mouseY / CELL_SIZE; int colSelected = mouseX / CELL_SIZE; if (currentState == GameState.PLAYING) { if (rowSelected >= 0 && rowSelected < ROWS && colSelected >= 0 && colSelected < COLS && board[rowSelected][colSelected] == Seed.EMPTY) { board[rowSelected][colSelected] = currentPlayer; // Make a move updateGame(currentPlayer, rowSelected, colSelected); // update state // Switch player currentPlayer = (currentPlayer == Seed.CROSS) ? Seed.NOUGHT : Seed.CROSS; } } else { // game over initGame(); // restart the game } // Refresh the drawing canvas repaint(); // Call-back paintComponent(). } }); // Setup the status bar (JLabel) to display status message statusBar = new JLabel(" "); statusBar.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 15)); statusBar.setBorder(BorderFactory.createEmptyBorder(2, 5, 4, 5)); Container cp = getContentPane(); cp.setLayout(new BorderLayout()); cp.add(canvas, BorderLayout.CENTER); cp.add(statusBar, BorderLayout.PAGE_END); // same as SOUTH setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); // pack all the components in this JFrame setTitle("Tic Tac Toe"); setVisible(true); // show this JFrame board = new Seed[ROWS][COLS]; // allocate array initGame(); // initialize the game board contents and game variables } /** Initialize the game-board contents and the status */ public void initGame() { for (int row = 0; row < ROWS; ++row) { for (int col = 0; col < COLS; ++col) { board[row][col] = Seed.EMPTY; // all cells empty } } currentState = GameState.PLAYING; // ready to play currentPlayer = Seed.CROSS; // cross plays first } /** Update the currentState after the player with "theSeed" has placed on (rowSelected, colSelected). */ public void updateGame(Seed theSeed, int rowSelected, int colSelected) { if (hasWon(theSeed, rowSelected, colSelected)) { // check for win currentState = (theSeed == Seed.CROSS) ? GameState.CROSS_WON : GameState.NOUGHT_WON; } else if (isDraw()) { // check for draw currentState = GameState.DRAW; } // Otherwise, no change to current state (still GameState.PLAYING). } /** Return true if it is a draw (i.e., no more empty cell) */ public boolean isDraw() { for (int row = 0; row < ROWS; ++row) { for (int col = 0; col < COLS; ++col) { if (board[row][col] == Seed.EMPTY) { return false; // an empty cell found, not draw, exit } } } return true; // no more empty cell, it's a draw } /** Return true if the player with "theSeed" has won after placing at (rowSelected, colSelected) */ public boolean hasWon(Seed theSeed, int rowSelected, int colSelected) { return (board[rowSelected][0] == theSeed // 3-in-the-row && board[rowSelected][1] == theSeed && board[rowSelected][2] == theSeed || board[0][colSelected] == theSeed // 3-in-the-column && board[1][colSelected] == theSeed && board[2][colSelected] == theSeed || rowSelected == colSelected // 3-in-the-diagonal && board[0][0] == theSeed && board[1][1] == theSeed && board[2][2] == theSeed || rowSelected + colSelected == 2 // 3-in-the-opposite-diagonal && board[0][2] == theSeed && board[1][1] == theSeed && board[2][0] == theSeed); } /** * Inner class DrawCanvas (extends JPanel) used for custom graphics drawing. */ class DrawCanvas extends JPanel { @Override public void paintComponent(Graphics g) { // invoke via repaint() super.paintComponent(g); // fill background setBackground(Color.WHITE); // set its background color // Draw the grid-lines10 g.setColor(Color.LIGHT_GRAY); for (int row = 1; row < ROWS; ++row) { g.fillRoundRect(0, CELL_SIZE * row - GRID_WIDHT_HALF, CANVAS_WIDTH-1, GRID_WIDTH, GRID_WIDTH, GRID_WIDTH); } for (int col = 1; col < COLS; ++col) { g.fillRoundRect(CELL_SIZE * col - GRID_WIDHT_HALF, 0, GRID_WIDTH, CANVAS_HEIGHT-1, GRID_WIDTH, GRID_WIDTH); } // Draw the Seeds of all the cells if they are not empty // Use Graphics2D which allows us to set the pen's stroke Graphics2D g2d = (Graphics2D)g; g2d.setStroke(new BasicStroke(SYMBOL_STROKE_WIDTH, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); // Graphics2D only for (int row = 0; row < ROWS; ++row) { for (int col = 0; col < COLS; ++col) { int x1 = col * CELL_SIZE + CELL_PADDING; int y1 = row * CELL_SIZE + CELL_PADDING; if (board[row][col] == Seed.CROSS) { g2d.setColor(Color.RED); int x2 = (col + 1) * CELL_SIZE - CELL_PADDING; int y2 = (row + 1) * CELL_SIZE - CELL_PADDING; g2d.drawLine(x1, y1, x2, y2); g2d.drawLine(x2, y1, x1, y2); } else if (board[row][col] == Seed.NOUGHT) { g2d.setColor(Color.BLUE); g2d.drawOval(x1, y1, SYMBOL_SIZE, SYMBOL_SIZE); } } } // Print status-bar message if (currentState == GameState.PLAYING) { statusBar.setForeground(Color.BLACK); if (currentPlayer == Seed.CROSS) { statusBar.setText("X's Turn"); } else { statusBar.setText("O's Turn"); } } else if (currentState == GameState.DRAW) { statusBar.setForeground(Color.RED); statusBar.setText("It's a Draw! Click to play again."); } else if (currentState == GameState.CROSS_WON) { statusBar.setForeground(Color.RED); statusBar.setText("'X' Won! Click to play again."); } else if (currentState == GameState.NOUGHT_WON) { statusBar.setForeground(Color.RED); statusBar.setText("'O' Won! Click to play again."); } } } /** The entry main() method */ public static void main(String[] args) { // Run GUI codes in the Event-Dispatching thread for thread safety SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new TTTGraphics2P(); // Let the constructor do the job } }); } }
import 'package:flutter/material.dart'; import '../class/ItemClass.dart'; import '../widgets/card_widget.dart'; //TODO: statelessW //* implement the code for statelessWidget class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Flutter'), // TODO: ctrl+space //* View the parameter of the object ), body: const SingleChildScrollView( child: Column( children: [ CardWidget( box: ItemClass( title: "Rocket", description: "the description of the rockets", image: "assets/images/rocket.png", )), Row( children: [ Expanded( child: CardWidget( box: ItemClass( title: "Space", description: "the description of the space", image: "assets/images/space.png", ), ), ), Expanded( child: CardWidget( box: ItemClass( title: "Travel", description: "the description of the travel", image: "assets/images/travel.png", ), ), ) ], ), CardWidget( box: ItemClass( title: "Yeah", description: "the description of the yeah", image: "assets/images/yeah.png", ), ) ], ), ), ); } } //*shift+alt+f //*for format
package com.example.service.aoc22; import com.example.service.AdventOfCode; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; import lombok.AllArgsConstructor; import lombok.Data; @Service public class Day2 implements AdventOfCode { /** Day 2 - 1 * Calculate the score of a score Rock Paper Scissors tournament. * opponent has A = rock, B = paper, C = scissors * C beats B beats A beats C - win is * - 1 for Rock, 2 for Paper, and 3 for Scissors PLUS * - 0 if you lost, 3 if the round was a draw, and 6 if you won * * BTW you have X = rock, Y = paper, Z = scissors * @param encryptedStrategyGuide the lines eg "A X" * @return calculated score */ public int scoreRockPaperScissors(List<String> encryptedStrategyGuide) { LOG.info("Rucksack - total lines: " + encryptedStrategyGuide.size()); List<RockPaperScissorsRound> rockPaperScissorRounds = new ArrayList<>(); RockPaperScissorsRound currentRockPaperScissorsRound; String opponentHand = ""; String yourHand = ""; int yourTotalScore = 0; // for-each loop the file lines for (String round : encryptedStrategyGuide) { //LOG.info("Rucksack - " + round + " gives : " + score); List<String> split = Pattern .compile(" ") .splitAsStream(round) .collect(Collectors.toList()); opponentHand = split.get(0); yourHand = split.get(1); //Integer.parseInt(split.get(1)); // populate the currentRockPaperScissorsRound = switch(yourHand) { case "X" -> new RockPaperScissorsRound(opponentHand,"A",0,null); case "Y" -> new RockPaperScissorsRound(opponentHand,"B",0,null); case "Z" -> new RockPaperScissorsRound(opponentHand,"C",0,null); default -> throw new IllegalStateException("Invalid X,Y,Z status: " + yourHand); }; currentRockPaperScissorsRound.yourScore = rockPaperScissorsScoreOfARound(currentRockPaperScissorsRound); yourTotalScore = yourTotalScore + currentRockPaperScissorsRound.yourScore; LOG.info("Rock Paper Scissors - round: " + round + " score: " + currentRockPaperScissorsRound.yourScore); LOG.info("A/X = rock, B/Y = paper, C/Z = scissors " + lineSeparator); rockPaperScissorRounds.add(currentRockPaperScissorsRound); } LOG.info("Rock Paper Scissors - score: " + yourTotalScore); return yourTotalScore; } @AllArgsConstructor @Data class RockPaperScissorsRound { String opponentHand; String yourHand; int yourScore; RoundResult yourRoundResult; }; // A = rock, B = paper, C = scissors static int rockPaperScissorsScoreOfARound(RockPaperScissorsRound rockPaperScissorsRound) { if (rockPaperScissorsRound.opponentHand.equals(rockPaperScissorsRound.yourHand)) { return rockPaperScissorsScoreCalculateRound(rockPaperScissorsRound.yourHand,RoundResult.draw); } else if (rockPaperScissorsRound.opponentHand.equals("A")) { if (rockPaperScissorsRound.yourHand.equals("B")) { return rockPaperScissorsScoreCalculateRound(rockPaperScissorsRound.yourHand, RoundResult.win); } else { return rockPaperScissorsScoreCalculateRound(rockPaperScissorsRound.yourHand, RoundResult.lose); } } else if (rockPaperScissorsRound.opponentHand.equals("B")) { if (rockPaperScissorsRound.yourHand.equals("C")) { return rockPaperScissorsScoreCalculateRound(rockPaperScissorsRound.yourHand, RoundResult.win); } else { return rockPaperScissorsScoreCalculateRound(rockPaperScissorsRound.yourHand, RoundResult.lose); } } else { // always opponent has C if (rockPaperScissorsRound.yourHand.equals("A")) { return rockPaperScissorsScoreCalculateRound(rockPaperScissorsRound.yourHand, RoundResult.win); } else { return rockPaperScissorsScoreCalculateRound(rockPaperScissorsRound.yourHand, RoundResult.lose); } } } enum RoundResult {draw, lose, win} static int rockPaperScissorsScoreCalculateRound(String shape, RoundResult result) { int outcome = 0; switch (shape) { // Rock is 1 case "A" -> outcome = 1 + outcomeOfRoundResultValue(result); // Paper is 2 case "B" -> outcome = 2 + outcomeOfRoundResultValue(result); // Scissors is 3 case "C" -> outcome = 3 + outcomeOfRoundResultValue(result); } LOG.info("Rock Paper Scissors - total outcome with shape 1,2 or 3 added: " + result); return outcome; } static int outcomeOfRoundResultValue(RoundResult roundResult) { int result = 0; switch (roundResult) { case lose -> result = 0; case draw -> result = 3; case win -> result = 6; default -> result = -999999; } LOG.info("Rock Paper Scissors - result of round value 0,3,6: " + result); return result; } /** day 2 -2 * opponent has A = rock, B = paper, C = scissors * C beats B beats A beats C - win is * - 1 for Rock, 2 for Paper, and 3 for Scissors PLUS * - 0 if you lost, 3 if the round was a draw, and 6 if you won * * BTW you have X = you need to lose, Y = you need to draw, Z = you need to win * @param encryptedStrategyGuide the lines eg "A X" * @return calculated score */ public int scoreRockPaperScissorsSecond(List<String> encryptedStrategyGuide) { LOG.info("Rucksack - total lines: " + encryptedStrategyGuide.size()); List<RockPaperScissorsRound> rockPaperScissorRounds = new ArrayList<>(); RockPaperScissorsRound currentRockPaperScissorsRound; String opponentHand = ""; String yourResult = ""; int yourTotalScore = 0; // for-each loop the file lines for (String round : encryptedStrategyGuide) { //LOG.info("Rucksack - " + round + " gives : " + score); List<String> split = Pattern .compile(" ") .splitAsStream(round) .collect(Collectors.toList()); opponentHand = split.get(0); yourResult = split.get(1); //Integer.parseInt(split.get(1)); // populate the class currentRockPaperScissorsRound = switch(yourResult) { case "X" -> new RockPaperScissorsRound(opponentHand,"",0,RoundResult.lose); case "Y" -> new RockPaperScissorsRound(opponentHand,"",0,RoundResult.draw); case "Z" -> new RockPaperScissorsRound(opponentHand,"",0,RoundResult.win); default -> throw new IllegalStateException("Invalid X,Y,Z status: " + yourResult); }; currentRockPaperScissorsRound.yourScore = rockPaperScissorsHandOfARound(currentRockPaperScissorsRound); yourTotalScore = yourTotalScore + currentRockPaperScissorsRound.yourScore; LOG.info("Rock Paper Scissors - round: " + round + " score: " + currentRockPaperScissorsRound.yourScore); LOG.info("A/X = rock, B/Y = paper, C/Z = scissors " + lineSeparator); rockPaperScissorRounds.add(currentRockPaperScissorsRound); } LOG.info("Rock Paper Scissors - score: " + yourTotalScore); return yourTotalScore; } // X = you need to lose, Y = you need to draw, Z = you need to win // opponent has A = rock, B = paper, C = scissors static int rockPaperScissorsHandOfARound(RockPaperScissorsRound rockPaperScissorsRound) { if (rockPaperScissorsRound.yourRoundResult.equals(RoundResult.draw)) { // draw rockPaperScissorsRound.yourHand = rockPaperScissorsRound.opponentHand; } else if (rockPaperScissorsRound.opponentHand.equals("A")) { // you win with opponent A if (rockPaperScissorsRound.yourRoundResult.equals(RoundResult.win)) { rockPaperScissorsRound.yourHand = "B"; } else { // you lose with opponent A rockPaperScissorsRound.yourHand = "C"; } } else if (rockPaperScissorsRound.opponentHand.equals("B")) { // you win with opponent B if (rockPaperScissorsRound.yourRoundResult.equals(RoundResult.win)) { rockPaperScissorsRound.yourHand = "C"; } else { // you lose with opponent B rockPaperScissorsRound.yourHand = "A"; } } else { // always opponent has C if (rockPaperScissorsRound.yourRoundResult.equals(RoundResult.win)) { // you win with opponent C rockPaperScissorsRound.yourHand = "A"; } else { // you lose with opponent C rockPaperScissorsRound.yourHand = "B"; } } return rockPaperScissorsScoreCalculateRound(rockPaperScissorsRound.yourHand, rockPaperScissorsRound.yourRoundResult); } }
//hook para controlar el ciclo de vida: useEffect import { useEffect, useState } from "react"; import { useSelector, useDispatch } from "react-redux"; import SearchBar from "../../components/SearchBar/searchBar"; import Loading from "../../components/Loading/loading"; import Cards from "../../components/Cards/cards"; import Header from "../../components/Headers/header"; import Paginate from "../../components/Paginate/paginate"; import { getGenres, getVideogames, clearHome } from "../../redux/actions"; import styles from"./home.module.css"; function Home() { const dispatch = useDispatch(); //se le envia una action al estado //componente quiero que estes suscripto a cualquier cambio que ocurra en el estado allVideogames const allVideogames = useSelector((state) => state.allVideogames); //se indica al componente de que estado depende, a que estado quiero estar suscripto // console.log(allVideogames); useEffect(() => { dispatch(getVideogames()); //1° parametro lo que queremos ejecutar al momento de hacer el dispatch, cuando se monta dispatch(getGenres()); // return(()=>{}) //=> en esta callback se ejecuta una fx al momento de desmontar} }, [dispatch]); //2° parametro una array de dependecia const handleAll = () => { dispatch(getVideogames()) } //PAGINADO!!!!: const [currentPage, setCurrentPage] = useState(1); //current page= pagina actual const perPage = 15; const totalVideogames = allVideogames.length; const totalPages = Math.ceil(totalVideogames / perPage); //cantidad de paginas que va a tener la SPA const numberStart = (currentPage - 1) * perPage; const numberEnd = (currentPage - 1) * perPage + perPage; const [input, setInput] = useState(1); return ( <div className={styles.home}> <div> <div className={styles.header}></div> {/* <h1 className={styles.titleHome}>VIDEOGAME´S WORLD</h1> */} <SearchBar setCurrentPage={setCurrentPage} setInput={setInput} /> <button className={styles.button} onClick={handleAll}> ALL VIDEOGAMES </button> <Header currentPage={currentPage} setCurrentPage={setCurrentPage} /> <Paginate currentPage={currentPage} setCurrentPage={setCurrentPage} totalPages={totalPages} input={input} setInput={setInput} /> {allVideogames.length ? ( <div className={styles.cardList}> <Cards allVideogames={allVideogames} numberEnd={numberEnd} numberStart={numberStart} /> </div> ) : ( <div className={styles.load}> {/* <h3 className={styles.loading}>Loading...</h3> */} <Loading /> </div> )} </div> </div> ); }; //le pasa como props el nombre no el destructuring export default Home; //Cards: componente que se renderiza dentro de otro //le pasa como props el nombre no el destructuring
<a name="readme-top"></a> # <div align="center">🛰Doctor Appointment Booking App 🚀</div> # 📗 Table of Contents - [📗 Table of Contents](#-table-of-contents) - [📖 Doctor Appointment Booking App ](#-final-group-capstone---doctor-appointment-booking-app-) - [🛠 Built With ](#-built-with-) - [Tech Stack ](#tech-stack-) - [Key Features ](#key-features-) - [💻 Getting Started ](#-getting-started-) - [Prerequisites](#prerequisites) - [Install](#install) - [Usage](#usage) - [Run tests](#run-tests) - [Run rails](#run-rails) - [👥 Authors ](#-authors-) - [📆 Kanban Board](#kanban-board) - [🔭 Future Features ](#-future-features-) - [🤝 Contributing ](#-contributing-) - [⭐️ Show your support ](#️-show-your-support-) - [🙏 Acknowledgments ](#-acknowledgments-) - [Development Team](#development-team) - [Institution](#institution) - [Reference Design](#reference-design) - [📝 License ](#-license-) <!-- PROJECT DESCRIPTION --> # 📖 Doctor Appointment Booking App <a name="doctor-appointment"></a> This is a Doctor's Appointment application that is intended to showcase full-stack web development skills, particularly in Ruby on Rails and React. Doctor's Appointments employs an API tied to a frontend written in React and is made using the methodology and specifications of the Capstone Project. And enables the users to sign up and book appointments with doctors. The project is a repository consisting of the following files: - Ruby files - Rails files - JS files - CSS files <p align="right">(<a href="#readme-top">back to top</a>)</p> ## 🛠 Built With <a name="built-with"></a> ### Tech Stack <a name="tech-stack"></a> <ul> <li> <a href="https://www.ruby-lang.org/en/"> <img align="center" width="19" height="auto" src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Ruby_logo.svg/198px-Ruby_logo.svg.png?20101129171534" alt="ruby logo" /> Ruby on Rails >=7 </a> </li> <li> <a href="https://rubyonrails.org/"> <img align="center" width="19" height="auto" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/1150px-React-icon.svg.png" alt="React logo" /> React </a> </li><li> <a href="https://rubyonrails.org/"> <img align="center" width="19" height="auto" src="https://cdn.freebiesupply.com/logos/large/2x/redux-logo-svg-vector.svg" alt="redux logo" /> Redux </a> </li> <li> <a href="https://www.postgresql.org/"> <img align="center" width="19" height="auto" src="https://wiki.postgresql.org/images/3/30/PostgreSQL_logo.3colors.120x120.png" alt="postgreSQL logo" /> PostgreSQL </a> </li> </ul> </ul> ### Key Features <a name="key-features"></a> - User can sign up - Users can create doctors - Users can book appointments with doctors - Users can view the details of doctors - User can delete doctors <p align="right">(<a href="#readme-top">back to top</a>)</p> ## 🌐 Live Demo <a name="#live-demo"></a> - [Live Demo](https://doctor-appointment-booking-app1.onrender.com/users/sign_in) <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- GETTING STARTED --> ## 💻 Getting Started <a name="getting-started"></a> ### Prerequisites - [Ruby on Rails >=7](https://rubyonrails.org/) - [React](https://reactjs.org/) - [Redux](https://redux.js.org/) - [Rails](https://rubyonrails.org/) - [Postgresql](https://www.postgresql.org/) - [Git](https://github.com/) ### Install ``` git clone https://github.com/Benawi/Doctor_Appointment-Booking_App.git cd Doctor_Appointment-Booking_App bundle install npm install ``` ### Usage In the project directory, run the : npm start command ### Run tests In the project directory, run: ``` rspec . ``` ### Run rails To configure the database connection in Rails, you need to update the database.yml file located in the config folder. Follow these steps: Locate the database.yml file in the config folder of your Rails application. 1. Open the database.yml file using a text editor. 2. Find the default: &default section in the file. 3. Add the following lines under the default: &default section: ``` host: localhost username: your_username password: your_password port: 5432 ``` 4. Replace your username with your actual database username and your password with your actual database password. 5. Save the changes to the database.yml file. 6. Run ``` rails db:create ``` ``` rails db:migrate ``` ``` rails db:seed ``` ``` npm start ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- AUTHORS --> ## 👥 Authors <a name="authors"></a> ### 👤 **Habtamu Alemayehu** - GitHub: [Benawi](https://github.com/Benawi) - Linkdin: [Habtamu](https://www.linkedin.com/in/habtamualemayehu/) 👤 **Falako Omotoyosi** - GitHub: [@toyman640](https://github.com/toyman640) - Twitter: [@_toyman](https://twitter.com/_toyman) - LinkedIn: [LinkedIn](https://www.linkedin.com/in/falako-omotoyosi/) <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- Kanban Board --> ## 📆 Kanban Board <a name="kanban-board"></a> - [Our kanban board](https://github.com/users/Benawi/projects/9) - Screenshot of the initial state of the Kanban board [screenshot1](https://user-images.githubusercontent.com/21217148/278274771-6e5d6cb9-2dbe-41c9-a944-e5eac5cf49ae.PNG) [screenshot2](https://user-images.githubusercontent.com/21217148/278274875-a2165b0b-bb55-4068-a5f8-0d4f73362181.PNG) - We are a team of 2 members as stated in the author's section <p align="right">(<a href="#readme-top">back to top</a>)</p> ## 🔭 Future Features <a name="future-features"></a> - Add a section to book appointments with doctors - Add proper front-end user authentication - Add extra styling <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- CONTRIBUTING --> ## 🤝 Contributing <a name="contributing"></a> Contributions, issues, and feature requests are welcome! Check the [issues page](https://github.com/Benawi/Doctor_Appointment-Booking_App/issues). <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- SUPPORT --> ## ⭐️ Show your support <a name="support"></a> If you found this project helpful, consider giving a ⭐️! <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- ACKNOWLEDGEMENTS --> ## 🙏 Acknowledgments <a name="acknowledgements"></a> We would like to express our deepest gratitude to all the people and institutions that have contributed to making this project possible. #### Development Team - **Falako Omotoyosi**: Thank you for being a productive partner with impressive technical thinking and good execusion style. - **Habtamu Alemayehu Benawi**: I appreciate your commitment and dedication. With your zeal and your promptness in executing the tasks at hand, you are a great partner. #### Institution - **Microverse**: My sincerest thanks for creating this bootcamp. The program's structure and the quality of education provided have been crucial for my growth as a developer. #### Reference Design - We would also like to thank [<a href="https://www.behance.net/muratk">Murat Korkmaz</a>] for the original design on Behance that served as inspiration for this project. <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- LICENSE --> ## 📝 License <a name="license"></a> This project is [MIT](./LICENSE) licensed. <p align="right">(<a href="#readme-top">back to top</a>)</p>
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class PoppinsText extends StatelessWidget { final String text; final double fontS; final Color? color; final FontWeight? fontWeight; final TextAlign? textAlign; const PoppinsText({ super.key, required this.text, required this.fontS, this.color, this.fontWeight, this.textAlign, }); @override Widget build(BuildContext context) { return Text( text, style: GoogleFonts.poppins( fontSize: fontS, color: color, fontWeight: fontWeight, ), textAlign: textAlign, ); } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; import { NotFoundComponent } from './not-found/not-found.component'; import { PostsComponent } from './posts/posts.component'; import { PostDetailComponent } from './post-detail/post-detail.component'; const routes: Routes = [ {path: 'home', component: HomeComponent}, {path: 'about', component: AboutComponent}, {path: 'posts', component: PostsComponent}, {path: 'posts/:id', component: PostDetailComponent}, {path: '', redirectTo: 'home', pathMatch: 'full'}, {path: '**', component: NotFoundComponent}, // Should be last!! ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
const customError = require("../utils/customError"); const User = require("../models/employee.model"); class AuthController { // register handler static async register(req, res, next) { try { const { name, email, password } = req.body; const user = await User.create({ firstName: name, email, password, }); if (!user) { return next(new customError("Failed to register", 400)); } const token = user.generateJWT(); const options = { expires: new Date(Date.now() + 1 * 60 * 60 * 1000), httpOnly: true, }; res.status(201).cookie("access_token", token, options).json({ message: "Successfully registered", data: user, token, }); } catch (error) { return next(new customError(error, 400)); } } // login handler static async login(req, res, next) { try { const { email, password } = req.body; if (!email || !password) { return next(new customError("Please provide email and password", 400)); } const user = await User.findOne({ email }); if (!user) { return next(new customError("Invalid email or password", 400)); } const isMatch = await user.comparePassword(password); if (!isMatch) { return next(new customError("Invalid email or password", 400)); } const token = user.generateJWT(); const options = { expires: new Date(Date.now() + 1 * 60 * 60 * 1000), httpOnly: true, }; res.clearCookie("access_token"); res.status(200).cookie("access_token", token, options).json({ message: "Successfully logged in", data: user, token, }); } catch (error) { return next(new customError(error.message, 400)); } } // logout handler static logout(req, res, next) { try { res.clearCookie("access_token"); res.status(200).json({ message: "Successfully logged out", }); } catch (error) { return next(new customError(error.message, 400)); } } } module.exports = AuthController;
/* * MIT License * * Copyright (C) 2021-2023 by wangwenx190 (Yuhang Zhao) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "framelessmanager.h" #include "framelessmanager_p.h" #include "framelesshelpercore_global_p.h" #if FRAMELESSHELPER_CONFIG(native_impl) # ifdef Q_OS_WINDOWS # include "framelesshelper_win.h" # elif (defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)) # elif defined(Q_OS_MACOS) # else # endif #else # include "framelesshelper_qt.h" #endif #include "framelessconfig_p.h" #include "utils.h" #ifdef Q_OS_WINDOWS # include "winverhelper_p.h" #endif #include <QtCore/qvariant.h> #include <QtCore/qcoreapplication.h> #include <QtCore/qloggingcategory.h> #include <QtGui/qfontdatabase.h> #include <QtGui/qwindow.h> #include <QtGui/qevent.h> #if (QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)) # include <QtGui/qguiapplication.h> # include <QtGui/qstylehints.h> #endif // (QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)) FRAMELESSHELPER_BEGIN_NAMESPACE #if FRAMELESSHELPER_CONFIG(debug_output) [[maybe_unused]] static Q_LOGGING_CATEGORY(lcFramelessManager, "wangwenx190.framelesshelper.core.framelessmanager") # define INFO qCInfo(lcFramelessManager) # define DEBUG qCDebug(lcFramelessManager) # define WARNING qCWarning(lcFramelessManager) # define CRITICAL qCCritical(lcFramelessManager) #else # define INFO QT_NO_QDEBUG_MACRO() # define DEBUG QT_NO_QDEBUG_MACRO() # define WARNING QT_NO_QDEBUG_MACRO() # define CRITICAL QT_NO_QDEBUG_MACRO() #endif using namespace Global; static constexpr const int kEventDelayInterval = 1000; struct InternalData { FramelessDataHash dataMap = {}; QHash<WId, QObject *> windowMap = {}; InternalData(); ~InternalData(); private: FRAMELESSHELPER_CLASS(InternalData) }; InternalData::InternalData() = default; InternalData::~InternalData() = default; Q_GLOBAL_STATIC(InternalData, g_internalData) #if FRAMELESSHELPER_CONFIG(bundle_resource) [[nodiscard]] static inline QString iconFontFamilyName() { static const auto result = []() -> QString { #ifdef Q_OS_WINDOWS if (WindowsVersionHelper::isWin11OrGreater()) { return FRAMELESSHELPER_STRING_LITERAL("Segoe Fluent Icons"); } if (WindowsVersionHelper::isWin10OrGreater()) { return FRAMELESSHELPER_STRING_LITERAL("Segoe MDL2 Assets"); } #endif // Q_OS_WINDOWS return FRAMELESSHELPER_STRING_LITERAL("iconfont"); }(); return result; } #endif class InternalEventFilter : public QObject { Q_OBJECT FRAMELESSHELPER_QT_CLASS(InternalEventFilter) public: explicit InternalEventFilter(const QObject *window, QObject *parent = nullptr); ~InternalEventFilter() override; protected: Q_NODISCARD bool eventFilter(QObject *object, QEvent *event) override; private: const QObject *m_window = nullptr; }; InternalEventFilter::InternalEventFilter(const QObject *window, QObject *parent) : QObject(parent), m_window(window) { Q_ASSERT(m_window); Q_ASSERT(m_window->isWidgetType() || m_window->isWindowType()); } InternalEventFilter::~InternalEventFilter() = default; bool InternalEventFilter::eventFilter(QObject *object, QEvent *event) { Q_ASSERT(object); Q_ASSERT(event); Q_ASSERT(m_window); if (!object || !event || !m_window || (object != m_window)) { return false; } const FramelessDataPtr data = FramelessManagerPrivate::getData(m_window); if (!data || !data->frameless || !data->callbacks) { return false; } switch (event->type()) { case QEvent::WinIdChange: { const WId windowId = data->callbacks->getWindowId(); Q_ASSERT(windowId); if (windowId) { FramelessManagerPrivate::updateWindowId(m_window, windowId); } } break; case QEvent::Close: { const auto ce = static_cast<const QCloseEvent *>(event); if (ce->isAccepted()) { std::ignore = FramelessManager::instance()->removeWindow(m_window); } } break; default: break; } return false; } FramelessManagerPrivate::FramelessManagerPrivate(FramelessManager *q) : QObject(q) { Q_ASSERT(q); if (!q) { return; } q_ptr = q; initialize(); } FramelessManagerPrivate::~FramelessManagerPrivate() = default; FramelessManagerPrivate *FramelessManagerPrivate::get(FramelessManager *pub) { Q_ASSERT(pub); if (!pub) { return nullptr; } return pub->d_func(); } const FramelessManagerPrivate *FramelessManagerPrivate::get(const FramelessManager *pub) { Q_ASSERT(pub); if (!pub) { return nullptr; } return pub->d_func(); } void FramelessManagerPrivate::initializeIconFont() { #if FRAMELESSHELPER_CONFIG(bundle_resource) static bool inited = false; if (inited) { return; } inited = true; FramelessHelperCoreInitResource(); // We always register this font because it's our only fallback. const int id = QFontDatabase::addApplicationFont(FRAMELESSHELPER_STRING_LITERAL(":/org.wangwenx190.FramelessHelper/resources/fonts/iconfont.ttf")); if (id < 0) { WARNING << "Failed to load icon font."; } else { DEBUG << "Successfully registered icon font."; } #endif // FRAMELESSHELPER_CORE_NO_BUNDLE_RESOURCE } QFont FramelessManagerPrivate::getIconFont() { #if FRAMELESSHELPER_CONFIG(bundle_resource) static const auto font = []() -> QFont { QFont f = {}; f.setFamily(iconFontFamilyName()); # ifdef Q_OS_MACOS f.setPointSize(10); # else // !Q_OS_MACOS f.setPointSize(8); # endif // Q_OS_MACOS return f; }(); return font; #else // !FRAMELESSHELPER_CONFIG(bundle_resource) return {}; #endif // FRAMELESSHELPER_CONFIG(bundle_resource) } void FramelessManagerPrivate::notifySystemThemeHasChangedOrNot() { themeTimer.start(); } void FramelessManagerPrivate::notifyWallpaperHasChangedOrNot() { wallpaperTimer.start(); } void FramelessManagerPrivate::doNotifySystemThemeHasChangedOrNot() { const SystemTheme currentSystemTheme = (Utils::shouldAppsUseDarkMode() ? SystemTheme::Dark : SystemTheme::Light); const QColor currentAccentColor = Utils::getAccentColor(); #ifdef Q_OS_WINDOWS const DwmColorizationArea currentColorizationArea = Utils::getDwmColorizationArea(); #endif bool notify = false; if (systemTheme != currentSystemTheme) { systemTheme = currentSystemTheme; notify = true; } if (accentColor != currentAccentColor) { accentColor = currentAccentColor; notify = true; } #ifdef Q_OS_WINDOWS if (colorizationArea != currentColorizationArea) { colorizationArea = currentColorizationArea; notify = true; } #endif // Don't emit the signal if the user has overrided the global theme. if (notify && !isThemeOverrided()) { Q_Q(FramelessManager); Q_EMIT q->systemThemeChanged(); DEBUG.nospace() << "System theme changed. Current theme: " << systemTheme << ", accent color: " << accentColor.name(QColor::HexArgb).toUpper() #ifdef Q_OS_WINDOWS << ", colorization area: " << colorizationArea #endif << '.'; } } void FramelessManagerPrivate::doNotifyWallpaperHasChangedOrNot() { const QString currentWallpaper = Utils::getWallpaperFilePath(); const WallpaperAspectStyle currentWallpaperAspectStyle = Utils::getWallpaperAspectStyle(); bool notify = false; if (wallpaper != currentWallpaper) { wallpaper = currentWallpaper; notify = true; } if (wallpaperAspectStyle != currentWallpaperAspectStyle) { wallpaperAspectStyle = currentWallpaperAspectStyle; notify = true; } if (notify) { Q_Q(FramelessManager); Q_EMIT q->wallpaperChanged(); DEBUG.nospace() << "Wallpaper changed. Current wallpaper: " << wallpaper << ", aspect style: " << wallpaperAspectStyle << '.'; } } FramelessDataPtr FramelessManagerPrivate::getData(const QObject *window) { Q_ASSERT(window); Q_ASSERT(window->isWidgetType() || window->isWindowType()); if (!window || !(window->isWidgetType() || window->isWindowType())) { return nullptr; } return g_internalData()->dataMap.value(const_cast<QObject *>(window)); } FramelessDataPtr FramelessManagerPrivate::createData(const QObject *window, const WId windowId) { Q_ASSERT(window); Q_ASSERT(window->isWidgetType() || window->isWindowType()); Q_ASSERT(windowId); if (!window || !(window->isWidgetType() || window->isWindowType()) || !windowId) { return nullptr; } const auto win = const_cast<QObject *>(window); auto it = g_internalData()->dataMap.find(win); if (it == g_internalData()->dataMap.end()) { FramelessDataPtr data = FramelessData::create(); data->window = win; data->windowId = windowId; it = g_internalData()->dataMap.insert(win, data); g_internalData()->windowMap.insert(windowId, win); } return it.value(); } WId FramelessManagerPrivate::getWindowId(const QObject *window) { Q_ASSERT(window); Q_ASSERT(window->isWidgetType() || window->isWindowType()); if (!window || !(window->isWidgetType() || window->isWindowType())) { return 0; } if (const FramelessDataPtr data = getData(window)) { return data->windowId; } return 0; } QObject *FramelessManagerPrivate::getWindow(const WId windowId) { Q_ASSERT(windowId); if (!windowId) { return nullptr; } return g_internalData()->windowMap.value(windowId); } void FramelessManagerPrivate::updateWindowId(const QObject *window, const WId newWindowId) { Q_ASSERT(window); Q_ASSERT(window->isWidgetType() || window->isWindowType()); Q_ASSERT(newWindowId); if (!window || !(window->isWidgetType() || window->isWindowType()) || !newWindowId) { return; } const auto win = const_cast<QObject *>(window); const FramelessDataPtr data = g_internalData()->dataMap.value(win); Q_ASSERT(data); if (!data) { return; } const WId oldWindowId = data->windowId; data->windowId = newWindowId; g_internalData()->windowMap.remove(oldWindowId); g_internalData()->windowMap.insert(newWindowId, win); data->frameless = false; std::ignore = FramelessManager::instance()->addWindow(window, newWindowId); } bool FramelessManagerPrivate::isThemeOverrided() const { return (overrideTheme.value_or(SystemTheme::Unknown) != SystemTheme::Unknown); } void FramelessManagerPrivate::initialize() { themeTimer.setInterval(kEventDelayInterval); themeTimer.callOnTimeout(this, [this](){ themeTimer.stop(); doNotifySystemThemeHasChangedOrNot(); }); wallpaperTimer.setInterval(kEventDelayInterval); wallpaperTimer.callOnTimeout(this, [this](){ wallpaperTimer.stop(); doNotifyWallpaperHasChangedOrNot(); }); systemTheme = (Utils::shouldAppsUseDarkMode() ? SystemTheme::Dark : SystemTheme::Light); accentColor = Utils::getAccentColor(); #ifdef Q_OS_WINDOWS colorizationArea = Utils::getDwmColorizationArea(); #endif wallpaper = Utils::getWallpaperFilePath(); wallpaperAspectStyle = Utils::getWallpaperAspectStyle(); DEBUG.nospace() << "Current system theme: " << systemTheme << ", accent color: " << accentColor.name(QColor::HexArgb).toUpper() #ifdef Q_OS_WINDOWS << ", colorization area: " << colorizationArea #endif << ", wallpaper: " << wallpaper << ", aspect style: " << wallpaperAspectStyle << '.'; // We are doing some tricks in our Windows message handling code, so // we don't use Qt's theme notifier on Windows. But for other platforms // we want to use as many Qt functionalities as possible. #if ((QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)) && !FRAMELESSHELPER_CONFIG(native_impl)) QStyleHints *styleHints = QGuiApplication::styleHints(); Q_ASSERT(styleHints); if (styleHints) { connect(styleHints, &QStyleHints::colorSchemeChanged, this, [this](const Qt::ColorScheme colorScheme){ Q_UNUSED(colorScheme); notifySystemThemeHasChangedOrNot(); }); } #endif // ((QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)) && !defined(Q_OS_WINDOWS)) static bool flagSet = false; if (!flagSet) { flagSet = true; // Set a global flag so that people can check whether FramelessHelper is being // used without actually accessing the FramelessHelper interface. static constexpr const char flag[] = "__FRAMELESSHELPER__"; const auto ver = quint64(FramelessHelperVersion().version.num); qputenv(flag, QByteArray::number(ver)); qApp->setProperty(flag, ver); } } FramelessManager::FramelessManager(QObject *parent) : QObject(parent), d_ptr(std::make_unique<FramelessManagerPrivate>(this)) { } FramelessManager::~FramelessManager() = default; FramelessManager *FramelessManager::instance() { static FramelessManager manager; return &manager; } SystemTheme FramelessManager::systemTheme() const { Q_D(const FramelessManager); // The user's choice has top priority. if (d->isThemeOverrided()) { return d->overrideTheme.value(); } return d->systemTheme; } QColor FramelessManager::systemAccentColor() const { Q_D(const FramelessManager); return d->accentColor; } QString FramelessManager::wallpaper() const { Q_D(const FramelessManager); return d->wallpaper; } WallpaperAspectStyle FramelessManager::wallpaperAspectStyle() const { Q_D(const FramelessManager); return d->wallpaperAspectStyle; } void FramelessManager::setOverrideTheme(const SystemTheme theme) { Q_D(FramelessManager); if ((!d->overrideTheme.has_value() && (theme == SystemTheme::Unknown)) || (d->overrideTheme.has_value() && (d->overrideTheme.value() == theme))) { return; } if (theme == SystemTheme::Unknown) { d->overrideTheme = std::nullopt; } else { d->overrideTheme = theme; } Q_EMIT systemThemeChanged(); } bool FramelessManager::addWindow(const QObject *window, const WId windowId) { Q_ASSERT(window); Q_ASSERT(window->isWidgetType() || window->isWindowType()); Q_ASSERT(windowId); if (!window || !(window->isWidgetType() || window->isWindowType()) || !windowId) { return false; } FramelessDataPtr data = FramelessManagerPrivate::getData(window); if (data && data->frameless) { return false; } if (!data) { data = FramelessData::create(); data->window = const_cast<QObject *>(window); data->windowId = windowId; g_internalData()->dataMap.insert(data->window, data); g_internalData()->windowMap.insert(windowId, data->window); } #if FRAMELESSHELPER_CONFIG(native_impl) # ifdef Q_OS_WINDOWS std::ignore = Utils::installWindowProcHook(windowId); FramelessHelperWin::addWindow(window); # elif (defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)) # elif defined(Q_OS_MACOS) # else # endif #else FramelessHelperQt::addWindow(window); #endif if (!data->internalEventHandler) { data->internalEventHandler = new InternalEventFilter(data->window, data->window); data->window->installEventFilter(data->internalEventHandler); } return true; } bool FramelessManager::removeWindow(const QObject *window) { Q_ASSERT(window); if (!window) { return false; } const auto it = g_internalData()->dataMap.constFind(const_cast<QObject *>(window)); if (it == g_internalData()->dataMap.constEnd()) { return false; } const FramelessDataPtr data = it.value(); Q_ASSERT(data); Q_ASSERT(data->window); Q_ASSERT(data->windowId); if (!data || !data->window || !data->windowId) { return false; } if (data->internalEventHandler) { data->window->removeEventFilter(data->internalEventHandler); delete data->internalEventHandler; data->internalEventHandler = nullptr; } #if FRAMELESSHELPER_CONFIG(native_impl) # ifdef Q_OS_WINDOWS FramelessHelperWin::removeWindow(window); std::ignore = Utils::uninstallWindowProcHook(data->windowId); # elif (defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)) # elif defined(Q_OS_MACOS) # else # endif #else FramelessHelperQt::removeWindow(window); #endif g_internalData()->dataMap.erase(it); g_internalData()->windowMap.remove(data->windowId); return true; } FRAMELESSHELPER_END_NAMESPACE #include "framelessmanager.moc"
import React from 'react'; import { ChargingStation } from '../api-station'; interface StationDropdownProps { stations: ChargingStation[]; onStationChange: (value: number) => void; } function StationsDropdown({ stations, onStationChange }: StationDropdownProps) { return ( <select name="selectStation" className="station-form__input" onChange={(e) => { const value = parseInt(e.target.value, 10); onStationChange(value); }} > <option value="">Available charging stations</option> {stations.map((station) => ( <option key={station.id} value={station.id}> {station.name} </option> ))} </select> ); } export default StationsDropdown;
Feature: Sign up feature involving DB layer Scenario: New User Sign Up from UI to DB flow Given I am on the sign up page and I am connected to the DB When I sign up with the following info |username| first | last | email | password| |bob.evans| Bob | Evans | [email protected]| bobevans23| Then I should land on the homepage And The database should also have the correct info Scenario: New User Creation from DB to UI flow Given I am connected to the DB When I add a new user to the database with the following info |username| first | last | email | password| |daisyduck| Daisy | Duck | [email protected]| daisyduck99| Then I should be able to log in with the "daisyduck" as uasername and "daisyduck99" as password on the UI Scenario: Verify Songs Table Column Names Given I am connected to the DB When I retrieve the column names for the Songs table Then It should be the following | id | | title | | artist | | album | | genre | | duration | | path | | albumOrder | | plays | Scenario: Test if input field leading and trailing spaces are truncated before committing data to the database Given I am on the sign up page and I am connected to the DB When I sign up with the following info " bob.evander " " Bob " " Evans " " [email protected] " "bobevans23" Then I should land on the homepage And The database should also have the correct info without spaces @duotify Scenario: Check for duplicate values in the username column Given I am connected to the DB When I send a query to check for duplicate usernames Then The returned result list should be empty
--- title: "Ubuntu 安装 MySQL8 并开启远程访问" author: "Charles" description: "" tags: - blog ogImage: "" postSlug: "ubuntu-mysql" pubDatetime: 2021-05-10T10:33:53.000Z upDatetime: 2022-06-28T18:24:00.000Z featured: false draft: false --- # 安装 MySQL ```bash # 到 https://dev.mysql.com/downloads/repo/apt/ 找到最新的 mysql apt 源配置文件下载地址,例如此处 wget 后边的地址 wget http://dev.mysql.com/get/mysql-apt-config_0.8.16-1_all.deb sudo dpkg -i mysql-apt-config_0.8.16-1_all.deb sudo apt install mysql-server ``` # 配置 MySQL ```bash # 登录 mysql mysql -uroot -p ``` ```bash # 切换数据库 use mysql; # 更改 root 的登录域 update user set host='%' where user='root'; # 给 root 设置密码 ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'toor'; # mysql8 之前修改 root 的权限 ,第一个星号是数据库名,第二个是表名 GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'WITH GRANT OPTION; # mysql8 之后修改 root 的权限 ,第一个星号是数据库名,第二个是表名 grant all privileges on *.* to 'test'@'%'; # 刷新权限 FLUSH PRIVILEGES; ``` # 关掉 ubuntu 防火墙 ```bash sudo ufw disable ``` # 修改 mysqld 配置 ```bash vim /etc/mysql/mysql.conf.d/mysqld.cnf ``` ``` # bind-address = 127.0.0.1 bind-address = 0.0.0.0 ``` # 重启 MySQL ```bash sudo service mysql restart ``` # 其他 ## 其他常用 SQL [https://www.yuque.com/charlesjohn/blog/anbwh6](<博客/MySQL/MySQL 常用操作>) ## Docker 中使用 MySQL <https://www.yuque.com/go/doc/13177685> # 其他和主题无关的话 Windows 开发环境推荐使用 Linux 子系统,或者 phpstudy 和 laragon phpstudy 可以很简单的设置各种常用环境,比如 一键修改 mysql8 的数据库账号密码,redis 账号密码等等 laragon 内置了右键打开控制台和编辑器和更多的开发环境和开发工具,但是对 mysql8 的支持不是很好 如果您使用win10,推荐使用 phpstudy,因为作为一个开发环境工具,初始化环境方便是最重要的。 至于右键打开控制台和编辑器有更好的解决方案,微软应用商店一键安装 terminal,更稳定强大美观。 目前装载了插件的 Terminal 已经可以达到 Mac 下 iterm2 + zsh 的易用程度。 详细的配置方式百度搜索 Windows Terminal 配置 如果您使用 win7 推荐使用 laragon,立刻可以拥有一整套开发环境,也不用想美观不美观了,Terminal 无缘。 当然 git bash 也可以右键打开,但是推荐关掉安装 git 时候生成右键打开 git bash 和 git gui 的开关,又丑又慢又卡。
package com.tangem.core.ui.screen import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.transition.TransitionInflater import com.hasan.jetfasthub.R import com.hasan.jetfasthub.core.ui.screen.ComposeScreen import com.hasan.jetfasthub.core.ui.screen.createComposeView /** * An abstract base class for fragments that use Compose for UI rendering. * Extends [Fragment] and implements [ComposeScreen] interface. */ abstract class ComposeFragment : Fragment(), ComposeScreen { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val isTransitionsInflated = TransitionInflater.from(requireContext()).inflateTransitions() return createComposeView(inflater.context).also { it.isTransitionGroup = isTransitionsInflated } } /** * Inflates transitions for the fragment. Override this method to customize * enter and exit transitions for the fragment. * * @return `true` if transitions were inflated; `false` otherwise. */ protected open fun TransitionInflater.inflateTransitions(): Boolean { enterTransition = inflateTransition(R.transition.slide_right) exitTransition = inflateTransition(R.transition.fade) return true } }
import React from "react"; import useAutoComplete from "./useAutocomplete"; const getSplitText = ( suggestions: any, index: number, selectedValue: string ) => ({ startString: suggestions[index].label.substr( 0, suggestions[index].label.toLowerCase().indexOf(selectedValue.toLowerCase()) ), endString: suggestions[index].label.substr( suggestions[index].label .toLowerCase() .indexOf(selectedValue.toLowerCase()) + selectedValue.length ), highlightedText: suggestions[index].label.substr( suggestions[index].label.toLowerCase().indexOf(selectedValue.toLowerCase()), selectedValue.length ), }); const Autocomplete = () => { const { bindInput, bindOptions, bindOption, isLoading, suggestions } = useAutoComplete(async (search: string) => { try { const res = await fetch( `http://universities.hipolabs.com/search?name=${search}` ); const data = await res.json(); return data.map((d: any, index: number) => ({ value: index, label: d.name, })); } catch (e) { return []; } }); return ( <div className="autocompleteContainer"> <div className="autocompleteInputContainer"> <input placeholder="Search" className="autocompleteInput" {...bindInput} /> {isLoading && <div className="autocompleteSpinner"></div>} </div> <ul {...bindOptions} className="autocompleteList"> {suggestions.map((_, index) => { const { startString, highlightedText, endString } = getSplitText( suggestions, index, bindInput.value ); return ( <li className="autocompleteItem" key={index} {...bindOption}> <div className="autocompleteItemContainer"> {startString} <span className="autocompleteInputMatching"> {highlightedText} </span> {endString} </div> </li> ); })} </ul> </div> ); }; export default Autocomplete;
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * @test * @bug 8073583 * @summary C2 support for CRC32C on SPARC * * @run main/othervm/timeout=600 -Xbatch TestCRC32C -m */ import java.nio.ByteBuffer; import java.util.zip.Checksum; import java.util.zip.CRC32C; public class TestCRC32C { public static void main(String[] args) { int offset = Integer.getInteger("offset", 0); int msgSize = Integer.getInteger("msgSize", 512); boolean multi = false; int iters = 20000; int warmupIters = 20000; if (args.length > 0) { if (args[0].equals("-m")) { multi = true; } else { iters = Integer.valueOf(args[0]); } if (args.length > 1) { warmupIters = Integer.valueOf(args[1]); } } if (multi) { test_multi(warmupIters); return; } System.out.println(" offset = " + offset); System.out.println("msgSize = " + msgSize + " bytes"); System.out.println(" iters = " + iters); byte[] b = initializedBytes(msgSize, offset); CRC32C crc0 = new CRC32C(); CRC32C crc1 = new CRC32C(); CRC32C crc2 = new CRC32C(); crc0.update(b, offset, msgSize); System.out.println("-------------------------------------------------------"); /* warm up */ for (int i = 0; i < warmupIters; i++) { crc1.reset(); crc1.update(b, offset, msgSize); } /* measure performance */ long start = System.nanoTime(); for (int i = 0; i < iters; i++) { crc1.reset(); crc1.update(b, offset, msgSize); } long end = System.nanoTime(); double total = (double)(end - start)/1e9; // in seconds double thruput = (double)msgSize*iters/1e6/total; // in MB/s System.out.println("CRC32C.update(byte[]) runtime = " + total + " seconds"); System.out.println("CRC32C.update(byte[]) throughput = " + thruput + " MB/s"); /* check correctness */ for (int i = 0; i < iters; i++) { crc1.reset(); crc1.update(b, offset, msgSize); if (!check(crc0, crc1)) break; } report("CRCs", crc0, crc1); System.out.println("-------------------------------------------------------"); ByteBuffer buf = ByteBuffer.allocateDirect(msgSize); buf.put(b, offset, msgSize); buf.flip(); /* warm up */ for (int i = 0; i < warmupIters; i++) { crc2.reset(); crc2.update(buf); buf.rewind(); } /* measure performance */ start = System.nanoTime(); for (int i = 0; i < iters; i++) { crc2.reset(); crc2.update(buf); buf.rewind(); } end = System.nanoTime(); total = (double)(end - start)/1e9; // in seconds thruput = (double)msgSize*iters/1e6/total; // in MB/s System.out.println("CRC32C.update(ByteBuffer) runtime = " + total + " seconds"); System.out.println("CRC32C.update(ByteBuffer) throughput = " + thruput + " MB/s"); /* check correctness */ for (int i = 0; i < iters; i++) { crc2.reset(); crc2.update(buf); buf.rewind(); if (!check(crc0, crc2)) break; } report("CRCs", crc0, crc2); System.out.println("-------------------------------------------------------"); } private static void report(String s, Checksum crc0, Checksum crc1) { System.out.printf("%s: crc0 = %08x, crc1 = %08x\n", s, crc0.getValue(), crc1.getValue()); } private static boolean check(Checksum crc0, Checksum crc1) { if (crc0.getValue() != crc1.getValue()) { System.err.printf("ERROR: crc0 = %08x, crc1 = %08x\n", crc0.getValue(), crc1.getValue()); return false; } return true; } private static byte[] initializedBytes(int M, int offset) { byte[] bytes = new byte[M + offset]; for (int i = 0; i < offset; i++) { bytes[i] = (byte) i; } for (int i = offset; i < bytes.length; i++) { bytes[i] = (byte) (i - offset); } return bytes; } private static void test_multi(int iters) { int len1 = 8; // the 8B/iteration loop int len2 = 32; // the 32B/iteration loop int len3 = 4096; // the 4KB/iteration loop byte[] b = initializedBytes(len3*16, 0); int[] offsets = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 32, 64, 128, 256, 512 }; int[] sizes = { 0, 1, 2, 3, 4, 5, 6, 7, len1, len1+1, len1+2, len1+3, len1+4, len1+5, len1+6, len1+7, len1*2, len1*2+1, len1*2+3, len1*2+5, len1*2+7, len2, len2+1, len2+3, len2+5, len2+7, len2*2, len2*4, len2*8, len2*16, len2*32, len2*64, len3, len3+1, len3+3, len3+5, len3+7, len3*2, len3*4, len3*8, len1+len2, len1+len2+1, len1+len2+3, len1+len2+5, len1+len2+7, len1+len3, len1+len3+1, len1+len3+3, len1+len3+5, len1+len3+7, len2+len3, len2+len3+1, len2+len3+3, len2+len3+5, len2+len3+7, len1+len2+len3, len1+len2+len3+1, len1+len2+len3+3, len1+len2+len3+5, len1+len2+len3+7, (len1+len2+len3)*2, (len1+len2+len3)*2+1, (len1+len2+len3)*2+3, (len1+len2+len3)*2+5, (len1+len2+len3)*2+7, (len1+len2+len3)*3, (len1+len2+len3)*3-1, (len1+len2+len3)*3-3, (len1+len2+len3)*3-5, (len1+len2+len3)*3-7 }; CRC32C[] crc0 = new CRC32C[offsets.length*sizes.length]; CRC32C[] crc1 = new CRC32C[offsets.length*sizes.length]; int i, j, k; System.out.printf("testing %d cases ...\n", offsets.length*sizes.length); /* set the result from interpreter as reference */ for (i = 0; i < offsets.length; i++) { for (j = 0; j < sizes.length; j++) { crc0[i*sizes.length + j] = new CRC32C(); crc1[i*sizes.length + j] = new CRC32C(); crc0[i*sizes.length + j].update(b, offsets[i], sizes[j]); } } /* warm up the JIT compiler and get result */ for (k = 0; k < iters; k++) { for (i = 0; i < offsets.length; i++) { for (j = 0; j < sizes.length; j++) { crc1[i*sizes.length + j].reset(); crc1[i*sizes.length + j].update(b, offsets[i], sizes[j]); } } } /* check correctness */ for (i = 0; i < offsets.length; i++) { for (j = 0; j < sizes.length; j++) { if (!check(crc0[i*sizes.length + j], crc1[i*sizes.length + j])) { System.out.printf("offsets[%d] = %d", i, offsets[i]); System.out.printf("\tsizes[%d] = %d\n", j, sizes[j]); } } } } }
// This file is part of Frontier. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. use ethereum_types::{Address, U128, U256, U64}; use serde::{ de, ser::{self, SerializeStruct}, Deserialize, Serialize, }; use crate::{access_list::AccessList, bytes::Bytes, transaction::TxType}; /// Transaction request from the RPC. #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TransactionRequest { /// [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction type #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")] pub tx_type: Option<TxType>, /// Sender #[serde(default, skip_serializing_if = "Option::is_none")] pub from: Option<Address>, /// Recipient #[serde(default, skip_serializing_if = "Option::is_none")] pub to: Option<Address>, /// Value of transaction in wei #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<U256>, /// Transaction's nonce #[serde(default, skip_serializing_if = "Option::is_none")] pub nonce: Option<U64>, /// Gas limit #[serde(default, skip_serializing_if = "Option::is_none")] pub gas: Option<U128>, /// The gas price willing to be paid by the sender in wei #[serde(default, skip_serializing_if = "Option::is_none")] pub gas_price: Option<U128>, /// The maximum total fee per gas the sender is willing to pay (includes the network / base fee and miner / priority fee) in wei #[serde(default, skip_serializing_if = "Option::is_none")] pub max_fee_per_gas: Option<U128>, /// Maximum fee per gas the sender is willing to pay to miners in wei #[serde(default, skip_serializing_if = "Option::is_none")] pub max_priority_fee_per_gas: Option<U128>, /// Additional data #[serde(default, flatten)] pub input: TransactionInput, /// Chain ID that this transaction is valid on #[serde(default, skip_serializing_if = "Option::is_none")] pub chain_id: Option<U64>, /// EIP-2930 access list #[serde(default, skip_serializing_if = "Option::is_none")] pub access_list: Option<AccessList>, } impl TransactionRequest { /// Sets the transactions type for the transactions. #[inline] pub const fn tx_type(mut self, tx_type: TxType) -> Self { self.tx_type = Some(tx_type); self } /// Sets the `from` field in the call to the provided address #[inline] pub const fn from(mut self, from: Address) -> Self { self.from = Some(from); self } /// Sets the recipient address for the transaction. #[inline] pub const fn to(mut self, to: Address) -> Self { self.to = Some(to); self } /// Sets the nonce for the transaction. #[inline] pub const fn nonce(mut self, nonce: U64) -> Self { self.nonce = Some(nonce); self } /// Sets the value (amount) for the transaction. #[inline] pub const fn value(mut self, value: U256) -> Self { self.value = Some(value); self } /// Sets the gas limit for the transaction. #[inline] pub const fn gas_limit(mut self, gas_limit: U128) -> Self { self.gas = Some(gas_limit); self } /// Sets the maximum fee per gas for the transaction. #[inline] pub const fn max_fee_per_gas(mut self, max_fee_per_gas: U128) -> Self { self.max_fee_per_gas = Some(max_fee_per_gas); self } /// Sets the maximum priority fee per gas for the transaction. #[inline] pub const fn max_priority_fee_per_gas(mut self, max_priority_fee_per_gas: U128) -> Self { self.max_priority_fee_per_gas = Some(max_priority_fee_per_gas); self } /// Sets the input data for the transaction. pub fn input(mut self, input: TransactionInput) -> Self { self.input = input; self } /// Sets the access list for the transaction. pub fn access_list(mut self, access_list: AccessList) -> Self { self.access_list = Some(access_list); self } /// Returns the configured fee cap, if any. /// /// The returns `gas_price` (legacy) if set or `max_fee_per_gas` (EIP1559) #[inline] pub fn fee_cap(&self) -> Option<U128> { self.gas_price.or(self.max_fee_per_gas) } } /// Additional data of the transaction. /// /// We accept (older) "data" and (newer) "input" for backwards-compatibility reasons. /// If both fields are set, it is expected that they contain the same value, otherwise an error is returned. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct TransactionInput { /// Transaction data pub input: Option<Bytes>, /// Transaction data /// /// This is the same as `input` but is used for backwards compatibility: <https://github.com/ethereum/go-ethereum/issues/15628> pub data: Option<Bytes>, } impl TransactionInput { /// Return the additional data of the transaction. pub fn into_bytes(self) -> Option<Bytes> { match (self.input, self.data) { (Some(input), _) => Some(input), (None, Some(data)) => Some(data), (None, None) => None, } } } impl serde::Serialize for TransactionInput { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match (&self.input, &self.data) { (Some(input), Some(data)) => { if input == data { let mut s = serde::Serializer::serialize_struct(serializer, "TransactionInput", 2)?; s.serialize_field("input", input)?; s.serialize_field("data", data)?; s.end() } else { Err(ser::Error::custom("Ambiguous value for `input` and `data`")) } } (Some(input), None) => { let mut s = serde::Serializer::serialize_struct(serializer, "TransactionInput", 1)?; s.serialize_field("input", input)?; s.skip_field("data")?; s.end() } (None, Some(data)) => { let mut s = serde::Serializer::serialize_struct(serializer, "TransactionInput", 1)?; s.skip_field("input")?; s.serialize_field("data", data)?; s.end() } (None, None) => { let mut s = serde::Serializer::serialize_struct(serializer, "TransactionInput", 0)?; s.skip_field("input")?; s.skip_field("data")?; s.end() } } } } impl<'de> serde::Deserialize<'de> for TransactionInput { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { #[derive(Deserialize)] struct InputOrData { input: Option<Bytes>, data: Option<Bytes>, } let InputOrData { input, data } = InputOrData::deserialize(deserializer)?; match (input, data) { (Some(input), Some(data)) => { if input == data { Ok(Self { input: Some(input), data: Some(data), }) } else { Err(de::Error::custom("Ambiguous value for `input` and `data`")) } } (input, data) => Ok(Self { input, data }), } } } #[cfg(test)] mod tests { use super::*; #[test] fn transaction_input_serde_impl() { let valid_cases = [ ( r#"{"input":"0x12","data":"0x12"}"#, TransactionInput { input: Some(Bytes(vec![0x12])), data: Some(Bytes(vec![0x12])), }, ), ( r#"{"input":"0x12"}"#, TransactionInput { input: Some(Bytes(vec![0x12])), data: None, }, ), ( r#"{"data":"0x12"}"#, TransactionInput { input: None, data: Some(Bytes(vec![0x12])), }, ), ( r#"{}"#, TransactionInput { input: None, data: None, }, ), ]; for (raw, typed) in valid_cases { let deserialized = serde_json::from_str::<TransactionInput>(raw).unwrap(); assert_eq!(deserialized, typed); let serialized = serde_json::to_string(&typed).unwrap(); assert_eq!(serialized, raw); } let invalid_serialization_cases = [TransactionInput { input: Some(Bytes(vec![0x12])), data: Some(Bytes(vec![0x23])), }]; for typed in invalid_serialization_cases { let serialized: Result<String, _> = serde_json::to_string(&typed); assert!(serialized.is_err()); } let invalid_deserialization_cases = [r#"{"input":"0x12","data":"0x23"}"#]; for raw in invalid_deserialization_cases { let input: Result<TransactionInput, _> = serde_json::from_str(raw); assert!(input.is_err()); } } }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # # Reference (https://ieeexplore.ieee.org/document/9625818) """Encoder modules.""" import torch import inspect from layers.conv_layer import NonCausalConv1d from layers.conv_layer import CausalConv1d from models.autoencoder.modules.residual_unit import NonCausalResidualUnit from models.autoencoder.modules.residual_unit import CausalResidualUnit from models.utils import check_mode class EncoderBlock(torch.nn.Module): """ Encoder block (downsampling) """ def __init__( self, in_channels, out_channels, stride, dilations=(1, 3, 9), bias=True, mode='causal', ): super().__init__() self.mode = mode if self.mode == 'noncausal': ResidualUnit = NonCausalResidualUnit Conv1d = NonCausalConv1d elif self.mode == 'causal': ResidualUnit = CausalResidualUnit Conv1d = CausalConv1d else: raise NotImplementedError(f"Mode ({self.mode}) is not supported!") self.res_units = torch.nn.ModuleList() for dilation in dilations: self.res_units += [ ResidualUnit(in_channels, in_channels, dilation=dilation)] self.num_res = len(self.res_units) self.conv = Conv1d( in_channels=in_channels, out_channels=out_channels, kernel_size=(2 * stride), stride=stride, bias=bias, ) def forward(self, x): for idx in range(self.num_res): x = self.res_units[idx](x) x = self.conv(x) return x def inference(self, x): check_mode(self.mode, inspect.stack()[0][3]) for idx in range(self.num_res): x = self.res_units[idx].inference(x) x = self.conv.inference(x) return x class Encoder(torch.nn.Module): def __init__(self, input_channels, encode_channels, combine_channel_ratios=(2, 4), seperate_channel_ratios_speech=(8, 16,32), seperate_channel_ratios_rir=(8, 8, 16,32), combine_strides=(2, 2), seperate_strides_speech=(3, 5, 5), seperate_strides_rir=(2, 3, 5, 5, 5), kernel_size=7, bias=True, mode='causal', ): super().__init__() assert len(combine_channel_ratios) == len(combine_strides) assert len(seperate_channel_ratios_speech) == len(seperate_strides_speech) assert len(seperate_channel_ratios_rir) == len(seperate_strides_rir) self.mode = mode if self.mode == 'noncausal': Conv1d = NonCausalConv1d elif self.mode == 'causal': Conv1d = CausalConv1d else: raise NotImplementedError(f"Mode ({self.mode}) is not supported!") self.conv = Conv1d( in_channels=input_channels, out_channels=encode_channels, kernel_size=kernel_size, stride=1, bias=False) self.conv_combine = Conv1d( in_channels=input_channels, out_channels=input_channels, kernel_size=3, stride=1, bias=False) self.combine_conv_blocks = torch.nn.ModuleList() self.seperate_conv_blocks_1 = torch.nn.ModuleList() # self.seperate_conv_blocks_2 = torch.nn.ModuleList() in_channels = encode_channels self.encode_RIR = torch.nn.Sequential( torch.nn.Conv1d(input_channels, 8*in_channels, 96001, 1500, 48000, bias=False), torch.nn.LeakyReLU(0.2, inplace=True), # state size. (ndf) x 1024 torch.nn.Conv1d(8*in_channels, 16*in_channels, 41, 2, 20, bias=False), torch.nn.BatchNorm1d(16*in_channels), torch.nn.LeakyReLU(0.2, inplace=True), torch.nn.Conv1d(16*in_channels, 32*in_channels, 41, 2, 20, bias=False), torch.nn.BatchNorm1d(32*in_channels), torch.nn.LeakyReLU(0.2, inplace=True), ) self.encode_RIR_s = torch.nn.Sequential( torch.nn.Conv1d(in_channels, 16*in_channels, 96001, 3000, 48000, bias=False), torch.nn.LeakyReLU(0.2, inplace=True), # state size. (ndf) x 1024 torch.nn.Conv1d(16*in_channels, 32*in_channels, 41, 2, 20, bias=False), torch.nn.BatchNorm1d(32*in_channels), torch.nn.LeakyReLU(0.2, inplace=True), ) for idx, stride in enumerate(combine_strides): out_channels = encode_channels * combine_channel_ratios[idx] self.combine_conv_blocks += [ EncoderBlock(in_channels, out_channels, stride, bias=bias, mode=self.mode)] in_channels = out_channels seperate_in_channels = in_channels in_channels=seperate_in_channels for idx, stride in enumerate(seperate_strides_speech): out_channels = encode_channels * seperate_channel_ratios_speech[idx] self.seperate_conv_blocks_1 += [ EncoderBlock(in_channels, out_channels, stride, bias=bias, mode=self.mode)] in_channels = out_channels in_channels=seperate_in_channels # for idx, stride in enumerate(seperate_strides_rir): # out_channels = encode_channels * seperate_channel_ratios_rir[idx] # self.seperate_conv_blocks_2 += [ # EncoderBlock(in_channels, out_channels, stride, bias=bias, mode=self.mode)] # in_channels = out_channels self.combine_num_blocks = len(self.combine_conv_blocks) self.seperate_num_blocks_speech = len(self.seperate_conv_blocks_1) # self.seperate_num_blocks_rir = len(self.seperate_conv_blocks_2) self.out_channels = out_channels def forward(self, x): x_combine = self.conv_combine(x) x_speech = self.conv(x_combine) # for i in range(self.combine_num_blocks): # x_combine = self.combine_conv_blocks[i](x_combine) # x_speech = x_combine x_rir = x_combine for i in range(self.seperate_num_blocks_speech): x_speech = self.seperate_conv_blocks_1[i](x_speech) # x_speech = self.encode_RIR_s(x_speech) # for i in range(self.seperate_num_blocks_rir): # x_rir = self.seperate_conv_blocks_2[i](x_rir) x_rir = self.encode_RIR(x_rir) return x_speech, x_rir def encode(self, x): check_mode(self.mode, inspect.stack()[0][3]) x_combine = self.conv_combine(x) x_speech = self.conv(x_combine) # for i in range(self.combine_num_blocks): # x_combine = self.combine_conv_blocks[i](x_combine) # x_speech = x_combine x_rir = x_combine for i in range(self.seperate_num_blocks_speech): x_speech = self.seperate_conv_blocks_1[i](x_speech) # x_speech = self.encode_RIR_s(x_speech) # for i in range(self.seperate_num_blocks_rir): # x_rir = self.seperate_conv_blocks_2[i](x_rir) x_rir = self.encode_RIR(x_rir) return x_speech, x_rir
import Container from "@/components/map/panels/Container"; import ProjectLayerDropdown from "@/components/map/panels/ProjectLayerDropdown"; import { useActiveLayer } from "@/hooks/map/LayerPanelHooks"; import { useAppDispatch } from "@/hooks/store/ContextHooks"; import { useTranslation } from "@/i18n/client"; import { updateProjectLayer, useProjectLayers } from "@/lib/api/projects"; import { setActiveRightPanel } from "@/lib/store/map/slice"; import type { ProjectLayer } from "@/lib/validations/project"; import { Accordion, AccordionDetails, AccordionSummary, Box, Divider, Slider, Stack, Typography, } from "@mui/material"; import { ICON_NAME, Icon } from "@p4b/ui/components/Icon"; import { useMemo, type ReactNode, useState } from "react"; import { v4 } from "uuid"; const AccordionHeader = ({ title }: { title: string }) => { return ( <Stack spacing={2} direction="row" alignItems="center"> <Typography variant="body2" fontWeight="bold"> {title} </Typography> </Stack> ); }; const AccordionWrapper = ({ header, body, }: { header: ReactNode; body: ReactNode; }) => { return ( <Accordion square={false}> <AccordionSummary sx={{ my: 0, py: 0, }} expandIcon={ <Icon iconName={ICON_NAME.CHEVRON_DOWN} style={{ fontSize: "15px" }} /> } aria-controls="panel1a-content" > {header} </AccordionSummary> <Divider sx={{ mt: 0, pt: 0 }} /> <AccordionDetails sx={{ pt: 0, mt: 0 }}>{body}</AccordionDetails> </Accordion> ); }; const LayerInfo = ({ layer }: { layer: ProjectLayer }) => { const { t } = useTranslation("maps"); return ( <AccordionWrapper header={ <> <AccordionHeader title="Layer Info" /> </> } body={ <> <Stack spacing={2}> <Typography variant="body2" fontWeight="bold"> Dataset Source </Typography> <Typography variant="body2">{layer.name}</Typography> <Typography variant="body2" fontWeight="bold"> Type </Typography> <Typography variant="body2">{t(layer.type)}</Typography> </Stack> </> } /> ); }; const Visibility = ({ layer, projectId, }: { layer: ProjectLayer; projectId: string; }) => { const { layers: projectLayers, mutate: mutateProjectLayers } = useProjectLayers(projectId); const layerType = layer.properties.type; const opacity = useMemo(() => { if (!layer.properties.paint) return 100; return layer.properties.paint[`${layerType}-opacity`] * 100; }, [layer.properties.paint, layerType]); const visibilityRange = useMemo(() => { const minZoom = layer.properties.minzoom || 0; const maxZoom = layer.properties.maxzoom || 22; return [minZoom, maxZoom]; }, [layer.properties.minzoom, layer.properties.maxzoom]); const [opacityValue, setOpacityValue] = useState<number>(opacity); const [visibilityRangeValue, setVisibilityRangeValue] = useState<number[]>(visibilityRange); const changeOpacity = async (value: number) => { const layers = JSON.parse(JSON.stringify(projectLayers)); const index = layers.findIndex((l) => l.id === layer.id); const layerToUpdate = layers[index]; layerToUpdate.updated_at = v4(); // temporary key until update_at is if (!layerToUpdate.properties.paint) { layerToUpdate.properties.paint = {}; } layerToUpdate.properties.paint[`${layerType}-opacity`] = value / 100; await mutateProjectLayers(layers, false); await updateProjectLayer(projectId, layer.id, layerToUpdate); }; const changeVisibilityRangeValue = async (value: number[]) => { const layers = JSON.parse(JSON.stringify(projectLayers)); const index = layers.findIndex((l) => l.id === layer.id); const layerToUpdate = layers[index]; layerToUpdate.updated_at = v4(); // temporary key until update_at is layerToUpdate.properties.minzoom = value[0]; layerToUpdate.properties.maxzoom = value[1]; await mutateProjectLayers(layers, false); await updateProjectLayer(projectId, layer.id, layerToUpdate); }; const marks = [ { value: 25, label: "25%", }, { value: 50, label: "50%", }, { value: 75, label: "75%", }, ]; return ( <AccordionWrapper header={<AccordionHeader title="Visibility" />} body={ <Stack spacing={4}> <Box> <Typography variant="body2">Opacity</Typography> <Box sx={{ px: 2, mt: 2 }}> <Slider aria-label="Layer Opacity" value={opacityValue} onChange={(_event: Event, newValue: number | number[]) => { setOpacityValue(newValue as number); }} onChangeCommitted={(_event: Event, value: number | number[]) => changeOpacity(value as number) } step={1} valueLabelDisplay="auto" marks={marks} /> </Box> </Box> <Box> <Typography variant="body2">Visibility Range</Typography> <Box sx={{ px: 2, mt: 2 }}> <Slider getAriaLabel={() => "Visibility Range"} value={visibilityRangeValue} min={0} max={22} onChange={(_event: Event, newValue: number | number[]) => { setVisibilityRangeValue(newValue as number[]); }} onChangeCommitted={(_event: Event, value: number | number[]) => changeVisibilityRangeValue(value as number[]) } step={1} valueLabelDisplay="auto" /> </Box> </Box> </Stack> } /> ); }; const Symbology = () => { return ( <AccordionWrapper header={<AccordionHeader title="Symbology" />} body={<></>} /> ); }; const PropertiesPanel = ({ projectId }: { projectId: string }) => { const dispatch = useAppDispatch(); const activeLayer = useActiveLayer(projectId); return ( <Container title="Properties" direction="right" disablePadding={true} close={() => dispatch(setActiveRightPanel(undefined))} body={ <> {activeLayer && ( <> <ProjectLayerDropdown projectId={projectId} /> <LayerInfo layer={activeLayer} /> <Symbology /> <Visibility layer={activeLayer} projectId={projectId} /> </> )} </> } /> ); }; export default PropertiesPanel;
import { Component, inject, OnInit } from '@angular/core'; import { HttpResponse } from '@angular/common/http'; import { ActivatedRoute } from '@angular/router'; import { Observable } from 'rxjs'; import { finalize, map } from 'rxjs/operators'; import SharedModule from 'app/shared/shared.module'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AlertError } from 'app/shared/alert/alert-error.model'; import { EventManager, EventWithContent } from 'app/core/util/event-manager.service'; import { DataUtils, FileLoadError } from 'app/core/util/data-util.service'; import { IPerson } from 'app/entities/person/person.model'; import { PersonService } from 'app/entities/person/service/person.service'; import { ActivationStatusEnum } from 'app/entities/enumerations/activation-status-enum.model'; import { SupplierService } from '../service/supplier.service'; import { ISupplier } from '../supplier.model'; import { SupplierFormService, SupplierFormGroup } from './supplier-form.service'; @Component({ standalone: true, selector: 'jhi-supplier-update', templateUrl: './supplier-update.component.html', imports: [SharedModule, FormsModule, ReactiveFormsModule], }) export class SupplierUpdateComponent implements OnInit { isSaving = false; supplier: ISupplier | null = null; activationStatusEnumValues = Object.keys(ActivationStatusEnum); peopleSharedCollection: IPerson[] = []; protected dataUtils = inject(DataUtils); protected eventManager = inject(EventManager); protected supplierService = inject(SupplierService); protected supplierFormService = inject(SupplierFormService); protected personService = inject(PersonService); protected activatedRoute = inject(ActivatedRoute); // eslint-disable-next-line @typescript-eslint/member-ordering editForm: SupplierFormGroup = this.supplierFormService.createSupplierFormGroup(); comparePerson = (o1: IPerson | null, o2: IPerson | null): boolean => this.personService.comparePerson(o1, o2); ngOnInit(): void { this.activatedRoute.data.subscribe(({ supplier }) => { this.supplier = supplier; if (supplier) { this.updateForm(supplier); } this.loadRelationshipsOptions(); }); } byteSize(base64String: string): string { return this.dataUtils.byteSize(base64String); } openFile(base64String: string, contentType: string | null | undefined): void { this.dataUtils.openFile(base64String, contentType); } setFileData(event: Event, field: string, isImage: boolean): void { this.dataUtils.loadFileToForm(event, this.editForm, field, isImage).subscribe({ error: (err: FileLoadError) => this.eventManager.broadcast( new EventWithContent<AlertError>('azimuteErpQuarkusAngularMonolith02App.error', { ...err, key: 'error.file.' + err.key }), ), }); } previousState(): void { window.history.back(); } save(): void { this.isSaving = true; const supplier = this.supplierFormService.getSupplier(this.editForm); if (supplier.id !== null) { this.subscribeToSaveResponse(this.supplierService.update(supplier)); } else { this.subscribeToSaveResponse(this.supplierService.create(supplier)); } } protected subscribeToSaveResponse(result: Observable<HttpResponse<ISupplier>>): void { result.pipe(finalize(() => this.onSaveFinalize())).subscribe({ next: () => this.onSaveSuccess(), error: () => this.onSaveError(), }); } protected onSaveSuccess(): void { this.previousState(); } protected onSaveError(): void { // Api for inheritance. } protected onSaveFinalize(): void { this.isSaving = false; } protected updateForm(supplier: ISupplier): void { this.supplier = supplier; this.supplierFormService.resetForm(this.editForm, supplier); this.peopleSharedCollection = this.personService.addPersonToCollectionIfMissing<IPerson>( this.peopleSharedCollection, supplier.representativePerson, ); } protected loadRelationshipsOptions(): void { this.personService .query() .pipe(map((res: HttpResponse<IPerson[]>) => res.body ?? [])) .pipe( map((people: IPerson[]) => this.personService.addPersonToCollectionIfMissing<IPerson>(people, this.supplier?.representativePerson)), ) .subscribe((people: IPerson[]) => (this.peopleSharedCollection = people)); } }
<!-- /* * Copyright 2018 Adobe. All rights reserved. * This file is licensed to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ --> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" /> <link rel="icon" href="/favicon.ico" /> <link rel="stylesheet" href="/styles.css" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" /> <script src="https://momentjs.com/downloads/moment.min.js"></script> <title>${content.title}</title> </head> <body> <div class="header"> <div class="title"> <h1> <span class="menu-icon"></span> <img src="/helix_logo.png" /> Documentation </h1> </div> <div class="search"> <form action="https://www.google.com/search" method="GET"> <input type="text" value="" placeholder="Search" class="searchinput" name="q"> <input type="hidden" value="site:www.project-helix.io" name="q"> </form> </div> </div> <div class="main"> <div class="nav"> <!-- include ${content.nav}.summary.html--> <esi:include src="${content.nav}.summary.html"></esi:include> </div> <div class="content"> <div class="content-body"> <div class="title"> <h1>${content.title}</h1> <div data-sly-test="${content.committers && content.lastModified}" class="author"> <sly data-sly-list="${content.committers}"><img title="${item.display}" src="${item.avatar_url}"></sly> <span class="lastModified">Last modified <time datetime="${content.lastModified.raw}">${content.lastModified.display}</time></span> </div> </div> <div data-sly-test="${content.document}">${content.document.body}</div> </div> </div> </div> <script> window.addEventListener('load', () => { const parent = document.getElementsByClassName('lastModified')[0]; const elem = parent.children[0]; const lastMod = elem.getAttribute('datetime'); elem.innerHTML = moment(lastMod).fromNow(); parent.className += ' visible'; document.querySelectorAll('ul li ul').forEach(function (elem) { elem.parentElement.addEventListener('click', function () { if (!elem.classList.contains('opened')) { elem.classList.add('opened'); } else { elem.classList.remove('opened'); } }); }); document.querySelectorAll('ul li a').forEach(function (elem) { if (elem.href == window.location.href) { let ul = elem.parentElement.parentElement; const sibling = ul.querySelector('ul'); if (sibling) { ul = sibling; } ul.classList.add('opened'); } elem.parentElement.addEventListener('click', function (ev) { ev.stopPropagation(); }); }); document.querySelector('.menu-icon').addEventListener('click', function (ev) { const nav = document.querySelector('.nav'); const content = document.querySelector('.content'); if (!nav.classList.contains('opened')) { nav.classList.add('opened'); content.classList.add('closed'); } else { nav.classList.remove('opened'); content.classList.remove('closed'); } }); }); </script> </body> </html>
import { createContext, useContext, useEffect, useState } from "react"; import {auth, db} from '../Firebase'; import { createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, onAuthStateChanged } from "firebase/auth"; import { setDoc, doc } from "firebase/firestore"; const AuthContext = createContext(); export function AuthContextProvider({children}){ const [user, setUser] = useState({}); async function signUp(email, password) { createUserWithEmailAndPassword(auth, email, password); await setDoc(doc(db, 'users', email), { savedShows: [] }) } function logIn(email,password) { return signInWithEmailAndPassword(auth, email, password) } function logOut() { return signOut(auth) } useEffect(() => { const unsubscribe = onAuthStateChanged(auth, (currentUser)=> { setUser(currentUser) }); return () => { unsubscribe() }; }, []) return( <AuthContext.Provider value={{ signUp,logIn,logOut, user }}> {children} </AuthContext.Provider> ) } export function UserAuth(){ return useContext(AuthContext) }
#![allow(unused_imports)] #![allow(clippy::all)] use super::*; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { # [wasm_bindgen (extends = :: js_sys :: Object , js_name = MediaConfiguration)] #[derive(Debug, Clone, PartialEq, Eq)] #[doc = "The `MediaConfiguration` dictionary."] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `MediaConfiguration`*"] pub type MediaConfiguration; #[cfg(feature = "AudioConfiguration")] #[wasm_bindgen(method, setter = "audio")] fn audio_shim(this: &MediaConfiguration, val: &AudioConfiguration); #[cfg(feature = "VideoConfiguration")] #[wasm_bindgen(method, setter = "video")] fn video_shim(this: &MediaConfiguration, val: &VideoConfiguration); } impl MediaConfiguration { #[doc = "Construct a new `MediaConfiguration`."] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `MediaConfiguration`*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); ret } #[cfg(feature = "AudioConfiguration")] #[doc = "Change the `audio` field of this object."] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `AudioConfiguration`, `MediaConfiguration`*"] pub fn audio(&mut self, val: &AudioConfiguration) -> &mut Self { self.audio_shim(val); self } #[cfg(feature = "VideoConfiguration")] #[doc = "Change the `video` field of this object."] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `MediaConfiguration`, `VideoConfiguration`*"] pub fn video(&mut self, val: &VideoConfiguration) -> &mut Self { self.video_shim(val); self } } impl Default for MediaConfiguration { fn default() -> Self { Self::new() } }
package by.bntu.backend.domain; import com.fasterxml.jackson.annotation.*; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; @Entity @Table(name = "usr") @Data @EqualsAndHashCode(of = "id") public class User implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @JsonView(Views.Id.class) private Long id; @JsonView(Views.IdName.class) private String username; @JsonView(Views.FullProfile.class) private String firstName; @JsonView(Views.FullProfile.class) private String lastName; private boolean active; private String password; private String activationCode; private String email; @ManyToMany @JoinTable( name = "user_projects", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "project_id") ) @JsonView(Views.FullProfile.class) Set<Project> projects = new HashSet<>(); @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER) @CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id")) @Enumerated(EnumType.STRING) @JsonView(Views.FullProfile.class) Set<Role> roles = new HashSet<>(); public User() { } public User(String username, String password, Collection<? extends GrantedAuthority> authorities) { this.username = username; this.password = password; this.roles = authorities.stream().map(grantedAuthority -> Role.valueOf(grantedAuthority.toString())).collect(Collectors.toSet()); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return roles.stream().map(role -> new SimpleGrantedAuthority(role.name())).collect(Collectors.toList()); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getActivationCode() { return activationCode; } public void setActivationCode(String activationCode) { this.activationCode = activationCode; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Set<Project> getProjects() { return projects; } public void setProjects(Set<Project> projects) { this.projects = projects; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } }
/** * @description welcome banner: under the navbar */ import React from "react"; // mui components import { Button, Container } from "@mui/material"; // styled components import { WelcomeBannerWrapper, WelcomeBannerTextWrapper, WelcomeBannerTitle, WelcomeBannerMessageMarktSpan, WelcomeBannerText, ShopButton, WelcomeBannerImg, } from "../../../styles/home/welcomeBanner"; // icons import ShoppingCartIcon from "@mui/icons-material/ShoppingCart"; // images import bannerImg from "../../../assets/imgs/banner-fruits.png"; // react router dom import { Link } from "react-router-dom"; const WelcomeBanner = () => { return ( <Container> <WelcomeBannerWrapper direction="row" spacing={2}> {/* welcome banner text wrapper */} <WelcomeBannerTextWrapper> <WelcomeBannerTitle> Welcome to <WelcomeBannerMessageMarktSpan> Egymarket </WelcomeBannerMessageMarktSpan> </WelcomeBannerTitle> <WelcomeBannerText> You can choose from very large collections of different fresh categoriesYou can choose from very large collections of different fresh categoriesYou can choose from very large collections of different fresh categoriesYou can choose from very </WelcomeBannerText> {/* ShopButton */} <Link to="/allproducts" style={{textDecoration:"none"}}> <ShopButton variant="contained" color="secondary" startIcon={<ShoppingCartIcon />} > Shop now </ShopButton> </Link> </WelcomeBannerTextWrapper> {/* welcome immage image */} <WelcomeBannerImg src={bannerImg} /> </WelcomeBannerWrapper> </Container> ); }; export default WelcomeBanner;
import React, { useEffect } from 'react'; function InfoTooltip(props) { const { name, isOpen, onClose, isSuccess, successIcon, failIcon } = props; function closeByOverlayClick(event) { if (event.target.classList.contains('popup')) { onClose(); } } useEffect(() => { const handleCloseByEsc = (event) => { if (event.key === 'Escape') { onClose() } } if (isOpen) { document.addEventListener('keydown', handleCloseByEsc); return () => { document.removeEventListener('keydown', handleCloseByEsc) }; } }, [isOpen]) return ( <div onClick={closeByOverlayClick} className={`popup popup_type_${name} ${isOpen ? 'popup_opened' : ''}`}> <div className="popup__container"> <img src={isSuccess ? successIcon : failIcon} alt="Успешная регистрация" className="infotooltip__icon"/> <p className="infotooltip__message">{isSuccess ? 'Вы успешно зарегистрировались!' : 'Что-то пошло не так! Попробуйте ещё раз.'}</p> <button onClick={onClose} type="button" className="popup__button popup__close-btn"></button> </div> </div> ) } export default InfoTooltip
/* * 74Hx164 - Generic serial-in/parallel-out 8-bits shift register GPIO driver * * Copyright (C) 2010 Gabor Juhos <[email protected]> * Copyright (C) 2010 Miguel Gaio <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/gpio/consumer.h> #include <linux/init.h> #include <linux/mutex.h> #include <linux/spi/spi.h> #include <linux/gpio.h> #include <linux/of_gpio.h> #include <linux/slab.h> #include <linux/module.h> #define GEN_74X164_NUMBER_GPIOS 8 struct gen_74x164_chip { struct gpio_chip gpio_chip; struct mutex lock; struct gpio_desc *gpiod_oe; u32 registers; /* * Since the registers are chained, every byte sent will make * the previous byte shift to the next register in the * chain. Thus, the first byte sent will end up in the last * register at the end of the transfer. So, to have a logical * numbering, store the bytes in reverse order. */ u8 buffer[]; }; static int __gen_74x164_write_config(struct gen_74x164_chip *chip) { return spi_write(to_spi_device(chip->gpio_chip.parent), chip->buffer, chip->registers); } static int gen_74x164_get_value(struct gpio_chip *gc, unsigned offset) { struct gen_74x164_chip *chip = gpiochip_get_data(gc); u8 bank = chip->registers - 1 - offset / 8; u8 pin = offset % 8; int ret; mutex_lock(&chip->lock); ret = (chip->buffer[bank] >> pin) & 0x1; mutex_unlock(&chip->lock); return ret; } static void gen_74x164_set_value(struct gpio_chip *gc, unsigned offset, int val) { struct gen_74x164_chip *chip = gpiochip_get_data(gc); u8 bank = chip->registers - 1 - offset / 8; u8 pin = offset % 8; mutex_lock(&chip->lock); if (val) chip->buffer[bank] |= (1 << pin); else chip->buffer[bank] &= ~(1 << pin); __gen_74x164_write_config(chip); mutex_unlock(&chip->lock); } static void gen_74x164_set_multiple(struct gpio_chip *gc, unsigned long *mask, unsigned long *bits) { struct gen_74x164_chip *chip = gpiochip_get_data(gc); unsigned int i, idx, shift; u8 bank, bankmask; mutex_lock(&chip->lock); for (i = 0, bank = chip->registers - 1; i < chip->registers; i++, bank--) { idx = i / sizeof(*mask); shift = i % sizeof(*mask) * BITS_PER_BYTE; bankmask = mask[idx] >> shift; if (!bankmask) continue; chip->buffer[bank] &= ~bankmask; chip->buffer[bank] |= bankmask & (bits[idx] >> shift); } __gen_74x164_write_config(chip); mutex_unlock(&chip->lock); } static int gen_74x164_direction_output(struct gpio_chip *gc, unsigned offset, int val) { gen_74x164_set_value(gc, offset, val); return 0; } static int gen_74x164_probe(struct spi_device *spi) { struct gen_74x164_chip *chip; u32 nregs; int ret; /* * bits_per_word cannot be configured in platform data */ spi->bits_per_word = 8; ret = spi_setup(spi); if (ret < 0) return ret; if (of_property_read_u32(spi->dev.of_node, "registers-number", &nregs)) { dev_err(&spi->dev, "Missing registers-number property in the DT.\n"); return -EINVAL; } chip = devm_kzalloc(&spi->dev, sizeof(*chip) + nregs, GFP_KERNEL); if (!chip) return -ENOMEM; chip->gpiod_oe = devm_gpiod_get_optional(&spi->dev, "enable", GPIOD_OUT_LOW); if (IS_ERR(chip->gpiod_oe)) return PTR_ERR(chip->gpiod_oe); gpiod_set_value_cansleep(chip->gpiod_oe, 1); spi_set_drvdata(spi, chip); chip->gpio_chip.label = spi->modalias; chip->gpio_chip.direction_output = gen_74x164_direction_output; chip->gpio_chip.get = gen_74x164_get_value; chip->gpio_chip.set = gen_74x164_set_value; chip->gpio_chip.set_multiple = gen_74x164_set_multiple; chip->gpio_chip.base = -1; chip->registers = nregs; chip->gpio_chip.ngpio = GEN_74X164_NUMBER_GPIOS * chip->registers; chip->gpio_chip.can_sleep = true; chip->gpio_chip.parent = &spi->dev; chip->gpio_chip.owner = THIS_MODULE; mutex_init(&chip->lock); ret = __gen_74x164_write_config(chip); if (ret) { dev_err(&spi->dev, "Failed writing: %d\n", ret); goto exit_destroy; } ret = gpiochip_add_data(&chip->gpio_chip, chip); if (!ret) return 0; exit_destroy: mutex_destroy(&chip->lock); return ret; } static int gen_74x164_remove(struct spi_device *spi) { struct gen_74x164_chip *chip = spi_get_drvdata(spi); gpiod_set_value_cansleep(chip->gpiod_oe, 0); gpiochip_remove(&chip->gpio_chip); mutex_destroy(&chip->lock); return 0; } static const struct of_device_id gen_74x164_dt_ids[] = { { .compatible = "fairchild,74hc595" }, { .compatible = "nxp,74lvc594" }, {}, }; MODULE_DEVICE_TABLE(of, gen_74x164_dt_ids); static struct spi_driver gen_74x164_driver = { .driver = { .name = "74x164", .of_match_table = gen_74x164_dt_ids, }, .probe = gen_74x164_probe, .remove = gen_74x164_remove, }; module_spi_driver(gen_74x164_driver); MODULE_AUTHOR("Gabor Juhos <[email protected]>"); MODULE_AUTHOR("Miguel Gaio <[email protected]>"); MODULE_DESCRIPTION("GPIO expander driver for 74X164 8-bits shift register"); MODULE_LICENSE("GPL v2");
<?php namespace app\models; use Yii; /** * This is the model class for table "fase_lap". * * @property int $id * @property string|null $st_descricao * @property int|null $orgao * @property int|null $bl_ativo * * @property Fase[] $fases */ class Faselap extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'fase_lap'; } /** * {@inheritdoc} */ public function rules() { return [ [['orgao', 'bl_ativo'], 'integer'], [['st_descricao'], 'string', 'max' => 200], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'st_descricao' => 'St Descricao', 'orgao' => 'Orgao', 'bl_ativo' => 'Bl Ativo', ]; } /** * Gets query for [[Fases]]. * * @return \yii\db\ActiveQuery */ public function getFases() { return $this->hasMany(Fase::class, ['fase_lap_id' => 'id']); } }
package com.gmail.pentominto.us.supernotes.repositories import com.gmail.pentominto.us.supernotes.data.Category import com.gmail.pentominto.us.supernotes.data.Note import com.gmail.pentominto.us.supernotes.database.NotesDao import javax.inject.Inject import javax.inject.Singleton import kotlinx.coroutines.flow.Flow @Singleton class LocalRepositoryImpl @Inject constructor( private val dao: NotesDao ) : LocalRepository { override suspend fun insertNote(note: Note): Long { return dao.insertNote(note) } override suspend fun insertTrashNote(trashNote: Note): Long { return dao.insertNote(trashNote) } override suspend fun updateNote( noteTitle: String, noteBody: String, noteId: Int ) { dao.updateNote( noteTitle, noteBody, noteId ) } override suspend fun updateNoteCategory(chosenCategory: String, noteId: Int) { dao.updateNoteCategory( chosenCategory, noteId ) } override suspend fun insertCategory(category: Category) { dao.insertCategory(category) } override suspend fun deleteNote(id: Int) { dao.deleteNote(id) } override suspend fun deleteTrashNote(id: Int) { dao.deleteNote(id) } override suspend fun deleteCategory(id: Int) { dao.deleteCategory(id) } override fun getNotesOfThisCategory(category: String): Flow<List<Note>> { return dao.getNotesOfThisCategory(category) } override fun getAllCategoriesAndNotes(): Flow<Map<Category, List<Note>>> { return dao.getAllCategoriesAndNotes() } override fun getNoteWithCategory(id: Int): Flow<Map<Category, Note>> { return dao.getNoteWithCategory(id) } override fun getNote(id: Int): Flow<Note> { return dao.getNote(id) } override fun getAllCategories(): Flow<List<Category>> { return dao.getAllCategories() } override suspend fun deleteAllNotes() { dao.deleteAllNotes() } override suspend fun deleteAllTrashNotes() { dao.deleteAllTrashNotes() } override suspend fun defaultCategoryExists(): Boolean { return dao.defaultCategoryExists() } }
<div class="solution" acro="PEE.T50"> <h5 class="solution"> <span class="type">Solution</span> <span class="acro">PEE.T50</span> <span class="contributor"><a knowl="./knowls/contributor.robertbeezer.knowl">Robert Beezer</a></span> </h5>Since $\lambda$ is an eigenvalue of a nonsingular matrix, $\lambda\neq 0$ (<a class="knowl" acro="SMZE" type="Theorem" title="Singular Matrices have Zero Eigenvalues" knowl="./knowls/theorem.SMZE.knowl">Theorem SMZE</a>). $A$ is invertible (<a class="knowl" acro="NI" type="Theorem" title="Nonsingularity is Invertibility" knowl="./knowls/theorem.NI.knowl">Theorem NI</a>), and so $-\lambda A$ is invertible (<a class="knowl" acro="MISM" type="Theorem" title="Matrix Inverse of a Scalar Multiple" knowl="./knowls/theorem.MISM.knowl">Theorem MISM</a>). Thus $-\lambda A$ is nonsingular (<a class="knowl" acro="NI" type="Theorem" title="Nonsingularity is Invertibility" knowl="./knowls/theorem.NI.knowl">Theorem NI</a>) and $\detname{-\lambda A}\neq 0$ (<a class="knowl" acro="SMZD" type="Theorem" title="Singular Matrices have Zero Determinants" knowl="./knowls/theorem.SMZD.knowl">Theorem SMZD</a>). \begin{align*} \charpoly{\inverse{A}}{\frac{1}{\lambda}} &amp;=\detname{\inverse{A}-\frac{1}{\lambda}I_n} &amp;&amp;\knowl{./knowls/definition.CP.knowl}{\text{Definition CP}}\\ &amp;=1\detname{\inverse{A}-\frac{1}{\lambda}I_n} &amp;&amp;\knowl{./knowls/property.OCN.knowl}{\text{Property OCN}}\\ &amp;=\frac{1}{\detname{-\lambda A}} \detname{-\lambda A}\detname{\inverse{A}-\frac{1}{\lambda}I_n} &amp;&amp;\knowl{./knowls/property.MICN.knowl}{\text{Property MICN}}\\ &amp;=\frac{1}{\detname{-\lambda A}} \detname{\left(-\lambda A\right)\left(\inverse{A}-\frac{1}{\lambda}I_n\right)} &amp;&amp;\knowl{./knowls/theorem.DRMM.knowl}{\text{Theorem DRMM}}\\ &amp;=\frac{1}{\detname{-\lambda A}} \detname{-\lambda A\inverse{A}-\left(-\lambda A\right)\frac{1}{\lambda}I_n} &amp;&amp;\knowl{./knowls/theorem.MMDAA.knowl}{\text{Theorem MMDAA}}\\ &amp;=\frac{1}{\detname{-\lambda A}} \detname{-\lambda I_n-\left(-\lambda A\right)\frac{1}{\lambda}I_n} &amp;&amp;\knowl{./knowls/definition.MI.knowl}{\text{Definition MI}}\\ &amp;=\frac{1}{\detname{-\lambda A}} \detname{-\lambda I_n+\lambda\frac{1}{\lambda}AI_n} &amp;&amp;\knowl{./knowls/theorem.MMSMM.knowl}{\text{Theorem MMSMM}}\\ &amp;=\frac{1}{\detname{-\lambda A}} \detname{-\lambda I_n+1AI_n} &amp;&amp;\knowl{./knowls/property.MICN.knowl}{\text{Property MICN}}\\ &amp;=\frac{1}{\detname{-\lambda A}} \detname{-\lambda I_n+AI_n} &amp;&amp;\knowl{./knowls/property.OCN.knowl}{\text{Property OCN}}\\ &amp;=\frac{1}{\detname{-\lambda A}} \detname{-\lambda I_n+A} &amp;&amp;\knowl{./knowls/theorem.MMIM.knowl}{\text{Theorem MMIM}}\\ &amp;=\frac{1}{\detname{-\lambda A}} \detname{A-\lambda I_n} &amp;&amp;\knowl{./knowls/property.ACM.knowl}{\text{Property ACM}}\\ &amp;=\frac{1}{\detname{-\lambda A}} \charpoly{A}{\lambda}&amp;&amp;\knowl{./knowls/definition.CP.knowl}{\text{Definition CP}}\\ &amp;=\frac{1}{\detname{-\lambda A}}\,0&amp;&amp;\knowl{./knowls/theorem.EMRCP.knowl}{\text{Theorem EMRCP}}\\ &amp;=0&amp;&amp;\knowl{./knowls/property.ZCN.knowl}{\text{Property ZCN}} \end{align*} So $\frac{1}{\lambda}$ is a root of the characteristic polynomial of $\inverse{A}$ and so is an eigenvalue of $\inverse{A}$. This proof is due to <a knowl="./knowls/contributor.sarabucht.knowl">Sara Bucht</a>. </div>
import unittest from BankAccount import BankAccount class TestBankAccount(unittest.TestCase): def setUp(self): self.account = BankAccount(123) def test_initial_balance(self): self.assertEquals(self.account.balance, 0, msg="Initial balance should be 0") def test_deposit(self): self.account.deposit(100) self.assertEquals(self.account.balance, 100, msg="Deposit amount should increase the balance") def test_withdraw_sufficient_balance(self): self.account.deposit(100) result = self.account.withdraw(50) self.assertTrue(result, msg="Withdrawal should return True for sufficient balance") self.assertEquals(self.account.balance, 50, msg="Withdrawal amount should decrease the balance") def test_withdraw_insufficient_balance(self): self.account.deposit(100) result = self.account.withdraw(150) self.assertFalse(result, msg="Withdrawal should return False for insufficient balance") self.assertEquals(self.account.balance, 100, msg="Withdrawal amount shouldn't change for insufficient withdraw") if __name__ == '__main__': unittest.main()
import { useState } from "react"; import PropTypes from "prop-types"; import { Menu } from "@material-ui/core"; import MoreVertIcon from "@material-ui/icons/MoreVert"; import ActionButton, { ACTION_BUTTON_TYPES } from "../action-button"; import { MenuItems } from "./components"; const Component = ({ actions, disabledCondition, showMenu }) => { const [anchorEl, setAnchorEl] = useState(null); const handleClick = event => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; return ( <> {showMenu && ( <ActionButton id="more-actions" icon={<MoreVertIcon />} type={ACTION_BUTTON_TYPES.icon} rest={{ "aria-label": "more", "aria-controls": "long-menu", "aria-haspopup": "true", onClick: handleClick }} /> )} <Menu id="long-menu" variant="menu" anchorEl={anchorEl} keepMounted open={Boolean(anchorEl)} onClose={handleClose} getContentAnchorEl={null} > <MenuItems actions={actions} disabledCondition={disabledCondition} handleClose={handleClose} /> </Menu> </> ); }; Component.defaultProps = { actions: [], disabledCondition: () => {}, showMenu: false }; Component.displayName = "Menu"; Component.propTypes = { actions: PropTypes.array, disabledCondition: PropTypes.func, showMenu: PropTypes.bool }; export default Component;
package com.tutorailsninja.demo.pages; import com.tutorailsninja.demo.utility.Utility; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.FindBys; import java.util.List; public class HomePage extends Utility { private static final Logger log = LogManager.getLogger(HomePage.class.getName()); @CacheLookup @FindBys(@FindBy(xpath = "//nav[@id='menu']//ul/li[contains(@class, 'open')]/div/child::*")) List<WebElement> selectMenu; //By selectMenu = By.xpath("//nav[@id='menu']//ul/li[contains(@class, 'open')]/div/child::*"); @CacheLookup @FindBy(xpath = "//a[text()='Desktops']") WebElement desktopTab; // By desktopTab = By.xpath("//a[text()='Desktops']"); @CacheLookup @FindBy(xpath = "//h2[text()='Desktops']") WebElement desktopsText; // By desktopsText = By.xpath("//h2[text()='Desktops']"); @CacheLookup @FindBy(linkText = "Laptops & Notebooks") WebElement laptopsAndNotebooksTab; //By laptopsAndNotebooksTab = By.linkText("Laptops & Notebooks"); @CacheLookup @FindBy(xpath = "//h2[contains(text(),'Laptops & Notebooks')]") WebElement laptopsAndNotBooksText; // By laptopsAndNotBooksText = By.xpath("//h2[contains(text(),'Laptops & Notebooks')]"); @CacheLookup @FindBy(linkText = "Components") WebElement componentsTab; // By componentsTab = By.linkText("Components"); @CacheLookup @FindBy(xpath = "//h2[contains(text(),'Components')]") WebElement componentsText; //By componentsText = By.xpath("//h2[contains(text(),'Components')]"); public void selectMenu(String menu) { // List<WebElement> topMenuList = driver.findElements(selectMenu); log.info("Select My Menu Option " + selectMenu.toString() ); try { for (WebElement element :selectMenu) { if (element.getText().equalsIgnoreCase(menu)) { element.click(); } } } catch (StaleElementReferenceException e) { selectMenu.toString(); } } public void hoverAndClickOnDesktop() { log.info("Mouse Hover and click on Desktop "+ desktopTab.toString()); mouseHoverToElementAndClick(desktopTab); } public String getDesktopsText() { log.info("Get the Desktop Tab "+ desktopsText.toString()); return getTextFromElement(desktopsText); } public void hoverAndClickOnLaptopsAndNotebooksTab() { log.info("Mouse Hover and click on "+ laptopsAndNotebooksTab.toString()); mouseHoverToElementAndClick(laptopsAndNotebooksTab); } public String getLaptopsAndNotBooksText() { log.info("Get the Laptop and NotBooks Text "+ laptopsAndNotBooksText.toString()); return getTextFromElement(laptopsAndNotBooksText); } public void hoverAndClickOnComponents() { log.info("Mouse Hover and click on "+ componentsTab.toString()); mouseHoverToElementAndClick(componentsTab); } public String getComponentsText() { log.info("Get the Components Menu Text "+ componentsText.toString()); return getTextFromElement(componentsText); } }
<div class="row"> <div class="col-md-6"> <form #f="ngForm" (ngSubmit)="save(f.value)"> <div class="form-group"> <label for="title">Название</label> <input #title="ngModel" [(ngModel)]="meditation.title" name="title" id="title" type="text" class="form-control" required /> <div class="alert alert-danger" *ngIf="title.touched && title.invalid">Введите, пожалуйста, название</div> </div> <div class="form-group"> <label for="videoUrl">Ссылка на видео</label> <input #videoUrl="ngModel" [(ngModel)]="meditation.videoUrl" name="videoUrl" id="videoUrl" type="URL" class="form-control" required /> <div class="alert alert-danger" *ngIf="videoUrl.touched && videoUrl.invalid">Нужна ссылка на видео</div> </div> <app-upload-files [urls]="urls" [type]="'meditation'" (upload)="onUploadFile($event)" (uploadIsValid)="uploadValidTrigger($event)" > </app-upload-files> <div class="form-group"> <label for="description">Описание</label> <textarea #description="ngModel" [(ngModel)]="meditation.description" name="description" id="description" type="text" class="form-control" required ></textarea> <div class="alert alert-danger" *ngIf="description.touched && description.invalid"> Введите, пожалуйста, описание </div> </div> <div class="container"> <div class="row"> <div class="col align-self-start"> <button [disabled]="!uploadIsValid" class="btn btn-outline-success">Сохранить</button> </div> <div class="col align-self-end"> <button type="button" (click)="delete()" class="btn btn-outline-warning">Удалить</button> </div> </div> </div> </form> </div> </div>
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Kukoo.Models { /// <summary> /// Request to update model settings. One of \&quot;name\&quot; or \&quot;defaultTypeId\&quot; must be set. /// </summary> [DataContract] public partial class UpdateModelSettingsRequest : IEquatable<UpdateModelSettingsRequest> { /// <summary> /// Model display name which is shown in the UX and mutable by the user. Initial value is \&quot;DefaultModel\&quot;. /// </summary> /// <value>Model display name which is shown in the UX and mutable by the user. Initial value is \&quot;DefaultModel\&quot;.</value> [DataMember(Name="name")] public string Name { get; set; } /// <summary> /// Default type id of the model that new instances will automatically belong to. /// </summary> /// <value>Default type id of the model that new instances will automatically belong to.</value> [DataMember(Name="defaultTypeId")] public string DefaultTypeId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class UpdateModelSettingsRequest {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" DefaultTypeId: ").Append(DefaultTypeId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((UpdateModelSettingsRequest)obj); } /// <summary> /// Returns true if UpdateModelSettingsRequest instances are equal /// </summary> /// <param name="other">Instance of UpdateModelSettingsRequest to be compared</param> /// <returns>Boolean</returns> public bool Equals(UpdateModelSettingsRequest other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return ( Name == other.Name || Name != null && Name.Equals(other.Name) ) && ( DefaultTypeId == other.DefaultTypeId || DefaultTypeId != null && DefaultTypeId.Equals(other.DefaultTypeId) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Name != null) hashCode = hashCode * 59 + Name.GetHashCode(); if (DefaultTypeId != null) hashCode = hashCode * 59 + DefaultTypeId.GetHashCode(); return hashCode; } } #region Operators #pragma warning disable 1591 public static bool operator ==(UpdateModelSettingsRequest left, UpdateModelSettingsRequest right) { return Equals(left, right); } public static bool operator !=(UpdateModelSettingsRequest left, UpdateModelSettingsRequest right) { return !Equals(left, right); } #pragma warning restore 1591 #endregion Operators } }
/** * IPクラスを取得します * @param {string} ip - IPアドレス * @returns {string} IPクラス(A, B, C, D, Eまたは空文字列) */ export const getIpClass = (ip: string): string => { if (!ip) { return ""; } // IPアドレスの最初のオクテットを取得 const firstOctet = parseInt(ip.split(".")[0]); if (firstOctet < 128) { return "A"; } if (firstOctet < 192) { return "B"; } if (firstOctet < 224) { return "C"; } if (firstOctet < 240) { return "D"; } if (firstOctet < 256) { return "E"; } return ""; };
"use client"; import React, { useRef, useState } from 'react' import Icon, { DeleteOutlined, EditOutlined, ReloadOutlined, SearchOutlined, EyeOutlined, } from "@ant-design/icons"; import dayjs from "dayjs"; import Link from 'next/link'; import { Button, Input, message, Space } from 'antd'; import { useDebounced } from '@/redux/hooks'; import { useDeleteEventMutation, useGetAllEventQuery } from '@/redux/api/eventApi'; import { IEvent } from '@/types'; import { ActionType, ProTable, ProColumns, RequestData, TableDropdown, ProDescriptions, } from '@ant-design/pro-components'; import { CiCircleMore } from 'react-icons/ci'; import { FiUsers } from 'react-icons/fi'; import BreadCrumb from '@/components/shared/BreadCrumb'; import ActionBar from '@/components/shared/ActionBar'; import UMTable from '@/components/shared/UMTable'; enum ActionKey { DELETE = 'delete', UPDATE = 'update', READ = 'read' } function ManageEvent() { const query: Record<string, any> = {}; const actionRef = useRef<ActionType>(); const [page, setPage] = useState<number>(1); const [size, setSize] = useState<number>(10); const [sortBy, setSortBy] = useState<string>(""); const [sortOrder, setSortOrder] = useState<string>(""); const [searchTerm, setSearchTerm] = useState<string>(""); const [deleteEvent] = useDeleteEventMutation(); query["limit"] = size; query["page"] = page; query["sortBy"] = sortBy; query["sortOrder"] = sortOrder; const debouncedSearchTerm = useDebounced({ searchQuery: searchTerm, delay: 600, }); if (!!debouncedSearchTerm) { query["searchTerm"] = debouncedSearchTerm; } const {data, isLoading} = useGetAllEventQuery({...query}); // @ts-ignore const events = data?.event?.data; // @ts-ignore const meta = data?.event?.meta; const handleDelete = async (id: string) => { message.loading("Deleting....."); try { await deleteEvent(id); message.success("Event Deleted successfully"); } catch (err: any) { message.error(err.message); } }; const columns: ProColumns[] = [ { title: "Title", render: function (data: any) { return <>{data.title}</>; }, }, { title: "Category Name", render: function (data: any) { return <>{data?.Category?.name}</>; }, }, { title: "price", dataIndex: "price", }, { title: "Is Booked", render: function (data: any) { return ( <> {data.isBooked ? ( <p>Booked</p> ) : ( <p>Available</p> )} </> ); }, }, { title: "People", dataIndex: "people", }, { title: "Created at", dataIndex: "createdAt", render: function (data: any) { return data && dayjs(data).format("MMM D, YYYY hh:mm A"); }, sorter: true, }, { title: "Action", align: 'center', key: 'option', fixed: 'right', render: (data: any) => [ <TableDropdown key="actionGroup" menus={[ { key: ActionKey.DELETE, name: ( <Space> <Button onClick={() => handleDelete(data?.id)} > <DeleteOutlined /> Delete </Button> </Space> ) }, { key: ActionKey.UPDATE, name: ( <Space> <Link href={`/admin/manage-category/update/${data.id}`}> <EditOutlined /> Update </Link> </Space> ) } ]} > <Icon component={CiCircleMore} className="text-primary text-xl" /> </TableDropdown> ], }, ]; const onPaginationChange = (page: number, pageSize: number) => { setPage(page); setSize(pageSize); }; const onTableChange = (pagination: any, filter: any, sorter: any) => { const { order, field } = sorter; setSortBy(field as string); setSortOrder(order === "ascend" ? "asc" : "desc"); }; const resetFilters = () => { setSortBy(""); setSortOrder(""); setSearchTerm(""); }; return ( <div style={{ border: "1px solid #d9d9d9", borderRadius: "5px", padding: "15px", marginBottom: "10px", marginTop: "10px", }} > <BreadCrumb items={[ { label: "admin", link: "/admin", }, ]} /> <ActionBar> <Input addonBefore={<SearchOutlined style={{ fontSize: '18px', color: "#FFA33C" }} />} placeholder="Search ......" onChange={(e) => { setSearchTerm(e.target.value); }} /> {(!!sortBy || !!sortOrder || !!searchTerm) && ( <button onClick={resetFilters} className="bg-orange-600 px-4 py-2 ml-2 text-white rounded font-semibold float-right" > <ReloadOutlined /> </button> )} <Link href="/admin/manage-event/create"> <Button type="primary" style={{ backgroundColor: "#54B435", margin: "0px 10px" }}>Create</Button> </Link> </ActionBar> <ProTable columns={columns} cardBordered={false} cardProps={{ subTitle: 'Event List', tooltip: { className: 'opacity-60', title: 'Mocked data', }, title: <FiUsers className="opacity-60" />, }} bordered={true} showSorterTooltip={false} scroll={{ x: true }} tableLayout={'fixed'} rowSelection={false} pagination={{ showQuickJumper: true, pageSize: 10, }} actionRef={actionRef} dataSource={events} dateFormatter="string" search={false} rowKey="id" options={{ search: false, }} /> </div> ) } export default ManageEvent
import Button from '@mui/material/Button'; import Dialog from '@mui/material/Dialog'; import DialogActions from '@mui/material/DialogActions'; import DialogContent from '@mui/material/DialogContent'; import DialogContentText from '@mui/material/DialogContentText'; import DialogTitle from '@mui/material/DialogTitle'; import Slide from '@mui/material/Slide'; import { TransitionProps } from '@mui/material/transitions'; import { Breakpoint, styled } from '@mui/material/styles'; import Image from 'next/image'; import React, { useEffect, useState } from 'react'; interface IAlertDialogSlide { isOpen: boolean; size?: false | Breakpoint; actionChild?: React.ReactNode; contentChild?: React.ReactNode; transitionProps?: TransitionProps; cancelButton?: React.ReactNode; okButton?: React.ReactNode; onChange: (isOpen: boolean) => void; onCancel: (event) => void; onConfirm: (event) => void; } const Transition = React.forwardRef(function Transition( props: TransitionProps & { children: React.ReactElement<any, any>; }, ref: React.Ref<unknown> ) { return <Slide direction="down" ref={ref} {...props} />; }); const AlertDialogSlide: React.FC<IAlertDialogSlide> = (props: IAlertDialogSlide) => { const { isOpen, actionChild, contentChild, onChange, onConfirm, onCancel, size, transitionProps, } = props; const [open, setOpen] = useState(isOpen ?? false); const handleClose = (event) => { setOpen(false); onChange(false); if (onCancel) { onCancel(event); } }; useEffect(() => { setOpen(isOpen); }, [isOpen]); return ( <div> <Dialog open={open} TransitionComponent={Transition} keepMounted disableScrollLock onClose={handleClose} classes={{ paper: 'tw-rounded-[20px] tw-overflow-visible', root: 'font-family: Lexend Deca', }} {...transitionProps} maxWidth={size} > <DialogTitle>{contentChild}</DialogTitle> <DialogActions>{actionChild}</DialogActions> <div className="tw-absolute -tw-right-[15px] -tw-top-[15px] tw-w-[48px] tw-h-[48px] tw-bg-transparent tw-rounded-full"> <Button onClick={handleClose} className="!tw-min-w-[1px] tw-h-full tw-w-full tw-p-0 tw-m-0 tw-bg-transparent tw-rounded-full" > <Image src="/images/icons/close-modal.svg" layout="fill" /> </Button> </div> </Dialog> </div> ); }; export default AlertDialogSlide;
"use client"; import Link from "next/link"; import React from "react"; import { usePathname } from "next/navigation"; import { MdOutlineTextFields } from "react-icons/md"; import { MdEmail } from "react-icons/md"; import { MdOutlineEmail } from "react-icons/md"; import { RiSpeakFill } from "react-icons/ri"; import { IoChatboxEllipses } from "react-icons/io5"; import { FaBookOpen, FaSearch } from "react-icons/fa"; import { FaCircleInfo } from "react-icons/fa6"; import { IoSettings } from "react-icons/io5"; import { FaRegUser } from "react-icons/fa"; export default function SideNavbar() { const path = usePathname(); const links = [ [ { href: "/grammar", text: "Grammar", icon: <FaBookOpen /> }, { href: "/grammar/paragraph", text: "Paragraph", icon: <MdOutlineTextFields />, }, { href: "/grammar/letter", text: "Letter", icon: <MdEmail /> }, { href: "/grammar/email", text: "Email", icon: <MdOutlineEmail /> }, { href: "/grammar/dialogue", text: "Dialogue", icon: <RiSpeakFill /> }, { href: "/conversation", text: "Conversation", icon: <IoChatboxEllipses />, }, ], [ { href: "/about", text: "About", icon: <FaCircleInfo /> }, { href: "/settings", text: "Settings", icon: <IoSettings /> }, { href: "/search", text: "Search", icon: <FaSearch /> }, { href: "/profile", text: "Profile", icon: <FaRegUser /> }, ], ]; const currentPath = path.split("/")[path.split("/").length - 1]; return ( <nav className="side-navbar"> <Link href="/" className="logo"> English AI </Link> <hr /> <div className="links"> {links.map((section, i) => ( <div key={i}> <div className="link-section"> {section.map((link, i) => ( <Link key={i} href={link.href} className={`${ currentPath === link.href.split("/")[link.href.split("/").length - 1] && "active" }`} > {link.icon} {link.text} </Link> ))} </div> {i === 0 && <hr />} </div> ))} </div> </nav> ); }
import React, { FC, RefObject } from 'react' import { Table, Button, Switch, FormikInput, ImageSelectorModal, Pagination, BasicModal as CreateCategoryModal, } from '@pabau/ui' import { ServiceCategoriesDocument, ServiceCategoriesAggregateDocument, } from '@pabau/graphql' import { Formik } from 'formik' import * as Yup from 'yup' import classNames from 'classnames' import { useTranslationI18 } from '../../../hooks/useTranslationI18' import { PlusOutlined, PictureOutlined, CloseCircleFilled, } from '@ant-design/icons' import { appointmentColors } from '../../../mocks/Services' import styles from './CategoriesTab.module.less' interface EditCategory { id: string name: string assigned: string color: string image: string order: number is_active: boolean } interface PaginateDataType { total: number offset: number limit: number currentPage: number showingRecords: number } export interface ColumnType { title: string dataIndex: string visible: boolean className?: string render?: (val, row) => JSX.Element } interface QueryVariablesType { variables: QueryVariablesProps } interface QueryVariablesProps { offset?: number limit?: number searchTerm?: string } interface CategoriesProps { editData: EditCategory handleSubmitCategory: (val, { resetForm }) => void categoryTableRef: RefObject<HTMLDivElement> isLoading: boolean sourceData: EditCategory[] columns: ColumnType[] searchTerm: string openModal: () => void setEditData: (e) => void updateOrder: (e) => void setSourceData: (e) => void paginateData: PaginateDataType onPaginationChange: (cp, limit) => void setPaginateData: (e) => void modalShowState: boolean closeModal: () => void showImageSelector: boolean setShowImageSelector: (e) => void openDeleteModal: boolean setDeleteModal: (e) => void deleteMutation: (e) => void listQueryVariables: () => QueryVariablesType listAggregateQueryVariables: () => QueryVariablesType } const Categories: FC<CategoriesProps> = ({ editData, handleSubmitCategory, categoryTableRef, isLoading, sourceData, columns, searchTerm, openModal, setEditData, updateOrder, setSourceData, paginateData, onPaginationChange, setPaginateData, modalShowState, closeModal, showImageSelector, setShowImageSelector, openDeleteModal, setDeleteModal, deleteMutation, listQueryVariables, listAggregateQueryVariables, }) => { const { t } = useTranslationI18() const categoriesSchema = Yup.object({ name: Yup.string().required( t('setup.services.categoriestab.createservicecategory.requiredmessage') ), }) return ( <Formik enableReinitialize={true} initialValues={ editData?.id ? editData : { name: undefined, color: undefined, is_active: true, image: undefined, } } validationSchema={categoriesSchema} onSubmit={(values, { resetForm }) => { handleSubmitCategory(values, { resetForm }) }} > {({ setFieldValue, handleSubmit, handleReset, values, errors }) => ( <div ref={categoryTableRef} className={styles.categoriesTabMain}> <Table loading={isLoading} draggable={true} dataSource={sourceData?.map((e: { id }) => ({ key: e.id, ...e, }))} scroll={{ x: 'max-content' }} columns={columns} pagination={false} searchTerm={searchTerm} noDataBtnText={t( 'setup.services.categoriestab.table.nodatabtntext' )} noDataText={t('setup.services.categoriestab.table.nodatatext')} onAddTemplate={openModal} onRowClick={(e) => { openModal() setEditData(e) }} updateDataSource={({ newData, oldIndex, newIndex }) => { setSourceData( (newData = newData.map((data: { order: number }, i: number) => { data.order = sourceData[i]?.order === sourceData[i + 1]?.order ? sourceData[i]?.order + 1 : !sourceData[i].order ? 1 : sourceData[i].order return data })) ) if (oldIndex > newIndex) { for (let i = newIndex; i <= oldIndex; i++) { updateOrder(newData[i]) } } else { for (let i = oldIndex; i <= newIndex; i++) { updateOrder(newData[i]) } } }} /> <div className={styles.paginationFooter}> <Pagination total={paginateData.total} defaultPageSize={50} showSizeChanger={false} onChange={onPaginationChange} pageSizeOptions={['10', '25', '50', '100']} onPageSizeChange={(pageSize) => { setPaginateData({ ...paginateData, limit: pageSize, offset: 0, currentPage: 1, }) }} pageSize={paginateData.limit} current={paginateData.currentPage} showingRecords={paginateData.showingRecords} className={styles.categoryPagination} /> </div> <CreateCategoryModal visible={modalShowState} modalWidth={500} wrapClassName="addCategoryModal" title={ editData?.id ? t('setup.services.categoriestab.editservicecategorymodal') : t('setup.services.categoriestab.createservicecategorymodal') } onCancel={() => { handleReset() setEditData(null) closeModal?.() }} > <div className="nameInput"> <label> {t( 'setup.services.categoriestab.createservicecategorymodal.name' )} </label> <FormikInput name="name" placeholder={t( 'setup.services.categoriestab.createservicecategorymodal.name.placeholder' )} value={values?.name} onChange={(val) => setFieldValue('name', val.target.value)} /> {errors.name && ( <span className={styles.errorText}>{errors.name}</span> )} </div> <div className={styles.appointmentColor}> <p className={styles.appointmentColorTitle}> {t( 'setup.services.categoriestab.createservicecategorymodal.defaultappointmentcolour' )} </p> <div className={styles.appointmentColorItems}> {appointmentColors.map((color) => ( <div key={color} className={ color === values?.color ? classNames( styles.appointmentColorItem, styles.appointmentColorSelected ) : styles.appointmentColorItem } onClick={() => setFieldValue('color', color)} > <div style={{ backgroundColor: color, }} /> </div> ))} </div> </div> <div className="chooseImageInput"> <label> {t('setup.services.servicestab.createmodal.general.image')} </label> <div className={styles.createCategoryImageContainer} style={{ backgroundImage: `url(${values.image})` }} > {values.image && ( <span className={styles.categoryCloseIcon} onClick={() => setFieldValue('image', null)} > <CloseCircleFilled /> </span> )} {!values.image && ( <PictureOutlined style={{ color: 'var(--light-grey-color)', fontSize: '32px', }} /> )} </div> <Button type="default" size="small" className={styles.chooseImgBtn} onClick={() => setShowImageSelector(true)} > <PlusOutlined /> {t( 'setup.services.categoriestab.createservicecategorymodal.choosefromlibrary' )} </Button> <ImageSelectorModal visible={showImageSelector} onOk={(image) => { setFieldValue('image', image.source) setShowImageSelector(false) }} onCancel={() => { setShowImageSelector(false) }} /> </div> <div className="footerBtnInput"> <div> <label>{t('marketingsource-status-label')}</label> <Switch size="small" checked={values?.is_active} onChange={(check) => setFieldValue('is_active', check)} /> </div> <div> <Button type="default" size="large" onClick={() => closeModal?.()} > {t('common-label-cancel')} </Button> </div> <div> {editData?.id && !values?.is_active && ( <Button size="large" onClick={() => { closeModal?.() setDeleteModal((val) => !val) }} > {t('common-label-delete')} </Button> )} <Button type="primary" size="large" onClick={() => handleSubmit()} > {!editData?.id ? t('common-label-create') : t('common-label-save')} </Button> </div> </div> </CreateCategoryModal> <CreateCategoryModal modalWidth={682} centered={true} onCancel={() => { setDeleteModal(false) }} onOk={async () => { const { id } = editData await deleteMutation({ variables: { id }, optimisticResponse: {}, refetchQueries: [ { query: ServiceCategoriesDocument, ...listQueryVariables(), }, { query: ServiceCategoriesAggregateDocument, ...listAggregateQueryVariables(), }, ], }) setDeleteModal(false) }} visible={openDeleteModal} title={t('setup.services.categoriestab.deletemodal.title')} newButtonText={t('setup.services.categoriestab.deletemodal.button')} isValidate={true} > <span className={styles.categoriesName}> {editData?.name} {t('common-label-delete-warning')} </span> </CreateCategoryModal> </div> )} </Formik> ) } export default Categories
package ar.edu.unq.obj1.c2.alimentos; import java.util.Collection; import java.util.HashSet; import java.util.stream.Collector; import java.util.stream.Collectors; import ar.edu.unq.obj1.c2.Alimento; public class Combo implements Alimento { Collection<Alimento> comidas = new HashSet<Alimento>(); public void agregar(Alimento alimento) { comidas.add(alimento); } @Override public int energiaQueAporta() { //opcion a mano: // int acumulador = 0; // for (Alimento alimento : comidas) { // acumulador += alimento.energiaQueAporta(); // } // return acumulador; // opcion map + reduce (parecido a map + sum de wollok) // return comidas.stream().mapToInt( (alimento) -> alimento.energiaQueAporta() ).reduce(0, (a,b)->a+b ); //Esta es la opción más parecida a collecion.sum(bloque) de wollok return comidas.stream().collect(Collectors.summingInt((alimento)->alimento.energiaQueAporta())); } public Collection<Alimento> aportanMasDe(int cantidad) { return comidas.stream().filter((alimento) -> alimento.energiaQueAporta() > cantidad).collect(Collectors.toSet()); } public boolean hayAlgunoQueAportaMas(int cantidad) { return comidas.stream().anyMatch((alimento)->alimento.energiaQueAporta() > cantidad); } public boolean todosAportanMas(int cantidad) { return comidas.stream().allMatch((alimento)->alimento.energiaQueAporta() > cantidad); } }
import axios from "axios"; import React, { useEffect, useRef, useState } from "react"; import styled from "styled-components"; import { toast } from "react-toastify"; import {ToastContainer} from 'react-toastify' import 'react-toastify/dist/ReactToastify.css'; import img from "../../assets/images/loginImage.jpg" import {Link} from 'react-router-dom'; import {useNavigate} from "react-router-dom" import useAuth from "../../hooks/useAuth"; const FormContainer = styled.form` display: flex; align-items: center; flex-direction: column; gap: 10px; flex-wrap: wrap; background-color:#fff; padding: 20px; box-shadow: 0px 0px 5px #ccc; border-radius: 5px; `; const InputArea = styled.div` display: flex; flex-direction: column; `; const Input = styled.input` width: 120px; padding: 0 10px; border: 1px solid #bbb; border-radius: 5px; height: 40px; `; const Label = styled.label``; const Button = styled.button` padding: 10px; cursor: pointer; border-radius: 5px; border: none; background-color: #2c73d2; color: white; height: 42px; `; const Signup = ({ getUsers, onEdit, setOnEdit }) => { const ref = useRef(); const navigate = useNavigate(); const {signin} = useAuth(); const [loggedInUserEmail, setLoggedInUserEmail] = useState(""); useEffect(() => { if (onEdit) { const user = ref.current; user.nome.value = onEdit.nome; user.email.value = onEdit.email; user.fone.value = onEdit.fone; user.data_nascimento.value = onEdit.data_nascimento; user.CPF.value = onEdit.CPF; user.Senha.value = onEdit.Senha; } }, [onEdit]); const handleSubmit = async (e) => { e.preventDefault(); const user = ref.current; if ( !user.nome.value || !user.email.value || !user.fone.value || !user.data_nascimento.value || !user.CPF.value|| !user.Senha.value ) { return toast.warn("Preencha todos os campos!"); } else { try { const response = await axios.post("http://localhost:8800", { nome: user.nome.value, email: user.email.value, fone: user.fone.value, data_nascimento: user.data_nascimento.value, CPF: user.CPF.value, Senha: user.Senha.value }); if (response.status === 200) { toast.success(response.data); // Limpe os campos após um cadastro bem-sucedido user.nome.value = ""; user.email.value = ""; user.fone.value = ""; user.data_nascimento.value = ""; user.CPF.value = ""; user.Senha.value = ""; const tempoDeEspera = 4000; // 4 segundos const mensagem = window.alert("Voce será redirecionado a tela de Login"); setTimeout(() => { navigate("/login"); }, tempoDeEspera); } else { toast.error(response.data); } } catch (error) { console.error(error); // Imprima o erro no console para depuração toast.error("Algum dado inserido já foi cadastrado."); } } //else primário, que não mostra o erro corretamente /* else{ await axios .post("http://localhost:8800", { nome: user.nome.value, email: user.email.value, fone: user.fone.value, data_nascimento: user.data_nascimento.value, CPF: user.CPF.value, Senha: user.Senha.value }) .then(({ data }) => { toast.success(data) } ) .catch(({ err }) => toast.error(err)); } user.nome.value = ""; user.email.value = ""; user.fone.value = ""; user.data_nascimento.value = ""; user.CPF.value = ""; user.Senha.value = ""; */ }; return ( <div> <FormContainer ref={ref} onSubmit={handleSubmit}> <InputArea> <Label>Nome</Label> <Input name="nome" /> </InputArea> <InputArea> <Label>E-mail</Label> <Input name="email" type="email" /> </InputArea> <InputArea> <Label>CPF</Label> <Input name="fone" /> </InputArea> <InputArea> <Label>Data de Nascimento</Label> <Input name="data_nascimento" type="date" /> </InputArea> <InputArea> <Label>Fone</Label> <Input name="CPF" type="text" /> </InputArea> <InputArea> <Label>Senha</Label> <Input name="Senha" type="password" /> </InputArea> <Button type="submit">Registrar-se</Button> <h3> Já possue uma conta ? <Link to={"/login"}> Entre </Link> </h3> <ToastContainer autoClose={3000} position={toast.POSITION.BOTTOM_LEFT} /> </FormContainer> </div> ); }; export default Signup;
import { useState, useEffect } from 'react'; import SetRep from './SetRep'; import Circuit from './Circuit'; import TimeDist from './TimeDist'; import axios from 'axios'; import { useHistory, useParams } from "react-router-dom"; import { TrashIcon } from "@heroicons/react/outline"; import NavBar from '../Navbar'; const WorkoutForm = (props) => { const userId = localStorage.getItem('userId'); const ObjectId = (m = Math, d = Date, h = 16, s = s => m.floor(s).toString(h)) => s(d.now() / 1000) + ' '.repeat(h).replace(/./g, () => s(m.random() * h)); const defaultWorkoutStep = { type: "", id: ObjectId() }; const [workoutForm, setWorkoutForm] = useState({ name: "", workout: [{ ...defaultWorkoutStep, _id: ObjectId() }], }); const history = useHistory(); const id = useParams(); useEffect(() => { if (id.id && userId) { axios.get(`http://localhost:3001/api/workouts/${id.id}/${userId}`, { withCredentials: true }) .then(res => { console.log(res); let editForm = structuredClone(res.data.workout[0]); editForm.workout.push(defaultWorkoutStep); setWorkoutForm(editForm); }) .catch(err => { console.log(err); }) } }, [userId]) function formType(type, i) { switch (type) { case "sets": return (<SetRep setWorkoutForm={setWorkoutForm} workoutForm={workoutForm} index={i} ObjectId={ObjectId} />) case "circuit": return (<Circuit setWorkoutForm={setWorkoutForm} workoutForm={workoutForm} index={i} ObjectId={ObjectId} />) case "timedist": return (<TimeDist setWorkoutForm={setWorkoutForm} workoutForm={workoutForm} index={i} ObjectId={ObjectId} />) default: return (<></>) } } function nameChange(e) { e.preventDefault(); setWorkoutForm({ ...workoutForm, [e.target.name]: e.target.value }); } function typeChange(e, index) { e.preventDefault(); let temp = structuredClone(workoutForm); if (index === temp.workout.length - 1) { temp.workout.push({ ...defaultWorkoutStep, _id: ObjectId() }); } if (e.target.value === "") { temp.workout.splice(index, 1); temp.workout[temp.workout.length - 1] = { ...defaultWorkoutStep, _id: ObjectId() }; } else { if (e.target.value === "sets") { temp.workout[index] = { _id: ObjectId(), type: e.target.value, steps: [] }; } else if (e.target.value === "circuit") { temp.workout[index] = { _id: ObjectId(), rounds: "", type: e.target.value, steps: [] }; } else if (e.target.value === "timedist") { temp.workout[index] = { _id: ObjectId(), type: e.target.value }; } } setWorkoutForm(temp); } function submitHandler(e) { e.preventDefault(); if (!userId) { history.push("/"); } let temp = structuredClone(workoutForm); for (let i = 0; i < temp.workout.length; i++) { let obj = temp.workout[i]; if (obj.type === "") { temp.workout.splice(i, 1); i--; } else if (obj.type === "sets") { for (let j = 0; j < obj.steps.length; j++) { let step = obj.steps[j]; if (step.movement === "" || step.reps === "" || step.sets === "") { obj.steps.splice(j, 1); j--; } } } else if (obj.type === "circuit") { for (let j = 0; j < obj.steps.length; j++) { let step = obj.steps[j]; if (step.movement === "" || step.reps === "" || step.units === "") { obj.steps.splice(j, 1); j--; } } } else { if (obj.movement === "" || obj.duration === "" || obj.units === "") { temp.workout.splice(i, 1); i--; } } } temp.userId = userId; if (id.id) { axios.put(`http://localhost:3001/api/workouts/${id.id}/${userId}`, { ...temp }, { withCredentials: true }) .then(res => { console.log(res); history.push("/workout") }) .catch(err => { console.log(err); }); } else { axios.post("http://localhost:3001/api/workouts", { ...temp }, { withCredentials: true }) .then(res => { console.log(res); setWorkoutForm({ name: "", workout: [{ }] }); history.push("/workout") }) .catch(err => { console.log(err); }); } } function deleteWorkout(e) { e.preventDefault(); axios.delete(`http://localhost:3001/api/workouts/${id.id}/${userId}`, { withCredentials: true }) .then(res => { console.log(res); history.push("/workout"); }) .catch(err => console.log(err)); } return ( <> <NavBar /> <form className='flex flex-col justify-evenly my-2 max-w-5xl mx-auto bg-white p-14 border-2 border-gray-100 shadow-sm' onSubmit={submitHandler}> <div>{id.id ? <TrashIcon className='cursor-pointer w-6 h-6 text-red-500 hover:text-red-700' onClick={deleteWorkout} /> : ""}</div> {/* Workout Name */} <div className='flex flex-col justify-center'> <label htmlFor="name" className='mb-2 self-center block text-lg font-bold text-center'>Name of Workout:</label> <input defaultValue={workoutForm.name} name='name' onChange={nameChange} type="text" placeholder="Name of Your Workout" className='mx-auto text-center self-center p-2 text-gray-900 border text-base border-gray-300 rounded-md bg-gray-50 focus:outline-none focus:ring-blue-500 focus:border-blue-500 w-3/5' /> </div> <hr className='mt-3' /> <div className='flex flex-col justify-center m-5'> { workoutForm.workout.map((ele, i) => { return ( <div key={ele._id} className="w-full"> <select defaultValue={ele.type} name="workouttype" onChange={(e) => typeChange(e, i)} className="mb-3 text-gray-900 text-base border-gray-300 rounded-md bg-gray-50 focus:outline-none focus:ring-blue-500 focus:border-blue-500"> <option none="true" value="" default></option> <option value="sets">Sets</option> <option value="circuit">Circuit</option> <option value="timedist">Time or Distance</option> </select> <div className='w-full flex flex-col items-center justify-center'> {formType(ele.type, i)} </div> </div> ) }) } </div> <button type='submit' className='w-1/5 self-center text-white bg-amber-500 hover:bg-amber-800 focus:outline-none focus:ring-4 focus:ring-blue-300 font-medium rounded-full text-sm px-5 py-2.5 text-center mr-2 mb-2'>{id.id ? 'Update Workout' : 'Add Workout'}</button> </form> </> ); } export default WorkoutForm;
#include <stdio.h> #include<stdlib.h> #include <assert.h> #include <time.h> #define LOWER 1 #define SIZE 10 typedef int song; typedef enum bool {false,true} bool; void test(void); song* make_empty(int num); void order_array(song arr[],int size); song* order_gen(int num); void swap(song* p, song* q); void print_arr(song* arr, int size); int main(void) { song* random_selection; song second_test[SIZE]={1,2,3,4,5,6,7,8,9,10}; srand(time(NULL)); test(); random_selection=order_gen(6); order_array(second_test,SIZE); print_arr(second_test,SIZE); printf("and another one\n"); print_arr(random_selection,6); free(random_selection); return 0; } void test(void) { int i,j; song* test_arr; song order_array_test[SIZE]={1,2,3,4,5,6,7,8,9,10}; test_arr=order_gen(SIZE); /* testing that values stay within bounds */ for(i=0;i<SIZE;i++) { assert(test_arr[i]<SIZE+1 &&test_arr[i]>0); } /* testing for duplicates*/ for(i=0;i<SIZE;i++) { for(j=i+1;j<SIZE;j++) { assert(test_arr[i]!=test_arr[j]); } } free(test_arr); order_array(order_array_test,SIZE); for(i=0;i<SIZE;i++) { assert(order_array_test[i]<=10&& order_array_test[i]>=1); } for(i=0;i<SIZE;i++) { for(j=i+1;j<SIZE;j++) { assert(order_array_test[i]!=order_array_test[j]); } } } song* make_empty(int num) { song *arr; int i; arr=(song *) malloc(sizeof(song)*num); if(arr==NULL) { printf("array could not be created\n"); exit(1); } for(i=0;i<num;i++) { arr[i]=0; } return arr; } song* order_gen(int num) { song *arr; song position; int count,i; bool state; state=true; arr= make_empty(num); count=0; while(count<num) { position= rand() % num + LOWER; for(i=0;i<num;i++) { if(arr[i]==position) { state=false; } } if(state==true) { arr[count]= position; count+=1; } state=true; } return arr; } /* swaps values in array randomly*/ void order_array(song arr[],int size) { int i; song j,k; for(i=0;i<size;i++) { j=rand() %size; k=rand() %size; swap(&arr[k],&arr[j]); } } void swap(song* p, song* q) { song temp; temp= *q; *q= *p; *p = temp; } void print_arr(song* arr, int size) { int i; for(i=0;i<size;i++) { printf("%d\n",arr[i]); } }
import 'package:emos/components/RoundedButton/rounded_button.dart'; import 'package:emos/components/VerticalSpacing/vertical_spacing.dart'; import 'package:emos/view/FamilyView/widgets/add_family_card.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import '../../res/GlobalColors/colors.dart'; import '../../routes/routes_name.dart'; class FamilyMembers extends StatelessWidget { const FamilyMembers({super.key}); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColor.bgFillColor, body: SafeArea( child: Container( height: double.infinity, width: double.infinity, decoration: const BoxDecoration( color: AppColor.whiteColor, borderRadius: BorderRadius.only( topRight: Radius.circular(50.0), ), ), child: Padding( padding: const EdgeInsets.only(left: 20.0, right: 20.0), child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( children: [ const VerticalSpeacing(26.0), Row( children: [ IconButton( onPressed: () { Navigator.pushNamed(context, RouteName.homeMenuView); }, icon: const Icon( Icons.arrow_back_ios_new_rounded, color: AppColor.textColor, ), ), const SizedBox(width: 10.0), Text( 'Family Members', style: GoogleFonts.getFont( "Poppins", textStyle: const TextStyle( fontSize: 24, fontWeight: FontWeight.w600, color: AppColor.textColor, ), ), ), ], ), const VerticalSpeacing(24.0), const AddFamilyCardWidget(), const VerticalSpeacing(16.0), const AddFamilyCardWidget(), const VerticalSpeacing(16.0), const AddFamilyCardWidget(), const VerticalSpeacing(16.0), const AddFamilyCardWidget(), const VerticalSpeacing(46.0), RoundedButton( title: 'Add New Dependent', onpress: () { Navigator.pushNamed(context, RouteName.cardInfotview); }, bgColor: Colors.transparent, titleColor: AppColor.linearBgTextColor, ) ], ), ), ), ), ), ); } }
import { useState, useEffect } from 'react' import Spinner from 'react-bootstrap/Spinner' import ListGroup from 'react-bootstrap/ListGroup' import { Link, useParams } from 'react-router-dom' import SWAPI from '../services/SW-API' import getIdFromUrl from '../helpers/index' const FilmPage = () => { const [Film, setFilm] = useState() const { id } = useParams() const [loading, setLoading] = useState(false) const getFilm = async (id) => { const data = await SWAPI.getFilm(id) setFilm(data) console.log("got data", data) console.log() setLoading(true) } useEffect(() => { getFilm(id) }, [id]) if(!loading) { return ( <> <span className="loading">Loading...</span> <Spinner animation="border" variant="light"> </Spinner> </> ) } return ( <> <h1>{Film.title}</h1> <div className="card"> <h4>Episode: {Film.episode_id}</h4> <p><strong>Released:</strong> {Film.release_date}</p> <p><strong>Director:</strong> {Film.director}</p> <p><strong>Producer/s:</strong> {Film.producer}</p> <div> <h5>Characters</h5> {Film.characters.length > 0 && ( <ListGroup> {Film.characters.map(people => <ListGroup.Item action as={Link} key={getIdFromUrl(people)} to={`/people/${getIdFromUrl(people)}`} > <p><u>Character {getIdFromUrl(people)} <i className="fa-solid fa-arrow-right"></i></u></p> </ListGroup.Item> )} </ListGroup> )} </div> </div> </> ) } export default FilmPage;
# BuySell-Backend The backend to the daysale day app using the MERN stack. Its purpose of this is to handle the database interation, authentication, and processing of the data as well as our api end points for a buying selling days app connecting with the front end here [Front end link](https://github.com/KirkWest/day-sale) ## URL link to deployed site [daysale](https://acelp-daysale-8a5708430aac.herokuapp.com/) ## database The data for the the app is held in MongoDB Atlas cloud server as per the calendarEvent model schema. ## list of dependencies "dependencies": { "bcryptjs": "^2.4.3", "cors": "^2.8.5", "dotenv": "^16.3.1", "express": "^4.18.2", "jsonwebtoken": "^9.0.2", "mongodb": "^6.3.0", "mongoose": "^8.0.3", }, ## src/index.js This file loads the environment variables from the .env set in the heroku var, it also establishes the connection to the database and starts the server on port 3000. ## src/server.js Makes an instance of our app ## src/database.js Database contains our function that connects us to MongoDB cloud Atlas using mongoose then logs the connection status. ## src/controllers/authController.js The auth controller controls the function of the registration and login of the admins. ## src/controllers/calendarController.js Contains a controller method for admin to interact with the calendar called manageChildNames, this allowd the admin to add more child names to the array set for a particular day as well as update and remove names, if there are no names left in the array it will delete the event from the database. It also contains our fetchEvents (for the admin to see the child names in the modal), and the fetchAvailableEvents for the buy button for both admin and guest to view ## src/models/CalendarEvent.js Defines the Mongoose schema for CalendarEvent, these involve simply date(this is taken from the day seleted on the calendar), and the childNames which is set to an array so it can hold multiple children or just one. ## src/models/User.js Defines the mongoose schema for User, this is the account holder, as of initial build only the admins will have a schema, there is potential to add in parents as users at a later date. Contains properties of username, email, password, and isAdmin(this is set to default for now but can be changed at a later date if non admin users are added into the model and app). All passwords are hashed before saving. ## src/middleware/authMiddleware.js AuthenticateToken will check if the request has a valid jwt token from the Authorization header. If it is valid it will decode the token, finds the user, and attaches the user object to the request. ### Registration ** Note - Registration is built in backend but not implemented in front end as of now - Checks if the user has infilled all fields, username, email, and password with validation - Regex for email format and also checks for existing users - Password hashing and user creation handling - Generates and returns the JWT if successfully registered ### Login - Validation for username and password - Checks for username and password in database - Generates JWT if successfully logs in - Error handling with responses ## src/functions/userAuthFunctions.js This contains the functions for using bcryptjs for hashing our password and also comparing it to the saved password in the database. It also contains a functions to generate JWT using jsonwebtoken with an expiry date of 4hrs set. ## src/routes/authRouter.js Contains the api endpoints for authorisation purposes, registration and logging in. ## src/routes/calendarRouter.js Contains the API endpoints for our calendar, manageChildNames (with auth token) so the admin user can add or remove child names from database, events (with auth token) so the adminuser can fetch the children names to populate in the managechildren modal, and eventsAvailable which just finds if there are children on any date then matches that date with a day in the calendar to populate the buy buttons.
import { AccountType } from "generated/graphql"; import { useState, useEffect } from "react"; const checkForDocumentVerificationRequired = (requirements: Array<string> | undefined) => { const result = requirements?.find((requirement: string) => requirement.includes(".verification.document")) || []; return result?.length > 0; }; export const useStripeOnboardingStatus = (account: AccountType | undefined) => { const [state, setState] = useState({ pending: false, restricted: false, restrictedSoon: false, showRatings: false, showNoRatings: false, showMerchantOnboardingChecklist: false, documentVerificationRequiredSoon: false, documentVerificationRequired: false, hasOnlyExternalAccountRequirement: false, }); const [processing, setProcessing] = useState(true); useEffect(() => { if (account) { const pastDueRequirements = account?.merchantProfileDetails?.businessDetails?.pastDueRequirements; const currentlyDueRequirements = account?.merchantProfileDetails?.businessDetails?.currentlyDueRequirements; const hasOnboarded = !!account?.merchantProfileDetails?.businessDetails?.hasOnboarded; const hasBanking = !!account?.merchantProfileDetails?.businessDetails?.hasBanking; const acceptsPayments = !!account?.merchantProfileDetails?.businessDetails?.chargesEnabled; const payoutsEnabled = !!account?.merchantProfileDetails?.businessDetails?.payoutsEnabled; const hasRatings = account?.averageRating !== undefined && account?.reviews?.pageInfo?.totalCount !== undefined && account?.reviews?.pageInfo?.totalCount > 0; const hasNoRatings = account?.averageRating === undefined || account?.reviews?.pageInfo?.totalCount === undefined || account?.reviews?.pageInfo?.totalCount === 0; const hasCurrentlyDueRequirements = (() => { const result = currentlyDueRequirements?.filter((requirement) => { if (requirement.includes(".verification.document")) return false; return true; }) || []; return result.length > 0; })(); const hasPastDueRequirements = (() => { const result = pastDueRequirements?.filter((requirement) => { if (requirement.includes(".verification.document")) return false; return true; }) || []; return result.length > 0; })(); const hasRequirements = hasCurrentlyDueRequirements || hasPastDueRequirements; const documentVerificationRequiredSoon = checkForDocumentVerificationRequired(currentlyDueRequirements); const documentVerificationRequired = checkForDocumentVerificationRequired(pastDueRequirements); // true if the only requirement is "external_account" for currently and past due const hasOnlyExternalAccountRequirement = pastDueRequirements?.every((item) => item.includes("external_account")) && currentlyDueRequirements?.every((item) => item.includes("external_account")); const pending = hasBanking && (!acceptsPayments || !payoutsEnabled) && !hasRequirements && !documentVerificationRequiredSoon && !documentVerificationRequired; setState({ pending, restricted: (hasOnboarded && hasPastDueRequirements) || (!hasBanking && acceptsPayments), restrictedSoon: hasOnboarded && hasCurrentlyDueRequirements && !hasPastDueRequirements, showMerchantOnboardingChecklist: pending || !hasOnboarded, showRatings: !pending && hasRatings, showNoRatings: !pending && hasNoRatings && hasOnboarded && hasBanking && !hasCurrentlyDueRequirements && !documentVerificationRequiredSoon && !documentVerificationRequired, documentVerificationRequiredSoon, documentVerificationRequired, hasOnlyExternalAccountRequirement: !!hasOnlyExternalAccountRequirement, }); setProcessing(false); } }, [account]); const { pending, restricted, restrictedSoon, showRatings, showNoRatings, showMerchantOnboardingChecklist, documentVerificationRequiredSoon, documentVerificationRequired, hasOnlyExternalAccountRequirement, } = state; return { processing, pending, restricted, restrictedSoon, showRatings, showNoRatings, showMerchantOnboardingChecklist, documentVerificationRequired, documentVerificationRequiredSoon, hasOnlyExternalAccountRequirement, }; };
from functions import * def damerau_levenshtein_distance_recursive_cache(str1, str2, flag_output=False): n, m = len(str1), len(str2) matrix = create_levenshtein_matrix(n + 1, m + 1) for i in range(n + 1): for j in range(m + 1): matrix[i][j] = -1 recursive_cache(str1, str2, n, m, matrix) if flag_output: print("\nМАТРИЦА:") print_matrix(matrix, str1, str2) result = matrix[n][m] return result def recursive_cache(str1, str2, n, m, matrix): if matrix[n][m] != -1: return matrix[n][m] if n == 0: matrix[n][m] = m return matrix[n][m] if n > 0 and m == 0: matrix[n][m] = n return matrix[n][m] action_add = recursive_cache(str1, str2, n - 1, m, matrix) + 1 action_delete = recursive_cache(str1, str2, n, m - 1, matrix) + 1 action_change = recursive_cache(str1, str2, n - 1, m - 1, matrix) if str1[n - 1] != str2[m - 1]: action_change += 1 matrix[n][m] = min(action_add, action_delete, action_change) if n > 1 and m > 1 and str1[n - 1] == str2[m - 2] and str1[n - 2] == str2[m - 1]: matrix[n][m] = min(matrix[n][m], recursive_cache(str1, str2, n - 2, m - 2, matrix) + 1) return matrix[n][m]
// { Driver Code Starts // driver code #include <iostream> using namespace std; struct Node { int data; Node *next; Node(int val) { data = val; next = NULL; } }; void loopHere(Node *head, Node *tail, int position) { if (position == 0) return; Node *walk = head; for (int i = 1; i < position; i++) walk = walk->next; tail->next = walk; } bool isLoop(Node *head) { if (!head) return false; Node *fast = head->next; Node *slow = head; while (fast != slow) { if (!fast || !fast->next) return false; fast = fast->next->next; slow = slow->next; } return true; } int length(Node *head) { int ret = 0; while (head) { ret++; head = head->next; } return ret; } class Solution { public: void removeLoop(Node *head) { Node *slow = head, *fast = head, *prev; int flag = 0; while (slow && fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) { flag = 1; break; } } if (flag == 0) { return; } else if (slow == head) { while (slow != fast->next) { fast = fast->next; } fast->next = NULL; } else { slow = head; while (slow != fast) { prev = fast; slow = slow->next; fast = fast->next; } if (slow == fast) { prev->next = NULL; } } } }; int main() { int t; cin >> t; while (t--) { int n, num; cin >> n; Node *head, *tail; cin >> num; head = tail = new Node(num); for (int i = 0; i < n - 1; i++) { cin >> num; tail->next = new Node(num); tail = tail->next; } int pos; cin >> pos; loopHere(head, tail, pos); Solution ob; ob.removeLoop(head); if (isLoop(head) || length(head) != n) cout << "0\n"; else cout << "1\n"; } return 0; }
--- title: Creating a website with the academic theme in blogdown author: Kevin Zolea date: '2019-02-13' slug: Creating-a-website-with-the-academic-theme-in-blogdown categories: - blogdown - R - Hugo tags: - blogdown - R summary: My thoughts and some guidance on how to set up a free website with blogdown, GitHub, and Netlify header: image: 'headers/test.png' caption: '' focal_point: '' --- <div id="introduction" class="section level3"> <h3>Introduction:</h3> <p>I have been told by a countless number of people that creating a personal website is a great way to showcase your skills and tell your story. I have been contemplating this for some time but kept procrastinating. The two biggest excuses I kept telling myself was that it would be too difficult &amp; it would cost money. Boy was I wrong! It wasn’t until I started using R this past year that I realized how wrong I was. After a quick google search I came across the <a href="https://cran.r-project.org/web/packages/blogdown/blogdown.pdf" target="_blank">blogdown</a> package. <code>Blogdown</code> is an amazing package in which you can create blogs and websites with <a href="https://rmarkdown.rstudio.com/" target="_blank">R Markdown</a>. Now I’m not saying that this stuff is extremely easy but if someone like myself(absolutely no website development knowledge) can do it, <strong>YOU CAN TOO!</strong> This blog post isn’t a sure fire way to do it but more of an overview of how I did it. I would also like to point out that this is a <strong>very basic introduction </strong> to creating a blog/website with blogdown. The amount of things you can do with this package is almost endless.. especially if you have an understanding of CSS, HTML, and Javascript.</p> <div class="figure"> <img src="https://media.giphy.com/media/Rl9Yqavfj2Ula/giphy.gif" /> </div> </div> <div id="prerequisites" class="section level3"> <h3>Prerequisites:</h3> <p>Before you jump right in I recommend reading some online material and watching some youtube videos. Here is a list of the resources that helped me a lot.</p> <ul> <li><p><a href="https://bookdown.org/yihui/blogdown/" target="_blank">blogdown: Creating Websites with R Markdown</a></p></li> <li><p><a href="https://alison.rbind.io/post/up-and-running-with-blogdown/" target="_blank">Up and Running with Blogdown</a></p></li> <li><p><a href="https://www.youtube.com/watch?v=syWAKaj-4ck&amp;t=649s" target="_blank">Making a Website with Blogdown</a></p></li> <li><p><a href="https://sourcethemes.com/academic/docs/">Academic Theme Documentation</a> (if your going to use the academic theme)</p></li> <li><p><a href="https://amber.rbind.io/blog/2016/12/19/creatingsite/" target="_blank">Making a Website Using Blogdown, Hugo, and GitHub pages</a></p></li> </ul> <p>Once you review the above material you should have a pretty firm grasp on how to get the ball rolling. One of the biggest hurdles I had was creating my site with the Hugo Academic Theme. It wasn’t until I found this <a href="https://stackoverflow.com/questions/54300535/unable-to-create-new-site-using-hugo-academic-theme">post</a> on stackoverflow that I was able to figure out what the problem was. There was a breaking change in the hugo-academic theme, so I had to download the development version of <code>blogdown</code>. Not sure if this is still a thing but if you have the same problem definitly check out that post! The last piece of advice I will give before we get started is to make sure you check what the minimum hugo verision is for the theme you want to use. You can do this by going to the <a href="https://themes.gohugo.io/" target="_blank">hugo website</a>. Pick the theme you want to use and look at the line that says <code>Minimum Hugo Verision:</code> You can check what verision of hugo you have by using <code>hugo_version()</code> in R. Now lets get started!</p> </div> <div id="creating-a-repository-and-cloning-it" class="section level3"> <h3>Creating a Repository and Cloning it</h3> <ol style="list-style-type: decimal"> <li>I am going to assume you have used <a href="https://github.com/" target="_blank">GitHub</a> before, but if you haven’t, that is completely fine. You can check out this <a href="https://guides.github.com/" target="_blank">site</a> to get a better understanding. Once you have a good understanding of GitHub and have an account created, you need to create a new repository. You can name this repository anything you want but it’s usually best practice to give it a meaningful name.</li> </ol> <div class="figure"> <img src="/img/screenshot1.png" /> </div> <p>Once you click create repository you should be on your repository page.</p> <ol start="2" style="list-style-type: decimal"> <li>Now you have to create a local copy of your repository or in other words “clone it”. To do this click the green “Clone or Download” button on the right hand side and copy the url displayed.</li> </ol> <div class="figure"> <img src="/img/screenshot2.png" /> </div> <ol start="3" style="list-style-type: decimal"> <li>So in order to “clone” the repo with the url that you just copied, you’re going to have to use git. If you don’t know anything about git, I recommend reading <a href="https://happygitwithr.com/" target="_blank">Happy Git and GitHub for the useR</a>. Now you can do this in numerous different ways. You can open <a href="https://macpaw.com/how-to/use-terminal-on-mac">Terminal</a> if you’re on a Mac, if you’re on windows you can open <a href="https://gitforwindows.org/" target="_blank">Git Bash</a> or you can use the Terminal in Rstudio. Personally, I like to use Rstudio. So if you’re in Rstudio you have to make sure that you navigate to your working directory. You can see your working directory by typing <code>pwd</code> and to change directories use <code>cd</code>. Type <code>git clone</code> and then paste the URL that you copied before.</li> </ol> <p>The command should look like this:</p> <p><code>git clone https://github.com/zoleak/Personal_Website.git</code></p> <p>If all went well then you should see a folder with the files in your repo in the directory that you chose.</p> <div class="figure"> <img src="/img/folder_stuff.png" /> </div> </div> <div id="getting-started-with-the-blogdown-package-in-rstudio" class="section level3"> <h3>Getting started with the blogdown package in Rstudio</h3> <p>The time has finally come to start creating the site.</p> <ol style="list-style-type: decimal"> <li>Open Rstudio and install <code>blogdown</code>. I recommend installing the development version, which can be done like this:</li> </ol> <p><code>remotes::install_github('rstudio/blogdown')</code></p> <ol start="2" style="list-style-type: decimal"> <li>Since <code>blogdown</code> is based on the static site generator Hugo, you need to install Hugo. You can easily do this by using a function in <code>blogdown</code>.</li> </ol> <p><code>install_hugo()</code></p> <ol start="3" style="list-style-type: decimal"> <li>Use the top menu buttons in Rstudio to browse to the directory on your computer where your GitHub repo is.</li> </ol> <p><code>File-&gt;New Project-&gt;Existing Directory</code></p> <ol start="4" style="list-style-type: decimal"> <li><p>Pick the theme you want to use. There are numerous different themes to pick from. I used the academic theme so I will use this one for the example. To browse themes <a href="https://themes.gohugo.io/" target="_blank">click here</a></p></li> <li><p>Create site using the <code>new_site()</code> function</p></li> </ol> <p>There are a couple different options to create the site but I believe the best one is using the <code>new_site()</code> function. You can do this like so:</p> <p><code>blogdown::new_site(theme = &quot;gcushen/hugo-academic&quot;)</code></p> <p>An example site should now be previewed in the Viewer panel of Rstudio.</p> <ol start="6" style="list-style-type: decimal"> <li>Personalize the website</li> </ol> <p>I am not going to go over this because I am still learning how to do this myself. The main thing you should know is that you can edit the example site in any way you would like. You can change the title, fonts, color scheme, widgets used, etc. If you decide to use the Academic Theme look over the <a href="https://sourcethemes.com/academic/docs/" target="_blank">documentation</a> . The author of the theme goes into great detail on how to get started and the different levels of customization you can do. The last thing I am going to touch base on is how to get your new site deployed to Netlify.</p> </div> <div id="deploy-in-netlify" class="section level3"> <h3>Deploy in Netlify</h3> <p><img src="/img/netlify.png" /> There are a number of ways to deploy your new website but I personally like Netlify. Netlify allows you to connect to your GitHub repo, add custom build settings, and deploy your website. The best part about Netlify is that it’s <strong>free</strong> and extremely <strong>easy</strong>.</p> <ol style="list-style-type: decimal"> <li>When you are ready to deploy, commit your changes and push to GitHub, then go online to <a href="https://www.netlify.com/" target="_blank">Netlify</a>. You can commit your changes and push to GitHub all in Rstudio. Use the top menu button.</li> </ol> <p><code>Tools-&gt;Version Control-&gt;Commit</code></p> <p>This will bring up a new window:</p> <p><img src="/img/version_control.png" /> You should see all your files there. Highlight all the files you want to commit and make sure they are set to staged. Add a commit message and then press commit. After you press commit a smaller window will pop up. Wait a couple seconds and let it do it’s thing. Once it’s done hit close. Lastly, click the push button. If you did this correctly the files will now be uploaded to your GitHub repo.</p> <ol start="2" style="list-style-type: decimal"> <li><p>Go to Netlify’s website and click on the sign up button and sign up using your existing GitHub account.</p></li> <li><p>Log in, and select: <code>New site from Git-&gt; Continuous Deployment: GitHub</code></p></li> <li><p>Netlify will then allow you to select from your existing GitHub repositories. Pick the repo you’ve been with.</p></li> </ol> </div> <div id="final-thoughts" class="section level3"> <h3>Final Thoughts</h3> <p>As you can see, it isn’t as difficult as you may have thought to create your own website/blog. <code>Blogdown</code> is a great resource to utilize. Like I mentioned in the beginning, this is a very <strong>basic</strong> introduction into <code>blogdown</code>. There is so much more you can do to your website to make it awesome! I hope this post has helped you in some way in getting your website going. If you have an comments, constructive critism, questions, etc. please let me know and contact me.</p> </div>
<?php /** * HTTP response class * * Contains a response from Requests::request() * @package Requests */ /** * HTTP response class * * Contains a response from Requests::request() * @package Requests */ class Requests_Response { /** * Constructor */ public function __construct() { $this->headers = new Requests_Response_Headers(); } /** * Response body * @var string */ public $body = ''; /** * Raw HTTP data from the transport * @var string */ public $raw = ''; /** * Headers, as an associative array * @var array */ public $headers = array(); /** * Status code, false if non-blocking * @var integer|boolean */ public $status_code = false; /** * Whether the request succeeded or not * @var boolean */ public $success = false; /** * Number of redirects the request used * @var integer */ public $redirects = 0; /** * URL requested * @var string */ public $url = ''; /** * Previous requests (from redirects) * @var array Array of Requests_Response objects */ public $history = array(); /** * Cookies from the request */ public $cookies = array(); /** * Throws an exception if the request was not successful * * @throws Requests_Exception If `$allow_redirects` is false, and code is 3xx (`response.no_redirects`) * @throws Requests_Exception_HTTP On non-successful status code. Exception class corresponds to code (e.g. {@see Requests_Exception_HTTP_404}) * @param boolean $allow_redirects Set to false to throw on a 3xx as well */ public function throw_for_status($allow_redirects = true) { if ($this->status_code >= 300 && $this->status_code < 400) { if (!$allow_redirects) { throw new Requests_Exception('Redirection not allowed', 'response.no_redirects', $this); } } elseif (!$this->success) { $exception = Requests_Exception_HTTP::get_class($this->status_code); throw new $exception(null, $this); } } }
--- layout: single title: Display the Background Grid while Drawing Graphics by LaTeX TikZ date: 2023-09-23 16:09:23 +0800 categories: - LaTeX - Graphic Design and Typography tags: - LaTeX TikZ --- While using LaTeX TikZ to draw diagrams, users maybe confused with determining the coordinate of each object. A background grid of drawing area could visually help user draw the figure. # TikZ `backgrounds ` library One choice is utilising the TikZ `backgrounds` library: ```latex \documentclass{article} \usepackage{geometry} \geometry{a2paper} \usepackage{xcolor} \usepackage{tikz} \usetikzlibrary{arrows.meta,bending} \usetikzlibrary{backgrounds} % Backgroud grid settings \tikzset{background top/.style={draw=blue!50,line width=1ex}, background bottom/.style={draw=blue!50,line width=1ex}, background left/.style={draw=blue!50,line width=1ex}, background right/.style={draw=blue!50,line width=1ex}} \begin{document} \begin{center} \begin{tikzpicture} % The drawing area is flexible [framed, show background top, show background bottom, show background left, show background right,background grid/.style={thin,draw=gray,step=0.5cm}, show background grid] % Set required grid options \draw[line width=1.5pt] (0,0) ellipse [x radius=2cm, y radius=1.5cm]; \draw[line width=1.5pt] (20,20) circle [radius=1cm]; \draw[line width=1.5pt,color=red] (0,0) rectangle (20,20); \draw[line width=1.5pt,color=red] (-5,-5) rectangle (0,0); \draw[line width=1.5pt] (-5,-5) circle [radius=1cm]; \draw[tips, -{Latex[open,length=10pt,bend]},line width=2pt,color=blue] (0,0) to [bend left] (-5,20); \draw[tips, -{Latex[open,length=10pt,bend]},line width=2pt,color=green] (0,0) to [bend left] (20,-5); \draw[tips, -{Latex[open,length=10pt,bend]},line width=2pt,color=blue] (0,0) to [bend left] (-5,20); \fill (0,0) circle (3pt); \fill (20,20) circle (3pt); \fill (-5,-5) circle (3pt); \fill (-5,20) circle (3pt); \fill (20,-5) circle (3pt); \end{tikzpicture} \end{center} \end{document} ``` ![image-20230923151638213](https://raw.githubusercontent.com/Ma1017/blog-images/main/imgs/image-20230923151638213.png) It is a great implementation method as this background grid is flexible, that is when a new object is added in the `tikzpicture` environment the grid will adjust automatically, like adding a new circle whose centre of coordinate is `(23,23)` for instance: ```latex ... \draw[line width=1.5pt] (23,23) circle [radius=1cm]; ... \fill (23,23) circle (3pt); ... ``` The grid area will enlarge adaptively: ![image-20230923161525294](https://raw.githubusercontent.com/Ma1017/blog-images/main/imgs/image-20230923161525294.png) <br> # TikZ `help lines` Another option is using TikZ `help lines` to draw background grid: ```latex \documentclass{article} \usepackage{geometry} \geometry{a2paper} \usepackage{xcolor} \usepackage{tikz} \usetikzlibrary{arrows.meta,bending} \usetikzlibrary{backgrounds} % Help line setttings \tikzset{help lines/.style=thin,color=gray} \begin{document} \begin{center} \begin{tikzpicture} \draw [help lines,step=.5cm] (-5,-5) grid (20,20); \draw[line width=1.5pt] (0,0) ellipse [x radius=2cm, y radius=1.5cm]; \draw[line width=1.5pt] (20,20) circle [radius=1cm]; \draw[line width=1.5pt,color=red] (0,0) rectangle (20,20); \draw[line width=1.5pt,color=red] (-5,-5) rectangle (0,0); \draw[line width=1.5pt] (-5,-5) circle [radius=1cm]; \draw[tips, -{Latex[open,length=10pt,bend]},line width=2pt,color=blue] (0,0) to [bend left] (-5,20); \draw[tips, -{Latex[open,length=10pt,bend]},line width=2pt,color=green] (0,0) to [bend left] (20,-5); \draw[tips, -{Latex[open,length=10pt,bend]},line width=2pt,color=blue] (0,0) to [bend left] (-5,20); \fill (0,0) circle (3pt); \fill (20,20) circle (3pt); \fill (-5,-5) circle (3pt); \fill (-5,20) circle (3pt); \fill (20,-5) circle (3pt); \end{tikzpicture} \end{center} \end{document} ``` ![image-20230923152810904](https://raw.githubusercontent.com/Ma1017/blog-images/main/imgs/image-20230923152810904.png) This grid area is fixed and completely determined by the diagonal points setting: ```latex \draw [help lines,step=.5cm] (-5,-5) grid (20,20); ``` where `(-5,-5)` is coordinate of lower left corner point, and `(20,20)` is the coordinate of top right-hand corner point. So, this method has a better application while drawing objects in the local area, but not appropriate to determine the coordinate of the whole area of `tikzpicture` environment. <br> **References** [1] [Background Library - PGF/TikZ Manual](https://tikz.dev/library-backgrounds). [2] [Tutorial: A Picture for Karl’s Students - PGF/TikZ Manual](https://tikz.dev/tutorial#autosec-69).
import AppError from '@shared/errors/AppError'; import CustomersRepository from '@modules/customers/typeorm/repositories/CustomersRepository'; import { ICustomersRepository, IUpdate } from '@modules/customers/typeorm/repositories/CustomersRepositoryInterface'; class UpdateCustomerService { private customersRepository: ICustomersRepository; constructor() { this.customersRepository = new CustomersRepository(); } public async execute({ id, name, email }: IUpdate): Promise<void> { const customer = await this.customersRepository.findById(id); if (!customer) { throw new AppError('Customer not found.'); } const customerExists = await this.customersRepository.findByEmail(email); if (customerExists && email !== customer.email) { throw new AppError('There already have one customer with this email.'); } await this.customersRepository.update({ id, name, email }); } } export default UpdateCustomerService;
/* Variable or function declared protected internal can be accessed in the assembly in which it is declared. It can also be accessed within a derived class in another assembly. */ using System; namespace AccessSpecifiers { class InternalTest { protected internal string name = "Shantosh Kumar"; protected internal void Msg(string msg) { Console.WriteLine("Hello " + msg); } } class Program { static void Main(string[] args) { InternalTest internalTest = new InternalTest(); // Accessing protected internal variable Console.WriteLine("Hello " + internalTest.name); // Accessing protected internal function internalTest.Msg("Peter Decosta"); } } }
import React, { useState, useEffect } from 'react'; import { Button, Modal as AntModal, Input, message, Select } from 'antd'; import { useSelector } from 'react-redux'; import axios from 'axios'; const { Option } = Select; const EditCategory = ({ showModal,categoryName, categoryId, parentName, parentId, fetchCategories }) => { const [loading, setLoading] = useState(false); const token = useSelector((state) => state.user?.token); const [open, setOpen] = useState(false); const [categoryData, setCategoryData] = useState({ name: '', parentId: '', parentName: '', }); const [parentCategories, setParentCategories] = useState([]); const user = useSelector((state) => state.user?.user); console.log("categoryName",categoryName); useEffect(() => { setCategoryData({ name: categoryName, parentId: parentId, parentName: parentName, }); }, [categoryName, parentId, parentName]); useEffect(() => { fetchParentCategories(); }, []); const fetchParentCategories = async () => { try { const response = await axios.get(`/api/GetParentCategories`); setParentCategories(response.data || []); } catch (error) { console.error("Error fetching parent categories:", error); } }; const showModalHandler = () => { showModal({ categoryId: categoryId }); setOpen(true); }; const handleCancel = () => { setOpen(false); }; const handleChange = (e, field) => { setCategoryData((prevCategoryData) => ({ ...prevCategoryData, [field]: e.target.value, })); }; const handleSelectParent = (value) => { setCategoryData({ ...categoryData, parentId: value, parentName: value ? parentCategories.find((category) => category.id === value).name : null, }); }; const handleEditCategory = async () => { try { if (user.role !== "ADMIN") { console.error("User information is missing"); return; } const requestBody = { name: categoryData.name, }; console.log("categoryData.parentId",categoryData.parentId); // Kiểm tra nếu có parentId thì thêm vào requestBody if (categoryData.parentId !== null) { requestBody.parent = { id: categoryData.parentId }; } console.log("requestBody",requestBody); const response = await axios.post( `/api/UpdateCategory?categoryId=${categoryId}`, requestBody, { headers: { Authorization: `Bearer ${token}` } } ); message.success("Cập nhật chuyên mục thành công"); fetchCategories(); setOpen(false); } catch (error) { console.error("Error updating category:", error); message.error("Cập nhật chuyên mục thất bại"); } }; return ( <> <Button type="primary" onClick={showModalHandler} className='bg-yellow-500 text-white'> Edit </Button> <AntModal visible={open} title="Edit Category" onOk={handleEditCategory} onCancel={handleCancel} footer={[ <Button key="back" onClick={handleCancel}> back </Button>, <Button key="submit" type='default' loading={loading} onClick={handleEditCategory}> Edit </Button>, ]} > <Input placeholder="Category Name" style={{ marginBottom: '15px' }} value={categoryData.name} onChange={(e) => handleChange(e, 'name')} /> <Select placeholder="Select Parent Category" style={{ width: '100%', marginBottom: '15px' }} value={categoryData.parentId} onChange={handleSelectParent} disabled={categoryData.parentId === null} // Vô hiệu hóa nếu parentId là null > <Option value={null}>None</Option> {parentCategories.map((category) => ( <Option key={category.id} value={category.id}> {category.name} </Option> ))} </Select> </AntModal> </> ); }; export default EditCategory;
############################################################################### # OpenVAS Vulnerability Test # $Id: gb_apache_tomcat_xee_info_disc_vuln.nasl 11402 2018-09-15 09:13:36Z cfischer $ # # Apache Tomcat XML External Entity Information Disclosure Vulnerability # # Authors: # Antu Sanadi <[email protected]> # # Copyright: # Copyright (C) 2014 Greenbone Networks GmbH, http://www.greenbone.net # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 # (or any later version), as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. ############################################################################### CPE = "cpe:/a:apache:tomcat"; if(description) { script_oid("1.3.6.1.4.1.25623.1.0.805019"); script_version("$Revision: 11402 $"); script_cve_id("CVE-2014-0119"); script_tag(name:"cvss_base", value:"4.3"); script_tag(name:"cvss_base_vector", value:"AV:N/AC:M/Au:N/C:P/I:N/A:N"); script_tag(name:"last_modification", value:"$Date: 2018-09-15 11:13:36 +0200 (Sat, 15 Sep 2018) $"); script_tag(name:"creation_date", value:"2014-11-28 19:52:03 +0530 (Fri, 28 Nov 2014)"); script_name("Apache Tomcat XML External Entity Information Disclosure Vulnerability"); script_category(ACT_GATHER_INFO); script_copyright("Copyright (C) 2014 Greenbone Networks GmbH"); script_family("Web Servers"); script_dependencies("gb_apache_tomcat_detect.nasl"); script_mandatory_keys("ApacheTomcat/installed"); script_require_ports("Services/www", 8080); script_xref(name:"URL", value:"http://secunia.com/advisories/59732"); script_xref(name:"URL", value:"http://tomcat.apache.org/security-7.html"); script_tag(name:"summary", value:"This host is running Apache Tomcat and is prone to information disclosure vulnerability."); script_tag(name:"vuldetect", value:"Checks if a vulnerable version is present on the target host."); script_tag(name:"insight", value:"The flaw is due to an application does not properly constrain the class loader that accesses the XML parser used with an XSLT stylesheet"); script_tag(name:"impact", value:"Successful exploitation will allow remote attackers to read arbitrary files via a crafted web application that provides an XML external entity declaration in conjunction with an entity reference."); script_tag(name:"affected", value:"Apache Tomcat before 6.0.40, 7.x before 7.0.54, and 8.x before 8.0.6"); script_tag(name:"solution", value:"Upgrade to version 6.0.40, 7.0.54, 8.0.6 or later. For updates refer to refer http://tomcat.apache.org"); script_tag(name:"qod_type", value:"remote_banner_unreliable"); script_tag(name:"solution_type", value:"VendorFix"); exit(0); } include("host_details.inc"); include("version_func.inc"); if( ! port = get_app_port( cpe:CPE ) ) exit( 0 ); if( ! vers = get_app_version( cpe:CPE, port:port ) ) exit( 0 ); if( version_in_range( version:vers, test_version:"6.0.0", test_version2:"6.0.39" ) || version_in_range( version:vers, test_version:"7.0.0", test_version2:"7.0.53" ) || version_in_range( version:vers, test_version:"8.0.0.RC1", test_version2:"8.0.5" ) ) { report = report_fixed_ver( installed_version:vers, fixed_version:"6.0.40/7.0.53/8.0.5" ); security_message( port:port, data:report ); exit( 0 ); } exit( 99 );
import random from django.core.management.base import BaseCommand, CommandParser from user.models import User from heart.models import Heart from product.models import Product class Command(BaseCommand): help = 'Generate fake hearts by users on products' def add_arguments(self, parser: CommandParser) -> None: parser.add_argument('-n', '--number', type=int, default=25, help='Number of products to heart') def handle(self, *args, **options): count = 0 users = User.objects.all() products = Product.objects.all() for _ in range(options['number']): user = random.choice(users) product = random.choice(products) if not Heart.objects.filter(user=user, product=product).exists(): count += 1 Heart.objects.create(user=user, product=product) self.stdout.write(self.style.SUCCESS(f'Generated {count} hearts'))
<page> <shortlink>report toc</shortlink> <topic>Report Table of Contents</topic> <description> <p>A live table of contents can be integrated into a report. Table of contents are fully customizable, allowing you to control both the contents and appearance of the table of contents.</p> </description> <discussion> <p>The table of contents appears before the report body and lists the page number for each entry. Entries are fully customizable as is the appearance of the table of contents.</p> </discussion> <sections> <section> <figure> <link>images/toc.png</link> </figure> </section> <section> <description> <p>The *[ui:Define Table of Contents]* menu option under the *[ui:Report]* menu is used to add a table of contents to a report.</p> </description> <figure> <link>images/tocMenu.png</link> </figure> </section> <section> <description> <p>In the table of contents builder, you will see several report sections listed that can be included in the table of contents. Each report section can have a *[ui:Table of Contents entry expression]* that defines the entry in the table of contents.</p> </description> <figure> <link>images/defineToc.png</link> </figure> </section> <section> <description> <p>The report sections that can be included in a table of contents will be displayed in the *[ui:Report Sections]* list. Report sections include:</p> </description> <list> <item> <name-title>Report Section</name-title> <description-title>Description</description-title> </item> <item> <name>Grand</name> <description>The "Grand" section is the page header and footer.</description> </item> <item> <name>Detail</name> <description>The "Detail" section refers to each detail entry, which is typically repeated for each report record.</description> </item>1 <item> <name>Group Break</name> <description>If the report contains one or more group breaks, an entry for each break will be listed. For example, if a report contains group breaks for each invoice number, then a Table of Contents entry can be defined for the invoice number.</description> </item> </list> </section> <section> <description> <p>For each Report Section, you can define the following properties:</p> </description> <list> <item> <name-title>Property</name-title> <description-title>Description</description-title> </item> <item> <name>Table of Contents entry expression</name> <description>An expression that generates the text shown in the table of contents.</description> </item> <item> <name>Target object</name> <description>Object in the report that receives focus when the user clicks on the entry in the table of contents.</description> </item> </list> </section> <section> <description> <p>Every time a record in a report section is printed, the *[ui:Table of Contents entry expression]* is evaluated and a new entry is inserted into the table of contents. The text shown in the table of contents is the result of the expression.</p> <p>When an entry in the table of contents is clicked, the corresponding page where the object is located is shown and the focus is given to the defined *[ui:Target object]*.</p> </description> </section> <section> <title>Customizing the Table of Contents Appearance</title> <description> <p>The table of content's appearance can be customized by creating a special type of report called a *[ui:Table of Contents Report]*. The custom *[ui:Table of Contents Report]* is built using the report builder. Any formatting or styling tools available in the report builder can be used to customize the table of content's appearance.</p> <p>To create a customized table of contents, click the *[ui:Add new custom 'Table of Contents' Report]* link at the bottom of the *[ui:Define Table of Contents for Report]* dialog. When prompted, specify a name for the new *[ui:Table of Contents Report]* and click *[ui:OK]*. Alpha Anywhere will open the report builder, which can be used to customize the table of contents. When you are satisfied with your changes, save and close the report.</p> </description> <figure> <link>images/createCustomToc.png</link> </figure> </section> <section> <description> <p>After the custom table of contents has been created, it can be added to the report. Open the *[ui:Define Table of Contents]* dialog. In the *[ui:Custom 'Table of Contents' Report]* dropdown, choose the table of contents report you created then click *[ui:OK]* to save your changes.</p> </description> <figure> <link>images/customtoc.png</link> </figure> </section> <section> <title>Where to Store a Custom Table of Contents Report</title> <description> <p>When you create a Table of Contents Report, you can store it in one of two locations:</p> </description> <list> <item> <name-title>Location</name-title> <description-title>Description</description-title> </item> <item> <name>Global Dictionary</name> <description>The Table of Contents Report will be saved in the global report dictionary.</description> </item> <item> <name>Local Dictionary</name> <description>The Table of Contents Report will be saved in a local report dictionary (required for web applications)</description> </item> </list> </section> <section> <description> <p>If the Table of Contents Report is stored in the global dictionary, it can be used in other reports that you have created.</p> <p>If stored in a local dictionary, the Table of Contents Report can only be referenced by the report used to create it.</p> <p>If a report will be used in a web application, the Table of Contents Report must be stored in a local dictionary. Desktop applications support storing Table of Contents Reports in both local and global dictionaries.</p> </description> <figure> <link>images/tocLocation.png</link> </figure> </section> <section> <title>Getting the Total Page Count of the Parent Report in a Custom Table of Contents</title> <description> <p>It may be desireable to display or use the total number of pages in a report in the table of contents layout. A calculated field can be used to display the total number of pages in the report. The *[xb:*parent_report_pagecount()]* function is used to fetch the total number of pages in the parent report. For example:</p> </description> <example code="xb"><![CDATA[toc_pageCount = *parent_report_pagecount()]]></example> <note> <p>If the report contains a table of contents or index, the pages for these sections are not included in the page count for the parent report.</p> </note> </section> <section> <title>Videos</title> <videos> <title>Reports - Table of Contents, Bookmarks and Index</title> <description> <p>A Table of Contents, Bookmarks, or Index can be added to a report using the report builder. You can completely customize the entries that are made in the Table of Contents, Bookmark section, and Index. In addition, you can completely customize the layout of the Table of Contents section and Index section.</p> <p>The entries that appear in the Table of Contents, Bookmark section, and Index are "live" - if you click on an entry, you will be navigated to the appropriate page in the report. In addition, when you print the report to a PDF file, the Table of Contents, Bookmarks, and Index are live.</p> </description> <note>This feature was originally sold as an optional add-on in Alpha Five Version 10 but is now included in all versions of Alpha Anywhere.</note> <video> <name>Watch Video - Part 1</name> <link>https://www.viddler.com/v/bb5995a5</link> </video> <video> <name>Watch Video - Part 2</name> <link>https://www.viddler.com/v/ee7ec641</link> </video> </videos> </section> </sections> <limitations>Freeform and Layout Table Reports Only</limitations> <see> <ref link="api star parent report pagecount function">*parent_report_pagecount Function</ref> </see> </page>
/* * Copyright 2015 Austin Lehman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ include net.html.caliBs.bsPages; include net.html.caliBs.bsComponents; include net.html.caliBs.bsGlyphs; include example.bsClasses; include reflect; /** * Demo page for glyphs. */ class bsGlyphs : examplePage { /** * Constructor to build page. */ public bsGlyphs() { // Call parent constructor with title. this.examplePage("caliBs Glyphs"); // Create a new bootstrap container div (defined in bsComponents). ctr = new bsContainer(); /* * Information section */ ctr .add(new _h1("Glyphs")) .add(new _p(this.glyph_desc_text())) .br() .add(new bsPre(new _text(this.glyph_desc_code()))) ; star_info = new _div(); star_info .add(new bsGlyph(glyph.star)) .add(new _span('cali-lang like star')) ; ctr .add(new _p("Below is an example of the code above.")) .add(star_info) .br() .add(new _p(this.all_glyph_text())) .add(new bsPre(new _text(this.all_glyph_code()))) .br() .add(new _h3("Available Glyphs")) ; /* * Grid with all glyphs. */ // Create new bsVbox and add it to the container. tbl = new bsVbox(); ctr.add(tbl); // Loop through all glyph names and add them in rows of 4 each. crow = new bsHbox(bsSize.xs); for(glname : this.allGlyphs()) { gdiv = new _div(); gdiv.set('style', 'text-align: center; width: 140px; height: 80px; padding-top: 20px; padding-bottom: 20px'); gdiv .add(new bsGlyph('glyphicon-' + glname)) .br() .add(new _span(new _text(glname))) ; crow.addCell(gdiv, 1); } tbl.add(crow); // Add the container to the body of the page. this.body.add(ctr); } /** * Returns a sorted list with all glyph names. * @r A sorted list of glyph names. */ public allGlyphs() { cls = reflect.getClassDef("glyph"); return list.sort(map.keySet(cls.getMembers())); } /***************************************************************** * Helper methods with text and code sections. ****************************************************************/ private glyph_desc_text() { return " Glyphs in caliBs are basically the same as the ones in normal bootstrap. The main difference is that in caliBs they are part of a static class so the cali-lang parser will throw an exception if you fat-finger the name. There's also a bsGlyph class that constructs a span object with the provided glyph name. "; } private all_glyph_text() { return " You can also get a list of all glyph names by using the reflect module. See the allGlyphs() method below for the implementation. Note that this method returns a list of glyph names, not the values. Take glyph.star for example. Referencing glyph.star actually returns a string with 'glyphicon-star'. When you get the list of all glyph names you get the member name, so that would be a string 'star'. In order to use the name you'll want to prepend 'glyphicon-' before the glyph name. "; } private glyph_desc_code() { return string.trim( """ // Creates a new span with the star glyph. glf = new bsGlyph(glyph.star); // The following creates a glyph and some text, // places it within a div and adds it to some // other element. star_info = new _div(); star_info .add(new bsGlyph(glyph.star)) .add(new _span('cali-lang like star')) ; some_element.add(star_info); """ ); } private all_glyph_code() { return string.trim( """ // Method uses reflect to get a sorted list of glpyh names. public allGlyphs() { cls = reflect.getClassDef("glyph"); return list.sort(map.keySet(cls.getMembers())); } // Get list of all glyph names. glist = this.allGlyphs(); // We can now create a new bsGlyph from // each list item. for(gname : glist) { ngly = new bsGlyph('glyphicon-' + gname); ... } """ ); } }
# -*- coding: utf-8 -*- ################################################################################ # # Cybrosys Technologies Pvt. Ltd. # # Copyright (C) 2024-TODAY Cybrosys Technologies(<https://www.cybrosys.com>). # Author: Vishnu KP ([email protected]) # # You can modify it under the terms of the GNU AFFERO # GENERAL PUBLIC LICENSE (AGPL v3), Version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU AFFERO GENERAL PUBLIC LICENSE (AGPL v3) for more details. # # You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE # (AGPL v3) along with this program. # If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from odoo import api, fields, models from odoo.exceptions import ValidationError class MealsPlanning(models.Model): """By using this model user can specify the time range and pos session""" _name = 'meals.planning' _description = "Product Planning" _inherit = ['mail.thread', 'mail.activity.mixin'] name = fields.Char(string='Name', required=True, help='Name for Product Planning', copy=False) pos_ids = fields.Many2many('pos.session', string='Shops', copy=False, help='Choose PoS Sessions', required=True) time_from = fields.Float(string='From', required=True, help='Add from time(24hr)') time_to = fields.Float(string='To', required=True, help='Add to time(24hr)') menu_product_ids = fields.Many2many('product.product', string='Product', domain=[('available_in_pos', '=', True)]) state = fields.Selection([('activated', 'Activated'), ('deactivated', 'Deactivated')], default='deactivated') company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company) @api.constrains('time_from', 'time_to') def _check_time_range(self): """Validation for from time and to time""" if self.time_from >= self.time_to: raise ValidationError('From time must be less than to time!') elif self.time_from > 24.0 or self.time_to > 24.0: raise ValidationError( 'Time value greater than 24 is not valid!') def action_activate_meals_plan(self): """Change state to activate""" self.write({ 'state': 'activated'}) def action_deactivate_meals_plan(self): """Change state to deactivate""" self.write({ 'state': 'deactivated'})
``` open class Dog class Puppy : Dog() class Hound : Dog() fun takeDog(dog: Dog) {} takeDog(Dog()) takeDog(Puppy()) takeDog(Hound()) ``` ``` //1 open class Dog class Puppy : Dog() class Hound : Dog() class Box<in T> { private var value: T? = null fun put(value: T) { this.value = value } } fun main() { val dogBox = Box<Dog>() dogBox.put(Dog()) dogBox.put(Puppy()) dogBox.put(Hound()) val puppyBox: Box<Puppy> = dogBox puppyBox.put(Puppy()) val houndBox: Box<Hound> = dogBox houndBox.put(Hound()) } ``` ``` class Box<out T> { private var value: T? = null fun set(value: T) { // Compilation Error this.value = value } fun get(): T = value ?: error("Value not set") } val dogHouse = Box<Dog>() val box: Box<Any> = dogHouse box.set("Some string") // Is this were possible, we would have runtime error here ``` ``` //2 class Box<out T> { private var value: T? = null private fun set(value: T) { // OK this.value = value } fun get(): T = value ?: error("Value not set") } ``` ``` open class Car interface Boat class Amphibious : Car(), Boat fun getAmphibious(): Amphibious = Amphibious() val amphibious: Amphibious = getAmphibious() val car: Car = getAmphibious() val boat: Boat = getAmphibious() ``` ``` //3 open class Car interface Boat class Amphibious : Car(), Boat class Producer<out T>(val factory: () -> T) { fun produce(): T = factory() } fun main() { val producer: Producer<Amphibious> = Producer { Amphibious() } val amphibious: Amphibious = producer.produce() val boat: Boat = producer.produce() val car: Car = producer.produce() val boatProducer: Producer<Boat> = producer val boat1: Boat = boatProducer.produce() val carProducer: Producer<Car> = producer val car2: Car = carProducer.produce() } ``` ``` open class Car interface Boat class Amphibious : Car(), Boat class Producer<in T>(val factory: () -> T) { fun produce(): T = factory() // Compilation Error } fun main() { val carProducer = Producer<Amphibious> { Car() } val amphibiousProducer: Producer<Amphibious> = carProducer val amphibious = amphibiousProducer.produce() // If not compilation error, we would have runtime error val producer = Producer<Amphibious> { Amphibious() } val nothingProducer: Producer<Nothing> = producer val str: String = nothingProducer.produce() // If not compilation error, we would have runtime error } ``` ``` class Box<in T>( val value: T // Compilation Error ) { fun get(): T = value // Compilation Error ?: error("Value not set") } ``` ``` //4 class Box<in T>( private val value: T ) { private fun get(): T = value ?: error("Value not set") } ``` ``` public interface Continuation<in T> { public val context: CoroutineContext public fun resumeWith(result: Result<T>) } ``` ``` class Box<in T1, out T2> { var v1: T1 // Compilation error var v2: T2 // Compilation error } ``` ``` //5 // Declaration-side variance modifier class Box<out T>(val value: T) val boxStr: Box<String> = Box("Str") val boxAny: Box<Any> = boxStr ``` ``` //6 class Box<T>(val value: T) val boxStr: Box<String> = Box("Str") // Use-site variance modifier val boxAny: Box<out Any> = boxStr ``` ``` //7 interface Dog interface Pet data class Puppy(val name: String) : Dog, Pet data class Wolf(val name: String) : Dog data class Cat(val name: String) : Pet fun fillWithPuppies(list: MutableList<in Puppy>) { list.add(Puppy("Jim")) list.add(Puppy("Beam")) } fun main() { val dogs = mutableListOf<Dog>(Wolf("Pluto")) fillWithPuppies(dogs) println(dogs) // [Wolf(name=Pluto), Puppy(name=Jim), Puppy(name=Beam)] val pets = mutableListOf<Pet>(Cat("Felix")) fillWithPuppies(pets) println(pets) // [Cat(name=Felix), Puppy(name=Jim), Puppy(name=Beam)] } ``` ``` if (value is List<*>) { ... } ```
// Queue Linked List Header With Functions // Author Omar Mohammad #include <iostream> #include <string> using namespace std; template<typename Type> struct NodeType { Type info; NodeType<Type>* link; }; template<typename Type> class Queue { NodeType<Type>* first = NULL; NodeType<Type>* last = NULL; int count = 0; public: void enqueue(Type); Type dequeuee(); //return the first element and remove it. Type First(); int queueSize(); bool isEmpty(); void clear(); void print(); void sortQueue(Queue<Type> qu); }; template<typename Type> void Queue<Type>::enqueue(Type info) { NodeType<Type>* newNode; newNode = new NodeType<Type>; newNode->info = info; newNode->link = NULL; if (first == NULL and last == NULL) { first = newNode; last = newNode; count++; } else { last->link = newNode; last = newNode; count++; } } template<typename Type> Type Queue<Type>::dequeuee() { if (count == 0) { cout << "Cannot delete from an empty queue!" << endl; return 0; } else { NodeType<Type>* newNode; newNode = first; if (count == 1) { Type data = newNode->info; first = NULL; last = NULL; delete newNode; count = 0; return data; } else { Type data = newNode->info; first = first->link; delete newNode; count--; return data; } } } template<typename Type> void Queue<Type>::print() { NodeType<Type>* newNode; newNode = new NodeType<Type>; newNode = first; while (newNode != NULL) { cout << newNode->info << " "; newNode = newNode->link; } cout << endl; } template<typename Type> Type Queue<Type>::First() { if (count == 0) { cout << "Empty Queue!" << endl; return 0; } else return first->info; } template<typename Type> bool Queue<Type>::isEmpty() { return count == 0; } template<typename Type> void Queue<Type>::clear() { NodeType<Type>* current = new NodeType<Type>; while (first != NULL) { current = first; first = first->link; delete current; } last = NULL; count = 0; } template<typename Type> int Queue<Type>::queueSize() { return count; } void generateBinaryNum1(int limit) { Queue<string> qu; qu.enqueue("1"); for (int i = 1; i <= limit; i++) { string binRep = qu.dequeuee(); cout << binRep << " "; qu.enqueue((binRep + "0")); qu.enqueue((binRep + "1")); } } void genrateBinaryNum2(int limit) { Queue<string> qu; int remainder; int product = 1; int binary = 0; for (int i = 1; i <= limit; i++) { while (i != 0) { remainder = i % 2; binary = binary + (remainder * product); i = i / 2; product *= 10; } qu.enqueue(to_string(binary)); } } template<typename Type> void Queue<Type>::sortQueue(Queue<Type> qu) { // Implementation of queue sorting algorithm } template<typename Type> class StackBasedQueue { private: Queue<Type> stackOne, stackTwo; public: /* the idea is that you will create a queue and each enqueue operation you will add the element to the first, if a dequeue operation will add a to a new queue but with a reversed order (it's like you are rebuilding a tower but from top so the bottom will be top and top will be bottom which what we want. */ void push(Type element){ stackOne.enqueue(element); } void dequeue() { if (stackTwo.isEmpty()) { while (!stackOne.isEmpty()) { stackTwo.enqueue(stackOne.dequeuee()); stackOne.pop(); } } stackTwo.dequeuee(); } };
import 'package:flutter/material.dart'; import 'package:loja_virtual/consts.dart'; import 'package:loja_virtual/models/cart_model.dart'; import 'package:loja_virtual/models/user_model.dart'; import 'package:loja_virtual/screens/loguin_screen.dart'; import 'package:loja_virtual/screens/order_screen.dart'; import 'package:loja_virtual/tiles/cart_tile.dart'; import 'package:loja_virtual/widgets/cart_price.dart'; import 'package:loja_virtual/widgets/discount_cart.dart'; import 'package:loja_virtual/widgets/ship_card.dart'; import 'package:scoped_model/scoped_model.dart'; class CartScreen extends StatelessWidget { const CartScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: secundaryColor, centerTitle: true, title: const Text("Meu carrinho"), actions: [ Container( alignment: Alignment.center, padding: const EdgeInsets.only(right: 8.0, top: 1.0), child: ScopedModelDescendant<CartModel>( builder: (context, child, model) { int? p = model.products.length; return Text( "$p ${p == 1 ? "ITEM" : "ITENS"}", style: const TextStyle( fontSize: 17.0, fontWeight: FontWeight.bold), ); }, ), ) ], ), body: ScopedModelDescendant<CartModel>( builder: (context, child, model) { if (model.isLoading && UserModel.of(context).isLoggedIn()) { return const Center( child: CircularProgressIndicator(), ); } else if (!UserModel.of(context).isLoggedIn()) { return Container( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.remove_shopping_cart, size: 80.0, color: Theme.of(context).primaryColor, ), const SizedBox( height: 16.0, ), const Text( "Faça o loguin para adicionar produtos!", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), textAlign: TextAlign.center, ), const SizedBox( height: 16.0, ), TextButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>( Theme.of(context).primaryColor)), onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => const LoguinScreen())); }, child: const Text( "Entrar", style: TextStyle(fontSize: 18.0, color: Colors.white), )) ], ), ); } else if (model.products.isEmpty) { return const Center( child: Text( "Nenhum produto no carrinho!", style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, ), textAlign: TextAlign.center, ), ); } else { return ListView( children: [ Column( children: model.products.map((product) { return CartTile(product); }).toList(), ), const DiscountCart(), const ShipCard(), CartPrice(() async { String? orderId = await model.finishOrder(); if (orderId != null) { Navigator.of(context).pushReplacement(MaterialPageRoute( builder: (context) => OrderScreen(orderId))); } }), ], ); } }, ), ); } }
import { useQuery } from '@tanstack/react-query'; import Slider from 'react-slick'; import useResume from '@/hooks/useResume'; import ResumeSliderItem from '@/components/slider/ResumeSliderItem'; import ResumeSlideLoader from '@/components/loader/ResumeSlideLoader'; import type { resumeType } from '@/types'; import 'slick-carousel/slick/slick.css'; import 'slick-carousel/slick/slick-theme.css'; export default function ResumeSlider() { const { fetchResumes } = useResume(); const { status, data } = useQuery(['fetchResumes'], fetchResumes); const settings = { dots: true, infinite: true, speed: 500, slidesToShow: 2, slidesToScroll: 2, swipeToSlide: true, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 3, slidesToScroll: 3, infinite: true, dots: true, }, }, { breakpoint: 600, settings: { slidesToShow: 2, slidesToScroll: 2, initialSlide: 2, }, }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1, }, }, ], }; return ( <div id="get-started" className="resume-grid relativ mt-6 mb-20"> {status === 'error' ? ( 'unable to fetch resumes' ) : status === 'loading' ? ( <ResumeSlideLoader /> ) : ( <Slider {...settings}> {data.map((item: resumeType) => ( <ResumeSliderItem key={item.name} item={item} /> ))} </Slider> )} </div> ); }
package com.example.otlcse; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.fragment.app.FragmentActivity; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.widget.FrameLayout; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; public class Map extends FragmentActivity implements OnMapReadyCallback { Location currentLocation; FusedLocationProviderClient fusedClient; private static final int REQUEST_CODE = 101; FrameLayout map; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); map = findViewById(R.id.map); fusedClient = LocationServices.getFusedLocationProviderClient(this); getLocation(); } private void getLocation() { if (ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE); return; } Task<Location> task = fusedClient.getLastLocation(); task.addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if (location != null) { currentLocation = location; SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); assert supportMapFragment != null; supportMapFragment.getMapAsync(Map.this); } } }); } @Override public void onMapReady(@NonNull GoogleMap googleMap) { LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()); MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("My Current Location"); googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10)); googleMap.addMarker(markerOptions); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { getLocation(); } } } }
import React, { useState } from "react"; import { Navbar, Nav, Container, Button } from "react-bootstrap"; import { Link } from "react-router-dom"; import { CgGitFork } from "react-icons/cg"; import { ImBlog } from "react-icons/im"; import { AiFillStar, AiOutlineHome, AiOutlineFundProjectionScreen, } from "react-icons/ai"; import { FaBlog } from "react-icons/fa"; import "../../style.css"; import { CgFileDocument } from "react-icons/cg"; export default function MyNav() { const [expand, updateExpanded] = useState(false); const [navColour, updateNavbar] = useState(false); function scrollHandler() { if (window.scrollY >= 20) { updateNavbar(true); } else { updateNavbar(false); } } window.addEventListener("scroll", scrollHandler); return ( <Navbar expanded={expand} fixed="top" expand="md" className={navColour ? "sticky" : "navbar"} > <Container> <Navbar.Brand href="/"> <div className="d-flex flex-row justify-content-between"> <img src="./profile.png" className="img-fluid logo" alt="brand" /> <h5 id="navhead" style={{ marginLeft: "21px", paddingTop: "6px", color: "#fbd9ad", }} > VELISHALA KEERTHANA </h5> </div> </Navbar.Brand> <Navbar.Toggle aria-controls="responsive-navbar-nav" onClick={() => { updateExpanded(expand ? false : "expanded"); }} > <span></span> <span></span> <span></span> </Navbar.Toggle> <Navbar.Collapse id="responsive-navbar-nav" className="navbarmain"> <Nav className="ml-auto" defaultActiveKey="#home"> <Nav.Item> <Nav.Link as={Link} to="/" onClick={() => updateExpanded(false)}> <AiOutlineHome style={{ marginBottom: "2px" }} /> Home </Nav.Link> </Nav.Item> <Nav.Item> <Nav.Link as={Link} to="/projectspage" onClick={() => updateExpanded(false)} > <AiOutlineFundProjectionScreen style={{ marginBottom: "2px" }} />{" "} Projects </Nav.Link> </Nav.Item> <Nav.Item> <Nav.Link as={Link} to="/resume" onClick={() => updateExpanded(false)} > <CgFileDocument style={{ marginBottom: "2px" }} /> Resume </Nav.Link> </Nav.Item> <Nav.Item> <Nav.Link as={Link} to="/certificatepage" onClick={() => updateExpanded(false)} > <ImBlog style={{ marginBottom: "2px" }} /> Certifications </Nav.Link> </Nav.Item> <Nav.Item> <Nav.Link as={Link} to="/blogs" onClick={() => updateExpanded(false)} > <FaBlog style={{ marginBottom: "2px" }} /> Blogs </Nav.Link> </Nav.Item> <Nav.Item className="fork-btn"> <Button href="https://github.com/keerthanavelishala/Personal-Portfolio" target="_blank" className="fork-btn-inner" > <CgGitFork style={{ fontSize: "1.2em" }} />{" "} <AiFillStar style={{ fontSize: "1.1em" }} /> </Button> </Nav.Item> </Nav> </Navbar.Collapse> </Container> </Navbar> ); }
import type { Balances } from 'entities/balance' import type { ReserveName } from 'entities/reserve' import type { AllocationReport } from 'entities/allocation' export const allocateTestCases: Array<{ summary: string allocationRequested?: number allocationRealised?: number initialBalances?: Balances sources?: ReserveName[] destination?: ReserveName expected: AllocationReport }> = [ { summary: 'no input -> empty remport', expected: { newBalances: {} } }, { summary: 'no allocation requests -> empty report', initialBalances: { liquidity: 100 }, sources: ['liquidity'], expected: { newBalances: { liquidity: 100 } } }, { summary: 'no destination requests -> empty report', allocationRequested: 100, initialBalances: { liquidity: 100 }, sources: ['liquidity'], expected: { newBalances: { liquidity: 100 } } }, { summary: 'no initialBalances requests -> empty report', allocationRequested: 100, initialBalances: {}, sources: ['liquidity'], destination: 'payable', expected: { newBalances: {} } }, { summary: '2 allocations from liquidity and flex to payable', allocationRequested: 25, initialBalances: { liquidity: 20, flex: 10, payable: 10 }, sources: ['liquidity', 'flex'], destination: 'payable', expected: { availableCash: 30, allocationRealised: 25, newBalances: { liquidity: 0, flex: 5, payable: 35 }, allocations: [ { source: 'liquidity', destination: 'payable', allocation: 20 }, { source: 'flex', destination: 'payable', allocation: 5 } ] } }, { summary: '1 allocation of 10 from liquidity to payable', allocationRequested: 10, initialBalances: { liquidity: 15, flex: 10, payable: 10 }, sources: ['liquidity', 'flex'], destination: 'payable', expected: { availableCash: 25, allocationRealised: 10, newBalances: { liquidity: 5, flex: 10, payable: 20 }, allocations: [{ source: 'liquidity', destination: 'payable', allocation: 10 }] } }, { summary: '20 to payable for 50 requested due to insufficient cash', allocationRequested: 50, initialBalances: { liquidity: 5, flex: 15, payable: 10 }, sources: ['liquidity', 'flex'], destination: 'payable', expected: { availableCash: 20, allocationRealised: 20, newBalances: { liquidity: 0, flex: 0, payable: 30 }, allocations: [ { source: 'liquidity', destination: 'payable', allocation: 5 }, { source: 'flex', destination: 'payable', allocation: 15 } ] } }, { summary: '20 to base for 50 requested due to insufficient cash', allocationRequested: 50, initialBalances: { liquidity: 5, flex: 15, base: 20 }, sources: ['liquidity', 'flex'], destination: 'base', expected: { availableCash: 20, allocationRealised: 20, newBalances: { liquidity: 0, flex: 0, base: 40 }, allocations: [ { source: 'liquidity', destination: 'base', allocation: 5 }, { source: 'flex', destination: 'base', allocation: 15 } ] } }, { summary: '2 allocations to base:5 from liquidity, 5 from flex', allocationRequested: 50, initialBalances: { liquidity: 5, flex: 5, base: 20 }, sources: ['liquidity', 'flex'], destination: 'base', expected: { availableCash: 10, allocationRealised: 10, newBalances: { liquidity: 0, flex: 0, base: 30 }, allocations: [ { source: 'liquidity', destination: 'base', allocation: 5 }, { source: 'flex', destination: 'base', allocation: 5 } ] } }, { summary: '1 allocations to payable:50 from liquidity', allocationRequested: 50, initialBalances: { liquidity: 1000 }, sources: ['liquidity', 'flex', 'base', 'strategic'], destination: 'payable', expected: { availableCash: 1000, allocationRealised: 50, newBalances: { liquidity: 950, payable: 50, base: 0, strategic: 0, flex: 0 }, allocations: [ { source: 'liquidity', destination: 'payable', allocation: 50 } ] } } ]
<?php use App\Http\Controllers\Auth\ForgotPasswordController; use App\Http\Controllers\Auth\LoginController; use App\Http\Controllers\Auth\LogoutController; use App\Http\Controllers\Auth\RegisterController; use App\Http\Controllers\DashboardController; use App\Http\Controllers\ForgotController; use App\Http\Controllers\PostController; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('home'); })->name('home'); Route::get('/dashboard', [DashboardController::class, 'showPosts'])->name('dashboard'); Route::delete('/delete-post/{id}', [DashboardController::class, 'deletePosts'])->name('delete.post'); Route::post('/logout', [LogoutController::class, 'store'])->name('logout'); Route::get('/login', [LoginController::class, 'index'])->name('login'); Route::post('/login', [LoginController::class, 'store']); Route::get('/register', [RegisterController::class, 'index'])->name('register'); Route::post('/register', [RegisterController::class, 'store']); Route::get('/posts', [PostController::class, 'index'])->name('posts'); Route::post('/posts', [PostController::class, 'store']); Route::get('/forget-password', [ForgotPasswordController::class, 'showForgetPasswordForm'])->name('forget.password.get'); Route::post('/forget-password', [ForgotPasswordController::class, 'submitForgetPasswordForm'])->name('forget.password.post'); Route::get('/reset-password/{token}', [ForgotPasswordController::class, 'showResetPasswordForm'])->name('reset.password.get'); Route::post('/reset-password', [ForgotPasswordController::class, 'submitResetPasswordForm'])->name('reset.password.post');
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { HttpHeaders, HttpResponse } from '@angular/common/http'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { of } from 'rxjs'; import { ImageStoreService } from '../service/image-store.service'; import { ImageStoreComponent } from './image-store.component'; describe('Component Tests', () => { describe('ImageStore Management Component', () => { let comp: ImageStoreComponent; let fixture: ComponentFixture<ImageStoreComponent>; let service: ImageStoreService; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], declarations: [ImageStoreComponent], }) .overrideTemplate(ImageStoreComponent, '') .compileComponents(); fixture = TestBed.createComponent(ImageStoreComponent); comp = fixture.componentInstance; service = TestBed.inject(ImageStoreService); const headers = new HttpHeaders().append('link', 'link;link'); spyOn(service, 'query').and.returnValue( of( new HttpResponse({ body: [{ id: 123 }], headers, }) ) ); }); it('Should call load all on init', () => { // WHEN comp.ngOnInit(); // THEN expect(service.query).toHaveBeenCalled(); expect(comp.imageStores?.[0]).toEqual(jasmine.objectContaining({ id: 123 })); }); }); });
/* This file is part of KDevelop * * Copyright 2010 Niko Sams <[email protected]> * Copyright 2010 Alexander Dymo <[email protected]> * Copyright (C) 2011-2015 Miquel Sabaté Solà <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef RUBY_DECLARATION_BUILDER_H #define RUBY_DECLARATION_BUILDER_H #include <language/duchain/builders/abstractdeclarationbuilder.h> #include <duchain/builders/typebuilder.h> #include <duchain/helpers.h> #include <util/stack.h> namespace ruby { class ModuleDeclaration; class MethodDeclaration; using DeclarationBuilderBase = KDevelop::AbstractDeclarationBuilder<Ast, NameAst, TypeBuilder>; /** * @class DeclarationBuilder * * The DeclarationBuilder iterates a Ast to build declarations. */ class KDEVRUBYDUCHAIN_EXPORT DeclarationBuilder : public DeclarationBuilderBase { public: explicit DeclarationBuilder(EditorIntegrator *editor); ~DeclarationBuilder() override; protected: /// Re-implemented from KDevelop::AbstractDeclarationBuilder. void closeDeclaration() override; void closeContext() override; /// Re-implemented from the ContextBuilder. void startVisiting(Ast *node) override; /// Methods re-implemented from AstVisitor. bool declaredInContext(const QByteArray &name) const override; void visitClassStatement(Ast *node) override; void visitSingletonClass(Ast *node) override; void visitModuleStatement(Ast *node) override; void visitMethodStatement(Ast *node) override; void visitParameter(Ast *node) override; void visitBlock(Ast *node) override; void visitBlockVariables(Ast *node) override; void visitReturnStatement(Ast *node) override; void visitAssignmentStatement(Ast *node) override; void visitAliasStatement(Ast *node) override; void visitMethodCall(Ast *node) override; void visitMixin(Ast *node, bool include) override; void visitForStatement(Ast *node) override; void visitAccessSpecifier(const access_t policy) override; void visitYieldStatement(Ast *node) override; void visitRescueArg(Ast *node) override; private: /// @returns the range of the name of the given @p node. const KDevelop::RangeInRevision getNameRange(const Ast *node) const; /** * Open a context for a class/module declaration. It will also open the * context for the eigen class. * * @param decl The declaration itself. * @param node The node where the declaration resides. */ void openContextForClassDefinition(ModuleDeclaration *decl, Ast *node); /** * Open or re-open if already exists a declaration in the current context. * * @param id The qualified identifier for the declaration. * @param range The range in which the declaration is contained. * @param context The context in which the declaration is being performed. * @returns an opened declaration. It returns nullptr if something * went wrong. */ template<typename T> T * reopenDeclaration(const KDevelop::QualifiedIdentifier &id, const KDevelop::RangeInRevision &range, KDevelop::DUContext *context, DeclarationKind kind = DeclarationKind::Unknown); /** * Open or re-open a method declaration in the current context. This is, * indeed, an specialization of the reopenDeclaration method. * * @param id The qualified identifier for the declaration. * @param range The range in which the declaration is contained. * @param classMethod Set to true of this is a class method, otherwise set * false if this is an instance method. * @returns an opened method declaration. It returns nullptr if something * went wrong. */ MethodDeclaration * reopenDeclaration(const KDevelop::QualifiedIdentifier &id, const KDevelop::RangeInRevision &range, bool classMethod); /** * Declare a variable in the current context. * * @param id The qualified identifier of the new variable declaration. * @param type The type of the new variable declaration. * @param node The node that contains this variable declaration. */ void declareVariable(const KDevelop::QualifiedIdentifier &id, const KDevelop::AbstractType::Ptr &type, Ast *node, KDevelop::DUContext::SearchFlag flags = KDevelop::DUContext::NoSearchFlags); /** * Alias a method declaration. * * @param id The id of the new method. * @param range The range of the new method. * @param decl The MethodDeclaration that it's being aliased. * @note the DUChain *must* be locked before calling this method. */ void aliasMethodDeclaration(const KDevelop::QualifiedIdentifier &id, const KDevelop::RangeInRevision &range, const MethodDeclaration *decl); /// @returns the current access policy. inline KDevelop::Declaration::AccessPolicy currentAccessPolicy() const { if (m_accessPolicy.isEmpty()) { return KDevelop::Declaration::Public; } return m_accessPolicy.top(); } /// Sets the current access policy to the given @p policy. inline void setAccessPolicy(KDevelop::Declaration::AccessPolicy policy) { m_accessPolicy.top() = policy; } /// Module mixins helper methods. /** * Get the module declaration that is being mixed-in. * * @param module The include/extend AST. * @returns the ModuleDeclaration that is being mixed-in, or nullptr if this * module doesn't actually exist. */ ModuleDeclaration * getModuleDeclaration(Ast *module) const; /** * @returns the declared methods inside the given declaration @p decl, * which is a class or a module. */ QList<MethodDeclaration *> getDeclaredMethods(const KDevelop::Declaration *decl); /// other stuff. /** * Check whether the given declaration can be redeclared or not. * * @param decl The declaration to be redeclared. * @param id The id of the declaration. * @param range The range of the declaration. * @param kind The kind that the declaration has to have. * @returns true if it's a valid re-declaration, and false otherwise. */ bool validReDeclaration(KDevelop::Declaration *decl, const KDevelop::QualifiedIdentifier &id, const KDevelop::RangeInRevision &range, DeclarationKind kind); /** * Get the context that contains the name of the class/module being * declared. If the container of the name does not exist, then the * current context is returned. For example, for the following declaration: * * class; A::B; end * * The returned context will be the internal context of A. In this same * example, if A does not exist, then the current context would've been * returned. * @param node The node of the class/module declaration. */ KDevelop::DUContext * getContainedNameContext(Ast *node); /** * This is a helper method that iterates over the call args of a method * call in order to update the type of each parameter accordingly. * @param mc A list of call args. * @param lastMethod The last encountered method call. */ void visitMethodCallArgs(const Ast *mc, const KDevelop::DeclarationPointer &lastMethod); /// @returns true if we're inside a class/module, false otherwise. inline bool insideClassModule() const { return m_classDeclarations.size() > 0; } /// @returns the last class/module. inline KDevelop::Declaration * lastClassModule() const { return m_classDeclarations.top().data(); } private: EditorIntegrator *m_editor; KDevelop::Stack<KDevelop::Declaration::AccessPolicy> m_accessPolicy; KDevelop::Stack<KDevelop::DeclarationPointer> m_classDeclarations; bool m_injected; bool m_instance; KDevelop::Declaration *m_lastMethodCall; }; } #endif // RUBY_DECLARATION_BUILDER_H
<template> <aw-container> <template slot="header">多选</template> <aw-crud :columns="columns" :data="data" selection-row @selection-change="handleSelectionChange"> </aw-crud> <el-card shadow="never" class="aw-mb"> <aw-markdown :source="doc"/> </el-card> <el-card shadow="never" class="aw-mb"> <aw-highlight :code="code"/> </el-card> <aw-link-btn slot="footer" title="文档" link="https://d2.pub/zh/doc/aw-crud-v2"/> </aw-container> </template> <script> import '../install' import doc from './doc.md' import code from './code.js' export default { data () { return { doc, code, columns: [ { title: '日期', key: 'date' }, { title: '姓名', key: 'name' }, { title: '地址', key: 'address' } ], data: [ { date: '2016-05-02', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' }, { date: '2016-05-04', name: '王小虎', address: '上海市普陀区金沙江路 1517 弄' }, { date: '2016-05-01', name: '王小虎', address: '上海市普陀区金沙江路 1519 弄' }, { date: '2016-05-03', name: '王小虎', address: '上海市普陀区金沙江路 1516 弄' } ] } }, methods: { handleSelectionChange (selection) { console.log(selection) } } } </script>
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; namespace Microsoft.ML.Tokenizers { /// <summary>Used as a key in a dictionary to enable querying with either a string or a span.</summary> /// <remarks> /// This should only be used with a Ptr/Length for querying. For storing in a dictionary, this should /// always be used with a string. /// </remarks> internal unsafe readonly struct StringSpanOrdinalKey : IEquatable<StringSpanOrdinalKey> { public readonly char* Ptr; public readonly int Length; public readonly string? Data; public StringSpanOrdinalKey(char* ptr, int length) { Ptr = ptr; Length = length; } public StringSpanOrdinalKey(string data) => Data = data; private ReadOnlySpan<char> Span => Ptr is not null ? new ReadOnlySpan<char>(Ptr, Length) : Data.AsSpan(); public override string ToString() => Data ?? Span.ToString(); public override bool Equals(object? obj) => obj is StringSpanOrdinalKey wrapper && Equals(wrapper); public bool Equals(StringSpanOrdinalKey other) => Span.SequenceEqual(other.Span); public override int GetHashCode() => Helpers.GetHashCode(Span); } internal unsafe readonly struct StringSpanOrdinalKeyPair : IEquatable<StringSpanOrdinalKeyPair> { private readonly StringSpanOrdinalKey _left; private readonly StringSpanOrdinalKey _right; public StringSpanOrdinalKeyPair(char* ptr1, int length1, char* ptr2, int length2) { _left = new StringSpanOrdinalKey(ptr1, length1); _right = new StringSpanOrdinalKey(ptr2, length2); } public StringSpanOrdinalKeyPair(string data1, string data2) { _left = new StringSpanOrdinalKey(data1); _right = new StringSpanOrdinalKey(data2); } public override bool Equals(object? obj) => obj is StringSpanOrdinalKeyPair wrapper && wrapper._left.Equals(_left) && wrapper._right.Equals(_right); public bool Equals(StringSpanOrdinalKeyPair other) => other._left.Equals(_left) && other._right.Equals(_right); public override int GetHashCode() => HashCode.Combine(_left.GetHashCode(), _right.GetHashCode()); } internal sealed class StringSpanOrdinalKeyCache<TValue> { private readonly int _capacity; private readonly Dictionary<StringSpanOrdinalKey, TValue> _map; private object SyncObj => _map; internal StringSpanOrdinalKeyCache() : this(Bpe.DefaultCacheCapacity) { } internal StringSpanOrdinalKeyCache(int capacity) { _capacity = capacity; _map = new Dictionary<StringSpanOrdinalKey, TValue>(capacity); } internal bool TryGetValue(string key, out TValue value) { lock (SyncObj) { return _map.TryGetValue(new StringSpanOrdinalKey(key), out value!); } } internal unsafe bool TryGetValue(ReadOnlySpan<char> key, out TValue value) { lock (SyncObj) { fixed (char* ptr = key) { return _map.TryGetValue(new StringSpanOrdinalKey(ptr, key.Length), out value!); } } } internal void Remove(string key) { lock (SyncObj) { _map.Remove(new StringSpanOrdinalKey(key)); } } internal void Set(string k, TValue v) { lock (SyncObj) { if (_map.Count < _capacity) { _map[new StringSpanOrdinalKey(k)] = v; } } } } /// <summary> /// Custom JSON converter for <see cref="StringSpanOrdinalKey"/>. /// </summary> internal sealed class StringSpanOrdinalKeyConverter : JsonConverter<StringSpanOrdinalKey> { public static StringSpanOrdinalKeyConverter Instance { get; } = new StringSpanOrdinalKeyConverter(); public override StringSpanOrdinalKey ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => new StringSpanOrdinalKey(reader.GetString()!); public override void WriteAsPropertyName(Utf8JsonWriter writer, StringSpanOrdinalKey value, JsonSerializerOptions options) => writer.WriteStringValue(value.Data!); public override StringSpanOrdinalKey Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => new StringSpanOrdinalKey(reader.GetString()!); public override void Write(Utf8JsonWriter writer, StringSpanOrdinalKey value, JsonSerializerOptions options) => writer.WriteStringValue(value.Data!); } internal class StringSpanOrdinalKeyCustomConverter : JsonConverter<Dictionary<StringSpanOrdinalKey, (int, string)>> { public static StringSpanOrdinalKeyCustomConverter Instance { get; } = new StringSpanOrdinalKeyCustomConverter(); public override Dictionary<StringSpanOrdinalKey, (int, string)> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var dictionary = new Dictionary<StringSpanOrdinalKey, (int, string)>(); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return dictionary; } if (reader.TokenType == JsonTokenType.PropertyName) { var key = reader.GetString(); reader.Read(); var value = reader.GetInt32(); dictionary.Add(new StringSpanOrdinalKey(key!), (value, key!)); } } throw new JsonException("Invalid JSON."); } public override void Write(Utf8JsonWriter writer, Dictionary<StringSpanOrdinalKey, (int, string)> value, JsonSerializerOptions options) => throw new NotImplementedException(); } /// <summary> /// Extension methods for <see cref="StringSpanOrdinalKey"/>. /// </summary> internal static class StringSpanOrdinalKeyExtensions { public unsafe static bool TryGetValue<TValue>(this Dictionary<StringSpanOrdinalKey, TValue> map, ReadOnlySpan<char> key, out TValue value) { fixed (char* ptr = key) { return map.TryGetValue(new StringSpanOrdinalKey(ptr, key.Length), out value!); } } public static bool TryGetValue<TValue>(this Dictionary<StringSpanOrdinalKey, TValue> map, string key, out TValue value) => map.TryGetValue(new StringSpanOrdinalKey(key), out value!); public unsafe static bool TryGetValue<TValue>(this Dictionary<StringSpanOrdinalKeyPair, TValue> map, ReadOnlySpan<char> key1, ReadOnlySpan<char> key2, out TValue value) { fixed (char* ptr1 = key1) fixed (char* ptr2 = key2) { return map.TryGetValue(new StringSpanOrdinalKeyPair(ptr1, key1.Length, ptr2, key2.Length), out value!); } } public static bool TryGetValue<TValue>(this Dictionary<StringSpanOrdinalKeyPair, TValue> map, string key1, string key2, out TValue value) => map.TryGetValue(new StringSpanOrdinalKeyPair(key1, key2), out value!); } }
;;; Sierra Script 1.0 - (do not remove this comment) ; ; Contains the Smopper cycler, which is used if you need to specify stopped, slowing and starting views in addition to in-motion views. (script# 17) (include sci.sh) (use Main) (use PFollow) (use Cycle) (use System) (public Smopper 0 ) (define SMOP_INMOTION 0) (define SMOP_SLOW_PENDING 1) (define SMOP_SLOW 2) (define SMOP_STOPPED_PENDING 3) (define SMOP_STOPPED 4) (define SMOP_STARTING_PENDING 5) (define SMOP_STARTING 6) (define SMOP_INMOTION_PENDING 7) (local [local0 8] = [2 6 4 0 3 5 1 7] [local8 8] = [3 6 0 4 2 5 1 7] ) ; ; Smopper is a complex cycler similar to :class:`StopWalk`, but allowing the use ; of separate starting and stopping views. This can be used to allow for more realistic ; movement when starting and stopping. ; ; Example usage:: ; ; // Cycle the boy with view 805 for stopped, 814 for slowing and 815 for starting. Cycle speed is 12. ; (boy:setCycle(Smopper 805 814 815 12)) (class Smopper of Cycle (properties client 0 caller 0 cycleDir 1 cycleCnt 0 completed 0 vInMotion 0 vStopped 0 vSlow 0 vStart 0 stopState 0 useSlow 0 cSpeed 0 oldSpeed 0 newCel 0 tempMover 0 ) ; ; .. function:: init(theClient [theVStopped theVSlow theVStart theCSpeed theCaller]) ; ; Initializes the Smopper. ; ; :param heapPtr theClient: The :class:`Actor` to which this applies. ; :param number theVStopped: The view number for the stopped state. ; :param number theVSlow: The view number for the slowing down state. ; :param number theVStart: The view number for the starting state. ; :param number theCSpeed: The cycle speed used for starting, stopped and stopped. ; :param heapPtr theCaller: Optional object that gets cue(0)'d when stopped, and cue(1)'d when starting motion again. ; (method (init theClient theVStopped theVSlow theVStart theCSpeed theCaller) (= useSlow (= cycleCnt (= vSlow (= vStart (= vStopped (= caller 0)))) ) ) (= cSpeed ((= client theClient) cycleSpeed?)) (= oldSpeed ((= client theClient) cycleSpeed?)) (if argc (= vInMotion ((= client theClient) view?)) (if (>= argc 2) (= vStopped theVStopped) (if (>= argc 3) (= vSlow theVSlow) (if (>= argc 4) (if (== theVStart -1) (= useSlow 1) (= vStart vSlow) else (= vStart theVStart) ) (if (>= argc 5) (if (!= theCSpeed -1) (= cSpeed theCSpeed)) (if (>= argc 6) (= caller theCaller)) ) else (= useSlow 1) (= vStart vSlow) ) ) ) ) (if (client isStopped:) (if vSlow (= stopState SMOP_SLOW_PENDING) else (= stopState SMOP_STOPPED_PENDING) ) else (= stopState SMOP_INMOTION_PENDING) ) (super init: client) ) (method (doit &tmp temp0 clientMover [temp2 10]) (cond ( (or (client isStopped:) (client isBlocked:) (not (client mover?)) ) (if (== (client view?) vInMotion) (cond ((and vSlow (IsOneOf stopState SMOP_INMOTION)) (= stopState SMOP_SLOW_PENDING)) ( (and vSlow (== stopState SMOP_STOPPED) (== vStopped -1) (!= (client loop?) (- (NumLoops client) 1)) ) (= stopState SMOP_SLOW_PENDING) ) ( (and (not vSlow) (IsOneOf stopState SMOP_INMOTION)) (= stopState SMOP_STOPPED_PENDING)) ( (not (IsOneOf stopState SMOP_SLOW SMOP_STOPPED_PENDING SMOP_SLOW_PENDING ) ) (= stopState SMOP_STOPPED) ) ) (= clientMover (client mover?)) (if (and clientMover (not ((= clientMover (client mover?)) completed?)) (not (clientMover isKindOf: PFollow)) ) (client setMotion: 0) ) ) ) ( (IsOneOf stopState SMOP_STOPPED SMOP_SLOW SMOP_STOPPED_PENDING SMOP_SLOW_PENDING ) (if vStart (= stopState SMOP_STARTING_PENDING) else (= stopState SMOP_INMOTION_PENDING) ) ) ) (switch stopState (SMOP_INMOTION ; Just keep cycling forward (= cycleDir 1) (= newCel (self nextCel:)) (if (> newCel (client lastCel:)) (= newCel 0)) (client cel: newCel) ) (SMOP_SLOW_PENDING ; If there's no slowing view set state to 3. ; If there is a slowing view, set state to 2 and set the slowing view (and cSpeed) (= cycleDir 1) (if (not vSlow) (if (!= vStopped -1) (client view: vStopped)) (= stopState SMOP_STOPPED_PENDING) else (= stopState SMOP_SLOW) (if (== (client view?) vInMotion) (= newCel 0) (client cel: 0) ) (client cycleSpeed: cSpeed view: vSlow) ) ) (SMOP_SLOW ; If we reach the last cel, set state to 3 (client cycleSpeed: cSpeed) (client cel: newCel forceUpd:) (= newCel (self nextCel:)) (if (> newCel (client lastCel:)) (= newCel 0) (= stopState SMOP_STOPPED_PENDING) ) ) (SMOP_STOPPED_PENDING (client cycleSpeed: cSpeed) (= stopState SMOP_STOPPED) (= cycleDir 1) (if (== vStopped -1) (client view: vInMotion cel: (client loop?)) (client loop: (- (NumLoops client) 1)) else (client view: vStopped cel: 0) ) (if caller (caller cue: 0)) ) (SMOP_STOPPED (if (!= vStopped -1) (client cycleSpeed: cSpeed) (if (client lastCel:) (= newCel (self nextCel:)) (if (> newCel (client lastCel:)) (= newCel 0)) (client cel: newCel) else 0 ) ) ) (SMOP_STARTING_PENDING (if caller (caller cue: 1)) (if (not vStart) (client view: vInMotion) (= stopState SMOP_INMOTION_PENDING) else (= stopState SMOP_STARTING) (if (== vStopped -1) (client loop: (client cel?))) (if useSlow (= cycleDir -1) (client cel: (client lastCel:) view: vSlow) else (= cycleDir 1) (client cel: 0 view: vStart) ) (client cycleSpeed: cSpeed) ) ) (SMOP_STARTING (client cycleSpeed: cSpeed) (if useSlow (if (not newCel) (= stopState SMOP_INMOTION_PENDING) else (client cel: newCel) ) (= newCel (self nextCel:)) else (= newCel (self nextCel:)) (if (> newCel (client lastCel:)) (= stopState SMOP_INMOTION_PENDING) else (client cel: newCel) ) ) ) (7 (= stopState SMOP_INMOTION) (= cycleDir 1) (if (client mover?) (= cycleCnt ((client mover?) b-moveCnt?)) ) (if (== vStopped -1) (client setLoop: -1) (if (== (client loop?) (- (NumLoops client) 1)) (client view: vInMotion loop: [local8 (/ (client heading?) 45)] ) ) ) (= oldSpeed gGEgoMoveSpeed) (client view: vInMotion cycleSpeed: oldSpeed cel: 0) ) ) ) (method (dispose) (client cycleSpeed: oldSpeed) (if (IsObject client) (client cycler: 0)) (self client: 0) (super dispose: &rest) ) )