text
stringlengths
184
4.48M
#include <map> #include <Arduino.h> #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <BSTest.h> #include <pgmspace.h> BS_ENV_DECLARE(); void setup() { Serial.begin(115200); Serial.setDebugOutput(false); BS_RUN(Serial); } bool pretest() { WiFi.persistent(false); WiFi.mode(WIFI_OFF); return true; } static std::map<WiFiEvent_t, int> sEventsReceived; static void onWiFiEvent(WiFiEvent_t event) { sEventsReceived[event]++; } TEST_CASE("WiFi.onEvent is called for specific events", "[wifi][events]") { sEventsReceived[WIFI_EVENT_STAMODE_CONNECTED] = 0; sEventsReceived[WIFI_EVENT_STAMODE_DISCONNECTED] = 0; sEventsReceived[WIFI_EVENT_STAMODE_GOT_IP] = 0; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" WiFi.onEvent(onWiFiEvent, WIFI_EVENT_STAMODE_CONNECTED); WiFi.onEvent(onWiFiEvent, WIFI_EVENT_STAMODE_DISCONNECTED); WiFi.onEvent(onWiFiEvent, WIFI_EVENT_STAMODE_GOT_IP); WiFi.onEvent(onWiFiEvent, WIFI_EVENT_ANY); #pragma GCC diagnostic pop WiFi.mode(WIFI_STA); WiFi.begin(getenv("STA_SSID"), getenv("STA_PASS")); unsigned long start = millis(); while (WiFi.status() != WL_CONNECTED) { delay(500); REQUIRE(millis() - start < 5000); } WiFi.disconnect(); delay(100); WiFi.mode(WIFI_OFF); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" REQUIRE(sEventsReceived[WIFI_EVENT_STAMODE_CONNECTED] == 2); REQUIRE(sEventsReceived[WIFI_EVENT_STAMODE_DISCONNECTED] >= 2 && sEventsReceived[WIFI_EVENT_STAMODE_DISCONNECTED] % 2 == 0); REQUIRE(sEventsReceived[WIFI_EVENT_STAMODE_GOT_IP] == 2); #pragma GCC diagnostic pop } TEST_CASE("STA mode events are called both when using DHCP and static config", "[wifi][events]") { String events; auto handler1 = WiFi.onStationModeConnected([&](const WiFiEventStationModeConnected& evt){ (void) evt; events += "connected,"; }); auto handler2 = WiFi.onStationModeDisconnected([&](const WiFiEventStationModeDisconnected& evt){ (void) evt; if (events.length()) { events += "disconnected,"; } }); auto handler3 = WiFi.onStationModeGotIP([&](const WiFiEventStationModeGotIP& evt){ (void) evt; events += "got_ip,"; }); // run the test with DHCP WiFi.mode(WIFI_STA); WiFi.begin(getenv("STA_SSID"), getenv("STA_PASS")); unsigned long start = millis(); while (WiFi.status() != WL_CONNECTED) { delay(500); REQUIRE(millis() - start < 5000); } // save IP config IPAddress localIP = WiFi.localIP(); IPAddress subnetMask = WiFi.subnetMask(); IPAddress gatewayIP = WiFi.gatewayIP(); WiFi.disconnect(); delay(100); REQUIRE(events == "connected,got_ip,disconnected,"); events.clear(); // now run the same with static IP config saved above WiFi.mode(WIFI_STA); WiFi.config(localIP, gatewayIP, subnetMask); WiFi.begin(getenv("STA_SSID"), getenv("STA_PASS")); start = millis(); while (WiFi.status() != WL_CONNECTED) { delay(500); REQUIRE(millis() - start < 5000); } WiFi.disconnect(); delay(100); WiFi.mode(WIFI_OFF); REQUIRE(events == "connected,got_ip,disconnected,"); } TEST_CASE("Events are not called if handler is deleted", "[wifi][events]") { String events; WiFi.onStationModeConnected([&](const WiFiEventStationModeConnected& evt){ (void) evt; events += "connected,"; }); WiFi.onStationModeDisconnected([&](const WiFiEventStationModeDisconnected& evt){ (void) evt; events += "disconnected,"; }); WiFi.onStationModeGotIP([&](const WiFiEventStationModeGotIP& evt){ (void) evt; events += "got_ip,"; }); WiFi.mode(WIFI_STA); WiFi.begin(getenv("STA_SSID"), getenv("STA_PASS")); unsigned long start = millis(); while (WiFi.status() != WL_CONNECTED) { delay(500); REQUIRE(millis() - start < 5000); } WiFi.disconnect(); delay(100); REQUIRE(events == ""); } void loop() {}
<template> <Popup :visible="visible" :title="$t('labels/settings')" @dismiss="$emit('dismiss')" > <div class="setting"> <span class="heading setting-title">{{ $t("labels/flavor") }}</span> <span class="setting-description flavor-description">{{ $t("descriptions/setting_flavor") }}</span> <div class="flavor-grid"> <button v-for="(colors, name) in flavors" :key="name" v-memo="[ flavorName === name, currentLanguage ]" class="button flavor-button" :class="{ 'selected-flavor': flavorName === name }" :style="{ backgroundColor: colors.primary }" @click="setFlavor(name)" > <span class="flavor-name">{{ $t(`flavors/${name}`) }}</span> </button> </div> </div> <div class="setting"> <span class="heading setting-title">{{ $t("labels/experience") }}</span> <span class="setting-description">{{ $t("descriptions/setting_experience") }}</span> <div class="experience-list"> <div class="experience-toggle"> <span class="experience-title">{{ $t("labels/video_effects") }}</span> <Toggle v-model="isLeafEnabled" /> </div> <div class="experience-toggle"> <span class="experience-title">{{ $t("labels/karaoke") }}</span> <Toggle v-model="isKaraokeEnabled" /> </div> <div class="experience-toggle"> <span class="experience-title">{{ $t("labels/splash_background") }}</span> <Toggle v-model="isSplashBackgroundEnabled" /> </div> </div> </div> <div class="setting"> <span class="heading setting-title">{{ $t("labels/language") }}</span> <div class="language-selector"> <span class="current-language-name">{{ $t("meta/name") }}</span> <Dropdown class="language-dropdown" :items="languageList" :current-index="currentLanguageIndex" @select-index="setLanguageByIndex" > <template #default="slotProps"> <MarkdownRenderer class="language-flag" :content="languageFlagList[slotProps.key]" /> </template> </Dropdown> </div> </div> </Popup> </template> <script lang="ts"> // Modules import { defineComponent } from "vue"; // Components import Popup from "@components/popups/Popup.vue"; import Toggle from "@components/Toggle.vue"; import Dropdown from "@components/Dropdown.vue"; // Renderers import MarkdownRenderer from "@renderers/Markdown.vue"; // Utils import { FLAVORS } from "@utils/constants"; export default defineComponent({ name: "SettingsPopup", components: { Popup, Toggle, Dropdown, MarkdownRenderer }, props: { visible: { type: Boolean, default: false } }, emits: [ "dismiss" ], computed: { flavors () { return FLAVORS; }, flavorName (): string { return this.$store.state.settings.flavor; }, isLeafEnabled: { get () { return this.$store.state.settings.effects; }, set (value: boolean) { this.$store.commit("settings/UPDATE_EFFECTS_STATE", value); } }, isKaraokeEnabled: { get () { return this.$store.state.settings.karaoke; }, set (value: boolean) { this.$store.commit("settings/UPDATE_KARAOKE_STATE", value); } }, isSplashBackgroundEnabled: { get () { return this.$store.state.settings.splashBackground; }, set (value: boolean) { this.$store.commit("settings/UPDATE_SPLASH_BACKGROUND_STATE", value); } }, currentLanguage (): string { return this.$store.state.settings.language; }, languageFlagList (): string[] { return Object.values(this.$store.state.cache.languages).map(lang => lang.meta.flag); }, languageList (): string[] { return Object.keys(this.$store.state.cache.languages); }, currentLanguageIndex (): number { return this.languageList.indexOf(this.currentLanguage); } }, methods: { setFlavor (flavorName: string) { this.$store.commit("settings/UPDATE_FLAVOR", flavorName); }, setLanguageByIndex (index: number) { this.$store.commit("settings/UPDATE_LANGUAGE", this.languageList[index]); } } }); </script> <style scoped lang="scss"> @import "@styles/main"; .setting { width: 400px; padding: .8rem; margin-bottom: .5rem; background-color: variable(background-color); border-radius: variable(card-border-radius); display: flex; flex-direction: column; justify-content: flex-start; align-items: flex-start; .setting-title { font-size: 1.3rem; margin-top: 0; margin-bottom: .5rem; } .setting-description { color: variable(faded-heading-text-color); font-size: 1rem; margin-bottom: 2rem; &.flavor-description { margin-bottom: .5rem; } } } @media only screen and (max-width: 500px) { .setting { width: 98%; } } // Flavor .flavor-grid { width: 100%; display: flex; flex-flow: row wrap; justify-content: center; align-items: flex-start; } .flavor-button { position: relative; width: 4em; height: 2em; margin: .2em; padding: .5em; margin-top: 1.5em; border: 3px solid transparent; display: flex; align-content: center; justify-content: center; transition: border-color .2s ease, transform .25s ease; .flavor-name { position: absolute; top: -1em; width: 200%; left: -50%; font-size: 1rem; text-align: center; opacity: 0; user-select: none; transition: transform .25s ease, opacity .2s ease; } &:hover { transform: translateY(-.2rem); .flavor-name { transform: translateY(-.6em); opacity: 1; } } &.selected-flavor { border-color: variable(text-color); } } // Experience .experience-list { width: 100%; display: flex; flex-direction: column; .experience-title { font-weight: bold; } .experience-toggle { flex: 1; display: flex; flex-direction: row; justify-content: space-between; align-items: center; padding: .3rem 0 .3rem 0; } } // Language .language-selector { width: 100%; display: inline-flex; justify-content: space-between; align-items: center; .current-language-name { font-weight: bold; } .language-dropdown { font-size: .6rem; } } .language-flag { font-size: 1.5rem; display: inline-flex; align-content: center; } </style>
from pox.core import core import pox.openflow.libopenflow_01 as of from pox.lib.revent.revent import * from pox.lib.util import dpidToStr from pox.lib.packet.ethernet import ethernet from pox.lib.packet.ipv4 import ipv4 from pox.lib.addresses import EthAddr, IPAddr import json ERROR = -1 class NumeroInvalidoDeSwitch(Exception): pass class LecturaIncorrectaDeReglas(Exception): pass def guardar_reglas(path): try: with open(path) as archivo: reglas = json.load(archivo) return reglas except Exception: log.error("Error al leer el archivo de reglas") raise LecturaIncorrectaDeReglas("Error al leer el archivo de reglas") log = core.getLogger() firewall_switch_id = 1 reglas = {"reglas": []} class Firewall(EventMixin): def __init__(self): self.listenTo(core.openflow) log.debug("Habilitando el Firewall") def _handle_PacketIn(self, evento): pass def _handle_ConnectionUp(self, evento): if evento.dpid == firewall_switch_id: for regla in reglas["reglas"]: mensaje = of.ofp_flow_mod() self.aplicar_regla(mensaje, regla) evento.connection.send(mensaje) log.debug(f"Reglas de Firewall instaladas en {dpidToStr(evento.dpid)} switch {firewall_switch_id}") def aplicar_regla_data_link(self, mensaje, clave, valor): if clave == "src_mac": log.debug(f"Regla instalada: droppeando paquete proveniente de dirección MAC {valor}") mensaje.match.dl_src = EthAddr(valor) elif clave == "dst_mac": log.debug(f"Regla instalada: droppeando paquete con dirección MAC destino {valor}") mensaje.match.dl_dst = EthAddr(valor) def aplicar_regla_network(self, mensaje, clave, valor): if clave == "src_ip": log.debug(f"Regla instalada: droppeando paquete proveniente de dirección IP {valor}") mensaje.match.nw_src = IPAddr(valor) elif clave == "dst_ip": log.debug(f"Regla instalada: droppeando paquete con dirección IP destino {valor}") mensaje.match.nw_dst = IPAddr(valor) elif clave == "src_port": log.debug(f"Regla instalada: droppeando paquete proveniente de puerto {valor}") mensaje.match.tp_src = valor elif clave == "dst_port": log.debug(f"Regla instalada: droppeando paquete con puerto de destino {valor}") mensaje.match.tp_dst = valor def aplicar_regla_transporte(self, mensaje, clave, valor): if clave == "protocol" and valor == "tcp": log.debug("Regla instalada: droppeando paquete TCP") mensaje.match.nw_proto = ipv4.TCP_PROTOCOL elif clave == "protocol" and valor == "udp": log.debug("Regla instalada: droppeando paquete UDP") mensaje.match.nw_proto = ipv4.UDP_PROTOCOL def aplicar_regla(self, mensaje, regla): mensaje.match.dl_type = ethernet.IP_TYPE for clave, valor in regla.items(): if clave in ["src_mac", "dst_mac"]: self.aplicar_regla_data_link(mensaje, clave, valor) elif clave in ["src_ip", "dst_ip", "src_port", "dst_port"]: self.aplicar_regla_network(mensaje, clave, valor) elif clave in ["protocol"]: self.aplicar_regla_transporte(mensaje, clave, valor) def launch(path_reglas, switch_id=1): id_switch = int(switch_id) if id_switch < 1: log.error("Switch ID invalido") raise NumeroInvalidoDeSwitch("El ID del switch debe ser mayor a 0") global firewall_switch_id global reglas reglas_a_aplicar = guardar_reglas(path_reglas) reglas = reglas_a_aplicar log.debug("Reglas:\n" + str(reglas)) firewall_switch_id = id_switch core.registerNew(Firewall)
<?php namespace App\DataTables\Audit; use App\Traits\LogReader; use Yajra\DataTables\Html\Column; use Yajra\DataTables\Services\DataTable; class QueryDataTable extends DataTable { use LogReader; /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->of($query['logs']) ->addIndexColumn(); } /** * Get query source of dataTable. * * @param \App\Models\Logging/QueryDataTable $model * @return \Illuminate\Database\Eloquent\Builder */ public function query() { return collect( (object) $this->getFileContent('daily', 'query') ); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { return $this->builder() ->serverSide(false) ->setTableId('querydatatable-table') ->columns($this->getColumns()) ->language($this->getLanguage()) ->minifiedAjax() ->dom('lBfrtip') ->lengthChange(true) ->lengthMenu() ->pageLength(10) ->responsive(true) ->autoWidth(true); } /** * Get language. * * @return array */ protected function getLanguage() { return trans('datatable.translate'); } /** * Get columns. * * @return array */ protected function getColumns() { return [ Column::make('id') ->data('DT_RowIndex') ->title(trans('table.query.id')) ->addClass('text-center'), Column::make('timestamp') ->title(trans('table.query.timestamp')) ->addClass('text-center'), Column::make('env') ->title(trans('table.query.env')) ->addClass('text-center'), Column::make('type') ->title(trans('table.query.type')) ->addClass('text-center'), Column::make('message') ->title(trans('table.query.message')) ->addClass('text-center') ]; } /** * Get filename for export. * * @return string */ protected function filename() { return 'Query_' . date('YmdHis'); } }
<template> <h3>Login Page</h3> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> | <router-link to="/register">Register</router-link> | <router-link to="/login">Login</router-link> | <router-link to="/profile">Profile</router-link> | <br/> <div class="container"> <div class="row"> <form action="javascript:void(0)" class="row" method="post"> <div class="col-12" v-if="Object.keys(validationErrors).length > 0"> <div class="alert alert-danger"> <ul class="mb-0"> <li v-for="(value, key) in validationErrors" :key="key">{{ value[0] }}</li> </ul> </div> </div> <div class="form-group col-12"> <label for="email" class="font-weight-bold">Email</label> <input type="text" v-model="auth.email" name="email" id="email" class="form-control"> </div> <div class="form-group col-12 my-2"> <label for="password" class="font-weight-bold">Password</label> <input type="password" v-model="auth.password" name="password" id="password" class="form-control"> </div> <div class="col-12 mb-2"> <button type="submit" :disabled="processing" @click="login" class="btn btn-primary btn-block"> {{ processing ? "Please wait" : "Login" }} </button> </div> </form> </div> </div> </template> <script> import axios from 'axios'; import { mapActions } from 'vuex'; export default{ name: "login", data(){ return{ auth:{ email:"", password:"" }, validationErrors:{}, processing:false } }, methods:{ ...mapActions({ signIn: 'auth/login', }), async login(){ this.processing = true; await axios.get('/sanctum/csrf-cookie') await axios.post('/api/login',this.auth).then(({data})=>{ this.signIn() }).catch(({response})=>{ if(response.status===422){ this.validationErrors = response.data.errors }else{ this.validationErrors = {} alert(response.data.message) } }).finally(()=>{ this.processing = false }) } } } </script>
<!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.w3.org/1999/xhtml"> <head th:replace="fragments/head :: head"></head> <header th:replace="fragments/header :: header"></header> <body> <main role="main" class="container"> <div class="jumbotron pb-3 pt-4"> <div class="row"> <div class="col-md-4"> <img th:src="${movieDetailsDTO.getCover().getSource()}" class="card-img" th:alt="${movieDetailsDTO.getCover().getName()}" th:title="'© ' + ${movieDetailsDTO.getCover().getAuthor()}"> </div> <div class="col"> <div class="row"> <div class="col"> <h1 id="moviePage:movieTitle" class="text-dark" th:text="${movieDetailsDTO.getTitle()}">Title</h1> </div> <div class="col"> <h1 class="text-right"><span class="text-warning">★</span><span id="moviePage:movieRating" class="text-dark" title="Średnia ocen TMDB" th:text="${movieDetailsDTO.getTmdbVoteAvg()}">Rating</span></h1> </div> </div> <h5 class="text-muted"> <a href="#" class="badge badge-pill badge-dark" th:each="category : ${movieDetailsDTO.getCategories()}" th:text="'#' + ${category}">#category</a> </h5> <br> <span id="moviePage:movieDescription" th:text="${movieDetailsDTO.getDescription().isEmpty()} ? 'Ten film nie ma jeszcze opisu...' : ${movieDetailsDTO.getDescription()}">Description</span> <hr class="my-4"> <ul> <li> <span th:text="'Rok produkcji: ' + ${movieDetailsDTO.getReleaseDate()}">Release date</span> </li> <li th:if="${movieDetailsDTO.getDuration() != 0}"> <span th:text="'Czas trwania: ' + ${movieDetailsDTO.getDuration() + ' min'}">Duration</span> </li> <li th:if="${!movieDetailsDTO.getDirector().isEmpty()}"> <span th:text="'Reżyseria: ' + ${movieDetailsDTO.getDirector()}">Director</span> </li> <li th:if="${!movieDetailsDTO.getScenario().isEmpty()}"> <span th:text="'Scenariusz: ' + ${movieDetailsDTO.getScenario()}">Scenario</span> </li> <li th:if="${!movieDetailsDTO.getCountry().isEmpty()}"> <span th:text="'Produkcja: ' + ${movieDetailsDTO.getCountry()}">Country</span> </li> </ul> </div> </div> </div> <div class="jumbotron pb-3 pt-4"> <h4>Oceny użytkowników</h4> <ul> <li> <span th:text="'Średnia ocena TMDB: ' + ${movieDetailsDTO.getTmdbVoteAvg()}">Tmdb vote average</span> </li> <li> <span th:text="'Ocen w TMDB: ' + ${movieDetailsDTO.getTmdbVoteCount()}">Tmdb vote count</span> </li> <li> <span th:text="'Średnia ocena Filmzone: ' + ${movieDetailsDTO.getFzVoteAvg()}">Filmzone vote average</span> </li> <li> <span th:text="'Ocen w Filmzone: ' + ${movieDetailsDTO.getFzVoteCount()}">Filmzone vote count</span> </li> </ul> <div sec:authorize="isAuthenticated()"> <hr class="my-4"> <form th:action="@{/rateMovie}" method="post"> <input type="hidden" th:name="rating_movieId" th:value="${movieDetailsDTO.getMovieId()}" /> <div class="btn-toolbar" style="justify-content: center; display: flex;" role="toolbar"> <div class="btn-group mr-2" data-toggle="tooltip" data-placement="bottom" th:with="intList=${ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} }" th:title="${userRating.getTooltip()}" role="group" aria-label="Rating group"> <div class="btn btn-outline-dark bg-dark text-white" th:text="${userRating.getHeader()}">Movie rating</div> <button type="submit" th:each="i : ${intList}" th:classappend="${userRating.getRate() == i}? text-warning : text-white" class="btn btn-outline-dark bg-dark" th:name="rating" th:text="|${i}|" th:value="|${i}|">1</button> </div> </div> </form> </div> </div> <div id="mymovies" class="jumbotron pb-3 pt-4" sec:authorize="isAuthenticated()" th:object="${myMovies}"> <h4>Twoje filmy</h4> <hr class="my-4"> <div th:if="${!myMovies.getListsContainMovie().isEmpty()}"> <h5>Twoje listy, na których znajduje się ten film:</h5> <ul> <li th:each="listName : ${myMovies.getListsContainMovie()}"> <a class="text-dark" th:href="@{'/myMovies'(listName=${listName})}" th:text="${listName}">List name</a> </li> </ul> </div> <div> <form th:action="@{/addMovieToList}" method="post"> <input type="hidden" th:name="mymovies_movieId" th:value="${movieDetailsDTO.getMovieId()}" /> <div class="input-group"> <select th:name="selectedList" class="custom-select border-dark"> <option class="disabled" value="-1">Wybierz listę, do której chcesz dodać film...</option> <option th:each="listName : ${myMovies.getAvailableLists()}" th:value="${listName}", th:text="${listName}">name</option> </select> <div class="input-group-append"> <button th:name="action" th:value="add" class="btn btn-outline-dark bg-dark text-white px-4" type="submit">Dodaj</button> </div> <input th:name="newListName" type="text" data-toggle="tooltip" title="Podaj nazwę nowej listy" class="form-control border-dark" placeholder="...lub utwórz nową"> <div class="input-group-append"> <button th:name="action" th:value="create" class="btn btn-outline-dark bg-dark text-white px-4" type="submit">Utwórz</button> </div> </div> </form> </div> </div> <div th:if="${!movieDetailsDTO.getPictures().isEmpty()}" class="jumbotron pb-3 pt-4"> <h4>Zdjęcia</h4> <div id="carouselPhotos" class="carousel slide bg-dark rounded" data-ride="carousel"> <ol class="carousel-indicators"> <li th:each="id : ${movieDetailsDTO.getPictures()}" data-target="#carouselPhotos" th:data-slide-to="${idStat.index}" th:classappend="${idStat.first}? active"></li> </ol> <div class="carousel-inner"> <div th:each="photo : ${movieDetailsDTO.getPictures()}" class="carousel-item" th:classappend="${photoStat.first}? active"> <img th:src="${photo.getSource()}" class="d-block mx-auto" style="max-height: 500px;" th:alt="${photo.getName()}"> <div class="carousel-caption d-none d-md-block"> <span class="bg-dark px-3 py-1 rounded-pill" th:text="'@Autor: ' + ${photo.getAuthor()}">@Author</span> </div> </div> </div> <a class="carousel-control-prev" href="#carouselPhotos" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselPhotos" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <div th:if="${!movieDetailsDTO.getTrailerLink().isEmpty()}" class="jumbotron pb-3 pt-4"> <h4>Trailer</h4> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" th:src="${movieDetailsDTO.getTrailerLink()}" allowfullscreen></iframe> </div> </div> <div th:if="${!movieDetailsDTO.getCharacters().isEmpty()}" class="jumbotron pb-3 pt-4"> <h4>Obsada</h4> <div th:each="character : ${movieDetailsDTO.getCharacters()}" class="row"> <div class="col"> <p class="text-right font-weight-bold" th:text="${character.getName()}">Actor name</p> </div> <div class="col"> <p class="text-left" th:text="${character.getCharacter()}">Character</p> </div> </div> </div> <div class="jumbotron pb-3 pt-4" id="comments"> <h4>Komentarze</h4> <form th:action="@{/movie/__${movieDetailsDTO.getMovieId()}__#comments}" method="get" class="row pb-4"> <div class="col" th:if="${commentPage.getTotalElements() > 0}"> <div class="input-group"> <div class="input-group-prepend"> <button class="btn btn-outline-dark bg-dark text-white px-4" type="submit">Sortuj</button> </div> <select class="custom-select border-dark" th:name="sort"> <option value="date:DESC" th:selected="${#httpServletRequest.getParameter('sort') == 'date:DESC'}">Wg. daty malejąco</option> <option value="date:ASC" th:selected="${#httpServletRequest.getParameter('sort') == 'date:ASC'}">Wg. daty rosnąco</option> </select> </div> </div> <div class="col text-center"> <h4> <span class="badge bg-dark text-white py-2">Liczba komentarzy <span class="badge badge-light" th:text="${commentPage.getTotalElements()}">number of comments</span></span> </h4> </div> <div class="col" th:if="${commentPage.getTotalElements() > 0}"> <div class="input-group"> <select class="custom-select border-dark" th:name="size" th:field="*{commentPage.size}"> <option value="10">10 komentarzy na strone</option> <option value="20">20 komentarzy na strone</option> <option value="50">50 komentarzy na strone</option> </select> <div class="input-group-append"> <button class="btn btn-outline-dark bg-dark text-white px-4" type="submit">Pokaż</button> </div> </div> </div> </form> <div class="card border-dark mb-2" sec:authorize="isAuthenticated()"> <div class="card-header"> <div class="row"> <div class="col text-left font-weight-bold text-dark">Nowy komentarz</div> </div> </div> <div class="card-body"> <form th:action="@{/addCommentToMovie}" method="post"> <div class="mb-3"> <input type="hidden" th:name="comment_movieId" th:value="${movieDetailsDTO.getMovieId()}" /> <textarea th:name="comment_content" class="form-control" placeholder="Wpisz treść komentarza"></textarea> </div> <div class="text-right"> <button type="submit" class="btn btn-outline-dark bg-dark text-white">Dodaj komentarz</button> </div> </form> </div> </div> <div class="card border-dark mb-2" th:each="comment : ${commentPage.getContent()}" th:if="${commentPage.getTotalElements() > 0}"> <div class="card-header"> <div class="row"> <div class="col text-left font-weight-bold text-dark" th:text="${comment.getUser().getNickname()}">author</div> <div class="col text-right font-weight-light text-dark" th:text="${#dates.format(comment.getDate(), 'dd.MM.yyyy HH:mm')}">dd.MM.yyyy HH:mm</div> </div> </div> <div class="card-body"> <div class="row"> <div class="col"> <span th:text="${comment.getContent()}">content</span> </div> <div sec:authorize="hasRole('ROLE_ADMIN')" class="col-md-auto"> <button th:attr="onclick='confirmCommentRemoval(\'' + ${comment.getUser().getNickname()} +'\',\''+ ${comment.getContent()} + '\',\''+ ${comment.getId()} + '\');'" class="btn btn-danger text-white">Usuń komentarz</button> </div> </div> </div> </div> <nav class="pt-3" th:if="${commentPage.getTotalElements() > 0}"> <ul class="pagination justify-content-center"> <li class="page-item" th:classappend="${commentPage.first}? disabled"> <a class="page-link border-dark text-dark" th:href="@{/movie/{id}#comments (id=${movieDetailsDTO.getMovieId()}, size=${commentPage.size}, page=1, sort=${#httpServletRequest.getParameter('sort')})}">|<</a> </li> <li class="page-item" th:classappend="${!commentPage.hasPrevious()}? disabled"> <a class="page-link border-dark text-dark" th:href="@{/movie/{id}#comments (id=${movieDetailsDTO.getMovieId()}, size=${commentPage.size}, page=${commentPage.getNumber()}, sort=${#httpServletRequest.getParameter('sort')})}"><</a> </li> <li class="page-item disabled"> <a class="page-link border-dark bg-dark text-white" th:text="${commentPage.getNumber()+1} + ' z ' + ${commentPage.getTotalPages()}">current page</a> </li> <li class="page-item" th:classappend="${!commentPage.hasNext()}? disabled"> <a class="page-link border-dark text-dark" th:href="@{/movie/{id}#comments (id=${movieDetailsDTO.getMovieId()}, size=${commentPage.size}, page=${commentPage.getNumber()+2}, sort=${#httpServletRequest.getParameter('sort')})}">></a> </li> <li class="page-item" th:classappend="${commentPage.last}? disabled"> <a class="page-link border-dark text-dark" th:href="@{/movie/{id}#comments (id=${movieDetailsDTO.getMovieId()}, size=${commentPage.size}, page=${commentPage.getTotalPages()}, sort=${#httpServletRequest.getParameter('sort')})}">>|</a> </li> </ul> </nav> </div> <div class="modal fade" id="commentRemovalModal" tabindex="-1" role="dialog" aria-hidden="true"> <form th:action="@{/removeComment}" method="post"> <input type="hidden" th:value="${movieDetailsDTO.getMovieId()}" name="movieId"/> <input type="hidden" id="commentRemovalModal_commentId" name="commentId"/> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Ostrzeżenie</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <span>Czy na pewno chcesz usunąć komentarz użytkownika </span> <label class="font-weight-bold" id="commentRemovalModal_username">username</label> <span> o treści </span> <span>"</span> <span class="font-italic" id="commentRemovalModal_content">content</span> <span>"?</span> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Anuluj</button> <button type="submit" class="btn btn-primary">Potwierdź</button> </div> </div> </div> </form> </div> </main> </body> <footer th:replace="fragments/footer :: footer"></footer> </html>
# DNS Spoofing Tool The DNS Spoofing Tool is a Python script that uses Scapy and NetfilterQueue to intercept and spoof DNS responses, redirecting a target website to a specified IP address. This tool can be used for educational purposes to demonstrate DNS spoofing and its implications. ## Requirements - Python 3.x - Scapy - NetfilterQueue ## Installation 1. Clone or download the repository to your local machine. 2. Install the required dependencies using pip: ```sh pip install scapy netfilterqueue ``` ## Usage 1. Open a terminal and navigate to the directory containing the `dns_spoof.py` script. 2. Run the script as root (administrator) using the following command: ```sh sudo python3 dns_spoof.py target new_ip ``` Replace `target` with the website you want to spoof (e.g., www.bing.com) and `new_ip` with the IP address you want to redirect the target website to. 3. The script will intercept DNS responses and spoof the target website, redirecting it to the specified IP address. 4. To stop the DNS spoofing, press `Ctrl+C` in the terminal. ## Example To spoof the website "www.example.com" and redirect it to the IP address "10.0.2.15", run the following command: ```sh sudo python3 dns_spoof.py www.example.com 10.0.2.15 ``` ## Important Notes - This tool is for educational and research purposes only. Do not use it for malicious activities. - DNS spoofing can disrupt network communication and potentially lead to security vulnerabilities. - Ensure you have proper authorization before using this tool on any network. ## Disclaimer This tool is provided for educational and research purposes only. The author shall not be held responsible for any misuse or illegal activities conducted using this tool.
import { Component, OnInit } from '@angular/core'; import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { NewVideogioco } from '../model/videogioco'; import { CategoriaService } from '../service/categoria.service'; import { VideogiocoService } from '../service/videogioco.service'; @Component({ selector: 'app-form-videogiochi', templateUrl: './form-videogiochi.component.html', styleUrls: ['./form-videogiochi.component.css'], }) export class FormVideogiochiComponent implements OnInit { form: FormGroup = new FormGroup({ title: new FormControl('', [Validators.required]), category: new FormControl('', [Validators.required]), releaseDate: new FormControl('', [Validators.required]), genre: new FormControl('', [Validators.required]), softwareHouse: new FormControl('', [Validators.required]), publisher: new FormControl('', [Validators.required]), numberOfPlayers: new FormControl('', [Validators.required]), languages: new FormGroup({ voice: new FormArray([new FormControl('', [Validators.maxLength(3)])]), text: new FormArray([ new FormControl('', [Validators.required, Validators.maxLength(3)]), ]), }), coverImage: new FormControl('', [Validators.required]), }); isEditMode: boolean = false; idModifiable: string = ''; noModifiable = false; __vModifiable = 0; // lista delle categorie/console che servirà nel slect del template per scegliere la console giusta categoryList: string[] = []; constructor( private videogiochiService: VideogiocoService, private categoriaService: CategoriaService, private route: ActivatedRoute, private router: Router ) {} reset() { this.form.reset(); this.isEditMode = false; this.noModifiable = false; this.idModifiable = ''; this.__vModifiable = 0; } ngOnInit(): void { this.categoriaService.getCategorie().subscribe((list) => { this.categoryList = list.map((obj) => obj.name as string); }); this.route.params.subscribe((params) => { const id = params['id']; if (id !== undefined) { //console.log('id check passed'); this.isEditMode = true; this.idModifiable = id; this.videogiochiService.getVideogioco(id).subscribe({ next: (gameData) => { const datoGioco = gameData; this.__vModifiable = datoGioco.__v; this.form = new FormGroup({ title: new FormControl(datoGioco.title, [Validators.required]), category: new FormControl(datoGioco.category, [ Validators.required, ]), releaseDate: new FormControl(datoGioco.releaseDate, [ Validators.required, ]), genre: new FormControl(datoGioco.genre, [Validators.required]), softwareHouse: new FormControl(datoGioco.softwareHouse, [ Validators.required, ]), publisher: new FormControl(datoGioco.publisher, [ Validators.required, ]), numberOfPlayers: new FormControl(datoGioco.numberOfPlayers, [ Validators.required, ]), languages: new FormGroup({ voice: new FormArray( datoGioco.languages.voice.map( (l) => new FormControl(l, [Validators.maxLength(3)]) ) ), text: new FormArray( datoGioco.languages.text.map( (t) => new FormControl(t, [ Validators.required, Validators.maxLength(3), ]) ) ), }), coverImage: new FormControl(datoGioco.coverImage, [ Validators.required, ]), }); }, error: (error) => { console.log(error); this.noModifiable = true; }, }); } }); } get voiceFormArray() { return this.form.get('languages.voice') as FormArray; } onClickAddVoice() { this.voiceFormArray.push(new FormControl('', [Validators.required])); } onClickRemoveVoice(index: number) { this.voiceFormArray.removeAt(index); } get textFormArray() { return this.form.get('languages.text') as FormArray; } onClickAddText() { this.textFormArray.push(new FormControl('', [Validators.required])); } onClickRemoveText(index: number) { this.textFormArray.removeAt(index); } onSubmit() { if ( this.form.get('languages.voice')?.hasError('maxlength') || this.form.get('languages.text')?.hasError('maxlength') ) { alert('Inserisci le lingue in codici da 3 lettere'); return; } if (this.form.invalid) { alert('Compila tutti i campi in modo corretto.'); return; } if (this.isEditMode) { console.log('AGGIORNAMENTO RECORD'); const modGioco = this.form.getRawValue(); this.videogiochiService .putVideogioco(this.idModifiable, modGioco, this.__vModifiable) .subscribe(() => { this.reset(); this.router.navigateByUrl('lista/games'); alert('record aggiornato'); }); } else { console.log('AGGIUNTA RECORD'); const newG: NewVideogioco = this.form.getRawValue(); this.videogiochiService.addVideogioco(newG).subscribe(() => { this.reset(); this.router.navigateByUrl('/lista/games'); alert('nuovo record aggiunto'); }); } } }
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct { char employee_name[100]; int emp_no; float emp_salary; } Employee; // Function to swap two Employee elements void swap(Employee *a, Employee *b, int *swap_count) { Employee temp = *a; *a = *b; *b = temp; (*swap_count)++; } // Partition function for Quick Sort int partition(Employee array[], int low, int high, int *swap_count) { int pivot = array[high].emp_no; // Pivot element int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than or equal to pivot if (array[j].emp_no <= pivot) { i++; // Increment index of smaller element swap(&array[i], &array[j], swap_count); } } swap(&array[i + 1], &array[high], swap_count); return (i + 1); } // Quick Sort function void quickSort(Employee array[], int low, int high, int *swap_count) { if (low < high) { int pi = partition(array, low, high, swap_count); // Partitioning index quickSort(array, low, pi - 1, swap_count); // Sort the elements before partition quickSort(array, pi + 1, high, swap_count); // Sort the elements after partition } } // Function to print the array of Employees void printArray(Employee array[], int n) { for (int i = 0; i < n; i++) { printf("Name: %s, Emp No: %d, Salary: %.2f\n", array[i].employee_name, array[i].emp_no, array[i].emp_salary); } } // Function to add an employee to the array void addEmployee(Employee array[], int *n) { if (*n >= 100) { printf("Array is full!\n"); return; } printf("Enter Employee Name: "); scanf("%s", array[*n].employee_name); printf("Enter Employee Number: "); scanf("%d", &array[*n].emp_no); printf("Enter Employee Salary: "); scanf("%f", &array[*n].emp_salary); (*n)++; } int main() { Employee employees[100]; int n = 0; int swap_count = 0; int choice; while (1) { printf("\nEmployee Management System\n"); printf("1. Add Employee\n"); printf("2. Display Employees\n"); printf("3. Sort Employees by Employee Number (Quick Sort)\n"); printf("4. Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch (choice) { case 1: addEmployee(employees, &n); break; case 2: printf("\nEmployees List:\n"); printArray(employees, n); break; case 3: swap_count = 0; quickSort(employees, 0, n - 1, &swap_count); printf("\nEmployees sorted by Employee Number:\n"); printArray(employees, n); printf("\nNumber of swaps performed: %d\n", swap_count); break; case 4: printf("Exiting...\n"); exit(0); default: printf("Invalid choice, please try again.\n"); } } return 0; }
package hero; public abstract class BaseHero implements BaseHeroInterface { protected String name; protected int strength; protected int dexterity; protected int intelligence; protected int endurance; protected int health; protected int healthMax; // Полный конструктор public BaseHero(String name, int strength, int dexterity, int intelligence, int endurance, int health, int healthMax) { this.name = name; this.strength = strength; this.dexterity = dexterity; this.intelligence = intelligence; this.endurance = endurance; this.health = health; this.healthMax = healthMax; } // Краткий конструктор, через this(...) public BaseHero( String name, int strength, int health ) { this( name, strength, 0, 0, 0, health, health ); } // Пустой конструктор, через this(...) public BaseHero() { this( "unknown", 1, 0, 0, 0, 5, 5 ); } // Геттеры, для изменения значений приватных полей @Override public String getName() { return name; } public int getStrength() { return strength; } public int getDexterity() { return dexterity; } public int getIntelligence() { return intelligence; } public int getEndurance() { return endurance; } public int getHealth() { return health; } public int getHealthMax() { return healthMax; } // Сеттеры, для получения значений приватных полей public void setName( String name ) { this.name = name; } public void setStrength( int strength ) { this.strength = strength; } public void setDexterity( int dexterity ) { this.dexterity = dexterity; } public void setIntelligence( int intelligence ) { this.intelligence = intelligence; } public void setEndurance( int endurance ) { this.endurance = endurance; } public void setHealth( int health ) { this.health = health; } public void setHealthMax( int health ) { this.healthMax = health; } // Действие - Смерть public void die() { setHealth( 0 ); setHealthMax( 0 ); } // Действие - Ранение public void takeDamage( int damage ) { if ( this.health > damage ) { this.health -= damage; System.out.println( this.name + " take damage -" + damage + "hp" ); } else { this.die(); System.out.println( this.name + " has been defeated!" ); } } // Действие - Атака public void attack( BaseHero target ) { int damage = this.strength * 1; target.takeDamage( damage ); System.out.println( this.name + " attacks " + target.getName() + " for " + damage + " damage!" ); } // Действие - Лечение (не больше максимума) public void rest( int hp ) { this.health = this.health + hp > this.healthMax ? this.healthMax : hp + this.health; System.out.println( this.name + " rests and recovers " + hp + " health points." ); } // Вывод в строковом виде (краткий, т.к. не все...) public String toString() { return String.format("-- %s -- %s[%d/%d], Сила: %d --", this.getClass().getName(), this.name, this.health, this.healthMax, this.strength); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <link href='https://fonts.googleapis.com/css?family=Poppins' rel='stylesheet'> <link href='https://fonts.googleapis.com/css?family=Poppins' rel='stylesheet'> <link href='https://fonts.googleapis.com/css?family=Major Mono Display' rel='stylesheet'> <title>Anuj UI/UX</title> <!-- MDB icon --> <link rel="icon" href="img/7.png" type="image/x-icon" /> <!-- MDB --> <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/3.10.1/mdb.min.css" rel="stylesheet" /> <style> .webgl { position: absolute; top: 0; left: 0; outline: none; z-index: -1; background-color: rgb(0, 0, 0); } h2.first { margin-right: 62.5vw; margin-top: 18vw; font-size: 4vw; font-family: Major Mono Display; } h2.last { margin-left: 62.5vw; margin-top: -5.6vw; font-size: 4vw; font-family: Major Mono Display; } .topnav { margin-top: 2.5vw; margin-left: -5vw; } .topnav-centered a { font-family: Poppins; color: rgb(255, 255, 255); text-align: center; padding: 2vw 0.5vw; text-decoration: none; font-size: 1.05vw; padding-top: 8vw; margin-left: 5vw; } .topnav-centered a:hover { color: rgb(94, 190, 253); } .foot { /* margin-left: 2vw; text-align: center; margin-top: 12.5vw; margin-left: -5vw;*/ position: fixed; left: 0; bottom: 2vw; width: 100%; text-align: center; margin-left: -3vw; } .twi { height: 1.9vw; width: 2.2vw; margin-left: 4vw; transition: transform ease-in-out .3s; } .twi:hover { transform: scale(1.25); /* (150% zoom - Note: if the zoom is too large, it will go outside of the viewport) */ } .inst { height: 1.95vw; width: 2vw; margin-left: 8vw; margin-top: 0vw; transition: transform ease-in-out .3s; } .inst:hover { transform: scale(1.25); /* (150% zoom - Note: if the zoom is too large, it will go outside of the viewport) */ } .link { height: 1.8vw; width: 1.85vw; margin-left: 8vw; margin-top: 0vw; margin-bottom: 0.25vw; transition: transform ease-in-out .3s; } .link:hover { transform: scale(1.25); /* (150% zoom - Note: if the zoom is too large, it will go outside of the viewport) */ } </style> </head> <body> <div class="container text-center text-white"> <header> <div class="topnav"> <!-- Centered link --> <div class="topnav-centered"> <a href="project.html">Projects</a> <a href="resume.html">Resume</a> <a href="#socials">Contact</a> </div> </div> </header> <h2 class="first">Anuj</h2> <h2 class="last">ui/uX</h2> <footer> <div class="foot"> <a href="https://twitter.com/A_n_u_j_06" target="_blank"> <img class="twi" src="img/1.png"></a> <a href="https://www.instagram.com/anuj.undesign/" target="_blank"> <img class="inst" src="img/2.png" alt=""></a> <a href="https://www.linkedin.com/in/anuj-sonawane-323359206/" target="_blank"> <img class="link" src="img/3.png" alt=""></a> </div> </footer> </div> <canvas class="webgl"></canvas> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/3.10.1/mdb.min.js"></script> <!-- Three.js core --> <script type="text/javascript" src="js/three.min.js"></script> <script type="text/javascript" src="js/OrbitControls.js"></script> <!-- Three.js setup --> <script type="text/javascript"> // Texture // Canvas const canvas = document.querySelector("canvas.webgl"); // Scene const scene = new THREE.Scene(); // Objects const geometry = new THREE.TorusKnotGeometry(0.45, 0.1, 250, 40); // Materials const material = new THREE.MeshStandardMaterial({ color: 0x049ef4, wireframe: false, metalness: 1, roughness: 0, emissive: 0x030d35 }); const spotLight = new THREE.SpotLight(0xffffff, 1000); spotLight.position.set(100, 50, 100); spotLight.castShadow = true; spotLight.shadow.mapSize.width = 1024; spotLight.shadow.mapSize.height = 1024; spotLight.shadow.camera.near = 500; spotLight.shadow.camera.far = 4000; spotLight.shadow.camera.fov = 100; scene.add(spotLight); const spotLight1 = new THREE.SpotLight(0xffffff, 3000); spotLight1.position.set(1000, 10000, -100); spotLight1.castShadow = true; spotLight1.shadow.mapSize.width = 1024; spotLight1.shadow.mapSize.height = 1024; spotLight1.shadow.camera.near = 500; spotLight1.shadow.camera.far = 4000; spotLight1.shadow.camera.fov = 30; scene.add(spotLight1); //const material = new THREE.MeshStandardMaterial(); //material.map = normalTexture; // Mesh const shape = new THREE.Mesh(geometry, material); scene.add(shape); // Lights const pointLight = new THREE.PointLight(0xffffff, 1); pointLight.position.x = 2; pointLight.position.y = 3.5; pointLight.position.z = 20; scene.add(pointLight); /** * Sizes */ const sizes = { width: window.innerWidth, height: window.innerHeight, }; window.addEventListener("resize", () => { // Update sizes sizes.width = window.innerWidth; sizes.height = window.innerHeight; // Update camera camera.aspect = sizes.width / sizes.height; camera.updateProjectionMatrix(); // Update renderer renderer.setSize(sizes.width, sizes.height); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); }); /** * Camera */ // Base camera const camera = new THREE.PerspectiveCamera( 75, sizes.width / sizes.height, 0.1, 100 ); camera.position.x = 0; camera.position.y = 1.75; camera.position.z = 0.25; scene.add(camera); /** * Renderer */ const renderer = new THREE.WebGLRenderer({ canvas: canvas, }); renderer.setSize(sizes.width, sizes.height); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); /** * Animate */ controls = new THREE.OrbitControls(camera, renderer.domElement); const clock = new THREE.Clock(); const tick = () => { const elapsedTime = clock.getElapsedTime(); // Update objects shape.rotation.y = 0.2 * elapsedTime; shape.rotation.x = 0.5 * elapsedTime; // Update Orbital Controls // controls.update() // Render renderer.render(scene, camera); // Call tick again on the next frame window.requestAnimationFrame(tick); }; tick(); </script> </body> </html>
import { Suspense } from 'react'; import MovieInfo, { getMovie } from '../../../../components/movie-info'; import MovieVideos from '../../../../components/movie-videos'; // dynamic metadata를 위해 자동으로 호출 export const generateMetadata = async ({ params: { id }, }: { params: { id: string }; }) => { const movie = await getMovie(id); return { title: movie.title, }; }; export default async function MovieDetail({ params: { id }, }: { params: { id: string }; }) { //Parallel Request // const [movie, video] = await Promise.all([getMovie(id), getVideo(id)]); return ( <> <Suspense fallback={<h1>Loading Movie Info</h1>}> <MovieInfo id={id} /> </Suspense> <Suspense fallback={<h1>Loading Movie Videos</h1>}> <MovieVideos id={id} /> </Suspense> </> ); }
import 'package:alarmtogether/controllers/firebase_helper/server_data.dart'; import 'package:alarmtogether/models/alarm.dart'; import 'package:alarmtogether/views/pages/alarm/alarm_layout.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class AlarmPage extends StatelessWidget { VoidCallback _newAlarm(BuildContext context) { Uri uri = Uri(pathSegments: ["", "alarm", "new"]); return () { context.push(uri.toString()); }; } @override Widget build(BuildContext context) { return FutureBuilder( future: ServerData.readAllAlarm(), builder: (context, snapshot) { List<Widget> sliver = [ SliverAppBar( leading: IconButton( icon: Icon(CupertinoIcons.add), onPressed: _newAlarm(context),), title: Text("Alarm"), centerTitle: true, pinned: true, ), ]; if (snapshot.hasData) { var alarms = snapshot.data ?? {}; sliver.add( SliverList.separated( itemBuilder: (context, i) => AlarmLayout(alarmID: alarms.keys.elementAt(i), alarm: alarms.values.elementAt(i)), itemCount: alarms.length, separatorBuilder: (BuildContext context, int index) { return const Divider(); }, ) ); } else { sliver.add( const SliverToBoxAdapter( child: Center(child: CircularProgressIndicator(),), ) ); } return CustomScrollView( slivers: sliver, ); } ); } }
const container = document.querySelector(".container"); const search = document.querySelector(".search-box button"); const weatherBox = document.querySelector(".weather-box"); const weatherDetails = document.querySelector(".weather-details"); const error404 = document.querySelector(".not-found"); //事件監聽點擊觸發功能 search.addEventListener("click", () => { const APIKey = "8c15f5127fda7e875b24210217dc35cc"; const city = document.querySelector(".search-box input").value; //如輸入空值則直接return if (city === "") return; //api fetch( `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${APIKey}` ) .then((response) => response.json()) .then((json) => { console.log(json); //如回傳404,將天氣資訊隱藏,顯示錯誤頁面 if (json.cod === "404") { container.style.height = "400px"; weatherBox.style.display = "none"; weatherDetails.style.display = "none"; error404.style.display = "block"; error404.classList.add("fade-in"); return; } //輸入值正確,隱藏404頁面,已添加fade-in移除 error404.style.display = "none"; error404.classList.remove("fade-in"); const date = document.querySelector(".weather-box .date"); const image = document.querySelector(".weather-box img"); const temperature = document.querySelector(".weather-box .temperature"); const description = document.querySelector(".weather-box .description"); const humidity = document.querySelector( ".weather-details .humidity span" ); const wind = document.querySelector(".weather-details .wind span"); //依據傳回資訊顯示對應的天氣圖片 switch (json.weather[0].main) { case "Clear": image.src = "images/clear.png"; break; case "Rain": image.src = "images/rain.png"; break; case "Snow": image.src = "images/snow.png"; break; case "Clouds": image.src = "images/cloud.png"; break; case "Haze": image.src = "images/mist.png"; break; default: image.src = ""; } //依據傳回資訊顯示對應的數值 temperature.innerHTML = `${parseInt(json.main.temp)}<span>°C</span>`; description.innerHTML = `${json.weather[0].description}`; humidity.innerHTML = `${json.main.humidity}%`; wind.innerHTML = `${parseInt(json.wind.speed)}Km/h`; //天氣資訊不隱藏,顯示天氣頁面 weatherBox.style.display = ""; weatherDetails.style.display = ""; weatherBox.classList.add("fade-in"); weatherDetails.classList.add("fade-in"); container.style.height = "590px"; }); });
<?php namespace App\Http\Controllers; use App\Models\Position; use App\Models\Employee; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; use RealRashid\SweetAlert\Facades\Alert; use PDF; class EmployeeController extends Controller { /** * Display a listing of the resource. */ public function index() { $pageTitle = 'Employee List'; confirmDelete(); return view('employee.index', compact('pageTitle')); } /** * Show the form for creating a new resource. */ public function create() { $pageTitle = 'Create Employee'; // ELOQUENT $positions = Position::all(); return view('employee.create', compact('pageTitle', 'positions')); } public function store(Request $request) { $messages = [ 'required' => ':Attribute harus diisi.', 'email' => 'Isi :attribute dengan format yang benar', 'numeric' => 'Isi :attribute dengan angka' ]; $validator = Validator::make($request->all(), [ 'firstName' => 'required', 'lastName' => 'required', 'email' => 'required|email', 'age' => 'required|numeric', ], $messages); if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); } // Get File $file = $request->file('cv'); if ($file != null) { $originalFilename = $file->getClientOriginalName(); $encryptedFilename = $file->hashName(); // Store File $file->store('public/files'); } // ELOQUENT $employee = New Employee; $employee->firstname = $request->firstName; $employee->lastname = $request->lastName; $employee->email = $request->email; $employee->age = $request->age; $employee->position_id = $request->position; if ($file != null) { $employee->original_filename = $originalFilename; $employee->encrypted_filename = $encryptedFilename; } $employee->save(); Alert::success('Added Successfully', 'Employee Data Added Successfully.'); return redirect()->route('employees.index'); } /** * Display the specified resource. */ public function show(string $id) { $pageTitle = 'Employee Detail'; // ELOQUENT $employee = Employee::find($id); return view('employee.show', compact('pageTitle', 'employee')); } /** * Show the form for editing the specified resource. */ public function edit(string $id) { $pageTitle = 'Edit Employee'; // ELOQUENT $positions = Position::all(); $employee = Employee::find($id); return view('employee.edit', compact('pageTitle', 'positions', 'employee')); } public function update(Request $request, string $id) { $messages = [ 'required' => ':Attribute harus diisi.', 'email' => 'Isi :attribute dengan format yang benar', 'numeric' => 'Isi :attribute dengan angka' ]; $validator = Validator::make($request->all(), [ 'firstName' => 'required', 'lastName' => 'required', 'email' => 'required|email', 'age' => 'required|numeric', ], $messages); if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); } // ELOQUENT $employee = Employee::find($id); $employee->firstname = $request->firstName; $employee->lastname = $request->lastName; $employee->email = $request->email; $employee->age = $request->age; $employee->position_id = $request->position; if ($request->hasFile('cv')) { $file = $request->file('cv'); $originalFilename = $file->getClientOriginalName(); $encryptedFilename = $file->hashName(); $file->store('public/files'); $employee->original_filename = $originalFilename; $employee->encrypted_filename = $encryptedFilename; // Hapus file CV lama jika ada if (!empty($employee->encrypted_filename)) { Storage::delete('public/files/' . $employee->encrypted_filename); } } $employee->save(); Alert::success('Changed Successfully', 'Employee Data Changed Successfully.'); return redirect()->route('employees.index'); } /** * Remove the specified resource from storage. */ public function destroy(string $id) { // ELOQUENT // Temukan employee berdasarkan ID $employee = Employee::find($id); if ($employee) { // Hapus file CV jika ada if (!empty($employee->encrypted_filename)) { Storage::delete('public/files/' . $employee->encrypted_filename); } // Hapus employee dari database $employee->delete(); } Alert::success('Deleted Successfully', 'Employee Data Deleted Successfully.'); // Redirect ke halaman daftar employee return redirect()->route('employees.index'); } public function downloadFile($employeeId) { $employee = Employee::find($employeeId); $encryptedFilename = 'public/files/'.$employee->encrypted_filename; $downloadFilename = Str::lower($employee->firstname.'_'.$employee->lastname.'_cv.pdf'); if(Storage::exists($encryptedFilename)) { return Storage::download($encryptedFilename, $downloadFilename); } } public function getData(Request $request) { $employees = Employee::with('position'); if ($request->ajax()) { return datatables()->of($employees) ->addIndexColumn() ->addColumn('action', function($employee) { return view('employee.action', compact('employee')); }) ->toJson(); } } public function exportPdf() { $employees = Employee::all(); $pdf = PDF::loadView('employee.export_pdf', compact('employees')); return $pdf->download('employees.pdf'); } }
#pragma once #include <string> #include <array> class Product{ public: enum Products : unsigned int{ BREAD, BUNS, MILK, JUICE, SODA, TEA, COFFEE, OATS, CHEESE, POLONY, ACHAR, NAPPIES, AIRTIME, DATA }; Products name; float price; int quantity; Product(); Product(Products pName, int pQuantity); float GetPrice(Products product); std::string GetName(Products product); private: std::array<std::string, 14> names { "BREAD", "BUNS", "MILK", "JUICE", "SODA", "TEA", "COFFEE", "OATS", "CHEESE", "POLONY", "ACHAR", "NAPPIES", "AIRTIME", "DATA" }; std::array<float, 14> prices { 15.0, 15.0, 20.0, 25.0, 23.0, 15.0, 40.0, 65.0, 43.0, 45.0, 150.0, 250.0, 10.0, 100.0 }; };
import { ConflictException, Injectable } from '@nestjs/common'; import { IBaseQuery } from '~libs/resource/interfaces'; import { CreateCategoryDTO, UpdateCategoryDTO } from './dtos'; import { CategoriesRepository } from './categories.repository'; import { Category } from './schemas'; import { RpcException } from '@nestjs/microservices'; import { FilterQuery } from 'mongoose'; @Injectable() export class CategoriesService { constructor(private readonly categoriesRepository: CategoriesRepository) {} async createCategory({ name, label, description, url, requireAttributes }: CreateCategoryDTO) { const isDuplicateLabel = await this.isExistCategory({ filterQueries: { label } }); if (isDuplicateLabel) { throw new RpcException(new ConflictException("Category's label is already exist")); } return await this.categoriesRepository.create({ name, label, description, url, requireAttributes, }); } async getCategory({ filterQueries, queryOptions, projectionArgs }: IBaseQuery<Category>) { const category = await this.categoriesRepository.findOne( filterQueries, queryOptions, projectionArgs, ); return category; } async getCategories({ filterQueries, queryOptions, projectionArgs, }: IBaseQuery<Partial<Category>>): Promise<Category[] | undefined> { return this.categoriesRepository.find({ filterQuery: filterQueries, queryOptions: queryOptions, projection: projectionArgs, }); } async updateCategory({ filterQueries, updateData, }: IBaseQuery<Category> & { updateData: UpdateCategoryDTO }) { return await this.categoriesRepository.findOneAndUpdate(filterQueries, updateData); } async isExistCategory({ filterQueries }: IBaseQuery<Category>) { try { const category = await this.categoriesRepository.findOne(filterQueries); console.log(category); return category ? true : false; } catch (error) { return false; } } async countCategories(filterQueries: FilterQuery<Category> = {}) { return await this.categoriesRepository.count(filterQueries); } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { UserProfileComponent } from './user-profile.component'; import { RegisterComponent } from './register/register.component'; import { ChangePwdComponent } from './change-pwd/change-pwd.component'; import { HomeComponent } from '../home/home.component'; import { NotFoundComponent } from '../not-found/not-found.component'; const routes: Routes = [ { path: '', component: UserProfileComponent }, { path: 'register', component: RegisterComponent }, { path: 'changePwd', component: ChangePwdComponent }, { path: 'home', component: HomeComponent }, { path: '**', component: NotFoundComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class UserProfileRoutingModule {}
import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {Course} from '../model/course'; import { debounceTime, distinctUntilChanged, startWith, tap, delay, map, concatMap, switchMap, withLatestFrom, concatAll, shareReplay, catchError } from 'rxjs/operators'; import {merge, fromEvent, Observable, concat, throwError, combineLatest} from 'rxjs'; import {Lesson} from '../model/lesson'; import { CoursesService } from '../services/courses.service'; // define an interface for single observer pattern interface CourseData{ course:Course; lessons:Lesson[] } @Component({ selector: 'course', templateUrl: './course.component.html', styleUrls: ['./course.component.css'] }) export class CourseComponent implements OnInit { // course$: Observable<Course>; // lessons$: Observable<Lesson[]>; // single observer pattern data$:Observable<CourseData> constructor(private route: ActivatedRoute,private coursesService:CoursesService) { } ngOnInit() { const courseId=parseInt(this.route.snapshot.paramMap.get("courseId")); // in single observable pattern we will combine two different observables //startWith -- Returns an observable that, at the moment of subscription, will synchronously emit all values provided to this operator, then subscribe to the source and mirror all of its emissions to subscribers. const course$=this.coursesService.loadCourseById(courseId).pipe(startWith(null)); const lessons$=this.coursesService.loadAllCourseLessons(courseId).pipe(startWith([])); // single observer pattern // combineLatest-Combines multiple Observables to create an Observable whose values are calculated from the latest values of each of its input Observables //returns data in tuple format so we need to map the data to our respective type //whenever even one of the observables(course$,lessons$) emits a data we will emit a data of type courseData this.data$=combineLatest([course$,lessons$]).pipe( map(([course,lessons])=>{ return{ course,lessons } }), tap(console.log) ) } }
import type { Metadata } from 'next'; import { Session } from 'next-auth'; import { Inter } from 'next/font/google'; import React from 'react'; import { siteConfig } from '@/config'; import { Providers } from '@lib/Providers'; import '@styles/global.css'; const inter = Inter({ subsets: ['latin'] }); export const metadata: Metadata = { metadataBase: new URL(siteConfig.url), title: { default: siteConfig.name, template: `%s | ${siteConfig.name}`, }, description: siteConfig.description, keywords: siteConfig.keywords, authors: [ { name: 'OtShellNick', url: siteConfig.url, }, ], creator: 'OtShellNick', openGraph: { type: 'website', locale: 'ru-RU', url: siteConfig.url, title: siteConfig.name, description: siteConfig.description, siteName: siteConfig.name, images: [ { url: siteConfig.ogImage, width: 1200, height: 630, alt: siteConfig.name, }, ], }, twitter: { card: 'summary_large_image', title: siteConfig.name, description: siteConfig.description, images: [siteConfig.ogImage], creator: '@CodeCollabSite', }, icons: { icon: '/favicon.ico', shortcut: '/favicon-16x16.png', apple: '/apple-touch-icon.png', }, manifest: `${siteConfig.url}/site.webmanifest`, }; type TLayoutProps = { children: React.ReactNode; session: Session | null; }; const RootLayout = ({ children, session }: TLayoutProps) => { return ( <html lang='ru'> <body className={inter.className}> <Providers session={session}>{children}</Providers> </body> </html> ); }; export default RootLayout;
package layout import scala.util.{Random => R} import scala.annotation.tailrec import layout.TypeAlias._ trait LayoutToolsEn extends LayoutTools with LeftKeysAndRightKeysEn with CharsEn with MakeChromosome with EvaluateFitness with KeyCharToCharKey with CrossoverChromosomes {} trait LayoutTools { val leftKeys: List[PhysicalKey] val rightKeys: List[PhysicalKey] val typingPatterns: Map[Chunk, Double] val chunkPatterns: Map[Chunk, Double] val nonChunkPatterns: Map[NonChunk, Double] val ngrams: Map[AssignableChar, Int] val evaluator: Evaluator def apply(): Layout def apply(chromosome: Chromosome): Layout def makeChromosome(): Chromosome def evaluateFitness(chromosome: Chromosome): Double def keyCharToCharKey(chromosome: Chromosome): Map[AssignableChar, PhysicalKey] def crossover(p1: Layout, p2: Layout): Layout def chromosomeToString(chromosome: Chromosome): String } trait LeftKeysAndRightKeysEn { val leftKeys: List[PhysicalKey] = List("q", "w", "e", "r", "t", "a", "s", "d", "f", "g", "z", "x", "c", "v", "b") val rightKeys: List[PhysicalKey] = List("y", "u", "i", "o", "p", "h", "j", "k", "l", ";", "n", "m", ",", ".", "/") val keys: List[PhysicalKey] = leftKeys ++ rightKeys } trait CharsEn { val keys: List[PhysicalKey] val chars: List[AssignableChar] = keys } trait MakeChromosome { val keys: List[PhysicalKey] val chars: List[AssignableChar] def makeChromosome(): Chromosome = { val ks = R.shuffle(keys) val cs = R.shuffle(chars) ks.zip(cs).toMap } } trait EvaluateFitness extends LayoutTools { def evaluateFitness(chromosome: Chromosome): Double = { val charToKey = keyCharToCharKey(chromosome) (for (ng <- ngrams.keys.toList) yield { val typingString = (for (c <- ng) yield { charToKey.get(c.toString).getOrElse("") }).mkString val frequency = ngrams(ng) evaluator(typingString) * frequency }).sum } } trait KeyCharToCharKey { val keys: List[PhysicalKey] def keyCharToCharKey(chromosome: Chromosome): Map[AssignableChar, PhysicalKey] = { val chars: List[AssignableChar] = keys.map(chromosome(_)) chars.zip(keys).toMap } } trait CrossoverChromosomes { def crossoverChromosomes( chr1: Chromosome, chr2: Chromosome, keys: List[PhysicalKey], chars: List[AssignableChar] ): Chromosome = { @tailrec def f(child: Chromosome, keys: List[PhysicalKey], chars: List[AssignableChar]): Chromosome = { val k = keys.head val candidateChars: List[AssignableChar] = { val parentGenes: List[AssignableChar] = List(chr1(k), chr2(k)).distinct.intersect(chars) R.shuffle(parentGenes) ++ chars.diff(parentGenes) } val newChild = child + (k -> candidateChars.head) (keys.tail, candidateChars.tail) match { case (Nil, _) => newChild case (_, Nil) => newChild case (restKeys, restChars) => f(newChild, restKeys, R.shuffle(restChars)) } } f(Map[PhysicalKey, AssignableChar](), R.shuffle(keys), R.shuffle(chars)) } }
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; import { expect } from "chai"; import { parseEther } from "ethers/lib/utils"; import { ethers } from "hardhat"; import { deployCrossChainWarriorsMock, deployZetaConnectorMock } from "../lib/cross-chain-warriors/CrossChainWarriors.helpers"; import { getAddress } from "../lib/shared/address.helpers"; import { deployZetaTokenConsumerUniV2, getZetaMock } from "../lib/shared/deploy.helpers"; import { CrossChainWarriorsMock, CrossChainWarriorsZetaConnectorMock, ZetaEthMock } from "../typechain-types"; import { ZetaTokenConsumerUniV2 } from "../typechain-types/@zetachain/protocol-contracts/contracts/ZetaTokenConsumerUniV2.strategy.sol"; import { addZetaEthLiquidityTest, getMintTokenId } from "./test.helpers"; describe("CrossChainWarriors tests", () => { let zetaConnectorMockContract: CrossChainWarriorsZetaConnectorMock; let zetaEthTokenMockContract: ZetaEthMock; let zetaTokenConsumerUniV2: ZetaTokenConsumerUniV2; let crossChainWarriorsContractChainA: CrossChainWarriorsMock; const chainAId = 1; let crossChainWarriorsContractChainB: CrossChainWarriorsMock; const chainBId = 2; let accounts: SignerWithAddress[]; let deployer: SignerWithAddress; let account1: SignerWithAddress; let deployerAddress: string; let account1Address: string; const encoder = new ethers.utils.AbiCoder(); beforeEach(async () => { accounts = await ethers.getSigners(); [deployer, account1] = accounts; deployerAddress = deployer.address; account1Address = account1.address; zetaEthTokenMockContract = await getZetaMock(); zetaConnectorMockContract = await deployZetaConnectorMock(); const uniswapRouterAddr = getAddress("uniswapV2Router02", { customNetworkName: "eth-mainnet", customZetaNetwork: "mainnet" }); await addZetaEthLiquidityTest(zetaEthTokenMockContract.address, parseEther("200000"), parseEther("100"), deployer); // @dev: guarantee that the account has no zeta balance but still can use the protocol :D const zetaBalance = await zetaEthTokenMockContract.balanceOf(deployer.address); await zetaEthTokenMockContract.transfer(accounts[5].address, zetaBalance); zetaTokenConsumerUniV2 = await deployZetaTokenConsumerUniV2(zetaEthTokenMockContract.address, uniswapRouterAddr); crossChainWarriorsContractChainA = await deployCrossChainWarriorsMock({ customUseEven: false, zetaConnectorMockAddress: zetaConnectorMockContract.address, zetaTokenConsumerAddress: zetaTokenConsumerUniV2.address, zetaTokenMockAddress: zetaEthTokenMockContract.address }); crossChainWarriorsContractChainB = await deployCrossChainWarriorsMock({ customUseEven: true, zetaConnectorMockAddress: zetaConnectorMockContract.address, zetaTokenConsumerAddress: zetaTokenConsumerUniV2.address, zetaTokenMockAddress: zetaEthTokenMockContract.address }); await crossChainWarriorsContractChainB.setInteractorByChainId( chainAId, ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]) ); await crossChainWarriorsContractChainA.setInteractorByChainId( chainBId, ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainB.address]) ); }); describe("constructor", () => { it("Should set the tokenIds counter to 1 when useEven is false", async () => { expect(await crossChainWarriorsContractChainA.tokenIds()).to.equal(1); }); it("Should set the tokenIds counter to 2 when useEven is true", async () => { expect(await crossChainWarriorsContractChainB.tokenIds()).to.equal(2); }); }); describe("mint", () => { it("Should increment tokenIds by two", async () => { expect(await crossChainWarriorsContractChainA.tokenIds()).to.equal(1); await (await crossChainWarriorsContractChainA.mint(account1Address)).wait(); expect(await crossChainWarriorsContractChainA.tokenIds()).to.equal(3); }); it("Should create a new NFT owned by the input address", async () => { const result = await (await crossChainWarriorsContractChainA.mint(account1Address)).wait(); const tokenId = getMintTokenId(result); expect(await crossChainWarriorsContractChainA.ownerOf(tokenId)).to.equal(account1Address); }); }); describe("mintId", () => { it("Should mint an NFT with the given input id owned by the input address", async () => { const id = 10; await (await crossChainWarriorsContractChainA.mintId(account1Address, id)).wait(); expect(await crossChainWarriorsContractChainA.ownerOf(id)).to.equal(account1Address); }); }); describe("crossChainTransfer", () => { it("Should revert if the caller is not the NFT owner nor approved", async () => { const id = 10; await (await crossChainWarriorsContractChainA.mintId(account1Address, id)).wait(); /** * The caller is the contract deployer and the NFT owner is account1 */ expect( crossChainWarriorsContractChainA.crossChainTransfer(chainBId, account1Address, id, { value: parseEther("1") }) ).to.be.revertedWith("Transfer caller is not owner nor approved"); }); it("Should burn the tokenId", async () => { const id = 10; await (await crossChainWarriorsContractChainA.mintId(deployerAddress, id)).wait(); expect(await crossChainWarriorsContractChainA.ownerOf(id)).to.equal(deployerAddress); await ( await crossChainWarriorsContractChainA.crossChainTransfer(chainBId, account1Address, id, { value: parseEther("1") }) ).wait(); expect(crossChainWarriorsContractChainA.ownerOf(id)).to.be.revertedWith( "ERC721: owner query for nonexistent token" ); }); it("Should mint tokenId in the destination chain", async () => { const id = 10; await (await crossChainWarriorsContractChainA.mintId(deployerAddress, id)).wait(); await ( await crossChainWarriorsContractChainA.crossChainTransfer(chainBId, account1Address, id, { value: parseEther("1") }) ).wait(); expect(await crossChainWarriorsContractChainB.ownerOf(id)).to.equal(account1Address); }); }); describe("onZetaMessage", () => { it("Should revert if the caller is not the Connector contract", async () => { await expect( crossChainWarriorsContractChainA.onZetaMessage({ destinationAddress: crossChainWarriorsContractChainB.address, message: encoder.encode(["address"], [deployerAddress]), sourceChainId: 1, zetaTxSenderAddress: ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]), zetaValue: 0 }) ) .to.be.revertedWith("InvalidCaller") .withArgs(deployer.address); }); it("Should revert if the cross-chain address doesn't match with the stored one", async () => { await expect( zetaConnectorMockContract.callOnZetaMessage( ethers.utils.solidityPack(["address"], [deployerAddress]), 1, crossChainWarriorsContractChainB.address, 0, encoder.encode(["address"], [zetaConnectorMockContract.address]) ) ).to.be.revertedWith("InvalidZetaMessageCall"); }); it("Should revert if the message type doesn't match with CROSS_CHAIN_TRANSFER_MESSAGE", async () => { const messageType = await crossChainWarriorsContractChainA.CROSS_CHAIN_TRANSFER_MESSAGE(); const invalidMessageType = messageType.replace("9", "8"); await expect( zetaConnectorMockContract.callOnZetaMessage( ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]), 1, crossChainWarriorsContractChainB.address, 0, encoder.encode( ["bytes32", "uint256 ", "address", "address"], [invalidMessageType, 1, deployerAddress, deployerAddress] ) ) ).to.be.revertedWith("InvalidMessageType"); }); it("Should revert if the token already exists", async () => { const messageType = await crossChainWarriorsContractChainA.CROSS_CHAIN_TRANSFER_MESSAGE(); await crossChainWarriorsContractChainB.mintId(deployerAddress, 1); await expect( zetaConnectorMockContract.callOnZetaMessage( ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]), 1, crossChainWarriorsContractChainB.address, 0, encoder.encode( ["bytes32", "uint256 ", "address", "address"], [messageType, 1, deployerAddress, deployerAddress] ) ) ).to.be.revertedWith("ERC721: token already minted"); }); describe("Given a valid input", () => { it("Should mint a new token in the destination chain", async () => { const messageType = await crossChainWarriorsContractChainA.CROSS_CHAIN_TRANSFER_MESSAGE(); await zetaConnectorMockContract.callOnZetaMessage( ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]), 1, crossChainWarriorsContractChainB.address, 0, encoder.encode( ["bytes32", "uint256 ", "address", "address"], [messageType, 1, deployerAddress, deployerAddress] ) ); expect(await crossChainWarriorsContractChainB.ownerOf(1)).to.equal(deployerAddress); }); it("Should mint a new token in the destination chain, owned by the provided 'to' address", async () => { const messageType = await crossChainWarriorsContractChainA.CROSS_CHAIN_TRANSFER_MESSAGE(); await zetaConnectorMockContract.callOnZetaMessage( ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainA.address]), 1, crossChainWarriorsContractChainB.address, 0, encoder.encode( ["bytes32", "uint256 ", "address", "address"], [messageType, 1, deployerAddress, account1Address] ) ); expect(await crossChainWarriorsContractChainB.ownerOf(1)).to.equal(account1Address); }); }); }); describe("onZetaRevert", () => { /** * @description note that given how this test was implemented, the NFT will exist in the two chains * that's not the real-world behavior but it's ok for this unit test */ it("Should give the NFT back to the sourceTxOriginAddress", async () => { const nftId = 1; await (await crossChainWarriorsContractChainA.mintId(deployerAddress, nftId)).wait(); await ( await crossChainWarriorsContractChainA.crossChainTransfer(chainBId, deployerAddress, nftId, { value: parseEther("1") }) ).wait(); // Make sure that the NFT was removed from the source chain await expect(crossChainWarriorsContractChainA.ownerOf(nftId)).to.be.revertedWith("ERC721: invalid token ID"); const messageType = await crossChainWarriorsContractChainA.CROSS_CHAIN_TRANSFER_MESSAGE(); await zetaConnectorMockContract.callOnZetaRevert( crossChainWarriorsContractChainA.address, 1337, chainBId, ethers.utils.solidityPack(["address"], [crossChainWarriorsContractChainB.address]), 0, 2500000, encoder.encode( ["bytes32", "uint256 ", "address", "address"], [messageType, nftId, deployerAddress, account1Address] ) ); expect(await crossChainWarriorsContractChainB.ownerOf(nftId)).to.equal(deployerAddress); }); }); });
<template> <v-dialog v-model="editMeetingDialog" max-height="550" max-width="320" persistent > <form @submit.prevent="checkCategoryChange" autocomplete="off"> <v-card dark> <v-card-text> <v-container> <v-row> <v-col cols="12" sm="6" md="4"> <v-text-field class="pt-1 mt-1" label="Meeting Name" v-model="addMeetingName" clearable ></v-text-field> </v-col> <v-col cols="12" sm="6" md="4"> <v-text-field class="pt-1 mt-1" clearable label="Meeting Link or ID" v-model="addMeetingID" ></v-text-field> </v-col> <v-col cols="12" sm="6" md="4"> <v-text-field clearable class="pt-1 mt-1" label="Meeting Passcode (optional)" v-model="addMeetingPasscode" ></v-text-field> </v-col> <v-col cols="12" sm="6" md="4"> <v-select v-model="categorySelect" class="pt-1 mt-1" :items="categories" item-text="name" label="Category" dense dark ></v-select> </v-col> <v-col v-if="inputError" cols="12" sm="6" md="4"> <v-alert dense color="primary" type="error"> Something's wrong! </v-alert> </v-col> </v-row> </v-container> </v-card-text> <v-card-actions> <v-spacer></v-spacer> <v-btn absolute left fab small dense color="primary" @click="confirmDeleteDialog = true" text > <v-icon class="mdi mdi-delete"></v-icon> </v-btn> <v-btn color="primary" text @click="closeModal"> Cancel </v-btn> <v-btn color="primary" type="submit" text> Enter </v-btn> </v-card-actions> </v-card> <ConfirmDelete :confirmDeleteDialog="confirmDeleteDialog" @deny-delete="confirmDeleteDialog = false" @confirm-delete="deleteMeeting" /> </form> </v-dialog> </template> <script> import ConfirmDelete from './ConfirmDelete'; export default { name: 'EditMeetingDialog', components: { ConfirmDelete, }, props: { editMeetingDialog: Boolean, catIndex: Number, meetingIndex: Number, categories: Array, }, data() { return { addMeetingName: null, addMeetingID: null, addMeetingPasscode: null, categorySelect: null, inputError: false, confirmDeleteDialog: false, originalCatIndex: null, }; }, mounted() { this.setDefault(); }, methods: { closeModal: function() { this.inputError = false; this.$emit('close-edit-meeting-modal'); }, isValidMeetingID(str) { let isValid = true; if ( isNaN(str) || !(str.length == 11 || str.length == 10 || str.length == 9) ) { if (!str.startsWith('http')) { isValid = false; this.inputError = true; } } else { this.addMeetingID = 'https://zoom.us/j/' + this.addMeetingID; } return isValid; }, isMeetingNameValid(str) { let isValid = true; if (str.length == 0) { isValid = false; this.inputError = true; } return isValid; }, isValidCategorySelect() { let isValid = true; if (this.categorySelect == null) { isValid = false; this.inputError = true; } return isValid; }, checkCategoryChange() { if (this.categorySelect == this.categories[this.originalCatIndex].name) { this.submitMeeting(); } else { this.submitMeetingNewCat(); this.deleteMeeting(); } }, submitMeeting() { let indexName = this.categorySelect; if ( this.isValidCategorySelect() && this.isValidMeetingID(this.addMeetingID) && this.isMeetingNameValid(this.addMeetingName) ) { const editedMeeting = { zoomName: this.addMeetingName, zoomLink: this.addMeetingID, zoomPass: this.addMeetingPasscode, }; this.$emit('edit-meeting', { catIndex: this.catIndex, meetingIndex: this.meetingIndex, editedMeeting: editedMeeting, }); this.inputError = false; this.$emit('close-edit-meeting-modal'); } }, deleteMeeting() { this.confirmDeleteDialog = false; this.$emit('delete-meeting', { catIndex: this.catIndex, meetingIndex: this.meetingIndex, }); this.$emit('close-edit-meeting-modal'); }, submitMeetingNewCat() { let indexName = this.categorySelect; if ( this.isValidCategorySelect() && this.isValidMeetingID(this.addMeetingID) && this.isMeetingNameValid(this.addMeetingName) ) { const newMeeting = { zoomName: this.addMeetingName, zoomLink: this.addMeetingID, zoomPass: this.addMeetingPasscode, }; this.$emit('add-meeting', { indexName: indexName, meeting: newMeeting, }); this.inputError = false; this.$emit('close-edit-meeting-modal'); } }, setDefault() { this.addMeetingName = this.categories[this.catIndex].meetings[ this.meetingIndex ].zoomName; this.addMeetingID = this.categories[this.catIndex].meetings[ this.meetingIndex ].zoomLink; this.addMeetingPasscode = this.categories[this.catIndex].meetings[ this.meetingIndex ].zoomPass; this.categorySelect = this.categories[this.catIndex].name; this.originalCatIndex = this.catIndex; }, }, watch: { editMeetingDialog() { if (this.editMeetingDialog == true) { this.setDefault(); } }, }, }; </script>
openEuler 22.03-V2 for RISC-V 系统镜像使用说明 ### 0.免责声明 须知:RISC-V 体系结构的 openEuler 22.03-V2 镜像只适用于体验与技术交流用途,不对因系统问题导致的诸如数据丢失等任何后果承担责任。 Note: openEuler 22.03-V2 for RISC-V is only for preview or development usage. Thus, openEuler RISC-V Community does not take responsibility for any consequences such as data loss caused by system problems. ### 1.背景说明 openEuler 22.03 for RISC-V 是openEuler 22.03-LTS 在RISC-V 架构上的适配,目前RISC-V作为创新支持只用于体验和技术交流,而不用于商业用途。目前提供了qemu、Unmatched、visionfive、D1、 Licheerv多种运行环境下的镜像文件。 ### 2.使用说明 openEuler 22.03-V2 for RISC-V 目前提供了qemu、Unmatched、visionfive、D1多种运行环境下的镜像文件,您可以按需选择并按照下面的说明文档使用体验: - [QEMU环境安装openEuler for riscv64](./Installation_Book/QEMU/README.md) - [Unmatched开发板安装openEuler](./Installation_Book/Unmatched/README.md) - [VisionFive开发板安装openEuler](./Installation_Book/Visionfive/README.md) - [D1开发板安装openEuler](./Installation_Book/D1_and_Licheerv/README.md) - [Licheerv开发板安装openEuler](./Installation_Book/D1_and_Licheerv/README.md) ### 3 用户手册 #### 3.1 系统管理 - [基础配置](./User_Book/系统管理/基础配置.md) - [查看系统信息](./User_Book/系统管理/查看系统信息.md) - [管理用户和用户组](./User_Book/系统管理/管理用户和用户组.md) - [配置网络](./User_Book/系统管理/配置网络.md) - [使用DNF管理软件包](./User_Book/系统管理/使用DNF管理软件包.md) - [使用LVM管理硬盘](./User_Book/系统管理/使用LVM管理硬盘.md) - [管理进程](./User_Book/系统管理/管理进程.md) - [管理服务](./User_Book/系统管理/管理服务.md) - [搭建FTP服务器](./User_Book/系统管理/搭建FTP服务器.md) - [搭建repo服务器](./User_Book/系统管理/搭建repo服务器.md) - [搭建web服务器](./User_Book/系统管理/搭建web服务器.md) - [搭建数据库服务器](./User_Book/系统管理/搭建数据库服务器.md) ### 3.2 应用软件 - [XFCE使用手册](./User_Book/XFCE使用手册) - [DDE使用手册](./User_Book/DDE使用手册) - [Chromium使用手册](./User_Book/Chromium使用手册) - [Firefox使用手册](./User_Book/Firefox使用手册) - [Libreoffice使用手册](./User_Book/Libreoffice使用手册) - [Libreoffice Base使用手册](./User_Book/Libreoffice使用手册/Base_userguide.md) - [Libreoffice Writer使用手册](./User_Book/Libreoffice使用手册/Writer_userguide.md) - [Libreoffice Calc使用手册](./User_Book/Libreoffice使用手册/Calc_userguide.md) - [Libreoffice Draw使用手册](./User_Book/Libreoffice使用手册/Draw_userguide.md) - [Libreoffice Impress使用手册](./User_Book/Libreoffice使用手册/Impress_userguide.md) - [Libreoffice Math使用手册](./User_Book/Libreoffice使用手册/Math_userguide.md) - [GIMP使用手册](./User_Book/GIMP使用手册) - [Thunderbird使用手册](./User_Book/Thunderbird使用手册) - [MySQL使用手册](./User_Book/MySQL使用手册) ### 3.写在最后 openEuler for RISC-V作为新架构支持,目前还有很多不足,您在使用过程中遇到问题可以在https://gitee.com/openeuler/RISC-V 中通过issue反馈,问题有可能在后续的版本中进行修复完善。同时也随时欢迎有志者加入openEuler RISC-V SIG 一起学习交流。
import React, { useState, useEffect } from "react"; import jwt from "jsonwebtoken"; import { Switch, BrowserRouter as Router, Route } from "react-router-dom"; import { useWeb3React } from '@web3-react/core'; import { Toaster } from 'react-hot-toast'; import "./App.css"; import "antd/dist/antd.css"; import { connectors, connectorLocalStorageKey } from './utils/connectors'; import { useEagerConnect } from "./hooks/useEagerConnect"; import { useInactiveListener } from "./hooks/useInactiveListener"; import { useAxios } from "./hooks/useAxios"; import { getErrorMessage } from "./utils/ethereum"; import { getUser, loginUser, logout, useAuthDispatch, useAuthState } from "./context/authContext"; import ConnectDialog from './components/ConnectDialog'; import NetworkErrorDialog from './components/NetworkErrorDialog'; import Collection from "./pages/collection/collection"; import EditCollection from "./pages/edit-collection"; import CreateMultiple from "./pages/create/create-multiple"; import CreateSingle from "./pages/create/create-single"; import ImportCollection from "./pages/import-collection/import-collection"; import Detail from "./pages/detail/detail"; import EditProfile from "./pages/edit-profile"; import ExploreCollections from "./pages/explore-collections/explore-collections"; import ExploreItems from "./pages/explore-items/explore-items"; import Home from "./pages/home/home"; import Profile from "./pages/profile"; import Search from "./pages/search/search"; import MysteryBoxes from "./pages/mysteryboxes"; import MysteryBoxDetail from "./pages/mysterybox-detail"; import NftStaking from "./pages/nft-staking"; function App() { const [connectModalOpen, setConnectModalOpen] = useState(null); const [errorModalOpen, setErrorModalOpen] = useState(null); const [networkError, setNetworkError] = useState(null); useAxios(); const { account, library, activate, active, connector } = useWeb3React(); const connectAccount = () => { setConnectModalOpen(true); } const connectToProvider = (connector) => { activate(connector); } // handle logic to recognize the connector currently being activated const [activatingConnector, setActivatingConnector] = React.useState(); useEffect(() => { if (activatingConnector && activatingConnector === connector) { setActivatingConnector(undefined); } }, [activatingConnector, connector]) // mount only once or face issues :P const [triedEager, triedEagerError] = useEagerConnect(); const { activateError } = useInactiveListener(!triedEager || !!activatingConnector); // handling connection error if ((triedEagerError || activateError) && errorModalOpen === null) { const errorMsg = getErrorMessage(triedEagerError || activateError); setNetworkError(errorMsg); setErrorModalOpen(true); window.localStorage.setItem(connectorLocalStorageKey, ""); } const dispatch = useAuthDispatch(); const { user, token } = useAuthState(); const login = async () => { if (!account || !library) { console.log('not connected to wallet'); return; } if (!user || (user && user.address.toLowerCase() !== account.toLowerCase())) { console.log('fetching user'); await getUser(dispatch, account); } if (token) { jwt.verify(token, '!@#456QWErty', (err, payload) => { if (err) { logout(dispatch); } let address = payload.data; if (address.toLowerCase() !== account.toLowerCase()) { loginUser(dispatch, account, user?.nonce, library.getSigner()); } }) } else { loginUser(dispatch, account, user?.nonce, library.getSigner()); } console.log("login 2") } useEffect(() => { if (active && account) { getUser(dispatch, account); } }, [active, account]) const closeErrorModal = () => { // window.localStorage.setItem(connectorLocalStorageKey, connectors[0].key); // window.location.reload(); setErrorModalOpen(false); } return ( <div className="App"> <Toaster position="top-center" toastOptions={{ success: { duration: 3000 }, error: { duration: 3000 }, }} /> <Router> <Switch> <Route path="/" exact render={(props) => (<Home {...props} connectAccount={connectAccount} />)} /> <Route path="/home" exact render={(props) => (<Home {...props} connectAccount={connectAccount} />)} /> <Route path="/search/:searchTxt" exact render={(props) => (<Search {...props} connectAccount={connectAccount} />)} /> <Route path="/detail/:chain_id/:collection/:tokenID" exact render={(props) => (<Detail {...props} user={user} login={login} connectAccount={connectAccount} />)} /> <Route path="/explore-collections" exact render={(props) => (<ExploreCollections {...props} connectAccount={connectAccount} />)} /> <Route path="/explore-items" exact render={(props) => (<ExploreItems {...props} connectAccount={connectAccount} />)} /> <Route path="/collection/:chain_id/:collection" exact render={(props) => (<Collection {...props} connectAccount={connectAccount} />)} /> <Route path="/profile/:id" exact render={(props) => (<Profile {...props} user={user} login={login} connectAccount={connectAccount} />)} /> <Route path="/edit_profile" exact render={(props) => (<EditProfile {...props} user={user} login={login} connectAccount={connectAccount} />)} /> <Route path="/edit_collection/:chain_id/:collection" exact render={(props) => (<EditCollection {...props} user={user} login={login} connectAccount={connectAccount} />)} /> <Route path="/create-single" exact render={(props) => (<CreateSingle {...props} connectAccount={connectAccount} />)} /> <Route path="/create-multiple" exact render={(props) => (<CreateMultiple {...props} connectAccount={connectAccount} />)} /> <Route path="/import" exact render={(props) => (<ImportCollection {...props} connectAccount={connectAccount} />)} /> <Route path="/mysteryboxes" exact render={(props) => (<MysteryBoxes {...props} connectAccount={connectAccount} />)} /> <Route path="/mysterybox/:chain_id/:address" exact render={(props) => (<MysteryBoxDetail {...props} connectAccount={connectAccount} />)} /> <Route path="/nft-staking" exact render={(props) => (<NftStaking {...props} connectAccount={connectAccount} />)} /> </Switch> </Router> {/* <NetworkErrorDialog open={!!errorModalOpen && !active} onClose={(event, reason) => { if (reason === "backdropClick") { return false; } if (reason === "escapeKeyDown") { return false; } setErrorModalOpen(false) }} handleClose={closeErrorModal} message={networkError} /> */} <ConnectDialog open={!!connectModalOpen} handleClose={(event, reason) => { if (reason === "backdropClick") { return false; } if (reason === "escapeKeyDown") { return false; } setConnectModalOpen(false) }} connectors={connectors} connectToProvider={connectToProvider} connectorLocalStorageKey={connectorLocalStorageKey} /> </div> ); } export default App;
import React from "react"; import { useState } from "react"; import { useParams, Link } from "react-router-dom"; import InfiniteScroll from "react-infinite-scroll-component"; import axios from "axios"; import "./moreGenrePage.css"; import { Watch } from "react-loader-spinner"; import MovieCard from "../components/MovieCard"; import logo from "../7b7a104adea125644e0e8d62a7d53d0d.png"; const MoreGenrerPage = () => { const [moviesGenre, setMoviesGenre] = useState([]); const [page, setPage] = useState(2); let params = useParams(); const getMoviesGenre = async () => { const result = await axios.get( `https://api.themoviedb.org/3/discover/movie?api_key=${process.env.REACT_APP_API_KEY}&with_genres=${params.id}&page=${page}` ); return result.data.results; }; React.useEffect(() => { const getMoviesGenre = async () => { const result = await axios.get( `https://api.themoviedb.org/3/discover/movie?api_key=${process.env.REACT_APP_API_KEY}&with_genres=${params.id}&page=1` ); setMoviesGenre(result.data.results); }; getMoviesGenre(); }, []); const fetchdata = async () => { const getMoreMovies = await getMoviesGenre(); setMoviesGenre([...moviesGenre, ...getMoreMovies]); setPage(page + 1); }; return ( <div className="main"> <div className="title"> <Link to="/"> <img src={logo} alt="" /> </Link> </div> <InfiniteScroll className="moreGenre" dataLength={moviesGenre.length} next={fetchdata} hasMore={true} loader={ <div className="loading"> <Watch height="80" width="80" radius="48" color="rgb(255, 115, 0)" ariaLabel="watch-loading" wrapperStyle={{}} wrapperClassName="" visible={true} /> </div> } endMessage={ <p style={{ textAlign: "center" }}> <b>Yay! You have seen it all</b> </p> } > <div className="more-genre container"> <div className="row"> {moviesGenre.map((movie) => { return ( <div className="col-md-3"> <MovieCard movie={movie} /> </div> ); })} </div> </div> </InfiniteScroll> </div> ); }; export default MoreGenrerPage;
// // AuthTextField.swift // Whatsapp_Clone // // Created by Kareddy Hemanth Reddy on 27/04/24. // import SwiftUI struct AuthTextField: View { @Binding var text:String let type:InputType var body: some View { HStack{ Image(systemName:type.imageName) .fontWeight(.semibold) .frame(width: 30) switch type { case .password: SecureField(type.placeholder,text: $text) default: TextField(type.placeholder, text: $text) .keyboardType(type.keybaordType) } } .foregroundStyle(.white) .padding() .background(Color.white.opacity(0.3)) .clipShape(RoundedRectangle(cornerRadius: 10,style: .continuous)) .padding(.horizontal,32) } } extension AuthTextField{ enum InputType{ case email case password case custom(_ placeholder:String,_ iconName:String) var placeholder:String{ switch self { case .email: return "Email" case .password: return "Password" case .custom(let placeholder, _): return placeholder } } var imageName:String{ switch self { case .email: return "envelope" case .password: return "lock" case .custom(_, let iconName): return iconName } } var keybaordType:UIKeyboardType{ switch self { case .email: return .emailAddress default: return .default } } } } #Preview { AuthTextField(text: .constant(""), type: .email) }
import supertest from 'supertest' import web from '../../src/applications/web.js' import { createTestUser, removeTestUser } from '../utils/user.util.js' const uniqueEmail = 'test33@example.com' describe('GET /register - endpoint', () => { it('should be able to show register page', async () => { const result = await supertest(web).get('/register') expect(result.status).toBe(200) expect(result.text).toContain('Register') expect(result.text).toContain('Please register') }) }) describe('POST /register - endpoint', () => { afterEach(async () => { await removeTestUser(uniqueEmail) }) it('should be able to register a new user with correct identities', async () => { const result = await supertest(web).post('/register').send({ name: 'Test 33', email: uniqueEmail, password: '123456', password_confirmation: '123456' }) expect(result.status).toBe(302) expect(result.header.location).toBe('/login') }) it('should fail to register a new user with incorrect identities', async () => { const result = await supertest(web) .post('/register') .send({ name: 'Test 33', email: uniqueEmail, password: '123456', password_confirmation: 'SALAH' }) .set('Referer', '/register') expect(result.status).toBe(302) expect(result.header.location).toBe('/register') }) }) describe('GET /login - endpoint', () => { it('should be able to show login page', async () => { const result = await supertest(web).get('/login') expect(result.status).toBe(200) expect(result.text).toContain('Login') expect(result.text).toContain('Please sign in') }) }) describe('POST /login - endpoint', () => { beforeEach(async () => { await createTestUser(uniqueEmail) }) afterEach(async () => { await removeTestUser(uniqueEmail) }) it('should be able to login with correct identities', async () => { const result = await supertest(web).post('/login').send({ email: uniqueEmail, password: '123456' }) expect(result.status).toBe(302) expect(result.header.location).toBe('/dashboard') }) it('should fail to login with incorrect identities', async () => { const result = await supertest(web) .post('/login') .send({ email: uniqueEmail, password: 'SALAH' }) .set('Referer', '/login') expect(result.status).toBe(302) expect(result.header.location).toBe('/login') }) })
--- date: 2023-10-12 tags: - theorem --- $E(x, \dot x) = \frac{1}{2}m \| \dot x \|^2 + V(x)$ is a [[📘 Constant of Motion]] $\Leftrightarrow - \nabla V = F$ >[!info]- > 1. $E(x, \dot x) = \frac{1}{2}m \| \dot x \|^2 + V(x)$ is the [[Energy function]] aka the [[📘 Total Energy]] > 2. $V(x) : \mathbb{R}^n \rightarrow \mathbb{R}^n$ is the [[📘 Potential energy]] > 3. $F(x(t)) = m\ddot x$ is the velocity-independent [[force]] >[!success] > We differentiate the potential energy to get > $$ \frac{d}{dt} \left ( \frac{1}{2}m \| \dot x \|^2 + V(x) \right ) = m \sum_{j=1}^{n}\dot x_j\ddot x_j + \sum_{j=1}^{n}\frac{\partial V}{\partial x_j}\dot x_j = \dot x \cdot \| m \ddot x + \nabla V \| = \dot x \cdot \| F(x) + \nabla V \| $$ > The derivative is zero iff $0=\dot x(t) . | F(x) + \nabla V | \Rightarrow F(x) + \nabla V = 0$
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Groza_Ionut_Barbershop.Data; using Groza_Ionut_Barbershop.Models; namespace Groza_Ionut_Barbershop.Pages.Appointments { public class EditModel : PageModel { private readonly Groza_Ionut_Barbershop.Data.Groza_Ionut_BarbershopContext _context; public EditModel(Groza_Ionut_Barbershop.Data.Groza_Ionut_BarbershopContext context) { _context = context; } [BindProperty] public Appointment Appointment { get; set; } = default!; public async Task<IActionResult> OnGetAsync(int? id) { if (id == null || _context.Appointment == null) { return NotFound(); } var appointment = await _context.Appointment.FirstOrDefaultAsync(m => m.AppointmentId == id); if (appointment == null) { return NotFound(); } Appointment = appointment; ViewData["BarberId"] = new SelectList(_context.Barber, "BarberId", "FirstName"); ViewData["CustomerId"] = new SelectList(_context.Customer, "CustomerId", "FirstName"); ViewData["ServiceId"] = new SelectList(_context.Service, "ServiceId", "ServiceName"); return Page(); } // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see https://aka.ms/RazorPagesCRUD. public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.Attach(Appointment).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AppointmentExists(Appointment.AppointmentId)) { return NotFound(); } else { throw; } } return RedirectToPage("./Index"); } private bool AppointmentExists(int id) { return (_context.Appointment?.Any(e => e.AppointmentId == id)).GetValueOrDefault(); } } }
package com.example.hikewise.model import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.hikewise.remote.UserRepository import com.example.hikewise.response.GetTransactionEmailResponse import com.example.hikewise.response.GetTransactionEmailResponseItem import com.example.hikewise.response.ListDataItem import kotlinx.coroutines.launch class GetTransactionByEmailViewModel (private val repository: UserRepository) : ViewModel() { private val _getTransactionByEmail = MutableLiveData<List<GetTransactionEmailResponseItem>>() val getTransactionByEmail : LiveData<List<GetTransactionEmailResponseItem>> = _getTransactionByEmail fun getTransactionByEmail(userEmail: String){ viewModelScope.launch { try { val response = repository.getTransactionByEmail(userEmail) _getTransactionByEmail.value = response } catch (e: Exception){ Log.d("ViewModel", e.message.toString()) } } } }
function calJV = solver(device, dataJV, retrievedParameters) % ------------------------------------------------------------------------- % Solving JV curved with the retrieved parameters from MDB model fitting. % % Arguments: % device: a Device object containing relevant params % dataJV: a table containing the voltage and current data % retrievedParameters: an array containing [Rs, Rsh, Ubulk, Uif, nbulk, % nif], i.e., the parameters in the MDB model. % Return value: % calJV: a table containing containing the calculated JV curves % % @ Author: Minshen Lin % @ Institution: Zhejiang University % % @ LICENSE % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published % by the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % ------------------------------------------------------------------------- % Constants kB = device.kB; % Boltzmann constant [J/K] T = device.T; % temperature [K] q = device.q; % elementary charge [C] % Params L = device.L; ni = device.ni; Rs = retrievedParameters(1); Rsh = retrievedParameters(2); ybulk = retrievedParameters(3); Uif = retrievedParameters(4); nbulk = retrievedParameters(5); nif = retrievedParameters(6); % J and V data dataV = dataJV{:, 'dataV'}; % [V] dataJ = dataJV{:, 'dataJ'}; % [A/cm2] Jph = dataJ(1); % Initialize variables syms J; f(J) = 0 * J; calJ = zeros(size(dataV, 1), 1); % The function of J to be solved is: f(J) = Jph - Jsh - Jbulk - Jif - J = 0 for i = 1 : size(dataV, 1) f(J) = Jph - J - (dataV(i) + J * Rs) / Rsh ... Jph - J - Jsh - q * ybulk * L * ni * (exp(q * (dataV(i) + J * Rs) / (nbulk * kB * T)) - 1) ... - Jbulk - q * Uif * (exp(q * (dataV(i) + J * Rs) / (nif * kB * T)) - 1); % - Jif S = vpasolve(f); calJ(i) = S; end % Calculate rec. and shunt current densities calJbulk = q * L * ni * ybulk * (exp(q * (dataV + calJ * Rs)/(nbulk * kB * T)) - 1); calJif = q * Uif * (exp(q * (dataV + calJ * Rs) / (nif * kB * T)) - 1); calJsh = (calJ * Rs + dataV) / Rsh; calJV = table(dataV, calJ, calJbulk, calJif, calJsh); end
import React from "react"; import PropTypes from "prop-types"; const shapes = { square: "rounded-[0px]", round: "rounded-[10px]", }; const variants = { fill: { white_A700: "bg-white-A700 text-gray-600_02", gray_50_02: "bg-gray-50_02 text-gray-700", }, }; const sizes = { sm: "h-[48px] pl-4 pr-[35px] text-sm", xs: "h-[25px] pr-[30px] text-lg", md: "h-[60px] px-4 text-lg", }; const Input = React.forwardRef( ( { className = "", name = "", placeholder = "", type = "text", children, label = "", prefix, suffix, onChange, shape = "", variant = "fill", size = "md", color = "white_A700", ...restProps }, ref, ) => { const handleChange = (e) => { if (onChange) onChange(e?.target?.value); }; return ( <> <div className={`${className} flex items-center justify-center ${shapes[shape] || ""} ${variants[variant]?.[color] || variants[variant] || ""} ${sizes[size] || ""}`} > {!!label && label} {!!prefix && prefix} <input ref={ref} type={type} name={name} onChange={handleChange} placeholder={placeholder} {...restProps} /> {!!suffix && suffix} </div> </> ); }, ); Input.propTypes = { className: PropTypes.string, name: PropTypes.string, placeholder: PropTypes.string, type: PropTypes.string, label: PropTypes.string, prefix: PropTypes.node, suffix: PropTypes.node, shape: PropTypes.oneOf(["square", "round"]), size: PropTypes.oneOf(["sm", "xs", "md"]), variant: PropTypes.oneOf(["fill"]), color: PropTypes.oneOf(["white_A700", "gray_50_02"]), }; export { Input };
import Link from "next/link"; import {RadioTower, Settings} from "lucide-react"; import {Tooltip, TooltipContent, TooltipTrigger} from "@/components/ui/tooltip"; import Header from "@/components/menu/header"; import RoutesLinks from "@/components/menu/routes-links"; export default function layout({children}: {children: React.ReactNode}) { return ( <div className="flex min-h-screen w-full flex-col bg-muted/40"> <aside className="fixed inset-y-0 left-0 z-10 hidden w-14 flex-col border-r bg-background sm:flex"> <nav className="flex flex-col items-center gap-4 px-2 sm:py-5"> <Link className="group flex h-9 w-9 shrink-0 items-center justify-center gap-2 rounded-full bg-primary text-lg font-semibold text-primary-foreground md:h-8 md:w-8 md:text-base" href="#" > <RadioTower className="h-4 w-4 transition-all group-hover:scale-110" /> <span className="sr-only">Acme Inc</span> </Link> <RoutesLinks /> </nav> <nav className="mt-auto flex flex-col items-center gap-4 px-2 sm:py-5"> <Tooltip> <TooltipTrigger asChild> <Link className="flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:text-foreground md:h-8 md:w-8" href="#" > <Settings className="h-5 w-5" /> <span className="sr-only">Settings</span> </Link> </TooltipTrigger> <TooltipContent side="right">Settings</TooltipContent> </Tooltip> </nav> </aside> <div className="flex flex-col sm:gap-4 sm:py-4 sm:pl-14"> <Header /> <div className="p-4 sm:px-6 sm:py-0">{children}</div> </div> </div> ); }
import * as O from "fp-ts/Option"; import * as E from "fp-ts/Either"; import validators from "../../utils/validators"; import { npgSessionFieldsResponse } from "../testUtils"; import "jest-location-mock"; import { ErrorsType } from "../errors/errorsModel"; const { evaluateHTTPFamilyStatusCode, cardNameValidation, digitValidation, expirationDateChangeValidation, validateSessionWalletCardFormFields, statusCodeValidator, badStatusHandler } = validators; describe("evaluateHTTPFamilyStatusCode function", () => { it("Should evaluate the correct HTTP family code", () => { expect(evaluateHTTPFamilyStatusCode(100)).toEqual( O.some({ actualCode: 100, familyCode: "1xx" }) ); expect(evaluateHTTPFamilyStatusCode(101)).toEqual( O.some({ actualCode: 101, familyCode: "1xx" }) ); expect(evaluateHTTPFamilyStatusCode(199)).toEqual( O.some({ actualCode: 199, familyCode: "1xx" }) ); expect(evaluateHTTPFamilyStatusCode(200)).toEqual( O.some({ actualCode: 200, familyCode: "2xx" }) ); expect(evaluateHTTPFamilyStatusCode(201)).toEqual( O.some({ actualCode: 201, familyCode: "2xx" }) ); expect(evaluateHTTPFamilyStatusCode(299)).toEqual( O.some({ actualCode: 299, familyCode: "2xx" }) ); expect(evaluateHTTPFamilyStatusCode(400)).toEqual( O.some({ actualCode: 400, familyCode: "4xx" }) ); expect(evaluateHTTPFamilyStatusCode(401)).toEqual( O.some({ actualCode: 401, familyCode: "4xx" }) ); expect(evaluateHTTPFamilyStatusCode(404)).toEqual( O.some({ actualCode: 404, familyCode: "4xx" }) ); expect(evaluateHTTPFamilyStatusCode(499)).toEqual( O.some({ actualCode: 499, familyCode: "4xx" }) ); expect(evaluateHTTPFamilyStatusCode(500)).toEqual( O.some({ actualCode: 500, familyCode: "5xx" }) ); expect(evaluateHTTPFamilyStatusCode(501)).toEqual( O.some({ actualCode: 501, familyCode: "5xx" }) ); expect(evaluateHTTPFamilyStatusCode(599)).toEqual( O.some({ actualCode: 599, familyCode: "5xx" }) ); }); it("Should return an instance of O.none with a wrong input", () => { expect(evaluateHTTPFamilyStatusCode(-1)).toEqual(O.none); expect(evaluateHTTPFamilyStatusCode(-0)).toEqual(O.none); expect(evaluateHTTPFamilyStatusCode(0)).toEqual(O.none); expect(evaluateHTTPFamilyStatusCode(99)).toEqual(O.none); expect(evaluateHTTPFamilyStatusCode(600)).toEqual(O.none); }); }); describe("cardNameValidation function", () => { it("Should test correctly a right input", () => { expect(cardNameValidation("Name Test")).toEqual(true); }); it("Should test correctly a wrong input", () => { expect(cardNameValidation("")).toEqual(false); expect(cardNameValidation(" ")).toEqual(false); expect(cardNameValidation("111")).toEqual(false); expect(cardNameValidation("a")).toEqual(false); }); }); describe("digitValidation function", () => { it("Should test correctly a right input", () => { expect(digitValidation("0")).toEqual(true); expect(digitValidation("1")).toEqual(true); expect(digitValidation("01")).toEqual(true); expect(digitValidation("0010")).toEqual(true); expect(digitValidation("999999999")).toEqual(true); }); it("Should test correctly a wrong input", () => { expect(digitValidation("-0")).toEqual(false); expect(digitValidation("-1")).toEqual(false); expect(digitValidation("1 1")).toEqual(false); expect(digitValidation("")).toEqual(false); expect(digitValidation(" ")).toEqual(false); expect(digitValidation("a")).toEqual(false); }); }); describe("expirationDateChangeValidation function", () => { it("Should test correctly a right input", () => { expect(expirationDateChangeValidation("")).toEqual(true); expect(expirationDateChangeValidation("11/23")).toEqual(true); }); it("Should test correctly a wrong input", () => { expect(expirationDateChangeValidation("a")).toEqual(false); expect(expirationDateChangeValidation("0/")).toEqual(false); expect(expirationDateChangeValidation("1.1")).toEqual(false); expect(expirationDateChangeValidation("11.23")).toEqual(false); expect(expirationDateChangeValidation("11-23")).toEqual(false); expect(expirationDateChangeValidation("11 23")).toEqual(false); expect(expirationDateChangeValidation("1 2023")).toEqual(false); expect(expirationDateChangeValidation("abc")).toEqual(false); }); }); describe("validateSessionWalletCardFormFields function", () => { it("Should validate correctly a wrong input", () => { expect(validateSessionWalletCardFormFields([])).toEqual(O.none); expect(validateSessionWalletCardFormFields([{}, {}, {}, {}])).toEqual( O.none ); expect( validateSessionWalletCardFormFields([ npgSessionFieldsResponse.sessionData.cardFormFields[1], npgSessionFieldsResponse.sessionData.cardFormFields[2], npgSessionFieldsResponse.sessionData.cardFormFields[3] ]) ).toEqual(O.none); expect( validateSessionWalletCardFormFields([ npgSessionFieldsResponse.sessionData.cardFormFields[1], npgSessionFieldsResponse.sessionData.cardFormFields[2], npgSessionFieldsResponse.sessionData.cardFormFields[3], npgSessionFieldsResponse.sessionData.cardFormFields[3] ]) ).toEqual(O.none); }); it("Should validate correctly a good input", () => { expect( validateSessionWalletCardFormFields( npgSessionFieldsResponse.sessionData.cardFormFields ) ).toEqual(O.some(npgSessionFieldsResponse.sessionData.cardFormFields)); }); }); describe("statusCodeValidator", () => { it("Returns a left familyCode on status code different from 200", () => { const result = statusCodeValidator(500); expect(result).toEqual(E.left({ familyCode: "5xx", actualCode: 500 })); }); it("Returns a left 5xx familyCode on invalid status code", () => { const result = statusCodeValidator(700); expect(result).toEqual(E.left({ familyCode: "5xx", actualCode: 700 })); }); it("Returns a right 2xx familyCode on 200 status code", () => { const result = statusCodeValidator(200); expect(result).toEqual(E.right({ familyCode: "2xx", actualCode: 200 })); }); }); describe("badStatusHandler", () => { it("Returns a generic error error on a 4xx status code", () => { const result = badStatusHandler({ familyCode: "4xx", actualCode: 400 }); expect(result).toEqual(ErrorsType.GENERIC_ERROR); }); it("Redirect with outcome 14 on a 401 status code", () => { const result = badStatusHandler({ familyCode: "4xx", actualCode: 401 }); expect(result).toEqual(ErrorsType.GENERIC_ERROR); expect(global.location.href).toContain("outcome=14"); }); it("Redirect with outcome 1 on a 4xx status code", () => { badStatusHandler({ familyCode: "4xx", actualCode: 400 }); expect(global.location.href).toContain("outcome=1"); badStatusHandler({ familyCode: "4xx", actualCode: 405 }); expect(global.location.href).toContain("outcome=1"); badStatusHandler({ familyCode: "4xx", actualCode: 404 }); expect(global.location.href).toContain("outcome=1"); badStatusHandler({ familyCode: "4xx", actualCode: 401 }); expect(global.location.href).toContain("outcome=14"); }); it("Returns GENERIC_ERROR on any other status code", () => { const result = badStatusHandler({ familyCode: "5xx", actualCode: 500 }); expect(result).toEqual(ErrorsType.GENERIC_ERROR); }); });
<template> <div class="app-container"> <!-- 头部筛选 --> <el-card shadow="never" class="card"> <el-form ref="queryForm" :inline="true" :model="queryParams"> <el-form-item prop="productOrderId"> <el-input v-model="queryParams.productOrderId" clearable size="small" placeholder="制令单号" style="width: 180px;" /> </el-form-item> <el-form-item prop="compIdSeq"> <el-input v-model="queryParams.compIdSeq" clearable size="small" placeholder="条形编码" style="width: 180px;" /> </el-form-item> <el-form-item> <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button> <el-button v-hasPermi="['hs:workpiece:bind']" type="primary" plain icon="el-icon-takeaway-box" :disabled="stoveInfo.list.length === 0" size="small" @click="handleBind">绑定炉号</el-button> <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button> </el-form-item> </el-form> </el-card> <!-- 表格信息 --> <dz-table ref="table" v-loading="loading" :column="column" :data="list" :total="total" pagination :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="getList" @sortChange="sortChange" @handleSelectionChange="handleSelectionChange" /> <!-- 编辑工件 --> <el-dialog v-dialogDrag :close-on-click-modal="false" :title="'修改工件信息'" :visible.sync="dialogVisible" class="dialog" width="530px"> <el-form ref="formData" :model="formData" :rules="addFormRules" label-width="90px" style=" margin-left:40px;"> <el-form-item label="制令单号" prop="productOrderId"> <el-input v-model="formData.productOrderId" disabled /> </el-form-item> <el-form-item label="粗加工号" prop="compId"> <el-input v-model="formData.compId" disabled /> </el-form-item> <el-form-item label="是否下发" prop="isXiafa"> <el-select v-model="formData.isXiafa" placeholder="请选择是否下发"> <el-option v-for="(item,index) in lineTypeList" :key="index" :label="item.name" :value="item.value" /> </el-select> </el-form-item> <el-form-item label="是否完成" prop="isProcess"> <el-select v-model="formData.isXiafa" placeholder="请选择是否完成" disabled> <el-option v-for="(item,index) in isProcessList" :key="index" :label="item.name" :value="item.value" /> </el-select> </el-form-item> <el-form-item label="条形编码" prop="compIdSeq"> <el-input v-model="formData.compIdSeq" disabled /> </el-form-item> </el-form> <!-- 操作按钮 --> <span slot="footer" class="dialog-footer"> <el-button @click="dialogVisible = false">取消</el-button> <el-button type="primary" @click="handleSubmit('formData')">提交</el-button> </span> </el-dialog> <!-- 绑定炉号 --> <el-dialog v-dialogDrag :close-on-click-modal="false" :title="'绑定炉号'" :visible.sync="stoveDialog" class="dialog" width="530px"> <el-form ref="stoveInfo" :model="stoveInfo" :rules="addStoveFormRules" label-width="90px" style=" margin-left:40px;"> <el-form-item label="炉号" prop="lno"> <el-input v-model="stoveInfo.lno" /> </el-form-item> </el-form> <!-- 操作按钮 --> <span slot="footer" class="dialog-footer"> <el-button @click="stoveDialog = false">取消</el-button> <el-button type="primary" @click="handleSubmitBind('stoveInfo')">提交</el-button> </span> </el-dialog> </div> </template> <script> import { listWorkpiece, updateWorkpiece, bingCompLno } from '@/api/hs/workpiece' // import { updateBrCode } from '@/api/hs/brCode' export default { name: 'Workpiece', data() { return { column: [ { type: 'selection', reserveSelection: true }, { type: 'index', index: this.indexMethod }, { label: '炉号', prop: 'lno' }, { label: '制令单号', prop: 'productOrderId' }, { label: '粗加工号', prop: 'compId' }, { label: '是否下发', prop: 'isXiafa', formatter: this.isXiafaFormat }, { label: '是否完成', prop: 'isProcess', formatter: this.isProcessFormat }, { label: '条形编码', prop: 'compIdSeq' }, { label: '操作', render: (h, scope) => { return ( <div> <el-button v-hasPermi={['hs:workpiece:edit']} type='primary' size='mini' onClick={() => { this.handleEdit(scope) }} >编辑</el-button> </div> ) }, width: 140, fixed: 'right' } ], loading: false, total: 0, // 列表总条数 // 查询信息 queryParams: { page: 1, limit: 20, field: undefined, type: undefined, productOrderId: undefined, compIdSeq: undefined }, list: [], dialogVisible: false, formData: {}, addFormRules: { compIdSeq: [ { required: true, message: '请输入条码', trigger: 'blur' } ] }, addStoveFormRules: { lno: [ { required: true, message: '请输入炉号', trigger: 'blur' } ] }, lineTypeList: [{ name: '未下发', value: 0 }, { name: '下发', value: 1 }], isProcessList: [{ name: '未完成', value: 0 }, { name: '已完成', value: 1 }], tableList: [], stoveDialog: false, stoveInfo: { list: [], lno: undefined } } }, mounted() { this.getList() }, methods: { // 格式化序号 indexMethod(index) { return (this.queryParams.page - 1) * this.queryParams.limit + index + 1 }, // 排序 sortChange(column) { this.$mySort(this.queryParams, column, this.getList) }, handleSelectionChange(list) { this.stoveInfo.list = Array.from(list, ({ compIdSeq }) => compIdSeq) }, getList() { this.loading = true listWorkpiece(this.queryParams).then(res => { this.list = res.data this.total = res.count || 0 this.loading = false }) }, handleEdit(scope) { this.formData = JSON.parse(JSON.stringify(scope.row)) // this.reset() // this.formData.equipmentNo = scope.row.equipmentNo this.dialogVisible = true }, // 提交新增订单信息 handleSubmit(formName) { updateWorkpiece(this.formData).then(res => { this.dialogVisible = false this.$message.success('修改成功') this.getList() }) }, handleSubmitBind(formName) { this.$refs[formName].validate((valid) => { if (valid) { bingCompLno(this.stoveInfo).then(res => { this.stoveDialog = false this.$message.success(res.msg) this.getList() this.$refs.table.clearSelection() }) } }) // this.stoveDialog = true }, // handleSubmit(formName) { // this.$refs[formName].validate((valid) => { // if (valid) { // updateBrCode(this.formData).then(res => { // this.$message.success(res.msg) // this.dialogVisible = false // this.getList() // }) // } // }) // }, /** 搜索按钮操作 */ handleQuery() { this.queryParams.page = 1 this.getList() }, handleBind() { this.stoveDialog = true }, /** 重置按钮操作 */ resetQuery() { this.resetForm('queryForm') this.handleQuery() this.$refs.table.clearSelection() // 清空表格多选 }, // 表单重置 reset() { this.formData = { compIdSeq: undefined, equipmentNo: undefined } this.resetForm('formData') }, // 格式化 isXiafaFormat(row) { const obj = { 0: '未下发', 1: '下发' } return obj[row.isXiafa] }, isProcessFormat(row) { const obj = { 0: '未完成', 1: '已完成' } return obj[row.isProcess] } } } </script> <style scoped> </style>
// Copyright (c) The OpenTofu Authors // SPDX-License-Identifier: MPL-2.0 // Copyright (c) 2023 HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 package globalref import ( "context" "path/filepath" "testing" "github.com/zclconf/go-cty/cty" "github.com/opentofu/opentofu/internal/addrs" "github.com/opentofu/opentofu/internal/configs/configload" "github.com/opentofu/opentofu/internal/configs/configschema" "github.com/opentofu/opentofu/internal/initwd" "github.com/opentofu/opentofu/internal/providers" "github.com/opentofu/opentofu/internal/registry" ) func testAnalyzer(t *testing.T, fixtureName string) *Analyzer { configDir := filepath.Join("testdata", fixtureName) loader, cleanup := configload.NewLoaderForTests(t) defer cleanup() inst := initwd.NewModuleInstaller(loader.ModulesDir(), loader, registry.NewClient(nil, nil)) _, instDiags := inst.InstallModules(context.Background(), configDir, "tests", true, false, initwd.ModuleInstallHooksImpl{}) if instDiags.HasErrors() { t.Fatalf("unexpected module installation errors: %s", instDiags.Err().Error()) } if err := loader.RefreshModules(); err != nil { t.Fatalf("failed to refresh modules after install: %s", err) } cfg, loadDiags := loader.LoadConfig(configDir) if loadDiags.HasErrors() { t.Fatalf("unexpected configuration errors: %s", loadDiags.Error()) } resourceTypeSchema := &configschema.Block{ Attributes: map[string]*configschema.Attribute{ "string": {Type: cty.String, Optional: true}, "number": {Type: cty.Number, Optional: true}, "any": {Type: cty.DynamicPseudoType, Optional: true}, }, BlockTypes: map[string]*configschema.NestedBlock{ "single": { Nesting: configschema.NestingSingle, Block: configschema.Block{ Attributes: map[string]*configschema.Attribute{ "z": {Type: cty.String, Optional: true}, }, }, }, "group": { Nesting: configschema.NestingGroup, Block: configschema.Block{ Attributes: map[string]*configschema.Attribute{ "z": {Type: cty.String, Optional: true}, }, }, }, "list": { Nesting: configschema.NestingList, Block: configschema.Block{ Attributes: map[string]*configschema.Attribute{ "z": {Type: cty.String, Optional: true}, }, }, }, "map": { Nesting: configschema.NestingMap, Block: configschema.Block{ Attributes: map[string]*configschema.Attribute{ "z": {Type: cty.String, Optional: true}, }, }, }, "set": { Nesting: configschema.NestingSet, Block: configschema.Block{ Attributes: map[string]*configschema.Attribute{ "z": {Type: cty.String, Optional: true}, }, }, }, }, } schemas := map[addrs.Provider]providers.ProviderSchema{ addrs.MustParseProviderSourceString("hashicorp/test"): { ResourceTypes: map[string]providers.Schema{ "test_thing": { Block: resourceTypeSchema, }, }, DataSources: map[string]providers.Schema{ "test_thing": { Block: resourceTypeSchema, }, }, }, } return NewAnalyzer(cfg, schemas) }
import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../../backend/styles/theme.dart'; import '../../../backend/widgets/randome_generator.dart'; import 'random_generator_result_screen.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.light().copyWith( primaryColor: CustomTheme.darkRed, scaffoldBackgroundColor: Colors.transparent, appBarTheme: const AppBarTheme( backgroundColor: Colors.transparent, elevation: 0, ), ), home: Container( decoration: const BoxDecoration( gradient: LinearGradient( colors: <Color>[ CustomTheme.loginGradientStart, CustomTheme.loginGradientEnd, ], begin: FractionalOffset(0.0, 0.0), end: FractionalOffset(1.0, 1.0), stops: <double>[0.0, 1.0], tileMode: TileMode.clamp, ), borderRadius: BorderRadius.all(Radius.circular(5.0)), boxShadow: <BoxShadow>[ BoxShadow( color: CustomTheme.loginGradientStart, offset: Offset(1.0, 6.0), blurRadius: 20.0, ), BoxShadow( color: CustomTheme.loginGradientEnd, offset: Offset(1.0, 6.0), blurRadius: 20.0, ), ], ), child: const RandomGeneratorScreen(), ), ); } } class RandomGeneratorScreen extends StatefulWidget { const RandomGeneratorScreen({Key? key}) : super(key: key); @override _RandomGeneratorScreenState createState() => _RandomGeneratorScreenState(); } class _RandomGeneratorScreenState extends State<RandomGeneratorScreen> { late List<String> selectedGenres = []; late SharedPreferences prefs; @override void initState() { super.initState(); _loadSelectedGenres(); } _loadSelectedGenres() async { prefs = await SharedPreferences.getInstance(); setState(() { selectedGenres = prefs.getStringList('selectedGenres') ?? []; }); } _saveSelectedGenres() async { await prefs.setStringList('selectedGenres', selectedGenres); } _navigateToRandomGeneratorResultScreen() { Navigator.push( context, MaterialPageRoute( builder: (context) => const RandomGeneratorResultScreen(), )); } @override Widget build(BuildContext context) { return Scaffold( appBar: PreferredSize( preferredSize: const Size.fromHeight(50), child: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: IconButton( icon: const Icon( Icons.arrow_back, color: CustomTheme.snowWhite, ), onPressed: () { _saveSelectedGenres(); Navigator.pop(context); }, ), title: const Text( "Deine Zufallsgenerator", style: TextStyle( color: CustomTheme.snowWhite, fontFamily: 'DancingScript', fontWeight: FontWeight.bold, fontSize: 24, ), ), ), ), body: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Padding( padding: EdgeInsets.all(16.0), child: Text( "Was möchtest du heute lesen? Du musst dich nicht für ein Genre entscheiden", textAlign: TextAlign.center, style: TextStyle( color: CustomTheme.snowWhite, fontSize: 16, ), ), ), YourBodyWidget(selectedGenres: selectedGenres), ], ), ), backgroundColor: Colors.transparent, bottomNavigationBar: Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( onPressed: () { _saveSelectedGenres(); ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Auswahl gespeichert!'), ), ); _navigateToRandomGeneratorResultScreen(); }, style: ElevatedButton.styleFrom( primary: Colors.white, onPrimary: Colors.black, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), shadowColor: CustomTheme.darkMode, elevation: 5, ), child: const Padding( padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0), child: Text('Weiter'), ), ), ), ); } } class YourBodyWidget extends StatefulWidget { final List<String> selectedGenres; const YourBodyWidget({Key? key, required this.selectedGenres}) : super(key: key); @override _YourBodyWidgetState createState() => _YourBodyWidgetState(); } class _YourBodyWidgetState extends State<YourBodyWidget> { void _toggleGenre(String genre) { if (widget.selectedGenres.contains(genre)) { widget.selectedGenres.remove(genre); } else { widget.selectedGenres.add(genre); } if (mounted) { setState(() {}); } } Widget _buildAnimatedButton(String genre, bool isSelected) { return GestureDetector( onTap: () { _toggleGenre(genre); }, child: Container( height: 50, width: 180, decoration: BoxDecoration( color: isSelected ? CustomTheme.darkRed : Colors.white, border: Border.all( color: Colors.white, width: 1, ), borderRadius: BorderRadius.circular(15), boxShadow: const [ BoxShadow( color: CustomTheme.darkMode, offset: Offset(2, 2), blurRadius: 5, ), ], ), child: Center( child: Text( genre, style: TextStyle( fontSize: 16, color: isSelected ? CustomTheme.snowWhite : CustomTheme.darkMode, ), ), ), ), ); } @override Widget build(BuildContext context) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: List.generate( (buttonTitles.length / 2).ceil(), (rowIndex) { final startIdx = rowIndex * 2; final endIdx = (rowIndex + 1) * 2; return Row( mainAxisAlignment: MainAxisAlignment.center, children: List.generate( endIdx - startIdx, (index) { final genreIndex = startIdx + index; if (genreIndex < buttonTitles.length) { final genre = buttonTitles[genreIndex]; final isSelected = widget.selectedGenres.contains(genre); return Expanded( child: Padding( padding: const EdgeInsets.all(8.0), child: _buildAnimatedButton(genre, isSelected), ), ); } return const SizedBox.shrink(); }, ), ); }, ), ), ); } }
# ptywrapper `ptywrapper` is a Go module that provides a simplified interface for running commands in a pseudo-terminal (PTY). It is essentially a wrapper around the [github.com/creack/pty](https://github.com/creack/pty) module, designed to make it easier to implement in your programs. This module was created to address specific challenges I encountered during development of programs written in Go that needed to use pseudo-terminals, such as blocking operations, unsynchronized copying operations, and issues with user input. `ptywrapper` offers a solution (at least, partial) to these problems, making it easier to run terminal commands within Go programs. It provides features like context support, output cleanup, and easy handling of command exit codes, all while ensuring smooth operation. ## Features `ptywrapper` provides a number of features to simplify the process of running commands in a pseudo-terminal (PTY): - **Command Execution in PTY**: `ptywrapper` allows you to easily run any command in a PTY. This can be useful for running commands that require a terminal environment. - **Context Support**: Each command run in a PTY has an associated context. This allows for better control over the command execution and can be used to cancel the command if necessary. - **Output Cleanup**: `ptywrapper` automatically cleans up the command's output by removing ANSI escape sequences and certain special characters. This makes the output easier to use in your Go programs. - **Output Discarding**: You can choose to discard the command's output, which means it won't be printed to the standard output during execution. However, the output will still be captured and stored in a variable for later use. - **Exit Code Handling**: `ptywrapper` captures the exit code of the command, which can be used to determine whether the command completed successfully. - **Custom Environment**: `ptywrapper` allows you to specify a custom environment for the command being run. This can be useful if you need to set specific environment variables or modify the existing environment in some way. If no custom environment is provided, the command will be run with the current environment (as returned by `os.Environ()`). - **Testing Support**: `ptywrapper` includes test files in the `./tests` subfolder that demonstrate how to use the module and can be used for testing purposes. ## Installation To install `ptywrapper`, you can use `go get`: ```bash go get github.com/fearlessdots/ptywrapper ``` ## Usage Here's a basic example of how to use ptywrapper: ```go import ( "github.com/fearlessdots/ptywrapper" "fmt" ) func main() { cmd := &ptywrapper.Command{ Entry: "ls", Args: []string{"-l"}, } completedCmd, err := cmd.RunInPTY() if err != nil { fmt.Println("Error:", err) return } if completedCmd.ExitCode != 0 { fmt.Println("Command exited with error. Exit code:", completedCmd.ExitCode) } else { fmt.Println("Command output:", completedCmd.Output) } } ``` If you want to run a command but discard its output (i.e., not print it to the standard output), you can set the `Discard` field to true: ```go package main import ( "github.com/fearlessdots/ptywrapper" "fmt" ) func main() { cmd := &ptywrapper.Command{ Entry: "ls", Args: []string{"-l"}, Discard: true, // Discard output } completedCmd, err := cmd.RunInPTY() if err != nil { fmt.Println("Error:", err) return } // The output will not be printed to the standard output, // but it will still be available in the Output field. fmt.Println("Command output:", completedCmd.Output) } ``` However, it's important to note that even when the output is discarded in this way, it is still captured and stored in the `Output` field of the `Command` struct. This allows you to access and operate on the command's output later in your code, even if it was not immediately visible during execution. This feature can be particularly useful when you want to run a command silently (without printing its output), but still need to use the output for further processing or logging. To append custom environment variables to the current environment and use them with a command, the following code can be used: ```go import ( "github.com/fearlessdots/ptywrapper" "fmt" "os" ) func main() { // Get the current environment currentEnv := os.Environ() // Define custom environment variables customEnv := map[string]string{ "FOO": "bar", "BAZ": "qux", } // Append custom environment variables to the current environment for key, value := range customEnv { currentEnv = append(currentEnv, key+"="+value) } cmd := &ptywrapper.Command{ Entry: "printenv", Args: []string{}, Env: currentEnv, } completedCmd, err := cmd.RunInPTY() if err != nil { fmt.Println("Error:", err) return } fmt.Println("Command output:", completedCmd.Output) } ``` Finally, here's an example of how to use only the custom environment: ```go import ( "github.com/fearlessdots/ptywrapper" "fmt" ) func main() { cmd := &ptywrapper.Command{ Entry: "printenv", Args: []string{}, Env: []string{"FOO=bar", "BAZ=qux"}, } completedCmd, err := cmd.RunInPTY() if err != nil { fmt.Println("Error:", err) return } fmt.Println("Command output:", completedCmd.Output) } ``` ### The `Command` Struct The `Command` struct represents a command to be run in a pseudo-terminal (PTY). It has several fields that can be set before running the command and some that are populated after the command has been run. #### Fields Available Before Running `command.RunInPTY()` - `Entry`: This is the command to be run. It should be a string representing the path to the executable. - `Args`: This is an array of strings representing the arguments to be passed to the command. - `Env`: This is an array of strings representing the environment variables for the command. Each string should be in the format `KEY=value`. If `Env` is not set, the command will be run with the current environment (as returned by `os.Environ()`). - `Discard`: This is a boolean that determines whether the command's output should be discarded. If set to `true`, the command's output will not be printed to the standard output during execution, but it will still be captured and stored in the `Output` field. #### Fields Available After Running `command.RunInPTY()` - `Completed`: This is a boolean that indicates whether the command has completed. It is set to `true` after the command has been run. - `Output`: This is a string that contains the command's output. It is populated after the command has been run. If the `Discard` field was set to `true`, the output will not have been printed to the standard output, but it will still be captured and stored in this field. - `ExitCode`: This is an integer that contains the command's exit code. It is populated after the command has been run. An exit code of 0 usually indicates that the command completed successfully, while a non-zero exit code usually indicates that an error occurred. #### Persistence of Fields in the `Command` Struct After executing `command.RunInPTY()`, the fields that were available before running the command (`Entry`, `Args`, `Env`, and `Discard`) remain accessible. They retain the values that were set before the command was run. This means you can still access the original command (`Entry`), its arguments (`Args`), the environment variables (`Env`), and the discard setting (`Discard`) even after the command has been executed. These fields are not modified by the execution of the command. In addition to these, the fields that are populated after the command has been run (`Completed`, `Output`, and `ExitCode`) are also available. This allows you to access a comprehensive set of information about the command and its execution, including what the command was, what arguments it was run with, what environment variables it used, whether its output was discarded, whether it has completed, what output it produced, and what its exit code was. ## Inner Workings The `ptywrapper` module is composed of several key components: ### Types - `contextWrapper`: This type is a struct that wraps a context and its cancel function. It is used to track the execution of the command. - `Writer`: This type is a struct that wraps two file pointers (source and destination) and a context. It implements the `io.Writer` interface and is used to copy data between the source and destination. - `Command`: This type is a struct that represents a command to be run in a PTY. It includes fields for the command entry, arguments, environment variables, a flag to discard output, a flag to indicate if the command has completed, the command output, and the exit code. ### Functions - `cleanupString`: This function takes a string as input and cleans it up by removing ANSI escape sequences and certain special characters. - `generateContextWrapper`: This function generates a new `contextWrapper`. - `RunInPTY`: This method of the `Command` type runs the command in a PTY. It handles the creation of the PTY, setting up the command, starting the command, copying data between the PTY and the standard input/output, waiting for the command to exit, and cleaning up the command output. ### Goroutines The `RunInPTY` method uses several goroutines to handle different aspects of the command execution: - A goroutine is used to resize the PTY whenever a `SIGWINCH` signal is received. - A goroutine is used to copy data from the standard input to the PTY. This goroutine reads data from the standard input in a non-blocking manner and writes it to the PTY. - A goroutine is used to copy data from the PTY to the standard output. This goroutine reads data from the PTY in a non-blocking manner and writes it to the standard output and a bytes buffer. - A goroutine is used to wait for the command to exit. When the command exits, this goroutine cancels the context, closes the PTY, and waits for the other goroutines to finish. These goroutines work together to ensure that the command is executed in a PTY and its output is captured and cleaned up. ## Testing The `./tests` subfolder in the source code contains test files that demonstrate how to use the `ptywrapper` module. ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. ## License ptywrapper is licensed under the MIT license.
# # (C) Tenable Network Security, Inc. # # References: # # http://www.nessus.org/u?fd6d1531 # # Date: Sun, 10 Mar 2002 21:37:33 +0100 # From: "Obscure" <obscure@eyeonsecurity.net> # To: bugtraq@securityfocus.com, vulnwatch@vulnwatch.org # Subject: IMail Account hijack through the Web Interface # # Date: Mon, 11 Mar 2002 04:11:43 +0000 (GMT) # From: "Zillion" <zillion@safemode.org> # To: "Obscure" <obscure@zero6.net> # CC: bugtraq@securityfocus.com, vulnwatch@vulnwatch.org, "Obscure" <obscure@eyeonsecurity.net> # Subject: Re: IMail Account hijack through the Web Interface # include("compat.inc"); if(description) { script_id(11271); script_version("$Revision: 1.15 $"); script_cve_id("CVE-2001-1286"); script_bugtraq_id(3432); script_osvdb_id(10845); script_name(english:"Ipswitch IMail Web Interface URI Referer Session Token Disclosure"); script_summary(english:"Checks for version of IMail web interface"); script_set_attribute(attribute:"synopsis", value: "The remote mail server is affected by an information disclosure vulnerability." ); script_set_attribute(attribute:"description", value: "The remote host is running IMail web interface. In this version, the session is maintained via the URL. It will be disclosed in the Referer field if you receive an email with external links (e.g. images)" ); script_set_attribute(attribute:"see_also", value:"http://seclists.org/bugtraq/2001/Oct/82" ); script_set_attribute(attribute:"see_also", value:"http://seclists.org/bugtraq/2002/Mar/164" ); script_set_attribute(attribute:"see_also", value:"http://seclists.org/bugtraq/2002/Mar/165" ); script_set_attribute(attribute:"see_also", value:"http://seclists.org/bugtraq/2002/Mar/206" ); script_set_attribute(attribute:"see_also", value:"http://seclists.org/bugtraq/2002/Mar/221" ); script_set_attribute(attribute:"solution", value: "Upgrade to IMail 7.06 or turn off the 'ignore source address in security check' option." ); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:P/I:N/A:N"); script_set_cvss_temporal_vector("CVSS2#E:H/RL:OF/RC:C"); script_set_attribute(attribute:"exploitability_ease", value:"No exploit is required"); script_set_attribute(attribute:"exploit_available", value:"true"); script_set_attribute(attribute:"plugin_publication_date", value: "2003/02/25"); script_set_attribute(attribute:"vuln_publication_date", value: "2001/10/11"); script_cvs_date("$Date: 2016/10/27 15:03:54 $"); script_set_attribute(attribute:"plugin_type", value:"remote"); script_set_attribute(attribute:"cpe",value:"cpe:/a:ipswitch:imail"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2003-2016 Tenable Network Security, Inc."); script_family(english:"CGI abuses"); script_dependencie("find_service1.nasl", "no404.nasl", "http_version.nasl"); #script_require_keys("www/IMail"); script_require_ports("Services/www", 80); exit(0); } # The script code starts here include("global_settings.inc"); include("misc_func.inc"); include("http.inc"); port = get_http_port(default:80); banner = get_http_banner(port: port); if (isnull(banner)) exit(1, "Failed to get the banner from port "+port+"."); serv = egrep(string: banner, pattern: "^Server:.*"); if(serv && ereg(pattern:"^Server:.*Ipswitch-IMail/(([1-6]\.)|(7\.0[0-5]))", string:serv)) security_warning(port);
<app-header-breadcrumb></app-header-breadcrumb> <div class="card panel-default-header"> <p-panel header="Recherche Personne"> <br> <div class="ui-g form-group"> <div class="ui-g-12 ui-md-6"> <span class="ui-float-label"> <p-dropdown class="disableddropdown" [options]="raisonSocialeList" [autoDisplayFirst]="false" [filter]="false" optionLabel="name" optionValue="code" name="raisonSociale" id="raisonSociale" (onChange)="onRaisonSocialeChange($event)" [(ngModel)]="typeRaisonSocialeSearch"></p-dropdown> <span class="foalting-label">Type</span> </span> </div> <div class="ui-g-12 ui-md-6"> <span class="ui-float-label" *ngIf="choixRaisonSociale == 'P'"> <input id="nom" class="ui-md-12" type="text" pInputText [(ngModel)]="nomSearch" (keyup.enter)="doSearch()" /> <span class="foalting-label">Nom</span> </span> <span class="ui-float-label" *ngIf="choixRaisonSociale == 'A'"> <input id="cin" class="ui-md-12" type="text" pInputText [(ngModel)]="designationSearch" (keyup.enter)="doSearch()" /> <span class="foalting-label">Désignation</span> </span> <span class="ui-float-label" *ngIf="choixRaisonSociale == 'M'"> <input id="cin" class="ui-md-12" type="text" pInputText [(ngModel)]="raisonSocialeSearch" (keyup.enter)="doSearch()" /> <span class="foalting-label">Nom de la société</span> </span> </div> <br *ngIf="choixRaisonSociale == 'M' || choixRaisonSociale == 'A' || !choixRaisonSociale"> <br *ngIf="choixRaisonSociale == 'M' || choixRaisonSociale == 'A' || !choixRaisonSociale"> <br *ngIf="choixRaisonSociale == 'M' || choixRaisonSociale == 'A' || !choixRaisonSociale"> <br *ngIf="choixRaisonSociale == 'M' || choixRaisonSociale == 'A' || !choixRaisonSociale"> <br *ngIf="choixRaisonSociale == 'M' || choixRaisonSociale == 'A' || !choixRaisonSociale"> <div class="ui-g-12 ui-md-6"> <span class="ui-float-label" *ngIf="choixRaisonSociale == 'P'"> <input id="prenom" class="ui-md-12" type="text" pInputText [(ngModel)]="prenomSearch" (keyup.enter)="doSearch()" /> <span class="foalting-label">Prénom</span> </span> </div> <div class="ui-g-12 ui-md-6"> <span class="ui-float-label" *ngIf="choixRaisonSociale == 'P'"> <input id="cin" class="ui-md-12" type="text" pInputText [(ngModel)]="cinSearch" (keyup.enter)="doSearch()" /> <span class="foalting-label">CIN / N° Passeport</span> </span> </div> <div class="ui-g-12 ui-md-6"> </div> <div class="ui-g-12 ui-md-12 right-align"> <span class="ui-float-label"> <button icon="fa fa-search" class="rougebutton" pButton label="Chercher" type="button" (click)="doSearch()"></button> </span> </div> </div> </p-panel> <div class="panel-secondary-header"> <p-panel header="Résultat" *ngIf="display"> <br> <div class="ui-g form-group"> <div class="ui-g-12 ui-md-6"> <span class="ui-float-label" *ngIf="choixRaisonSociale == 'P'"> <input id="nom" class="ui-md-12" type="text" pInputText class="disabledinput" [(ngModel)]="nom" /> <span class="foalting-label">Nom</span> </span> <span class="ui-float-label" *ngIf="choixRaisonSociale == 'A'"> <input id="designation" class="ui-md-12" type="text" pInputText class="disabledinput" [(ngModel)]="designation" /> <span class="foalting-label">Désignation</span> </span> <span class="ui-float-label" *ngIf="choixRaisonSociale == 'M'"> <input id="raisonSociale" class="ui-md-12" type="text" pInputText class="disabledinput" [(ngModel)]="raisonSociale" /> <span class="foalting-label">Nom de la société</span> </span> </div> <div class="ui-g-12 ui-md-6" *ngIf="choixRaisonSociale == 'P'"> <span class="ui-float-label"> <input id="prenom" class="ui-md-12" type="text" pInputText class="disabledinput" [(ngModel)]="prenom" /> <span class="foalting-label">Prénom</span> </span> </div> <div class="ui-g-12 ui-md-6" *ngIf="choixRaisonSociale == 'P'"> <span class="ui-float-label"> <input id="cin" class="ui-md-12" type="text" pInputText class="disabledinput" [(ngModel)]="cin" /> <span class="foalting-label">CIN / N° Passeport</span> </span> </div> </div> <br> <p-tabView *ngIf="type == 'P'"> <p-tabPanel header="Hébergement" [headerStyle]="{'background-color':'white'}"> <div class="pagescheduler"> <app-calendar [nombreReservations]="nombreReservations" [nomPersonne]="nomComplet" [day]="day" [typeReservation]="typeReservation" [month]="month" [year]="year" [rooms]="rooms" [bookings]="bookings" (changereservation)="onReservationChanged($event)" (reservation)="onDayReservation($event)"> </app-calendar> </div> </p-tabPanel> </p-tabView> <br> </p-panel> </div> <div class="ui-g-12 ui-md-12 center-align" *ngIf="display"> <span class="ui-float-label"> <button icon="fa fa-undo" class="rougebutton" pButton label="Réinitialiser" type="button" (click)="reset()"></button> </span> </div> </div> <p-dialog [(visible)]="selectionDisplay" showEffect="fade" [style]="{width: '65%'}" (onHide)="closeSelectionDialog()"> <p-header>Choix multiple</p-header> <br> <p-table [style]="{width: '90%', margin: '0 auto'}" [value]="personnes" responsiveLayout="scroll" [paginator]="true" [rows]="5" [resizableColumns]="true" [reorderableColumns]="true"> <ng-template pTemplate="header"> <tr> <th *ngIf="choixRaisonSociale == 'P'" style="width: 25%;">Nom</th> <th *ngIf="choixRaisonSociale == 'P'" style="width: 25%;">Prenom</th> <th *ngIf="choixRaisonSociale == 'P'" style="width: 20%;">CIN / N° Passeport</th> <th *ngIf="choixRaisonSociale == 'A'" style="width: 75%;">Désignation</th> <th *ngIf="choixRaisonSociale == 'M'" style="width: 75%;">Nom de la société</th> <th></th> </tr> </ng-template> <ng-template pTemplate="body" let-personne> <tr> <td *ngIf="choixRaisonSociale == 'P'">{{ personne?.nom }}</td> <td *ngIf="choixRaisonSociale == 'P'">{{ personne?.prenom }}</td> <td *ngIf="choixRaisonSociale == 'P'">{{ personne?.numeroPieceIdentite }}</td> <td *ngIf="choixRaisonSociale == 'A'">{{ personne?.designation }} </td> <td *ngIf="choixRaisonSociale == 'M'">{{ personne?.raisonSociale }} </td> <td style="text-align: center;">(<a (click)="selectionner(personne)">Sélectionner</a>)</td> </tr> </ng-template> </p-table> <br> <div class="ui-g-12 ui-md-12 right-align"> <span class="ui-float-label"> <button icon="fa fa-times" class="rougebutton" pButton label="Fermer" type="button" (click)="closeSelectionDialog()"></button> </span> </div> </p-dialog> <p-toast class="custom-toast" position="bottom-center"></p-toast>
import { Component } from 'react'; import axios from "axios"; import { Link } from "react-router-dom"; class LoanList extends Component{ constructor(props){ super(props) this.state = { loans:[] } } componentDidMount(){ axios.get('http://localhost:3032/api/customer').then((response)=> { this.setState({loans: response.data }); }); console.log('response'); } render() { return( <div className="Loan-summary"> <h2>Loan Applications</h2> <table class="table border shadow"> <thead class="table-dark"> <tr> <th>Loan Id</th> <th>AccountNumber</th> <th>Amount</th> <th>Amount Balance</th> <th>Tenure</th> <th>Tenure Balance</th> <th>Status</th> <th>Update</th> </tr> </thead> <tbody> { this.state.loans.map( loan => <tr key={loan.id}> <td>{loan.id}</td> <td>{loan.accId} </td> <td>{loan.loan_amount} </td> <td>{loan.loan_balance} </td> <td>{loan.tenure} </td> <td>{loan.tenure_balance} </td> <td>{loan.status} </td> <td><Link class="btn btn-outline-primary mr-2" to={`/loans/edit/${loan.id}`}> Edit </Link> </td> </tr> ) } </tbody> </table> </div> ); } } export default LoanList;
<template> <a-spin :loading="loading" style="width: 100%" :size="40"> <a-form :model="setting" :style="{width:'900px'}" layout='vertical'> <a-form-item field="rad_config" label="Rad爬虫配置"> <a-textarea v-model="setting.rad_config" :auto-size="{ minRows:12, maxRows:20 }"/> <template #extra> <div>yml格式的配置文件</div> </template> </a-form-item> <a-form-item field="thread_num" label="扫描线程数"> <a-input-number v-model="setting.thread_num" :style="{width:'320px'}" placeholder="请输入线程数" class="input-demo" :min="1" :max="1000"/> <template #extra> <div>修改线程数量会销毁当前平台所有正在进行的扫描任务</div> </template> </a-form-item> <a-form-item field="name" label="扫描header头部"> <a-textarea v-model="setting.headers" :auto-size="{ minRows:12, maxRows:20 }"/> <template #extra> <div>json格式</div> </template> </a-form-item> <a-form-item field="name" label="扫描cookies"> <a-textarea v-model="setting.cookies" :auto-size="{ minRows:12, maxRows:20 }"/> <template #extra> <div>json格式</div> </template> </a-form-item> <a-form-item field="name" label="扫描超时时间"> <a-input-number v-model="setting.timeout" :style="{width:'320px'}" placeholder="请输入超时时间" class="input-demo" :min="0" :max="100"/> </a-form-item> </a-form> <a-space> <a-button type="primary" @click="submit">提交修改</a-button> <a-button type="primary" status="success" @click="reset">重置为默认值</a-button> </a-space> </a-spin> </template> <script> import {onMounted, reactive, ref} from "vue"; import {getConfig, setConfig, getDefaultConfig} from "../../api/config.js"; import {getMessage} from "../../utils"; export default { name: "ScanSetting", setup() { const message = getMessage() const loading = ref(false) const data = reactive({ }) const setting = reactive({ thread_num: 1, rad_config: '', timeout: 10, headers: '', cookies: '' }) const loadConfig = () => { loading.value = true getConfig().then((res) => { if (res.data.code === 200) { setting.rad_config = res.data.data.rad_config setting.headers = JSON.stringify(res.data.data.headers, null, 4) setting.cookies = JSON.stringify(res.data.data.cookies, null, 4) setting.thread_num = res.data.data.thread_num setting.timeout = res.data.data.timeout } loading.value = false }).catch((error) => { console.log(error) loading.value = false message.value.error("服务端错误,请重试!") }) } const load = () => { loadConfig() } onMounted(() => { load() }) const submit = () => { loading.value = true setConfig(setting).then((res) => { if (res.data.code === 200) { message.value.success("修改成功") } loading.value = false }).catch((error) => { console.log(error) loading.value = false message.value.error("服务端错误,请重试!") }) } const reset = () => { loading.value = true getDefaultConfig().then((res) => { if (res.data.code === 200) { setting.rad_config = res.data.data.rad_config setting.headers = JSON.stringify(res.data.data.headers, null, 4) setting.cookies = JSON.stringify(res.data.data.cookies, null, 4) setting.thread_num = res.data.data.thread_num setting.timeout = res.data.data.timeout } loading.value = false }).catch((error) => { console.log(error) loading.value = false message.value.error("服务端错误,请重试!") }) } return { data, loading, setting, submit, reset } } } </script> <style scoped> </style>
import { Box, Button, FormControl, Input, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, Spinner, Text, useDisclosure, useToast, } from "@chakra-ui/react"; import { useState } from "react"; import UserListItem from "../UsersItems/UserListItem"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { makeRequest } from "../../utils/axios"; import UserBadgeItem from "../UsersItems/UserBadgeItem"; const GroupChatModal = ({ children, user }) => { const [groupName, setGroupName] = useState(""); const [selectedUsers, setSelectedUsers] = useState([]); const [search, setSearch] = useState(""); const { isOpen, onOpen, onClose } = useDisclosure(); const toast = useToast(); const queryClient = useQueryClient(); const { isLoading, data: users } = useQuery({ queryKey: ["users", search], queryFn: async () => { const res = await makeRequest(`/user/allUsers?search=${search}`); return res.data; }, enabled: !!search, }); const addUserToGroupHandler = async (userToAdd) => { if (selectedUsers.includes(userToAdd)) { toast({ title: "User already added", description: "This user has already been added. Search Others.", status: "warning", duration: 5000, isClosable: true, position: "top", }); return; } setSelectedUsers((prevState) => [...prevState, userToAdd]); }; const removeAddedUserHandler = async (addedUser) => { setSelectedUsers((prevState) => prevState.filter((user) => user._id !== addedUser._id) ); }; const { mutate } = useMutation({ mutationFn: (groupData) => { return makeRequest.post(`/chat/createGroup`, groupData); }, onError: (error) => { const errorMessage = error?.response?.data?.message || "Something went wrong."; toast({ title: "Error Occured!", description: errorMessage, status: "error", duration: 5000, isClosable: true, position: "top", }); }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["chats"], }); }, }); const createGroupSubmitHandler = async () => { if (!groupName || !selectedUsers) { toast({ title: "Please fill all the felids", description: "Add group name and group members.", status: "warning", duration: 5000, isClosable: true, position: "top", }); return; } if (selectedUsers.length < 2) { toast({ title: "Group should have 2 group members.", description: "Add more to group or chat One To One.", status: "warning", duration: 5000, isClosable: true, position: "top", }); return; } mutate({ groupName: groupName, groupMembers: selectedUsers, }); onClose(); setSearch(""); setSelectedUsers([]); }; return ( <> <span onClick={onOpen}>{children}</span> <Modal onClose={() => { onClose(); setSearch(""); setSelectedUsers([]); }} isOpen={isOpen} isCentered > <ModalOverlay /> <ModalContent mx={"5px"}> <ModalHeader fontSize="30px" fontFamily="Work sans" display="flex" justifyContent="center" > Create Group Chat </ModalHeader> <ModalCloseButton /> <ModalBody d="flex" flexDir="column" alignItems="center"> <FormControl> <Input placeholder="Group Name" mb={3} onChange={(e) => setGroupName(e.target.value)} type="search" /> </FormControl> <FormControl> <Input placeholder="Add Users eg: vipin, Kalia, Jane" mb={1} onChange={(e) => setSearch(e.target.value)} type="search" /> </FormControl> <Box w="100%" display="flex" flexWrap="wrap"> {selectedUsers.map((u) => ( <UserBadgeItem key={u._id} user={u} handleFunction={() => removeAddedUserHandler(u)} admin={user} /> ))} </Box> {isLoading ? ( <Spinner mx="auto" display="flex" /> ) : users?.length > 0 ? ( users?.map((user) => ( <UserListItem key={user._id} user={user} handleFunction={() => addUserToGroupHandler(user)} /> )) ) : ( users && ( <Box bg="#E8E8E8" w="100%" display="flex" alignItems="center" color="black" px={3} py={2} mt={5} borderRadius="lg" > <Text>No user found with this search.</Text> </Box> ) )} </ModalBody> <ModalFooter> <Button onClick={createGroupSubmitHandler} colorScheme="blue"> Create Chat </Button> </ModalFooter> </ModalContent> </Modal> </> ); }; export default GroupChatModal;
import React, { useEffect, useState } from 'react'; import { GlobeAltIcon, DocumentDownloadIcon } from '@heroicons/react/outline'; function SiteTitle({ site }) { const [favicon, setFavicon] = useState({ url: `${site}/favicon.ico`, loading: true, error: false }); const title = site.replace('https://', '').replace('http://', ''); useEffect(() => { const tempImage = new Image(); tempImage.onload = (e) => { setFavicon({ url: favicon.url, loading: false, error: false }); }; tempImage.onerror = () => { setFavicon({ url: undefined, loading: false, error: true }); }; tempImage.src = `${site}/favicon.ico`; }, []); return ( <div className="w-full flex items-center justify-center"> <div className="w-1/3 flex items-center justify-start text-mBlack"> {favicon.loading ? ( <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" className="w-6 h-6 fill-current" > <path d="M0 0h24v24H0z" fill="none" /> <path d="M12 3a9 9 0 0 1 9 9h-2a7 7 0 0 0-7-7V3z" /> </svg> ) : favicon.error ? ( <GlobeAltIcon className="w-6 h-6 stroke-current mr-3" /> ) : ( <img src={favicon.url} alt={site} className="w-6 h-6 object-contain mr-3" /> )} <h2 className="m-0 font-bold text-2xl">{title}</h2> </div> <div className="w-1/3 flex items-center justify-center text-mBlack"> <span className="w-3 h-3 bg-green-300 rounded-full relative"> <span className="absolute w-full h-full rounded-full animate-ping bg-green-300"></span> </span> <p className="text-sm ml-2"> <strong>5</strong> usuarios en línea </p> </div> <div className="w-1/3 flex items-center justify-end text-mBlack"> <button initial={{ opacity: 0, x: 50 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: 50 }} type="button" className="bg-main text-white font-bold flex items-center justify-center whitespace-nowrap rounded-md px-4 py-2 ml-5 shadow-main transform scale-100 hover:scale-95 transition-all duration-100 ease-in-out hover:shadow-mainActive z-0" > <DocumentDownloadIcon className="w-4 h-4 mr-1 stroke-current text-white" /> <p className="m-0 font-medium">Descargar reporte</p> </button> </div> </div> ); } export default SiteTitle;
import {Builder} from '@logi/base/ts/common/builder' import {Impl} from '@logi/base/ts/common/mapped_types' import {ResolvedNode} from '@logi/src/lib/intellisense/utils' import {ViewPart} from './part' export interface PanelItem { readonly parts: readonly ViewPart[] readonly resolvedNode?: ResolvedNode } class PanelItemImpl implements Impl<PanelItem> { public parts: readonly ViewPart[] = [] public resolvedNode?: ResolvedNode } export class PanelItemBuilder extends Builder<PanelItem, PanelItemImpl> { public constructor(obj?: Readonly<PanelItem>) { const impl = new PanelItemImpl() if (obj) PanelItemBuilder.shallowCopy(impl, obj) super(impl) } public parts(parts: readonly ViewPart[]): this { this.getImpl().parts = parts return this } public resolvedNode(resolvedNode: ResolvedNode): this { this.getImpl().resolvedNode = resolvedNode return this } protected get daa(): readonly string[] { return PanelItemBuilder.__DAA_PROPS__ } protected static readonly __DAA_PROPS__: readonly string[] = [ 'parts', ] } export function isPanelItem(obj: unknown): obj is PanelItem { return obj instanceof PanelItemImpl } export interface PanelTab { readonly items: readonly PanelItem[] readonly selected: number } class PanelTabImpl implements Impl<PanelTab> { public items: readonly PanelItem[] = [] public selected!: number } export class PanelTabBuilder extends Builder<PanelTab, PanelTabImpl> { public constructor(obj?: Readonly<PanelTab>) { const impl = new PanelTabImpl() if (obj) PanelTabBuilder.shallowCopy(impl, obj) super(impl) } public items(items: readonly PanelItem[]): this { this.getImpl().items = items return this } public selected(selected: number): this { this.getImpl().selected = selected return this } } export function isPanelTab(obj: unknown): obj is PanelTab { return obj instanceof PanelTabImpl } /** * The response that informs the frontend to show or hide the panel. */ export interface PanelResponse { readonly tab: PanelTab } class PanelResponseImpl implements Impl<PanelResponse> { public tab!: PanelTab } // tslint:disable-next-line: max-classes-per-file export class PanelResponseBuilder extends Builder<PanelResponse, PanelResponseImpl> { public constructor(obj?: Readonly<PanelResponse>) { const impl = new PanelResponseImpl() if (obj) PanelResponseBuilder.shallowCopy(impl, obj) super(impl) } public tab(tab: PanelTab): this { this.getImpl().tab = tab return this } protected get daa(): readonly string[] { return PanelResponseBuilder.__DAA_PROPS__ } protected static readonly __DAA_PROPS__: readonly string[] = ['tab'] } export function isPanelResponse(obj: unknown): obj is PanelResponse { return obj instanceof PanelResponseImpl }
package server import ( "context" api "github.com/bhatti/PlexAuthZ/api/v1/services" "github.com/bhatti/PlexAuthZ/api/v1/types" "github.com/bhatti/PlexAuthZ/internal/authz" "github.com/bhatti/PlexAuthZ/internal/service" ) type relationshipsServer struct { api.RelationshipsServiceServer authAdminService service.AuthAdminService authorizer authz.Authorizer } // NewRelationshipsServer constructor func NewRelationshipsServer( authAdminService service.AuthAdminService, authorizer authz.Authorizer, ) (api.RelationshipsServiceServer, error) { return &relationshipsServer{ authAdminService: authAdminService, authorizer: authorizer, }, nil } // Create Relationship func (s *relationshipsServer) Create( ctx context.Context, req *api.CreateRelationshipRequest, ) (*api.CreateRelationshipResponse, error) { if _, err := s.authorizer.Authorize( ctx, &api.AuthRequest{ PrincipalId: authz.Subject(ctx), Resource: objectWildcard, Action: updateAction, }, ); err != nil { return nil, err } relationship := &types.Relationship{ Namespace: req.Namespace, Relation: req.Relation, PrincipalId: req.PrincipalId, ResourceId: req.ResourceId, Attributes: req.Attributes, } relationship, err := s.authAdminService.CreateRelationship(ctx, req.OrganizationId, relationship) if err != nil { return nil, err } return &api.CreateRelationshipResponse{ Id: relationship.Id, }, nil } // Update Relationship func (s *relationshipsServer) Update( ctx context.Context, req *api.UpdateRelationshipRequest, ) (*api.UpdateRelationshipResponse, error) { if _, err := s.authorizer.Authorize( ctx, &api.AuthRequest{ PrincipalId: authz.Subject(ctx), Resource: objectWildcard, Action: updateAction, }, ); err != nil { return nil, err } relationship := &types.Relationship{ Id: req.Id, Namespace: req.Namespace, Relation: req.Relation, PrincipalId: req.PrincipalId, ResourceId: req.ResourceId, Attributes: req.Attributes, } if err := s.authAdminService.UpdateRelationship(ctx, req.OrganizationId, relationship); err != nil { return nil, err } return &api.UpdateRelationshipResponse{}, nil } // Query Relationship swagger:route GET /api/{organization_id}/{namespace}/relationships/{id} relationships queryRelationshipRequest // // Responses: // 200: queryRelationshipResponse // 400 Bad Request // 401 Not Authorized // 500 Internal Error func (s *relationshipsServer) Query( req *api.QueryRelationshipRequest, sender api.RelationshipsService_QueryServer, ) error { if _, err := s.authorizer.Authorize( sender.Context(), &api.AuthRequest{ PrincipalId: authz.Subject(sender.Context()), Resource: objectWildcard, Action: deleteAction, }, ); err != nil { return err } res, nextOffset, err := s.authAdminService.GetRelationships( sender.Context(), req.OrganizationId, req.Namespace, req.Predicates, req.Offset, req.Limit) if err != nil { return err } for _, relationship := range res { err = sender.Send( &api.QueryRelationshipResponse{ Id: relationship.Id, Namespace: relationship.Namespace, Version: relationship.Version, Relation: relationship.Relation, PrincipalId: relationship.PrincipalId, ResourceId: relationship.ResourceId, Created: relationship.Created, Updated: relationship.Updated, NextOffset: nextOffset, }) if err != nil { return err } } return nil } // Delete Relationship func (s *relationshipsServer) Delete( ctx context.Context, req *api.DeleteRelationshipRequest, ) (*api.DeleteRelationshipResponse, error) { if _, err := s.authorizer.Authorize( ctx, &api.AuthRequest{ PrincipalId: authz.Subject(ctx), Resource: objectWildcard, Action: deleteAction, }, ); err != nil { return nil, err } err := s.authAdminService.DeleteRelationship(ctx, req.OrganizationId, req.Namespace, req.Id) if err != nil { return nil, err } return &api.DeleteRelationshipResponse{}, nil }
import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit' import chatReducer from './slices/chatSlice' import authReducer from './slices/authSlice' import profileReducer from './slices/profileSlice' import marketplaceReducer from './slices/marketplaceSlice' import commonReducer from './slices/commonSlice' import eventReducer from './slices/eventSlice' export function makeStore() { return configureStore({ reducer: { common: commonReducer, chat: chatReducer, auth: authReducer, profile: profileReducer, marketplace: marketplaceReducer, event: eventReducer, }, }) } const store = makeStore() export type AppState = ReturnType<typeof store.getState> export type AppDispatch = typeof store.dispatch export type AppThunk<ReturnType = void> = ThunkAction< ReturnType, AppState, unknown, Action<string> > export default store
import { Field, Int, ObjectType } from '@nestjs/graphql'; import { BeforeInsert, BeforeUpdate, Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn, } from 'typeorm'; @Entity({ name: 'users' }) @ObjectType() export class User { @PrimaryGeneratedColumn('increment') @Field(() => Int) id: string; @Column({ name: 'username' }) @Field(() => String) username: string; @Column({ name: 'password' }) @Field(() => String) password: string; @CreateDateColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP(6)', }) @Field() created_at: Date; @UpdateDateColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP(6)', }) @Field() updated_at: Date; @BeforeInsert() insertCreated() { this.created_at = new Date(); this.updated_at = new Date(); } @BeforeUpdate() insertUpdate() { this.updated_at = new Date(); } }
package com.lab.server.command.commands; import com.lab.common.exchange.Response; import com.lab.common.musicBand.MusicBand; import com.lab.common.musicBand.exceptions.ValidationException; import com.lab.common.user.User; import com.lab.server.command.Command; import com.lab.server.executor.Editor; import java.util.Locale; import java.util.ResourceBundle; /** Replace if lower command class */ public final class ReplaceIfLowerCommand extends Command { public ReplaceIfLowerCommand(User user, Locale locale, Editor editor) { super(user, locale, editor); } /** * Replaces the value by key, if the new value is less than the old * * @return response and correctness */ @Override public Response execute() { if (editor.getValue() == null) { return new Response( false, ResourceBundle.getBundle("ReplaceIfLowerCommand", locale).getString("needKey")); } int key; try { key = Integer.parseInt(editor.getValue()); } catch (NumberFormatException e) { return new Response( false, ResourceBundle.getBundle("ReplaceIfLowerCommand", locale).getString("wrongFormat") + editor.getValue()); } if (editor.getCollection().getSize() > 0) { if (editor.getCollection().containsKey(key)) { MusicBand musicBand; musicBand = editor.getMusicBand(); if (musicBand == null) { return new Response(true); } if (editor.getCollection().get(key).compareTo(musicBand) > 0) { try { if (editor.getCollection().replace(key, musicBand, user)) { return new Response( true, ResourceBundle.getBundle("ReplaceIfLowerCommand", locale).getString("replaced")); } else { return new Response( true, ResourceBundle.getBundle("ReplaceIfLowerCommand", locale).getString("notOwner") + user.getLogin()); } } catch (ValidationException e) { return new Response(false, e.getMessage()); } } else { return new Response( true, ResourceBundle.getBundle("ReplaceIfLowerCommand", locale).getString("notReplaced") + key); } } else { return new Response( false, String.format( ResourceBundle.getBundle("ReplaceIfLowerCommand", locale).getString("notFound"), key)); } } return new Response( false, ResourceBundle.getBundle("ReplaceIfLowerCommand", locale).getString("noElements")); } }
/* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 3.3.0 build: 3167 */ YUI.add('array-extras', function(Y) { /** * Collection utilities beyond what is provided in the YUI core * @module collection * @submodule array-extras */ var L = Y.Lang, Native = Array.prototype, A = Y.Array; /** * Adds the following array utilities to the YUI instance * (Y.Array). This is in addition to the methods provided * in the core. * @class YUI~array~extras */ /** * Returns the index of the last item in the array that contains the specified * value, or -1 if the value isn't found. * @method Array.lastIndexOf * @static * @param {Array} a Array to search in. * @param {any} val Value to search for. * @param {Number} fromIndex (optional) Index at which to start searching * backwards. Defaults to the array's length - 1. If negative, it will be * taken as an offset from the end of the array. If the calculated index is * less than 0, the array will not be searched and -1 will be returned. * @return {Number} Index of the item that contains the value, or -1 if not * found. */ A.lastIndexOf = Native.lastIndexOf ? function(a, val, fromIndex) { // An undefined fromIndex is still considered a value by some (all?) // native implementations, so we can't pass it unless it's actually // specified. return fromIndex || fromIndex === 0 ? a.lastIndexOf(val, fromIndex) : a.lastIndexOf(val); } : function(a, val, fromIndex) { var len = a.length, i = len - 1; if (fromIndex || fromIndex === 0) { i = Math.min(fromIndex < 0 ? len + fromIndex : fromIndex, len); } if (i > -1 && len > 0) { for (; i > -1; --i) { if (a[i] === val) { return i; } } } return -1; }; /** * Returns a copy of the specified array with duplicate items removed. * @method Array.unique * @param {Array} a Array to dedupe. * @return {Array} Copy of the array with duplicate items removed. * @static */ A.unique = function(a, sort) { // Note: the sort param is deprecated and intentionally undocumented since // YUI 3.3.0. It never did what the API docs said it did (see the older // comment below as well). var i = 0, len = a.length, results = [], item, j; for (; i < len; ++i) { item = a[i]; // This loop iterates over the results array in reverse order and stops // if it finds an item that matches the current input array item (a // dupe). If it makes it all the way through without finding a dupe, the // current item is pushed onto the results array. for (j = results.length; j > -1; --j) { if (item === results[j]) { break; } } if (j === -1) { results.push(item); } } // Note: the sort option doesn't really belong here... I think it was added // because there was a way to fast path the two operations together. That // implementation was not working, so I replaced it with the following. // Leaving it in so that the API doesn't get broken. if (sort) { if (L.isNumber(results[0])) { results.sort(A.numericSort); } else { results.sort(); } } return results; }; /** * Executes the supplied function on each item in the array. Returns a new array * containing the items for which the supplied function returned a truthy value. * @method Array.filter * @param {Array} a Array to filter. * @param {Function} f Function to execute on each item. * @param {Object} o Optional context object. * @static * @return {Array} Array of items for which the supplied function returned a * truthy value (empty if it never returned a truthy value). */ A.filter = Native.filter ? function(a, f, o) { return a.filter(f, o); } : function(a, f, o) { var i = 0, len = a.length, results = [], item; for (; i < len; ++i) { item = a[i]; if (f.call(o, item, i, a)) { results.push(item); } } return results; }; /** * The inverse of filter. Executes the supplied function on each item. * Returns a new array containing the items that the supplied * function returned *false* for. * @method Array.reject * @param {Array} a the array to iterate. * @param {Function} f the function to execute on each item. * @param {object} o Optional context object. * @static * @return {Array} The items on which the supplied function * returned false. */ A.reject = function(a, f, o) { return A.filter(a, function(item, i, a) { return !f.call(o, item, i, a); }); }; /** * Executes the supplied function on each item in the array. * Iteration stops if the supplied function does not return * a truthy value. * @method Array.every * @param {Array} a the array to iterate. * @param {Function} f the function to execute on each item. * @param {object} o Optional context object. * @static * @return {boolean} true if every item in the array returns true * from the supplied function. */ A.every = Native.every ? function(a, f, o) { return a.every(f, o); } : function(a, f, o) { for (var i = 0, l = a.length; i < l; ++i) { if (!f.call(o, a[i], i, a)) { return false; } } return true; }; /** * Executes the supplied function on each item in the array. * @method Array.map * @param {Array} a the array to iterate. * @param {Function} f the function to execute on each item. * @param {object} o Optional context object. * @static * @return {Array} A new array containing the return value * of the supplied function for each item in the original * array. */ A.map = Native.map ? function(a, f, o) { return a.map(f, o); } : function(a, f, o) { var i = 0, len = a.length, results = a.concat(); for (; i < len; ++i) { results[i] = f.call(o, a[i], i, a); } return results; }; /** * Executes the supplied function on each item in the array. * Reduce "folds" the array into a single value. The callback * function receives four arguments: * the value from the previous callback call (or the initial value), * the value of the current element, the current index, and * the array over which iteration is occurring. * @method Array.reduce * @param {Array} a the array to iterate. * @param {any} init The initial value to start from. * @param {Function} f the function to execute on each item. It * is responsible for returning the updated value of the * computation. * @param {object} o Optional context object. * @static * @return {any} A value that results from iteratively applying the * supplied function to each element in the array. */ A.reduce = Native.reduce ? function(a, init, f, o) { // ES5 Array.reduce doesn't support a thisObject, so we need to // implement it manually return a.reduce(function(init, item, i, a) { return f.call(o, init, item, i, a); }, init); } : function(a, init, f, o) { var i = 0, len = a.length, result = init; for (; i < len; ++i) { result = f.call(o, result, a[i], i, a); } return result; }; /** * Executes the supplied function on each item in the array, * searching for the first item that matches the supplied * function. * @method Array.find * @param {Array} a the array to search. * @param {Function} f the function to execute on each item. * Iteration is stopped as soon as this function returns true * on an item. * @param {object} o Optional context object. * @static * @return {object} the first item that the supplied function * returns true for, or null if it never returns true. */ A.find = function(a, f, o) { for (var i = 0, l = a.length; i < l; i++) { if (f.call(o, a[i], i, a)) { return a[i]; } } return null; }; /** * Iterates over an array, returning a new array of all the elements * that match the supplied regular expression * @method Array.grep * @param {Array} a a collection to iterate over. * @param {RegExp} pattern The regular expression to test against * each item. * @static * @return {Array} All the items in the collection that * produce a match against the supplied regular expression. * If no items match, an empty array is returned. */ A.grep = function(a, pattern) { return A.filter(a, function(item, index) { return pattern.test(item); }); }; /** * Partitions an array into two new arrays, one with the items * that match the supplied function, and one with the items that * do not. * @method Array.partition * @param {Array} a a collection to iterate over. * @param {Function} f a function that will receive each item * in the collection and its index. * @param {object} o Optional execution context of f. * @static * @return {object} An object with two members, 'matches' and 'rejects', * that are arrays containing the items that were selected or * rejected by the test function (or an empty array). */ A.partition = function(a, f, o) { var results = { matches: [], rejects: [] }; A.each(a, function(item, index) { var set = f.call(o, item, index, a) ? results.matches : results.rejects; set.push(item); }); return results; }; /** * Creates an array of arrays by pairing the corresponding * elements of two arrays together into a new array. * @method Array.zip * @param {Array} a a collection to iterate over. * @param {Array} a2 another collection whose members will be * paired with members of the first parameter. * @static * @return {array} An array of arrays formed by pairing each element * of the first collection with an item in the second collection * having the corresponding index. */ A.zip = function(a, a2) { var results = []; A.each(a, function(item, index) { results.push([item, a2[index]]); }); return results; }; /** * forEach is an alias of Array.each. This is part of the * collection module. * @method Array.forEach */ A.forEach = A.each; }, '3.3.0' ); YUI.add('arraylist', function(Y) { /** * Collection utilities beyond what is provided in the YUI core * @module collection * @submodule arraylist */ var YArray = Y.Array, YArray_each = YArray.each, ArrayListProto; /** * Generic ArrayList class for managing lists of items and iterating operations * over them. The targeted use for this class is for augmentation onto a * class that is responsible for managing multiple instances of another class * (e.g. NodeList for Nodes). The recommended use is to augment your class with * ArrayList, then use ArrayList.addMethod to mirror the API of the constituent * items on the list's API. * * The default implementation creates immutable lists, but mutability can be * provided via the arraylist-add submodule or by implementing mutation methods * directly on the augmented class's prototype. * * @class ArrayList * @constructor * @param items { Array } array of items this list will be responsible for */ function ArrayList( items ) { if ( items !== undefined ) { this._items = Y.Lang.isArray( items ) ? items : YArray( items ); } else { // ||= to support lazy initialization from augment this._items = this._items || []; } } ArrayListProto = { /** * Get an item by index from the list. Override this method if managing a * list of objects that have a different public representation (e.g. Node * instances vs DOM nodes). The iteration methods that accept a user * function will use this method for access list items for operation. * * @method item * @param i { Integer } index to fetch * @return { mixed } the item at the requested index */ item: function ( i ) { return this._items[i]; }, /** * <p>Execute a function on each item of the list, optionally providing a * custom execution context. Default context is the item.</p> * * <p>The callback signature is <code>callback( item, index )</code>.</p> * * @method each * @param fn { Function } the function to execute * @param context { mixed } optional override 'this' in the function * @return { ArrayList } this instance * @chainable */ each: function ( fn, context ) { YArray_each( this._items, function ( item, i ) { item = this.item( i ); fn.call( context || item, item, i, this ); }, this); return this; }, /** * <p>Execute a function on each item of the list, optionally providing a * custom execution context. Default context is the item.</p> * * <p>The callback signature is <code>callback( item, index )</code>.</p> * * <p>Unlike <code>each</code>, if the callback returns true, the * iteratation will stop.</p> * * @method some * @param fn { Function } the function to execute * @param context { mixed } optional override 'this' in the function * @return { Boolean } True if the function returned true on an item */ some: function ( fn, context ) { return YArray.some( this._items, function ( item, i ) { item = this.item( i ); return fn.call( context || item, item, i, this ); }, this); }, /** * Finds the first index of the needle in the managed array of items. * * @method indexOf * @param needle { mixed } The item to search for * @return { Integer } Array index if found. Otherwise -1 */ indexOf: function ( needle ) { return YArray.indexOf( this._items, needle ); }, /** * How many items are in this list? * * @method size * @return { Integer } Number of items in the list */ size: function () { return this._items.length; }, /** * Is this instance managing any items? * * @method isEmpty * @return { Boolean } true if 1 or more items are being managed */ isEmpty: function () { return !this.size(); }, /** * Provides an array-like representation for JSON.stringify. * * @method toJSON * @return { Array } an array representation of the ArrayList */ toJSON: function () { return this._items; } }; // Default implementation does not distinguish between public and private // item getter /** * Protected method for optimizations that may be appropriate for API * mirroring. Similar in functionality to <code>item</code>, but is used by * methods added with <code>ArrayList.addMethod()</code>. * * @method _item * @protected * @param i { Integer } Index of item to fetch * @return { mixed } The item appropriate for pass through API methods */ ArrayListProto._item = ArrayListProto.item; ArrayList.prototype = ArrayListProto; Y.mix( ArrayList, { /** * <p>Adds a pass through method to dest (typically the prototype of a list * class) that calls the named method on each item in the list with * whatever parameters are passed in. Allows for API indirection via list * instances.</p> * * <p>Accepts a single string name or an array of string names.</p> * * <pre><code>list.each( function ( item ) { * item.methodName( 1, 2, 3 ); * } ); * // becomes * list.methodName( 1, 2, 3 );</code></pre> * * <p>Additionally, the pass through methods use the item retrieved by the * <code>_item</code> method in case there is any special behavior that is * appropriate for API mirroring.</p> * * @method addMethod * @static * @param dest { Object } Object or prototype to receive the iterator method * @param name { String | Array } Name of method of methods to create */ addMethod: function ( dest, names ) { names = YArray( names ); YArray_each( names, function ( name ) { dest[ name ] = function () { var args = YArray( arguments, 0, true ), ret = []; YArray_each( this._items, function ( item, i ) { item = this._item( i ); var result = item[ name ].apply( item, args ); if ( result !== undefined && result !== item ) { ret.push( result ); } }, this); return ret.length ? ret : this; }; } ); } } ); Y.ArrayList = ArrayList; }, '3.3.0' ); YUI.add('arraylist-add', function(Y) { /** * Collection utilities beyond what is provided in the YUI core * @module collection * @submodule arraylist-add */ /** * Adds methods add and remove to Y.ArrayList * @class ArrayList~add */ Y.mix(Y.ArrayList.prototype, { /** * Add a single item to the ArrayList. Does not prevent duplicates. * * @method add * @param { mixed } item Item presumably of the same type as others in the * ArrayList. * @param {Number} index (Optional.) Number representing the position at * which the item should be inserted. * @return {ArrayList} the instance. * @chainable */ add: function(item, index) { var items = this._items; if (Y.Lang.isNumber(index)) { items.splice(index, 0, item); } else { items.push(item); } return this; }, /** * Removes first or all occurrences of an item to the ArrayList. If a * comparator is not provided, uses itemsAreEqual method to determine * matches. * * @method remove * @param { mixed } needle Item to find and remove from the list. * @param { Boolean } all If true, remove all occurrences. * @param { Function } comparator optional a/b function to test equivalence. * @return {ArrayList} the instance. * @chainable */ remove: function(needle, all, comparator) { comparator = comparator || this.itemsAreEqual; for (var i = this._items.length - 1; i >= 0; --i) { if (comparator.call(this, needle, this.item(i))) { this._items.splice(i, 1); if (!all) { break; } } } return this; }, /** * Default comparator for items stored in this list. Used by remove(). * * @method itemsAreEqual * @param { mixed } a item to test equivalence with. * @param { mixed } b other item to test equivalance. * @return { Boolean } true if items are deemed equivalent. */ itemsAreEqual: function(a, b) { return a === b; } }); }, '3.3.0' ,{requires:['arraylist']}); YUI.add('arraylist-filter', function(Y) { /** * Collection utilities beyond what is provided in the YUI core * @module collection * @submodule arraylist-filter */ /** * Adds filter method to ArrayList prototype * @class ArrayList~filter */ Y.mix(Y.ArrayList.prototype, { /** * <p>Create a new ArrayList (or augmenting class instance) from a subset * of items as determined by the boolean function passed as the * argument. The original ArrayList is unchanged.</p> * * <p>The validator signature is <code>validator( item )</code>.</p> * * @method filter * @param { Function } validator Boolean function to determine in or out. * @return { ArrayList } New instance based on who passed the validator. */ filter: function(validator) { var items = []; Y.Array.each(this._items, function(item, i) { item = this.item(i); if (validator(item)) { items.push(item); } }, this); return new this.constructor(items); } }); }, '3.3.0' ,{requires:['arraylist']}); YUI.add('array-invoke', function(Y) { /** * Collection utilities beyond what is provided in the YUI core * @module collection * @submodule array-invoke */ /** * Adds the <code>Y.Array.invoke( items, methodName )</code> utility method. * @class YUI~array~invoke */ /** * <p>Execute a named method on an array of objects. Items in the list that do * not have a function by that name will be skipped. For example, * <code>Y.Array.invoke( arrayOfDrags, 'plug', Y.Plugin.DDProxy );</code></p> * * <p>The return values from each call are returned in an array.</p> * * @method invoke * @static * @param { Array } items Array of objects supporting the named method. * @param { String } name the name of the method to execute on each item. * @param { mixed } args* Any number of additional args are passed as * parameters to the execution of the named method. * @return { Array } All return values, indexed according to item index. */ Y.Array.invoke = function(items, name) { var args = Y.Array(arguments, 2, true), isFunction = Y.Lang.isFunction, ret = []; Y.Array.each(Y.Array(items), function(item, i) { if (isFunction(item[name])) { ret[i] = item[name].apply(item, args); } }); return ret; }; }, '3.3.0' ); YUI.add('collection', function(Y){}, '3.3.0' ,{use:['array-extras', 'arraylist', 'arraylist-add', 'arraylist-filter', 'array-invoke']});
import { ContainerPreview, Content } from './styles'; import { LuClock3 } from 'react-icons/lu'; import { BiArrowBack } from 'react-icons/bi'; import { Header } from '../../components/Header'; import { Section } from '../../components/Section'; import { Tag } from '../../components/Tag'; import { Link } from 'react-router-dom'; import { api } from '../../services/api'; import { useState, useEffect } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import avatarPlaceHolder from '../../assets/userProfileDefault.png'; import { useAuth } from '../../hooks/auth'; export function Preview(){ const { user } = useAuth(); const [data, setData] = useState(null); const params = useParams(); const navigate = useNavigate(); const avatarUrl = user.avatar ? `${api.defaults.baseURL}/file/${user.avatar}` : avatarPlaceHolder; useEffect(()=>{ async function fetchMovie(){ const response = await api.get(`/movies/${params.id_movie}`); setData(response.data); } fetchMovie(); }, []); return( <ContainerPreview> <Header /> <Link to="/"> <BiArrowBack /> Voltar </Link> { data && <Content> <section> <h1>{ data.title }</h1> </section> <div className='wrappedUserData'> <img src={avatarUrl} alt="Imagem do usuario"/> <p>Por {user.username}</p> <LuClock3 /> <p>{user.created}</p> </div> { data.tags && <div className='wrappedTags'> { data.tags.map((tag, id)=>( <Tag key={id} title={tag.tagname} /> )) } </div> } <p>{ data.description }</p> </Content> } </ContainerPreview> ); }
from array import array from cmath import sqrt from datetime import datetime import numpy as np import copy import time import random class VectorOperator: def unesi_vektore_iz_fajla(self, broj_vektora, velicina_baze): vektori = [] with open('C:/Users/Tihomir/Documents/Faks/Zavrsni/.vscode/vektoriFile.txt') as file: for line in file: vektori.append(line.rstrip()) novi_vektor = [] novi_vektori = [] i = 0 for broj in range(len(vektori)): novi_vektor.append(vektori[broj]) i+=1 if int(i) == int(velicina_baze): novi_vektori.append(novi_vektor.copy()) novi_vektor.clear() i = 0 return novi_vektori def unesi_vektore(self, broj_vektora, velicina_baze): vektori = [] vektor = [] i = 0 j = 0 for broj in range(int(broj_vektora)): print("Unesi " + str(i+1) + ". vektor: ") for velicina in range(int(velicina_baze)): vrijednost = input("Unesi " + str(j+1) + ". dimenziju vektora: ") #vrijednost = random.randint(1, 10) vektor.append(vrijednost) j=j+1 vektori.append(vektor.copy()) vektor.clear() i=i+1 j=0 return vektori def normiraj_vektor(self, vektori): duljina = [] temp = [] normirani_vektor = [] for i in range(len(vektori)): duljina.append(np.linalg.norm(vektori[i])) for i in range(len(vektori)): for j in range(len(vektori[i])): temp.append(float(vektori[i][j])/float(duljina[i])) normirani_vektor.append(temp.copy()) temp.clear() return normirani_vektor def ispisi_vektore(self, vektori): for i in range(len(vektori)): print(str(vektori[i])) print(str(i+1) + ". vektor: " + str(vektori[i])) def gram_schmidtov_postupak_ortogonalizacije(self, vektori): e = [] ortogonalizirani_vektori = [] projekcija = [] temp = [] aux = [] for i in range(len(vektori)): if i==0: e.append(vektori[i]) ortogonalizirani_vektori.append(e[i]) else: for j in range(i): razlomak = VectorOperator.izracunaj_razlomak( self, vektori[i], e[j]) for k in range(len(vektori[i])): projekcija.append(float(razlomak)*float(e[j][k])) temp.append(projekcija.copy()) projekcija.clear() for j in range(len(vektori[i])): aux.append(vektori[i][j]) for j in range(i): for k in range(len(vektori[i])): aux[k] = float(aux[k]) - float(temp[j][k]) e.append(aux.copy()) ortogonalizirani_vektori.append(e[i]) temp.clear() aux.clear() return ortogonalizirani_vektori def izracunaj_razlomak(self, vektor, e): brojnik = np.dot(np.array(vektor, dtype=float), np.array(e, dtype=float)) nazivnik = np.dot(np.array(e, dtype=float), np.array(e, dtype=float)) return brojnik/nazivnik def dobij_gramovu_matricu(self, vektori): gramova_matrica = [] redak = [] for i in range(len(vektori)): for j in range(len(vektori)): redak.append(np.dot( np.array( vektori[i], dtype=float), np.array(vektori[j], dtype=float))) gramova_matrica.append(redak.copy()) redak.clear() return gramova_matrica vector_operator = VectorOperator() broj_vektora = input("Unesi broj vektora: ") velicina_baze = input("Unesi velicinu baze: ") vektori = vector_operator.unesi_vektore(broj_vektora, velicina_baze) gramova_matrica = vector_operator.dobij_gramovu_matricu(vektori) gramova_determinanta = '{:.2f}'.format(np.linalg.det(np.matrix(gramova_matrica, dtype=float))) print("Gramova matrica: ") print(gramova_matrica) if float(gramova_determinanta) == 0: print("Gramova determinanta: " + gramova_determinanta) print ("Vektori su linearno zavisni") exit(1) print("Gramova determinanta: " + gramova_determinanta) print("Uneseni vektori su linearno nezavisni") #vektori = vector_operator.unesi_vektore_iz_fajla(broj_vektora, velicina_baze) start = datetime.now() ortogonalizirani_vektori = vector_operator.gram_schmidtov_postupak_ortogonalizacije( vektori) print("Ortogonalizirani vektori: ") vector_operator.ispisi_vektore(ortogonalizirani_vektori) normirani_vektori = vector_operator.normiraj_vektor( ortogonalizirani_vektori) print("Ortonormirani vektori: ") vector_operator.ispisi_vektore(normirani_vektori) end = datetime.now() razlika = end-start time_diff = razlika.total_seconds()*1000 print("Vrijeme izvodenja programa: " + str(time_diff) + "[ms]")
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>组件嵌套</title> <script src="../js/vue.js"></script> </head> <body> <div id="root"> <app></app> </div> <script> //创建teacher组件 const teacher = Vue.extend({ template: ` <div> <h2>教师姓名:{{name}}</h2> <h2>教师年龄:{{age}}</h2> </div> `, data() { return { name: '马保国', age: 69 } } }) // 创建school组件 const school = Vue.extend({ template: ` <div> <h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <teacher></teacher> </div> `, data() { return { name: '浑元形意太极', address: '河南' } }, components: { teacher } }) //创建hello组件 const hello = Vue.extend({ template: `<h2>松果弹抖闪电鞭</h2>` }) //创建app组件 const app = Vue.extend({ template: ` <div> <hello></hello> <school></school> </div> `, components: { school, hello } }) new Vue({ el: '#root', //第二步:注册组件(局部) components: { app } }) </script> </body> </html>
# 로또 게임 ## 프로젝트 개요 프로젝트의 목표는 로또 게임을 구현하는 것이다. 로또 게임 프로그램은 사용자가 금액을 입력하면 해당 금액에 따라 로또를 발행하고, 사용자에게 당첨 번호와 보너스 번호를 입력받아 발행된 로또와 당첨 번호를 비교하여 당첨 내역 및 수익률을 계산한다. ## 구현 기능 목록 ### Model - - - **Lotto** - ✅ 6개의 번호를 가진 로또를 생성한다. - ✅ (E) 번호의 개수가 6개가 아닐 경우 예외를 발생시킨다. - ✅ (E) 번호의 범위가 1~45의 범위가 아닐 경우 예외를 발생시킨다. - ✅ (E) 중복된 번호가 있을 경우 예외를 발생시킨다. **Bonus** - ✅ 1개의 보너스 번호를 생성한다. - ✅ (E) 번호의 범위가 1~45의 범위가 아닐 경우 예외를 발생시킨다. - ✅ (E) 당첨 번호와 중복되었을 경우 예외를 발생시킨다. **Purchase** - ✅ 구매 금액을 생성한다. - ✅ (E) 유효하지 않은 금액 단위에 대해 예외를 발생시킨다. - 1,000원 단위 **Publisher** - ✅ 구입하려는 로또 개수만큼 로또를 발행한다. **WinningRank** - ✅ 당첨 번호 개수와 보너스 번호에 해당하는 등수를 찾는다. - 1등: 6개 번호 일치 / 2,000,000,000원 - 2등: 5개 번호 + 보너스 번호 일치 / 30,000,000원 - 3등: 5개 번호 일치 / 1,500,000원 - 4등: 4개 번호 일치 / 50,000원 - 5등: 3개 번호 일치 / 5,000원 **WinningRecord** - ✅ 당첨 내역을 기록한다. - ✅ 구매 로또와 당첨 로또를 비교해 일치하는 번호 개수를 계산한다. - ✅ 구매 로또와 보너스 번호를 비교한다. **ProfitRate** - ✅ 총 당첨 금액을 계산한다. - ✅ 수익률을 계산한다. - 소수점 둘째자리에서 반올림 ### View - - - **InputView** - ✅ 로또 구입 금액을 입력받는다. - ✅ (E) 유효하지 않은 입력에 대해 예외를 발생시킨다. - 빈 문자열 - 숫자가 아닌 문자 - ✅ 당첨 번호 6개를 입력받는다. - ✅ (E) 유효하지 않은 입력에 대해 예외를 발생시킨다. - 빈 문자열 - 구분자(,) 외 숫자가 아닌 문자 - ✅ 보너스 번호 1개를 입력받는다. - ✅ (E) 유효하지 않은 입력에 대해 예외를 발생시킨다. - 빈 문자열 - 숫자가 아닌 문자 **OutputView** - ✅ 발행한 로또 개수와 번호를 출력한다. - 각 로또 번호는 오름차순 정렬 - ✅ 당첨 내역을 출력한다. - 보너스 번호 없는 경우 - {당첨 번호 개수}개 일치 ({당첨 금액}원) - {당첨 개수}개 - 보너스 번호 있는 경우 - {당첨 번호 개수}개 일치, 보너스 볼 일치 ({당첨 금액}원) - {당첨 개수}개 - ✅ 수익률을 소수점 첫째 자리까지 출력한다. - ✅ 에러 메세지를 출력한다. - [ERROR] 접두사 포함한 메세지 출력 ### Controller - - - **LottoGame** - ✅ 로또 구입 금액 입력을 요청한다. - ✅ 구입 금액만큼 로또를 발행을 요청한다. - ✅ 구입한 로또 출력을 요청한다. - ✅ 당첨 번호를 입력 요청한다. - ✅ 보너스 번호를 입력 요청한다. - ✅ 당첨 내역 계산을 요청한다. - ✅ 당첨 내역 출력을 요청한다. - ✅ 수익률 계산을 요청한다. - ✅ 수익률 출력을 요청한다. - ✅ 입력 예외 발생 시 재입력을 요청한다.
// // SecureConfig.swift // FoursquareVenues // // Created by Dan Merlea on 03.09.2023. // import Foundation @propertyWrapper struct SecuredConfig { var key: String var value: String = "" init(_ value: String) { self.key = value } var wrappedValue: String { get { return readConfig(key: key) } set { value = newValue } } private func readConfig(key: String) -> String { guard let filePath = Bundle.main.path(forResource: "ApiConfig", ofType: "plist") else { fatalError("Couldn't find file 'ApiConfig.plist'.") } let plist = NSDictionary(contentsOfFile: filePath) guard let value = plist?.object(forKey: key) as? String else { fatalError("Couldn't find key '\(key)' in 'ApiConfig.plist'.") } return value } }
import React from "react"; import Card from "./Card"; // import { api } from '../utils/api'; import { CurrentUserContext } from "../contexts/CurrentUserContext"; function Main(props) { const currentUser = React.useContext(CurrentUserContext); return ( <main> <section className="profile"> <div className="profile__container"> <div className="profile__avatar-edit" type="button" title="Обновить аватар" onClick={props.onEditAvatar} > <img className="profile__avatar" alt="фото профиля" src={currentUser.avatar} /> </div> <div className="profile__info"> <h1 className="profile__name">{currentUser.name}</h1> <button className="profile__edit-button" type="button" aria-label="редактировать профиль" onClick={props.onEditProfile} ></button> <p className="profile__description">{currentUser.about}</p> </div> </div> <button className="profile__add-button" type="button" aria-label="добавить фотографию" onClick={props.onAddCard} ></button> </section> <section className="elements"> {props.cards.map((card, id) => ( <Card key={id} card={card} link={card.link} name={card.name} likes={card.likes.length} onCardClick={props.onCardClick} onCardLike={props.onCardLike} onCardDelete={props.onCardDelete} /> ))} </section> </main> ); } export default Main;
import { Directive, ElementRef, OnDestroy, OnInit, Renderer2, TemplateRef, ViewContainerRef } from '@angular/core'; import { GlobalPositionStrategy, Overlay, OverlayRef } from '@angular/cdk/overlay'; import { GhmDraggableDirective } from './ghm-draggable.directive'; import { ComponentPortal, Portal, TemplatePortal } from '@angular/cdk/portal'; @Directive({ selector: '[appGhmDraggableHelper]' }) export class GhmDraggableHelperDirective implements OnInit, OnDestroy { private overlayRef: OverlayRef; private positionStrategy = new GlobalPositionStrategy(); private startPosition: { x: number; y: number }; constructor( private ghmDraggableDirective: GhmDraggableDirective, private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef, private overlay: Overlay, private renderer: Renderer2 ) { console.log('init draggable helper.'); } ngOnInit(): void { this.ghmDraggableDirective.dragStart.subscribe(event => this.onDragStart(event)); this.ghmDraggableDirective.dragMove.subscribe(event => this.onDragMove(event)); this.ghmDraggableDirective.dragEnd.subscribe(event => this.onDragEnd(event)); const clientRect = this.ghmDraggableDirective.element.nativeElement.getBoundingClientRect(); this.overlayRef = this.overlay.create({ positionStrategy: this.positionStrategy, width: clientRect.width, height: clientRect.height }); } ngOnDestroy() { this.overlayRef.dispose(); } private onDragStart(event: PointerEvent) { const clientRect = this.ghmDraggableDirective.element.nativeElement.getBoundingClientRect(); // Get start position. this.startPosition = { x: event.clientX - clientRect.left, y: event.clientY - clientRect.top }; } private onDragMove(event: PointerEvent) { if (!this.overlayRef.hasAttached()) { this.overlayRef.attach(new TemplatePortal(this.templateRef, this.viewContainerRef)); // this.overlayRef.attach(new Portal<ElementRef>(this.ghmDraggableDirective.element, this.viewContainerRef)); } this.positionStrategy.left(`${event.clientX - this.startPosition.x}px`); this.positionStrategy.top(`${event.clientY - this.startPosition.y}px`); this.positionStrategy.apply(); } private onDragEnd(event: PointerEvent) { this.overlayRef.detach(); // this.viewContainerRef.clear(); } }
/* *********************************************** 단일행 함수: - 행별로 처리하는 함수. 문자/숫자/날짜/변환 함수 - 단일행은 select, where절에 사용가능 다중행 함수: - 여러행을 묶어서 한번에 처리하는 함수 => 집계함수, 그룹함수라고 한다. - 다중행은 where절에는 사용할 수 없다. (sub query 이용) * ***********************************************/ /* *************************************************************************************************************** # 함수 - 문자열관련 함수 char_length(v) - v의 글자수 반환 concat(v1, v2[, ..]) - 값들을 합쳐 하나의 문자열로 반환 format(숫자, 소수부 자릿수) - 정수부에 단위 구분자 "," 를 표시하고 지정한 소수부 자리까지만 문자열로 만들어 반환 upper(v), lower(v) - v를 모두 대문자/소문자 로 변환 insert(기준문자열, 위치, 길이, 삽입문자열): 위치기준으로 변경. 기준문자열의 위치(1부터 시작)에서부터 길이까지 지우고 삽입문자열을 넣는다. replace(기준문자열, 원래문자열, 바꿀문자열): 문자열기준으로 변경. 기준문자열의 원래문자열을 바꿀문자열로 바꾼다. left(기준문자열, 길이), right(기준문자열, 길이): 기준문자열에서 왼쪽(left), 오른쪽(right)의 길이만큼의 문자열을 반환한다. substring(기준문자열, 시작위치, 길이): 기준문자열에서 시작위치부터 길이 개수의 글자 만큼 잘라서 반환한다. 길이를 생략하면 마지막까지 잘라낸다. substring_index(기준문자열, 구분자, 개수): 기준문자열을 구분자를 기준으로 나눈 뒤 개수만큼 반환. 개수: 양수 – 앞에서 부터 개수, 음수 – 뒤에서 부터 개수만큼 반환 ltrim(문자열), rtrim(문자열), trim(문자열): 문자열에서 왼쪽(ltrim), 오른쪽(rtrim), 양쪽(trim)의 공백을 제거한다. 중간공백은 유지 trim(방향 제거할문자열 from 기준문자열): 기준문자열에서 방향에 있는 제거할문자열을 제거한다. 방향: both (앞,뒤), leading (앞), trailing (뒤) lpad(기준문자열, 길이, 채울문자열), rpad(기준문자열, 길이, 채울문자열): 기준문자열을 길이만큼 늘린 뒤 남는 길이만큼 채울문자열로 왼쪽(lpad), 오른쪽(rpad)에 채운다. 기준문자열 글자수가 길이보다 많을 경우 나머지는 자른다. *************************************************************************************************************** */ SELECT char_length('abcdefg'); -- 글자수 SELECT upper('aaaaa'), lower('AAAAA'); -- 대소문자 변환 SELECT format(312001000, 0); SELECT concat('$', format(1020202.982929, 3)); SELECT replace('aaaabbbcccddd', 'aaa', 'AAA'); SELECT left('1234567890', 5); -- 왼쪽(앞에서) 5글자만 조회 SELECT right('1234567890', 5); -- 오른쪽(뒤에서) 5글자만 조회 SELECT substring('1234567890', 4, 3); -- 4번째부터 3글자 SELECT mid('1234567890', 4, 3); -- 4번째부터 3글자 SELECT char_length(' 123 '); -- 공백 제거 SELECT char_length(trim(' 123 ')); SELECT char_length(rtrim(' 123 ')); SELECT char_length(ltrim(' 123 ')); SELECT LPAD('abc', 10, '+'); -- 글자수를 10에 맞춘다. 모자라면 왼쪽에 +를 붙인다. SELECT RPAD('abc', 10, '+'); SELECT LPAD(30, 10, '+'); -- 대상이 꼭 문자열이 아니어도 됨. SELECT LPAD('abcdef', 3, '+'); -- 모자라면 채우고 남으면 제거. -- EMP 테이블에서 직원의 이름(emp_name)을 모두 대문자, 소문자, 이름 글자수를 조회 SELECT emp_name, UPPER(emp_name), LOWER(emp_name), CHAR_LENGTH(emp_name) FROM emp ORDER BY 4; -- char_length(emp_name); -- TODO: EMP 테이블에서 직원의 ID(emp_id), 이름(emp_name), 급여(salary),부서(dept_name)를 조회. -- 단 직원이름(emp_name)은 모두 대문자, 부서(dept_name)는 모두 소문자로 출력. SELECT emp_id, UPPER(emp_name), salary, LOWER(dept_name) FROM emp; -- TODO: 직원 이름(emp_name) 의 자릿수를 15자리로 맞추고 15자가 안되는 이름의 경우 공백을 앞에 붙여 조회. SELECT LPAD(emp_name, 15, ' ') "emp_name" FROM emp; -- TODO: EMP 테이블에서 이름(emp_name)이 10글자 이상인 직원들의 이름(emp_name)과 이름의 글자수 조회 SELECT emp_name, CHAR_LENGTH(emp_name) as '글자수' FROM emp WHERE CHAR_LENGTH(emp_name) >= 10; /* ************************************************************************** - 숫자관련 함수 abs(값): 절대값 반환 round(값, 자릿수): 자릿수이하에서 반올림 (양수 - 실수부, 음수 - 정수부, 기본값: 0-0이하에서 반올림이므로 정수로 반올림) truncate(값, 자릿수): 자릿수이하에서 절삭-버림(자릿수: 양수 - 실수부, 음수 - 정수부, 기본값: 0) ceil(값): 값보다 큰 정수중 가장 작은 정수. 소숫점 이하 올린다. floor(값): 값보다 작은 정수중 가장 작은 정수. 소숫점 이하를 버린다. 내림 sign(값): 숫자 n의 부호를 정수로 반환(1-양수, 0, -1-음수) mod(n1, n2): n1 % n2 ************************************************************************** */ SELECT ABS(10), ABS(- 10); SELECT SIGN(10), SIGN(0), SIGN(- 100); -- 반올림: round() SELECT ROUND(50.12345, 3); -- 3자리 이하에서 반올림 SELECT ROUND(50.12345, 0); -- 정수 => 0을 기본값 SELECT ROUND(50.12345); SELECT ROUND(987654, -3); -- 음수 -> 정수부 자릿수 SELECT TRUNCATE(50.9999, 2); SELECT TRUNCATE(50.9999, 0); SELECT TRUNCATE(15550.9999, - 2); -- TODO: EMP 테이블에서 각 직원에 대해 직원ID(emp_id), 이름(emp_name), 급여(salary) 그리고 15% 인상된 급여(salary)를 조회하는 질의를 작성하시오. -- (단, 15% 인상된 급여는 올림해서 정수로 표시하고, 별칭을 "SAL_RAISE"로 지정.) select emp_id, emp_name, salary, ceil(salary * 1.15) "SAL_RAISE" from emp; -- TODO: 위의 SQL문에서 인상 급여(sal_raise)와 급여(salary) 간의 차액을 추가로 조회 -- (직원ID(emp_id), 이름(emp_name), 15% 인상급여, 인상된 급여와 기존 급여(salary)와 차액) select emp_id, emp_name, ceil(salary * 1.15) 'SAL_RAISE', ceil(salary * 1.15) - salary '차액' -- salary * 0.15 from emp; -- TODO: EMP 테이블에서 커미션이 있는 직원들의 직원_ID(emp_id), 이름(emp_name), 커미션비율(comm_pct), 커미션비율(comm_pct)을 8% 인상한 결과를 조회. -- (단 커미션을 8% 인상한 결과는 소숫점 이하 2자리에서 반올림하고 별칭은 comm_raise로 지정) select emp_id, emp_name, comm_pct, comm_pct * 1.08 as 'comm_riase' from emp where comm_pct is not null; /* *************************************************************************************************************** - 날짜관련 함수 now(): 현재 datetime curdate(): 현재 date curtime(): 현재 time year(날짜), month(날짜), day(날짜): 날짜 또는 일시의 년, 월, 일 을 반환한다. hour(시간), minute(시간), second(시간), microsecond(시간): 시간 또는 일시의 시, 분, 초, 밀리초를 반환한다. date(), time(): datetime 에서 날짜(date), 시간(time)만 추출한다. 날짜 연산 adddate/subdate(DATETIME/DATE/TIME, INTERVAL 값 단위) - 날짜에서 특정 일시만큼 더하고(add) 빼는(sub) 함수. - 단위: MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER(분기-3개월), YEAR datediff(날짜1, 날짜2): 날짜1 – 날짜2한 일수를 반환 timediff(시간1, 시간2): 시간1-시간2 한 시간을 계산해서 반환 (뺀 결과를 시:분:초 로 반환) dayofweek(날짜): 날짜의 요일을 정수로 반환 (1: 일요일 ~ 7: 토요일) date_format(일시, 형식문자열): 일시를 원하는 형식의 문자열로 반환 *************************************************************************************************************** */ -- 실행시점의 일/시를 조회 함수 SELECT NOW(); SELECT CURDATE(); SELECT CURTIME(); -- insert into xxxxx () values (curdate()); -- 날짜 타입에서 년 월 일 조회 SELECT CURDATE(), YEAR(CURDATE()), MONTH(CURDATE()), DAY(CURDATE()); -- 시간 타입에서 시 분 초 조회 SELECT HOUR(CURTIME()), MINUTE(CURTIME()), SECOND(CURTIME()); -- SELECT hour(curdate()); -- year(), month(), day(): datetime, timestamp, date (time(X)) -- hour(), minute(), second(): datetime, timestamp, time (date(X)) SELECT month(hire_date) FROM emp; -- 특정 기간 만큼 전,후의 일시를 조회 -- 오늘 기준 3일 후 날짜 SELECT ADDDATE(CURDATE(), INTERVAL 3 DAY); SELECT ADDDATE(NOW(), INTERVAL 3 DAY); -- 2년 전 날짜 SELECT SUBDATE(CURDATE(), INTERVAL 2 YEAR); SELECT ADDDATE(NOW(), INTERVAL -2 YEAR); -- 2년 5개월 후의 날짜 SELECT ADDDATE(NOW(), INTERVAL '2-5' YEAR_MONTH); -- 35시간 25분 전 SELECT SUBDATE(NOW(), INTERVAL '35:25' HOUR_MINUTE); SELECT DATEDIFF(CURDATE(), '2024-01-10'); -- 두 날짜의 일수 차이 SELECT TIMEDIFF(CURTIME(), '12:30:20'); SELECT DAYOFWEEK(NOW()); SELECT DAYOFWEEK('2000-10-21'); -- 형식 문자: %로 시작 SELECT DATE_FORMAT(NOW(), '%Y년 %m월 %d일 %H시 %i분 %s초 %W %p'); SELECT DATE_FORMAT(NOW(), '%Y%m%d%H%i%s'); -- TODO: EMP 테이블에서 부서이름(dept_name)이 'IT'인 직원들의 '입사일(hire_date)로 부터 10일전', 입사일, '입사일로 부터 10일 후' 의 날짜를 조회. -- select adddate(hire_date, interval -10 day), hire_date, adddate(hire_date, interval 10 day) select subdate(hire_date, interval 10 day), adddate(hire_date, interval - 10 day) '10일 전', hire_date '입사일', adddate(hire_date, interval 10 day) '10일 후' from emp where dept_name = 'IT'; -- TODO: 부서가 'Purchasing' 인 직원의 이름(emp_name), 입사 6개월전과 입사일(hire_date), 6개월후 날짜를 조회. select emp_name, subdate(hire_date, interval 6 month), -- adddate(hire_date, interval - 6 month), hire_date, adddate(hire_date, interval 6 month) from emp where dept_name = 'Purchasing'; -- TODO ID(emp_id)가 200인 직원의 이름(emp_name), 입사일(hire_date)를 조회. 입사일은 yyyy년 mm월 dd일 형식으로 출력. select emp_name, date_format(hire_date, '%Y년 %m월 %d일'), concat('$', format(salary, 2)) as 'salary' from emp where emp_id = 200; -- TODO: 각 직원의 이름(emp_name), 근무 개월수 (입사일에서 현재까지의 달 수)를 계산하여 조회. 근무개월수 내림차순으로 정렬. select emp_name, datediff(curdate(), hire_date) as '근무일수', timestampdiff(day, hire_date, curdate()) as "근무일수", timestampdiff(month, hire_date, curdate()) as "근무개월수" -- timestampdiff (계산할 대상, 시작일시, 끝일시) from emp order by 4 desc; /* ************************************************************************************* 함수 - 조건 처리함수 ifnull (기준컬럼(값), 기본값): 기준컬럼(값)이 NULL값이면 기본값을 출력하고 NULL이 아니면 기준컬럼 값을 출력 if (조건수식, 참, 거짓): 조건수식이 True이면 참을 False이면 거짓을 출력한다. ************************************************************************************* */ SELECT IFNULL('a', 0); -- 값('a')이 null면 0을 반환 SELECT IFNULL(null, 0); -- 값이 null 이면 0을 반환 SELECT IFNULL(comm_pct, 0) * salary FROM emp WHERE emp_id = 100; -- TODO: EMP 테이블에서 직원의 ID(emp_id), 이름(emp_name), 업무(job), 부서(dept_name)을 조회. 부서가 없는 경우 '부서미배치'를 출력. select emp_id, emp_name, job, ifnull(dept_name, '부서미배치') 'dept_name' from emp order by dept_name desc; -- TODO: EMP 테이블에서 직원의 ID(emp_id), 이름(emp_name), 급여(salary), 커미션 (salary * comm_pct)을 조회. 커미션이 없는 직원은 0이 조회되록 한다. select emp_id, emp_name, salary, ifnull(salary * comm_pct, 0) "커미션" from emp; SELECT CAST(10 AS SIGNED); SELECT CONVERT(10 , SIGNED); /*********************************************** 함수 - 타입변환함수 cast(값 as 변환할타입) convert(값, 변환할타입) 변환가능 타입 - BINARY: binary 데이터로 변환 (blob) - SIGNED: 부호있는 정수(64bit) - UNSIGNED: 부호없는 정수(64bit) - DECIMAL: 실수 - CHAR: 문자열 타입 - DATE: 날짜 - TIME: 시간 - DATATIME: 날짜시간 타입 - 정수를 날짜, 시간타입으로 변환할 때는 양수만 가능. (음수는 NULL 반환) ***********************************************/ -- 시간을 정수형태로 변환 SELECT '10' + 10; SELECT CAST(NOW() AS SIGNED); -- 2024/01/12 14:25:21 SELECT CONVERT(CURDATE() , SIGNED); -- 숫자를 날짜로 변환 SELECT CAST(20231231 AS DATE); SELECT CONVERT(20231231 , date); SELECT CAST('2023-12-31' AS DATE); SELECT * FROM emp WHERE hire_date = CAST('2003-06-17' AS DATE); -- 타입 변환작업이 묵시적으로 처리된다. SELECT DATEDIFF(NOW(), CAST('2023-10-20' AS DATE)); -- 숫자를 문자열로 변환 SELECT CAST(2000 AS CHAR); SELECT CONCAT(2000, '원'); SELECT CAST('1000' AS SIGNED) + 3000; SELECT '1000' + 3000; /* ************************************* CASE 문 case문 동등비교 case 컬럼 when 비교값 then 출력값 [when 비교값 then 출력값] [else 출력값] end case문 조건문 case when 조건 then 출력값 [when 조건 then 출력값] [else 출력값] end ************************************* */ /* dept_name이 'IT'면 '전산실' 출력 'Finance'면 '회계부' 출력 'Sales'면 '영업부' 출력 나머지는 그대로 출력; */ SELECT CASE dept_name WHEN 'IT' THEN '전산실' WHEN 'FINAnce' THEN '회계부' WHEN ' Sales' THEN '영업부' ELSE IFNULL(dept_name, '미배치') END AS "부서" FROM EMP; -- Sales이면 '영업부' 나머지는 그대로; SELECT IF(dept_name = 'Sales', '영업부', dept_name) AS "부서명" FROM emp; -- EMP테이블에서 급여와 급여의 등급을 조회하는데 급여 등급은 10000이상이면 '1등급', 10000미만이면 '2등급' 으로 나오도록 조회 SELECT salary, CASE WHEN salary >= 10000 THEN "1등급" WHEN salary < 10000 THEN "2등급" END AS "급여등급1", CASE WHEN salary >= 10000 THEN "1등급" ELSE "2등급" END AS "급여등급2" FROM emp; SELECT salary, IF(salary >= 10000, "1등급", "2등급") AS "등급" FROM emp; -- case dept_name when null then "a" (X) -- case when dept_name is null then "a", ifnull -- TODO: EMP 테이블에서 업무(job)이 'AD_PRES'거나 'FI_ACCOUNT'거나 'PU_CLERK'인 직원들의 ID(emp_id), 이름(emp_name), 업무(job)을 조회. -- 업무(job)가 'AD_PRES'는 '대표', 'FI_ACCOUNT'는 '회계', 'PU_CLERK'의 경우 '구매'가 출력되도록 조회 select emp_id, emp_name, case job when 'AD_PRES' then '대표' when 'FI_ACCOUNT' then '회계' else '구매' end 'job' from emp where job IN ('AD_PRES' , 'FI_ACCOUNT', 'PU_CLERK'); -- TODO: EMP 테이블에서 부서이름(dept_name)과 급여 인상분을 조회. -- 급여 인상분은 부서이름이 'IT' 이면 급여(salary)에 10%를 'Shipping' 이면 급여(salary)의 20%를 'Finance'이면 30%를 나머지는 0을 출력 select dept_name, case dept_name when 'IT' then salary * 0.1 when 'Shipping' then salary * 0.2 when 'Finance' then salary * 0.3 else 0 end 'raise' from emp; -- TODO: EMP 테이블에서 직원의 ID(emp_id), 이름(emp_name), 급여(salary), 인상된 급여를 조회한다. -- 단 급여 인상율은 급여가 5000 미만은 30%, 5000이상 10000 미만는 20% 10000 이상은 10% 로 한다. SELECT emp_id, emp_name, salary, CASE when salary < 5000 then salary * 0.3 WHEN salary BETWEEN 5000 AND 9999.99 THEN salary * 0.2 ELSE salary * 0.1 END 'raise' FROM emp ORDER BY 4 DESC;
#include "Pipeline.h" #include <QDebug> #include <gst/video/videooverlay.h> void Pipeline::handle_pipeline_message(GstMessage* msg) { GError* err; gchar* debug_info; switch (GST_MESSAGE_TYPE(msg)) { case GST_MESSAGE_INFO: gst_message_parse_info(msg, &err, &debug_info); qInfo() << QString("Info from %1: %2\n").arg( GST_OBJECT_NAME(msg->src), err->message); qInfo() << QString("Debugging information: %1\n").arg(debug_info ? debug_info : "none"); g_clear_error(&err); g_free(debug_info); break; case GST_MESSAGE_WARNING: gst_message_parse_warning(msg, &err, &debug_info); qWarning() << QString("Warning from %1: %2\n").arg(GST_OBJECT_NAME(msg->src), err->message); qWarning() << QString("Debugging information: %1\n").arg(debug_info ? debug_info : "none"); g_clear_error(&err); g_free(debug_info); break; case GST_MESSAGE_ERROR: gst_message_parse_error(msg, &err, &debug_info); qCritical() << QString("Error from %1: %2\n").arg(GST_OBJECT_NAME(msg->src), err->message); qCritical() << QString("Debugging information: %1\n").arg(debug_info ? debug_info : "none"); g_clear_error(&err); g_free(debug_info); break; case GST_MESSAGE_EOS: qCritical() << ("\nEnd-Of-Stream reached!\n"); break; case GST_MESSAGE_STATE_CHANGED: { GstState old_state, new_state, pending_state; gst_message_parse_state_changed(msg, &old_state, &new_state, &pending_state); GstObject* sender = GST_MESSAGE_SRC(msg); qInfo() << "Element " << GST_ELEMENT_NAME(GST_ELEMENT(sender)) << " state changed from" << gst_element_state_get_name(old_state) << " to " << gst_element_state_get_name(new_state); } break; default: /* We should not reach here */ // g_printerr("Unexpected message received.\n"); break; } } Pipeline::Pipeline(int port, WId windowHandle) { //gst_debug_set_active(true); //gst_debug_set_default_threshold(GST_LEVEL); this->port = port; this->windowHandle = windowHandle; } Pipeline::~Pipeline() { if (gst_pipeline) { GstState state = GstState::GST_STATE_NULL; GstStateChangeReturn state_ret = gst_element_get_state(gst_pipeline, &state, NULL, 0); if (state_ret != GstStateChangeReturn::GST_STATE_CHANGE_SUCCESS) { qWarning() << "[~Pipeline] Failed to get pipeline's state"; } else if (state != GstState::GST_STATE_NULL) { qDebug() << "[~Pipeline] Setting pipeline to NULL state..."; GstStateChangeReturn ret = gst_element_set_state(gst_pipeline, GstState::GST_STATE_NULL); if (ret != GstStateChangeReturn::GST_STATE_CHANGE_SUCCESS) { qCritical() << "[~Pipeline] Failed to set pipeline to NULL state!"; } else { qCritical() << "[~Pipeline] Pipeline set to NULL state successfully!"; } } gst_object_unref(gst_pipeline); } if (gst_bus) { gst_object_unref(gst_bus); } } bool Pipeline::constructPipeline(QString pipelineStr) { gst_pipeline = gst_parse_launch(pipelineStr.toStdString().c_str(), NULL); if (!gst_pipeline) { return false; } gst_bus = gst_element_get_bus(gst_pipeline); Q_ASSERT(gst_bus); GstElement* udpsrc = gst_bin_get_by_name(GST_BIN(gst_pipeline), "udpsrc"); Q_ASSERT(udpsrc); g_object_set(udpsrc, "port", port, NULL); GstElement* videosink = gst_bin_get_by_name(GST_BIN(gst_pipeline), "videosink"); Q_ASSERT(videosink); gst_video_overlay_set_window_handle(GST_VIDEO_OVERLAY(videosink), windowHandle); return true; } bool Pipeline::constructPipeline() { qDebug() << "Trying to construct pipeline automatically"; // QString launchStr = "udpsrc name=udpsrc ! application/x-rtp,clock-rate=90000,payload=96 ! rtph264depay ! decodebin ! video/x-raw(memory:D3D11Memory) ! d3d11videosink name=videosink"; QString launchStr = "udpsrc name=udpsrc ! application/x-rtp,clock-rate=90000,payload=96 ! queue ! rtph264depay ! avdec_h264 ! d3d11videosink name=videosink"; if (constructPipeline(launchStr)) { return true; } qWarning() << "Failed to autoconstruct pipeline"; GError* error; //QString launchStr = QString("udpsrc name=udpsrc port=%1 ! application/x-rtp,clock-rate=90000,payload=96 ! rtph264depay ! avdec_h264 ! glimagesink name=glimagesink").arg(port); //gst_pipeline = gst_parse_launch(launchStr.toStdString().c_str(), NULL); gst_pipeline = gst_pipeline_new("main-pipeline"); Q_ASSERT(gst_pipeline); GstElement* udpsrc = gst_element_factory_make("udpsrc", "udpsrc"); Q_ASSERT(udpsrc); g_object_set(udpsrc, "port", port, NULL); GstElement* capsfilter = gst_element_factory_make("capsfilter", NULL); Q_ASSERT(capsfilter); GstCaps* caps = gst_caps_new_simple( "application/x-rtp", "clock-rate", G_TYPE_INT, 90000, "payload", G_TYPE_STRING, "video", NULL); g_object_set(capsfilter, "caps", caps, NULL); GstElement* rtph264depay = gst_element_factory_make("rtph264depay", "rtph264depay"); Q_ASSERT(rtph264depay); GstElement* decoder = gst_element_factory_make("avdec_h264", "avdec_h264"); Q_ASSERT(decoder); GstElement* videosink = gst_element_factory_make("glimagesink", "videosink"); Q_ASSERT(videosink); gst_bin_add_many(GST_BIN(gst_pipeline), udpsrc, capsfilter, rtph264depay, decoder, videosink, NULL); if (!gst_element_link_many(udpsrc, capsfilter, rtph264depay, decoder, videosink, NULL)) { return false; } gst_bus = gst_element_get_bus(gst_pipeline); Q_ASSERT(gst_bus); gst_video_overlay_set_window_handle(GST_VIDEO_OVERLAY(videosink), windowHandle); return gst_pipeline; } void Pipeline::setPort(int port) { Q_ASSERT(gst_pipeline); GstElement* udpsrc = gst_bin_get_by_name(GST_BIN(gst_pipeline), "udpsrc"); Q_ASSERT(udpsrc); g_object_set(udpsrc, "port", port, NULL); } bool Pipeline::startPipeline() { Q_ASSERT(gst_pipeline); GstStateChangeReturn set_state_code = gst_element_set_state(gst_pipeline, GST_STATE_PLAYING); if (set_state_code == GST_STATE_CHANGE_FAILURE) { qCritical() << "Failed to set the pipeline to the playing state!"; return false; } qInfo() << "Pipeline successfully set to PLAYING state with result code:" << set_state_code; return true; } bool Pipeline::stopPipeline() { Q_ASSERT(gst_pipeline); GstStateChangeReturn set_state_code = gst_element_set_state(gst_pipeline, GST_STATE_NULL); if (set_state_code == GST_STATE_CHANGE_FAILURE) { qCritical() << "Failed to set the pipeline to the NULL state!"; return false; } qInfo() << "Pipeline successfully set to NULL state with result code: " << set_state_code; return true; } bool Pipeline::isPipelinePlaying() const { Q_ASSERT(gst_pipeline); GstState current; GstState pending; if (gst_element_get_state(gst_pipeline, &current, &pending, 100) == GstStateChangeReturn::GST_STATE_CHANGE_FAILURE) { qCritical() << "Failed to get pipeline state!"; return false; } return current == GST_STATE_PLAYING; } void Pipeline::busPoll() { if (!gst_bus) { qCritical() << ("Cannot poll buss, it is nullptr!"); return; } GstMessage* message = gst_bus_pop_filtered(gst_bus, (GstMessageType)( GST_MESSAGE_INFO | GST_MESSAGE_WARNING | GST_MESSAGE_ERROR | GST_MESSAGE_EOS | GST_MESSAGE_STATE_CHANGED)); if (message) { handle_pipeline_message(message); } }
/****************************************************************************** * @file export_format_combobox.h ** @author DS Caskey ** @date Mar 15, 2022 ** ** @brief ** @copyright ** ** Seamly2D is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** Seamly2D 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 Seamly2D. If not, see <http://www.gnu.org/licenses/>. ** *****************************************************************************/ #ifndef EXPORT_FORMAT_COMBOBOX_H #define EXPORT_FORMAT_COMBOBOX_H #include <QComboBox> #include <QWidget> #include "../vmisc/def.h" #include "../ifc/xml/vabstractpattern.h" /** * A comboBox for choosing an export format type. */ class ExportFormatCombobox: public QComboBox { Q_OBJECT public: ExportFormatCombobox(QWidget *parent = nullptr, const char *name = nullptr); virtual ~ExportFormatCombobox(); void init(); LayoutExportFormat getExportFormat() const; void setExportFormat(LayoutExportFormat &format); static QString exportFormatDescription(LayoutExportFormat format); static QString makeHelpFormatList(); void setCurrentToDefault(); private slots: void updateExportFormat(int index); signals: void exportFormatChanged(const LayoutExportFormat &format); private: static QVector<std::pair<QString, LayoutExportFormat> > initFormats(); static bool supportPSTest(); static bool testPdf(); static bool havePdf; static bool tested; LayoutExportFormat m_currentFormat; }; #endif //EXPORT_FORMAT_COMBOBOX_H
package net.janci.zoregano.core; import net.janci.zoregano.api.BIOS; import net.janci.zoregano.api.BIOSModule; import net.janci.zoregano.concurrent.NamedThreadFactory; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; /** * Default implementation for {@link BIOS} interface. * * @see BIOS */ public class BIOSImpl implements BIOS { private String[] args; private ExecutorService moduleLoaderExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("bios-module")); private List<BIOSModule> loadedBIOSModules; private CountDownLatch latch; BIOSImpl(String[] args) { this.args = args; ServiceLoader<BIOSModule> biosModules = ServiceLoader.load(BIOSModule.class); loadedBIOSModules = biosModules.stream() .map(ServiceLoader.Provider::get) .collect(Collectors.toList()); } /** * {@inheritDoc} */ @Override public void loadBIOSModules() { latch = new CountDownLatch(loadedBIOSModules.size()); loadedBIOSModules.parallelStream() .forEach(module -> moduleLoaderExecutor.execute(() -> { module.load(args); latch.countDown(); })); } /** * {@inheritDoc} */ @Override public void awaitToStartKernel() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } /** * {@inheritDoc} */ @Override public void terminate() { loadedBIOSModules.parallelStream().forEach(BIOSModule::unload); } }
import { VStack, Image, Text as ChakraText, Heading, Card, CardHeader, CardBody, Skeleton, SkeletonText, Button, } from "@chakra-ui/react"; import { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import { useTheme } from "../../assets/context/theme.context.js"; import { useServer } from "../../assets/context/server.context.js"; import useSearchFetching from "../../services/search.service.js"; import "../../assets/styles/style.css"; import { vietnameseToSlug } from "../../utils/function.js"; function Search({ title }) { const { selectedServer } = useServer(); const [storyData, setStoryData] = useState([]); const [page, setPage] = useState(1); const [fetching, setFetching] = useState(false); // Remove ":" from title title = title.replace(/:/g, ""); // Fetch data for the current page const { data, loading } = useSearchFetching( `/${selectedServer}/search/${title}?page=${page}` ); useEffect(() => { if (data && data.length > 0) { setStoryData((prevData) => [...prevData, ...data.slice(0, 12)]); } }, [data]); useEffect(() => { setFetching(loading); }, [loading]); const navigate = useNavigate(); const handleClick = (id) => { console.log("Item Click:", id); navigate(`/detail/${id}/${vietnameseToSlug(title)}`); }; const loadMore = () => { if (!fetching) { setPage((prevPage) => prevPage + 1); } }; const { theme } = useTheme(); return ( <> <VStack spacing={4} align="stretch" style={{ padding: "100px 50px 50px 50px" }} > <Heading size="lg" mb={4} style={{ color: "#13ABA2", textDecoration: "underline", textUnderlineOffset: "8px", }} > Kết quả tìm kiếm cho từ "{title}" </Heading> {fetching && page === 1 ? Array.from({ length: 12 }).map((_, index) => ( <Card key={index} bg={theme === "dark" ? "#DDF2FD" : "#1D3557"} color={theme === "dark" ? "#000" : "#fff"} style={{ display: "flex", flexDirection: "row", alignItems: "center", textAlign: "left", position: "relative", width: "60%", margin: "0 auto", }} > <CardHeader style={{ paddingRight: "10px" }}> <Skeleton height="200px" width="200px" borderRadius="lg" /> </CardHeader> <CardBody style={{ flex: 1, padding: "5px" }}> <SkeletonText mt="4" noOfLines={1} spacing="4" /> </CardBody> </Card> )) : storyData.map((item, index) => ( <Card className="card" key={index} bg={theme === "dark" ? "#DDF2FD" : "#1D3557"} color={theme === "dark" ? "#000" : "#fff"} style={{ display: "flex", flexDirection: "row", alignItems: "center", textAlign: "left", position: "relative", width: "60%", margin: "0 auto", }} onClick={() => handleClick( item.id, item.titleUrl ? item.titleUrl : item.title ) } > <CardHeader style={{ padding: "15px" }}> <Image src={item.image} alt={item.title} borderRadius="lg" width="80px" height="80px" style={{ border: "1px solid #053B50" }} className="card-image" onError={(e) => { e.target.onerror = null; // Prevents infinite loop in case the fallback image also fails e.target.src = `${process.env.PUBLIC_URL}/images/default-image.jpg`; }} /> </CardHeader> <CardBody style={{ flex: 1, padding: "5px" }}> <Heading size="md" mt="2"> {item.title} </Heading> <ChakraText fontSize="sm" style={{ margin: "0px" }}> Số chương: {item.total_chapters} </ChakraText> <ChakraText fontSize="sm" style={{ margin: "0px" }}> Loại truyện: {item.categories} </ChakraText> <ChakraText fontSize="sm">Tác giả: {item.author}</ChakraText> </CardBody> </Card> ))} <div style={{ display: "flex", justifyContent: "center", alignItems: "center", }} > <Button onClick={() => loadMore()} isLoading={fetching} mt={4} style={{ width: "20%" }} > Xem thêm </Button> </div> </VStack> </> ); } export default Search;
/*************************************************************************** * The FreeMedForms project is a set of free, open source medical * * applications. * * (C) 2008-2015 by Eric MAEKER, MD (France) <eric.maeker@gmail.com> * * All rights reserved. * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program (COPYING.FREEMEDFORMS file). * * If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ /*************************************************************************** * Main developer: Eric MAEKER, <eric.maeker@gmail.com> * * Contributors: * * NAME <MAIL@ADDRESS.COM> * * NAME <MAIL@ADDRESS.COM> * ***************************************************************************/ #ifndef CORE_APPCONFIGWIZARD_H #define CORE_APPCONFIGWIZARD_H #include <QObject> #include <QWidget> #include <QWizardPage> #include <QWizard> #include <QLineEdit> #include <QPushButton> #include <QGridLayout> QT_BEGIN_NAMESPACE class QLabel; class QComboBox; class QProgressBar; QT_END_NAMESPACE /** * \file appconfigwizard.h * \author Eric Maeker * \version 0.10.0 * \date 22 Jul 2014 */ namespace Utils { class LanguageComboBox; class PathChooser; } namespace Core { class ServerPreferencesWidget; namespace Internal { class ProxyPreferencesWidget; } class AppConfigWizard : public QWizard { Q_OBJECT public: AppConfigWizard(QWidget *parent = 0); protected Q_SLOTS: void done(int r); protected: void resizeEvent(QResizeEvent *event); void changeEvent(QEvent *event); }; class CoreConfigPage: public QWizardPage { Q_OBJECT public: CoreConfigPage(QWidget *parent = 0); bool validatePage(); int nextId() const; private: void changeEvent(QEvent *e); void retranslate(); private: QLabel *langLabel, *typeLabel; Utils::LanguageComboBox *combo; QComboBox *installCombo; mutable bool _proxyDectectionDone, _proxyDetected; }; class ProxyPage: public QWizardPage { Q_OBJECT public: ProxyPage(QWidget *parent = 0); bool validatePage(); int nextId() const; private: void changeEvent(QEvent *e); void retranslate(); private: Core::Internal::ProxyPreferencesWidget *_proxyWidget; }; class ServerConfigPage: public QWizardPage { Q_OBJECT public: ServerConfigPage(QWidget *parent = 0); void initializePage(); bool isComplete() const; bool validatePage(); int nextId() const; private: void changeEvent(QEvent *e); void retranslate(); private: Core::ServerPreferencesWidget *serverWidget; }; class ClientConfigPage: public QWizardPage { Q_OBJECT public: ClientConfigPage(QWidget *parent = 0); void initializePage(); bool isComplete() const; bool validatePage(); int nextId() const; private: void changeEvent(QEvent *e); void retranslate(); private: Core::ServerPreferencesWidget *serverWidget; }; class CoreDatabaseCreationPage: public QWizardPage { Q_OBJECT public: CoreDatabaseCreationPage(QWidget *parent = 0); public: void initializePage(); bool isComplete() const; bool validatePage(); int nextId() const; private Q_SLOTS: void startDbCreation(); private: void retranslate(); void changeEvent(QEvent *e); private: QProgressBar *_progressBar; QLabel *_prefixLbl, *_sqlitePathLbl; Utils::PathChooser *_sqlitePath; QLineEdit *_prefix; QPushButton *_createBaseButton; QGridLayout *layout; bool _completed; }; class EndConfigPage: public QWizardPage { Q_OBJECT public: EndConfigPage(QWidget *parent = 0); public: void initializePage(); private Q_SLOTS: void comboDbActivated(int); void comboVirtualActivated(int); private: void retranslate(); void changeEvent(QEvent *e); private: QLabel *lblDb; QComboBox *comboDb; QLabel *lblVirtual; QComboBox *comboVirtual; QLabel *lbl1, *lbl1_1, *lbl2, *lbl2_1; }; } // End namespace Core #endif // CORE_APPCONFIGWIZARD_H
<%@ page language="java" contentType="text/html; charset=UTF-8" import="java.util.*" import="sec02.ex01.*" pageEncoding="UTF-8" %> <!-- 사용자가 입력한 이름을 기반으로 회원을 검색하고, 검색 결과를 테이블 형태로 출력하는 기능을 제공 --> <% // 요청의 문자 인코딩을 설정 request.setCharacterEncoding("utf-8"); // 사용자가 입력한 이름을 가져옴 String _name = request.getParameter("name"); // MemberVO 객체를 생성하고, 사용자가 입력한 이름을 MemberVO 객체에 설정 MemberVO memberVO = new MemberVO(); memberVO.setName(_name); // MemberDAO 객체를 생성하고, listMembers 메서드를 호출하여 회원을 검색 MemberDAO dao=new MemberDAO(); // 검색 결과는 membersList에 저장 List membersList=dao.listMembers(memberVO); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>회원 정보 출력창</title> <style> h1 { text-align: center; } table { width: 80%; border:1px solid black; border-collapse:collapse; margin-left: auto; margin-right: auto; border-spacing: 0px; } td, th { border:1px solid gray; padding:10px; vertical-align: top; text-align: center; } thead, th { background:#eee; } </style> </head> <body> <h1>회원 정보 출력</h1> <!-- 태그를 사용하여 회원 정보를 출력할 테이블을 생성 --> <table border='1' width='800' align='center'> <!-- 태그 내부에서 테이블의 헤더 부분을 정의 --> <thead> <tr> <th>아이디</th> <th>비밀번호</th> <th>이름</th> <th>이메일</th> <th>가입일자</th> </tr> </thead> <!-- 태그 내부에서 for 루프를 사용하여 membersList에 저장된 회원 정보를 순회 --> <% for (int i = 0; i < membersList.size(); i++) { MemberVO vo = (MemberVO)membersList.get(i); String id = vo.getId(); String pwd = vo.getPwd(); String name = vo.getName(); String email = vo.getEmail(); Date joinDate = vo.getJoinDate(); %> <tr> <!-- 각 회원 정보를 변수에 저장하고, 해당 정보를 테이블의 각 열에 출력 --> <td><%= id %></td> <td><%= pwd %></td> <td><%= name %></td> <td><%= email %></td> <td><%= joinDate %></td> </tr> <% } %> </table> </body> </html>
import cv2 import numpy # Initialization function for call the trackbar def call_trackbar(x): # No action needed, just a reference. print("") # Camera Initialization cap = cv2.VideoCapture(1) # Creates six bars for upper hsv and lower hsv bars = cv2.namedWindow("bars") # Creating the trackbar # Max value for hue is 180, Max of value and saturation is 255 cv2.createTrackbar("upper_hue", "bars", 110, 180, call_trackbar) cv2.createTrackbar("upper_saturation", "bars", 255, 255, call_trackbar) cv2.createTrackbar("upper_value", "bars", 255, 255, call_trackbar) cv2.createTrackbar("lower_hue", "bars", 68, 180, call_trackbar) cv2.createTrackbar("lower_saturation", "bars", 55, 255, call_trackbar) cv2.createTrackbar("lower_value", "bars", 54, 255, call_trackbar) # Capture initial frame for the background creation while (True): cv2.waitKey(1000) ret, init_frame = cap.read() # check if the frame is returned then break if (ret): break # Start capturing all consecutive frames while (True): ret, frame = cap.read() # BGR to HSV conversion inspect = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # Upper and lower values for view saturation is obtained from the trackbars # getting the HSV values for masking the cloak # getTrackbarPos() - Gets the current position number of the trackbar upper_hue = cv2.getTrackbarPos("upper_hue", "bars") upper_saturation = cv2.getTrackbarPos("upper_saturation", "bars") upper_value = cv2.getTrackbarPos("upper_value", "bars") lower_value = cv2.getTrackbarPos("lower_value", "bars") lower_hue = cv2.getTrackbarPos("lower_hue", "bars") lower_saturation = cv2.getTrackbarPos("lower_saturation", "bars") # Kernel to be used for dilation to remove impurities from camera stream # numpy.ones() creates a (n,n) matrix of 1s kernel = numpy.ones((3, 3), numpy.uint8) # Create two small arrays that hold the values of lower and upper hsv upper_hsv = numpy.array([upper_hue, upper_saturation, upper_value]) lower_hsv = numpy.array([lower_hue, lower_saturation, lower_value]) # @inspect contains the frame that was converted into hsv # Subtract lower_hsv from upper_hsv and create a mask for that range in the middle mask = cv2.inRange(inspect, lower_hsv, upper_hsv) # Further remove impurities mask = cv2.medianBlur(mask, 3) mask_inv = 255 - mask mask = cv2.dilate(mask, kernel, 5) # The mixing of frames in a combination to achieve the required output frame b = frame[:, :, 0] g = frame[:, :, 1] r = frame[:, :, 2] # Makes the mentioned color space area of the video stream blank using bitwise_and b = cv2.bitwise_and(mask_inv, b) g = cv2.bitwise_and(mask_inv, g) r = cv2.bitwise_and(mask_inv, r) # Merges b,g and r values for a consolidated frame frame_inv = cv2.merge((b, g, r)) b = init_frame[:, :, 0] g = init_frame[:, :, 1] r = init_frame[:, :, 2] b = cv2.bitwise_and(b, mask) g = cv2.bitwise_and(g, mask) r = cv2.bitwise_and(r, mask) blanket_area = cv2.merge((b, g, r)) final = cv2.bitwise_or(frame_inv, blanket_area) cv2.imshow("Invisibility Cloak", final) if (cv2.waitKey(3) == ord('q')): break; # Always call these - to deallocate usage of camera etc, to prevent cpu usage unnecessarily. cv2.destroyAllWindows() cap.release()
% % tridiagonal_vector Solves the tridiagonal linear system Ax = d for x % using the vector implementation of the tridiagonal matrix algorithm. % % x = tridiagonal_vector(a,b,c,d) % % Copyright © 2021 Tamas Kis % Last Update: 2022-10-22 % Website: https://tamaskis.github.io % Contact: tamas.a.kis@outlook.com % % TECHNICAL DOCUMENTATION: % https://tamaskis.github.io/files/Tridiagonal_Matrix_Algorithm.pdf % %-------------------------------------------------------------------------- % % ------ % INPUT: % ------ % a - ((n-1)×1 double) tridiagonal vector % b - (n×1 double) tridiagonal vector % c - ((n-1)×1 double) tridiagonal vector % d - (n×1 double) vector % % ------- % OUTPUT: % ------- % x - (n×1 double) solution of the tridiagonal linear system Ax = d % % ----- % NOTE: % ----- % --> The vectors a, b, and c define the diagonals of the tridiagonal % matrix, A, as shown below: % % ⌈ ⋱ ⋱ ⌉ % | ⋱ ⋱ c | % A = | ⋱ b ⋱ | % | a ⋱ ⋱ | % ⌊ ⋱ ⋱ ⌋ % function x = tridiagonal_vector(a,b,c,d) % determines n n = length(d); % preallocates solution vector x = zeros(n,1); % forward elimination for i = 2:n w = a(i-1)/b(i-1); b(i) = b(i)-w*c(i-1); d(i) = d(i)-w*d(i-1); end % backward substitution x(n) = d(n)/b(n); for i = (n-1):(-1):1 x(i) = (d(i)-c(i)*x(i+1))/b(i); end end
import type Spotify from 'spotify-web-api-node'; import Queue from 'better-queue'; import chunk from 'lodash/chunk'; import { asyncSafeInvoke } from '@moovin-groovin/shared'; import ServerModule, { assertContext, Handlers, Services, } from '../../lib/ServerModule'; import type { ApiSpotifyData } from './data'; import type { RecentlyPlayedTracksOptions, ApiSpotifyDeps, SpotifyTrack, } from './types'; import assertSpotify from './utils/assertSpotify'; interface WithAccessTokenContext { accessToken: string; spotifyClient: Spotify; } interface BatchedAddTracksToPlaylistOptions { spotifyUserId: string; playlistId: string; trackUris: string[]; } interface BatchedGetTracksOptions { spotifyUserId: string; trackIds: string[]; } interface ApiSpotifyServices extends Services { withAccessToken: <T>( spotifyUserId: string, fn: (context: WithAccessTokenContext) => T | Promise<T> ) => Promise<T>; getRecentlyPlayedTracks: ( spotifyUserId: string, options?: RecentlyPlayedTracksOptions ) => Promise<SpotifyTrack[]>; batchedAddTracksToPlaylist: ( input: BatchedAddTracksToPlaylistOptions ) => Promise<string[]>; batchedGetTracks: ( input: BatchedGetTracksOptions ) => Promise<SpotifyApi.TrackObjectFull[]>; } type ThisModule = ServerModule< ApiSpotifyServices, Handlers, ApiSpotifyData, ApiSpotifyDeps >; interface SpotifyClientQueueTask { context: WithAccessTokenContext; taskFn: (context: WithAccessTokenContext) => unknown | Promise<unknown>; } // The SpotifyApi sets the accessToken globally. To ensure that the access token // is set to the right user for the entirety of the execution of the callback // passed to withAccessToken, we queue the tasks, so they run one after another. // See https://github.com/diamondio/better-queue for details. const spotifyClientQueue = new Queue<SpotifyClientQueueTask, unknown>( async ({ context, taskFn }: SpotifyClientQueueTask, cb) => { const { spotifyClient, accessToken } = context; spotifyClient.setAccessToken(accessToken); const { result, error } = await asyncSafeInvoke(() => taskFn(context)); spotifyClient.resetAccessToken(); cb(error, result); } ); const createApiSpotifyServices = (): ApiSpotifyServices => { async function withAccessToken<T>( this: ThisModule, spotifyUserId: string, fn: (context: WithAccessTokenContext) => T | Promise<T> ): Promise<T> { assertContext(this.context); assertSpotify(this.data.spotify); const spotifyClient = this.data.spotify; const { getAccessToken } = this.context.modules.oauthSpotify.services; const accessToken = await getAccessToken(spotifyUserId); return new Promise<T>((res, rej) => { spotifyClientQueue .push({ context: { accessToken, spotifyClient }, taskFn: fn, }) .on('finish', res) .on('failed', rej); }); } /** * Wrapper for SpotifyApi.getMyRecentlyPlayedTracks that uses spotifyUserId * to get and set access token. */ async function getRecentlyPlayedTracks( this: ThisModule, spotifyUserId: string, options: RecentlyPlayedTracksOptions = {} ): Promise<SpotifyTrack[]> { return this.services.withAccessToken( spotifyUserId, async ({ spotifyClient }) => { const { limit = 50 } = options; const response = await spotifyClient.getMyRecentlyPlayedTracks({ ...options, limit, }); return response.body.items; } ); } async function batchedAddTracksToPlaylist( this: ThisModule, input: BatchedAddTracksToPlaylistOptions ): Promise<string[]> { const { playlistId, trackUris, spotifyUserId } = input; // Note: addTracksToPlaylist endpoints accepts max of 100 tracks per request. const chunkedTrackUris = chunk(trackUris, 100); const snapshots = await this.services.withAccessToken( spotifyUserId, async ({ spotifyClient }) => chunkedTrackUris.reduce<Promise<string[]>>( async (aggPromise, tracksChunk) => { const aggArr = await aggPromise; const response = await spotifyClient.addTracksToPlaylist( playlistId, tracksChunk ); aggArr.push(response.body.snapshot_id); return aggArr; }, Promise.resolve([]) ) ); return snapshots; } async function batchedGetTracks( this: ThisModule, options: BatchedGetTracksOptions ): Promise<SpotifyApi.TrackObjectFull[]> { const { trackIds, spotifyUserId } = options; // Note: getTracks endpoints accepts max of 50 tracks per request. const chunkedTrackIds = chunk(trackIds, 50); const tracks = await this.services.withAccessToken( spotifyUserId, async ({ spotifyClient }) => chunkedTrackIds.reduce<Promise<SpotifyApi.TrackObjectFull[]>>( async (aggPromise, tracksChunk) => { const aggArr = await aggPromise; const response = await spotifyClient.getTracks(tracksChunk); const responseTracks = response?.body?.tracks || []; aggArr.push(...responseTracks); return aggArr; }, Promise.resolve([]) ) ); return tracks; } return { withAccessToken, getRecentlyPlayedTracks, batchedAddTracksToPlaylist, batchedGetTracks, }; }; export default createApiSpotifyServices; export type { ApiSpotifyServices };
import React, { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import logo from "../logo.png" import add from "../add.png" import "./Navbar.css" export default function Navbar(props){ const navigate = useNavigate() function logOut(e){ localStorage.removeItem("token") props.setLogin(false) navigate("/") } return( <div className="container"> <nav className="navbar navbar-expand-md navbar-light"> <a href="/" className="brand right"> <img src={logo} alt="Brood Logo" width="50" className="d-inline-block align-top"/><span className="blank"></span></a> <form className="d-flex"> <input className="form-control me-2" type="search" placeholder="Search" aria-label="Search"></input> <button className="btn btn-outline-success" type="submit">Search</button> </form> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#toggleMobileMenu" aria-controls="toggleMovileMenu" aria-expanded="false" aria-lable="Toggle navigation" > <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="toggleMobileMenu"> <ul className="navbar-nav ms-auto"> {props.login ? <> <li> <a className="btn" href='/create'> <img src={add} alt="addLogo" width="30" className="d-inline-block"/>Add Story</a> </li> <li> <a href="#" className="nav-link">{props.userData.name}</a> </li> <li> <span className="nav-link">{props.userData.reputation}</span> </li> </> : <> <li> <a href='/login' className='btn'>Login</a> </li> <li> <a href='/register' className='btn'>Register</a> </li> </> } <li className="nav-item dropdown"> <a className="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <span>&#8942;</span> </a> <ul className="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <li><a className="dropdown-item" href="#">Setting</a></li> <li><a className="dropdown-item" href="#">Help</a></li> <li><button className="dropdown-item" onClick={logOut}>Log Out</button></li> </ul> </li> </ul> </div> </nav> </div> ) // }else{ // return( // <div className="container"> // <nav className="navbar navbar-expand-md navbar-light"> // <a href="/" className="brand right"> // <img src={logo} alt="Brood Logo" width="50" className="d-inline-block align-top"/><span className="blank"></span></a> // <form className="d-flex"> // <input className="form-control me-2" type="search" placeholder="Search" aria-label="Search"></input> // <button className="btn btn-outline-success" type="submit">Search</button> // </form> // <button // className="navbar-toggler" // type="button" // data-bs-toggle="collapse" // data-bs-target="#toggleMobileMenu" // aria-controls="toggleMovileMenu" // aria-expanded="false" // aria-lable="Toggle navigation" // > // <span className="navbar-toggler-icon"></span> // </button> // <div className="collapse navbar-collapse" id="toggleMobileMenu"> // <ul className="navbar-nav ms-auto"> // <li> // <a href='/login' className='btn'>Login</a> // </li> // <li> // <a href='/register' className='btn'>Register</a> // </li> // {/* <li> // <a className="btn" href='/create'> // <img src={add} alt="addLogo" width="30" className="d-inline-block"/>Add Story</a> // </li> // <li> // <a href="#" className="nav-link">{props.name}</a> // </li> // <li> // <a href="#" className="nav-link">Rating</a> // </li> */} // <li className="nav-item dropdown"> // <a className="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> // <span>&#8942;</span> // </a> // <ul className="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> // <li><a className="dropdown-item" href="#">Setting</a></li> // <li><a className="dropdown-item" href="#">Help</a></li> // {/* <li><button className="dropdown-item" onClick={logOut}>Log Out</button></li> */} // </ul> // </li> // </ul> // </div> // </nav> // </div> // ) // } }
package core; import org.lwjgl.*; import org.lwjgl.glfw.*; import org.lwjgl.opengl.*; import static org.lwjgl.glfw.Callbacks.*; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL40.*; /* Created on February 16, 2024 @author David Eichinger Anticipating that the applications created will eventually feature user interaction and animation, this class will be designed to handle the standard phases or “life cycle” of such an application: • Startup: During this stage, objects are created, values are initialized, and any required external files are loaded. • The Main Loop: This stage repeats continuously (typically 60 times per second) while the application is running, and consists of the following three substages: • Process Input: Check if the user has performed any action that sends data to the computer, such as pressing keys on a keyboard or clicking buttons on a mouse. • Update: Changing values of variables and objects. • Render: Create graphics that are displayed on the screen. • Shutdown: This stage typically begins when the user performs an action indicating that the program should stop running (for example, by clicking a button to quit the application). This stage may involve tasks such as signaling the application to stop checking for user input and closing any windows that were created by the application. */ public abstract class Base { //window dimensions private int windowWidth; private int windowHeight; //the window handle private long window; //is the loop currently active? private boolean running; public Base() { } public void startup() { //intialize GLFW boolean initSuccess = glfwInit(); if (!initSuccess) throw new RuntimeException("Unable to initalize GLFW"); //create window and assoicated OpenGL context, which stores framebuffer and other state information glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); window = glfwCreateWindow( windowWidth, windowHeight,"Graphics Window", 0, 0); if ( window == 0 ) throw new RuntimeException("Failed to create the GLFW window"); running = true; //Make all OpenGL function calls apply to this context instance glfwMakeContextCurrent(window); //Specify number of screen updates to wait before swapping buffers. //Setting to 1 synchronizes the application frame rate with the display refresh rate; prevents visual // "screen tearing" artifacts glfwSwapInterval(1); //Detect current context and makes OpenGL bindings available for use: GL.createCapabilities(); } public abstract void initialize(); public abstract void update(); public void run() { run(512, 512); } public void run(int windowWidth, int windowHeight) { this.windowWidth = windowWidth; this.windowHeight = windowHeight; startup(); // application-specific startup code initialize(); //main loop while (running) { //check for user interaction events glfwPollEvents(); // check if window close icon is clicked if (glfwWindowShouldClose(window)) running = false; //application-specific update code update(); //swap the color buffers to display rendered graphics on screen glfwSwapBuffers(window); } shutdown();; } public void shutdown() { //stop window monitoring for user input glfwFreeCallbacks(window); //close the window glfwDestroyWindow(window); //stop GLFW glfwTerminate(); //stop error callback glfwSetErrorCallback(null).free(); } }
import { Component, ChangeDetectorRef} from '@angular/core'; import { Album } from '../album-list/service/album'; import { CommonModule, Location } from '@angular/common'; import { ActivatedRoute, RouterModule } from '@angular/router'; import { FormsModule } from '@angular/forms'; import { AlbumListComponent } from '../album-list/album-list.component'; import { AlbumListApiService } from '../album-list/service/album-list-api.service'; @Component({ selector: 'app-album-detail', standalone: true, imports: [CommonModule, RouterModule, FormsModule, AlbumListComponent], templateUrl: './album-detail.component.html', styleUrl: './album-detail.component.css', }) export class AlbumDetailComponent { album: Album | undefined; constructor( private route: ActivatedRoute, private location: Location, private api: AlbumListApiService ) {} ngOnInit() { const routeParams = this.route.snapshot.paramMap; const id = Number(routeParams.get('id')); this.album = this.api.albums.find((item) => item.id == id); } back() { this.location.back(); } }
import { ObjectId } from 'mongoose'; import { Body, Controller, Get, Param, Post, Put, Query, UploadedFiles, UseInterceptors, } from '@nestjs/common'; import { CourseService } from './course.service'; import { CreateCourseDto } from './dto/create-course.dto'; import { UpdateCourseDto } from './dto/update-course.dto'; import { FileFieldsInterceptor } from '@nestjs/platform-express'; import { BuyCourseDto } from './dto/buy-course.dto'; @Controller('courses') export class CourseController { constructor(private courseService: CourseService) {} @Post('/create') @UseInterceptors(FileFieldsInterceptor([{ name: 'picture', maxCount: 1 }])) create(@UploadedFiles() files, @Body() dto: CreateCourseDto) { const { picture } = files; return this.courseService.create(dto, picture[0]); } @Put('/:id') update(@Body() dto: UpdateCourseDto) { return this.courseService.update(dto); } @Post('/buy') buyCourse(@Body() dto: BuyCourseDto) { return this.courseService.buy(dto); } @Get() getAll() { return this.courseService.getAll(); } @Get('/purchased/:id') getPurchasedUserCourses(@Param('id') id: ObjectId) { return this.courseService.getPurchasedUserCourses(id); } @Get('/created/:id') getCreatedUserCourses(@Param('id') id: ObjectId) { return this.courseService.getCreatedUserCourses(id); } @Get('/search') search(@Query('query') query: string) { return this.courseService.search(query); } @Get(':id') getOne(@Param('id') id: ObjectId) { return this.courseService.getOne(id); } }
package com.yaude.modules.demo.mock; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.swing.filechooser.FileSystemView; import org.apache.commons.io.IOUtils; import com.yaude.common.api.vo.Result; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import lombok.extern.slf4j.Slf4j; @RestController @RequestMapping("/mock/api") @Slf4j public class MockController { private final String JSON_PATH = "classpath:com/yaude/modules/demo/mock/json"; /** * 通用json訪問接口 * 格式: http://localhost:8080/jeecg-boot/api/json/{filename} * @param filename * @return */ @RequestMapping(value = "/json/{filename}", method = RequestMethod.GET) public String getJsonData(@PathVariable String filename) { String jsonpath = "classpath:com/yaude/modules/demo/mock/json/"+filename+".json"; return readJson(jsonpath); } @GetMapping(value = "/asynTreeList") public String asynTreeList(String id) { return readJson(JSON_PATH + "/asyn_tree_list_" + id + ".json"); } @GetMapping(value = "/user") public String user() { return readJson("classpath:com/yaude/modules/demo/mock/json/user.json"); } /** * 老的登錄獲取用戶信息接口 * @return */ @GetMapping(value = "/user/info") public String userInfo() { return readJson("classpath:com/yaude/modules/demo/mock/json/user_info.json"); } @GetMapping(value = "/role") public String role() { return readJson("classpath:com/yaude/modules/demo/mock/json/role.json"); } @GetMapping(value = "/service") public String service() { return readJson("classpath:com/yaude/modules/demo/mock/json/service.json"); } @GetMapping(value = "/permission") public String permission() { return readJson("classpath:com/yaude/modules/demo/mock/json/permission.json"); } @GetMapping(value = "/permission/no-pager") public String permission_no_page() { return readJson("classpath:com/yaude/modules/demo/mock/json/permission_no_page.json"); } /** * 省市縣 */ @GetMapping(value = "/area") public String area() { return readJson("classpath:com/yaude/modules/demo/mock/json/area.json"); } /** * 測試報表數據 */ @GetMapping(value = "/report/getYearCountInfo") public String getYearCountInfo() { return readJson("classpath:com/yaude/modules/demo/mock/json/getCntrNoCountInfo.json"); } @GetMapping(value = "/report/getMonthCountInfo") public String getMonthCountInfo() { return readJson("classpath:com/yaude/modules/demo/mock/json/getCntrNoCountInfo.json"); } @GetMapping(value = "/report/getCntrNoCountInfo") public String getCntrNoCountInfo() { return readJson("classpath:com/yaude/modules/demo/mock/json/getCntrNoCountInfo.json"); } @GetMapping(value = "/report/getCabinetCountInfo") public String getCabinetCountInfo() { return readJson("classpath:com/yaude/modules/demo/mock/json/getCntrNoCountInfo.json"); } @GetMapping(value = "/report/getTubiao") public String getTubiao() { return readJson("classpath:com/yaude/modules/demo/mock/json/getTubiao.json"); } /** * 實時磁盤監控 * @param request * @param response * @return */ @GetMapping("/queryDiskInfo") public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){ Result<List<Map<String,Object>>> res = new Result<>(); try { // 當前文件系統類 FileSystemView fsv = FileSystemView.getFileSystemView(); // 列出所有windows 磁盤 File[] fs = File.listRoots(); log.info("查詢磁盤信息:"+fs.length+"個"); List<Map<String,Object>> list = new ArrayList<>(); for (int i = 0; i < fs.length; i++) { if(fs[i].getTotalSpace()==0) { continue; } Map<String,Object> map = new HashMap<>(); map.put("name", fsv.getSystemDisplayName(fs[i])); map.put("max", fs[i].getTotalSpace()); map.put("rest", fs[i].getFreeSpace()); map.put("restPPT", fs[i].getFreeSpace()*100/fs[i].getTotalSpace()); list.add(map); log.info(map.toString()); } res.setResult(list); res.success("查詢成功"); } catch (Exception e) { res.error500("查詢失敗"+e.getMessage()); } return res; } //------------------------------------------------------------------------------------------- /** * 工作臺首頁的數據 * @return */ @GetMapping(value = "/list/search/projects") public String projects() { return readJson("classpath:com/yaude/modules/demo/mock/json/workplace_projects.json"); } @GetMapping(value = "/workplace/activity") public String activity() { return readJson("classpath:com/yaude/modules/demo/mock/json/workplace_activity.json"); } @GetMapping(value = "/workplace/teams") public String teams() { return readJson("classpath:com/yaude/modules/demo/mock/json/workplace_teams.json"); } @GetMapping(value = "/workplace/radar") public String radar() { return readJson("classpath:com/yaude/modules/demo/mock/json/workplace_radar.json"); } @GetMapping(value = "/task/process") public String taskProcess() { return readJson("classpath:com/yaude/modules/demo/mock/json/task_process.json"); } //------------------------------------------------------------------------------------------- //author:lvdandan-----date:20190315---for:添加數據日志json---- public String sysDataLogJson() { return readJson("classpath:com/yaude/modules/demo/mock/json/sysdatalog.json"); } //author:lvdandan-----date:20190315---for:添加數據日志json---- //--update-begin--author:wangshuai-----date:20201023---for:返回用戶信息json數據---- @GetMapping(value = "/getUserInfo") public String getUserInfo(){ return readJson("classpath:com/yaude/modules/demo/mock/json/userinfo.json"); } //--update-end--author:wangshuai-----date:20201023---for:返回用戶信息json數據---- /** * 讀取json格式文件 * @param jsonSrc * @return */ private String readJson(String jsonSrc) { String json = ""; try { //File jsonFile = ResourceUtils.getFile(jsonSrc); //json = FileUtils.re.readFileToString(jsonFile); //換個寫法,解決springboot讀取jar包中文件的問題 InputStream stream = getClass().getClassLoader().getResourceAsStream(jsonSrc.replace("classpath:", "")); json = IOUtils.toString(stream,"UTF-8"); } catch (IOException e) { log.error(e.getMessage(),e); } return json; } }
// leetcode844: backspace-string-compare #include <cstdio> #include <iostream> #include <stack> #include <vector> #include <string> #include <sstream> using namespace std; bool backspaceCompare(string S, string T) { if (S == "" && T == "") return true; bool res = true; stack<char> stackS; stack<char> stackT; // convert the string to char* vector<char> S_cstr(S.c_str(), S.c_str()+S.size()+1); vector<char> T_cstr(T.c_str(), T.c_str()+T.size()+1); // traverse the two strings for populating the stacks for (int i = 0; i < S.size(); i++) { char item = S_cstr[i]; if (item == '#') { if (!stackS.empty()) { stackS.pop(); } } else { stackS.push(item); } } for (int i = 0; i < T.size(); i++) { char item = T_cstr[i]; if (item == '#') { if (!stackT.empty()) { stackT.pop(); } } else { stackT.push(item); } } // compare the stack items while (!stackS.empty() && !stackT.empty()) { char itemS = stackS.top(); char itemT = stackT.top(); // if found difference -> false if (itemS != itemT) { res = false; break; } else { stackS.pop(); stackT.pop(); } } if (!stackS.empty() || !stackT.empty()) { res = false; } return res; } void judge(string s1, string s2) { if (backspaceCompare(s1,s2)) { cout << "true" << endl; } else { cout << "false" << endl; } return; } void test() { string a1 = "ab#c"; string a2 = "ad#c"; string b1 = "ab##"; string b2 = "c#d#"; string c1 = "a##c"; string c2 = "#a#c"; string d1 = "a#c"; string d2 = "b"; judge(a1,a2); judge(b1,b2); judge(c1,c2); judge(d1,d2); return; } int main() { test(); return 0; }
#! /usr/bin/python2.4 # pajekpart -- a partition maker for Pajek (a program for network analysis) # # Copyright (c) 2005 Ryszard Szopa # # Author: Ryszard Szopa <ryszard (dot) szopa (at) gmail (dot) com> # http://szopa.tasak.gda.pl/ # http://szopa.wordpress.com/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 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 """ pajekpart automates preparing partitions for Pajek. It takes two files, a pajek *.net file and the categories file (with a .cat extension) and outputs a partition file. The categories file has a very simple syntax: it consists of pairs <node label> <category>, separated by a tab, each in a new line. The labels should be the same as in the .net file. For more information about Pajek see http://vlado.fmf.uni-lj.si/pub/networks/pajek/. """ from sets import Set import re import sys __version__ = '1.02' __date__ = 'September 2, 2006' __author__= 'Ryszard Szopa' __help__ = """ pajekpart automates preparing partitions for Pajek. It takes two files, a pajek *.net file and the categories file (with a .cat extension) and outputs a partition file. The categories file has a very simple syntax: it consists of pairs <node label> <category>, separated by a tab, each in a new line. The labels should be the same as in the .net file. For more information about Pajek see http://vlado.fmf.uni-lj.si/pub/networks/pajek/. """ __usage__ = """ usage: pajekpart.py [-o file.clu] file.net file.cat pajekpart.py --help """ class NoFilesError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class CorruptedNet(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def importNodesFromNet(filename): """importNodesFromNet(filename) -> list Returns a list of node labels from the .net file, in the right order. See pajek's files specification.""" if not filename: raise NoFilesError("You haven't specified a NET file.") #this is no good or bug nets: #nodesTable = file(filename).readlines() nodesFile = file(filename) match = re.search('\*Vertices (.+)', nodesFile.readline()) if not match: raise CorruptedNet('Your NET file seems to be corrupted') nodes = [] for i in range(int(match.group(1))): regNaz = re.search('\A\d+ "(.+)"', nodesFile.readline()) #it isn't really neccessary, but let's keep it in case the file is a bit corrupted if regNaz: nodes.append(regNaz.groups()[0]) return nodes ## for node in nodesTable: ## regNaz = re.search('\A\d+ "(.+)"', node) ## if regNaz: ## nodes.append(regNaz.groups()[0]) ## return nodes def importCategories(filename): """importCategories(filename) -> (hash, list) Returns a hash with node-labels as keys and the assigned categories as values and the et of categories (without duplicates).""" if not filename: raise NoFilesError("You haven't specified a CAT file.") categoriesTable = file(filename).readlines() category = {} for i in categoriesTable: # the fields of the record are separated by tabs datum = i.strip().split('\t') category[datum[0]] = datum[1] categories = list(Set(category.values())) return (category, categories) def makePartition(nodes, category, categories, err=sys.stderr): partycja = [] for i in nodes: try: partycja.append(categories.index(category[i])) except KeyError: # not sys.stderr because it doesn't play nice with the gui logs print >> err, "Warning: Something wrong with '%s'.\n Maybe it hasn't been assigned a category? I added it to `Unknown.'"%(i) partycja.append(len(categories)+1) return partycja if __name__=='__main__': print >> sys.stderr, "This is pajekpart, a Pajek partition maker, version %s (%s)."%(__version__, __date__) print >> sys.stderr, "(c) 2006 Ryszard Szopa." if '--help' in sys.argv: print >> sys.stderr, __help__ sys.exit(0) nazwaNet = '' nazwaAf = '' if '-o' in sys.argv: minusO = sys.argv.index('-o') sys.stdout = open(sys.argv[minusO+1], "w") del sys.argv[minusO:minusO+2] for arg in sys.argv: if re.search('.net\Z', arg): nazwaNet = arg if re.search('.cat\Z', arg): nazwaAf = arg if not nazwaNet or not nazwaAf: print >> sys.stderr, __usage__ sys.exit(1) nazwiska = importNodesFromNet(nazwaNet) afiliacja, afiliacje = importCategories(nazwaAf) partycja =makePartition(nazwiska, afiliacja, afiliacje) print "*Vertices %s \r\n"%(len(partycja)) for i in partycja: print i sys.exit(0)
<%@page import="java.io.FileOutputStream"%> <%@page import="java.text.SimpleDateFormat"%> <%@page import="org.jdom2.output.Format"%> <%@page import="kr.co.sist.member.vo.StudentVO"%> <%@page import="java.util.List"%> <%@page import="java.sql.SQLException"%> <%@page import="kr.co.sist.dao.StuDAO"%> <%@page import="java.io.File"%> <%@page import="org.jdom2.output.XMLOutputter"%> <%@page import="org.jdom2.Element"%> <%@page import="org.jdom2.Document"%> <%@ page language="java" contentType="application/xml; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page info="" trimDirectiveWhitespaces="true"%> <% //1. 문서 객체 생성 Document doc = new Document(); //2. 최상위 부모 노드 생성 Element studentsNode = new Element("students"); StuDAO sDAO = StuDAO.getInstance(); boolean errFlag= false; List<StudentVO> list=null; File file = new File("E:/dev/Workspace/jsp_prj/src/main/java/xml1031/student.xml"); try{ list = sDAO.selectAllStudent(); Element dataSizeNode = new Element("dataSize"); dataSizeNode.setText(String.valueOf(list.size())); studentsNode.addContent(dataSizeNode); }catch(SQLException se) { errFlag=true; se.printStackTrace(); }//end catch Element requestUrlNode = new Element("requestURL"); requestUrlNode.setText("http://localhost/jsp_prj/xml1031/"+file.getName() ); studentsNode.addContent(requestUrlNode); //3. 자식 노드을 생성 Element errFlagNode = new Element("isErrFlag"); errFlagNode.setText(String.valueOf(errFlag)); studentsNode.addContent(errFlagNode); if(!errFlag) { Element studentNode = null; Element numNode = null; Element nameNode = null; Element ageNode = null; Element emailNode = null; Element input_dateNode = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd EEEE"); for(StudentVO sVO : list){ studentNode= new Element("student"); numNode= new Element("num"); numNode.setText(String.valueOf(sVO.getNum())); nameNode= new Element("name"); nameNode.setText(sVO.getName()); ageNode= new Element("age"); ageNode.setText(String.valueOf(sVO.getAge())); emailNode= new Element("age"); emailNode.setText(sVO.getEmail()); input_dateNode= new Element("input_date"); input_dateNode.setText(sdf.format(sVO.getInput_date())); studentNode.addContent(numNode); studentNode.addContent(nameNode); studentNode.addContent(ageNode); studentNode.addContent(emailNode); studentsNode.addContent(studentNode); }//end for }//end if //4. //5. doc.setRootElement(studentsNode); //6. XMLOutputter xOut = new XMLOutputter(Format.getPrettyFormat()); xOut.output(doc, out); FileOutputStream fos = new FileOutputStream(file); xOut.output(doc, fos); //7. %>
#include <iostream> using namespace std; class node { public: int data; node *next; node() { this->data = 0; this->next = NULL; } }; class stack { node *top; public: stack() { top = NULL; } void push(int num) { node *temp = new node(); if (temp == NULL) { cout << "The stack is overflow" << endl; return; } else { temp->data = num; temp->next = top; top = temp; } } void pop() { node *temp; if (top == NULL) { cout << "The stack is empty" << endl; } else { temp = top; cout << "This is element = " << temp->data << endl; top = temp->next; // n = n->next; delete temp; } } void display() { node *temp; // Check for stack underflow if (top == NULL) { cout << "\nStack Underflow"; exit(1); } else { temp = top; while (temp != NULL) { // Print node data cout << temp->data; // Assign temp link to temp temp = temp->next; if (temp != NULL) cout << " -> "; } } } int peek(int num) { cout << "i am peek" << endl; node *temp = top; if (top == NULL) { cout << "You stack is empty" << endl; } else { for (int i = 0; (i < num - 1 && temp != NULL); i++) { temp = temp->next; } // cout<<endl<<"The peek value of "<<num<<" = "<<temp->data<<endl; } int fine = temp->data; return fine; } void top_botton_in_stack() { node *temp = top; cout << "\nThe top must element in the stack is = " << top->data << endl; while (temp != NULL) { temp = temp->next; } cout << "The bottom most value in the stack is = " << temp->data << endl; } void list_trivisal() { node *temp = top; int i = 0; while (temp != NULL) { temp = temp->next; cout << "Value at position " << i + 1 << " = " << peek(i + 1) << endl; i++; } } }; int main() { stack s; s.push(23); s.push(10); s.push(89); // s.pop();4 s.push(999); // s.pop(); // s.display(); // s.list_trivisal(); // s.top_botton_in_stack(); return 0; }
import { useEffect, useState } from 'react' import type { GetStaticProps } from 'next' import { DefaultLayout } from '@templates/index' import { getProjectsContent } from '@services/projects' import { getBannersPpalContent } from '@services/bannersPpal' import { getLogoContent } from '@services/logo' import { getAboutUsContent } from '@services/aboutUs' import { getServicesContent } from '@services/services' import { getNumberWpContent } from '@services/numWhatsapp' import { getDataContact } from '@services/contact' import { getFooterContent } from '@services/footer' // import { getMapContent } from '@services/map' import { BtnWhatsapp, LoadingInitialSite, SectionSliderBg, Services, Projects, About, // Location, Contact } from '@components/index' import { IFooterData, IContactContent, IPropsServices, ILogoData, IAboutData, IBannerData, IPropsProject } from '@typed/index' interface IPropsData { projects: { items: [IPropsProject] } services: IPropsServices bannersPpal: IBannerData logo: ILogoData numberWp: string aboutUs: IAboutData googleMap: { apiKeyMap: string coordenadasGoogle: { lat: number lon: number } } contact: IContactContent footer: IFooterData } export default function Home(props: IPropsData) { const { projects, bannersPpal, logo, services, numberWp, aboutUs, // googleMap, contact, footer } = props const [isLoadingHome, setIsLoadingHome] = useState(true) useEffect(() => { window.scrollTo(0, 0) const timeoutId = setTimeout(() => { setIsLoadingHome(false) }, 1500) return () => clearTimeout(timeoutId) }, []) if (isLoadingHome) { return <LoadingInitialSite /> } return ( <DefaultLayout title="IENEL - Home" logo={logo} footer={footer} isHeaderMenu> <SectionSliderBg dataBanner={bannersPpal} /> <Services dataServices={services} /> <About dataAbout={aboutUs} /> <Projects dataProjects={projects} /> {/* <Location googleMap={googleMap} /> */} <Contact dataContact={contact} /> <BtnWhatsapp number={numberWp} /> </DefaultLayout> ) } export const getStaticProps: GetStaticProps<any> = async () => { return { props: { projects: await getProjectsContent(), bannersPpal: await getBannersPpalContent(), logo: await getLogoContent(), services: await getServicesContent(), numberWp: await getNumberWpContent(), aboutUs: await getAboutUsContent(), // googleMap: await getMapContent(), contact: await getDataContact(), footer: await getFooterContent() } } }
<?php namespace App\Http\Controllers; use App\Models\Testmonial; use Illuminate\Http\Request; use App\Traits\Common; class TestmonialController extends Controller { /** * Display a listing of the resource. */ use Common; public function index() { $testmonials = Testmonial::get(); return view('testmonials', compact("testmonials")); } public function list() { $testmonials = Testmonial::latest()->take(3)->get(); //$testmonials = Testmonial::get(); return view('showtestimonials', compact("testmonials")); } /** * Show the form for creating a new resource. */ public function create() { return view('addtestmonial'); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $data = $request->only("name", "content", "position", "published", "image"); $fileName = $this->uploadFile($request->image, 'assets/images'); $data['image'] = $fileName; $data['published'] = isset($request->published); Testmonial::create($data); return redirect('testmonials'); } /** * Display the specified resource. */ public function show(string $id) { $testmonials = Testmonial::findOrFail($id); return view('testmonials', compact('testmonials')); } /** * Show the form for editing the specified resource. */ public function edit(string $id) { $testmonials = Testmonial::get(); $testmonial = Testmonial::findOrFail($id); return view('updatetestmonial', compact('testmonial', 'testmonials')); } /** * Update the specified resource in storage. */ public function update(Request $request, string $id) { $data = $request->only("name", "content", "position", "published", "image"); if ($request->hasFile('image')) { $fileName = $this->uploadFile($request->image, 'assets/images'); $data['image'] = $fileName; // unlink("assets/images/" . $request->oldImage); } $data["published"] = isset($request->published); Testmonial::where('id', $id)->update($data); return redirect('testmonials'); } /** * Remove the specified resource from storage. */ public function destroy(string $id) { Testmonial::where('id', $id)->delete(); return redirect('testmonials'); } }
<template> <div class="card"> <img class="image" :src="img" :alt="text" /> <div class="info"> <span class="info-top">{{ text }}</span> <span class="info-bottom"> <time>{{ date || today }}</time> <button> <a :href="img" :download="file"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"> <path fill="currentColor" d=" M 216 0 h 80 c 13.3 0 24 10.7 24 24 v 168 h 87.7 c 17.8 0 26.7 21.5 14.1 34.1 L 269.7 378.3 c -7.5 7.5 -19.8 7.5 -27.3 0 L 90.1 226.1 c -12.6 -12.6 -3.7 -34.1 14.1 -34.1 H 192 V 24 c 0 -13.3 10.7 -24 24 -24 z m 296 376 v 112 c 0 13.3 -10.7 24 -24 24 H 24 c -13.3 0 -24 -10.7 -24 -24 V 376 c 0 -13.3 10.7 -24 24 -24 h 146.7 l 49 49 c 20.1 20.1 52.5 20.1 72.6 0 l 49 -49 H 488 c 13.3 0 24 10.7 24 24 z m -124 88 c 0 -11 -9 -20 -20 -20 s -20 9 -20 20 s 9 20 20 20 s 20 -9 20 -20 z m 64 0 c 0 -11 -9 -20 -20 -20 s -20 9 -20 20 s 9 20 20 20 s 20 -9 20 -20 z " ></path> </svg> </a> </button> </span> </div> </div> </template> <script lang="ts"> import { computed, defineComponent, ref, toRefs } from 'vue'; export default defineComponent({ props: { img: { type: String, default: '/img/logo/logo-with-name.png', }, text: { type: String, default: '活动掠影', }, date: { type: String, default: '', }, }, setup(props) { const { img, text } = toRefs(props); const file = computed(() => { const index = img.value.lastIndexOf('.'); const extension = img.value.substr(index); return text.value + extension; }); const date = new Date(); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); const today = ref(`${year}年${month}月${day}日`); return { file, today, }; }, }); </script> <style> .card { margin: 20px; background-color: var(--c-bg); border-color: var(--c-border); border-radius: 6px; border-style: solid; border-width: 1px; overflow: hidden; } .image { width: 100%; display: block; } .info { padding: 16px; } .info-top { color: var(--c-text); display: block; font-size: 16px; } .info-bottom { margin-top: 8px; color: var(--c-text-lightest); display: block; font-size: 14px; } .info-bottom > button { padding: 0; border-width: 0; height: 16px; width: 16px; margin: 0; background: transparent; float: right; } </style>
import React, { ReactNode, createContext, useEffect, useState } from 'react'; import axios from 'axios'; import { Contato } from '../../types/contato'; interface ContatoContextProps { contatos: Contato[]; addContato: (contato: Contato) => Promise<void>; editContato: (contato: Contato) => Promise<void>; deleteContato: (id: number) => Promise<void>; } interface ContatoProviderProps { children: ReactNode; } const ContatoContext = createContext<ContatoContextProps>({} as ContatoContextProps); const ContatoProvider: React.FC<ContatoProviderProps> = ({ children }) => { const [contatos, setContatos] = useState<Contato[]>([]); const fetchContatos = async () => { try { const response = await axios.get('http://192.168.68.113:8080/contatos'); setContatos(response.data); } catch (error) { console.error('Houve um erro ao obter os contatos!', error); } }; useEffect(() => { fetchContatos(); }, []); const addContato = async (contato: Contato) => { try { await axios.post('http://192.168.68.113:8080/contatos', contato); fetchContatos(); } catch (error) { console.error('Erro ao adicionar contato', error); } }; const editContato = async (contato: Contato) => { try { await axios.put(`http://192.168.68.113:8080/contatos/${contato.id}`, contato); fetchContatos(); } catch (error) { console.error('Erro ao editar contato', error); } }; const deleteContato = async (id: number) => { try { await axios.delete(`http://192.168.68.113:8080/contatos/${id}`); fetchContatos(); } catch (error) { console.error('Erro ao deletar contato', error); } }; return ( <ContatoContext.Provider value={{ contatos, addContato, editContato, deleteContato, }} > {children} </ContatoContext.Provider> ); }; export { ContatoContext, ContatoProvider };
import logging import os from typing import Dict from unittest.mock import Mock, patch import pytest from backend.layers.common.entities import CollectionId, CollectionVersionId, DatasetStatus, DatasetVersionId from backend.layers.processing.upload_failures.app import ( FAILED_ARTIFACT_CLEANUP_MESSAGE, FAILED_CXG_CLEANUP_MESSAGE, FAILED_DATASET_CLEANUP_MESSAGE, cleanup_artifacts, get_failure_slack_notification_message, parse_event, ) module_path = "backend.layers.processing.upload_failures.app" @pytest.fixture def sample_slack_header_block(): return { "type": "header", "text": { "type": "plain_text", "text": "Dataset failed to process:fire:", "emoji": True, }, } @pytest.fixture def sample_slack_status_block(): return { "type": "section", "text": { "type": "mrkdwn", "text": "```{\n" ' "cxg_status": null,\n' ' "h5ad_status": null,\n' ' "processing_status": null,\n' ' "rds_status": null,\n' ' "upload_status": null,\n' ' "validation_message": null,\n' ' "validation_status": null\n' "}```", }, } @pytest.fixture def sample_slack_status_block_empty(): return { "type": "section", "text": { "type": "mrkdwn", "text": "``````", }, } def test_parse_event_with_empty_event(): ( dataset_id, collection_version_id, error_step_name, error_job_id, error_aws_regions, error_cause, execution_arn, ) = parse_event({}) assert dataset_id is None assert collection_version_id is None assert error_step_name is None assert error_job_id is None assert error_aws_regions is None assert error_cause == "" assert execution_arn is None def test_parse_event_with_error_cause(): expected_error_cause = ( '{"JobName": "Step1", "JobId": "789", "Container": {"Environment": [{"Name": "AWS_DEFAULT_REGION", ' '"Value": "us-east-1"}]}}' ) event = { "execution_id": "arn", "dataset_id": "123", "collection_id": "456", "error": {"Cause": expected_error_cause}, } ( dataset_id, collection_version_id, error_step_name, error_job_id, error_aws_regions, error_cause, execution_arn, ) = parse_event(event) assert dataset_id == "123" assert collection_version_id == "456" assert error_step_name == "Step1" assert error_job_id == "789" assert error_aws_regions == "us-east-1" assert expected_error_cause is error_cause assert execution_arn == "arn" def test_parse_event_without_error_cause(): event = {"dataset_id": "123", "collection_id": "456", "error": {}} ( dataset_id, collection_version_id, error_step_name, error_job_id, error_aws_regions, error_cause, execution_arn, ) = parse_event(event) assert dataset_id == "123" assert collection_version_id == "456" assert error_step_name is None assert error_job_id is None assert error_aws_regions is None assert error_cause == "" assert execution_arn is None def test_parse_event_with_invalid_error_cause(): event = {"dataset_id": "123", "collection_id": "456", "error": {"Cause": "invalid JSON"}} ( dataset_id, collection_version_id, error_step_name, error_job_id, error_aws_regions, error_cause, execution_arn, ) = parse_event(event) assert dataset_id == "123" assert collection_version_id == "456" assert error_step_name is None assert error_job_id is None assert error_aws_regions is None assert error_cause == "invalid JSON" assert execution_arn is None def mock_get_dataset_version(collection_id): MockDatasetVersionId = Mock() MockDatasetVersionId.collection_id = collection_id MockDatasetVersionId.status = DatasetStatus(None, None, None, None, None, None) return MockDatasetVersionId def test_get_failure_slack_notification_message_with_dataset_id_none( sample_slack_header_block, sample_slack_status_block_empty, caplog ): dataset_id = None step_name = "Step 1" job_id = "123456" aws_regions = "us-west-2" execution_arn = "arn:aws:states:us-west-2:123456789012:execution:MyStateMachine" collection_version_id = "collection_version_id123" with caplog.at_level(logging.ERROR): result = get_failure_slack_notification_message( dataset_id, collection_version_id, step_name, job_id, aws_regions, execution_arn ) assert result == { "blocks": [ sample_slack_header_block, { "type": "section", "text": { "type": "mrkdwn", "text": f"Dataset processing job failed! @sc-oncall-eng please follow the [triage steps](https://docs.google.com/document/d/1n5cngEIz-Lqk9737zz3makXGTMrEKT5kN4lsofXPRso/edit#bookmark=id.3ofm47y0709y)\n" "*Owner*: \n" f"*Collection Version URL*: https://cellxgene.cziscience.com/collections/{collection_version_id}\n" "*Batch Job ID*: <https://us-west-2.console.aws.amazon.com/batch/v2/home?region=us-west-2" "#jobs/detail/123456|123456>\n" "*Step Function ARN*: " "<https://us-west-2.console.aws.amazon.com/states/home?region=us-west-2#/v2/executions" "/details/arn:aws:states:us-west-2:123456789012:execution:MyStateMachine|arn:aws:states" ":us-west-2:123456789012:execution:MyStateMachine>\n" f"*Error Step*: {step_name}\n" f"*Dataset ID*: None(not found)\n" f"*Processing Status*:\n", }, }, sample_slack_status_block_empty, ] } assert "Dataset None not found" in caplog.text def test_get_failure_slack_notification_message_with_dataset_not_found( sample_slack_header_block, sample_slack_status_block_empty, caplog ): dataset_id = "dataset123" step_name = "Step 1" job_id = "123456" aws_regions = "us-west-2" execution_arn = "arn:aws:states:us-west-2:123456789012:execution:MyStateMachine" collection_version_id = "collection_version_id123" get_dataset_version_mock = Mock(return_value=None) get_business_logic_mock = Mock() get_business_logic_mock.get_dataset_version = get_dataset_version_mock get_business_logic_constructor_mock = Mock(return_value=get_business_logic_mock) Mock() with patch(f"{module_path}.get_business_logic", get_business_logic_constructor_mock), caplog.at_level( logging.ERROR ): result = get_failure_slack_notification_message( dataset_id, collection_version_id, step_name, job_id, aws_regions, execution_arn ) assert result == { "blocks": [ sample_slack_header_block, { "type": "section", "text": { "type": "mrkdwn", "text": f"Dataset processing job failed! @sc-oncall-eng please follow the [triage steps](https://docs.google.com/document/d/1n5cngEIz-Lqk9737zz3makXGTMrEKT5kN4lsofXPRso/edit#bookmark=id.3ofm47y0709y)\n" "*Owner*: \n" f"*Collection Version URL*: https://cellxgene.cziscience.com/collections/{collection_version_id}\n" "*Batch Job ID*: <https://us-west-2.console.aws.amazon.com/batch/v2/home?region=us-west-2" "#jobs/detail/123456|123456>\n" "*Step Function ARN*: " "<https://us-west-2.console.aws.amazon.com/states/home?region=us-west-2#/v2/executions" "/details/arn:aws:states:us-west-2:123456789012:execution:MyStateMachine|arn:aws:states" ":us-west-2:123456789012:execution:MyStateMachine>\n" f"*Error Step*: {step_name}\n" f"*Dataset ID*: {dataset_id}(not found)\n" f"*Processing Status*:\n", }, }, sample_slack_status_block_empty, ] } assert "Dataset dataset123 not found" in caplog.text get_dataset_version_mock.assert_called_with(DatasetVersionId(dataset_id)) def mock_collection_version(owner, version_id): MockCollectionVersion = Mock() MockCollectionVersion.owner = owner MockCollectionVersion.version_id = version_id return MockCollectionVersion def test_get_failure_slack_notification_message_with_missing_collection( sample_slack_header_block, sample_slack_status_block, caplog ): dataset_id = "dataset123" collection_id = "collection123" collection_version_id = "collection_version_id123" step_name = "Step 1" job_id = "123456" aws_regions = "us-west-2" execution_arn = "arn:aws:states:us-west-2:123456789012:execution:MyStateMachine" get_dataset_version_mock = Mock(return_value=mock_get_dataset_version(CollectionId(collection_id))) get_unpublished_collection_version_from_canonical_mock = Mock(return_value=None) get_business_logic_mock = Mock() get_business_logic_mock.get_dataset_version = get_dataset_version_mock get_business_logic_mock.get_unpublished_collection_version_from_canonical = ( get_unpublished_collection_version_from_canonical_mock ) get_business_logic_constructor_mock = Mock(return_value=get_business_logic_mock) Mock() with patch(f"{module_path}.get_business_logic", get_business_logic_constructor_mock), caplog.at_level( logging.ERROR ): result = get_failure_slack_notification_message( dataset_id, collection_version_id, step_name, job_id, aws_regions, execution_arn ) assert result == { "blocks": [ sample_slack_header_block, { "type": "section", "text": { "type": "mrkdwn", "text": f"Dataset processing job failed! @sc-oncall-eng please follow the [triage steps](https://docs.google.com/document/d/1n5cngEIz-Lqk9737zz3makXGTMrEKT5kN4lsofXPRso/edit#bookmark=id.3ofm47y0709y)\n" f"*Owner*: \n" f"*Collection Version URL*: https://cellxgene.cziscience.com/collections/{collection_version_id}\n" "*Batch Job ID*: <https://us-west-2.console.aws.amazon.com/batch/v2/home?region=us-west-2" "#jobs/detail/123456|123456>\n" "*Step Function ARN*: " "<https://us-west-2.console.aws.amazon.com/states/home?region=us-west-2#/v2/executions" "/details/arn:aws:states:us-west-2:123456789012:execution:MyStateMachine|arn:aws:states" ":us-west-2:123456789012:execution:MyStateMachine>\n" f"*Error Step*: {step_name}\n" f"*Dataset ID*: {dataset_id}\n" f"*Processing Status*:\n", }, }, sample_slack_status_block, ] } assert f"Collection {collection_id} not found" in caplog.text get_dataset_version_mock.assert_called_with(DatasetVersionId(dataset_id)) get_unpublished_collection_version_from_canonical_mock.assert_called_with(CollectionId(collection_id)) def test_get_failure_slack_notification_message_with_dataset_and_collection( sample_slack_header_block, sample_slack_status_block ): dataset_id = "dataset123" collection_id = "collection123" step_name = "Step 1" job_id = "123456" aws_regions = "us-west-2" execution_arn = "arn:aws:states:us-west-2:123456789012:execution:MyStateMachine" owner = "test" collection_version_id = "version123" get_dataset_version_mock = Mock(return_value=mock_get_dataset_version(CollectionId(collection_id))) get_unpublished_collection_version_from_canonical_mock = Mock( return_value=mock_collection_version(owner, CollectionVersionId(collection_version_id)) ) get_business_logic_mock = Mock() get_business_logic_mock.get_dataset_version = get_dataset_version_mock get_business_logic_mock.get_unpublished_collection_version_from_canonical = ( get_unpublished_collection_version_from_canonical_mock ) get_business_logic_constructor_mock = Mock(return_value=get_business_logic_mock) with patch(f"{module_path}.get_business_logic", get_business_logic_constructor_mock): result = get_failure_slack_notification_message( dataset_id, collection_version_id, step_name, job_id, aws_regions, execution_arn ) assert result == { "blocks": [ sample_slack_header_block, { "type": "section", "text": { "type": "mrkdwn", "text": f"Dataset processing job failed! @sc-oncall-eng please follow the [triage steps](https://docs.google.com/document/d/1n5cngEIz-Lqk9737zz3makXGTMrEKT5kN4lsofXPRso/edit#bookmark=id.3ofm47y0709y)\n" f"*Owner*: {owner}\n" f"*Collection Version URL*: https://cellxgene.cziscience.com/collections/{collection_version_id}\n" "*Batch Job ID*: <https://us-west-2.console.aws.amazon.com/batch/v2/home?region=us-west-2" "#jobs/detail/123456|123456>\n" "*Step Function ARN*: " "<https://us-west-2.console.aws.amazon.com/states/home?region=us-west-2#/v2/executions" "/details/arn:aws:states:us-west-2:123456789012:execution:MyStateMachine|arn:aws:states" ":us-west-2:123456789012:execution:MyStateMachine>\n" f"*Error Step*: {step_name}\n" f"*Dataset ID*: {dataset_id}\n" f"*Processing Status*:\n", }, }, sample_slack_status_block, ] } get_dataset_version_mock.assert_called_with(DatasetVersionId(dataset_id)) get_unpublished_collection_version_from_canonical_mock.assert_called_with(CollectionId(collection_id)) @pytest.fixture def mock_env_vars() -> Dict[str, str]: mock_env_vars = { "ARTIFACT_BUCKET": "artifact_bucket", "DATASETS_BUCKET": "datasets_bucket", "CELLXGENE_BUCKET": "cxg_bucket", } with patch.dict(os.environ, mock_env_vars): yield mock_env_vars @pytest.fixture def mock_delete_many_from_s3() -> Mock: with patch(f"{module_path}.delete_many_from_s3") as mock_delete_many_from_s3: yield mock_delete_many_from_s3 @pytest.fixture def dataset_id() -> str: return "example_dataset" class TestCleanupArtifacts: @pytest.mark.parametrize("error_step", ["download-validate", "", None]) def test_cleanup_artifacts__OK(self, mock_env_vars, mock_delete_many_from_s3, dataset_id, error_step): """Check that all artifacts are deleted for the given cases.""" cleanup_artifacts(dataset_id, error_step) # Assertions mock_delete_many_from_s3.assert_any_call(mock_env_vars["ARTIFACT_BUCKET"], dataset_id + "/") mock_delete_many_from_s3.assert_any_call(mock_env_vars["DATASETS_BUCKET"], dataset_id + ".") mock_delete_many_from_s3.assert_any_call(mock_env_vars["CELLXGENE_BUCKET"], dataset_id + ".cxg/") assert mock_delete_many_from_s3.call_count == 3 def test_cleanup_artifacts__not_download_validate(self, mock_env_vars, mock_delete_many_from_s3, dataset_id): """Check that file in the artifact bucket are not delete if error_step is not download-validate.""" cleanup_artifacts(dataset_id, "not_download_validate") # Assertions mock_delete_many_from_s3.assert_any_call(mock_env_vars["DATASETS_BUCKET"], dataset_id + ".") mock_delete_many_from_s3.assert_any_call(mock_env_vars["CELLXGENE_BUCKET"], dataset_id + ".cxg/") assert mock_delete_many_from_s3.call_count == 2 @patch.dict(os.environ, clear=True) def test_cleanup_artifacts__no_buckets(self, caplog, mock_delete_many_from_s3, dataset_id): """Check that no files are deleted if buckets are not specified.""" cleanup_artifacts(dataset_id) # Assertions mock_delete_many_from_s3.assert_not_called() assert FAILED_ARTIFACT_CLEANUP_MESSAGE in caplog.text assert FAILED_CXG_CLEANUP_MESSAGE in caplog.text assert FAILED_DATASET_CLEANUP_MESSAGE in caplog.text def test_cleanup_artifacts__elete_many_from_s3_error( self, caplog, mock_env_vars, mock_delete_many_from_s3, dataset_id ): """Check that delete_many_from_s3 errors are logged but do not raise exceptions.""" mock_delete_many_from_s3.side_effect = Exception("Boom!") cleanup_artifacts(dataset_id) # Assertions mock_delete_many_from_s3.assert_any_call(mock_env_vars["ARTIFACT_BUCKET"], dataset_id + "/") mock_delete_many_from_s3.assert_any_call(mock_env_vars["DATASETS_BUCKET"], dataset_id + ".") mock_delete_many_from_s3.assert_any_call(mock_env_vars["CELLXGENE_BUCKET"], dataset_id + ".cxg/") assert mock_delete_many_from_s3.call_count == 3 assert FAILED_ARTIFACT_CLEANUP_MESSAGE in caplog.text assert FAILED_CXG_CLEANUP_MESSAGE in caplog.text assert FAILED_DATASET_CLEANUP_MESSAGE in caplog.text
<template> <div> <span v-html="htmlContent"></span> </div> </template> <script lang="ts"> import { Component, Prop, Vue, Watch } from 'vue-property-decorator' import MarkdownIt from 'markdown-it' const md = new MarkdownIt(({ html: true })) @Component export default class MarkdownDisplay extends Vue { @Prop() private markdown!: string htmlContent: string = '' beforeMount() { this.generateHtml() } @Watch('markdown') onMarkdownInputChange(newMarkdown: string) { this.generateHtml() } generateHtml() { try { this.htmlContent = md.render(this.markdown) } catch (error) { /* eslint-disable no-console */ console.error(error) this.htmlContent = `Error: ${error.message}` } } } </script>
import React, { useEffect, useState } from 'react'; import axios from 'axios'; const Check = () => { const [data, setData] = useState(null); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await axios.get('http://localhost:8000/api/my-posts', { headers: { Authorization: 'Token d77cf0791b4c11251a7de4f2ae1ef53a4f99a842', }, }); setData(response.data); } catch (err) { setError(err); } }; fetchData(); }, []); return ( <div> {error && <p>Error: {error.message}</p>} {data && ( <div> {data.map(item => ( <div key={item.id}> <h2>{item.title}</h2> <p>{item.content}</p> <p>Created at: {item.created_at}</p> </div> ))} </div> )} </div> ); }; export default Check;
import React, { Component } from "react"; import { CometChat } from "@cometchat-pro/chat"; import { CC_APP_ID, CC_API_KEY, CC_API_REGION } from "../../constants"; import ChatContainer from "./ChatContainer"; import Cookies from "js-cookie"; import jwt_decode from "jwt-decode"; import axios from "axios"; var groupsRequest = new CometChat.GroupsRequestBuilder() .joinedOnly(true) .setLimit(50) .build(); export default class OrgBase extends Component { state = { username: "", authToken: "", errors: [], formData: {}, eventList: [], groupListId: [], name: "" }; componentDidMount() { //initialize cometchat CometChat.init( CC_APP_ID, new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(CC_API_REGION) .build() ); if (Cookies.get("token") && Cookies.get("type") === "/odashboard/") { //cometchat initialze console.log("Initialization completed successfully"); // You can now call login function. var UID = jwt_decode(Cookies.get("token")).uid; const p = this; //getformdata axios .get("/organizer/" + UID) .then(function(response) { p.setState({ formData: response.data }); p.setState({ name: response.data.Name }); let nam = response.data.Name; nam = nam.replace(/\s+/g, ''); p.setState({ username: UID + nam + UID }); //get registered events axios .get("/event/organizer/" + UID) .then(function(response) { p.setState({ eventList: response.data }); //login with name id on formdata p.loginUser(); }) .catch(function(error) { console.log(error); }); }) .catch(function(error) { console.log(error); }); } else { this.props.history.push("/"); } document.getElementById("orgbase").style.overflow = "hidden"; } loginUser() { const username = this.state.username; CometChat.login(username, CC_API_KEY).then( user => { this.setState({ username: username, authToken: user.authToken, loginBtnDisabled: false }); this.joinedGroups(this.state.groupID); }, error => { this.createUser(); this.setState({ error: "Username and/or password is incorrect." }); } ); } createUser = () => { var endPoint = "https://api-us.cometchat.io/v2.0/users"; var data = { uid: this.state.username, name: this.state.name }; var xhr = new XMLHttpRequest(); let p = this; xhr.addEventListener("readystatechange", function() { if (this.readyState === this.DONE) { console.log(this.responseText); p.createAuthToken(); } }); xhr.open("POST", endPoint); xhr.setRequestHeader("appid", CC_APP_ID); xhr.setRequestHeader("apikey", CC_API_KEY); xhr.setRequestHeader("content-type", "application/json"); xhr.setRequestHeader("accept", "application/json"); xhr.send(JSON.stringify(data)); }; createAuthToken() { var data = null; let p = this; var xhr = new XMLHttpRequest(); xhr.addEventListener("readystatechange", function() { if (this.readyState === this.DONE) { console.log(this.responseText); p.loginUser(); } }); xhr.open( "POST", "https://api-us.cometchat.io/v2.0/users/" + this.state.username + "/auth_tokens" ); xhr.setRequestHeader("appid", CC_APP_ID); xhr.setRequestHeader("apikey", CC_API_KEY); xhr.setRequestHeader("content-type", "application/json"); xhr.setRequestHeader("accept", "application/json"); xhr.send(data); } handleLogout = () => { CometChat.logout().then( () => { window.location.reload(true); }, error => { window.location.reload(true); } ); }; joinedGroups() { groupsRequest.fetchNext().then( groupList => { let groupID = []; // let groupListId=[] /* groupList will be the list of Group class */ console.log("Groups list fetched successfully", groupList); /* you can display the list of groups available using groupList */ // if (groupList.length>0){ // groupList.forEach(element=>groupListId.push((element['guid']))) // } if (groupList.length > 0) { groupList.forEach(el => this.state.groupListId.push(el["guid"])); } let groupListId = this.state.groupListId; this.setState({ groupListId }); this.state.eventList.forEach(element => { if (!this.state.groupListId.includes(String(element["id"]))) { groupID.push(element); } }); // let difference = groupID.filter(x => !groupListId.includes(x)); console.log(this.state.groupListId, groupList); if (groupID.length > 0) { groupID.forEach(element => this.createGroup(element)); } }, error => { console.log("Groups list fetching failed with error", error); } ); } createGroup(formd) { var GUID = String(formd["id"]); var groupName = formd["EventName"]; var groupType = CometChat.GROUP_TYPE.PUBLIC; var password = ""; var group = new CometChat.Group(GUID, groupName, groupType, password); CometChat.createGroup(group).then( group => { console.log("Group created successfully:", group); this.state.groupListId.push(GUID); }, error => { console.log("Group creation failed with exception:", error); } ); } render() { const userstate = this.state; return ( <React.Fragment> <div className="container-fluid"> <div className="row"> <main className="col-12 col-md-12 col-xl-12"> {this.state.username !== "" && ( <ChatContainer user={userstate} uid={this.state.username} handleLogout={this.handleLogout} /> )} </main> </div> </div> </React.Fragment> ); } }
=== Members Restricted Access === Contributors: mcostales84 Donate Link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=VWWTUHZWRS4DG Tags: restrict access, members, visitor, restric by role Requires at least: 3.0.1 Tested up to: 4.4.2 Stable tag: 3.0 License: GPLv2 License URI: http://www.gnu.org/licenses/gpl-2.0.html This plugin creates shortcodes to restrict the access to users (visitors, members or by an specific role). You can also add a shortcode and use nested shortcodes. == Description == This plugin create shortcodes to restrict the access to Visitors, Members or specific role. You can create sections in your page/post only visible to members (logged users), visitors or for an specific role. To use you need to create the content and wrap it with these shortcodes: [visitor], [member] or [showifrole]. * You can use the parameters 'is' and 'msg'. If you not specify them, the default value will be use instead. * The paramater 'is' is use it with the shortcode [showifrole] to check for that specific user. The default value is 'administrator'. * And 'msg' is the message the system is going to show. You can use html code with single apostrophes ('). The default value is null. Examples: '[visitor] content only visible to visitors [/visitor] [member msg="You need to <a href='/wp-login'>Login</a> to see this content."] content only visible to members [/member] [showifrole is=administrator] content only visible for administrators [/showifrole] [showifrole is=author msg="You don't have the required role."] content only visible for authors [showifrole]' == Installation == To install this plugin just follow the standard procedure. or 1. Upload `members-restricted-access.php` to the `/wp-content/plugins/` directory 2. Activate the plugin through the 'Plugins' menu in WordPress == Frequently Asked Questions == = Any question? = Send me an email at mcostales@jumptoweb.com and I will answer you as soon as I can. == Changelog == = 3.0 = - Now you can use nested shortcodes, so you can use a any shortcode inside our shortcode verification. = 2.1 = - Add the parameters for message in the members, visitors and showifrole shortcodes. - Add a default value for 'is' and 'msg'. = 2.0 = - Added the shortcode to check by role. = 1.0 = - Just launch the plugin!
import { Heading, Text } from '@radix-ui/themes'; import React from 'react' import { useNavigate } from 'react-router-dom'; interface IConversationCard { id: number; channelId: string | undefined; name: string; description: string; } function ConversationCard({ id, channelId, name, description }: IConversationCard) { const navigate = useNavigate() const openConversation = () => { navigate(`/channel/${channelId}/conversation/${id}`) } return ( <div className='drop-shadow-md bg-paynesgray text-white rounded-sm p-5 hover:bg-gray-800 transition cursor-pointer' onClick={openConversation}> <Heading size="5">{name}</Heading> <Text>{description}</Text> </div> ) } export default ConversationCard
const cluster = require("node:cluster"); const express = require("express"); const dotenv = require("dotenv"); const nodemailer = require("nodemailer"); const os = require("os"); const fs = require("fs"); const cookieParser = require("cookie-parser"); const csv = require("csv-parser"); const cors = require("cors"); const bodyParser = require("body-parser"); const { upload } = require("./middleware/multer"); dotenv.config(); const app = express(); app.use(cors()); app.use(cookieParser()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const numCPUs = os.cpus().length; if (cluster.isPrimary) { console.log(`Primary Server PID:- ${process.pid} is running`); for (let i = 0; i < numCPUs; i++) { cluster.fork(); } } else { const PORT = process.env.PORT || 5432; app.get("/", (_, res) => { return res.send({ numberCPUs: `(${numCPUs})Core CPUs`, server: ` ${process.pid}`, projectName: "Email Broadcast", }); }); app.post("/send-emails", upload.single("file"), (req, res) => { const { email, password, subject, body } = req.body; const file = req?.file; const filePath = req?.file?.path; if (!(email && password && subject && body)) { return res.status(404).send({ message: "Fields Required" }); } let domain = email?.match(/@gmail\.com$/); if (!filePath) { return res.status(404).send({ message: "File Required" }); } if (!(file?.mimetype === "text/csv")) { return res.status(404).send({ message: "only CSV File Allowed" }); } if (!domain) { return res.status(404).send({ message: "Only Gmail Allowed" }); } // fs.readFile("uploads/clients.csv", "utf8", (err, data) => { // if (err) { // console.error(err); // console.log("step-1-done"); // return; // } // const updatedContent = content + data; // fs.writeFile("uploads/clients.csv", updatedContent, (error, result) => { // error ? console.log(error) : console.log(result); // }); // console.log("step-2-done"); // return; // }); try { const transporter = nodemailer.createTransport({ host: "smtp.gmail.com", port: 465, secure: true, auth: { user: `${email}`, pass: `${password}`, }, }); const message = { from: `${email}`, subject: `${subject}`, text: `${body}`, }; fs.createReadStream("uploads/clients.csv") .pipe(csv()) .on("data", (row) => { message.to = row.email; transporter.sendMail(message, (error, info) => { try { if (error) { res.status(error?.responseCode).json(error); } else { console.log(`Email sent: ${info}`); res .status(202) .send({ message: "Email Sent Success.", info: info }); } } catch (error) { res.status(500).json(error); } }); }) .on("end", () => { console.log("Send Process Done..."); }); } catch (error) { res.status(500).json(error); } }); app.listen(PORT, () => { console.log(`🎉🎉 Server PID:- ${process.pid} on http://localhost:${PORT}`); }); }
--- title: deleteMessagesFromUser description: Deletes all messages in the chat sent by the specified user. Works only in supergroup channel chats, needs appropriate privileges --- ## Method: deleteMessagesFromUser [Back to methods index](index.md) Deletes all messages in the chat sent by the specified user. Works only in supergroup channel chats, needs appropriate privileges ### Params: | Name | Type | Required | Description | |----------|:-------------:|:--------:|------------:| |chat\_id|[InputPeer](../types/InputPeer.md) | Yes|Chat identifier| |user\_id|[int](../types/int.md) | Yes|User identifier| ### Return type: [Ok](../types/Ok.md) ### Example: ``` $MadelineProto = new \danog\MadelineProto\API(); if (isset($token)) { // Login as a bot $this->bot_login($token); } if (isset($number)) { // Login as a user $sentCode = $MadelineProto->phone_login($number); echo 'Enter the code you received: '; $code = ''; for ($x = 0; $x < $sentCode['type']['length']; $x++) { $code .= fgetc(STDIN); } $MadelineProto->complete_phone_login($code); } $Ok = $MadelineProto->deleteMessagesFromUser(['chat_id' => InputPeer, 'user_id' => int, ]); ``` Or, if you're into Lua: ``` Ok = deleteMessagesFromUser({chat_id=InputPeer, user_id=int, }) ```
package com.timeless.events.controller.impl; import com.timeless.events.controller.ICountryController; import com.timeless.events.dto.entity.country.CountryRequest; import com.timeless.events.dto.entity.country.CountryResponse; import com.timeless.events.service.ICountryService; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.UUID; @Validated @RestController @RequestMapping(value = "v1/") public class CountryControllerImpl implements ICountryController { private final ICountryService iCountryService; @Autowired CountryControllerImpl(ICountryService iCountryService){ this.iCountryService = iCountryService; } @Override @PostMapping("/countries") public ResponseEntity<Void> createCountry(@Valid @RequestBody CountryRequest countryRequestDto) throws Exception{ iCountryService.createCountry(countryRequestDto); return new ResponseEntity<>(HttpStatus.CREATED); } @Override @GetMapping("/countries") public ResponseEntity<List<CountryResponse>> getAllCountry() { return new ResponseEntity<>(iCountryService.getAllCountry(), HttpStatus.OK); } @Override @GetMapping("/countries/{id}") public ResponseEntity<CountryResponse> getCountryById(@NotNull @PathVariable("id") UUID id) throws Exception { return new ResponseEntity<>(iCountryService.getCountryById(id), HttpStatus.OK); } @Override @PutMapping("/countries/{id}") public ResponseEntity<Void> updateCountry(@NotNull @PathVariable("id") UUID id , @Valid @RequestBody CountryRequest countryRequestDto) throws Exception { iCountryService.updateCountry(id, countryRequestDto); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Override @DeleteMapping("countries/{id}") public ResponseEntity<Void> deleteCountry(@NotNull @PathVariable("id") UUID id) throws Exception { iCountryService.deleteCountry(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } }
package com.mdd.coupon.validate; import com.mdd.common.validate.BaseParam; import com.mdd.common.validator.annotation.IDMust; import com.mdd.common.validator.annotation.IDLongMust; import com.mdd.common.validator.annotation.IntegerContains; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.hibernate.validator.constraints.Length; import lombok.Data; import javax.validation.constraints.*; import java.math.BigDecimal; import java.math.BigDecimal; import java.math.BigDecimal; /** * 秒杀活动商品关联参数 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class SeckillSkuRelationParam extends BaseParam { @IDLongMust(message = "id参数必传且需大于等于0", groups = {update.class, delete.class, change.class}) private Long id; @NotNull(message = "promotionId参数缺失", groups = {create.class, update.class}) @DecimalMin(value = "0", message = "promotionId参数值不能少于0", groups = {create.class, update.class}) private Long promotionId; @NotNull(message = "promotionSessionId参数缺失", groups = {create.class, update.class}) @DecimalMin(value = "0", message = "promotionSessionId参数值不能少于0", groups = {create.class, update.class}) private Long promotionSessionId; @NotNull(message = "skuId参数缺失", groups = {create.class, update.class}) @DecimalMin(value = "0", message = "skuId参数值不能少于0", groups = {create.class, update.class}) private Long skuId; @NotNull(message = "seckillPrice参数缺失", groups = {create.class, update.class}) private BigDecimal seckillPrice; @NotNull(message = "seckillCount参数缺失", groups = {create.class, update.class}) private BigDecimal seckillCount; @NotNull(message = "seckillLimit参数缺失", groups = {create.class, update.class}) private BigDecimal seckillLimit; @NotNull(message = "seckillSort参数缺失", groups = {create.class, update.class}) @DecimalMin(value = "0", message = "seckillSort参数值不能少于0", groups = {create.class, update.class}) private Integer seckillSort; }
{% extends 'form_div_layout.html.twig' %} {# widgets #} {%- block widget_attributes -%} {%- if id %}id="{{ id }}"{% endif -%} name="{{ full_name }}" {%- if disabled %} disabled{% endif -%} {%- if required %} required{% endif -%} {{ block('attributes') }} {%- endblock widget_attributes -%} {%- block form_widget_simple -%} {%- set label = (label | default('')) | trans -%} {%- set attr = attr | merge({ class: ('input input--expand' ~ (errors is not empty ? ' input--error' : ' ') ~ (attr.class | default(''))) | trim, type: type | default('text'), placeholder: attr.placeholder | default(label) }) -%} <input {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %} /> {%- endblock -%} {%- block textarea_widget -%} {%- set label = (label | default('')) | trans -%} {%- set attr = attr | merge({ class: ('textarea textarea--expand' ~ (errors is not empty ? ' textarea--error' : ' ') ~ (attr.class | default(''))) | trim, placeholder: attr.placeholder | default(label) }) -%} <textarea {{ block('widget_attributes') }}>{% if value is not empty %}{{ value }}{% endif %}</textarea> {%- endblock textarea_widget -%} {%- block choice_widget_collapsed -%} {%- if required and placeholder is none and not placeholder_in_choices and not multiple and (attr.size is not defined or attr.size <= 1) -%} {% set required = false %} {%- endif -%} {%- set modifiers = errors is empty ? ['full-width'] : ['full-width', 'error'] -%} {% embed molecule('custom-select') with { modifiers: modifiers, attributes: { multiple: multiple, placeholder: placeholder, required: required, 'config-width': '100%' }, embed: { attributes: block('widget_attributes'), value: value, translation_domain: translation_domain, preferred_choices: preferred_choices, choices: choices, separator: separator, choice_translation_domain: choice_translation_domain, class: attr.class ?? '', } } only %} {% block selectAttributes %} {{ parent() }} {{ embed.attributes | raw }} {% endblock %} {% block selectClass %} {{ parent() }} {{ embed.class }} {% endblock %} {% block options %} {%- if attributes.placeholder is not none -%} <option value=""{% if attributes.required and embed.value is empty %} selected="selected"{% endif %}> {{ attributes.placeholder != '' ? (embed.translation_domain is same as(false) ? attributes.placeholder : attributes.placeholder|trans({}, embed.translation_domain)) }} </option> {%- endif -%} {%- if embed.preferred_choices|length > 0 -%} {% set options = embed.preferred_choices %} {{- block('renderOptions') -}} {%- if attributes.choices|length > 0 and embed.separator is not none -%} <option disabled="disabled">{{ embed.separator }}</option> {%- endif -%} {%- endif -%} {%- set options = embed.choices -%} {%- block renderOptions -%} {% for group_label, choice in options %} {%- if choice is iterable -%} <optgroup label="{{ embed.choice_translation_domain is same as(false) ? group_label : group_label|trans({}, embed.choice_translation_domain) }}"> {% set options = choice %} {{- block('renderOptions') -}} </optgroup> {%- else -%} <option value="{{ choice.value }}"{% if choice.attr %}{% with { attr: choice.attr } %}{{ block('attributes') }}{% endwith %}{% endif %}{% if choice is selectedchoice(embed.value) %} selected="selected"{% endif %}> {{ embed.choice_translation_domain is same as(false) ? choice.label : choice.label|trans({}, embed.choice_translation_domain) }} </option> {%- endif -%} {% endfor %} {%- endblock -%} {% endblock %} {% endembed %} {%- endblock -%} {% block choice_widget_expanded -%} <ul class="list {{ '--inline' in label_attr.class|default('') ? 'list--inline' : 'list--checkbox' }}" {{ block('widget_container_attributes') }}> {% for child in form %} <li class="list__item list__item--checkbox"> {{- form_errors(child, { parent_label_class: label_attr.class|default(''), }) -}} {{- form_widget(child, { parent_label_class: label_attr.class|default(''), }) -}} </li> {% endfor %} </ul> {%- endblock choice_widget_expanded %} {%- block checkbox_widget -%} {%- set type = type | default('checkbox') -%} {%- set component = component | default(atom(type)) -%} {%- set label = label | default(name | humanize) | trans -%} {%- set modifiers = errors is empty ? ['expand'] : ['expand', 'error'] -%} {%- set inputClass = attr.class | default -%} {% define attributes = { id: id, name: full_name, checked: checked | default(false), required: required | default(false), disabled: disabled | default(false), value: value | default() } %} {% include component with { modifiers: modifiers, data: { label: label, inputClass: inputClass, }, attributes: attributes } only %} {%- endblock -%} {%- block radio_widget -%} {% set type = 'radio' %} {{block('checkbox_widget')}} {%- endblock -%} {%- block password_widget -%} {%- set attr = attr | merge({ id: id | default(false), placeholder: attr.placeholder | default(label) | trans(attr_translation_parameters, translation_domain), name: full_name, disabled: disabled | default(false), required: required | default(false), }) -%} {% if attr.title | default %} {%- set attr = attr | merge({ title: attr.title | trans(attr_translation_parameters, translation_domain), }) -%} {% endif %} {% set inputComplexityJsCLass = 'js-password-complexity-indicator__' ~ attr.name %} {% include molecule('password-field') with { data: { inputAttributes: attr, inputExtraClasses: ('input input--expand ' ~ (errors is not empty ? ' input--error ') ~ (attr.class | default) ~ inputComplexityJsCLass) | trim, }, } only %} {% if attr.password_complexity_indicator | default %} {% include molecule('password-complexity-indicator') with { attributes: { 'input-class-name': inputComplexityJsCLass, }, } only %} {% endif %} {%- endblock password_widget -%} {# rows #} {%- block form_row -%} {%- set rowClass = rowAttr.class | default('') -%} <div class="{{rowClass}}"> {{- form_label(form) -}} {{- form_errors(form) -}} {{- form_widget(form) -}} </div> {%- endblock -%} {%- block form_rows -%} {% for child in form %} {% if not child.isRendered %} {{- form_row(child, { rowAttr: rowAttr | default({}) }) -}} {% endif %} {% endfor %} {%- endblock -%} {%- block checkbox_row -%} {%- set rowClass = rowAttr.class | default('') -%} <div class="{{rowClass}}"> {{- form_widget(form) -}} {{- form_errors(form) -}} </div> {%- endblock -%} {%- block radio_row -%} {{- block('checkbox_row') -}} {%- endblock -%} {# labels #} {%- block form_label -%} {% if label is not same as(false) -%} {% if not compound -%} {% set label_attr = label_attr|merge({'for': id, 'class': (label_attr.class|default('') ~ ' label')|trim}) %} {% else %} {% set label_attr = label_attr|merge({'for': id, 'class': (label_attr.class|default('') ~ ' label label--title')|trim}) %} {%- endif -%} {% if required -%} {% set label_attr = label_attr|merge({'class': (label_attr.class|default('') ~ ' label--required')|trim}) %} {%- endif -%} {% if label is empty -%} {%- if label_format is not empty -%} {% set label = label_format|replace({ '%name%': name, '%id%': id, }) %} {%- else -%} {% set label = name|humanize %} {%- endif -%} {%- endif -%} <label{% if label_attr %}{% with { attr: label_attr } %}{{ block('attributes') }}{% endwith %}{% endif %}>{{ translation_domain is same as(false) ? label : label|trans({}, translation_domain) }}</label> {%- endif -%} {%- endblock -%} {# errors #} {% block form_errors %} {% apply spaceless %} {% if errors | length > 0 %} <ul class="list list--bullet list--alert"> {% for error in errors %} <li class="list__item">{{ error.message | trans }}</li> {% endfor %} </ul> {% endif %} {% endapply %} {% endblock %} {%- block datetime_widget -%} {% if widget == 'single_text' %} {%- set label = (label | default('')) | trans -%} {%- set attr = attr | merge({ class: ('input input--expand ' ~ (errors is not empty ? 'input--error ') ~ (attr.class | default(''))) | trim, type: 'text', autocomplete: 'off', placeholder: 'yyyy-mm-dd HH:mm', }) -%} <input {{ block('widget_attributes') }} {% if value %}value="{{ value }}" {% endif %}> {%- else -%} <div {{ block('widget_container_attributes') }}> {{- form_errors(form.date) -}} {{- form_errors(form.time) -}} {{- form_widget(form.date) -}} {{- form_widget(form.time) -}} </div> {%- endif -%} {%- endblock datetime_widget -%} {%- block date_widget -%} {%- if widget == 'single_text' -%} {%- set label = (label | default('')) | trans -%} {%- set attr = attr | merge({ class: ('input input--expand ' ~ (errors is not empty ? 'input--error ') ~ (attr.class | default(''))) | trim, type: 'text', autocomplete: 'off', placeholder: 'yyyy-mm-dd', }) -%} <input {{ block('widget_attributes') }} {% if value %}value="{{ value }}" {% endif %}> {%- else -%} <div {{ block('widget_container_attributes') }}> {{- date_pattern|replace({ '{{ year }}': form_widget(form.year), '{{ month }}': form_widget(form.month), '{{ day }}': form_widget(form.day), })|raw -}} </div> {%- endif -%} {%- endblock date_widget -%}
<?PHP //Ejercicio 1: Semáforo //Cree una función llamada Semaforo, que recibe por parametro un cólor cómo texto (“rojo” //“amarillo”,”verde”). Dicha función devolverá el estado que corresponde: “frene”, “precaución”, //“avance” o “estado desconocido” ante un caso no esperado. //a) función semaforo_a($color): Resuelva la solución utilizando if else //b) función semaforo_b($color): Resuelva la solución utilizando if inline (return ?: ) //c) función semaforo_c($color): Resuelva la solución utilizando switch function semaforo_a($color){ if($color=="rojo"){ echo "frene" . "<br>"; }else if($color=="amarillo"){ echo "precaucion" . "<br>"; }else if($color=="verde"){ echo "avance" . "<br>"; }else{ echo "estado desconocido" . "<br>"; } } function semaforo_b($color){ //`(a ? b : c) ? d : e` or `a ? b : (c ? d : e)` $semaforo = ($color ==="rojo") ? "frene" . "<br>" : (($color === "amarillo") ? "precaucion" . "<br>" : (($color ==="verde") ? "avance" . "<br>" : "estado desconocido <br>")); echo $semaforo; } function semaforo_c($color){ switch($color){ case "rojo": echo "frene " . "<br>"; break; case "amarillo" : echo "precaucion" ."<br>"; break; case "verde": echo "avance" . "<br>"; break; default: echo "estado desconocido" . "<br>"; break; } }
/* Task: Shortest Segment with Sum at Least K A financial company trades on the stock exchange for n days. Its earnings for each day are known (it can be negative if the company traded unfavorably that day). Determine the minimum number of consecutive days in which the sum of the company's earnings is at least k. Input: The standard input includes an integer k (1 ≤ k ≤ 105), followed by the number of days n (1 ≤ n ≤ 105). In the next line, enter the earnings for each of the n days (integers between -2000 and 2000). Output: Print to the standard output the requested minimum number of days, or - if the company has never achieved a cumulative earning of k during those n days. Example 1: Input 15 10 1 -2 3 4 5 4 3 2 -1 2 Output 4 Explanation: A total earnings of 15 is achieved, for example, on the days with earnings 3, 4, 5, 4. Example 2: Input 13 10 1 -2 3 4 5 4 3 2 -1 2 Output 3 Explanation: A total earnings of 13 is achieved, for example, on the days with earnings 4, 5, 4. Example 3: Input 30 10 1 -2 3 4 5 4 3 2 -1 2 Output - */ #include <bits/stdc++.h> using namespace std; typedef long long ll; #define forn(i, n) for (int i = 0; i < int(n); i++) #define forn1(i, n) for (int i = 1; i < int(n); i++) #define all(c) (c).begin(), (c).end() #define pb push_back #define MOD 1000000007 // 998244353 #define FIO \ ios::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0); bool found(vector <int> a, int n, int k, int mid) { int i = 0; int sum = 0; while(i < mid) sum += a[i++]; if (sum >= k) return true; for(; i < n; i++) { sum -= a[i - mid]; sum += a[i]; if (sum >= k) return true; } return false; } int main() { int k, n; cin >> k >> n; vector <int> a(n); for (int &x : a) cin >> x; int start = 0, end = n; int mn = INT_MAX; while(start < end) { int mid = start + (end - start) / 2; if (found(a, n, k, mid)) {end = mid; mn = min(mn, mid);} else start = mid + 1; } if (mn != INT_MAX) cout << mn; else cout << "-"; }
@extends('AdminPanel.Layouts.app') @section('page_title') @lang('app.UPDATE') @lang('app.METHODOLOGY') @lang('app.DESC') @endsection @section('content') <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">@lang('app.UPDATE')</h3> <img id="img-preview" class="card-image" src="{{ asset('uploads/methodologyDetails/' . $methodologyDetail->icon_image) }}" alt="Panner" srcset=""> </div> <!-- /.card-header --> <!-- form start --> <form role="form" action="{{ route('methodologyDetail.update', ['methodologyDetail' => $methodologyDetail->id]) }}" method="post" enctype="multipart/form-data"> @csrf @method('PUT') <div class="card-body"> <div class="form-group"> <label for="exampleInputEmail1">@lang('app.NAME')</label> <input type="text" name="name" value="{{ $methodologyDetail->name }}" class="form-control" id="exampleInputName" placeholder="@lang('app.Enter') @lang('app.NAME')"> </div> @error('name') <div class="alert alert-danger">{{ $message }}</div> @enderror <div class="form-group"> <label for="exampleInputFile">@lang('app.IMAGE')</label> <div class="input-group"> <div class="custom-file"> <input type="file" onchange="showPreview(event)" class="custom-file-input" name="icon_image" id="exampleInputFile" {{ $methodologyDetail->icon_image }}> <label class="custom-file-label" for="exampleInputFile">Choose Icon</label> </div> </div> </div> @error('icon_image') <div class="alert alert-danger">{{ $message }}</div> @enderror <div class="form-group"> <label for="exampleInputEmail1">@lang('app.METHODOLOGY') @lang('app.DESC')</label> <input type="text" name="methodology_desc" value="{{ $methodologyDetail->methodology_desc }}" class="form-control" id="exampleInputName" placeholder="@lang('app.Enter') @lang('app.METHODOLOGY') @lang('app.DESC')"> </div> @error('methodology_desc') <div class="alert alert-danger">{{ $message }}</div> @enderror <!-- /.card-body --> </div> <!-- /.card-body --> <div class="card-footer"> <button type="submit" class="btn btn-primary">@lang('app.UPDATE')</button> <a href="{{ url('/methodologyDetail') }}" class="btn btn-success">@lang('app.CANCEL')</a> </div> </form> </div> <!-- /.card --> @endsection @section('page_style') <!-- SpecialStyles --> <link rel="stylesheet" href="{{ asset('first/styles/showData.css') }}"> @endsection @section('page_js') <script> function showPreview(event) { if (event.target.files.length > 0) { let src = URL.createObjectURL(event.target.files[0]); let preview = document.getElementById('img-preview'); preview.src = src; } } </script> @endsection
import { numberOfPairs } from './main'; describe('numberOfPairs', () => { it('returns 0 for an empty array', () => { expect(numberOfPairs([])).toBe(0); }); it('returns 0 when there are no pairs', () => { expect(numberOfPairs(['red', 'green', 'blue'])).toBe(0); }); it('returns 1 when there is 1 pair of gloves of the same color', () => { expect(numberOfPairs(['red', 'green', 'red', 'blue'])).toBe(1); }); it('returns 2 when there are 2 pairs of gloves of different colors', () => { expect(numberOfPairs(['red', 'green', 'red', 'blue', 'blue'])).toBe(2); }); it('returns 3 when there are 3 pairs of gloves of the same color', () => { expect(numberOfPairs(['red', 'red', 'red', 'red', 'red', 'red'])).toBe(3); }); it('handles mixed case colors', () => { expect( numberOfPairs(['Red', 'red', 'GREEN', 'green', 'Blue', 'blue']) ).toBe(3); }); it('handles colors with leading/trailing whitespace', () => { expect(numberOfPairs([' red', 'red ', ' green ', ' blue ', 'blue'])).toBe( 2 ); }); });
import asyncio import logging import os from PIL import Image, ImageDraw, ImageOps from aiogram import Bot, Dispatcher from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.dispatcher.storage import FSMContext from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram import types from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.orm import scoped_session, sessionmaker, declarative_base logging.basicConfig(level=logging.INFO) bot = Bot(token="") dp = Dispatcher(bot=bot, storage=MemoryStorage()) @dp.message_handler(text='/start') async def start(message: types.Message): await message.answer(text='Здравствуйте!\nКак Вас зовут?') # Настройка базы данных engine = create_engine('sqlite:///bot.db') Base = declarative_base() # Определение модели пользователя class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String(50), unique=True) password = Column(String(100)) email = Column(String(100), unique=True) avatar = Column(String(100)) # Путь к файлу аватара пользователя def __init__(self, username, password, email, avatar): self.username = username self.password = password self.email = email self.avatar = avatar Base.metadata.create_all(engine) # FSM Состояния class Registration(StatesGroup): waiting_for_username = State() waiting_for_password = State() waiting_for_email = State() waiting_for_avatar = State() db_session = sessionmaker(bind=engine) session = scoped_session(sessionmaker(bind=engine)) # Регистрация пользователя @dp.message_handler(commands='register', state='*') async def register(message: types.Message): await Registration.waiting_for_username.set() await message.answer("Введите ваш логин:") @dp.message_handler(state=Registration.waiting_for_username) async def process_username(message: types.Message, state: FSMContext): async with state.proxy() as data: data['username'] = message.text await Registration.next() await message.answer("Введите ваш пароль:") @dp.message_handler(state=Registration.waiting_for_password) async def process_password(message: types.Message, state: FSMContext): async with state.proxy() as data: data['password'] = message.text await Registration.next() await message.answer("Введите ваш email:") @dp.message_handler(state=Registration.waiting_for_email) async def process_email(message: types.Message, state: FSMContext): async with state.proxy() as data: data['email'] = message.text await Registration.next() await message.answer("Загрузите вашу аватарку:", reply_markup=types.ReplyKeyboardRemove()) @dp.message_handler(content_types=['photo'], state=Registration.waiting_for_avatar) async def process_avatar(message: types.Message, state: FSMContext): document_id = message.photo[-1].file_id file_info = await bot.get_file(document_id) file_path = file_info.file_path file = await bot.download_file(file_path) async with state.proxy() as data: # Сохранение аватара пользователя users_avatar_path = 'user_avatars/' if not os.path.exists(users_avatar_path): os.makedirs(users_avatar_path) # Создание круглого аватара с использованием Pillow with Image.open(file) as img: size = (128, 128) mask = Image.new('L', size, 0) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + size, fill=255) img.thumbnail(size) output = ImageOps.fit(img, mask.size, centering=(0.5, 0.5)) output.putalpha(mask) # Сохраняем аватарку avatar_path = f"{users_avatar_path}{message.from_user.id}_avatar.png" output.save(avatar_path) data['avatar'] = avatar_path # Создание нового пользователя и сохранение в БД new_user = User(username=data['username'], password=data['password'], email=data['email'], avatar=data['avatar']) db = db_session() db.add(new_user) db.commit() await state.finish() await message.answer("Вы успешно зарегистрированы!") async def main(): Base.metadata.create_all(engine) await dp.start_polling(bot)
package com.example.a18478 import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await class UserProfile : AppCompatActivity() { private lateinit var imagePickerLauncher: ActivityResultLauncher<Intent> private val PERMISSION_REQUEST_CODE = 100 private lateinit var imageViewProfilePicture: ImageView private lateinit var userId: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_user_profile) userId = FirebaseAuth.getInstance().currentUser!!.uid // Inicijalizacija prikaza i dugmadi val textViewUsername: TextView = findViewById(R.id.textViewUsername) val userScheduleFragment = UserScheduleFragment() supportFragmentManager.beginTransaction() .replace(R.id.containerUserSchedule, userScheduleFragment) .commit() val btnGoToPretragaDogadjaja: Button = findViewById(R.id.btnGoToPretragaDogadjaja) val btnLogout: Button = findViewById(R.id.btnLogout) // Postavljanje klika na dugme za navigaciju ka aktivnosti PretragaDogadjaja btnGoToPretragaDogadjaja.setOnClickListener { val intent = Intent(this, PretragaDogadjaja::class.java) startActivity(intent) } // Provera i zahtevanje dozvole za čitanje spoljnog skladišta ako nije već odobreno if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), PERMISSION_REQUEST_CODE) } // Dohvatanje korisničkih podataka val userId = FirebaseAuth.getInstance().currentUser!!.uid val databaseURL = "https://project-4778345136366669416-default-rtdb.europe-west1.firebasedatabase.app" val database = FirebaseDatabase.getInstance(databaseURL) val databaseRef = database.reference.child("korisnici").child(userId) // Korišćenje Coroutines za dohvat podataka iz baze podataka lifecycleScope.launch { try { val dataSnapshot = databaseRef.get().await() if (dataSnapshot.exists()) { val userData = dataSnapshot.getValue(User::class.java) userData?.let { val name = userData.ime textViewUsername.text = name } } } catch (e: Exception) { // Gracefulno rukovanje greškama textViewUsername.text = "Greška pri učitavanju korisničkih podataka" } } // Postavljanje klika na dugme za odjavu btnLogout.setOnClickListener { odjavaKorisnika() } } private fun odjavaKorisnika() { // Odjava trenutnog korisnika iz Firebase autentifikacije FirebaseAuth.getInstance().signOut() // Preusmeravanje korisnika na ekran za prijavu ili drugo željeno ponašanje val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() // Zatvaranje trenutne aktivnosti } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { PERMISSION_REQUEST_CODE -> { if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // Dozvola je odobrena } else { } return } // Dodajte druge slučajeve po potrebi } } // Ostale metode ako ih imate }
// C++ program to demonstrate // Run Time Type Identification successfully // With virtual function #include <iostream> using namespace std; // Initialization of base class class B { public: virtual void fun() { cout<< "Dynamic cast\n"; } }; // Initialization of Derived class class D : public B { }; // Driver Code int main() { B* b = new D; // Base class pointer D* d = dynamic_cast<D*>(b); // Derived class pointer if (d != NULL) cout << "works"<<endl; else cout << "cannot cast B* to D*"; d->fun(); getchar(); return 0; }
.\" Copyright (c) 2015, Carsten Kunze .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .Dd September 18, 2015 .Dt DHTML 1 .Sh NAME .Nm dhtml .Nd HTML postprocessor for troff .Sh SYNOPSIS .Nm .Op Fl t Ar title .Li < Ar ditroff_output Li > Ar html_output .Sh DESCRIPTION .Nm is a HTML postprocessor for .Xr troff 1 . It reads the ditroff output from .Dv STDIN and writes HTML5 output to .Dv STDOUT . .Nm troff must in this case be called with option .Fl Thtml . Missing charaters can be added by changing the files .Pa charset and .Pa CHAR (see section .Sx FILES ) . For adding fonts the tool needs to be recompiled (currently the legacy fonts .Li R I B BI C CW CR CI CB H HI HB S are available). .Pp Options: .Bl -tag -width ".Fl t Ar title" .It Fl t Ar title Set text for the HTML .Li <title> tag. .El .Sh FILES .Bl -tag .It Ar source_dir Ns Pa /troff/troff.d/font/devhtml/charset .Sy charset which is appended to each font description file at installation of the tool (run .Pp .Dl # make install .Pp after changes of this file). .It Pa $FNTDIR/devhtml/CHAR Character to HTML name mapping which is read at each run of .Nm . .El .Sh EXAMPLES .Bd -unfilled -offset indent .Li tbl Ar manpage Li | troff -Thtml -mandoc \(rs .Li " |" dhtml Li -t Ar html_title Li > Ar html_file .Ed .Pp Convert .Ar manpage into HTML format with title .Ar html_title and save it as .Ar html_file . .Sh SEE ALSO .Xr troff 1 , .Xr dpost 1 .Sh BUGS For the current version no changes to the ditroff interface are done. All information for formatting the HTML page is taken from legacy ditroff commands. As a consequence the alignment cannot be as accurate as in the .Xr dpost 1 output since the character widths of HTML fonts must be supposed to be unknown. .Pp At the moment no HTML tables are generated. .Xr tbl 1 (without options) can be used for preprocessing but mayor alingment issues may result. There is no support for equations, graphics, images, and links in this versions. These features are subject to be implemented later.