text
stringlengths
184
4.48M
/* Copyright 2020-2021 Dennis Rohde 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 <typeinfo> #include "curve.hpp" #include "simplification.hpp" Curve::Curve(const Points &points, const std::string &name) : Points(points), vstart{0}, vend{points.size() - 1}, name{name} { if (points.empty()) { std::cerr << "warning: constructed empty curve" << std::endl; return; } #if DEBUG std::cout << "constructed curve of complexity " << points.size() << std::endl; #endif } Curves Curves::simplify(const curve_size_t l, const bool approx = false) { Curves result(size(), l, Curves::dimensions()); for (curve_number_t i = 0; i < size(); ++i) { if (approx) { Curve simplified_curve = Simplification::approximate_minimum_error_simplification(std::vector<Curve>::operator[](i), l); simplified_curve.set_name("Simplification of " + std::vector<Curve>::operator[](i).get_name()); result[i] = simplified_curve; } else { Simplification::Subcurve_Shortcut_Graph graph(std::vector<Curve>::operator[](i)); Curve simplified_curve = graph.minimum_error_simplification(l); simplified_curve.set_name("Simplification of " + std::vector<Curve>::operator[](i).get_name()); result[i] = simplified_curve; } #if DEBUG std::cout << "Simplified curve " << i + 1 << "/" << size() << "." << std::endl; #endif } return result; } std::string Curve::repr() const { std::stringstream ss; ss << "fred.Curve '" << name << "' of complexity " << complexity() << " and " << dimensions() << " dimensions"; return ss.str(); } std::string Curves::repr() const { std::stringstream ss; ss << "fred.Curves collection with " << number() << " curves"; return ss.str(); } std::string Curve::str() const { std::stringstream ss; ss << name << std::endl; ss << *this; return ss.str(); } std::string Curves::str() const { std::stringstream ss; ss << *this; return ss.str(); } std::string Curve::get_name() const { return name; } void Curve::set_name(const std::string &name) { this->name = name; } std::ostream& operator<<(std::ostream &out, const Curve &curve) { if (curve.empty()) return out; out << "["; for (curve_size_t i = 0; i < curve.complexity() - 1; ++i) { out << curve[i] << ", "; } out << curve[curve.complexity() -1] << "]"; return out; } std::ostream& operator<<(std::ostream &out, const Curves &curves) { if (curves.empty()) return out; out << "{"; for (curve_number_t i = 0; i < curves.number() - 1; ++i) { out << curves[i] << ", "; } out << curves[curves.size() -1] << "}"; return out; }
<template> <v-layout row justify-center> <v-dialog v-model="dialog" scrollable persistent max-width="650px" :fullscreen="$vuetify.breakpoint.xsOnly" id="show-loading-create-question-dialog-container"> <div class="show-loading-create-question-dialog" v-if="loading"> <v-progress-circular indeterminate color="primary"></v-progress-circular> </div> <show-instruction @close-dialog="closeInstruction" class="show-instruction-container" v-else-if="(showInstruction && !hasAskedQuestion) || showInstructionAgain" @next="showQuestion"> <div slot="header"> <div id="dumonda-me-dialog-header"> {{$t('pages:question.instructionDialog.title')}} </div> <v-divider></v-divider> </div> </show-instruction> <create-question-dialog-content @close-dialog="$emit('close-dialog')" v-else @open-instruction="showInstructionAgain = true" :init-question="$store.getters['createQuestion/getQuestionCopy']"> </create-question-dialog-content> </v-dialog> </v-layout> </template> <script> import ShowInstruction from './Instruction'; import CreateQuestionDialogContent from './CreateQuestionDialogContent'; export default { data() { return {dialog: true, showInstruction: true, showInstructionAgain: false, loading: false} }, async created() { try { this.loading = true; this.$store.commit('createQuestion/RESET'); await this.$store.dispatch('createQuestion/getHasQuestionCreated'); } catch (e) { } finally { this.loading = false; } }, components: {CreateQuestionDialogContent, ShowInstruction}, methods: { closeInstruction() { if (this.showInstructionAgain) { this.showInstructionAgain = false; this.showInstruction = false; } else { this.$emit('close-dialog'); } }, showQuestion() { this.showInstruction = false; this.showInstructionAgain = false } }, computed: { hasAskedQuestion() { return this.$store.state.createQuestion.hasAskedQuestion; } } } </script> <style lang="scss"> #show-loading-create-question-dialog-container { .show-loading-create-question-dialog { width: 100%; min-height: 400px; } .show-instruction-container { width: 100%; } } </style>
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Train { class Program { private static Deque<Train> trains = new Deque<Train>(); // този път ще пазим историята тук, така Deque е по-универсален клас private static Stack<Train> history = new Stack<Train>(); private static void Add(int number, string name, string type, int cars) { if (type == "F") { trains.AddBack(new Train(number, name, type, cars)); } else { trains.AddFront(new Train(number, name, type, cars)); } } private static void Travel() { if (trains.Count > 0) { Train frontTrain = trains.GetFront(); Train backTrain = trains.GetBack(); if (backTrain != null && backTrain.Type == "F" && backTrain.Cars > 15) { // когато замине влак, той отива в историята history.Push(backTrain); Console.WriteLine(trains.RemoveBack()); } else if (frontTrain != null && frontTrain.Type == "P") { history.Push(frontTrain); Console.WriteLine(trains.RemoveFront()); } else if (backTrain != null && backTrain.Type == "F") { history.Push(backTrain); Console.WriteLine(trains.RemoveBack()); } } } private static void Next() { if (trains.Count > 0) { Train frontTrain = trains.GetFront(); Train backTrain = trains.GetBack(); if (backTrain != null && backTrain.Type == "F" && backTrain.Cars > 15) { Console.WriteLine(backTrain); } else if (frontTrain != null && frontTrain.Type == "P") { Console.WriteLine(frontTrain); } else if (backTrain != null && backTrain.Type == "F") { Console.WriteLine(backTrain); } } } private static void History() { // ако ги вземем с Pop(), ще изчезнат от history Train[] trains = history.ToArray<Train>(); foreach(var t in trains) { Console.WriteLine(t); } } static void Main(string[] args) { Console.WriteLine("INPUT:"); var standartOutput = Console.Out; var standartError = Console.Error; var bufferOutput = new StringWriter(); Console.SetOut(bufferOutput); Console.SetError(bufferOutput); Console.WriteLine(); Console.WriteLine("OUTPUT:"); string[] command; do { command = Console.ReadLine().Split(' ').ToArray(); switch (command[0]) { case "Add": Add(int.Parse(command[1]), command[2], command[3], int.Parse(command[4])); break; case "Travel": Travel(); break; case "Next": Next(); break; case "History": History(); break; } } while (command[0] != "End"); Console.SetOut(standartOutput); Console.SetError(standartError); Console.Write(bufferOutput.ToString()); } } }
data_prep <- function(x) { x_prep <- x |> mutate( IDADE = if_else( grepl("anos", IDADE), str_sub(IDADE,1,3), "0" ), IDADE = as.numeric(IDADE), ESC_DECOD = factor( ESC_DECOD, levels = c( "nenhuma", "1 a 3 anos", "4 a 7 anos", "8 a 11 anos", "12 a mais" ) ) ) |> drop_na() |> select(IDADE, RACACOR, SEXO, ESTCIV, LOCOCOR, ESC_DECOD, MOTOCICLISTA) |> rename( idade = IDADE, cor = RACACOR, sexo = SEXO, estado_civil = ESTCIV, local_obito = LOCOCOR, escolaridade = ESC_DECOD, motociclista = MOTOCICLISTA) |> mutate( across(c(cor, sexo, estado_civil, local_obito), as_factor), motociclista = factor(motociclista, levels = c("nao","sim")) ) return(x_prep) } train_test_split <- function(x) { #set seed set.seed(123) #separar em teste e treino inicial data_split <- initial_split(x, prop = 0.8) train_split <- training(data_split) test_split <- testing(data_split) return(list(train = train_split, test = test_split)) } get_best_cvfold <- function(x) { metrix <- metric_set(accuracy, precision, sens, roc_auc) log_model <- logistic_reg(mixture = 1) |> set_engine("glm") prep_steps <- recipe(motociclista ~ ., x) |> step_dummy(all_nominal_predictors()) data_folds <- vfold_cv(data = x) log_wflow <- workflow() |> add_recipe(prep_steps) |> add_model(log_model) log_cvfit <- fit_resamples( object = log_wflow, resamples = data_folds, metrics = metrix ) best_fold_id <- log_cvfit |> collect_metrics(summarize = FALSE) |> pivot_wider(names_from = .metric, values_from = .estimate) |> select(-.estimator, -.config) |> mutate(mean = (accuracy + precision + sens + roc_auc)/4) |> filter(mean == max(mean)) |> pull(id) |> str_sub(-1,) |> as.numeric() best_fold <- analysis(log_cvfit$splits[[best_fold_id]]) return(best_fold) } log_modeller <- function(x, test) { log_model <- logistic_reg(mixture = 1) |> set_engine("glm") prep_steps <- recipe(motociclista ~ ., x) |> step_dummy(all_nominal_predictors()) log_wflow <- workflow() |> add_recipe(prep_steps) |> add_model(log_model) log_fit <- log_wflow |> fit(x) log_preds <- log_fit |> predict(test) |> bind_cols(test) metricas <- metric_set(accuracy, precision, sens) metricas_res <- metricas( log_preds, truth = motociclista, estimate = .pred_class ) coefs <- log_fit |> tidy() |> mutate(odds = exp(estimate)) return(list( predictions = log_preds, metrics = metricas_res, coefs = coefs, fit = log_fit )) }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/Css/style.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer"/> <title>Product Design Landing Page</title> </head> <body> <div class="main-div"> <div class="header"> <div class="navbar"> <div class="navbar-logo"> <img src="/Images/logo.svg" alt=""> </div> <div class="grow"> <ul class="list"> <li class="list-item">HOME</li> <li class="list-item">PROJECT</li> <li class="list-item">ABOUT</li> <li class="list-item">CONTACT</li> <li class="list-item">OTHER PAGE</li> </ul> </div> <i class="fa-solid fa-bars barss "></i> </div> <div class="about"> <div class="person-img"> <img src="/Images/person.png" alt=""> </div> <div class="person-description"> <h4>Hello i'm Shivaram</h4> <h2>Frontend Developer</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis placeat quas eligendi molestiae voluptatibus tempora dolorum totam, enim, delectus rerum, cupiditate fugiat? Fugiat provident.</p> <button>ABOUT ME</button> </div> </div> </div> <div class="design-client-section"> <div class="design-section"> <div class="section"> <img src="/Images/ui.svg" alt="UI"> <h4>UI Design</h4> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> <a href="#">KNOW MORE <i class="fa-solid fa-arrow-right"></i></a> </div> <div class="section"> <img src="/Images/product.svg" alt="UI"> <h4>Product Design</h4> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> <a href="#" class="white-a">KNOW MORE <i class="fa-solid fa-arrow-right"></i></a> </div> <div class="section"> <img src="/Images/branding.svg" alt="UI"> <h4>Branding</h4> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> <a href="#">KNOW MORE <i class="fa-solid fa-arrow-right"></i></a> </div> </div> <div class="client-section"> <div class="section-one"> <h2>12</h2> <h3>Years Experience</h3> </div> <div class="section-two"> <div class="section21"> <h3>60+</h3> <h5>Clients</h5> </div> <div class="section21"> <h3>122+</h3> <h5>Completed Projects</h5> </div> </div> <div class="section-two"> <div class="section21"> <h3>08</h3> <h5>Years Experience</h5> </div> <div class="section21"> <h3>10</h3> <h5>Achivements</h5> </div> </div> </div> </div> <div class="projects"> <div class="project-heading"> <div class="heading"> <h2>FEATURED PROJECTS</h2> <h6>Lorem ipsum dolor sit amet consectetur adipisicing elit.</h6> </div> <button>VIEW ALL</button> </div> <div class="project-description"> <div class="project"> <img src="/Images/pic-1.jpg" alt="image1"> <h3>The Vintage</h3> <a href="#">KNOW MORE <i class="fa-solid fa-arrow-right"></i></a> </div> <div class="project"> <img src="/Images/pic-2.jpg" alt="image1"> <h3>Foodasa</h3> <a href="#">KNOW MORE <i class="fa-solid fa-arrow-right"></i></a> </div> </div> <div class="project-description"> <div class="project"> <img src="/Images/pic-3.jpg" alt="image1"> <h3>Macro Accent</h3> <a href="#">KNOW MORE <i class="fa-solid fa-arrow-right"></i></a> </div> <div class="project"> <img src="/Images/pic-4.jpg" alt="image1"> <h3>Mozaik</h3> <a href="#">KNOW MORE <i class="fa-solid fa-arrow-right"></i></a> </div> </div> <div class="contact"> <div class="contact-left"> <h2>Let's work together on <br> your next project</h2> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Deleniti, minima.</p> </div> <div class="contact-right"> <button>Contact</button> </div> </div> <div class="buttom-nav"> <ul> <li>Home</li> <li>About</li> <li>Projects</li> <li>Contact</li> </ul> </div> </div> </div> <div class="bottom-social"> <div class="bottom-social-logo"> <img src="/Images/logo.svg" alt=""> </div> <div class="bottom-social-icons"> <img src="/Images/fb.svg" alt=""> <img src="/Images/twitter.svg" alt=""> <img src="/Images/youtube.svg" alt=""> </div> </div> </body> </html>
import { useState } from 'react'; import Loader from '../../../../components/Loader'; import AddButton from '../../../../components/AddButton'; import TrashButtonMini from '../../../../components/TrashButtonMini'; import ConfirmModal from '../../../../utils/modal/ConfirmModal'; import InfoModal from '../../../../utils/modal/InfoModal'; import api from '../../../../packages/api'; const ManagersSection = (props) => { /* PROPS: props.managers */ let [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false); let [confirmModalData, setConfirmModalData] = useState(null); let [isModalOpen, setIsModalOpen] = useState(false); let [modalData, setModalData] = useState(null); let closeModal = () => { setIsModalOpen(false); } let onDeleteItem = (data) => { setIsConfirmModalOpen(false); api.managers.remove({id: data}).then(result => { if (result.data.success) { setModalData({content: "<p>Управляющий успешно удалён</p>"}); setIsModalOpen(true); let index = props.managers.findIndex(item => item.idAdmin == data); props.managers.splice(index, 1); } else { setModalData({content: "<p>" + result.data.message + "</p>"}); setIsModalOpen(true); } }); } let confirmModalDataGeneral = { heading: "Подтверждение действия", text: "Уверены, что хотите удалить управляющего?", buttonTextAgree: "Да, удалить", onAgree: onDeleteItem, onCancel: () => setIsConfirmModalOpen(false), data: null } let deleteItem = (itemId) => { setIsConfirmModalOpen(true); confirmModalDataGeneral.data = itemId; setConfirmModalData(confirmModalDataGeneral); } return ( <div className="ManagersSection"> <h3 className="mb-3">Управляющие</h3> {props.id ? <AddButton to="add-manager" state={{idFranchisee: props.id}} name="Создать управляющего" /> : ""} <div className="table-responsive mt-3"> <table className="table table-hover"> <thead> <tr> <th scope="col">ФИО</th> <th scope="col">Список подразделений</th> <th scope="col">Действия</th> </tr> </thead> <tbody> {props.managers ? props.managers.map((item, key) => <tr key={key}> <th scope="row">{item.fio}</th> <td> {item.filials.length ? <ul> {item.filials.map((filialItem, filialKey) => <li key={filialKey}>{filialItem}</li> )} </ul> : "Не привязан ни к одному" } </td> <td> <TrashButtonMini onClick={() => deleteItem(item.idAdmin)} /> </td> </tr> ) : <tr> <td colSpan="3" className="text-center"><Loader /></td> </tr> } {props.managers && !props.managers.length ? <tr> <td colSpan="3" className="text-center">Ничего нет</td> </tr> : null} </tbody> </table> </div> <ConfirmModal isOpen={isConfirmModalOpen} {...confirmModalData} /> <InfoModal isOpen={isModalOpen} onCancel={() => closeModal()} {...modalData} /> </div> ); } export default ManagersSection;
package cmd import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/nikoksr/dbench/internal/build" "github.com/nikoksr/dbench/internal/mocks" ) // Test for determineDefaultDataPath func TestDetermineDefaultDataPath(t *testing.T) { t.Parallel() appName := "testapp" // Test cases tests := []struct { name string envDataDir string homeDir string homeDirErr error expectedDataDir string expectErr bool }{ { name: "env set", envDataDir: "/custom/dir", expectedDataDir: "/custom/dir", expectErr: false, }, { name: "standard path", homeDir: "/home/user", expectedDataDir: "/home/user/.local/share/testapp", expectErr: false, }, { name: "home dir error", homeDirErr: fmt.Errorf("error"), expectErr: true, }, } for _, tc := range tests { tc := tc // capture range variable t.Run(tc.name, func(t *testing.T) { t.Parallel() mockFS := new(mocks.MockFileSystem) mockEnv := new(mocks.MockEnvironment) mockEnv.On("Getenv", envDataDir).Return(tc.envDataDir) if tc.envDataDir == "" { mockFS.On("UserHomeDir").Return(tc.homeDir, tc.homeDirErr).Once() } dataDir, err := determineDefaultDataPath(appName, mockEnv, mockFS) if (err != nil) != tc.expectErr { t.Errorf("determineDefaultDataPath() error = %v, expectErr %v", err, tc.expectErr) return } if err == nil && dataDir != tc.expectedDataDir { t.Errorf("determineDefaultDataPath() = %v, want %v", dataDir, tc.expectedDataDir) } mockEnv.AssertExpectations(t) mockFS.AssertExpectations(t) }) } } func TestBuildDSN(t *testing.T) { t.Parallel() // return "file:" + filepath.Join(dataDir, build.AppName) + ".db" // Test cases tests := []struct { name string dataDir string expected string }{ { name: "valid path", dataDir: "/path/to/data", expected: "file:/path/to/data/" + build.AppName + ".db", }, { name: "empty path", dataDir: "", expected: "file:" + build.AppName + ".db", }, } for _, tc := range tests { tc := tc // capture range variable t.Run(tc.name, func(t *testing.T) { t.Parallel() dsn := getDefaultDSN(tc.dataDir) assert.Equal(t, tc.expected, dsn) }) } }
import java.util.Iterator; import java.util.NoSuchElementException; /** * This class implements unit test methods to check the correctness of Song, LinkedNode, SongPlayer * ForwardSongIterator and BackwardSongIterator classes in P07 Iterable Song Player assignment. * */ public class SongPlayerTester { /** * This method test and make use of the Song constructor, an accessor (getter) method, * overridden method toString() and equal() method defined in the Song class. * * @return true when this test verifies a correct functionality, and false otherwise */ public static boolean testSong() { Song a=new Song("a","aa","1:06"); Song b=new Song("aa","aaa","1:16"); if(!a.getSongName().equals("a")) return false; if(!a.getArtist().equals("aa")) return false; if(!a.getDuration().equals("1:06")) return false; if(!a.toString().equals("a---aa---1:06")) return false; if(a.equals(b)) return false; return true; } /** * This method test and make use of the LinkedNode constructor, an accessor * (getter) method, and a mutator (setter) method defined in the LinkedCart class. * * @return true when this test verifies a correct functionality, and false otherwise */ public static boolean testLinkedNode() { LinkedNode<Integer> n1 = new LinkedNode<>(null, 1, null); LinkedNode<Integer> n2 = new LinkedNode<>(n1, 3, null); n1.setNext(n2); LinkedNode a=new LinkedNode(n1,2,n2); Integer expPrev=new Integer("1"); Integer expNext=new Integer("3"); if(!a.getPrev().getData().equals(expPrev)) return false; if(!a.getNext().getData().equals(expNext)) return false; LinkedNode<Integer> x1 = new LinkedNode<>(null, 9, null); LinkedNode<Integer> x2 = new LinkedNode<>(x1, 7, null); x1.setNext(x2); a.setPrev(x1) ; Integer xPrev=new Integer("9"); if(!a.getPrev().getData().equals(xPrev)) return false; a.setNext(x2); Integer xNext=new Integer("7"); if(!a.getNext().getData().equals(xNext)) return false; return true; } /** * This method checks for the correctness of addFirst(), addLast() and add(int index) * method in SongPlayer class * * @return true when this test verifies a correct functionality, and false otherwise */ public static boolean testSongPlayerAdd(){ //System.out.print("1"); //check exceptions SongPlayer a=new SongPlayer(); // System.out.print("1"); Song b=new Song("aa","aaa","1:06"); Song c=new Song("aab","aaab","1:07"); // System.out.print("1"); Song d=new Song("aad","aaad","1:08"); //System.out.print("1"); Song wrong=null; // System.out.print("1"); System.out.println(a.size()); a.add​(0,b); System.out.println(a.getFirst()); a.addFirst​(c); // System.out.print("1"); System.out.println(a.size()); System.out.println(a.getFirst()); a.addLast​(d); System.out.println(a.getLast()); System.out.println(a.size()); System.out.println(a.getFirst()); System.out.print("122"); //cbd try{ a.add​(0,wrong); return false; }catch(NullPointerException e) { }catch(Exception e1) { return false; } try{ a.addFirst​(wrong); return false; }catch(NullPointerException e) { }catch(Exception e1) { return false; } System.out.print("122"); try{ a.addLast​(wrong); return false; }catch(NullPointerException e) { }catch(Exception e1) { return false; } if(!a.getFirst().equals(c)) { System.out.println("size"+a.getFirst()); return false; } if(!a.getLast().equals(d)) { return false; } if(!a.get​(1).equals(b)) { return false; } return true; } /** * This method checks for the correctness of getFirst(), getLast() and get(int index) * method in SongPlayer class * * @return true when this test verifies a correct functionality, and false otherwise */ public static boolean testSongPlayerGet() { //check exceptions SongPlayer a=new SongPlayer(); Song b=new Song("aa","aaa","1:06"); Song c=new Song("aab","aaab","1:07"); Song d=new Song("aad","aaad","1:08"); a.add​(0,b); a.addFirst​(c); a.addLast​(d); if(!a.getFirst().equals(c)) { return false; } if(!a.getLast().equals(d)) { return false; } if(!a.get​(2).equals(d)) { return false; } try { a.get​(-1); return false; }catch(IndexOutOfBoundsException e) { }catch(Exception e1) { return false; } return true; } /** * This method checks for the correctness of removeFirst(), removeLast() and remove(int index) * method in SongPlayer class * * @return true when this test verifies a correct functionality, and false otherwise */ public static boolean testSongPlayerRemove() { SongPlayer a=new SongPlayer(); Song b=new Song("aa","aaa","1:06"); Song c=new Song("aab","aaab","1:07"); Song d=new Song("aad","aaad","1:08"); a.addLast​(b); a.addLast​(c); a.addLast​(d); try {a.remove​(-1); return false; }catch(IndexOutOfBoundsException e1) { }catch(Exception e2) { return false; } a.removeFirst(); System.out.print(a.size()); a.remove​(0); System.out.print(a.size()); a.removeLast(); System.out.print(a.size()); if(a.size()!=0) { System.out.print(a.size()); return false;} return true; } /** * This method checks for the correctness of iterator(), switchPlayingDirection() and String * play() * method in SongPlayer class * * @return true when this test verifies a correct functionality, and false otherwise */ public static boolean testSongPlayerIterator() { SongPlayer a=new SongPlayer(); Song b=new Song("aa","aaa","1:06"); Song c=new Song("aab","aaab","1:07"); a.addLast​(b); a.addLast​(c); a.iterator(); String check=a.play(); if(!check.equals("aa---aaa---1:06"+"\n"+"aab---aaab---1:07"+"\n")) { return false;} a.switchPlayingDirection(); a.iterator(); String check2=a.play(); if(!check2.equals("aab---aaab---1:07"+"\n"+"aa---aaa---1:06"+"\n")){ System.out.println(check2); return false; } return true; } /** * This method checks for the correctness of contains(Object song), clear(), * isEmpty()and size() method in SongPlayer class * * @return true when this test verifies a correct functionality, and false otherwise */ public static boolean testSongPlayerCommonMethod() { SongPlayer a=new SongPlayer(); Song b=new Song("aa","aaa","1:06"); Song c=new Song("aab","aaab","1:07"); Song d=new Song("aad","aaad","1:08"); a.addLast​(b); a.addLast​(c); a.addLast​(d); if(a.size()!=3) return false; if(a.contains​(b)==false) return false; a.clear(); if(a.size()!=0) return false; if(a.isEmpty()==false) return false; return true; } /** * This method checks for the correctness of ForwardSongIterator class * * @return true when this test verifies a correct functionality, and false otherwise */ public static boolean testForwardSongIterator() { LinkedNode<Song> first=new LinkedNode<Song>(null,null,null); ForwardSongIterator a=new ForwardSongIterator(first); if(a.hasNext()==false) { // System.out.print("1"); return false;} Song song=null; song=a.next(); if(first.getData()!=song) { // System.out.print("1"); return false; } LinkedNode<Song> next=null; ForwardSongIterator ab=new ForwardSongIterator(next); try { ab.next(); // System.out.print("1"); return false; }catch(NoSuchElementException e) { }catch(Exception e1) { // System.out.print("1"); return false; } return true; } /** * This method checks for the correctness of BackwardSongIterator class * * @return true when this test verifies a correct functionality, and false otherwise */ public static boolean testBackwardSongIterator() { LinkedNode<Song> first=new LinkedNode<Song>(null,null,null); ForwardSongIterator a=new ForwardSongIterator(first); if(a.hasNext()==false) return false; Song song=null; song=a.next(); if(first.getData()!=song) return false; LinkedNode<Song> next=null; ForwardSongIterator ab=new ForwardSongIterator(next); try { ab.next(); return false; }catch(NoSuchElementException e) { }catch(Exception e1) { return false; } return true; } /** * This method calls all the test methods defined and implemented in your SongPlayerTester * class. * * @return true if all the test methods defined in this class pass, and false otherwise. */ public static boolean runAllTests() { return testSong()&&testLinkedNode() &&testSongPlayerAdd()&& testSongPlayerGet() &&testSongPlayerRemove() &&testSongPlayerIterator()&& testSongPlayerCommonMethod() && testForwardSongIterator() &&testBackwardSongIterator(); } /** * Driver method defined in this SongPlayerTester class * * @param args input arguments if any. */ public static void main(String[] args) { System.out.println( runAllTests() ); } }
import {useEffect, useState} from "react"; import {DeathType} from "../api/models/DeathType"; import {add_death_type, get_deaths_types} from "../api/Routes"; import {NumericOption} from "../components/shared/formUtils/formUtils"; export const useDeathTypes = () => { const [deathTypes, setDeathTypes] = useState<DeathType[]>([]); const [deathTypeOptions, setDeathTypeOptions] = useState<NumericOption[]>([]); useEffect(() => { refreshDeathTypes(); }, []); const refreshDeathTypes = () => { fetch(get_deaths_types()) .then((response) => { return response.json(); }) .then((json) => { const newDeathTypes = json as DeathType[]; setDeathTypes(newDeathTypes); const newDeathTypeOptions: NumericOption[] = []; newDeathTypes.forEach(d => { const option: NumericOption = { label: d.name, value: d.id, }; newDeathTypeOptions.push(option); }); setDeathTypeOptions(newDeathTypeOptions); }); }; const addDeathType = (deathType: DeathType) => { fetch(add_death_type(), { method: 'POST', headers:{ accept: 'application/json', 'User-agent': 'learning app', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify(deathType), }) .then(()=> { refreshDeathTypes() }); } const getDeathTypeById = (id: number): DeathType | undefined => { return deathTypes.find(d => d.id === id) || undefined; } return { deathTypes, deathTypeOptions, refreshDeathTypes, addDeathType, getDeathTypeById } }
import React, { useEffect, useState } from "react"; import axios from "../api/axios"; import useAuth from "../hooks/useAuth"; import { useParams } from "react-router-dom"; import useThesis from "../hooks/useThesis"; import AddSubjectModal from "../components/AddSubjectModal"; import SubjectModal from "../components/SubjectModal"; import { FaBook, FaPlusSquare } from "react-icons/fa"; import LoadingSpinner from "../components/LoadingSpinner"; const ManageSubjects = () => { const [loading, setLoading] = useState(); const { auth, setAuth } = useAuth(); const { thesisParams, setThesisParams } = useThesis(); const [selectedSubject, setSelectedSubject] = useState(null); const [isModalOpen, setIsModalOpen] = useState(false); const [isChanged, setIsChanged] = useState(); const getAllParams = async () => { try { setLoading(true); const subjectResponse = await axios.get("/api/v1/subject", { headers: { Authorization: `Bearer ${auth.accessToken}`, }, }); setThesisParams((prevParams) => ({ ...prevParams, subjects: subjectResponse.data.data, })); setLoading(false); } catch (error) { console.error("Error fetching data:", error); setLoading(false); } }; const openModal = () => { setIsModalOpen(true); }; const closeModal = () => { setIsModalOpen(false); }; const closeSubjectModal = () => { setSelectedSubject(null); }; const openSubjectModal = (subject) => { setSelectedSubject(subject); }; useEffect(() => { thesisParams.subjects.length < 1 && getAllParams(); }, []); useEffect(() => { isChanged && getAllParams(); }, [isChanged]); return ( <div className="w-full h-full"> {isModalOpen && ( <AddSubjectModal isChanged={isChanged} setIsChanged={setIsChanged} closeModal={closeModal} /> )} {selectedSubject && ( <SubjectModal subject={selectedSubject} isChanged={isChanged} setIsChanged={setIsChanged} closeModal={closeSubjectModal} /> )} { loading ? <div className="w-screen h-screen ml-[-30px] flex items-center justify-center"> <LoadingSpinner /> </div> : <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3"> {thesisParams?.subjects?.map((subject) => ( <div onClick={() => openSubjectModal(subject)} key={subject.subject_id} className="bg-white transition hover:scale-105 cursor-pointer hover:shadow-2xl shadow-lg p-5 rounded m-6 flex justify-between items-center" > <h2 className="tracking-wider font-bold"> {subject.subject_name} </h2> <div className="bg-main rounded text-white p-5"> <FaBook className="w-[2em] h-[2em]" /> </div> </div> ))} <div onClick={openModal} className="bg-white transition hover:scale-105 hover:shadow-2xl shadow-lg p-5 m-6 flex justify-between items-center cursor-pointer" > <h2 className="tracking-wider font-bold">Add New Subject</h2> <div className="bg-main rounded text-white p-5"> <FaPlusSquare className="w-[2em] h-[2em]" /> </div> </div> </div> } </div> ) } export default ManageSubjects
package com.example.foodapp.ui.favorites.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.foodapp.data.local.entity.Favorite import com.example.foodapp.databinding.FavoriteItemBinding class FavoritesAdapter() : RecyclerView.Adapter<FavoritesAdapter.FavoritesViewHolder>() { var onItemLongClick: ((Favorite) -> Unit)? = null var onItemClick: ((Favorite) -> Unit)? = null private var favorites = ArrayList<Favorite>() fun setFavorites(favorites: ArrayList<Favorite>) { this.favorites = favorites notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoritesViewHolder { return FavoritesViewHolder(FavoriteItemBinding.inflate(LayoutInflater.from(parent.context))) } override fun onBindViewHolder(holder: FavoritesViewHolder, position: Int) { Glide.with(holder.itemView) .load(favorites[position].img) .into(holder.binding.ivFavoriteItem) holder.binding.tvFavoriteItem.text = favorites[position].title holder.itemView.setOnLongClickListener { onItemLongClick?.invoke(favorites[position]) true } holder.itemView.setOnClickListener { onItemClick?.invoke(favorites[position]) } } override fun getItemCount(): Int { return favorites.size } fun setOnFavoriteItemLongClickListener(favorite: (Favorite) -> Unit) { onItemLongClick = favorite } fun setOnFavoriteItemClickListener(favorite: (Favorite) -> Unit) { onItemClick = favorite } class FavoritesViewHolder(val binding: FavoriteItemBinding): RecyclerView.ViewHolder(binding.root) }
import { Inject } from '@nestjs/common'; import { BigNumber } from 'ethers'; import { APP_TOOLKIT, IAppToolkit } from '~app-toolkit/app-toolkit.interface'; import { PositionTemplate } from '~app-toolkit/decorators/position-template.decorator'; import { getLabelFromToken } from '~app-toolkit/helpers/presentation/image.present'; import { MetaType } from '~position/position.interface'; import { isSupplied } from '~position/position.utils'; import { ContractPositionTemplatePositionFetcher } from '~position/template/contract-position.template.position-fetcher'; import { DefaultContractPositionDefinition, GetTokenDefinitionsParams, GetDisplayPropsParams, GetTokenBalancesParams, } from '~position/template/contract-position.template.types'; import { ZhartaViemContractFactory } from '../contracts'; import { ZhartaLendingPoolCore } from '../contracts/viem'; interface ZhartaLendingPoolCoreContractPositionDefinition extends DefaultContractPositionDefinition { type: 'LENDING_POOL_CORE'; } @PositionTemplate() export class EthereumZhartaLendingPoolCoreContractPositionFetcher extends ContractPositionTemplatePositionFetcher<ZhartaLendingPoolCore> { groupLabel = 'Deposits'; contracts = ['0xe3c959bc97b92973d5367dbf4ce1b7b9660ee271']; constructor( @Inject(APP_TOOLKIT) protected readonly appToolkit: IAppToolkit, @Inject(ZhartaViemContractFactory) protected readonly contractFactory: ZhartaViemContractFactory, ) { super(appToolkit); } getContract(_address: string) { return this.contractFactory.zhartaLendingPoolCore({ address: _address, network: this.network }); } async getDefinitions(): Promise<ZhartaLendingPoolCoreContractPositionDefinition[]> { return this.contracts.map(address => ({ address, type: 'LENDING_POOL_CORE', })); } async getTokenDefinitions( _params: GetTokenDefinitionsParams<ZhartaLendingPoolCore, ZhartaLendingPoolCoreContractPositionDefinition>, ) { const { definition: { type }, } = _params; switch (type) { case 'LENDING_POOL_CORE': return this.getRegularTokenDefinitions(_params); } } private async getRegularTokenDefinitions({ contract, }: GetTokenDefinitionsParams<ZhartaLendingPoolCore, ZhartaLendingPoolCoreContractPositionDefinition>) { const [depositAddress] = await Promise.all([contract.read.erc20TokenContract()]); return [ { metaType: MetaType.SUPPLIED, address: depositAddress, network: this.network, }, { metaType: MetaType.CLAIMABLE, address: depositAddress, network: this.network, }, ]; } async getLabel({ contractPosition }: GetDisplayPropsParams<ZhartaLendingPoolCore>) { const suppliedToken = contractPosition.tokens.find(isSupplied)!; return `${getLabelFromToken(suppliedToken)} Pool`; } async getTokenBalancesPerPosition({ address, contract }: GetTokenBalancesParams<ZhartaLendingPoolCore>) { const [lenderFundsRaw, withdrawableAmountRaw] = await Promise.all([ contract.read.funds([address]), contract.read.computeWithdrawableAmount([address]), ]); return [ lenderFundsRaw.currentAmountDeposited, BigNumber.from(withdrawableAmountRaw).sub(lenderFundsRaw.currentAmountDeposited), ]; } }
--- title: "\"[Updated] 2024 Approved Capture Vimeo Essence The Art of Transforming Into a GIF\"" date: 2024-05-22T05:26:23.360Z updated: 2024-05-23T05:26:23.360Z tags: - ai video - ai vimeo - ai vimeo video categories: - ai - vimeo description: "\"This Article Describes [Updated] 2024 Approved: Capture Vimeo Essence: The Art of Transforming Into a GIF\"" excerpt: "\"This Article Describes [Updated] 2024 Approved: Capture Vimeo Essence: The Art of Transforming Into a GIF\"" keywords: "\"Vimeo GIF Conversion,High-Quality Vimeo GIFs,GIF From Video Snippets,Artistic Video to GIF,Professional GIF Creation,Elegant Video GIFs,Creative Vimeo Transformations\"" thumbnail: https://www.lifewire.com/thmb/Upemm_83fheu5JnASUVL9rXiGqw=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/TheOscarsStatue-33f6c30d7ffd4694a4dd1d1113de57f5.jpg --- ## Capture Vimeo Essence: The Art of Transforming Into a GIF # How to Make a GIF from Vimeo Video ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) ##### Shanoon Cox Mar 27, 2024• Proven solutions If you use Vimeo to share your videos, you can now easily create GIFs from Vimeo videos in just a few steps. If making a GIF using conventional tools is not of interest to you, Vimeo has the drag and drop feature to create gifs of your videos in no time. Here’s the detailed guide on how to make a GIF from a Vimeo video. **You might be interested in:** [Top GIF Apps for Android](https://tools.techidaily.com/wondershare/filmora/download/) --- ## **Part 1: How to Make a GIF with Vimeo** Vimeo has rolled out a new feature that allows you to create a GIF with Vimeo directly, and you’ll love it! Here are the steps of creating GIFs with Vimeo video, and you’ll be done creating one in no time. ### **Step 1: Go to Advanced Settings** Visit your Vimeo account, and then find the video that you want to make GIFs from. Click “Advanced” on the video manage center. ![create gif on vimeo - settings](https://images.wondershare.com/filmora/article-images/vimeo-video-advanced-settings-menu.jpg) ### **Step 2: Select Create a GIF** In the advanced settings page, you will see the GIF section on the General category. Click on the “Create a GIF” button. That will take you to the GIF editor, from where you can create a GIFs from Vimeo video directly. ![create gif on vimeo](https://images.wondershare.com/filmora/article-images/create-a-gif-on-vimeo.jpg) ### **Step 3: Create Your GIFs from Vimeo** You need to select your favorite clip from the video and choose the start and end times. And then hit the “Create GIF” button. And Vimeo will create a gif automatically with a maximum time limit of 6 seconds. ![select clips for gif on vimeo](https://images.wondershare.com/filmora/article-images/select-vimeo-clips-to-gifs.jpg) Note: you may need to scroll down the preview window to see the timing setting options. You can create several gifs from one Vimeo video. ### **Step 4: Download your GIF or share** Vimeo allows you to download the created GIFs for both small and large file sizes, and you can either download the GIF file and share it across your network or embed the code to your email by clicking on the “Embed in email” button, and voila! There you go! Creating a GIF from a Vimeo video can be done in no time. ![download and share gif on vimeo](https://images.wondershare.com/filmora/article-images/download-share-gifs-created-on-vimeo.jpg) Note: There will be a watermark in the created GIF with Vimeo. To remove the Vimeo watermark on the screen, you may need to upgrade to the Vimeo Pro version. ## **Part 2: How to Make GIFs from Vimeo Videos** Now you know how to create a GIF on Vimeo from the uploaded video. But what if you like a clip from videos other than yours? How to create a gif using that video? Here are three tools to help you out: ### 1\. **GfyCat** GfyCat allows you to create GIFs from Vimeo easily. You need to go “[Video to Gif Creator](https://gfycat.com/create)” and paste the Vimeo link. The best part of GfyCat is, it takes video of any length – be it 1GB or 1MB. ![convert vimeo to gif with GfyCat](https://images.wondershare.com/filmora/article-images/gfycat-vimeo-video-to-gif-creator.jpg) Once you upload the video, choose the time range, you can also add captions, titles, and tags to your GIF. Click on the “Finish” button and share it on your social media handles right away! With GfyCat, you can make gifs up to 60 seconds, not beyond that. ![convert vimeo to gif with GfyCat](https://images.wondershare.com/filmora/article-images/gfycat-create-gifs-from-vimeo-video.jpg) With its easy-to-use interface and drop-down options, creating a gif from your favorite Vimeo videos is no longer a daunting task. If you want your [gifs to have sound](https://tools.techidaily.com/wondershare/filmora/download/), you can add it too in CfyCat. ### **2\.** **ImgFlip** ImgFlip is another helpful tool to convert Vimeo to gif. You can upload or add the Vimeo video link by going to “[ImgFlip Gif Maker](https://imgflip.com/gif-maker).” You can preview the uploaded video from where you should choose the start and the end time. You can add text, images, or even draw on your Gif. ![convert vimeo to gif with imgflip](https://images.wondershare.com/filmora/article-images/imgflip-vimeo-video-to-gif.jpg) ImgFlip allows you to customize the width. Add a title and insert tags, and you’re good to go! Click on “Generate GIF,” from where you can get the image link or share it on your social media or get the HTML code to embed in your email or other places. ### **3\.** **Gifrun** [Gifrun](https://gifrun.com/) is also pretty easy to use. You can add the Vimeo link to it and preview it. Jump to the desired clip you want to create a gif of. ![convert vimeo to gif with gifrun](https://images.wondershare.com/filmora/article-images/gifrun-create-vimeo-video-to-gif.jpg) Click on “create a gif,” and you can also add texts to it if needed. Gifs from Gifrun can be up to 10 seconds long and not more than that. You also have the option to crop the GIF and finally download it. Gifrun makes it easy to create Vimeo to GIF, and their interface is easy to navigate and use. They have a wide array of fonts to choose from to make your GIF more appealing. ## **Part 3: How to Convert Vimeo Video to GIF with Filmora X?** If you want to create Vimeo gifs without length limitations, or changing the playback speed of the GIF, you can try Wondershare Filmora X. Below is how to convert a Vimeo video to GIF with Filmora X, and upload the created GIF to Vimeo. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ### **Step 1: Import the Vimeo Video** You need to install Filmora X on your system, and if you have it already, go to “New project” and import the Vimeo video from your device folder. ![convert vimeo to gif with Filmora X - import](https://images.wondershare.com/filmora/article-images/import-vimeo-video-filmora.jpg) ### **Step 2: Drag the Video to the Timeline** Once the video is on the Filmora window, you just need to drag and drop the video to the timeline. Choose the start and the end time by trimming out or cutting out the unwanted parts. ![convert vimeo to gif with Filmora X - import](https://images.wondershare.com/filmora/article-images/drag-vimeo-video-to-filmora.jpg) ### **Step 3: Add Effects** Make your gifs more appealing by adding effects and also texts as needed. That will spice up your GIF and add that extra element to it. Or, you can speed up or slow down the play back of the clip by changing the video speed. ![Add effects in Filmora](https://images.wondershare.com/filmora/article-images/add-effects-vimeo-video.jpg) ### **Step 4: Export the GIF and Share to Vimeo** Once your GIF is ready, you can find the “export” button on the top from where you can export it and share it. In the Export window, you can find GIF under the Local tab. Click Export and save the Vimeo video as a GIF. ![export in Filmora](https://images.wondershare.com/filmora/article-images/export-video-filmora.jpg) You can then [upload the created GIF to your Vimeo](https://tools.techidaily.com/wondershare/filmora/download/) account with ease. **Conclusion** GIFs are fun, so is creating one. You just need the right tools to make it. No longer do you have to be a Photoshop pro to create a Vimeo gif. Tools like Vimeo and other [gif makers](https://tools.techidaily.com/wondershare/filmora/download/) are designed to make it easy for all. All these tools have a three-step approach – upload the video, choose the time frame, and create. That’s it! It’s that simple. ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox ##### Shanoon Cox Mar 27, 2024• Proven solutions If you use Vimeo to share your videos, you can now easily create GIFs from Vimeo videos in just a few steps. If making a GIF using conventional tools is not of interest to you, Vimeo has the drag and drop feature to create gifs of your videos in no time. Here’s the detailed guide on how to make a GIF from a Vimeo video. **You might be interested in:** [Top GIF Apps for Android](https://tools.techidaily.com/wondershare/filmora/download/) --- ## **Part 1: How to Make a GIF with Vimeo** Vimeo has rolled out a new feature that allows you to create a GIF with Vimeo directly, and you’ll love it! Here are the steps of creating GIFs with Vimeo video, and you’ll be done creating one in no time. ### **Step 1: Go to Advanced Settings** Visit your Vimeo account, and then find the video that you want to make GIFs from. Click “Advanced” on the video manage center. ![create gif on vimeo - settings](https://images.wondershare.com/filmora/article-images/vimeo-video-advanced-settings-menu.jpg) ### **Step 2: Select Create a GIF** In the advanced settings page, you will see the GIF section on the General category. Click on the “Create a GIF” button. That will take you to the GIF editor, from where you can create a GIFs from Vimeo video directly. ![create gif on vimeo](https://images.wondershare.com/filmora/article-images/create-a-gif-on-vimeo.jpg) ### **Step 3: Create Your GIFs from Vimeo** You need to select your favorite clip from the video and choose the start and end times. And then hit the “Create GIF” button. And Vimeo will create a gif automatically with a maximum time limit of 6 seconds. ![select clips for gif on vimeo](https://images.wondershare.com/filmora/article-images/select-vimeo-clips-to-gifs.jpg) Note: you may need to scroll down the preview window to see the timing setting options. You can create several gifs from one Vimeo video. ### **Step 4: Download your GIF or share** Vimeo allows you to download the created GIFs for both small and large file sizes, and you can either download the GIF file and share it across your network or embed the code to your email by clicking on the “Embed in email” button, and voila! There you go! Creating a GIF from a Vimeo video can be done in no time. ![download and share gif on vimeo](https://images.wondershare.com/filmora/article-images/download-share-gifs-created-on-vimeo.jpg) Note: There will be a watermark in the created GIF with Vimeo. To remove the Vimeo watermark on the screen, you may need to upgrade to the Vimeo Pro version. ## **Part 2: How to Make GIFs from Vimeo Videos** Now you know how to create a GIF on Vimeo from the uploaded video. But what if you like a clip from videos other than yours? How to create a gif using that video? Here are three tools to help you out: ### 1\. **GfyCat** GfyCat allows you to create GIFs from Vimeo easily. You need to go “[Video to Gif Creator](https://gfycat.com/create)” and paste the Vimeo link. The best part of GfyCat is, it takes video of any length – be it 1GB or 1MB. ![convert vimeo to gif with GfyCat](https://images.wondershare.com/filmora/article-images/gfycat-vimeo-video-to-gif-creator.jpg) Once you upload the video, choose the time range, you can also add captions, titles, and tags to your GIF. Click on the “Finish” button and share it on your social media handles right away! With GfyCat, you can make gifs up to 60 seconds, not beyond that. ![convert vimeo to gif with GfyCat](https://images.wondershare.com/filmora/article-images/gfycat-create-gifs-from-vimeo-video.jpg) With its easy-to-use interface and drop-down options, creating a gif from your favorite Vimeo videos is no longer a daunting task. If you want your [gifs to have sound](https://tools.techidaily.com/wondershare/filmora/download/), you can add it too in CfyCat. ### **2\.** **ImgFlip** ImgFlip is another helpful tool to convert Vimeo to gif. You can upload or add the Vimeo video link by going to “[ImgFlip Gif Maker](https://imgflip.com/gif-maker).” You can preview the uploaded video from where you should choose the start and the end time. You can add text, images, or even draw on your Gif. ![convert vimeo to gif with imgflip](https://images.wondershare.com/filmora/article-images/imgflip-vimeo-video-to-gif.jpg) ImgFlip allows you to customize the width. Add a title and insert tags, and you’re good to go! Click on “Generate GIF,” from where you can get the image link or share it on your social media or get the HTML code to embed in your email or other places. ### **3\.** **Gifrun** [Gifrun](https://gifrun.com/) is also pretty easy to use. You can add the Vimeo link to it and preview it. Jump to the desired clip you want to create a gif of. ![convert vimeo to gif with gifrun](https://images.wondershare.com/filmora/article-images/gifrun-create-vimeo-video-to-gif.jpg) Click on “create a gif,” and you can also add texts to it if needed. Gifs from Gifrun can be up to 10 seconds long and not more than that. You also have the option to crop the GIF and finally download it. Gifrun makes it easy to create Vimeo to GIF, and their interface is easy to navigate and use. They have a wide array of fonts to choose from to make your GIF more appealing. ## **Part 3: How to Convert Vimeo Video to GIF with Filmora X?** If you want to create Vimeo gifs without length limitations, or changing the playback speed of the GIF, you can try Wondershare Filmora X. Below is how to convert a Vimeo video to GIF with Filmora X, and upload the created GIF to Vimeo. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ### **Step 1: Import the Vimeo Video** You need to install Filmora X on your system, and if you have it already, go to “New project” and import the Vimeo video from your device folder. ![convert vimeo to gif with Filmora X - import](https://images.wondershare.com/filmora/article-images/import-vimeo-video-filmora.jpg) ### **Step 2: Drag the Video to the Timeline** Once the video is on the Filmora window, you just need to drag and drop the video to the timeline. Choose the start and the end time by trimming out or cutting out the unwanted parts. ![convert vimeo to gif with Filmora X - import](https://images.wondershare.com/filmora/article-images/drag-vimeo-video-to-filmora.jpg) ### **Step 3: Add Effects** Make your gifs more appealing by adding effects and also texts as needed. That will spice up your GIF and add that extra element to it. Or, you can speed up or slow down the play back of the clip by changing the video speed. ![Add effects in Filmora](https://images.wondershare.com/filmora/article-images/add-effects-vimeo-video.jpg) ### **Step 4: Export the GIF and Share to Vimeo** Once your GIF is ready, you can find the “export” button on the top from where you can export it and share it. In the Export window, you can find GIF under the Local tab. Click Export and save the Vimeo video as a GIF. ![export in Filmora](https://images.wondershare.com/filmora/article-images/export-video-filmora.jpg) You can then [upload the created GIF to your Vimeo](https://tools.techidaily.com/wondershare/filmora/download/) account with ease. **Conclusion** GIFs are fun, so is creating one. You just need the right tools to make it. No longer do you have to be a Photoshop pro to create a Vimeo gif. Tools like Vimeo and other [gif makers](https://tools.techidaily.com/wondershare/filmora/download/) are designed to make it easy for all. All these tools have a three-step approach – upload the video, choose the time frame, and create. That’s it! It’s that simple. ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox ##### Shanoon Cox Mar 27, 2024• Proven solutions If you use Vimeo to share your videos, you can now easily create GIFs from Vimeo videos in just a few steps. If making a GIF using conventional tools is not of interest to you, Vimeo has the drag and drop feature to create gifs of your videos in no time. Here’s the detailed guide on how to make a GIF from a Vimeo video. **You might be interested in:** [Top GIF Apps for Android](https://tools.techidaily.com/wondershare/filmora/download/) --- ## **Part 1: How to Make a GIF with Vimeo** Vimeo has rolled out a new feature that allows you to create a GIF with Vimeo directly, and you’ll love it! Here are the steps of creating GIFs with Vimeo video, and you’ll be done creating one in no time. ### **Step 1: Go to Advanced Settings** Visit your Vimeo account, and then find the video that you want to make GIFs from. Click “Advanced” on the video manage center. ![create gif on vimeo - settings](https://images.wondershare.com/filmora/article-images/vimeo-video-advanced-settings-menu.jpg) ### **Step 2: Select Create a GIF** In the advanced settings page, you will see the GIF section on the General category. Click on the “Create a GIF” button. That will take you to the GIF editor, from where you can create a GIFs from Vimeo video directly. ![create gif on vimeo](https://images.wondershare.com/filmora/article-images/create-a-gif-on-vimeo.jpg) ### **Step 3: Create Your GIFs from Vimeo** You need to select your favorite clip from the video and choose the start and end times. And then hit the “Create GIF” button. And Vimeo will create a gif automatically with a maximum time limit of 6 seconds. ![select clips for gif on vimeo](https://images.wondershare.com/filmora/article-images/select-vimeo-clips-to-gifs.jpg) Note: you may need to scroll down the preview window to see the timing setting options. You can create several gifs from one Vimeo video. ### **Step 4: Download your GIF or share** Vimeo allows you to download the created GIFs for both small and large file sizes, and you can either download the GIF file and share it across your network or embed the code to your email by clicking on the “Embed in email” button, and voila! There you go! Creating a GIF from a Vimeo video can be done in no time. ![download and share gif on vimeo](https://images.wondershare.com/filmora/article-images/download-share-gifs-created-on-vimeo.jpg) Note: There will be a watermark in the created GIF with Vimeo. To remove the Vimeo watermark on the screen, you may need to upgrade to the Vimeo Pro version. ## **Part 2: How to Make GIFs from Vimeo Videos** Now you know how to create a GIF on Vimeo from the uploaded video. But what if you like a clip from videos other than yours? How to create a gif using that video? Here are three tools to help you out: ### 1\. **GfyCat** GfyCat allows you to create GIFs from Vimeo easily. You need to go “[Video to Gif Creator](https://gfycat.com/create)” and paste the Vimeo link. The best part of GfyCat is, it takes video of any length – be it 1GB or 1MB. ![convert vimeo to gif with GfyCat](https://images.wondershare.com/filmora/article-images/gfycat-vimeo-video-to-gif-creator.jpg) Once you upload the video, choose the time range, you can also add captions, titles, and tags to your GIF. Click on the “Finish” button and share it on your social media handles right away! With GfyCat, you can make gifs up to 60 seconds, not beyond that. ![convert vimeo to gif with GfyCat](https://images.wondershare.com/filmora/article-images/gfycat-create-gifs-from-vimeo-video.jpg) With its easy-to-use interface and drop-down options, creating a gif from your favorite Vimeo videos is no longer a daunting task. If you want your [gifs to have sound](https://tools.techidaily.com/wondershare/filmora/download/), you can add it too in CfyCat. ### **2\.** **ImgFlip** ImgFlip is another helpful tool to convert Vimeo to gif. You can upload or add the Vimeo video link by going to “[ImgFlip Gif Maker](https://imgflip.com/gif-maker).” You can preview the uploaded video from where you should choose the start and the end time. You can add text, images, or even draw on your Gif. ![convert vimeo to gif with imgflip](https://images.wondershare.com/filmora/article-images/imgflip-vimeo-video-to-gif.jpg) ImgFlip allows you to customize the width. Add a title and insert tags, and you’re good to go! Click on “Generate GIF,” from where you can get the image link or share it on your social media or get the HTML code to embed in your email or other places. ### **3\.** **Gifrun** [Gifrun](https://gifrun.com/) is also pretty easy to use. You can add the Vimeo link to it and preview it. Jump to the desired clip you want to create a gif of. ![convert vimeo to gif with gifrun](https://images.wondershare.com/filmora/article-images/gifrun-create-vimeo-video-to-gif.jpg) Click on “create a gif,” and you can also add texts to it if needed. Gifs from Gifrun can be up to 10 seconds long and not more than that. You also have the option to crop the GIF and finally download it. Gifrun makes it easy to create Vimeo to GIF, and their interface is easy to navigate and use. They have a wide array of fonts to choose from to make your GIF more appealing. ## **Part 3: How to Convert Vimeo Video to GIF with Filmora X?** If you want to create Vimeo gifs without length limitations, or changing the playback speed of the GIF, you can try Wondershare Filmora X. Below is how to convert a Vimeo video to GIF with Filmora X, and upload the created GIF to Vimeo. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ### **Step 1: Import the Vimeo Video** You need to install Filmora X on your system, and if you have it already, go to “New project” and import the Vimeo video from your device folder. ![convert vimeo to gif with Filmora X - import](https://images.wondershare.com/filmora/article-images/import-vimeo-video-filmora.jpg) ### **Step 2: Drag the Video to the Timeline** Once the video is on the Filmora window, you just need to drag and drop the video to the timeline. Choose the start and the end time by trimming out or cutting out the unwanted parts. ![convert vimeo to gif with Filmora X - import](https://images.wondershare.com/filmora/article-images/drag-vimeo-video-to-filmora.jpg) ### **Step 3: Add Effects** Make your gifs more appealing by adding effects and also texts as needed. That will spice up your GIF and add that extra element to it. Or, you can speed up or slow down the play back of the clip by changing the video speed. ![Add effects in Filmora](https://images.wondershare.com/filmora/article-images/add-effects-vimeo-video.jpg) ### **Step 4: Export the GIF and Share to Vimeo** Once your GIF is ready, you can find the “export” button on the top from where you can export it and share it. In the Export window, you can find GIF under the Local tab. Click Export and save the Vimeo video as a GIF. ![export in Filmora](https://images.wondershare.com/filmora/article-images/export-video-filmora.jpg) You can then [upload the created GIF to your Vimeo](https://tools.techidaily.com/wondershare/filmora/download/) account with ease. **Conclusion** GIFs are fun, so is creating one. You just need the right tools to make it. No longer do you have to be a Photoshop pro to create a Vimeo gif. Tools like Vimeo and other [gif makers](https://tools.techidaily.com/wondershare/filmora/download/) are designed to make it easy for all. All these tools have a three-step approach – upload the video, choose the time frame, and create. That’s it! It’s that simple. ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox ##### Shanoon Cox Mar 27, 2024• Proven solutions If you use Vimeo to share your videos, you can now easily create GIFs from Vimeo videos in just a few steps. If making a GIF using conventional tools is not of interest to you, Vimeo has the drag and drop feature to create gifs of your videos in no time. Here’s the detailed guide on how to make a GIF from a Vimeo video. **You might be interested in:** [Top GIF Apps for Android](https://tools.techidaily.com/wondershare/filmora/download/) --- ## **Part 1: How to Make a GIF with Vimeo** Vimeo has rolled out a new feature that allows you to create a GIF with Vimeo directly, and you’ll love it! Here are the steps of creating GIFs with Vimeo video, and you’ll be done creating one in no time. ### **Step 1: Go to Advanced Settings** Visit your Vimeo account, and then find the video that you want to make GIFs from. Click “Advanced” on the video manage center. ![create gif on vimeo - settings](https://images.wondershare.com/filmora/article-images/vimeo-video-advanced-settings-menu.jpg) ### **Step 2: Select Create a GIF** In the advanced settings page, you will see the GIF section on the General category. Click on the “Create a GIF” button. That will take you to the GIF editor, from where you can create a GIFs from Vimeo video directly. ![create gif on vimeo](https://images.wondershare.com/filmora/article-images/create-a-gif-on-vimeo.jpg) ### **Step 3: Create Your GIFs from Vimeo** You need to select your favorite clip from the video and choose the start and end times. And then hit the “Create GIF” button. And Vimeo will create a gif automatically with a maximum time limit of 6 seconds. ![select clips for gif on vimeo](https://images.wondershare.com/filmora/article-images/select-vimeo-clips-to-gifs.jpg) Note: you may need to scroll down the preview window to see the timing setting options. You can create several gifs from one Vimeo video. ### **Step 4: Download your GIF or share** Vimeo allows you to download the created GIFs for both small and large file sizes, and you can either download the GIF file and share it across your network or embed the code to your email by clicking on the “Embed in email” button, and voila! There you go! Creating a GIF from a Vimeo video can be done in no time. ![download and share gif on vimeo](https://images.wondershare.com/filmora/article-images/download-share-gifs-created-on-vimeo.jpg) Note: There will be a watermark in the created GIF with Vimeo. To remove the Vimeo watermark on the screen, you may need to upgrade to the Vimeo Pro version. ## **Part 2: How to Make GIFs from Vimeo Videos** Now you know how to create a GIF on Vimeo from the uploaded video. But what if you like a clip from videos other than yours? How to create a gif using that video? Here are three tools to help you out: ### 1\. **GfyCat** GfyCat allows you to create GIFs from Vimeo easily. You need to go “[Video to Gif Creator](https://gfycat.com/create)” and paste the Vimeo link. The best part of GfyCat is, it takes video of any length – be it 1GB or 1MB. ![convert vimeo to gif with GfyCat](https://images.wondershare.com/filmora/article-images/gfycat-vimeo-video-to-gif-creator.jpg) Once you upload the video, choose the time range, you can also add captions, titles, and tags to your GIF. Click on the “Finish” button and share it on your social media handles right away! With GfyCat, you can make gifs up to 60 seconds, not beyond that. ![convert vimeo to gif with GfyCat](https://images.wondershare.com/filmora/article-images/gfycat-create-gifs-from-vimeo-video.jpg) With its easy-to-use interface and drop-down options, creating a gif from your favorite Vimeo videos is no longer a daunting task. If you want your [gifs to have sound](https://tools.techidaily.com/wondershare/filmora/download/), you can add it too in CfyCat. ### **2\.** **ImgFlip** ImgFlip is another helpful tool to convert Vimeo to gif. You can upload or add the Vimeo video link by going to “[ImgFlip Gif Maker](https://imgflip.com/gif-maker).” You can preview the uploaded video from where you should choose the start and the end time. You can add text, images, or even draw on your Gif. ![convert vimeo to gif with imgflip](https://images.wondershare.com/filmora/article-images/imgflip-vimeo-video-to-gif.jpg) ImgFlip allows you to customize the width. Add a title and insert tags, and you’re good to go! Click on “Generate GIF,” from where you can get the image link or share it on your social media or get the HTML code to embed in your email or other places. ### **3\.** **Gifrun** [Gifrun](https://gifrun.com/) is also pretty easy to use. You can add the Vimeo link to it and preview it. Jump to the desired clip you want to create a gif of. ![convert vimeo to gif with gifrun](https://images.wondershare.com/filmora/article-images/gifrun-create-vimeo-video-to-gif.jpg) Click on “create a gif,” and you can also add texts to it if needed. Gifs from Gifrun can be up to 10 seconds long and not more than that. You also have the option to crop the GIF and finally download it. Gifrun makes it easy to create Vimeo to GIF, and their interface is easy to navigate and use. They have a wide array of fonts to choose from to make your GIF more appealing. ## **Part 3: How to Convert Vimeo Video to GIF with Filmora X?** If you want to create Vimeo gifs without length limitations, or changing the playback speed of the GIF, you can try Wondershare Filmora X. Below is how to convert a Vimeo video to GIF with Filmora X, and upload the created GIF to Vimeo. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ### **Step 1: Import the Vimeo Video** You need to install Filmora X on your system, and if you have it already, go to “New project” and import the Vimeo video from your device folder. ![convert vimeo to gif with Filmora X - import](https://images.wondershare.com/filmora/article-images/import-vimeo-video-filmora.jpg) ### **Step 2: Drag the Video to the Timeline** Once the video is on the Filmora window, you just need to drag and drop the video to the timeline. Choose the start and the end time by trimming out or cutting out the unwanted parts. ![convert vimeo to gif with Filmora X - import](https://images.wondershare.com/filmora/article-images/drag-vimeo-video-to-filmora.jpg) ### **Step 3: Add Effects** Make your gifs more appealing by adding effects and also texts as needed. That will spice up your GIF and add that extra element to it. Or, you can speed up or slow down the play back of the clip by changing the video speed. ![Add effects in Filmora](https://images.wondershare.com/filmora/article-images/add-effects-vimeo-video.jpg) ### **Step 4: Export the GIF and Share to Vimeo** Once your GIF is ready, you can find the “export” button on the top from where you can export it and share it. In the Export window, you can find GIF under the Local tab. Click Export and save the Vimeo video as a GIF. ![export in Filmora](https://images.wondershare.com/filmora/article-images/export-video-filmora.jpg) You can then [upload the created GIF to your Vimeo](https://tools.techidaily.com/wondershare/filmora/download/) account with ease. **Conclusion** GIFs are fun, so is creating one. You just need the right tools to make it. No longer do you have to be a Photoshop pro to create a Vimeo gif. Tools like Vimeo and other [gif makers](https://tools.techidaily.com/wondershare/filmora/download/) are designed to make it easy for all. All these tools have a three-step approach – upload the video, choose the time frame, and create. That’s it! It’s that simple. ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://vimeo-videos.techidaily.com/updated-vimeo-mastery-in-motion-building-high-impact-gifs-for-2024/"><u>[Updated] Vimeo Mastery in Motion Building High-Impact GIFs for 2024</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/updated-strategies-to-perfect-the-last-push-on-your-vimeo-videos-for-2024/"><u>[Updated] Strategies to Perfect the Last Push on Your Vimeo Videos for 2024</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/updated-non-vimeo-showstoppers-for-online-content-creators-for-2024/"><u>[Updated] Non-Vimeo Showstoppers for Online Content Creators for 2024</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/new-in-2024-cut-costs-improve-videos-learn-free-vimeo-editing/"><u>[New] In 2024, Cut Costs, Improve Videos Learn Free Vimeo Editing</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/updated-visualizing-stories-turning-your-favorite-vimeo-into-dynamic-gifs-for-2024/"><u>[Updated] Visualizing Stories Turning Your Favorite Vimeo Into Dynamic GIFs for 2024</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/tutorial-extracting-audio-from-vimeo-video-for-2024/"><u>Tutorial Extracting Audio From Vimeo Video for 2024</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/new-elevating-earnings-the-essentials-of-vimeo-revenue-model-for-2024/"><u>[New] Elevating Earnings The Essentials of Vimeo Revenue Model for 2024</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/updated-in-2024-strategies-to-promote-vimeo-films/"><u>[Updated] In 2024, Strategies to Promote Vimeo Films</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/updated-in-2024-ultimate-guide-10-superior-vimeo-downloader-apps/"><u>[Updated] In 2024, Ultimate Guide 10 Superior Vimeo Downloader Apps</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/direct-download-process-from-vimeo-to-mp3-format/"><u>Direct Download Process From Vimeo to MP3 Format</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/updated-in-2024-mixing-tunes-with-videos-on-vimeo-platform/"><u>[Updated] In 2024, Mixing Tunes with Videos on Vimeo Platform</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/quick-reference-how-to-insert-vimeo-media-into-powerpoint-files/"><u>Quick Reference How to Insert Vimeo Media Into PowerPoint Files</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/the-complete-guide-to-earnings-via-vimeo-ads/"><u>The Complete Guide to Earnings via Vimeo Ads</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/2024-approved-expert-tips-for-effortless-acquisition-of-vimeo-videos-softwares-and-no-softwares-included/"><u>2024 Approved Expert Tips for Effortless Acquisition of Vimeo Videos - Softwares & No-Softwares Included</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/updated-essential-chrome-tools-maximize-vimeo-content-access-for-2024/"><u>[Updated] Essential Chrome Tools Maximize Vimeo Content Access for 2024</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/updated-in-2024-rising-above-vimeo-10-next-level-editing-applications/"><u>[Updated] In 2024, Rising Above Vimeo 10 Next-Level Editing Applications</u></a></li> <li><a href="https://vimeo-videos.techidaily.com/new-vimeos-no-money-solution-easy-editing-basics-for-2024/"><u>[New] Vimeo's No-Money Solution Easy Editing Basics for 2024</u></a></li> <li><a href="https://video-capture.techidaily.com/in-2024-deciding-the-best-for-screens-is-obs-more-effective-than-fraps/"><u>In 2024, Deciding the Best for Screens Is OBS More Effective than Fraps?</u></a></li> <li><a href="https://audio-shaping.techidaily.com/2024-approved-the-comprehensive-tutorial-on-detaching-audible-elements-from-video-clips/"><u>2024 Approved The Comprehensive Tutorial on Detaching Audible Elements From Video Clips</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/in-2024-best-10-hindi-video-translators-with-step-by-step-guidance/"><u>In 2024, Best 10 Hindi Video Translators with Step-by-Step Guidance</u></a></li> <li><a href="https://twitter-clips.techidaily.com/updated-trending-in-real-time-10-hot-tweets-captivating-audiences-for-2024/"><u>[Updated] Trending in Real Time 10 Hot Tweets Captivating Audiences for 2024</u></a></li> <li><a href="https://video-creation-software.techidaily.com/new-in-2024-quicktime-player-tutorial-speed-up-videos-on-windows-and-mac-computers/"><u>New In 2024, QuickTime Player Tutorial Speed Up Videos on Windows and Mac Computers</u></a></li> <li><a href="https://facebook-clips.techidaily.com/new-in-2024-driving-traffic-with-creative-fb-video-marketing-hacks/"><u>[New] In 2024, Driving Traffic with Creative FB Video Marketing Hacks</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-3-facts-you-need-to-know-about-screen-mirroring-xiaomi-redmi-note-12t-pro-drfone-by-drfone-android/"><u>In 2024, 3 Facts You Need to Know about Screen Mirroring Xiaomi Redmi Note 12T Pro | Dr.fone</u></a></li> <li><a href="https://android-transfer.techidaily.com/in-2024-how-to-transfer-music-from-oppo-a2-to-ipod-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>In 2024, How to Transfer Music from Oppo A2 to iPod | Dr.fone</u></a></li> <li><a href="https://twitter-videos.techidaily.com/new-breaking-tiktok-trends-twitters-1-list-unveiled-for-2024/"><u>[New] Breaking TikTok Trends Twitter's #1 List Unveiled for 2024</u></a></li> <li><a href="https://screen-recording.techidaily.com/updated-logitech-4k-pro-webcam-complete-review-2024/"><u>[Updated] Logitech 4K Pro Webcam Complete Review 2024</u></a></li> <li><a href="https://on-screen-recording.techidaily.com/screen-capture-showdown-is-obs-better-than-fraps-for-2024/"><u>Screen Capture Showdown Is OBS Better Than Fraps for 2024</u></a></li> <li><a href="https://sound-optimizing.techidaily.com/in-2024-vimeo-film-metadata-aspect-ratio-noted/"><u>In 2024, Vimeo Film Metadata Aspect Ratio Noted</u></a></li> </ul></div>
import React from 'react'; import { Checkbox } from 'antd'; import { CheckboxValueType } from 'antd/lib/checkbox/Group'; import styled from 'styled-components'; import { STheme } from '../../theme/theme'; interface Props { style?: React.CSSProperties; onChangeLevelFilter?: (checkedValue: CheckboxValueType[]) => void; onChangeStatusFilter?: (checkedValue: CheckboxValueType[]) => void; } const statusOptions = [ { label: 'Solved', value: 'solved' }, { label: 'Unsolved', value: 'unsolved' }, ]; const levelOptions = [ { label: 'Easy', value: 'easy' }, { label: 'Medium', value: 'medium' }, { label: 'Hard', value: 'hard' }, ]; const SortTable: React.FC<Props> = (props) => { const { style, onChangeLevelFilter, onChangeStatusFilter } = props; return ( <SSortTable style={style}> <Checkbox.Group options={statusOptions} defaultValue={['solved', 'unsolved']} style={{ display: 'flex', flexFlow: 'column nowrap' }} onChange={onChangeStatusFilter} /> <Checkbox.Group options={levelOptions} defaultValue={['easy', 'medium', 'hard']} style={{ display: 'flex', flexFlow: 'column nowrap' }} onChange={onChangeLevelFilter} /> </SSortTable> ); }; const SSortTable = styled.div` border-left: 1px solid ${({ theme }: { theme: STheme }) => theme.palette.common.lightGrey}; padding-left: 20px; & > :first-child { border-bottom: 1px solid ${({ theme }: { theme: STheme }) => theme.palette.common.lightGrey}; } .ant-checkbox-group, .ant-checkbox-group-item { margin: 5px 0; } .title { margin: 0; font-size: ${({ theme }: { theme: STheme }) => theme.typography.fontSize.large}; color: ${({ theme }: { theme: STheme }) => theme.palette.common.grey}; font-weight: lighter; } `; export default SortTable;
//model Imports const { createErr } = require("../Error/error.js"); const User = require("../Models/AuthModel.js"); //bcrypt import var bcrypt = require("bcryptjs"); // index of users page // Get all user Request const Getusers = async (request, response, next) => { try { await User.find({}).then((resp) => { response.status(200).json(resp); }); } catch (err) { next(createErr(404,"No Users Found")); } }; //Create Request const userRegister = async (request, response, next) => { try { const { body } = request; console.log(body) var salt = bcrypt.genSaltSync(10); var hash = bcrypt.hashSync(body.password, salt); body.password = hash; const user = new User(body); await user.save().then((resp) => { response.status(201).json(resp); }); } catch (err) { next(createErr(500,`${err.message}`)); } }; //Delete Request const Deleteuser = async (request, response, next) => { try { const { id } = request.params; await User.findByIdAndDelete(id).then((resp) => { response.status(200).json("User Has Been Deleted."); }); } catch (err) { next(createErr(404,"No such ID.")); } }; //Get Request for users const Getuser = async (request, response, next) => { try { const { id } = request.params; await User.findById(id).then((resp) => { response.status(200).json(resp); }); } catch (err) { next(err); } }; //Update Request for users const updateuser = async (request, response, next) => { try { const { id } = request.params; const { body } = request; await User.findByIdAndUpdate(id, body,{new: true}).then((resp) => { response.status(200).json(resp); }); } catch (err) { next(err); } }; module.exports = { Getusers, userRegister, Deleteuser, Getuser, updateuser, };
// // AllOrderViewModel.swift // Carrefour-Bayi // // Created by Veysel Bozkurt on 7.11.2022. // import Foundation protocol AllOrderViewModelDelegate: BaseViewModelDelegate { func pageContentSuccess() func pageContentFailed(message: String) } class AllOrderViewModel: BaseViewModel { weak var delegate: AllOrderViewModelDelegate? private var orderRepository: OrderRespository var ordersModel: GetOrdersResponseDTO? var getFilteredOrdersRequestDTO: GetOrdersRequestDTO? var getOrdersRequestDTO: GetOrdersRequestDTO? var currentCompanyAndStore: CurrentCompanyAndStore? var currentPage = 1 var fieldsDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .none formatter.locale = Locale(identifier: "tr_TR") formatter.dateFormat = "dd.MM.yyy" return formatter }() var endpointDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy.MM.dd" return formatter }() init(orderRepository: OrderRespository = RepositoryProvider.orderRepository) { self.orderRepository = orderRepository } override func viewWillAppear() { getAllOrders() } func getAllOrders() { if let companyID = currentCompanyAndStore?.companyID, let storeID = currentCompanyAndStore?.storeID { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.baseVMDelegate?.contentWillLoad() } getOrdersRequestDTO = GetOrdersRequestDTO(Language: ServiceConfiguration.Language, ProcessType: ServiceConfiguration.ProcessType, RecordSizeFromPage: 100, CurrentPage: currentPage, SortColumn: "Id", SortColumnAscDesc: "Desc", CompanyId: companyID, StoreId: storeID, Filter: OrderFilter(OrderNumber: nil, FirstDate: nil, LastDate: nil, OrderState: nil, MaxPrice: nil, MinPrice: nil)) orderRepository.getOrders(getOrdersRequestDTO: getOrdersRequestDTO!) { [weak self] getOrdersResponse in self?.baseVMDelegate?.contentDidLoad() self?.ordersModel = getOrdersResponse self?.delegate?.pageContentSuccess() } failure: { [weak self] errorDTO in self?.delegate?.pageContentFailed(message: errorDTO?.messageText ?? "generalErrorMessage".localized) self?.baseVMDelegate?.contentDidLoad() } } } func getMoreOrders(completion: @escaping () -> ()) { if getOrdersRequestDTO != nil { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.baseVMDelegate?.contentWillLoad() } currentPage += 1 getOrdersRequestDTO?.CurrentPage = currentPage orderRepository.getOrders(getOrdersRequestDTO: getOrdersRequestDTO!) { [weak self] getOrdersResponse in self?.ordersModel?.Data! += getOrdersResponse.Data! self?.baseVMDelegate?.contentDidLoad() completion() } failure: { [weak self] errorDTO in self?.delegate?.pageContentFailed(message: errorDTO?.messageText ?? "generalErrorMessage".localized) self?.baseVMDelegate?.contentDidLoad() } } } func getFilteredOrders(orderNumber: String?, firstDate: String?, lastDate: String?, orderState: Int?, maxPrice: Double?, minPrice: Double?, completion: @escaping () -> ()) { if let companyID = currentCompanyAndStore?.companyID, let storeID = currentCompanyAndStore?.storeID { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.baseVMDelegate?.contentWillLoad() } currentPage = 1 getFilteredOrdersRequestDTO = GetOrdersRequestDTO(Language: ServiceConfiguration.Language, ProcessType: ServiceConfiguration.ProcessType, RecordSizeFromPage: 100, CurrentPage: currentPage, SortColumn: "Id", SortColumnAscDesc: "Desc", CompanyId: companyID, StoreId: storeID, Filter: OrderFilter(OrderNumber: orderNumber, FirstDate: firstDate, LastDate: lastDate, OrderState: orderState, MaxPrice: maxPrice, MinPrice: minPrice)) orderRepository.getOrders(getOrdersRequestDTO: getFilteredOrdersRequestDTO!) { [weak self] getFilteredOrdersResponse in self?.baseVMDelegate?.contentDidLoad() self?.ordersModel = getFilteredOrdersResponse self?.delegate?.pageContentSuccess() } failure: { [weak self] errorDTO in self?.delegate?.pageContentFailed(message: errorDTO?.messageText ?? "generalErrorMessage".localized) self?.baseVMDelegate?.contentDidLoad() } } } func getMoreFilteredOrders(completion: @escaping () -> ()) { if getFilteredOrdersRequestDTO != nil { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.baseVMDelegate?.contentWillLoad() } currentPage += 1 getFilteredOrdersRequestDTO?.CurrentPage = currentPage orderRepository.getOrders(getOrdersRequestDTO: getFilteredOrdersRequestDTO!) { [weak self] getFilteredOrdersResponse in self?.baseVMDelegate?.contentDidLoad() self?.ordersModel?.Data! += getFilteredOrdersResponse.Data! completion() } failure: { [weak self] errorDTO in self?.delegate?.pageContentFailed(message: errorDTO?.messageText ?? "generalErrorMessage".localized) self?.baseVMDelegate?.contentDidLoad() } } } }
"use client"; import { userValidation } from "@/components/userValidation"; import { useEffect, useState } from "react"; export default function Orders() { const [orders, setOrders] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [totalPages, setTotalPages] = useState(0); const [hasNextPage, setHasNextPage] = useState(false); const [hasPreviousPage, setHasPreviousPage] = useState(false); useEffect(() => { userValidation(localStorage); const fetchOrders = async () => { try { const request = await fetch("http://localhost:3005/user/orders?page=1", { headers: { Authorization: `Bearer ${localStorage.getItem("token")}` }, }); const { orders, totalPages, hasNextPage, hasPreviousPage } = await request.json(); setOrders(orders); setCurrentPage(1); setTotalPages(totalPages); setHasNextPage(hasNextPage); setHasPreviousPage(hasPreviousPage); } catch (err) { console.error(err); } }; fetchOrders(); }, []); const handleNextPage = () => { if (currentPage < totalPages) { fetchOrdersPerPage(currentPage + 1); } }; const handlePreviousPage = () => { if (currentPage > 1) { fetchOrdersPerPage(currentPage - 1); } }; const fetchOrdersPerPage = async (page: number) => { try { const request = await fetch(`http://localhost:3005/user/orders?page=${page}`, { headers: { Authorization: `Bearer ${localStorage.getItem("token")}` }, }); const { orders, hasNextPage, hasPreviousPage } = await request.json(); setOrders(orders); setCurrentPage(page); setHasNextPage(hasNextPage); setHasPreviousPage(hasPreviousPage); } catch (err) { console.error(err); } }; return ( <div className="min-h-screen flex flex-col justify-start"> <div className="overflow-x-auto"> <table className="table table-sm"> <thead> <tr> <th className="text-xl">Звідки</th> <th className="text-xl">Куди</th> <th className="text-xl">Вага (тонн)</th> <th className="text-xl">Контактна особа</th> <th className="text-xl">Номер телефону</th> <th className="text-xl">Заявку створено</th> </tr> </thead> <tbody> {orders.map( (order: { from: string; to: string; weight: number; fullName: string; phone: string; createdAt: string; }) => ( <tr> <td>{order.from}</td> <td>{order.to}</td> <td>{order.weight}</td> <td>{order.fullName}</td> <td>{order.phone}</td> <td>{new Date(order.createdAt).toLocaleString("uk-UA")}</td> </tr> ), )} </tbody> </table> </div> <div className="flex justify-around my-10"> <button className={`btn ${!hasPreviousPage ? "btn-disabled" : "btn-ghost"} rounded-box hover:btn-warning`} onClick={handlePreviousPage} disabled={!hasPreviousPage} > Попередня сторінка </button> <button className={`btn ${!hasNextPage ? "btn-disabled" : "btn-ghost"} rounded-box hover:btn-warning`} onClick={handleNextPage} disabled={!hasNextPage} > Наступна сторінка </button> </div> </div> ); }
import React, { useState, useRef } from 'react'; import axios from 'axios'; import { Button, Form, Row, Col, Container, Table, FloatingLabel, } from 'react-bootstrap'; import { useEffect } from 'react'; import instance from '../../util/axios-setting'; function AdminProductUD() { const ProductTable = ({ product }) => { const category = categories.find((data) => data._id === product.categoryId); const [title, setTitle] = useState(product.title); const [shortDescription, setShortDescription] = useState( product.shortDescription, ); const [detailDescription, setDetailDescription] = useState( product.detailDescription, ); const [price, setPrice] = useState(product.price); const [inventory, setInventory] = useState(product.inventory); const [categoryId, setCategoryId] = useState(product.categorId); const [imgSrc, setImgSrc] = useState(''); const [currentImgSrc, setCurrentImgSrc] = useState(''); const [file, setFile] = useState(''); useEffect(() => { instance .get(`/api/products/img/${product.imageKey}`, { headers: { 'Content-type': 'application/json; charset=UTF-8', }, responseType: 'blob', }) .then((res) => { const getfile = new File([res.data], product.imageKey); const reader = new FileReader(); reader.onload = (event) => { const previewImage = String(event.target?.result); console.log(previewImage); setCurrentImgSrc(previewImage); }; reader.readAsDataURL(getfile); }); }, []); const updateHandler = (e) => { e.preventDefault(); const formdata = new FormData(); if (file) { formdata.append('imageKey', file); } if (categoryId !== product.categorId) { formdata.append('categoryId', categoryId); } if (title !== product.title) { formdata.append('title', title); } if (price !== product.price) { formdata.append('price', price); } if (shortDescription !== product.shortDescription) { formdata.append('shortDescription', shortDescription); } if (detailDescription !== product.detailDescription) { formdata.append('detailDescription', detailDescription); } if (inventory !== product.inventory) { formdata.append('inventory', inventory); } instance .put(`/api/products/${product._id}`, formdata, { headers: { 'Content-Type': 'multipart/form-data', }, }) .then(() => { instance.get(`/api/products`).then((res) => { setProducts(res.data); }); }); }; const deleteHandler = (e) => { e.preventDefault(); instance.delete(`/api/products/${product._id}`).then((res) => { instance .get(`${process.env.REACT_APP_SERVER_ADDRESS}/api/products`) .then((res) => { setProducts(res.data); }); }); }; return ( <tr> <td style={{ width: '400px' }}> <img style={{ width: '100%' }} src={currentImgSrc} alt="current" /> <img style={{ width: '100%' }} src={imgSrc} alt="change" /> <Form.Control type="file" onChange={(e) => { e.preventDefault(); const upfile = e.target.files[0]; const reader = new FileReader(); reader.readAsDataURL(upfile); reader.onloadend = () => { setImgSrc(reader.result); console.log('changed'); }; setFile(upfile); }} /> <button onClick={(e) => { e.preventDefault(); setImgSrc(''); setFile(''); }} type="submit" > Reset </button> </td> <td style={{ width: '600px' }}> <FloatingLabel label="Title" className=""> <Form.Control //defaultValue={product.title} value={title} onChange={(e) => { e.preventDefault(); setTitle(e.target.value); }} /> </FloatingLabel> <FloatingLabel label="Short Description" className=""> <Form.Control // defaultValue={product.shortDescription} value={shortDescription} onChange={(e) => { e.preventDefault(); setShortDescription(e.target.value); }} /> </FloatingLabel> <FloatingLabel label="Detail" className=""> <Form.Control // defaultValue={product.detailDescription} value={detailDescription} onChange={(e) => { e.preventDefault(); setDetailDescription(e.target.value); }} /> </FloatingLabel> <FloatingLabel label="Price" className=""> <Form.Control // defaultValue={product.price} value={price} onChange={(e) => { e.preventDefault(); setPrice(e.target.value); }} /> </FloatingLabel> <FloatingLabel label="Inventory"> <Form.Control // defaultValue={product.inventory} value={inventory} onChange={(e) => { e.preventDefault(); setInventory(e.target.value); }} /> </FloatingLabel> <FloatingLabel label="Category" className=""> <Form.Control defaultValue={category ? category.title : '없음'} readOnly /> </FloatingLabel> <Form.Select defaultValue={product.categoryId} value={categoryId} onChange={(e) => { e.preventDefault(); setCategoryId(e.target.value); }} > <option>변경할 카테고리 고르세요.</option> {categories.map((data) => { return ( <option key={data._id} value={data._id}> {data.title} </option> ); })} </Form.Select> </td> <td> <Button variant="warning" onClick={updateHandler}> 수정 </Button> <Button variant="danger" onClick={deleteHandler}> 삭제 </Button> </td> </tr> ); }; const [products, setProducts] = useState([]); const [categories, setCategories] = useState([]); useEffect(() => { instance .get(`/api/products`) .then((res) => { setProducts(res.data); }) .then(() => { instance.get(`/api/categories`).then((res) => { setCategories(res.data); }); }) .catch((err) => { console.log(err); }); }, []); return ( <Container> <Table striped bordered hover size="sm"> <thead> <tr> <th>Image</th> <th>정보</th> <th>수정/삭제</th> </tr> </thead> <tbody> {products.map((product) => { return <ProductTable key={product._id} product={product} />; })} </tbody> </Table> </Container> ); } export default AdminProductUD;
package com.hailin.job.schedule.core.executor; import com.google.common.collect.Maps; import com.hailin.job.schedule.core.basic.JobTypeManager; import com.hailin.job.schedule.core.basic.config.ConfigurationNode; import com.hailin.job.schedule.core.config.JobConfiguration; import com.hailin.job.schedule.core.config.JobType; import com.hailin.job.schedule.core.strategy.JobScheduler; import com.hailin.shrine.job.common.exception.JobException; import com.hailin.shrine.job.common.exception.JobInitAlarmException; import com.hailin.shrine.job.common.util.AlarmUtils; import com.hailin.shrine.job.common.util.LogEvents; import com.hailin.job.schedule.core.basic.storage.JobNodePath; import com.hailin.job.schedule.core.basic.threads.ScheduleThreadFactory; import com.hailin.job.schedule.core.reg.base.CoordinatorRegistryCenter; import com.hailin.shrine.job.common.util.SystemEnvProperties; import org.apache.commons.lang3.StringUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.cache.TreeCacheListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static com.hailin.job.schedule.core.executor.ScheduleExecutorService.WAIT_JOBCLASS_ADDED_COUNT; /** * 初始化新任务的服务 * @author zhanghailin */ public class InitNewJobService { private static final Logger LOGGER = LoggerFactory.getLogger(InitNewJobService.class); /** * record the alarm message hashcode, permanently saved, used for just raising alarm one time for one type exception */ private static final ConcurrentMap<String, ConcurrentMap<String, Set<Integer>>> JOB_INIT_FAILED_RECORDS = new ConcurrentHashMap<>(); private ScheduleExecutorService scheduleExecutorService; private String executorName; private CoordinatorRegistryCenter regCenter; private TreeCache treeCache; private ExecutorService executorService; private List<String> jobNames = new ArrayList<>(); public InitNewJobService(ScheduleExecutorService scheduleExecutorService) { this.scheduleExecutorService = scheduleExecutorService; this.executorName = scheduleExecutorService.getExecutorName(); this.regCenter = scheduleExecutorService.getCoordinatorRegistryCenter(); JOB_INIT_FAILED_RECORDS.putIfAbsent(executorName , Maps.newConcurrentMap()); } public void start()throws Exception{ treeCache = TreeCache.newBuilder((CuratorFramework) regCenter.getRawClient() , JobNodePath.ROOT) .setExecutor(Executors.newSingleThreadExecutor(new ScheduleThreadFactory(executorName + "-$Job-watcher" , false)) ) .setMaxDepth(1).build(); executorService = Executors.newSingleThreadExecutor(new ScheduleThreadFactory(executorName + "-initNewJob-thread" ,false)); treeCache.getListenable().addListener(new InitNewJobListener() ,executorService); treeCache.start(); } public void shutdown() { try { if (treeCache != null) { treeCache.close(); } } catch (Throwable t) { LOGGER.error( LogEvents.ExecutorEvent.INIT_OR_SHUTDOWN, t.toString(), t); } try { if (executorService != null && !executorService.isTerminated()) { executorService.shutdownNow(); int count = 0; while (!executorService.awaitTermination(50, TimeUnit.MILLISECONDS)) { if (++count == 4) { LOGGER.info(LogEvents.ExecutorEvent.INIT_OR_SHUTDOWN, "InitNewJob executorService try to shutdown now"); count = 0; } executorService.shutdownNow(); } } } catch (Throwable t) { LOGGER.error( LogEvents.ExecutorEvent.INIT_OR_SHUTDOWN, t.toString(), t); } } public boolean removeJobName(String jobName){ return jobNames.remove(jobName); } class InitNewJobListener implements TreeCacheListener { @Override public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent treeCacheEvent) throws Exception { if (treeCacheEvent== null){ return; } ChildData data = treeCacheEvent.getData(); if (data == null){ return; } String path = data.getPath(); if (path == null || path.equals(JobNodePath.ROOT)){ return; } TreeCacheEvent.Type type = treeCacheEvent.getType(); if (type == null || !type.equals(TreeCacheEvent.Type.NODE_ADDED)){ return; } String jobName = StringUtils.substringAfter(path , "/"); String jobClassPath = JobNodePath.getNodeFullPath(jobName , ConfigurationNode.JOB_CLASS); for (int i = 0 ; i < WAIT_JOBCLASS_ADDED_COUNT; i ++ ){ if (!regCenter.isExisted(jobClassPath)){ Thread.sleep(200L); continue; } LOGGER.info( jobName, "new job: {} 's jobClass created event received", jobName); if (!jobNames.contains(jobName)) { if (canInitTheJob(jobName) && initJobScheduler(jobName)) { jobNames.add(jobName); LOGGER.info( jobName, "the job {} initialize successfully", jobName); } } else { LOGGER.warn( jobName, "the job {} is unnecessary to initialize, because it's already existing", jobName); } break; } } private boolean initJobScheduler(String jobName) { try{ LOGGER.info( jobName, "start to initialize the new job"); JOB_INIT_FAILED_RECORDS.get(executorName).putIfAbsent(jobName, new HashSet<Integer>()); JobConfiguration jobConfig = new JobConfiguration(regCenter, jobName); String jobTypeStr = jobConfig.getJobType(); JobType jobType = JobTypeManager.get(jobTypeStr); if (jobType == null) { String message = String .format("the jobType %s is not supported by the executor version %s", jobTypeStr, scheduleExecutorService.getExecutorVersion()); LOGGER.warn( jobName, message); throw new JobInitAlarmException(message); } if (Objects.isNull(jobType.getHandlerClass())) { throw new JobException( "unexpected error, the saturnJobClass cannot be null, jobName is %s, jobType is %s", jobName, jobTypeStr); } if (jobConfig.isDeleting()) { String serverNodePath = JobNodePath.getServerNodePath(jobName, executorName); regCenter.remove(serverNodePath); LOGGER.warn( jobName, "the job is on deleting"); return false; } JobScheduler scheduler = new JobScheduler( jobConfig , regCenter); scheduler.setScheduleExecutorService(scheduleExecutorService); scheduler.init(); // clear previous records when initialize job successfully JOB_INIT_FAILED_RECORDS.get(executorName).get(jobName).clear(); return true; } catch (JobInitAlarmException e) { if (!SystemEnvProperties.SCHEDULE_DISABLE_JOB_INIT_FAILED_ALARM) { // no need to log exception stack as it should be logged in the original happen place raiseAlarmForJobInitFailed(jobName, e); } }catch (Throwable t){ LOGGER.error(jobName , "job initialize failed, but will not stop the init process", t); } return false; } private void raiseAlarmForJobInitFailed(String jobName, JobInitAlarmException jobInitAlarmException) { String message = jobInitAlarmException.getMessage(); int messageHashCode = message.hashCode(); Set<Integer> records = JOB_INIT_FAILED_RECORDS.get(executorName).get(jobName); if (!records.contains(messageHashCode)) { try { String namespace = regCenter.getNamespace(); AlarmUtils.raiseAlarm(constructAlarmInfo(namespace, jobName, executorName, message), namespace); records.add(messageHashCode); } catch (Exception e) { LOGGER.error( jobName, "exception throws during raise alarm for job init fail", e); } } else { LOGGER.info( jobName, "job initialize failed but will not raise alarm as such kind of alarm already been raise before"); } } private Map<String, Object> constructAlarmInfo(String namespace, String jobName, String executorName, String alarmMessage) { Map<String, Object> alarmInfo = new HashMap<>(); alarmInfo.put("jobName", jobName); alarmInfo.put("executorName", executorName); alarmInfo.put("name", "Saturn Event"); alarmInfo.put("title", String.format("JOB_INIT_FAIL:%s", jobName)); alarmInfo.put("level", "CRITICAL"); alarmInfo.put("message", alarmMessage); Map<String, String> customFields = Maps.newHashMap(); customFields.put("sourceType", "saturn"); customFields.put("domain", namespace); alarmInfo.put("additionalInfo", customFields); return alarmInfo; } /** * 如果Executor配置了Groups,则只能初始化属于groups的作业; 否则初始化全部作业 */ private boolean canInitTheJob(String jobName) { Set<String> executorGroups = SystemEnvProperties.SCHEDULE_INIT_JOB_BY_GROUPS; if (executorGroups.isEmpty()){ return true; } String jobGrops = regCenter.getDirectly(JobNodePath.getNodeFullPath(jobName , ConfigurationNode.GROUPS)); if (StringUtils.isNoneBlank(jobGrops)) { String[] spilt = jobGrops.split(","); for (String temp : spilt) { if (StringUtils.isBlank(temp)) { continue; } if (executorGroups.contains(temp.trim())) { return true; } } } LOGGER.info( jobName, "the job {} wont be initialized, because it's not in the groups {}", jobName, executorGroups); return false; } } public static boolean containsJobInitFailedRecord(String executorName, String jobName, String message) { return JOB_INIT_FAILED_RECORDS.get(executorName).get(jobName).contains(message.hashCode()); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> function Dad(name,age){ this.name = name this.age = age } Dad.prototype.fn = function(){ console.log("dad fn") } function Son(name,age){ Dad.call(this,name,age) } Son.prototype.getFn = function(){ console.log("son fn") } let xiaoming = new Son("小明",20) console.log(xiaoming) // Uncaught TypeError: xiaoming.fn is not a function xiaoming.fn() /* xiaoming这个实例对象,可以调用其构造函数以及构造函数的显示原型上的属性和方法(换句话说,它的构造函数以及构造函数的显示原型的this都指向xiaoming这个实例对象) Son这个构造函数使用call将Dad这个构造函数的this指向自己,但是没能改变Dad的的显示原型的this指向 如果通过 Son.prototype = Dad.prototype 来实现this指向的改变,会有问题(两个对象的值指向同一个地址),修改Son.prototype上的属性和方法 Dad实例化后的对象也会调用Son上的属性和方法(影响了父类) */ // </script> </body> </html>
import type { File as ASTFile, Node } from '@babel/types'; interface IHbsTagSources { [key: string]: string | string[]; } interface ISearchAndExtractHbsOptions { hbsTagSources?: IHbsTagSources; parse: (source: string) => ASTFile | never; } interface IGetTemplateNodesOptions extends ISearchAndExtractHbsOptions { sortByStartKey?: boolean; } declare type ITemplateNode = Node & { template: string; startLine: number; startColumn: number; endLine: number; endColumn: number; }; export declare const defaultHbsTagSources: IHbsTagSources; /** * Search and extract ember inline templates using the `import declarations`. * * Extract both **Tagged Template** *hbs\`my tagged template\`* and **Literal String** *hbs('my literal string')*: * ```js * import hbs from 'htmlbars-inline-precompile'; * * const taggedTemplate = hbs`tagged template`; // valid * const fromFunctionCall = hbs('template from function call'); // valid * const fromFunctionCallWithArgs = hbs('from function call with args', { moduleId: 'layout.hbs' }); // valid * ``` * * ### Options: * * - `hbsTagSources` - [Optional] The **additional** hbs tag sources used in the import declaration(s), e.g.: * ```js * { * "hbs-source-with-default-export": "default", // import hbs from 'hbs-source-with-default-export'; * "hbs-source-with-named-export" : "handlebars", // import { handlebars } from 'hbs-source-wth-named-export'; * "hbs-source-with-renamed-export": "hbs" // import { hbs as h } from 'hbs-source-with-renamed-export'; * } * ``` * * - `babylonPlugins` - [Optional] The **additional** babylon plugins to use, e.g. `[ 'typescipt', 'jsx' ]`, see: * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/babylon/index.d.ts#L45. * * ### Example * * from: * ```ts * import GlimmerComponent from '@glimmer/component'; * import hbs from 'ember-cli-htmlbars-inline-precompile'; * * const template = hbs` * <button * type={{this.type}} * > * {{yield}} * </button> * `; * * class MyButtonComponent extends GlimmerComponent { * type: string = 'button'; * }; * * export default Ember._setComponentTemplate(template, MyButtonComponent); * ``` * to: * ```hbs * * * * <button * type={{this.type}} * > * {{yield}} * </button> * * ``` * * @param {string} source The script(js/ts) file content. * @param {IOptions} options The passed options. * @returns {(string | never)} The converted to hbs source. * @throws {SyntaxError} Will throw an error if invalid source(ts/js) is passed or a **missing plugin**, e.g. `flow` * plugin for **typescript syntax**. */ export declare function searchAndExtractHbs(source: string, options: ISearchAndExtractHbsOptions): string | never; /** * Parse the source(js/ts file content) and get only the template nodes array. * * Template nodes are **TaggedTemplateExpression**, **StringLiteral** and **TemplateLiteral**. * * ### Options: * * - `hbsTagSources` - [Optional] The **additional** hbs tag sources used in the import declaration(s), e.g.: * ```js * { * "hbs-source-with-default-export": "default", // import hbs from 'hbs-source-with-default-export'; * "hbs-source-with-named-export" : "handlebars", // import { handlebars } from 'hbs-source-wth-named-export'; * "hbs-source-with-renamed-export": "hbs" // import { hbs as h } from 'hbs-source-with-renamed-export'; * } * ``` * * - `parse` - [Optional] parser function. * * - `sortByStartKey` - [Optional] The extracted template nodes from the **ast** will not be ordered by their original * position in the source, so we can sort them using the `start` key, `false` by default. * * ### Example * * from: * ```js * import hbs from 'ember-cli-htmlbars-inline-precompile'; * * const taggedTemplate = hbs`my tagged template`; // `TaggedTemplateExpression` node * const stringLiteralTemplate = hbs('my string literal template'); // `StringLiteral` node * const templateLiteralTemplate = hbs(`my template literal template`); // `TemplateLiteral` node * ``` * to: * ```js * [ * { * template: 'my tagged template', * startLine: 4, * startColumn: 27, * endLine: 4, * endColumn: 45, * type: 'TemplateElement', * start: 85, * end: 103, * loc: SourceLocation { start: [Position], end: [Position] }, * value: { raw: 'my tagged template', cooked: 'my tagged template' }, * tail: true * }, * { * template: 'my string literal template', * startLine: 5, * startColumn: 35, * endLine: 5, * endColumn: 62, * type: 'StringLiteral', * start: 140, * end: 168, * loc: SourceLocation { start: [Position], end: [Position] }, * extra: { * rawValue: 'my string literal template', * raw: "'my string literal template'" * }, * value: 'my string literal template' * }, * { * template: 'my template literal template', * startLine: 6, * startColumn: 37, * endLine: 6, * endColumn: 65, * type: 'TemplateElement', * start: 208, * end: 236, * loc: SourceLocation { start: [Position], end: [Position] }, * value: { * raw: 'my template literal template', * cooked: 'my template literal template' * }, * tail: true * } * ] * ``` * * @param {string} source The script(js/ts) file content. * @param {IGetTemplateNodesOptions} options The passed options. * @returns {ITemplateNode[]} The extracted template nodes array. * @throws {SyntaxError} Will throw an error if invalid source(ts/js) is passed or a **missing plugin**, e.g. `flow` * plugin for **typescript syntax**. */ export declare function getTemplateNodes(source: string, options: IGetTemplateNodesOptions): ITemplateNode[]; export {};
import { Injectable, OnInit, OnDestroy } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Router, NavigationEnd } from '@angular/router'; import { BehaviorSubject, Subscription, Observable } from 'rxjs'; import { AuthService } from '../auth.service'; import { DisplayCoUser } from '../auth-data.model'; import { environment } from '../../../environments/environment'; /** 16102020 - Gaurav - GraphQL API changes */ import { Apollo } from 'apollo-angular'; import gql from 'graphql-tag'; import { map } from 'rxjs/operators'; const BACKEND_URL = `${environment.apiUrl}/users`; @Injectable({ providedIn: 'root' }) export class UserService implements OnDestroy { tabs = Object.freeze({ USER_SETTINGS: 'USER_SETTINGS', USER_CAMPGROUNDS: 'USER_CAMPGROUNDS', USER_NOTIFICATIONS: 'USER_NOTIFICATIONS', }); UserActivityPayload: Observable<any>; CoUserDataPayload: Observable<any>; ToggleUserUpdate: Observable<any>; private authStatusSub$: Subscription; private currentUserId: string; private coUserId: string; private _showOnInitTab = this.tabs.USER_CAMPGROUNDS; private _currentUrl: string; private _userRouteChangeListener = new BehaviorSubject<{ showTab: string; showCoUser: boolean; }>({ showTab: this.tabs.USER_CAMPGROUNDS, showCoUser: false, }); constructor( private http: HttpClient, private router: Router, private authService: AuthService, private _apollo: Apollo ) { // Calling this subscription DID NOT work in ngOnInit() this.authStatusSub$ = this.authService .getAuthStatusListener() .subscribe((authStatus) => { this.currentUserId = authStatus.userId; // console.log('this.currentUserId', this.currentUserId); }); this.router.events.subscribe((event) => { if (event instanceof NavigationEnd) { this._currentUrl = event.url; // console.log(this._currentUrl); const substr = this._currentUrl.substr( this._currentUrl.lastIndexOf('/') + 1 ); switch (substr) { case 'current': this._showOnInitTab = this.tabs.USER_SETTINGS; break; case 'notifications': this._showOnInitTab = this.tabs.USER_NOTIFICATIONS; break; default: this._showOnInitTab = this.tabs.USER_CAMPGROUNDS; } // This may be same when if (this._currentUrl.includes('/other')) { // this may happen if user had an /other with own id (a link in email) if (substr === this.currentUserId) { this.coUserId = null; router.navigate(['/user/current']); } else { this.coUserId = substr; } } else { this.coUserId = null; } this._userRouteChangeListener.next({ showTab: this._showOnInitTab, showCoUser: !!this.coUserId, }); } }); } ngOnDestroy() { this.authStatusSub$?.unsubscribe(); } getUserRouterChangeListener() { return this._userRouteChangeListener.asObservable(); } getCoUserData() { if (environment.useApi === 'GRAPHQL') { this.CoUserDataPayload = this._apollo .watchQuery<{ coUser: { coUserData: any; userCampgrounds: any }; }>({ query: gql` query GetCoUserDataPayload($userId: ID!) { coUser(_id: $userId) { coUserData { coUserId email username firstname lastname avatar followers } userCampgrounds { campgroundId campgroundName } } } `, variables: { userId: this.coUserId, }, }) .valueChanges.pipe(map(({ data: { coUser } }) => coUser)); return this.CoUserDataPayload; } else { return this.http.get<{ message: string; coUserData: DisplayCoUser; userCampgrounds: []; }>(`${BACKEND_URL}/${this.coUserId}`); } } getUserActivity(userId: string) { if (environment.useApi === 'GRAPHQL') { this.UserActivityPayload = this._apollo .watchQuery<{ userActivity: { userCampgrounds: any; userComments: any }; }>({ query: gql` query GetUserActivity { userActivity { userCampgrounds { _id name createdAt } userComments { _id } } } `, }) .valueChanges.pipe( map( ({ data: { userActivity: { userCampgrounds, userComments }, }, }) => { return { userCampgrounds: userCampgrounds.map((record) => { return { campgroundId: record._id, campgroundName: record.name, campgroundCreatedAt: record.createdAt, }; }), userComments, }; } ) ); return this.UserActivityPayload; } else { return this.http.get<{ message: string; userCampgrounds: []; userComments: []; }>(`${BACKEND_URL}/activity/${userId}`); } } toggleFollowUser( userToFollowId: string, followerUserId: string, follow: boolean ) { if (environment.useApi === 'GRAPHQL') { this.ToggleUserUpdate = this._apollo.mutate({ mutation: gql` mutation ToggleFollowUser( $userToFollowId: String! $follow: Boolean! ) { toggleFollowUser(userToFollowId: $userToFollowId, follow: $follow) } `, variables: { userToFollowId, follow, }, }); return this.ToggleUserUpdate; } else { return this.http.post<{ message: string }>(`${BACKEND_URL}/follow`, { userToFollowId, followerUserId, follow, }); } } redirectToHomePage(): void { this.router.navigate(['/campgrounds']); } }
import React from 'react' import { Box, useTheme } from '@mui/material' import Header from '../component/Header' import { useGetCustomersQuery } from '../state/api' import { DataGrid } from "@mui/x-data-grid" import CustomerCustomToolbar from '../component/CustomerCustomToolbar' const Customers = () => { const theme = useTheme(); const { data, isLoading } = useGetCustomersQuery(); const columns = [ { field: "_id", headerName: "ID", flex: 1, }, { field: "name", headerName: "Name", flex: 0.5, }, { field: "email", headerName: "Email", flex: 1, }, { field: "phoneNumber", headerName: "Phone Number", flex: 0.5, renderCell: (params) => { return params.value.replace(/^(\d{3})(\d{3})(\d{4})/, "($1)$2-$3"); }, }, { field: "country", headerName: "Country", flex: 0.4, }, { field: "occupation", headerName: "Occupation", flex: 1, }, { field: "role", headerName: "Role", flex: 0.5, }, ]; return ( <div className='my-4 mx-6 overflow-y-auto'> <Header title="CUSTOMERS" subtitle="List of Customers"/> <div className='h-[75vh] mt-4'> <DataGrid rows={data || []} columns={columns} getRowId={(row) => row._id} loading={isLoading || !data} components={{ Toolbar: CustomerCustomToolbar }} sx={{ "& .MuiDataGrid-columnHeaders": { backgroundColor: theme.palette.color.background2, color: theme.palette.color.text2, fontWeight: 700 }, "& .MuiDataGrid-columnHeaderTitle": { color: theme.palette.color.text2, fontWeight: 700 }, "& .MuiDataGrid-virtualScroller": { backgroundColor: theme.palette.color.background2, }, "& .MuiDataGrid-footerContainer": { backgroundColor: theme.palette.color.background2, color: theme.palette.color.text2, borderTop: "none", }, "& .MuiDataGrid-toolbarContainer .MuiButton-text": { color: `${theme.palette.color.text2} !important`, }, }} /> </div> </div> ) } export default Customers
import React, { useEffect, useState } from "react"; import LayoutCustomer from "../../layouts/LayoutCustomer"; import { useParams } from "react-router-dom"; import { Box, Grid } from "@mui/material"; import BreadcrumbsNav from "../../components/nav-crumbs/Breadcrumbs "; import FilterSideBar from "./FilterSideBar"; import { shallowEqual, useDispatch, useSelector } from "react-redux"; import * as productAction from "../Admin/Product/api/productAction"; import ListContentProduct from "./ListContentProduct"; const Content = () => { const { slug } = useParams(); const defaultValues = { tenDanhMuc: slug, sizes: "", }; const [filter, setFilter] = useState(defaultValues); const [valuesPrice, setValuePrice] = useState(null); const { currentState } = useSelector( (state) => ({ currentState: state.product }), shallowEqual ); const { productDataDanhMuc: productData } = currentState; const dispatch = useDispatch(); useEffect(() => { dispatch(productAction.fetchProductCustomer({ params: { ...filter } })); }, [dispatch, filter]); const handleFilter = (values) => { setFilter({ ...filter, sizes: values, }); }; useEffect(() => { if (slug) { setFilter({ ...filter, tenDanhMuc: slug, }); } }, [slug]); const handleValuePrice = (value) => { setValuePrice({ ...valuesPrice, ...value, }); }; const handleSearched = (type) => { if (type === "reset") { setFilter({ ...filter, fromPrice: 500000, toPrice: 20000000, }); } else { setFilter({ ...filter, ...valuesPrice, }); } }; return ( <LayoutCustomer> <Box className="max-w-[1200px] w-full mx-auto mb-5"> <Box sx={{ paddingY: "20px" }}> <BreadcrumbsNav title="Trang chủ" subtitle={slug} /> </Box> <Grid container> <Grid item md={3}> <FilterSideBar onFilter={handleFilter} valuePrice={handleValuePrice} onSearched={handleSearched} /> </Grid> <Grid item md={9}> <ListContentProduct data={productData ? productData : null} /> </Grid> </Grid> </Box> </LayoutCustomer> ); }; export default Content;
import { IUserRepository } from '../IUser.repository'; import { UserModel } from '@db/models/User.model'; import { User } from '../../entities/User'; import { IUpdateUser, IUser, IUserList } from '@interfaces/IUser.interface'; import { getSqlOptions } from '../../helpers/customSQL'; export class UserRepository implements IUserRepository { public async createUser(createUserInput: User): Promise<IUser> { try { const newUser = new User(createUserInput); return await UserModel.create({...newUser}); } catch (err) { throw new Error(err); } } public async getUserById(userId: string): Promise<IUser> { try { return await UserModel.findByPk(userId); } catch (err) { throw new Error(err); } } public async getUserList(filter): Promise<IUserList> { const { limit, offset, order, orientation, where, raw } = getSqlOptions.userListOptions(filter); try { const userListFromDB = await UserModel.findAndCountAll({ limit, offset, order: [[order, orientation]], where, raw }); return { data: userListFromDB.rows, totalCount: userListFromDB.count }; } catch (err) { throw new Error(err); } } public async updateUser(userId: string, updateUserInput: IUpdateUser): Promise<IUser> { try { const userToBeUpdated = await UserModel.findByPk(userId); userToBeUpdated.set(updateUserInput); return await userToBeUpdated.save(); } catch (err) { throw new Error(err); } } public async removeUser(userId: string): Promise<IUser> { try { const userToBeRemoved = await UserModel.findByPk(userId); userToBeRemoved.set('removedAt', new Date()); return await userToBeRemoved.save(); } catch (err) { throw new Error(err); } } }
def rle_encode(text, use_bwt=True): r"""Perform encoding of run-length-encoding (RLE). This is a wrapper for :py:meth:`RLE.encode`. Parameters ---------- text : str A text string to encode use_bwt : bool Indicates whether to perform BWT encoding before RLE encoding Returns ------- str Word decoded by RLE Examples -------- >>> rle_encode('align') 'n\x00ilag' >>> rle_encode('align', use_bwt=False) 'align' >>> rle_encode('banana') 'annb\x00aa' >>> rle_encode('banana', use_bwt=False) 'banana' >>> rle_encode('aaabaabababa') 'ab\x00abbab5a' >>> rle_encode('aaabaabababa', False) '3abaabababa' """ if use_bwt: text = BWT().encode(text) return RLE().encode(text)
import { useState, useEffect } from "react"; import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js"; import { Pie } from "react-chartjs-2"; import Question from "./Question"; import { createRoutesFromElements, useNavigate, createBrowserRouter, Link, } from "react-router-dom"; import { Route } from "react-router"; import "../styles/QuestionList.scss"; import Dashboard from "../pages/dashboard"; import "../styles/ExamGenerated.scss" const QuestionList = (props) => { ChartJS.register(ArcElement, Tooltip, Legend); // console.log("questionlist", props) // const [currentQuestion, setCurrentQuestion] = useState(0); const [selectedOption, setSelectedOption] = useState(null); const [showResults, setShowResults] = useState(false); const [userInput, setUserInput] = useState([]); const [correct, setCorrect] = useState(false); const [incorrect, setIncorrect] = useState(false); const navigate = useNavigate(); // console.log("user input", userInput); // useEffect(() => { // fetch("http://localhost:8080/dashboard") // .then((res) => res.json()) // .then((data) => { // props.setUserQuestion(data); // }); // }, []); const questions = props.questions; //validation of answer and change set of message Correct or incorrect const handleOptionChange = (e) => { const userAnswer = e.target.value; setUserInput([...userInput, userAnswer]); setSelectedOption(userAnswer); // console.log("user answer", userAnswer); if (userAnswer === questions[props.currentQuestion].answer) { setCorrect(true); props.setFinalScore(props.finalScore + 1); } else { setIncorrect(true); } }; // Move to the next question const handleNextQuestion = () => { setSelectedOption(null); setCorrect(false); setIncorrect(false); if (props.currentQuestion + 1 < questions.length) { props.setCurrentQuestion(props.currentQuestion + 1); } else { setShowResults(true); } }; // finish exam an redirect to Daschboard const finishExam = () => { navigate("/dashboard"); const finalScore = props.finalScore; const result = { finalScore, userInput }; fetch("http://localhost:8080/result", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(result), }).then(() => { console.log("user answer added"); }); }; const data = { labels : ["correct", "incorrect"], datasets : [ { label: "results", data: [props.finalScore, questions.length - props.finalScore], // data: [3, 5], backgroundColor: ["#85C1E9", "#EC7063"], borderColor: "black" } ] }; const options = { responsive : true, title : { display : true, text : "Pia chart" }, } const mappedQuestion = questions.map((question, index) => { return ( <Question key={index} id={index} question={question.question} options={question.options} answer={question.answer} feedback={question.feedback} currentQuestion={props.currentQuestion} selectedOption={selectedOption} handleOptionChange={handleOptionChange} handleNextQuestion={handleNextQuestion} correct={correct} incorrect={incorrect} /> ); }); return ( <> {showResults ? ( <div className="final-results"> <h1>Fianl Results</h1> <div style={ {width: "50%"}}> <Pie data = {data} options={options} /> </div> <h2> {props.finalScore} out of {questions.length} correct - ( {(props.finalScore / questions.length) * 100}%) </h2> <button className="button-pushable" onClick={finishExam}> <span class="button-shadow"></span> <span class="button-edge"></span> <span class="button-front text">Finish Exam</span> </button> </div> ) : ( <div className="question-list">{mappedQuestion}</div> )} </> ); }; export default QuestionList;
import styled from "styled-components"; const StyledTestimonials = styled.div` background-color: #f8f8f8; padding: 12rem 0; `; const Layout = styled.div` max-width: 110rem; margin: 0 auto; height: 100%; `; const Header = styled.div` display: flex; flex-direction: column; gap: 1.6rem; align-items: center; text-align: center; max-width: 70rem; margin: 0 auto; `; const H4 = styled.h4` font-size: 2.6rem; font-weight: 500; color: var(--color-text-black); @media (max-width: 600px) { font-size: 2rem; } @media (max-width: 490px) { font-size: 1.6rem; } `; const H2 = styled.h2` font-size: 4.8rem; color: var(--color-text-black); @media (max-width: 600px) { font-size: 4rem; } @media (max-width: 490px) { font-size: 3.6rem; } `; const P = styled.p` color: #706f7b; font-size: 1.8rem; line-height: 1.4; @media (max-width: 600px) { font-size: 1.4rem; line-height: 1.2; max-width: 80%; } @media (max-width: 490px) { font-size: 1.2rem; } `; const TestimonialsBoxes = styled.div` display: grid; grid-template-columns: repeat(2, 1fr); gap: 5rem; margin-top: 5rem; @media (max-width: 1180px) { justify-items: center; } @media (max-width: 950px) { grid-template-columns: 1fr; padding: 0 4rem; } `; const Box = styled.div` padding: 8rem 6rem; background-color: #fff; box-shadow: rgba(0, 0, 0, 0.05) 0px 6px 24px 0px, rgba(0, 0, 0, 0.08) 0px 0px 0px 1px; position: relative; `; const BoxP = styled.p` font-size: 2.2rem; font-weight: 600; color: var(--color-text-black); @media (max-width: 400px) { font-size: 1.8rem; } `; const BoxFooter = styled.div` display: flex; gap: 2rem; align-items: center; margin-top: 3rem; `; const Img = styled.img` border-radius: 50%; height: 7rem; width: 7rem; `; const Info = styled.div` display: flex; flex-direction: column; gap: 1.2rem; `; const Name = styled.h4` font-size: 1.8rem; color: var(--color-text-black); @media (max-width: 400px) { font-size: 1.4rem; } `; const Country = styled.p` font-size: 1.6rem; font-weight: 400; color: var(--color-text-black); @media (max-width: 400px) { font-size: 1.2rem; } `; const Svg = styled.svg` position: absolute; bottom: 8rem; right: 6rem; color: var(--color-orange); @media (max-width: 400px) { height: 5rem; right: 2rem; } `; function Testimonials() { return ( <StyledTestimonials> <Layout> <Header> <H4>Reviewed by People</H4> <H2>Client's Testimonials</H2> <P> Discover the positive impact we've made on the our clients by reading through their testimonials. Our clients have experienced our service and results, and they're eager to share their positive experiences with you. </P> </Header> <TestimonialsBoxes> <Box> <Svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="tabler-icon tabler-icon-quote" > <path d="M10 11h-4a1 1 0 0 1 -1 -1v-3a1 1 0 0 1 1 -1h3a1 1 0 0 1 1 1v6c0 2.667 -1.333 4.333 -4 5"></path> <path d="M19 11h-4a1 1 0 0 1 -1 -1v-3a1 1 0 0 1 1 -1h3a1 1 0 0 1 1 1v6c0 2.667 -1.333 4.333 -4 5"></path> </Svg> <BoxP> "We rented a car from this website and had an amazing experience! The booking was easy and the rental rates were very affordable. " </BoxP> <BoxFooter> <Img src="./testimonials/pfp1.jpg" alt="Parry Potter"></Img> <Info> <Name>Parry Hotter</Name> <Country>Belgrade</Country> </Info> </BoxFooter> </Box> <Box> <Svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="tabler-icon tabler-icon-quote" > <path d="M10 11h-4a1 1 0 0 1 -1 -1v-3a1 1 0 0 1 1 -1h3a1 1 0 0 1 1 1v6c0 2.667 -1.333 4.333 -4 5"></path> <path d="M19 11h-4a1 1 0 0 1 -1 -1v-3a1 1 0 0 1 1 -1h3a1 1 0 0 1 1 1v6c0 2.667 -1.333 4.333 -4 5"></path> </Svg> <BoxP> "The car was in great condition and made our trip even better. Highly recommend for this car rental website!"{" "} </BoxP> <BoxFooter> <Img src="./testimonials/pfp2.jpg" alt="Ron Rizzly"></Img> <Info> <Name>Ron Rizzly</Name> <Country>Novi Sad</Country> </Info> </BoxFooter> </Box> </TestimonialsBoxes> </Layout> </StyledTestimonials> ); } export default Testimonials;
package com.bigodebombado.backend.Controller; import com.bigodebombado.backend.Exception.ResourceNotFoundException; import com.bigodebombado.backend.Model.User.User; import com.bigodebombado.backend.Repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; @RestController @CrossOrigin(origins = "http://localhost:4200") @RequestMapping("/workprousers") public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/users") public List<User> getAllUsers() { return userRepository.findAll(); } @GetMapping("/users/{id}") public ResponseEntity<User> getUserById (@PathVariable(value = "id") Long userId) throws ResourceNotFoundException { User user = userRepository.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("User not found for this id :: " + userId)); return ResponseEntity.ok().body(user); } @PostMapping("/users") public User createUser(@Valid @RequestBody User user){ return userRepository.save(user); } // @PutMapping("/users/{id}") // public ResponseEntity<User> updateUser (@PathVariable(value = "id") Long userId, // @Valid @RequestBody User userDetails) throws ResourceNotFoundException{ // User user = userRepository.findById(userId) // .orElseThrow(() -> new ResourceNotFoundException("User not found for this id :: " + userId)); // // user.setFirstName(userDetails.getFirstName()); // user.setLastName(userDetails.getLastName()); // user.setEmail(userDetails.getEmail()); // user.setPassword(userDetails.getPassword()); // // final User updatedUser = userRepository.save(user); // return ResponseEntity.ok(updatedUser); // } @DeleteMapping("/users/{id}") public Map<String, Boolean> deleteUser(@PathVariable(value = "id") Long userId) throws ResourceNotFoundException{ User user = userRepository.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("User not found for this id :: " + userId)); userRepository.delete(user); Map<String, Boolean> response = new HashMap<>(); response.put("deleted", Boolean.TRUE); return response; } }
class Bicycle { // displays bicycle /* every part is available in multiple styles: race, regular, mtb all in their own respective style folder every part is called wheel.png, frame.png etc. the default bicycle shown when nothing has been selected is the mountain bike*/ PImage wheelImage = loadImage("bikeparts/mtb/wheels.png"); PImage frameImage = loadImage("bikeparts/mtb/frame.png"); PImage handlebarImage = loadImage("bikeparts/mtb/handlebars.png"); /* floats for offsets, every bicycle frame has different attachment points for the bicycle parts, these values change when changing frames, default is that of mountain bike */ float frameXPosition = width/2; float frameYPosition = height/2.18; float leftWheelXOffset = -0.13*width; float rightWheelXOffset = 0.1275*width; float wheelsYOffset = 0.1*height; float handlebarXOffset = 0.0825*width; float handlebarYOffset = -0.14*height; void display() { pushMatrix(); translate(frameXPosition, frameYPosition); // set position of the frame to be 0,0 pushMatrix(); translate(leftWheelXOffset, wheelsYOffset); // set the wheels to be in their own matrix, for rotating rotate(0.1*frameCount); image(wheelImage, 0, 0); // left wheel popMatrix(); pushMatrix(); translate(rightWheelXOffset, wheelsYOffset); // set the wheels to be in their own matrix, for rotating rotate(0.1*frameCount); image(wheelImage, 0, 0); // right wheel popMatrix(); image(frameImage, 0, 0); // frame image(handlebarImage, handlebarXOffset, handlebarYOffset); // handlebars popMatrix(); } }
options { // force creation of instance-style parser STATIC = false; } PARSER_BEGIN(XPathTransformer) // place the transformer in a meaningful package package nl.utwente.cs.pxml.transform.xpath; import java.io.StringReader; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import nl.utwente.cs.pxml.util.CollectionUtils; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; /** * XPathTransformer - JavaCC-generated parser to transform an XPath-expression on an a regular context to an * XQuery-expression of that same document with a probabilistic overlay. */ class XPathTransformer { // store the currently supported axes for ease of use public static final List<String> SUPPORTED_AXES = Arrays.asList("child", "descendant"); // store the axes participating in 'anchor' optimization public static final List<String> ANCHOR_AXES = Arrays.asList("child", "descendant-or-self", "descendant"); // parameter to enable 'anchor' optimization @Parameter(names = "--anchor-opt", description = "use anchor optimization") protected boolean anchorOpt = false; // parameter to capture required arguments (required to be a list...) @Parameter(description = "<xpath-expression>", required = true) protected List<String> input; // helper variable to work around XQuery's immutable variables protected int currentStep = 0; // empty constructor (to be able to use it with JCommander) public XPathTransformer() { } // copied from generated code to be able to bypass constructor protected void init(Reader stream) { jj_input_stream = new SimpleCharStream(stream, 1, 1); token_source = new XPathTransformerTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 1; i++) jj_la1[i] = -1; } /** * Generates lines of XQuery code to perform a single step (in practice only supports descendant-style axes). * * @param step * The XPath step to take. */ protected List<String> stepCode(String step) { List<String> expression = new ArrayList<String>(); // increment step counter this.currentStep++; expression.add(""); expression.add("(: take step " + this.currentStep + ": " + step + " :)"); // create 'next' context expression.add(String.format("for $context%d in $context%d/%s", this.currentStep, this.currentStep - 1, step)); // collect variable descriptors and combine expression.add(String.format(" let $descriptors%d := pxml:combine($descriptors%d, $context%d/ancestor-or-self::*/@p:descriptors/string())", this.currentStep, this.currentStep - 1, this.currentStep)); // prune inconsistent possibilities expression.add(String.format(" where pxml:consistent($descriptors%d)", this.currentStep)); expression.add("return"); return expression; } public static void main(String... args) { // create a new transformer XPathTransformer transformer = new XPathTransformer(); JCommander arguments = new JCommander(transformer); // parse the input string, the result is a string containing the resulting XQuery-expression try { // have JCommander parse and assign arguments arguments.parse(args); // force the transformer to (re)init using the captured input transformer.init(new StringReader(transformer.input.get(0))); // compile input to output String code = transformer.parseInput(); // print header System.out.println("(: transforming XPath expression " + transformer.input.get(0) + " :)\n"); // print the actual generated code System.out.println(code); } catch (ParameterException e) { arguments.usage(); System.exit(1); } catch (ParseException e) { System.err.println(e.getMessage()); System.exit(1); } catch (TokenMgrError e) { System.err.println(e.getMessage()); System.exit(1); } } /** * Simple record class combining an axis and a node test. */ public class AxisStep { // the axis this step takes public final String axis; // the node test along the axis public final String nodeTest; public AxisStep(String axis, String nodeTest) { this.axis = axis; this.nodeTest = nodeTest; } /** * Prints a verbose axis step in the form * axis::nodeTest */ @Override public String toString() { return this.axis + "::" + this.nodeTest; } } } PARSER_END(XPathTransformer) TOKEN : { // string constant (document name) < STRING : ("\""(["A"-"z", "0"-"9", ".", "_", "-"])*"\"") > // XPath step character | < STEP : "/" > // XPath axis names (copied from http://www.w3.org/TR/xpath/ section 2.2) | < AXIS : "ancestor" | "ancestor-or-self" | "attribute" | "child" | "descendant" | "descendant-or-self" | "following" | "following-sibling" | "namespace" | "parent" | "preceding" | "preceding-sibling" | "self" > // separator between axis name and node test | < SEPARATOR : "::" > | < NODETEST : (["A"-"z", "_"])(["0"-"9", "A"-"z", "_"])* | "*" | "comment()" | "text()" | "processing-instruction()" | "node()" > } String parseInput() : { String docName; AxisStep axisStep; boolean onDescendantAxis = false; List<String> anchorBacklog = new ArrayList<String>(); List<String> expression = new ArrayList<String>(); } { // start with a document name match docName = document() { // declare a namespace for the answers expression.add("declare namespace p = \"http://www.cs.utwente.nl/~keulen/pxml\";"); // import PXML query module expression.add("import module namespace pxml = \"java:nl.utwente.cs.pxml.PXML\";"); // declare some variables to be used expression.add(""); // start of XQuery content (collect answers in result node) expression.add("<p:result>{"); expression.add(""); expression.add("let $context0 := doc(" + docName + ")"); // quotes are included in the document name expression.add("let $descriptors0 := \"\""); } // proceed with one or more axis steps ( axisStep = axisStep() { // check if the axis is supported if (!SUPPORTED_AXES.contains(axisStep.axis)) { // TODO: throw more meaningful exception throw new RuntimeException("axis " + axisStep.axis + " is not supported"); } if (this.anchorOpt && ANCHOR_AXES.contains(axisStep.axis)) { // optimize descendant axis if requested anchorBacklog.add(axisStep.toString()); } else { // if backlog is not empty and we got to this point, clear backlog now before appending current step if (!anchorBacklog.isEmpty()) { expression.addAll(this.stepCode(CollectionUtils.join(anchorBacklog, "/"))); anchorBacklog.clear(); } // append code for current step expression.addAll(this.stepCode(axisStep.toString())); } } )+ { // first check to see if backlog is clear if (!anchorBacklog.isEmpty()) { expression.addAll(this.stepCode(CollectionUtils.join(anchorBacklog, "/"))); anchorBacklog.clear(); } // prepare result variables expression.add(""); expression.add("(: all steps taken, calculate probabilities for all resulting nodes :)"); expression.add("let $answer := $context" + this.currentStep); expression.add("let $descriptors := $descriptors" + this.currentStep); expression.add("let $probability := pxml:probability($context0//p:variables, $descriptors)"); // output result nodes expression.add(""); expression.add("return <p:answer p:descriptors=\"{$descriptors}\" p:probability=\"{$probability}\">{$answer}</p:answer>"); // end of XQuery expression, close scope and result node expression.add(""); expression.add("}</p:result>"); // return final expression as a single string return CollectionUtils.join(expression, "\n"); } } /** * Matches a document reference of the form * doc("docName.xml") * and returns the string literal (including the quotes). */ String document() : { // use local variable docName to store document name token Token docName; } { "doc(" docName = < STRING > ")" { // return the string constant (including quotes) return docName.image; } } /** * Matches a single XPath axis step of the form * /axis::nodeTest * and returns it as it was matched. */ AxisStep axisStep() : { // use local variable axis to store the axis (initialized at null so javac won't complain about initialization) Token axis = null; // use local variable nodeTest to store the nodeTest on the axis Token nodeTest = null; } { < STEP > axis = < AXIS > < SEPARATOR > nodeTest = < NODETEST > { // return the input, an XPath axis step return new AxisStep(axis.image, nodeTest.image); } }
<?php namespace Laraditz\Bayar; use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; class BayarServiceProvider extends ServiceProvider { /** * Bootstrap the application services. */ public function boot() { /* * Optional methods to load your package assets */ // $this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'bayar'); $this->loadViewsFrom(__DIR__ . '/../resources/views', 'bayar'); $this->loadMigrationsFrom(__DIR__ . '/../database/migrations'); $this->registerRoutes(); if ($this->app->runningInConsole()) { $this->publishes([ __DIR__ . '/../config/config.php' => config_path('bayar.php'), ], 'config'); // Publishing the views. /*$this->publishes([ __DIR__.'/../resources/views' => resource_path('views/vendor/bayar'), ], 'views');*/ // Publishing assets. /*$this->publishes([ __DIR__.'/../resources/assets' => public_path('vendor/bayar'), ], 'assets');*/ // Publishing the translation files. /*$this->publishes([ __DIR__.'/../resources/lang' => resource_path('lang/vendor/bayar'), ], 'lang');*/ // Registering package commands. // $this->commands([]); } } /** * Register the application services. */ public function register() { // Automatically apply the package configuration $this->mergeConfigFrom(__DIR__ . '/../config/config.php', 'bayar'); // Register the main class to use with the facade $this->app->singleton('bayar', function ($app) { return new Bayar($app); }); } protected function registerRoutes() { $config = $this->routeConfiguration(); Route::name($config['name']) ->prefix($config['prefix']) ->middleware($config['middleware']) ->group(function () { $this->loadRoutesFrom(__DIR__ . '/../routes/web.php'); }); } protected function routeConfiguration() { return [ 'prefix' => config('bayar.route_prefix'), 'name' => config('bayar.route_name'), 'middleware' => config('bayar.middleware'), ]; } }
import BasePublic import CommonCorePublic import Foundation /// The `DivStateManagement` protocol provides essential functionality for managing card states. /// /// Conforming to this protocol allows your class to handle state management for cards. It requires /// the implementation of three methods: /// - `getStateManagerForCard(cardId:)`: This method should return a ``DivStateManager`` object /// associated with the given `cardId`. /// - `reset()`: This method resets states for all cards. /// - `reset(cardId:)`: This method resets the state for the card identified by the provided /// `cardId`. public protocol DivStateManagement: DivStateUpdater { /// Retrieves the `DivStateManager` object associated with the given `cardId`. /// /// - Parameter cardId: The identifier of the card. /// - Returns: A `DivStateManager` object for the specified card. func getStateManagerForCard(cardId: DivCardID) -> DivStateManager /// Resets states for all cards. func reset() /// Resets the state for the card identified by the provided `cardId`. /// /// - Parameter cardId: The identifier of the card to reset. func reset(cardId: DivCardID) } public class DefaultDivStateManagement: DivStateManagement { static let storageFileName = "divkit.states_storage" private let timestampProvider: Variable<Milliseconds> private var persistentStorage = Property<StoredStates>( fileName: storageFileName, initialValue: StoredStates(items: [:]), onError: { error in DivKitLogger.error("Failed to create storage: \(error)") } ) private var stateManagersForCards: [DivCardID: DivStateManager] = [:] public init( timestampProvider: Variable<Milliseconds> = Variable { Date().timeIntervalSince1970.milliseconds } ) { self.timestampProvider = timestampProvider removeOutdatedStoredStates() } public func set( path: DivStatePath, cardId: DivCardID, lifetime: DivStateLifetime ) { let stateManager = getStateManagerForCard(cardId: cardId) let (parentPath, stateId) = path .split() ?? (DivData.rootPath, DivStateID(rawValue: path.rawValue.root)) stateManager.setStateWithHistory(path: parentPath, stateID: stateId) stateManagersForCards[cardId] = stateManager if lifetime == .long { var storedStates = persistentStorage.value var storedStatesForCard = storedStates.getStates(cardId: cardId) storedStatesForCard[parentPath] = StoredState( stateId: stateId, timestamp: timestampProvider.value ) storedStates.items[cardId] = storedStatesForCard persistentStorage.value = storedStates } } public func getStateManagerForCard(cardId: DivCardID) -> DivStateManager { if let stateManager = stateManagersForCards[cardId] { return stateManager } let storedStates = persistentStorage.value.getStates(cardId: cardId) let stateManager = DivStateManager( items: storedStates.mapValues { DivStateManager.Item( currentStateID: $0.stateId, previousState: .initial ) } ) stateManagersForCards[cardId] = stateManager return stateManager } public func reset() { stateManagersForCards.values.forEach { $0.reset() } } public func reset(cardId: DivCardID) { stateManagersForCards[cardId]?.reset() } private func removeOutdatedStoredStates() { let currentTimestamp = timestampProvider.value let items = persistentStorage.value.items let newItems = items.compactMapValues { states in let newStates = states.filter { _, state in currentTimestamp - state.timestamp < storagePeriod } return (newStates.count > 0) ? newStates : nil } if newItems != items { persistentStorage.value = StoredStates(items: newItems) } } } struct StoredStates: Equatable, Codable { var items: [DivCardID: [DivStatePath: StoredState]] func getStates(cardId: DivCardID) -> [DivStatePath: StoredState] { items[cardId] ?? [:] } } struct StoredState: Equatable, Codable { let stateId: DivStateID let timestamp: Milliseconds } private let storagePeriod = 2 * 24 * 60 * 60 * 1000
<ion-header [translucent]="true"> <ion-toolbar> <ion-title> Meu App </ion-title> </ion-toolbar> </ion-header> <ion-content [fullscreen]="true" class="ion-padding"> <h1>Modelos</h1> <ion-item> <ion-label position="stacked">Digite sua pesquisa</ion-label> <ion-input [(ngModel)]="pesquisa" type="text"></ion-input> </ion-item> <ion-button (click)="recuperar()" routerDirection="forward" expand="full" color="warning"> Click </ion-button> <br> {{ resultado }} <br> <h1>Navegação</h1> <ion-grid fixed> <ion-row> <ion-col size="6"> <ion-button [href]="'/botoes/'" routerDirection="forward" expand="full" color="warning"> Botão </ion-button> </ion-col> <ion-col size="6" class="ion-text-end"> <ion-button [href]="'/lista/'" routerDirection="forward" expand="full" color="warning"> Lista </ion-button> </ion-col> </ion-row> </ion-grid> <h1>Navegação 2</h1> <h6>Forma mais rapida. </h6> <ion-grid fixed> <ion-row> <ion-col size="6"> <ion-button (click)="abrirBotoes()" expand="full" color="secondary"> Botão </ion-button> </ion-col> <ion-col size="6" class="ion-text-end"> <ion-button (click)="abrirLista()" expand="full" color="secondary"> Lista </ion-button> </ion-col> </ion-row> </ion-grid> <!-- <h1>{{ titulo }}</h1> <h4>Event Binding</h4> <ion-item> <ion-label position="stacked">Nome:</ion-label> <ion-input (input)="atualiza()" ></ion-input> </ion-item> <ion-item> <ion-label position="stacked">Nome:</ion-label> <ion-input (click)="normaliza()"></ion-input> </ion-item> <h4>String interpolation</h4> {{ 2 + 2 }} <br> <ion-img src="{{ imagemLocal }}"></ion-img> <h4>Propety Binding</h4> <ion-img [src]="imagemRandomica"></ion-img> <h1>Grid</h1> <ion-grid fixed> <ion-row> <ion-col size="6">Teste-1</ion-col> <ion-col size="3" offset="3">Teste-2</ion-col> </ion-row> </ion-grid> <ion-grid fixed> <ion-row> <ion-col size="9">Teste-1</ion-col> <ion-col size="3">Teste-2</ion-col> </ion-row> <ion-row> <ion-col size="4">Teste-1</ion-col> <ion-col size="4">Teste-2</ion-col> <ion-col size="4">Teste-3</ion-col> </ion-row> </ion-grid> <h4>Grid: Alinhamento de textos. </h4> <ion-grid fixed> <ion-row class="ion-text-end"> <ion-col size="4">1</ion-col> <ion-col size="4">2</ion-col> <ion-col size="4">3</ion-col> </ion-row> </ion-grid> <ion-grid fixed> <ion-row class="ion-text-center"> <ion-col size="4">1</ion-col> <ion-col size="4">2</ion-col> <ion-col size="4">3</ion-col> </ion-row> </ion-grid> <h4>Grid: Alinhamento vertical. </h4> <ion-grid fixed> <ion-row class="ion-align-items-start"> <ion-col size="4">1</ion-col> <ion-col size="4">2</ion-col> <ion-col size="4">3 <br> + <br> + <br> </ion-col> </ion-row> </ion-grid> <ion-grid fixed> <ion-row class="ion-align-items-center"> <ion-col size="4">1</ion-col> <ion-col size="4">2</ion-col> <ion-col size="4">3 <br> + <br> + <br> </ion-col> </ion-row> </ion-grid> <ion-grid fixed> <ion-row class="ion-align-items-end"> <ion-col size="4">1</ion-col> <ion-col size="4">2</ion-col> <ion-col size="4">3 <br> + <br> + <br> </ion-col> </ion-row> </ion-grid> <h1>Componentes de entrada de dados</h1> <h4>Tipos de dados de entrada</h4> <ion-item color="light"> <ion-label position="stacked">Seu nome:</ion-label> <ion-input type="number"></ion-input> </ion-item> <ion-item color="light"> <ion-label position="stacked">Seu nome:</ion-label> <ion-input type="password"></ion-input> </ion-item> <ion-item color="light"> <ion-label position="stacked">Seu nome:</ion-label> <ion-input type="text"></ion-input> </ion-item> <ion-item color="light"> <ion-label position="stacked">Seu nome:</ion-label> <ion-input type="url"></ion-input> </ion-item> <h4>value, placeholder e clearinput</h4> <ion-item color="light"> <ion-label position="stacked">Seu nome:</ion-label> <ion-input value="Fernando Paschoeto"></ion-input> </ion-item> <ion-item color="light"> <ion-label position="stacked">Seu nome:</ion-label> <ion-input placeholder="Digite seu nome."></ion-input> </ion-item> <ion-item color="light"> <ion-label position="stacked">Seu nome:</ion-label> <ion-input clearInput placeholder="Botão de limpar"></ion-input> </ion-item> <h4>floating, fixed e stacked</h4> <br> <ion-item color="light"> <ion-label position="floating">Seu nome:</ion-label> <ion-input></ion-input> </ion-item> <ion-item color="light"> <ion-label position="fixed">Seu e-mail:</ion-label> <ion-input></ion-input> </ion-item> <ion-item color="light"> <ion-label position="stacked">Sua senha:</ion-label> <ion-input></ion-input> </ion-item> <h1>Cartões</h1> <ion-card color="dark" mode="md"> <ion-img src="https://source.unsplash.com/random/800x600"></ion-img> <ion-card-content> <ion-card-title>Awesome Title</ion-card-title> <p> At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi </p> </ion-card-content> </ion-card> <ion-card color="dark" mode="ios"> <ion-img src="https://source.unsplash.com/random/800x600"></ion-img> <ion-card-content> <ion-card-title>Awesome Title</ion-card-title> <p> At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi </p> </ion-card-content> </ion-card> <h4>Cartões com Cabeçalho</h4> <ion-card color="dark"> <ion-card-header> <ion-card-title>Awesome Title</ion-card-title> <ion-card-subtitle>Awesome Subtitle</ion-card-subtitle> </ion-card-header> <ion-card-content> <p> At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi </p> </ion-card-content> </ion-card> <ion-card color="dark"> <ion-card-header> <ion-card-title>Awesome Title</ion-card-title> <ion-card-subtitle>Awesome Subtitle</ion-card-subtitle> </ion-card-header> <ion-img src="https://source.unsplash.com/random/800x600"></ion-img> <ion-card-content> <p> At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi </p> </ion-card-content> </ion-card> <ion-card color="dark"> <ion-item color="primary" href="http://www.google.com.br"> <ion-label>Click me</ion-label> </ion-item> <ion-item href="http://www.google.com.br"> <ion-label>Click me</ion-label> </ion-item> <ion-item href="http://www.google.com.br"> <ion-label>Click me</ion-label> </ion-item> <ion-item href="http://www.google.com.br"> <ion-label>Click me</ion-label> </ion-item> </ion-card> <h4>Listas</h4> <ion-list> <ion-item href="http://www.google.com.br"> <ion-label>Click me</ion-label> </ion-item> </ion-list> <ion-list> <ion-item href="http://www.google.com.br"> <ion-label>Click me</ion-label> </ion-item> </ion-list> <ion-list> <ion-item href="http://www.google.com.br"> <ion-label>Click me</ion-label> </ion-item> </ion-list> <h4>Lista com Avatar</h4> <ion-list> <ion-item> <ion-avatar slot="start"> <img src="https://source.unsplash.com/random/200x200" /> </ion-avatar> <ion-label>Fernando Paschoeto</ion-label> </ion-item> </ion-list> <ion-list> <ion-item> <ion-avatar slot="start"> <img src="https://source.unsplash.com/random/100x100" /> </ion-avatar> <ion-label>Alice Paschoeto</ion-label> </ion-item> </ion-list> <h4>Lista com Slide</h4> <ion-list> <ion-list> <ion-item-sliding> <ion-item> <ion-label>Fernando Paschoeto</ion-label> </ion-item> <ion-item-options side="end"> <ion-item-option color="success" (click)="favorite(item)"> <ion-icon slot="start" name="create"></ion-icon> Alterar </ion-item-option> <ion-item-option color="danger" (click)="favorite(item)"> <ion-icon slot="start" name="trash"></ion-icon> Excluir </ion-item-option> </ion-item-options> </ion-item-sliding> </ion-list> </ion-list> <h1>Botões</h1> <ion-button> Padrão </ion-button> <ion-button href="http://bytesdeprosa.com.br"> Link </ion-button> <h4>Cores</h4> <ion-button color="primary"> primary </ion-button> <ion-button color="secondary"> secondary </ion-button> <ion-button color="tertiary"> tertiary </ion-button> <ion-button color="danger"> danger </ion-button> <ion-button color="success"> success </ion-button> <ion-button color="warning"> warning </ion-button> <ion-button color="light"> light </ion-button> <ion-button color="dark"> dark </ion-button> <ion-button color="medium"> medium </ion-button> <h4>Expandido</h4> <ion-button expand="full" color="warning"> Click me </ion-button> <ion-button expand="block" color="success"> Click me </ion-button> <h4>Arredondado</h4> <ion-button shape="round" color="tertiary"> Click me </ion-button> <h4>Preenchimento</h4> <ion-button fill="outline" color="dark"> Click me </ion-button> <h4>Ícones</h4> <ion-button (click)="onClick()"> <ion-icon slot="start" name="star"></ion-icon> Estrela </ion-button> <ion-button (click)="onClick()" color="secondary"> <ion-icon slot="end" name="star"></ion-icon> Estrela </ion-button> <ion-button (click)="onClick()" color="tertiary"> <ion-icon slot="icon-only" name="star"></ion-icon> </ion-button> <ion-icon name="walk-outline"></ion-icon> <h4>Tamanhos de botôes</h4> <ion-button size="large" (click)="onClick()" shape="round"> Large </ion-button> <ion-button (click)="onClick()" shape="round"> Padrão </ion-button> <ion-button size="small" (click)="onClick()" shape="round"> Small </ion-button> --> </ion-content>
import ktl from kpf.KPFTranslatorFunction import KPFTranslatorFunction from kpf import (log, KPFException, FailedPreCondition, FailedPostCondition, FailedToReachDestination, check_input) class SetND2(KPFTranslatorFunction): '''Set the filter in the ND2 filter wheel (the one at the output of the octagon) via the `kpfcal.ND2POS` keyword. ARGS: ===== :CalND2: The neutral density filter to put in the second filter wheel. Allowed values are "OD 0.1", "OD 0.3", "OD 0.5", "OD 0.8", "OD 1.0", "OD 4.0" :wait: (bool) Wait for move to complete before returning? (default: True) ''' @classmethod def pre_condition(cls, args, logger, cfg): keyword = ktl.cache('kpfcal', 'ND2POS') allowed_values = list(keyword._getEnumerators()) if 'Unknown' in allowed_values: allowed_values.pop(allowed_values.index('Unknown')) check_input(args, 'CalND2', allowed_values=allowed_values) @classmethod def perform(cls, args, logger, cfg): target = args.get('CalND2') log.debug(f"Setting ND2POS to {target}") kpfcal = ktl.cache('kpfcal') kpfcal['ND2POS'].write(target, wait=args.get('wait', True)) @classmethod def post_condition(cls, args, logger, cfg): timeout = cfg.getfloat('times', 'nd_move_time', fallback=20) ND2target = args.get('CalND2') ND2POS = ktl.cache('kpfcal', 'ND2POS') if ND2POS.waitFor(f"== '{ND2target}'", timeout=timeout) == False: raise FailedToReachDestination(ND2POS.read(), ND2target) @classmethod def add_cmdline_args(cls, parser, cfg=None): '''The arguments to add to the command line interface. ''' parser.add_argument('CalND2', type=str, choices=["OD 0.1", "OD 0.3", "OD 0.5", "OD 0.8", "OD 1.0", "OD 4.0"], help='ND2 Filter to use.') parser.add_argument("--nowait", dest="wait", default=True, action="store_false", help="Send move and return immediately?") return super().add_cmdline_args(parser, cfg)
--- title: "Markup: HTML Tags and Formatting" excerpt: A variety of common markup showing how the theme styles them. toc: true mathjax: true --- # Header one ## Header two ### Header three #### Header four ##### Header five ###### Header six <figure> <img src="https://vuepress.vuejs.org/hero.png" alt="Fallback teaser"> <figcaption>This is my fallback teaser.</figcaption> </figure> ## Code ```javascript document .getElementById('#button') .addEventListener('click', (event) => { event.target.innerHTML = 'Yay!' }) ``` ```cpp #include <iostream> #include <memory> typedef std::string Data; struct string { std::unique_ptr<Data> p; // 也可以定义拷贝构造和移动构造函数,这里从略 string(const char* str="") : p(new Data(str)) {} string& operator=(const string& rhs) { // 1: 拷贝赋值 this->p.reset(new Data(*rhs.p)); // 新建 Data,拷贝了 rhs 的资源 return *this; } string& operator=(string&& rhs) { // 2: 移动赋值 this->p = std::move(rhs.p); // 没有新建 Data,直接拿走了 rhs 的资源 return *this; } }; std::ostream& operator<<(std::ostream& out, const string& str) { if (str.p) out << *str.p; return out; } int main() { string a = "Hello", b = "World"; std::cout << a << " " << b << std::endl; // Hello World a = b; // b 是 lvalue,拷贝赋值 std::cout << a << " " << b << std::endl; // World World b = "War"; // "War" 是 rvalue,移动赋值 std::cout << a << " " << b << std::endl; // World War a = std::move(b); // 将 b 转换为 rvalue,强制移动赋值 std::cout << a << " " << b << std::endl; // War } ``` ## Math An LR(0) item (or just item for short) of a context-free grammar is a production choice with a distinguished position in its right-hand side. We indicate this distinguished position by a period. e.g. Consider the grammar $$\begin{align} & S' \rightarrow S \\& S \rightarrow \text{ ( } S \text{ ) } S | \epsilon \end{align}$$ The grammar has the following eight items: $$ \begin{align} & S' \rightarrow .S \\& S' \rightarrow S. \\& S \rightarrow .\text{ ( } S \text{ ) } S \\& S \rightarrow \text{ ( } .S \text{ ) } S \\& S \rightarrow \text{ ( } S .\text{ ) } S \\& S \rightarrow \text{ ( } S \text{ ) } .S \\& S \rightarrow \text{ ( } S \text{ ) } S. \\& S \rightarrow . \end{align} $$ An item records an intermediate step in the recognition of the right-hand side of a particular grammar rule choice. - The item $A \rightarrow \beta . \gamma$ constructed from the grammar rule choice $A \rightarrow \beta \gamma$ means that $\beta$ has already been seen and that it may be possible to derive the next input token from $\gamma$. This means $\beta$ must appear at the top of the stack. - Initial items: An item such as $A \rightarrow .\alpha$ that means we may be about to recognize an $A$ by using the grammar rule choice $A \rightarrow \alpha$. - Complete items: An item such as $A \rightarrow \alpha.$ that means $\alpha$ now resides on the top of the parsing stack and may be the handle, if $A \rightarrow \alpha$ is to be used for the next reduction. ## Blockquotes Single line blockquote: > Stay hungry. Stay foolish. Multi line blockquote with a cite reference: > People think focus means saying yes to the thing you've got to focus on. But that's not what it means at all. It means saying no to the hundred other good ideas that there are. You have to pick carefully. I'm actually as proud of the things we haven't done as the things I have done. Innovation is saying no to 1,000 things. ::: small <cite>Steve Jobs</cite> --- Apple Worldwide Developers' Conference, 1997 ::: photo gallery: {% include gallery caption="This is a sample gallery with **Markdown support**." %} ## Tables | Employee | Salary | | | -------- | ------ | ------------------------------------------------------------ | | [John Doe](#) | $1 | Because that's all Steve Jobs needed for a salary. | | [Jane Doe](#) | $100K | For all the blogging she does. | | [Fred Bloggs](#) | $100M | Pictures are worth a thousand words, right? So Jane × 1,000. | | [Jane Bloggs](#) | $100B | With hair like that?! Enough said. | | Header1 | Header2 | Header3 | |:--------|:-------:|--------:| | cell1 | cell2 | cell3 | | cell4 | cell5 | cell6 | |-----------------------------| | cell1 | cell2 | cell3 | | cell4 | cell5 | cell6 | | Foot1 | Foot2 | Foot3 | ## Definition Lists Definition List Title : Definition list division. Startup : A startup company or startup is a company or temporary organization designed to search for a repeatable and scalable business model. #dowork : Coined by Rob Dyrdek and his personal body guard Christopher "Big Black" Boykins, "Do Work" works as a self motivator, to motivating your friends. Do It Live : I'll let Bill O'Reilly [explain](https://www.youtube.com/watch?v=O_HyZ5aW76c "We'll Do It Live") this one. ## Unordered Lists (Nested) * List item one * List item one * List item one * List item two * List item three * List item four * List item two * List item three * List item four * List item two * List item three * List item four ## Ordered List (Nested) 1. List item one 1. List item one 1. List item one 2. List item two 3. List item three 4. List item four 2. List item two 3. List item three 4. List item four 2. List item two 3. List item three 4. List item four ## Buttons Make any link standout more when applying the `.btn .btn--primary` classes. ```html <a href="#" class="btn btn--primary">Link Text</a> ``` | Button Type | Example | Class | Kramdown | | ------ | ------- | ----- | ------- | | Default | <Btn href="https://github.com" target="_blank">Text</Btn> | `.btn` | `<Btn href="https://github.com" target="_blank">Text</Btn>` | | Primary | <Btn type="primary" to="/short">Text</Btn> | `.btn .btn--primary` | `<Btn type="primary" :to="{ hash: '#notices' }">Text</Btn>` | | Success | <Btn type="success" @click="greet">Text</Btn> | `.btn .btn--success` | `<Btn type="success" @click="greet">Text</Btn>` | | Warning | <Btn type="warning" href="#link">Text</Btn> | `.btn .btn--warning` | `<Btn type="warning" href="#link">Text</Btn>` | | Danger | <Btn type="danger" href="#link">Text</Btn> | `.btn .btn--danger` | `<Btn type="danger" href="#link">Text</Btn>` | | Info | <Btn type="info" href="#link">Text</Btn> | `.btn .btn--info` | `<Btn type="info" href="#link">Text</Btn>` | | Inverse | <Btn type="inverse" href="#link">Text</Btn> | `.btn .btn--inverse` | `<Btn type="inverse" href="#link">Text</Btn>` | | Light Outline | <Btn type="light-outline" href="#link">Text</Btn> | `.btn .btn--light-outline` | `<Btn type="light-outline" href="#link">Text</Btn>` | | Button Size | Example | Class | Kramdown | | ----------- | ------- | ----- | -------- | | X-Large | <Btn type="x-large primary" href="#link">Text</Btn> | `.btn .btn--x-large .btn--primary` | `<Btn type="x-large primary" href="#link">Text</Btn>` | | Large | <Btn type="info large" href="#link">Text</Btn> | `.btn .btn--info .btn--large` | `<Btn type="info large" href="#link">Text</Btn>` | | Default | <Btn type="success" href="#link">Text</Btn> | `.btn .btn--success` | `<Btn type="success" href="#link">Text</Btn>` | | Small | <Btn type="small" href="#link">Text</Btn> | `.btn .btn--small` | `<Btn type="small" href="#link">Text</Btn>` | ## Notices Call attention to a block of text. | Notice Type | Class | | ----------- | ----- | | Default | `.notice` | | Primary | `.notice--primary` | | Info | `.notice--info` | | Warning | `.notice--warning` | | Success | `.notice--success` | | Danger | `.notice--danger` | ::: notice **Watch out!** This paragraph of text has been [emphasized](#) with the `notice` class. ::: ::: notice--primary **Watch out!** This paragraph of text has been [emphasized](#) with the `notice--primary` class. ::: ::: notice--info **Watch out!** This paragraph of text has been [emphasized](#) with the `notice--info` class. ::: ::: notice--warning **Watch out!** This paragraph of text has been [emphasized](#) with the `notice--warning` class. ::: ::: notice--success **Watch out!** This paragraph of text has been [emphasized](#) with the `notice--success` class. ::: ::: notice--danger **Watch out!** This paragraph of text has been [emphasized](#) with the `notice--danger` class. ::: ::: notice You can also add the `.notice` class to a `<div>` element. * Bullet point 1 * Bullet point 2 ::: ::: notice--info <h4>Notice Headline:</h4> Hello ::: ## Text alignment Align text blocks with the following classes. ::: text-left Left aligned text `.text-left` ::: ```markdown ::: text-left Left aligned text ::: ``` ::: text-center Center aligned text. `.text-center` ::: ```markdown ::: text-center Center aligned text. ::: ``` ::: text-right Right aligned text. `.text-right` ::: ```markdown ::: text-right Right aligned text. ::: ``` ::: text-justify **Justified text.** `.text-justify` Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vel eleifend odio, eu elementum purus. In hac habitasse platea dictumst. Fusce sed sapien eleifend, sollicitudin neque non, faucibus est. Proin tempus nisi eu arcu facilisis, eget venenatis eros consequat. ::: ```markdown ::: text-justify Justified text. ::: ``` ::: text-nowrap No wrap text. `.text-nowrap` ::: ```markdown ::: text-nowrap No wrap text. ::: ``` ## HTML Tags ### Address Tag <address> 1 Infinite Loop<br /> Cupertino, CA 95014<br /> United States </address> ### Anchor Tag (aka. Link) This is an example of a [link](http://apple.com "Apple"). ### Abbreviation Tag The abbreviation CSS stands for "Cascading Style Sheets". *[CSS]: Cascading Style Sheets ### Cite Tag "Code is poetry." ---<cite>Automattic</cite> ### Code Tag You will learn later on in these tests that `word-wrap: break-word;` will be your best friend. ### Emphasize Tag The emphasize tag should _italicize_ text. ### Insert Tag This tag should denote <ins>inserted</ins> text. ### Keyboard Tag This scarcely known tag emulates <kbd>keyboard text</kbd>, which is usually styled like the `<code>` tag. ### Preformatted Tag This tag styles large blocks of code. <pre> .post-title { margin: 0 0 5px; font-weight: bold; font-size: 38px; line-height: 1.2; and here's a line of some really, really, really, really long text, just to see how the PRE tag handles it and to find out how it overflows; } </pre> ### Quote Tag <q>Developers, developers, developers&#8230;</q> &#8211;Steve Ballmer ### Strong Tag This tag shows **bold text**. ### Subscript Tag Getting our science styling on with H<sub>2</sub>O, which should push the "2" down. ### Superscript Tag Still sticking with science and Albert Einstein's E = MC<sup>2</sup>, which should lift the 2 up. ### Variable Tag This allows you to denote <var>variables</var>. <script setup> function greet() { alert('Hello world!'); } </script>
/** * Check if the object is empty * @param {Object} obj - Object to check * @returns {Boolean} true if the object is empty (no keys) */ export const objectIsEmpty = (obj: object): boolean => { for (const key in obj) return false return true } /** * Compare two objects of values * @param {Object} obj1 - Object 1 to compare * @param {Object} obj2 - Object 2 to compare * @returns {Boolean} true if the two objects are equal (same keys and values) */ export const compareObjects = (obj1: any, obj2: any): boolean => { if (typeof obj1 !== "object" || typeof obj2 !== "object") return false if (Array.isArray(obj1) || Array.isArray(obj2)) return false if (objectIsEmpty(obj1) && objectIsEmpty(obj2)) return true for (const key in obj1) { const value1 = obj1[key] const value2 = obj2[key] if (value1 !== value2) return false if ( !Array.isArray(value1) && !Array.isArray(value2) && typeof value1 === "object" ) return compareObjects(value1, value2) if (Array.isArray(value1) && Array.isArray(value2)) return compareArrays(value1, value2) } return true } /** * Compare two arrays of values or arrays of objects * @param {Array} arr1 - Array 1 to compare * @param {Array} arr2 - Array 2 to compare * @returns {Boolean} true if the two arrays are equal (same values or objects) */ export const compareArrays = (arr1: any, arr2: any): boolean => { if (!Array.isArray(arr1) || !Array.isArray(arr2)) return false if (arr1.length === 0 && arr2.length === 0) return true if (arr1.length !== arr2.length) return false for (const [key1, value1] of arr1.entries()) { const value2 = arr2[key1] if (value1 !== value2) return false if ( !Array.isArray(value1) && !Array.isArray(value2) && typeof value1 === "object" ) return compareObjects(value1, value2) if (Array.isArray(value1) && Array.isArray(value2)) return compareArrays(value1, value2) } return true }
import 'package:flutter/material.dart'; import 'package:shwe_kabaw/views/course_screen.dart'; class HomeScreen extends StatelessWidget { const HomeScreen({super.key}); //Creating Static data in lists static const List catNames = [ "Category", "Classes", "Free Course", "Book Store", "Live Course", "Leader Board" ]; static const List<Color> catColors = [ Color(0XFFFFCF2F), Color(0XFF6FE08D), Color(0XFF61BDFD), Color(0XFFFC7C7F), Color(0XFFCB84FB), Color(0XFF78E667), ]; static const List<Icon> catIcons = [ Icon(Icons.category , color: Colors.white , size: 30), Icon(Icons.video_library , color: Colors.white , size: 30), Icon(Icons.assignment , color: Colors.white , size: 30), Icon(Icons.store , color: Colors.white , size: 30), Icon(Icons.play_circle_fill , color: Colors.white , size: 30), Icon(Icons.emoji_events , color: Colors.white , size: 30), ]; static const imageList = [ "carOne", "carTwo", "carThree", "carFour", "carFive", ]; @override Widget build(BuildContext context) { return Scaffold( body: ListView( children: [ Container( padding: EdgeInsets.only(top: 15, left: 15,right: 15,bottom: 10), decoration: BoxDecoration( color: Color(0xFF674AEF), borderRadius: BorderRadius.only( bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20) ) ), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Icon(Icons.dashboard, size: 30, color: Colors.white,), Icon(Icons.notifications, size: 30, color: Colors.white,) ], ), SizedBox(height: 20,), Padding(padding: EdgeInsets.only(left: 3,bottom: 15), child: Text("Hi ,Aung Naing Phyo", style: TextStyle(color:Colors.white,fontSize: 25, fontWeight: FontWeight.w600, letterSpacing: 1, wordSpacing: 1),),), Container( margin: EdgeInsets.only(top: 5 , bottom: 20), width: MediaQuery.of(context).size.width, height: 55, alignment: Alignment.center, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10) ), child: TextFormField( decoration: InputDecoration( border: InputBorder.none, hintText: "Search here...", hintStyle: TextStyle( color: Colors.black.withOpacity(0.5) ), prefixIcon: Icon( Icons.search, size: 25 ) ) ) ), ], ), ), Padding( padding: EdgeInsets.only(top: 20, left: 15, right: 15), child: Column( children: [ GridView.builder( itemCount: catNames.length, shrinkWrap: true, physics: NeverScrollableScrollPhysics(), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount:3, childAspectRatio: 1.1 ), itemBuilder: (context , index) { return Column( children: [ Container( width: 60, height: 60, decoration: BoxDecoration( color : catColors[index], shape: BoxShape.circle, ), child: Center(child: catIcons[index]) ), SizedBox(height: 10), Text( catNames[index], style: TextStyle( fontSize: 16, color: Colors.black.withOpacity(0.7), fontWeight: FontWeight.bold), ), ] ); } ), SizedBox(height:20), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "Courses", style: TextStyle( fontSize: 23, fontWeight: FontWeight.w600 ) ), Text( "See All", style: TextStyle( fontSize: 18, fontWeight: FontWeight.w500, color: Color(0xFF674AEF) ) ) ] ), SizedBox(height: 10), GridView.builder( itemCount: imageList.length, shrinkWrap: true, physics: NeverScrollableScrollPhysics(), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount:2, childAspectRatio: (MediaQuery.of(context).size.height - 50 - 25 ) / (4 * 240) , mainAxisSpacing: 10, crossAxisSpacing: 10 ), itemBuilder: (context, index) { return InkWell( onTap: (){ Navigator.push( context, MaterialPageRoute( builder: (context) => CourseScreen(imageList[index]), ), ); }, child: Container( padding: EdgeInsets.symmetric(vertical: 10 , horizontal: 10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: Color(0xFFF5F3FF) ), child: Column( children: [ Padding( padding: EdgeInsets.all(5), child: Image.asset( 'assets/images/${imageList[index]}.png',scale: 0.5,) ), SizedBox(height:3), Text( imageList[index], style: TextStyle( fontSize: 22, fontWeight: FontWeight.bold, color: Colors.black.withOpacity(0.6) ) ), SizedBox(height:5), Text( "55 Videos", style: TextStyle( fontSize: 15, fontWeight: FontWeight.w500, color: Colors.black.withOpacity(0.5) ) ) ] ), ), ); }, ) ] ) ) ], ), bottomNavigationBar: BottomNavigationBar( iconSize: 32, selectedItemColor: Color(0xFF674AEF), selectedFontSize: 18, unselectedItemColor: Colors.grey, showUnselectedLabels: true, items: [ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'), BottomNavigationBarItem(icon: Icon(Icons.assignment), label: 'Courses'), BottomNavigationBarItem(icon: Icon(Icons.favorite), label: 'Wishlist'), BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Account'), ]) ); } }
import { useState, useEffect } from "react"; // Import necessary modules from React import axios from "axios"; // Import axios for making HTTP requests import { Pokemon } from "../types/interfaces"; // Import Pokemon interface const useFetchPokemonDetails = ( pokemonId?: string // Accepts an optional Pokemon ID as input ): [Pokemon | null, boolean] => { // State variables const [pokemon, setPokemon] = useState<Pokemon | null>(null); // State for storing fetched Pokemon details const [loading, setLoading] = useState<boolean>(true); // State for loading status // Function to fetch Pokemon details const fetchData = async () => { if (!pokemonId) return; // Check if pokemonId exists try { setLoading(true); // Set loading state to true // Make GET request to the PokeAPI endpoint to fetch Pokemon details const response = await axios.get<Pokemon>( `https://pokeapi.co/api/v2/pokemon/${pokemonId}` ); setPokemon(response.data); // Set fetched Pokemon data to state } catch (error) { console.error("Error fetching Pokemon details:", error); // Log error if fetching fails setPokemon(null); // Set Pokemon data to null } finally { setLoading(false); // Set loading state to false regardless of success or failure } }; // Fetch Pokemon details when pokemonId changes useEffect(() => { fetchData(); }, [pokemonId]); return [pokemon, loading]; // Return fetched Pokemon data and loading status }; export default useFetchPokemonDetails; // Export the custom hook
<!DOCTYPE html> <meta charset="utf-8"> <style> .link { stroke: #212121; stroke-width: 0.5px; } .node text { pointer-events: none; font-family: "Sans-serif"; } .node circle { stroke-width: 0px; } .d3-tip { line-height: 0; color: black; font-family: "Sans-serif"; } </style> <body style ="background-color:#BBDEFB;"> <script src="https://d3js.org/d3.v4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.js"></script> <script> //Toggle stores whether the highlighting is on var toggle = 0; //Create an array logging what is connected to what var linkedByIndex = {}; var link, node; var min_zoom = 0.1; var max_zoom = 10; // var zoom = d3.zoom().scaleExtent([min_zoom,max_zoom]) var width = 960, height = 900 // var allNodes; var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) .call(d3.zoom().scaleExtent([0.1, 10]).on("zoom", zoomed)) .append("g") .attr("transform", "translate(40,0)"); var tool_tip = d3.tip() .attr('class', 'd3-tip') .offset([-8, 0]) .html(function(d) { return d.id; }); svg.call(tool_tip); var color = d3.scaleOrdinal(d3.schemeCategory20); var simulation = d3.forceSimulation() .force("link", d3.forceLink().id(function(d) { return d.id; })) .force("charge", d3.forceManyBody()) .force("center", d3.forceCenter(width / 4, height / 2)); var defs = svg.append('svg:defs'); defs.append('svg:marker') .attr('id', 'end-arrow') .attr('viewBox', '0 -5 10 10') .attr('refX', "32") .attr('markerWidth', 3.5) .attr('markerHeight', 3.5) .attr('orient', 'auto') .append('svg:path') .attr('d', 'M0,-5L10,0L0,5'); d3.json("graph.json", function(error, json) { if (error) throw error; link = svg.selectAll(".link") .data(json.links) .enter().append("line") .attr("class", "link") .attr('marker-end', 'url(#end-arrow)'); node = svg.selectAll(".node") .data(json.nodes) .enter().append("g") .attr("class", "node"); json.nodes = appendInDegree(json.nodes, json.links); simulation .nodes(json.nodes) .on("tick", ticked, {passive: true}); simulation.force("link") .links(json.links); simulation.force("charge").strength(-5) simulation.force("charge").distanceMax(400) simulation.force("charge").theta(1) simulation.force("collision", d3.forceCollide(function(d) { var rad = findRadius(d, json.links) if(rad == 3) return rad*2 + 1 return rad + 1 })); simulation.force("collision").strength(0.5) for (i = 0; i < json.nodes.length; i++) { linkedByIndex[i + "," + i] = 1; }; json.links.forEach(function (d) { linkedByIndex[d.source.index + "," + d.target.index] = 1; }); node.append(function(d) { // var indegree = inDegree(d,json.links) if(d.inDegree < 1) { var circle = document.createElementNS("http://www.w3.org/2000/svg","circle") circle.setAttribute("r", 5) circle.setAttribute("fill", color(d.group)) circle.setAttribute("stroke", "#ccc") return circle } var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); var length = findRadius(d,json.links) rect.setAttribute('x',-1*length/2); rect.setAttribute('y',-1*length/2); rect.setAttribute('width',length); rect.setAttribute('height',length); var pvt = "#d50000"; if(findPrivate(d) == 1) { pvt = "#76FF03"; } rect.setAttribute("fill", pvt); rect.setAttribute("stroke", "#212121") return rect }) // .on('mouseover', tool_tip.show) //Added // .on('mouseout', tool_tip.hide) // .on('dblclick', connectedNodes) //Added code; //Added // .call(d3.drag() // .on("start", dragstarted) // .on("drag", dragged) // .on("end", dragended)) // .on('mouseover', tool_tip.show) //Added // .on('mouseout', tool_tip.hide) // .on('dblclick', connectedNodes) //Added code; //Added // node.append("text") // .attr("dx", -10) // .attr("dy", ".35em") // .attr("fill", function(d) { return textColor(d, json.links); }) // .attr("font-size", function(d) { // var count = inDegree(d, json.links); // if(count > 0) return "15px"; // return "0px" // }) // .text(function(d) { return d.id }); }); //This function looks up whether a pair are neighbours function neighboring(a, b) { return linkedByIndex[a.index + "," + b.index]; } function connectedNodes() { if (toggle == 0) { //Reduce the opacity of all but the neighbouring nodes d = d3.select(this).node().__data__; node.style("opacity", function (o) { return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1; }); link.style("opacity", function (o) { return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1; }); //Reduce the op toggle = 1; } else { //Put them back to opacity=1 node.style("opacity", 1); link.style("opacity", 1); toggle = 0; } } function textColor(d,allLinks) { var count = d.inDegree; if(count < 1) { return "#757575"; } return "#212121"; } function findPrivate(d) { if(d.inDegree == 1) { return 1 } return 0 } function appendInDegree(nodes,links) { for (var i = 0; i < nodes.length ; i++) { nodes[i].inDegree = inDegree(nodes[i],links); // console.log(nodes[i].inDegree) } return nodes; } function findRadius(n,allLinks) { var count = n.inDegree count = count == 0 ? 3 : 15 + (count/3) return count } function inDegree(n,allLinks) { var degree = 0 for(var i = 0; i < allLinks.length; i++) { // console.log(allLinks[i].target) if(allLinks[i].target == n.id) { // console.log(degree) degree += 1 } } return degree; } function ticked() { var ticksPerRender = 3; requestAnimationFrame(function render() { for (var i = 0; i < ticksPerRender; i++) { simulation.tick(); } link .attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node.attr("transform", function(d) { return "translate(" + (d.x) + "," + (d.y) + ")"; }) if (simulation.alpha() > 0) { requestAnimationFrame(render); } }) } function zoomed() { var transform = d3.event.transform svg.attr("transform",transform) } </script>
import 'package:express_all/src/config/style/constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; class ChooseAccountTypePage extends StatelessWidget { const ChooseAccountTypePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: const BackButton(), title: const Text('Create an account'), ), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const SizedBox(height: 70), const Text( 'I am a ...', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: primaryColor), // ), const SizedBox(height: 40), const Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ OptionCard( label: 'Parent', imagePath: 'assets/images/parents.png', routeName: '/ParentSignUp', ), OptionCard( label: 'Child', imagePath: 'assets/images/children.png', routeName: '/ChildSignUp'), ], ), const Spacer(), Align( alignment: Alignment.bottomCenter, child: Padding( padding: const EdgeInsets.all(16.0), child: SvgPicture.asset( 'assets/images/svg/family_together.svg'), // Replace with your asset image ), ), ], ), ); } } class OptionCard extends StatelessWidget { final String label; final String imagePath; final String routeName; const OptionCard( {Key? key, required this.label, required this.imagePath, required this.routeName}) : super(key: key); @override Widget build(BuildContext context) { return Card( child: InkWell( onTap: () { Navigator.pushNamed(context, routeName); // TODO: Here should separate difference account type signup, currently both are the same signup page }, splashColor: Theme.of(context).splashColor, // Default splash color child: Container( width: 150, // Define a fixed width for the card height: 180, // Define a fixed height for the card padding: const EdgeInsets.all(8), // Add some padding inside the card child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Image.asset(imagePath, width: 70, height: 70), // Display the image const SizedBox(height: 10), // Spacing between image and text Text( label, style: const TextStyle( color: primaryColor, fontSize: 20, fontWeight: FontWeight.w400), ), // Text label for the card ], ), ), ), ); } }
package com.samourai.wallet.widgets; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.text.Editable; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.text.style.ImageSpan; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.widget.LinearLayout; import android.widget.MultiAutoCompleteTextView; import android.widget.TextView; import android.widget.Toast; import com.samourai.wallet.R; import org.bitcoinj.crypto.MnemonicCode; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; /** * Created by Sarath kumar on 1/23/2018. */ public class MnemonicSeedEditText extends androidx.appcompat.widget.AppCompatMultiAutoCompleteTextView { TextWatcher textWatcher; private static final String TAG = "MnemonicSeedEditText"; String lastString; int counter = 0; String separator = " "; private Context context = null; private List<String> validWordList = null; public MnemonicSeedEditText(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; this.setDropDownBackgroundResource(R.drawable.rounded_rectangle_pinview); init(); } public MnemonicSeedEditText(Context context) { super(context); init(); } public MnemonicSeedEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { setMovementMethod(LinkMovementMethod.getInstance()); setSelection(0); setThreshold(2); setCursorVisible(true); requestFocus(); textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String thisString = s.toString(); String[] arr = thisString.split(separator); if(arr.length != 0 && !thisString.isEmpty()) { String lastItem = arr[arr.length - 1]; if (validWordList.indexOf(lastItem) != -1 && !thisString.equals(lastString)) { format(thisString); } if(lastItem.length() > 1 && lastItem.length() <= 4){ MnemonicSeedEditText.this.showDropDown(); }else { MnemonicSeedEditText.this.dismissDropDown(); } } } @Override public void afterTextChanged(Editable s) { } }; addTextChangedListener(textWatcher); validWordList = MnemonicCode.INSTANCE.getWordList(); } private void format(String thisString) { SpannableStringBuilder sb = new SpannableStringBuilder(); String[] words = thisString.split(separator); if(thisString.charAt(thisString.length() - 1) == separator.charAt(0)) { for (int i = 0; i < words.length; i++) { String word = words[i]; sb.append(word.replace("\n", "")); if (validWordList.indexOf(word.trim()) == -1) { Toast.makeText(context, R.string.invalid_mnemonic_word, Toast.LENGTH_SHORT).show(); break; } BitmapDrawable bd = convertViewToDrawable(createTokenView(word)); bd.setBounds(0, 0, bd.getIntrinsicWidth(), bd.getIntrinsicHeight()); int startIdx = sb.length() - (word.length()); int endIdx = sb.length(); sb.setSpan(new ImageSpan(bd), startIdx, endIdx, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); SpanClick myClickableSpan = new SpanClick(startIdx, endIdx); sb.setSpan(myClickableSpan, Math.max(endIdx - 2, startIdx), endIdx, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); if (i < words.length - 1) { sb.append(separator); } else if (thisString.charAt(thisString.length() - 1) == separator.charAt(0)) { sb.append(separator); } } lastString = sb.toString(); setText(sb); setSelection(sb.length()); } } public View createTokenView(String text) { LinearLayout layout = new LinearLayout(getContext()); layout.setOrientation(LinearLayout.HORIZONTAL); layout.setBackgroundResource(R.drawable.round_rectangle_token_word_background); TextView tv = new TextView(getContext()); tv.setPadding(22, 5, 22, 5); layout.addView(tv); tv.setText(text); tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); tv.setTextColor(Color.WHITE); return layout; } public BitmapDrawable convertViewToDrawable(View view) { int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); view.measure(spec, spec); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); Bitmap b = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); c.translate(-view.getScrollX(), -view.getScrollY()); view.draw(c); view.setDrawingCacheEnabled(true); Bitmap cacheBmp = view.getDrawingCache(); Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true); view.destroyDrawingCache(); return new BitmapDrawable(getContext().getResources(), viewBmp); } private class SpanClick extends ClickableSpan { int startIdx; int endIdx; public SpanClick(int startIdx, int endIdx) { super(); this.startIdx = startIdx; this.endIdx = endIdx; } @Override public void onClick(View widget) { String s = getText().toString(); String s1 = s.substring(0, startIdx); String s2 = s.substring(Math.min(endIdx + 1, s.length() - 1), s.length()); String finalString = s1 + s2; if(finalString.trim().isEmpty()) { MnemonicSeedEditText.this.setText(null); } else { MnemonicSeedEditText.this.setText(s1 + s2); } } } /** * Tokenizer class for handling autocomplete tokens * SpaceTokenizer splits given text based white space character * when user adds spaces we will show suggestions */ public static class SpaceTokenizer implements MultiAutoCompleteTextView.Tokenizer { Context mContext; public SpaceTokenizer(Context context) { mContext = context; } public int findTokenStart(CharSequence text, int cursor) { int i = cursor; while (i > 0 && text.charAt(i - 1) != ' ') { i--; } while (i < cursor && text.charAt(i) == ' ') { i++; } return i; } public int findTokenEnd(CharSequence text, int cursor) { int i = cursor; int len = text.length(); while (i < len) { if (text.charAt(i) == ' ') { return i; } else { i++; } } return len; } public CharSequence terminateToken(CharSequence text) { int i = text.length(); while (i > 0 && text.charAt(i - 1) == ' ') { i--; } if (i > 0 && text.charAt(i - 1) == ' ') { return text; } else { return text + " "; } } } }
>[!summary] Resumen. >En Lua se pueden iterar todos los key-value con el iterador _pairs_ debido a que si la tabla tiene keys tanto numéricas como de string el\# no contara las key strings. Para iterar tablas con llaves solo numericas podemos hacer uso o bien de \# o del iterador _ipairs_. >[!example] Ejemplo. >```Lua >t = {10, print, x = 12, k = "hi"} for k, v in pairs(t) do print(k, v) end --> 1 10 --> k hi --> 2 function: 0x420610 --> x 1 >t = {10, print, 12, "hi"} for k, v in ipairs(t) do print(k, v) end --> 1 10 --> 2 function: 0x420610 --> 3 12 --> 4 hi >``` [[Lua]]
/******************************************************************************* * * Delta Chat Core * Copyright (C) 2017 Björn Petersen * Contact: r10s@b44t.com, http://b44t.com * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see http://www.gnu.org/licenses/ . * ******************************************************************************/ /* Parse MIME body; this is the text part of an IMF, see https://tools.ietf.org/html/rfc5322 dc_mimeparser_t has no deep dependencies to dc_context_t or to the database (dc_context_t is used for logging only). */ #ifndef __DC_MIMEPARSER_H__ #define __DC_MIMEPARSER_H__ #ifdef __cplusplus extern "C" { #endif #include "dc_hash.h" #include "dc_param.h" typedef struct dc_e2ee_helper_t dc_e2ee_helper_t; typedef struct dc_mimepart_t { /** @privatesection */ int type; /*one of DC_MSG_* */ int is_meta; /*meta parts contain eg. profile or group images and are only present if there is at least one "normal" part*/ int int_mimetype; char* msg; char* msg_raw; int bytes; dc_param_t* param; } dc_mimepart_t; typedef struct dc_mimeparser_t { /** @privatesection */ /* data, read-only, must not be free()'d (it is free()'d when the dc_mimeparser_t object gets destructed) */ carray* parts; /* array of dc_mimepart_t objects */ struct mailmime* mimeroot; dc_hash_t header; /* memoryhole-compliant header */ struct mailimf_fields* header_root; /* must NOT be freed, do not use for query, merged into header, a pointer somewhere to the MIME data*/ struct mailimf_fields* header_protected; /* MUST be freed, do not use for query, merged into header */ char* subject; int is_send_by_messenger; int decrypting_failed; /* set, if there are multipart/encrypted parts left after decryption */ dc_e2ee_helper_t* e2ee_helper; const char* blobdir; int is_forwarded; dc_context_t* context; carray* reports; /* array of mailmime objects */ int is_system_message; } dc_mimeparser_t; dc_mimeparser_t* dc_mimeparser_new (const char* blobdir, dc_context_t*); void dc_mimeparser_unref (dc_mimeparser_t*); void dc_mimeparser_empty (dc_mimeparser_t*); void dc_mimeparser_parse (dc_mimeparser_t*, const char* body_not_terminated, size_t body_bytes); /* the following functions can be used only after a call to dc_mimeparser_parse() */ struct mailimf_field* dc_mimeparser_lookup_field (dc_mimeparser_t*, const char* field_name); struct mailimf_optional_field* dc_mimeparser_lookup_optional_field (dc_mimeparser_t*, const char* field_name); struct mailimf_optional_field* dc_mimeparser_lookup_optional_field2 (dc_mimeparser_t*, const char* field_name, const char* or_field_name); dc_mimepart_t* dc_mimeparser_get_last_nonmeta (dc_mimeparser_t*); #define dc_mimeparser_has_nonmeta(a) (dc_mimeparser_get_last_nonmeta((a))!=NULL) int dc_mimeparser_is_mailinglist_message (dc_mimeparser_t*); int dc_mimeparser_sender_equals_recipient(dc_mimeparser_t*); /* low-level-tools for working with mailmime structures directly */ #ifdef DC_USE_MIME_DEBUG void mailmime_print (struct mailmime*); #endif struct mailmime_parameter* mailmime_find_ct_parameter (struct mailmime*, const char* name); int mailmime_transfer_decode (struct mailmime*, const char** ret_decoded_data, size_t* ret_decoded_data_bytes, char** ret_to_mmap_string_unref); struct mailimf_fields* mailmime_find_mailimf_fields (struct mailmime*); /*the result is a pointer to mime, must not be freed*/ char* mailimf_find_first_addr (const struct mailimf_mailbox_list*); /*the result must be freed*/ struct mailimf_field* mailimf_find_field (struct mailimf_fields*, int wanted_fld_type); /*the result is a pointer to mime, must not be freed*/ struct mailimf_optional_field* mailimf_find_optional_field (struct mailimf_fields*, const char* wanted_fld_name); dc_hash_t* mailimf_get_recipients (struct mailimf_fields*); #ifdef __cplusplus } /* /extern "C" */ #endif #endif /* __DC_MIMEPARSER_H__ */
import { Resolver, Query, Mutation, Args, Int } from '@nestjs/graphql'; //_____________________Custom Imports_____________________// import { CaseHistoryService } from '../services/case_history.service'; import { CaseHistory } from '../entities/case_history.entity'; import { CreateCaseHistoryInput } from '../dto/create-case_history.input'; import { UpdateCaseHistoryInput } from '../dto/update-case_history.input'; /** * Resolver for casehistory */ @Resolver(() => CaseHistory) export class CaseHistoryResolver { constructor(private readonly caseHistoryService: CaseHistoryService) {} //_____________________Query_____________________// /** * Summary : Query For Fetching all case history * Created By : Akhila U S * @param args * @returns */ @Query(() => [CaseHistory], { name: 'getAllCaseHistory' }) async findAll() { return await this.caseHistoryService.findAll(); } /** * Summary : Query For Fetching casehistory by passing id * Created By : Akhila U S * @param args * @returns */ @Query(() => CaseHistory, { name: 'caseHistory' }) findOne(@Args('id', { type: () => Int }) id: number) { return this.caseHistoryService.findOne(id); } //_____________________Mutation_____________________// /** * Summary : Mutation for Creating Casehistory * Created By : Akhila U S * @param createCaseHistoryInput * @returns */ @Mutation(() => CaseHistory) createCaseHistory( @Args('createCaseHistoryInput') createCaseHistoryInput: CreateCaseHistoryInput, ) { return this.caseHistoryService.create(createCaseHistoryInput); } /** * Summary : Mutation for updating Casehistory * Created By : Akhila U S * @param updateCaseHistoryInput * @returns */ @Mutation(() => CaseHistory) updateCaseHistory( @Args('updateCaseHistoryInput') updateCaseHistoryInput: UpdateCaseHistoryInput, ) { return this.caseHistoryService.update( updateCaseHistoryInput.id, updateCaseHistoryInput, ); } /** * Mutation for remove Cases * @param id * @returns */ @Mutation(() => CaseHistory) removeCaseHistory(@Args('id', { type: () => Int }) id: number) { return this.caseHistoryService.remove(id); } }
# Registry **HKEY\_CLASSES\_ROOT (HKCR)**: Provides information related to file types and properties. The subkeys under HKCR are often used by shell applications (such as the Command Prompt) and by _Component Object Model_ (COM)[5](https://portal.offensive-security.com/courses/soc-100/books-and-videos/modal/modules/windows-basics-ii/windows-registry/windows-registry-overview#fn5) applications. **HKEY\_CURRENT\_CONFIG (HKCC)**: Provides information related to the hardware configurations upon which the OS is running, specifically in comparison to the default configuration. **HKEY\_CURRENT\_USER (HKCU)**: Provides information related to the setting configurations of the current user. Note that the HKCU key and subkeys will be different depending on what user is logged in, including SYSTEM. **HKEY\_LOCAL\_MACHINE**: Provides information about the local machine related to input/output devices, memory, and drivers. **HKEY\_PERFORMANCE\_DATA**: Provides information related to system performance. Notably, data associated with this key isn't stored within the Registry itself but is rather referenced by _Registry functions_[6](https://portal.offensive-security.com/courses/soc-100/books-and-videos/modal/modules/windows-basics-ii/windows-registry/windows-registry-overview#fn6). **HKEY\_USERS** Provides information related to the default settings assigned to new users. Using reg query on Run and RunOnce keys ```powershell reg query hkcu\software\microsoft\windows\currentversion\runonce reg query hkcu\software\microsoft\windows\currentversion\run ``` Using reg delete ```powershell reg delete hkcu\software\microsoft\windows\currentversion\run /va ``` Using reg add {% code overflow="wrap" %} ```powershell reg add hkcu\software\microsoft\windows\currentversion\run /v OneDrive /t REG_SZ /d "C:\Users\Offsec\AppData\Local\Microsoft\OneDrive\OneDrive.exe" ``` {% endcode %} Using reg export ```powershell reg export hkcu\environment environment ```
package onealldigital.nizara.in.adapter; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.squareup.picasso.Picasso; import androidx.annotation.RequiresApi; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.RecyclerView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import onealldigital.nizara.in.R; import onealldigital.nizara.in.activity.MainActivity; import onealldigital.nizara.in.fragment.TrackerDetailFragment; import onealldigital.nizara.in.helper.ApiConfig; import onealldigital.nizara.in.helper.Constant; import onealldigital.nizara.in.helper.Session; import onealldigital.nizara.in.helper.VolleyCallback; import onealldigital.nizara.in.model.Category; import onealldigital.nizara.in.model.OrderTracker; public class TrackerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { // for load more public final int VIEW_TYPE_ITEM = 0; public final int VIEW_TYPE_LOADING = 1; final Activity activity; final ArrayList<OrderTracker> orderTrackerArrayList; final Context context; public boolean isLoading; public TrackerAdapter(Context context, Activity activity, ArrayList<OrderTracker> orderTrackerArrayList) { this.context = context; this.activity = activity; this.orderTrackerArrayList = orderTrackerArrayList; } public void add(int position, OrderTracker item) { orderTrackerArrayList.add(position, item); notifyItemInserted(position); } public void setLoaded() { isLoading = false; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) { if (viewType == VIEW_TYPE_ITEM) { View view = LayoutInflater.from(activity).inflate(R.layout.lyt_trackorder, parent, false); return new TrackerHolderItems(view); } else if (viewType == VIEW_TYPE_LOADING) { View view = LayoutInflater.from(activity).inflate(R.layout.item_progressbar, parent, false); return new ViewHolderLoading(view); } return null; } @RequiresApi(api = Build.VERSION_CODES.M) @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(RecyclerView.ViewHolder holderparent, final int position) { if (holderparent instanceof TrackerHolderItems) { final TrackerHolderItems holder = (TrackerHolderItems) holderparent; final OrderTracker order = orderTrackerArrayList.get(position); // System.out.println(activity.getString(R.string.order_status)); holder.txtorderid.setText(activity.getString(R.string.order_number) + order.getId()); String[] date = order.getDate_added().split("\\s+"); holder.txtorderdate.setText(date[0]); holder.txtorderamount.setText(new Session(context).getData(Constant.CURRENCY) + ApiConfig.StringFormat(order.getFinal_total())); Picasso.get().load(order.getItemsList().get(0).getImage()) .fit() .centerInside() .placeholder(R.drawable.placeholder) .error(R.drawable.placeholder) .into(holder.imgOrder); Log.d("orderImg", "onBindViewHolder: "+order.getImage()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Fragment fragment = new TrackerDetailFragment(); Bundle bundle = new Bundle(); bundle.putString("id", ""); bundle.putSerializable("model", order); fragment.setArguments(bundle); MainActivity.fm.beginTransaction().add(R.id.container, fragment).addToBackStack(null).commit(); } }); ArrayList<String> items = new ArrayList<>(); for (int i = 0; i < order.getItemsList().size(); i++) { items.add(order.getItemsList().get(i).getName()); } // holder.tvItems.setText(Arrays.toString(items.toArray()).replace("]", "").replace("[", "")); // holder.tvTotalItems.setText(items.size() + activity.getString(R.string.item)); } else if (holderparent instanceof ViewHolderLoading) { ViewHolderLoading loadingViewHolder = (ViewHolderLoading) holderparent; loadingViewHolder.progressBar.setIndeterminate(true); } } @Override public int getItemCount() { return orderTrackerArrayList.size(); } @Override public int getItemViewType(int position) { return orderTrackerArrayList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM; } @Override public long getItemId(int position) { return position; } static class ViewHolderLoading extends RecyclerView.ViewHolder { public final ProgressBar progressBar; public ViewHolderLoading(View view) { super(view); progressBar = view.findViewById(R.id.itemProgressbar); } } public class TrackerHolderItems extends RecyclerView.ViewHolder { private final TextView txtorderid; private final TextView txtorderdate; private final TextView txtorderamount; private final ImageView imgOrder; // final TextView carddetail; // final TextView tvTotalItems; // final TextView tvItems; // final CardView cardView; public TrackerHolderItems(View itemView) { super(itemView); txtorderid = itemView.findViewById(R.id.txtorderid); txtorderdate = itemView.findViewById(R.id.txtorderdate); txtorderamount = itemView.findViewById(R.id.txtorderamount); imgOrder = itemView.findViewById(R.id.img_order); imgOrder.setClipToOutline(true); // carddetail = itemView.findViewById(R.id.carddetail); // tvTotalItems = itemView.findViewById(R.id.tvTotalItems); // tvItems = itemView.findViewById(R.id.tvItems); // cardView = itemView.findViewById(R.id.cardView); } } }
package com.example.demo.service; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.example.demo.model.LoginInfo; public class UserInfoService implements UserDetails { private String id; private String password; private List<GrantedAuthority> role; public UserInfoService(LoginInfo data) { super(); this.id = data.getId(); this.password = data.getPassword(); this.role = Arrays.stream(data.getRole().split(",")).map(SimpleGrantedAuthority::new).collect(Collectors.toList()); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { // TODO Auto-generated method stub return role; } @Override public String getPassword() { // TODO Auto-generated method stub return password; } @Override public String getUsername() { // TODO Auto-generated method stub return id; } @Override public boolean isAccountNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isAccountNonLocked() { // TODO Auto-generated method stub return true; } @Override public boolean isCredentialsNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isEnabled() { // TODO Auto-generated method stub return true; } }
import { ItemService } from "@/api/item.service"; import { useGetSection } from "@/hooks/useGetSection"; import { AddButon } from "@/shared/components/addButon/AddButon"; import { Loading } from "@/shared/components/loading/Loading"; import { Autocomplete, FormControl, IconButton, InputLabel, MenuItem, Modal, Select, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, } from "@mui/material"; import { IGetItemBySection, IItemData } from "interfaces/item.interface"; import { useEffect, useState } from "react"; import { Controller, useForm } from "react-hook-form"; import { MdChecklist, MdEdit } from "react-icons/md"; export const ItemView = () => { const [itemData, setitemData] = useState<IGetItemBySection | undefined>(); const [isloading, setisloading] = useState<boolean>(false); const [isEdit, setisEdit] = useState<boolean>(false); const [open, setOpen] = useState<boolean>(false); const [dataSelected, setdataSelected] = useState<IItemData | undefined>( undefined ); const [itemId, setitemId] = useState<number | undefined>(undefined); const [successData, setsuccessData] = useState(false); const [errorData, seterrorData] = useState(false); const { register, handleSubmit, reset, control } = useForm(); const allSection = useGetSection(); const handleOpen = (data?: IItemData | undefined) => { if (data) { setisEdit(true); setitemId(data.id); } setOpen(true); setdataSelected(data); }; const handleClose = () => { setOpen(false); setisEdit(false); reset(); setdataSelected(undefined); setitemId(undefined); }; useEffect(() => {}, [itemData]); const handleSelectionChange = async (event: any, newValue: any | null) => { setisloading(true); const result = await getItems(newValue.id); setitemData(result); setisloading(false); }; const getItems = async (sectionId: string) => { try { const items = await ItemService.itemsBySection(sectionId); return items; } catch (error) { throw new Error("Error al obtener items por sección"); } }; const onSubmit = handleSubmit(async (data) => { if (isEdit) { const dataUpdate = { name: data.name, description: data.description, quantity: data.quantity, sectionId: data.section, }; const { status } = await ItemService.updateItem(itemId ?? 0, dataUpdate); if (status === 200 || status === 201) { setsuccessData(true); } if (status >= 300) { seterrorData(true); } } else { const dataCreate = { name: data.name, description: data.description, quantity: data.quantity, sectionId: data.section, }; const { status } = await ItemService.createItem(dataCreate); if (status === 200 || status === 201) { setsuccessData(true); } if (status >= 300) { seterrorData(true); } } }); return ( <div className="bg-white rounded-xl p-10"> <h1>Items</h1> <div className="flex flex-col gap-3 lg:flex-row justify-center lg:justify-between mt-5"> <div className="w-full lg:w-1/3"> <Autocomplete disablePortal id="combo-box-demo" options={Array.isArray(allSection.data) ? allSection.data : []} getOptionLabel={(option) => option.name} sx={{ width: "100%" }} renderInput={(params) => <TextField {...params} label="section" />} onChange={handleSelectionChange} /> </div> <AddButon title="Crear" onClick={() => handleOpen(undefined)} /> </div> <div className="w-full my-5 border-b-2 border-gray-300" /> {isloading && <Loading />} {Array.isArray(itemData?.items) && itemData.length !== 0 && ( <div className="w-full"> <TableContainer sx={{ overflowX: "auto" }}> <Table stickyHeader aria-label="sticky table"> <TableHead> <TableRow> <TableCell>Nº</TableCell> <TableCell align="right">Nombre</TableCell> <TableCell align="right">Descripción</TableCell> <TableCell align="right">Cantidad</TableCell> <TableCell align="right">Acción</TableCell> </TableRow> </TableHead> <TableBody> {itemData?.items.map((row: any, idx: number) => ( <TableRow key={row.id}> <TableCell component="th" scope="row"> {idx + 1} </TableCell> <TableCell align="right">{row.name}</TableCell> <TableCell align="right">{row.description}</TableCell> <TableCell align="right">{row.quantity}</TableCell> <TableCell align="right"> <IconButton aria-label="delete" onClick={() => handleOpen(row)} > <MdEdit /> </IconButton> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </div> )} {Array.isArray(itemData) && itemData.length === 0 && ( <div className="flex flex-col gap-3 justify-center items-center mt-10"> <MdChecklist className="text-7xl text-gray-500" /> <h1 className="my-3 text-xl text-gray-500"> No se encontraron datos </h1> </div> )} <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white lg:w-[700px] w-3/4 p-5 rounded-xl"> <h1 className="my-3 text-3xl text-gray-500"> {isEdit ? `Editar ${dataSelected?.name}` : "Crear Sección"} </h1> {successData && ( <div className="bg-green-100 border-2 border-green-400 rounded-md my-3"> <h1 className="text-green-600 text-center text-lg p-2"> {isEdit ? "Item modificados correctamente" : "Item creado correctamente"} </h1> </div> )} {errorData && ( <div className="bg-red-100 border-2 border-red-400 rounded-md my-3"> <h1 className="text-red-600 text-center text-lg p-2"> {isEdit ? "Error al modificar item" : "Error al crear item"} </h1> </div> )} <form onSubmit={onSubmit}> {isEdit && ( <TextField {...register("id")} id="outlined-basic" label="Id" variant="outlined" fullWidth disabled={true} defaultValue={dataSelected ? dataSelected?.id : undefined} sx={{ marginTop: "10px" }} /> )} <TextField {...register("name", { required: true })} id="outlined-basic" label="Nombre" variant="outlined" fullWidth defaultValue={dataSelected?.name} autoComplete="off" sx={{ marginTop: "10px" }} /> <TextField {...register("description", { required: true })} id="outlined-basic" label="Descripción" variant="outlined" fullWidth defaultValue={dataSelected?.description} autoComplete="off" sx={{ marginTop: "10px" }} /> <TextField {...register("quantity", { required: true, min: 1 })} id="outlined-basic" label="Cantidad" variant="outlined" type="number" fullWidth defaultValue={dataSelected?.quantity} autoComplete="off" sx={{ marginTop: "10px" }} /> <Controller name="section" control={control} defaultValue={dataSelected?.sectionId || ""} rules={{ required: "Selecciona una sección" }} render={({ field }) => ( <FormControl fullWidth sx={{ marginTop: "10px" }}> <InputLabel id="demo-simple-select-label">Sección</InputLabel> <Select label="seccion" value={field.value || ""} onChange={(e) => field.onChange(e.target.value)} > {allSection.data?.map((section: any) => ( <MenuItem key={section.id} value={section.id}> {section.name} </MenuItem> ))} </Select> </FormControl> )} /> <button type="submit" className="w-full bg-green-100 text-green-600 mt-10 rounded-xl p-3" > Guardar </button> </form> </div> </Modal> </div> ); };
from langchain.document_loaders import PyPDFLoader, DirectoryLoader from langchain import PromptTemplate from langchain.embeddings import HuggingFaceEmbeddings from langchain.vectorstores import FAISS from langchain.chains import RetrievalQA from langchain.callbacks.manager import CallbackManager from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain.memory import ConversationBufferMemory from langchain.vectorstores import Pinecone # Use for CPU #from langchain.llms import CTransformers #from ctransformers.langchain import CTransformers # Use for GPU from langchain.llms import LlamaCpp import chainlit as cl import warnings import pinecone import os warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated') MODEL_PATH = r"D:/llama2_quantized_models/7B_chat/llama-2-7b-chat.ggmlv3.q5_K_M.bin" custom_prompt_template = """[INST] <<SYS>> Your name is Kelly, You are foundry technologies expert and very helpful assistant, you always open and only answer for the question professionally. If you don't know the answer, just say you don't know and submit the request to hotline@xfab.com for further assistance. <</SYS>> {context} {chat_history} Question: {question} [/INST]""" print(custom_prompt_template) def set_custom_prompt(): """ Prompt template for QA retrieval for each vectorstore """ prompt = PromptTemplate(input_variables=['chat_history','context', 'question'], template=custom_prompt_template) return prompt # Use CUDA GPU callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]) llm = LlamaCpp( model_path= MODEL_PATH, max_tokens=256, n_gpu_layers=35, n_batch= 512, #256, callback_manager=callback_manager, n_ctx= 1024, verbose=False, temperature=0, ) #Retrieval QA Chain def retrieval_qa_chain(llm, prompt, db, memory): chain_type_kwargs = {"prompt": prompt, "memory": memory} qa_chain = RetrievalQA.from_chain_type(llm=llm, chain_type='stuff', retriever=db.as_retriever(), return_source_documents=True, chain_type_kwargs=chain_type_kwargs ) return qa_chain def rag_retrieval_qa_chain(llm,prompt, db,memory): chain_type_kwargs = {"prompt": prompt, "memory": memory} rag_pipeline = RetrievalQA.from_chain_type(llm=llm, chain_type='stuff', retriever=db.as_retriever(search_kwargs={'k': 1}), chain_type_kwargs=chain_type_kwargs) return rag_pipeline def load_llm(): # Use CUDA GPU callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]) llm = LlamaCpp( model_path= MODEL_PATH, max_tokens=256, n_gpu_layers=35, n_batch= 512, #256, callback_manager=callback_manager, n_ctx= 2048, #1024, - Increase this to add context length1024, verbose=True, temperature=0, ) return llm def init_pinecone(): PINECONE_API_KEY = os.environ.get('PINECONE_API_KEY', '700dbf29-7b1d-435b-9da1-c242f7a206e6') PINECONE_API_ENV = os.environ.get('PINECONE_API_ENV', 'us-west1-gcp-free') pinecone.init( api_key=PINECONE_API_KEY, environment=PINECONE_API_ENV, ) index_name = "llama2-pdf-chatbox" embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2", model_kwargs={"device": "cuda"}) docsearch = Pinecone.from_existing_index(index_name, embeddings) return docsearch def semantic_search(docsearch,query): docs=docsearch.similarity_search(query) return docs #QA Model Function def qa_bot(ask): db = init_pinecone() #llm = load_llm() qa_prompt = set_custom_prompt() memory = ConversationBufferMemory(input_key="question", memory_key="chat_history", return_messages=True) # Semantic Search semantic = semantic_search(db,ask) #print(f"""{semantic} \n\n""") # AI Search #qa = retrieval_qa_chain(llm, qa_prompt, db, memory) # RAG rqa = retrieval_qa_chain(llm, qa_prompt, db, memory) return rqa def final_result(query): qa_result = qa_bot(query) response = qa_result(query) return response while True: query = input(f"\n\nPrompt: " ) if query == "exit": print("exiting") break if query == "": continue answer = final_result(query)
package net.dalytics.models.enricher import cats.implicits._ import derevo.derive import tofu.logging.derivation.loggable import vulcan.Codec import supertagged.postfix._ import net.dalytics.models.{ozon, Event, Timestamp} sealed trait EnricherEvent extends Event { def timestamp: Timestamp } object EnricherEvent { @derive(loggable) final case class OzonCategoryResultsV2ItemEnriched( created: Timestamp, timestamp: Timestamp, page: ozon.Page, item: ozon.Item, category: ozon.Category, sale: ozon.Sale = ozon.Sale.Unknown ) extends EnricherEvent { override val key: Option[Event.Key] = Some(category.id.show @@@ Event.Key) def aggregate(that: OzonCategoryResultsV2ItemEnriched): OzonCategoryResultsV2ItemEnriched = if (timestamp.isBefore(that.timestamp)) that.aggregate(this) else OzonCategoryResultsV2ItemEnriched(created, timestamp, page, item, category, ozon.Sale.from(List(that.item, item))) } object OzonCategoryResultsV2ItemEnriched { implicit val vulcanCodec: Codec[OzonCategoryResultsV2ItemEnriched] = Codec.record[OzonCategoryResultsV2ItemEnriched]( name = "OzonCategoryResultsV2ItemEnriched", namespace = "enricher.events" ) { field => ( field("_created", _.created), field("timestamp", _.timestamp), ozon.Page.vulcanCodecFieldFA(field)(_.page), ozon.Item.vulcanCodecFieldFA(field)(_.item), ozon.Category.vulcanCodecFieldFA(field)(_.category), ozon.Sale.vulcanCodecFieldFA(field)(_.sale) ).mapN(apply) } } implicit val vulcanCodec: Codec[EnricherEvent] = Codec.union[EnricherEvent](alt => alt[OzonCategoryResultsV2ItemEnriched]) }
<?php // required headers header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); include_once '../config/database.php'; require(realpath(__DIR__ . '/../../vendor/autoload.php')); // database connection will be here // include database and object files // instantiate database $database = new Database(); $db = $database->getConnection(); $auth = new \Delight\Auth\Auth($db); if ($auth->isLoggedIn()) { include_once '../objects/person.php'; // initialize object $person = new Person($db); $person->authid = $auth->getUserId(); // query person $stmt = $person->getTeamMembers(); $num = $stmt->rowCount(); // check if more than 0 record found if($num>0){ // person array $person_arr=array(); // retrieve our table contents // fetch() is faster than fetchAll() // http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ // extract row // this will make $row['name'] to // just $name only extract($row); $person_item=array( "id" => $id, "nickname" => $nickname ); array_push($person_arr, $person_item); } // set response code - 200 OK http_response_code(200); // show person data in json format echo json_encode($person_arr); } else{ // set response code - 404 Not found http_response_code(404); // tell the user no person found echo json_encode( array("message" => "No person found.") ); } } else { // set response code - 404 Not found http_response_code(401); // tell the user no person found echo json_encode( array("message" => "Unauthorized.") ); } ?>
<?php namespace App\Http\Controllers; use App\LoanApproval; use App\Permission; use App\Services\LoanProductService; use App\Services\StaffLoanService; use App\User; use Illuminate\Http\Request; class LoanApprovalController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $user = auth()->user(); if ($user->hasRole('superadmin') || $user->hasAllPermissions(Permission::all())) { $loanApprovals = LoanApproval::latest(); } else if ($user->can('cpo-approval') && !$user->hasRole('cpo-manager')) { $loanApprovals = LoanApproval::where('cpo_manager_id', '!=', null)->latest(); } else if ($user->can('hr-approval') && !$user->hasRole('hr-manager')) { $loanApprovals = LoanApproval::where('hr_manager_id', '!=', null)->latest(); } else if ($user->can('line-manager-approval') && !$user->hasRole('line-manager')) { $loanApprovals = LoanApproval::where('line_manager_id', '!=', null)->latest(); } else { $loanApprovals = $user->approvals()->latest(); } $loanApprovals = $loanApprovals->with('loan', 'loan.user', 'loan.approval')->paginate(1000); return view('pages.approvals.index', compact('loanApprovals')); } /** * Display the specified resource. * * @param \App\LoanApproval $loanApproval * @return \Illuminate\Http\Response */ public function show(LoanApproval $loanApproval, LoanProductService $loanProductService) { try { $loan = $loanApproval->loan; $staff = $loan->user; $data = [ 'loan' => $loan, 'staff' => $staff, 'loanApproval' => $loanApproval, 'loanProduct' => $loanProductService->find($loan->loan_product_id), ]; return view('pages.approvals.show', $data); } catch (\Exception $e) { return back()->with('message', messageResponse('danger', 'An error occurred when getting the loan from mambu. Please try again later.')); } } /** * Update the specified resource in storage. * * @param Request $request * @param \App\LoanApproval $loanApproval * @return \Illuminate\Http\Response */ public function update(Request $request, LoanApproval $loanApproval, StaffLoanService $staffLoanService) { if ($request->has('line_manager_approval_status')) { $staffLoanService->updateLineManagerStatus($request, $loanApproval); } if ($request->has('hr_manager_approval_status')) { $staffLoanService->updateHRManagerStatus($request, $loanApproval); } if ($request->has('cpo_manager_approval_status')) { return $staffLoanService->updateCPOManagerStatus($request, $loanApproval); } return back()->with('message', messageResponse('success', 'Loan updated successfully')); } }
package com.test.kotlin import io.kotlintest.shouldBe import io.kotlintest.specs.StringSpec class KotlinObjectTest: StringSpec() { init { "companion object" { val newBaby = Person2.newBaby("name") Person2.log() newBaby.age shouldBe 1 } "singleton" { val a = Singleton.a a shouldBe 0 } "anonymous class" { moveSomething(object : Movable { override fun move() { println("영차영차") } override fun fly() { println("날다날다") } }) } } } /** * kotlin에서는 static 키워드가 존재하지 않는다. * 대신 companion object 블락 안에 넣어둔 변수 or 함수가 java의 static 변수, 함수 처럼 활용된다. * * 그리고 val MIN_AGE 변수에 const 키워드를 붙히지 않으면 런타임시 값이 할당된다. * const 키워드를 붙히면 컴파일 시 할당된다. -> 진짜 상수일 때 사용하자. * * 또한 companion object 또한 객체(동반객체) 이기 때문에 이름을 가질 수 있고 인터페이스를 상속 받을 수 있다. */ class Person2 private constructor( var name: String, var age: Int, ) { companion object Factory : Log { private const val MIN_AGE = 1 @JvmStatic fun newBaby(name: String): Person2 { return Person2(name, MIN_AGE) } override fun log() { println("Im Factory Object") } } } interface Log { fun log() } /** * kotlin에서 싱글톤 클래스를 만들기 위해서는 object 키워드를 활용하면 된다. */ object Singleton { val a = 0 } private interface Movable { fun move() fun fly() } private fun moveSomething(movable: Movable) { movable.move() movable.fly() }
import Vue from 'vue' import Vuex from 'vuex' import { api } from 'boot/axios' // import example from './module-example' Vue.use(Vuex) /* * If not building with SSR mode, you can * directly export the Store instantiation; * * The function below can be async too; either use * async/await or return a Promise which resolves * with the Store instance. */ export default function (/* { ssrContext } */) { const Store = new Vuex.Store({ state: { productTypes: '', products: '' }, actions: { async getAllProducts ({commit}) { return api.get('/product') .then((resp) => { if (resp) { commit('changeProducts', resp.data) return resp.data } }) }, async getProductTypes({commit}){ return api.get('/product/get-product-types') .then(resp => { commit('changeProductTypes', resp.data) return resp.data }) }, async createProduct({commit}, data){ return api.post('/product', data) .then(resp => { commit('changeProducts', resp.data) return resp.data }) }, async updateProduct({commit}, data){ return api.put('/product', data) .then(resp => { commit('changeProducts', resp.data) return resp.data }) }, async deleteSingleProduct({commit}, product_id){ return api.delete(`/product/${product_id}`) .then(resp => { commit('changeProducts', resp.data) return resp.data }) } }, mutations: { changeProductTypes(state, data){ state.productTypes = data }, changeProducts(state, data){ state.products = data } }, getters: {}, // enable strict mode (adds overhead!) // for dev mode only strict: process.env.DEBUGGING }) return Store }
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; import { RootState } from 'redux/store'; import { IContact, LoginCredentials, SignupCredentials } from 'global/types'; type ContactsResponse = IContact[]; export const api = createApi({ reducerPath: 'contactsApi', baseQuery: fetchBaseQuery({ baseUrl: 'https://connections-api.herokuapp.com', prepareHeaders: (headers, { getState }) => { const token = (getState() as RootState).auth.token; if (token) { headers.set('Authorization', `Bearer ${token}`); } return headers; }, }), tagTypes: ['Contacts'], endpoints: builder => ({ signup: builder.mutation({ query: (credentials: SignupCredentials) => ({ url: '/users/signup', method: 'POST', body: credentials, }), }), login: builder.mutation({ query: (credentials: LoginCredentials) => ({ url: '/users/login', method: 'POST', body: credentials, }), }), logout: builder.mutation({ query: () => ({ url: '/users/logout', method: 'POST', }), }), refresh: builder.query({ query: () => ({ url: '/users/current', method: 'GET', }), }), getContacts: builder.query<ContactsResponse, void>({ query: () => '/contacts', providesTags: result => result ? [ ...result.map(({ id }) => ({ type: 'Contacts', id } as const)), { type: 'Contacts', id: 'LIST' }, ] : [{ type: 'Contacts', id: 'LIST' }], }), addContact: builder.mutation<IContact, Partial<IContact>>({ query: data => { return { url: '/contacts', method: 'POST', body: data }; }, invalidatesTags: [{ type: 'Contacts', id: 'LIST' }], }), removeContact: builder.mutation<{}, string>({ query: id => ({ url: `/contacts/${id}`, method: 'DELETE' }), invalidatesTags: (_, __, id) => [{ type: 'Contacts', id }], }), editContact: builder.mutation<IContact, Partial<IContact>>({ query: ({ id, ...body }) => { return { url: `/contacts/${id}`, method: 'PATCH', body }; }, invalidatesTags: [{ type: 'Contacts', id: 'LIST' }], }), }), // ----- Too many requests: devTools trigger refocus // refetchOnFocus: true, // refetchOnReconnect: true, }); export const { useSignupMutation, useLoginMutation, useLogoutMutation, useRefreshQuery, useGetContactsQuery, useAddContactMutation, useRemoveContactMutation, useEditContactMutation, } = api;
package lans.hotels.use_cases; import lans.hotels.datasource.search_criteria.BookingsSearchCriteria; import lans.hotels.datasource.search_criteria.UserSearchCriteria; import lans.hotels.domain.IDataSource; import lans.hotels.domain.booking.Booking; import lans.hotels.domain.user.User; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; public class ViewHotelGroupBookings extends UseCase { Integer h_id; ArrayList<Booking> bookings; public ViewHotelGroupBookings(IDataSource dataSource,Integer h_id) { super(dataSource); this.h_id = h_id; this.bookings = new ArrayList<>(); } @Override public void doExecute() throws Exception { BookingsSearchCriteria b_criteria = new BookingsSearchCriteria(); b_criteria.setHotelId(h_id); try { bookings = dataSource.findBySearchCriteria(Booking.class, b_criteria); succeed(); } catch (Exception e) { fail(); e.printStackTrace(); throw e; } } @Override protected void constructResult() { try { if (succeeded) responseData.put("bookings", createHotelGroupsJSON()); } catch (Exception e) { fail(); e.printStackTrace(); setResponseErrorMessage("error marshalling result"); } } private JSONArray createHotelGroupsJSON() { JSONArray jsonArray = new JSONArray(); try { if (bookings == null) { System.err.println("null bookings"); } bookings.forEach(booking -> { JSONObject b_entry; b_entry = new JSONObject(); b_entry.put("id", booking.getId()); b_entry.put("customer_id", booking.getCustomerId()); b_entry.put("customer_name", booking.getCustomerName()); b_entry.put("hotel_id", booking.getHotelId()); b_entry.put("hotel_name", booking.getHotelName()); b_entry.put("start_date", booking.getDateRange().getFrom().toString()); b_entry.put("end_date", booking.getDateRange().getTo().toString()); b_entry.put("is_active", booking.getActive()); b_entry.put("version", booking.getVersion()); jsonArray.put(b_entry); }); } catch (Exception e) { e.printStackTrace(); fail(); setResponseErrorMessage("error marshalling hotel group data"); } return jsonArray; } }
# Ruta de aprendizaje POO (programacion orientada a objetos) ( Consola ) ## Paso 1: Introduccion a la POO - Definición de POO: Investiga qué es la Programación Orientada a Objetos. - Pilares de POO: Investigar cuales son los pilares. - Clases y Objetos: Aprende la diferencia entre una clase y un objeto en POO. - Atributos y Métodos: Comprende qué son los atributos (variables) y métodos (funciones) de una clase. ### Tarea de Práctica: - Crea una clase llamada Persona con atributos como `nombre`, `edad`, y métodos como `MostrarInformacion()` - Crea 5 objetos (instancias) diferentes de la clase `Persona` y utiliza sus métodos para mostrar información. ### Tarea de Práctica 2 - Crea una clase Empleado con los siguientes atributos: `nombre`, `apellido`, `salario`, `fechaContratacion`. - Implementa métodos para calcular el salario anual de un empleado, calcular el número de años de antigüedad y mostrar toda la información del empleado. ## Paso 2: Herencia y Polimorfismo 1. **Herencia**: Entender cómo una clase puede heredar atributos y métodos de otra clase. 2. **Clases Base y Derivadas**: Comprender la relación entre una clase base y sus clases derivadas, y cómo extender funcionalidades mediante la herencia. ## Tarea de Práctica: - Define una clase base `Vehiculo` con atributos como `marca`, `modelo` y `año`, y un método `ObtenerInformacion()` que imprima la información del vehículo. - Crea clases derivadas como Automovil, Motocicleta y Camioneta, que hereden de Vehiculo y sobrescribe el método ObtenerInformacion() para incluir información específica de cada tipo de vehículo. ## Paso 3: Encapsulación y Abstracción ### Tema: Encapsulación 1. **Encapsulación**: Aprender cómo ocultar los detalles internos de una clase y exponer una interfaz para interactuar con ella. 2. **Propiedades**: Entender cómo usar propiedades para controlar el acceso a los atributos de una clase. ### Tarea de Práctica: - Crea la clase `Automovil` la cual tendra 5 atributos: - CantidadRuedas: sera accesible por cualquiera. - Color: sera accesible solo dentro de esa clase y para acceder a ella habra que usar metodos get y set. - cantidadPuertas: sera accesible dentro de la clase y sus hijos pero no se podra acceder desde fuera. - Motor: sera accesible solo desde esta clase y no habran metodos para acceder a ella. - Propietario: sera accesible por cualquiera. - Demostrar con codigo que cada caso se cumple. ## Paso 4: Polimorfismo e Interfaces 1. **Polimorfismo**: Comprender cómo los objetos de diferentes clases pueden ser tratados de manera uniforme. - tipos de polimorfismo: - Polimorfismo de sobrecarga - Polimorfismo de sobrescritura 2. **Interfaces**: Aprender cómo definir y utilizar interfaces para definir comportamientos comunes entre clases. ### Tarea de Práctica: - Definir una interfaz `IVehiculo` con métodos como `Arrancar()` y `Detener()` - implementarla en clases como `Automovil`, `Motocicleta`. ## Paso 5: Sobrecarga de Métodos y Constructores 1. **Sobrecarga de Métodos**: Entender cómo definir múltiples métodos con el mismo nombre pero diferentes parámetros. 2. **Constructores**: Aprender cómo definir múltiples constructores en una clase para permitir diferentes formas de inicialización de objetos. ### Tarea de Práctica: - Sobrecargar el constructor de la clase `Persona` para permitir la creación de objetos con diferentes conjuntos de parámetros. (se creativo). - Implementar un metodo que implemente sobrecarga llamado: `Comunicarse()` - ## Paso 6: Clase Abstracta vs Interfaces **Tema: Clase Abstracta vs Interfaces** ### Concepto de Clase Abstracta: Una clase abstracta es una clase que no puede ser instanciada directamente y puede contener métodos abstractos (métodos sin implementación) y métodos concretos (métodos con implementación). Las clases abstractas se utilizan para proporcionar una estructura común y definir un conjunto de métodos que deben ser implementados por las clases derivadas. ### Concepto de Interface: Una interfaz define un contrato que especifica un conjunto de métodos y propiedades que una clase debe implementar. A diferencia de las clases abstractas, las interfaces solo pueden contener definiciones de métodos y propiedades, pero no pueden proporcionar implementaciones. Las interfaces se utilizan para definir un comportamiento común que puede ser compartido por diferentes clases, independientemente de su jerarquía de herencia. ### Tareas de Práctica: 1. Crear una clase abstracta `FiguraGeometrica` que contenga un método abstracto `CalcularArea()` y un método concreto `ImprimirInformacion()` que imprima información general sobre la figura geométrica. 2. Definir una interfaz `IDibujable` que contenga un método `Dibujar()` para representar gráficamente la figura geométrica. 3. Implementar la clase `Cuadrado` que herede de `FiguraGeometrica` e implemente la interfaz `IDibujable`. En la clase `Cuadrado`, proporcionar una implementación para el método `CalcularArea()` y para el método `Dibujar()`. 4. Implementar la clase `Circulo` que herede de `FiguraGeometrica` e implemente la interfaz `IDibujable`. En la clase `Circulo`, proporcionar una implementación para el método `CalcularArea()` y para el método `Dibujar()`. Este ejercicio te ayudará a comprender la diferencia entre clases abstractas e interfaces y cómo se utilizan en la programación orientada a objetos para proporcionar una estructura común y definir comportamientos específicos. ¡Adelante con la práctica! ## Paso 7: Tipos Genéricos ### Tema: Tipos Genéricos 1. **Concepto de Tipos Genéricos**: Entender qué son los tipos genéricos y cómo permiten la reutilización de código con diferentes tipos de datos. 2. **Clases y Métodos Genéricos**: Aprender a definir clases y métodos genéricos que pueden trabajar con tipos de datos específicos determinados en tiempo de compilación. ### Tareas de Práctica: - Crear una clase `Lista<T>` que implemente una lista genérica que puede contener elementos de cualquier tipo. - Implementar métodos genéricos en la clase `Lista<T>` para agregar elementos, eliminar elementos y obtener elementos de la lista. El uso de tipos genéricos proporciona flexibilidad y reutilización de código al permitir que las clases y métodos trabajen con diferentes tipos de datos sin necesidad de escribir código específico para cada tipo. ¡Explora y practica con los tipos genéricos para mejorar tu comprensión de la programación orientada objetos. ## Paso 8: Manejo de Excepciones 1. **Manejo de Excepciones**: Aprender a identificar y manejar errores y excepciones que pueden ocurrir durante la ejecución de un programa. 2. **Try-Catch**: Entender cómo utilizar bloques try-catch para manejar excepciones y controlar el flujo del programa. ### Tarea de Práctica: - Implementar un método que realice una operación aritmética y manejar la excepción si se produce un error (por ejemplo, división por cero). ## Paso 9: Programación Orientada a Objetos Avanzada ### Tema: Patrones de Diseño y SOLID 1. **Patrones de Diseño**: Conocer algunos patrones de diseño comunes, como Singleton, Factory, Observer, etc., y entender cuándo y cómo aplicarlos. 2. **SOLID**: Familiarizarse con los principios SOLID (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion) y aprender a aplicarlos en el diseño de clases. ### Tarea de Práctica: - Implementar el patrón Singleton en una clase utilitaria. - Refactorizar una clase existente para cumplir con los principios SOLID. ## Descripción del Proyecto: Sistema de Gestión de Empleados ### Descripción: El proyecto consiste en desarrollar un sistema de gestión de empleados para una empresa. Se utilizarán los principios de la programación orientada a objetos en C# para crear un sistema modular y flexible. El sistema permitirá registrar, actualizar, eliminar y mostrar información sobre los empleados de la empresa. Se aplicarán los siguientes pasos para lograr un diseño robusto y escalable: - **Paso 1: Introducción a la POO y C#**: Definición de las clases base como `Persona` y `Empleado` con atributos y métodos básicos. - **Paso 2: Herencia y Polimorfismo**: Creación de clases derivadas como `EmpleadoTiempoCompleto` y `EmpleadoTiempoParcial` para representar diferentes tipos de empleados. - **Paso 3: Encapsulación y Abstracción**: Encapsulación de los atributos de las clases para garantizar el principio de encapsulamiento y uso de propiedades para controlar el acceso a los atributos. - **Paso 4: Polimorfismo y Interfaces**: Definición de la interfaz `IGestorEmpleado` para gestionar las operaciones relacionadas con los empleados y su implementación en una clase `GestorEmpleado`. - **Paso 5: Sobrecarga de Métodos y Constructores**: Sobrecarga del constructor de la clase `Empleado` y implementación de métodos sobrecargados para actualizar la información de los empleados. - **Paso 6: Manejo de Excepciones**: Implementación de manejo de excepciones en los métodos que pueden generar errores, como la eliminación de un empleado inexistente. - **Paso 7: Programación Orientada a Objetos Avanzada**: Implementación de patrones de diseño como Singleton para manejar la conexión a una base de datos y refactorización del código para cumplir con los principios SOLID. - **Paso 8: Tipos Genéricos**: Creación de una clase genérica `Lista<T>` para almacenar objetos de cualquier tipo y definición de métodos genéricos para manipular la lista de empleados. - **Paso 9: Aplicación de Principios SOLID**: Refactorización del código para cumplir con los principios de diseño SOLID (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion). - **Paso 10 (Opcional): Clase para CRUD Genérico**: Creación de una clase genérica `CRUD<T>` que implemente métodos para realizar operaciones CRUD (Crear, Leer, Actualizar, Eliminar) en una lista de objetos de tipo `T`. Este proyecto tiene como objetivo crear un sistema completo y funcional para gestionar los empleados de una empresa, aplicando los conceptos de POO y C# aprendidos en cada paso. ## Requerimientos: ### Registro de Empleados: - El sistema debe permitir registrar nuevos empleados proporcionando su nombre, edad y salario. - Se deben validar los datos proporcionados para garantizar que sean válidos y coherentes. ### Actualización de Información: - Se debe proporcionar la opción de actualizar la información de un empleado existente, incluyendo su nombre, edad y salario. - Las actualizaciones deben reflejarse correctamente en la lista de empleados. ### Eliminación de Empleados: - Debe ser posible eliminar un empleado existente de la lista de empleados. - Se deben proporcionar controles para evitar la eliminación accidental de empleados. ### Mostrar Detalles de Empleados: - El sistema debe permitir mostrar los detalles de todos los empleados almacenados en la lista. - Los detalles mostrados deben incluir el nombre, edad y salario de cada empleado. ### Diseño Orientado a Objetos: - El sistema debe seguir los principios de la programación orientada a objetos (POO), utilizando clases, herencia, encapsulamiento, polimorfismo, interfaces y tipos genéricos según sea necesario. Aplicación de Principios SOLID: - Se debe aplicar los principios de diseño SOLID (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion) para garantizar un diseño flexible y mantenible. ### Clase para Operaciones CRUD Genéricas (Opcional): - Se puede implementar una clase genérica CRUD<T> que contenga métodos para realizar operaciones CRUD (Crear, Leer, Actualizar, Eliminar) en una lista de objetos de tipo T. - Esta clase proporcionaría funcionalidad genérica para operaciones de CRUD en cualquier tipo de dato. ### Observaciones: - El sistema debe ser modular y flexible, permitiendo futuras expansiones y modificaciones fácilmente. - Se debe prestar especial atención a la validación de datos y al manejo de excepciones para garantizar la robustez y la integridad de los datos del sistema. - Se recomienda seguir las mejores prácticas de codificación y documentación para facilitar el mantenimiento y la colaboración en el proyecto.
package cl.qande.mmii.app.models.service.impl; import cl.qande.mmii.app.config.AppConfig; import cl.qande.mmii.app.models.exception.QandeMmiiException; import cl.qande.mmii.app.models.mail.EmailDetails; import cl.qande.mmii.app.models.service.IEmailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @Service public class EmailServiceImpl implements IEmailService { private static final String MSG_MAIL_OFF = "Mailing desactivado... omitiendo mail: "; private static final String MSG_MAIL_ERROR = "Error al enviar correo"; @Autowired private AppConfig appConfig; @Autowired private JavaMailSender javaMailSender; @Value("${app.properties.mailing.enabled}") private boolean mailingEnabled; //https://www.geeksforgeeks.org/spring-boot-sending-email-via-smtp/ public void sendSimpleMail(EmailDetails details) throws QandeMmiiException { if (!mailingEnabled) { appConfig.customLog.info(MSG_MAIL_OFF+details.toString()); return; } // Try block to check for exceptions try { // Creating a simple mail message SimpleMailMessage mailMessage = new SimpleMailMessage(); // Setting up necessary details mailMessage.setFrom(details.getSenderName()); mailMessage.setTo(details.getRecipientsTo()); mailMessage.setCc(details.getRecipientsCc()); mailMessage.setBcc(details.getRecipientsBcc()); mailMessage.setText(details.getMsgBody()); mailMessage.setSubject(details.getSubject()); // Sending the mail javaMailSender.send(mailMessage); } // Catch block to handle the exceptions catch (Exception e) { throw new QandeMmiiException(e, MSG_MAIL_ERROR); } } //TODO: Crear mail HTML /* https://mailtrap.io/blog/spring-send-email/#How-to-send-HTML-emails-in-Spring-Boot https://stackoverflow.com/questions/5289849/how-do-i-send-html-email-in-spring-mvc */ public void sendHtmlMail(EmailDetails details) throws QandeMmiiException { if (!mailingEnabled) { appConfig.customLog.info(MSG_MAIL_OFF+details.toString()); return; } MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper; try { mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom(details.getSenderName()); mimeMessageHelper.setTo(details.getRecipientsTo()); mimeMessageHelper.setCc(details.getRecipientsCc()); mimeMessageHelper.setBcc(details.getRecipientsBcc()); mimeMessageHelper.setText(details.getMsgBody(), true); mimeMessageHelper.setSubject( details.getSubject()); } catch (MessagingException e) { throw new QandeMmiiException(e, MSG_MAIL_ERROR); } javaMailSender.send(mimeMessage); } public void sendMailWithAttachment(EmailDetails details) throws QandeMmiiException { if (!mailingEnabled) { appConfig.customLog.info(MSG_MAIL_OFF+details.toString()); return; } // Creating a mime message MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper; try { // Setting multipart as true for attachments to // be send mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom(details.getSenderName()); mimeMessageHelper.setTo(details.getRecipientsTo()); mimeMessageHelper.setCc(details.getRecipientsCc()); mimeMessageHelper.setBcc(details.getRecipientsBcc()); mimeMessageHelper.setText(details.getMsgBody()); mimeMessageHelper.setSubject( details.getSubject()); // Adding the attachment FileSystemResource file = new FileSystemResource( new File(details.getAttachment())); mimeMessageHelper.addAttachment( file.getFilename(), file); // Sending the mail javaMailSender.send(mimeMessage); } // Catch block to handle MessagingException catch (javax.mail.MessagingException e) { throw new QandeMmiiException(e, MSG_MAIL_ERROR); } } }
import React, { Fragment, useEffect } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { getProfiles } from '../../actions/profile'; import Spinner from '../layout/spinner.comonent'; import ProfileItem from './profile-item.component'; const Profiles = ({ getProfiles, profile: { profiles, loading } }) => { useEffect(() => { getProfiles(); }, [getProfiles]); return ( <Fragment> {loading ? ( <Spinner /> ) : ( <Fragment> <h1 className='large text-primary'>Connected Developers</h1> <p className='lead'> <i className='fab da-connectdevelop'></i> Brows and connect with developers </p> <div className='profiles'> {/* map through the profiles and display them */} {profiles.length > 0 ? ( profiles.map((profile) => ( <ProfileItem key={profile._id} profile={profile} /> )) ) : ( <h4>No Profiles found</h4> )} </div> </Fragment> )} </Fragment> ); }; Profiles.propTypes = { getProfiles: PropTypes.func.isRequired, profile: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ profile: state.profile, }); export default connect(mapStateToProps, { getProfiles })(Profiles);
#include "CustomScalarField2.h" namespace Engine { CustomScalarField2::CustomScalarField2( const std::function<double(const Vector2D&)>& customFunction, double derivativeResolution) : _customFunction(customFunction), _resolution(derivativeResolution) {} CustomScalarField2::CustomScalarField2( const std::function<double(const Vector2D&)>& customFunction, const std::function<Vector2D(const Vector2D&)>& customGradientFunction, double derivativeResolution) : _customFunction(customFunction), _customGradientFunction(customGradientFunction), _resolution(derivativeResolution) {} CustomScalarField2::CustomScalarField2( const std::function<double(const Vector2D&)>& customFunction, const std::function<Vector2D(const Vector2D&)>& customGradientFunction, const std::function<double(const Vector2D&)>& customLaplacianFunction) : _customFunction(customFunction), _customGradientFunction(customGradientFunction), _customLaplacianFunction(customLaplacianFunction), _resolution(1e-3) {} double CustomScalarField2::sample(const Vector2D& x) const { return _customFunction(x); } std::function<double(const Vector2D&)> CustomScalarField2::sampler() const { return _customFunction; } Vector2D CustomScalarField2::gradient(const Vector2D& x) const { if (_customGradientFunction) return _customGradientFunction(x); else { double left = _customFunction(x - Vector2D(0.5 * _resolution, 0.0)); double right = _customFunction(x + Vector2D(0.5 * _resolution, 0.0)); double bottom = _customFunction(x - Vector2D(0.0, 0.5 * _resolution)); double top = _customFunction(x + Vector2D(0.0, 0.5 * _resolution)); return Vector2D((right - left) / _resolution, (top - bottom) / _resolution); } } double CustomScalarField2::laplacian(const Vector2D& x) const { if (_customLaplacianFunction) return _customLaplacianFunction(x); else { double center = _customFunction(x); double left = _customFunction(x - Vector2D(0.5 * _resolution, 0.0)); double right = _customFunction(x + Vector2D(0.5 * _resolution, 0.0)); double bottom = _customFunction(x - Vector2D(0.0, 0.5 * _resolution)); double top = _customFunction(x + Vector2D(0.0, 0.5 * _resolution)); return (left + right + bottom + top - 4.0 * center) / (_resolution * _resolution); } } CustomScalarField2::Builder CustomScalarField2::builder() { return Builder(); } CustomScalarField2::Builder& CustomScalarField2::Builder::withFunction(const std::function<double(const Vector2D&)>& func) { _customFunction = func; return *this; } CustomScalarField2::Builder& CustomScalarField2::Builder::withGradientFunction(const std::function<Vector2D(const Vector2D&)>& func) { _customGradientFunction = func; return *this; } CustomScalarField2::Builder& CustomScalarField2::Builder::withLaplacianFunction(const std::function<double(const Vector2D&)>& func) { _customLaplacianFunction = func; return *this; } CustomScalarField2::Builder& CustomScalarField2::Builder::withDerivativeResolution(double resolution) { _resolution = resolution; return *this; } CustomScalarField2 CustomScalarField2::Builder::build() const { if (_customLaplacianFunction) return CustomScalarField2(_customFunction, _customGradientFunction, _customLaplacianFunction); else return CustomScalarField2(_customFunction, _customGradientFunction, _resolution); } CustomScalarField2Ptr CustomScalarField2::Builder::makeShared() const { if (_customLaplacianFunction) { return std::shared_ptr<CustomScalarField2>( new CustomScalarField2(_customFunction, _customGradientFunction, _customLaplacianFunction), [](CustomScalarField2* obj) { delete obj; }); } else { return std::shared_ptr<CustomScalarField2>( new CustomScalarField2(_customFunction, _customGradientFunction, _resolution), [](CustomScalarField2* obj) { delete obj; }); } } }
import java.util.Arrays; import java.util.Scanner; // https://www.luogu.com.cn/problem/P1529 public class CowReturnHome { static final int n = 52; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int m = scanner.nextInt(); // 边数 int[][] g = new int[n + 1][n + 1]; // 邻接矩阵 for (int i = 0; i <= n; i++) { Arrays.fill(g[i], 0x3f3f3f3f); } while (m-- > 0) { int u = convert(scanner.next().charAt(0)), v = convert(scanner.next().charAt(0)), w = scanner.nextInt(); g[u][v] = g[v][u] = Math.min(g[u][v], w); // 可能有重边 } scanner.close(); // 单源最短路:Dijkstra O(n^2 + m) int[] dist = new int[n + 1]; dijkstra(g, dist, 26); // 找最近 int nearest = 1; for (int i = 2; i <= 25; i++) { if (dist[i] < dist[nearest]) { nearest = i; } } System.out.print((char) (nearest - 1 + 'A') + " " + dist[nearest]); } private static void dijkstra(int[][] g, int[] dist, int source) { Arrays.fill(dist, 0x3f3f3f3f); dist[source] = 0; boolean[] vis = new boolean[n + 1]; for (int i = 0; i < n - 1; i++) { // 更新 n-1 次 int u = -1; // 未确定最短路长度的节点中距离最小的节点 for (int v = 1; v <= n; v++) { if (!vis[v] && (u == -1 || dist[v] < dist[u])) { u = v; } } vis[u] = true; // 标记 // 松弛 for (int v = 1; v <= n; v++) { if (!vis[v]) { dist[v] = Math.min(dist[v], dist[u] + g[u][v]); } } } } private static int convert(char c) { // 字母 --> 数字 1~26 27~52 if (c <= 'Z') return c - 'A' + 1; else return c - 'a' + 27; } }
# Constructors ❤🍕 **Links:** - [Constructors in c#](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-in-c-) - [Default Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#default-constructor-) - [Parameterized Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#parameterized-constructor-) - [Copy Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#copy-constructor-) - [Private Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#private-constructor-) - [Static Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#static-constructor-) - [Default Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#default-constructor--1) - [Copy Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#copy-constructor--1) - [Private Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#private-constructor--1) - [Parameterized Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#parameterized-constructor--1) - [Static Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#static-constructor--1) - [Static Constructor Vs Non-Static Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#static-constructor-vs-non-static-constructor-) - [Constructor Overloading](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructor-overloading-) - [Overloaded Constructor using “this” keyword](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#overloaded-constructor-using-this-keyword-) - [Overloaded Constructor using Copy Constructor](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#overloaded-constructor-using-copy-constructor-) - [Destructors in c#](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#destructors-in-c-) ## **Constructors in c#:** [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) In C#, constructors are special member methods used to initialize objects of a class. They are called automatically when an instance of the class is created and are responsible for initializing the object's state. ### Key Characteristics of Constructors: 1. **Same Name as Class**: Constructors have the same name as the class they belong to. 2. **No Return Type**: Constructors do not have a return type, not even `void`. 3. **Automatic Invocation**: Constructors are automatically invoked when an object of the class is created using the `new` keyword. 4. **Initialization**: Constructors are primarily used to initialize the object's state, such as initializing fields, properties, or other resources. ```csharp using System; class Car { public string Make; public string Model; public int Year; // Default Constructor public Car() { Make = "Unknown"; Model = "Unknown"; Year = 0; } // Parameterized Constructor public Car(string make, string model, int year) { Make = make; Model = model; Year = year; } // Static Constructor static Car() { Console.WriteLine("Static constructor invoked."); } } class Program { static void Main() { // Creating objects using different constructors Car car1 = new Car(); // Default Constructor Car car2 = new Car("Toyota", "Camry", 2020); // Parameterized Constructor // Accessing object properties Console.WriteLine($"Car 1: {car1.Year} {car1.Make} {car1.Model}"); Console.WriteLine($"Car 2: {car2.Year} {car2.Make} {car2.Model}"); } } ``` **Output** ``` Static constructor invoked. Car 1: 0 Unknown Unknown Car 2: 2020 Toyota Camry ``` Here's the explanation: 1. When the program starts executing, the static constructor of the `Car` class is invoked. This happens before any static member of the class is accessed. Therefore, the message "Static constructor invoked." is printed to the console. 2. Two objects of the `Car` class are created using different constructors: - `car1` is created using the default constructor, so its properties (`Make`, `Model`, and `Year`) are initialized to their default values. - `car2` is created using the parameterized constructor with specific values for the `make`, `model`, and `year` parameters. 3. Finally, the properties of both `car1` and `car2` objects are accessed and printed to the console, showing their respective values. So, the output reflects the initialization and usage of objects created with different constructors. ### Default Constructor: [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) A default constructor is a constructor with no parameters. If no constructor is defined in a class, a default constructor is provided by the compiler. It initializes the object's fields to their default values. **Example:** ```csharp using System; class Car { public string Make; public string Model; public int Year; // Default Constructor public Car() { Make = "Unknown"; Model = "Unknown"; Year = 0; } } class Program { static void Main() { // Creating an object using the default constructor Car car = new Car(); // Accessing object properties Console.WriteLine($"Car: {car.Year} {car.Make} {car.Model}"); } } ``` **Output:** ``` Car: 0 Unknown Unknown ``` ### Parameterized Constructor: [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) A parameterized constructor is a constructor with one or more parameters. It allows you to initialize object properties with specific values at the time of object creation. **Example:** ```csharp using System; class Car { public string Make; public string Model; public int Year; // Parameterized Constructor public Car(string make, string model, int year) { Make = make; Model = model; Year = year; } } class Program { static void Main() { // Creating an object using the parameterized constructor Car car = new Car("Toyota", "Camry", 2020); // Accessing object properties Console.WriteLine($"Car: {car.Year} {car.Make} {car.Model}"); } } ``` **Output:** ``` Car: 2020 Toyota Camry ``` ### Copy Constructor: [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) In C#, there is no direct support for copy constructors like in some other languages. However, you can create a copy constructor by defining a constructor that takes an instance of the same class as a parameter and copies its state. **Example:** ```csharp using System; class Car { public string Make; public string Model; public int Year; // Copy Constructor public Car(Car other) { Make = other.Make; Model = other.Model; Year = other.Year; } } class Program { static void Main() { // Creating an object using the parameterized constructor Car originalCar = new Car("Toyota", "Camry", 2020); // Creating a copy of the original car Car copiedCar = new Car(originalCar); // Accessing object properties Console.WriteLine($"Original Car: {originalCar.Year} {originalCar.Make} {originalCar.Model}"); Console.WriteLine($"Copied Car: {copiedCar.Year} {copiedCar.Make} {copiedCar.Model}"); } } ``` **Output:** ``` Original Car: 2020 Toyota Camry Copied Car: 2020 Toyota Camry ``` ### Private Constructor: [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) A private constructor is a constructor with a private access modifier. It is used to prevent the instantiation of a class from outside the class itself. Private constructors are often used in singleton design patterns. **Example:** ```csharp using System; class Singleton { private static Singleton instance; // Private Constructor private Singleton() { Console.WriteLine("Singleton instance created."); } // Static Method to Get Instance public static Singleton GetInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } class Program { static void Main() { // Attempting to create an instance using the new keyword will result in a compile-time error // Singleton singleton = new Singleton(); // Creating an instance using the static method Singleton singleton = Singleton.GetInstance(); } } ``` **Output:** ``` Singleton instance created. ``` ### Static Constructor: [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) A static constructor is a special type of constructor used to initialize static members of a class. It is called automatically before any static member of the class is accessed for the first time. **Example:** ```csharp using System; class MyClass { public static int Count; // Static Constructor static MyClass() { Count = 0; Console.WriteLine("Static constructor invoked."); } } class Program { static void Main() { // Accessing a static member triggers the static constructor Console.WriteLine($"Count: {MyClass.Count}"); } } ``` **Output:** ``` Static constructor invoked. Count: 0 ``` In summary, constructors play a vital role in initializing object state in C#. By understanding the different types of constructors and their usage, you can effectively manage object initialization and ensure proper behavior in your applications. ## **Default Constructor:** [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) A default constructor is a constructor in a class that takes no parameters. If a class does not have any constructors explicitly defined, the C# compiler automatically provides a default constructor with no parameters. Default constructors are responsible for initializing the object's state to default values. ### Scenario: Consider a scenario where you have a `Person` class that represents individuals. Each `Person` object should have default values for properties like name, age, and gender when created. ### Example: ```csharp using System; class Person { public string Name; public int Age; public string Gender; // Default Constructor public Person() { // Initialize default values Name = "Unknown"; Age = 0; Gender = "Unknown"; } } class Program { static void Main() { // Creating a Person object using the default constructor Person person = new Person(); // Accessing object properties Console.WriteLine($"Name: {person.Name}"); Console.WriteLine($"Age: {person.Age}"); Console.WriteLine($"Gender: {person.Gender}"); } } ``` ### Output: ``` Name: Unknown Age: 0 Gender: Unknown ``` ### Explanation: In this example: - The `Person` class defines a default constructor with no parameters. - Inside the default constructor, the properties `Name`, `Age`, and `Gender` are initialized to default values: "Unknown" for `Name` and `Gender`, and 0 for `Age`. - In the `Main` method, a `Person` object `person` is created using the default constructor. - The properties of the `person` object are accessed and printed to the console, showing their default values. This demonstrates how a default constructor is used to initialize object properties to default values when an object is created without specifying any values explicitly. Default constructors are useful for ensuring that objects have valid initial states even when no specific initialization logic is provided. ## **Copy Constructor:** [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) A copy constructor is a constructor that creates a new object by copying the state of an existing object of the same class. It allows you to create a new object with the same values as an existing object, providing a convenient way to clone objects. ### Scenario: Consider a scenario where you have a `Point` class representing a point in a two-dimensional coordinate system. You want to create a copy of an existing `Point` object. ### Example: ```csharp using System; class Point { public int X; public int Y; // Copy Constructor public Point(Point other) { // Copy the state of the other object X = other.X; Y = other.Y; } } class Program { static void Main() { // Creating an original Point object Point originalPoint = new Point(); originalPoint.X = 10; originalPoint.Y = 20; // Creating a copy of the original Point object using the copy constructor Point copiedPoint = new Point(originalPoint); // Displaying the properties of both original and copied points Console.WriteLine("Original Point:"); Console.WriteLine($"X: {originalPoint.X}, Y: {originalPoint.Y}"); Console.WriteLine("\nCopied Point:"); Console.WriteLine($"X: {copiedPoint.X}, Y: {copiedPoint.Y}"); } } ``` ### Output: ``` Original Point: X: 10, Y: 20 Copied Point: X: 10, Y: 20 ``` ### Explanation: In this example: - The `Point` class defines a copy constructor that takes another `Point` object as its parameter. - Inside the copy constructor, the properties `X` and `Y` of the current object are assigned the values of the corresponding properties of the other object. - In the `Main` method, an original `Point` object `originalPoint` is created with coordinates (10, 20). - Then, a copy of the original `Point` object is created using the copy constructor, passing the `originalPoint` object as a parameter. - Both the original and copied `Point` objects have the same values for their `X` and `Y` properties, demonstrating that the copy constructor successfully created a new object with the same state as the original object. This demonstrates how a copy constructor can be used to create a new object by copying the state of an existing object, providing a convenient way to clone objects in C#. ## **Private Constructor:** [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) A private constructor is a constructor with a private access modifier, meaning it can only be accessed from within the same class. Private constructors are typically used to prevent the instantiation of a class from outside the class itself. They are commonly used in scenarios such as implementing the singleton pattern, where only one instance of a class should exist. ### Scenario: Consider a scenario where you have a `Singleton` class that should only have one instance throughout the lifetime of the application. You want to ensure that no other instances of the class can be created from outside the class itself. ### Example: ```csharp using System; class Singleton { private static Singleton instance; // Private Constructor private Singleton() { Console.WriteLine("Singleton instance created."); } // Static Method to Get Instance public static Singleton GetInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } class Program { static void Main() { // Attempting to create an instance using the new keyword will result in a compile-time error // Singleton singleton = new Singleton(); // Creating an instance using the static method Singleton singleton = Singleton.GetInstance(); } } ``` ### Output: ``` Singleton instance created. ``` ### Explanation: In this example: - The `Singleton` class defines a private constructor, which means it cannot be accessed from outside the class itself. - The `GetInstance` static method provides a way to access the singleton instance. It checks if the instance already exists; if not, it creates a new instance using the private constructor. - In the `Main` method, an attempt to create an instance of the `Singleton` class using the `new` keyword results in a compile-time error because the constructor is private. - Instead, the `GetInstance` method is called to obtain the singleton instance, which successfully creates a single instance of the `Singleton` class. This demonstrates how a private constructor can be used to control the instantiation of a class and enforce certain design patterns such as the singleton pattern in C#. Only the class itself can create instances of itself, ensuring that the desired behavior is maintained throughout the application. ## **Parameterized Constructor:** [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) A parameterized constructor in C# is a constructor with one or more parameters. It allows you to initialize object properties with specific values at the time of object creation. Parameterized constructors provide flexibility by allowing you to create objects with different initial states based on the provided parameters. ### Scenario: Imagine you have a `Car` class that represents vehicles, and you want to create instances of `Car` objects with specific make, model, and year values. ### Example: ```csharp using System; class Car { public string Make; public string Model; public int Year; // Parameterized Constructor public Car(string make, string model, int year) { Make = make; Model = model; Year = year; } } class Program { static void Main() { // Creating a Car object using the parameterized constructor Car car = new Car("Toyota", "Camry", 2020); // Accessing object properties Console.WriteLine($"Car: {car.Year} {car.Make} {car.Model}"); } } ``` ### Output: ``` Car: 2020 Toyota Camry ``` ### Explanation: In this example: - The `Car` class defines a parameterized constructor that takes three parameters: `make`, `model`, and `year`. - Inside the constructor, the properties `Make`, `Model`, and `Year` of the `Car` object are initialized with the values provided as parameters. - In the `Main` method, a `Car` object `car` is created using the parameterized constructor with the values "Toyota" for make, "Camry" for model, and 2020 for year. - The properties of the `car` object are accessed and printed to the console, showing the specific make, model, and year values provided during object creation. This demonstrates how a parameterized constructor allows you to initialize object properties with specific values at the time of object creation. Parameterized constructors are useful for creating objects with different initial states based on the provided parameters, providing flexibility in object instantiation. ## **Static Constructor:** [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) A static constructor in C# is a special type of constructor used to initialize static members of a class. It is called automatically before any static member of the class is accessed for the first time. Static constructors are useful for performing one-time initialization tasks for a class's static members. ### Scenario: Consider a scenario where you have a `Logger` class that contains static members to log messages. You want to ensure that the logging system is initialized before any other code tries to use it. ### Example: ```csharp using System; class Logger { // Static member to count log messages public static int LogCount; // Static Constructor static Logger() { // Perform one-time initialization tasks LogCount = 0; Console.WriteLine("Logging system initialized."); } // Static method to log a message public static void Log(string message) { Console.WriteLine($"Log #{LogCount++}: {message}"); } } class Program { static void Main() { // Calling a static method triggers the static constructor Logger.Log("First log message"); // Accessing a static member does not trigger the static constructor again Console.WriteLine($"Log count: {Logger.LogCount}"); } } ``` ### Output: ``` Logging system initialized. Log #0: First log message Log count: 1 ``` ### Explanation: In this example: - The `Logger` class contains a static member `LogCount` to count the number of log messages and a static method `Log` to log messages. - The `Logger` class also defines a static constructor that initializes the `LogCount` to 0 and prints a message to indicate that the logging system has been initialized. - In the `Main` method, the `Log` method is called to log a message. This triggers the static constructor to be invoked, which initializes the logging system. - After the static constructor is called, the log message is printed, and the `LogCount` is incremented. - Accessing the `LogCount` static member again does not trigger the static constructor because it has already been initialized. This demonstrates how a static constructor can be used to perform one-time initialization tasks for static members of a class in C#. Static constructors are invoked automatically before any static member of the class is accessed, ensuring that the initialization tasks are performed when needed. ## **Static Constructor Vs Non-Static Constructor:** [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) Let's compare static constructors and non-static constructors in C# in tabular form with detailed explanations and use cases: | Feature | Static Constructors | Non-Static Constructors | |------------------------|----------------------------------------------------------|----------------------------------------------------------| | Invocation | Called automatically before any static member access | Called explicitly by the `new` keyword | | Access Modifier | Cannot have access modifiers (always implicit `private`) | Can have various access modifiers (`public`, `private`, etc.) | | Parameters | Cannot have parameters | Can have parameters | | Initialization | Typically used for one-time initialization of static members | Used for initializing instance members | | Use Cases | - Initializing static fields or performing one-time initialization tasks for a class; - Initializing static data or resources; - Ensuring that static members are initialized before they are accessed | - Initializing instance fields or performing instance-specific initialization tasks; - Setting up an object's initial state based on provided parameters; - Customizing object behavior during instantiation | ### Detailed Explanation: - **Invocation**: - Static constructors are automatically invoked before any static member of the class is accessed, ensuring that static members are initialized before they are used. - Non-static constructors are called explicitly using the `new` keyword when creating an instance of the class. - **Access Modifier**: - Static constructors cannot have access modifiers and are always implicitly `private`. - Non-static constructors can have various access modifiers (`public`, `private`, `protected`, etc.), allowing control over their accessibility. - **Parameters**: - Static constructors cannot have parameters, as they are called automatically without any arguments. - Non-static constructors can have parameters, allowing initialization of object properties based on provided values. - **Initialization**: - Static constructors are typically used for one-time initialization of static members, such as initializing static fields or performing initialization tasks for a class. - Non-static constructors are used for initializing instance members, setting up an object's initial state, and performing instance-specific initialization tasks. - **Use Cases**: - Static constructors are useful for ensuring that static members are initialized before they are accessed, initializing static data or resources, and performing one-time initialization tasks for a class. - Non-static constructors are used for setting up an object's initial state based on provided parameters, customizing object behavior during instantiation, and initializing instance fields or resources. ### Use Case Examples: - **Static Constructors**: - Initializing a static logger instance in a logging utility class. - Initializing a static database connection pool in a database access class. - **Non-Static Constructors**: - Initializing instance variables like name, age, and gender in a `Person` class. - Customizing the behavior of objects based on constructor parameters, such as initializing the size and color of a `Rectangle` object. In summary, static constructors and non-static constructors serve different purposes in C#. Static constructors are used for one-time initialization of static members, while non-static constructors are used for initializing instance members and customizing object behavior during instantiation. Understanding when to use each type of constructor is essential for designing well-structured and maintainable C# code. ## **Constructor Overloading:** [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) Constructor overloading in C# allows you to define multiple constructors with the same name but with different parameter lists. This enables you to create objects using different combinations of parameters, providing flexibility in object initialization. ### Scenario: Let's consider a scenario where you have a `Rectangle` class representing rectangles. You want to create `Rectangle` objects using different combinations of parameters, such as specifying width and height, specifying only width, or specifying no parameters (default constructor). ### Example: ```csharp using System; class Rectangle { public double Width { get; } public double Height { get; } // Constructor with different types of arguments public Rectangle(double width, double height) { Width = width; Height = height; } // Constructor with different number of arguments public Rectangle(double width) { Width = width; Height = width; // Square by default } // Constructor with different order of arguments public Rectangle(double height, double width) { Width = width; Height = height; } // Default constructor public Rectangle() { Width = 1; // Default width Height = 1; // Default height } // Method to calculate area public double CalculateArea() { return Width * Height; } } class Program { static void Main() { // Creating Rectangle objects using different constructors Rectangle rectangle1 = new Rectangle(5, 3); // By using different type of arguments Rectangle rectangle2 = new Rectangle(4); // By using different number of arguments Rectangle rectangle3 = new Rectangle(2, 6); // By using different order of arguments Rectangle rectangle4 = new Rectangle(); // Default constructor // Calculating and displaying the area of each rectangle Console.WriteLine("Area of Rectangle 1: " + rectangle1.CalculateArea()); Console.WriteLine("Area of Rectangle 2: " + rectangle2.CalculateArea()); Console.WriteLine("Area of Rectangle 3: " + rectangle3.CalculateArea()); Console.WriteLine("Area of Rectangle 4: " + rectangle4.CalculateArea()); } } ``` ### Output: ``` Area of Rectangle 1: 15 Area of Rectangle 2: 16 Area of Rectangle 3: 12 Area of Rectangle 4: 1 ``` ### Explanation: In this example: - The `Rectangle` class defines multiple constructors to demonstrate constructor overloading. - Constructor overloading is achieved by defining constructors with different parameter lists: - Constructor with different types of arguments: `(double width, double height)` - Constructor with different number of arguments: `(double width)` (height is set equal to width) - Constructor with different order of arguments: `(double height, double width)` - Default constructor: `()` - Each constructor initializes the `Width` and `Height` properties of the `Rectangle` object based on the provided parameters or default values. - In the `Main` method, different `Rectangle` objects are created using different constructors, showcasing constructor overloading. - The area of each rectangle is calculated using the `CalculateArea` method and displayed to the console. This demonstrates how constructor overloading allows you to create objects using different combinations of parameters, providing flexibility in object initialization based on different scenarios. ## **Overloaded Constructor using “this” keyword:** [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) In C#, you can use the `this` keyword within a constructor to invoke another constructor within the same class. This is known as constructor chaining or using an overloaded constructor using the `this` keyword. It allows you to avoid duplicating initialization logic by reusing it in multiple constructors within the same class. ### Scenario: Let's consider a scenario where you have a `Person` class representing individuals. You want to create overloaded constructors to initialize `Person` objects with different combinations of properties. Instead of duplicating initialization logic in each constructor, you'll use the `this` keyword to chain constructors together. ### Example: ```csharp using System; class Person { public string Name { get; } public int Age { get; } public string Gender { get; } // Constructor with all properties public Person(string name, int age, string gender) { Name = name; Age = age; Gender = gender; } // Constructor with only name and age (gender defaults to "Unknown") public Person(string name, int age) : this(name, age, "Unknown") { } // Constructor with only name (age defaults to 0, gender defaults to "Unknown") public Person(string name) : this(name, 0) { } } class Program { static void Main() { // Creating Person objects using different constructors Person person1 = new Person("Alice", 30, "Female"); Person person2 = new Person("Bob", 25); Person person3 = new Person("Charlie"); // Displaying the properties of each person Console.WriteLine($"Person 1: {person1.Name}, {person1.Age}, {person1.Gender}"); Console.WriteLine($"Person 2: {person2.Name}, {person2.Age}, {person2.Gender}"); Console.WriteLine($"Person 3: {person3.Name}, {person3.Age}, {person3.Gender}"); } } ``` ### Output: ``` Person 1: Alice, 30, Female Person 2: Bob, 25, Unknown Person 3: Charlie, 0, Unknown ``` ### Explanation: In this example: - The `Person` class defines multiple constructors with different parameter lists to demonstrate constructor overloading. - Constructor overloading is used to provide flexibility in object initialization. - The constructor with all properties initializes all properties of the `Person` object. - The other constructors use the `this` keyword to chain to the primary constructor, passing default values for omitted parameters. - In the `Main` method, different `Person` objects are created using different constructors, showcasing constructor overloading and constructor chaining. - The properties of each `Person` object are displayed to the console, showing the result of object initialization. This demonstrates how you can use the `this` keyword to chain constructors together, avoiding code duplication and providing flexibility in object initialization in C#. ## **Overloaded Constructor using Copy Constructor:** [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) In C#, you can overload the copy constructor of a class to provide different ways of copying objects. Overloading the copy constructor allows you to customize the copying process based on specific requirements or scenarios. ### Scenario: Consider a scenario where you have a `Rectangle` class representing rectangles, and you want to provide different ways of copying `Rectangle` objects. You may want to copy only the dimensions, or you may want to perform a deep copy including additional properties. ### Example: ```csharp using System; class Rectangle { public double Width { get; } public double Height { get; } public string Color { get; } // Constructor with dimensions and color public Rectangle(double width, double height, string color) { Width = width; Height = height; Color = color; } // Copy constructor (overloaded) public Rectangle(Rectangle other) { Width = other.Width; Height = other.Height; Color = other.Color; } // Method to display rectangle information public void DisplayInfo() { Console.WriteLine($"Width: {Width}, Height: {Height}, Color: {Color}"); } } class Program { static void Main() { // Creating a rectangle Rectangle originalRectangle = new Rectangle(5, 3, "Red"); // Copying the rectangle using the copy constructor Rectangle copiedRectangle = new Rectangle(originalRectangle); // Displaying information of both rectangles Console.WriteLine("Original Rectangle:"); originalRectangle.DisplayInfo(); Console.WriteLine("\nCopied Rectangle:"); copiedRectangle.DisplayInfo(); } } ``` ### Output: ``` Original Rectangle: Width: 5, Height: 3, Color: Red Copied Rectangle: Width: 5, Height: 3, Color: Red ``` ### Explanation: In this example: - The `Rectangle` class defines a copy constructor that takes another `Rectangle` object as its parameter. This constructor is used to create a copy of a `Rectangle` object. - Inside the copy constructor, the dimensions (`Width` and `Height`) and color properties of the new `Rectangle` object are initialized with the values of the corresponding properties of the `other` `Rectangle` object. - In the `Main` method, an original `Rectangle` object `originalRectangle` is created with dimensions 5x3 and color "Red". - Then, a copy of the original `Rectangle` object is created using the copy constructor, resulting in a new `Rectangle` object `copiedRectangle` with the same dimensions and color as the original object. - The information of both the original and copied rectangles is displayed to the console, showing that the copied rectangle has the same properties as the original rectangle. This demonstrates how you can overload the copy constructor in C# to customize the copying process of objects, providing flexibility in object duplication based on specific requirements or scenarios. ## **Destructors in c#:** [🏠](https://github.com/SMitra1993/theNETInterrogation/blob/master/5%20-%20Constructors.md#constructors-) In C#, destructors are special methods used to clean up resources and perform finalization tasks before an object is destroyed or garbage collected. Unlike constructors, which are used to initialize objects when they are created, destructors are invoked automatically when an object is about to be removed from memory. ### Example: ```csharp using System; class MyClass { // Destructor ~MyClass() { Console.WriteLine("Destructor called."); } } class Program { static void Main() { // Creating an object of MyClass MyClass myObject = new MyClass(); // No explicit call to the destructor // Destructor will be called when the object is garbage collected } } ``` ### Output: ``` Destructor called. ``` ### Explanation: In this example: - The `MyClass` class defines a destructor using the `~` symbol followed by the class name. - The destructor is automatically invoked when the `myObject` object of `MyClass` is no longer in use and is eligible for garbage collection. - In the `Main` method, an object of `MyClass` is created using the `new` keyword. - When the program terminates or when the object is no longer referenced and is garbage collected, the destructor is automatically called, and "Destructor called." is printed to the console. ### Note: - Destructors are not explicitly called like constructors. They are automatically invoked by the garbage collector when the object is being collected. - Destructors cannot be overloaded or inherited. Each class can have only one destructor. - Destructors cannot have parameters or modifiers. - It's important to note that destructors are less commonly used in C# compared to constructors, as C# provides other mechanisms such as the `using` statement and IDisposable interface for managing resources more efficiently.
@model TARpe22ShopVaitmaa.Models.RealEstate.RealEstateCreateUpdateViewModel @if (Model.Id.HasValue) { <h1>Update</h1> } else { <h1>Create</h1> } <div> <form method="post" enctype="multipart/form-data"> <input asp-for="Id" type="hidden" /> <input asp-for="CreatedAt" type="hidden" /> <input asp-for="ModifiedAt" type="hidden" /> <div class="form-group row"> <label asp-for="Type" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="Type" class="form-control"/> </div> </div> <div class="form-group row"> <label asp-for="ListingDescription" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="ListingDescription" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="Address" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="Address" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="County" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="County" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="Country" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="Country" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="City" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="City" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="PostalCode" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="PostalCode" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="ContactPhone" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="ContactPhone" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="ContactFax" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="ContactFax" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="SquareMeters" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="SquareMeters" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="Floor" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="Floor" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="FloorCount" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="FloorCount" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="Price" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="Price" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="RoomCount" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="RoomCount" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="BedroomCount" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="BedroomCount" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="BathroomCount" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="BathroomCount" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="WhenEstateListedAt" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="WhenEstateListedAt" class="form-control" /> </div> </div> <div class="form-group row"> <label asp-for="IsPropertySold" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="IsPropertySold" class="form-check" /> </div> </div> <div class="form-group row"> <label asp-for="DoesHaveSwimmingPool" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="DoesHaveSwimmingPool" class="form-check" /> </div> </div> <div class="form-group row"> <label asp-for="BuiltAt" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="BuiltAt" class="form-control" /> </div> </div> <hr/> <div class="form-group row"> <label asp-for="Files" class="col-sm-2 col-form-label"></label> <div class="col-sm-5"> <div class="custom-file"> <input class="form-control custom-file-input" asp-for="Files" multiple type="file" /> <label class="custom-file-label">Choose File...</label> </div> </div> </div> @foreach (var images in Model.FileToApiViewModels) { <partial name="_Images" model="images"/> <input asp-action="removeImage" asp-controller="realEstates" asp-route-imageId="@images.ImageId" type="submit" class="btn btn-danger" value="Remove Image"/> } @if (Model.Id.HasValue) { <input asp-action="update" asp-controller="realEstates" type="submit" class="btn btn-primary"value="Update"/> } else { <input asp-action="create" asp-controller="realEstates" type="submit" class="btn btn-primary" value="create" /> } </form> </div> @section Scripts { <script> $(document).ready(function () { $('custom-file-input').on("change", function() { var fileLabel = $(this).next('custom-file-label'); var files = $(this)[0].files; if (files.length > 1) { fileLabel.html(files.length + ` files selected`); } else if (files.length == 1) { fileLabel.html(files[0].name); } }); }); </script> }
import React, { useState, useReducer, useEffect } from 'react'; import { reducer, initialState } from "../reduc" import Factory from './Factory'; import Ship from './Ship'; function Game() { const [state, dispatch] = useReducer(reducer, initialState); const [metal, setMetal] = useState(0); const [water, setWater] = useState(0); const [profitMetal, setProfitMetal] = useState(0); const [profitWater, setProfitWater] = useState(0); const [feesMetal, setFeesMetal] = useState(0); const [feesWater, setFeesWater] = useState(0); const ships = state.ship; const factories = state.factory; const interval = 100; useEffect(() => { let totalMetal = 0; let totalWater = 0; Object.keys(ships).forEach((name) => { totalMetal += ships[name].qty * ships[name].maintenance.metal; totalWater += ships[name].qty * ships[name].maintenance.water; }) setFeesMetal(totalMetal); setFeesWater(totalWater); }, [ships]); useEffect(() => { let totalMetal = 0; let totalWater = 0; totalMetal += factories.metal.qty * factories.metal.unit; totalWater += factories.water.qty * factories.water.unit; setProfitMetal(totalMetal); setProfitWater(totalWater); }, [factories]); useEffect(() => { const metalFactory = state.factory.metal; const waterFactory = state.factory.water; const productionTimer = setInterval(() => { if(metal < metalFactory.maxCapacity * metalFactory.qty) { setMetal((prevRessource) => prevRessource + (profitMetal - feesMetal)); } if(water < waterFactory.maxCapacity * waterFactory.qty) { setWater((prevRessource) => prevRessource + (profitWater - feesWater)); } }, interval); return () => { clearInterval(productionTimer); }; }, [state.factory.metal, state.factory.water, water, metal, profitMetal, profitWater, feesMetal, feesWater]); return ( <div> <div className='head-board'> <div className='head-board-title'>Metal:</div><div className='head-board-amount'>{metal}</div> <div className='head-board-title'>/</div><div className='head-board-amount'>{state.factory.metal.maxCapacity*state.factory.metal.qty}</div> <div className='head-board-title'>Water:</div><div className='head-board-amount'>{water}</div> <div className='head-board-title'>/</div><div className='head-board-amount'>{state.factory.water.maxCapacity*state.factory.water.qty}</div> </div> <div className='head-board'> <div className='head-board-title'>Profit Metal:</div><div className='head-board-amount'>{profitMetal}/s</div> <div className='head-board-title'>Profit Water:</div><div className='head-board-amount'>{profitWater}/s</div> </div> <div className='head-board'> <div className='head-board-title'>Cost Metal:</div><div className='head-board-amount'>{feesMetal}/s</div> <div className='head-board-title'>Cost Water:</div><div className='head-board-amount'>{feesWater}/s</div> </div> <Factory factory={state.factory.metal} ressource={metal} setRessource={setMetal} level={state.factory.metal.qty} increase={ () => dispatch({ type: 'metal' })} /> <Factory factory={state.factory.water} ressource={water} setRessource={setWater} level={state.factory.water.qty} increase={ () => dispatch({ type: 'water' })} /> <div className='ship-list'> {Object.keys(ships).map((name, key) => ( <Ship key={key} ressource={metal} setRessource={setMetal} qty={ships[name].qty} increase={ () => dispatch({ type: 'ship', name: name })} {...ships[name]} /> ))} </div> </div> ); } export default Game;
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:icorrect_pc/core/app_assets.dart'; import 'package:provider/provider.dart'; import '../../../../core/app_colors.dart'; import '../../../providers/test_room_provider.dart'; class StartTestWidget extends StatelessWidget { Function onClickStartTest; StartTestWidget({super.key, required this.onClickStartTest}); @override Widget build(BuildContext context) { return Consumer<TestRoomProvider>(builder: (context, provider, child) { return Visibility( visible: !provider.isStartTest, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset( AppAssets.img_start, width: 150, ), const SizedBox(height: 20), ElevatedButton( onPressed: () { provider.setStartTest(true); onClickStartTest(); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(AppColors.purpleBlue), shape: MaterialStateProperty.all(RoundedRectangleBorder( borderRadius: BorderRadius.circular(13)))), child: const Padding( padding: EdgeInsets.symmetric(vertical: 10), child: Text("Start Test", style: TextStyle(fontSize: 17))), ) ], )); }); } }
import { allImages } from "../../assets/images/allImages"; import Button from "../Button/Button"; import "./HomeBanner.scss"; import { useNavigate } from "react-router-dom"; const HomeBanner = () => { //const navigate is used to navigate from one route to other. const navigate = useNavigate(); /** * The purpose of this function is to redirect the user to the * shop page when they click a button or link. */ const handleButtonClick = () => { navigate("/shop"); }; return ( <div className="home-banner-container"> <div className="home-banner-text"> <div className="home-banner-heading"> <div className="home-banner-heading-text"> Fresh and Nutritious Vegetables </div> <div className="home-banner-sub-text"> Discover a world of fresh, locally sourced vegetables for a healthy lifestyle. </div> <Button buttonName="Shop Now" buttonClick={() => handleButtonClick()} /> </div> <img className="home-banner-img" src={allImages.banner} alt="home-banner" /> </div> </div> ); }; export default HomeBanner;
<template> <form @submit.prevent="update"> <div class="grid grid-cols-6 gap-4"> <div class="col-span-2"> <label class="label">Beds</label> <input v-model.number="form.beds" type="text" class="input" /> <div v-if="form.errors.beds" class="input-error"> {{ form.errors.beds }} </div> </div> <div class="col-span-2"> <label class="label">Baths</label> <input v-model.number="form.baths" type="text" class="input" /> <div v-if="form.errors.baths" class="input-error"> {{ form.errors.baths }} </div> </div> <div class="col-span-2"> <label class="label">Area</label> <input v-model.number="form.area" type="text" class="input" /> <div v-if="form.errors.area" class="input-error"> {{ form.errors.area }} </div> </div> <div class="col-span-4"> <label class="label">City</label> <input v-model="form.city" type="text" class="input" /> <div v-if="form.errors.city" class="input-error"> {{ form.errors.city }} </div> </div> <div class="col-span-2"> <label class="label">Post Code</label> <input v-model="form.code" type="text" class="input" /> <div v-if="form.errors.code" class="input-error"> {{ form.errors.code }} </div> </div> <div class="col-span-4"> <label class="label">Street</label> <input v-model="form.street" type="text" class="input" /> <div v-if="form.errors.street" class="input-error"> {{ form.errors.street }} </div> </div> <div class="col-span-2"> <label class="label">Street Nr</label> <input v-model.number="form.street_nr" type="text" class="input" /> <div v-if="form.errors.street_nr" class="input-error"> {{ form.errors.street_nr }} </div> </div> <div class="col-span-6"> <label class="label">Price</label> <input v-model.number="form.price" type="text" class="input" /> <div v-if="form.errors.price" class="input-error"> {{ form.errors.price }} </div> </div> <div class="col-span-6"> <button type="submit" class="btn-primary">Edit</button> </div> </div> </form> </template> <script setup> import { useForm } from '@inertiajs/vue3' const props = defineProps({ listing: Object, }) const form = useForm({ beds: props.listing.beds, baths: props.listing.baths, area: props.listing.area, city: props.listing.city, street: props.listing.street, code: props.listing.code, street_nr: props.listing.street_nr, price: props.listing.price, }) const update = () => form.put(route('realtor.listing.update', { listing: props.listing.id })) </script> <style scoped> label { margin-right: 2em; } div { padding: 2px } </style>
import math import random import uuid from io import BytesIO from typing import List import pandas as pd from fastapi import FastAPI, UploadFile, File, HTTPException, APIRouter from fastapi.encoders import jsonable_encoder from starlette.responses import JSONResponse import logging import json import numpy as np from datetime import datetime, timedelta # Initialize logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) # Initialize FastAPI app and router app = FastAPI() router = APIRouter() # Load the template from the specified file in the root directory template_file_path = 'app/storage/extract_templates/poc_template.json' with open(template_file_path, 'r') as template_file: template = json.load(template_file) def dynamic_apply_template(df, template_actions): # Initially, create a set to keep track of all columns to retain columns_to_retain = set() for action in template_actions: column_names = action["column_name"] field_name = action["field_name"] # Ensure the field_name is included in the columns to retain columns_to_retain.add(field_name) if action["action"] == "split": # Assuming each column in column_names will have the same split for column_name in column_names: # Create the new field with an empty dict to populate later df[field_name] = [{} for _ in range(len(df))] split_info = action["split_into"] for part_key, part_value in split_info.items(): # Split and populate the new dictionary field df[field_name] = df.apply( lambda row: {**row[field_name], part_key: float(row[column_name].split(action["separator"])[0].strip()) if part_key == 'lat' else float(row[column_name].split(action["separator"])[1].strip())}, axis=1 ) elif action["action"] == "*": # Check for the 'format' key if 'format' in action: # If 'clean_spaces' option is selected if action['format'] == 'clean_spaces': for column_name in column_names: if df[column_name].dtype == 'object': # Check if the column contains string values df[field_name] = df[column_name].str.replace(' ', '') # Remove spaces else: df[field_name] = df[column_name] # If 'lower_case' option is selected elif action['format'] == 'lower_case': for column_name in column_names: if df[column_name].dtype == 'object': # Check if the column contains string values df[field_name] = df[column_name].str.lower() # Convert to lower case else: df[field_name] = df[column_name] else: # No special formatting specified, simply copy the value without any changes for column_name in column_names: if df[column_name].dtype == 'object': # Check if the column contains string values df[field_name] = df[column_name].str.replace(' ', '') # Remove spaces else: df[field_name] = df[column_name] elif action["action"] == "date_range": array_info = action["array"] result = [] for index, row in df.iterrows(): date_values = {} from_date = None # Initialize variable to hold the "from" date for comparison # Process each column specified in the action for column_name, part_key in zip(column_names, array_info.keys()): # Extract the prefix to determine if the field is "from" or "to" prefix = array_info[part_key]["prefix"] date_str = row[column_name].strip() # Strip whitespace from the date string # Convert the date string to a datetime object current_date = pd.to_datetime(date_str) if prefix == "from": from_date = current_date # Save "from" date for later comparison date_values[prefix] = current_date.strftime('%Y-%m-%dT%H:%M:%SZ') elif prefix == "to": # Ensure that we have a "from" date to compare against if from_date is not None and current_date < from_date: current_date += timedelta(days=1) # Add a day if "to" date is before "from" date date_values[prefix] = current_date.strftime('%Y-%m-%dT%H:%M:%SZ') else: # Handle any other date types that might be present date_values[prefix] = current_date.strftime('%Y-%m-%dT%H:%M:%SZ') result.append(date_values) df[field_name] = pd.Series(result) # Assign the processed date values back to the DataFrame elif action["action"] == "concat_uuid": # Concatenate required_vehicle_type with a UUID for column_name in column_names: df[field_name] = df.apply( lambda row: f"order_{row[column_name]}_{uuid.uuid4().hex[:8]}", axis=1 ) elif action["action"] == "minutes_to_seconds": for column_name in column_names: df[field_name] = df[column_name] * 60 # Replace NaN values or empty strings with None df.replace({np.nan: None, '': None}, inplace=True) # Retain only the columns that were processed as per the template, plus any newly created columns df = df[list(columns_to_retain)] return df def read_vehicle_types_from_file(file_path): with open(file_path, 'r') as file: vehicle_types = json.load(file) return vehicle_types # this function will be deleted .... def generate_nearby_location(lat, lng, max_distance_in_meters): """ Generate a nearby location within a random distance up to a maximum distance in meters. """ R = 6378.1 # Radius of the Earth in kilometers # Generate a random distance up to the maximum distance distance_in_meters = random.uniform(0, max_distance_in_meters) # Convert distance to kilometers distance_km = distance_in_meters / 1000 # Randomize bearing between 0 and 360 degrees bearing = math.radians(random.randint(0, 360)) lat1 = math.radians(lat) lon1 = math.radians(lng) lat2 = math.asin(math.sin(lat1) * math.cos(distance_km / R) + math.cos(lat1) * math.sin(distance_km / R) * math.cos(bearing)) lon2 = lon1 + math.atan2(math.sin(bearing) * math.sin(distance_km / R) * math.cos(lat1), math.cos(distance_km / R) - math.sin(lat1) * math.sin(lat2)) new_lat = math.degrees(lat2) new_lng = math.degrees(lon2) return new_lat, new_lng def generate_vehicle_locations(shipments: List[dict], w: int) -> List[dict]: vehicle_locations = [] # Extract pickup locations from shipments pickup_locations = list(set((shipment['pickup']['lat'], shipment['pickup']['lng']) for shipment in shipments)) random.shuffle(pickup_locations) file_path = 'app/storage/profiles/vehicles/silal.json' vehicle_types = read_vehicle_types_from_file(file_path) # Create all vehicles without assigning locations vehicles = [] for vehicle_type in vehicle_types: count = vehicle_type["demo_count"] on_demand = vehicle_type["demo_count"] * 3 for _ in range(count): vehicle_uuid = uuid.uuid4().hex[:8] vehicle = { 'type': vehicle_type["name"], 'capacity': vehicle_type["capacity"], 'label': f"{vehicle_type['name']}_{vehicle_uuid}", 'display_name': f"vehicle_{vehicle_type['name']}_{vehicle_uuid}", 'on_demand': False, 'cost': 1 } vehicles.append(vehicle) for _ in range(on_demand): vehicle_uuid = uuid.uuid4().hex[:8] vehicle = { 'type': vehicle_type["name"], 'capacity': vehicle_type["capacity"], 'label': f"{vehicle_type['name']}_{vehicle_uuid}", 'display_name': f"vehicle_{vehicle_type['name']}_{vehicle_uuid}", 'on_demand': True, 'cost': 1000 } vehicles.append(vehicle) # Assign vehicles to pickup locations in a round-robin manner pickup_index = 0 for vehicle in vehicles: nearby_lat, nearby_lng = generate_nearby_location(pickup_locations[pickup_index][0], pickup_locations[pickup_index][1], w) vehicle['lat'] = nearby_lat vehicle['lng'] = nearby_lng vehicle_locations.append(vehicle) # Move to the next pickup location in a round-robin manner pickup_index = (pickup_index + 1) % len(pickup_locations) return vehicle_locations @router.post("/api/v1/files/parse") async def parse(file: UploadFile = File(...)): try: if file.content_type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": contents = await file.read() data = BytesIO(contents) # Specify the sheet names directly from the template sheet_names = list(template.keys()) # Assume template might specify multiple sheets dfs = pd.read_excel(data, sheet_name=sheet_names) processed_data = {} for sheet_name, df in dfs.items(): if sheet_name in template: df_processed = dynamic_apply_template(df, template[sheet_name]) processed_data[sheet_name] = df_processed.to_dict(orient='records') # If only interested in "Stock transfer & Delivery", directly return its data if "Stock transfer & Delivery" in processed_data: records = processed_data["Stock transfer & Delivery"] vehicles = generate_vehicle_locations(records, 150) records = apply_exclusive_customers(records, processed_data['Sheet2']) return {'records': records, 'vehicles': vehicles, 'exclusive_customers': processed_data['Sheet2']} else: return JSONResponse(content={"error": "Specified sheet not found in the file"}, status_code=404) else: raise HTTPException(status_code=400, detail="Unsupported file type") except Exception as e: logger.exception("An error occurred during file processing", exc_info=e) raise HTTPException(status_code=500, detail="Internal server error") def apply_exclusive_customers(data, exclusive_customers): # Iterate over each element in data for element in data: # Check if the customer exists in the exclusive_customers array customer = element.get('customer') if customer in (customer_info.get('customer') for customer_info in exclusive_customers): element['exclusive'] = True # Set flag to True if customer is exclusive else: element['exclusive'] = False # Set flag to False if customer is not exclusive return data # Return the modified data array
package com.BD; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Conexion { private String host; private String port; private String database; private String user; private String password; private Connection connection; public Conexion(String host, String port, String database, String user, String password) { this.host = host; this.port = port; this.database = database; this.user = user; this.password = password; } public Connection getConnection() throws SQLException { if (connection == null || connection.isClosed()) { try { Class.forName("org.postgresql.Driver"); connection = DriverManager.getConnection( "jdbc:postgresql://" + host + ":" + port + "/" + database, user, password); } catch (SQLException e) { throw new SQLException("Error al conectar con la base de datos: " + e.getMessage()); } catch (ClassNotFoundException e) { throw new SQLException("Error al cargar el driver de la base de datos: " + e.getMessage()); } } return connection; } public void closeConnection() throws SQLException { if (connection != null && !connection.isClosed()) { try { connection.close(); } catch (SQLException e) { throw new SQLException("Error al cerrar la conexión con la base de datos: " + e.getMessage()); } } } }
import { ISteamGameNews } from "../../../src/interfaces/ISteamGameNews"; import { fetchGameNews } from "../../../src/utils/api"; import axios from "axios"; describe("steam game news api call tests", () => { afterEach(() => { jest.clearAllMocks(); }); describe("get steam news", () => { const axiosGetSpy = jest.spyOn(axios, "get"); it("should make a correct API call to retrieve steam game news", async () => { await fetchGameNews(1337520); expect(axiosGetSpy).toHaveBeenCalledWith("/api/steamGameNews", { params: { appId: 1337520 }, }); }); it("should return steam game news data", async () => { const mockResponseData: ISteamGameNews = { appid: 1337520, count: 1, newsitems: [ { appid: 1337520, author: "some_author", contents: "some_contents", date: 111, feed_type: 111, feedlabel: "some_feedlabel", feedname: "some_feedname", gid: "some_gid", is_external_url: true, title: "some_title", url: "some_url", }, ], }; axiosGetSpy.mockResolvedValueOnce({ data: mockResponseData }); const result = await fetchGameNews(1337520); expect(result).toHaveProperty("appid"); expect(result).toHaveProperty("count"); expect(result).toHaveProperty("newsitems"); }); }); });
#include <iostream> class Tool { public: virtual void mouseDown() = 0; virtual void mouseUp() = 0; }; class SelectionTool : public Tool { public: void mouseDown() override { std::cout << "Selection icon\n"; } void mouseUp() override { std::cout << "Draw dashed rectangle\n"; } }; class BrushTool : public Tool { public: void mouseDown() override { std::cout << "Brush icon\n"; } void mouseUp() override { std::cout << "Draw a line\n"; } }; class EraserTool : public Tool { public: void mouseDown() override { std::cout << "Eraser icon\n"; } void mouseUp() override { std::cout << "Eraser object\n"; } }; class Canvas { private: Tool *currentTool; public: void mouseDown() { currentTool->mouseDown(); } void mouseUp() { currentTool->mouseUp(); } Tool *getCurrentTool() { return currentTool; } void setCurrentTool(Tool *tool) { this->currentTool = tool; } }; void state_test() { Canvas canvas; SelectionTool selectionTool; BrushTool brushTool; EraserTool eraserTool; canvas.setCurrentTool(&selectionTool); canvas.mouseDown(); canvas.mouseUp(); canvas.setCurrentTool(&brushTool); canvas.mouseDown(); canvas.mouseUp(); canvas.setCurrentTool(&eraserTool); canvas.mouseDown(); canvas.mouseUp(); }
package mipstart; import java.util.HashMap; import formulation.FormulationEdge; import ilog.concert.IloException; import ilog.concert.IloNumVar; import formulation.AbstractFormulation; import formulation.Edge; /** * This class aims at containing a MIP Start (feasible, integer) solution * provided by a primal heuristic. * It stores the feasible solution as <i>var</i> (edge variables) and <i>val</i> * (values of the associated edge variables) arrays, * which is required by CPLEX. * This feasible solution is created in the method aiming at performing primal heuristic. * * @param author Zacharie ALES, Nejat ARINIK */ public class SolutionManager { AbstractFormulation formulation; public IloNumVar[] var; // edge variables in array format instead of matrix public double[] val; // edge values in array format instead of matrix public int[] membership; // partition information array // total weight of the misplaced links in the current best formulation private double evaluation = -1.0; /** * Links between and edge and its index in <i>val</i> and <i>var</i> arrays. */ HashMap<Edge, Integer> id = new HashMap<Edge, Integer>(); /** * Copies the formulation in input. * Initializes the class variables <i>var</i> (i.e. edge variables), * <i>val</i> (i.e. values of the edge variables) * and <i>membership</i> (partition information) * * @param formulation current best <i>formulation</i> * @throws IloException */ public SolutionManager(AbstractFormulation formulation) throws IloException{ this.formulation = formulation; var = new IloNumVar[arraySize()]; val = new double[arraySize()]; membership = new int[formulation.n()]; setValToZeroAndCreateID(formulation.n()); setVar(); } /** * Returns the size of the arrays associated with '<i>var</i>' and '<i>val</i>' arrays. * If we suppose that there are <i>n</i> vertices in the graph, * the size will be <i>(n * (n-1)) / 2</i>. * * @return size */ private int arraySize() { return formulation.getEdges().size(); } /** * Returns the stored best partition (i.e. membership) array. * * @return membership */ public int [] getMembership() { return membership; } /** * Saves the partition in input into the stored best partition (i.e. membership) array. * * @param membership */ public void setMembership(int [] mem) { for(int i=0;i<formulation.n();i++) { membership[i]=mem[i]; } } /** * Set all the edge variables to zero, and creates and id for each edge variable * * @param n number of nodes */ public void setValToZeroAndCreateID(int n){ /* Set all the edge variables to zero */ int v = 0; for(Edge e : formulation.getEdges()){ val[v] = 0; id.put(e, v); v++; } } /** * Set all the edge variables from the current best <i>formulation</i>. * * @throws IloException */ public void setVar() throws IloException{ var = new IloNumVar[arraySize()]; int v = 0; for(Edge e : formulation.getEdges()){ var[v] = formulation.edgeVar(e.getSource(),e.getDest()); v++; } } /** * Set the value of the corresponding edge variable e_ij. * * @param i <i>i</i>.th node * @param j <i>j</i>.th node * @param value weight of the corresponding edge * @throws IloException */ public void setEdge(int i, int j, double value){ Edge e = new Edge(this.formulation.n(),i,j); this.val[id.get(e)] = value; } /** * It computes the objective function value of Correlation Clustering. * The '<i>membership</i>' vector contains the partition information obtained * by 'PrimalHeuristicRounding.java' * * @return evaluation */ public double evaluate(){ if(evaluation == -1.0){ double result = 0.0; for(Edge e : formulation.getEdges()){ double weight = e.getWeight(); if(membership[e.getSource()] == membership[e.getDest()] && weight<0) { result += Math.abs(weight); } else if(membership[e.getSource()] != membership[e.getDest()] && weight>0) { result += weight; } } return result; } else return evaluation; } /** * Updates the formulation and the variables. The number of nodes must be * the same in both formulations. * * @param formulation2 The new formulation * @throws IloException */ public void updateFormulationAndVariables(AbstractFormulation formulation2) throws IloException { if(formulation.n() == formulation2.n()) { this.formulation = formulation2; var = new IloNumVar[arraySize()]; setVar(); } } }
function cal = sssSpoofOneLightCal(varargin) % Make a OneLight calibration structure for the spatial-spectral simulator % % Syntax: % cal = sssSpoofOneLightCal % % Description: % Make a OneLight calibration structure that describes the spatial-spectral simulator. % % Inputs: % None. % % Outputs: % cal - The generated calibration structure. % % Optional key/value pairs: % S - Wavelength support. Default [380 2 201]. % plotBasis - Boolean (default false). Make a plot of the basis. % ledFilename - Name of the LED Excel ata file to read in. String, % default 'LUXEON_CZ_SpectralPowerDistribution.xlsx'. % whichLedsToOmit - Indices of LEDs in data file to omit from returned % basis. Row vector, default [6 7 8 12]. % gaussianPeakWls - Row vector of peak wavelengths of Gaussian basis functions. % Default [440 550]. % gaussianFWHM - Full width at half max of Gaussian basis functions. % In nanometers. Scalar, default 30. % See Also: % sssGetSpectralBasis % % History: % 05/03/20 dhb Wrote it. % Examples: %{ cal = sssSpoofOneLightCal; %} %{ cal = sssSpoofOneLightCal('plotBasis',true,... 'gaussianPeakWls',[437 485 540 562 585 618 652], ... 'gaussianFWHM',25); %} %% Parse varagin p = inputParser; p.addParameter('S',[380 2 201],@isnumeric); p.addParameter('plotBasis', false, @islogical); p.addParameter('ledFilename','LUXEON_CZ_SpectralPowerDistribution.xlsx', @ischar); p.addParameter('whichLedsToOmit',[6 7 8 13],@isnumeric); p.addParameter('gaussianPeakWls',[440 540],@isnumeric); p.addParameter('gaussianFWHM',30,@isscalar);p.parse(varargin{:}); p.parse(varargin{:}); %% ID cal.calID = 'sssSpoofCal'; %% Describe cal.describe.gammaFitType = 'betacdfpiecelin'; cal.describe.useAverageGamma = 1; cal.describe.nGammaFitLevels = 256; cal.describe.nGammaLevels = 24; cal.describe.gammaNumberWlUseIndices = 5; cal.describe.whichAverageGamma = 'median'; cal.describe.S = p.Results.S; cal.describe.useOmni = false; %% Spectral basis B = sssGetSpectralBasis(cal.describe.S,'plotBasis',p.Results.plotBasis,... 'ledFilename',p.Results.ledFilename, ... 'whichLedsToOmit',p.Results.whichLedsToOmit, ... 'gaussianPeakWls',p.Results.gaussianPeakWls, ... 'gaussianFWHM',p.Results.gaussianFWHM); wls = SToWls(cal.describe.S); cal.describe.numWavelengthBands = size(B,2); cal.describe.nGammaBands = cal.describe.numWavelengthBands; cal.raw.darkMeas = zeros(size(wls,1),2); cal.raw.darkMeasCheck = cal.raw.darkMeas; cal.raw.lightMeas = B; %% Gamma cal.describe.gamma.gammaLevels = linspace(1/cal.describe.nGammaLevels,1,cal.describe.nGammaLevels); cal.describe.gamma.gammaBands = 1:cal.describe.nGammaBands; for ii = 1:cal.describe.numWavelengthBands for jj = 1:cal.describe.nGammaLevels cal.raw.gamma.rad(ii).meas(:,jj) = cal.describe.gamma.gammaLevels(jj)*cal.raw.lightMeas(:,ii); end end %% Get cal.computed % Wavelength sampling cal.computed.pr650S = cal.describe.S; cal.computed.pr650Wls = SToWls(cal.computed.pr650S); cal.computed.commonWls = cal.computed.pr650Wls; % Copy over spectral data cal.computed.pr650M = cal.raw.lightMeas; cal.computed.pr650Md = cal.raw.darkMeas; cal.computed.pr650MeanDark = mean(cal.computed.pr650Md,2); cal.computed.pr650MeanDark(cal.computed.pr650MeanDark < 0) = 0; % Use the stops information to get the fraction of max power for each gamma measurement, in range [0,1]. cal.computed.gammaInputRaw = [0 ; cal.describe.gamma.gammaLevels']; % Extract the gamma data for the PR-6XX. % % This gets the measured spectrum and dark subtracts. % It then computes the range of wavelengths around the peak % that will be used when we compute power for each gamma band % and computes the fraction of max power using regression on % the spectra from the selected wavelength bands. % % Note: raw.gamma.rad is a structure array. Each element % of the structure array contains the measurements for one % of the measured gamma bands. if (size(cal.raw.gamma.rad,2) ~= cal.describe.nGammaBands) error('Mismatch between specified number of gamma bands and size of measurement struct array'); end for k = 1:cal.describe.nGammaBands % Dark subtract with time correction. As with primary spectra above, % there are two distinct ways we can do this, depending on whether we % calibrated around dark or around a specified background. The end % result of this makes the two sets of measurements equivalent going % onwards. gammaTemp = cal.raw.gamma.rad(k).meas; gammaMeas{k} = gammaTemp - cal.computed.pr650MeanDark(:,ones(1,size(cal.raw.gamma.rad(k).meas,2))); [~,peakWlIndices{k}] = max(gammaMeas{k}(:,end)); % Get wavelength indices around peak to use. cal.describe.peakWlIndex(k) = peakWlIndices{k}(1); cal.describe.minWlIndex(k) = cal.describe.peakWlIndex(k)-cal.describe.gammaNumberWlUseIndices; if (cal.describe.minWlIndex(k) < 1) cal.describe.minWlIndex(k) = 1; end cal.describe.maxWlIndex(k) = cal.describe.peakWlIndex(k)+cal.describe.gammaNumberWlUseIndices; if (cal.describe.maxWlIndex(k) > cal.describe.S(3)) cal.describe.maxWlIndex(k) = cal.describe.S(3); end % Little check and then get power for each measured level for this measured band if (size(cal.raw.gamma.rad(k).meas,2) ~= cal.describe.nGammaLevels) error('Mismatch between specified number of gamma levels and size of measurement array'); end for i = 1:cal.describe.nGammaLevels wavelengthIndices = cal.describe.minWlIndex(k):cal.describe.maxWlIndex(k); cal.computed.gammaData1{k}(i) = gammaMeas{k}(wavelengthIndices,end)\ ... gammaMeas{k}(wavelengthIndices,i); %#ok<*AGROW> cal.computed.gammaRatios(k,i+1).wavelengths = cal.computed.commonWls(wavelengthIndices); cal.computed.gammaRatios(k,i+1).ratios = gammaMeas{k}(wavelengthIndices,i) ./ gammaMeas{k}(wavelengthIndices,end); end cal.computed.gammaRatios(k,1).wavelengths = cal.computed.gammaRatios(k,2).wavelengths; cal.computed.gammaRatios(k,1).ratios = 0*cal.computed.gammaRatios(k,2).ratios; end % Fit each indivdually measured gamma function to finely spaced real valued % primary levels. cal.computed.gammaInput = linspace(0,1,cal.describe.nGammaFitLevels)'; for k = 1:cal.describe.nGammaBands cal.computed.gammaTableMeasuredBands(:,k) = [0 ; cal.computed.gammaData1{k}']; cal.computed.gammaTableMeasuredBandsFit(:,k) = OLFitGamma(cal.computed.gammaInputRaw,cal.computed.gammaTableMeasuredBands(:,k),cal.computed.gammaInput,cal.describe.gammaFitType); end % Interpolate the measured bands out across all of the bands for l = 1:cal.describe.nGammaFitLevels cal.computed.gammaTable(l,:) = interp1(cal.describe.gamma.gammaBands',cal.computed.gammaTableMeasuredBandsFit(l,:)',(1:cal.describe.numWavelengthBands)','linear','extrap')'; end % Make each band's gamma curve monotonic for b = 1:cal.describe.numWavelengthBands cal.computed.gammaTable(:,b) = MakeMonotonic(cal.computed.gammaTable(:,b)); end % Average gamma measurements over bands switch (cal.describe.whichAverageGamma) case 'median' cal.computed.gammaTableAvg = median(cal.computed.gammaTableMeasuredBandsFit,2); case 'middle' nMeasuredBands = size(cal.computed.gammaTableMeasuredBandsFit,2); middleIndex = round(nMeasuredBands/2); cal.computed.gammaTableAvg = cal.computed.gammaTableMeasuredBandsFit(:,middleIndex); otherwise error('Unknown value for whichAverage gamma provided.') end cal.computed.gammaTableAvg = MakeMonotonic(cal.computed.gammaTableAvg);
import type { BotInformation, UserStatus, User as UserI, RelationshipStatus, FieldsUser, DataEditUser, } from "revolt-api"; import type { File } from "revolt-api"; import { makeAutoObservable, action, runInAction, computed } from "mobx"; import isEqual from "lodash.isequal"; import { U32_MAX, UserPermission } from "../permissions/definitions"; import { toNullable, Nullable } from "../util/null"; import Collection from "./Collection"; import { Client, FileArgs } from ".."; import _ from "lodash"; import { decodeTime } from "ulid"; export class User { client: Client; _id: string; username: string; avatar: Nullable<File>; badges: Nullable<number>; status: Nullable<UserStatus>; relationship: Nullable<RelationshipStatus>; online: boolean; privileged: boolean; flags: Nullable<number>; bot: Nullable<BotInformation>; /** * Get timestamp when this user was created. */ get createdAt() { return decodeTime(this._id); } constructor(client: Client, data: UserI) { this.client = client; this._id = data._id; this.username = data.username; this.avatar = toNullable(data.avatar); this.badges = toNullable(data.badges); this.status = toNullable(data.status); this.relationship = toNullable(data.relationship); this.online = data.online ?? false; this.privileged = data.privileged ?? false; this.flags = toNullable(data.flags); this.bot = toNullable(data.bot); makeAutoObservable(this, { _id: false, client: false, }); } @action update(data: Partial<UserI>, clear: FieldsUser[] = []) { const apply = (key: string) => { // This code has been tested. if ( // @ts-expect-error TODO: clean up types here typeof data[key] !== "undefined" && // @ts-expect-error TODO: clean up types here !isEqual(this[key], data[key]) ) { // @ts-expect-error TODO: clean up types here this[key] = data[key]; if (key === "relationship") { this.client.emit("user/relationship", this); } } }; for (const entry of clear) { switch (entry) { case "Avatar": this.avatar = null; break; case "StatusText": { if (this.status) { this.status.text = undefined; } } } } apply("username"); apply("avatar"); apply("badges"); apply("status"); apply("relationship"); apply("online"); apply("privileged"); apply("flags"); apply("bot"); } /** * Open a DM with a user * @returns DM Channel */ async openDM() { let dm = [...this.client.channels.values()].find( (x) => x.channel_type === "DirectMessage" && x.recipient == this, ); if (!dm) { const data = await this.client.api.get( `/users/${this._id as ""}/dm`, ); dm = await this.client.channels.fetch(data._id, data)!; } runInAction(() => { dm!.active = true; }); return dm; } /** * Send a friend request to a user */ async addFriend() { return await this.client.api.post(`/users/friend`, { username: this.username, }); } /** * Remove a user from the friend list */ async removeFriend() { return await this.client.api.delete(`/users/${this._id as ""}/friend`); } /** * Block a user */ async blockUser() { return await this.client.api.put(`/users/${this._id as ""}/block`); } /** * Unblock a user */ async unblockUser() { return await this.client.api.delete(`/users/${this._id as ""}/block`); } /** * Fetch the profile of a user * @returns The profile of the user */ async fetchProfile() { return await this.client.api.get(`/users/${this._id as ""}/profile`); } /** * Fetch the mutual connections of the current user and a target user * @returns The mutual connections of the current user and a target user */ async fetchMutual() { return await this.client.api.get(`/users/${this._id as ""}/mutual`); } /** * Get the default avatar URL of a user */ get defaultAvatarURL() { return `${this.client.apiURL}/users/${this._id}/default_avatar`; } @computed generateAvatarURL(...args: FileArgs) { return ( this.client.generateFileURL(this.avatar ?? undefined, ...args) ?? this.defaultAvatarURL ); } @computed get permission() { let permissions = 0; switch (this.relationship) { case "Friend": case "User": return U32_MAX; case "Blocked": case "BlockedOther": return UserPermission.Access; case "Incoming": case "Outgoing": permissions = UserPermission.Access; } if ( [...this.client.channels.values()].find( (channel) => (channel.channel_type === "Group" || channel.channel_type === "DirectMessage") && channel.recipient_ids?.includes(this.client.user!._id), ) || [...this.client.members.values()].find( (member) => member._id.user === this.client.user!._id, ) ) { if (this.client.user?.bot || this.bot) { permissions |= UserPermission.SendMessage; } permissions |= UserPermission.Access | UserPermission.ViewProfile; } return permissions; } } export default class Users extends Collection<string, User> { constructor(client: Client) { super(client); this.createObj = this.createObj.bind(this); this.set( "00000000000000000000000000", new User(client, { _id: "00000000000000000000000000", username: "Revolt", }), ); } @action $get(id: string, data?: UserI) { const user = this.get(id)!; if (data) user.update(data); return user; } /** * Fetch a user * @param id User ID * @returns User */ async fetch(id: string, data?: UserI) { if (this.has(id)) return this.$get(id, data); const res = data ?? (await this.client.api.get(`/users/${id as ""}`)); return this.createObj(res); } /** * Create a user object. * This is meant for internal use only. * @param data: User Data * @returns User */ createObj(data: UserI) { if (this.has(data._id)) return this.$get(data._id, data); const user = new User(this.client, data); runInAction(() => { this.set(data._id, user); }); this.client.emit("user/relationship", user); return user; } /** * Edit the current user * @param data User edit data object */ async edit(data: DataEditUser) { await this.client.api.patch("/users/@me", data); } /** * Change the username of the current user * @param username New username * @param password Current password */ async changeUsername(username: string, password: string) { return await this.client.api.patch("/users/@me/username", { username, password, }); } }
function cx = legendre_associated_normalized_N3D ( n, m, x ) %% LEGENDRE_ASSOCIATED: normalized associated Legendre functions. % With normalization for N3D % % Discussion: % % The unnormalized associated Legendre functions P_N^M(X) have % the property that % % Integral ( -1 <= X <= 1 ) ( P_N^M(X) )^2 dX % = 2 * ( N + M )! / ( ( 2 * N + 1 ) * ( N - M )! ) % % By dividing the function by the square root of this term, % the normalized associated Legendre functions have norm 1. % % However, we plan to use these functions to build spherical % harmonics, so we use a slightly different normalization factor of % % sqrt ( ( ( 2 * N + 1 ) * ( N - M )! ) / ( 4 * pi * ( N + M )! ) ) % % Modified: % % 07 March 2005 % % Author: % % John Burkardt % % Reference: % % Milton Abramowitz and Irene Stegun, % Handbook of Mathematical Functions, % US Department of Commerce, 1964. % % Parameters: % % Input, integer N, the maximum first index of the Legendre % function, which must be at least 0. % % Input, integer M, the second index of the Legendre function, % which must be at least 0, and no greater than N. % % Input, real X, the point at which the function is to be % evaluated. X must satisfy -1 <= X <= 1. % % Output, real CX(1:N+1), the values of the first N+1 function. % if ( m < 0 ) fprintf ( 1, '\n' ); fprintf ( 1, 'LEGENDRE_ASSOCIATED_NORMALIZED - Fatal error!\n' ); fprintf ( 1, ' Input value of M is %d\n', m ); fprintf ( 1, ' but M must be nonnegative.\n' ); error ( 'LEGENDRE_ASSOCIATED_NORMALIZED - Fatal error!' ); end if ( n < m ) fprintf ( 1, '\n' ); fprintf ( 1, 'LEGENDRE_ASSOCIATED_NORMALIZED - Fatal error!\n' ); fprintf ( 1, ' Input value of M = %d\n', m ); fprintf ( 1, ' Input value of N = %d\n', n ); fprintf ( 1, ' but M must be less than or equal to N.\n' ); error ( 'LEGENDRE_ASSOCIATED_NORMALIZED - Fatal error!' ); end if ( x < -1.0E+00 ) fprintf ( 1, '\n' ); fprintf ( 1, 'LEGENDRE_ASSOCIATED_NORMALIZED - Fatal error!\n' ); fprintf ( 1, ' Input value of X = %f\n', x ); fprintf ( 1, ' but X must be no less than -1.\n' ); error ( 'LEGENDRE_ASSOCIATED_NORMALIZED - Fatal error!' ); end if ( 1.0E+00 < x ) fprintf ( 1, '\n' ); fprintf ( 1, 'LEGENDRE_ASSOCIATED_NORMALIZED - Fatal error!\n' ); fprintf ( 1, ' Input value of X = %f\n', x ); fprintf ( 1, ' but X must be no more than 1.\n' ); error ( 'LEGENDRE_ASSOCIATED_NORMALIZED - Fatal error!' ); end cx(1:m) = 0.0; cx(m+1) = 1.0; somx2 = sqrt ( 1.0 - x * x ); fact = 1.0; for i = 1 : m cx(m+1) = -cx(m+1) * fact * somx2; fact = fact + 2.0; end if ( m < n ) cx(m+2) = x * ( 2 * m + 1 ) * cx(m+1); end for i = m+2 : n cx(i+1) = ( ( 2 * i - 1 ) * x * cx(i) ... + ( - i - m + 1 ) * cx(i-1) ) ... / ( i - m ); end % % Normalization for N3D. (not including 2-delta(0,n)factor ). % for mm = m : n factor = sqrt ( ( ( 2 * mm + 1 ) * d_factorial ( mm - m ) ) ... / ( d_factorial ( mm + m ) ) ); factor = factor / sqrt(4*pi) * (-1)^m; % normalize for Y.Y = delta , remove Condon-Shortley cx(mm+1) = cx(mm+1) * factor; end
import { Observable } from 'rxjs'; import { MOTOR_ACC_DEC_DEFAULT_PROFILE_ID, MOTOR_LIMITS, MessageType, MotorServoEndState, MotorUseProfile, PortModeName, PortOperationCompletionInformation, WELL_KNOWN_PORT_MODE_IDS, } from '../../constants'; import { HubConfig, IMotorsFeature, IOutboundMessenger, PortCommandExecutionStatus, ServoCommandOptions, StartPowerOptions, StartSpeedOptions } from '../../hub'; import { RawMessage } from '../../types'; import { IMotorCommandsOutboundMessageFactory } from './i-motor-commands-outbound-message-factory'; export class MotorsFeature implements IMotorsFeature { constructor( private readonly messenger: IOutboundMessenger, private readonly portOutputCommandOutboundMessageFactoryService: IMotorCommandsOutboundMessageFactory, private readonly config: HubConfig ) { } public setAccelerationTime( portId: number, timeMs: number, ): Observable<PortCommandExecutionStatus> { const message = this.portOutputCommandOutboundMessageFactoryService.setAccelerationTime( portId, timeMs, MOTOR_ACC_DEC_DEFAULT_PROFILE_ID ); return this.execute(message); } public setDecelerationTime( portId: number, timeMs: number, ): Observable<PortCommandExecutionStatus> { const message = this.portOutputCommandOutboundMessageFactoryService.setDecelerationTime( portId, timeMs, MOTOR_ACC_DEC_DEFAULT_PROFILE_ID ); return this.execute(message); } public startPower( portId: number, power: number, powerModeId: number, options?: StartPowerOptions ): Observable<PortCommandExecutionStatus> { const message = this.portOutputCommandOutboundMessageFactoryService.startPower( portId, power, powerModeId, options?.bufferMode ?? this.config.defaultBufferMode, options?.noFeedback ? PortOperationCompletionInformation.noAction : PortOperationCompletionInformation.commandFeedback, ); return this.execute(message); } public startSpeed( portId: number, speed: number, options?: StartSpeedOptions ): Observable<PortCommandExecutionStatus> { const message = this.portOutputCommandOutboundMessageFactoryService.startSpeed( portId, speed, options?.power ?? MOTOR_LIMITS.maxPower, options?.useProfile ?? MotorUseProfile.dontUseProfiles, options?.bufferMode ?? this.config.defaultBufferMode, options?.noFeedback ? PortOperationCompletionInformation.noAction : PortOperationCompletionInformation.commandFeedback, ); return this.execute(message); } public setSpeedSynchronized( virtualPortId: number, speed1: number, speed2: number, options?: StartSpeedOptions ): Observable<PortCommandExecutionStatus> { const message = this.portOutputCommandOutboundMessageFactoryService.startRotationSynchronized( virtualPortId, speed1, speed2, options?.power ?? MOTOR_LIMITS.maxPower, options?.useProfile ?? MotorUseProfile.dontUseProfiles, options?.bufferMode ?? this.config.defaultBufferMode, options?.noFeedback ? PortOperationCompletionInformation.noAction : PortOperationCompletionInformation.commandFeedback, ); return this.execute(message); } public goToPosition( portId: number, absoluteDegree: number, options?: ServoCommandOptions ): Observable<PortCommandExecutionStatus> { const message = this.portOutputCommandOutboundMessageFactoryService.goToAbsolutePosition( portId, absoluteDegree, options?.speed ?? MOTOR_LIMITS.maxSpeed, options?.power ?? MOTOR_LIMITS.maxPower, options?.endState ?? MotorServoEndState.hold, options?.useProfile ?? MotorUseProfile.dontUseProfiles, options?.bufferMode ?? this.config.defaultBufferMode, options?.noFeedback ? PortOperationCompletionInformation.noAction : PortOperationCompletionInformation.commandFeedback, ); return this.execute(message); } public goToPositionSynchronized( virtualPortId: number, targetDegree1: number, targetDegree2: number, options?: ServoCommandOptions ): Observable<PortCommandExecutionStatus> { const message = this.portOutputCommandOutboundMessageFactoryService.goToAbsolutePositionSynchronized( virtualPortId, targetDegree1, targetDegree2, options?.speed ?? MOTOR_LIMITS.maxSpeed, options?.power ?? MOTOR_LIMITS.maxPower, options?.endState ?? MotorServoEndState.hold, options?.useProfile ?? MotorUseProfile.dontUseProfiles, options?.bufferMode ?? this.config.defaultBufferMode, options?.noFeedback ? PortOperationCompletionInformation.noAction : PortOperationCompletionInformation.commandFeedback, ); return this.execute(message); } public setZeroPositionRelativeToCurrentPosition( portId: number, offset: number, positionModeId: number = WELL_KNOWN_PORT_MODE_IDS.motor[PortModeName.position] ): Observable<PortCommandExecutionStatus> { const message = this.portOutputCommandOutboundMessageFactoryService.presetEncoder( portId, // We use negative value here because: // 1. presetting encoder sets absolute zero relative to current absolute motor position // e.g. if current position is 100 and absolutePosition is 50, then absolute zero will be set to 150 // 2. somehow hub treats absolute zero in an unusual way - while positive motor angle increase treated as clockwise rotation, // incrementing absolute zero by positive value shifts absolute zero in counter-clockwise direction, // so we invert value here to have an expected behavior of API. // Also, we invert value here (and not in presetEncoder method) in order to keep message factories as close // to original documentation as possible. -offset, positionModeId ); return this.execute(message); } public rotateByDegree( portId: number, degree: number, options?: ServoCommandOptions ): Observable<PortCommandExecutionStatus> { const message = this.portOutputCommandOutboundMessageFactoryService.startSpeedForDegrees( portId, Math.abs(degree), Math.abs(options?.speed ?? MOTOR_LIMITS.maxSpeed) * Math.sign(degree), options?.power ?? MOTOR_LIMITS.maxPower, options?.endState ?? MotorServoEndState.brake, options?.useProfile ?? MotorUseProfile.dontUseProfiles, options?.bufferMode ?? this.config.defaultBufferMode, options?.noFeedback ? PortOperationCompletionInformation.noAction : PortOperationCompletionInformation.commandFeedback, ); return this.execute(message); } private execute( message: RawMessage<MessageType.portOutputCommand>, ): Observable<PortCommandExecutionStatus> { return this.messenger.sendPortOutputCommand(message); } }
# # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from Mandrake Linux Security Advisory MDKSA-2003:072. # The text itself is copyright (C) Mandriva S.A. # include("compat.inc"); if (description) { script_id(14055); script_version ("$Revision: 1.14 $"); script_cvs_date("$Date: 2013/05/31 23:47:34 $"); script_cve_id("CVE-2003-0251"); script_xref(name:"MDKSA", value:"2003:072"); script_name(english:"Mandrake Linux Security Advisory : ypserv (MDKSA-2003:072)"); script_summary(english:"Checks rpm output for the updated package"); script_set_attribute( attribute:"synopsis", value:"The remote Mandrake Linux host is missing a security update." ); script_set_attribute( attribute:"description", value: "A vulnerability was found in versions of ypserv prior to version 2.7. If a malicious client were to query ypserv via TCP and subsequently ignore the server's response, ypserv will block attempting to send the reply. The result is that ypserv will fail to respond to other client requests. ypserv 2.7 and above have been altered to fork a child for each client request, which prevents any one request from causing the server to block." ); script_set_attribute( attribute:"see_also", value:"http://www.linux-nis.org/nis/ypserv/ChangeLog" ); script_set_attribute( attribute:"solution", value:"Update the affected ypserv package." ); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:N/I:N/A:P"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:ypserv"); script_set_attribute(attribute:"cpe", value:"cpe:/o:mandrakesoft:mandrake_linux:8.2"); script_set_attribute(attribute:"cpe", value:"cpe:/o:mandrakesoft:mandrake_linux:9.0"); script_set_attribute(attribute:"patch_publication_date", value:"2003/06/27"); script_set_attribute(attribute:"plugin_publication_date", value:"2004/07/31"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2004-2013 Tenable Network Security, Inc."); script_family(english:"Mandriva Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/cpu", "Host/Mandrake/release", "Host/Mandrake/rpm-list"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("rpm.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); if (!get_kb_item("Host/Mandrake/release")) audit(AUDIT_OS_NOT, "Mandriva / Mandake Linux"); if (!get_kb_item("Host/Mandrake/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING); cpu = get_kb_item("Host/cpu"); if (isnull(cpu)) audit(AUDIT_UNKNOWN_ARCH); if (cpu !~ "^(amd64|i[3-6]86|x86_64)$") audit(AUDIT_LOCAL_CHECKS_NOT_IMPLEMENTED, "Mandriva / Mandrake Linux", cpu); flag = 0; if (rpm_check(release:"MDK8.2", cpu:"i386", reference:"ypserv-2.8-1.1mdk", yank:"mdk")) flag++; if (rpm_check(release:"MDK9.0", cpu:"i386", reference:"ypserv-2.8-1.1mdk", yank:"mdk")) flag++; if (flag) { if (report_verbosity > 0) security_warning(port:0, extra:rpm_report_get()); else security_warning(0); exit(0); } else audit(AUDIT_HOST_NOT, "affected");
//Build html elements document.body.innerHTML=`<div class="heading-container"> <h1>Dictionary</h1> </div> <div class="main-Container" id="mainContainer" </div>` mainContainer.innerHTML+= ` <div class="container-heading"> <h3>English Meaning</h3> </div> <div class="container"> <label for="name" =>Name</label> <input type="text" class="form-control" id="name" placeholder="Enter a word"> <button type="submit" class="btn btn-primary" onclick="getData()">Submit</button> <button class="btn btn-primary" onclick="history.go(0);">Reset</button> </div> ` //create a function to fetch data from API using async and await //Displaying error using try and catch const getData=async()=>{ try{ let name=document.getElementById("name").value; const data=await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${name}`); const nationalityDetails1=await data.json(); const meaning=JSON.stringify(nationalityDetails1); displayData(meaning); //calling function to display data }catch(error){ console.log(error); } } //create a function to display data const displayData=(obj)=>{ mainContainer.innerHTML+= `<div class="container" id="resultData"> <h2 id="name">Word: ${obj.word}</h2> <p> Meaning: ${obj.meanings.definitions.definition}</p> </div> ` } // [{ // "word":"hello", // "phonetics":[ // {"audio":"https://api.dictionaryapi.dev/media/pronunciations/en/hello-au.mp3", // "sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=75797336", // "license":{ // "name":"BY-SA 4.0", // "url":"https://creativecommons.org/licenses/by-sa/4.0" // } // }, // {"text":"/həˈləʊ/", // "audio":"https://api.dictionaryapi.dev/media/pronunciations/en/hello-uk.mp3", // "sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=9021983", // "license":{"name":"BY 3.0 US","url":"https://creativecommons.org/licenses/by/3.0/us"} // }, // {"text":"/həˈloʊ/","audio":""} // ], // "meanings":[ // {"partOfSpeech":"noun", // "definitions":[ // {"definition":"\"Hello!\" or an equivalent greeting.", // "synonyms":[], // "antonyms":[] // }], // "synonyms":["greeting"], // "antonyms":[] // }, // {"partOfSpeech":"verb","definitions":[{"definition":"To greet with \"hello\".","synonyms":[],"antonyms":[]}],"synonyms":[],"antonyms":[]},{"partOfSpeech":"interjection","definitions":[{"definition":"A greeting (salutation) said when meeting someone or acknowledging someone’s arrival or presence.","synonyms":[],"antonyms":[],"example":"Hello, everyone."},{"definition":"A greeting used when answering the telephone.","synonyms":[],"antonyms":[],"example":"Hello? How may I help you?"},{"definition":"A call for response if it is not clear if anyone is present or listening, or if a telephone conversation may have been disconnected.","synonyms":[],"antonyms":[],"example":"Hello? Is anyone there?"},{"definition":"Used sarcastically to imply that the person addressed or referred to has done something the speaker or writer considers to be foolish.","synonyms":[],"antonyms":[],"example":"You just tried to start your car with your cell phone. Hello?"},{"definition":"An expression of puzzlement or discovery.","synonyms":[],"antonyms":[],"example":"Hello! What’s going on here?"}],"synonyms":[],"antonyms":["bye","goodbye"]}],"license":{"name":"CC BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"},"sourceUrls":["https://en.wiktionary.org/wiki/hello"]}]
import Header from "./layout/Header"; import Home from "./pages/Home"; import { Routes, Route } from "react-router-dom"; import Login from "./pages/Login"; import ShoppingCart from "./pages/ShoppingCart"; import About from "./pages/About"; import Contact from "./pages/Contact"; import NotFound from "./pages/NotFound"; import Footer from "./layout/Footer"; import Product from "./pages/ProductDetails"; import Tab from "./pages/Tab"; import Category from "./pages/Category"; import SubCategory from "./pages/SubCategory"; import Deliveries from "./pages/Deliveries"; import TermsOfSales from "./pages/TermsOfSales"; import LegalNotice from "./pages/LegalNotice"; import Register from "./pages/Register"; import ForgotPassword from "./pages/ForgotPassword"; import AccountClient from "./pages/AccountClient"; import AdminDashboard from "./pages/AdminDashboard"; function App() { return ( <div className="App"> <Header /> <Routes> <Route path="/admin/dashboard" element={<AdminDashboard />} /> <Route path="/" element={<Home />} /> <Route path="/account" element={<AccountClient />} /> <Route path="/account/login" element={<Login />} /> <Route path="account/register" element={<Register />} /> <Route path="account/forgot-password" element={<ForgotPassword />} /> <Route path="/cart" element={<ShoppingCart />} /> <Route path="/menu-tab/:tab" element={<Tab />} /> <Route path="/menu-tab-category/:category" element={<Category />} /> <Route path="/menu-tab-subcategory/:subcategory" element={<SubCategory />} /> <Route path="/products/:id" element={<Product />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> <Route path="/deliveries&returns" element={<Deliveries />} /> <Route path="/terms-of-sales" element={<TermsOfSales />} /> <Route path="/legal-notice" element={<LegalNotice />} /> <Route path="/*" element={<NotFound />} /> </Routes> <Footer /> </div> ); } export default App;
import UIKit struct user: Codable { // Main data of this class. var name:String? var last_name:String var age:String // To handle if different names are in the JSON received. enum CodingKeys: String, CodingKey { case name case last_name = "apellido" case age } } let json_data = """ { "name": "Emmanuel", "apellido": "Perez", "age": "Veinte" } """ // Decode the data. let my_data = json_data.data(using: .utf8)! print(my_data) let my_user = try JSONDecoder().decode(user.self, from: my_data) print(my_user)
<script lang="ts"> import { onMount } from "svelte"; import jwt_decode from "jwt-decode"; import bs58 from "bs58"; import { walletStore } from "@svelte-on-solana/wallet-adapter-core"; import { WalletProvider } from "@svelte-on-solana/wallet-adapter-ui"; import { PhantomWalletAdapter, SolflareWalletAdapter, } from "@solana/wallet-adapter-wallets"; import { user } from "~/store"; import { i18n } from "~/lib/i18n"; import { nimbus } from "~/lib/network"; import { handleGetAccessToken } from "~/utils"; import { useQueryClient } from "@tanstack/svelte-query"; import AppOverlay from "~/components/Overlay.svelte"; import GoogleAuth from "~/components/GoogleAuth.svelte"; import SolanaAuth from "~/components/SolanaAuth.svelte"; import User from "~/assets/user.png"; const MultipleLang = { modal_login_title: i18n( "newtabPage.modal-login-title", "Login to enjoy more features" ), }; const signatureString = "Hello Nimbus"; const wallets = [new PhantomWalletAdapter(), new SolflareWalletAdapter()]; const queryClient = useQueryClient(); let isOpenAuthModal = false; let signMessageAddress = ""; let showPopover = false; let addressWallet = ""; onMount(() => { const token = localStorage.getItem("token"); const solanaToken = localStorage.getItem("solana_token"); if (token || solanaToken) { if (token) { const { access_token, id_token } = JSON.parse(token); fetch("https://www.googleapis.com/oauth2/v3/userinfo", { headers: { Authorization: `Bearer ${access_token}`, }, }) .then((response) => { if (response.ok) { // User is authenticated and access token is still valid user.update((n) => (n = jwt_decode(id_token))); } else { // Access token is invalid or expired, prompt user to sign in again user.update((n) => (n = {})); showPopover = false; localStorage.removeItem("token"); } }) .catch((error) => { console.error(error); }); } if (solanaToken) { user.update( (n) => (n = { picture: User, }) ); } } else { user.update((n) => (n = {})); showPopover = false; localStorage.removeItem("token"); localStorage.removeItem("solana_address"); localStorage.removeItem("solana_token"); addressWallet = ""; signMessageAddress = ""; $walletStore.disconnect(); } }); const handleGetGoogleUserInfo = async () => { const urlParams = new URLSearchParams(window.location.search); const code = urlParams.get("code"); if (code && APP_TYPE.TYPE !== "EXT") { const userData = await handleGetAccessToken(code); user.update((n) => (n = userData)); } }; const handleSignOut = () => { user.update((n) => (n = {})); showPopover = false; localStorage.removeItem("token"); localStorage.removeItem("solana_address"); localStorage.removeItem("solana_token"); addressWallet = ""; signMessageAddress = ""; $walletStore.disconnect(); queryClient.invalidateQueries(["list-address"]); queryClient.invalidateQueries(["users-me"]); }; $: { handleGetGoogleUserInfo(); } const handleSignAddressMessage = async () => { if ($walletStore.connected) { const res = await $walletStore?.signMessage( Uint8Array.from( Array.from(signatureString).map((letter) => letter.charCodeAt(0)) ) ); signMessageAddress = bs58.encode(res); } }; const handleGetSolanaToken = async (data) => { const res = await nimbus .post("/auth/solana", data) .then((response) => response); if (res.data.result) { localStorage.setItem("solana_token", res.data.result); user.update( (n) => (n = { picture: User, }) ); } }; $: addressWallet = $walletStore?.publicKey?.toBase58(); $: { if (addressWallet) { const solanaToken = localStorage.getItem("solana_token"); if (!solanaToken) { handleSignAddressMessage(); } } } $: { if (addressWallet && signMessageAddress) { const solanaLoginPayload = { message: signatureString, addressWallet, signMessageAddress, }; localStorage.setItem("solana_address", addressWallet); handleGetSolanaToken(solanaLoginPayload); } } $: { if ($user && Object.keys($user).length !== 0) { isOpenAuthModal = false; } } </script> {#if $user && Object.keys($user).length !== 0} <div class="relative"> <div class="w-[40px] h-[40px] rounded-full overflow-hidden cursor-pointer" on:click={() => (showPopover = !showPopover)} > <img src={$user.picture} alt="" class="object-cover w-full h-full" /> </div> {#if showPopover} <div class="bg-white py-2 px-3 text-sm rounded-lg absolute -bottom-17 left-1/2 transform -translate-x-1/2 flex flex-col gap-1 w-[80px] z-50" style="box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.15);" > <a class="text-gray-500 cursor-pointer" href="/entries/options/index.html?tab=nft" target="_blank" on:click={() => { showPopover = false; }} > My NFT </a> <div class="font-medium text-red-500 cursor-pointer" on:click={handleSignOut} > Log out </div> </div> {/if} </div> {:else} <div on:click={() => { isOpenAuthModal = true; }} class="text-sm font-semibold text-white cursor-pointer xl:text-base" > Connect Wallet </div> {/if} <WalletProvider localStorageKey="walletAdapter" {wallets} autoConnect /> <AppOverlay clickOutSideToClose isOpen={isOpenAuthModal} on:close={() => (isOpenAuthModal = false)} > <div class="xl:title-3 title-1 text-gray-600 font-semibold mb-5"> Connect wallet to enjoy more features </div> <div class="flex flex-col items-center justify-center xl:gap-2 gap-4"> <SolanaAuth /> <GoogleAuth /> </div> </AppOverlay> <style></style>
# [1378] Replace Employee ID With The Unique Identifier **[database]** ### Statement Table: `Employees` ``` +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | name | varchar | +---------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table contains the id and the name of an employee in a company. ``` Table: `EmployeeUNI` ``` +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | unique_id | int | +---------------+---------+ (id, unique_id) is the primary key (combination of columns with unique values) for this table. Each row of this table contains the id and the corresponding unique id of an employee in the company. ``` Write a solution to show the **unique ID** of each user, If a user does not have a unique ID replace just show `null`. Return the result table in **any** order. The result format is in the following example. **Example 1:** ``` **Input:** Employees table: +----+----------+ | id | name | +----+----------+ | 1 | Alice | | 7 | Bob | | 11 | Meir | | 90 | Winston | | 3 | Jonathan | +----+----------+ EmployeeUNI table: +----+-----------+ | id | unique_id | +----+-----------+ | 3 | 1 | | 11 | 2 | | 90 | 3 | +----+-----------+ **Output:** +-----------+----------+ | unique_id | name | +-----------+----------+ | null | Alice | | null | Bob | | 2 | Meir | | 3 | Winston | | 1 | Jonathan | +-----------+----------+ **Explanation:** Alice and Bob do not have a unique ID, We will show null instead. The unique ID of Meir is 2. The unique ID of Winston is 3. The unique ID of Jonathan is 1. ``` <br /> ### Hints None <br /> ### Solution ```py import pandas as pd def replace_employee_id(employees: pd.DataFrame, employee_uni: pd.DataFrame) -> pd.DataFrame: return employees.merge(employee_uni, "left", on="id")[["unique_id", "name"]] ``` <br /> ### Statistics - total accepted: 119514 - total submissions: 140234 - acceptance rate: 85.2% - likes: 534 - dislikes: 62 <br /> ### Similar Problems None
# ----- BUILD ENVIRONMENT ----- # import gym from gym import Env from gym.spaces import Discrete, Box import random import numpy as np import scipy.integrate as integrate from scipy.integrate import solve_ivp import pygame import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style import os import random from collections import deque, namedtuple import gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim HOURS = 16 SAMPLING_INTERVAL = 5 # min class insulin_env(Env): def __init__(self): # actions we can take, discrete dosing size 0-10 self.action_space = Discrete(10) # BGL level self.observation_space = Box(low=np.float32(40), high=np.float32(160)) # set insulin bounds self.target = 80 # target blood glucose level self.lower = 65 # below this level is dangerous self.upper = 105 # above this is dangerous # set start BGL self.state = [] self.state.append(80) # blood glucose self.state.append(30) # remote insulin level self.state.append(30) # insulin self.state.append(17) self.state.append(17) self.state.append(50) self.state.append(0) # time # set epoch length self.day_length = int(HOURS*60/SAMPLING_INTERVAL) # awake for 16 hours, 10 mins * 96 times = 16 hours # create a list of randomly generated meals #self.meals = [500*np.sin(i/300) + random.randint(-300,300) for i in range(int(HOURS*60/SAMPLING_INTERVAL))] self.meals = [900 + 200*(1 + np.sin(i/12)) + random.randint(-200,200) for i in range(int(HOURS*60/SAMPLING_INTERVAL))] pass def dynamics(self, t, y, ui, d): g = y[0] # blood glucose (mg/dL) x = y[1] # remote insulin (micro-u/ml) i = y[2] # insulin (micro-u/ml) q1 = y[3] q2 = y[4] g_gut = y[5] # gut blood glucose (mg/dl) # Parameters: gb = 291.0 # Basal Blood Glucose (mg/dL) p1 = 3.17e-2 # 1/min p2 = 1.23e-2 # 1/min si = 2.9e-2 # 1/min * (mL/micro-U) ke = 9.0e-2 # 1/min kabs = 1.2e-2 # 1/min kemp = 1.8e-1 # 1/min f = 8.00e-1 # L vi = 12.0 # L vg = 12.0 # L g = y[0] # blood glucose measurement (mg/dL) x = y[1] # remote insulin (micro-u/ml) i = y[2] # insulin (micro-u/ml) q1 = y[3] q2 = y[4] g_gut = y[5] # gut blood glucose (mg/dl) # Compute change in state: dydt = np.empty(6) dydt[0] = -p1*(g-gb) - si*x*g + f*kabs/vg * g_gut + f/vg * d dydt[1] = p2*(i-x) # remote insulin compartment dynamics dydt[2] = -ke*i + ui # insulin dynamics dydt[3] = ui - kemp * q1 dydt[4] = -kemp*(q2-q1) dydt[5] = kemp*q2 - kabs*g_gut # dydt[6] = placeholder for previous glucose measurements return 60*dydt def step(self, action): # intrease by 1 self.state[6] += 1 # check if day is over if self.day_length <= self.state[6]: done = True else: done = False time_step = np.array([0,5]) # assume measurements are taken every 5 min y0 = np.array(self.state[0:6]) meal = self.meals[self.state[6] % len(self.meals)] # solve the ivp to get new state x = solve_ivp(self.dynamics, time_step, y0, args = (action, meal)) # assign new state values self.state[0:6] = x.y[:,-1] # calculate reward if self.state[0] <= self.lower: reward = 0 if self.lower < self.state[0] < self.target: reward = (self.state[0] - self.lower) if self.target < self.state[0] < self.upper: reward = (self.upper - self.state[0]) if self.upper <= self.state[0]: reward = 0 # set placeholder for info info = {} # print("bgl: ", self.state[0]) # print("reward: ", reward) return self.state, reward, done def render(self, xs, ys): pass def reset(self): # reset state self.state[0] = 80 self.state[1] = 30 self.state[2] = 30 self.state[3] = 17 self.state[4] = 17 self.state[5] = 250 #self.state[6] = self.state[0] self.day_length = HOURS*60/SAMPLING_INTERVAL return self.state # ----- TEST ENVIRONMENT ----- # env = insulin_env() env.__init__() env = insulin_env() env.__init__() style.use('fivethirtyeight') fig = plt.figure() ax1 = fig.add_subplot(1,1,1) iters = env.day_length idx = list(range(iters)) bgl_memory = [] for i in range(iters): if env.state[0] < env.lower: env.step(0) if env.lower <= env.state[0] and env.state[0] <= env.target: env.step(1) if env.target <= env.state[0] and env.state[0] <= env.upper: env.step(5) if env.upper < env.state[0]: env.step(10) bgl_memory.append(env.state[0]) plt.subplot(1,2,1) plt.plot(idx, bgl_memory, label = "meals") plt.subplot(1,2,2) plt.plot(idx, env.meals) plt.show() ''' #import cv2 import gym import numpy as np #import torch #import torch.nn as nn #import torch.nn.functional as F #import torch.optim as optim ''' states = 1 actions = 11 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") NAME = "vanilla-update-every-4-steps" SAVE_FREQ = 25 ACTIONS = [list(range(10)) ] # --- building the DQN --- class DQN(nn.Module): def __init__( self, ninputs, noutputs, seed=None, ): super(DQN, self).__init__() if seed: self.seed = torch.manual_seed(seed) self.fc1 = nn.Linear(ninputs, 432) self.fc1 = nn.Linear(432, 216) self.fc3 = nn.Linear(216, noutputs) def forward(self, x): x = self.fc1(x) x = self.fx2(x) x = self.fc3(x) return x def predict(self, state): state = torch.from_numpy(state).float().unsqueeze(0).to(device) self.eval() with torch.no_grad(): pred = self.forward(state) return pred """Fixed-size buffer to store experience tuples.""" class ReplayBuffer: def __init__(self, action_size, buffer_size, batch_size, seed): self.action_size = action_size self.memory = deque(maxlen=buffer_size) self.batch_size = batch_size self.experience = namedtuple( "Experience", field_names=["state", "action", "reward", "next_state", "done"], ) self.seed = random.seed(seed) def add(self, state, action, reward, next_state, done): e = self.experience(state, action, reward, next_state, done) self.memory.append(e) def sample(self): experiences = random.sample(self.memory, k=self.batch_size) states = ( torch.from_numpy(np.array([e.state for e in experiences if e is not None])) .float() .to(device) ) actions = ( torch.from_numpy(np.array([e.action for e in experiences if e is not None])) .long() .to(device) ) rewards = ( torch.from_numpy(np.array([e.reward for e in experiences if e is not None])) .float() .to(device) ) next_states = ( torch.from_numpy( np.array([e.next_state for e in experiences if e is not None]) ) .float() .to(device) ) dones = ( torch.from_numpy(np.array([e.done for e in experiences if e is not None])) .float() .to(device) ) return (states, actions, rewards, next_states, dones) def __len__(self): return len(self.memory) class insulinAgent: def __init__( self, actions=ACTIONS, gamma=0.95, # discount rate epsilon=1.0, # random action rate epsilon_min=0.1, epsilon_decay=0.9999, learning_rate=0.001, tau=1e-3, # soft update discount update_main_network_freq=1, hard_update=False, dqn_loss="mse", act_interval=2, buffer_size=5000, batch_size=64, save_freq=25, seed=None, ): self.obs_shape = 2 self.actions = actions self.gamma = gamma self.epsilon = epsilon self.epsilon_min = epsilon_min self.epsilon_decay = epsilon_decay self.learning_rate = learning_rate self.tau = tau self.update_main_network_freq = update_main_network_freq self.hard_update = hard_update self.dqn_loss = dqn_loss self.seed = seed if seed is not None else np.random.randint(1000) random.seed(self.seed) np.random.seed(self.seed) self.dqn_behavior = DQN(3, len(self.actions), self.seed).to(device) self.dqn_target = DQN(3, len(self.actions), self.seed).to(device) self.optimizer = optim.Adam(self.dqn_behavior.parameters(), lr=learning_rate) self.buffer_size = buffer_size self.batch_size = batch_size self.memory = ReplayBuffer( action_size=len(self.actions), buffer_size=self.buffer_size, batch_size=self.batch_size, seed=seed, ) self.act_interval = act_interval self.save_freq = save_freq self.training_steps = 0 def act(self, state): # Epsilon-greedy action selection if np.random.rand() > self.epsilon: action_values = self.dqn_behavior.predict(state) aind = np.argmax(action_values.cpu().data.numpy()) else: aind = random.randrange(len(self.actions)) return self.actions[aind] def soft_update_target(self): """Soft update model parameters. θ_target = τ*θ_local + (1-τ)*θ_target """ for target_param, local_param in zip( self.dqn_target.parameters(), self.dqn_behavior.parameters() ): target_param.data.copy_( self.tau * local_param.data + (1.0 - self.tau) * target_param.data ) def learn(self): states, actions, rewards, next_states, dones = self.memory.sample() # get Q tables from both networks q_targets_next = self.dqn_target(next_states).detach().max(1)[0] q_targets = (rewards + self.gamma * q_targets_next * (1 - dones)).unsqueeze(1) q_preds = self.dqn_behavior(states) q_preds = q_preds.gather(1, actions.unsqueeze(1)) # fit behavior dqn self.dqn_behavior.train() self.optimizer.zero_grad() if self.dqn_loss == "mse": loss = F.mse_loss(q_preds, q_targets) elif self.dqn_loss == "huber": loss = F.huber_loss(q_preds, q_targets) loss.backward() self.training_steps += 1 # Frequency at which main network weights should be updated if self.training_steps % self.update_main_network_freq == 0: self.optimizer.step() if not self.hard_update: self.soft_update_target() else: self.hard_update_target() # decay epsilon if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay return loss.item() def load(self, fp): checkpoint = torch.load(fp) self.dqn_behavior.load_state_dict(checkpoint["model_state"]) self.dqn_target.load_state_dict(checkpoint["model_state"]) self.optimizer.load_state_dict(checkpoint["optimizer"]) def save(self, epoch, steps, reward, epsilon, loss): print(f"saving model to models/{NAME}-{epoch}.pth") fp = f"{NAME}-hist.csv" if not os.path.exists(fp): with open(fp, "w") as f: f.write(f"epoch,epsilon,steps,reward,loss\n") with open(fp, "a") as f: f.write(f"{epoch},{epsilon},{steps},{reward},{loss}\n") torch.save( { "model_state": self.dqn_target.state_dict(), "optimizer": self.optimizer.state_dict(), }, f"models/{NAME}-{epoch}.pth", ) def train(self, env: gym.Env, start_ep: int, end_ep: int, max_neg=25): print(f"Starting training from ep {start_ep} to {end_ep}...") for ep in range(start_ep, end_ep + 1): state = env.reset() total_reward = 0 n_rewards = 0 state_queue = deque([state] * 3, maxlen=3) # queue 3 states t = 1 done = False while True: state_stack = np.array(state_queue) action = self.act(state_stack) reward = 0 for _ in range(self.act_interval + 1): next_state, r, done = env.step(action) reward += r if done: break # end episode if continually getting negative reward n_rewards = n_rewards + 1 if t > 100 and reward < 0 else 0 total_reward += reward next_state = process_state(next_state) # type: ignore state_queue.append(next_state) next_state_stack = np.array(state_queue) self.memory.add( state_stack, self.actions.index(action), reward, next_state_stack, done, ) if done or n_rewards >= max_neg or total_reward < 0: print( f"episode: {ep}/{end_ep}, length: {t}, total reward: {total_reward:.2f}, epsilon: {self.epsilon:.2f}" ) break if len(self.memory) > self.batch_size: loss = self.learn() t += 1 if ep % self.save_freq == 0: self.save(ep, t, total_reward, epsilon, loss) def get_args(): import argparse parser = argparse.ArgumentParser() parser.add_argument( "-m", "--model", help="Path to partially trained model (hd5)", ) parser.add_argument( "-s", "--start", type=int, default=1, help="starting episode (to continue training from)", ) parser.add_argument("-x", "--end", type=int, default=1000, help="ending episode") parser.add_argument( "-e", "--epsilon", type=float, default=1.0, help="Starting epsilon (default: 1)", ) args = parser.parse_args() if args.model: print("loading a model, make sure start and epsilon are set correctly") return args.model, args.start, args.end, args.epsilon if __name__ == "__main__": model_path, start, end, epsilon = get_args() env = insulin_env() env.__init__() agent = insulinAgent( actions=ACTIONS, gamma=0.95, # discount rate epsilon=epsilon, # random action rate epsilon_min=0.1, epsilon_decay=0.9999, learning_rate=0.001, tau=1e-3, # soft update discount update_main_network_freq=1, hard_update=False, dqn_loss="mse", act_interval=2, buffer_size=5000, batch_size=64, save_freq=SAVE_FREQ, seed=420, ) if model_path: agent.load(model_path) # agent.train(env, start, end) env.close() '''
```js <!--  * @Date: 2023-05-18 14:36:40  * @LastEditors: zhoule  * @LastEditTime: 2023-05-18 16:14:46  * @Description: 公共表格  * --> <template>     <div>         <el-table             class="my-table"             v-loading="loading"             ref="table"             :data="tempData"             :header-cell-style="headerCellStyle"             :cell-style="cellStyle"             v-bind="$attrs"             v-on="$listeners"         >             <template slot="append">                 <slot name="append"></slot>             </template>             <component :is="TableColumn" :columns="columns">                 <template v-for="(index, name) in $slots" :slot="name">                     <slot :name="name"></slot>                 </template>                 <template v-for="(index, name) in $scopedSlots" v-slot:[name]="data">                     <slot :name="name" v-bind="data"></slot>                 </template>             </component>         </el-table>         <el-pagination             class="pagination"             v-bind="tempPagination"             :current-page="currentPage"             :page-size="pageSize"             :total="total"             @size-change="handleSizeChange"             @current-change="handleCurrentChange"         ></el-pagination>     </div> </template> <script> /**  * slot="header-xxx",可配置表头插槽,xxx表示columns属性名  * slot="xxx",可设置表格内容自定义插入  * 示例   columns:[   {         prop: 'selection',         type: 'selection',         width: 80     },{         prop: 'date',         label: 'xxx',         width: 180,         sortable: true,         children: [{}]     }]     //分页器     pagination:{         pageSizes: [2,5],         currentPage:10     }  */ import TableColumn from './table-column.vue' const defaultPagination = {background: true, layout: 'total, sizes, prev, pager, next, jumper'} export default {     name: 'BaseTable',     props: {         columns: {             type: Array,             default: () => ([])         },         pagination: {             type: Object,             default: () => ({})         },         data: {             type: Array,             default: () => []         },         // 表头单元格样式         headerCellStyle: {             type: Function || Object,             default: () => {                 return {                     'background-color': '#f5f6f7',                     'font-size': '12px',                     'padding': '10px',                 }             }         },         // 单元格样式         cellStyle: {             type: Function || Object,             default: () => {                 return {                     'font-size': '12px',                     'padding': '10px'                 }             }         },     },     data() {         return {             loading: false,             currentPage: 1,             pageSize: 10,             tempData: [],             TableColumn: TableColumn,         }     },     computed: {         paging() {             const offset = (this.currentPage - 1) * this.pageSize             return { offset, limit: this.pageSize }         },         total() {             return this.data?.length || 0         },         tempPagination() {             return {...defaultPagination, ...this.pagination}         }     },     watch: {         pagination: {             handler(nVal) {                 this.currentPage = nVal.currentPage || 1                 this.pageSize = nVal.pageSize || nVal.pageSizes?.[0] || 10             },             immediate: true,             deep: true,         },         paging: {             handler() {                 this.getTableData()             },             immediate: true,             deep: true,         }     },     mounted() {         const tempStore = this.$refs?.table || {}         for(const key in tempStore) {             if(typeof tempStore[key] === 'function') {                 this[key] = tempStore[key]             }         }     },     methods: {         handleSizeChange(val) {             this.pageSize = val;             this.getTableData();         },         handleCurrentChange(val) {             this.currentPage = val;             this.getTableData();         },         getTableData() {             const { offset, limit } = this.paging || {}         this.loading = true             setTimeout(() => {                 this.tempData = this.data.filter((v, i) => i >= offset && i < (offset + limit))                 this.loading = false             }, 1000);         },     } } </script> <style scoped lang="scss"> .pagination {     display: flex;     padding: 10px 0;     ::v-deep button.btn-prev {         margin-left:auto     } } .my-table ::v-deep .is-group tr:nth-child(odd) {     display: none; } </style> ``` //TableColumn ```js <!--  * @Date: 2023-05-18 14:52:03  * @LastEditors: zhoule  * @LastEditTime: 2023-05-18 15:35:05  * @Description: 表格列配置 --> <template>     <el-table-column class="my-column">         <template v-for="item in columns">             <el-table-column v-if="item.children && item.children.length" :label="item.label" :key="item.prop">                 <table-column                     :columns="item.children || []"                 >                     <template v-for="(index, name) in $slots" :slot="name">                         <slot :name="name"></slot>                     </template>                     <template v-for="(index, name) in $scopedSlots" v-slot:[name]="data">                         <slot :name="name" v-bind="data"></slot>                     </template>                 </table-column>             </el-table-column>             <el-table-column                 v-else-if="['selection', 'index'].includes(item.prop)"                 :key="`${item.prop}-if`"                 v-bind="item"             >                 <template v-slot:header="scope">                     <slot :name="`header-${item.prop}`" v-bind="scope"></slot>                 </template>             </el-table-column>             <el-table-column                 v-else                 :key="`${item.prop}-else`"                 v-bind="item"             >                 <template v-slot:header="scope">                     <span v-if="$scopedSlots[`header-${item.prop}`]">                         <slot :name="`header-${item.prop}`" v-bind="scope"></slot>                     </span>                     <span v-else>{{scope.column.label}}</span>                 </template>                 <template slot-scope="scope">                     <span v-if="$scopedSlots[item.prop]">                         <slot :name="item.prop" v-bind="scope"></slot>                     </span>                     <span v-else>{{scope.row[item.prop]}}</span>                 </template>             </el-table-column>         </template>     </el-table-column> </template> <script> export default {     name: 'TableColumn',     props: {         columns: {             type: Array,             default: () => ([])         }     }, } </script> <style scoped lang="scss"> </style> ```
//const winston = require("winston"); const DailyRotateFile = require('winston-daily-rotate-file'); import * as path from "path"; import * as winston from "winston" import { Logger } from "winston"; export class LogManager { private static instance: LogManager; private logger: Logger; static getInstance() { if (!LogManager.instance) { LogManager.instance = new LogManager(); // ... any one time initialization goes here ... } return LogManager.instance; } private constructor() { this.logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ // // - Write to all logs with level `info` and below to `combined.log` // - Write all logs error (and below) to `error.log`. // new winston.transports.Console({ format: winston.format.simple() }), new DailyRotateFile({ filename: path.join(__dirname, "../logs", 'log-%DATE%.log'), datePattern: 'YYYY-MM-DD-HH', zippedArchive: false, maxSize: '20m', maxFiles: '14d', }), new winston.transports.File({ filename: path.join(__dirname, "../logs", 'error.log'), level: 'error' }), new winston.transports.File({ filename: path.join(__dirname, "../logs",'combined.log') }) ] }); } public get log():Logger { return this.logger; } } export default LogManager.getInstance().log; // do something with the instance...
/** * JSON : 클라이언트와 서버 간 HTTP 통신을 위한 텍스트 데이터 포맷 방식 * Javascript에 종속되지 않는 독립적인 데이터 포맷 * 대부분의 프로그래밍 언어에서 사용 가능 */ // JSON 작성방식: Javascript의 객체 작성 방식과 유사 //Javascript Object const book = { title: "노인과 바다", author: "해밍웨이", isSold: false, genre: ["소설", "비극"], }; //JSON 문법 : key 값(property)도 ""로 작성 ('는 사용불가) // { // "title": "노인과 바다", // "author": "해밍웨이", // "isSold": false, // "genre": ["소설", "비극"], // } const jsonData = JSON.stringify (book); console.log(typeof jsonData); console.log(jsonData); console.log(book); console.log(jsonData.title); //문자열 타입이기때문에 프로퍼티 참조 불가 console.log(book.title); //객체이기 때문에 프로퍼티 값을 참조 가능 /** * JSON.stringfy()는 client측에서 서버로 데이터(일반적으로 객체)를 전송하기 위해 객체를 문자열화해야함 * 문자열화 = 직렬화 (serialization) */ const books = [ {id: 1, title: '여름', author: '이디스 워튼', isSold: true}, {id: 1, title: '오만과 편견', author: '제인 오스틴', isSold: true}, {id: 1, title: '동급생', author: '프레드 울만', isSold: false}, ]; //배열을 JSON 포맷의 문자열로 변환 const jsonBookdata = JSON.stringify(books); console.log(books); console.log(jsonBookdata); console.log(typeof jsonBookdata);
import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import NextLessonButton from '@/components/pages/lessons/NextLessonButton'; describe('NextLessonButton component', () => { test('display the next lesson button', () => { const handleClickNextLessonButton = jest.fn(); render( <NextLessonButton handleClickNextLessonButton={handleClickNextLessonButton} /> ); const nextLessonButton = screen.getByRole('button', { name: '次のレッスン', }); expect(nextLessonButton).toBeInTheDocument(); }); test('event handler is called when the next lesson button is clicked', async () => { const handleClickNextLessonButton = jest.fn(); render( <NextLessonButton handleClickNextLessonButton={handleClickNextLessonButton} /> ); const user = userEvent.setup(); await user.click(screen.getByRole('button', { name: '次のレッスン' })); expect(handleClickNextLessonButton).toHaveBeenCalledTimes(1); }); });
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LoginComponent } from './login/login.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ReactiveFormsModule } from '@angular/forms'; import { MatIconModule } from '@angular/material/icon' import { FormsModule } from '@angular/forms'; import { MatCardModule } from '@angular/material/card'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatButtonModule } from '@angular/material/button'; import { MatTableModule } from '@angular/material/table'; import { MatDialogModule } from '@angular/material/dialog'; import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; import { AuthService } from './Shared/Services/auth.service'; import { AuthGuard } from './Shared/Guards/auth-guard.service'; import { JwtHelperService, JwtModule } from '@auth0/angular-jwt'; import { CustomersListComponent } from './customers-list/customers-list.component'; import { CustomerViewComponent } from './customer-view/customer-view.component'; import { CustomerSubmitComponent } from './customer-submit/customer-submit.component'; import { TokenInterceptor } from './Shared/Interceptors/token.interceptor'; import { InitialAccountAddComponent } from './initial-account-add/initial-account-add.component'; @NgModule({ declarations: [ AppComponent, LoginComponent, CustomersListComponent, CustomerViewComponent, CustomerSubmitComponent, InitialAccountAddComponent ], imports: [ BrowserModule, MatDialogModule, AppRoutingModule, BrowserAnimationsModule, FormsModule, MatCardModule, MatFormFieldModule, MatInputModule, MatButtonModule, ReactiveFormsModule, MatTableModule, MatIconModule, HttpClientModule, JwtModule.forRoot({ // Add JwtModule configuration here config: { tokenGetter: () => { return localStorage.getItem('auth_token'); }, allowedDomains: ['http://localhost:4200'], // Replace with your domain or '*' for all domains disallowedRoutes: ['http://localhost:4200/login'] // Replace with your login route } }), ], providers: [ AuthService, AuthGuard, { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true, } ], bootstrap: [AppComponent] }) export class AppModule { }
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter_test/flutter_test.dart'; import 'package:lab_2/dart/functions.dart'; void main() { test('first and last name', () { var result = fullName("Khaled", "Alhendi"); expect(result, "Khaled Alhendi"); }); test('empty first name', () { var result = fullName("", "Alhendi"); expect(result, " Alhendi"); }); test('empty last name', () { var result = fullName("Khaled", ""); expect(result, "Khaled "); }); }
package ex03_date_time; public class Ex01_System { //UUID처럼 난수 겹치지 않는 수를 이용할려고 배우는거 같음 public static void ex01() { /* 타임스탬프 1. 현재 시간을 long 타입의 정수 값으로 가지고 있는 값을 의미한다. 2. 1970년 01월 01일 0시 1/1000초마다 1씩 증가하고 있는 값이다. 3. 두가지의 순간을 찍어 차잇값으로 걸린시간을 알수있다. */ long timestamp = System.currentTimeMillis(); System.out.println(timestamp); } public static void ex02() { /* 시간 단위 second >㎳ >㎲ >㎱ >㎰ 밀리초 마이크로초 나노초 피코초 */ // String의 + 연산과 StringBuilder의 append 메소드 성능 확인하기 String str = ""; StringBuilder sb = new StringBuilder(); //시작시간 long nanoTime1 = System.nanoTime(); //작업수행 for(char ch = 'A'; ch <= 'z'; ch++) { //str += ch; sb.append(ch); } //종료시간 long nanoTime2 = System.nanoTime(); //결과확인 System.out.println("작업수행시간 : " + (nanoTime2 - nanoTime1) + "ns"); } public static void main(String[] args) { ex02(); } }
import { Component, OnInit, Input, OnChanges } from '@angular/core'; import { Book } from 'src/app/book'; import { BookService } from 'src/app/book.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-list-of-books', templateUrl: './list-of-books.component.html', styleUrls: ['./list-of-books.component.scss'] }) export class ListOfBooksComponent implements OnInit { constructor(private bookService: BookService, private router: Router) { } selectedSort:string = ''; selectChangeHandler (event: any) { //update the ui this.selectedSort = event.target.value; if (this.selectedSort == "asc-title") { this.sortAscendingTitle(); } if (this.selectedSort == "desc-title") { this.sortDescendingTitle(); } if (this.selectedSort == "asc-description") { this.sortAscendingDescription(); } if (this.selectedSort == "desc-description") { this.sortDescendingDescription(); } if (this.selectedSort == "asc-authorName") { this.sortAscendingAuthorName(); } if (this.selectedSort == "desc-authorName") { this.sortDescendingAuthorName(); } if (this.selectedSort == "asc-publishedDate") { this.sortAscendingDate(); } if (this.selectedSort == "desc-publishedDate") { this.sortDescendingDate(); } } public books: Book [] = []; //title:string; //description:string; ngOnInit(): void { this.getBooks(); } getBooks(): void { this.bookService.getBooks() .subscribe(books => this.books = books); } remove(id): void{ this.bookService.removeBook(id); } gotoAddBook(): void{ this.router.navigateByUrl('add-book'); } gotoHome(): void{ this.router.navigateByUrl('dashboard'); } goToSearch(): void{ this.router.navigateByUrl('search'); } gotoEditBook(book): void{ //this.editBook.editBook(id); this.bookService.getId(book.id); this.bookService.getDetailes(book.title, book.description, book.authorName, book.publishedDate); this.router.navigateByUrl('edit-book'); } sortAscendingTitle() : void{ this.books.sort((a,b)=>a.title.localeCompare(b.title)); } sortDescendingTitle(): void{ this.books.sort((a,b)=>b.title.localeCompare(a.title)); } sortAscendingDescription() : void{ this.books.sort((a,b)=>a.description.localeCompare(b.description)); } sortDescendingDescription(): void{ this.books.sort((a,b)=>b.description.localeCompare(a.description)); } sortAscendingAuthorName() : void{ this.books.sort((a,b)=>a.authorName.localeCompare(b.authorName)); } sortDescendingAuthorName(): void{ this.books.sort((a,b)=>b.authorName.localeCompare(a.authorName)); } sortAscendingDate() : void{ this.books.sort((a,b)=> { return <any>new Date(a.publishedDate)-<any>new Date(b.publishedDate) }); } sortDescendingDate(): void{ this.books.sort((a,b)=> { return <any>new Date(b.publishedDate)-<any>new Date(a.publishedDate) }); } }
export type WeatherType = | 'thunderstorm' | 'drizzle' | 'rain' | 'snow' | 'atmosphere' | 'clear' | 'clouds'; export type Forecast = { city: string; periods: ForecastPeriod[]; sunrise: string; sunset: string; timestamp: string; }; export type ForecastPeriod = { atmosphere: { humidity: number; pressure: number; visibility: number; }; rain: { precipitation?: number; volume?: number; }; temp: { feelsLike: number; max?: number; min?: number; value: number; }; weather: { description: string; type: WeatherType; }; wind: { direction: number; gust: number; speed: number; }; timestamp: string; }; export type LocationCoord = { lat: number; long: number; };
package com.davidrl.sap.service.customer.store; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import com.davidrl.sap.dto.dtos.StoreDto; import com.davidrl.sap.entity.entities.Store; import com.davidrl.sap.entity.repositories.StoreRepository; import com.davidrl.sap.mapper.mappers.StoreMapperImpl; import com.davidrl.sap.test.dto.StoreDtoParameterResolver; import com.davidrl.sap.test.entity.StoreParameterResolver; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @ExtendWith({StoreParameterResolver.class, StoreDtoParameterResolver.class}) class StoreServiceTest { @InjectMocks StoreService storeService; @Mock StoreRepository storeRepository; @Mock StoreMapperImpl storeMapper; @BeforeEach void setUp(StoreDto storeDto) { MockitoAnnotations.initMocks(this); when(storeMapper.toDto(any())).thenReturn(storeDto); } @Test void getStores_storeFound_returnsStoreDtoList(Store store) { // given when(storeRepository.findAll()).thenReturn(Arrays.asList(store)); // when List<StoreDto> storeDtos = storeService.getStores(); // then assertFalse(storeDtos.isEmpty()); } }
use axum::extract::State; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::{infra::{axum::{AppJsonRequest, AppJsonResponse}, errors::AppError}, state::AppState}; use super::{domain::{BiometricDtoRequest, BiometricDtoResponse, Biometrics, BiometricsStatus}, validators::Validator}; #[derive(Serialize, Deserialize)] pub struct BiometricUpdateDtoRequest { pub customer_id: Uuid, pub image_path: String, pub status: BiometricsStatus, } pub struct UpdateUseCase; impl UpdateUseCase { pub async fn update( State(app_state): State<AppState>, AppJsonRequest(request): AppJsonRequest<BiometricUpdateDtoRequest> ) -> Result<AppJsonResponse<BiometricDtoResponse>, AppError> { Validator::customer_id_and_image_not_empty(&BiometricDtoRequest { customer_id: request.customer_id, image_path: request.image_path.clone() })?; let mut transaction = app_state.begin_transaction().await?; let mut biometric = Biometrics::get_by(&mut transaction, request.customer_id).await?; biometric.image_path = request.image_path; biometric.status = request.status; biometric = Biometrics::update(&mut transaction, biometric).await?; app_state.commit_transaction(transaction).await?; Ok(AppJsonResponse::new(BiometricDtoResponse::from(biometric))) } }
#include<iostream> #include<set> using namespace std; class Edge { public: int src; int dest; int weight; Edge(int u, int v, int w) { src = u; dest = v; weight = w; } bool operator< (const Edge & rhs) const { return this->weight < rhs.weight; } }; int findParent(int v, int* parent) { if(parent[v] == v) return v; return findParent(parent[v], parent); } void kruskal() { int n; cout << "Enter number of vertices: "; cin >> n; set<Edge> edges; int m; cout << "Enter number of edges: "; cin >> m; int u, v, w; for(int i=0; i<m; i++) { cin >> u >> v >> w; edges.insert(Edge(u, v, w)); edges.insert(Edge(v, u, w)); } int* parent = new int[n]; for(int i=0; i<n; i++) parent[i] = i; vector<Edge> MST; for(auto e : edges) { int srcParent = findParent(e.src, parent); int destParent = findParent(e.dest, parent); if(srcParent != destParent) { MST.push_back(e); parent[srcParent] = destParent; } } int x = n - MST.size(); vector<Edge> MSTs[x]; vector<Edge> temp; for (int i = 0; i < x; i++) { int p = findParent((*MST.begin()).src, parent); MSTs[i].push_back((*MST.begin())); MST.erase(MST.begin()); for (auto e : MST) { if (p == findParent(e.src, parent)) MSTs[i].push_back(e); else temp.push_back(e); } MST.clear(); MST = temp; temp.clear(); } if(x > 1) { cout << "Graph is disconnected! " << endl; cout << "Possible Minimum spanning trees are :- " << endl; } for(int i=0; i<x; i++) { cout << "MST " << i+1 << endl; cout << "Edges\t" << "Weight" << endl; for(auto e: MSTs[i]) { if(e.src < e.dest) cout << e.src << ' ' << e.dest << '\t' << e.weight << endl; else cout << e.dest << ' ' << e.src << '\t' << e.weight << endl; } } } int main() { kruskal(); }
import { useState } from "react"; // redux import { useDispatch, useSelector } from "react-redux"; // import { nanoid } from "@reduxjs/toolkit" import { todoAdded } from "./todosSlice" import {selectAllUsers} from '../users/usersSlice' const AddTodoForm = () => { const dispatch = useDispatch() // temporary state const [title, setTitle] = useState('') const [content, setContent] = useState('') const [userId, setUserId] = useState('') const users = useSelector(selectAllUsers) // one line function .. const onTitleChanged = e => setTitle(e.target.value) const onContentChanged = e => setContent(e.target.value) const onAuthorChanged = e => setUserId(e.target.value) // if canSave is true .. const canSave = Boolean(title) && Boolean(content) && Boolean(userId) // global states const onSaveTodoClicked = () => { if (title && content) { dispatch( todoAdded(title, content, userId) ) setTitle('') setContent('') } } const userOptions = users.map(user => ( <option key={user.id} value={user.id}> {user.name} </option> )) return ( <section> <h2>Add a new Todo</h2> <form> <label htmlFor="todoTitle">Todo Title:</label> <input type="text" name="todoTitle" value={title} onChange={onTitleChanged} /> <label htmlFor="postAuthor">Author:</label> <select id="postAuthor" value={userId} onChange={onAuthorChanged}> <option value=""></option> {userOptions} </select> <label htmlFor="todoContent">Content:</label> <textarea name="todoContent" value={content} onChange={onContentChanged} /> <button type="button" onClick={onSaveTodoClicked} disabled={!canSave}>send</button> </form> </section> ) } export default AddTodoForm
# server-status-app ## Rodando o projeto ### Usando Maven + Spring Boot action Rodar o projeto ```shell mvn spring-boot:run ``` [Acesse](http://localhost:8080/) Parar o projeto ```shell mvn spring-boot:stop ``` ### Usando Maven + Jar Gerar o arquivo jar ```shell mvn clean install ``` Executar o projeto ```shell java -jar target/server-status.jar ``` [Acesse](http://localhost:8080/) ### Usando Docker ```shell docker run --name server_status_docker -p 8080:8080 andrefelix/server-status:V2 ``` [Acesse](http://localhost:8080/) ### Usando Docker-compose ```shell docker-compose -f docker/docker-compose.yaml up ``` [Acesse](http://localhost:8080/) ```shell docker-compose -f docker/docker-compose.yaml down ``` ## Deploy no ElasticBeanstalk 1. Instalar o Beanstalk command line https://docs.aws.amazon.com/pt_br/elasticbeanstalk/latest/dg/eb-cli3.html 1. Configurar a aplicação. Será criado um arquivo: ```.elasticbeanstalk/config.yml``` ``` eb init ``` 1. Adicione esta linhas ao seu arquivo .elasticbeanstalk/config.yml ``` deploy: artifact: target/server-status.jar ``` 1. Criar o ambiente. ``` eb create ``` 1. Definir a variável de ambiente para acesso à aplicação. ```eb setenv SERVER_PORT=5000``` 1. Fazer o deploy ```eb deploy``` 1. Verificar o status do deploy ```eb status``` 1. Abrir a aplicação. ```eb open``` 1. Criar mais de uma instância. ```eb scale 2``` 1. Terminar todas as instâncias. Adicione (--force) para evitar a confirmação. ```eb terminate --all``` ## Gerando a image Docker do projeto ### Criar a imagem localmente `docker build -t andrefelix/server-status:v5 .` ### Enviar a imagem para o DockerHub `docker push andrefelix/server-status:v5`
package com.example.kaisebhiadmin.ui.report import android.os.Bundle import android.util.Log import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.example.kaisebhiadmin.R import com.example.kaisebhiadmin.adapters.ReportAnsAdapter import com.example.kaisebhiadmin.data.MainRepository import com.example.kaisebhiadmin.databinding.ActivityReportBinding import com.example.kaisebhiadmin.utils.AppCustom import com.example.kaisebhiadmin.utils.ResponseError import com.example.kaisebhiadmin.utils.Success import com.example.kaisebhiadmin.utils.Utility import kotlinx.coroutines.launch class ReportActivity : AppCompatActivity() { private lateinit var binding: ActivityReportBinding private lateinit var viewModel: ReportViewModel private lateinit var reportAdapter: ReportAnsAdapter private val TAG: String = "ReportActivity.kt" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this@ReportActivity, R.layout.activity_report) viewModel = ViewModelProvider( this@ReportActivity, ReportViewModelFactory(MainRepository((application as AppCustom).firebaseApiClass)) )[ReportViewModel::class.java] binding.model = viewModel binding.toolbar.setNavigationOnClickListener { onBackPressed() } // throw RuntimeException("test") binding.reportAnsList.layoutManager = LinearLayoutManager(this@ReportActivity) reportAdapter = ReportAnsAdapter(this) binding.reportAnsList.adapter = reportAdapter getData() setListeners() setObservers() } private fun getData() { binding.shimmer.startShimmerAnimation() binding.shimmer.visibility = View.VISIBLE binding.reportAnsList.visibility = View.GONE lifecycleScope.launch { viewModel.getReportedAnswers().observe(this@ReportActivity) { it?.let { reportAdapter.submitData(lifecycle, it) binding.shimmer.stopShimmerAnimation() binding.shimmer.visibility = View.GONE binding.reportAnsList.visibility = View.VISIBLE } } } binding.swiperef.isRefreshing = false } private fun setListeners() { binding.swiperef.setOnRefreshListener { getData() } } private fun setObservers() { // viewModel.reportAnsLiveData.observe(this@ReportActivity) { // if(it is Success<*>) { // reportAdapter = ReportAnsAdapter(this, it.response as ArrayList<ReportedModel>, layoutInflater) // val layoutManager = LinearLayoutManager(this@ReportActivity) // binding.reportAnsList.layoutManager = layoutManager // binding.reportAnsList.adapter = reportAdapter // binding.shimmer.stopShimmerAnimation() // binding.shimmer.visibility = View.GONE // binding.reportAnsList.visibility = View.VISIBLE // Log.d(TAG, "setObservers: " + (it as Success<*>).response) // } else if(it is ResponseError){ // Toast.makeText(this, it.msg, Toast.LENGTH_SHORT).show() // } // binding.swiperef.isRefreshing = false // } viewModel.deleteAnsLiveData.observe(this@ReportActivity, Observer { if (it is Success<*>) { getData() binding.shimmer.stopShimmerAnimation() binding.shimmer.visibility = View.GONE binding.reportAnsList.visibility = View.VISIBLE Utility.showSnackBar(binding.root, it.response.toString()) Log.d(TAG, "setObservers: ${it.response}") } else if (it is ResponseError) { Toast.makeText(this, it.msg, Toast.LENGTH_SHORT).show() } }) } fun deleteAnswer(docId: String) { viewModel.deleteAnswer(docId) } override fun onBackPressed() { super.onBackPressed() } }
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; export function passwordValidator(): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { const validPassword = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/.test( control.value ); const errorMessages: string[] = []; const errorCases = [ { regex: new RegExp(/\d/), message: 'Should have at least one number', }, { regex: new RegExp(/[A-Za-z]/), message: 'Should have at least one letter', }, { regex: new RegExp(/[@$!%*#?&]/), message: 'Should have at least one special character', }, ]; if (!validPassword) { errorCases.forEach((c) => { if (!c.regex.test(control.value)) { errorMessages.push(c.message); } }); } return !validPassword ? { errors: errorMessages } : null; }; }