text
stringlengths
184
4.48M
(ns swarmpit.component.service.form-labels (:require [material.component :as comp] [material.component.form :as form] [material.component.list-table-form :as list] [swarmpit.component.state :as state] [swarmpit.component.handler :as handler] [swarmpit.routes :as routes] [rum.core :as rum])) (enable-console-print!) (def cursor [:form :labels]) (def headers [{:name "Name" :width "35%"} {:name "Value" :width "35%"}]) (defonce label-names (atom [])) (defn labels-handler [] (handler/get (routes/path-for-backend :labels-service) {:on-success (fn [response] (reset! label-names response))})) (defn- form-name [value index label-names] (comp/autocomplete {:name (str "form-name-text-" index) :key (str "form-name-text-" index) :value value :onUpdateInput #(state/update-item index :name % cursor) :fullWidth true :searchText value :dataSource label-names})) (defn- form-value [value index] (list/textfield {:name (str "form-value-text-" index) :key (str "form-value-text-" index) :value value :onChange (fn [_ v] (state/update-item index :value v cursor))})) (defn- render-labels [item index data] (let [{:keys [name value]} item] [(form-name name index data) (form-value value index)])) (defn- form-table [labels label-names] (list/table headers labels label-names render-labels (fn [index] (state/remove-item index cursor)))) (defn- add-item [] (state/add-item {:name "" :value ""} cursor)) (rum/defc form < rum/reactive [] (let [labels (state/react cursor)] (if (empty? labels) (form/value "No labels defined for the service.") (form-table labels (rum/react label-names)))))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./assets/css/bootstrap.min.css"> <link rel="stylesheet" href="./assets/css/style.css"> <title>Document</title> </head> <body> <header> <section id="nav-area"> <div class="container"> <nav class="navbar navbar-expand-lg"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled">Disabled</a> </li> </ul> <form class="d-flex" role="search"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> </div> </section> </header> <main> <section id="slide"> <div class="container"> <div class="row"> <div class="col-8"> <div class="left-side"> <img src="./assets/images/main.jpg" alt=""> </div> </div> <div class="col-4"> <div class="right-side"> <h5>Lates from the galery</h5> <div class="row" style="row-gap:28px;"> <div class="col-4"> <div class="box-img"> <img src="./assets/images/4.jpg" alt=""> </div> </div> <div class="col-4"> <div class="box-img"> <img src="./assets/images/5.jpg" alt=""> </div> </div> <div class="col-4"> <div class="box-img"> <img src="./assets/images/6.jpg" alt=""> </div> </div> <div class="col-4"> <div class="box-img"> <img src="./assets/images/7.jpg" alt=""> </div> </div> <div class="col-4"> <div class="box-img"> <img src="./assets/images/8.jpg" alt=""> </div> </div> <div class="col-4"> <div class="box-img"> <img src="./assets/images/7.jpg" alt=""> </div> </div> </div> </div> </div> </div> </div> </section> <section id="works"> <div class="container"> <h5>Our bes work</h5> <div class="row" style="row-gap:26px;"> <div class="col-4"> <div class="box-img"> <img src="./assets/images/4.jpg" alt=""> </div> </div> <div class="col-4"> <div class="box-img"> <img src="./assets/images/5.jpg" alt=""> </div> </div> <div class="col-4"> <div class="box-img"> <img src="./assets/images/6.jpg" alt=""> </div> </div> <div class="col-4"> <div class="box-img"> <img src="./assets/images/7.jpg" alt=""> </div> </div> <div class="col-4"> <div class="box-img"> <img src="./assets/images/8.jpg" alt=""> </div> </div> <div class="col-4"> <div class="box-img"> <img src="./assets/images/7.jpg" alt=""> </div> </div> </div> </div> </section> <section id="test"> <div class="box d-flex justify-content-between align-items-center"> <div class="item item1"></div> <div class="item item2"></div> </div> </section> </main> </body> </html>
# CIPHOGRAM - when a Cipher meets an Anagram ๐Ÿคช [![Angular](https://img.shields.io/badge/Angular-DD0031?style=for-the-badge&logo=angular&logoColor=white)](https://angular.io/) [![Bulma](https://img.shields.io/badge/Bulma-00D1B2?style=for-the-badge&logo=bulma&logoColor=white)](https://bulma.io/) [![Firebase](https://img.shields.io/badge/firebase-FFCA28?style=for-the-badge&logo=firebase&logoColor=black)](https://firebase.google.com/) [![Node Forge](https://img.shields.io/badge/node_forge-CB3837?style=for-the-badge&logo=npm&logoColor=white)](https://www.npmjs.com/package/node-forge) ๐Ÿค The 1st rule of CIPHOGRAM is you do not talk about CIPHOGRAM! ๐Ÿค The 2nd rule of CIPHOGRAM is you DO NOT talk about CIPHOGRAM! ## [**Available LIVE at**: https://ciphogram.web.app/](https://ciphogram.web.app/) [![GPLv3 license](https://img.shields.io/badge/License-GPLv3-blue.svg?style=for-the-badge)](http://perso.crans.org/besson/LICENSE.html) [![Open Source? Yes!](https://img.shields.io/badge/Open_Source%3F-Yes!-blue?style=for-the-badge&logo=gitHub&logoColor=white)](https://opensource.com/resources/what-open-source/) ![Language](https://img.shields.io/github/languages/top/dusk196/ciphogram-messenger?style=for-the-badge) ![Size](https://img.shields.io/github/languages/code-size/dusk196/ciphogram-messenger?style=for-the-badge) ## An anonymous, untrackable, private, highly safe & secure yet a blazing fast messenger ๐Ÿ˜Ž Have you ever felt not safe using big corporates messaging platform? Have you ever felt the need of safe & secure, 100% anonymous, untrackable & yet fast messenger with is truly end-to-end encrypted? I sure did! Personally, I take privacy very seriously. I don't even support using WhatsApp or even Google services; only because of my privacy concerns. Hence, the **CIPHOGRAM Messenger**! ## How is it different ๐Ÿค๐Ÿผ Pretty small & fast! Only 250+ KB (gZipped, without background image & sounds). ๐Ÿ”ฅ No session, no cookie, no tracking! 100% anonymous. ๐Ÿ’ฅ As obvious, no data stealing in the name of running advertisement (like other big corporations). ๐Ÿ‘ค No accounts required. Only real-time usage! ๐Ÿ” Uses true end-to-end encryption (E2EE) for both 1 to 1 and group chats without taking any toll on performanceโ€ฆ How? By the power of both symmetrical (AES CBC) & asymmetrical encryption (RSA)! ๐Ÿ’พ Thanks to Firebaseโ€™s real time database, itโ€™s quite fast and everything is almost real-time even for the slowest connections. ๐Ÿ’ฃ Your messages are self-destructible and are destroyed as soon as you either leave the system or lost the connection for a certain period of time. ## So, how the End to End Encryption works here in details (combination of symmetrical AES-CBC & asymmetrical RSA) 1. User gets a `RSA Key pair` that includes a `Public Key` & a super super super secret `Private Key`. 2. A random room is created/joined. 3. User (let's say A) shares his/her `Public Key` with other members (let's say B & C) of the room. 4. Now, if B needs to send any message to A, he will generate a random super secret `AES Key` and encrypt the plaintext message (let's call that `Cipher Text`). 5. Then B will encrypt the `AES Key` using A's `Public RSA Key` and share it along with `Cipher Text`. Note that, **Cipher Text can only be decrypted by that particular super secret AES Key**. And in RSA, **anything that's encrypted with a Public Key can only be decrypted by a Private Key of the same pair**. 6. Now, A will use his `Private Key` (_which is only in his system in real-time & never left it_) to get the super secret `AES Key`. 7. Once A gets the super secret `AES Key`, now he can finally use it to decrypt the `Cipher Text`. ## And finally, how to run it in local? Well, it's an Angular application. Just `npm i` and you're done like any other Angular application. To run in local use `npm run start` OR to deploy just use `npm run deploy` (works only when Angular Firebase is properly configured)! Cool? Ohh... You also need to setup Google Firebase first before you can actually play with it. **_Note:_** _To run the application in local, you also need to configure the application with a new Firebase project. You can create a new Firebase Project (put any name; say **XYZGram**) at the [Firebase Console](https://console.firebase.google.com/) with hosting & Realtime Database. Hosting with Firebase is completely optional (in case, you know what you're really doing and how to setup with everything) but **Firebase's real time database is mandatory**. Also try to create a domain and an app for this. Now, use the official Firebase CLI tool to configure the application as follows:_ * Run `npm i -g @angular/fire` (or `NPX`; whichever you prefer). * Once done, login to your Firebase Account by `firebase login` in the terminal. * Done? Great! Now run `ng add @angular/fire` and follow the steps in the terminal. * Once prompted, please select `ng deploy -- hosting` & `Realtime Database` from the options. * Then select your Firebase Project **XYZGram** or whichever you created. * Select a hosting site (please create new, if already not created earlier). * Select an app (please create new, if already not created earlier). * Now just wait & watch the magic of the CLI tool while it create and configure the application for you. You might need to make some changes as well as per your deployment settings (like inside `angular.json` or in `firebase.json`). Search a bit in case of any confusion. * You also need to add a random UUID. Well, I really prefer any properly generated random UUIDs or GUIDs (Why? Read Pro tip below) but you can put a STRING or even literally ANYTHING. So get anything of your choice and put it at the `dbKey` field in the `environment.ts` & `environment.prod.ts` file. So, your realtime database will have two different entries like `ciphogram-dev-{uuid}` or `ciphogram-prod-{uuid}`. Looks neat, right? * **Pro tip (with example below):** You can have custom permission set up just for `ciphogram-dev-{uuid}` and `ciphogram-prod-{uuid}` entries at the Realtime Database rules page so that any sniffer with your database URL can not misuse your DB. Remember to keep the global read/write as `false` and allow only for the designated URL using proper `uuid`. After all, it's just some free quota that most of us will ever use at the end of the day. ```JSON { "rules": { ".read": false, ".write": false, "ciphogram-dev-64a3ffd6-eaeb-42b2-8ccd-0c1db7b8dcff": { ".read": true, ".write": true }, "ciphogram-prod-5d93e17e-4fab-49e5-90ec-cc45596f49e2": { ".read": true, ".write": true } } } ``` **And... ๐Ÿ˜’** Hold your horses down bro. You're NOT done just yet! To prevent any kind of malicious uses, reCaptcha has also been enabled in this application. You can either disable or remove the reCaptcha in the `app.module.ts` file (just look for `provideAppCheck`) file OR if you really really want to use it, follow this: * At first, head to [Google reCaptcha Admin Console](https://www.google.com/recaptcha/admin/). * Create a website & register your domain. * Copy the reCAPTCHA Site key & paste it at both `environment.ts` & `environment.prod.ts` file in the `recaptchaSiteKey` field (same key for both file). * Now, copy the reCAPTCHA Secret key & paste it at Firestore's App Check -> Apps -> register with reCAPTCHA & put the site key there and you're done! _Or so you thought! ๐Ÿ˜‚_ Still, it'd not work in `localhost:4200` as the reCaptcha you have just set is for the domain name you provided only. Now, run the application and check the console. See that weird message and a `{UUID}` they're asking you put it as debug token? Do that in the Firebase's App Check page. Note that, it's different from browser to browser. **IMPORTANT: It goes without saying but please don't commit all this secret info inside the `environment.ts` and `environment.prod.ts` to any public repository!** Don't forget to add `git update-index --assume-unchanged <file>` for `environment.ts` & `environment.prod.ts` to prevent any accidental commit. Then create a replica of the both files inside the environments folder as well (it's already git ignored) since git sometimes reset these files. If such a thing happens, you still can copy-paste the values from the replicas. ## Documentations * [Understand Firebase Realtime Database Security Rules](https://firebase.google.com/docs/database/security) * [reCAPTCHA v3](https://developers.google.com/recaptcha/docs/v3) * [Use App Check with the debug provider in web apps](https://firebase.google.com/docs/app-check/web/debug-provider) ## Happy chatting with your loved ones worry-free! :wink: :wink: Bugs, informations and suggestions are highly welcome. Thank you for reading.
Nรบmeros primos -- Criar uma funรงรฃo em sua linguagem preferida. A funรงรฃo deve receber um numero N > 1 (validar o input), e retornar todos os nรบmeros primos atรฉ o numero N. EX. p(2) = [2]; p(3) = [2, 3]; p(10) = [2, 3, 5, 7]; def primos(n): if n < 2: return "Entrada invรกlida. Insira um nรบmero maior que 1." primoslista = [] for num in range(2, n + 1): primo = True for i in range(2, num): if (num % i) == 0: primo = False break if primo: primoslista.append(num) return primoslista print(primos(-1)) print(primos(2)) print(primos(3)) print(primos(50)) _________________________________________________________________________________________________________________________________________________________________________ --- Criar uma funรงรฃo recursiva que resolva p def primos_recursive(n, start=2, primoslista=None): if primoslista is None: primoslista = [] if n < 2: return "Entrada invรกlida. Insira um nรบmero maior que 1." if start > n: return primoslista primo = True for i in range(2, start): if (start % i) == 0: primo = False break if primo: primoslista.append(start) return primos_recursive(n, start + 1, primoslista) print(primos_recursive(2)) print(primos_recursive(3)) print(primos_recursive(50)) _________________________________________________________________________________________________________________________________________________________________________ --- Criar uma funรงรฃo linear que resolva p def primos_linear(n): if n < 2: return "Entrada invรกlida. Insira um nรบmero maior que 1." primos = [2] for i in range(3, n + 1): is_primo = True for j in range(2, int(i ** (1 / 2)) + 1): if i % j == 0: is_primo = False break if is_primo: primos.append(i) return primos print(primos_linear(-1)) print(primos_linear(2)) print(primos_linear(3)) print(primos_linear(20))
<template> <main> <!-- MVP --> <article id="mvp"> <Table :title="'BEST PLAYERS'" :area="'mvp'" :column="'Rating'" :list="mvp" :format="identity" /> </article> <!-- Activity stats --> <article id="activity"> <Table :title="'MOST ACTIVE THIS DAY'" :area="'activeDay'" :column="'Time'" :list="dailyActive" :format="identity" /> <section style="grid-area:online"> <h1>{{ playerCount }} PLAYERS ONLINE</h1> <table style="width:200px;margin: 0 auto;"> <thead> <tr> <th>Username</th> </tr> </thead> <tbody> <tr v-for="(player, index) in online" v-if="index < onlineIndex" :key="index"> <td>{{ player.Name }}</td> </tr> <tr v-if="online.length>4 && onlineIndex!=online.length"> <td>...</td> </tr> </tbody> </table> <button @click="onlineIndex=online.length" v-if="online.length>4 && onlineIndex!=online.length" >Show all</button> </section> <Table :title="'MOST ACTIVE THIS WEEK'" :area="'activeWeek'" :column="'Time'" :list="weeklyActive" :format="identity" /> </article> <!-- General stats --> <article id="general"> <Table :title="'MOST SURVIVALS THIS WEEK'" :area="'survivedDay'" :column="'# Rounds'" :list="weeklySurvivals" :format="identity" /> <Table :title="'MOST SURVIVALS THIS DAY'" :area="'survivedWeek'" :column="'# Rounds'" :list="dailySurvivals" :format="identity" /> <Table :title="'MOST KILLS THIS DAY'" :area="'killsDay'" :column="'Kills'" :list="dailyKills" :format="identity" /> <Table :title="'MOST KILLS THIS WEEK'" :area="'killsWeek'" :column="'Kills'" :list="weeklyKills" :format="identity" /> </article> <!-- Current map --> <section style="grid-area:current"> <h1>Current Map</h1> <img :src="mapImage" width="30%" height="30%"> </section> <!-- Activity over 48 hours --> <article style="display: flex; justify-content: center;"> <ActivityChart/> </article> <!-- human wins/zombie wins --> <article id="wins"> <div style="grid-area: humans;"> <h1>HUMAN WINS</h1> <h1>{{ humanWins }}</h1> </div> <div style="grid-area: zombies;"> <h1>ZOMBIE WINS</h1> <h1>{{ zombieWins }}</h1> </div> </article> <!-- Pick/Kill distribution --> <article id="classes"> <div style="grid-area: picks;"> <h1>PICK DISTRIBUTION</h1> <DonutChart :series="chartPickDistribution"/> </div> <div style="grid-area: kills;"> <h1>KILL DISTRIBUTION</h1> <DonutChart :series="chartKillDistribution"/> </div> </article> <!-- Survival/Score distribution --> <article id="class-survivals"> <div style="grid-area: count;"> <h1>CLASS MOST SURVIVED</h1> <DonutChart :series="classSurvivals"/> </div> <div style="grid-area: time;"> <h1>CLASS SCORE DISTRIBUTION</h1> <DonutChart :series="chartScoreDistribution"/> </div> </article> <!-- Average alive time --> <div> <h1>CLASS AVERAGE ALIVE</h1> <SurvivalChart :series="chartAliveTime"/> </div> <!-- Class stats --> <h1>PLAYER'S MOST PICKED CLASS</h1> <article style="width:95%; margin: 0 auto;"> <tabs :options="{ useUrlFragment: false }"> <tab v-for="(role, index) in classes" :name="getName(role)" :key="index"> <ClassPage :className="role"/> </tab> </tabs> </article> <!-- Top5 in class --> <article id="topfive"> <List v-for="(role, index) in classes" :key="index" v-if="index < 5" :title="role" :area="role" :list="classBest(role)" /> <List v-for="(role, index) in classes" :key="index" v-if="index >= 5" :title="role" :area="role" :list="classBest(role)" /> </article> <!-- Map stats --> <h1>MAP STATISTICS</h1> <article> <MapStatistic v-for="(map, index) in maps" :key="index" :mapName="map"/> </article> <!-- Reset Counter --> <br> <br> <h1>Time until Reset</h1> <p>{{ resetTime }}</p> <br> <br> </main> </template> <script> import moment from "moment"; import { mapGetters, mapState } from "vuex"; import Row from "@/components/Row.vue"; import Table from "@/components/Table.vue"; import List from "@/components/List.vue"; import ClassPage from "@/components/ClassPage.vue"; import MapStatistic from "@/components/MapStatistic.vue"; import ActivityChart from "@/components/ActivityChart.vue"; import DonutChart from "@/components/DonutChart.vue"; import SurvivalChart from "@/components/SurvivalChart.vue"; export default { name: "home", components: { Row, Table, List, ClassPage, MapStatistic, ActivityChart, DonutChart, SurvivalChart }, data() { return { countdown: 0, // seconds left until reset identity: a => a, // amount of players shown onlineIndex: 4, maps: [ "infc_warehouse_winter", "infc_floatingislands", "infc_warehouse2", "infc_damascus", "infc_eidalfitr", "infc_newdust", "infc_halfdust", "infc_canyon", "infc_headquarter", "infc_hardcorepit", "infc_normandie", "infc_normandie_2k19", "infc_lunaroutpost", //"infc_skull", "infc_toilet", "infc_toilet_old", "infc_malinalli_k9f", "infc_k9f_small", "infc_bamboo2", "infc_bamboo3", "infc_towers", "infc_spacelab", "infc_sewers", "infc_skull_winter", //"infc_deathdealer", //'infc_cherrytemple', //'infc_crystalcave', ], classes: [ "Soldier", "Scientist", "Biologist", "Medic", "Hero", "Ninja", "Mercenary", "Sniper", "Engineer", "Looper" ] }; }, beforeMount() { // Calculate next friday morning (00:00) const friday = 5; const today = moment.utc().isoWeekday(); let nextReset; if (today < friday) { // then just give me this week's instance of that day nextReset = moment.utc().isoWeekday(friday); } else { // *next week's* instance of that same day nextReset = moment .utc() .add(1, "weeks") .isoWeekday(friday); } nextReset.utc().startOf("day"); this.countdown = Math.floor(Math.abs(moment().diff(nextReset)) / 1000); setInterval(() => { this.countdown -= 1; }, 1000); }, computed: { ...mapState([ "mvp", "online", "zombieWins", "humanWins", "dailyActive", "weeklyActive", "dailySurvivals", "weeklySurvivals", "classSurvivals", "dailyKills", "weeklyKills" ]), ...mapGetters([ "mapImage", "playerCount", "classBest", "chartPickDistribution", "chartKillDistribution", "chartScoreDistribution", "chartAliveTime" ]), resetTime() { let seconds = this.countdown; const days = Math.floor(seconds / (60 * 60 * 24)); seconds -= days * (60 * 60 * 24); const hours = Math.floor(seconds / (60 * 60)); seconds -= hours * (60 * 60); const minutes = Math.floor(seconds / 60); seconds -= minutes * 60; return `${days}d ${hours}h ${minutes}min ${seconds}s`; } }, methods: { getName(role) { return `<img src='https://stats.resamvi.io/classes/${role}.png' width='75%' height='75%' style='margin: 0px auto'>`; } } }; </script> <style scoped> #general { display: grid; grid-template-columns: 25% 25% 25% 25%; grid-template-rows: auto; grid-template-areas: "survivedDay survivedWeek killsDay killsWeek"; margin-bottom: 5%; } #activity { display: grid; grid-template-columns: 33% 33% 33%; grid-template-rows: auto; grid-template-areas: "activeDay online activeWeek"; margin-bottom: 5%; } #mvp { display: grid; grid-template-columns: 25% 50% 25%; grid-template-rows: auto; grid-template-areas: ". mvp ."; margin-bottom: 5%; } #wins { display: grid; margin-bottom: 5%; grid-template-columns: 50% 50%; grid-template-rows: auto; grid-template-areas: "humans zombies"; } #topfive { display: grid; grid-template-columns: 10% 16% 16% 16% 16% 16% 10%; grid-template-rows: auto; grid-template-areas: ". Soldier Scientist Biologist Medic Hero ." ". Ninja Mercenary Sniper Engineer Looper ."; } #classes { display: grid; grid-template-columns: 50% 50%; grid-template-rows: auto; grid-template-areas: "picks kills"; } #class-survivals { display: grid; grid-template-columns: 50% 50%; grid-template-rows: auto; grid-template-areas: "count time"; } main { background-color: #f2f2f2; display: inline-block; width: 100%; } button { background: none; border: none; cursor: pointer; } .center { display: flex; justify-content: center; align-items: center; text-align: center; } </style>
// #define RH_TEST_NETWORK 1 // activate Forced Topology #include <RHMesh.h> #include <RH_RF95.h> #include <SPI.h> // #include <esp_task_wdt.h> #include <string.h> #define RF95_FREQ 433.0 #define WDT_TIMEOUT 15 #define SENDING_MODE 0 #define RECEIVING_MODE 1 #define ENDNODE_ADDRESS 2 // purposefully using the last namber #if defined(SELF_ADDRESS) && defined(TARGET_ADDRESS) const uint8_t selfAddress_ = SELF_ADDRESS; const uint8_t targetAddress_ = TARGET_ADDRESS; #else // Topology #define NODE1_ADDRESS 1 #define NODE2_ADDRESS 2 #define NODE3_ADDRESS 3 const uint8_t selfAddress_ = NODE1_ADDRESS; // CHANGE THIS!!! const uint8_t targetAddress_ = ENDNODE_ADDRESS; #endif //radio driver & message mesh delivery/receipt manager RH_RF95 RFM95Modem_; RHMesh RHMeshManager_(RFM95Modem_, selfAddress_); uint8_t mode_ = SENDING_MODE; // these are expected to be global/externally exposed variables, if you plan to // make a class to wrap this String msgSend = String("Hello from node #" + String(selfAddress_) + "!"); String msgRcv; // void rhSetup(); void setup() { Serial.begin(9600); while (!Serial) ; //esp_task_wdt_init(WDT_TIMEOUT, true); // enable panic so ESP32 restarts //esp_task_wdt_add(NULL); // add current thread to WDT watch rhSetup(); Serial.println(" ---------------- LORA NODE " + String(selfAddress_) + " INIT ---------------- "); } long _lastSend = 0, sendInterval_ = 3000; // send every 10 seconds uint8_t _msgRcvBuf[RH_MESH_MAX_MESSAGE_LEN]; char buf_[RH_MESH_MAX_MESSAGE_LEN]; void loop() { uint8_t _msgFrom; uint8_t _msgRcvBufLen = sizeof(_msgRcvBuf); if ((millis() - _lastSend > sendInterval_) && selfAddress_ != ENDNODE_ADDRESS) { mode_ = SENDING_MODE; } if (mode_ == SENDING_MODE) { // Send a message to another rhmesh node Serial.print("Sending msg "); Serial.print(msgSend); Serial.print(" to node #"); Serial.println(String(targetAddress_)); uint8_t _err = RHMeshManager_.sendtoWait(reinterpret_cast<uint8_t *>(&msgSend[0]), msgSend.length(), targetAddress_); if (_err == RH_ROUTER_ERROR_NONE) { // message successfully be sent to the target node, or next neighboring // expecting to recieve a simple reply from the target node //esp_task_wdt_reset(); Serial.println("Successfull! Awaiting for Reply"); if (RHMeshManager_.recvfromAckTimeout(_msgRcvBuf, &_msgRcvBufLen, 4000, &_msgFrom)) { char buf_[RH_MESH_MAX_MESSAGE_LEN]; //Serial.println(buf_); sprintf(buf_, "%s", reinterpret_cast<char *>(_msgRcvBuf)); Serial.print("Message was from node #"); Serial.println(String(_msgFrom)); Serial.println(buf_); // Serial.printf("[%d] \"%s\" (%d). Sending a reply...\n", _msgFrom, msgRcv.c_str(), RFM95Modem_.lastRssi()); } else { Serial.println("No reply, is the target node running?"); } // esp_task_wdt_reset(); } else { Serial.println( "sendtoWait failed. No response from intermediary node, are they " "running?"); } _lastSend = millis(); mode_ = RECEIVING_MODE; //delay(100); } if (mode_ == RECEIVING_MODE) { // while at it, wait for a message from other nodes Serial.println("Receiving mode active"); if (RHMeshManager_.recvfromAckTimeout(_msgRcvBuf, &_msgRcvBufLen, 3000, &_msgFrom)) { char buf_[RH_MESH_MAX_MESSAGE_LEN]; // esp_task_wdt_reset(); Serial.println("Received a message"); printf(buf_, "%s", reinterpret_cast<char *>(_msgRcvBuf)); Serial.println(buf_); msgRcv = String(buf_); // do something with message, for example pass it through a callback // printf("[%d] \"%s\" (%d). Sending a reply...\n", _msgFrom, // msgRcv.c_str(), RFM95Modem_.lastRssi()); String _msgRply = String("Hi node " + String(_msgFrom) + ", got the message!").c_str(); uint8_t _err = RHMeshManager_.sendtoWait( reinterpret_cast<uint8_t *>(&_msgRply[0]), _msgRply.length(), _msgFrom); if (_err == RH_ROUTER_ERROR_NONE) { // message successfully received by either final target node, or next // neighboring node. do nothing... } else { Serial.println("Fail to send reply..."); } // esp_task_wdt_reset(); } } // esp_task_wdt_reset(); } void rhSetup() { if (!RHMeshManager_.init()) Serial.println("init failed"); RFM95Modem_.setTxPower(23, false); RFM95Modem_.setFrequency(RF95_FREQ); RFM95Modem_.setCADTimeout(500); }
import 'package:formapp/app/data/models/user_model.dart'; import 'package:formapp/app/data/provider/user_provider.dart'; class UserRepository { final UserApiClient apiClient = UserApiClient(); getAll(String token) async { List<User> list = <User>[]; var response = await apiClient.getAll(token); if (response != null) { response.forEach((e) { list.add(User.fromJson(e)); }); } return list; } insertUser(String token, User user) async { try { var response = await apiClient.insertUser(token, user); return response; } catch (e) { print('Erro ao inserir a usuรกrio: $e'); rethrow; } } updateUser(String token, User user) async { try { var response = await apiClient.updateUser(token, user); return response; } catch (e) { print('Erro ao atualizar a famรญlia: $e'); rethrow; } } deleteUser(String token, User user) async { try { var response = await apiClient.deleteUser(token, user); return response; } catch (e) { print('Erro ao atualizar a famรญlia: $e'); rethrow; } } updateFirebaseTokenUser(String token, User user, String firebaseToken) async { try { var response = await apiClient.updateFirebaseTokenUser(token, user, firebaseToken); return response; } catch (e) { print('Erro ao atualizar a famรญlia: $e'); rethrow; } } }
package net.ukr.dreamsicle.validation.currencyCode; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * ValidCurrencyCode interface for class {@link ValidCurrencyCodeValidator}. * * @author yurii.loienko * @version 1.0 */ @Target({FIELD, PARAMETER}) @Retention(RUNTIME) @Constraint(validatedBy = ValidCurrencyCodeValidator.class) @Documented public @interface ValidCurrencyCode { String message() default "wrong iso code"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
import duplicates_cli as dc import pytest def test_get_hash_md5(): import hash_functions filename = 'files/test.txt' with open(filename, 'rb') as fin: message = fin.read() assert dc.get_hash(filename) == hash_functions.hashmd5(message) def test_no_args_passed(capsys): expected_out_parts = ["[-h] [-e EXTENSION]", "dirname", "error: the following arguments are required: dirname"] with pytest.raises(SystemExit): dc.cli([]) captured = capsys.readouterr() result = captured.err result = result.splitlines() result = [line.strip() for line in result] assert expected_out_parts[0] in result[0] assert expected_out_parts[1] in result[1] def test_extension_pdf_output(capsys): expected_out = ["These files have the same hash:", "files/archive/sines_archive.pdf", "files/fig/sines.pdf", "files/sines.pdf"] dc.cli(['-e', '.pdf', 'files']) captured = capsys.readouterr() result = captured.out result = result.splitlines() result = [line.strip() for line in result] result = [line.replace('\\', '/') for line in result] assert result == expected_out def test_full_output(capsys): expected_out = ["These files have the same hash:", "files/archive/sines_archive.pdf", "files/fig/sines.pdf", "files/sines.pdf", "These files have the same hash:", "files/archive/test_archive.txt", "files/test.txt", "files/test_copy.txt", "files/txt/test.txt", "files/txt/test_copy.txt", "These files have the same hash:", "files/test2.txt", "files/txt/test2.txt"] dc.cli(['files']) captured = capsys.readouterr() result = captured.out result = result.splitlines() result = [line.strip() for line in result] result = [line.replace('\\', '/') for line in result] assert result == expected_out
<!doctype html> <meta charset ="utf-8"> <html> <script src="http://d3js.org/d3.v3.min.js"></script> <body> <script> var margin = {top : 20, right : 400, bottom : 40, left : 90}, width = 1400 - margin.left - margin.right, height = 680 - margin.top - (margin.bottom - 20); var x = d3.scale.linear().range([0, width]); var y = d3.scale.linear().range([height, 0]); var color = d3.scale.category10(); var xAxis = d3.svg.axis().scale(x).orient("bottom") .tickFormat(function(d) {return d;}) .ticks(10); var yAxis = d3.svg.axis().scale(y).orient("left") .tickFormat(function(d) {return d;}) .ticks(10); var axisName = ["App Rating", "App Reviews", "App Size", "Number Of Intallations", "Current Android Version"] var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.csv("GPS_DATA.csv", function(error, data){ if (error){ throw error; } data.forEach(function(d) { d.AppRating = +d.AppRating; d.AppReviews = +d.AppReviews; d.AppSize = +d.AppSize; d.NumberOfInstallations = +d.NumberOfInstallations; d.CurrentAndroidVersion = +d.CurrentAndroidVersion; }); x.domain([ d3.min(data, function(d) {return d.AppRating;}), d3.max(data, function(d) {return d.AppRating;}) ]) y.domain([ d3.min(data, function(d) {return d.AppRating;}), d3.max(data, function(d) {return d.AppRating;}) ]) svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) svg.append("g") .attr("class", "y axis") .call(yAxis) var circles = svg.selectAll(".dot") .data(data) .enter().append("circle") .attr("class", "dot") .attr("r", 5) .attr("cx", function(d) {return x(d.AppRating);}) .attr("cy", function(d) {return y(d.AppRating);}) .style("fill", function(d) {return color(d.Category);}); var legend = svg.selectAll(".legend") .data(color.domain()) .enter().append("g") .attr("class", "legend") .attr("transform", function(d,i) {return "translate(0," + i * 20 + ")";}); legend.append("rect") .attr("x", width + 240) .attr("width", 5) .attr("height", 5) .style("fill", color); legend.append("text") .style("font-size", "8px") .attr("x", width + 224) .attr("y", 9) .attr("dy", "-.30em") .style("text-anchor", "end") .text(function(d) {return d;}); d3.select("[name=xAX]").on("change", function() { xAxy = this.value; console.log(xAxy); x.domain([ d3.min(data, function(d) {return d[xAxy];}), d3.max(data, function(d) {return d[xAxy];}) ]) svg.select(".x.axis").transition().duration(500).call(xAxis); svg.selectAll(".dot").transition().duration(500) .attr("cx", function(d) {return x(d[xAxy]);}) svg.selectAll(".x.axis").selectAll("text.label") .text(axisName[xAxy]); }); d3.select("[name=yAX]").on("change", function() { yAxy = this.value; console.log(yAxy); y.domain([ d3.min(data, function(d) {return d[yAxy];}), d3.max(data, function(d) {return d[yAxy];}) ]) svg.select(".y.axis").transition().duration(500).call(yAxis); svg.selectAll(".dot").transition().duration(500) .attr("cy", function(d) { return y(d[yAxy]); }); svg.selectAll(".y.axis").selectAll("text.label") .text(axisName[yAxy]); }); }); </script> <div id = "label"><b>Select X-Axis:<b></div> <select name = "xAX" id = "xAXs"> <option value = "AppRating">App Rating</option> <option value = "AppReviews">App Reviews</option> <option value = "AppSize">App Size</option> <option value = "NumberOfInstallations">Number of Installations</option> <option value = "CurrentAndroidVersion">Current Android Version</option> </select> <div id = "label2"><b>Select Y-Axis:<b></div> <select name = "yAX" id = "yAXs"> <option value = "AppRating">App Rating</option> <option value = "AppReviews">App Reviews</option> <option value = "AppSize">App Size</option> <option value = "NumberOfInstallations">Number of Installations</option> <option value = "CurrentAndroidVersion">Current Android Version</option> </select> <p> Select a Visualization to View<br> <select name="menu1" id="menu1"> <option selected disabled>Select a Visualization</option> <option value="MainHomePage.html">Homepage</option> <option value="Correlation.html">Correlation Matrix</option> <option value="Scatter_Matrix.html">Scatterplot Matrix</option> <option value="Scree.html">PCA Scree Plot</option> <option value="GPS_Biplot.html">Biplot</option> <option value="Euclidean_MDS.html">MDS Plot ~ Euclidean Distance</option> <option value="Correlation_MDS.html">MDS Plot ~ 1 - |Correlation| Distance</option> </select> <script type="text/javascript"> var urlmenu = document.getElementById( 'menu1' ); urlmenu.onchange = function() { window.open(this.options[ this.selectedIndex ].value, '_self'); }; </script> </body> </html>
import Footer from "@/components/Footer"; import User from "@/components/user"; import { Title } from "@/styles/styled.about"; interface User { name: string; email: string; id: number; } export default function About({ users }: { users: User[] }) { return ( <> <Title>About page</Title> {users?.map((item) => ( <User user={item} key={item.id} /> ))} </> ); } export async function getStaticProps() { const response = await fetch("https://jsonplaceholder.typicode.com/users"); const data = await response.json(); console.log(data); return { props: { users: data, }, }; } About.getLayout = function pageLayout(page: any) { return ( <> {page} <Footer /> </> ); };
import { useEffect, useState } from "react" import AutoAwesomeIcon from "@mui/icons-material/AutoAwesome" import Box from "@mui/material/Box" import Button from "@mui/material/Button" import CircleIcon from "@mui/icons-material/Circle" import ListItemText from "@mui/material/ListItemText" import Stack from "@mui/material/Stack" import Typography from "@mui/material/Typography" import toast from "react-hot-toast" const USE_EFFECT_LIFECYCLES = [ "`useEffect(() => {})` excludes the dependency array, resulting in the provided callback executing on the initial render and for every rerender of the encapsulating component. This behavior replicates the `componentDidUpdate` lifecycle method of class components.", "`useEffect(() => {}, [])` includes an empty dependency array, which will result in the provided callback executing only on the initial render of the encapsulating component. This behavior replicates the `componentDidMount` lifecycle method of class components.", "`useEffect(() => {}, [dep1, ...])` includes a populated dependency array, which will limit the execution of the provided callback to instances where the value of any of the included dependencies has changed. This behavior replicates the `componentWillUnmount` lifecycle method of class components.", ] export default function SideEffects() { const [stateA, setStateA] = useState(1) const [stateB, setStateB] = useState(1) function handleStateChangeA() { setStateA(stateA + 1) } function handleStateChangeB() { setStateB(stateB + 1) } useEffect(() => { if (stateB > 3) { toast.custom( <> <AutoAwesomeIcon sx={{ color: "purple", mr: 1 }} /> <Typography>stateB: {stateB}</Typography> <AutoAwesomeIcon sx={{ color: "purple", ml: 1 }} /> </> ) } }, [stateB]) return ( <Box display="flex" flexDirection="column" alignItems="center"> <h2>useEffect</h2> <Typography sx={{ mb: 2 }}> `useEffect` provides a way for components to introduce side effects. Depending on what, if any, dependencies are provided to `useEffect`, the provided callback will execute when those dependencies change or at certain points during the component's lifecycle. </Typography> {USE_EFFECT_LIFECYCLES.map((content, idx) => ( <ListItemText key={`${idx}-${content}`} sx={{ mb: 2 }}> <CircleIcon sx={{ fontSize: ".5rem", mr: 1 }} /> {content} </ListItemText> ))} <Stack direction="row" spacing={3}> <Typography sx={{ mb: 1, fontSize: "1.5rem" }}>stateA: {stateA}</Typography> <Typography sx={{ mb: 2, fontSize: "1.5rem" }}>stateB: {stateB}</Typography> </Stack> <Stack direction="row"> <Button onClick={handleStateChangeA} variant="outlined"> Increment `stateA` (no side effect) </Button> <Button onClick={handleStateChangeB} variant="outlined"> Imcrement `stateB` (side effect when stateB {">"} 3) </Button> </Stack> </Box> ) }
document.addEventListener("DOMContentLoaded", function() { let popup = document.getElementById("popup"); // Function to open the modal function openModal() { popup.classList.add("open-popup"); } // Function to close the modal function closeModal() { popup.classList.remove("open-popup"); } // Get the form element let form = document.querySelector(".buy_form"); // Add event listener to the form form.addEventListener("submit", function(event) { // Prevent the default form submission behavior event.preventDefault(); // Check if all required fields are filled before opening the modal let nameInput = document.getElementById("name1"); let addressInput = document.querySelector("[name=myAddr]"); let paymentInput = document.getElementById("paym"); let phoneInput = document.getElementById("phone"); // Check if all fields are filled let isCompleted = nameInput.value.trim() !== "" && addressInput.value.trim() !== "" && paymentInput.value.trim() !== "" && phoneInput.value.trim() !== ""; // If all fields are filled, open the modal if (isCompleted) { openModal(); } else { // Otherwise, show an alert or handle the incomplete form as needed alert("Please fill in all required fields."); } }); // Event delegation for "Proceed to Pay" button popup.addEventListener("click", function(event) { if (event.target.id === "closeit") { // Prevent the default behavior of the button event.preventDefault(); // Close the modal when "Proceed to Pay" is clicked closeModal(); // Here you can add additional logic if needed } }); // Event delegation for payment method change document.getElementById("paym").addEventListener("change", function() { var selectedOption = this.value; var popupContent = document.getElementById("popup"); // Reset content popupContent.innerHTML = ""; if (selectedOption === "upi") { popupContent.innerHTML = ` UPI ID <input type="text"> <br> OR <br> Holder Name <input type="text"> Amount โ‚น99999 <button class="btn1" id="closeit">Proceed to Pay</button> `; } else if (selectedOption === "cash") { popupContent.innerHTML = ` Thank You for ordering <br> You will receive your order in 2-3 days <br> Payment will be done in cash <br> <button class="btn1" id="closeit">Close</button> `; } else if (selectedOption === "card") { popupContent.innerHTML = ` Card Number <input type="text"> <br> Expiry Date <input type="date"> CVV <input type="text"> Amount โ‚น99999 <button class="btn1" id="closeit">Proceed to Pay</button> `; } else if (selectedOption === "emi") { var tenureOptions = ` <option value="3">3 months</option> <option value="6">6 months</option> <option value="12">12 months</option> `; popupContent.innerHTML = ` <strong>Choose Tenure:</strong> <select id="emiTenure">${tenureOptions}</select> <br> <p id="emiAmount"></p> <button class="btn1" id="closeit">Proceed to Pay</button> `; document.getElementById("emiTenure").addEventListener("change", function() { var selectedTenure = parseInt(this.value); var totalAmount = 99999; // Total amount var amountPerMonth = totalAmount / selectedTenure; document.getElementById("emiAmount").textContent = `Amount per month: โ‚น${amountPerMonth.toFixed(2)}`; }); } }); });
<script setup> import { onMounted, ref } from 'vue' import {useAuthStore} from '../../stores/Auth.js' import useProfile from '../../composables/profile' const authStore = useAuthStore() const formData = new FormData(); const {updateUser, updatePasswordUser, loading} = useProfile(); const userId = ref('') const name = ref('') const email = ref('') const oldPassword = ref('') const newPassword = ref('') const confimNewPassword = ref('') onMounted(async() => { const user = await authStore.getUser() userId.value = authStore.user.id name.value = authStore.user.name email.value = authStore.user.email }) const editUser = async ()=>{ formData.append('userId', userId.value); formData.append('name', name.value); formData.append('email', email.value); for (const [key, value] of formData) { formData[key] = value } await updateUser({...formData}, userId.value) } const editPasswordUser = async ()=>{ formData.append('oldPassword', oldPassword.value); formData.append('newPassword', newPassword.value); formData.append('confimNewPassword', confimNewPassword.value); for (const [key, value] of formData) { formData[key] = value } await updatePasswordUser({...formData}, userId.value) } </script> <template> <div class="space-y-4 w-11/12 mx-auto rounded-md shadow-md bg-white mt-12 p-6"> <div class="flex justify-between flex-row"> <header class="mb-3 text-2xl font-bold">Profile</header> </div> <form action="" @submit.prevent="editUser()"> <div class="grid grid-cols-2 gap-2"> <div class="w-full rounded-2xl bg-gray-50 px-4 ring-2 ring-gray-200 focus-within:ring-blue-400"> <input type="text" placeholder="Name" v-model="name" class="my-3 w-full border-none bg-transparent outline-none focus:outline-none" /> </div> <div class="w-full rounded-2xl bg-gray-50 px-4 ring-2 ring-gray-200 focus-within:ring-blue-400"> <input type="text" placeholder="email" v-model="email" class="my-3 w-full border-none bg-transparent outline-none focus:outline-none" /> </div> </div> <div class="mt-2 flex justify-center"> <button class="w-20 text-center items-center rounded-2xl border-b-4 border-b-blue-600 bg-blue-500 py-3 font-bold text-white hover:bg-blue-400 active:translate-y-[0.125rem] active:border-b-blue-400">Save</button> </div> </form> <form action="" @submit.prevent="editPasswordUser()"> <div class="grid grid-cols-2 gap-2"> <div class="w-full rounded-2xl bg-gray-50 px-4 ring-2 ring-gray-200 focus-within:ring-blue-400"> <input type="password" placeholder="old Password" v-model="oldPassword" class="my-3 w-full border-none bg-transparent outline-none focus:outline-none" /> </div> <div class="w-full rounded-2xl bg-gray-50 px-4 ring-2 ring-gray-200 focus-within:ring-blue-400"> <input type="password" placeholder="New Password" v-model="newPassword" class="my-3 w-full border-none bg-transparent outline-none focus:outline-none" /> </div> <div class="w-full rounded-2xl bg-gray-50 px-4 ring-2 ring-gray-200 focus-within:ring-blue-400 col-start-2"> <input type="password" placeholder="Confirm New Password" v-model="confimNewPassword" class="my-3 w-full border-none bg-transparent outline-none focus:outline-none" /> </div> </div> <div class="mt-2 flex justify-center"> <button class="px-2 text-center items-center rounded-2xl border-b-4 border-b-blue-600 bg-blue-500 py-3 font-bold text-white hover:bg-blue-400 active:translate-y-[0.125rem] active:border-b-blue-400">Save Password</button> </div> <!-- <alert v-bind:errorsVehiculo="errorsVehiculo" v-bind:success="status"></alert> --> </form> </div> </template> <style> </style>
from django.forms import ModelForm from django import forms from .models import User from .models import Doctor from .models import DoctorAppointment from .models import DoctorSpecialization from .models import Medicine from .models import Message from .models import Nurse from .models import NurseAppointment from .models import Sanatorium from .models import SanatoriumAppointment class LoginForm(forms.Form): username = forms.CharField(label='Username') password = forms.CharField(label='Password', widget=forms.PasswordInput) class UserForm(ModelForm): class Meta: model:User fields:'__all__' class DoctorForm(ModelForm): class Meta: model:Doctor fields:'__all__' class DoctorAppointmentForm(ModelForm): class Meta: model:DoctorAppointment fields:'__all__' class DoctorSpecializationForm(ModelForm): class Meta: model:DoctorSpecialization fields:'__all__' class NurseForm(ModelForm): class Meta: model:Nurse fields:'__all__' class NurseAppointmentForm(ModelForm): class Meta: model:NurseAppointment fields:'__all__' class SanatoriumForm(ModelForm): class Meta: model:Sanatorium fields:'__all__' class MedicineForm(ModelForm): class Meta: model:Medicine fields:'__all__' class MessageForm(ModelForm): class Meta: model:Message fields:'__all__' class SanatoriumAppointmentForm(ModelForm): class Meta: model:SanatoriumAppointment fields:'__all__'
/** * WizardMC API Source Code. * * @license GPLv3 * @copyright EvoWide - Valentin Kaelin & Quentin Fialon */ import Env from '@ioc:Adonis/Core/Env' import got from 'got' import CacheService from '../CacheService' import { DateTime } from 'luxon' import Database from '@ioc:Adonis/Lucid/Database' import User from 'App/Models/User' class Paysafecard { private readonly production_url = 'https://api.paysafecard.com/v1/payments/' private readonly sandbox_url = 'https://apitest.paysafecard.com/v1/payments/' private readonly fees = [ { max: 999, fees: 15, }, { max: 9999, fees: 14, }, { max: 100000, fees: 13, }, ] constructor ( private marchantId = Env.get('PAYMENT_PAYSAFECARD_ID') as string, private sandbox = Env.get('PAYMENT_PAYSAFECARD_SANDBOX') as boolean, ) { } public async initiate (amount: number, customer: {}) { const baseUrl = Env.get('FRONTEND_URL') as string const response = await got.post(this.getUrl(), { json: { type: 'PAYSAFECARD', amount: amount, currency: 'EUR', redirect: { success_url: `${baseUrl}/credits/success/paysafecard?payment_id={payment_id}`, failure_url: `${baseUrl}/credits/failure/paysafecard`, }, notification_url: 'https://api.wizardmc.fr/payment/notification/paysafecard/{payment_id}', customer: customer, shop_id: '1', }, headers: { Authorization: 'Basic ' + Buffer.from(this.marchantId).toString('base64'), }, responseType: 'json', }).catch() return response.body ?? false } public async capture (paymentId: string): Promise<any> { let response = await got.post(`${this.getUrl()}${paymentId}/capture`, { json: { id: paymentId, }, headers: { Authorization: 'Basic ' + Buffer.from(this.marchantId).toString('base64'), }, responseType: 'json', }).catch() return response.body } public async retrieve (paymentId: string): Promise<any> { let response = await got.get(`${this.getUrl()}${paymentId}`, { headers: { Authorization: 'Basic ' + Buffer.from(this.marchantId).toString('base64'), }, responseType: 'json', }).catch() return response.body } public async validate (paymentId: string): Promise<boolean> { const paymentRetrieve = await this.retrieve(paymentId) if (!paymentRetrieve || paymentRetrieve.status !== 'AUTHORIZED') { return paymentRetrieve && paymentRetrieve.status === 'SUCCESS' } const paymentCapture = await this.capture(paymentId) if (!paymentCapture || paymentCapture.status !== 'SUCCESS') { return false } const paymentRow = await Database.from('payment_paysafecards') .where('token', paymentId) .where('credited', false) .first() if (!paymentRow) { return false } const priceRow = await Database.from('payment_prices') .where('method', 'paysafecard') .where('price', paymentRow.price) .first() if (!priceRow || priceRow.credits <= 0) { return false } const user = await User.findOrFail(paymentRow.user_id) user.credits += priceRow.credits await user.save() await Database.from('payment_paysafecards') .where('id', paymentRow.id) .update({ credited: true, }) const payout = paymentRow.price * ((100 - await this.getPaysafecardFees()) / 100) await Database .insertQuery() .table('user_payments') .insert({ user_id: user.id, method: 'paysafecard', price: paymentRow.price, payout: payout, credits: priceRow.credits, }) return true } public async getPaysafecardFees (): Promise<number> { return await CacheService.remember('paysafecard-fee', async () => { let datetime = DateTime.local().set({ day: 1, hour: 0, minute: 0, second: 0 }) const result = await Database.from('user_payments') .where('created_at', '>=', datetime.toSQL()) .where('method', 'paysafecard') .sum('price as sum') const sum = result[0]['sum'] ?? 0 return this.fees.find(value => value.max >= sum)?.fees }, '1h') } private getUrl () { return this.sandbox ? this.sandbox_url : this.production_url } } export default new Paysafecard()
## ็ป™ๅฎšไธ€ไธชไบŒๅ‰ๆ ‘๏ผŒๆŒ‰้ซ˜ๅบฆ็”ฑ้ซ˜ๅˆฐไฝŽไพๆฌกๆ‰“ๅฐไปŽๅณไพง่ง†่ง’็œ‹ๅˆฐ็š„่Š‚็‚น ## ๆ€่ทฏ๏ผšๅคงๆ–นๅ‘ๅฑžไบŽไบŒๅ‰ๆ ‘็š„ๅฑ‚ๆฌก้ๅކ๏ผŒๅชไธ่ฟ‡ๆฏๆฌกๅชๅ…ณๆณจๆฏไธ€ๅฑ‚็š„ๆœ€ๅŽไธ€ไธช๏ผˆๆœ€ๅณ๏ผ‰่Š‚็‚น๏ผŒๆ•ฐๆฎ็ป“ๆž„่€ƒ่™‘ไฝฟ็”จ้˜Ÿๅˆ—๏ผŒๅ› ไธบ้˜Ÿๅˆ—ๆ˜ฏๅ…ˆ่ฟ›ๅ…ˆๅ‡บ็š„ใ€‚๏ผŒ ้ฆ–ๅ…ˆๅ–ๅˆฐๅนถๆ‰“ๅฐๆฏไธ€ๅฑ‚็š„ๆœ€ๅŽไธ€ไธช่Š‚็‚น๏ผˆๆœ€ๅŽๅ…ฅ้˜Ÿ๏ผ‰๏ผŒ็„ถๅŽๅฐ†้˜Ÿๅˆ—ไธญ็š„ๆฏไธ€ไธช่Š‚็‚นๅ‡บ้˜Ÿ๏ผŒๅนถๅฐ†ๅ…ถๅทฆๅณๅญ่Š‚็‚นๆŒ‰ๅบๅ…ฅ้˜Ÿ๏ผŒ็›ด่‡ณ่ฏฅๅฑ‚็š„ๆœ€ๅŽไธ€ไธช ่Š‚็‚น๏ผŒ้šๅŽ้€’ๅฝ’๏ผŒๅผ€ๅง‹ไธ‹ๅฑ‚ๅพช็Žฏใ€‚ class TreeNode { int val; TreeNode left; TreeNode right; } void scanRightSide(TreeNode Root) { if (root == null) { return; } LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while(!queue.isEmpty()) { //ๅฝ“้˜Ÿๅˆ—ๅ–็ฉบ็š„ๆ—ถๅ€™๏ผŒๅฐฑ้ๅކๅฎŒๆˆ TreeNode last = queue.getLast(); println(last.val); // ๆ‰“ๅฐๅฝ“ๅ‰้˜Ÿๅˆ—ไธญ็š„ๆœ€ๅŽไธ€ไธชๅ…ƒ็ด  TreeNode item = null; do{ item = queue.remove(); if (item.left != null) { queue.add(item.left); } if (item.right != null) { queue.add(item.right); } } while(item != last); } return result; }
import 'package:chatapp_1/components/my_button.dart'; import 'package:chatapp_1/components/my_text_field.dart'; import 'package:chatapp_1/services/auth/auth_services.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class LoginPage extends StatefulWidget { final void Function()? onTap; const LoginPage({super.key, required this.onTap}); @override State<LoginPage> createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { //text controller final emailController = TextEditingController(); final passwordController = TextEditingController(); Future<void> signIn() async { //auth service final authService = Provider.of<AuthService>(context, listen: false); try { await authService.signInWithEmailandPassword( emailController.text, passwordController.text); } catch (e) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( e.toString(), ), ), ); } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.grey[300], body: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 25.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const SizedBox(height: 50), //logo Icon( Icons.message_sharp, size: 100, color: Colors.blue[800], ), const SizedBox(height: 10), //welcome back msg const Text( "Welcome back you've been missed!", style: TextStyle( fontSize: 16, ), ), const SizedBox(height: 10), //email txtfield MyTextField( controller: emailController, hintText: 'Email', obscureText: false), const SizedBox(height: 25), //pwd txtfield MyTextField( controller: passwordController, hintText: 'password', obscureText: true), const SizedBox(height: 20), //sign in btn MyButton(onTap: signIn, text: "Sign in"), const SizedBox(height: 50), //not a mem? reg now Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text('Not a member?'), const SizedBox(width: 4), GestureDetector( onTap: widget.onTap, child: const Text( 'Register Now', style: TextStyle( fontWeight: FontWeight.bold, ), ), ), ], ) ], ), ), ), ); } }
import styled from "styled-components"; import Box from "./Box"; import Loader from "./Loader"; import ErrorMessage from "./ErrorMessage"; import MovieList from "../features/movie/MovieList"; import MovieDetails from "../features/movie/MovieDetails"; import WatchedMoviesSummary from "../features/movie/WatchedMoviesSummary"; import WatchedMoviesList from "../features/movie/WatchedMoviesList"; import { useMoviesContext } from "../contexts/MoviesContext"; import { useWatchedMoviesContext } from "../contexts/WatchedMoviesContext"; const StyledMain = styled.main` margin-top: 2.4rem; height: 95.6vh; display: flex; gap: 2.4rem; justify-content: center; `; function Main() { const { isLoading, error } = useMoviesContext(); const { selectedMovieId } = useWatchedMoviesContext(); return ( <StyledMain> <Box> {isLoading && <Loader />} {!isLoading && !error && <MovieList />} {error && <ErrorMessage message={error} />} </Box> <Box> {selectedMovieId ? ( <MovieDetails /> ) : ( <> <WatchedMoviesSummary /> <WatchedMoviesList /> </> )} </Box> </StyledMain> ); } export default Main;
// create component for chars of characters import React from "react"; import Highcharts from "highcharts"; import HighchartsReact from "highcharts-react-official"; import { ListCharactersContextInterface } from "../../interfaces/charactersList.Interfaces"; import { ListCharactersContext } from "../../contexts/charactersList.context"; import { IChar } from "../../interfaces/chars.interfaces"; export const CharStatus = () => { const { ElementList } = React.useContext( ListCharactersContext ) as ListCharactersContextInterface; // function definition the status of ElementList const statusList = () => { const status: Array<IChar> = []; ElementList.forEach((element) => { if (!status.find((item) => item.name === element.status)) { status.push({ name: element.status, y: 1, }); } else { const index = status.findIndex((item) => item.name === element.status); status[index].y++; } }); return status; }; // funtion definition for char status const optionsCharStatus = () => { const charStatus = { chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false, type: "pie", }, title: { text: "Status of Rick and Morty Characters per page", }, tooltip: { pointFormat: "{series.name}: <b>{point.percentage:.1f}%</b>", }, accessibility: { point: { valueSuffix: "%", }, }, plotOptions: { series: { borderWidth: 0, colorByPoint: true, type: 'pie', size: '100%', innerSize: '60%', dataLabels: { enabled: true, crop: false, distance: '-10%', style: { fontWeight: 'bold', fontSize: '16px' }, connectorWidth: 0 } } }, colors: ['#FCE700', '#F8C4B4', '#B8E8FC', '#BCE29E', '#f6e1ea'], series: [ { name: "Status", colorByPoint: true, data: statusList(), }, ], credits: { text: '', } }; return charStatus; }; return ( <HighchartsReact highcharts={Highcharts} options={optionsCharStatus()} /> ); }; export default CharStatus;
<script setup lang="ts"> // dependencies import { ref } from 'vue'; import { generateFakeData } from '@/fakes/generate'; import type { Character } from '@/fakes/models'; import { useCharacterStore } from '@/stores/character'; // composables import { usePagination } from '@/composables/pagination'; // components import Header from '@/components/Header.vue'; import UserInventory from '@/components/UserInventory.vue'; import GameModes from '@/components/GameModes.vue'; import TeamSelected from '@/components/TeamSelected.vue'; import CharacterDetail from '@/components/CharacterDetail.vue'; // store const characterStore = useCharacterStore(); // setup vars const page = ref(1); const characters = ref<Character[]>([]); characters.value = generateFakeData(); characterStore.setCurrentCharacter(characters.value[0]); // hooks const { paginatedList, numberOfPages, currentPage, goToPrev, goToNext } = usePagination( characters, { page: page, perPage: 10 } ); // methods const viewCharacterDetail = (character: Character) => { characterStore.setCurrentCharacter(character); }; </script> <template> <div> <Header /> <UserInventory /> <GameModes /> <TeamSelected /> <CharacterDetail /> <div class="container-list-characters"> <div><input type="text" placeholder="Pesquisar" /></div> <ul id="characters-list"> <li v-for="char in paginatedList" :key="char.id" @click="viewCharacterDetail(char)"> <button> <img :src="char.avatarURL" alt="" /> </button> </li> </ul> <div> <button @click="goToPrev">Prev</button> {{ currentPage }} / {{ numberOfPages }} <button @click="goToNext">Next</button> </div> </div> </div> </template> <style scoped lang="scss"> .container-list-characters { margin-top: 1rem; display: flex; flex-direction: column; place-items: center; gap: 1rem; } #characters-list { width: 100%; display: grid; gap: 0.5rem; grid-template-columns: repeat(auto-fill, minmax(50px, 1fr)); grid-template-rows: repeat(2, 50px); li { list-style: none; width: 100%; height: 50px; border: 1px solid white; button { cursor: pointer; width: 100%; height: 100%; border: 0; img { width: 100%; height: 100%; } } } } </style>
import {Component, OnInit, ViewChild} from '@angular/core'; import {MatSidenav} from '@angular/material/sidenav'; import {Student} from './student/student.model'; import {MatTable, MatTableDataSource, MatTableModule} from '@angular/material/table'; import {SelectionModel} from '@angular/cdk/collections'; import {Observable} from 'rxjs'; import {FormControl} from '@angular/forms'; import {map, startWith} from 'rxjs/operators'; import {MatPaginator} from '@angular/material/paginator'; import {MatSort} from '@angular/material/sort'; const STUDENTS: Student[] = [ {id: 's257009', name: 'Caso', firstName: 'Paola', group: 'TeamProva'}, {id: 's256665', name: 'Michele', firstName: 'Greco', group: 'TeamProva'}, {id: 's238906', name: 'Bruno', firstName: 'Alberto', group: 'TeamProva'}, ]; const OPTIONS: Student[] = [ {id: 's253309', name: 'Burlacu', firstName: 'Iustin', group: ''}, {id: 's247948', name: 'Buffo', firstName: 'Matteo', group: ''}, {id: 's222767', name: 'Massafra', firstName: 'Christian', group: 'TeamProva2'}, {id: 's236564', name: 'Lamberti', firstName: 'Giovanni', group: ''}, {id: 's378748', name: 'Agosta', firstName: 'Anna', group: ''} ]; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit{ title = 'lab4'; @ViewChild('MatTable') table: MatTable<Student>; @ViewChild('sidenav') sidenav: MatSidenav; @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator; @ViewChild(MatSort, {static: true}) sort: MatSort; colsToDisplay: string[] = ['select', 'id', 'firstName', 'name', 'group']; students = new MatTableDataSource<Student>(STUDENTS); selection = new SelectionModel<Student>(true, []); studentCtrl = new FormControl(); options: Observable<Student[]>; studentToAdd: Student; constructor() { this.options = this.studentCtrl.valueChanges .pipe( startWith(''), map(value => typeof value === 'string' ? value : value.name), map(student => student ? this._filterStudents(student) : OPTIONS.slice()) ); } ngOnInit() { this.students.paginator = this.paginator; this.students.sort = this.sort; } toggleForMenuClick(){ this.sidenav.opened ? this.sidenav.close() : this.sidenav.open(); } /** Whether the number of selected elements matches the total number of rows. */ isAllSelected() { const numSelected = this.selection.selected.length; const numRows = this.students.data.length; return numSelected === numRows; } /** Selects all rows if they are not all selected; otherwise clear selection. */ masterToggle() { this.isAllSelected() ? this.selection.clear() : this.students.data.forEach(row => this.selection.select(row)); } /** The label for the checkbox on the passed row */ checkboxLabel(row?: Student): string { if (!row) { return `${this.isAllSelected() ? 'select' : 'deselect'} all`; } return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.id + 1}`; } deleteSelected(){ const filteredStudents: Student[] = []; this.students.data.forEach(s => { if (!this.selection.isSelected(s)) { filteredStudents.push(s); }}); delete this.students; this.students = new MatTableDataSource<Student>(filteredStudents); this.selection.clear(); } private _filterStudents(value: string): Student[] { const filterValue = value.toLowerCase(); return OPTIONS.filter(s => s.name.toLowerCase().indexOf(filterValue) === 0); } displayOptions(student: Student): string { return student ? student.name + ' ' + student.firstName + ' (' + student.id + ')' : ''; } addStudent(student: Student){ this.studentToAdd = student; } commitStudent() { if (this.studentToAdd != null && !this.students.data.includes(this.studentToAdd)) { this.students.data.push(this.studentToAdd); const index = OPTIONS.indexOf(this.studentToAdd, 0); if (index > -1) { OPTIONS.splice(index, 1); } this.students._updateChangeSubscription(); } } }
#include "main.h" /** * multiply_digit - multiplies two numbers * @num1: first number * @num2: second number * * Retun: the result of the multiplication */ int multiply_digit(char num1, char num2) { return ((num1 - '0') * (num2 - '0')); } /** * print_number - prints a number * @num: a pointer to the number * Return: void */ void print_number(char *num) { int i = 0; while (num[i] == '0' && num[i + 1] != '\0') i++; while (num[i] != '\0') { _putchar(num[i]); i++; } } /** * reverse_string - reverses a string * @str: a pointer to the string * @length: the length of the string * Return: void */ void reverse_string(char *str, int length) { int start = 0; int end = length - 1; while (start < end) { char temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } /** * multiply_and_print - multiplies and prints numbers * @num1: a pointer to first number * @num2: a pointer to second number * Return: void */ void multiply_and_print(char *num1, char *num2) { int len1 = 0, len2 = 0; int result_size, i, j, sum, product, carry = 0; char *result; while (num1[len1] != '\0') len1++; while (num2[len2] != '\0') len2++; result_size = len1 + len2; result = malloc(result_size + 1); if (result == NULL) { _putchar('E'); _putchar('r'); _putchar('r'); _putchar('o'); _putchar('r'); _putchar('\n'); return; } for (i = 0; i < result_size; i++) result[i] = '0'; for (i = len1 - 1; i >= 0; i--) { carry = 0; for (j = len2 - 1; j >= 0; j--) { product = multiply_digit(num1[i], num2[j]); sum = result[i + j + 1] - '0' + product + carry; carry = sum / 10; result[i + j + 1] = sum % 10 + '0'; } result[i + j + 1] += carry; } result[result_size] = '\0'; print_number(result); _putchar('\n'); free(result); } /** * main - Entry point * @argc: the argument counter * @argv: a pointer to the arguments * Return: Always 0 (Success) */ int main(int argc, char *argv[]) { char *num1; char *num2; int i; if (argc != 3) { _putchar('E'); _putchar('r'); _putchar('r'); _putchar('o'); _putchar('r'); _putchar('\n'); _putchar(0x00); return (98); } num1 = argv[1]; num2 = argv[2]; for (i = 0; num1[i] != '\0'; i++) { if (!isdigit(num1[i])) { _putchar('E'); _putchar('r'); _putchar('r'); _putchar('o'); _putchar('r'); _putchar('\n'); _putchar(0x00); return (98); } } for (i = 0; num2[i] != '\0'; i++) { if (!isdigit(num2[i])) { _putchar('E'); _putchar('r'); _putchar('r'); _putchar('o'); _putchar('r'); _putchar('\n'); _putchar(0x00); return (98); } } multiply_and_print(num1, num2); _putchar(0x00); return (0); }
# summary 1. Form merupakan widget untuk menampung data inputtan user dan dapat memuat beberapa komponen lain seperti TextFormField/TextField dan juga ElevatedButton untuk megolah data inputannya. Form digunakan melalui stateful widget dan state/keadaan form disimpan melalui ```GlobalKey<FormState>```. - Contoh penggunaan Form dalam stateful widget ```dart class MyFormWidget extends StatefulWidget { @override _MyFormWidgetState createState() => _MyFormWidgetState(); } class _MyFormWidgetState extends State<MyFormWidget> { final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Form( key: _formKey, child: Column( children: [ TextFormField( // ), TextFormField( // ), ElevatedButton( onPressed: () { // }, child: Text('Submit'), ), ], ), ); } } ``` 2. Ada beberapa cara untuk menerima nilai inputtan dari user, kita dapat menggunakan widget seperti TextField untuk menerima data ketikkan dari user, Radio untuk memberikan user opsi memilih yang hanya dapat dipilih satu, Checkbox untuk memberikan user opsi yang dapat dipilih lebih dari satu, dan masih banyak lagi seperti Toggle, DropdownButton maupun Switch. Penggunaan masing-masing widget ditentukan dari studi kasus dan jenis data apa yang ingin diambil serta metodenya. - Contoh penggunaan TextField dengan menggunakan controller untuk menerima datanya ```dart class MyTextField extends StatefulWidget { @override _MyTextFieldState createState() => _MyTextFieldState(); } class _MyTextFieldState extends State<MyTextField> { TextEditingController _controller = TextEditingController(); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return TextField( controller: _controller, decoration: InputDecoration( labelText: 'Name', hintText: 'Type your name here ....', ), onChanged: (text) { // }, ), } } ``` 3. Untuk mengolah data yang sudah diambil dari widget penerima inputtan, kita dapat menggunakan button seperti ElevatedButton ataupun IconButton yang berbentuk seperti icon namun bisa ditekan dan menjalankan perintah yang berada di fungsi callback onPressed. - Contoh penggunaan ElevatedButton ```dart class MyElevatedButton extends StatelessWidget { @override Widget build(BuildContext context) { return ElevatedButton( onPressed: () { print('Button pressed'); }, child: Text('Submit'), style: ElevatedButton.styleFrom( primary: Colors.blue, onPrimary: Colors.white, padding: EdgeInsets.all(14), ), ); } } ```
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable() export class CartService { private cartItemsSubject = new BehaviorSubject<any[]>([]); cartItems$ = this.cartItemsSubject.asObservable(); private localStorageKey = 'cartItems'; constructor() { const storedCartItems = localStorage.getItem(this.localStorageKey); if (storedCartItems) { this.cartItemsSubject.next(JSON.parse(storedCartItems)); } } addToCart(product: any) { const currentCartItems = this.cartItemsSubject.value; const existingProductIndex = currentCartItems.findIndex( (item) => item.productId === product.productId, ); if (existingProductIndex !== -1) { const updatedCartItems = [...currentCartItems]; updatedCartItems[existingProductIndex].quantity += 1; this.updateCartItems(updatedCartItems); } else { const updatedCartItems = [ ...currentCartItems, { ...product, quantity: 1 }, ]; this.updateCartItems(updatedCartItems); } } removeFromCart(productId: number) { const currentCartItems = this.cartItemsSubject.value; const existingProductIndex = currentCartItems.findIndex( (item) => item.productId === productId, ); if (existingProductIndex !== -1) { const updatedCartItems = [...currentCartItems]; if (updatedCartItems[existingProductIndex].quantity > 1) { updatedCartItems[existingProductIndex].quantity -= 1; } else { updatedCartItems.splice(existingProductIndex, 1); } this.updateCartItems(updatedCartItems); } } private updateCartItems(updatedCartItems: any[]) { this.cartItemsSubject.next(updatedCartItems); localStorage.setItem( this.localStorageKey, JSON.stringify(updatedCartItems), ); } }
package gov.gsa.sst.util.data; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * Extracts scenario names from feature files in directory(ies) and from the * specified JSON data file(s). It will then print: * * 1) Unique scenario names collected from all files * 2) Name of file(s) where scenario is found along with a * count of how many times it appears in each file * * The information will help find inconsistencies across feature files and * corresponding data file. * * @param args * path/to/featuresDirectory1, ... ,path/to/featuresDirectoryN * path/to/data1.json, ... ,path/to/dataN.json */ public class ScenarioAuditor { private static Logger logger = LoggerFactory.getLogger(ScenarioAuditor.class); private static Map<String, Scenario> scenarios = new HashMap<>(); private static List<String> dataFiles; public static void main(String[] args) { if (args.length != 2) { throw new IllegalArgumentException("Example Usage: path/to/featuresDir1,path/to/featureDir2 path/to/data1.json,path/to/data2.json"); } String[] featureDirectories = args[0].split(","); for (String featureDir : featureDirectories) { ScenarioAuditor.getScenariosFromFeatures(featureDir); } dataFiles = Arrays.asList(args[1].split(",")); for (String dataFile : dataFiles) { ScenarioAuditor.getScenariosFromData(dataFile); } try { ScenarioAuditor.printCSVReport(); } catch (IOException e) { e.printStackTrace(); } try { ScenarioAuditor.writeReport(); } catch (IOException e) { e.printStackTrace(); } } /** * Generates CSV output file with scenario names and whether or not * they are present in the input file paths. * * Output directory is project folder. * * @throws IOException */ private static void printCSVReport() throws IOException { Path path = Paths.get("scenario-auditor-report.csv"); try (BufferedWriter writer = Files.newBufferedWriter(path); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.EXCEL);) { csvPrinter.print("Scenario Name"); for (String fileName : dataFiles) { csvPrinter.print(fileName); } csvPrinter.println(); Iterator<String> scenarioItr = scenarios.keySet().iterator(); while (scenarioItr.hasNext()) { String scenarioName = scenarioItr.next(); csvPrinter.print(scenarioName); for (String fileNameHeader : dataFiles) { if (scenarios.get(scenarioName).fileNames.containsKey(fileNameHeader)) { csvPrinter.print("X"); } else { csvPrinter.print(""); } } csvPrinter.println(); } } } /** * Write map into JSON to console. * Reference: https://sites.google.com/site/gson/streaming * * @throws IOException */ private static void writeReport() throws IOException { JsonWriter writer = new JsonWriter(new OutputStreamWriter(System.out, "UTF-8")); writer.setIndent(" "); writer.beginArray(); Gson gson = new Gson(); scenarios.forEach((scenarioName, scenario) -> { gson.toJson(scenario, Scenario.class, writer); }); writer.endArray(); writer.close(); } /** * Read JSON data file and add to map * of scenarios. * * @param path */ private static void getScenariosFromData(String path) { try { JsonReader reader = new JsonReader(new FileReader(path)); reader.beginObject(); while (reader.hasNext()) { addScenario(reader.nextName(), path); // Skip nested JSON objects since we're // only interested in scenario names reader.skipValue(); } reader.endObject(); reader.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Read scenarios from feature files and * add to scenario map * * @param path */ private static void getScenariosFromFeatures(String path) { File featurePath = new File(path); FilenameFilter filter = (dir, name) -> { return dir.getAbsolutePath().contains("feature"); }; for (File file : featurePath.listFiles(filter)) { if (file.isDirectory()) { logger.debug("Skipping directory " + file.getName()); continue; } Scanner scanner = null; try { scanner = new Scanner(file); while(scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("Scenario:")) { addScenario(line.replace("Scenario:", "").trim(), file.getName()); } } } catch (IOException e) { e.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } } } } /** * Adds new scenario or update previously * existing scenario. * * @param scenarioName * @param fileName */ private static void addScenario(String scenarioName, String fileName) { if (!scenarios.containsKey(scenarioName)) { // New scenario not found before Scenario scenario = new ScenarioAuditor.Scenario(scenarioName); scenario.fileNames.put(fileName, 1); scenarios.put(scenario.scenarioName, scenario); } else { Scenario existingScenario = scenarios.get(scenarioName); if (existingScenario.fileNames.containsKey(fileName)) { int count = existingScenario.fileNames.get(fileName); existingScenario.fileNames.replace(fileName, ++count); } else { existingScenario.fileNames.put(fileName, 1); } } } /** * Represents a scenario, the feature and/or * data files where it is found, and the number * of times it is found in each file. * */ static class Scenario { String scenarioName; Map<String, Integer> fileNames = new HashMap<>(); public Scenario(String name) { this.scenarioName = name; } } }
# MNIST-classification-using-CNN The repository contains the code for classifying the Images of handwritten digits using the Convolutional Neural Network(CNN) and Dropouts approach. ## Dataset Loading the MNIST data set directly using TensorFlow API. ```python mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() ``` First, we check the distribution of classes in the training set. ![data_distribution](https://github.com/Mayurwaghela1997/MNIST-classification-using-CNN/blob/main/Images/Class_distribution.JPG) We can see there is no class imbalance problem in the training set. Next, Let's have a look at a random image and label for that image from the training set. ![Sample_data](https://github.com/Mayurwaghela1997/MNIST-classification-using-CNN/blob/main/Images/Sample_data.JPG) ## Normalizing & Reshaping the Images The TensorFlow Conv2D layer expects the data in 4 dimensions (w,x,y,z) tensor, but the current dimension for of data is 3. ```python x_train.reshape(x_train.shape[0], x_train.shape[1], x_train.shape[2], 1) ``` Once the data is reshaped, we must normalize it to have data on a standard scale of 0 to 1. We divide the data with 255 because the RGB values of the image range from 0 to 255. ```python x_train / 255.0 ``` ## One-Hot Encoding of the Labels The label ranges from 0 to 9. In order to make a classification, the model expects the data in the form of encodings. We use TensorFlow one-hot encoding method to encode the Labels. For e.g. ```python Label_before_encoding = 8 Label_after_encoding = [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0] ``` ## Model Summary & Training The below image represents the architecture of the sequential model. ![model](https://github.com/Mayurwaghela1997/MNIST-classification-using-CNN/blob/main/Images/model_summary.JPG) Here, we use Max pooling to reduce the computation and increase the training speed. We also use Dropout, where we randomly nullify neurons to avoid overfitting of data. For training the model, we use an 80/20 split of training data and use EarlyStopping callback to stop training when loss doesn't change for 3 Epochs. The below Image represents the training history of the model. ![history](https://github.com/Mayurwaghela1997/MNIST-classification-using-CNN/blob/main/Images/Training_history.JPG) ## Evaluating the model The model was evaluated on unseen data and achieved 98.94% Accuracy. The below image represents the confusion matrix of the evaluation. ![confusion_matrix](https://github.com/Mayurwaghela1997/MNIST-classification-using-CNN/blob/main/Images/Confusion_matrix.JPG)
<template> <el-container class="home-container"> <!-- ๅคด้ƒจๅŒบๅŸŸ --> <el-header> <div> <el-avatar v-bind:src="this.avatar"></el-avatar> <span>ๅšๅฎขๅŽๅฐ็ฎก็†</span> </div> <el-button type="info" @click="returnHome">้€€ๅ‡บ</el-button> </el-header> <!-- ้กต้ขไธปไฝ“ๅŒบๅŸŸ --> <el-container> <!-- ไพง่พนๆ ๏ผŒ็‚นๅ‡ปๆ”ถ็ผฉ--> <el-aside :width="isCollapse ? '64px' : '200px'"> <div class="toggle-button" @click="toggleCollapse">|||</div> <!-- ไพง่พนๆ ่œๅ•ๅŒบๅŸŸ --> <el-menu background-color="#333744" text-color="#fff" active-text-color="#409EFF" unique-opened :collapse="isCollapse" :collapse-transition="false" router :default-active="activePath"> <!-- ไธ€็บง่œๅ• --> <el-submenu :index="item.id + ''" v-for="item in menulist" :key="item.id"> <!-- ไธ€็บง่œๅ•็š„ๆจกๆฟๅŒบๅŸŸ --> <template slot="title"> <!-- ๅ›พๆ ‡ --> <i :class="iconsObj[item.id]"></i> <!-- ๆ–‡ๆœฌ --> <span>{{item.authName}}</span> </template> <!-- ไบŒ็บง่œๅ• --> <el-menu-item :index="subItem.path" v-for="subItem in item.children" :key="subItem.id" @click="saveNavState('/' + subItem.path)"> <template slot="title"> <!-- ๅ›พๆ ‡ --> <i v-bind:class="subItem.icon"></i> <!-- ๆ–‡ๆœฌ --> <span>{{subItem.authName}}</span> </template> </el-menu-item> </el-submenu> </el-menu> </el-aside> <!-- ๅณไพงๅ†…ๅฎนไธปไฝ“ --> <el-main> <!-- ่ทฏ็”ฑๅ ไฝ็ฌฆ --> <router-view></router-view> </el-main> </el-container> </el-container> </template> <script> // import { initDynamicRoutes } from '../router' export default { data () { return { // ๅทฆไพง่œๅ•ๆ•ฐๆฎ menulist: [ { id: 101, authName: '็”จๆˆท็ฎก็†', path: null, children: [ { id: 203, authName: 'ๆŸฅ็œ‹็”จๆˆท', path: '/adminHome/Users', icon: 'el-icon-view', children: [] } ] }, { id: 201, authName: 'ๅšๅฎข็ฎก็†', path: null, children: [ { id: 203, authName: 'ๆŸฅ็œ‹ๅšๅฎข', path: '/adminHome/Blogs', icon: 'el-icon-view', children: [] }, { id: 205, authName: 'ๅˆ†็ฑป็ฎก็†', path: '/adminHome/Types2', icon: 'el-icon-s-operation', children: [] } ] }, { id: 501, authName: 'ๆ•ฐๆฎ็ปŸ่ฎก', path: null, children: [ { id: 502, icon: 'el-icon-s-data', authName: '็‚น่ตžๆ•ฐ็ปŸ่ฎก', path: '/adminHome/thumbChart', children: [] }, { id: 503, icon: 'el-icon-s-data', authName: 'ๆต่งˆๆ•ฐ็ปŸ่ฎก', path: '/adminHome/viewChart', children: [] }, { id: 504, icon: 'el-icon-s-data', authName: 'ๆ€ป็ปŸ่ฎก', path: '/adminHome/Report2', children: [] } ] },{ id: 601, authName: '่ฏ„่ฎบ็ฎก็†', path: '/adminHome/Comments', icon: 'el-icon-s-comment', children: [{ id: 601, authName: '่ฏ„่ฎบ็ฎก็†', path: '/adminHome/Comments', icon: 'el-icon-s-comment', }] } ], iconsObj: { 101: 'el-icon-s-custom', 201: 'el-icon-edit-outline', 301: 'iconfont icon-tijikongjian', 401: 'iconfont icon-baobiao', 501: 'el-icon-s-marketing', 601:'el-icon-s-comment' }, // ๆ˜ฏๅฆๆŠ˜ๅ  isCollapse: false, // ่ขซๆฟ€ๆดป็š„้“พๆŽฅๅœฐๅ€ activePath: '', nickname: '', avatar: '' } }, created () { this.activePath = window.sessionStorage.getItem('activePath') this.getUser() }, methods: { getUser () { this.user = window.sessionStorage.getItem('user') if (this.user != null) { this.nickname = JSON.parse(this.user).nickname this.avatar = JSON.parse(this.user).avatar } }, returnHome () { this.$router.push('/Login') sessionStorage.removeItem('admin_blogid') }, // ็‚นๅ‡ปๆŒ‰้’ฎ๏ผŒๅˆ‡ๆข่œๅ•็š„ๆŠ˜ๅ ไธŽๅฑ•ๅผ€ toggleCollapse () { this.isCollapse = !this.isCollapse }, // ไฟๅญ˜้“พๆŽฅ็š„ๆฟ€ๆดป็Šถๆ€ saveNavState (activePath) { window.sessionStorage.setItem('activePath', activePath) this.activePath = activePath } }, mounted: function() { if (location.href.indexOf("#reloaded") == -1) { location.href = location.href + "#reloaded"; location.reload(); } }, } </script> <style lang="less" scoped> .home-container { margin: 0 auto; max-width:2300px; } .el-header { background-color: #373d41; display: flex; justify-content: space-between; padding-left: 0; align-items: center; color: #fff; font-size: 20px; > div { display: flex; align-items: center; span { margin-left: 15px; } } } .el-aside { background-color: #333744; .el-menu { border-right: none; } } .el-main { background-color: #eaedf1; } .iconfont2 { margin-right: 10px; } .toggle-button { background-color: #4a5064; font-size: 10px; line-height: 24px; color: #fff; text-align: center; letter-spacing: 0.2em; cursor: pointer; } </style>
"use client"; import React, { useEffect, useState, ChangeEvent, lazy, Suspense } from "react"; import { useUser } from "@clerk/clerk-react"; import LoadingSpinner from "@/components/ui/LoadingSpinner"; import Alert from "@/components/ui/Alert"; const VideoConferencingRoom = lazy(() => import("./VideoConferencingRoom")); const Form = lazy(() => import("./Form")); // Lazy import for the Form component interface FormData { location: string; bookedExam: string; examDate: string; } interface Step { id: number; question: string; key: keyof FormData; } const steps: Step[] = [ { id: 1, question: "Where do you belong?", key: "location" }, { id: 2, question: "Have you booked your TOEFL exam?", key: "bookedExam" }, { id: 3, question: "When are you planning to give TOEFL?", key: "examDate" }, ]; export default function App() { const [showAlert, setShowAlert] = useState(false); const [stage, setStage] = useState<'home' | 'form' | 'video'>('home'); const [onlineCount, setOnlineCount] = useState(23044); const { isSignedIn } = useUser(); useEffect(() => { const interval = setInterval(() => { setOnlineCount((prevCount) => prevCount + Math.floor(Math.random() * 10) + 1); }, 2000); return () => clearInterval(interval); // Cleanup interval on component unmount }, []); const handleButtonClick = () => { if (!isSignedIn) { setShowAlert(true); return; } else setStage('form'); }; const handleCloseAlert = () => { setShowAlert(false); }; return ( <> {showAlert && ( <Alert message="Please log in to continue" type="warning" onClose={handleCloseAlert} /> )} {stage === 'home' && ( <div className="z-[0] relative overflow-hidden rounded-xl m-2 flex items-center min-h-screen bg-gradient-to-r from-pink-500 via-red-500 to-yellow-500"> <div className="absolute inset-0 z-0"> <img src="/assets/video-confrencing-bg.jpg" alt="Background" className="w-full h-full object-cover blur" /> <div className="absolute inset-0 bg-black opacity-50"></div> </div> <div className="relative text-white max-w-3xl p-10"> <h1 className="lg:text-7xl md:text-5xl font-bold mb-4 text-4xl"> Meet, chat, and study with students from all over the world ๐ŸŒ </h1> <p className="text-lg mb-10 md:text-2xl"> Join the largest global student community online and say goodbye to lack of motivation. </p> <button onClick={handleButtonClick} className="bg-white text-pink-500 font-bold py-2 px-4 rounded-full mb-7 animate-bounce"> Study Together now </button> <div className="flex items-center mb-4"> <span className="bg-green-500 text-white px-2 py-1 rounded-full">100% free!</span> <span className="ml-2 text-white animate-pulse">{onlineCount} Online</span> </div> </div> </div> )} {stage === 'form' && ( <Suspense fallback={<div><LoadingSpinner /></div>}> <Form setStage={setStage} /> </Suspense> )} {stage === 'video' && ( <div style={{ backgroundImage: `url(/assets/lib-bg.jpg)`, backgroundSize: 'cover', backgroundPosition: 'center', width: '100%', height: '100vh', borderRadius: '0.5rem', padding: '1rem', }} > <Suspense fallback={<div>Loading video conferencing room...</div>}> <VideoConferencingRoom /> </Suspense> </div> )} </> ); }
package com.atguigu.case3; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.retry.ExponentialBackoffRetry; /** * @author Feng * @date 2021/7/10 22:07 * <p> * Curator ๆกˆไพ‹ๅฎžๆ“ * Curator ๆ˜ฏไธ€ไธชไธ“้—จ่งฃๅ†ณๅˆ†ๅธƒๅผ้”็š„ๆก†ๆžถ๏ผŒ่งฃๅ†ณไบ†ๅŽŸ็”Ÿ JavaAPI ๅผ€ๅ‘ๅˆ†ๅธƒๅผ้‡ๅˆฐ็š„้—ฎ้ข˜ใ€‚ * ่ฏฆๆƒ…่ฏทๆŸฅ็œ‹ๅฎ˜ๆ–นๆ–‡ๆกฃ๏ผšhttps://curator.apache.org/index.html */ public class CuratorLockTest { public static void main(String[] args) { //ๅˆ›ๅปบๅˆ†ๅธƒๅผ้”1 InterProcessMutex lock1 = new InterProcessMutex(getCuratorFramework(), "/locks"); //ๅˆ›ๅปบๅˆ†ๅธƒๅผ้”1 InterProcessMutex lock2 = new InterProcessMutex(getCuratorFramework(), "/locks"); new Thread(new Runnable() { @Override public void run() { // ่Žทๅ–้”ๅฏน่ฑก try { lock1.acquire(); System.out.println("็บฟ็จ‹ 1 ่Žทๅ–้”"); // ๆต‹่ฏ•้”้‡ๅ…ฅ lock1.acquire(); System.out.println("็บฟ็จ‹ 1 ๅ†ๆฌก่Žทๅ–้”"); Thread.sleep(5 * 1000); lock1.release(); System.out.println("็บฟ็จ‹ 1 ้‡Šๆ”พ้”"); lock1.release(); System.out.println("็บฟ็จ‹ 1 ๅ†ๆฌก้‡Šๆ”พ้”"); } catch (Exception e) { e.printStackTrace(); } } }).start(); new Thread(new Runnable() { @Override public void run() { // ่Žทๅ–้”ๅฏน่ฑก try { lock2.acquire(); System.out.println("็บฟ็จ‹ 2 ่Žทๅ–้”"); // ๆต‹่ฏ•้”้‡ๅ…ฅ lock2.acquire(); System.out.println("็บฟ็จ‹ 2 ๅ†ๆฌก่Žทๅ–้”"); Thread.sleep(5 * 1000); lock2.release(); System.out.println("็บฟ็จ‹ 2 ้‡Šๆ”พ้”"); lock2.release(); System.out.println("็บฟ็จ‹ 2 ๅ†ๆฌก้‡Šๆ”พ้”"); } catch (Exception e) { e.printStackTrace(); } } }).start(); } private static CuratorFramework getCuratorFramework() { //้‡่ฏ•็ญ–็•ฅ๏ผŒๅˆ่ฏ•ๆ—ถ้—ด 3 ็ง’๏ผŒ้‡่ฏ• 3 ๆฌก RetryPolicy policy = new ExponentialBackoffRetry(3000, 3); CuratorFramework client = CuratorFrameworkFactory.builder() .connectString("node1:2181,node2:2181") .connectionTimeoutMs(2000) .sessionTimeoutMs(2000) .retryPolicy(policy).build(); //ๅฏๅŠจๅฎขๆˆท็ซฏ client.start(); System.out.println("zookeeper ๅฏๅŠจๆˆๅŠŸไบ†๏ผ"); return client; } }
import React, { Suspense } from 'react'; import { StyledMain } from './styles'; import { Routes, Route } from 'react-router-dom'; import { NavBar } from '../../pages/nav_bar/NavBar'; import { Preloader } from '../../ui/preloader/Preloader'; import { Navigate } from 'react-router-dom'; const MessagesContainer = React.lazy(() => import('../../pages/messages/MessagesContainer') ); const ProfileContainer = React.lazy(() => import('../../pages/profile/ProfileContainer') ); const News = React.lazy(() => import('../../pages/news/News') ); const Music = React.lazy(() => import('../../pages/music/Music') ); const Settings = React.lazy(() => import('../../pages/settings/Settings') ); const Users = React.lazy(() => import('../../pages/users/Users') ); const Login = React.lazy(() => import('../../pages/login/Login') ); export const Main = () => { return ( <StyledMain> <NavBar /> <Suspense fallback={ <div> <Preloader /> </div> } > <Routes> <Route exact path="/" element={<Navigate to="/profile" />} /> <Route path="/profile/:userId?" element={<ProfileContainer />} /> <Route path="/messages/*" element={<MessagesContainer />} /> <Route path="/users/*" element={<Users />} /> <Route path="/news/*" element={<News />} /> <Route path="/music/*" element={<Music />} /> <Route path="/settings/*" element={<Settings />} /> <Route path="/login/*" element={<Login />} /> </Routes> </Suspense> </StyledMain> ); };
// // SwiftUIWebview.swift // AncestralWatch // // Created by Jakob Hartman on 12/20/22. // import Foundation import SwiftUI import WebKit struct SwiftUIWebView: UIViewRepresentable { typealias UIViewType = WKWebView let webView: WKWebView init(url: String, callback: @escaping () -> Void) { webView = WKWebView(frame: .zero) webView.isLoaded = callback webView.navigationDelegate = self.webView webView.load(URLRequest(url: URL(string: url)!)) } func getUrl() -> String { return webView.getUrl() } func makeUIView(context: Context) -> WKWebView { webView } func updateUIView(_ uiView: WKWebView, context: Context) { } } extension WKWebView: WKNavigationDelegate { struct Holder { static var callback: () -> Void = {} } var isLoaded: () -> Void { set(callback){ Holder.callback = callback } get{ return Holder.callback } } private var httpCookieStore: WKHTTPCookieStore { return WKWebsiteDataStore.default().httpCookieStore} func getCookies(for domain: String? = nil, completion: @escaping ([String : Any])->()) { var cookieDict = [String : AnyObject]() httpCookieStore.getAllCookies { cookies in for cookie in cookies { if let domain = domain { if cookie.domain.contains(domain) { cookieDict[cookie.name] = cookie.properties as AnyObject? } } else { cookieDict[cookie.name] = cookie.properties as AnyObject? } } completion(cookieDict) } } func getUrl() -> String { if let url = self.url?.absoluteString { return url } return "" } public func webView(_ webView: WKWebView, didFinish: WKNavigation){ let ts = Date().timeIntervalSince1970 if(getUrl().contains("familysearch.org")){ webView.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in let defaults = UserDefaults.standard for cookie in cookies { switch(cookie.name){ case "fssessionid": defaults.set(cookie.value, forKey: "AccessToken") //ten mins from now although realistally its about 15mins according to my sources defaults.set(ts + (1000 * 10 * 60 * 10), forKey: "Expiration") Holder.callback() break; default: continue; } } } } } public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { decisionHandler(.allow) } }
from abc import ABC, abstractmethod from datetime import datetime class Szoba(ABC): def __init__(self, ar, szobaszam): self.ar = ar self.szobaszam = szobaszam @abstractmethod def leiras(self): pass class EgyagyasSzoba(Szoba): def __init__(self, szobaszam, meret): super().__init__(ar=45000, szobaszam=szobaszam) self.meret = meret def leiras(self): return f"Egyรกgyas szoba {self.szobaszam}-as sorszรกmmal. Az รกra: {self.ar} Ft. egy รฉjszakรกra. Mรฉrete: {self.meret}." def __repr__(self): return f"Egyรกgyas szoba(szobaszรกm={self.szobaszam}, mรฉret='{self.meret}')" class KetagyasSzoba(Szoba): def __init__(self, szobaszam, meret): super().__init__(ar=70000, szobaszam=szobaszam) self.meret = meret def leiras(self): return f"Kรฉtรกgyas szoba {self.szobaszam}-as sorszรกmmal. Az รกra: {self.ar} Ft. egy รฉjszakรกra. Mรฉrete: {self.meret}." def __repr__(self): return f"Kรฉtรกgyas szoba(szobaszam={self.szobaszam}, mรฉret='{self.meret}')" class Szalloda: def __init__(self, nev): self.nev = nev self.szobak = [] self.foglalasok = [] def add_szoba(self, szoba): self.szobak.append(szoba) def szobak_szama(self): return len(self.szobak) def szoba_foglalas(self, szobaszam, datum): try: foglalas_datum = datetime.strptime(datum, "%Y-%m-%d") today = datetime.today() if foglalas_datum <= today: print("Ez a dรกtum mรกr elmรบlt!") return None except ValueError: print("Kรฉrem adjon meg egy รฉrvรฉnyes dรกtumot") return None for foglalas in self.foglalasok: if foglalas.szoba.szobaszam == szobaszam and foglalas.datum == datum: print("A megadott szoba mรกr foglalt ezen a dรกtumon.") return None for szoba in self.szobak: if szoba.szobaszam == szobaszam: foglalas = Foglalas(szoba, datum) self.foglalasok.append(foglalas) return foglalas.szoba.ar print("Nincs ilyen szoba a szรกllodรกban!") return None def foglalas_lemondas(self, szobaszam, datum): for foglalas in self.foglalasok: if foglalas.szoba.szobaszam == szobaszam and foglalas.datum == datum: self.foglalasok.remove(foglalas) return True return False def foglalasok_listazasa(self): for foglalas in self.foglalasok: print(f"Foglalรกsok: {foglalas.szoba.szobaszam}, Dรกtum: {foglalas.datum}") class Foglalas: def __init__(self, szoba, datum): self.szoba = szoba self.datum = datum def __repr__(self): return f"Foglalt szoba: {self.szoba}, dรกtum:{self.datum}" def main(): szalloda = Szalloda("Isten Kirรกly Hotel") szalloda.add_szoba(EgyagyasSzoba(101, "Kicsi")) szalloda.add_szoba(KetagyasSzoba(102, "Nagy")) szalloda.add_szoba(EgyagyasSzoba(103, "Kicsi")) szalloda.szoba_foglalas(101, "2024-05-30") szalloda.szoba_foglalas(103, "2024-06-12") szalloda.szoba_foglalas(102, "2024-06-04") szalloda.szoba_foglalas(101, "2024-08-20") szalloda.szoba_foglalas(101, "2024-07-24") while True: print("\nVรกlasszon mลฑveletet:") print("1. Foglalรกs") print("2. Lemondรกs") print("3. Foglalรกsok listรกzรกsa") print("4. Kilรฉpรฉs") valasztas = input("Kรฉrem vรกlasszon:") if valasztas == "1": szobaszam = int(input("Kรฉrem adja meg a szoba szรกmรกt: ")) datum = input("Kรฉrem adja meg a foglalรกs dรกtumรกt:") szalloda.szoba_foglalas(szobaszam, datum) print("Foglalรกs sikeren rรถgzรญtve!") elif valasztas == "2": szobaszam = int(input("Kรฉrem adja meg a szoba sorszรกmรกt: ")) datum = input("Kรฉrem adja meg a foglalรกs dรกtumรกt: ") if szalloda.foglalas_lemondas(szobaszam, datum): print("A foglalรกsรกt sikeresen lemondta!") else: print("Nem talรกlhatรณ ilyen foglalรกs.") elif valasztas == "3": szalloda.foglalasok_listazasa() elif valasztas == "4": print("Kilรฉpรฉs") break else: print("Ez az opciรณ nem elรฉrhetล‘, kรฉrem vรกlasszon รบjra!") ''' szalloda = Szalloda("Isten Kirรกly Hotel") szalloda.add_szoba(EgyagyasSzoba(101, "Kicsi")) szalloda.add_szoba(KetagyasSzoba(102, "Nagy")) szalloda.add_szoba(EgyagyasSzoba(103, "Kicsi")) foglalas1 = szalloda.szoba_foglalas(101, "2024-06-23") foglalas2 = szalloda.szoba_foglalas(102, "2024-07-25") foglalas3 = szalloda.szoba_foglalas(101, "2024-07-26") #szalloda.foglalas_lemondas(101, "2024-06-23") szalloda.foglalas_lemondas(102, "2024-07-25") print(f"{szalloda.nev} szรกllodรกban รถsszesen {szalloda.szobak_szama()} szoba van.") print(foglalas1) print(foglalas2) print(szalloda.foglalasok) szalloda.foglalasok_listazasa() ''' if __name__ == "__main__": main()
// Fill out your copyright notice in the Description page of Project Settings. #include "Grabber.h" #include "Engine/World.h" #include "DrawDebugHelpers.h" // Sets default values for this component's properties UGrabber::UGrabber() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. PrimaryComponentTick.bCanEverTick = true; // ... } // Called when the game starts void UGrabber::BeginPlay() { Super::BeginPlay(); UPhysicsHandleComponent* PhysicsHandle = GetPhysicsHandler(); if (PhysicsHandle != nullptr) { //PhysicsHandle->GetName(); UE_LOG(LogTemp, Display, TEXT("PhysicsHandle Name: %s"), *PhysicsHandle->GetName()); } else { UE_LOG(LogTemp, Warning, TEXT("Warning! PhysicsHandle Nullptr")) } // ... } // Called every frame void UGrabber::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); UPhysicsHandleComponent* PhysicsHandle = GetPhysicsHandler(); if (PhysicsHandle && PhysicsHandle->GetGrabbedComponent()) { FVector TargetLocation = GetComponentLocation() + GetForwardVector() * HoldDistance; PhysicsHandle->SetTargetLocationAndRotation(TargetLocation, GetComponentRotation()); } } void UGrabber::Grab() { UPhysicsHandleComponent* PhysicsHandle = GetPhysicsHandler(); FHitResult HitResult; //Potenitally make a bool for getgrabbleinreach if its used more than once in grab if (PhysicsHandle && GetGrabbleInReach(HitResult)) { UPrimitiveComponent* HitComponent = HitResult.GetComponent(); HitComponent->SetSimulatePhysics(true); HitComponent->WakeAllRigidBodies(); AActor* HitActor = HitResult.GetActor(); HitActor->Tags.Add("Grabbed"); HitActor->DetachFromActor(FDetachmentTransformRules::KeepWorldTransform); PhysicsHandle->GrabComponentAtLocationWithRotation(HitResult.GetComponent(), NAME_None, HitResult.ImpactPoint, GetComponentRotation()); } } bool UGrabber::GetGrabbleInReach(FHitResult& OutHitResult) const { UWorld* World = GetWorld(); FVector Start = GetComponentLocation(); FVector End = GetComponentLocation() + GetForwardVector() * MaxGrabDist; FString HitName; //DrawDebugLine(World, Start, End, FColor::Red); //DrawDebugSphere(World, End, 10, 12, FColor::Blue, false, 5); FCollisionShape Sphere = FCollisionShape::MakeSphere(GrabRadius); bool OutHasHit = World->SweepSingleByChannel(OutHitResult, Start, End, FQuat::Identity, ECC_GameTraceChannel2, Sphere); return OutHasHit; } void UGrabber::Release() { UPhysicsHandleComponent* PhysicsHandle = GetPhysicsHandler(); if (PhysicsHandle && PhysicsHandle->GetGrabbedComponent()) { PhysicsHandle->GetGrabbedComponent()->WakeAllRigidBodies(); PhysicsHandle->GetGrabbedComponent()->GetOwner()->Tags.Remove("Grabbed"); PhysicsHandle->ReleaseComponent(); } } UPhysicsHandleComponent* UGrabber::GetPhysicsHandler() const { UPhysicsHandleComponent* Result = GetOwner()->FindComponentByClass<UPhysicsHandleComponent>(); if (Result == nullptr) { UE_LOG(LogTemp, Error, TEXT("Grabber Requires a UPhysicsHandlerComponent")); } return Result; }
from abc import ABC, abstractmethod class Notification(ABC): def __init__(self, notification_id, creation_date, content): self.__notification_id = notification_id self.__creation_date = creation_date self.__content = content def send_notification(self): None class PostalNotification(Notification): def __init__(self, notification_id, creation_date, content, address): super().__init__(notification_id, creation_date, content) self.__address = address class EmailNotification(Notification): def __init__(self, notification_id, creation_date, content, email): super().__init__(notification_id, creation_date, content) self.__email = email
%This work is licensed under the Creative Commons License Attribution 4.0 International (CC-BY 4.0) %https://creativecommons.org/licenses/by/4.0/legalcode \documentclass[rgb]{standalone} \usepackage{tikz} \usepackage{pgfplots} \usepgfplotslibrary{patchplots} \definecolor{myorange}{hsb}{0.0833, 1, 0.8} \definecolor{mygreen}{hsb}{0.3333, 1, 0.8} \definecolor{myblue}{hsb}{0.5833, 1, 0.8} \definecolor{mymagenta}{hsb}{0.8333, 1, 0.8} \begin{document} \begin{tikzpicture}[font=\Large] \begin{axis}[scale=2.5,clip=false, hide axis, view={45}{15}, xmin=-3, xmax=3, ymin=-3, ymax=3, zmin=-2, zmax=2, mesh/interior colormap= {interior}{color=(gray) color=(gray)}, colormap= {exterior}{color=(lightgray) color=(lightgray)}, samples=40, samples y=80, z buffer=sort, ] % surface cone: x^2+y^2=z^2 % plane hyperbola (blue): x=3/4 % plane ellipse (orange): z=-3/5(1+x) % plane parabola (green): z= 1-x \draw[very thick, dashed, myblue] (axis cs:3/4,-3,-2) -- (axis cs:3/4,3,-2); \draw[very thick, dashed, myorange] (axis cs:-1,3,0) -- (axis cs:-1,-3,0); \addplot3[surf,patch, domain=-2:2,y domain=0:360] ({x*cos(y)},{x*sin(y)},{x}); \addplot3 [ultra thick, smooth, patch, thick, myblue,domain={-sqrt(55)/4}:{sqrt(55)/4}, samples = 100, samples y=0] ( {3/4}, {x}, {(9/16+x^2)^(1/2)}); \addplot3 [ultra thick, smooth, patch, thick, myblue,domain={-sqrt(55)/4}:{sqrt(55)/4}, samples = 100, samples y=0] ( {3/4}, {x}, {-(9/16+x^2)^(1/2)}); \addplot3 [ultra thick, smooth, patch, thick, myorange,domain=0:360, samples = 100, samples y=0] ( {15/16*cos(x)+9/16}, {3/4*sin(x)}, {-15/16-9/16*cos(x)}); \addplot3 [ultra thick, smooth, patch, thick, mygreen,domain={-sqrt(3)}:{sqrt(3)}, samples = 100, samples y=0] ( {1/2-1/2*x^2}, {x}, {1/2+1/2*x^2}); \draw[very thick, dashed, myblue] (axis cs:3/4,-3,-2) -- (axis cs:3/4,-3,2) -- (axis cs:3/4,3,2) -- (axis cs:3/4,3,-2); \draw[very thick, dashed, myorange] (axis cs:-1,-3,0) -- (axis cs:7/3,-3,-2) -- (axis cs:7/3,3,-2) -- (axis cs:-1,3,0); \draw[very thick, dashed, mygreen] (axis cs:-1,-3,2) -- (axis cs:-1,3,2) -- (axis cs:{2*sqrt(2)-1},3,{2-2*sqrt(2)}) -- (axis cs:{2*sqrt(2)-1},-3,{2-2*sqrt(2)}) -- cycle; \end{axis} \end{tikzpicture} \end{document}
const API_KEY = "API KEY"; const url = "https://newsapi.org/v2/everything?q="; window.addEventListener('load', () => fetchNews("India")); // Reload / Refresh function reload(){ window.location.reload(); } // Fetch News async function fetchNews(query) { const res = await fetch(`${url}${query}&apiKey=${API_KEY}`); const data = await res.json(); bindData(data.articles); } // Binding data function bindData(articles) { const template = document.getElementById("template"); const cardContainer = document.getElementById("card-container"); cardContainer.innerHTML = ""; articles.forEach(article => { if(!article.urlToImage) return; const cardClone = template.content.cloneNode(true); fillData(cardClone, article); cardContainer.appendChild(cardClone); }); } // Filling data function fillData(cardClone, article) { const newsImage = cardClone.querySelector("#news-image"); const title = cardClone.querySelector("#title"); const source = cardClone.querySelector("#source"); const newsDesc = cardClone.querySelector("#desc"); newsImage.src = article.urlToImage; title.innerHTML = article.title; newsDesc.innerHTML = article.description; const date = new Date(article.publishedAt).toLocaleString("en-US", { timeZone: "Asia/Jakarta" }); source.innerHTML = `${article.source.name} ${date}`; cardClone.firstElementChild.addEventListener("click", () => { window.open(article.url, "_blank"); }); } // Search const searchText = document.getElementById("search-text"); const search = document.getElementById("search"); search.addEventListener("click", () => { if(searchText.value.length > 0){ fetchNews(searchText.value); currentSelected?.classList.remove("active"); } }) // Active elements and navigation let currentSelected = document.getElementById("home"); currentSelected.classList.add("active"); function nav(id){ fetchNews(id); const navItem = document.getElementById(id); currentSelected?.classList.remove("active"); currentSelected = navItem; currentSelected.classList.add("active"); }
import { createSlice } from '@reduxjs/toolkit' import anecdoteService from '../services/anecdotes' const initialState = [] const anecdoteSlice = createSlice({ name: 'anecdote', initialState, reducers: { refreshAnecdote(state, action) { const anecdoteToVote = action.payload return state.map(a => a.id !== anecdoteToVote.id ? a : anecdoteToVote ) }, appendAnecdote(state, action) { state.push(action.payload) }, setAnecdotes(state, action) { return action.payload } }, }) export const { refreshAnecdote, appendAnecdote, setAnecdotes } = anecdoteSlice.actions export const initializeAnecdotes = () => { return async dispatch => { const anecdotes = await anecdoteService.getAll() dispatch(setAnecdotes(anecdotes)) } } export const createAnecdote = content => { return async dispatch => { const newAnecdote = await anecdoteService.createNew(content) dispatch(appendAnecdote(newAnecdote)) } } export const voteAnecdote = id => { return async dispatch => { const anecdotes = await anecdoteService.getAll() const anecdoteToVote = anecdotes.find(a => a.id === id) const changedAnecdote = { ...anecdoteToVote, votes: anecdoteToVote.votes + 1 } const newAnecdote = await anecdoteService.update(id, changedAnecdote) dispatch(refreshAnecdote(newAnecdote)) } } export default anecdoteSlice.reducer
๏ปฟusing Zack.DomainCommons.Models; namespace Listening.Domain.Entities; /// <summary> /// ๅˆ†็ฑป /// </summary> public record Category : AggregateRootEntity, IAggregateRoot { private Category() { Name = new MultilingualString(string.Empty, string.Empty); CoverUrl = new Uri("https://img-s-msn-com.akamaized.net/tenant/amp/entityid/AA1eFepO.img?w=768&h=439&m=6&x=1030&y=283&s=108&d=108"); } public Category(Guid id, int sequenceNumber, MultilingualString name, Uri coverUrl) { Id = id; SequenceNumber = sequenceNumber; Name = name; CoverUrl = coverUrl; } public static Category Create(Guid id, int sequenceNumber, MultilingualString name, Uri coverUrl) { Category category = new(id, sequenceNumber, name, coverUrl); //category.AddDomainEvent(new CategoryCreatedEventArgs { NewObj = category }); return category; } /// <summary> /// ๅœจๆ‰€ๆœ‰Categoryไธญ็š„ๆ˜พ็คบๅบๅท๏ผŒ่ถŠๅฐ่ถŠ้ ๅ‰ /// </summary> public int SequenceNumber { get; private set; } public MultilingualString Name { get; private set; } /// <summary> /// ๅฐ้ขๅ›พ็‰‡ใ€‚็Žฐๅœจไธ€่ˆฌ้ƒฝไธไผš็›ดๆŽฅๆŠŠๅ›พ็‰‡ไฟๅญ˜ๅˆฐๆ•ฐๆฎๅบ“ไธญ๏ผˆBlob๏ผ‰๏ผŒ่€Œๆ˜ฏๅชๆ˜ฏไฟๅญ˜ๅ›พ็‰‡็š„่ทฏๅพ„ใ€‚ /// </summary> public Uri CoverUrl { get; private set; } public Category ChangeSequenceNumber(int value) { SequenceNumber = value; return this; } public Category ChangeName(MultilingualString value) { Name = value; return this; } public Category ChangeCoverUrl(Uri value) { //todo: ๅš้กน็›ฎ็š„ๆ—ถๅ€™๏ผŒไธ็ฎก่ฟ™ไธชไบ‹ไปถๆ˜ฏๅฆๆœ‰่ขซ็”จๅˆฐ๏ผŒ้ƒฝๅฐฝ้‡publishใ€‚ CoverUrl = value; return this; } }
// refactoring adalah sebuah proses mengubah kode agar menjadi lebih 'baik' tanpa mengubah fungsionalitasnya // kenapa harus refactoring // a. readability // b. dry(dont repeat yourself) // c. testability // d. performance // e. maintainability // dari ini // function kubus2(a, b) { // let kubusA = a * a * a; // let kubusB = b * b * b; // let total = kubusA + kubusB; // return total; // } // alert(kubus2(5,8)); // ke ini function kubus2(a, b) { return a * a * a + b * b * b; } alert(kubus2(5,8));
import { connectDB } from '@/helper/db'; import { getErrorResponseMessage } from '@/helper/errorResponseMessage'; import { Task } from '@/models/task'; import { endOfDay, startOfDay } from 'date-fns'; import mongoose from 'mongoose'; import { NextResponse } from 'next/server'; import nodemailer from 'nodemailer'; connectDB(); export async function GET() { try { const todayStart = startOfDay(new Date()); const todayEnd = endOfDay(new Date()); const tasks = await Task.aggregate([ { $match: { reminderDate: { $gte: todayStart, $lte: todayEnd, }, }, }, { $lookup: { from: 'users', localField: 'userId', foreignField: '_id', as: 'user', }, }, { $unwind: '$user', }, { $project: { _id: 0, title: 1, content: 1, status: 1, email: '$user.email', }, }, ]); tasks.map(async (task) => { let transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: process.env.GMAIL_USERNAME, pass: process.env.GMAIL_PASS, }, }); const mailOptions = { from: process.env.GMAIL_USERNAME, to: task.email, subject: 'Tasks Reminder', text: `${task.title} - ${task.content}`, }; await transporter.sendMail(mailOptions); }); return NextResponse.json( { success: true, message: 'Emails sent successfully' }, { status: 200, }, ); } catch (error: any) { return getErrorResponseMessage( false, 'Unable to send email', 500, error, ); } }
package com.arsiu.eduhub.course.infrastructure.persistence.mongo import com.arsiu.eduhub.course.application.port.CoursePersistenceRepository import com.arsiu.eduhub.course.domain.Course import com.arsiu.eduhub.course.infrastructure.mapper.CourseToEntityMapper import com.arsiu.eduhub.course.infrastructure.persistence.entity.MongoCourse import org.springframework.data.mongodb.core.ReactiveMongoTemplate import org.springframework.data.mongodb.core.aggregation.Aggregation import org.springframework.data.mongodb.core.query.Criteria import org.springframework.data.mongodb.core.query.Query import org.springframework.data.mongodb.core.query.Update import org.springframework.stereotype.Repository import reactor.core.publisher.Flux import reactor.core.publisher.Mono @Repository class CourseMongoRepositoryImpl( private val reactiveMongoTemplate: ReactiveMongoTemplate, private val mapper: CourseToEntityMapper ) : CoursePersistenceRepository { override fun save(model: Course): Mono<Course> = reactiveMongoTemplate.save(mapper.toEntity(model)).map { mapper.toModelWithChapters(it) } override fun findAll(): Flux<Course> = reactiveMongoTemplate.findAll(MongoCourse::class.java).map { mapper.toModel(it) } override fun findById(id: String): Mono<Course> = reactiveMongoTemplate.findById(id, MongoCourse::class.java).map { mapper.toModel(it) } override fun upsert(model: Course): Mono<Course> { val entity = mapper.toEntityWithId(model) val query = Query.query(Criteria.where("id").`is`(entity.id)) val update = Update() .set("id", entity.id) .set("name", entity.name) .set("ownerId", entity.ownerId) .set("chapters", entity.chapters) return reactiveMongoTemplate.upsert(query, update, MongoCourse::class.java) .thenReturn(model) } override fun remove(model: Course): Mono<Void> = reactiveMongoTemplate.remove(mapper.toEntityWithId(model)).then() override fun find(query: Query): Flux<Course> = reactiveMongoTemplate.find(query, MongoCourse::class.java).map { mapper.toModel(it) } override fun aggregate(aggregation: Aggregation): Flux<Course> = reactiveMongoTemplate.aggregate( aggregation, "courseEntity", MongoCourse::class.java ).map { mapper.toModel(it) } }
import com.codeborne.selenide.Configuration; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static com.codeborne.selenide.Condition.*; import static com.codeborne.selenide.Selectors.byText; import static com.codeborne.selenide.Selenide.*; public class SelenideTests { @BeforeAll static void beforeAll() { Configuration.browserSize = "1920x1080"; Configuration.pageLoadStrategy = "eager"; //Configuration.holdBrowserOpen = true; Configuration.timeout = 5000; // default 4000 } @Test void selenideHomework() { String codeExample = """ @ExtendWith({SoftAssertsExtension.class}) class Tests { @Test void test() { Configuration.assertionMode = SOFT; open("page.html"); $("#first").should(visible).click(); $("#second").should(visible).click(); } } """; //ะžั‚ะบั€ั‹ั‚ัŒ ั€ะตััƒั€ั open("https://github.com/"); //ะะฐะถะฐั‚ัŒ ะฝะฐ ัั‚ั€ะพะบัƒ ะฟะพะธัะบะฐ $$(".flex-1").findBy(matchText("Search or jump to...")) .shouldBe(enabled).click(); //ะ’ะฒะตัั‚ะธ ะฒ ัั‚ั€ะพะบัƒ ะฟะพะธัะบะฐ ัะปะพะฒะพ "Selenide" ะธ ะฝะฐะถะฐั‚ัŒ ะ’ะฒะพะด $("#query-builder-test").setValue("Selenide").pressEnter(); //ะžั‚ะบั€ั‹ั‚ัŒ ัั‚ั€ะฐะฝะธั†ัƒ Selenide ะฒ Github $$("[data-testid='results-list']").first().$("a").click(); //ะŸะตั€ะตะนั‚ะธ ะฒ ั€ะฐะทะดะตะป Wiki ะฟั€ะพะตะบั‚ะฐ $("#wiki-tab").click(); //ะฃะฑะตะดะธั‚ัŒัั, ั‡ั‚ะพ ะฒ ัะฟะธัะบะต ัั‚ั€ะฐะฝะธั† (Pages) ะตัั‚ัŒ ัั‚ั€ะฐะฝะธั†ะฐ SoftAssertions $("#wiki-body").shouldHave(text("Soft assertions")).shouldBe(visible); //ะžั‚ะบั€ั‹ั‚ัŒ ัั‚ั€ะฐะฝะธั†ัƒ SoftAssertion; ะฟั€ะพะฒะตั€ะธั‚ัŒ, ั‡ั‚ะพ ะฒะฝัƒั‚ั€ะธ ะตัั‚ัŒ ะฟั€ะธะผะตั€ ะบะพะดะฐ ะดะปั JUnit5 $(byText("Soft assertions")).click(); $(".markdown-body").shouldHave(text(codeExample)); } }
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Manager.h" #include "NeuralNetworksOEM.h" #include "NeuralNetworksWrapper.h" #include <gtest/gtest.h> #include "OemModel.h" using namespace android::nn::wrapper; namespace { typedef float Matrix3x4[3][4]; typedef float Matrix4[4]; class TrivialOEMTest : public ::testing::Test { protected: virtual void SetUp() {} const Matrix3x4 matrix1 = {{1.f, 2.f, 3.f, 4.f}, {5.f, 6.f, 7.f, 8.f}, {9.f, 10.f, 11.f, 12.f}}; const Matrix3x4 matrix2 = {{100.f, 200.f, 300.f, 400.f}, {500.f, 600.f, 700.f, 800.f}, {900.f, 1000.f, 1100.f, 1200.f}}; const Matrix3x4 matrix3 = {{20.f, 30.f, 40.f, 50.f}, {21.f, 22.f, 23.f, 24.f}, {31.f, 32.f, 33.f, 34.f}}; const Matrix3x4 expected2 = {{101.f, 202.f, 303.f, 404.f}, {505.f, 606.f, 707.f, 808.f}, {909.f, 1010.f, 1111.f, 1212.f}}; const Matrix3x4 expected3 = {{121.f, 232.f, 343.f, 454.f}, {526.f, 628.f, 730.f, 832.f}, {940.f, 1042.f, 1144.f, 1246.f}}; const Matrix3x4 expected3b = {{22.f, 34.f, 46.f, 58.f}, {31.f, 34.f, 37.f, 40.f}, {49.f, 52.f, 55.f, 58.f}}; }; // Create a model that can add two tensors using a one node graph. void CreateSingleOEMOperation(android::nn::wrapper::Model* model) { android::nn::wrapper::OperandType matrixType(Type::TENSOR_FLOAT32, {3, 4}); android::nn::wrapper::OperandType scalarType(Type::INT32, {}); android::nn::wrapper::OperandType oemModelType(Type::INT32, {}); int32_t oemModel = static_cast<int32_t>(paintbox_nn::OemModel::MATRIX_ADD); int32_t activation(ANEURALNETWORKS_FUSED_NONE); auto select = model->addOperand(&oemModelType); auto a = model->addOperand(&matrixType); auto b = model->addOperand(&matrixType); auto c = model->addOperand(&matrixType); auto d = model->addOperand(&scalarType); model->setOperandValue(select, &oemModel, sizeof(oemModel)); model->setOperandValue(d, &activation, sizeof(activation)); model->addOperation(ANEURALNETWORKS_OEM_OPERATION, {select, a, b, d}, {c}); model->identifyInputsAndOutputs({a, b}, {c}); ASSERT_TRUE(model->isValid()); model->finish(); } // Create a model that can add three tensors using a two node graph, // with one tensor set as part of the model. void CreateMixedOEMModel(android::nn::wrapper::Model* model, const Matrix3x4 bias) { android::nn::wrapper::OperandType matrixType(Type::TENSOR_FLOAT32, {3, 4}); android::nn::wrapper::OperandType scalarType(Type::INT32, {}); int32_t activation(ANEURALNETWORKS_FUSED_NONE); auto a = model->addOperand(&matrixType); auto b = model->addOperand(&matrixType); auto c = model->addOperand(&matrixType); auto d = model->addOperand(&matrixType); auto e = model->addOperand(&matrixType); auto f = model->addOperand(&scalarType); model->setOperandValue(e, bias, sizeof(Matrix3x4)); model->setOperandValue(f, &activation, sizeof(activation)); model->addOperation(ANEURALNETWORKS_OEM_OPERATION, {a, c, f}, {b}); model->addOperation(ANEURALNETWORKS_ADD, {b, e, f}, {d}); model->identifyInputsAndOutputs({c, a}, {d}); ASSERT_TRUE(model->isValid()); model->finish(); } // Check that the values are the same. This works only if dealing with integer // value, otherwise we should accept values that are similar if not exact. int CompareMatrices(const Matrix3x4& expected, const Matrix3x4& actual) { int errors = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { if (expected[i][j] != actual[i][j]) { printf("expected[%d][%d] != actual[%d][%d], %f != %f\n", i, j, i, j, static_cast<double>(expected[i][j]), static_cast<double>(actual[i][j])); errors++; } } } return errors; } TEST_F(TrivialOEMTest, SingleOEMOperationTest) { android::nn::wrapper::Model modelAdd2; CreateSingleOEMOperation(&modelAdd2); // Test the one node model. Matrix3x4 actual; memset(&actual, 0, sizeof(actual)); Compilation compilation(&modelAdd2); compilation.finish(); Execution execution(&compilation); ASSERT_EQ(execution.setInput(0, matrix1, sizeof(Matrix3x4)), Result::NO_ERROR); ASSERT_EQ(execution.setInput(1, matrix2, sizeof(Matrix3x4)), Result::NO_ERROR); ASSERT_EQ(execution.setOutput(0, actual, sizeof(Matrix3x4)), Result::NO_ERROR); ASSERT_EQ(execution.compute(), Result::NO_ERROR); ASSERT_EQ(CompareMatrices(expected2, actual), 0); } TEST_F(TrivialOEMTest, MultipleOEMOperationTest) { for (int i = 0; i < 10; i++) { android::nn::wrapper::Model modelAdd2; CreateSingleOEMOperation(&modelAdd2); // Test the one node model. Matrix3x4 actual; memset(&actual, 0, sizeof(actual)); Compilation compilation(&modelAdd2); compilation.finish(); Execution execution(&compilation); ASSERT_EQ(execution.setInput(0, matrix1, sizeof(Matrix3x4)), Result::NO_ERROR); ASSERT_EQ(execution.setInput(1, matrix2, sizeof(Matrix3x4)), Result::NO_ERROR); ASSERT_EQ(execution.setOutput(0, actual, sizeof(Matrix3x4)), Result::NO_ERROR); ASSERT_EQ(execution.compute(), Result::NO_ERROR); ASSERT_EQ(CompareMatrices(expected2, actual), 0); } } TEST_F(TrivialOEMTest, MultiplePreparedModelTest) { std::vector<android::nn::wrapper::Model> modelList; std::vector<Compilation> compilationList; for (int i = 0; i < 10; i++) { android::nn::wrapper::Model modelAdd2; CreateSingleOEMOperation(&modelAdd2); modelList.emplace_back(std::move(modelAdd2)); Compilation compilation(&modelList.back()); compilation.finish(); compilationList.emplace_back(std::move(compilation)); } for (int i = 0; i < 10; i++) { Execution execution(&compilationList[i]); ASSERT_EQ(execution.setInput(0, matrix1, sizeof(Matrix3x4)), Result::NO_ERROR); ASSERT_EQ(execution.setInput(1, matrix2, sizeof(Matrix3x4)), Result::NO_ERROR); // Test the one node model. Matrix3x4 actual; memset(&actual, 0, sizeof(actual)); ASSERT_EQ(execution.setOutput(0, actual, sizeof(Matrix3x4)), Result::NO_ERROR); ASSERT_EQ(execution.compute(), Result::NO_ERROR); ASSERT_EQ(CompareMatrices(expected2, actual), 0); } } } // end namespace
<?php namespace App\Http\Requests\Admin; use Illuminate\Foundation\Http\FormRequest; class StoreProductRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> */ public function rules(): array { return [ 'name' => ['required', 'string', 'max:255','unique:products,name'], 'image' => ['required', 'image', 'mimes:png,jpg,jpeg,gif'], 'description' => ['required', 'string', 'max:255'], 'price' => ['required', 'numeric', 'min:0'], 'category_id' => ['required', 'exists:categories,id'], 'colors' => ['required', 'array'], 'colors.*' => ['exists:colors,id'], 'sizes' => ['required', 'array'], 'sizes.*' => ['exists:sizes,id'], ]; } }
import { Component, OnInit } from "@angular/core"; import { FormControl, FormGroup, Validators } from "@angular/forms"; import { MatSnackBar } from "@angular/material/snack-bar"; import { Login } from "src/app/class/login"; import { TipoEnum } from "src/app/enum/tipoEnum"; import { UsuarioService } from "src/app/services/usuario.service"; @Component({ selector: 'cadastro-login-dialog', templateUrl: 'cadastro-login-dialog.html', styleUrls: ['./cadastro-login.scss'] }) export class CadastroLoginDialog implements OnInit { createDialogForm!: FormGroup; tipoUsuarioList: any[] = [ { idTipo: 0, name: TipoEnum.ADM }, { idTipo: 1, name: TipoEnum.CLIENTE }, { idTipo: 2, name: TipoEnum.FUNCIONARIO }, { idTipo: 3, name: TipoEnum.RH } ]; constructor( private usuarioService: UsuarioService, private snackBar: MatSnackBar) { } ngOnInit(): void { this.createLoginForm( new Login()); } createLoginForm(login: Login){ this.createDialogForm = new FormGroup({ id:new FormControl(login.id, [Validators.required]), email: new FormControl(login.email, [Validators.required]), senha: new FormControl(login.senha, [Validators.required]), tipo: new FormControl(login.tipo,[Validators.required]), }); } createdLogin(){ let createLogin: Login createLogin = this.buildCreateLogin() this.usuarioService.registro(createLogin) .subscribe(()=>{ this.snackBar.open('Salvo com sucesso!', '', { horizontalPosition: 'start', verticalPosition: 'bottom', duration: 3000, panelClass: ['mat-toolbar', 'mat-primary'] }); }) } buildCreateLogin() { let createLogin = new Login(); createLogin.id = Math.floor(Math.random() * 100) + 1; createLogin.email= this.createDialogForm.value.email; createLogin.senha= this.createDialogForm.value.senha; createLogin.tipo = this.createDialogForm.value.tipo; return createLogin; } }
import 'dart:async'; import 'dart:io'; import 'package:bot_toast/bot_toast.dart'; import 'package:famedlysdk/famedlysdk.dart'; import 'package:fluffychat/provider/situaciones_provider.dart'; import 'package:fluffychat/views/homeserver_picker.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_gen/gen_l10n/l10n.dart'; import 'package:provider/provider.dart'; import 'package:sentry/sentry.dart'; import 'package:universal_html/prefer_universal/html.dart' as html; import 'components/matrix.dart'; import 'components/theme_switcher.dart'; import 'utils/famedlysdk_store.dart'; import 'views/situaciones_list_refactor.dart'; final sentry = SentryClient(dsn: '8591d0d863b646feb4f3dda7e5dcab38'); void captureException(error, stackTrace) async { debugPrint(error.toString()); debugPrint(stackTrace.toString()); final storage = await getLocalStorage(); if (storage.getItem('sentry') == true) { await sentry.captureException( exception: error, stackTrace: stackTrace, ); } } void main() { SystemChrome.setSystemUIOverlayStyle( SystemUiOverlayStyle(statusBarColor: Colors.transparent)); runZonedGuarded( () => runApp( MultiProvider( providers: [ ChangeNotifierProvider(create: (_) => SituacionesProvider()), ], child: App(), ), ), captureException, ); } class App extends StatelessWidget { final String platform = kIsWeb ? 'Web' : Platform.operatingSystem; @override Widget build(BuildContext context) { return Matrix( clientName: 'iveapp $platform', child: Builder( builder: (BuildContext context) => ThemeSwitcherWidget( child: Builder( builder: (BuildContext context) => MaterialApp( title: 'SIILVE', builder: BotToastInit(), navigatorObservers: [BotToastNavigatorObserver()], theme: ThemeSwitcherWidget.of(context).themeData, localizationsDelegates: L10n.localizationsDelegates, supportedLocales: L10n.supportedLocales, locale: kIsWeb ? Locale(html.window.navigator.language.split('-').first) : null, home: FutureBuilder<LoginState>( future: Matrix.of(context).client.onLoginStateChanged.stream.first, builder: (context, snapshot) { if (!snapshot.hasData) { return Scaffold( backgroundColor: Theme.of(context).primaryColor, body: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Container( height: MediaQuery.of(context).size.height * 0.4, width: double.maxFinite, child: Hero( tag: 'loginBanner', child: Image.asset('assets/logo_enia_1025.png'), ), ), SizedBox( height: MediaQuery.of(context).size.height * 0.16, ), Text( L10n.of(context).loading, style: TextStyle(color: Colors.white), ), SizedBox( height: MediaQuery.of(context).size.height * 0.05, ), CircularProgressIndicator( valueColor: AlwaysStoppedAnimation<Color>(Colors.white)), SizedBox( height: MediaQuery.of(context).size.height * 0.05, ), Text( Matrix.versionSIILVE, style: TextStyle(color: Colors.white, fontSize: 12), ), ], ), ); } if (Matrix.of(context).client.isLogged()) { context .read<SituacionesProvider>() .setUserId(Matrix.of(context).client.userID); return SituacionesListRefactorView(); } return HomeserverPicker(); }, ), ), ), ), ), ); } }
<div class="standard-form-wrapper registration-wrapper"> <fieldset class="standard-form-set"> <legend class="legend">ะ ะ•ะ“ะ˜ะกะขะ ะะฆะ˜ะฏ</legend> <form (ngSubmit)="signUp()" #registerForm="ngForm"> <div class="form-group"> <label for="name" class="label">ะŸะพั‚ั€ะตะฑะธั‚ะตะปัะบะพ ะธะผะต</label> <input id="name" type="text" class="input" required ngModel #name="ngModel" name="name"> <div class="standard-form-notification-container"> <div *ngIf="name.invalid && name.touched" class="standard-form-notification"> ะœะพะปั ะฟะพะฟัŠะปะฝะตั‚ะต ะฟะพั‚ั€ะตะฑะธั‚ะตะปัะบะพ ะธะผะต! </div> </div> </div> <div class="form-group"> <label for="email" class="label">ะ˜ะผะตะนะป</label> <input id="email" type="email" class="input" required email ngModel #email="ngModel" name="email"> <div class="standard-form-notification-container"> <div *ngIf="email.invalid && email.touched" class="standard-form-notification"> ะœะพะปั ะฟะพะฟัŠะปะฝะตั‚ะต ะบะพั€ะตะบั‚ะตะฝ ะธะผะตะนะป ะฐะดั€ะตั! </div> </div> </div> <div class="form-group"> <label for="profileImageUrl" class="label">ะŸั€ะพั„ะธะปะฝะฐ ัะฝะธะผะบะฐ(ะปะธะฝะบ)</label> <input id="profileImageUrl" type="text" class="input" ngModel #profileImageUrl="ngModel" name="profileImageUrl"> <div class="standard-form-notification-container"></div> </div> <div class="form-group"> <label for="password" class="label">ะŸะฐั€ะพะปะฐ</label> <input id="password" type="password" class="input" required ngModel #password="ngModel" name="password" minlength="4"> <div class="standard-form-notification-container"> <div *ngIf="password.invalid && password.touched" class="standard-form-notification"> ะŸะฐั€ะพะปะฐั‚ะฐ ั‚ั€ัะฑะฒะฐ ะดะฐ ะต ั ะดัŠะปะถะธะฝะฐ ะผะธะฝะธะผัƒะผ 4 ัะธะผะฒะพะปะฐ! </div> </div> </div> <!-- <div class="form-group">--> <!-- <label for="repeatPassReg" class="label">ะŸะพะฒั‚ะพั€ะตั‚ะต ะฟะฐั€ะพะปะฐั‚ะฐ</label>--> <!-- <input id="repeatPassReg" type="password" class="input">--> <!-- </div>--> <div class="form-group"> <button type="submit" class="button" [disabled]="registerForm.invalid">ะ˜ะทะฟั€ะฐั‚ะธ</button> </div> </form> </fieldset> </div>
import { UserDocument } from "@/types/user"; import UsFirbaseAuth from "@/hooks/use-firebase-auth"; import { createContext, useContext } from "react"; const init = { uid: "", email: "", displayName: "", emailVerified: false, phoneNumber: "", photoURL: "", userDocument: {} as UserDocument, }; const authUserContext = createContext({ authUser: init, authUserIsLoading: true, }); interface Props { children: React.ReactNode; } export function AuthUserProvider({ children }: Props) { const auth = UsFirbaseAuth(); return ( <authUserContext.Provider value={{ authUser: auth.authUser as { uid: string; email: string; displayName: string; emailVerified: boolean; phoneNumber: string; photoURL: string; userDocument: UserDocument; }, authUserIsLoading: auth.authUserIsLoading, }} > {children} </authUserContext.Provider> ); } export const useAuth = () => useContext(authUserContext);
/* eslint-disable @typescript-eslint/no-explicit-any */ import { LoggingLevel, NetworkerEvents } from "./types"; export interface IEvent { get_name(): string; get_args(): any[]; } export class CharEvent implements IEvent { public character: string = ""; public get_name() { return "char"; } public get_args() { return [this.character]; } public static init(args: any[]): IEvent | null { if (!(typeof args[0] === "string") || (args[0] as string) !== "char") return null; const ev = new CharEvent(); ev.character = args[1] as string; return ev; } } export class KeyEvent implements IEvent { public key: Key = 0; public isHeld: boolean = false; public isUp: boolean = false; public get_name() { return this.isUp ? "key_up" : "key"; } public get_args() { return [this.key, this.isUp ? null : this.isHeld]; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || ((args[0] as string) !== "key" && (args[0] as string) !== "key_up") ) return null; const ev = new KeyEvent(); ev.key = args[1] as number; ev.isUp = (args[0] as string) === "key_up"; ev.isHeld = ev.isUp ? false : (args[2] as boolean); return ev; } } export class PasteEvent implements IEvent { public text: string = ""; public get_name() { return "paste"; } public get_args() { return [this.text as any]; } public static init(args: any[]): IEvent | null { if (!(typeof args[0] === "string") || (args[0] as string) !== "paste") return null; const ev = new PasteEvent(); ev.text = args[1] as string; return ev; } } export class TimerEvent implements IEvent { public id: number = 0; public isAlarm: boolean = false; public get_name() { return this.isAlarm ? "alarm" : "timer"; } public get_args() { return [this.id]; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || ((args[0] as string) !== "timer" && (args[0] as string) !== "alarm") ) return null; const ev = new TimerEvent(); ev.id = args[1] as number; ev.isAlarm = (args[0] as string) === "alarm"; return ev; } } export class TaskCompleteEvent implements IEvent { public id: number = 0; public success: boolean = false; public error: string | null = null; public params: any[] = []; public get_name() { return "task_complete"; } public get_args() { if (this.success) return [this.id, this.success].concat(this.params); else return [this.id, this.success, this.error]; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || (args[0] as string) !== "task_complete" ) return null; const ev = new TaskCompleteEvent(); ev.id = args[1] as number; ev.success = args[2] as boolean; if (ev.success) { ev.error = null; ev.params = args.slice(3); } else { ev.error = args[3] as string; ev.params = []; } return ev; } } export class RedstoneEvent implements IEvent { public get_name() { return "redstone"; } public get_args() { return []; } public static init(args: any[]): IEvent | null { if (!(typeof args[0] === "string") || (args[0] as string) !== "redstone") return null; const ev = new RedstoneEvent(); return ev; } } export class TerminateEvent implements IEvent { public get_name() { return "terminate"; } public get_args() { return []; } public static init(args: any[]): IEvent | null { if (!(typeof args[0] === "string") || (args[0] as string) !== "terminate") return null; const ev = new TerminateEvent(); return ev; } } export class DiskEvent implements IEvent { public side: string = ""; public eject: boolean = false; public get_name() { return this.eject ? "disk_eject" : "disk"; } public get_args() { return [this.side]; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || ((args[0] as string) !== "disk" && (args[0] as string) !== "disk_eject") ) return null; const ev = new DiskEvent(); ev.side = args[1] as string; ev.eject = (args[0] as string) === "disk_eject"; return ev; } } export class PeripheralEvent implements IEvent { public side: string = ""; public detach: boolean = false; public get_name() { return this.detach ? "peripheral_detach" : "peripheral"; } public get_args() { return [this.side]; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || ((args[0] as string) !== "peripheral" && (args[0] as string) !== "peripheral_detach") ) return null; const ev = new PeripheralEvent(); ev.side = args[1] as string; ev.detach = (args[0] as string) === "peripheral_detach"; return ev; } } export class RednetMessageEvent implements IEvent { public sender: number = 0; public message: any; public protocol: string | null = null; public get_name() { return "rednet_message"; } public get_args() { return [this.sender, this.message, this.protocol]; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || (args[0] as string) !== "rednet_message" ) return null; const ev = new RednetMessageEvent(); ev.sender = args[1] as number; ev.message = args[2]; ev.protocol = args[3] as string; return ev; } } export class ModemMessageEvent implements IEvent { public side: string = ""; public channel: number = 0; public replyChannel: number = 0; public message: any; public distance: number = 0; public get_name() { return "modem_message"; } public get_args() { return [ this.side, this.channel, this.replyChannel, this.message, this.distance, ]; } public static init(args: any[]): IEvent | null { if (typeof args[0] !== "string" || (args[0] as string) !== "modem_message") return null; const ev = new ModemMessageEvent(); ev.side = args[1] as string; ev.channel = args[2] as number; ev.replyChannel = args[3] as number; ev.message = args[4]; ev.distance = args[5] as number; return ev; } } export class HTTPEvent implements IEvent { public url: string = ""; public handle: HTTPResponse | null = null; public error: string | null = null; public get_name() { return this.error === null ? "http_success" : "http_failure"; } public get_args() { return [ this.url, this.error === null ? this.handle : this.error, this.error !== null ? this.handle : null, ]; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || ((args[0] as string) !== "http_success" && (args[0] as string) !== "http_failure") ) return null; const ev = new HTTPEvent(); ev.url = args[1] as string; if ((args[0] as string) === "http_success") { ev.error = null; ev.handle = args[2] as HTTPResponse; } else { ev.error = args[2] as string; if (ev.error === null) ev.error = ""; ev.handle = args[3] as HTTPResponse; } return ev; } } export class WebSocketEvent implements IEvent { public handle: WebSocket | null = null; public error: string | null = null; public get_name() { return this.error === null ? "websocket_success" : "websocket_failure"; } public get_args() { return [this.handle === null ? this.error : this.handle]; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || ((args[0] as string) !== "websocket_success" && (args[0] as string) !== "websocket_failure") ) return null; const ev = new WebSocketEvent(); if ((args[0] as string) === "websocket_success") { ev.handle = args[1] as WebSocket; ev.error = null; } else { ev.error = args[1] as string; ev.handle = null; } return ev; } } export enum MouseEventType { Click, Up, Scroll, Drag, Touch, Move, } export class MouseEvent implements IEvent { public button: number = 0; public x: number = 0; public y: number = 0; public side: string | null = null; public type: MouseEventType = MouseEventType.Click; public get_name() { return { [MouseEventType.Click]: "mouse_click", [MouseEventType.Up]: "mouse_up", [MouseEventType.Scroll]: "mouse_scroll", [MouseEventType.Drag]: "mouse_drag", [MouseEventType.Touch]: "monitor_touch", [MouseEventType.Move]: "mouse_move", }[this.type]; } public get_args() { return [ this.type === MouseEventType.Touch ? this.side : this.button, this.x, this.y, ]; } public static init(args: any[]): IEvent | null { if (!(typeof args[0] === "string")) return null; const ev = new MouseEvent(); const type = args[0] as string; if (type === "mouse_click") { ev.type = MouseEventType.Click; ev.button = args[1] as number; ev.side = null; } else if (type === "mouse_up") { ev.type = MouseEventType.Up; ev.button = args[1] as number; ev.side = null; } else if (type === "mouse_scroll") { ev.type = MouseEventType.Scroll; ev.button = args[1] as number; ev.side = null; } else if (type === "mouse_drag") { ev.type = MouseEventType.Drag; ev.button = args[1] as number; ev.side = null; } else if (type === "monitor_touch") { ev.type = MouseEventType.Touch; ev.button = 0; ev.side = args[1] as string; } else if (type === "mouse_move") { ev.type = MouseEventType.Move; ev.button = args[1] as number; ev.side = null; } else return null; ev.x = args[2] as number; ev.y = args[3] as number; return ev; } } export class ResizeEvent implements IEvent { public side: string | null = null; public get_name() { return this.side === null ? "term_resize" : "monitor_resize"; } public get_args() { return [this.side]; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || ((args[0] as string) !== "term_resize" && (args[0] as string) !== "monitor_resize") ) return null; const ev = new ResizeEvent(); if ((args[0] as string) === "monitor_resize") ev.side = args[1] as string; else ev.side = null; return ev; } } export class TurtleInventoryEvent implements IEvent { public get_name() { return "turtle_inventory"; } public get_args() { return []; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || (args[0] as string) !== "turtle_inventory" ) return null; const ev = new TurtleInventoryEvent(); return ev; } } class SpeakerAudioEmptyEvent implements IEvent { public side: string = ""; public get_name() { return "speaker_audio_empty"; } public get_args() { return [this.side]; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || (args[0] as string) !== "speaker_audio_empty" ) return null; const ev = new SpeakerAudioEmptyEvent(); ev.side = args[1] as string; return ev; } } class ComputerCommandEvent implements IEvent { public args: string[] = []; public get_name() { return "computer_command"; } public get_args() { return this.args; } public static init(args: any[]): IEvent | null { if ( !(typeof args[0] === "string") || (args[0] as string) !== "computer_command" ) return null; const ev = new ComputerCommandEvent(); ev.args = args.slice(1); return ev; } } //#region custom-events export class ChatEvent implements IEvent { public username: string = ""; public message: string = ""; public uuid: string = ""; public isHidden: boolean = false; public get_name() { return ""; } public get_args() { return []; } public static init(args: any[]): IEvent | null { if (!(typeof args[0] === "string") || (args[0] as string) !== "chat") return null; const ev = new ChatEvent(); ev.username = args[1] as string; ev.message = args[2] as string; ev.uuid = args[3] as string; ev.isHidden = args[4] as boolean; return ev; } } //#region Networker events export class Networker_LoggingEvent implements IEvent { public level: LoggingLevel = LoggingLevel.info; public message: string = ""; public get_name() { return NetworkerEvents.logEvent; } public get_args() { return [this.level, this.message]; } public static init(args: any[]): Networker_LoggingEvent | null { if ( !(typeof args[0] === "string") || (args[0] as string) !== NetworkerEvents.logEvent ) return null; let ev = new Networker_LoggingEvent(); ev.level = args[2]; ev.message = args[1]; return ev; } } //#endregion //#region custom-events /* export class Event implements IEvent { public get_name() {return "";} public get_args() {return [(: any)];} public static init(args: any[]): IEvent | null { if (!(typeof args[0] === "string") || (args[0] as string) !=="") return null; let ev = new this(); return ev; } } */ export class GenericEvent implements IEvent { public args: any[] = []; public get_name() { return this.args[0] as string; } public get_args() { return this.args.slice(1); } public static init(args: any[]): IEvent { const ev = new GenericEvent(); ev.args = args; return ev; } } const eventInitializers: ((args: any[]) => IEvent | null)[] = [ // default cc event CharEvent.init, KeyEvent.init, PasteEvent.init, TimerEvent.init, TaskCompleteEvent.init, RedstoneEvent.init, TerminateEvent.init, DiskEvent.init, PeripheralEvent.init, RednetMessageEvent.init, ModemMessageEvent.init, HTTPEvent.init, WebSocketEvent.init, MouseEvent.init, ResizeEvent.init, TurtleInventoryEvent.init, SpeakerAudioEmptyEvent.init, ComputerCommandEvent.init, // Custom events ChatEvent.init, // Custom networker events Networker_LoggingEvent.init, // Should always be the final event GenericEvent.init, ]; export function eventInit(...args: any[]) { for (const init of eventInitializers) { const ev = init(args); if (ev !== null) return ev; } return GenericEvent.init(args); } /** * all implemented cc events */ export enum EventNames { alarm = "alarm", char = "char", computerCommand = "computer_command", disk = "disk", diskEject = "disk_eject", fileTransfer = "file_transfer", httpCheck = "http_check", httpFailure = "http_failure", httpSuccess = "http_success", keyUp = "key_up", key = "key", modemMessage = "modem_message", monitorResize = "monitor_resize", monitorTouch = "monitor_touch", mouseClick = "mouse_click", mouseDrag = "mouse_drag", mouseScroll = "mouse_scroll", mouseUp = "mouse_up", paste = "paste", peripheral = "peripheral", peripheralDetach = "peripheral_detach", rednetMessage = "rednet_message", redstone = "redstone", speakerAudioEmpty = "speaker_audio_empty", taskComplete = "task_complete", terminate = "terminate", timer = "timer", turtleInventory = "turtle_inventory", websocketClosed = "websocket_closed", websocketFailure = "websocket_failure", websocketMessage = "websocket_message", websocketSucces = "websocket_success", } type Constructor<T extends object = object> = new (...args: any[]) => T; /** * @deprecated Use the registry to let basalt handle events */ export function pullEventRaw(filter: string | null = null): IEvent | null { const args: any[] = coroutine.yield(filter); for (const init of eventInitializers) { const ev = init(args); if (ev !== null) return ev; } return GenericEvent.init(args); } /** * @deprecated Use the registry to let basalt handle events */ export function pullEvent(filter: string | null = null): IEvent | null { const ev = pullEventRaw(filter); if (ev instanceof TerminateEvent) throw "Terminated"; return ev; } /** * @deprecated Use the registry to let basalt handle events */ export function pullEventRawAs<T extends IEvent>( type: Constructor<T>, filter: string | null = null ): T | null { const ev = pullEventRaw(filter); if (ev instanceof type) return ev as T; else return null; } /** * @deprecated Use the registry to let basalt handle events */ export function pullEventAs<T extends IEvent>( type: Constructor<T>, filter: string | null = null ): T | null { const ev = pullEvent(filter); if (ev instanceof type) return ev as T; else return null; }
wav2cdr - convert wav sound files to CD-ROM format and/or do some editing Copyright (C) 1997, 1998, 1999, 2000, 2006 Volker Kuhlmann This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA wav2cdr converts sound data into a format which can be recorded on a CD (compact disc). The wav and a few raw formats can be handled (both read and write). Input can be chopped into pieces, which can then be recorded as separate tracks on CD. Some other transformations are also offered, e.g. volume change. Most of the functionality is also offered by sox, but when I tried it I only got stupid messages about missing effects or some such (sox-11gamma-cb3, command "sox -t raw -r 44100 -s -w -c 2 -V -x test.raw t"). Swapping the argument order or reading the manual didn't help. Funnily enough, it didn't complain on Solaris, but nevertheless I didn't want to trust it any more. (It turned out not to work at all with GNU getopt() ). After a lot of tries with different options and orders of options I gave up and decided it was faster to make a quick thing myself. Hence wav2cdr, which by now is no longer a quick thing. SUPPORTED PLATFORMS ------------------- All which have an ANSI C compiler, and some understanding of command lines. The program adapts to both big and little endian machines automatically. Unless I made a mistake, the source code is strictly ANSI conformant. wav2cdr works on at least: Linux, Solaris, Dec Alpha Unix (was this Linux?), MSDos. If your system is neither Unix nor MSDOS/Borland C, check the name of your bit bucket file in open_message_file(). If necessary, enter another conditional and the correct name, *and* let me know about it so that I can incorporate it. There is a Makefile for Unix and MSDos (the latter slightly restricted because of limitations of Borland make). INSTALLATION ------------ 1) Some version of GNU getopt() is needed, or the (inferior) mygetopt() shipped with wav2cdr can be used instead. The former is now the default. To use GNU getopt, get the following files: 28711 Jan 25 1997 getopt.c 4691 Jan 25 1997 getopt.h 4651 Jan 25 1997 getopt1.c from somwhere, e.g. tar-1.12.tar.gz, and copy them into the wav2cdr directory (or rather the directory specified in the Makefile). These files should also be part of many other GNU programs (not to say all?). 2) Edit the Makefile for your system, compiler, and getopt() version used. There are examples at the beginning of the file. The provided Makefile should work for most Unix systems with gcc. To some extent it might also work for MSDos. It works with GNU make and Sun/Solaris make. (Use the file Makefile.bc for MSDos instead.) The settings to check are mainly where the executable and man page is installed. If you do make any changes, please send them back to me. 3) Compile with: make depend make 4) Install with (not MSDos): make install Or copy the executable and man page into place by hand. 5) If you get sick ot it (hey!), wav2cdr can be uninstalled with (not msdos): make uninstall The files usage.-c, help.-c, version.-c, wav2cdr.txt are automatically generated using the programs awk/nawk/gawk, nroff, troff, cx. These programs are typically found on a Unix system. cx is self-baked and strips BS characters together with the following character (this gets rid of the underline effect in output produced by man). If you don't have these programs or some equivalent, don't delete these files. DOCUMENTATION ------------- The file help.txt, or running wav2cdr with option --help. The Unix style man page (roff format), or its plain text equivalent wav2cdr.txt. LICENSE + WARRANTY ------------------ See the file COPYING for details. To those still not with it: my liability is restricted to what you paid me. Volker Kuhlmann c/o University of Canterbury EEE Dept Christchurch New Zealand <[email protected]> [very old] <[email protected]>
// this is how hoisting works in function declarations event though the function is defined afterwards var result = add(5, 5); console.log('result:', result) function add(num1, num2) { return num1 + num2; } // because function is a function expression it doesnt have hoisting so this expression will return an error // let resultSecond = addSecond(2, 3) // console.log('resultSecond:', resultSecond) var addSecond = function(a, b) { return a + b } // Using the ARGUMENTS KEYWORD inside a funtion function numberOfArguments() { return arguments.length } console.log(numberOfArguments('Hi', 1)) // as you can see this function returns the number of arguments passes due to the ARGUMENTS KEYWORD // Applying the ARGUMENTS KEYWORD to a sum function function sum() { let result = 0 for (let i = 0; i < arguments.length; i++) { result += arguments[i] } return result } // And here you can see the result of all those values summed console.log(sum(5, 3, 2)) // FUNCTION OVERLOADING // is like having a default output even if there aren't any arguments in the function function sayMessage(message = "Default Message") { console.log(message) } sayMessage("Hello!") sayMessage() // OBJECT METHODS // when you create object methods you have to avoid arrow functions to use the THIS KEYWORD, otherwise you have to bind the method const person = { name: "Nicholas", sayName: function() { console.log(this.name)} } person.sayName() //Nicholas const person2 = { name: "Tatiana", sayName: () => console.log(this.name) } person2.sayName.call(person2) //undefined console.log('test') // when using the this KEYWORD you have to use function expression because arrow functions override the this KEYWORD and lose context of the object // You can also use the same method for many objects like: function sayRoyalNames() { console.log(this.name) } const tzar = { name: "Nicholas", sayName: sayRoyalNames } const tzarDaughter = { name: "Olga", sayName: sayRoyalNames } const secondTzarDaughter = { name: "Tatiana", sayName: sayRoyalNames } const thirdTzarDaughter = { name: "Maria", sayName: sayRoyalNames } tzar.sayName() tzarDaughter.sayName() secondTzarDaughter.sayName() thirdTzarDaughter.sayName() // as you can see you are using the same function in all the objects as methods // THE CALL METHOD function sayBeatlesNames(label) { console.log(`${label}: ${this.name}`) } const JohnLennon = { name: "JohnLennon" } const PaulMcCartney = { name: "Paul McCartney" } let name = "George Harrison" // var name = "George Harrison" // const name = "George Harrison" // in global variables to reference the this you can use let or var but no const // const will return undefined in the call with (this, "global") // varv works just as fine as let sayBeatlesNames.call(this, "global") sayBeatlesNames.call(JohnLennon, "JohnLennon") sayBeatlesNames.call(PaulMcCartney, "PaulMcCartney") // THE APPLY METHOD function sayRollingStonesNames(label) { console.log(`${label}: ${this.name}`) } // as you can see this function is exactly the same as sayBeatlesNames const MickJagger = { name: "Mick Jagger" } const KeithRichards = { name: "Keith Richards" } sayRollingStonesNames.apply(this, ["global"]) // here it says a beatle beause in the global environment the name variable is a beatle name sayRollingStonesNames.apply(MickJagger, ["Mick Jagger"]) sayRollingStonesNames.apply(KeithRichards, ["Keith Richards"]) // here it works properly because the apply is done to RollingStone members // as you can see the apply differs from the call because the arguments are passed in an array // THE BIND METHOD function sayMetallicaNames(label) { console.log(`${label}: ${this.name}`) } const JamesHetfield = { name: "James Hetfield" } const LarsUlrich = { name: "Lars Ulrich" } // you have to create a function for JamesHetfield const sayNameForJamesHetfield = sayMetallicaNames.bind(JamesHetfield) // and then you pass the label sayNameForJamesHetfield("JamesHetfield") // if you call it without the label it will sow undefined in the log message sayNameForJamesHetfield() // or you have to again create the function but you can pass the label in the bind method const sayNameForLarsUlrich = sayMetallicaNames.bind(LarsUlrich, "LarsUlrich") // and then you can just call it sayNameForLarsUlrich()
import Util from '@services/util.js'; import Content from './content.js'; import './row.scss'; export default class Row { /** * @class * @param {object} [params] Parameters. * @param {string} [params.colorBackground] Background color. * @param {number} [params.contentId] Content id. * @param {object[]} [params.fields] Fields. * @param {string} [params.imageHeightLimit] Image height limit. * @param {number} [params.index] Index of first field. * @param {object} [params.mainInstance] Main instance. * @param {object[]} [params.previousStates] Previous states. * @param {object} [callbacks] Callbacks. * @param {function} [callbacks.xAPI] Callback for xAPI events. */ constructor(params = {}, callbacks = {}) { params = Util.extend({ fields: [], previousStates: [] }, params); callbacks = Util.extend({ xAPI: () => {} }, callbacks); params = Util.extend({ fields: [] }, params); this.dom = document.createElement('div'); this.dom.classList.add('h5p-active-reader-placeholder-content-row'); /* * totalSpaceHorizontal holds the sum of the width of all fields in the row. * It is used to calculate the relative width of each field. */ const totalSpaceHorizontal = params.fields.reduce((space, field) => { return space + field.width; }, 0); this.contents = params.fields.map((field, index) => { const previousState = (params?.previousStates.length > params.index + index) ? params.previousStates[params.index + index] : {}; const content = new Content( { contentId: params.contentId, field: field, imageHeightLimit: params.imageHeightLimit, index: params.index + index, mainInstance: params.mainInstance, previousState: previousState, totalSpaceHorizontal: totalSpaceHorizontal, verticalAlignment: field.verticalAlignment, width: field.width, widthRelative: `${ 100 * field.width / totalSpaceHorizontal }%` }, { xAPI: (event, index) => { callbacks.xAPI(event, index); } } ); return content; }); this.contents.forEach((content) => { this.dom.appendChild(content.getDOM()); }); } /** * Get the DOM element. * @returns {HTMLElement} The DOM element. */ getDOM() { return this.dom; } /** * Get instance wrappers. * @returns {object[]} Instance wrappers. */ getInstanceWrappers() { return this.contents.map((content) => content.getInstanceWrapper()); } }
package com.fxDeals.progresSoft.progresSoftApplication.handler; import com.fxDeals.progresSoft.progresSoftApplication.exception.DealAlreadyExistException; import com.fxDeals.progresSoft.progresSoftApplication.exception.DealNotFoundException; import com.fxDeals.progresSoft.progresSoftApplication.exception.InvalidDealDetailsException; import com.fxDeals.progresSoft.progresSoftApplication.pojo.ErrorDetails; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Global exception handler class for centralizing exception handling and response customization * across the application. * <p> * This class extends {@link ResponseEntityExceptionHandler} to provide additional common * handling mechanisms for Spring MVC exceptions. It is annotated with {@code @RestControllerAdvice} * to allow it to be auto-detected through classpath scanning and applied to all controllers. * </p> */ @RestControllerAdvice @Slf4j public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { List<String> errorList = ex .getBindingResult() .getFieldErrors() .stream() .map(fieldError -> fieldError.getDefaultMessage()) .collect(Collectors.toList()); ErrorDetails errorDetails = new ErrorDetails(HttpStatus.BAD_REQUEST, "Validation failed", errorList); return this.handleExceptionInternal(ex, errorDetails, headers, errorDetails.getStatus(), request); } @ExceptionHandler({DealNotFoundException.class, InvalidDealDetailsException.class, DealAlreadyExistException.class}) protected ErrorDetails handleDealExceptions(DealNotFoundException ex) { return new ErrorDetails(HttpStatus.NOT_FOUND, ex.getMessage(), null); } }
class UsersController < ApplicationController def index @users=User.all end def show @user =User.find(params[:id]) end def new @user = User.new end def create @user =User.new(params.require(:user).permit(:name, :email)) if @user.valid? redirect_to users_path else flash[:errors] = @user.errors.full_messages redirect_to new_student_path end end def edit @user =User.find(params[:id]) end private def user_params params.require(:user).permit(:name, :email) end end
/* ๆ€ป็ป“๏ผš 1.ๅœจๅ“ชไธช่ทฏ็”ฑ็ป„ไปถไธญๅตŒๅฅ—ๅญ่ทฏ็”ฑ็ป„ไปถ๏ผŒๅฐฑๅœจๅ“ชไธช่ทฏ็”ฑไธญ้…็ฝฎๅญ่ทฏ็”ฑ 2.ไฝฟ็”จchildrenๅฑžๆ€ง้…็ฝฎ๏ผŒไธ”ๅญ่ทฏ็”ฑ็š„ ่ทฏๅพ„ไธ็”จๅŠ  / 3.่ฐƒ็”จๅญ่ทฏ็”ฑๆ—ถ๏ผŒ้œ€่ฆๆŠŠ็ˆถ็บง่ทฏๅพ„ไธ€ๅนถๅธฆไธŠ */ // ๅฏผๅ…ฅvue import Vue from 'vue' // ๅฏผๅ…ฅapp.vue import App from './App.vue' // ๅฏผๅ…ฅvue-routerๆก†ๆžถ import Vuerouter from 'vue-router' // ๅฏผๅ…ฅ่ทฏ็”ฑๆ–‡ไปถ import route from './router/index' // ไฝฟ็”จVue-routerๆก†ๆžถ Vue.use(Vuerouter) Vue.config.productionTip = false new Vue({ el: '#app', render: h => h(App), // ้…็ฝฎ่ทฏ็”ฑๅ™จ router:route })
export const Table = ({ columns, rows, }: { columns: string[]; rows: any[]; }) => { return ( <div className="relative overflow-auto shadow-md sm:rounded-lg max-h-96"> <table className="w-full text-sm text-left dark:text-slate-800"> <thead className="text-xs uppercase bg-blue-500 dark:text-white sticky top-0 z-10"> <tr> {columns?.map((column, index) => ( <th key={index} scope="col" className="px-6 py-3"> {column} </th> ))} </tr> </thead> <tbody className=""> {rows?.map((row, rowIndex) => ( <tr key={rowIndex} className="bg-white"> {columns?.map((column, colIndex) => ( <td key={colIndex} className="px-6 py-4"> {row[column]} </td> ))} </tr> ))} </tbody> </table> </div> ); };
package ink.champ.models; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import javax.persistence; import java.util.Collection; import java.util.Set; @Entity(name = "users") public class User implements UserDetails{ @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(nullable = false, unique = true) private String username; @Column(nullable = false) private String password; @Column(nullable = false) private String name; @Column(nullable = false, unique = true) private String email; private boolean active; @OneToMany(targetEntity = Champ.class, mappedBy = "user", orphanRemoval = true, fetch = FetchType.LAZY) private Set<Champ> champs; @OneToMany(mappedBy = "user") private Set<Team> teams; @OneToMany(targetEntity = Player.class, mappedBy = "user", orphanRemoval = true, fetch = FetchType.LAZY) private Set<Player> players; @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER) @CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id")) @Enumerated(EnumType.STRING) private Set<Role> roles; /** * ะšะพะฝัั‚ั€ัƒะบั‚ะพั€ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั */ public User() { }/** * ะšะพะฝัั‚ั€ัƒะบั‚ะพั€ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั * @param username ะ›ะพะณะธะฝ * @param password ะŸะฐั€ะพะปัŒ * @param name ะ˜ะผั * @param email ะะดั€ะตั ัะปะตะบั‚ั€ะพะฝะฝะพะน ะฟะพั‡ั‚ั‹ */ public User(String username, String password, String name, String email) { this.username = username; this.password = new BCryptPasswordEncoder().encode(password); this.name = name; this.email = email; this.active = true; } public void setName(String name){ this.name = name; } public void setPassword(String password){ this.password = password; } public String getName(){ return name; } public void setTeams(Set<Team> teams){ this.teams = teams; } public Long getId(){ return id; } public boolean isActive(){ return active; } @Override public Collection<? extends GrantedAuthority> getAuthorities(){ return getRoles(); } public String getUsername(){ return username; } @Override public boolean isAccountNonExpired(){ return true; } public void setId(Long id){ this.id = id; } public void setRoles(Set<Role> roles){ this.roles = roles; } public Set<Player> getPlayers(){ return players; } public Set<Role> getRoles(){ return roles; } public void setPlayers(Set<Player> players){ this.players = players; } public void setUsername(String username){ this.username = username; } public Set<Champ> getChamps(){ return champs; } @Override public boolean isAccountNonLocked(){ return true; } public boolean isAdmin(){ return getRoles().contains(Role.ADMIN); } public Set<Team> getTeams(){ return teams; } public String getPassword(){ return password; } public void setActive(boolean active){ this.active = active; } public void setEmail(String email){ this.email = email; } public void setChamps(Set<Champ> champs){ this.champs = champs; } @Override public boolean isCredentialsNonExpired(){ return true; } @Override public boolean isEnabled(){ return isActive(); } public String getEmail(){ return email; } }
@extends('frontend.layouts.master') @section('content') <!-- Header End --> <div class="container-xxl py-5 bg-dark page-header mb-5"> <div class="container my-5 pt-5 pb-4"> <h1 class="display-3 text-white mb-3 animated slideInDown">Job List</h1> <nav aria-label="breadcrumb"> <ol class="breadcrumb text-uppercase"> <li class="breadcrumb-item"><a href="{{ route('home.page') }}">Home</a></li> <li class="breadcrumb-item"><a href="javascript:;">Job List</a></li> </ol> </nav> </div> </div> <!-- Header End --> <!-- Search Start --> <div class="container-fluid bg-primary wow fadeIn" data-wow-delay="0.1s" style="padding: 35px;"> <div class="container"> <div class="row g-2"> <div class="col-md-10"> <form action="{{ route('search.job') }}" method="GET"> @csrf <div class="row g-2"> <div class="col-md-12"> <input type="text" name="keyword" class="form-control border-0 p-3" placeholder="Search Via Address, Category, Remote Or Office" /> </div> </div> </div> <div class="col-md-2"> <button type="submit" class="btn btn-dark border-0 w-100 p-3">Search</button> </div> </form> </div> </div> </div> <!-- Search End --> <!-- Jobs Start --> <div class="container-xxl py-5"> <div class="container"> @if (count($jobs) > 0) <h1 class="text-center mb-5 wow fadeInUp" data-wow-delay="0.1s">Job Listing</h1> @endif <div class="tab-class text-center wow fadeInUp" data-wow-delay="0.3s"> <div class="tab-content"> <div id="tab-1" class="tab-pane fade show p-0 active"> @if (count($jobs) > 0) <div class="job-item p-4 mb-4"> {{ $jobs->links() }} @foreach ($jobs as $item) @if ($item->end_date > \Carbon\Carbon::now()) <div class="row g-4 mb-3"> <div class="col-sm-12 col-md-8 d-flex align-items-center"> <a href="{{ route('job.details', $item->id) }}"> <div class="text-start m-3"> <h5 class="mb-2">{{ $item->name }} <span class="text-truncate me-3 text-primary"><i class="text-primary me-2"></i>{{ $item->user->name }}</span> </h5> <span class="text-truncate me-3"><i class="fa fa-map-marker-alt text-primary me-2"></i>{{ $item->address }}</span> <span class="text-truncate me-3"><i class="far fa-clock text-primary me-2"></i>{{ $item->office_from }}</span> <span class="text-truncate me-3"><i class="far fa-clock text-primary me-2"></i>{{ $item->office_time }}</span> <span class="text-truncate me-0"><i class="far fa-money-bill-alt text-primary me-2"></i>{{ $item->salary }}</span> <br> <span class="text-truncate me-3 mb-2"><i class="far fa-clock text-primary me-2"></i><span class="text-info">Publish: {{ $item->created_at->diffForHumans() }}</span></span> <span class="text-truncate me-3 mb-2"><i class="far fa-clock text-primary me-2"></i><span class="text-info">Last Date: {{ \Carbon\Carbon::parse($item->end_date)->format('d F Y') }}</span></span> </div> </a> </div> <div class="col-sm-12 col-md-4 d-flex flex-column align-items-start align-items-md-end justify-content-center"> <div class="d-flex mb-3"> <a class="btn btn-primary" href="{{ route('job.details', $item->id) }}">See More</a> </div> </div> </div> <hr> @endif @endforeach {{ $jobs->links() }} </div> @else <div class="card py-5"> <h3 class="text-primary">No data were found matching your selection</h3> </div> </div> </div> @endif </div> </div> </div> <!-- Jobs End --> @endsection
//! ๋ฌธ์ œ: ๊ฒŒ์ž„ ์บ๋ฆญํ„ฐ ์Šคํ‚ฌ ์‹œ๋ฎฌ๋ ˆ์ดํ„ฐ // ๋ชฉ์ : ํ•จ์ˆ˜์˜ ์ •์˜, ๋งค๊ฐœ๋ณ€์ˆ˜์™€ ์ธ์ž์˜ ์ดํ•ด, ๋ฐ˜ํ™˜๊ฐ’์˜ ํ™œ์šฉ์„ ๋ณต์Šต // ๊ธฐ๋ณธ ๋ฐ์ดํ„ฐ ํƒ€์ž…๋งŒ์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ฒŒ์ž„ ์บ๋ฆญํ„ฐ์˜ ์Šคํ‚ฌ์„ ์‹œ๋ฎฌ๋ ˆ์ด์…˜ํ•˜๋Š” ๊ฐ„๋‹จํ•œ ํ”„๋กœ๊ทธ๋žจ //? ๊ฒŒ์ž„ ์„ค๋ช… // RPG ๊ฒŒ์ž„์˜ ์บ๋ฆญํ„ฐ๋ฅผ ์ œ์–ดํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑ // ์บ๋ฆญํ„ฐ๋Š” ์—ฌ๋Ÿฌ ์Šคํ‚ฌ ์‚ฌ์šฉ ๊ฐ€๋Šฅ, ๊ฐ ์Šคํ‚ฌ์€ ๋‹ค์–‘ํ•œ ํšจ๊ณผ๋ฅผ ๋ณด์œ  // ์Šคํ‚ฌ์„ ์‚ฌ์šฉํ•  ๋•Œ๋งˆ๋‹ค ์บ๋ฆญํ„ฐ์˜ ์ƒํƒœ ๋ณ€ํ™” // => ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ๊ตฌํ˜„ //? ์บ๋ฆญํ„ฐ ์ƒํƒœ(๋ฐ์ดํ„ฐ) // ์ฒด๋ ฅ (HP) // ๋งˆ๋ ฅ (MP) // ์Šคํ‚ฌ //? ์Šคํ‚ฌ(๊ธฐ์ˆ ) // ํž(Heal): ์ฒด๋ ฅ์„ ์ผ์ •๋Ÿ‰ ํšŒ๋ณต / ์‚ฌ์šฉํ•  ๋•Œ ๋งˆ๋ ฅ์„ ์†Œ๋ชจ // ํŒŒ์ด์–ด๋ณผ(Fireball): ์ ์—๊ฒŒ ํ”ผํ•ด๋ฅผ ์ฃผ๊ณ  ๋งˆ๋ ฅ์„ ์†Œ๋ชจ // ๋ฉ”๋””ํ…Œ์ด์…˜(Meditation): ๋งˆ๋ ฅ์„ ์†Œ๋Ÿ‰ ํšŒ๋ณต / ์ถ”๊ฐ€ ์ฒด๋ ฅ ์†Œ๋ชจ X //? ๋ฌธ์ œ ์ƒํ™ฉ // ์บ๋ฆญํ„ฐ์˜ ์ดˆ๊ธฐ ์ฒด๋ ฅ(HP)์€ 100, ๋งˆ๋ ฅ(MP)์€ 50์œผ๋กœ ์‹œ์ž‘ // ๊ฐ ์Šคํ‚ฌ์˜ ๊ธฐ๋Šฅ์„ ์ˆ˜ํ–‰ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑ // - ๊ฐ ํ•จ์ˆ˜๋Š” ํ˜„์žฌ HP ๋˜๋Š” MP๋ฅผ ์ธ์ž๋กœ ๋ฐ›๊ณ , ๊ฐ ์Šคํ‚ฌ์˜ ๊ฒฐ๊ณผ๋กœ ๋ณ€๊ฒฝ๋œ HP ๋˜๋Š” MP๋ฅผ ๋ฐ˜ํ™˜ //? ๊ฐ ์Šคํ‚ฌ(ํ•จ์ˆ˜)์˜ ์ž‘๋™ // ํž(Heal): ์ฒด๋ ฅ์„ 30 ํšŒ๋ณตํ•˜๊ณ , 10์˜ ๋งˆ๋ ฅ ์†Œ๋ชจ // ๋‹จ, ๋งˆ๋ ฅ์ด ๋ถ€์กฑํ•˜๋ฉด ์Šคํ‚ฌ ์‚ฌ์šฉ X // ํŒŒ์ด์–ด๋ณผ(Fireball): ์ ์—๊ฒŒ 25์˜ ํ”ผํ•ด๋ฅผ ์ฃผ๊ณ , 15์˜ ๋งˆ๋ ฅ์„ ์†Œ๋ชจ // ๋งˆ๋ ฅ์ด ๋ถ€์กฑํ•˜๋ฉด ์Šคํ‚ฌ ์‚ฌ์šฉ X // ๋ฉ”๋””ํ…Œ์ด์…˜(Meditation): 20์˜ ๋งˆ๋ ฅ์„ ํšŒ๋ณต // - ์Šคํ‚ฌ ์‚ฌ์šฉ ์‹œ๋งˆ๋‹ค ํ˜„์žฌ์˜ ์ฒด๋ ฅ๊ณผ ๋งˆ๋ ฅ์„ ์ถœ๋ ฅํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ // - ์‚ฌ์šฉ์ž๊ฐ€ ์„ ํƒํ•œ ์Šคํ‚ฌ์— ๋”ฐ๋ผ ์ ์ ˆํ•œ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๊ณ  ๊ฒฐ๊ณผ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฉ”์ธ ๋กœ์ง์„ ์ž‘์„ฑ // : ์‚ฌ์šฉ์ž ์ž…๋ ฅ์œผ๋กœ ์Šคํ‚ฌ์„ ์„ ํƒํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋˜, ์ž…๋ ฅ์€ ์Šคํ‚ฌ ์ด๋ฆ„์˜ ์ฒซ ๊ธ€์ž ('H', 'F', 'M')๋กœ ์ œํ•œ //? ์—ฐ์Šต ์ƒํ™ฉ(๊ตฌํ˜„ ํ…Œ์ŠคํŠธ) // ํ˜„์žฌ ์ƒํƒœ: HP = 100, MP = 50 // ์‚ฌ์šฉํ•  ์Šคํ‚ฌ์„ ์„ ํƒํ•˜์„ธ์š” (H, F, M): H // ํž ์‚ฌ์šฉ: HP = 130, MP = 40 // ํ˜„์žฌ ์ƒํƒœ: HP = 130, MP = 40 // ์‚ฌ์šฉํ•  ์Šคํ‚ฌ์„ ์„ ํƒํ•˜์„ธ์š” (H, F, M): F // ํŒŒ์ด์–ด๋ณผ ์‚ฌ์šฉ: ์ ์—๊ฒŒ 25์˜ ํ”ผํ•ด๋ฅผ ์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค. MP = 25 // ํ˜„์žฌ ์ƒํƒœ: HP = 130, MP = 25 // ์‚ฌ์šฉํ•  ์Šคํ‚ฌ์„ ์„ ํƒํ•˜์„ธ์š” (H, F, M): M // ๋ฉ”๋””ํ…Œ์ด์…˜ ์‚ฌ์šฉ: MP = 45 // ํ˜„์žฌ ์ƒํƒœ: HP = 130, MP = 45 //! ์†Œ์Šค์ฝ”๋“œ ์ž‘์„ฑ //! ํž(Heal) ๊ธฐ์ˆ ์„ ์‚ฌ์šฉํ•˜๋Š” ํ•จ์ˆ˜ ์ •์˜ // ๋งค๊ฐœ๋ณ€์ˆ˜ hp์™€ mp๋Š” ๊ฐ๊ฐ ์‚ฌ์šฉ์ž์˜ ํ˜„์žฌ ์ฒด๋ ฅ๊ณผ ๋งˆ๋ ฅ function heal(hp, mp) { if (mp >= 10) { // ๋งˆ๋ ฅ์— 10 ์ด์ƒ์ธ ๊ฒฝ์šฐ์—๋งŒ ํž ์‚ฌ์šฉ ๊ฐ€๋Šฅ hp += 30; // ์ฒด๋ ฅ 30 ํšŒ๋ณต mp -= 10; // ๋งˆ๋ ฅ 10 ์†Œ๋ชจ console.log(`ํž ์‚ฌ์šฉ: HP = ${hp}, MP = ${mp}`); // ์‚ฌ์šฉ ๊ฒฐ๊ณผ ๋กœ๊ทธ ์ถœ๋ ฅ } else { console.log('๋งˆ๋ ฅ ๋ถ€์กฑ์œผ๋กœ ํž ์‚ฌ์šฉ ๋ถˆ๊ฐ€'); } // ํ•ด๋‹น ์Šคํ‚ฌ ์‚ฌ์šฉ ํ›„ ๋ณ€๊ฒฝ๋œ hp์™€ mp๋ฅผ ๋ฐ˜ํ™˜ return [hp, mp]; } //! ํŒŒ์ด์–ด๋ณผ(Fireball) ๊ธฐ์ˆ ์„ ์‚ฌ์šฉํ•˜๋Š” ํ•จ์ˆ˜ ์ •์˜ // mp๋Š” ์‚ฌ์šฉ์ž์˜ ํ˜„์žฌ ๋งˆ๋ ฅ function fireball(mp) { if (mp >= 15) { const damage = 25; mp -= 15; console.log(`ํŒŒ์ด์–ด๋ณผ ์‚ฌ์šฉ: ์ ์—๊ฒŒ ${damage}์˜ ๊ณต๊ฒฉ์„ ํ•˜์˜€์Šต๋‹ˆ๋‹ค. MP = ${mp}`); } else { console.log('๋งˆ๋ ฅ ๋ถ€์กฑ์œผ๋กœ ํŒŒ์ด์–ด๋ณผ ์‚ฌ์šฉ ๋ถˆ๊ฐ€'); } return mp; } //! ๋ฉ”๋””ํ…Œ์ด์…˜(Meditation) ๊ธฐ์ˆ ์„ ์‚ฌ์šฉํ•˜๋Š” ํ•จ์ˆ˜ ์ •์˜ function meditation(mp) { mp += 20; console.log(`๋ฉ”๋””ํ…Œ์ด์…˜ ์‚ฌ์šฉ: MP = ${mp}`); return mp; } //! ์‹คํ–‰ ํ•จ์ˆ˜ ๊ตฌํ˜„ - ๊ฒŒ์ž„์˜ ์‹คํ–‰ ๋กœ์ง์„ ๋‹ด๋‹น function main() { // ์ดˆ๊ธฐ ์บ๋ฆญํ„ฐ ์„ค์ • let hp = 100; let mp = 50; //* readline ๋ชจ๋“ˆ์„ ์‚ฌ์šฉํ•˜์—ฌ ์ฝ˜์†”์—์„œ ์‚ฌ์šฉ์ž ์ž…๋ ฅ ๋ฐ›๊ธฐ. // : Node.js์— ๋‚ด์žฅ๋œ ์ž…์ถœ๋ ฅ ๊ด€๋ฆฌ ๊ธฐ๋Šฅ ์‚ฌ์šฉ์„ ์š”์ฒญ // : Node.js์—์„œ ์ œ๊ณตํ•˜๋Š” readline ๋ชจ๋“ˆ์„ ๋ถˆ๋Ÿฌ์™€ readline์ด๋ผ๋Š” ์ƒ์ˆ˜์— ํ• ๋‹น // : require("readline") ํ˜ธ์ถœ์€ ํ•ด๋‹น ๋ชจ๋“ˆ์˜ ๊ธฐ๋Šฅ๋“ค์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋ฉฐ // , ์ด๋ฅผ ํ†ตํ•ด ์ž…๋ ฅ๊ณผ ์ถœ๋ ฅ์„ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋Š” ์—ฌ๋Ÿฌ ๋ฉ”์„œ๋“œ์™€ ์†์„ฑ์— ์ ‘๊ทผ ๊ฐ€๋Šฅ const readline = require('readline'); //* readline.createInterface() ๋ฉ”์„œ๋“œ // : readline.Interface ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑ // : ํ•ด๋‹น ์ธ์Šคํ„ด์Šค๋Š” ํ…์ŠคํŠธ ์ž…๋ ฅ ์ŠคํŠธ๋ฆผ๊ณผ ์ถœ๋ ฅ ์ŠคํŠธ๋ฆผ์„ ๊ด€๋ฆฌํ•˜๋ฉฐ, ์‚ฌ์šฉ์ž์™€์˜ ๋Œ€ํ™”ํ˜• ์„ธ์…˜์„ ๊ตฌ์ถ• // : ๋ฉ”์„œ๋“œ๋Š” ์„ค์ • ๊ฐ์ฒด๋ฅผ ์ธ์ž๋กœ ๋ฐ›์Œ // - ์ฃผ์š” ๊ตฌ์„ฑ ์š”์†Œ // input: ์ž…๋ ฅ ์ŠคํŠธ๋ฆผ์„ ์ง€์ • // process.stdin์€ ํ‘œ์ค€ ์ž…๋ ฅ ์ŠคํŠธ๋ฆผ(๋ณดํ†ต ํ‚ค๋ณด๋“œ ์ž…๋ ฅ)์„ ์˜๋ฏธํ•˜๋ฉฐ, ์ด๋ฅผ ํ†ตํ•ด ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ์˜ ์ž…๋ ฅ ๋ฐ›์Œ // output: ์ถœ๋ ฅ ์ŠคํŠธ๋ฆผ์„ ์ง€์ • // process.stdout์€ ํ‘œ์ค€ ์ถœ๋ ฅ ์ŠคํŠธ๋ฆผ(๋ณดํ†ต ์ฝ˜์†” ์ถœ๋ ฅ)์„ ์˜๋ฏธํ•˜๋ฉฐ, ์ด๋ฅผ ํ†ตํ•ด ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ฉ”์‹œ์ง€๋ฅผ ์ถœ๋ ฅ // - ์ด ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ํ‚ค๋ณด๋“œ ์ž…๋ ฅ์„ ๋น„๋™๊ธฐ์ ์œผ๋กœ ๋ฐ›์•„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์ž…๋ ฅ๋งˆ๋‹ค ์ฝœ๋ฐฑ ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ๊ฐ ์ž…๋ ฅ์„ ๊ฐœ๋ณ„์ ์œผ๋กœ ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅ // rl ๊ฐ์ฒด๋Š” ๋‹ค์–‘ํ•œ ์ด๋ฒคํŠธ๋ฅผ ์ˆ˜์‹ ํ•˜๊ณ  ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋Š” ๋ฉ”์„œ๋“œ๋“ค์„ ์ œ๊ณต // : rl.question() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด ์‚ฌ์šฉ์ž์—๊ฒŒ ์งˆ๋ฌธ์„ ํ•  ์ˆ˜ ์žˆ๊ณ , ์‚ฌ์šฉ์ž์˜ ์‘๋‹ต์„ ๋ฐ›์•„ ๋‹ค์Œ ๋กœ์ง์„ ์‹คํ–‰ ๊ฐ€๋Šฅ // : rl.close() ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ์ž…๋ ฅ ์ŠคํŠธ๋ฆผ์„ ๋‹ซ๊ณ  ํ”„๋กœ๊ทธ๋žจ์„ ์ข…๋ฃŒ const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); // ์‹ค์ œ ํ˜ธ์ถœ ํ”„๋กœ๊ทธ๋žจ const prompt = () => { // ํ˜„์žฌ ์ƒํƒœ ์ถœ๋ ฅ console.log(`ํ˜„์žฌ ์ƒํƒœ: HP = ${hp}, MP = ${mp}`); // ์‚ฌ์šฉ์ž์—๊ฒŒ ์ž…๋ ฅ ๋ฐ›๊ธฐ rl.question( '---์‚ฌ์šฉํ•  ์Šคํ‚ฌ์„ ์„ ํƒํ•˜์„ธ์š” (H, F, M, Q to quit) :---', function (input) { const choice = input.toUpperCase(); // ์ž…๋ ฅ์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ switch (choice) { case 'H': // heal ํ•จ์ˆ˜ ์‚ฌ์šฉ ํ›„ ๋ฐ˜ํ™˜ ๊ฐ’์„ ์ €์žฅ [hp, mp] = heal(hp, mp); prompt(); // ๋‹ค์‹œ ๋ช…๋ น ์ž…๋ ฅ ๋Œ€๊ธฐ break; case 'F': mp = fireball(mp); prompt(); break; case 'M': mp = meditation(mp); prompt(); break; case 'Q': console.log('๊ฒŒ์ž„์„ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.'); rl.close(); // readline ์ธํ„ฐํŽ˜์ด์Šค ์ข…๋ฃŒ break; default: console.log('์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์„ ํƒํ•˜์„ธ์š”.'); prompt(); } } ); }; prompt(); // ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ์ฒ˜์Œ์œผ๋กœ ๋ฐ›๋Š” ํ•จ์ˆ˜ ํ˜ธ์ถœ } main(); // main ํ•จ์ˆ˜ ํ˜ธ์ถœํ•˜์—ฌ ํ”„๋กœ๊ทธ๋žจ ์‹œ์ž‘
import Image from 'next/image' import { Container } from '@components/Container' import { Shortcut } from '@components/Shortcut' export const Presentation = ({ locale }: { locale?: string }) => { return ( <header> <Container> <div className="flex flex-col md:flex-row py-14 gap-6 md:gap-12 md:py-28"> <div className="w-32 h-32 md:w-40 md:h-40 rounded-full overflow-hidden"> <Image src="/images/fernando.JPG" alt="Fernando dos Santos" width={160} height={160} className="flex w-32 h-32 md:w-40 md:h-40" /> </div> <div className="flex flex-col gap-4 md:gap-6 flex-1"> <h1 className="text-2xl md:text-3xl font-bold text-neutral-900 dark:text-neutral-50"> Fernando dos Santos <span className="text-fuchsia-500 dark:text-fuchsia-400">.</span> </h1> <h2 className="text-gray-700 dark:text-gray-200 mb-4"> Software developer at{' '} <span className="font-semibold">Creative Labs</span> </h2> <p className="text-base font-medium text-neutral-500 dark:text-neutral-400"> {locale === 'pt-BR' ? 'Eu sou um desenvolvedor frontend angolano. Trabalhando na Creative Labs. Entusiasta de design e amante de tecnologia, compartilhando conhecimento pela web e colaborando com projetos OpenSource.' : "I'm an Angolan frontend developer. Working at Creative Labs. Design enthusiast and technology lover, sharing knowledge over the web and collaborating with OpenSource projects."} </p> <Shortcut locale={locale} /> </div> </div> </Container> </header> ) }
// Section 19 // Challenge 1 // Formatting output #include <iostream> #include <iomanip> #include <vector> #include <string> struct City { std::string name; long population; double cost; }; // Assume each country has at least 1 city struct Country { std::string name; std::vector<City> cities; }; struct Tours { std::string title; std::vector<Country> countries; }; int main() { Tours tours { "Tour Ticket Prices from Miami", { { "Colombia", { { "Bogota", 8778000, 400.98 }, { "Cali", 2401000, 424.12 }, { "Medellin", 2464000, 350.98 }, { "Cartagena", 972000, 345.34 } }, }, { "Brazil", { { "Rio De Janiero", 13500000, 567.45 }, { "Sao Paulo", 11310000, 975.45 }, { "Salvador", 18234000, 855.99 } }, }, { "Chile", { { "Valdivia", 260000, 569.12 }, { "Santiago", 7040000, 520.00 } }, }, { "Argentina", { { "Buenos Aires", 3010000, 723.77 } } }, } }; const int width1 = 24; const int width2 = 18; std::cout << "\t\t\t" << tours.title << std::endl << std::endl; std::cout << std::left << std::setw(width1) << "Country" << std::setw(width2) << "City" << std::setw(width2) << "Population" << std::setw(width2) << "Price" << std::endl << "-------------------------------------------------------------------" << std::endl; for(Country country : tours.countries) { std::cout << std::left << std::setw(width1) << country.name; for(int i = 0; i < country.cities.size(); ++i){ if (i != 0) { std::cout << "\t\t\t"; } std::cout << std::left << std::setw(width2) << country.cities.at(i).name << std::left << std::setw(width2) << country.cities.at(i).population << std::left << std::setw(width2) << country.cities.at(i).cost << std::endl; } } std::cout << std::endl << std::endl; return 0; }
import "./style.scss"; document.querySelector("#app").innerHTML = ` <main class="main-container"> <nav class="nav-container"> <img src="/logo.webp" class="logo" alt=""> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="mobile-nav"> <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 5.25h16.5m-16.5 4.5h16.5m-16.5 4.5h16.5m-16.5 4.5h16.5" /> </svg> <div class="navbar"> <ul class="first-nav-items"> <li>Trending</li> <li>Pre-orders</li> <li>Upcoming</li> <li>Support 24/7</li> </ul> <ul class="second-nav-items"> <li class="nav-items-with-icons"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="other-icons"> <path stroke-linecap="round" stroke-linejoin="round" d="M9 17.25v1.007a3 3 0 01-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0115 18.257V17.25m6-12V15a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 15V5.25m18 0A2.25 2.25 0 0018.75 3H5.25A2.25 2.25 0 003 5.25m18 0V12a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 12V5.25" /> </svg> PC <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="other-icons drop-down-icons"> <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" /> </svg> </li> <li class="nav-items-with-icons"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="other-icons"> <path stroke-linecap="round" stroke-linejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.348a1.125 1.125 0 010 1.971l-11.54 6.347a1.125 1.125 0 01-1.667-.985V5.653z" /> </svg> Playstation <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="other-icons drop-down-icons"> <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" /> </svg> </li> <li class="nav-items-with-icons"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="other-icons"> <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /> </svg> Xbox <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="other-icons drop-down-icons"> <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" /> </svg> </li> <li class="nav-items-with-icons"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="other-icons"> <path stroke-linecap="round" stroke-linejoin="round" d="M10.5 6h9.75M10.5 6a1.5 1.5 0 11-3 0m3 0a1.5 1.5 0 10-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m-9.75 0h9.75" /> </svg> Nintendo <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="other-icons drop-down-icons"> <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" /> </svg> </li> <li class="search-box"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="search-icon"> <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" /> </svg> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="serch-bar-close"> <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /> </svg> </li> </ul> <div class="dropdown-container"> <div class="dropdown-view"> <div class="dropdown-header"> <h4>Platforms</h4> <button class="view-all-button">View all</button> </div> <div class="dropdown-items"> <ul> </ul> </div> </div> <div class="dropdown-view"> <div class="dropdown-header"> <h4>Prepaid Cards</h4> <button class="view-all-button">View all</button> </div> <div class="dropdown-items"> <ul> <li>Steam Gift Cards</li> <li>IG Gift Cards</li> <li>Blizzard Gift Cards</li> </ul> </div> </div> </div> </div> <aside class="rightside-buttons"> <div> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="cart-and-profile-icons"> <path stroke-linecap="round" stroke-linejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 00-16.536-1.84M7.5 14.25L5.106 5.272M6 20.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm12.75 0a.75.75 0 11-1.5 0 .75.75 0 011.5 0z" /> </svg> </div> <div class="user-profile-icon"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="cart-and-profile-icons"> <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" /> </svg> </div> </aside> </nav> <section class="hero-container"> <div class="hero-text"> <span class="days-badge">In 15 days</span> <span class="early-access-text">Starfield Digital Premium <br> Edition + Early Access</span> <div class="hero-price"> <span class="discount-badge">-25%</span> <span class="hero-price-text">74.89$</span> </div> </div> </section> </main> `; const dropDownData = { PC: [ "Steam", "Ubisoft Connect", "EA App", "Battle.net", "Rockstar", "GOG.com", "Microsoft Store", "Epic", ], Playstation: ["Playstation Store", "PS Plus", "PS Now"], Xbox: ["Xbox Store", "Xbox Game Pass"], Nintendo: ["Nintendo eShop", "Switch Online"], }; const dropdownItems = document.querySelector(".dropdown-items ul"); const dropdownContainers = Array.from( document.getElementsByClassName("nav-items-with-icons") ); const dropdownMenus = document.querySelectorAll(".nav-items-with-icons"); const searchBox = document.querySelector(".search-box"); const searchClose = document.querySelector(".serch-bar-close"); const inputBox = document.createElement("input"); const leftsideDrawer = document.createElement("div"); leftsideDrawer.className = "leftside-drawer"; document.body.appendChild(leftsideDrawer); const mobileNavSvg = document.querySelector(".mobile-nav"); mobileNavSvg.addEventListener("click", () => { leftsideDrawer.classList.toggle("open"); }); const drawerItemsUl = document.createElement("ul"); const drawerItemTitles = ["Home", "Profile", "Settings", "Logout"]; drawerItemTitles.forEach((title) => { const li = document.createElement("li"); li.textContent = title; drawerItemsUl.appendChild(li); }); leftsideDrawer.appendChild(drawerItemsUl); const closeButton = document.createElement("button"); closeButton.className = "close-button"; leftsideDrawer.appendChild(closeButton); closeButton.addEventListener("click", () => { leftsideDrawer.classList.remove("open"); }); document.body.appendChild(leftsideDrawer); dropdownContainers.forEach((container) => { container.addEventListener("click", (event) => { const selectedPlatform = container.textContent.trim(); const platformData = dropDownData[selectedPlatform]; if (platformData) { dropdownItems.innerHTML = ""; platformData.forEach((item) => { const listItem = document.createElement("li"); listItem.textContent = item; dropdownItems.appendChild(listItem); }); const dropdownContainer = document.querySelector(".dropdown-container"); dropdownContainer.style.display == "block" ? (dropdownContainer.style.display = "none") : (dropdownContainer.style.display = "block"); } }); }); searchBox.addEventListener("click", () => { inputBox.classList.add("input-box"); inputBox.setAttribute("type", "text"); inputBox.setAttribute("placeholder", "Minecraft, RPG, Multiplayer..."); searchClose.style.display = "block"; searchClose.addEventListener("click", () => { inputBox.style.display = "none"; console.log(searchClose.style); searchClose.style.display = "none"; }); dropdownMenus.forEach((menuItem) => { menuItem.innerHTML = ""; menuItem.appendChild(inputBox); }); });
clc clear // Ejercicio 10 // f(x) = e^x en [-1,1] // Funcion que calcula los nodos de raices segun el grado. function r = Chev(n) for k=0:n-1 r(k+1) = cos(%pi/2*(1+2*k)/n) end endfunction function y = Lk(x, k) [Xn,Xm] = size(x) // Se genera un vector con las raices del polinomio Lk r = [x(1:k-1) x(k+1:Xm)] // Con poly generamos el polinomio cuyas raices son r p = poly(r,"x","roots") // Evaluamos pk = horner(p, x(k)) y = p / pk endfunction function z = interpolLagrange(x,y) [Xn,Xm] = size(x) pol = 0 // Conformamos el polinomio de lagrange. for k = 1:Xm pol = pol + (Lk(x,k)*y(k)) end z = pol endfunction disp("Raices de Chev") disp(Chev(4)) disp(exp(Chev(4))) /* Chev(4) = 0.9238795 0.3826834 -0.3826834 -0.9238795 exp(Chev(4) = 2.5190442 1.4662138 0.6820288 0.396976 */ pol3 = interpolLagrange(Chev(4)', exp(Chev(4)')) disp(pol3) //pol3 = 0.9946153 +0.9989332x +0.5429007x^2 +0.1751757x^3 rango = [-1:0.001:1] figure plot(rango, horner(pol3, rango), 'r') // HORNER VALORIZA Pol3(x) para todo x en [-1:0.001:1] plot(rango, exp(rango), 'b') xgrid() h1 = legend(['Polinomio Interpolacion','f(x)']) figure plot(rango, abs(horner(pol3, rango)-exp(rango)), 'r') h1 = legend(['Error del polinomio']) xgrid() /* figure polConstante = interpolLagrange([-1:2/3:1], exp([-1:2/3:1])) plot(rango, abs(horner(polConstante, rango)-exp(rango)), 'r') h1 = legend(['Error del polinomio']) xgrid() */
import React, { useEffect, useState } from 'react' import EditModal from './EditModal' import {RiDeleteBin6Fill} from 'react-icons/ri' // import Exp from './Expenses.json' import CreateModal from './CreateModal' import ReactPaginate from "react-paginate"; function ViewExpense() { const getLocalItems = () => { let list = localStorage.getItem('card'); if (list) { return JSON.parse(localStorage.getItem('card')); } else { return []; } } const [card,setCard] = useState(getLocalItems()); const [expense,setExpense] = useState({id:"",name:"",discription:"",category:"",dateofExp:"",amount:""}); const [search,setSearch] =useState(""); const [date,setDate] = useState(""); const [pageNumber, setPageNumber] = useState(0); const usersPerPage = 5; const pagesVisited = pageNumber * usersPerPage; const pageCount = Math.ceil(card.length / usersPerPage); const changePage = ({ selected }) => { setPageNumber(selected); } const AddChanges=(e)=>{ setExpense({...expense,[e.target.name]: e.target.value,id: new Date().getTime().toString()}); } const handleSearch=(e)=>{ if(e.key==="Enter"){ e.preventDefault(); setSearch(e.target.value.toLowerCase().trim()); } } const handleDate=(e)=>{ if(e.key==="Enter"){ e.preventDefault(); setDate(e.target.value); } } const createExpense=(e)=>{ e.preventDefault(); let card = localStorage.getItem("card"); let cardObj; if (card == null) { cardObj = []; } else { cardObj = JSON.parse(card); } cardObj.push(expense); setCard(cardObj); setExpense({id:"",name:"",discription:"",category:"",dateofExp:"",amount:""}); } const handleDelete=(id)=>{ if(window.confirm("Are you sure you want to delete the Expense?")){ const updatedItems = card.filter((elem) => { return elem.id !== id; }) setCard(updatedItems); } } const [editExp,setEditExp] = useState({id:"",name:"",discription:"",category:"",dateofExp:"",amount:""}); const EditChanges=(e)=>{ setEditExp({...editExp,[e.target.name]: e.target.value}); } const storeEditExp=(id,exp)=>{ localStorage.setItem('index',id); localStorage.setItem('time',Date.now()); localStorage.setItem('editExpense',JSON.stringify(exp)); setEditExp(exp); } const handleEdit = (editExp) => { const EditItem = localStorage.getItem('index'); setCard( card.map((elem) => { if (elem.id === EditItem) { return editExp; } return elem; }) ); localStorage.removeItem('index'); localStorage.removeItem('editExpense'); } const getDate=(dt)=>{ let monthNames = ["January", "February", "March", "April", "May","June","July", "August", "September", "October", "November","December"]; let d = new Date(dt); return d.getDate()+' '+monthNames[d.getMonth()]+", "+ dt.slice(0,4) ; } const getAmount=(rs)=>{ return rs.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } useEffect(()=>{ localStorage.setItem('card', JSON.stringify(card)); },[card]) return ( <div className='container'> <div className="expenseHeader"> <div> <h2>MY EXPENSE MANAGER</h2> </div> <div> <span className="searchFilter"> <input type="date" id="filter-date" name="date" min="2018/01/01" max="2023/12/31" placeholder='Filter by Date of Expenses' onKeyDown={handleDate}/> </span> <span className="searchFilter"> <input type="search" id="search" placeholder='Search Expense by Name' onKeyDown={handleSearch}/> </span> <span><CreateModal createExpense={createExpense} AddChanges={AddChanges} expense={expense}/></span> </div> </div> <div className="expenseContent"> <table > <thead> <tr style={{height:"65px",textAlign:"center"}}> <th width="220px">Name</th> <th width="160px">Category</th> <th width="230px">Date of Expense</th> <th width="160px">Amount</th> <th width="180px">Updated At</th> <th width="170px">Created by</th> <th > </th> </tr> </thead> <tbody> {card.slice(pagesVisited, pagesVisited + usersPerPage).reverse().map((exp)=>{ if((search==="" || search===exp.name.toLowerCase()) && (date==="" || date===exp.dateofExp)) return( <tr key={exp.id}> <td >{exp.name}</td> <td >{exp.category}</td> <td >{getDate(exp.dateofExp)}</td> <td >INR {getAmount(exp.amount)}</td> <td >Just Now</td> <td >me</td> <td className='action'><span className='action'><EditModal handleEdit={handleEdit} storeEditExp={storeEditExp} id={exp.id} exp={exp} AddChanges={EditChanges} editExp={editExp}/></span> <span className='action' onClick={()=>{handleDelete(exp.id)}}><RiDeleteBin6Fill size={"1.5rem"} color='red'/></span></td> </tr>) else return<></> })} </tbody> </table> </div> <ReactPaginate previousLabel={" < "} nextLabel={" > "} pageCount={pageCount} onPageChange={changePage} containerClassName={"paginationBttns"} previousLinkClassName={"previousBttn"} nextLinkClassName={"nextBttn"} disabledClassName={"paginationDisabled"} activeClassName={"paginationActive"} /> </div> ) } export default ViewExpense
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { WelcomeComponent } from './page/welcome/welcome.component'; import { PageNotFoundComponent } from './page/page-not-found/page-not-found.component'; import { MainComponent } from './page/main/main.component'; import { LegalNoticeComponent } from './components/info/legal-notice/legal-notice.component'; import { DataProtectionComponent } from './components/info/data-protection/data-protection.component'; import { AuthGuard } from './shared/service/auth.guard'; import { ChatContentComponent } from './chat/chat-content/chat-content.component'; import { ChatHintComponent } from './chat/chat-hint/chat-hint.component'; const routes: Routes = [ { path: '', component: WelcomeComponent }, { path: 'main', component: MainComponent, canActivate: [AuthGuard], children: [ { path: '', component: ChatHintComponent }, //Hier eine Info Componente erstellen / einstzen { path: ':name', component: ChatContentComponent }, ], }, { path: 'legal-notice', component: LegalNoticeComponent }, { path: 'data-protection', component: DataProtectionComponent }, { path: '**', component: PageNotFoundComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { addToCart, addQuantityWithNumber } from '../../store/actions/cartActions'; import { ToastContainer, toast } from 'react-toastify'; class MainContent extends Component { state = { qty: 1, max: 10, min: 1 } handleAddToCartFromView = () => { this.props.addQuantityWithNumber(1, this.state.qty); toast.success('Added to the cart', { position: "bottom-left", autoClose: 5000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true }); } handleAddToCart = (id) => { this.props.addToCart(id); toast.success('Added to the cart', { position: "bottom-left", autoClose: 5000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true }); } IncrementItem = () => { this.setState(prevState => { if(prevState.qty < 10) { return { qty: prevState.qty + 1 } } else { return null; } }); } DecreaseItem = () => { this.setState(prevState => { if(prevState.qty > 1) { return { qty: prevState.qty - 1 } } else { return null; } }); } render() { return ( <div className="col-lg-6 col-md-12"> <ToastContainer /> <div className="product-details-desc"> <h3>White Book</h3> <div className="price"> <span className="new-price">$8.00</span> <span className="old-price">$12.00</span> </div> <div className="product-review"> <div className="rating"> <i className="fas fa-star"></i> <i className="fas fa-star"></i> <i className="fas fa-star"></i> <i className="fas fa-star"></i> <i className="fas fa-star-half-alt"></i> </div> <a href="#" className="rating-count">3 reviews</a> </div> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et.</p> <div className="product-add-to-cart"> <div className="input-counter"> <span className="minus-btn" onClick={this.DecreaseItem} > <i className="fas fa-minus"></i> </span> <input type="text" value={this.state.qty} min={this.state.min} max={this.state.max} onChange={e => this.setState({ qty: e.target.value })} /> <span className="plus-btn" onClick={this.IncrementItem} > <i className="fas fa-plus"></i> </span> </div> <button className="btn btn-primary" onClick={this.handleAddToCartFromView} > <i className="fas fa-cart-plus"></i> Add to Cart </button> </div> <div className="buy-checkbox-btn"> <div className="item"> <input className="inp-cbx" id="cbx" type="checkbox" /> <label className="cbx" htmlFor="cbx"> <span> <svg width="12px" height="10px" viewBox="0 0 12 10"> <polyline points="1.5 6 4.5 9 10.5 1"></polyline> </svg> </span> <span>I agree with the terms and conditions</span> </label> </div> <div className="item"> <a href="#" className="btn btn-light">Buy it now!</a> </div> </div> <div className="custom-payment-options"> <span>Guaranteed safe checkout:</span> <div className="payment-methods"> <a href="#"><img src="/images/payment/1.svg" alt="image" /></a> <a href="#"><img src="/images/payment/2.svg" alt="image" /></a> <a href="#"><img src="/images/payment/3.svg" alt="image" /></a> <a href="#"><img src="/images/payment/4.svg" alt="image" /></a> <a href="#"><img src="/images/payment/5.svg" alt="image" /></a> <a href="#"><img src="/images/payment/6.svg" alt="image" /></a> <a href="#"><img src="/images/payment/7.svg" alt="image" /></a> </div> </div> </div> </div> ); } } const mapDispatchToProps= (dispatch)=>{ return { addQuantityWithNumber: (id, qty) => {dispatch(addQuantityWithNumber(id, qty))}, addToCart: (id) => { dispatch(addToCart(id)) } } } export default connect( null, mapDispatchToProps )(MainContent)
import 'dart:io'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../resources/resources.dart'; import '../../domain/blocs/auth_bloc/auth_bloc.dart'; import '../../domain/blocs/auth_bloc/auth_event.dart'; import '../../domain/blocs/auth_bloc/auth_state.dart'; import '../main_page/main_page_bloc.dart'; class EditProfileWidget extends StatelessWidget { const EditProfileWidget({super.key}); @override Widget build(BuildContext context) { return BlocBuilder<AuthBloc, AuthBlocState>(builder: (BuildContext context, state) { final authModel = state.authModel; return Scaffold( appBar: AppBar( title: const Text( "Edit Profile", // style: TextStyle(color: Colors.white), ), centerTitle: true, ), body: ListView( children: [ Column( children: [ InkWell( onTap: () { context.read<AuthBloc>().add(GetImageEvent()); }, child: SizedBox( height: 150, child: Padding( padding: const EdgeInsets.all(10.0), child: ClipRRect( borderRadius: BorderRadius.circular(5), child: authModel.file != null ? Image.file( authModel.file as File, fit: BoxFit.fill, ) : authModel.user?.getUserImage() == "" ? Image.asset(AppImages.person) : CachedNetworkImage( imageUrl: authModel.user?.getUserImage() ?? "", errorWidget: (context, error, obj) => const Icon( Icons.person_outline_rounded, size: 100, ), fit: BoxFit.fill, ), ), ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Card( // color: const Color(0xFF212934), child: Column( children: [ TextField( // style: const TextStyle(color: Colors.white), controller: authModel.editName, // onChanged: (text) => name = text, decoration: const InputDecoration( labelText: "Name", labelStyle: TextStyle(color: Color(0xFF56AE7C)), border: OutlineInputBorder(), ), ), const SizedBox( height: 15, ), TextField( // style: const TextStyle(color: Colors.white), controller: authModel.editEmail, decoration: const InputDecoration( labelText: "Email", labelStyle: TextStyle(color: Color(0xFF56AE7C)), border: OutlineInputBorder(), ), ), const SizedBox( height: 15, ), TextField( keyboardType: TextInputType.phone, // style: const TextStyle(color: Colors.white), controller: authModel.editPhoneNumber, decoration: const InputDecoration( labelText: "Phone Number", labelStyle: TextStyle(color: Color(0xFF56AE7C)), border: OutlineInputBorder(), ), ), authModel.errorMessage != null ? Column( children: [ const SizedBox( height: 10, ), Text( authModel.errorMessage ?? "", style: const TextStyle(color: Colors.red), ), const SizedBox( height: 10, ) ], ) : const Text(""), Padding( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10), child: SizedBox( width: MediaQuery.of(context).size.width, child: state is AuthLoadState ? const Center( child: CircularProgressIndicator(), ) : BlocBuilder<MainBloc, MainViewBlocState>( builder: (BuildContext context, state) { return OutlinedButton( onPressed: () { context.read<AuthBloc>().add(UpdateUserEvent( userId: authModel.user?.id, name: authModel.editName.text, email: authModel.editEmail.text, phoneNumber: authModel.editPhoneNumber.text, )); if (authModel.errorMessage == null) { Navigator.of(context).pop(); } }, style: const ButtonStyle( backgroundColor: MaterialStatePropertyAll(Color(0xFF56AE7C))), child: const Text( "Update", style: TextStyle( // color: Colors.white, fontSize: 18), ), ); })), ) ], ), ), ), ], ), ], ), ); }); } }
<template> <div class="codemirror-demo"> <MarkdownEditor v-model="value" @toolbarItemAction="toolbarItemAction" :beforeInitToolbars="beforeInitToolbars" /> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue' import MarkdownEditor from '../components/editor/markdown/index.vue' import { ToolbarsType, ToolbarItemType } from '../components/editor/markdown/types' import IconUpload from '../components/editor/theme/markdown/upload.svg?component' export default defineComponent({ components: { MarkdownEditor }, setup () { const value = ref('') const TopCustom: ToolbarItemType = { type: 'top_custom', title: '่‡ชๅฎšไน‰', icon: IconUpload, shortcutKey: 'Alt-x', action: () => { console.log('in') } } const beforeInitToolbars = (toolbars: ToolbarsType) => { toolbars.top.push(TopCustom) return toolbars } const toolbarItemAction = (item: ToolbarItemType, type: string, editor: typeof MarkdownEditor) => { console.log(item.type, type) // type: click[็‚นๅ‡ป], keyboard[้”ฎ็›˜] editor.setValue('test demo') } return { value, beforeInitToolbars, toolbarItemAction } }, }) </script> <style lang="scss" scoped> .codemirror-demo { --editor-bg-light: #f5f5f5; --editor-bg-dark: #000000; border: 1px #dddddd solid; box-sizing: border-box; width: 375px; height: 667px; margin: 0 auto; } </style>
# John Rexpearl Tumlos # Hash Exercise #02 # Sales Data Merge # # You have two hashes representing sales data from two different sources. Each hash contains sales data for the same products, but the keys may not match exactly. Write a Ruby program that merges the two sales data hashes into a single hash, combining the sales data for each product. # Here are the two sales data hashes: sales_data1 = { "product_A" => 100, "product_B" => 200, "product_C" => 150 } sales_data2 = { "product_B" => 300, "product_C" => 250, "product_D" => 50 } # Your program should produce a merged hash that combines the sales data for all products from both sources. In case a product appears in both hashes, add the sales quantities together. If a product appears in only one hash, include it in the merged hash with its respective sales quantity. # The merged hash for the given example should be: # { # "product_A" => 100, # "product_B" => 500, # "product_C" => 400, # "product_D" => 50 # } def sales_merge(data1, data2) data2.each do | key, value | if data1.include?(key) data1[key] += value else data1[key] = value end end return data1 end print sales_merge(sales_data1, sales_data2)
import React, { useState } from 'react' import Logo from '../img/logo.png' import Avatar from '../img/avatar.png' import { HiShoppingCart } from 'react-icons/hi' import { MdAdd, MdLogout } from 'react-icons/md' import { motion } from 'framer-motion' import { Link } from 'react-router-dom' import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth"; import { app } from "../firebase.config"; import { useStateValue } from '../context/StateProvider' import { actionType } from '../context/reducer' const Header = () => { const firebaseAuth = getAuth(app); const provider = new GoogleAuthProvider(); const [{ user }, dispatch] = useStateValue() const [isMenu, setIsMenu] = useState(false); const login = async () => { // We get all the login data from stateContext if (!user) { const { user: { refreshToken, providerData } } = await signInWithPopup(firebaseAuth, provider); dispatch({ type: actionType.SET_USER, user: providerData[0], }); localStorage.setItem("user", JSON.stringify(providerData[0])); } else { setIsMenu(!isMenu); } }; // Update stateprovider, local storage and hide the menu const logout = () => { setIsMenu(false); localStorage.clear(); dispatch({ type: actionType.SET_USER, user: null }); }; return ( <header className="fixed bg-primary drop-shadow-lg z-50 w-screen p-3 px-4 md:p-5 md:px-16"> {/* For desktop and Tablets View */} <div className="hidden md:flex w-full h-full items-center justify-between"> <Link to={'/'} className="flex items-center gap-2"> <img src={Logo} className="w-14 object-cover rounded-full" alt="logo"></img> <p className="text-headingColor text-xl font-bold">Food Mart</p> </Link> <div className="flex items-center gap-8"> <motion.ul initial={{ opacity: 0, x: 200 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: 200 }} className="flex items-center gap-8"> <li className="text-base text-textColor hover:text-headingColor duration-100 transition-all ease-in-out cursor-pointer"> Home </li> <li className="text-base text-textColor hover:text-headingColor duration-100 transition-all ease-in-out cursor-pointer"> Menu </li> <li className="text-base text-textColor hover:text-headingColor duration-100 transition-all ease-in-out cursor-pointer"> About Us </li> <li className="text-base text-textColor hover:text-headingColor duration-100 transition-all ease-in-out cursor-pointer"> Service </li> </motion.ul> <div className="relative flex items-center justify-center"> <HiShoppingCart className="text-textColor text-2xl cursor-pointer" /> <div className="absolute -top-1 -right-4 w-5 h-5 rounded-full bg-cartNumBg flex items-center justify-center"> <p className="text-xs text-white font-semibold"></p> </div> </div> <div className="ralative"> <motion.img whileTap={{ scale: 0.6 }} src={user ? user.photoURL : Avatar} className="w-10 h-10 min-w-[40px] min-h-[40px] drop-shadow-2xl cursor-pointer rounded-full" alt="userprofile" referrerPolicy="no-referrer" onClick={login} /> { isMenu && ( <motion.div initial={{ opacity: 0, scale: 0.6 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.6 }} className="w-40 bg-gray-50 shadow-xl rounded-lg flex flex-col absolute top-20 right-4"> {user && user.email === "[email protected]" && ( <Link to={"/createItem"}> <p className="px-4 py-2 flex items-center gap-3 cursor-pointer hover:bg-slate-100 transition-all duratio-100 ease-in-out text-textColor text-base" onClick={() => setIsMenu(false)}> New Item <MdAdd /> </p> </Link> )} <p className="px-4 py-2 flex items-center gap-3 cursor-pointer hover:bg-slate-100 transition-all duratio-100 ease-in-out text-textColor text-base first-letter" onClick={logout}> Logout <MdLogout /> </p> </motion.div> ) } </div> </div> </div> {/* For Mobile View */} <div className="flex items-center justify-between md:hidden w-full h-full"> <div className="relative flex items-center justify-center"> <HiShoppingCart className="text-textColor text-2xl cursor-pointer" /> <div className="absolute -top-1 -right-4 w-5 h-5 rounded-full bg-cartNumBg flex items-center justify-center"> <p className="text-xs text-white font-semibold"></p> </div> </div> <Link to={'/'} className="flex items-center gap-2"> <img src={Logo} className="w-14 object-cover rounded-full" alt="logo"></img> <p className="text-headingColor text-xl font-bold">Food Mart</p> </Link> <div className="ralative"> <motion.img whileTap={{ scale: 0.6 }} src={user ? user.photoURL : Avatar} className="w-10 h-10 min-w-[40px] min-h-[40px] drop-shadow-2xl cursor-pointer rounded-full" alt="userprofile" referrerPolicy="no-referrer" onClick={login} /> { isMenu && ( <div initial={{ opacity: 0, scale: 0.6 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.6 }} className="w-40 bg-gray-50 shadow-xl rounded-lg flex flex-col absolute top-20 right-4"> {user && user.email === "[email protected]" && ( <Link to={"/createContainer"}> <p className="px-4 py-2 flex items-center gap-3 cursor-pointer hover:bg-slate-100 transition-all duratio-100 ease-in-out text-textColor text-base" onClick={() => setIsMenu(false)}> New Item <MdAdd /> </p> </Link> )} <ul className="flex flex-col"> <li className="text-base text-textColor hover:text-headingColor duration-100 transition-all ease-in-out cursor-pointer hover:bg-slate-100 px-4 py-2" onClick={() => setIsMenu(false)}> Home </li> <li className="text-base text-textColor hover:text-headingColor duration-100 transition-all ease-in-out cursor-pointer hover:bg-slate-100 px-4 py-2" onClick={() => setIsMenu(false)}> Menu </li> <li className="text-base text-textColor hover:text-headingColor duration-100 transition-all ease-in-out cursor-pointer hover:bg-slate-100 px-4 py-2" onClick={() => setIsMenu(false)}> About Us </li> <li className="text-base text-textColor hover:text-headingColor duration-100 transition-all ease-in-out cursor-pointer hover:bg-slate-100 px-4 py-2" onClick={() => setIsMenu(false)}> Service </li> </ul> <p className="m-2 p-2 rounded-md shadow-md flex items-center justify-center bg-slate-200 gap-3 cursor-pointer hover:bg-slate-300 transition-all duratio-100 ease-in-out text-textColor text-base first-letter" onClick={logout}> Logout <MdLogout /> </p> </div> ) } </div> </div> </header> ) } export default Header
import 'package:conditional_builder_rec/conditional_builder_rec.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:social_app/const/constant.dart'; import 'package:social_app/register/register_cubit.dart'; import 'package:social_app/register/register_states.dart'; import 'package:social_app/screens/layout_screen.dart'; class RegieterScreen extends StatelessWidget { //const RegieterScreen({Key? key}) : super(key: key); var formKey = GlobalKey<FormState>(); var emailController = TextEditingController(); var passwordController = TextEditingController(); var nameController = TextEditingController(); var phoneController = TextEditingController(); @override Widget build(BuildContext context) { return BlocProvider( create: (context) => SocialRegisterCubit(), child: BlocConsumer<SocialRegisterCubit, RegisterStates>( listener: (context, state) { if (state is CreateSucseesState) { Fluttertoast.showToast( msg: 'Hello ${nameController}', toastLength: Toast.LENGTH_LONG, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 5, backgroundColor: Colors.green, textColor: Colors.white, fontSize: 18.0, ); // CacheHellper.setData( // key: 'uid', // value: state.loginModel.data.token, // ); Navigator.of(context).pushReplacement(MaterialPageRoute( builder: (context) => const Layoutscreen(), )); } }, builder: (context, state) { return Scaffold( // appBar: AppBar(), body: Center( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(20.0), child: Form( key: formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text( 'REGISTER', style: TextStyle( fontSize: 35, fontWeight: FontWeight.bold, ), ), const SizedBox( height: 15, ), const Text( 'Register now to browse our hot offers', style: TextStyle( fontSize: 18, color: Colors.grey, ), ), const SizedBox( height: 30, ), deafualtTextformField( controller: nameController, saved: (value) {}, obSecure: false, validator: (value) { if (value!.isEmpty) { return 'name is must not be Empty'; } return null; }, lable: "Name", icon: const Icon(Icons.person), //suffixicon: const Icon(Icons.visibility_outlined), ), const SizedBox( height: 20, ), deafualtTextformField( controller: emailController, saved: (value) {}, obSecure: false, validator: (value) { if (value!.isEmpty) { return 'Please enter Your email'; } return null; }, lable: "Email", icon: const Icon(Icons.email_outlined), ), const SizedBox( height: 20, ), deafualtTextformField( controller: passwordController, saved: (value) {}, obSecure: true, validator: (value) { if (value!.isEmpty) { return 'Password is too short'; } return null; }, lable: "password", icon: const Icon(Icons.lock_outline), suffixicon: const Icon(Icons.visibility_outlined), ), const SizedBox(height: 20), deafualtTextformField( controller: phoneController, saved: (value) {}, obSecure: false, validator: (value) { if (value!.isEmpty) { return 'Phone is too short'; } return null; }, lable: "Phone", icon: const Icon(Icons.phone), ), const SizedBox(height: 30), ConditionalBuilderRec( condition: state != UserRegisterLodingState(), builder: (context) { return FlatButton( onPressed: () { if (formKey.currentState!.validate()) { SocialRegisterCubit.get(context).userRegister( email: emailController.text, name: nameController.text, phone: phoneController.text, password: passwordController.text, ); } }, child: const Text( 'REGISTER ', style: TextStyle(color: Colors.white), ), color: Colors.blue, minWidth: 400, height: 50, ); }, fallback: (context) => const Center(child: CircularProgressIndicator()), ), const SizedBox(height: 15), ], ), ), ), ), ), ); }, ), ); } }
import { Service } from "typedi"; import FARM_ABI from "../constants/farm_abi"; import { Logger } from "winston"; import { FARM_ADDRESS, PAIR_CONTRACT_ABI, RPC_URL, BLOCKS_PER_YEAR} from "../constants"; import TokenListSelector from "../constants/tokenAddress"; import Web3 from "web3"; @Service() export default class FarmService { farmModel: any; chainId: any; logger: Logger; supportedTokens: any; constructor( models, logger, chainId ) { this.farmModel = models.farmModel; this.chainId = chainId; this.logger = logger; this.supportedTokens = TokenListSelector(chainId); } public getTokenSymbol(address) { return this.supportedTokens.find(token => token.address.toLowerCase() == address.toLowerCase()).symbol; } public async massUpdateFarm() { try { this.logger.debug("updating in massUdpdateFarm..."); const web3 = new Web3(RPC_URL[this.chainId]); const contract = new web3.eth.Contract(FARM_ABI, FARM_ADDRESS[this.chainId]); const numPools = await contract.methods.numPools().call(); for(var poolId = 0 ; poolId < numPools ; poolId++) { this.updatePoolNew(poolId) } return true; }catch (e){ console.log("FARM UPDATE FAILED with error",e); } } public async getAllPools() { let farms = await this.farmModel.find(); if(farms) return farms; return []; } public async getPool(poolId) { let farm = await this.farmModel.findOne({poolId:poolId}); if(farm) return farm; return null; } public async testFarm(){ const testPrice = this.updatePoolNew(0); return testPrice } public async updatePoolNew(poolId) { const web3 = new Web3(RPC_URL[this.chainId]); const contract = new web3.eth.Contract(FARM_ABI, FARM_ADDRESS[this.chainId]); const [poolInfo, poolRewardTokens, rewardTokensAddresses, poolPositons] = await Promise.all([ contract.methods.poolInfo(poolId).call(), contract.methods.getPoolRewardTokens(poolId).call(), contract.methods.getPoolRewardTokenAddresses(poolId).call(), contract.methods.getPoolPositions(poolId).call() ]); const rewardTokensSymbols = rewardTokensAddresses.map(address => this.supportedTokens.find(token => token.address.toLowerCase() == address.toLowerCase()) ); let token0; let token1; let lpDecimals = 18; const pairTokens = []; try { const lpTokenContract = new web3.eth.Contract(PAIR_CONTRACT_ABI, poolInfo[0]); [token1, token0, lpDecimals] = await Promise.all([ lpTokenContract.methods.token1().call(), lpTokenContract.methods.token0().call(), lpTokenContract.methods.decimals().call() ]); pairTokens.push(token0); pairTokens.push(token1); } catch (e) { // not a lp token, maybe a single token? token0 = poolInfo[0]; token1 = null; pairTokens.push(token0); } const lpToken = { address: poolInfo[0], decimals: lpDecimals, lpBalance: poolInfo[1], lpScore: poolInfo[2], } const startBlock = poolInfo[4]; const endBlock = poolInfo[5]; const tokens = pairTokens.map(address => { let token = this.supportedTokens.find(token => token.address.toLowerCase() == address.toLowerCase()); return { symbol: token.symbol, logoURI: token.logoURI, address: token.address, decimals: token.decimals } }) const [allTokenAmount, poolRewardsPerYear] = await Promise.all([ // this.getPoolPositionInfo(poolId, poolPositons, contract), this.getPoolAccumulateRewards(poolId, poolRewardTokens, poolPositons, contract), this.getPoolRewardsPerYear(poolId, poolRewardTokens, contract) ]); const rewardTokens = rewardTokensSymbols.map((token,i) => { return { symbol: token.symbol, logoURI: token.logoURI, address: token.address, decimals: token.decimals, farmToken: poolRewardTokens[i], rewardPerYear: poolRewardsPerYear[i], accumulateReward: allTokenAmount[i] }; }); const find = await this.farmModel.findOne({poolId}).exec(); if(find) { const created = await this.farmModel.updateOne( { poolId }, { poolId, lpToken, tokens, rewardTokens, startBlock, endBlock }, (err, data) => { if (err) { this.logger.debug(`Mongo update new farm error ${err}`); return false; } this.logger.debug(`Mongo update a new farm record`); return data; }); } else { const created = await this.farmModel.create( { poolId, lpToken, tokens, rewardTokens, startBlock, endBlock }, (err, data) => { if (err) { this.logger.debug(`Mongo update new farm error ${err}`); return false; } this.logger.debug(`Mongo update a new farm record`); return data; }); } return true; } public async getPoolAccumulateRewards(poolId, poolRewardTokens, poolPositons, contract){ const totalRewards = poolRewardTokens.map(rewardToken => { return poolPositons.map(position => contract.methods.getTotalRewards(poolId, position, rewardToken).call()); }); const allTokenAmountPromise = totalRewards.map(reward => Promise.all(reward)) return Promise.all(allTokenAmountPromise).then(rewards => { return rewards.map(reward => reward.reduce((total, currentAmount) => total += parseInt(currentAmount),0)); }); } public async getPoolRewardsPerYear(poolId, poolRewardTokens, contract) { const poolTokenRewardInfoPromise = poolRewardTokens.map(rewardToken => contract.methods.getPoolTokenRewardInfo(poolId,rewardToken).call() ); return Promise.all(poolTokenRewardInfoPromise).then(result => { return result.map(info => info[3] * BLOCKS_PER_YEAR[this.chainId]) }) } public async getPoolPositionInfo(poolId, poolPositons, contract) { const position = poolPositons.map(positionId => contract.methods.stakingPosition(poolId,positionId).call() ); return Promise.all(position).then( stakesData => stakesData.map((data,i) => { return { positionId: poolPositons[i], address: data[0], lpAmount: data[1], stakeTimestamp: data[2], lockDuration: data[3] }}) ); } }
package com.ohgiraffers.section01; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.Persistence; import org.junit.jupiter.api.*; public class A_EntityManagerLifeCycleTests { /* ํ•„๊ธฐ. * entity manager factory ๋ž€? * 1. entity manager ๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๋Š” ํŒฉํ† ๋ฆฌ ํด๋ž˜์Šค์ด๋‹ค. * 2. thread-safe ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์—ฌ๋Ÿฌ thread ๊ฐ€ ๋™์‹œ์— ์ ‘๊ทผํ•ด๋„ ์•ˆ์ „ํ•จ. ์„œ๋กœ ๋‹ค๋ฅธ thread ๊ฐ„ ๊ณต์œ ํ•ด์„œ ์žฌ์‚ฌ์šฉํ•œ๋‹ค. * 3. thread-safe ํ•œ ๊ธฐ๋Šฅ์„ ์š”์ฒญ ์Šค์ฝ”ํ”„๋งˆ๋‹ค ์ƒ์„ฑํ•˜๊ธฐ์—๋Š” ๋น„์šฉ(์‹œ๊ฐ„, ๋ฉ”๋ชจ๋ฆฌ) ๋ถ€๋‹ด์ด ํฌ๋ฏ€๋กœ * application ์Šค์ฝ”ํ”„์™€ ๋™์ผํ•˜๊ฒŒ ์‹ฑ๊ธ€ํ†ค์œผ๋กœ ์ƒ์„ฑํ•ด์„œ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ํšจ์œจ์ ์ด๋‹ค. * 4. ๋”ฐ๋ผ์„œ DB ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋‹น ํ•œ ๊ฐœ์˜ EntityManagerFactory ๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. * . * * thread-safe: ์Šค๋ ˆ๋“œ ์—ฌ๋Ÿฌ๊ฐœ๊ฐ€ ๋™์‹œ์— ๋Œ์•„๊ฐ€์ง€ ์•Š๋Š”๋‹ค. * * ํ•„๊ธฐ. * entity manager ๋ž€? * 1. entity manager ๋Š” entity ๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฉ”๋ชจ๋ฆฌ ์ƒ์˜ DB ๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ์ธ์Šคํ„ด์Šค์ด๋‹ค. * 2. entity ๋ฅผ ์ €์žฅํ•˜๊ณ , ์ˆ˜์ •, ์‚ญ์ œ, ์กฐํšŒํ•˜๋Š” ๋“ฑ์˜ entity ์˜ ๊ด€๋ จ๋œ ๋ชจ๋“  ์ผ์„ ํ•œ๋‹ค. * 3. entity manager ๋Š” thread-safe ํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ๋™์‹œ์„ฑ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค. * 4. ๋”ฐ๋ผ์„œ thread ๊ฐ„ ๊ณต์œ ๋ฅผ ํ•˜์ง€ ์•Š๊ณ , web์˜ ๊ฒฝ์šฐ ์ผ๋ฐ˜์ ์œผ๋กœ request scope ์™€ ์ผ์น˜์‹œํ‚จ๋‹ค. * * ํ•„๊ธฐ. * ์˜์†์„ฑ ์ปจํ…์ŠคํŠธ(PersistenceContext)๋ž€? * 1. entity manager ๋ฅผ ํ†ตํ•ด entity ๋ฅผ ์ €์žฅํ•˜๊ฑฐ๋‚˜ ์กฐํšŒํ•˜๋ฉด entity manager ๋Š” ์˜์†์„ฑ ์ปจํ…์ŠคํŠธ์— entity ๋ฅผ ๋ณด๊ด€ํ•˜๊ณ  ๊ด€๋ฆฌํ•œ๋‹ค. * 2. ์˜์†์„ฑ ์ปจํ…์ŠคํŠธ๋Š” entity ๋ฅผ key-value ๋ฐฉ์‹์œผ๋กœ ์ €์žฅํ•˜๋Š” ์ €์žฅ์†Œ์ด๋‹ค. * 3. ์˜์†์„ฑ ์ปจํ…์ŠคํŠธ๋Š” entity manager ๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ๊ฐ™์ด ํ•˜๋‚˜ ๋งŒ๋“ค์–ด์ง„๋‹ค. * 4. ๊ทธ๋ฆฌ๊ณ  entity manager ๋ฅผ ํ†ตํ•ด์„œ ์˜์†์„ฑ ์ปจํ…์ŠคํŠธ์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๊ณ , ๋˜ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค. * */ private static EntityManagerFactory entityManagerFactory; private EntityManager entityManager; @BeforeAll public static void initFactory() { entityManagerFactory = Persistence.createEntityManagerFactory("jpatest"); // jpatest ๋ผ๋Š” ์œ ๋‹›์— ๋งž๊ฒŒ factory ๋ฅผ ์ƒ์„ฑ } @BeforeEach public void initManager() { entityManager = entityManagerFactory.createEntityManager(); } @Test public void check_lifeCycle_of_entityManagerFactory_and_entityManager1() { // ์—”ํ‹ฐํ‹ฐ_๋งค๋‹ˆ์ €_ํŒฉํ† ๋ฆฌ์™€_์—”ํ‹ฐํ‹ฐ_๋งค๋‹ˆ์ €_์ƒ๋ช…์ฃผ๊ธฐ_ํ™•์ธ1 System.out.println("entityManagerFactory.hashCode:" + entityManagerFactory.hashCode()); System.out.println("entityManager.hashCode:" + entityManager.hashCode()); } @Test public void check_lifeCycle_of_entityManagerFactory_and_entityManager2() { // ์—”ํ‹ฐํ‹ฐ_๋งค๋‹ˆ์ €_ํŒฉํ† ๋ฆฌ์™€_์—”ํ‹ฐํ‹ฐ_๋งค๋‹ˆ์ €_์ƒ๋ช…์ฃผ๊ธฐ_ํ™•์ธ2 System.out.println("entityManagerFactory.hashCode:" + entityManagerFactory.hashCode()); System.out.println("entityManager.hashCode:" + entityManager.hashCode()); } @AfterAll public static void closeFactory() { entityManagerFactory.close(); } @AfterEach public void closeManager() { entityManager.close(); } }
๏ปฟ//// |metadata| { "name": "wingrid-using-different-editors-in-individual-cells", "controlName": ["WinGrid"], "tags": ["Application Scenarios","Extending","Grids"], "guid": "{CF4C213D-092A-4CC0-A2FC-87B43B64B28E}", "buildFlags": [], "createdOn": "0001-01-01T00:00:00Z" } |metadata| //// = Using Different Editors in Individual Cells In addition to using Embeddable Editors on a Column level, they can also be set at the Cell level. If you specify a particular Editor for a Column, then only one instance of that Editor is shared for all Cells in that Column. If you specify an Editor on an individual Cell, then that one Cell will use that single instance of the Editor. Most use cases require one editor to be assigned to the entire column. For example, the OrderDate Column may be configured to use WinCalendarComboโ„ข so that end users can navigate and select a Date value from the drop down calendar that appears within the cells of that column. Less frequent use cases require a different editor on a cell by cell basis. For example, you may have a column called Value that can represent different kinds of data types. Row 1 can have a Value cell which is a number, so you can create and assign a Numeric editor for that particular cell. Row 2โ€™s Value cell may contain a Date data type, which can be represented using an instance of the WinCalendarCombo. Row 3โ€™s Value cell may represent a Boolean which can be represented by an instance of the WinCheckEditorโ„ข control. Either way, WinGridโ„ข supports both scenarios. == Accommodating Multiple Data Types Usually to accommodate for multiple data types, you will need a data model that has a property that can accommodate for multiple data types. The following code example shows a simple implementation using a DataTable: *In Visual Basic:* ---- Dim t As New DataTable t.Columns.Add("Col_1", GetType(Object)) t.Rows.Add(New Object() {Color.Red}) t.Rows.Add(New Object() {False}) t.Rows.Add(New Object() {"Hello"}) t.Rows.Add(New Object() {Color.Blue}) t.Rows.Add(New Object() {True}) t.Rows.Add(New Object() {"Goodbye"}) ---- *In C#:* ---- DataTable t = new DataTable(); t.Columns.Add("Col_1", typeof(object)); t.Rows.Add(new object[] { Color.Red }); t.Rows.Add(new object[] { false }); t.Rows.Add(new object[] { "Hello" }); t.Rows.Add(new object[] { Color.Blue }); t.Rows.Add(new object[] { true }); t.Rows.Add(new object[] { "Goodbye" }); ---- An appropriate event to test for and assign different editor types is the WinGridโ€™s InitializeRow event. This event will fire once for each WinGrid Row that is being rendered. The event arguments will expose each Row as it comes in through the event. Here is where you can perform your tests and depending on the results, you can assign different editors to the cells of interest. The following code shows how the InitializeRow event is being handled in order to test the Data Type of a specific Cell Value and then assign the appropriate editor to that Cell: *In Visual Basic:* ---- Imports Infragistics.Win Imports Infragistics.Win.UltraWinEditors ... Private Sub UltraGrid1_InitializeRow( _ ByVal sender As System.Object, _ ByVal e As InitializeRowEventArgs) _ Handles UltraGrid1.InitializeRow 'Create the Settings Object: Dim theSettings As New DefaultEditorOwnerSettings 'as well as the Editor Owner: Dim theOwner As New DefaultEditorOwner(theSettings) Dim theEditor As EmbeddableEditorBase = Nothing Dim theValue As Object = e.Row.Cells(0).Value 'Create an appropriate editor based on the 'Value's Data Type: If TypeOf theValue Is Boolean Then theSettings.DataType = GetType(Boolean) theEditor = New CheckEditor(theOwner) ElseIf TypeOf theValue Is Color Then theSettings.DataType = GetType(Color) theEditor = New ColorPickerEditor(theOwner) ElseIf TypeOf theValue Is String Then theSettings.DataType = GetType(String) theEditor = New EditorWithText(theOwner) End If 'Assign it to the Cell.Editor e.Row.Cells(0).Editor = theEditor End Sub ---- *In C#:* ---- using Infragistics.Win; using Infragistics.Win.UltraWinEditors; ... private void ultraGrid1_InitializeRow( object sender, Infragistics.Win.UltraWinGrid.InitializeRowEventArgs e) { //Create the Settings Object: DefaultEditorOwnerSettings theSettings = new DefaultEditorOwnerSettings(); //as well as the Editor Owner: DefaultEditorOwner theOwner = new DefaultEditorOwner(theSettings); EmbeddableEditorBase theEditor = null; object theValue = e.Row.Cells[0].Value; //Create an appropriate editor based on the //Value's Data Type: if (theValue is bool) { theSettings.DataType = typeof(bool); theEditor = new CheckEditor(theOwner); } else if (theValue is Color) { theSettings.DataType = typeof(Color); theEditor = new ColorPickerEditor(theOwner); } else if (theValue is string) { theSettings.DataType = typeof(string); theEditor = new EditorWithText(theOwner); } //Assign it to the Cell.Editor e.Row.Cells[0].Editor = theEditor; } ---- As each Row is being initialized, Cell 0's Value is being examined in order to determine its Data Type. If it is a Boolean, then we create a new instance of the CheckEditor and assign it to that Cell. If it is a Color, then we create a new instance of the Color Picker and assign it to that Cell. Finally if it is a String, we create a standard EditorWithText and assign it to that Cell. This can be elaborated to include more complex logic as well as diverse Data Types. When run, the grid will look similar to the following: image::images/WinGrid_Using_Different_Editors_in_Individual_Cells_01.png[using different editors in individual cells in ultragrid] If you notice in the code, the class DefaultEditorOwnerSettings is being used. This is simply a class that contains property settings that will be applied to the various Editor Controls that it is associated with. The DefaultEditorOwnerSettings Class contains properties that allow you to configure the Mask characteristics, Formatting, Data Type, Minimum and Maximum Character Length as well as Minimum and Maximum Value. Whenever we assign editors on a Cell by Cell basis, we need to construct the Editors on a lower level much like we have shown in this example. Now that you understand how to implement both Column and Cell level Editors, you can build a UI that can accommodate any of these use cases.
<!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"> <meta name="description" content="Pooches and Pints, social meet ups for people and their dogs in manchester"> <meta name="keywords" content="pooches and pints, dog walking, Manchester"> <link rel="stylesheet" href="assets/css/style.css"> <title>Pooches and Pints</title> </head> <body> <!--HEADER CONTAINER--> <!--heading, logo and nav bar, same as index.html page--> <header class="header-container"> <div class="logo-title"> <div> <a href="index.html"> <img class="logo" src="assets/images/pooches_and_pints_logo.png" alt="pooches and pints logo"> </a> </div> <div> <h1 class="title">Pooches & Pints</h1> </div> </div> <nav class="menu"> <div> <ul> <li> <a href="index.html" class="active">Home</a> </li> <li> <a href="locations.html">Locations</a> </li> <li> <a href="index.html#events-title">Events</a> </li> <li> <a href="join_us.html">Join Us</a> </li> </ul> </div> </nav> </header> <section> <!--LOCATION CONTAINER--> <!--flexbox used to organise locations boxes for responsive design--> <div class="location-container"> <!--canal location box containing image of a canal and details of walk--> <div id="canal-walk" class="location-box"> <!--image of canal for canal walk location--> <div class="location-image"> <img src="./assets/images/canal.webp" alt="Canal in the city"> </div> <!--meeting information for canal walk--> <div class="location-content"> <!--canal heading and icon--> <h4>Canal Walk - City Centre <i class="fa-solid fa-city"></i></h4> <!--canal schedule info--> <ul> <li>Meet up point: Deansgate train station</li> <li>Duration: 2 hours</li> <li>Pub/ Restaurant : The Wharf</li> <li>Drive time: N/A</li> </ul> </div> </div> <!--lakeside location box containing lakeside image, with details of walk--> <div id="lakeside-walk" class="location-box"> <!--image of man and dog lakeside, with walk location information--> <div class="location-image"> <img src="./assets/images/man-and-dog-by-lake.webp" alt="Man and dog walking by a lake"> </div> <!--meeting information for lakeside walk--> <div class="location-content"> <!--lakeside heading and icon--> <h4>Lakeside Stroll - Sale Waterpark <i class="fa-solid fa-water"></i></h4> <!--lakeside walk schedule info--> <ul> <li>Meet up point: Deansgate train station</li> <li>Duration: 4 hours</li> <li>Pub/ Restaurant : The Boathouse</li> <li>Drive time: 20 Minutes</li> </ul> </div> </div> <!--forest location box containing forest image, with details of walk--> <div class="location-box"> <!--image of man and dog lakeside, with walk location information--> <div id="forest-adventure" class="location-image"> <img src="./assets/images/dog-and-women-in-forest.webp" alt="One dog and two people in a forest"> </div> <!--meeting information for forest walk--> <div class="location-content"> <!--forest heading and icon--> <h4>Forest Adventure - Delamere Forest <i class="fa-solid fa-tree"></i></h4> <!--forest walk schedule info--> <ul> <li>Meet up point: Deansgate train station</li> <li>Duration: 5 hours</li> <li>Pub/ Restaurant : The Fishpool Inn</li> <li>Drive time: 50 Minutes</li> </ul> </div> </div> </div> </section> <!--MAP SECTION--> <!--container for map and description to ensure responsive design--> <div class="map-container"> <!--description of meeting point for all walks--> <div class="map-description"> <p> We begin all walks at Deansgate train staion in the centre of Manchester. </p> <p> Address: Deansgate, Manchester M3 4LG </p> </div> <!--iframe containing map of start point for all walks--> <div class="map"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2374.6801890223383!2d-2.253188684615538!3d53.47417547283034!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x487bb1e6281dd63f%3A0xf540b03ce1c8a95c!2sDeansgate!5e0!3m2!1sen!2suk!4v1646602992383!5m2!1sen!2suk" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"></iframe> </div> <div> <!--join up buttion linking to join us page--> <a class="join-us" href="join_us.html">Join Us</a> </div> </div> <!--FOOTER SECTION--> <!--footer items in 3 flex containers for responsive design when in row and column depending on device size--> <footer class="footer-wrapper"> <!--container 3 social links--> <ul class="footer-container"> <!--link to facebook page, opening blank page--> <li> <a href="https://facebook.com" target="_blank" rel="noopener" aria-label="Visit our Facebook page (opens in a new tab)"><i class="fab fa-facebook-square"></i></a> </li> <!--link to twitter page, opening blank page--> <li> <a href="https://twitter.com" target="_blank" rel="noopener" aria-label="Visit our Twitter page (opens in a new tab)"><i class="fab fa-twitter-square"></i></a> </li> <!--link to instagram page, opening blank page--> <li> <a href="https://instagram.com" target="_blank" rel="noopener" aria-label="Visit our Instagram page (opens in a new tab)"><i class="fab fa-instagram-square"></i></a> </li> </ul> <!--container for sign up form with placeholder and submit button--> <form class="footer-container" method="POST" action="https://formdump.codeinstitute.net/"> <input id="email-newsletter" type="email" name="email" placeholder="Enter email for Newsletter" required> <button type="submit" class="icon-button"><i class="fa-solid fa-user-plus"></i></button> </form> <!--button for to top of page button--> <div class="footer-container"> <a class="icon-button" href="index.html"><i class="fa-solid fa-angles-up"></i></a> </div> </footer> <!-- font awesome script --> <script src="https://kit.fontawesome.com/b7fb006b67.js" crossorigin="anonymous"></script> </body> </html>
#include <pso/particle_swarm_optimization.h> #include <common/random.h> namespace core { ParticleSwarmOptimization::ParticleSwarmOptimization(const FunctionApproximation& fa, const SearchSpace& searchSpace, const Parameter& parameter) : m_fa{ fa }, m_searchSpace{ searchSpace }, m_parameter{ parameter } { initSwarm(); evaluate(); } ParticleSwarmOptimization::~ParticleSwarmOptimization() { } void ParticleSwarmOptimization::initSwarm() { const size_t swarmSize = m_parameter.getSwarmSize(); m_swarm.particles.resize(swarmSize); for (size_t i = 0; i < swarmSize; i++) { auto& pos = m_swarm.particles[i].pos; auto& vel = m_swarm.particles[i].vel; for (size_t i = 0; i < numCoefficients; i++) { pos.coords[i] = random::get(m_searchSpace.pos.min, m_searchSpace.pos.max); vel.coords[i] = random::get(m_searchSpace.vel.min, m_searchSpace.vel.max); } } } void ParticleSwarmOptimization::step() { calculateVelocity(); for (auto& particle : m_swarm.particles) particle.pos += particle.vel; evaluate(); } void ParticleSwarmOptimization::evaluate() { for (auto& particle : m_swarm.particles) { if (fitness(particle.pos) < fitness(particle.opt)) { particle.opt = particle.pos; if (fitness(particle.pos) < fitness(m_swarm.globalOpt)) { m_swarm.globalOpt = particle.pos; } } } } void ParticleSwarmOptimization::calculateVelocity() { for (auto& particle : m_swarm.particles) { float rand1 = random::get<float>(0.0f, 1.0f); float rand2 = random::get<float>(0.0f, 1.0f); particle.vel = m_parameter.getOmega() * particle.vel + m_parameter.getPhiLocal() * rand1 * (particle.opt - particle.pos) + m_parameter.getPhiGlobal() * rand2 * (m_swarm.globalOpt - particle.pos); } } float ParticleSwarmOptimization::fitness(const Vec& position) const { return m_fa.objective(std::vector<float>(position.coords, position.coords + numCoefficients)); } }
import { IssueType } from '../../../types/type'; import * as S from './IssueListItem.styled'; interface IssueListItemProps { issue: IssueType; } const IssueListItem = ({ issue }: IssueListItemProps) => { const formattedDate = new Date(issue.created_at).toLocaleDateString('ko-KR', { year: 'numeric', month: 'long', day: 'numeric', }); return ( <S.IssueItemWrapper> <div> <S.TitleWrapper> <span>{`#${issue.number}`}</span> <S.Title>{issue.title}</S.Title> </S.TitleWrapper> <S.UserWrapper> <span>{`์ž‘์„ฑ์ž: ${issue.user.login}`}</span> <span>{`, ์ž‘์„ฑ์ผ: ${formattedDate}`}</span> </S.UserWrapper> </div> <S.Comment>{`์ฝ”๋ฉ˜ํŠธ: ${issue.comments}`}</S.Comment> </S.IssueItemWrapper> ); }; export default IssueListItem;
/** * Author: Kulikov Pavel (Crystal2033) * Date: 10.01.2024 */ package org.crystal.qrserviceinventarization.controller; import io.swagger.v3.oas.annotations.parameters.RequestBody; import org.crystal.qrserviceinventarization.database.dto.OrganizationDTO; import org.crystal.qrserviceinventarization.service.impl.OrganizationServiceImpl; import org.crystal.qrserviceinventarization.service.interfaces.OrganizationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.security.Principal; import java.util.List; @RestController @RequestMapping("/api/organizations") public class OrganizationController { private final OrganizationService organizationService; @Autowired public OrganizationController(OrganizationService organizationService) { this.organizationService = organizationService; } @GetMapping("/{orgId}") public ResponseEntity<OrganizationDTO> getOrganizationById(@PathVariable Long orgId) { var organizationDTO = organizationService.getOrganizationById(orgId); return new ResponseEntity<>(organizationDTO, HttpStatus.OK); } @GetMapping public ResponseEntity<List<OrganizationDTO>> getAllOrganizations(Principal principal) { System.out.println(principal); var organizationsDTO = organizationService.getAllOrganizations(); return new ResponseEntity<>(organizationsDTO, HttpStatus.OK); } @PostMapping public ResponseEntity<OrganizationDTO> saveOrganization(@RequestBody OrganizationDTO organizationDTO) { var savedOrganizationDTO = organizationService.saveOrganization(organizationDTO); return new ResponseEntity<>(savedOrganizationDTO, HttpStatus.CREATED); } @DeleteMapping("/{orgId}") public void deleteOrganization(@PathVariable Long orgId) { organizationService.deleteOrganizationById(orgId); } }
<script setup lang="ts"> import hljs from 'highlight.js/lib/core'; import 'highlight.js/styles/panda-syntax-dark.css'; import javascript from 'highlight.js/lib/languages/javascript'; import json from 'highlight.js/lib/languages/json'; import { onMounted, ref, Ref } from 'vue'; import Lienzo from '../componentes/Lienzo.vue'; import { Datos } from '../tipos'; import { usarCerebroGeneral } from '../cerebros/general'; hljs.registerLanguage('javascript', javascript); hljs.registerLanguage('json', json); const cerebro = usarCerebroGeneral(); const calidad: Ref<HTMLInputElement | null> = ref(null); const formatoImagen: Ref<HTMLSelectElement | null> = ref(null); const formatoDatos: Ref<HTMLSelectElement | null> = ref(null); const datos: Ref<string | null> = ref(null); const valorCalidad = ref(1); const nombreArchivo = ref(cerebro.nombre); let nombre = ''; onMounted(() => { actualizarDatos(); }); function actualizarDatos() { if (!cerebro.archivoActual || !calidad.value || !formatoImagen.value || !formatoDatos.value) return null; const { ancho, alto, columnas, filas, archivoActual } = cerebro; const { valueAsNumber: valorCalidad } = calidad.value; nombre = `${nombreArchivo.value}_${columnas}x${filas}-${ancho}x${alto}_${valorCalidad}.${formatoImagen.value.value}`; const respuesta: Datos = { fuente: `/${nombre}`, ancho, alto, columnas, filas, fotogramas: [], }; const { imagenes } = archivoActual; if (imagenes) { let columna = 0; let fila = 0; const anchoFotograma = (ancho / columnas) | 0; const altoFotograma = (alto / filas) | 0; respuesta.fotogramas = imagenes.map(() => { const x = columna * anchoFotograma; const y = fila * altoFotograma; if (columna < columnas - 1) { columna++; } else { fila++; columna = 0; } return { x, y, ancho: anchoFotograma, alto: altoFotograma }; }); } if (formatoDatos.value.value === 'json') { datos.value = hljs.highlight(JSON.stringify(respuesta, null, 2), { language: 'json' }).value; return; } else if (formatoDatos.value.value === 'js') { const js = `const ${nombreArchivo.value} = { fuente: '${respuesta.fuente}', ancho: ${respuesta.ancho}, alto: ${respuesta.alto}, columnas: ${respuesta.columnas}, filas: ${respuesta.filas}, fotogramas: [ ${respuesta.fotogramas ?.map((fotograma) => { return `{x: ${fotograma.x}, y: ${fotograma.y}, ancho: ${fotograma.ancho}, alto: ${fotograma.alto}},`; }) .join(`\n `)} ] };`; datos.value = hljs.highlight(js, { language: 'javascript' }).value; return; } return ''; } function actualizarCalidad({ target }: Event) { const { value } = target as HTMLInputElement; if (value) { valorCalidad.value = +value; } actualizarDatos(); } function actualizarNombre({ target }: Event) { const { value } = target as HTMLInputElement; if (value) { nombreArchivo.value = value; } actualizarDatos(); } function exportar() { if (cerebro.mensajero && cerebro.imagen) { cerebro.mensajero.postMessage({ llave: 'exportar', nombre, formato: formatoImagen.value ? formatoImagen.value.value : 'webp', calidad: valorCalidad.value || 1, imagen: cerebro.imagen, }); } } </script> <template> <div class="contenedorPagina"> <div class="entradas"> <span class="entradaNombre">Nombre: </span> <input type="text" :value="nombreArchivo" @input="actualizarNombre" /> <span class="entradaNombre">Opciones: </span> <select @change="actualizarCalidad"> <option value="1">Mรกximo</option> <option value="0.8">Alto</option> <option value="0.5">Medio</option> <option value="0.1">Bajo</option> </select> <span class="entradaNombre">Calidad: </span> <input ref="calidad" class="opcionEntrada" type="number" min="0.1" max="1" step="0.01" :value="valorCalidad" @change="actualizarCalidad" /> <span class="entradaNombre">Formato Imagen: </span> <select ref="formatoImagen" @change="actualizarDatos"> <option value="webp">webp</option> <option value="png">png</option> <option value="jpeg">jpeg</option> </select> <span class="entradaNombre">Formato Datos: </span> <select ref="formatoDatos" @change="actualizarDatos"> <option value="js">js</option> <option value="json">json</option> </select> <button id="build" @click="exportar">Exportar Imagen</button> </div> <pre><code dangerousl v-if="datos" v-html="datos"></code></pre> <ul id="downloads-list"></ul> <Lienzo /> </div> </template> <style lang="scss" scoped> pre { background-color: #1d394a; padding: 2em; color: white; } </style>
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Todo } from 'src/app/welcome/welcome.component'; import { API_URL } from 'src/app/app.constants'; @Injectable({ providedIn: 'root' }) export class TodoDataService { constructor(private http: HttpClient) { } retrieveAllTodos(username: string){ const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa('user98' + ':' + 'dummy') }); return this.http.get<Todo[]>(`${API_URL}/users/${username}/todos`, {headers, responseType: 'json' }) } deleteTodo(username: string, id: number){ const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa('user98' + ':' + 'dummy') }); return this.http.delete(`${API_URL}/users/${username}/todos/${id}`, {headers, responseType: 'json' }) } retriveTodo(username: string, id: number){ const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa('user98' + ':' + 'dummy') }); return this.http.get<Todo>(`${API_URL}/users/${username}/todos/${id}`, {headers, responseType: 'json' }) } updateTodo(username: string, id: number, todo: Todo){ const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa('user98' + ':' + 'dummy') }); return this.http.put(`${API_URL}/users/${username}/todos/${id}`, todo, {headers, responseType: 'json' }); } createTodo(username: string, todo: Todo){ const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa('user98' + ':' + 'dummy') }); return this.http.post(`${API_URL}/users/${username}/todos`, todo, {headers, responseType: 'json' }); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Grid</title> <style> .container { display: grid; grid-gap: 21px; grid-template-areas: 'navbar navbar navbar navbar' 'section section section aside' 'footer footer footer footer'; } .item { background-color: yellow; border: 3px solid blue; padding :12px 12px; } #navbar { grid-area: navbar; } #section { grid-area: section; } #aside { grid-area: aside; } footer{ grid-area: footer; } </style> </head> <body> <div class="container"> <div id="navbar" class="item"> Home About ContactUs Help </div> <div id="section" class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim delectus, vitae cupiditate fugit animi ducimus dicta ab atque assumenda officiis facilis nam veniam!</div> <div id="aside" class="item">Lorem ipsum dolor sit amet consectetur adipisicing elit. Corrupti, molestias. Aperiam?</div> <!-- <div class="item">item-1</div> <div class="item">item-2</div> <div class="item">item-3</div> <div class="item">item-4</div> <div class="item">item-5</div> <div class="item">item-6</div> <div class="item">item-7</div> <div class="item">item-8</div> <div class="item">item-9</div> <div class="item">item-10</div> <div class="item">item-11</div> <div class="item">item-12</div> --> </div> <footer class="item">Lorem ipsum dolor sit amet consectetur adipisicing elit. Magnam modi enim id.</footer> </body> </html>
import React, { useCallback, useEffect, useState } from "react"; import { SettingsEvents, SettingsState, useSettingsMutation, } from "../../../../store/modules"; import { MAX_HEIGHT, MAX_WIDTH, MIN_HEIGHT, MIN_WIDTH, } from "../../../../shared/constants"; import { useStoreon } from "storeon/react"; import styles from "./styles.module.css"; const isWidthValid = (width: string): boolean => { return +MAX_WIDTH >= +width && +MIN_WIDTH <= +width; }; const isHeightValid = (height: string): boolean => { return +MAX_HEIGHT >= +height && +MIN_HEIGHT <= +height; }; export const OptionsPage = () => { const { popupWidth, popupHeight } = useStoreon<SettingsState, SettingsEvents>( "popupWidth", "popupHeight", "loading" ); const { setSettings, clearSettings } = useSettingsMutation(); const [localWidth, setLocalWidth] = useState<string>(""); const [localHeight, setLocalHeight] = useState<string>(""); useEffect(() => { setLocalWidth(popupWidth.toString()); setLocalHeight(popupHeight.toString()); }, [popupWidth, popupHeight]); const onSave = useCallback(() => { const newHeight = isHeightValid(localHeight) ? localHeight : popupHeight; const newWidth = isWidthValid(localWidth) ? localWidth : popupWidth; setSettings({ popupHeight: +newHeight, popupWidth: +newWidth, }); }, [localWidth, localHeight, popupWidth, popupHeight]); return ( <main className={styles.content}> <section className={styles.settings}> <div className={styles["settings-header"]}> <h2 className={styles["settings-header_text"]}>Settings</h2> <button className={styles["clear-storage"]} onClick={clearSettings}> Clear storage </button> </div> <div className={styles["settings-block settings-view"]}> <h3 className={styles["settings-block_header"]}>View</h3> <div className={styles["delimiter"]}></div> <div className={styles["setting-items"]}> <div className={styles["setting-item"]}> <div className={styles.left}> <h3 className={styles["setting-item_title"]}>Width</h3> <p className={styles["setting-item_description"]}> Setup width for note panel in the px. Min: 300, Max: 760 . </p> </div> <div className={styles["right"]}> <div className={styles.group}> <input type="text" value={localWidth} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setLocalWidth(e.target.value) } required /> <span className={styles.highlight}></span> <span className={styles.bar}></span> <label>px</label> </div> </div> </div> <div className={styles["setting-item"]}> <div className={styles.left}> <h3 className={styles["setting-item_title"]}>Height</h3> <p className={styles["setting-item_description"]}> Setup height for note panel in the px. Min: 300, Max: 540. </p> </div> <div className={styles.right}> <div className={styles.group}> <input type="text" value={localHeight} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setLocalHeight(e.target.value) } required /> <span className={styles.highlight}></span> <span className={styles.bar}></span> <label>px</label> </div> </div> </div> </div> </div> <button className={styles.save} onClick={onSave}> Save </button> </section> </main> ); };
# Playwright https://playwright.dev/docs/writing-tests ### Tests `tests/e2e/example.spec.js` ```javascript // @ts-check const {test, expect} = require('@playwright/test'); test.beforeEach(async ({page}) => { /** * navigate to the login screen */ await page.goto('/redaxo/index.php'); /** * check if the login input is present * add username */ await page.locator('input[id=rex-id-login-user]').fill('nightwatch_username'); /** * check if the password input is present * add password */ await page.locator('input[id=rex-id-login-password]').fill('nightwatch_password'); await page.locator('input[id=rex-id-login-password]').press('Enter'); /** * check if the session cookie is available /** * check if we are logged in to the backend */ await expect(page).toHaveURL('/redaxo/index.php?page=structure'); }); test('Test Addon functionality', async ({page}) => { /** * check if the username-link is available * click the username-link */ await page.locator('.navbar a.rex-username').click(); await expect(page).toHaveURL('/redaxo/index.php?page=profile'); // do stuff... /** * TODO: write some tests... */ }); ``` ## Resultat ```shell Running 1 test using 1 worker ok 1 [chromium] โ€บ example.spec.js:32:1 โ€บ Test Addon functionality (4s) 1 passed (6s) ```
#pragma once #include <functional> #include "SoundEngine.h" struct SoundEventInstanceHandle; typedef enum SERESULT { OK, ERR_BADCOMMAND, ERR_CHANNEL_ALLOC, ERR_CHANNEL_STOLEN, ERR_DMA, ERR_DSP_CONNECTION, ERR_DSP_DONTPROCESS, ERR_DSP_FORMAT, ERR_DSP_INUSE, ERR_DSP_NOTFOUND, ERR_DSP_RESERVED, ERR_DSP_SILENCE, ERR_DSP_TYPE, ERR_FILE_BAD, ERR_FILE_COULDNOTSEEK, ERR_FILE_DISKEJECTED, ERR_FILE_EOF, ERR_FILE_ENDOFDATA, ERR_FILE_NOTFOUND, ERR_FORMAT, ERR_HEADER_MISMATCH, ERR_HTTP, ERR_HTTP_ACCESS, ERR_HTTP_PROXY_AUTH, ERR_HTTP_SERVER_ERROR, ERR_HTTP_TIMEOUT, ERR_INITIALIZATION, ERR_INITIALIZED, ERR_INTERNAL, ERR_INVALID_FLOAT, ERR_INVALID_HANDLE, ERR_INVALID_PARAM, ERR_INVALID_POSITION, ERR_INVALID_SPEAKER, ERR_INVALID_SYNCPOINT, ERR_INVALID_THREAD, ERR_INVALID_VECTOR, ERR_MAXAUDIBLE, ERR_MEMORY, ERR_MEMORY_CANTPOINT, ERR_NEEDS3D, ERR_NEEDSHARDWARE, ERR_NET_CONNECT, ERR_NET_SOCKET_ERROR, ERR_NET_URL, ERR_NET_WOULD_BLOCK, ERR_NOTREADY, ERR_OUTPUT_ALLOCATED, ERR_OUTPUT_CREATEBUFFER, ERR_OUTPUT_DRIVERCALL, ERR_OUTPUT_FORMAT, ERR_OUTPUT_INIT, ERR_OUTPUT_NODRIVERS, ERR_PLUGIN, ERR_PLUGIN_MISSING, ERR_PLUGIN_RESOURCE, ERR_PLUGIN_VERSION, ERR_RECORD, ERR_REVERB_CHANNELGROUP, ERR_REVERB_INSTANCE, ERR_SUBSOUNDS, ERR_SUBSOUND_ALLOCATED, ERR_SUBSOUND_CANTMOVE, ERR_TAGNOTFOUND, ERR_TOOMANYCHANNELS, ERR_TRUNCATED, ERR_UNIMPLEMENTED, ERR_UNINITIALIZED, ERR_UNSUPPORTED, ERR_VERSION, ERR_EVENT_ALREADY_LOADED, ERR_EVENT_LIVEUPDATE_BUSY, ERR_EVENT_LIVEUPDATE_MISMATCH, ERR_EVENT_LIVEUPDATE_TIMEOUT, ERR_EVENT_NOTFOUND, ERR_STUDIO_UNINITIALIZED, ERR_STUDIO_NOT_LOADED, ERR_INVALID_STRING, ERR_ALREADY_LOCKED, ERR_NOT_LOCKED, ERR_RECORD_DISCONNECTED, ERR_TOOMANYSAMPLES, SERESULT_FORCEINT = 65536 } SERESULT; typedef enum CALLBACKTYPE { CALLBACKTYPE_CREATED = 0x00000001, CALLBACKTYPE_DESTROYED = 0x00000002, CALLBACKTYPE_STARTING = 0x00000004, CALLBACKTYPE_STARTED = 0x00000008, CALLBACKTYPE_RESTARTED = 0x00000010, CALLBACKTYPE_STOPPED = 0x00000020, CALLBACKTYPE_START_FAILED = 0x00000040, CALLBACKTYPE_CREATE_PROGRAMMER_SOUND = 0x00000080, CALLBACKTYPE_DESTROY_PROGRAMMER_SOUND = 0x00000100, CALLBACKTYPE_PLUGIN_CREATED = 0x00000200, CALLBACKTYPE_PLUGIN_DESTROYED = 0x00000400, CALLBACKTYPE_TIMELINE_MARKER = 0x00000800, CALLBACKTYPE_TIMELINE_BEAT = 0x00001000, CALLBACKTYPE_SOUND_PLAYED = 0x00002000, CALLBACKTYPE_SOUND_STOPPED = 0x00004000, CALLBACKTYPE_REAL_TO_VIRTUAL = 0x00008000, CALLBACKTYPE_VIRTUAL_TO_REAL = 0x00010000, CALLBACKTYPE_START_EVENT_COMMAND = 0x00020000, CALLBACKTYPE_NESTED_TIMELINE_BEAT = 0x00040000, CALLBACKTYPE_ANY = 0xFFFFFFFF } CALLBACKTYPE; template<class Class> class SoundEngineCallback { public: // This declares the type Raw with void args. typedef void (Class::*Raw)(CALLBACKTYPE aCallbackType, const std::string& anEventName, const SoundEventInstanceHandle& anInstanceHandle, CALLBACKTYPE anEventType); }; struct EventCallbackBase { int CallbackTypes; EventCallbackBase(int aType) : CallbackTypes(aType) {} virtual ~EventCallbackBase() = default; #pragma warning(disable: 4100) virtual void Broadcast(CALLBACKTYPE aCallbackType, const std::string& anEventName, const SoundEventInstanceHandle& anInstanceHandle, CALLBACKTYPE anEventType) {} #pragma warning(default: 4100) virtual bool IsValid() { return false; } }; template<class Class> struct EventCallbackRaw : public EventCallbackBase { std::weak_ptr<Class> CallbackOwner; //Class* CallbackOwner; typename SoundEngineCallback<Class>::Raw Callback; EventCallbackRaw(std::shared_ptr<Class> ownerPtr, int aType, typename SoundEngineCallback<Class>::Raw func) : EventCallbackBase(aType), CallbackOwner(ownerPtr), Callback(func) { } void Broadcast(CALLBACKTYPE aCallbackType, const std::string& anEventName, const SoundEventInstanceHandle& anInstanceHandle, CALLBACKTYPE anEventType) override { if(!CallbackOwner.expired()) { std::shared_ptr<Class> ptr = CallbackOwner.lock(); (*(ptr.get()).*Callback)(aCallbackType, anEventName, anInstanceHandle, anEventType); } } bool IsValid() override { return CallbackOwner.expired(); } }; struct EventCallbackLambda : public EventCallbackBase { typedef std::function<void(CALLBACKTYPE, const std::string&, const SoundEventInstanceHandle& anInstanceHandle, CALLBACKTYPE anEventType)> Lambda; Lambda aFunction; EventCallbackLambda(int aType, Lambda aLambda) : EventCallbackBase(aType), aFunction(std::move(aLambda)) { } void Broadcast(CALLBACKTYPE aCallbackType, const std::string& anEventName, const SoundEventInstanceHandle& anInstanceHandle, CALLBACKTYPE anEventType) override { aFunction(aCallbackType, anEventName, anInstanceHandle, anEventType); } bool IsValid() override { return true; } }; struct SoundEventInstanceHandle { friend struct SoundEngineImpl; private: std::string myEventName; int myInstance = -1; SoundEventInstanceHandle(const std::string& anEvent, int aHandleId); public: SoundEventInstanceHandle() = default; static SoundEventInstanceHandle InvalidHandle; int GetId() const; const std::string& GetEvent() const; bool IsValid() const; };
<?php use App\Http\Controllers\ProfileController; use App\Http\Controllers\Auth\GoogleController; use App\Http\Controllers\AccountController; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "web" middleware group. Make something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth', 'verified'])->name('dashboard'); Route::middleware('auth')->group(function () { Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit'); Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update'); Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy'); }); Route::get('auth/google',[GoogleController::class,'google'])->name('auth.google'); Route::get('auth/google/callback',[GoogleController::class,'googleCallback']); Route::get('account/create',[AccountController::class,'create'])->name('account.create'); Route::post('account/store',[AccountController::class,'store'])->name('account.store'); Route::get('accounts',[AccountController::class,'list'])->name('account.list'); Route::get('account/edit/{id}',[AccountController::class,'edit'])->name('account.edit'); Route::put('account/update/{id}',[AccountController::class,'update'])->name('account.update'); // ajax call Route::get('getbranch/{id}',[AccountController::class,'branches']); Route::get('getDistrict/{id}',[AccountController::class,'district']); Route::get('getThanas/{id}',[AccountController::class,'thanas']); Route::get('getCategory/{id}',[AccountController::class,'category']); require __DIR__.'/auth.php';
package com.whut.community.controller; import com.qiniu.util.Auth; import com.qiniu.util.StringMap; import com.whut.community.annotation.LoginRequired; import com.whut.community.entity.Comment; import com.whut.community.entity.DiscussPost; import com.whut.community.entity.Page; import com.whut.community.entity.User; import com.whut.community.service.*; import com.whut.community.util.CommunityConstant; import com.whut.community.util.CommunityUtil; import com.whut.community.util.CookieUtil; import com.whut.community.util.HostHolder; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/user") public class UserController implements CommunityConstant { private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Value("${community.path.upload}") private String uploadPath; @Value("${community.path.domain}") private String domain; @Value("${server.servlet.context-path}") private String contextPath; @Value("${qiniu.key.access}") private String accessKey; @Value("${qiniu.key.secret}") private String secretKey; @Value("${qiniu.bucket.header.name}") private String headerBucketName; @Value("${qiniu.bucket.header.url}") private String headerBucketUrl; private final UserService userService; private final HostHolder hostHolder; private LikeService likeService; private FollowService followService; private DiscussPostService discussPostService; private CommentService commentService; @Autowired public UserController(UserService userService, HostHolder hostHolder, LikeService likeService, FollowService followService, DiscussPostService discussPostService, CommentService commentService) { this.userService = userService; this.hostHolder = hostHolder; this.likeService = likeService; this.followService = followService; this.discussPostService = discussPostService; this.commentService = commentService; } // ่ฟ”ๅ›ž่ฎพ็ฝฎ้กต้ข(ๅœจ่ฟ™ไธช้กต้ขไธŠไผ ๅคดๅƒ)๏ผŒ // ๅœจ่ฟ™้‡Œๅฐ†ไธƒ็‰›ไบ‘ๆœๅŠกๅ™จ็š„ๅ‡ญ่ฏๆทปๅŠ ๅˆฐๆจกๆฟไธญ๏ผŒ // ๅฝ“่กจๅ•ๆไบคๆ—ถ๏ผŒ้กบๅธฆๅฐ†ๅ‡ญ่ฏๆไบค็ป™ไธƒ็‰›ไบ‘ๆœๅŠกๅ™จ๏ผŒๆ–‡ไปถๆ‰่ƒฝไธŠไผ ๆˆๅŠŸ @LoginRequired @GetMapping("/setting") public String getSettingPage(Model model) { // 1.ไธŠไผ ๅคดๅƒๆ–‡ไปถ็š„ๅ็งฐ String fileName = CommunityUtil.generateUUID(); // 2.่ฎพ็ฝฎๅ“ๅบ”ไฟกๆฏ(ๅธŒๆœ›ไธƒ็‰›ไบ‘ๆœๅŠกๅ™จ่ฟ”ๅ›ž็š„็ป“ๆžœ) StringMap policy = new StringMap(); policy.put("returnBody", CommunityUtil.getJSONString(0)); // 3.็”ŸๆˆไธŠไผ ๅ‡ญ่ฏ Auth auth = Auth.create(accessKey, secretKey); // ่ฟ›ๅ…ฅ headerBucketName ็ฉบ้—ด๏ผŒ // ไธŠไผ ๆ–‡ไปถๅไธบ fileName๏ผŒๅ‡ญ่ฏ่ฟ‡ๆœŸๆ—ถ้—ดไธบ 3600 ็ง’๏ผŒ // ๆœŸๆœ›่ฟ”ๅ›ž็ป“ๆžœๆ˜ฏ policy String uploadToken = auth.uploadToken(headerBucketName, fileName, 3600L, policy); // 4.ๅ‘ๆจกๆฟๆทปๅŠ ๆ•ฐๆฎ model.addAttribute("uploadToken", uploadToken); model.addAttribute("fileName", fileName); return "/site/setting"; } // ๆ›ดๆ–ฐๅคดๅƒ่ฎฟ้—ฎ่ทฏๅพ„ @PostMapping("/header/url") @ResponseBody public String updateHeaderUrl(String fileName) { if (StringUtils.isBlank(fileName)) { return CommunityUtil.getJSONString(1, "ๆ–‡ไปถๅไธ่ƒฝไธบ็ฉบ๏ผ"); } // ๆž„้€  headerUrl ๅนถๆ›ดๆ–ฐ็”จๆˆท็š„ headerUrl ๅฑžๆ€ง String headerUrl = headerBucketUrl + "/" + fileName; userService.updateHeader(hostHolder.getUser().getId(), headerUrl); return CommunityUtil.getJSONString(0); } // ไธŠไผ ๅˆฐไธƒ็‰›ไบ‘ๆœๅŠกๅ™จ๏ผŒๆญคๆ–นๆณ•ๅบŸๅผƒ // ไธŠไผ ๅคดๅƒๅ›พ็‰‡ @LoginRequired @PostMapping("/upload") public String uploadHeader(MultipartFile headerImage, Model model) { // 1.็ฉบๅ€ผๅค„็† if (headerImage == null) { model.addAttribute("error", "ๆ‚จ่ฟ˜ๆฒกๆœ‰้€‰ๆ‹ฉๅ›พ็‰‡๏ผ"); return "/site/setting"; } // 2.ไธบไบ†้ฟๅ…็”จๆˆทไผ ๅ…ฅ็š„ๅ›พ็‰‡ๅ้‡ๅค๏ผŒ้œ€่ฆ้šๆœบ็”Ÿๆˆๅ›พ็‰‡ๅๅญ— // 2.1ๆˆชๅ–ๆ–‡ไปถๅŽ็ผ€ String filename = headerImage.getOriginalFilename(); String suffix = null; if (!StringUtils.isBlank(filename)) { suffix = filename.substring(filename.lastIndexOf(".")); } if (StringUtils.isBlank(suffix)) { // ๆ–‡ไปถๆ ผๅผไธๆญฃ็กฎ model.addAttribute("error", "ๆ–‡ไปถๆ ผๅผไธๆญฃ็กฎ๏ผ"); return "/site/setting"; } // 2.1็”Ÿๆˆ้šๆœบๆ–‡ไปถๅ filename = CommunityUtil.generateUUID() + suffix; // 3.ๅˆ›ๅปบๆ–‡ไปถ็›ฎๅฝ•๏ผŒๅฐ†ๅ›พ็‰‡ๅ†™ๅ…ฅๅˆฐ็›ฎๅฝ•ไธญ File dest = new File(uploadPath + "/" + filename); try { headerImage.transferTo(dest); } catch (IOException e) { logger.error("ๆ–‡ไปถไธŠไผ ๅคฑ่ดฅ : " + e.getMessage()); throw new RuntimeException("ๆ–‡ไปถไธŠไผ ๅคฑ่ดฅ๏ผŒๆœๅŠกๅ™จๅ‘็”Ÿๅผ‚ๅธธ๏ผ", e); } // 4.ๆ›ดๆ–ฐๅฝ“ๅ‰็”จๆˆท็š„ๅคดๅƒ่ทฏๅพ„(web ็ซฏ่ฎฟ้—ฎ่ทฏๅพ„) // http://localhost:8080//community/user/header/xxx.png User user = hostHolder.getUser(); String headerUrl = domain + contextPath + "/user/header/" + filename; // ๆ‹ผๆŽฅ่ฎฟ้—ฎ่ทฏๅพ„ userService.updateHeader(user.getId(), headerUrl); // ้‡ๅฎšๅ‘ไปฅๅ…ๅ‘้€ๅคšๆฌก่ฏทๆฑ‚ return "redirect:/index"; } // ไปŽไธƒ็‰›ไบ‘ๆœๅŠกๅ™จไธญ่Žทๅ–ๅ›พ็‰‡๏ผŒๆญคๆ–นๆณ•ๅบŸๅผƒ // ่Žทๅ–ๅคดๅƒๅ›พ็‰‡ @GetMapping("/header/{fileName}") public void getHeaderImage(@PathVariable("fileName") String fileName, HttpServletResponse response) { // 1.่Žทๅ–ๆ–‡ไปถๅŽ็ผ€ String suffix = fileName.substring(fileName.lastIndexOf(".")); // 2.ๆž„ๅปบ่ฏฅๆ–‡ไปถๅœจๆœๅŠกๅ™จไธญ็š„ไฝ็ฝฎ String filePath = uploadPath + "/" + fileName; // 3.่Žทๅ–่พ“ๅ‡บๆต๏ผŒๆž„ๅปบ่พ“ๅ…ฅๆตๅนถๅ†™ๅ‡บๆ–‡ไปถ response.setContentType("image/" + suffix); try (ServletOutputStream os = response.getOutputStream(); FileInputStream fis = new FileInputStream(filePath)) { // ๅ“ๅบ”ๅ›พ็‰‡ byte[] buffer = new byte[2048]; int len; while ((len = fis.read(buffer)) != -1) { os.write(buffer, 0, len); } } catch (IOException e) { logger.error("่ฏปๅ–ๅคดๅƒๅคฑ่ดฅ : " + e.getMessage()); } } // ไฟฎๆ”นๅฏ†็  @LoginRequired @PostMapping("/updatePassword") public String updatePassword(String oldPassword, String newPassword, String confirmPassword, Model model, HttpServletRequest request) { // ็”จไบŽๅฐ†ๆœฌๆฌก่ฏทๆฑ‚ๅฏนๅบ”็š„ ticket ๆ”นไธบๅคฑๆ•ˆ็Šถๆ€ // ไปŽ็บฟ็จ‹ไธญ่Žทๅ–่ฏฅ็”จๆˆท User user = hostHolder.getUser(); // ่Žทๅ–็ป“ๆžœ Map<String, Object> map = userService.updatePassword(user, oldPassword, newPassword, confirmPassword); if (map.containsKey("user")) { // ๅค„็†ๆˆๅŠŸ // ไฟฎๆ”นๅฏ†็ ๅŽ๏ผŒๆœๅŠก็ซฏ่ฟ™่พนๆ‰€ๆœ‰ๅ’Œ่ฟ™ไธช็”จๆˆท็š„ๅ‡ญ่ฏๅบ”่ฏฅไฟฎๆ”นไธบๆ— ๆ•ˆ็Šถๆ€ String ticket = CookieUtil.getValue(request, "ticket"); userService.logout(ticket); // ๅนถไธ”ๆœๅŠก็ซฏไธญ่ฏฅ็บฟ็จ‹ๆŒๆœ‰็š„่ฟ™ไธช็”จๆˆทไนŸๅบ”่ฏฅ็งป้™ค hostHolder.clear(); // ๆทปๅŠ ๆ“ไฝœ็ป“ๆžœ็š„ไฟกๆฏ model.addAttribute("msg", "ๅฏ†็ ไฟฎๆ”นๆˆๅŠŸ๏ผ^_^"); model.addAttribute("target", "/login"); // ่ทณ่ฝฌๅˆฐ ๆ“ไฝœๆˆๅŠŸ ็•Œ้ข return "/site/operate-result"; } else { // ๅค„็†ๅคฑ่ดฅ model.addAttribute("oldPasswordMsg", map.get("oldPasswordMsg")); model.addAttribute("newPasswordMsg", map.get("newPasswordMsg")); model.addAttribute("confirmPasswordMsg", map.get("confirmPasswordMsg")); model.addAttribute("oldPassword", oldPassword); model.addAttribute("newPassword", newPassword); model.addAttribute("confirmPassword", confirmPassword); // ่ฟ”ๅ›žๅˆฐๅŽŸๆœฌ็š„้กต้ข return "/site/setting"; } } // ่ฟ”ๅ›žไธชไบบไธป้กต็š„้กต้ข @GetMapping("/profile/{userId}") public String getProfilePage(@PathVariable("userId") Integer userId, Model model) { // 1.ๆŸฅ่ฏข่ฏฅ็”จๆˆท User user = userService.findUserById(userId); if (user == null) { throw new IllegalArgumentException("่ฏฅ็”จๆˆทไธๅญ˜ๅœจ๏ผ"); } // 2.ๆทปๅŠ ็”จๆˆทๅฏน่ฑกๅ’Œ็‚น่ตžๆ•ฐ้‡ model.addAttribute("user", user); int likeCount = likeService.findUserLikeCount(user.getId()); model.addAttribute("likeCount", likeCount); // 3.ๆทปๅŠ ็”จๆˆทๅฏน่ฑก็š„ ๅ…ณๆณจๆ•ฐ้‡ใ€็ฒ‰ไธๆ•ฐ้‡ใ€ๅฝ“ๅ‰็”จๆˆทๆ˜ฏๅฆๅ…ณๆณจไบ†่ฟ™ไธช็”จๆˆท // ๅ…ณๆณจๆ•ฐ้‡ long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER); model.addAttribute("followeeCount", followeeCount); // ็ฒ‰ไธๆ•ฐ้‡ long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId); model.addAttribute("followerCount", followerCount); // ๅฝ“ๅ‰็”จๆˆทๆ˜ฏๅฆๅ…ณๆณจไบ†่ฟ™ไธช็”จๆˆท boolean hasFollowed = false; User curUser = hostHolder.getUser(); // ๅฝ“ๅ‰็”จๆˆท if (curUser != null) { hasFollowed = followService.hasFollowed(curUser.getId(), ENTITY_TYPE_USER, userId); } model.addAttribute("hasFollowed", hasFollowed); return "/site/profile"; } // ่ฟ”ๅ›žโ€œๆˆ‘็š„ๅธ–ๅญโ€้กต้ข๏ผŒๆ”ฏๆŒๅˆ†้กตๅŠŸ่ƒฝ @GetMapping("/myPost/{userId}") public String getMyPostPage(@PathVariable("userId") Integer userId, Model model, Page page, @RequestParam(name = "current", required = false) Integer current) { // 1.ๆŸฅ่ฏข่ฏฅ็”จๆˆท User user = userService.findUserById(userId); if (user == null) { throw new IllegalArgumentException("่ฏฅ็”จๆˆทไธๅญ˜ๅœจ๏ผ"); } // 2.ๆŸฅ่ฏขๅนถๆทปๅŠ ่ฏฅ็”จๆˆท็š„ๅธ–ๅญๆ•ฐ้‡ int discussPostCount = discussPostService.findDiscussPostRows(userId); model.addAttribute("discussPostCount", discussPostCount); // 3.ๅกซๅ…ฅๅˆ†้กตไฟกๆฏ page.setLimit(5); page.setPath("/user/myPost/" + userId); page.setRows(discussPostCount); if (current != null) { page.setCurrent(current); } // 4.ๆŸฅ่ฏขๅนถๆทปๅŠ ่ฏฅ็”จๆˆทๅ‘ๅธƒ็š„ๅธ–ๅญ้›†ๅˆ(้ป˜่ฎค็š„ไฝฟ็”จๆ–นๆณ•๏ผŒไธ็”จๆŒ‰็…ง็ƒญๅบฆๆŽ’ๅบ) List<DiscussPost> discussPosts = discussPostService.findDiscussPosts(userId, page.getOffset(), page.getLimit(), 0); // ้œ€่ฆๆŸฅ่ฏขๆฏไธชๅธ–ๅญๆ”ถๅˆฐ็š„่ตž็š„ๆ•ฐ้‡๏ผŒๅฐ†ๅธ–ๅญ้›†ๅˆ่ฝฌๅŒ–ไธบ VO ๅฏน่ฑก้›†ๅˆ List<Map<String, Object>> discussPostVoList = new ArrayList<>(); if (discussPosts != null) { for (DiscussPost discussPost : discussPosts) { // ๅˆ›ๅปบๆฏไธชๅธ–ๅญ็š„ VO ๅฏน่ฑก Map<String, Object> discussPostVo = new HashMap<>(); // 4.1ๆทปๅŠ ๅธ–ๅญๅฏน่ฑกๆœฌ่บซ discussPostVo.put("discussPost", discussPost); // 4.2ๆทปๅŠ ๅธ–ๅญ็š„่Žท่ตžๆ•ฐ้‡ discussPostVo.put("discussPostLikeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId())); // ๆทปๅŠ ่ฟ™ไธช VOๅฏน่ฑก discussPostVoList.add(discussPostVo); } } model.addAttribute("discussPostVoList", discussPostVoList); return "/site/my-post"; } // ่ฟ”ๅ›žโ€œๆˆ‘็š„ๅ›žๅคโ€้กต้ข๏ผŒๆ”ฏๆŒๅˆ†้กตๅŠŸ่ƒฝ @GetMapping("/myComment/{userId}") public String getMyCommentPage(@PathVariable("userId") Integer userId, Model model, Page page, @RequestParam(name = "current", required = false) Integer current) { // 1.ๆŸฅ่ฏข่ฏฅ็”จๆˆท User user = userService.findUserById(userId); if (user == null) { throw new IllegalArgumentException("่ฏฅ็”จๆˆทไธๅญ˜ๅœจ๏ผ"); } // 2.ๆŸฅ่ฏขๅนถๆทปๅŠ ่ฏฅ็”จๆˆท็š„่ฏ„่ฎบๆ•ฐ้‡ int commentCount = commentService.findCommentCountByUserId(userId); model.addAttribute("commentCount", commentCount); // 3.ๅกซๅ…ฅๅˆ†้กตไฟกๆฏ page.setLimit(5); page.setPath("/user/myComment/" + userId); page.setRows(commentCount); if (current != null) { page.setCurrent(current); } // 4.ๆŸฅ่ฏขๅนถๆทปๅŠ ่ฏฅ็”จๆˆทๅ‘ๅธƒ็š„่ฏ„่ฎบ้›†ๅˆ List<Comment> commentList = commentService.findCommentsByUserId(userId, page.getOffset(), page.getLimit()); // ้œ€่ฆๆŸฅ่ฏขๆฏไธชๅธ–ๅญๅฏนๅบ”็š„่ฏ„่ฎบๆ ‡้ข˜๏ผŒๅฐ†่ฏ„่ฎบ้›†ๅˆ่ฝฌๆขไธบVOๅฏน่ฑก้›†ๅˆ List<Map<String, Object>> commentVoList = new ArrayList<>(); if (commentList != null) { for (Comment comment : commentList) { // ๅˆ›ๅปบไธ€ไธช ่ฏ„่ฎบ VO ๅฏน่ฑก Map<String, Object> commentVo = new HashMap<>(); // 4.1ๆทปๅŠ ่ฏ„่ฎบๅฏน่ฑกๆœฌ่บซ commentVo.put("comment", comment); // 4.2ๆทปๅŠ ๅธ–ๅญๅฏน่ฑก๏ผŒๅธ–ๅญ็š„id ๅฐฑๆ˜ฏ ่ฏ„่ฎบ็š„entityId commentVo.put("discussPost", discussPostService.findDiscussPostById(comment.getEntityId())); // ๆทปๅŠ ่ฟ™ไธช VO ๅฏน่ฑก commentVoList.add(commentVo); } } model.addAttribute("commentVoList", commentVoList); return "/site/my-reply"; } }
import { Component, OnDestroy, OnInit } from '@angular/core'; import { delay, filter, forkJoin, from, interval, map, mergeMap, Observable, of, scan, Subscription, tap } from 'rxjs'; import { RxjsService } from './services/rxjs.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnDestroy, OnInit { profesores: any = []; cursos: any = []; cursosSuscription: Subscription; cursos$: Observable<any> constructor( private rxjsService: RxjsService ){ // this.rxjsService.obtenerPromiseProfesores().then((profesores) => { // console.log('Estoy desde el promise de profesores: ', profesores); // // console.log(profesores); // this.profesores = profesores; // }).catch((error) => { // console.log(error); // }); this.rxjsService.obtenerObservableProfesores().subscribe((profesores) =>{ console.log('Estoy desde el observable de profesores: ', profesores); this.profesores = profesores; }); this.cursosSuscription = this.rxjsService.obtenerObservableCursos().subscribe((cursos) => { this.cursos = cursos; } ); // pipe operator this.cursos$ = this.rxjsService.obtenerObservableCursos(); console.log(this.cursos$); } ngOnInit(): void{ // this.rxjsService.obtenerObservableAlumnos().subscribe((alumnos) => { // console.log('Desde el subscribe de alumnos', alumnos); // }); // this.rxjsService.obtenerObservableAlumnos().pipe( // map((alumnos: any[]) => alumnos.filter(alumno => alumno.curso === 'Angular')) // ).subscribe((alumnos) => { // console.log('Desde el subscribe de alumnos', alumnos); // }); from([1,2,3,4,5,6,7,8,9,10]).pipe( tap(valor => console.log('TAP antes del scan', valor)), // acumulador el primero tiene un valor 0 y el valor: es 1 por lo que seria = 1 // acumulador el primero tiene un valor 1(este es el resultado del primer resultado) y el valor: es 2 por lo que seria = 3 scan((acumulador: number, valor: number) => acumulador+valor), //filtra de acuerdo a la condiciรณn filter((valor: number) => valor % 2 === 0), tap(valor => console.log('TAP despes del filter', valor)) ).subscribe((data) => { console.log("Probando operadores", data); }); // const letras = of('a', 'b', 'c'); // letras.pipe( // mergeMap( // x => interval(1000).pipe(map(i => x+i)) // ) // ).subscribe(x => console.log('Utilizando el MergeMap', x)); const fork = forkJoin({ sourceOne: of('Hola'), sourceTwo: of('Mundo').pipe(delay(1000)) }).subscribe((datos) => { console.log('Utilizando el forkjoin', datos) }) } ngOnDestroy(): void{ console.log('Ejecutando ngOnDestroy para desuscribirme del observable') this.cursosSuscription.unsubscribe(); } agregarNuevoProfesor(){ // let profesor = { // id: 5, // nombre: 'Elizabeth', // curso: 'UI/UX' // } let curso = { id: 1, nombre: 'UI/UX', curso: '32450' } // this.rxjsService.agregarNuevoProfesor(profesor); this.rxjsService.agregarNuevoCurso(curso); } }
/* eslint-disable max-len */ import { createSlice } from '@reduxjs/toolkit'; interface InitialStateType { profilePhoto: string; id: string, username: string, email: string, } const initialState: InitialStateType = { id: '', username: '', email: '', profilePhoto: '', }; const userSlice = createSlice({ name: 'userSlice', initialState, reducers: { setUserDetails: (state, action) => action.payload, logoutUser: () => initialState, }, }); export const { setUserDetails, logoutUser } = userSlice.actions; export default userSlice.reducer;
import 'package:real_estate_app/model/properties_list.dart'; import 'package:real_estate_app/screens/home/PropertiesCard/properties_card_widget.dart'; import 'package:real_estate_app/util/config.dart'; import '../../../ShimmerLayout/Home/property_card_layout.dart'; import '../../../constants/constants.dart'; class PropertiesCard extends StatelessWidget { final String title; final bool isLoading; final PropertiesList data; final bool isRent; const PropertiesCard(this.title, this.isLoading, this.data, this.isRent, {super.key}); @override Widget build(BuildContext context) { return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( title, style: Theme.of(context).textTheme.bodyMedium, ), Text( Constants.seeAll, style: Theme.of(context).textTheme.bodyMedium, ), ], ), isLoading ? const PropertyCardShimmering() : SizedBox( width: double.infinity, height: MediaQuery.of(context).size.height / 3, child: ListView.builder( scrollDirection: Axis.horizontal, shrinkWrap: true, itemCount: data.data?.length ?? 0, itemBuilder: (context, index) { return PropertiesWidget(data.data![index], isRent); }), ), ], ); } }
// ContactForm.js import React, { Component } from 'react'; class ContactForm extends Component { state = { name: '', number: '', }; handleInputChange = (e) => { const { name, value } = e.target; this.setState({ [name]: value }); }; handleAddContact = () => { const { name, number } = this.state; if (name === '' || number === '') { alert('Please fill in all fields'); return; } this.props.onAddContact({ name, number }); this.setState({ name: '', number: '' }); }; render() { return ( <div> <form> <input type="text" name="name" placeholder="Name" value={this.state.name} onChange={this.handleInputChange} /> <input type="tel" name="number" placeholder="Phone Number" value={this.state.number} onChange={this.handleInputChange} /> <button type="button" onClick={this.handleAddContact}> Add Contact </button> </form> </div> ); } } export default ContactForm;
import { PermissionsContext, usePermission, } from "../../utils/contexts/PermissionsContext"; import { PERMISSIONS } from "../../utils/constants"; import { Error } from "../"; import { Button } from "antd"; import styles from "./Roles.module.scss"; import { Link } from "react-router-dom"; import member from "../../assets/icons/member.svg"; import kebabMenu from "../../assets/icons/kebabMenu.svg"; import { useCallback, useContext, useState } from "react"; import AddNewRoleSidebar from "./AddNewRole"; import { Menu, MenuItem, IconButton } from "@mui/material"; import MainLayout from "../../layouts/MainLayout"; import { Add as AddIcon } from "@mui/icons-material"; import { message } from "antd"; import deleteIcon from "../../assets/icons/delete.svg"; const Roles = () => { const hasPermission = usePermission(PERMISSIONS.ROLE.READ); const [isOpenAddNewRole, setIsOpenAddNewRole] = useState(false); const { allRoles } = useContext(PermissionsContext); const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null); const open = Boolean(anchorEl); const { deleteRole } = useContext(PermissionsContext); const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => { setAnchorEl(event.currentTarget); }; function handleCloseIsOpenAddNewRole() { setIsOpenAddNewRole(false); } const handleClose = () => { setAnchorEl(null); }; const handleDeleteRole = useCallback( (id: string) => { try { const res = deleteRole(id); // console.log(res); res .then((res) => { message.success("Role deleted successfully"); }) .catch((e) => { message.error("Something wrong occured"); }); } catch (err) { message.error("Something wrong occured"); console.log(err); } handleClose(); }, [deleteRole] ); return ( <MainLayout name="Roles" menuActions={ hasPermission ? ( <Button type="primary" style={{ display: "flex", alignItems: "center", justifyContent: "center", }} onClick={() => setIsOpenAddNewRole(true)} icon={<AddIcon />} > Create New </Button> ) : null } > {hasPermission ? ( <> <div className={styles.roles}> <div className={styles.tableHeader}> <h4>Roles</h4> <h4>Members</h4> </div> <div className={styles.tableContent}> {allRoles?.map((role: any) => ( <div key={role.id} className={styles.memberContainer}> <Link key={role.id} to={`/roles/${role.id}`}> <p>{role?.name}</p>{" "} <div className={styles.member}> <img src={member} alt="Member" /> <p>{role.members?.length}</p> </div> </Link> <IconButton onClick={() => { handleDeleteRole(role.id); }} > <img src={deleteIcon} /> </IconButton> </div> ))} </div> </div> {/* <Sidebar title="Create New Role" open={isOpenAddNewRole} width="30%" handleClose={handleCloseIsOpenAddNewRole} </Sidebar> */} <AddNewRoleSidebar open={isOpenAddNewRole} handleClose={handleCloseIsOpenAddNewRole} /> </> ) : ( <Error /> )} </MainLayout> ); }; export default Roles;
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Show Event</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> </head> <body> <div class="container my-5"> <a href="/events" class="float-right">Dashboard</a> <a href="/logout" class="float-right mx-5">Logout</a> <div class="row py-5"> <div class="col mr-5"> <h1>${event.name}</h1> <p>Host: ${event.host.firstName} ${event.host.lastName}</p> <p>Date: ${event.eventDate}</p> <p>Location: ${event.city} ${event.state}</p> <p>People who are attending this event: ${event.joinedUsers.size()}</p> <table class="table table-striped"> <thead> <tr> <th>Name</th> <th>Location</th> </tr> </thead> <tbody> <c:forEach items="${event.joinedUsers}" var="user"> <tr> <td>${user.firstName} ${user.lastName}</td> <td>${user.state}</td> </tr> </c:forEach> </tbody> </table> </div> <div class="col"> <h2>Message Wall</h2> <table class="table table-striped table-bordered table-sm"> <tbody> <c:forEach items="${event.messages}" var = "message"> <p>${message.author.firstName} says: ${message.comment}</p> </c:forEach> </tbody> </table> <form:form method="POST" action="/events/${event.id}/messages" modelAttribute="message"> <p> <form:label path="comment">Add comment:</form:label> <form:errors path="comment"/> <form:input path="comment" type="text"/> </p> <button class="btn btn-primary">Submit</button> </form:form> </div> </div> </div> </body> </html>
import os restaurantes = [{'nome':'Praรงa', 'categoria': 'Japonesa', 'ativo': False}, {'nome':'Pizza Suprema', 'categoria': 'Italiana', 'ativo': True}, {'nome':'Cantina', 'categoria':'Italiana', 'ativo':False}] def exibir_mome_do_programa(): '''Essa funรงรฃo exibe o nome estilizado do programa na tela''' print(""" โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘ โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•ฆโ•โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• โ–‘โ•šโ•โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•ฆโ•โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–ˆโ–ˆโ•‘ โ•šโ•โ•โ•โ•โ•โ•โ–‘โ•šโ•โ•โ–‘โ–‘โ•šโ•โ•โ•šโ•โ•โ•โ•โ•โ•โ–‘โ–‘โ•šโ•โ•โ•โ•โ•โ–‘โ•šโ•โ•โ–‘โ–‘โ•šโ•โ• โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•—โ–‘โ–‘โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ•šโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ• โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–‘โ–‘โ•šโ–ˆโ–ˆโ–ˆโ•”โ•โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–‘โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘ โ–ˆโ–ˆโ•”โ•โ•โ•โ–‘โ–‘โ–‘โ–ˆโ–ˆโ•”โ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ–‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ•โ–‘โ–‘โ–‘โ•šโ•โ•โ•โ–ˆโ–ˆโ•—โ–‘โ•šโ•โ•โ•โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•šโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• โ•šโ•โ•โ•โ•โ•โ•โ•โ•šโ•โ•โ–‘โ–‘โ•šโ•โ•โ•šโ•โ•โ–‘โ–‘โ–‘โ–‘โ–‘โ•šโ•โ•โ–‘โ–‘โ•šโ•โ•โ•šโ•โ•โ•โ•โ•โ•โ•โ•šโ•โ•โ•โ•โ•โ•โ–‘โ•šโ•โ•โ•โ•โ•โ•โ–‘ """) def exibir_opcoes(): '''Essa funรงรฃo exibe as opรงรตes do menu principal''' print('1. Cadastrar restaurante') print('2. Listar restaurantes') print('3. Alterar estado do restaurante') print('4. Sair\n') def finalizar_app(): '''Esaa funรงรฃo exibe mensagem de finalizaรงรฃo do aplicativo''' exibir_subtitulo('Finalizar app') def voltar_ao_menu_principal(): '''Essa funรงรฃo solicita que se digite uma tecla para voltar ao menu principal Inputs: - Tecla digitada Outputs: - Retorna ao menu principal ''' input('\nDigite uma tecla para voltar ao menu principal ') main() def opcao_invalida(): '''Exibe mensagem de opรงรฃo invรกlida e retorna ao menu principal Outputs: - Retorna ao menu principal ''' print('Opรงรฃo invรกlida!\n') voltar_ao_menu_principal() def exibir_subtitulo(texto): '''Exibe um subtitulo Input: - texto: str ( O texto de cada subtitulo) ''' os.system('cls') linha = '*' * (len(texto)) print(linha) print(texto) print(linha) print() def cadastrar_novo_restaurante(): '''Essa funรงรฃo รฉ responsavel por cadastrar um novo restaurante Inputs: - Nome do restaurante - Categoria Outputs: - Adiciona um novo restaurante a lista de restaurantes ''' exibir_subtitulo('Cadastro de novos restaurantes') nome_do_restaurante = input('Digite o nome do restaurante que deseja cadastrar: ') categoria = input(f'Digite o nome da cagetegoria do restaurante {nome_do_restaurante}: ') dados_do_restaurante = {'nome': nome_do_restaurante, 'categoria': categoria, 'ativo':False} restaurantes.append(dados_do_restaurante) print(f'O restaurante {nome_do_restaurante} foi cadastrado com sucesso!') voltar_ao_menu_principal() def listar_restaurantes(): '''Essa funรงรฃo exibe uma lista contendo os restaurantes cadastrados Outputs: - Exibe lista de restaurantes na tela ''' exibir_subtitulo('Listando os restaurantes') print(f'{"Nome do restaurante".ljust(22)} | {"Categoria".ljust(20)} | Status') for restaurante in restaurantes: nome_restaurante = restaurante['nome'] categoria = restaurante['categoria'] ativo = 'ativado' if restaurante['ativo'] else 'desativado' print(f'- {nome_restaurante.ljust(20)} | {categoria.ljust(20)} | {ativo}') voltar_ao_menu_principal() def alternar_estado_restaurante(): '''Altera o status do restaurante ativo/desativado Outputs: - Exibe msg de indicando sucesso da operaรงรฃo''' exibir_subtitulo('Alterando estado do restaurante') nome_restaurante = input('Digite o nome do restaurante que deseja alterar o estado : ') restaurante_encontrado = False for restaurante in restaurantes: if nome_restaurante == restaurante['nome']: restaurante_encontrado = True restaurante['ativo'] = not restaurante['ativo'] mensagem = f'O restaurante {nome_restaurante} foi ativado om sucesso' if restaurante ['ativo'] else f'O restaurante {nome_restaurante} foi desativado com sucesso' print(mensagem) if not restaurante_encontrado: print('O restaurante nรฃo foi encontrado') voltar_ao_menu_principal() def escolher_opcao(): '''Solicita e executa a opรงรฃo escolhida pelo usuรกrio Outputs: - Executa a opรงรฃo selecionada pelo usuรกrio ''' try: opcao_escolhida = int(input('Escolha uma opรงรฃo: ')) if opcao_escolhida == 1: cadastrar_novo_restaurante() elif opcao_escolhida == 2: listar_restaurantes() elif opcao_escolhida == 3: alternar_estado_restaurante() elif opcao_escolhida == 4: finalizar_app() else: opcao_invalida() except: opcao_invalida() def main(): '''Funรงรฃo principal que executa o programa''' os.system('cls') exibir_mome_do_programa() exibir_opcoes() escolher_opcao() if __name__ == '__main__': main()
import { useEffect, useState } from "react"; import { Box, CardMedia, Card, CardHeader, CardContent, Typography, Button, CardActions, } from "@mui/material"; import { useDispatch, useSelector } from "react-redux"; import { updateAppbar } from "../store/slices/meta"; import { InnerPageLayout } from "../component/InnerPageLayout"; import { api } from "../api/api"; import QuestionMarkIcon from "@mui/icons-material/QuestionMark"; import { useParams } from "react-router-dom"; import toast from "react-hot-toast"; import dayjs from "dayjs"; import QuestionAnswerIcon from "@mui/icons-material/QuestionAnswer"; import AddAnswerForm from "./AddAnswerForm"; const QuestionDetail = () => { const dispatch = useDispatch(); const { id } = useParams(); const metaState = useSelector((state) => state.meta); const [openAddAnswerModal, setOpenAddAnswerModal] = useState(false); const [questionData, setQuestionData] = useState({}); const getQuestionDetail = async () => { if (id) { const response = await api.get(`questions/${id}`); if (response.status === 200) { if (response.data.success) { setQuestionData(response.data.data); } else { toast.error(response.data.message); } } } }; useEffect(() => { if (id) { getQuestionDetail(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [id]); const deleteAnswer = async (answerId) => { const response = await api.delete(`answers/${answerId}`); if (response.status === 200) { if (response.data.success) { getQuestionDetail(); setQuestionData(response.data.data); } else { toast.error(response.data.message); } } }; useEffect(() => { dispatch( updateAppbar({ ...metaState, breadCrumbData: { trail: [{ title: "Question", path: "", icon: <QuestionMarkIcon /> }], title: "Question Detail", }, }) ); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const menuAction = [ { label: "Add Answer", onClickHandler: () => setOpenAddAnswerModal(true), }, ]; return ( <> <InnerPageLayout pageTitle="Questions" actionMenuItems={menuAction}> <Box sx={{ p: 2 }}> <Card> <CardHeader avatar={<QuestionMarkIcon />} action={ <Button aria-label="status">{questionData?.status}</Button> } title="Question" subheader={dayjs(questionData?.createdAt).format( "MMMM D, YYYY h:mm A " )} /> {questionData?.questionImage && ( <CardMedia component="img" height="500" src={api.buildUrl( `public/uploads/questions/${questionData?.questionImage}` )} alt="Question Image" /> )} <CardContent> <Typography paragraph> {questionData?.description ?? "Question"} </Typography> </CardContent> </Card> </Box> {questionData?.answers?.map((answer, idx) => { return ( <Box sx={{ p: 2 }} key={answer?._id}> <Card> <CardHeader avatar={<QuestionAnswerIcon />} title={`Answer ${idx + 1}`} subheader={dayjs(answer?.createdAt).format( "MMMM D, YYYY h:mm A " )} /> {answer?.answerImage && ( <CardMedia component="img" height="500" src={api.buildUrl( `public/uploads/answers/${answer?.answerImage}` )} alt="Answer Image" /> )} <CardContent> <Typography paragraph>{answer?.description}</Typography> </CardContent> {/* <CardActions disableSpacing> <Button onClick={() => { deleteAnswer(answer?._id); }} > Delete </Button> </CardActions> */} </Card> </Box> ); })} </InnerPageLayout> <AddAnswerForm open={openAddAnswerModal} setOpen={setOpenAddAnswerModal} questionId={id} submitHandler={() => { getQuestionDetail(); }} /> </> ); }; export default QuestionDetail;
import java.util.*; LifeType life_type; GameState game_state; void setup() { fullScreen(); colorMode(HSB, 1.0); background(1.0, 0.0, 0.1); life_type = new LifeType("3", "23"); game_state = new GameState(displayWidth, displayHeight, 12, life_type); } void draw() { if (mousePressed && mouseX >= 0 && mouseX < displayWidth && mouseY >= 0 && mouseY < displayHeight) { game_state.add_point(mouseX, mouseY); } if (game_state.update()) { background(1.0, 0.0, 0.1); } game_state.draw(); } void keyPressed() { if (key == ' ') game_state.toggle_pause(); } public class GameState { Grid grid_state; LifeType life_type; boolean paused; GameState(int width, int height, int scale, LifeType life_type) { this.grid_state = new Grid(width, height, scale); this.life_type = life_type; this.paused = true; } void toggle_pause() { paused = !paused; } boolean update() { if (paused) return false; grid_state.update(life_type.born, life_type.survive); return true; } void add_point(int x, int y) { grid_state.add_point(x, y); } void draw() { grid_state.draw(); } } private class Grid { byte[][][] state; boolean current_frame; int width, height, scale; Grid(int width, int height, int scale) { state = new byte[width / scale][height / scale][2]; current_frame = false; this.width = width / scale; this.height = height / scale; this.scale = scale; } void add_point(int x, int y) { state[x / scale][y / scale][current_frame ? 1 : 0] = 1; } void update(Set<Integer> born, Set<Integer> survive) { int old_frame_index = current_frame ? 1 : 0; current_frame = !current_frame; int new_frame_index = current_frame ? 1 : 0; for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { int num_neighbours = num_neighbours(i, j, old_frame_index); if (state[i][j][old_frame_index] == 1) { // If Alive state[i][j][new_frame_index] = (byte)(survive.contains(num_neighbours) ? 1 : 0); } else { state[i][j][new_frame_index] = (byte)(born.contains(num_neighbours) ? 1 : 0); } } } } int num_neighbours(int x, int y, int frame_index) { int sum = 0; for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) { continue; } if (is_in_bounds(x + dx, y + dy)) { sum += state[x+dx][y+dy][frame_index]; } } } return sum; } boolean is_in_bounds(int x, int y) { return x >= 0 && y >= 0 && x < this.width && y < this.height; } void draw() { int frame_index = current_frame ? 1 : 0; for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { if (state[i][j][frame_index] == 1) { fill(0.0, 0.0, 1.0); rect(i * scale, j * scale, scale, scale); } } } } } public class LifeType { public Set<Integer> born; public Set<Integer> survive; LifeType(String born_values, String survive_values) { born = new HashSet<>(); survive = new HashSet<>(); for (char amount : born_values.toCharArray()) { born.add(amount - '0'); } for (char amount : survive_values.toCharArray()) { survive.add(amount - '0'); } } }
/* gpx-parser.vala * * Copyright (C) 2010 Tomaลพ Vajngerl * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Author: * Tomaลพ Vajngerl <[email protected]> */ namespace Gpx { public class Parser : Object { public Root? parse_file (string filename) { var document = new XmlHelp.Document (); var element = document.parse_file (filename); if (element != null) { return parse_root (element); } return null; } public Root? parse_data (string data) { var document = new XmlHelp.Document (); var element = document.parse_data (data); if (element != null) { return parse_root (element); } return null; } Root parse_root (XmlHelp.Element element) { var root = new Root (); foreach (var sub_element in element) { switch (sub_element.name) { case "name": root.name = sub_element.get_content (); break; case "desc": root.description = sub_element.get_content (); break; case "author": root.author = sub_element.get_content (); break; case "time": root.time = sub_element.get_content (); break; case "keywords": root.keywords = sub_element.get_content (); break; case "bounds": root.bounds = sub_element.get_content (); break; case "trk": var track = parse_track (sub_element); root.add_track (track); break; case "wpt": var waypoint = parse_waypoint (sub_element); root.add_waypoint (waypoint); break; } } return root; } Track parse_track (XmlHelp.Element element) { var track = new Track (); foreach (var sub_element in element) { switch (sub_element.name) { case "name": track.name = sub_element.get_content (); break; case "desc": track.description = sub_element.get_content (); break; case "cmt": track.comment = sub_element.get_content (); break; case "src": track.source = sub_element.get_content (); break; case "number": track.number = sub_element.get_int64_content (); break; case "trkseg": track.add_segment (parse_segment (sub_element)); break; } } return track; } TrackSegment parse_segment (XmlHelp.Element element) { var segment = new TrackSegment (); foreach (var sub_element in element) { switch (sub_element.name) { case "trkpt": segment.add_point (parse_waypoint (sub_element)); break; } } return segment; } Waypoint parse_waypoint (XmlHelp.Element element) { var waypoint = new Waypoint (); waypoint.latitude = element["lat"].to_double (); waypoint.longitude = element["lon"].to_double (); foreach (var sub_element in element) { switch (sub_element.name) { case "ele": waypoint.elevation = sub_element.get_int_content (); break; case "time": waypoint.time = sub_element.get_content (); break; case "name": waypoint.name = sub_element.get_content (); break; case "desc": waypoint.description = sub_element.get_content (); break; case "src": waypoint.source = sub_element.get_content (); break; case "link": waypoint.link = sub_element.get_content (); break; case "type": waypoint.waypoint_type = sub_element.get_content (); break; case "sat": waypoint.number_of_satellites = sub_element.get_int_content (); break; } } return waypoint; } } }
import { CodeProblemsEntity } from '@entities/code_problems.entity'; import { Challenge } from '@interfaces/challange.interface'; import { CodeProblem } from '@interfaces/code_problem.interface'; import { Difficulty } from '@interfaces/course.interface'; import { IsNotEmpty } from 'class-validator'; import { BaseEntity, Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, JoinColumn, OneToOne } from 'typeorm'; @Entity({ name: 'challenges' }) export class ChallengesEntity extends BaseEntity implements Challenge { @PrimaryGeneratedColumn('uuid') id: string; @OneToOne(() => CodeProblemsEntity, { onDelete: 'CASCADE' }) @JoinColumn() codeProblem: CodeProblem; @Column({ type: 'enum', enum: Difficulty, default: Difficulty.BEGINNER, }) @IsNotEmpty() difficulty: Difficulty; @Column() @IsNotEmpty() authorId: string; @Column() @CreateDateColumn() createdAt: Date; @Column() @UpdateDateColumn() updatedAt: Date; }
/** * e2e runner */ import Api from "./api"; import Launch from "./launch"; import { ChildProcess } from "child_process"; import { Event, Phase, DispatchError } from "@polkadot/types/interfaces"; import { ApiPromise } from "@polkadot/api"; import BN from "bn.js"; const OCW = "filecoindot"; const OCW_PREPARED = "haven't set filecoin rpc yet"; // Kill subprocesses function killAll(ps: ChildProcess, exitCode: number) { try { if (ps.send && !ps.killed) { ps.send("exit"); } ps.kill("SIGINT"); } catch (e) { if ((e as any).code !== "EPERM") { process.stdout.write(JSON.stringify(e)); process.exit(2); } } process.exit(exitCode); } /** * proof inteface */ export interface IProof { proof: string; cid: string; } /** * e2e runner config */ export interface IRunnerConfig { filecoindotRpc: string[]; id: string; suri: string; ws: string; proof: IProof; } /** * e2e runner */ export default class Runner { config: IRunnerConfig; constructor(config: IRunnerConfig) { this.config = config; } public async run() { console.log("bootstrap filecoindot template..."); const ps = await Launch.launch("pipe"); // bootstrap testing let started: boolean = false; this.listenStdout(ps); this.listenStderr(ps, started); this.listenExit(ps); } /** * check filecoindot events */ private checkEvents(api: ApiPromise, event: Event, phase: Phase) { const maybeErr = event.data[0]; if (maybeErr && (maybeErr as DispatchError).isModule) { const error = api.registry.findMetaError( (event.data[0] as DispatchError).asModule.toU8a() ); console.log(`${error.section}.${error.method}: ${error.docs}`); process.exit(1); } if (event.method == "VoteCasted") { console.log( `\t${event.section}:${event.method}:: (phase=${phase.toString()})` ); console.log(`\t\t${event.meta.docs.toString()}`); console.log("setup completed!"); process.exit(0); } } /** * init offchain worker */ public async setup() { const { ws, filecoindotRpc, id, suri } = this.config; const api = await Api.New(ws, suri); // test verifying proof if (this.config.proof) { if ((await api.verifyProof(this.config.proof.proof, this.config.proof.cid)).toHuman() === false) { throw "verify proof failed" } } else { console.log("WARN: no proof field found in config, skipping testing proof"); } await api.insertAuthor(id); await api.setEndpoint(filecoindotRpc); await api.addRelayer(); await api.depositFund(1000); api.events(this.checkEvents); } /** * listen stderr */ private listenStderr(ps: ChildProcess, started: boolean) { if (ps.stderr) { ps.stderr.on("data", async (chunk: Buffer) => { chunk.includes(OCW) && process.stderr.write(chunk.toString()); if (!started && chunk.includes(OCW_PREPARED)) { await this.setup(); started = true; } }); } } /** * listen stdout */ private listenStdout(ps: ChildProcess) { if (ps.stdout) { ps.stdout.on("data", async (chunk: Buffer) => { process.stdout.write(chunk.toString()); }); } } /** * listen the exit signal and kill all processes */ private listenExit(ps: ChildProcess) { // kill all processes when exiting. process.on("exit", () => { killAll(ps, Number(process.exitCode)); }); // handle ctrl+c to trigger `exit`. process.on("SIGINT", () => killAll(ps, 0)); } }
<template> <a-modal :title="title" :width="800" :visible="visible" :confirmLoading="confirmLoading" @cancel="handleCancel" > <a-spin :spinning="confirmLoading"> <a-form :form="form" :class="[['show'].includes(operateType) ? 'view-form' : null]"> <a-row :gutter="16"> <a-card title="ๅŸบๆœฌไฟกๆฏ" :bordered="false"> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="่ฎขๅ•็ผ–ๅท" hasFeedback> <!-- <a-input v-if="['add','edit'].includes(operateType)" placeholder="่ฏท่พ“ๅ…ฅ่ฎขๅ•็ผ–ๅท" v-decorator="['orderNo', validatorRules.orderNo]" />--> <template v-if="['show'].includes(operateType)">{{ model.orderNo }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="ๆ€ป้‡‘้ข" hasFeedback> <!-- <a-input-number v-if="['add','edit'].includes(operateType)" placeholder="่ฏท่พ“ๅ…ฅๆ€ป้‡‘้ข" v-decorator="['totalAmount', validatorRules.totalAmount]" />--> <template v-if="['show'].includes(operateType)">{{ model.totalAmount }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="่ฎขๅ•็Šถๆ€" hasFeedback> <!-- <a-input v-if="['add','edit'].includes(operateType)" placeholder="่ฎขๅ•็Šถๆ€" v-decorator="['orderStatus',{}]" />--> <template v-if="['show'].includes(operateType)" >{{ model.orderStatus === 0 ? 'ๅพ…ๆ”ฏไป˜' : model.orderStatus === 1 ? 'ๅทฒๆ”ฏไป˜' : model.orderStatus === 1 ? 'ๅ–ๆถˆไธญ' : model.orderStatus === 2 ? 'ๅทฒๅ–ๆถˆ' : '' }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="ไธ‹ๅ•ๆ—ถ้—ด" hasFeedback> <!-- <a-input v-if="['add','edit'].includes(operateType)" placeholder="่ฏท่พ“ๅ…ฅไธ‹ๅ•ๆ—ถ้—ด" v-decorator="['orderTime', {}]" />--> <template v-if="['show'].includes(operateType)">{{ model.orderTime }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="ๆ”ฏไป˜ๆ—ถ้—ด" hasFeedback> <!-- <a-input v-if="['add','edit'].includes(operateType)" placeholder="่ฏท่พ“ๅ…ฅๆ”ฏไป˜ๆ—ถ้—ด" v-decorator="['payTime', {}]" />--> <template v-if="['show'].includes(operateType)">{{ model.payTime }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="ๅ–ๆถˆๆ—ถ้—ด" hasFeedback> <!-- <a-input v-if="['add','edit'].includes(operateType)" placeholder="่ฏท่พ“ๅ…ฅ่ฎขๅ•ๅ–ๆถˆๆ—ถ้—ด" v-decorator="['orderCancelTime', {}]" />--> <template v-if="['show'].includes(operateType)">{{ model.orderCancelTime }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="ๅค‡ๆณจ" hasFeedback> <!-- <a-input v-if="['add','edit'].includes(operateType)" placeholder="่ฏท่พ“ๅ…ฅ่ฎขๅ•ๅค‡ๆณจ" v-decorator="['mark', {}]" />--> <template v-if="['show'].includes(operateType)">{{ model.mark }}</template> </a-form-item> </a-col> </a-card> <a-card title="ๅ‘็ฅจไฟกๆฏ" :bordered="false" v-if="model.orderInvoice!==null&&model.simpleStatus!==0&&model.orderStatus === 2" > <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="ๅ‘็ฅจๆŠฌๅคด" hasFeedback> <!-- <a-input v-if="['add','edit'].includes(operateType)" v-decorator="['orderInvoiceType', {}]" />--> <template v-if="['show'].includes(operateType)" >{{ model.orderInvoice.type===1?'ไธชไบบ':'ๅ•ไฝ' }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="ๅ•ไฝๅ็งฐ" hasFeedback> <!-- <a-input v-if="['add','edit'].includes(operateType)" v-decorator="['businessName', {}]" />--> <template v-if="['show'].includes(operateType)" >{{ model.orderInvoice.businessName }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="่ฏ†ๅˆซๅท" hasFeedback> <!-- <a-input v-if="['add','edit'].includes(operateType)" v-decorator="['taxId', {}]" /> --> <template v-if="['show'].includes(operateType)">{{ model.orderInvoice.taxId }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="ๆ‰‹ๆœบๅท" hasFeedback> <!-- <a-input v-if="['add','edit'].includes(operateType)" v-decorator="['phone', {}]" /> --> <template v-if="['show'].includes(operateType)">{{ model.orderInvoice.phone }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="้‚ฎ็ฎฑ" hasFeedback> <!-- <a-input v-if="['add','edit'].includes(operateType)" v-decorator="['email', {}]" /> --> <template v-if="['show'].includes(operateType)">{{ model.orderInvoice.email }}</template> </a-form-item> </a-col> </a-card> <a-card title="็‰ฉๆตไฟกๆฏ" :bordered="false" v-if="model.simpleStatus === 1"> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="็‰ฉๆตๅ…ฌๅธ" hasFeedback> <a-input v-if="['add','edit'].includes(operateType)" placeholder="่ฏท่พ“ๅ…ฅ็‰ฉๆตๅ…ฌๅธๅ็งฐ" v-decorator="['courierCompany', validatorRules.courierCompany]" /> <template v-else>{{ model.orderLogistics[0].courierCompany }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="็‰ฉๆตๅ•ๅท" hasFeedback> <a-input v-if="['add','edit'].includes(operateType)" placeholder="่ฏท่พ“ๅ…ฅ็‰ฉๆตๅ•ๅท" v-decorator="['trackingNo', validatorRules.trackingNo]" /> <template v-else>{{ model.orderLogistics[0].trackingNo }}</template> </a-form-item> </a-col> <a-col class="gutter-row" v-bind="formColResponsiveCfg"> <a-form-item v-bind="formItemResponsiveCfg" label="ๅ‘่ดงๆ—ถ้—ด" hasFeedback> <a-date-picker v-if="['add','edit'].includes(operateType)" placeholder="ๅ‘่ดงๆ—ถ้—ด" v-decorator="['shippingTime', validatorRules.shippingTime]" /> <template v-else>{{ model.orderLogistics[0].shippingTime }}</template> </a-form-item> </a-col> </a-card> </a-row> </a-form> </a-spin> <template slot="footer"> <a-popconfirm v-if="['add', 'edit'].includes(operateType)" title="็กฎๅฎšๅ–ๆถˆๅ—?" @confirm="() => handleCancel()" > <a-button>ๅ–ๆถˆ</a-button> </a-popconfirm> <a-button @click="handleCancel" v-else>ๅ…ณ้—ญ</a-button> <a-button class="m-l-8" @click="handleOk" v-if="['add', 'edit'].includes(operateType)" type="primary" >็กฎๅฎš</a-button> </template> </a-modal> </template> <script> import ModalMixin from '@/mixins/ModalMixin' import { Modal, Spin, Form, Row, Col, Input, InputNumber, Button, Popconfirm, Card, DatePicker } from 'ant-design-vue' import moment from 'moment' import JDictSelectTag from '@/components/dict/JDictSelectTag.vue' import JDictViewTag from '@/components/dict/JDictViewTag.vue' import JDate from '@/components/jeecg/JDate.vue' import { request } from '@/api' export default { name: 'OrderModal', mixins: [ModalMixin], components: { AModal: Modal, ASpin: Spin, AForm: Form, AFormItem: Form.Item, ARow: Row, ACol: Col, AInput: Input, AInputNumber: InputNumber, AButton: Button, APopconfirm: Popconfirm, JDictSelectTag, JDictViewTag, ACard: Card, ADatePicker: DatePicker, JDate }, data() { return { title: 'ๆ“ไฝœ', operateType: 'add', formColResponsiveCfg: { xs: 24, sm: 12 }, formItemResponsiveCfg: { labelCol: { xs: { span: 24 }, sm: { span: 6 }, md: { span: 6 }, lg: { span: 5 }, xl: { span: 5 }, xxl: { span: 5 } }, wrapperCol: { xs: { span: 24 }, sm: { span: 16 }, md: { span: 16 }, lg: { span: 17 }, xl: { span: 17 }, xxl: { span: 17 } } }, validatorRules: { name: { rules: [{ required: true, message: '่ฏท่พ“ๅ…ฅๅ•†ๅ“ๅ็งฐ' }] }, price: { rules: [{ required: true, message: '่ฏท่พ“ๅ…ฅๅ•†ๅ“ไปทๆ ผ' }] }, totalCount: { rules: [{ required: true, message: '่ฏท่พ“ๅ…ฅๅ•†ๅ“ไปทๆ ผ' }] }, courierCompany: { rules: [{ required: true, message: '่ฏท่พ“ๅ…ฅ็‰ฉๆตๅ…ฌๅธๅ' }] }, trackingNo: { rules: [{ required: true, message: '่ฏท่พ“ๅ…ฅ็‰ฉๆตๅ•ๅท' }] }, shippingTime: { rules: [{ required: true, message: '่ฏท่พ“ๅ…ฅๅ‘่ดงๆ—ถ้—ด' }] } }, api: { // add: { // url: '/orders/{id}/simple-delivered', // method: 'post' // }, edit: { url: '/orders/{id}/simple-delivered', method: 'post' }, getById: { url: '/orders/{id}', method: 'get' } }, formFields: [ 'orderNo', 'totalAmount', 'orderStatus', 'orderTime', 'payTime', 'orderCancelTime', 'mark' // 'courierCompany', // 'trackingNo', // 'shippingTime' ] } }, methods: { /** * ็‚นๅ‡ป็กฎ่ฎคๆŒ‰้’ฎๅ‘ๅŽๅฐไผ ่พ“็š„่กจๅ•ๆ•ฐๆฎๅค„็†. * * ๆณจ๏ผšๆญคๆ–นๆณ•่ฟ”ๅ›ž็š„ๆ•ฐๆฎไผš็›ดๆŽฅไผ ๅ‘ๅŽๅฐ. */ moment, handleOk() { const _this = this // ่งฆๅ‘่กจๅ•้ชŒ่ฏ this.form.validateFields((err, values) => { if (!err) { _this.confirmLoading = true let params = { courierCompany: values.courierCompany, shippingTime: moment(values.shippingTime).format('YYYY-MM-DD HH:mm:ss'), trackingNo: values.trackingNo } request({ ...this.api.edit, urlReplacements: [{ substr: '{id}', replacement: this.model.id }], params }) .then(res => { if (res.success) { _this.$message.success(res.message) _this.close() _this.$emit('ok') } else { _this.$message.warning(res.message) } }) .finally(() => { _this.confirmLoading = false }) } }) }, getFormData(formData) { Object.keys(formData).forEach(k => { if (typeof formData[k] === 'string') { formData[k] = formData[k].trim() } }) return formData } } } </script> <style scoped> </style>