text
stringlengths
184
4.48M
// common/primitives/set.mjs v11.301 type SetTestPredicate<T, S extends T> = ( value: T, index: number, set: Set<T> ) => value is S declare global { interface Set<T> { /** * Return the difference of two sets. * @param other - Some other set to compare against * @returns The difference defined as objects in this which are not present in other */ difference<U>(other: Set<U>): this /** * Return the symmetric difference of two sets. * @param other - Another set. * @returns The set of elements that exist in this or other, but not both. */ symmetricDifference<U>(other: Set<U>): Set<U | T> /** * Test whether this set is equal to some other set. * Sets are equal if they share the same members, independent of order * @param other - Some other set to compare against * @returns Are the sets equal? */ equals<U>(other: Set<U>): this is typeof other /** * Return the first value from the set. * @returns The first element in the set, or undefined */ first(): T | undefined /** * Return the intersection of two sets. * @param other - Some other set to compare against * @returns The intersection of both sets */ intersection<U>(other: Set<U>): Set<T & U> /** * Test whether this set has an intersection with another set. * @param other Another set to compare against * @returns Do the sets intersect? */ intersects<U>(other: Set<U>): this is Set<T | U> /** * Return the union of two sets. * @param other - The other set. */ union<U>(other: Set<U>): Set<U | T> /** * Test whether this set is a subset of some other set. * A set is a subset if all its members are also present in the other set. * @param other - Some other set that may be a subset of this one * @returns Is the other set a subset of this one? */ isSubset<U>(other: Set<U>): this is Set<U> /** * Convert a set to a JSON object by mapping its contents to an array * @returns The set elements as an array. */ toObject(): T[] /** * Test whether every element in this Set satisfies a certain test criterion. * @see Array#every * @param test - The test criterion to apply. Positional arguments are the value, * the index of iteration, and the set being tested. * @returns Does every element in the set satisfy the test criterion? */ every<S extends T>(test: SetTestPredicate<T, S>): this is Set<S> /** * Filter this set to create a subset of elements which satisfy a certain test criterion. * @see Array#filter * @param test - The test criterion to apply. Positional arguments are the value, the index of iteration, and the set being filtered. * @returns A new Set containing only elements which satisfy the test criterion. */ filter<S extends T>(test: SetTestPredicate<T, S>): Set<S> /** * Find the first element in this set which satisfies a certain test criterion. * @see Array#find * @param test - The test criterion to apply. Positional arguments are the value, * the index of iteration, and the set being searched. * @returns The first element in the set which satisfies the test criterion, or undefined. */ find<S extends T>(test: SetTestPredicate<T, S>): S | undefined /** * Create a new Set where every element is modified by a provided transformation function. * @see Array#map * @param transform The transformation function to apply.Positional arguments are * the value, the index of iteration, and the set being transformed. * @returns A new Set of equal size containing transformed elements. */ map<U>( transform: (value: T, index: number, set: Set<T>) => U, thisArg?: any ): Set<U> /** * Create a new Set with elements that are filtered and transformed by a provided reducer function. * @see Array#reduce * @param reducer - A reducer function applied to each value. Positional arguments are the accumulator, the value, the index of iteration, and the set being reduced. * @param accumulator - The initial value of the returned accumulator. * @returns The final value of the accumulator. */ reduce( reducer: ( previousValue: T, currentValue: T, currentIndex: number, set: Set<T> ) => T ): T reduce( reducer: ( previousValue: T, currentValue: T, currentIndex: number, set: Set<T> ) => T, accumulator?: T ): T reduce<S extends T>( reducer: ( previousValue: T, currentValue: T, currentIndex: number, set: Set<T> ) => Partial<S> | S, accumulator?: Partial<S> | S ): S /** * Test whether any element in this Set satisfies a certain test criterion. * @see Array#some * @param test - The test criterion to apply. Positional arguments are the value, the index of iteration, and the set being tested. * @returns Does any element in the set satisfy the test criterion? */ some<S extends T>( test: SetTestPredicate<T, S>, thisArg?: any ): this is Set<T | S> } } export {}
import Twit from "twit" import { config } from "dotenv" import { Autohook } from "twitter-autohook" config() // sanity check // console.log(process.env.ACCESS_TOKEN) const T = new Twit({ consumer_key: process.env.API_KEY!, consumer_secret: process.env.API_SECRET_KEY!, access_token: process.env.APP_ACCESS_TOKEN, access_token_secret: process.env.APP_ACCESS_TOKEN_SECRET, timeout_ms: 60 * 1000, // optional HTTP request timeout to apply to all requests. strictSSL: true, // optional - requires SSL certificates to be valid. }) const main = async () => { try { const webhook = new Autohook({ token: process.env.APP_ACCESS_TOKEN, token_secret: process.env.APP_ACCESS_TOKEN_SECRET, consumer_key: process.env.API_KEY, consumer_secret: process.env.API_SECRET_KEY, env: "sandbox", port: 80, }) // Removes existing webhooks await webhook.removeWebhooks() console.log("__removed") // Starts a server and adds a new webhook await webhook.start() console.log("__started") // Subscribes to your own user's activity await webhook.subscribe({ oauth_token: process.env.APP_ACCESS_TOKEN, oauth_token_secret: process.env.APP_ACCESS_TOKEN_SECRET, }) console.log("__subscribed") webhook.on("event", async event => { const screenName = event?.follow_events?.[0]?.source?.screen_name if (screenName && screenName !== "thekevinwang") { T.post("statuses/update", { status: `🤖 Meep. Thanks for following me, @${screenName}! 🎈🎉`, }) } }) } catch (e) { // Display the error and quit console.error("$$$", e) console.log({ ...e }) process.exit(1) } } main()
/*************************************************************************** * Copyright (C) 2008-2012 by Andrzej Rybczak * * electricityispower@gmail.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., * * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef NCMPCPP_HELPERS_H #define NCMPCPP_HELPERS_H #include "interfaces.h" #include "mpdpp.h" #include "screen.h" #include "settings.h" #include "status.h" #include "utility/string.h" #include "utility/wide_string.h" inline HasColumns *hasColumns(BaseScreen *screen) { return dynamic_cast<HasColumns *>(screen); } inline HasSongs *hasSongs(BaseScreen *screen) { return dynamic_cast<HasSongs *>(screen); } inline ProxySongList proxySongList(BaseScreen *screen) { auto pl = ProxySongList(); auto hs = hasSongs(screen); if (hs) pl = hs->proxySongList(); return pl; } inline MPD::Song *currentSong(BaseScreen *screen) { MPD::Song *ptr = 0; auto pl = proxySongList(screen); if (pl) ptr = pl.currentSong(); return ptr; } template <typename Iterator> bool hasSelected(Iterator first, Iterator last) { for (; first != last; ++first) if (first->isSelected()) return true; return false; } template <typename Iterator> std::vector<Iterator> getSelected(Iterator first, Iterator last) { std::vector<Iterator> result; for (; first != last; ++first) if (first->isSelected()) result.push_back(first); return result; } /// @return selected range within given range or original range if no item is selected template <typename Iterator> std::pair<Iterator, Iterator> getSelectedRange(Iterator first, Iterator second) { auto result = std::make_pair(first, second); if (hasSelected(first, second)) { while (!result.first->isSelected()) ++result.first; while (!(result.second-1)->isSelected()) --result.second; } return result; } template <typename T> void selectCurrentIfNoneSelected(NC::Menu<T> &m) { if (!hasSelected(m.begin(), m.end())) m.current().setSelected(true); } template <typename Iterator> std::vector<Iterator> getSelectedOrCurrent(Iterator first, Iterator last, Iterator current) { std::vector<Iterator> result = getSelected(first, last); if (result.empty()) result.push_back(current); return result; } template <typename Iterator> void reverseSelectionHelper(Iterator first, Iterator last) { for (; first != last; ++first) first->setSelected(!first->isSelected()); } template <typename T, typename F> void withUnfilteredMenu(NC::Menu<T> &m, F action) { bool is_filtered = m.isFiltered(); m.showAll(); action(); if (is_filtered) m.showFiltered(); } template <typename T, typename F> void withUnfilteredMenuReapplyFilter(NC::Menu<T> &m, F action) { m.showAll(); action(); if (m.getFilter()) { m.applyCurrentFilter(m.begin(), m.end()); if (m.empty()) { m.clearFilter(); m.clearFilterResults(); } } } template <typename F> void moveSelectedItemsUp(NC::Menu<MPD::Song> &m, F swap_fun) { if (m.choice() > 0) selectCurrentIfNoneSelected(m); auto list = getSelected(m.begin(), m.end()); auto begin = m.begin(); if (!list.empty() && list.front() != m.begin()) { Mpd.StartCommandsList(); for (auto it = list.begin(); it != list.end(); ++it) swap_fun(Mpd, *it - begin, *it - begin - 1); if (Mpd.CommitCommandsList()) { if (list.size() > 1) { for (auto it = list.begin(); it != list.end(); ++it) { (*it)->setSelected(false); (*it-1)->setSelected(true); } m.highlight(list[(list.size())/2] - begin - 1); } else { // if we move only one item, do not select it. however, if single item // was selected prior to move, it'll deselect it. oh well. list[0]->setSelected(false); m.scroll(NC::Scroll::Up); } } } } template <typename F> void moveSelectedItemsDown(NC::Menu<MPD::Song> &m, F swap_fun) { if (m.choice() < m.size()-1) selectCurrentIfNoneSelected(m); auto list = getSelected(m.rbegin(), m.rend()); auto begin = m.begin() + 1; // reverse iterators add 1, so we need to cancel it if (!list.empty() && list.front() != m.rbegin()) { Mpd.StartCommandsList(); for (auto it = list.begin(); it != list.end(); ++it) swap_fun(Mpd, it->base() - begin, it->base() - begin + 1); if (Mpd.CommitCommandsList()) { if (list.size() > 1) { for (auto it = list.begin(); it != list.end(); ++it) { (*it)->setSelected(false); (*it-1)->setSelected(true); } m.highlight(list[(list.size())/2].base() - begin + 1); } else { // if we move only one item, do not select it. however, if single item // was selected prior to move, it'll deselect it. oh well. list[0]->setSelected(false); m.scroll(NC::Scroll::Down); } } } } template <typename F> void moveSelectedItemsTo(NC::Menu<MPD::Song> &m, F move_fun) { auto cur_ptr = &m.current().value(); withUnfilteredMenu(m, [&]() { // this is kinda shitty, but there is no other way to know // what position current item has in unfiltered menu. ptrdiff_t pos = 0; for (auto it = m.begin(); it != m.end(); ++it, ++pos) if (&it->value() == cur_ptr) break; auto begin = m.begin(); auto list = getSelected(m.begin(), m.end()); // we move only truly selected items if (list.empty()) return; // we can't move to the middle of selected items //(this also handles case when list.size() == 1) if (pos >= (list.front() - begin) && pos <= (list.back() - begin)) return; int diff = pos - (list.front() - begin); Mpd.StartCommandsList(); if (diff > 0) // move down { pos -= list.size(); size_t i = list.size()-1; for (auto it = list.rbegin(); it != list.rend(); ++it, --i) move_fun(Mpd, *it - begin, pos+i); if (Mpd.CommitCommandsList()) { i = list.size()-1; for (auto it = list.rbegin(); it != list.rend(); ++it, --i) { (*it)->setSelected(false); m[pos+i].setSelected(true); } } } else if (diff < 0) // move up { size_t i = 0; for (auto it = list.begin(); it != list.end(); ++it, ++i) move_fun(Mpd, *it - begin, pos+i); if (Mpd.CommitCommandsList()) { i = 0; for (auto it = list.begin(); it != list.end(); ++it, ++i) { (*it)->setSelected(false); m[pos+i].setSelected(true); } } } }); } template <typename F> bool deleteSelectedSongs(NC::Menu<MPD::Song> &m, F delete_fun) { bool result = false; selectCurrentIfNoneSelected(m); // ok, this is tricky. we need to operate on whole playlist // to get positions right, but at the same time we need to // ignore all songs that are not filtered. we use the fact // that both ranges share the same values, ie. we can compare // pointers to check whether an item belongs to filtered range. NC::Menu<MPD::Song>::Iterator begin; NC::Menu<MPD::Song>::ReverseIterator real_begin, real_end; withUnfilteredMenu(m, [&]() { // obtain iterators for unfiltered range begin = m.begin() + 1; // cancel reverse iterator's offset real_begin = m.rbegin(); real_end = m.rend(); }); // get iterator to filtered range auto cur_filtered = m.rbegin(); Mpd.StartCommandsList(); for (auto it = real_begin; it != real_end; ++it) { // current iterator belongs to filtered range, proceed if (&*it == &*cur_filtered) { if (it->isSelected()) { it->setSelected(false); delete_fun(Mpd, it.base() - begin); } ++cur_filtered; } } if (Mpd.CommitCommandsList()) result = true; return result; } template <typename F> bool cropPlaylist(NC::Menu<MPD::Song> &m, F delete_fun) { reverseSelectionHelper(m.begin(), m.end()); return deleteSelectedSongs(m, delete_fun); } template <typename F, typename G> bool clearPlaylist(NC::Menu<MPD::Song> &m, F delete_fun, G clear_fun) { bool result = false; if (m.isFiltered()) { for (auto it = m.begin(); it != m.end(); ++it) it->setSelected(true); result = deleteSelectedSongs(m, delete_fun); } else result = clear_fun(Mpd); return result; } template <typename Iterator> std::string getSharedDirectory(Iterator first, Iterator last) { assert(first != last); std::string result = first->getDirectory(); while (++first != last) { result = getSharedDirectory(result, first->getDirectory()); if (result == "/") break; } return result; } template <typename Iterator> void stringToBuffer(Iterator first, Iterator last, NC::BasicBuffer<typename Iterator::value_type> &buf) { for (auto it = first; it != last; ++it) { if (*it == '$') { if (++it == last) { buf << '$'; break; } else if (isdigit(*it)) { buf << NC::Color(*it-'0'); } else { switch (*it) { case 'b': buf << NC::Format::Bold; break; case 'u': buf << NC::Format::Underline; break; case 'a': buf << NC::Format::AltCharset; break; case 'r': buf << NC::Format::Reverse; break; case '/': if (++it == last) { buf << '$' << '/'; break; } switch (*it) { case 'b': buf << NC::Format::NoBold; break; case 'u': buf << NC::Format::NoUnderline; break; case 'a': buf << NC::Format::NoAltCharset; break; case 'r': buf << NC::Format::NoReverse; break; default: buf << '$' << *--it; break; } break; default: buf << *--it; break; } } } else if (*it == MPD::Song::FormatEscapeCharacter) { // treat '$' as a normal character if song format escape char is prepended to it if (++it == last || *it != '$') --it; buf << *it; } else buf << *it; } } template <typename CharT> void stringToBuffer(const std::basic_string<CharT> &s, NC::BasicBuffer<CharT> &buf) { stringToBuffer(s.begin(), s.end(), buf); } template <typename T> void ShowTime(T &buf, size_t length, bool short_names) { const unsigned MINUTE = 60; const unsigned HOUR = 60*MINUTE; const unsigned DAY = 24*HOUR; const unsigned YEAR = 365*DAY; unsigned years = length/YEAR; if (years) { buf << years << (short_names ? "y" : (years == 1 ? " year" : " years")); length -= years*YEAR; if (length) buf << ", "; } unsigned days = length/DAY; if (days) { buf << days << (short_names ? "d" : (days == 1 ? " day" : " days")); length -= days*DAY; if (length) buf << ", "; } unsigned hours = length/HOUR; if (hours) { buf << hours << (short_names ? "h" : (hours == 1 ? " hour" : " hours")); length -= hours*HOUR; if (length) buf << ", "; } unsigned minutes = length/MINUTE; if (minutes) { buf << minutes << (short_names ? "m" : (minutes == 1 ? " minute" : " minutes")); length -= minutes*MINUTE; if (length) buf << ", "; } if (length) buf << length << (short_names ? "s" : (length == 1 ? " second" : " seconds")); } template <typename BufferT> void ShowTag(BufferT &buf, const std::string &tag) { if (tag.empty()) buf << Config.empty_tags_color << Config.empty_tag << NC::Color::End; else buf << tag; } bool addSongToPlaylist(const MPD::Song &s, bool play, size_t position = -1); bool addSongsToPlaylist(const MPD::SongList &list, bool play, size_t position = -1); std::string Timestamp(time_t t); void markSongsInPlaylist(ProxySongList pl); std::wstring Scroller(const std::wstring &str, size_t &pos, size_t width); void writeCyclicBuffer(const NC::WBuffer &buf, NC::Window &w, size_t &start_pos, size_t width, const std::wstring &separator); #endif // NCMPCPP_HELPERS_H
--- id: example-react-intl title: React Intl --- > **Nota** > > Se quiseres combinar a `setupTests` com uma outra configuração deverias verificar a [`setup`](react-testing-library/setup.mdx). ## Configurando `Polyfills` de `React-Intl` ou Locais Se estiveres a usar a `React-Intl` no teu projeto, e **precisas** de carregar uma localização, tens duas opções: 1. Quando estiveres a usar a Node 13 e superior, o suporte de `Intl` está agora fora da caixa. A opção padrão de Componentes Internacionais para Unicode (ICU, sigla em Inglês) para Node é `full-icu` significando todos ICUs. Tudo o que precisas de fazer é fixar o conjunto de dados de ICU precisas de: ```js // test-utils.js const hasFullICU = () => { // É a maneira recomendada para testar pelo suporte de ICU de acordo com a documentação da Node.js try { const january = new Date(9e8) const pt = new Intl.DateTimeFormat('pt', {month: 'long'}) return pt.format(january) === 'janeiro' } catch (err) { return false } } export const setupTests = () => { if (hasFullICU()) { Intl.NumberFormat.format = new Intl.NumberFormat('pt').format Intl.DateTimeFormat.format = new Intl.DateTimeFormat('pt').format } else { global.Intl = IntlPolyfill } } ``` 2. Quando estiveres a usar a Node com versões anteriores, a opção padrão de ICU é `small-icu` significando que inclui um subconjunto de dados de ICU (normalmente apenas o local Inglês). Se precisares de carregar um local tens duas opções: 1. Carregar os `Polyfills` de acordo com a linguagem: ```js // test-utils.js import IntlPolyfill from 'intl' import 'intl/locale-data/jsonp/pt' export const setupTests = () => { // https://formatjs.io/docs/guides/runtime-requirements/#nodejs if (global.Intl) { Intl.NumberFormat = IntlPolyfill.NumberFormat Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat } else { global.Intl = IntlPolyfill } } ``` 2. Carregar os ICUs em tempo de execução: Instale o pacote [`full-icu`](https://github.com/unicode-org/full-icu-npm) e injete-o no teu ambiente de teste, podes fazer isto definindo `NODE_ICU_DATA` antes da chamada de Jest: `NODE_ICU_DATA=node_modules/full-icu jest`. Fazendo isto dar-te-ás o suporte `full-icu` como mostrado na opção 1. ## Criando um função interpretadora personalizada Para testar o nosso componente traduzido podemos criar uma função `render` personalizada usando a opção `wrapper` conforme explicado na página de [configuração](react-testing-library/setup.mdx). A nossa função `render` personalizada pode parecer-se com esta: ```jsx // test-utils.js import React from 'react' import {render as rtlRender} from '@testing-library/react' import {IntlProvider} from 'react-intl' function render(ui, {locale = 'pt', ...renderOptions} = {}) { function Wrapper({children}) { return <IntlProvider locale={locale}>{children}</IntlProvider> } return rtlRender(ui, {wrapper: Wrapper, ...renderOptions}) } // re-exporta tudo export * from '@testing-library/react' // sobrepõe o método `render` export {render} ``` ## Um exemplo completo ```jsx import React from 'react' import '@testing-library/jest-dom' // Estamos a importar a partir da nossa própria `test-utils` e // não da RTL import {render, screen, setupTests} from '../test-utils.js' import {FormattedDate} from 'react-intl' const FormatDateView = () => { return ( <div data-testid="date-display"> <FormattedDate value="2019-03-11" timeZone="utc" day="2-digit" month="2-digit" year="numeric" /> </div> ) } setupTests() test('it should render FormattedDate and have a formatted pt date', () => { render(<FormatDateView />) expect(screen.getByTestId('date-display')).toHaveTextContent('11/03/2019') }) ``` ## Estratégia de testagem de componentes traduzidos Quando estiveres a testar um componente traduzido podem existir diferentes abordagens para alcançar a cobertura desejada, onde o objetivo definido deveria ser permitir testar o componente de uma maneira que simulará o comportamento do utilizador o máximo possível: | Abordagem | Pós | Contras | | ------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Usar sequências de caracteres da linguagem padrão | O teste é fácil de ler, e afirma a saída padrão esperada. Se tens variáveis nas tuas sequências de caracteres, podes testar se funcionam apropriadamente com a saída correta. | 1. As sequências de caracteres escritas manualmente nos testes significa que tens de atualizar ambos testes e código para quaisquer mudanças da cópia. 2. Se vários elementos têm a mesmo texto de sequência de caracteres ou subsequência de caracteres, encontrar e substituir pode ser difícil de usar com confiança. | Imitar a biblioteca de tradução | Se a tua biblioteca for difícil de usar no ambiente de teste, podes imitá-la assim é mais fácil. Por exemplo, podes adicionar um identificador de mensagem de acordo com atributo de dado para o texto assim podes consultar por esta. | Testar o código afasta-se do que executa em produção. Os testes podem afirmar sobre os identificadores da mensagem mas não o suficiente sobre o conteúdo, assim erros são possíveis. | | Usar a biblioteca de tradução nos testes | Separa as sequências de caracteres dos testes, assim podes atualizar os ficheiros da mensagem em um lugar sem a preocupação de quebrar os testes. Podes executar os testes em uma outra linguagem ou várias linguagens. `const buttonText = getNodeText(<FormattedMessage id="buttonText" defaultMessage="Hello Button" />);` | Despesa geral - custa mais linhas de código para escrever o teste, e precisas de conhecer as variáveis e identificadores da mensagem para criar as sequências de caracteres corretas. Não é óbvio o que o texto realmente é quando lês o código de teste, tornando mais difícil de mantê-lo. | | Usar a biblioteca de tradução + fotografia em linha | O mesmo que o de cima, mas adicionado uma fotografia em linha da sequência de caracteres, podes ler o código de teste e ver quais sequências de caracteres estão em uso, mas facilmente atualizá-los com `jest -u` se as mensagens mudarem. `expect(buttonText).toMatchInlineSnapshot("'My button text'")` | Os testes são mais longos por causa das linhas adicionais. Tu podes embrulhar algum do código relacionado com a tradução em uma função auxiliar para torná-lo um pouco mais em linha e evitar repetires-te, mas ainda precisas de conhecer os identificadores da mensagem e as variáveis dentro do teste. |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> //枠の設定 const width = 320; const height = 480; //一つのブロックについてのサイズ設定 const blockInfoList = []; const blockWidth = width / 10; const blockHeight = blockWidth / 2; //下の跳ね返す板 const heroWidth = blockWidth * 2; const heroHeight = heroWidth / 5; let heroDiv = null; let heroLeft = width / 2 - heroWidth / 2; let heroTop = height * 0.8; //ボールのスタイル const ballSize = 8; let ballLeft = width / 2 - ballSize / 2; let ballTop = height / 2; let ballDiv = null; //ボールのアクションについての設定 let ballSpeed = 5; let ballDx = 0; let ballDy = ballSpeed; let gameover = false; let messageDiv = null; let blockCount = 0; //板の最大最小の位置 const heroMinleft = 0; const heroMaxLeft = width - heroWidth; //初期設定 const init = () => { //ブロックの生成 const container = document.createElement("div"); document.body.appendChild(container); container.style.position = "absolute"; container.style.width = `${width}px`; container.style.height = `${height}px`; container.style.backgroundColor = "#000"; //生成されたブロックのスタイル設定 let colorIndex = 1; //ブロックの殻をつける際に用いる //この繰り返し文の意味:y=0の時、x=123...となり上段からブロックからできていくイメージ。 for (let y = 0; y < 10; y++) { for (let x = 0; x < 9; x++) { blockCount++; const div = document.createElement("div"); container.appendChild(div); const px = (x + 0.5) * blockWidth; //これと下の0.5や1を足しているのは連鎖を作るためらしい。もしこれがないと通り過ぎてしまう。 const py = (y + 1) * blockHeight; //また、右と上があく。 div.style.position = "absolute"; div.style.left = `${px}px`; div.style.top = `${py}px`; div.style.backgroundColor = `hsl(${(360 / 8) * (colorIndex % 8)}deg, 100%, 50%)`; //hslは色相と彩度と明度が順番になっている。彩度と明度はそれぞれ50%が真ん中。彩度が高くなると黒からその色に強くなっていく。明度は高くなると白くなっていく。 div.style.boxSizing = "border-box"; div.style.border = `3px ridge hsl(${(360 / 8) * (colorIndex++ % 8)}deg, 100%, 30%)`; div.style.width = `${blockWidth}px`; div.style.height = `${blockHeight}px`; blockInfoList.push({ //配列blockInfoListに4つの要素の追加 px, py, available: true, element: div }); } } //下の跳ね返す板のアペンド heroDiv = document.createElement("div"); container.appendChild(heroDiv); //ボールのアペンド ballDiv = document.createElement("div"); container.appendChild(ballDiv); let originalX = 0; let originalHeroLeft = 0; container.onpointerdown = (e) => { //要素が長押しされたときに用いる。eはクリックされたりなどのイベントが起きた要素の情報などをオブジェクトとしてゲットできるイメージ。今回はコンテイナー(クリエイトエレメントdivで定義された)がクリックされたときにその情報を返す。 e.preventDefault(); //サブミットなど、その要素が本来持つ動作を止める。 originalX = e.pageX; originalHeroLeft = heroLeft; console.log(e.pageX,heroLeft) }; container.onpointermove = (e) => { e.preventDefault(); if (originalX) { console.log(e.pageX) heroLeft = originalHeroLeft + (e.pageX - originalX) * 2; if(heroLeft <= heroMinleft){ heroLeft = heroMinleft; } if(heroLeft >= heroMaxLeft){ heroLeft = heroMaxLeft; } update(); } }; container.onpointerup = () => { originalX = 0; }; //これはクリアかゲームオーバーかを表示させるためのもの。 messageDiv = document.createElement("div"); container.appendChild(messageDiv); messageDiv.style.position = "absolute"; messageDiv.style.left = 0; messageDiv.style.top = 0; messageDiv.style.right = 0; messageDiv.style.bottom = 0; messageDiv.style.display = "flex"; messageDiv.style.alignItems = "center"; messageDiv.style.justifyContent = "center"; messageDiv.style.color = "#fff"; messageDiv.style.fontSize = "50px"; messageDiv.style.fontFamily = "sans-serif"; }; const update = () => { if (gameover) { //上でゲームオーバーはフォルスと定義されている。 return; } heroDiv.style.position = "absolute"; heroDiv.style.left = `${heroLeft}px`; heroDiv.style.top = `${heroTop}px`; heroDiv.style.width = `${heroWidth}px`; heroDiv.style.height = `${heroHeight}px`; heroDiv.style.backgroundColor = "#fff"; heroDiv.style.borderRadius = "50% 50% 0 0"; ballDiv.style.position = "absolute"; ballDiv.style.left = `${ballLeft}px`; ballDiv.style.top = `${ballTop}px`; ballDiv.style.width = `${ballSize}px`; ballDiv.style.height = `${ballSize}px`; ballDiv.style.backgroundColor = "#fff"; ballDiv.style.borderRadius = "50%"; if (ballTop > height) { gameover = true; messageDiv.style.color = "#c00"; messageDiv.textContent = "game over"; } if (blockCount === 0) { gameover = true; messageDiv.style.color = "#cc0"; messageDiv.textContent = "CLEAR"; } }; //ここはボールの跳ね返りをしている。 //ここからは完全に写しただけで微妙なところが多い。知らない構文などは一応調べた。 const collisionCheck = () => { const bx = ballLeft + ballSize / 2; //÷2をしているのはボールを点として扱うため。 const by = ballTop + ballSize / 2; if (heroLeft < bx && bx < heroLeft + heroWidth) { if (heroTop < by && by < heroTop + heroHeight) { if (ballDy > 0) { const ratio = ((bx - heroLeft) / heroWidth) * 2 - 1; const angle = 60 * ratio; ballDy = -Math.cos((angle * Math.PI) / 180) * ballSpeed; ballDx = Math.sin((angle * Math.PI) / 180) * ballSpeed; } } } //ボールの当たり判定 if ((bx < 0 && ballDx < 0) || (bx > width && ballDx > 0)) { ballDx *= -1; } if (by < 0 && ballDy < 0) { ballDy *= -1; } for (const blockInfo of blockInfoList) { const { px, py, available, element } = blockInfo; if (!available) { continue; } if (px < bx && bx < px + blockWidth) { if (py < by && by < py + blockHeight) { const gl = bx - px; const gr = px + blockWidth - bx; const gt = by - py; const gb = py + blockHeight - by; const g = Math.min(gl, gr, gt, gb); if (g === gl || g === gr) { ballDx *= -1; //直線の直行条件を用いている。 } else { ballDy *= -1; } element.style.display = "none"; //ブロックを消すスタイル。 blockInfo.available = false; blockCount--; } } } }; window.onload = () => { init(); //最初の状態を作る。 update(); //処理が始まった後。 const tick = () => { if (!gameover) { setTimeout(tick, 16); } ballLeft += ballDx; ballTop += ballDy; collisionCheck(); update(); }; tick(); }; </script> </body> </html>
#include "moveit/planning_scene_interface/planning_scene_interface.h" #include "tf2/LinearMath/Quaternion.h" #include "tf2/LinearMath/Matrix3x3.h" void pose_to_string(char* pose_str, geometry_msgs::Pose pose) { geometry_msgs::Vector3 orientation; tf2::Quaternion quaternion(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w); tf2::Matrix3x3(quaternion).getRPY(orientation.x, orientation.y, orientation.z); sprintf(pose_str, "(%f, %f, %f, %f, %f, %f)", pose.position.x, pose.position.y, pose.position.z, orientation.x, orientation.y, orientation.z); } void log_pose(char* pose_name, geometry_msgs::Pose pose) { char pose_str[100]; pose_to_string(pose_str, pose); ROS_INFO_NAMED("pose", "%s: %s", pose_name, pose_str); } geometry_msgs::PoseStamped create_pose_stamped(float x, float y, float z, float a, float b, float c) { geometry_msgs::PoseStamped target_pose; target_pose.header.frame_id = "world"; target_pose.header.stamp = ros::Time::now(); tf2::Quaternion target_quaternion; target_quaternion.setRPY(a, b, c); target_pose.pose.orientation.x = target_quaternion.getX(); target_pose.pose.orientation.y = target_quaternion.getY(); target_pose.pose.orientation.z = target_quaternion.getZ(); target_pose.pose.orientation.w = target_quaternion.getW(); target_pose.pose.position.x = x; target_pose.pose.position.y = y; target_pose.pose.position.z = z; return target_pose; } geometry_msgs::PoseStamped get_pose_from_keyboard_key(std::string c, geometry_msgs::PoseStamped home_pose, const char* side) { geometry_msgs::Vector3 home_orientation; tf2::Quaternion home_quaternion(home_pose.pose.orientation.x, home_pose.pose.orientation.y, home_pose.pose.orientation.z, home_pose.pose.orientation.w); tf2::Matrix3x3(home_quaternion).getRPY(home_orientation.x, home_orientation.y, home_orientation.z); geometry_msgs::PoseStamped keyboard_key_pose = create_pose_stamped( home_pose.pose.position.x + keyboard_key_offset_position_scale * left_arm_keyboard_key_to_offset[c].x, home_pose.pose.position.y + keyboard_key_offset_position_scale * left_arm_keyboard_key_to_offset[c].y, home_pose.pose.position.z + keyboard_key_offset_position_scale * left_arm_keyboard_key_to_offset[c].z, home_orientation.x + left_arm_keyboard_key_to_offset[c].a, home_orientation.y + left_arm_keyboard_key_to_offset[c].b, home_orientation.z + left_arm_keyboard_key_to_offset[c].c ); return keyboard_key_pose; } void trigger_joint_publisher(ros::Publisher* joint_triggers_pub, const char* side) { int i = side == RIGHT; joint_triggers.data = side == RIGHT; joint_triggers_pub->publish(joint_triggers); } void move_planning_group(ros::Publisher* joint_triggers_pub, moveit::planning_interface::MoveGroupInterface* move_group_interface, char* target_pose_name) { move_group_interface->setJointValueTarget(move_group_interface->getNamedTargetValues(target_pose_name)); moveit::planning_interface::MoveGroupInterface::Plan plan_arm; bool success = (move_group_interface->plan(plan_arm) == moveit::planning_interface::MoveItErrorCode::SUCCESS); move_group_interface->move(); geometry_msgs::PoseStamped target_pose = move_group_interface->getCurrentPose("link_l6"); ROS_INFO_NAMED("movement", "Moving arm to %s: %s", target_pose_name, success ? "" : "FAILED"); log_pose(target_pose_name, target_pose.pose); trigger_joint_publisher(joint_triggers_pub, move_group_interface->getName() == PLANNING_GROUP_LEFT_ARM ? LEFT : RIGHT); } void move_planning_group(ros::Publisher* joints_trigger_pub, moveit::planning_interface::MoveGroupInterface* move_group_interface, geometry_msgs::PoseStamped target_pose) { move_group_interface->setPoseTarget(target_pose); moveit::planning_interface::MoveGroupInterface::Plan plan_arm; bool success = (move_group_interface->plan(plan_arm) == moveit::planning_interface::MoveItErrorCode::SUCCESS); char target_pose_name[100] = "target_pose"; ROS_INFO_NAMED("movement", "Moving arm to %s. %s", target_pose_name, success ? "" : "FAILED"); log_pose(target_pose_name, target_pose.pose); move_group_interface->move(); trigger_joint_publisher(joints_trigger_pub, move_group_interface->getName() == PLANNING_GROUP_LEFT_ARM ? LEFT : RIGHT); } void push_key(ros::Publisher* endeffector_triggers_pub, moveit::planning_interface::MoveGroupInterface* move_group_interface, const char* side) { char target_pose[100]; sprintf(target_pose, "%s_endeffector_open", side); int i = side == RIGHT; endeffector_triggers.data = side == RIGHT; endeffector_triggers_pub->publish(endeffector_triggers); // move_planning_group(move_group_interface, target_pose); // sprintf(target_pose, "%s_endeffector_closed", side); // move_planning_group(move_group_interface, target_pose); } void test_keys(ros::Publisher* joint_triggers_pub, ros::Publisher* endeffector_triggers_pub, moveit::planning_interface::MoveGroupInterface* move_group_interface, geometry_msgs::PoseStamped home_pose, const char* side) { std::map<std::string, PoseOffset> keyboard_key_to_offset = left_arm_keyboard_key_to_offset; if (side == RIGHT) { keyboard_key_to_offset = right_arm_keyboard_key_to_offset; } int NUM_TESTS = left_arm_keyboard_key_to_offset.size(); std::map<std::string, PoseOffset>::iterator it; int i = 0; for (it = left_arm_keyboard_key_to_offset.begin(); it != left_arm_keyboard_key_to_offset.end(); it++) { i++; if (i > NUM_TESTS) break; std::string test_str = it->first; ROS_INFO_NAMED("test", "Testing %s", test_str.c_str()); geometry_msgs::PoseStamped target_pose1 = get_pose_from_keyboard_key(it->first, home_pose, side); move_planning_group(joint_triggers_pub, move_group_interface, target_pose1); push_key(endeffector_triggers_pub, move_group_interface, LEFT); ros::Duration(1).sleep(); } }
import React, { useState, useEffect } from "react"; import Swal from "sweetalert2"; import "./style.module.css"; import Header from "./Header"; import Table from "./Table"; import Add from "./Add"; import Edit from "./Edit"; import { productData } from "../../data"; const Dashboard = ({ setIsAuthenticated }) => { const [products, setproducts] = useState([]); const [selectedproduct, setSelectedproduct] = useState(null); const [isAdding, setIsAdding] = useState(false); const [isEditing, setIsEditing] = useState(false); useEffect(() => { const data = JSON.parse(localStorage.getItem("products_data")); if (data !== null && Object.keys(data).length !== 0) setproducts(data); }, []); const handleEdit = (id) => { const [product] = products.filter((product) => product.id === id); console.log(products); setSelectedproduct(product); setIsEditing(true); }; const handleDelete = async (id) => { // Swal.fire({ // icon: "warning", // title: "Are you sure?", // text: "You won't be able to revert this!", // showCancelButton: true, // confirmButtonText: "Yes, delete it!", // cancelButtonText: "No, cancel!", // }).then((result) => { // if (result.value) { // const [product] = products.filter((product) => product.id === id); // Swal.fire({ // icon: "success", // title: "Deleted!", // text: `${product.title} by ${product.createdBy}'s data has been deleted.`, // showConfirmButton: false, // timer: 1500, // }); // const productsCopy = products.filter((product) => product.id !== id); // localStorage.setItem("products_data", JSON.stringify(productsCopy)); // setproducts(productsCopy); // } // }); console.log(id); // const itemResponse = await fetch(`http://localhost:8080/inventory/${id}`, { // method: "DELETE", // headers: { // "Content-Type": "application/json", // Authorization: `Bearer ${localStorage.getItem("token")}`, // }, // }); // console.log(await itemResponse.json()); }; return ( <div className="styles.container" style={{ backgroundColor: "#4e54c8", padding: "2rem", margin: "2rem", borderRadius: "5px", }} > <div style={{ backgroundColor: "white", padding: "2rem", margin: "2rem", borderRadius: "5px", }} > {!isAdding && !isEditing && ( <> <Header setIsAdding={setIsAdding} setIsAuthenticated={setIsAuthenticated} /> <Table products={products} handleEdit={handleEdit} handleDelete={handleDelete} /> </> )} {isAdding && ( <Add products={products} setproducts={setproducts} setIsAdding={setIsAdding} /> )} {isEditing && ( <Edit products={products} selectedproduct={selectedproduct} setproducts={setproducts} setIsEditing={setIsEditing} /> )} </div> </div> ); }; export default Dashboard;
<!doctype html> <html lang="it"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>BootPro</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.2/font/bootstrap-icons.css"> <link rel="stylesheet" href="scss/main.css"> </head> <body> <!----------------------Apro il container fluid per una width totale---------------------------------> <div class="container-fluid p-0"> <!----------------------Apro l'header con la sua navbar---------------------------------> <header class="header position-sticky top-0"> <nav class="navbar navbar-expand-lg fs-5"> <div class="container-fluid"> <a class="navbar-brand ms-5 fs-4" href="#">BootPro</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse " id="navbarSupportedContent"> <ul class="navbar-nav mb-2 mb-lg-0 ms-auto me-5 "> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Servizi</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contatti</a> </li> <li class="nav-item"> <a class="nav-link" href="#"><i class="bi bi-twitter"></i></a> </li> <li class="nav-item"> <a class="nav-link" href="#"><i class="bi bi-twitch"></i></a> </li> <li class="nav-item"> <a class="nav-link" href="#"><i class="bi bi-discord"></i></a> </li> <li class="nav-item"> <a class="nav-link" href="#"><i class="bi bi-whatsapp"></i></a> </li> </ul> </div> </div> </nav> </header> <!----------------------Chiudo l'header con relativa navbar---------------------------------> <!----------------------Apro il main---------------------------------> <main class="main"> <!----------------------Apro la section del banner---------------------------------> <section class="banner"> <div class="pt-4 ps-5 pe-5"> <h1 class="pb-3">La nostra passione si erge sopra ogni cosa</h1> <p class="pb-3">Carrot cake fruitcake donut tart dragée tiramisu shortbread. Cupcake sweet candy canes muffin wafer lemon drops cupcake chocolate bar liquorice.</p> <button type="button" class="btn">Iscriviti alla lista contatti</button> </div> </section> <!----------------------Chiudo la section del banner---------------------------------> <!----------------------Apro la section jobs---------------------------------> <section class="jobs"> <div class="row mx-auto text-center fw-bold"> <div class="col-lg-4 p-5"> <i class="bi bi-briefcase-fill fs-1"></i> <h3 class="fs-1">Job 1</h3> <p>Carrot cake fruitcake donut tart dragée tiramisu shortbread. Cupcake sweet candy canes muffin wafer lemon drops cupcake chocolate bar liquorice.</p> </div> <div class="col-lg-4 p-5"> <i class="bi bi-person-plus-fill fs-1"></i> <h3 class="fs-1">Job 2</h3> <p>Carrot cake fruitcake donut tart dragée tiramisu shortbread. Cupcake sweet candy canes muffin wafer lemon drops cupcake chocolate bar liquorice.</p> </div> <div class="col-lg-4 p-5"> <i class="bi bi-binoculars-fill fs-1"></i> <h3 class="fs-1">Job 3</h3> <p>Carrot cake fruitcake donut tart dragée tiramisu shortbread. Cupcake sweet candy canes muffin wafer lemon drops cupcake chocolate bar liquorice.</p> </div> </div> </section> <!----------------------Chiudo la section jobs---------------------------------> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"> <path fill="#f5f5f5" fill-opacity="1" d="M0,96L60,90.7C120,85,240,75,360,69.3C480,64,600,64,720,90.7C840,117,960,171,1080,170.7C1200,171,1320,117,1380,90.7L1440,64L1440,0L1380,0C1320,0,1200,0,1080,0C960,0,840,0,720,0C600,0,480,0,360,0C240,0,120,0,60,0L0,0Z"> </path> </svg> <!----------------------Apro la section partnership---------------------------------> <section class="partnership"> <div class="row mx-auto text-center"> <div> <h2>Partnerships</h2> </div> <div class="col-lg-3 p-5"> <img src="img/company-1.png" class="img-fluid" alt="Foto Azienda"> </div> <div class="col-lg-3 p-5"> <img src="img/company-2.png" class="img-fluid" alt="Foto Azienda"> </div> <div class="col-lg-3 p-5"> <img src="img/company-3.png" class="img-fluid" alt="Foto Azienda"> </div> <div class="col-lg-3 p-5"> <img src="img/company-4.png" class="img-fluid" alt="Foto Azienda"> </div> </div> </section> <!----------------------Chiudo la section partnership---------------------------------> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"> <path fill="#f5f5f5" fill-opacity="1" d="M0,96L60,90.7C120,85,240,75,360,69.3C480,64,600,64,720,90.7C840,117,960,171,1080,170.7C1200,171,1320,117,1380,90.7L1440,64L1440,320L1380,320C1320,320,1200,320,1080,320C960,320,840,320,720,320C600,320,480,320,360,320C240,320,120,320,60,320L0,320Z"> </path> </svg> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"> <path fill="#f5f5f5" fill-opacity="1" d="M0,192L60,197.3C120,203,240,213,360,192C480,171,600,117,720,112C840,107,960,149,1080,149.3C1200,149,1320,107,1380,85.3L1440,64L1440,0L1380,0C1320,0,1200,0,1080,0C960,0,840,0,720,0C600,0,480,0,360,0C240,0,120,0,60,0L0,0Z"> </path> </svg> <!----------------------Apro la section del carosello---------------------------------> <section class="carosello text-center"> <h2 class="mb-5">Le opinioni dei nostri clienti</h2> <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active mt-5"> <p class="pb-3">Carrot cake fruitcake donut tart dragée tiramisu shortbread. Cupcake sweet candy canes muffin wafer lemon drops cupcake chocolate bar liquorice.</p> <img src="img/reviews/reviews-1.jpg" class="img-fluid rounded-circle mb-3" alt="Foto consumatore"> <h4 class="mb-5">Jamie Batty</h4> </div> <div class="carousel-item mt-5"> <p class="pb-3">Carrot cake fruitcake donut tart dragée tiramisu shortbread. Cupcake sweet candy canes muffin wafer lemon drops cupcake chocolate bar liquorice. Carrot cake fruitcake donut tart dragée tiramisu shortbread. Cupcake sweet candy canes muffin wafer lemon drops cupcake chocolate bar liquorice.</p> <img src="img/reviews/reviews-2.jpg" class="img-fluid rounded-circle mb-3" alt="Foto consumatore"> <h4 class="mb-5">Peppina Di Lorenzo</h4> </div> <div class="carousel-item mt-5"> <p class="pb-3">Carrot cake fruitcake donut tart dragée tiramisu shortbread. Cupcake sweet candy canes muffin wafer lemon drops cupcake chocolate bar liquorice. Carrot cake fruitcake donut tart dragée tiramisu shortbread.</p> <img src="img/reviews/reviews-3.jpg" class="img-fluid rounded-circle mb-3" alt="Foto consumatore"> <h4 class="mb-5">Oscar Turandot</h4> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon sfondo-icona" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon sfondo-icona" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </section> <!----------------------Chiudo la section del carosello---------------------------------> </main> <!----------------------Chiudo il main---------------------------------> <!----------------------Apro il footer---------------------------------> <footer class="footer"> <div class="row mx-auto text-center"> <div class="col-lg-3 p-3 p-lg-5"> <h3 class="pt-3">BootPro</h3> </div> <div class="col-lg-3 p-3 p-lg-5"> <h4>Mission & Vision</h4> <p>Lorem ipsum</p> <p>Lorem ipsum</p> <p>Lorem ipsum</p> </div> <div class="col-lg-3 p-3 p-lg-5"> <h4>Dove Siamo</h4> <p>Lorem ipsum</p> <p>Lorem ipsum</p> <p>Lorem ipsum</p> </div> <div class="col-lg-3 p-3 p-lg-5"> <h4>Contatti</h4> <p>Lorem ipsum</p> <p>Lorem ipsum</p> <p>Lorem ipsum</p> </div> <p>&copy; Manuel per Epicode School</p> </div> </footer> <!----------------------Chiudo il footer---------------------------------> </div> <!----------------------Chiudo il container fluid---------------------------------> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> </body> </html>
<template> <div class="app-container"> <AppNavbar/> <div class="main-content"> <SideBar/> <div class="form-container"> <form @submit="handleSubmit"> <div class="mb-3"> <label for="mode" class="form-label">Operation Mode</label> <select class="form-control" id="mode" v-model="mode"> <option value="add">Add</option> <option value="delete">Delete</option> </select> </div> <div class="mb-3"> <label for="id" class="form-label">ID</label> <input type="text" class="form-control" id="id" v-model="id"> </div><div v-if="formErrors.id" class="alert alert-warning" role="alert"> {{ formErrors.id }} </div> <div class="mb-3" v-if="mode === 'add'"> <label for="name" class="form-label">Name</label> <input type="text" class="form-control" id="name" v-model="name"> </div><div v-if="formErrors.name" class="alert alert-warning" role="alert"> {{ formErrors.name }} </div> <div class="mb-3" v-if="mode === 'add'"> <label for="title" class="form-label">Title</label> <select class="form-select" id="title" v-model="title_id"> <option value="admin">Admin</option> <option value="technician">Technician</option> <option value="caretaker">Caretaker</option> </select> </div><div v-if="formErrors.title_id" class="alert alert-warning" role="alert"> {{ formErrors.title_id }} </div> <button type="submit" class="btn btn-primary">Submit</button> <div class="alert" v-if="responseMessage" :class="isSuccess ? 'alert-success' : 'alert-danger'" role="alert"> {{ responseMessage }} </div> </form> </div> </div> </div> </template> <script> import axios from 'axios'; import AppNavbar from "@/components/AppNavbar.vue"; import SideBar from "@/components/SideBar.vue"; export default { components: {SideBar, AppNavbar}, data() { return { mode: 'add', id: '', name: '', title_id: '', responseMessage: '', isSuccess: null, formErrors: { id: null, name: null, title_id: null } }; }, methods: { async handleSubmit(event) { event.preventDefault(); this.formErrors.id = this.validateInput('id', this.id, "ID"); if (this.mode === 'add') { this.formErrors.name = this.validateInput('name', this.name, "Name"); this.formErrors.title_id = !this.title_id ? "Title is required." : null; } if (!this.formErrors.id && (this.mode === 'delete' || (!this.formErrors.name && !this.formErrors.title_id))) { // Prepare the data const userData = { id: this.id, name: this.name, title_id: this.title_id }; try { let response; if (this.mode === 'add') { response = await axios.post('http://127.0.0.1:5000/user', userData); } else if (this.mode === 'delete') { response = await axios.delete(`http://127.0.0.1:5000/user/${this.id}`); } console.log(response.data.message); this.responseMessage = response.data.message; this.isSuccess = response.status === 200; } catch (error) { this.responseMessage = error.response.data.message; this.isSuccess = false; } } }, validateInput(field, value, label) { if (!value) { return `${label} is required.`; } else if (!/^[a-z0-9]+$/i.test(value)) { return `${label} can only contain alphanumeric characters.`; } else { return null; } } } }; </script> <style scoped> form { width: 500px; height: 450px; margin-left: 0px; margin-top: 10px; } .container { margin-top: 2px; margin-left: 400px; } .sidebar { margin-top: 20px; } .form-signin-heading { color: #CBB26A; } .wrapper { margin-left: 400px; background-color: #1b8dbb; width: 800px; } .form-label { float: left; margin-right: 1em; color: #CBB26A; } .form-check-label { float: left; } .form-check-label { color: #CBB26A; } .form-signin { max-width: 480px; padding: 15px 35px 45px; margin: 0 auto; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.1); } .form-signin-heading, .checkbox { margin-bottom: 30px; } .checkbox { font-weight: normal; } .form-control { position: relative; font-size: 16px; height: auto; padding: 10px; box-sizing: border-box; border-color: #CBB26A; } .form-control:focus { z-index: 2; } input[type='serialNumber '] { margin-bottom: -1px; } input[type='model'] { margin-bottom: 20px; } input[type='location'] { margin-bottom: 20px; } .app-container { display: flex; flex-direction: column; height: 100vh; /* Adjust as needed */ } .main-content { display: flex; flex-grow: 1; } .form-container { display: flex; justify-content: center; align-items: center; flex-grow: 1; } select{ border-color: #CBB26A; } </style>
# What Is An IPVM? To date, IPFS has been a project focused on data. IPVM is a specification for bringing content-addressed execution to content-addressed data on IPFS. To this end, the IPVM spec aims to be the easiest, fastest, most secure, and open way to run decentralized compute jobs everywhere. Another way to describe IPVM would be "an open, decentralized, and local-first competitor to AWS Lambda". The project leverages Wasm, content addressing, SPKI, and object capabilities to liberate computation from depending on specific prenegotiated services like the big cloud providers. Execution should scale flexibly from on-device by default all the way up to edge PoPs and data centers. ## 📋 High-Level Attributes * Wasm-on-IPFS * Declarative invocation (not an ABI, see section below) * Captured results, re-ingested to IPFS * A distributed scheduler * Single vs cron, local vs remote vs either, etc * Matchmaking * Poster/acceptor * Push-to-remote * (Global) memoization table & adaptive optimization * Managed effects (via an IPVM runtime) * Mobile (ambient) computing, compute-to-data, and data-to-compute * "The HTTP of Compute" * Stretch: autonomous agents ## Implementations * [Homestar](https://github.com/ipvm-wg/homestar/) - the core, Rust-based implementation and runtime of IPVM ## Interop * [Bacalhau](https://bacalhau.org) * [Web3Storage](https://web3.storage/) ## :no_good_woman: Antigoals: What An IPVM Is Not * A replacement of IPFS internals — that's wasm-ipfs * A language for distributed applications * A WASI interface * A new blockchain ## 🤹 Separate Projects 1. Autocodec 2. wasm-ipfs 3. IPVM These are related, but separate. The relatedness comes from the fact that if we have one Wasm engine in IPFS, then the other components can rely on it too. ## 👩‍💻 Get Involved * [Community Calls](https://lu.ma/ipvm) ## Presentations - [Seamless Services for an Open World](https://youtu.be/Kr3B3sXh_VA) by Brooklyn Zelenka - [Foundations for Open-World Compute](https://youtu.be/dRz5mau6fsY) by Zeeshan Lakhani - [Foundations for Open-World Compute: Homestar, an IPVM Tale](https://youtu.be/BFAMy5-VHak) by Zeeshan Lakhani - [IPVM: The Long-Fabled Execution Layer](https://www.youtube.com/watch?v=3y1RB8wt_YY) by Brooklyn Zelenka - [IPVM: Content Addressed Compute for an Open World](https://youtu.be/jhtEYr3ORfk) by Brooklyn Zelenka - [IPVM - IPFS and WASM](https://www.youtube.com/watch?v=rzJWk1nlYvs) by Brooklyn Zelenka - [IPVM: Use Cases & System Designs](https://www.youtube.com/watch?v=FhwzEKNZEIA) by Juan Benet ## Related Specs - [IPVM: High-Level Spec](https://github.com/ipvm-wg/spec) - [IPVM Workflow Spec](https://github.com/ipvm-wg/workflow) - [UCAN Invocation Spec](https://github.com/ucan-wg/invocation) ## External Resources - [Contributing Research](https://github.com/ipvm-wg/research) - [Breaking Down the Interplanetary Virtual Machine](https://fission.codes/blog/ipfs-thing-breaking-down-ipvm/) - [IPVM Q1 2023 Update: The Quest to Bring Computation to IPFS](https://fission.codes/blog/ipvm-computation-ipfs/)
from multiprocessing import Lock, Process, Queue, current_process import time import queue from ReceiveDataCallback import ReceiveLSLStreamToKafka # imported for using queue.Empty exception def take_job(tasks_to_accomplish, tasks_that_are_done, inletType='ET',receiveLSLStreamToKafka=ReceiveLSLStreamToKafka()): while True: try: ''' try to get task from the queue. get_nowait() function will raise queue.Empty exception if the queue is empty. queue(False) function would do the same task also. ''' task = tasks_to_accomplish.get_nowait() except queue.Empty: break else: ''' if no exception has been raised, add the task completion message to task_that_are_done queue ''' print(task) receiveLSLStreamToKafka.receiveFromInletProduceToKafka(inletType,'quickstart-events',9092) tasks_that_are_done.put(task + ' is done by ' + current_process().name) time.sleep(.5) return True def main(): inletType=['EEG','ET'] number_of_task = len(inletType) number_of_processes = len(inletType) tasks_to_accomplish = Queue() tasks_that_are_done = Queue() processes = [] receiveLSLStreamToKafka = ReceiveLSLStreamToKafka() for i in range(number_of_task): tasks_to_accomplish.put("Task no " + str(i)) # creating processes for w in range(number_of_processes): p = Process(target=take_job, args=(tasks_to_accomplish, tasks_that_are_done,inletType[w],receiveLSLStreamToKafka)) processes.append(p) p.start() # completing process for p in processes: p.join() # print the output while not tasks_that_are_done.empty(): print(tasks_that_are_done.get()) return True if __name__ == '__main__': main()
//! Example of subscribing and listening for specific contract events by WebSocket subscription. use alloy::{ primitives::address, providers::{Provider, ProviderBuilder, WsConnect}, rpc::types::{BlockNumberOrTag, Filter}, }; use eyre::Result; use futures_util::stream::StreamExt; #[tokio::main] async fn main() -> Result<()> { // Set up the WS transport which is consumed by the RPC client. let rpc_url = "wss://eth-mainnet.g.alchemy.com/v2/your-api-key"; // Create the provider. let ws = WsConnect::new(rpc_url); let provider = ProviderBuilder::new().on_ws(ws).await?; // Create a filter to watch for UNI token transfers. let uniswap_token_address = address!("1f9840a85d5aF5bf1D1762F925BDADdC4201F984"); let filter = Filter::new() .address(uniswap_token_address) // By specifying an `event` or `event_signature` we listen for a specific event of the // contract. In this case the `Transfer(address,address,uint256)` event. .event("Transfer(address,address,uint256)") .from_block(BlockNumberOrTag::Latest); // Subscribe to logs. let sub = provider.subscribe_logs(&filter).await?; let mut stream = sub.into_stream(); while let Some(log) = stream.next().await { println!("Uniswap token logs: {log:?}"); } Ok(()) }
import React from 'react'; import { Controller, SubmitHandler, UseFormReturn, } from 'react-hook-form'; import {useTheme} from 'styled-components'; import TextInput from '../../components/Inputs/TextInput'; import { BtnPrimary, Col, Primary, Row, Text, Img, Container, Form, InfoBar, GreenBar, } from '../../styles/global.styled'; import HeaderApollo from '../../components/Header/Header.apollo'; import FooterView from '../../components/Footer/Footer.view'; import { isCorrectPassword, isPasswordEqual, } from '../../utils/utils'; import {ResetPasswordData} from '../../@types/user'; interface Props { form: UseFormReturn<{ token: string; new_password: string; passwordAgain: string; }>; onSubmit: SubmitHandler<ResetPasswordData>; } const ChangePasswordView = ({form, onSubmit}: Props) => { const theme = useTheme() as {palette: {[k: string]: string}}; return ( <> <HeaderApollo /> <Col alignItems="center"> <Container backgroundColor={theme.palette.Grey5}> <Col justifyContent="center" alignItems="center" gap="20px" padding="50px 0"> <Form onSubmit={form.handleSubmit(onSubmit)}> <Row alignItems="center" gap="20px"> <Img width="50px" height="50px" src="/logo192.png" alt="Logo AlkohoLove" /> <Text as="h1" type="h3" weight="bold" size="large" color={theme.palette.Grey80}> Alkoho<Primary>Love</Primary> </Text> </Row> <Row> <Text as="h2" type="h4" weight="bold" size="large" color={theme.palette.Grey80}> Resetowanie hasła </Text> </Row> <GreenBar margin="0 0 10px 0"> <span className="icon-Success" /> <p> Teraz należy wypełnic poniższe pola tekstowe <br /> i hasło zostanie zmienione. </p> </GreenBar> <Col width="100%" gap="10px"> <Controller control={form.control} name="new_password" rules={{required: true, validate: isCorrectPassword}} render={({field}) => ( <> <Row width="100%"> <TextInput value={field.value} onChange={field.onChange} inputRef={field.ref} icon="icon-Password" title="Hasło" type="password" placeholder="User123" error="Hasło nie jest poprawne." state={ form.formState.errors.new_password ? 'error' : '' } isAutoCompleted /> </Row> <InfoBar> <span className="icon-Info" /> <p> Hasło musi zawierać przynajmniej 8 znaków, <br /> jedną cyfrę oraz jedną dużą literę. </p> </InfoBar> </> )} /> </Col> <Row width="100%"> <Controller control={form.control} name="passwordAgain" rules={{ required: true, validate: (passwordAgain: string) => isPasswordEqual( form.getValues('new_password'), passwordAgain, ), }} render={({field}) => ( <TextInput value={field.value} onChange={field.onChange} icon="icon-Password" inputRef={field.ref} title="Powtórz hasło" placeholder="**********" error="Hasła nie są identyczne!" state={form.formState.errors.passwordAgain ? 'error' : ''} type="password" autoComplete="on" isAutoCompleted /> )} /> </Row> <Row justifyContent="center"> <BtnPrimary type="submit" padding="0 20px"> Zmień hasło </BtnPrimary> </Row> </Form> <Row gap="5px"> <Text type="body" weight="regular" size="medium" color={theme.palette.Grey40}> Masz już konto? </Text> <Text as="a" href="/login" type="body" weight="regular" size="medium" color={theme.palette.Secondary90}> Zaloguj się </Text> </Row> </Col> </Container> </Col> <Row width="100%" padding="50px 0" backgroundColor={theme.palette.White}> <Container> <FooterView /> </Container> </Row> </> ); }; export default ChangePasswordView;
import { Types } from "mongoose"; import { connectionMongo } from "../../database/conection"; import { CatalogueI } from "../../interfaces/catalogue.interface"; import { catalogueModelMongo } from "./model"; export class CatalogueRepository { async getAll() { try { const cnxMongo = await connectionMongo(); const catalogueModel = await catalogueModelMongo(cnxMongo); const response = await catalogueModel.find().exec(); await cnxMongo.close(); return response as CatalogueI[]; } catch (error) { throw new Error(error as string); } } async getByOptions(id: string) { try { const cnxMongo = await connectionMongo(); const catalogueModel = await catalogueModelMongo(cnxMongo); const response = await catalogueModel .find({ parentCatalogueId: id }) .exec(); await cnxMongo.close(); return response as CatalogueI[]; } catch (error) { throw new Error(error as string); } } async getById(id: string) { try { const cnxMongo = await connectionMongo(); const catalogueModel = await catalogueModelMongo(cnxMongo); const response = await catalogueModel.findOne({ _id: id }).exec(); await cnxMongo.close(); return response as CatalogueI; } catch (error) { throw new Error(error as string); } } async getByCode(code: string) { try { const cnxMongo = await connectionMongo(); const catalogueModel = await catalogueModelMongo(cnxMongo); const response = await catalogueModel.findOne({ code }).exec(); await cnxMongo.close(); return response as CatalogueI; } catch (error) { throw new Error(error as string); } } async save(data: CatalogueI) { try { const cnxMongo = await connectionMongo(); const catalogueModel = await catalogueModelMongo(cnxMongo); const response = await catalogueModel.create({ _id: new Types.ObjectId(), ...data, }); await cnxMongo.close(); return response as CatalogueI; } catch (error) { throw new Error(error as string); } } }
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Models\Archivo; use App\Models\Categoria; use App\Models\Emergencia; use App\Models\Incidencia; use App\Models\Statu; use App\Models\Subcategoria; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; use Illuminate\Http\File; use Illuminate\Support\Facades\DB; class IncidenciaController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ // public function index() // { // $incidencias = Incidencia::with(['statu', 'emergencia', 'categoria', 'subcategoria']) // // ->where('user_id', Auth::user()->idusuario) // id de usuario autenticado // ->where('statu_id', 1) // ->get(); // // return $incidencias; // return view('admin.incidencias.index', compact('incidencias')); // } public function index() { // $estatuscreado = Statu::find(1); $estatusespera = Statu::find(1); $estatusasignado = Statu::find(2); $estatuscerrare = Statu::find(3); $estatuscerrano = Statu::find(4); // $incidenciascreadas = Incidencia::where('statu_id', $estatuscreado->id)->get(); // $incidenciascreadascount = Incidencia::where('statu_id', $estatuscreado->id)->count(); $incidenciascreadas = Incidencia::orderBy('id', 'desc')->get(); $incidenciascreadascount = Incidencia::all()->count(); $incidenciasespera = Incidencia::where('statu_id', $estatusespera->id)->orderBy('id', 'desc')->get(); $incidenciasesperacount = Incidencia::where('statu_id', $estatusespera->id)->count(); $incidenciasasignado = Incidencia::where('statu_id', $estatusasignado->id)->orderBy('id', 'desc')->get(); $incidenciasasignadocount = Incidencia::where('statu_id', $estatusasignado->id)->count(); $incidenciascerrare = Incidencia::where('statu_id', $estatuscerrare->id)->orderBy('id', 'desc')->get(); $incidenciascerrarecount = Incidencia::where('statu_id', $estatuscerrare->id)->count(); $incidenciascerrano = Incidencia::where('statu_id', $estatuscerrano->id)->orderBy('id', 'desc')->get(); $incidenciascerranocount = Incidencia::where('statu_id', $estatuscerrano->id)->count(); $incidenciasAll = Incidencia::orderBy('id', 'desc')->get(); return view('template.panel', compact( // 'estatuscreado', 'estatusespera', 'estatusasignado', 'estatuscerrare', 'estatuscerrano', 'incidenciascreadas','incidenciascreadascount', 'incidenciasespera','incidenciasesperacount', 'incidenciasasignado','incidenciasasignadocount', 'incidenciascerrare','incidenciascerrarecount', 'incidenciascerrano','incidenciascerranocount', 'incidenciasAll' )); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $categorias = Categoria::all(); $subcategorias = Subcategoria::with(['categoria'])->get(); $emergencias = Emergencia::all(); return view('admin.incidencias.create', compact('categorias', 'subcategorias', 'emergencias')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $rules = [ 'titulo' => 'required|min:5', 'slug' => 'required|min:5', 'descripcion' => 'required|min:10', 'categoria_id' => 'required|exists:categorias,id', 'subcategoria_id' => 'required|exists:subcategorias,id', 'emergencia_id' => 'required|exists:emergencias,id', 'archivo' => 'nullable|mimes:jpeg,jpg,png,doc,docx,xls,xlsx,csv,pdf,ods,odt', ]; $messages = [ 'titulo.required' => 'Es necesario ingresar un título para la incidencia', 'titulo.min' => 'El título debe contener al menos 5 caracteres', 'slug.required' => 'Es necesario ingresar el título', 'slug.min' => 'El título debe contener al menos 5 caracteres', 'descripcion.required' => 'Es necesario ingresar una descripcion para la incidencia', 'descripcion.min' => 'El descripcion debe contener al menos 10 caracteres', 'categoria_id.required' => 'Es necesario seleccionar una categoría', 'subcategoria_id.required' => 'Es necesario seleccionar una subcategoría', 'emergencia_id.required' => 'Es necesario seleccionar tipo urgencia', 'archivo.mimes' => 'El archivo debe ser de tipo JPEG, JPG, PNG, DOC, DOCX, XLS, XLSX, CSV o PDF', ]; $this->validate($request, $rules, $messages); $incidencia = new Incidencia(); $incidencia->titulo = $request->input('titulo'); $incidencia->slug = $request->input('slug'); $incidencia->descripcion = $request->input('descripcion'); $incidencia->categoria_id = $request->input('categoria_id'); $incidencia->subcategoria_id = $request->input('subcategoria_id'); $incidencia->emergencia_id = $request->input('emergencia_id'); $incidencia->user_id = auth()->user()->idusuario; //usuario que crea la incidencia $incidencia->unidadestructura_id = Auth::user()->cargoxunidad()->idunidadestructura; //BD meru, tabla emp_unidadestructura // // Procesar y guardar el archivo // if ($request->hasFile('archivo')) { // $archivo = $request->file('archivo'); // $extension = $archivo->getClientOriginalExtension(); // $nombreArchivo = $archivo->getClientOriginalName(); // // Verificar que el nombre de archivo no contenga más de un punto // if (substr_count($nombreArchivo, '.') > 1) { // return redirect()->back()->withErrors(['archivo' => 'El nombre del archivo no puede contener más de un punto']); // } // // Guardar el archivo en una ubicación específica // $archivo->storeAs('ruta_de_almacenamiento', $nombreArchivo); // $incidencia->archivo = $nombreArchivo; // $incidencia->extension = $extension; // } $incidencia->saveOrFail(); if ($request->hasFile('nuevos_archivos')) { foreach ($request->file('nuevos_archivos') as $archivo) { if ($archivo) { $nombreArchivo = time() . '_' . $archivo->getClientOriginalName(); $rutaArchivo = $archivo->storeAs('archivos', $nombreArchivo, 'public'); $nuevoArchivo = new Archivo(); $nuevoArchivo->incidencia_id = $incidencia->id; $nuevoArchivo->nombre = $nombreArchivo; $nuevoArchivo->descripcion = $archivo->getClientOriginalName(); $nuevoArchivo->ruta = $rutaArchivo; // Verificar que el nombre de archivo contenga solo un punto if (substr_count($nombreArchivo, '.') !== 1) { return redirect()->back()->withErrors(['archivo' => 'Uno o más archivos tienen un formato inválido'])->withInput(); } $nuevoArchivo->save(); } } } return redirect()->route('admin.incidencias.index')->with('info', 'Incidencia creada con éxito'); } /** * Display the specified resource. * * @param \App\Models\Incidencia $incidencia * @return \Illuminate\Http\Response */ public function show(Incidencia $incidencia) { $incidencia = Incidencia::with('archivos')->find($incidencia->id); return view('admin.incidencias.show', compact('incidencia')); } /** * Show the form for editing the specified resource. * * @param \App\Models\Incidencia $incidencia * @return \Illuminate\Http\Response */ public function edit(Incidencia $incidencia) { $categorias = Categoria::all(); // $subcategorias = Subcategoria::with(['categoria'])->get(); // $subcategorias = $incidencia->categoria_id ? Subcategoria::where('categoria_id', $incidencia->categoria_id)->get() : collect(); $emergencias = Emergencia::all(); $archivos = $incidencia->archivos; $status = Statu::all(); $tecnologiaUsers = DB::connection('rrhh')->table('rrhh.vis_exp_datos_empleado') ->where('idgerencia', 901) // ->where('idstatus', 1) ->orderBy('nombre', 'ASC') // ->latest('nombre') ->pluck('nombre', 'idusuario'); // ->get(); // return $tecnologiaUsers; return view('admin.incidencias.edit', compact('incidencia', 'categorias', /* 'subcategorias', */'emergencias', 'status', 'tecnologiaUsers', 'archivos')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Incidencia $incidencia * @return \Illuminate\Http\Response */ public function update(Request $request, Incidencia $incidencia) { // return $request; $rules = [ 'titulo' => 'required|min:5', 'slug' => 'required|min:5', 'descripcion' => 'required|min:10', 'categoria_id' => 'required|exists:categorias,id', 'subcategoria_id' => 'required|exists:subcategorias,id', 'emergencia_id' => 'required|exists:emergencias,id', 'archivo' => 'nullable|mimes:jpeg,jpg,png,doc,docx,xls,xlsx,csv,pdf,ods,odt', ]; $messages = [ 'titulo.required' => 'Es necesario ingresar un título para la incidencia', 'titulo.min' => 'El título debe contener al menos 5 caracteres', 'slug.required' => 'Es necesario ingresar el título', 'slug.min' => 'El título debe contener al menos 5 caracteres', 'descripcion.required' => 'Es necesario ingresar una descripción para la incidencia', 'descripcion.min' => 'La descripción debe contener al menos 10 caracteres', 'categoria_id.required' => 'Es necesario seleccionar una categoría', 'subcategoria_id.required' => 'Es necesario seleccionar una subcategoría', 'emergencia_id.required' => 'Es necesario seleccionar tipo urgencia', 'archivo.mimes' => 'El archivo debe ser de tipo JPEG, JPG, PNG, DOC, DOCX, XLS, XLSX, CSV o PDF', ]; $this->validate($request, $rules, $messages); $incidencia->titulo = $request->input('titulo'); $incidencia->slug = $request->input('slug'); $incidencia->descripcion = $request->input('descripcion'); $incidencia->categoria_id = $request->input('categoria_id'); $incidencia->subcategoria_id = $request->input('subcategoria_id'); $incidencia->emergencia_id = $request->input('emergencia_id'); $incidencia->asigna_id = auth()->user()->idusuario; //usuario que asigna la incidencia $incidencia->asignado_id = $request->input('asignado_id'); $incidencia->statu_id = $request->input('statu_id'); $incidencia->observacion = $request->input('observacion'); $incidencia->observacion2 = $request->input('observacion2'); $incidencia->save(); // Procesa los nuevos archivos y eliminaciones foreach ($request->input('eliminar_archivos', []) as $archivoId => $eliminar) { if ($eliminar) { $archivo = Archivo::find($archivoId); if ($archivo) { Storage::disk('public')->delete($archivo->ruta); $archivo->delete(); } } } // Procesa los archivos nuevos relacionados if ($request->hasFile('nuevos_archivos')) { // dd($request); foreach ($request->file('nuevos_archivos') as $nuevoArchivo) { if ($nuevoArchivo) { $nombreArchivo = time() . '_' . $nuevoArchivo->getClientOriginalName(); $rutaArchivo = $nuevoArchivo->storeAs('archivos', $nombreArchivo, 'public'); $archivo = new Archivo(); $archivo->incidencia_id = $incidencia->id; $archivo->nombre = $nombreArchivo; $archivo->descripcion = $nuevoArchivo->getClientOriginalName(); $archivo->ruta = $rutaArchivo; $archivo->save(); } } } if ($request->hasFile('nuevo_archivo')) { // dd($request); $nuevoArchivo = $request->file('nuevo_archivo'); $nombreArchivo = time() . '_' . $nuevoArchivo->getClientOriginalName(); $rutaArchivo = $nuevoArchivo->storeAs('archivos', $nombreArchivo, 'public'); $archivo = new Archivo(); $archivo->incidencia_id = $incidencia->id; $archivo->nombre = $nombreArchivo; $archivo->ruta = $rutaArchivo; $archivo->save(); } return redirect()->route('admin.incidencias.index')->with('info', 'Incidencia actualizada con éxito'); } /** * Remove the specified resource from storage. * * @param \App\Models\Incidencia $incidencia * @return \Illuminate\Http\Response */ public function destroy(Incidencia $incidencia) { $incidencia->delete(); return redirect()->route('admin.incidencias.index')->with('info', 'Incidencia eliminada con éxito'); } public function asignar(Incidencia $incidencia) { $tecnologiaUsers = DB::connection('rrhh')->table('rrhh.vis_exp_datos_empleado') ->where('idgerencia', 901) // ->where('idstatus', 1) ->orderBy('nombre', 'ASC') // ->latest('nombre') ->pluck('nombre', 'idusuario'); // ->get(); return view('admin.incidencias.asignar', compact('incidencia','tecnologiaUsers')); } public function asignarIncidencia(Request $request, Incidencia $incidencia) { // Validación de datos del formulario de asignación $request->validate([ 'asignado_id' => 'required|numeric', // Asegúrate de que el campo 'asignado_id' sea requerido y numérico ]); // Actualiza la incidencia con el nuevo asignado $incidencia->asigna_id = auth()->user()->idusuario; //usuario que asigna la incidencia $incidencia->asignado_id = $request->input('asignado_id');; $incidencia->statu_id = 2; // Asignada $incidencia->save(); // Redirige de vuelta a la página de detalles de la incidencia o donde sea necesario return redirect()->route('admin.incidencias.show', $incidencia->id) ->with('success', 'Incidencia asignada con éxito.'); } }
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QMessageBox, QCheckBox from snap7.types import S7CpuInfo import snap7.util import snap7.client import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Siemens x Python") self.setMinimumSize(800, 400) self.db_number = 1 #index of DB / index de la base de données self.client = snap7.client.Client() self.connected = False self.label_IPadress = QLabel("Adresse IP CPU", self) self.label_IPadress.move(10, 5) self.entry_IPadress = QLineEdit(self) self.entry_IPadress.move(10, 30) self.label_Rack = QLabel("Rack", self) self.label_Rack.move(230, 5) self.entry_Rack = QLineEdit(self) self.entry_Rack.move(200, 30) self.label_Slot = QLabel("Slot", self) self.label_Slot.move(425, 5) self.entry_Slot = QLineEdit(self) self.entry_Slot.move(390, 30) self.btn_connect = QPushButton("Connecter", self) self.btn_connect.clicked.connect(self.toggle_connection) self.btn_connect.move(10, 70) self.status_label = QLabel(self) self.status_label.setGeometry(100, 70, 15, 15) self.status_label.setStyleSheet("background-color: #D60000; border-radius: 7px; border: 0.5px solid black;") # Set style self.checkbox_layout = [] self.checkbox_color_labels = [] for x in range(4): for i in range(8): checkbox = QCheckBox(f"Q{x}.{i}", self) checkbox.move(10 + i * 100, 100 + x * 50) checkbox.stateChanged.connect(self.toggle_color) self.checkbox_layout.append(checkbox) color_label = QLabel(self) color_label.setGeometry(50 + i * 100 + 20, 105 + x * 50 + 5, 10, 10) # Adjust position color_label.setStyleSheet("background-color: black; border: 1px solid black;") # Set style self.checkbox_color_labels.append(color_label) self.btn_set_all = QPushButton("SET ALL", self) self.btn_set_all.clicked.connect(self.set_all_checked) self.btn_set_all.move(10, 280) self.btn_reset_all = QPushButton("RESET ALL", self) self.btn_reset_all.clicked.connect(self.rst_all_checked) self.btn_reset_all.move(150, 280) # Function to verify if an IP address is valid / Fonction pour vérifier si l'adresse IP est valide def verifier_ip(self, ip): octets = ip.split(".") if len(octets) != 4: return False for octet in octets: try: octet = int(octet) if octet < 0 or octet > 255: return False except ValueError: return False return True # Function to establish a connection to the PLC / Fonction pour établir une connexion au PLC def connect(self): try: ip = self.entry_IPadress.text() rack = int(self.entry_Rack.text()) slot = int(self.entry_Slot.text()) if not self.verifier_ip(ip): QMessageBox.critical(self, "Erreur", "Adresse IP invalide") return self.client.connect(ip, rack, slot) cpu_info: S7CpuInfo = self.client.get_cpu_info() cpu_tab = str(cpu_info).split("'") QMessageBox.information(self, "Connecté", f"Connexion réussie : {cpu_tab[1]}") self.connected = True self.update_button_color() print(self.client.list_blocks()) except Exception as e: print("Connexion CPU impossible:", e) QMessageBox.critical(self, "Erreur de connexion", "La tentative de connexion à la CPU a échoué. " "Veuillez vérifier votre adresse!") self.connected = False self.update_button_color() # Function to write a boolean value to a PLC address / Fonction pour écrire une valeur booléenne à une adresse PLC def writeBool(self, db_number, start_offset, bit_offset, value): reading = self.client.db_read(db_number, start_offset, 1) snap7.util.set_bool(reading, 0, bit_offset, value) self.client.db_write(db_number, start_offset, reading) # Function to toggle background color of checkboxes / Fonction pour basculer la couleur de fond des cases à cocher def toggle_color(self): for i, checkbox in enumerate(self.checkbox_layout): if checkbox.isChecked(): self.checkbox_color_labels[i].setStyleSheet("background-color: green; border: 1px solid black;") else: self.checkbox_color_labels[i].setStyleSheet("background-color: black; border: 1px solid black;") self.read_write_Qx() # Function to set all checkboxes to True / Fonction pour définir toutes les cases à cocher à True def set_all_checked(self): for checkbox in self.checkbox_layout: checkbox.setChecked(True) self.toggle_color() # Function to set all checkboxes to False / Fonction pour définir toutes les cases à cocher à False def rst_all_checked(self): for checkbox in self.checkbox_layout: checkbox.setChecked(False) self.toggle_color() # Function to read or write to Qx variables / Fonction pour lire ou écrire dans les variables Qx def read_write_Qx(self): try: for x in range(4): for i in range(8): checked = self.checkbox_layout[x * 8 + i].isChecked() self.writeBool(self.db_number, x, i, checked) print(f"Q{x}.{i}: {checked}") except Exception as e: print("Erreur lors de la lecture/écriture de la variable Qx:", e) # Function to update the button color based on connection status / Fonction pour mettre à jour la couleur du bouton en fonction de l'état de la connexion def update_button_color(self): if self.connected: self.status_label.setGeometry(100, 70, 15, 15) self.status_label.setStyleSheet("background-color: #36ED04 ; border-radius: 7px; border: 0.5px solid black;") else: self.status_label.setGeometry(100, 70, 15, 15) self.status_label.setStyleSheet("background-color: #D60000; border-radius: 7px; border: 1px solid black;") # Set style # Function to toggle connection / Fonction pour basculer la connexion def toggle_connection(self): if not self.connected: self.connect() else: # Add code here to close the connection / Ajouter du code ici pour fermer la connexion self.client.disconnect() self.connected = False self.update_button_color() if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
import React from "react"; import PropTypes from "prop-types"; import Item from "./Item"; function List({ notes, onDelete, onArchive, query }) { const unarchivedNotes = notes .filter((note) => note.archived === false) .filter((note) => { if (query) { return note.title.toLowerCase().includes(query.toLowerCase()); } return true; }); const archivedNotes = notes .filter((note) => note.archived === true) .filter((note) => { if (query) { return note.title.toLowerCase().includes(query.toLowerCase()); } return true; }); return ( <> <section id="unarchivedNotes" className="mb-10"> <h2 className="mb-3 text-3xl font-bold">Catatan</h2> <div className="grid grid-cols-1 gap-8 sm:grid-cols-2"> {unarchivedNotes.length > 0 ? ( unarchivedNotes.map((note) => ( <Item key={note.id} id={note.id} onDelete={onDelete} onArchive={onArchive} {...note} /> )) ) : ( <p>Tidak ada catatan</p> )} </div> </section> <section id="archivedNotes"> <h2 className="mb-3 text-3xl font-bold">Arsip</h2> <div className="grid grid-cols-1 gap-8 md:grid-cols-2"> {archivedNotes.length > 0 ? ( archivedNotes.map((note) => ( <Item key={note.id} id={note.id} onDelete={onDelete} onArchive={onArchive} {...note} /> )) ) : ( <p>Tidak ada catatan</p> )} </div> </section> </> ); } List.propTypes = { notes: PropTypes.array, onDelete: PropTypes.func, onArchive: PropTypes.func, query: PropTypes.string, }; export default List;
import React, { useRef } from 'react' import { Input } from 'components/ui' import { HiOutlineSearch, } from 'react-icons/hi' import { setSearch, } from '../store/stateSlice' import { useDispatch } from 'react-redux' import debounce from 'lodash/debounce' const ActionBar = () => { const dispatch = useDispatch() const inputRef = useRef() const debounceFn = debounce(handleDebounceFn, 500) function handleDebounceFn(val) { dispatch(setSearch(val)) } const handleInputChange = (e) => { debounceFn(e.target.value) } return ( <div className="lg:flex items-center justify-between mb-4"> <h3 className="mb-4 lg:mb-0">Manage Teams Members</h3> <div className="flex flex-col md:flex-row md:items-center gap-1"> <Input ref={inputRef} size="sm" placeholder="Search" prefix={<HiOutlineSearch className="text-lg" />} onChange={handleInputChange} /> </div> </div> ) } export default ActionBar
import React, { useState, useEffect, forwardRef, Ref, useImperativeHandle, useRef } from 'react'; import { message, Select } from 'antd'; import TheDrawer from '@/common/components/the-drawer/index'; import { adminRoleUpdate, adminRoleId } from './server'; import { roleListAll, RoleType } from '@/common/public-fetch'; import { FormData } from './types'; function AdministratorDrawer(props: PropsType, ref: Ref<unknown>) { const { id, getList } = props; const [openDrawer, setOpenDrawer] = useState(false); const [roleList, setRoleList] = useState<RoleType[]>([]); const [dataInfo, setDataInfo] = useState<FormData>({ adminId: '', roleIds: [] }); const onSubmit = async () => { try { await adminRoleUpdate(dataInfo) getList(); } catch(error: any) { message.error(error?.message || '请求失败') } } useImperativeHandle(ref, () => { return { isOpen: () => { setOpenDrawer(!openDrawer) } } }) const getAdminRole = async () => { try { const res = await adminRoleId(id!); const data: number[] = []; res.data.forEach(item => { data.push(item.id); }) setDataInfo({ adminId: id!, roleIds: [...data] }) } catch(error: any) { message.error(error.message || '请求失败') } } const getRoleListAll = async () => { try { const res = await roleListAll(); setRoleList([ ...res.data ]) } catch(error: any) { message.error(error?.message || '请求失败') } } const handleChange = (value: number[]) => { setDataInfo(prev => ({ ...prev, roleIds: [...value] })) }; useEffect(() => { if(id) { getRoleListAll(); getAdminRole() } }, [id]) return <TheDrawer title="分配角色" open={openDrawer} onOpenClose={(value) => setOpenDrawer(value)} onSave={() => onSubmit()} > <Select value={dataInfo.roleIds as number[]} mode="multiple" style={{ width: 300 }} allowClear onChange={handleChange} options={(roleList || []).map((d) => ({ value: d.id, label: d.name, })) } /> </TheDrawer> } interface PropsType { id: number | null; getList: () => void; } export default forwardRef<HTMLDivElement, PropsType>(AdministratorDrawer);
#load libraries library(ggplot2) library(grid) library(gridExtra) library(tidyverse) library(stringr) library(interp) ## Settings ------------------------------------------------------- inDir = c('J:/ModelingCovarData/Temperature') covar = 'water_temp' depths = c(0,50,100,200,500,1000,2000,3000,4000) # order to organize depth layers for plotting sites = c('HZ','OC','NC','BC','WC','NFC','HAT','GS','BP','BS','JAX') # NOTE: site order should match order of coordinates below HARPs = t(data.frame(c(41.06165, -66.35155), # WAT_HZ c(40.22999, -67.97798), # WAT_OC c(39.83295, -69.98194), # WAT_NC c(39.19192, -72.22735), # WAT_BC c(38.37337, -73.36985), # WAT_WC c(37.16452, -74.46585), # NFC c(35.5841, -74.7499), # HAT c(33.66992, -75.9977), # WAT_GS c(32.10527, -77.09067), # WAT_BP c(30.58295, -77.39002), # WAT_BS c(30.27818, -80.22085))) # JAX_D rownames(HARPs) = sites colnames(HARPs) = c("Lat","Lon") # Load and organize data by site ----------------------------------------------------------------- fileList = dir(inDir,".Rdata") # # will need to interpolate depths by repeating depth layers # depInt = diff(depths) # depRep = c(depInt/50,1) for (i in 1:length(fileList)){ # Load data from this depth load(paste(inDir,'/',fileList[i],sep="")) if (i==1){ # on first pass, initialize data frames for each site; assumes each depth layer has same timestamps action = paste(sites,rep('=',length(sites)),rep('matrix(nrow=length(depths),ncol=dim(masterData.Covar)[2])', length(sites)),collapse=";") eval(parse(text=action)) action = paste(paste(sites,rep('_time',length(sites)),sep=""),rep('=',length(sites)), rep('matrix(nrow=length(depths),ncol=dim(masterData.Covar)[2])',length(sites)),collapse=";") eval(parse(text=action)) } # Get depth level from file thisFile = fileList[i] thisDepth = str_replace(thisFile,paste(covar,'_',sep=""),"") thisDepth = as.numeric(str_replace(thisDepth,"m.Rdata","")) depthInd = which(depths==thisDepth) # loop through HARP sites for (j in 1:length(sites)){ # find row containing observations at lat closest to this site sitelat = which.min(abs(HARPs[j,1]-masterData.Lat)) # Pull obs to the appropriate site's data frame, with depth given by row action = paste(sites[j],'[',depthInd,', ] = masterData.Covar[sitelat,]',sep="") eval(parse(text=action)) action = paste(sites[j],'_time[',depthInd,', ] = masterData.Time[sitelat,]',sep="") eval(parse(text=action)) } } #CREATE CONTOUR PLOTS --------------------------------------------------------------- z = as.vector(t(HZ[,1:2500])) x= as.vector(t(HZ_time[,1:2500])) y = rep(depths,each=2500) HZ_plot=as.data.frame(cbind(z,x,y)) colnames(HZ_plot) = c("Data","Time","Depth") # Interpolate between vertical layers interpVar = interp(x=HZ_plot$Time,y=HZ_plot$Depth,z=HZ_plot$Data, xo=seq(min(HZ_plot$Time),max(HZ_plot$Time),by=3), yo=seq(min(depths),max(depths),by=50), input="points", output="grid") z = as.vector(interpVar$z) x = rep(interpVar$x,times=81) y = rep(interpVar$y,each=2546) smoothDat = as.data.frame(cbind(z,x,y)) colnames(smoothDat) = c("Data","Time","Depth") # Plot ggplot(smoothDat,aes(x=Time,y=Depth))+ geom_tile(aes(fill=Data))+ scale_y_reverse() x = unlist(lapply(HZ[,1:2500],c));y= unlist(lapply(HZ_time[,1:2500],c)) HZ_plot=as.data.frame(cbind(x,y)) HZ_plot=as.data.frame(cbind(HZ_plot,c(depths))) colnames(HZ_plot) = c("Data","Time","Depth") ggplot(HZ_plot, aes(x=Time, y=Depth, z=Data)) + geom_contour_filled() + scale_y_reverse() + labs(x="Time", y="Depth (m)", title = "HYCOM_Temp") + theme(plot.title = element_text(hjust = 0.5)) + guides(fill = guide_legend(title = "Temperature (?C)"))
import { Box, Button, FormControl, InputLabel, MenuItem, Select, styled, Tab, Tabs, TextField } from '@mui/material'; import { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import ErroModal from '../../components/erroModal/ErroModal'; import SucessoModal from '../../components/sucessoModal/SucessoModal'; import ImgNavioHorizontal from '../../components/imagem/ImgNavioHorizontal'; import ClientRest from '../../integracao/ClientRest'; import UserState from '../../integracao/UserState'; import { MdDetalheNavioTema } from '../../modelos/importarBack/MdDetalheNavioTema'; import { PostNovoTema } from '../../modelos/importarBack/PostNovoTema'; import { LiteralNavio } from '../../modelos/LiteralNavio'; import { StringUteis } from '../../util/StringUteis'; import { UtilNumber } from '../../util/UtilNumber'; const EncVnTextField = styled(TextField)({ '& input + fieldset': { outerWidth: 340, borderColor: '#505050', borderWidth: 2, } }); interface AdicionarNavioTemaProps { onCancelar: () => void; onSalvar: (navioTema: MdDetalheNavioTema) => void; naviosAdicionados: number[] } const AdicionarNavioTema = (props: AdicionarNavioTemaProps) => { // const navigate = useNavigate(); // const userState = new UserState(); // const clientRest = new ClientRest(); const [tamnQuadradosAsString, setTamnQuadradosAsString] = useState(''); const [nomePersonalizado, setNomePersonalizado] = useState(''); const [bytesImagem, setBytesImagem] = useState<Blob | null>(null); const [numeroRecuperacaoImagem, setNumeroRecuperacaoImagem] = useState<string | null>(null); const calcularSrcImagemPrevia = (): string => { if (bytesImagem != null) return URL.createObjectURL(bytesImagem); return ''; } const [srcImagemPrevia, setSrcImagemPrevia] = useState(calcularSrcImagemPrevia()); useEffect(() => setSrcImagemPrevia(_ => calcularSrcImagemPrevia()), [bytesImagem]); const [erroEstaAberto, setErroEstaAberto] = useState(false); const [problemaErro, setProblemaErro] = useState(''); const handleArquivoSelecionado = (event: any) => { setBytesImagem(_ => event.target.files[0]); setNumeroRecuperacaoImagem(_ => StringUteis.gerarNovoIdDe24Caracteres()); } const naviosFiltrados = ()=>{ if (props.naviosAdicionados.length == 0){ return LiteralNavio.listar() } else{ return LiteralNavio.listar().filter((navio) => { return !props.naviosAdicionados.includes(navio.tamnQuadrados) }) } } const handleClickSalvar = async () => { // Validaçao let camposNulos: string[] = []; let tamnQuadradosAsNumber = 0; try { tamnQuadradosAsNumber = parseInt(tamnQuadradosAsString); if (LiteralNavio.obterPorTamnQuadradosOrDefault(tamnQuadradosAsNumber) == null) { camposNulos.push('Ocupação de slots'); } } catch (er) { camposNulos.push('Ocupação de slots'); } if (nomePersonalizado.length == 0) { camposNulos.push('Nome Personalizado'); } if (numeroRecuperacaoImagem == null) { camposNulos.push('Imagem'); } if (camposNulos.length > 0) { setProblemaErro(_ => 'Os campos ' + StringUteis.listarEmPt(camposNulos) + ' são obrigatórios'); setErroEstaAberto(_ => true); return; } let novoNavioTema = new MdDetalheNavioTema(); novoNavioTema.tamnQuadrados = tamnQuadradosAsNumber; novoNavioTema.nomePersonalizado = nomePersonalizado.toLowerCase(); novoNavioTema.numeroRecuperacaoArquivoImagemNavio = numeroRecuperacaoImagem; novoNavioTema.bytesParaUploadArquivo = bytesImagem; if (sessionStorage.getItem(novoNavioTema.nomePersonalizado) == novoNavioTema.nomePersonalizado){ setProblemaErro(_ => 'Os objetos não podem ter o mesmo nome.'); setErroEstaAberto(_ => true); return; } sessionStorage.setItem(novoNavioTema.nomePersonalizado, novoNavioTema.nomePersonalizado); props.onSalvar(novoNavioTema); } return ( <> <h1 style={{color: 'black'}}>Adicionar Personalização</h1> <div className="row g-0"> <FormControl> <InputLabel>Ocupação de Slots</InputLabel> <Select value={tamnQuadradosAsString} label="Ocupação de Slots" onChange={ev => setTamnQuadradosAsString(_ => (ev.target.value as string))} > <MenuItem value=""> <span>Selecione...</span> </MenuItem> {naviosFiltrados().map(iNavioLt => { return ( <MenuItem value={iNavioLt.tamnQuadrados.toString()}> {iNavioLt.nome} </MenuItem> ) })} </Select> </FormControl> </div> <div className="row g-0"> <EncVnTextField label="Nome Personalizado" variant="outlined" className="mt-4" sx={{ width: 350 }} onChange={ev => setNomePersonalizado(_ => ev.target.value)} value={nomePersonalizado} /> {/* Botao de upload */} <div className="d-flex mt-3 align-items-center"> <span>Imagem:</span> <label htmlFor="btn-upload" className="ms-3"> <input id="btn-upload" name="btn-upload" style={{ display: 'none' }} type="file" onChange={handleArquivoSelecionado} /> <Button className="btn-choose" variant="outlined" component="span" > Escolher Arquivo </Button> </label> <strong className='ms-3'>Atenção! O tamanho máximo é de 0,97 MB</strong> </div> <div className="file-name mt-3">{bytesImagem != null ? (bytesImagem as File).name : null}</div> </div> <div> {bytesImagem != null && tamnQuadradosAsString != '' && <ImgNavioHorizontal dadosBase64='' eSrcBase64={false} srcImagem={srcImagemPrevia} tamanhoQuadrados={parseInt(tamnQuadradosAsString)} altImagem='imagem' ePositionAbsolute={false} cssLeftAsPx={0} cssTopAsPx={0} />} </div> <div className="row g-0 mt-3"> <div className="col-6"> <Button size="medium" onClick={() => props.onCancelar()}>Cancelar</Button> </div> <div className="col-6"> <Button size="medium" variant="contained" onClick={() => handleClickSalvar()} style={{marginTop: '10px'}}>Confirmar Personalização</Button> </div> </div> <ErroModal estaAberto={erroEstaAberto} onFechar={() => setErroEstaAberto(_ => false)} problema={problemaErro} /> </> ) } export default AdicionarNavioTema
<template> <div class="relative bg-[#081992]"> <img class="z-1 object-cover absolute h-screen lg:h-auto w-full max-h-full object-top" alt="JeVeuxAider.gouv.fr" srcset="/images/bg-jva.webp, /images/bg-jva@2x.webp 2x, /images/bg-jva.jpg" data-not-lazy > <div class="relative container py-12 lg:py-16"> <div class="mb-12 text-center text-white"> <h1 class="text-4xl lg:text-5xl font-bold mb-4 lg:mb-8 max-w-4xl mx-auto tracking-tight"> Acceptez les règles de bon fonctionnement </h1> <p class="text-lg lg:text-2xl"> Charte co-rédigée avec les responsables d’organisation de la plateforme </p> </div> <Box :padding="false" class="max-w-[1000px] mx-auto px-6 py-8 md:py-12 md:px-16 lg:px-24 lg:py-16"> <p class="md:text-center md:text-lg lg:text-xl mb-4 lg:mb-8"> <span>Le fonctionnement de JeVeuxAider.gouv.fr est régi par la </span> <Link to="https://reserve-civique.crisp.help/fr/article/quelle-est-la-charte-de-la-reserve-civique-1g521m5" target="_blank" > <span>Charte de la Réserve Civique</span> </Link> <span>. En vous inscrivant sur cette plateforme, vous vous engagez à suivre quelques règles de bon fonctionnement qui encadrent la mobilisation de bénévoles. Les voici (en 3 minutes top chrono, c’est promis !) :</span> </p> <AccordionsGroup> <Accordion title-variant="xxl" title-emoji="⏰"> <template slot="title"> Répondre aux bénévoles dès que possible </template> <div class="formatted-text md:text-lg lg:text-xl"> <p> Les bénévoles peuvent consulter plus de 10 000 missions sur JeVeuxAider.gouv.fr. </p> <p> Lorsqu’ils proposent leur aide, ils s’attendent à une réponse rapide de votre part. <strong>Ils choisiront souvent la première mission pour laquelle ils auront eu une réponse.</strong> Nous vous recommandons, en tant qu'organisation, de répondre aux sollicitations des bénévoles dans un délai raisonnable (<strong>si possible dans la semaine qui suit la demande de participation</strong>). La messagerie de JeVeuxAider.gouv.fr est à privilégier dans le cadre des échanges. </p> </div> </Accordion> <Accordion title-variant="xxl" title-emoji="📋"> <template slot="title"> Mettre à jour les demandes de participations </template> <div class="formatted-text md:text-lg lg:text-xl"> <p> Le suivi des participations que vous allez pouvoir réaliser sur la plateforme, <strong>est un élément clef</strong> à de nombreux niveaux. Nous vous demandons ainsi de bien passer les nouvelles demandes de participation au statut “En cours de traitement”, puis <strong>de les valider ou de les refuser en précisant le motif de refus, dans un délai de deux mois</strong>. </p> </div> </Accordion> <Accordion title-variant="xxl" title-emoji="✊"> <template slot="title"> Proposer exclusivement des missions de bénévolat </template> <div class="formatted-text md:text-lg lg:text-xl"> <p> Nous portons une attention toute particulière au fait que les missions publiées sont bien des missions de bénévolat, ne se substituent pas à l’emploi, et sont bien d’intérêt général. </p> <p> <span aria-hidden="true">❗</span> Si nous observons que votre mission ne respecte pas ce cadre légal, nous serons contraints de la signaler et de la supprimer de la plateforme. Ce serait dommage ! </p> </div> </Accordion> <Accordion title-variant="xxl" title-emoji="🙅"> <template slot="title"> Proposer des missions sans exiger de participation financière en contrepartie </template> <div class="formatted-text md:text-lg lg:text-xl"> <p> Vous ne pouvez en aucun cas demander à un bénévole qui s’engage par l’intermédiaire de JeVeuxAider.gouv.fr une participation financière (don financier, adhésion obligatoire…). </p> <p> <span aria-hidden="true">❗</span> Là encore, si vous ne respectez pas ce cadre, nous ne pourrons pas conserver votre mission sur la plateforme. </p> </div> </Accordion> <Accordion title-variant="xxl" title-emoji="🤓"> <template slot="title"> Avoir des informations complètes et à jour sur la plateforme </template> <div class="formatted-text md:text-lg lg:text-xl"> <p> Afin de faciliter le traitement des missions et les échanges que nous serions amenés à avoir avec vous, nous avons besoin d’informations complètes et à jour. Nous comptons sur vous pour mettre à jour sur la plateforme tout changement concernant : les responsables de votre organisation, les responsables des missions, les coordonnées (téléphone, e-mail, adresse…) </p> <p> <span aria-hidden="true">🙂</span> Nous vous en remercions d’avance ! </p> </div> </Accordion> <Accordion title-variant="xxl" title-emoji="✅"> <template slot="title"> Publier des missions dont les contenus respectent les exigences de la plateforme </template> <div class="formatted-text md:text-lg lg:text-xl"> <p> Une mission publiée sur JeVeuxAider.gouv.fr doit comporter les éléments suivants : </p> <ul> <li>Un titre accrocheur à la première personne du singulier décrivant la mission</li> <li>Le contexte de la mission</li> <li>L’engagement nécessaire (ponctuel ou récurrent) et les créneaux spécifiques le cas échéant</li> <li>Les actions / activités à effectuer par le bénévole</li> <li>Les publics auprès desquels le bénévole interviendra</li> </ul> <p>Pour inciter au mieux les bénévoles à se mobiliser, nous vous conseillons :</p> <ul> <li>De rédiger des phrases courtes et claires</li> <li>De faire une mise en page fluide</li> <li>De rédiger un message personnalisé</li> <li>D’ajouter des pré-requis si nécessaire</li> </ul> <p> Il n'est pas admis de mentionner un lien externe sur la fiche mission (Doodle, Airtable, Excel…), des coordonnées (e-mail, téléphone) ou de proposer aux bénévoles de passer par un autre moyen que la plateforme JeVeuxAider.gouv.fr pour s’engager. Pas d'inquiétude, vous disposerez de toutes les informations nécessaires pour échanger avec les bénévoles via la messagerie JeVeuxAider.gouv.fr, par téléphone ou par e-mail lors de leur inscription à la mission que vous proposez. </p> <p> <span aria-hidden="true">❓</span> Encore des doutes sur la rédaction d’une mission, besoin d’un coup de pouce ?! Tous les détails sont par ici <span aria-hidden="true">👉 </span> <Link to="https://www.notion.so/jeveuxaider/Bien-r-diger-votre-mission-63c451d649634e1eacff8a4b9279cbee" target="_blank" > <span>Bien rédiger votre mission</span> </Link> </p> </div> </Accordion> <Accordion title-variant="xxl" title-emoji="‼"> <template slot="title"> Éviter la publication de missions en doublon, triplon… </template> <div class="formatted-text md:text-lg lg:text-xl"> <p> Nous souhaitons éviter d’avoir des missions en doublon, triplon… Ainsi, soyez attentif à la publication dans les cas suivants : </p> <ul> <li> <strong>les missions à distance</strong>, qui sont disponibles auprès de l’ensemble des bénévoles, quelle que soit leur localisation géographique </li> <li> <strong>les missions complètes</strong> : si vous cherchez de nouveaux bénévoles, il vous suffit d’augmenter la jauge de bénévoles recherchés dans la fiche mission pour que l’inscription soit de nouveau possible. </li> <li> <strong>les missions avec une date de fin expirée</strong> : Si la date de votre mission est dépassée et que vous avez toujours besoin de mobiliser des bénévoles, vous pouvez repousser la date de fin, ou supprimer la date de fin en précisant que la mission est récurrente. </li> </ul> <p> <span aria-hidden="true">💡</span> Une même mission proposée sur plusieurs localités différentes n'est pas considérée comme un doublon. </p> </div> </Accordion> <Accordion title-variant="xxl" title-emoji="🦺"> <template slot="title"> Garantir la sécurité et le bon déroulement de la mission de bénévolat </template> <div class="formatted-text md:text-lg lg:text-xl"> <p> Vous êtes garant de la sécurité du bénévole et de l’encadrement lui permettant de réaliser sa mission dans de bonnes conditions. </p> <p> <strong>La charte de la Réserve Civique rappelle que la structure d’accueil s’engage à couvrir les bénévoles mobilisés par l’intermédiaire de JeVeuxAider.gouv.fr contre les dommages subis par lui ou causés à des tiers dans l'accomplissement de sa mission.</strong> </p> <p> <strong>Ceci implique que la structure d’accueil ait souscrit à une assurance afin de couvrir les bénévoles.</strong> </p> <p> Si votre <strong>structure d’accueil est une collectivité publique ou un service public</strong> assuré par une personne privée : </p> <ul> <li>S’il subit un préjudice pendant sa participation au service public, le bénévole peut obtenir une indemnisation tant que son engagement est formalisé.</li> <li>Si un bénévole cause un dommage à un tiers dans le cadre de sa mission, la collectivité publique prend en charge l’indemnisation des préjudices. En tant qu’organisation, vous pouvez vous retourner contre le réserviste s’il a commis une faute personnelle détachable du service. Ce mécanisme est d’origine jurisprudentielle, il est connu sous le nom de collaborateur occasionnel du service public.</li> </ul> </div> </Accordion> <Accordion title-variant="xxl" title-emoji="😁"> <template slot="title"> Veiller au respect des règles élémentaires de politesse et de courtoisie </template> <div class="formatted-text md:text-lg lg:text-xl"> <p> En tant qu’organisation, vous vous engagez à faire preuve de politesse et de respect lorsque vous communiquez ou interagissez avec les bénévoles. Aucun propos discriminant et/ou insultant ne pourra être toléré. Ces règles concernent aussi bien les échanges ayant lieu sur la plateforme qu’en dehors de la plateforme. Des mesures pourront être prises en cas de non-respect de ces règles. </p> </div> </Accordion> </AccordionsGroup> <p class="md:text-center md:text-lg lg:text-xl mt-4 lg:mt-8"> En cas de non-respect de ces règles, des mesures restrictives d’utilisation seront mises en place (limitation des fonctionnalités de la plateforme jusqu’à l’exclusion de la plateforme). Bien sûr, nous ne le souhaitons pas et ce serait dommage d’en arriver là ! </p> <div v-if="!$store.state.auth.user?.has_agreed_responsable_terms_at" class="md:text-center mt-6 md:mt-10 lg:mt-12 flex flex-col items-center gap-4"> <Button type="primary" size="lg" class="w-full md:w-auto" @click.native.prevent="onSubmit"> J'accepte la charte </Button> </div> </Box> </div> </div> </template> <script> import Accordion from '~/components/dsfr/Accordion.vue' import AccordionsGroup from '~/components/dsfr/AccordionsGroup.vue' import Button from '@/components/dsfr/Button.vue' import Link from '@/components/dsfr/Link.vue' export default { components: { Accordion, AccordionsGroup, Button, Link }, data () { return {} }, mounted () { if (!this.$store.state.auth.user?.has_agreed_responsable_terms_at) { this.$toast.success("Merci d'accepter les règles de bon fonctionnement ci-dessous 😉") } }, methods: { async onSubmit () { await this.$store.dispatch('auth/updateUser', { has_agreed_responsable_terms_at: this.$dayjs().utc(true).toISOString() }) // Seulement pour les nouvelles inscriptions const dateFeatureLaunch = this.$dayjs('2023-04-18 17:00:00').utc(true) const userCreatedAt = this.$dayjs(this.$store.state.auth.user?.created_at).utc(true) if (userCreatedAt.isAfter(dateFeatureLaunch)) { this.$plausible.trackEvent('Inscription responsable - CTA - Charte bon fonctionnement') } this.$router.push(this.$route.query?.redirect || '/inscription/responsable/step/profile') }, onCancel () { this.$router.push({ path: '/' }) } } } </script>
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CvManagementApp.Models { public class Candidate : Entity { [Required] public string LastName { get; set; } = string.Empty; [Required] public string FirstName { get; set; } = string.Empty; [Required] [EmailAddress] public string Email { get; set; } = string.Empty; [RegularExpression("^([0-9]{10})$", ErrorMessage = "Invalid Mobile Number.")] public string? Mobile { get; set; } public ICollection<Degree>? Degrees { get; set; } = new List<Degree>(); public byte[]? CV { get; set; } public string? CVFileName { get; set; } public string? CVMimeType { get; set; } } }
/* * === Copyright (C) 2021 Food and Agriculture Organization of the * === United Nations (FAO-UN), United Nations World Food Programme (WFP) * === and United Nations Environment Programme (UNEP) * === * === 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA * === * === Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, * === Rome - Italy. email: geonetwork@osgeo.org * === * === Development of this program was financed by the European Union within * === Service Contract NUMBER – 941143 – IPR – 2021 with subject matter * === "Facilitating a sustainable evolution and maintenance of the INSPIRE * === Geoportal", performed in the period 2021-2023. * === * === Contact: JRC Unit B.6 Digital Economy, Via Enrico Fermi 2749, * === 21027 Ispra, Italy. email: JRC-INSPIRE-SUPPORT@ec.europa.eu */ package com.geocat.ingester.model.linkchecker.helper; import javax.persistence.*; //Base class for information in a metadata record (i.e. <MD_Metadata>....) @MappedSuperclass public class MetadataRecord extends UpdateCreateDateTimeEntity { //not saved to DB - use the SHA2 link to get the data from blobstorage @Transient public String actualXML; @Column(columnDefinition = "text") private String title; //SHA2 of the XMNL Text @Column(columnDefinition = "varchar(64)") private String sha2; //File identifier (see XML XSL) @Column(columnDefinition = "text") private String fileIdentifier; //File identifier (see XML XSL) @Column(columnDefinition = "text") private String parentIdentifier; // what type of metadata document is this (service/dataset/series/...) @Column(columnDefinition = "varchar(22)") @Enumerated(EnumType.STRING) private MetadataDocumentType metadataRecordType; // summary of this document's processing in a somewhat human-readable format @Column(columnDefinition = "text") private String humanReadable; //Number of documents links that resolve to a capabilities document. // null = not evaluated Integer INDICATOR_RESOLVES_TO_CAPABILITIES; //If >1 capabilities, then the most common type (WMS/WFS/WMTS/ATOM). If there is an equal number, then choose any one. // null = not evaluated @Enumerated(EnumType.STRING) @Column(columnDefinition = "varchar(5)") CapabilitiesType INDICATOR_CAPABILITIES_TYPE; public MetadataRecord() { super(); } //--------------------------------------------------------------------------- public String getParentIdentifier() { return parentIdentifier; } public void setParentIdentifier(String parentIdentifier) { this.parentIdentifier = parentIdentifier; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getINDICATOR_RESOLVES_TO_CAPABILITIES() { return INDICATOR_RESOLVES_TO_CAPABILITIES; } public void setINDICATOR_RESOLVES_TO_CAPABILITIES(Integer INDICATOR_RESOLVES_TO_CAPABILITIES) { this.INDICATOR_RESOLVES_TO_CAPABILITIES = INDICATOR_RESOLVES_TO_CAPABILITIES; } public CapabilitiesType getINDICATOR_CAPABILITIES_TYPE() { return INDICATOR_CAPABILITIES_TYPE; } public void setINDICATOR_CAPABILITIES_TYPE(CapabilitiesType INDICATOR_CAPABILITIES_TYPE) { this.INDICATOR_CAPABILITIES_TYPE = INDICATOR_CAPABILITIES_TYPE; } public String getHumanReadable() { return humanReadable; } public void setHumanReadable(String humanReadable) { this.humanReadable = humanReadable; } public String getSha2() { return sha2; } public void setSha2(String sha2) { this.sha2 = sha2; } public String getFileIdentifier() { return fileIdentifier; } public void setFileIdentifier(String recordIdentifier) { this.fileIdentifier = recordIdentifier; } public MetadataDocumentType getMetadataRecordType() { return metadataRecordType; } public void setMetadataRecordType(MetadataDocumentType metadataRecordType) { this.metadataRecordType = metadataRecordType; } protected void onUpdate() { super.onUpdate(); } protected void onInsert() { super.onInsert(); } //--------------------------------------------------------------------------- @Override public String toString() { String result = super.toString(); result += " title: " + title + "\n"; result += " sha2: " + sha2 + "\n"; result += " fileIdentifier: " + fileIdentifier + "\n"; result += " metadataRecordType: " + metadataRecordType + "\n"; return result; } }
import React from 'react'; import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink } from 'reactstrap'; export default class Example extends React.Component { constructor(props) { super(props); this.toggleNavbar = this.toggleNavbar.bind(this); this.state = { collapsed: true }; } toggleNavbar() { this.setState({ collapsed: !this.state.collapsed }); } render() { return ( <div style={{}} > <Navbar style={{backgroundImage:"linear-gradient(#D82E2F,rgb(161, 65, 65),rgb(77, 63, 50))"}} light> <NavbarToggler onClick={this.toggleNavbar} className="mr-2" /> <NavbarBrand href="/" className="mr-auto " style={{color:"rgb(236, 132, 13)",fontWeight:"900"}}>BTECH BIRYANI</NavbarBrand> <span ><NavLink style={{color:"rgb(236, 132, 13)",fontWeight:"700"}} href="/#/cart">CART</NavLink></span> <Collapse isOpen={!this.state.collapsed} navbar> <Nav navbar> <NavItem> <NavLink href="/#/home" style={{color:"rgb(236, 132, 13)",fontWeight:"700"}}>Home</NavLink> </NavItem> <NavItem> <NavLink href="/#/cart" style={{color:"rgb(236, 132, 13)",fontWeight:"700"}}>Cart</NavLink> </NavItem> <NavItem> </NavItem> </Nav> </Collapse> </Navbar> </div> ); } }
import { Search } from '@mui/icons-material' import { Fade, FormControlLabel, IconButton, LinearProgress, Menu, MenuItem, Switch, TextField, Typography } from '@mui/material' import { Stack } from '@mui/system' import { AxiosResponse } from 'axios' import React, { useContext, useEffect, useState } from 'react' import { useQuery } from 'react-query' import DBPagination from '../../components/pagination/DBpagination'; import { BackendError } from '../..' import { Menu as MenuIcon } from '@mui/icons-material'; import { ChoiceContext, TodoChoiceActions } from '../../contexts/dialogContext' import ExportToExcel from '../../utils/ExportToExcel' import AlertBar from '../../components/snacks/AlertBar' import { ITodo } from '../../types/todo.types' import { IUser } from '../../types/user.types' import { GetUsers } from '../../services/UserServices' import moment from 'moment' import { UserContext } from '../../contexts/userContext' import NewTodoDialog from '../../components/dialogs/todos/NewTodoDialog' import TableSkeleton from '../../components/skeleton/TableSkeleton' import TodoSTable from '../../components/tables/TodoTable' import { FuzzySearchTodos, GetTodos } from '../../services/TodoServices' import BulkHideTodoDialog from '../../components/dialogs/todos/BulkHideTodoDialog' export default function TodosAdminPage() { const [hidden, setHidden] = useState(false) const { user } = useContext(UserContext) const [users, setUsers] = useState<IUser[]>([]) const [paginationData, setPaginationData] = useState({ limit: 100, page: 1, total: 1 }); const [filter, setFilter] = useState<string | undefined>() const [todo, setTodo] = useState<ITodo>() const [todos, setTodos] = useState<ITodo[]>([]) const [selectAll, setSelectAll] = useState(false) const MemoData = React.useMemo(() => todos, [todos]) const [preFilteredData, setPreFilteredData] = useState<ITodo[]>([]) const [preFilteredPaginationData, setPreFilteredPaginationData] = useState({ limit: 100, page: 1, total: 1 }); const [filterCount, setFilterCount] = useState(0) const [selectedTodos, setSelectedTodos] = useState<ITodo[]>([]) const [userId, setUserId] = useState<string>() const [dates, setDates] = useState<{ start_date?: string, end_date?: string }>({ start_date: moment(new Date("Mon Dec 01 2023 12:00:00 GMT+0530 (India Standard Time)")).format("YYYY-MM-DD") , end_date: moment(new Date().setDate(new Date().getDate() + 1)).format("YYYY-MM-DD") }) const { data: usersData, isSuccess: isUsersSuccess } = useQuery<AxiosResponse<IUser[]>, BackendError>("users", async () => GetUsers()) const { data, isLoading, refetch: ReftechTodos } = useQuery<AxiosResponse<{ todos: ITodo[], page: number, total: number, limit: number }>, BackendError>(["todos", paginationData, userId, dates?.start_date, dates?.end_date], async () => GetTodos({ limit: paginationData?.limit, page: paginationData?.page, id: userId, start_date: dates?.start_date, end_date: dates?.end_date, hidden: hidden })) const { data: fuzzytodos, isLoading: isFuzzyLoading, refetch: refetchFuzzy } = useQuery<AxiosResponse<{ todos: ITodo[], page: number, total: number, limit: number }>, BackendError>(["fuzzytodos", filter], async () => FuzzySearchTodos({ searchString: filter, limit: paginationData?.limit, page: paginationData?.page, hidden: hidden }), { enabled: false }) const [selectedData, setSelectedData] = useState<{ todo_description: string, person: string, created_at: string, updated_at: string, created_by: string, updated_by: string, }[]>() const [sent, setSent] = useState(false) const { setChoice } = useContext(ChoiceContext) const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null); function handleExcel() { setAnchorEl(null) try { selectedData && ExportToExcel(selectedData, "todos_data") setSent(true) setSelectAll(false) setSelectedData([]) setSelectedTodos([]) } catch (err) { console.log(err) setSent(false) } } // refine data useEffect(() => { let data: { todo_description: string, person: string, created_at: string, updated_at: string, updated_by: string, created_by: string, }[] = [] selectedTodos.map((todo) => { return data.push( { todo_description: todo.work_description, person: todo.person.username, created_at: todo.created_at.toLocaleString(), created_by: todo.created_by.username, updated_by: todo.updated_by.username, updated_at: todo.updated_at.toLocaleString(), }) }) if (data.length > 0) setSelectedData(data) }, [selectedTodos]) useEffect(() => { if (isUsersSuccess) setUsers(usersData?.data) }, [users, isUsersSuccess, usersData]) useEffect(() => { if (!filter) { setTodos(preFilteredData) setPaginationData(preFilteredPaginationData) } }, [filter]) useEffect(() => { ReftechTodos() }, [hidden]) useEffect(() => { if (filter) { refetchFuzzy() } }, [paginationData]) useEffect(() => { if (data && !filter) { setTodos(data.data.todos) setPreFilteredData(data.data.todos) setPreFilteredPaginationData({ ...paginationData, page: data.data.page, limit: data.data.limit, total: data.data.total }) setPaginationData({ ...paginationData, page: data.data.page, limit: data.data.limit, total: data.data.total }) } }, [data]) useEffect(() => { if (fuzzytodos && filter) { setTodos(fuzzytodos.data.todos) let count = filterCount if (count === 0) setPaginationData({ ...paginationData, page: fuzzytodos.data.page, limit: fuzzytodos.data.limit, total: fuzzytodos.data.total }) count = filterCount + 1 setFilterCount(count) } }, [fuzzytodos]) return ( <> { isLoading && <LinearProgress /> } { isFuzzyLoading && <LinearProgress /> } {/*heading, search bar and table menu */} <Stack spacing={2} padding={1} direction="row" justifyContent="space-between" width="100vw" > <Typography variant={'h6'} component={'h1'} sx={{ pl: 1 }} > {window.screen.width > 450 ? "Todo Admin" : "Admin"} </Typography> <Stack direction="row" > {/* search bar */} < Stack direction="row" spacing={2}> <FormControlLabel control={<Switch defaultChecked={Boolean(hidden)} onChange={() => setHidden(!hidden)} />} label="Show hidden" /> <TextField fullWidth size="small" onChange={(e) => { setFilter(e.currentTarget.value) setFilterCount(0) }} autoFocus placeholder={`${MemoData?.length} records...`} style={{ fontSize: '1.1rem', border: '0', }} onKeyUp={(e) => { if (e.key === "Enter") { refetchFuzzy() } }} /> <IconButton sx={{ bgcolor: 'whitesmoke' }} onClick={() => { refetchFuzzy() }} > <Search /> </IconButton> </Stack > <> {sent && <AlertBar message="File Exported Successfuly" color="success" />} <IconButton size="small" color="primary" onClick={(e) => setAnchorEl(e.currentTarget) } sx={{ border: 2, borderRadius: 3, marginLeft: 1 }} > <MenuIcon /> </IconButton> <Menu anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={() => setAnchorEl(null) } TransitionComponent={Fade} MenuListProps={{ 'aria-labelledby': 'basic-button', }} sx={{ borderRadius: 2 }} > { user?.todos_access_fields.is_editable && <> <MenuItem onClick={() => { setChoice({ type: TodoChoiceActions.create_todo }) setAnchorEl(null) }} > Add New</MenuItem> <MenuItem onClick={() => { setChoice({ type: TodoChoiceActions.bulk_hide_todo }) setAnchorEl(null) }} > Hide Todos</MenuItem> </> } < MenuItem onClick={handleExcel} >Export To Excel</MenuItem> </Menu > <NewTodoDialog /> <BulkHideTodoDialog todos={selectedTodos} /> </> </Stack > </Stack > {/* filter dates and person */} <Stack direction='row' gap={2} p={2} alignItems={'center'} justifyContent={'center'}> < TextField size='small' type="date" id="start_date" label="Start Date" fullWidth value={dates.start_date} focused onChange={(e) => { if (e.currentTarget.value) { setDates({ ...dates, start_date: moment(e.target.value).format("YYYY-MM-DD") }) } }} /> < TextField size='small' type="date" id="end_date" label="End Date" value={dates.end_date} focused fullWidth onChange={(e) => { if (e.currentTarget.value) { setDates({ ...dates, end_date: moment(e.target.value).format("YYYY-MM-DD") }) } }} /> {user?.is_admin && < TextField size='small' select SelectProps={{ native: true, }} onChange={(e) => { setUserId(e.target.value) ReftechTodos() }} required id="todo_owner" label="Filter Todos Of Indivdual" fullWidth > <option key={'00'} value={undefined}> </option> { users.map((user, index) => { return (<option key={index} value={user._id}> {user.username} </option>) }) } </TextField>} </Stack> {/* table */} {isLoading && <TableSkeleton />} {!isLoading && < TodoSTable todo={todo} setTodo={setTodo} selectAll={selectAll} selectedTodos={selectedTodos} setSelectedTodos={setSelectedTodos} setSelectAll={setSelectAll} todos={MemoData} />} <DBPagination paginationData={paginationData} setPaginationData={setPaginationData} setFilterCount={setFilterCount} /> </> ) }
package main import ( "testing" ) // Unit tests func TestEnqueue(t *testing.T) { q := NewLockFreeQueue() q.Enqueue(1) q.Enqueue(2) q.Enqueue(3) if got, _ := q.Dequeue(0); got != 1 { t.Errorf("expected 1, got %v", got) } if got, _ := q.Dequeue(0); got != 2 { t.Errorf("expected 2, got %v", got) } if got, _ := q.Dequeue(0); got != 3 { t.Errorf("expected 3, got %v", got) } if _, ok := q.Dequeue(0); ok { t.Errorf("expected queue to be empty") } } func TestDequeueEmpty(t *testing.T) { q := NewLockFreeQueue() if _, ok := q.Dequeue(0); ok { t.Errorf("expected queue to be empty") } } func TestEnqueueDequeueInterleaved(t *testing.T) { q := NewLockFreeQueue() q.Enqueue(1) if got, _ := q.Dequeue(0); got != 1 { t.Errorf("expected 1, got %v", got) } q.Enqueue(2) q.Enqueue(3) if got, _ := q.Dequeue(0); got != 2 { t.Errorf("expected 2, got %v", got) } q.Enqueue(4) if got, _ := q.Dequeue(0); got != 3 { t.Errorf("expected 3, got %v", got) } if got, _ := q.Dequeue(0); got != 4 { t.Errorf("expected 4, got %v", got) } } func TestRetireNode(t *testing.T) { q := NewLockFreeQueue() q.Enqueue(1) q.Enqueue(2) q.Enqueue(3) q.Dequeue(0) q.Dequeue(0) q.Dequeue(0) if len(q.epoch.retired[0]) != 3 { t.Errorf("expected 3 retired nodes, got %v", len(q.epoch.retired[0])) } } func TestEpochReclamation(t *testing.T) { q := NewLockFreeQueue() // Enqueue some elements q.Enqueue(1) q.Enqueue(2) q.Enqueue(3) // Dequeue all elements q.Dequeue(0) q.Dequeue(0) q.Dequeue(0) // Ensure nodes are retired if len(q.epoch.retired[0]) != 3 { t.Errorf("expected 3 retired nodes, got %v", len(q.epoch.retired[0])) } // Move epoch to trigger reclamation q.IncrementEpoch() q.IncrementEpoch() q.IncrementEpoch() // Ensure nodes are reclaimed if len(q.epoch.retired[0]) != 0 { t.Errorf("expected 0 retired nodes, got %v", len(q.epoch.retired[0])) } } func TestEnqueueN(t *testing.T) { q := NewLockFreeQueue() values := []interface{}{1, 2, 3, 4, 5} q.EnqueueN(values) for i := 0; i < len(values); i++ { if got, _ := q.Dequeue(0); got != values[i] { t.Errorf("expected %v, got %v", values[i], got) } } } func TestDequeueN(t *testing.T) { q := NewLockFreeQueue() values := []interface{}{1, 2, 3, 4, 5} q.EnqueueN(values) dequeuedValues, _ := q.DequeueN(0, 3) expectedValues := []interface{}{1, 2, 3} for i := 0; i < len(expectedValues); i++ { if dequeuedValues[i] != expectedValues[i] { t.Errorf("expected %v, got %v", expectedValues[i], dequeuedValues[i]) } } dequeuedValues, _ = q.DequeueN(0, 3) expectedValues = []interface{}{4, 5} for i := 0; i < len(expectedValues); i++ { if dequeuedValues[i] != expectedValues[i] { t.Errorf("expected %v, got %v", expectedValues[i], dequeuedValues[i]) } } }
import "./App.css"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import Home from "./pages/Home"; import SignIn from "./pages/auth/SignIn"; import SignUp from "./pages/auth/SignUp"; import ChatPage from "./pages/ChatPage"; import { useGlobalContext } from "./context/ChatContext"; function App() { const {authUser} = useGlobalContext(); return ( <BrowserRouter> <div className="min-h-screen w-full"> <Routes> <Route path="/" element={<Home /> } /> <Route path="/signin" element={ authUser ? <ChatPage /> : <SignIn />} /> <Route path="/signup" element={<SignUp /> } /> <Route path="/chat-page" element={authUser ? <ChatPage /> : <SignIn />} /> </Routes> </div> </BrowserRouter> ); } export default App;
package com.julianhzgn.proyectodesarrollomobiles import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.appcompat.widget.SearchView import androidx.core.view.isVisible import androidx.recyclerview.widget.LinearLayoutManager import com.julianhzgn.proyectodesarrollomobiles.DetailRecipeActivity.Companion.EXTRA_ID import com.julianhzgn.proyectodesarrollomobiles.databinding.ActivitySeachBinding import com.squareup.picasso.Picasso import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class SeachActivity : AppCompatActivity() { private lateinit var binding: ActivitySeachBinding private lateinit var retrofit: Retrofit private lateinit var adapter: RecipeAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySeachBinding.inflate(layoutInflater) setContentView(binding.root) retrofit = getRetrofit() initUI() } private fun initUI() { binding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { searchByName(query.orEmpty()) return false } override fun onQueryTextChange(newText: String?) = false } ) adapter = RecipeAdapter { RecipeId -> navigateToDetail(RecipeId) } binding.rvRecipe.setHasFixedSize(true) binding.rvRecipe.layoutManager = LinearLayoutManager(this) binding.rvRecipe.adapter = adapter } private fun searchByName(query: String) { val apiKey = "e71fb43c3d0a4578845ec750cd79bcce" binding.progressBar.isVisible = true CoroutineScope(Dispatchers.IO).launch { val myResponse = retrofit.create(ApiService::class.java).getFood(query, apiKey) if (myResponse.isSuccessful) { Log.i("Julian", "SI funciona") val response: IngredientDataResponse? = myResponse.body() if (response != null) { Log.i("Julian", response.toString()) runOnUiThread { adapter.updateList(response.results) binding.progressBar.isVisible = false } } } else { Log.i("Julian", "NO funciona") } } } private fun getRetrofit(): Retrofit { return Retrofit.Builder().baseUrl("https://api.spoonacular.com/") .addConverterFactory(GsonConverterFactory.create()).build() } private fun navigateToDetail(id: String) { val intent = Intent(this, DetailRecipeActivity::class.java) intent.putExtra(EXTRA_ID, id) startActivity(intent) } }
import React, { useState } from "react"; import { DndProvider } from "react-dnd"; import { Tree, MultiBackend, getBackendOptions } from "@minoru/react-dnd-treeview"; import { CustomNode } from "./CustomNode"; import { Placeholder } from "./Placeholder"; import { CustomDragPreview } from "./CustomDragPreview"; import styles from "./Hierarchy.module.css"; import { treeDataToUiState, uiStateToTreeData } from './utils'; function Hierarchy({ uiState, setUiState, selectedElement, setSelectedElement, }) { const treeData = uiStateToTreeData(uiState); const handleDrop = (newTree => { setUiState(treeDataToUiState(newTree)); }); const addNewById = (contextNode) => { const newNodeData = { text: 'Awesome New Element', id: new Date().getTime(), droppable: false, data: { tagName: 'div', tagProps: { style: { padding: '10px', backgroundColor: '#fff', border: '1px solid #ddd', borderRadius: '4px' } }, innerHtml: 'I am a div, but I can be anything you want!', children: [] } }; if (contextNode.droppable) { newNodeData.parent = contextNode.id; } else { newNodeData.parent = contextNode.parent; } treeData.push(newNodeData); setUiState(treeDataToUiState(treeData)); }; const deleteById = (contextNode) => { const newTree = treeData.filter(node => node.id !== contextNode.id); setUiState(treeDataToUiState(newTree)); setTimeout(() => { setSelectedElement(null); },1); }; return ( <div className={styles.container}> <DndProvider backend={MultiBackend} options={getBackendOptions()}> <div> <Tree initialOpen={true} tree={treeData} rootId="root" render={(node, { depth, isOpen, onToggle }) => ( <CustomNode node={node} depth={depth} isOpen={isOpen} onToggle={onToggle} isSelected={node.id === selectedElement?.id} onSelect={setSelectedElement} onNew={addNewById} onDelete={deleteById} /> )} dragPreviewRender={(monitorProps) => ( <CustomDragPreview monitorProps={monitorProps} /> )} onDrop={handleDrop} classes={{ root: styles.treeRoot, draggingSource: styles.draggingSource, placeholder: styles.placeholderContainer, dropTarget: styles.dropTarget }} sort={false} insertDroppableFirst={false} canDrop={(tree, { dragSource, dropTargetId, dropTarget }) => { if (dragSource?.parent === dropTargetId) { return true; } }} dropTargetOffset={5} placeholderRender={(node, { depth }) => ( <Placeholder node={node} depth={depth} /> )} /> </div> </DndProvider> </div> ); } export default Hierarchy;
import { useReducer } from "react"; const initializeState = () => ({ width: 100, }); // ✅ note how the value returned from the fn above overrides initialState below: const initialState = { width: 15 }; const reducer = (state, action) => { switch (action) { case "plus": return { width: state.width + 15 }; case "minus": return { width: Math.max(state.width - 15, 2) }; default: throw new Error("what's going on?"); } }; const UseReducer = () => { const [state, dispatch] = useReducer( reducer, initialState, initializeState ); return ( <> <div style={{ background: "teal", height: "30px", width: state.width, }} ></div> <div style={{ marginTop: "3rem" }}> <button onClick={() => dispatch("plus")}> Increase bar size </button> <button onClick={() => dispatch("minus")}> Decrease bar size </button> </div> </> ); }; export default UseReducer;
package club.evolutioniot.ssh.system.web.action; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionContext; import club.evolutioniot.ssh.common.util.ThisStaticCodes; import club.evolutioniot.ssh.common.web.action.BaseAction; import club.evolutioniot.ssh.system.domain.Menu; import club.evolutioniot.ssh.system.domain.PlayUser; import club.evolutioniot.ssh.system.service.MenuService; import club.evolutioniot.ssh.system.service.PlayUserService; @Controller("backgroundAction") @Scope(value="prototype") public class BackgroundAction extends BaseAction<PlayUser>{ @Autowired private PlayUserService playUserService; @Autowired private MenuService menuService; public String loginUI(){ return "loginUI"; } public String login(){ PlayUser user = this.t; user = this.playUserService.Login(user, ThisStaticCodes.SYS_MANAGER); if (user != null) { // 将完整登陆用户查询出来后,对象存入Session ActionContext.getContext().getSession().put("usersInfo", user); List<Menu> menuList = menuService.findMenu(user.getUserRole()); ActionContext.getContext().getSession().put("menus", menuList); return LOGIN; } else return ERROR; } public String userList(){ PlayUser userInfo = this.t; ActionContext.getContext().put("userInfo", userInfo); if(userInfo!=null){ List<PlayUser> userList = playUserService.selectNomalUser(userInfo); userList.stream().forEach(System.out::println); ActionContext.getContext().put("userList", userList); } return "userList"; } public String findUsers(){ //输入框获取查询的对象 PlayUser userInfo = this.t; ActionContext.getContext().put("userInfo", userInfo); System.out.println(userInfo.getPlayUserId()+ " ::: " + userInfo.getPlayUserName()); if(userInfo!=null){ List<PlayUser> userList = playUserService.selectNomalUser(userInfo); userList.stream().forEach(System.out::println); ActionContext.getContext().put("userList", userList); } return "findUsers"; } public String updateUsers(){ //获取即将修改的单个对象 PlayUser userDetail = this.t; //组装数据 userDetail = playUserService.findUserById(userDetail.getPlayUserId()); //存入Request域 ActionContext.getContext().put("user", userDetail); //跳转页面 return "updateUsers"; } /** * 修改单个用户对象 * @return */ public String updateUser(){ //获取表单提交数据 PlayUser userDetail = this.t; System.out.println(userDetail); //组装数据 PlayUser user = playUserService.findUserById(userDetail.getPlayUserId()); user.setPlayUserPassword(userDetail.getPlayUserPassword()); user.setPlayUserSex(userDetail.getPlayUserSex()); user.setPlayUserBirthday(userDetail.getPlayUserBirthday()); user.setPlayUserPhone(userDetail.getPlayUserPhone()); user.setPlayUserEmail(userDetail.getPlayUserEmail()); playUserService.modifyUser(user); ActionContext.getContext().put("user", user); return "updateUser"; } public String addUserUI(){ return "addUserUI"; } }
/* eslint-disable react/prop-types */ /* eslint-disable no-unused-vars */ import React, { useState } from "react"; import searchIcon from "../assets/search.svg"; import { useDispatch } from "react-redux"; import { setFilter } from "../redux/features/filterSlice"; import "./Search.css"; export function Search() { let [search, setSearch] = useState(""); let dispatch = useDispatch(); let handleOnChange = (e) => { let value = e.target.value; setSearch(value); }; let handleOnclick = () => { if (search == "") return; dispatch(setFilter({ name: search, region: "", filterByName: true })); }; let handleOnKeyUp = (e) => { if (search == "") return; if (e.keyCode == 13) { dispatch(setFilter({ name: search, region: "", filterByName: true })); } }; return ( <div className="search"> <button onClick={handleOnclick} className="search_button"> <img src={searchIcon} alt="icon search" className="search_image" /> </button> <input type="text" className="search_input" onChange={handleOnChange} onKeyUp={handleOnKeyUp} value={search} placeholder="Search for a country..." /> </div> ); }
\chapter{Local invariant features II} \section{Difference of Gaussians (DoG)} It is possible to define an approximation of the Laplacian of Gaussian by using difference of Gaussians: \[DoG = G(x,y,k\sigma) - G(x,y,\sigma)\] where $k$ is a scalar value and $G$ is the two-dimensional Gaussian function \[\frac{1}{2\pi \sigma^{2}}e^{-\frac{x^{2} + y^{2}}{2\sigma^{2}}}\] Basically, it approximates the behavior of the Laplacian of Gaussian computing the difference between two Gaussian functions with different values of $\sigma$ \begin{center} \includegraphics[scale = 0.7]{images/DoG Approx.png} \end{center} This is useful because $DoG$ is more efficient from a computational point of view. In fact, computing the second order derivative is more expensive than performing a difference between two functions. \section{SIFT algorithm} SIFT is a scale invariant feature detection algorithm that applies $DoG$ both in space and over different scales. Thanks to this, it is computationally more efficient than the Harris-Laplacian algorithm. Following are the major stages of computation used to generate the set of image features: \begin{enumerate} \item \textbf{Scale-space extrema detection:} The first stage of computation searches for local features over all scales and image locations using a difference of Gaussian function. \item \textbf{Key-point localization:} At each candidate location, a detailed model is fit to determine location and scale. Key-points are selected based on measures of their stability (\textbf{It was not covered in class}). \item \textbf{Orientation assignment:} One or more orientations are assigned to each key-point location based on local image gradient directions. \item \textbf{Key-point descriptor:} Describing the key-points as a high dimensional vector such that it is highly distinctive and invariant as possible to variations such as changes in viewpoint, illumination, translation, rotation and scale. \end{enumerate} \begin{center} \includegraphics[]{images/DoG space scales.png} \end{center} \subsection{Scale-space peak Selection} The initial image is repeatedly convolved with Gaussians with different values of $\sigma$ to produce a set of scale-space images. Adjacent Gaussian images are subtracted to produce the difference of Gaussian images. These $DoG$ images contain the details of the original image at different scales\footnote{look at the Sharpening filter and derivative of Gaussian sections}. This procedure creates the first \textbf{ octave of scale-space}. In order to find a good approximation of the Laplacian of Gaussian, this process is repeated multiple times and after each octave the Gaussian image is down-sampled by a factor of 2 (each octave’s image size is half the previous one). \begin{center} \includegraphics[scale = 0.9]{images/SIFT octaves.png} \end{center} Maxima and minima of the $DoG$ images are detected by comparing a pixel to its 26 neighbors in 3x3 regions at the current and adjacent scales (previous and next scales with respect to the current). A key-point is selected only if it is larger, in term of intensity, than all of these neighbors or smaller than all of them. \begin{center} \includegraphics[]{images/SIFT DoG space.png} \end{center} Thanks to this, the local features detected are more robust also to some transformations across scales. \subsection{Orientation assignment} \label{subsection:orientation} After the detection process we already know the scale at which each key-point was detected (parameter $\sigma$), so we have scale \textit{invariance}. By assigning a consistent orientation to each key-point based on local image properties, the key-point descriptor can be represented relative to this orientation and therefore achieve invariance to image rotation.\newline\newline An orientation histogram is formed from the gradient orientations of sample points within a region around the key-point (using the scale of the key-point to select the level of Gaussian blur for the image). The orientation histogram covers the 360 degree range of orientations. Each sample point added to the histogram is weighted by its gradient magnitude and by a Gaussian-weighted circular window. The highest peak in the histogram is selected as the dominant direction of the key-point and then any other local peak that is within 80\% of the highest peak is used to also create a key-point with that orientation. Therefore, for locations with multiple peaks of similar magnitude, there will be multiple key-points created at the same location and scale but different orientations. \subsection{Key-point descriptor} At this point, each key-point has a location, scale and orientation. The next step is to compute a descriptor for the local image region. To do this, a $16 \times 16$ window around the key-point is taken and it is divided into 16 sub-blocks of $4 \times 4$ size \footnote{The size of the window can be modified, $16 \times 16$ is the standard SIFT }. For each sub-block, an 8 bin orientation histogram is created following the procedure mentioned before (\ref{subsection:orientation}). Therefore, a descriptor will be a $4 \times 4 \times 8 = 128$ element feature vector. \begin{center} \includegraphics[scale = 0.7]{images/sift descriptor.png} \end{center} The feature vector uses gradient orientations, but if you rotate the image, these orientations change. So, in order to achieve orientation invariance, the coordinates of the descriptor and the gradient orientations are rotated relative to the key-point orientation. \subsection{Key-points matching} A comparative evaluation of different scale invariant key-points detectors can be done by using the repeatability rate. It is defined as the ratio between the number of point-to-point correspondences that can be established for detected points and the number of all possible correspondences. \begin{center} \includegraphics[scale = 1.3]{images/repeatability rate.png} \end{center} But how can we match key-points? One way to do it is by computing, for each descriptor in the first image, the Euclidean distance between this descriptor and all the descriptors of the second image and select the one with minimum distance. A more robust method can be, instead of looking only for the minimum distance, compute the ratio between the first two closest distances. If it is greater that 0.8, the match is rejected. \begin{center} \includegraphics[]{images/ratio closest distances.png} \end{center} Now we can describe a pipeline to perform features matching: \begin{enumerate} \item Detect key-points \item Build key-points descriptors \item Match key-point features \item Align images \end{enumerate}
<!DOCTYPE html> <html> <head> <title>Teste vue</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta charset="utf-8"> </head> <body> <div id="container-fluid"> <div id="app"> <div class="row col-md-12"> <table class="table table-dark table-bordered table-hover"> <tr> <th>Moeda</th> <th>Valor</th> <th>Ultima Consulta</th> </tr> <tr> <td>Dolar</td><td>{{dolar}}</td><td>{{Cdolar}}</td> </tr> <tr> <td>Euro:</td><td>{{euro}}</td><td>{{Ceuro}}</td> </tr> <tr> <td>Bitcoin:</td><td>{{bitcoin}}</td><td>{{Cbitcoin}}</td> </tr> <tr> <td>Peso Argentino:</td><td>{{ars}}</td><td>{{Cpeso_argentino}}</td> </tr> <tr> <td>Libra esterlina</td><td>{{gbp}}</td><td>{{Clibra_esterlina}}</td> </tr> </table> </div><!--Linha--> </div><!--App--> </div><!--Container--> <script type="text/javascript"> function httpGet(theUrl){ var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", theUrl, false ); xmlHttp.send( null ); return xmlHttp.responseText; } var jsontext = httpGet(" https://api.promasters.net.br/cotacao/v1/valores"); var contact = JSON.parse(jsontext); var valores = contact; var status = (valores.status); function ultima_consulta(tempo){ var date = new Date(tempo*1000); // converte para data var dado = date.toLocaleDateString("pt-BR"); //formata de acordo com o requisito return dado; } var app = new Vue({ el:"#app", data:{ dolar:contact.valores.USD.valor, euro:contact.valores.EUR.valor, bitcoin:contact.valores.BTC.valor, ars:contact.valores.ARS.valor, gbp:contact.valores.GBP.valor, Cdolar:ultima_consulta(contact.valores.USD.ultima_consulta), Ceuro:ultima_consulta(contact.valores.EUR.ultima_consulta), Cbitcoin:ultima_consulta(contact.valores.BTC.ultima_consulta), Cpeso_argentino:ultima_consulta(contact.valores.ARS.ultima_consulta), Clibra_esterlina:ultima_consulta(contact.valores.GBP.ultima_consulta) } }) </script> </div> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>반복문 for</title> </head> <body> *** for test ***<br> <script type="text/javascript"> // *누적 k = 1; k = k + 1; k += 1; //k-=2, k*=2, k/=2, (속도가 빠름/ 권장) ++k; //전위 증가 연산자 --k; k++; //후위 증가 연산자 k--; (선호) document.write("k는 " + k + "<br>"); for (var a = 1; a <= 5; a++){ //초기, 목적, 증가(*누적) document.write("a는 " + a + " "); document.write("안녕 "); // a = 7; for 조건에 변수 값은 증가치에 의해서만 변화시켜라 } document.write("<br>for 탈출 후 a는 " + a); document.write("<br>"); for(a = 5; a >= 1; a--){ document.write("a는 " + a + " "); } document.write("<br>for 탈출 후 a는 " + a); document.write("<br>"); for(a = 3; a <= 10; a += 2){ document.write("a는 " + a + " "); } document.write("<br>for 탈출 후 a는 " + a); document.write("<br>"); var m = 1.5; n = 5.5; for(a = m + 1; a <= n + 1; a += 0.5){ document.write("a는 " + a + " "); } document.write("<br>for 탈출 후 a는 " + a); document.write("<br><br>"); //다중 for for(i = 1; i <= 3; i++){ // 1싸이클 i : 1회 j : 4회 document.write("<b>i:" + i + "</b>&nbsp;&nbsp;"); for(j = 1; j <= 4; j++){ document.write("j:" + j + "&nbsp;&nbsp;"); } document.write("<br>") } document.write("<br><br>"); hap = 0; // 중요********** 누적 기억장소는 초기화하자 for(su = 1; su <= 10; su++){ //hap = 0; for문 안이므로 싸이클 돌때마다 초기화로 결국 값은 10이 됨 document.write(su + " "); hap += su; } document.write("<br>합은 " + hap); // 문제) 키보드로 부터 숫자를 받아 1부터 해당 숫자까지의 합을 출력 // 숫자는 2이상의 양의 정수만 입력한다. //문제2) 1 ~ 100 사이의 숫자 중 3의 배수의 합과 갯수 출력 //문제3) 1 ~ 100 사이의 숫자 중 2의 배수이나 5의 배수가 아닌 수의 합과 갯수 출력 // 문제) 키보드로 부터 숫자를 받아 1부터 해당 숫자까지의 합을 출력 // 숫자는 2이상의 양의 정수만 입력한다. document.write("<hr>") document.write("<br>"); var pa = prompt('2 이상 양의 정수를 입력하세요'); s = 0; for(a = 1; a <= pa; a++){ s += a } document.write("<br>합은 " + s); //문제2) 1 ~ 100 사이의 숫자 중 3의 배수의 합과 갯수 출력 document.write("<br>"); sum = 0; var i=0; for(var m = 1; m <= 100; m++){ if(m%3===0){ sum+=m; i++} } document.write("<br>"+sum+"갯수"+i); //문제3) 1 ~ 100 사이의 숫자 중 2의 배수이나 5의 배수가 아닌 수의 합과 갯수 출력 document.write("<br>"); su = 0; pu = 0; for (var m = 1; m <= 100; m++){ if((m%2===0)&&(m%5!=0)){ su+=m; pu++ } } document.write("<br>"+su+"갯수"+pu); </script> </body> </html>
import { createReducer, on } from '@ngrx/store'; import { AuthState } from "../../../models/auth/auth.models"; import * as AuthActions from './auth.actions'; export const initialState: AuthState = { user: null, token: null, loaded: false, isAuthenticated: false, errors: null }; export const authReducer = createReducer( initialState, on(AuthActions.login, state => ({ ...state, loaded: false, isAuthenticated: false })), on(AuthActions.loginSuccess, (state, { user, token }) => ({ ...state, user, token, isAuthenticated: true, loaded: true })), on(AuthActions.loginFailure, (state, { error }) => ({ ...state, isAuthenticated: false, errors: error, loaded: true })), on(AuthActions.logout, state => initialState) );
import React, {useEffect} from 'react'; import {Col, Container, Row} from "react-bootstrap"; import moment from "moment/moment.js"; import "moment/locale/bn.js" import banglaTarikh from "bangla-tarikh"; import {useDispatch, useSelector} from "react-redux"; import {getAllBreakingNew} from "../../../features/BreakingNews/BreakingNewsSlice.js"; import {Link, NavLink} from "react-router-dom"; import Marquee from "react-fast-marquee"; function Index(props) { const {isLoading, breakingNews, errorMessage} = useSelector(state => state.breakingNews) const dispatch = useDispatch() useEffect(() => { dispatch(getAllBreakingNew()) }, []) return ( <section className="breaking pt-25 pb-25"> <Container> <Row> <Col xl={12}> <div className="breaking__meta mb-30"> <ul> <li><i className="fas fa-calendar-alt"></i> <span>{moment().format('LL')}</span></li> <li><i className="fas fa-calendar-alt"></i> <span>{banglaTarikh.format('DTS MMMM, YYYYT')}</span></li> <li><i className="fas fa-clock"></i> <span>{moment().format('LT')}</span></li> </ul> </div> </Col> </Row> <Row> <Col> <div className="breaking__wrapper"> <h5 className="breaking__title ">তাজা খবর</h5> <Marquee direction="Left" speed={60} pauseOnHover style={{display: "flex", justifyContent: "center", alignItems: 'center'}} > {breakingNews && breakingNews.map(brn => { return ( <p key={brn.id} style={{padding:"10px 0", margin:"0"}}> <Link to={`/article/${brn.slug}`}> &nbsp;&nbsp;&nbsp;&nbsp; <i className="fas fa-star text-warning"></i> &nbsp;&nbsp;&nbsp;&nbsp; {brn.title} </Link> </p> ) })} </Marquee> {/*{!isLoading && <ul className="breaking__ticker-active owl-carousel">*/} {/* {breakingNews && breakingNews.map(brn=><li key={brn.id}>*/} {/* <NavLink to={/article/${brn.slug}}>{brn.title}</NavLink>*/} {/* </li>)}*/} {/*</ul>}*/} </div> </Col> </Row> </Container> </section> ); } export default Index;
from turtle import Screen,Turtle import time import food as food from score import ScoreBoard from wall_tail import WallTail import snake screen = Screen() screen.bgcolor("black") screen.setup(width=600,height=600) screen.title("Classic Snake Game") screen.tracer(0) snake = snake.Snake() food = food.Food() score_board = ScoreBoard() wall = WallTail() screen.listen() screen.onkey(snake.up,"Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left,"Left") screen.onkey(snake.right,"Right") game_on = True while game_on: screen.update() time.sleep(0.05) snake.snake_movement() # detecting collision if snake.head.distance(food)<15: food.refresh() score_board.increase_score() snake.snake_growth() # collision with wall if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: score_board.high_score_update() score_board.score_refresh() snake.reset() # collision with tail for segment in snake.segments: if segment == snake.head: pass elif snake.head.distance(segment) <10: score_board.high_score_update() score_board.score_refresh() snake.reset() screen.exitonclick()
Implements specialized logic for visual-selecting Rust code syntax tree nodes stopping by at more places than any language-agnostic plugin can. Why would want to do that? It speeds up frequent editing scenarios by requiring fewer steps to select the interesting bits. It lifts your editing routines up a semantic level from "visually select this word and the trailing comma" to "visually select this function argument". [nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter#incremental-selection) | this plugin :--------------:|:-------------------------: ![nvim-treesitter](https://raw.githubusercontent.com/adaszko/tree_climber_rust.nvim/demo/demo/treesitter.gif) | ![tree_climber_rust](https://raw.githubusercontent.com/adaszko/tree_climber_rust.nvim/demo/demo/tree_climber_rust.gif) The demo illustrates selecting a tuple element but that's not all the pluging offers. Analogous selection behavior also works for any comma-separated syntax element, e.g. `vec![1, 2, 3]`, `<A, B, C>`, `f(1, 2, 3)`, function parameters, etc. # Setup Instruct your favorite Neovim package manager to clone `adaszko/tree_climber_rust.nvim` from GitHub and then hook it up to [rustaceanvim](https://github.com/mrcjkb/rustaceanvim) (which you should be using if you aren't already): ```lua vim.g.rustaceanvim = { server = { on_attach = function(client, bufnr) local opts = { noremap=true, silent=true } vim.api.nvim_buf_set_keymap(bufnr, 'n', 's', '<cmd>lua require("tree_climber_rust").init_selection()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'x', 's', '<cmd>lua require("tree_climber_rust").select_incremental()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'x', 'S', '<cmd>lua require("tree_climber_rust").select_previous()<CR>', opts) end, }, } ``` # Prior work All of these below work well but do more coarse-grained jumps due to being language-agnostic and relying on tree-sitter grammars to define jump points. * [tree-sitter's builtin incremental selection](https://github.com/nvim-treesitter/nvim-treesitter#incremental-selection) * [syntax-tree-surfer](https://github.com/ziontee113/syntax-tree-surfer) implements walking the syntax tree in all directions whereas this pluging only does walking upwards to keep cognitive load low while maximizing utility at the same time * [Helix's builtin `expand_selection`, `shrink_selection`, `select_prev_sibling`, `select_next_sibling`](https://docs.helix-editor.com/keymap.html) * Demo: [Navigating the syntax tree with helix](https://www.youtube.com/watch?v=8BikrCguI6M) * An alternative way to achieve similarish effects would be to define custom text objects via [nvim-treesitter-textobjects](https://github.com/nvim-treesitter/nvim-treesitter-textobjects#text-objects-select) custom [treesitter queries](https://github.com/nvim-treesitter/nvim-treesitter-textobjects/blob/23b820146956b3b681c19e10d3a8bc0cbd9a1d4c/queries/rust/textobjects.scm).
package controllers import ( "encoding/json" "net/http" "github.com/gorilla/mux" "github.com/ivinayakg/hypergroai_assignment/helpers" "github.com/ivinayakg/hypergroai_assignment/middleware" "github.com/ivinayakg/hypergroai_assignment/models" "go.mongodb.org/mongo-driver/bson" ) type AddFavouriteRequestBody struct { StockCode string `json:"stockCode"` } func AddFavourite(w http.ResponseWriter, r *http.Request) { var body AddFavouriteRequestBody err := json.NewDecoder(r.Body).Decode(&body) if err != nil { helpers.SendJSONError(&w, http.StatusBadRequest, err.Error()) return } user := r.Context().Value(middleware.UserAuthKey).(*models.User) res, err := models.AddFavourite(user.ID.Hex(), body.StockCode) if err != nil { helpers.SendJSONError(&w, http.StatusBadRequest, err.Error()) return } helpers.SetHeaders("POST", &w, http.StatusCreated) json.NewEncoder(w).Encode(bson.M{"message": "success", "data": res}) } func RemoveFavourite(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) stockCode := vars["code"] user := r.Context().Value(middleware.UserAuthKey).(*models.User) res, err := models.RemoveFavourite(user.ID.Hex(), stockCode) if err != nil { helpers.SendJSONError(&w, http.StatusBadRequest, err.Error()) return } helpers.SetHeaders("DELETE", &w, http.StatusAccepted) json.NewEncoder(w).Encode(bson.M{"message": "success", "data": res}) } func GetUserFavourite(w http.ResponseWriter, r *http.Request) { user := r.Context().Value(middleware.UserAuthKey).(*models.User) res, err := models.GetFavouriteStocks(user.ID.Hex()) if err != nil { helpers.SendJSONError(&w, http.StatusBadRequest, err.Error()) return } helpers.SetHeaders("GET", &w, http.StatusOK) json.NewEncoder(w).Encode(bson.M{"message": "success", "data": res}) } func GetUserFavouriteCodes(w http.ResponseWriter, r *http.Request) { user := r.Context().Value(middleware.UserAuthKey).(*models.User) res, err := models.GetFavouriteStocks(user.ID.Hex()) if err != nil { helpers.SendJSONError(&w, http.StatusBadRequest, err.Error()) return } results := []string{} for _, entry := range res { results = append(results, entry.StockCode) } helpers.SetHeaders("GET", &w, http.StatusOK) json.NewEncoder(w).Encode(bson.M{"message": "success", "data": results}) }
@APIRegression @BeforeAPI @AfterAPI Feature: Reqres API validation Scenario: Verify create users POST API /api/users When [POST] create users API is called to create users Then [POST] API should return response code 201 Scenario Outline: Json schema validation check for API /api/users When [POST] create users API is called to create users with request name "<name>" and job "<job>" Then [POST] validate the json schema of the response "<schemaFile>" Examples: | name | job | schemaFile | | Yunus | QA | src/test/resources/schemas/createUsersJsonsShema.json | Scenario: Verify get users list GET API /api/users?page=2 When [GET] users API is called to get the details of users Then [GET] API should return response code 200 * users api response should not be empty * users api response should contain the first name "Michael" * users api response should match the schema "src/test/resources/schemas/getUsers.json" Scenario Outline: Verify register users POST API /api/register When [POST] register users API is called to register the users with username "<username>" and password "<password>" Then [POST] auth token should be returned in response Then auth token is shared is other flow Examples: | username | password | | eve.holt@reqres.in | pistol |
import 'package:clean_arch_omran/core/utilities/theme.dart'; import 'package:clean_arch_omran/features/posts/presentation/bloc/posts_bloc/posts_bloc.dart'; import 'package:clean_arch_omran/features/posts/presentation/bloc/posts_crud_bloc/posts_crud_bloc.dart'; import 'package:clean_arch_omran/features/posts/presentation/pages/all_posts_page.dart'; import 'package:flutter/material.dart'; import 'package:clean_arch_omran/injection_container.dart' as di; import 'package:flutter_bloc/flutter_bloc.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await di.init(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider(create: (context) => di.sl<PostsBloc>()..add(GetPostsEvent())), BlocProvider(create: (context) => di.sl<PostsCrudBloc>()), ], child: MaterialApp( title: 'Flutter Demo', theme: ThemeHelper.darkTheme /* ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), */ , home: const AllPostsPage(), ), ); } }
let trucoDeck = []; // maso o baraja const suits = ["swords", "coins", "cups", "clubs"]; // suits === palos const ranks = ["1", "2", "3", "4", "5", "6", "7", "10", "11", "12"]; // rank === tipo de carta let playerHands = []; // mano final de cada player function createTrucoDeck() { for (let suit of suits) { for (let rank of ranks) { trucoDeck.push({ rank: rank, suit: suit }); } } } function shuffleTrucoDeck() { for (let i = trucoDeck.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * i + 1); [trucoDeck[i], trucoDeck[j]] = [trucoDeck[j], trucoDeck[i]]; } } function dealCards(numPlayers) { for (let i = 0; i < numPlayers; i++) { const hand = []; for (let j = 0; j < 3; j++) { hand.push(trucoDeck.pop()); } playerHands.push(hand); } } createTrucoDeck(); // creamos el maso completo shuffleTrucoDeck(); // barajando cartas /* **************************************************** */ // Probando mi juego antes de mostrarlo... /* console.log("modalidad 1 vs 1:"); dealCards(2); console.log("Player 1's hand:", playerHands[0]); console.log("Player 2's hand:", playerHands[1]); */ /* **************************************************** */ // Solicitamos al usuario/cliente el tipo de juego a través de mi INPUT const numPlayers = parseInt( prompt(`Elija jugadores:\n(2) 1 vs 1\n(4) 2 vs 2\n(6) 3 vs 3`) ); // 1er OUTPUT switch (numPlayers) { case 2: alert("Player 1 es team 1 y Player 2 es team 2"); dealCards(numPlayers); break; case 4: alert("Player 1 y Player 3 son team 1 / Player 2 y Player 4 son team 2"); dealCards(numPlayers); break; case 6: alert( "Player 1, Player 3 y Player 5 son team 1 / Player 2, Player 4 y Player 6 son team 2" ); dealCards(numPlayers); break; default: alert( "Número de jugadores no válido. Por favor, elige 2, 4 o 6 jugadores." ); break; } // 2do OUTPUT let msg = ""; for (let i = 0; i < numPlayers; i++) { msg += `Player ${i + 1}'s hand: `; for (let card of playerHands[i]) { msg += `[${card.rank} of ${card.suit}], `; } msg = msg.slice(0, -2); // Eliminando la coma y el espacio final msg += "\n"; } alert(msg);
// $Id$ // // SuperTux // Copyright (C) 2006 Matthias Braun <matze@braunis.de> // // 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. #include <config.h> #include "badguy.hpp" #include "object/camera.hpp" #include "object/tilemap.hpp" #include "tile.hpp" #include "statistics.hpp" #include "game_session.hpp" #include "log.hpp" #include "level.hpp" static const float SQUISH_TIME = 2; static const float X_OFFSCREEN_DISTANCE = 1600; static const float Y_OFFSCREEN_DISTANCE = 1200; BadGuy::BadGuy() : countMe(true), sprite(0), dir(LEFT), state(STATE_INIT) { set_group(COLGROUP_DISABLED); } BadGuy::~BadGuy() { delete sprite; } void BadGuy::draw(DrawingContext& context) { if(!sprite) return; if(state == STATE_INIT || state == STATE_INACTIVE) return; if(state == STATE_FALLING) { DrawingEffect old_effect = context.get_drawing_effect(); context.set_drawing_effect((DrawingEffect) (old_effect | VERTICAL_FLIP)); sprite->draw(context, get_pos(), LAYER_OBJECTS); context.set_drawing_effect(old_effect); } else { sprite->draw(context, get_pos(), LAYER_OBJECTS); } } void BadGuy::update(float elapsed_time) { if(!Sector::current()->inside(bbox)) { remove_me(); return; } if(is_offscreen()) { set_state(STATE_INACTIVE); } switch(state) { case STATE_ACTIVE: active_update(elapsed_time); break; case STATE_INIT: case STATE_INACTIVE: inactive_update(elapsed_time); try_activate(); break; case STATE_SQUISHED: if(state_timer.check()) { remove_me(); break; } movement = physic.get_movement(elapsed_time); break; case STATE_FALLING: movement = physic.get_movement(elapsed_time); break; } } void BadGuy::activate() { } void BadGuy::deactivate() { } void BadGuy::save(lisp::Writer& ) { log_warning << "tried to write out a generic badguy" << std::endl; } void BadGuy::active_update(float elapsed_time) { movement = physic.get_movement(elapsed_time); } void BadGuy::inactive_update(float ) { } void BadGuy::collision_tile(uint32_t tile_attributes) { if(tile_attributes & Tile::HURTS) kill_fall(); } HitResponse BadGuy::collision(GameObject& other, const CollisionHit& hit) { switch(state) { case STATE_INIT: case STATE_INACTIVE: return ABORT_MOVE; case STATE_ACTIVE: { if(other.get_flags() & FLAG_SOLID) return collision_solid(other, hit); BadGuy* badguy = dynamic_cast<BadGuy*> (&other); if(badguy && badguy->state == STATE_ACTIVE) return collision_badguy(*badguy, hit); Player* player = dynamic_cast<Player*> (&other); if(player) return collision_player(*player, hit); return FORCE_MOVE; } case STATE_SQUISHED: if(other.get_flags() & FLAG_SOLID) return CONTINUE; return FORCE_MOVE; case STATE_FALLING: return FORCE_MOVE; } return ABORT_MOVE; } HitResponse BadGuy::collision_solid(GameObject& , const CollisionHit& ) { return FORCE_MOVE; } HitResponse BadGuy::collision_player(Player& player, const CollisionHit& ) { if(player.is_invincible()) { kill_fall(); return ABORT_MOVE; } /* printf("PlayerHit: GT %3.1f PM: %3.1f %3.1f BM: %3.1f %3.1f Hit: %3.1f %3.1f\n", game_time, player.get_movement().x, player.get_movement().y, get_movement().x, get_movement().y, hit.normal.x, hit.normal.y); */ // hit from above? if(player.get_movement().y /*- get_movement().y*/ > 0 && player.get_bbox().p2.y < (get_bbox().p1.y + get_bbox().p2.y) / 2) { // if it's not possible to squish us, then this will hurt if(collision_squished(player)) return ABORT_MOVE; } player.kill(Player::SHRINK); return FORCE_MOVE; } HitResponse BadGuy::collision_badguy(BadGuy& , const CollisionHit& ) { return FORCE_MOVE; } bool BadGuy::collision_squished(Player& ) { return false; } void BadGuy::kill_squished(Player& player) { sound_manager->play("sounds/squish.wav", get_pos()); physic.enable_gravity(true); physic.set_velocity_x(0); physic.set_velocity_y(0); set_state(STATE_SQUISHED); set_group(COLGROUP_MOVING_ONLY_STATIC); if (countMe) Sector::current()->get_level()->stats.badguys++; player.bounce(*this); } void BadGuy::kill_fall() { sound_manager->play("sounds/fall.wav", get_pos()); if (countMe) Sector::current()->get_level()->stats.badguys++; physic.set_velocity_y(0); physic.enable_gravity(true); set_state(STATE_FALLING); } void BadGuy::set_state(State state) { if(this->state == state) return; State laststate = this->state; this->state = state; switch(state) { case STATE_SQUISHED: state_timer.start(SQUISH_TIME); break; case STATE_ACTIVE: set_group(COLGROUP_MOVING); bbox.set_pos(start_position); break; case STATE_INACTIVE: // was the badguy dead anyway? if(laststate == STATE_SQUISHED || laststate == STATE_FALLING) { remove_me(); } set_group(COLGROUP_DISABLED); break; case STATE_FALLING: set_group(COLGROUP_DISABLED); break; default: break; } } bool BadGuy::is_offscreen() { float scroll_x = Sector::current()->camera->get_translation().x; float scroll_y = Sector::current()->camera->get_translation().y; if(bbox.p2.x < scroll_x - X_OFFSCREEN_DISTANCE || bbox.p1.x > scroll_x + X_OFFSCREEN_DISTANCE || bbox.p2.y < scroll_y - Y_OFFSCREEN_DISTANCE || bbox.p1.y > scroll_y + Y_OFFSCREEN_DISTANCE) return true; return false; } void BadGuy::try_activate() { float scroll_x = Sector::current()->camera->get_translation().x; float scroll_y = Sector::current()->camera->get_translation().y; /* Activate badguys if they're just around the screen to avoid * the effect of having badguys suddenly popping up from nowhere. */ if (start_position.x > scroll_x - X_OFFSCREEN_DISTANCE && start_position.x < scroll_x - bbox.get_width() && start_position.y > scroll_y - Y_OFFSCREEN_DISTANCE && start_position.y < scroll_y + Y_OFFSCREEN_DISTANCE) { dir = RIGHT; set_state(STATE_ACTIVE); activate(); } else if (start_position.x > scroll_x && start_position.x < scroll_x + X_OFFSCREEN_DISTANCE && start_position.y > scroll_y - Y_OFFSCREEN_DISTANCE && start_position.y < scroll_y + Y_OFFSCREEN_DISTANCE) { dir = LEFT; set_state(STATE_ACTIVE); activate(); } else if (start_position.x > scroll_x - X_OFFSCREEN_DISTANCE && start_position.x < scroll_x + X_OFFSCREEN_DISTANCE && ((start_position.y > scroll_y && start_position.y < scroll_y + Y_OFFSCREEN_DISTANCE) || (start_position.y > scroll_y - Y_OFFSCREEN_DISTANCE && start_position.y < scroll_y))) { dir = start_position.x < scroll_x ? RIGHT : LEFT; set_state(STATE_ACTIVE); activate(); } else if(state == STATE_INIT && start_position.x > scroll_x - X_OFFSCREEN_DISTANCE && start_position.x < scroll_x + X_OFFSCREEN_DISTANCE && start_position.y > scroll_y - Y_OFFSCREEN_DISTANCE && start_position.y < scroll_y + Y_OFFSCREEN_DISTANCE) { dir = LEFT; set_state(STATE_ACTIVE); activate(); } } bool BadGuy::might_fall(int height) { // make sure we check for at least a 1-pixel fall assert(height > 0); float x1; float x2; float y1 = bbox.p2.y + 1; float y2 = bbox.p2.y + 1 + height; if (dir == LEFT) { x1 = bbox.p1.x - 1; x2 = bbox.p1.x - 1; } else { x1 = bbox.p2.x + 1; x2 = bbox.p2.x + 1; } return Sector::current()->is_free_space(Rect(x1, y1, x2, y2)); } Player* BadGuy::get_nearest_player() { // FIXME: does not really return nearest player std::vector<Player*> players = Sector::current()->get_players(); for (std::vector<Player*>::iterator playerIter = players.begin(); playerIter != players.end(); ++playerIter) { Player* player = *playerIter; return player; } return 0; }
<?php session_start(); include("../user_register/connection.php"); // Check if the professor_id exists in the session if (isset($_SESSION['professor_id'])) { $professor_id = $_SESSION['professor_id']; } else { header("Location: http://localhost/testovi/project/professor_index.php"); exit; // Terminate script execution } // Check if the form is submitted if (isset($_POST['submit'])) { // Retrieve form data $title = $_POST['title']; $skill_description = $_POST['skill_description']; $category = $_POST['category']; // File upload handling $image = $_FILES['image']; $image_name = $image['name']; $image_tmp_name = $image['tmp_name']; $image_size = $image['size']; $image_error = $image['error']; // Check if file is uploaded without errors if ($image_error === 0) { // Generate a unique name for the image to avoid conflicts $image_new_name = uniqid('', true) . '.' . strtolower(pathinfo($image_name, PATHINFO_EXTENSION)); // Define the directory where the image will be stored $image_destination = '../uploads/' . $image_new_name; // Move the uploaded file to the destination directory if (move_uploaded_file($image_tmp_name, $image_destination)) { // Insert skill into the database $insert_skill_query = "INSERT INTO skills (professor_id, title, image, description, category) VALUES (?, ?, ?, ?, ?)"; $insert_stmt = $con->prepare($insert_skill_query); if ($insert_stmt) { $insert_stmt->bind_param("issss", $professor_id, $title, $image_new_name, $skill_description, $category); if ($insert_stmt->execute()) { echo "Skill added successfully"; } else { echo "Error adding skill: " . $insert_stmt->error; } } else { echo "Error preparing SQL statement: " . $con->error; } $insert_stmt->close(); } else { echo "Error uploading image"; } } else { echo "Error uploading file: " . $image_error; } } ?> <!DOCTYPE html> <html> <head> <title>Add Skill</title> <!-- Include jQuery and jQuery UI library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <!-- Include jQuery UI CSS for styling --> <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> </head> <body> <a href="../professor_index.php">Back to Dashboard</a> <h1>Add Skill</h1> <form method="post" enctype="multipart/form-data"> <label for="title">Title:</label> <input type="text" name="title" required><br><br> <label for="image">Image:</label> <input type="file" name="image" accept="image/*" required><br><br> <label for="skill_description">Skill Description:</label><br> <textarea name="skill_description" rows="4" cols="50" required></textarea><br><br> <label for="category">Category:</label> <!-- Replace the text input with an autocomplete combobox --> <input type="text" id="category" name="category" required><br><br> <button type="submit" name="submit">Submit</button> </form> <script> $(document).ready(function() { // Define available categories for autocomplete var availableCategories = [ "Programming", "Graphic Design", "Cooking", "Writing", "Photography", "Public Speaking", "Playing a Musical Instrument", "Video Editing", "Data Analysis", "Gardening", "Dancing", "Carpentry", "Knitting", "Foreign Language Proficiency", "Painting", "Martial Arts", "Digital Marketing", "Singing", "Yoga", "Woodworking", "Acting", "Sewing", "Web Development", "Pottery", "Creative Writing", "Hiking", "Chess", "Meditation", "Interior Design", "Event Planning", "Animation", "Calligraphy", "Sculpting", "Mountain Biking", "Strategic Planning", "Bird Watching", "Home Brewing", "Origami", "Survival Skills", "Baking", "Horseback Riding", "Astronomy", "Drone Flying", "Leatherworking", "Stand-up Comedy", "Archery", "Urban Gardening", "Glassblowing", "App Development", "Fishing", "Makeup Artistry", "Blogging", "Electrical Repair", "Wine Tasting", "Storytelling", "Robotics", "Scuba Diving", "Creative Problem Solving", "DIY Projects", "Brewing", "Cosplay", "Kayaking", "Floral Arrangement", "Journaling", "Public Relations", "Paragliding", "Tarot Reading", "Dog Training", "Sustainable Living", "Wood Carving", "Video Game Design", "Rock Climbing", "Feng Shui", "Crossword Puzzles", "Food Styling", "Geocaching", "Volunteer Work", "Wine Making", "Quilting", "Stand-up Paddleboarding", "Podcasting", "Antique Restoration", "Home Decorating", "Magic Tricks", "Skiing", "Journalism", "Perfume Making", "Aquascaping", "Beekeeping", "Virtual Reality Design", "Mixology", "Parkour", "Political Activism", "Other" ]; // Initialize autocomplete on the category input field $("#category").autocomplete({ source: availableCategories }); }); </script> </body> </html>
package com.example.mytestapplicationforstudyclearcode.data.repository import com.example.mytestapplicationforstudyclearcode.data.storage.models.User import com.example.mytestapplicationforstudyclearcode.data.storage.UserStorage import com.example.mytestapplicationforstudyclearcode.domain.models.SaveUserNameParam import com.example.mytestapplicationforstudyclearcode.domain.models.UserName import com.example.mytestapplicationforstudyclearcode.domain.repository.UserRepository class UserRepositoryImpl(private val userStorage: UserStorage): UserRepository { override fun saveName(saveParam: SaveUserNameParam): Boolean { val user = mapToStorage(saveParam) return userStorage.save(user) } override fun getName(): UserName { val user = userStorage.get() return mapToDomain(user = user) } private fun mapToStorage(saveParam: SaveUserNameParam): User { return User(firstName = saveParam.name, lastName = "") } private fun mapToDomain(user: User): UserName { return UserName(firstName = user.firstName, lastName = user.lastName) } }
import { useCallback, useEffect, useState } from 'react'; import { Breakpoint, Layout } from './types'; const breakpoints: Breakpoint[] = [ { layout: Layout.MOBILE, query: '(max-width: 767px)', matches: false }, { layout: Layout.TABLET, query: '(max-width: 1260px)', matches: false }, { layout: Layout.DESKTOP, query: '(max-width: 1366px)', matches: false }, ]; function getActiveLayout() { const matchedBreakpoints = breakpoints.map((bp) => ({ ...bp, matches: window.matchMedia ? window.matchMedia(bp.query).matches : false, })); const activeLayout = matchedBreakpoints.find((bp) => bp.matches); return activeLayout?.layout || Layout.DESKTOP; } export default function useLayout() { const [layout, setLayout] = useState<Layout>(getActiveLayout); const handleQueryMatch = useCallback(() => { const nextLayout = getActiveLayout(); if (nextLayout !== layout) { setLayout(nextLayout) } }, [layout]); useEffect(() => { if (window.matchMedia) { breakpoints.forEach((bp) => ( window .matchMedia(bp.query) .addEventListener('change', handleQueryMatch) )); } }, [handleQueryMatch]); return layout; }
@extends('layouts.app') @section('content') <div class="row justify-content-center"> <div class="col-12"> @if(session('status')) {!! session('status') !!} @endif <div class="card"> <div class="card-header d-flex"> <a href="{{ url("/video/" . $video->video_id) }}" class="btn btn-sm btn-round"><i class="fas fa-arrow-left"></i></a> <h4>Detil Video {{ $video->nama }}</h4> </div> <div class="card-body"> @if(session('msg')){!! session('msg') !!} @endif <div class="alert alert-success" role="alert"> <h4 class="alert-heading">Cara Pengisian</h4> <p style="font-size: 20px;">Url diisi oleh https://www.youtube.com/watch?v=<strong><span style="font-weight: bold; background-color: red;">ggp18gpPeuo</span></strong>.<br />yang di beri warna merah adalah ID video youtube maka itulah yang dimasukkan ke dalam Url di form ini!</p> </div> <form action="{{ url('/video/' . $video->video_id) }}" method="post" enctype="multipart/form-data">@csrf @method('put') <div class="row"> <div class="col-md-12"> <div class="row mb-3 justify-content-center"> <label for="organisasi_id" class="col-md-4 col-form-label text-md-end">{{ __('Organisasi') }}</label> <div class="col-md-6"> <select name="organisasi_id" id="organisasi_id" class="custom-select @error('organisasi_id') is-invalid @enderror"> <option value="">{{ $video->organisasi()->first()->nama }}</option> </select> @error('organisasi_id') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="row mb-3 justify-content-center"> <label for="nama_video" class="col-md-4 col-form-label text-md-end">{{ __('Nama Video') }}</label> <div class="col-md-6"> <input id="nama_video" type="text" class="form-control @error('nama_video') is-invalid @enderror" name="nama_video" value="{{ $video->nama_video }}" autocomplete="name" autofocus> @error('nama_video') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="row mb-3 justify-content-center"> <label for="url" class="col-md-4 col-form-label text-md-end">{{ __('Url') }}</label> <div class="col-md-6"> <input id="url" type="text" class="form-control @error('url') is-invalid @enderror" name="url" value="{{ $video->url }}" autocomplete="url" autofocus> @error('url') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="row mb-3 justify-content-center"> <label for="status" class="col-md-4 col-form-label text-md-end">{{ __('status') }}</label> <div class="col-md-6"> <select name="status" id="status" class="custom-select @error('status') is-invalid @enderror"> <option value="aktif" {{ $video->status == 'aktif' ? 'selected' : '' }}>Aktif</option> <option value="tidak_aktif" {{ $video->status == 'tidak_aktif' ? 'selected' : '' }}>Tidak Aktif</option> </select> @error('status') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="row mb-3 justify-content-center"> <label for="gambar" class="col-md-4 col-form-label text-md-end">{{ __('Gambar') }}</label> <div class="col-md-6"> <div class="custom-file"> <input type="file" name="gambar" class="custom-file-input" id="gambar"> <label class="custom-file-label" for="gambar">Pilih File</label> </div> @error('gambar') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror <img src="{{ asset('storage/video/' . $video->gambar) }}" alt="{{ $video->nama }}" class="img img-thumbnail img-temporary" style="width: 800px; height: auto"> </div> </div> <div class="row mb-0"> <div class="col-md-6 offset-md-4 d-flex align-items-end"> <a type="button" href="{{ url("/video/" . $video->video_id) }}" class="btn btn-primary mr-2"><i class="fas fa-arrow-left"></i> Kembali</a> <button type="submit" class="btn mr-2 btn-success"><i class="fas fa-pen"></i> Simpan</button> </div> </div> </div> </div> </form> </div> </div> </div> </div> @endsection
In this part of my Django tutorial series we'll focus on Generic Views and Automated Testing. Through testing we can quickly check how are site is operating after each change. You can also simulate how the site will interact with a user depending upon an unlimited number of randomized inputs. With a little work up front you will save yourself from numerous future headaches. # In this lesson we will cover Generic views and Automated Testing. We will start off # in polls/urls.py. First of as usual 'python manage.py runserver' in terminal to start your server. # ---------- /polls/urls.py ---------- # 1 Generic views are normally used from the beginning # and they help you avoid having to write a lot # of custom code. We will fix these generic patterns so we can use generic views. # from django.conf.urls import url # this import has been depricated since django v2, use re_path from django.urls import re_path from . import views app_name = 'polls' # (1 code layout) We'll first change the index urlpattern from 'views.index,' to: # views.IndexView.as_view() # We will also change the detail view, by deleting '<question_id>' and replacing it with: <pk> # Then replace '/detail/$', views.detail,' with: views.DetailView.as_view(), # Then for the results view, replace <question> with <pk> # and replace 'views.results,' with: views.ResultsView.as_view() # We will leave our votes view, exactly the same as it was. urlpatterns = [ # re_path(r'^$', views.index, name='index'), re_path(r'^$', views.IndexView.as_view(), name='index'), # re_path(r'^(?P<question_id>[0-9]+)/detail/$', views.detail, name='detail'), re_path(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), # re_path(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results') re_path(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'), re_path(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] # (1 code layout) Now remove our index, detail and results views in polls/views.py # First we will omit the 'detail' function by commenting it out. # We will leave the vote function, as it is. # We will also comment out the results and index functions. # Now we will have to create them for use with generic views. So next, import module # for generic views: # ---------- /polls/views.py ---------- # (2 code layout) Add the generic module from django.views import generic from django.http import HttpResponse from .models import Question, Choice from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse # (8 code layout) Import so we can get time information from django.utils import timezone # After importing the module for generic views, we will work on a 'class' # to set up our list view: # (2 code layout) The ListView displays your list of questions being, the # latest_question_list class IndexView(generic.ListView): # This points to the address location, of the template we are going to use, for the list: template_name = 'polls/index.html' # (2 code layout)This defines the question list we want to use context_object_name = 'latest_question_list' # 8 Replace get_queryset and don't return questions # published in the future # function, for listing our questions, using Question model by order of date, but only the last 5 def get_queryset(self): # 2 Return the last 5 questions entered return Question.objects.order_by('-pub_date')[:5] # (2 code layout) The DetailView displays the details on your object # being the Question model # The generic view expects the pk (Primary Key) value # from the URL to be called pk as we set in polls/urls.py class DetailView(generic.DetailView): model = Question # Define the path directory of the template to use with this data template_name = 'polls/detail.html' # (2 code layout) Get the results from the questions class ResultsView(generic.DetailView): # define model we will be using for the details model = Question # define the path directory to the template we will use template_name = 'polls/results.html' # (12 code layout) Add tests in polls/tests.py # We could test the code by plugging in variables randomly, and perhaps miss some, # or explore automated testing. # There is a bug in Djangos' 'was_published_recently', where future entries where introduced as # recent entries. That makes no sense in linear time, but the Django coders set this up to show bad # information ahead of time. Instead it post questions in from a future date and not the current date/time. # These questions get listed on the screen as current questions. We will test for this bug and try to fix # them, in terinal, cmd prompt, or PowerShell, using 'shell'. python manage.py shell # First we will import date time, to calculate our current time: import datetime # we will also import timezone module: from django.utils import timezone # also, import 'question' from our models so we can work with that: from polls.models import Question # then to create a question inside of here, and define its publication date, # to some time some time in the future, which will be 30 days in the future: future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30)) # Now we can check the future date function, to see if it is working properly: # We will do that by referencing the question, we just entered, and see if it says # that it was published recently or not: future_question.was_published_recently() OUTPUT: True # It gave us a True which is, incorrect, an error in our system, so we will have to # correct the system by using automated testing. To do this we will have to open up, # test.py and create it there. # To leave shell: quit() # 3 Open the file called tests.py # ---------- /polls/tests.py ---------- # Inside sampsite/polls/test.py add these modules: # This is already inside tests.py from django.test import TestCase # (4 code layout) Import your needed modules; the same ones we just used in shell: import datetime from django.utils import timezone from .models import Question # TestsCase, runs tests without affecting data, by creating a temporary database, # to do our tests with: from django.test import TestCase # (4 code layout) We will create a class to test our Question method: class QuestionMethodTests(TestCase): # Put the code used in the shell here # Start the method name with test def test_was_published_recently_with_future_question(self): # Create a time, 30 days in the future time = timezone.now() + datetime.timedelta(days=30) # Create a question using the future time future_question = Question(pub_date=time) # Check to see if the output is False, pass in .was_published_recently(), we expect False will be the answer. self.assertIs(future_question.was_published_recently(), False) # (4 code layout) We will Run the test in the terminal python manage.py test polls THE LAST LINES OUTPUT- 'FAILED (errors=1)' # see 'cmd log.txt' # You'll see that the test failed # (4 code layout) To Fix the bug in models.py, open the file, find: def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) # comment out, the line that was giving us the error, on the test: #return self.pub_date >= timezone.now() - datetime.timedelta(days=1) # We will replace that line with the current time, and return the current time # calculated by the code : now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now # This return means, things that are published within the last day, are current. # To check this, we will run the same test... 'python manage.py test polls' in terminal. I GOT AN ERROR THAT I CANNOT FIX: " line 369, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'sampsite.polls' " We will continue despite the error, since I have not been able to fix or get help fixing this error... ************** I could not try any of these test ***************** # All these functions need to start off with the word 'test', to work. In the test.py # enter this next test: # (6 code layout) Return false if pub_date is older then 1 day def test_was_published_recently_with_old_question(self): # Should return false if pub_date is older then 1 day time = timezone.now() - datetime.timedelta(days=30) # creat an old question old_question = Question(pub_date=time) # test the old question self.assertIs(old_question.was_published_recently(), False) # In cmd prompt or whatever you are using, enter: python manage.py test polls to initiate this test> # I received the same error: ModuleNotFoundError: No module named 'sampsite.polls' # (6 code layout) Return True if published within the last day def test_was_published_recently_with_recent_question(self): time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) # Test with : python3 manage.py test polls ***************** end of the non working test code area ******************* # We can simulate user interaction at the view level in the shell. # (7 code layout) We can simulate user interaction at the view level in the shell python manage.py shell # This allows us access variable values in our templates # We will be using our real database here from django.test.utils import setup_test_environment setup_test_environment() # import Client module and Create the object client that we'll use to run our app: from django.test import Client client = Client() # Get the status code from localhost:8000/, the root of our site, we call for it with get: response = client.get('/') # now we ask for our status code: response.status_code OUTPUT: 200 # We can do something similar to Get the status code for index in localhost:8000/polls/ # we import reverse to be able to get the namespace, for index in our polls app. directory from django.urls import reverse # Load this into our client: response = client.get(reverse('polls:index')) # get status for the polls app.: response.status_code OUTPUT: 200 # means its good # Get the HTML content for that page: response.content OUTPUT: ' b'<!--if there is a list of latest_question_list then...-->\n\n<!--we will us an unordere d list and a for statement to iterate through the list-->\n <ul>\n \n <! --in list item, questions in latest_question_list as links, using the name space in polls urls.py -->\n <li>\n <!--We get the question from text using What& #x27;s Up?-->\n <a href="/polls/1/">What&#x27;s Up?</a>\n </li> \n \n </ul>\n<!--in case the if statement doesn\'t find a list of latest_questi on_list-->\n\n\n<!---->\n' ' # Get the value of latest_question_list, context allows us to access specific variables inside our template: response.context['latest_question_list'] OUTPUT: <QuerySet [<Question: What's Up?>]> # (7 code layout) Now let's update polls/views.py, so it doesn't show questions published in the future: # first we will import a module that allows us to get our timezone information: from django.utils import timezone # Next we will make some changes in our index view to our get query set function # We will change our get_queryset to only return dates of our current publish date time or less. # We will replace 'return Question.objects.order_by('-pub_date')[:5]', with: def get_queryset(self): return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('pub_date')[:5] # Next we will go to our admin.py file and add Choice as an option, in the admin panel. from .models import Question, Choice # L4 register Choice to show up in admin panel admin.site.register(Choice) # Run sever and go to the admin page to see the results. Under the POLLS field # there should be a Choice option, that can be used, to edit or add choices. # Now lets quit shell 'quit()' # (10 code layout) We will now return to the text.py page and create some more questions. # Create a function that creates questions at a specified date def create_question(question_text, days): # get current time plus whatever day is passed in to this function time = timezone.now() + datetime.timedelta(days=days) # return this question object, with passed in question text using time created above return Question.objects.create(question_text=question_text, pub_date=time) # Add more question tests to our test.py file, using new class QuestionViewTests # for our temporary database, created by the 'TestCase' imported module class QuestionViewTests(TestCase): # 10 Test to see what happens if there are no questions to show def test_index_view_with_no_questions(self): # Get the client for index part of our polls app using namespace response = self.client.get(reverse('polls:index')) # Check the status code, like we did in shell, and we expect 200 back self.assertEqual(response.status_code, 200) # Verify that response contains this string self.assertContains(response, "No polls are available.") # Check if latest_question_list is empty self.assertQuerysetEqual(response.context['latest_question_list'], []) # Make sure questions with a, pub_date in past, are shown def test_index_view_with_a_past_question(self): # Create sample question in our temporary database; negative 30 create_question(question_text="Past question.", days=-30) # Get client, using namespace using reverse, of our index response = self.client.get(reverse('polls:index')) # Verify that the question shows, locking for questions with 'Past question' in them self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) # 10 Make sure questions with future pub_dates, don't show def test_index_view_with_a_future_question(self): # Create question, "Future question." by calling create_question, 30 days in the future create_question(question_text="Future question.", days=30) # Get client, using namespace, using module reverse, in the polls index response = self.client.get(reverse('polls:index')) # Verify response contains text'self.assertContains', "No polls are available." self.assertContains(response, "No polls are available.") # Verify that latest_question_list is empty self.assertQuerysetEqual(response.context['latest_question_list'], []) # Verify that if past and future questions exist that only past is going to show def test_index_view_with_future_question_and_past_question(self): # Create 2 questions using create_question, notice negative 30 for Past question create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) # Get client, using namespace, using reverse for index in polls response = self.client.get(reverse('polls:index')) # Verify that question list only contains the past questions '<Question: Past question.>' self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) # 10 Make sure question list shows multiple questions def test_index_view_with_two_past_questions(self): # Create 2 questions using create_question, notice both are negative create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) # Get client, using namespace, using reverse for index in polls response = self.client.get(reverse('polls:index')) # Verify that both questions show self.assertQuerysetEqual( response.context['latest_question_list'], # we are looking for both questions ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) # (11 code layout) Make sure future questions can't be accessed if the user guesses the URL in polls/views.py # If a user tries hacking the site, in the details section by trying different numbers to get access to details pages # ie http://localhost:8000/admin/auth/user/1/ We will block them from doing this. # We will open views.py and as we did for the get_query function in the IndexView function, # we will do something similar for the DetailView function: # function, for listing our questions, using Question model by order of date, but only the last 5 def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) # Go back to the test.py file to check the changes in our views.py details function. # (13 code layout( Add tests to make sure future posts aren't shown in the detail function # as before we will use TestCase to create a temporary database class QuestionIndexDetailTests(TestCase): # 13 Make sure future question detail pages show 404 def test_detail_view_with_a_future_question(self): # Create question future_question = create_question(question_text='Future question.', days=5) # Open url using the future question in the url url = reverse('polls:detail', args=(future_question.id,)) # Get client response response = self.client.get(url) # Verify that it returns expected 404 self.assertEqual(response.status_code, 404) # Verify that past questions show in detail, as in, be displayed def test_detail_view_with_a_past_question(self): # Create question, past question, its already been created past_question = create_question(question_text='Past Question.', days=-5) # Open url with past question url = reverse('polls:detail', args=(past_question.id,)) # Get response response = self.client.get(url) # Verify the question shows self.assertContains(response, past_question.question_text) ******************** the Lesson stops here ********************** ******************** below is reference for lesson files *************** # ---------- /polls/models.py ---------- from django.db import models import datetime from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): # 5 return self.pub_date >= timezone.now() - datetime.timedelta(days=1) # 5 Fix the code now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now # 5 Now the test will pass # 5 Add further tests to polls/tests.py class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text # ---------- /polls/admin.py ---------- from django.contrib import admin # 9 Add choice to imports from .models import Question, Choice admin.site.register(Question) # 9 Add Choice to the Admin page admin.site.register(Choice) # 9 Create some future questions # 9 Add some tests in polls/tests.py ***************** highlights from the comments area ***************** Hello everyone with the create_question errors, to fix the error copy the create_question method and place it before the classes start(where you import stuff) That should fix the errors if not check for typos Also, you could just remove the indent behind def instead of copying and pasting Didn't understand how you could use "create_question" function from one class in another. The "def create_question" is indented inside the first test class, isn't it? Another thing a would say(but it's not very important) is that you should use 'string {}'.format() instead % format string. Again, this is not very important but it's python and it's elegant. Nice tutorial Derek, thanks a lot. I moved create_question into the scope of the file so it can be used. Also I think he forgot to import reverse so you will need to do that too. Should work after that. Probably too late for you but may help someone else for those using path instead of url in urlpatterns should add "pk_url_kwarg = 'question_id' " to DetailView and ResultView class in views.py How can a deploy the local django project to a production server and can join many different apps like poll into one site? Thanks for your videos, they are very helpful. git it best for web deployment, in my opinion. I simply run my web app on my local machine where i develop from, gitignore the sensitive data like my settings.py and local_settings.py, then push any commits to git where i can then pull them on my remote server to ensure the easiest, reliable insurance that any tests or code i write on my local machine will accurately reflect the live version. After pulling - assuming you're using apache on a linux machine - simply run /etc/init.d/apache2 restart or service apache2 restart to apply the changes. Hope that helps!
import './App.css'; import SignUp from './Pages/SignUp'; import SignIn from './Pages/SignIn'; import Hero from './Pages/Hero'; import { Routes, Route } from "react-router-dom"; import Mentors from './Pages/Mentors'; import Profile from './Pages/Profile'; import Verification from './Pages/Verification'; import ProtectedPages from './components/protected/ProtectedPages'; import CallRoom from './Pages/CallRoom'; import HomeHeader from './components/HomeHeader'; import Footer from './components/Footer'; import Meeting from './Pages/Meeting'; import OSProject from './Pages/OSProject'; import Blogs from './Pages/Blogs'; import Blog from './Pages/Blog'; import StudentsRequest from './Pages/StudentsRequest'; import CreateBlog from './Pages/CreateBlog'; import { ToastContainer } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; function App() { return ( <div className="App"> <HomeHeader /> <ToastContainer /> <Routes> <Route path="/" element={<Hero />} /> <Route path="/signIn" element={<SignIn />} /> <Route path="/signUp" element={<SignUp />} /> <Route path="/profile" element={<ProtectedPages Component={<Profile />} />} /> <Route path="/verification" element={<Verification />} /> <Route path="mentors/" element={<ProtectedPages Component={<Mentors />} />} /> <Route path="/meeting" element={<ProtectedPages Component={<Meeting />} />} /> <Route path="/student-request" element={<ProtectedPages Component={<StudentsRequest />} />} /> <Route path="/call-room" element={<ProtectedPages Component={<CallRoom />} />} /> <Route path="/open-source" element={<OSProject />} /> <Route path="/blogs" element={<Blogs />} /> <Route path="/blog/:blogId" element={<Blog/>}/> <Route path='/create-blog' element={<ProtectedPages Component={<CreateBlog />} />} /> </Routes> <Footer /> </div> ); } export default App;
class Basic_Controller extends Game_Component { float speed; Basic_Controller() { super("Basic_Controller"); speed = 0.1; } Basic_Controller(JSONObject j) { super("Basic_Controller"); speed = j.getFloat("speed"); } void update() { if (kb.keyDown(37) || kb.keyDown(65)) { parent.vx -= speed; } if (kb.keyDown(39) || kb.keyDown(68)) { parent.vx += speed; } if (kb.keyDown(38) || kb.keyDown(87)) { parent.vy -= speed; } if (kb.keyDown(40) || kb.keyDown(83)) { parent.vy += speed; } } JSONObject saveJSON() { JSONObject j = super.saveJSON(); j.setFloat("speed", speed); return j; } } class Eblock_Controller extends Basic_Controller { float jumpHeight; Physics_Body body; Eblock_Controller() { super(); this.clss = "Eblock_Controller"; speed = 0.15; jumpHeight = 35; } Eblock_Controller(JSONObject j) { super(j); this.clss = "Eblock_Controller"; jumpHeight = j.getFloat("jumpHeight"); } void setParent(Game_Object _parent) { super.setParent(_parent); if (parent.body != null) body = parent.body; } void move(int dir) { float spd = speed; //if (!body.support) {spd *= 0.3;} if (dir < 0) { //LEFT parent.ax -= spd; body.box.addForce(-2599, -5); } else { //RIGHT body.box.addForce(2500, -5); } } void jump() { //if (body.support) { body.box.addImpulse(0, -2000); //} } void update() { body.box.setRotation(0); } JSONObject saveJSON() { JSONObject j = super.saveJSON(); j.setFloat("jumpHeight", jumpHeight); return j; } }
<template> <div> <el-button type="primary" style="margin-bottom: 15px;" @click="showAddUserDialog">添加用户</el-button> <el-table :data="userData" style="width: 100%"> <el-table-column prop="userId" label="用户ID"></el-table-column> <el-table-column prop="username" label="用户名"></el-table-column> <el-table-column prop="registrationTime" label="注册时间"> <template slot-scope="scope"> {{ formatDate(scope.row.registrationTime) }} </template> </el-table-column> <el-table-column label="操作"> <template slot-scope="scope"> <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row)">编辑</el-button> <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row)">删除</el-button> </template> </el-table-column> </el-table> <el-dialog :visible.sync="addUserDialogVisible" title="添加用户"> <el-form ref="addUserForm" :model="newUser"> <el-form-item label="用户名" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"> <el-input v-model="newUser.username"></el-input> </el-form-item> <el-form-item label="密码" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"> <el-input type="password" v-model="newUser.password"></el-input> </el-form-item> </el-form> <span slot="footer" class="dialog-footer"> <el-button @click="addUserDialogVisible = false">取消</el-button> <el-button type="primary" @click="addUser">确定</el-button> </span> </el-dialog> <el-dialog :visible.sync="editUserDialogVisible" title="编辑用户"> <el-form ref="editUserForm" :model="editedUser"> <el-form-item label="用户名"> <el-input v-model="editedUser.username" :readonly="true"></el-input> </el-form-item> <el-form-item label="新密码" :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' }]"> <el-input type="password" v-model="editedUser.newPassword"></el-input> </el-form-item> </el-form> <span slot="footer" class="dialog-footer"> <el-button @click="editUserDialogVisible = false">取消</el-button> <el-button type="primary" @click="saveEditedUser">保存</el-button> </span> </el-dialog> </div> </template> <script> import axios from 'axios'; export default { data() { return { userData: [], addUserDialogVisible: false, editUserDialogVisible: false, newUser: { userId: '', username: '', password: '' }, editedUser: { userId: '', // 添加userId属性 username: '', newPassword: '' } }; }, mounted() { this.fetchUserData(); }, methods: { editUser(user) { // 设置编辑用户对话框中的数据 this.editedUser.userId = user.userId; // 确保获取用户的 ID this.editedUser.username = user.username; this.editUserDialogVisible = true; }, fetchUserData() { axios.get('/api/users/all') .then(response => { this.userData = response.data; }) .catch(error => { console.error('Error fetching user data: ', error); }); }, formatDate(date) { return new Date(date).toLocaleString(); }, showAddUserDialog() { this.addUserDialogVisible = true; }, addUser() { axios.post('/api/users/create-user', this.newUser) .then(response => { this.addUserDialogVisible = false; this.fetchUserData(); this.$message.success('用户添加成功'); this.newUser = { username: '', password: '' }; }) .catch(error => { console.error('Error adding user: ', error); this.$message.error('用户添加失败'); }); }, editUser(user) { this.editedUser.username = user.username; this.editUserDialogVisible = true; }, saveEditedUser() { axios.put(`/api/users/update`, { userId: this.editedUser.userId, // 将用户ID包含在请求体中 username: this.editedUser.username, password: this.editedUser.newPassword }) .then(response => { this.editUserDialogVisible = false; this.fetchUserData(); this.$message.success('用户信息更新成功'); this.editedUser = { userId: '', // 重置用户ID username: '', newPassword: '' }; }) .catch(error => { console.error('Error updating user: ', error); this.$message.error('用户信息更新失败'); }); }, deleteUser(user) { axios.delete(`/api/users/${user.userId}`) .then(() => { this.fetchUserData(); this.$message.success('用户删除成功'); }) .catch(error => { console.error('Error deleting user: ', error); this.$message.error('用户删除失败'); }); } } }; </script>
package com.cricketboard.processor; import com.cricketboard.domain.Activity; import com.cricketboard.domain.NewBowlActivity; import com.cricketboard.domain.Over; import com.cricketboard.service.ActivityRecordService; import com.cricketboard.service.BowlService; import org.springframework.stereotype.Service; import java.util.Objects; @Service public class NewBowlActivityProcessor implements ActivityProcessor { private final BowlService bowlService; private final ActivityRecordService activityRecordService; public NewBowlActivityProcessor(BowlService bowlService, ActivityRecordService activityRecordService) { this.bowlService = bowlService; this.activityRecordService = activityRecordService; } @Override public Activity processActivity(Activity activity) { NewBowlActivity newBowlActivity = (NewBowlActivity) activity; Over currentOverSummary = bowlService.getCurrentOverSummary( newBowlActivity.getMatchId(), newBowlActivity.getInningsId()); isBowlSequenceValid(currentOverSummary, newBowlActivity); bowlService.saveBowl(newBowlActivity.getBowl()); activityRecordService.saveActivityRecord(activity); return activity; } private static void isBowlSequenceValid(Over currentOverSummary, NewBowlActivity newBowlActivity) { if (!Objects.equals(currentOverSummary.nextBowlNumber(), newBowlActivity.getBowl().getBallNumber()) || !Objects.equals(currentOverSummary.nextOverNumber(), newBowlActivity.getBowl().getOverNumber())) { throw new RuntimeException( "Bowl sequence is not correct, Expected next over: %s, ball: %s while trying to add ball with over: %s ball: %s" .formatted( currentOverSummary.nextOverNumber(), currentOverSummary.nextBowlNumber(), newBowlActivity.getBowl().getOverNumber(), newBowlActivity.getBowl().getBallNumber())); } } }
import React, { Fragment } from "react"; import Slider from "@material-ui/core/Slider"; import { ComboBox, TextInput } from "carbon-components-react"; // custom components import Validated from "../common/Validated.jsx"; import StepTitles from "../common/StepTitles.jsx"; import Buttons from "../common/Buttons.jsx"; import { sieves } from "../../config.json"; import "../../styles/mill.scss"; const screen = "mill"; const comboProps = (titleText) => ({ id: titleText, placeholder: "Cribas", titleText, light: true, size: "sm", }); const inputProps = (labelText) => ({ id: labelText, size: "sm", labelText, light: true, type: "number", step: 1, min: 0, max: 10, }); const Mill2 = ({ step, submit, data, onComboChange, onInputChange, onCheckChange, handleMillSlider, disabled, }) => { console.log("rendering Mill2..."); if (!data) return "Cargando..."; const { supervisor } = data; const { sieve, microtalcum, enzymes, validated } = data.payload; return ( <Fragment> <div className="bx--grid bx--grid--full-width"> <StepTitles title="Ingreso al molino" step="2" /> <div className="bx--row custom__row"> <div className="bx--col"> <ComboBox items={sieves} itemToString={(item) => (item ? item.text : "")} onChange={(event) => onComboChange(event, screen, "sieve")} {...comboProps("Criba")} selectedItem={sieve ? sieves[sieve - 1] : ""} /> </div> <div className="bx--col-sm-1"> <TextInput value={microtalcum} onChange={(event) => onInputChange(event, screen, "microtalcum",1)} {...inputProps("Microtalco (kg/ton)")} /> </div> </div> <div className="bx--row custom__row"> <div className="bx--col"> <div className="mill--slider"></div> <span>Enzimas</span> <Slider defaultValue={enzymes} aria-labelledby="discrete-slider" valueLabelDisplay="auto" step={50} min={0} max={500} onChange={(event, value) => handleMillSlider(event, value, screen, "enzymes") } /> </div> <Validated mode={supervisor} screen={screen} onCheckChange={onCheckChange} validated={validated} /> </div> <Buttons screen={screen} left="Anterior" right="Registrar" onStep={step} onSubmit={submit} disabled={disabled} /> </div> </Fragment> ); }; export default Mill2;
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { SlickCarouselModule } from 'ngx-slick-carousel'; import { HttpClient, HttpHandler, HttpEvent, HttpEventType } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { HomeComponent } from './home.component'; import { HttpService } from '../../services/Http/http.service'; describe('HomeComponent', () => { let component: HomeComponent; let fixture: ComponentFixture<HomeComponent>; let compiled: any; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule, SlickCarouselModule ], declarations: [ HomeComponent ], providers: [ HttpClient, HttpHandler, HttpService, HttpTestingController ], schemas: [NO_ERRORS_SCHEMA] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(HomeComponent); compiled = fixture.debugElement.nativeElement; component = fixture.componentInstance; component.ngOnInit(); fixture.detectChanges(); }); it('Verificando textos e link do banner', () => { fixture.detectChanges(); expect(compiled.querySelector('.content__banner--text-content h1').textContent.trim()).toEqual('Conheça uma de nossos planos agora!'); expect(compiled.querySelector('.content__banner--text-content h2').textContent.trim()).toEqual('Temos planos para seu tablet, computador e para sua casa!!! Escolha o plano que cabe no seu bolso!'); }); it('Verificando textos das box de plataforma', () => { fixture.detectChanges(); expect(compiled.querySelector('.platforms h2').textContent.trim()).toEqual('Selecione uma plataforma'); }); });
using System.Reflection.PortableExecutable; namespace Data.Repositories{ public class ArticleRepository { // public List<Article> Articles; private readonly ApplicationContext _context; public ArticleRepository( ApplicationContext context) { _context = context; // Articles = new List<Article>() // { // new Article(){Id=1, Content="content1fsdfsdfsdfsdfsdf", Summary="this is a summary of the content1", Title="First Article"}, // new Article(){Id=2, Content="content2fsdfsdfsdfsdfsdf", Summary="this is a summary of the content2", Title="Second Article"}, // new Article(){Id=3, Content="content3fsdfsdfsdfsdfsdf", Summary="this is a summary of the content3", Title="Third Article"}, // new Article(){Id=4, Content="content4fsdfsdfsdfsdfsdf", Summary="this is a summary of the content4", Title="Fourth Article"} // }; } public int AddArticle(Article newArticle) { _context.Articles.Add(newArticle); _context.SaveChanges(); return newArticle.Id; } public List<Article> GetAll() { return _context.Articles.Where(a => a.State == "Active").ToList(); } public Article? Get(int Id) { return _context.Articles.Where(a => a.State == "Active").FirstOrDefault(a => a.Id == Id); } public bool Delete(int id) { var articleToDelete = _context.Articles.FirstOrDefault(a => a.Id == id); if(articleToDelete is not null) { articleToDelete.State = "Deleted"; _context.Articles.Update(articleToDelete); _context.SaveChanges(); return true; } return false; } } }
import React from 'react' import PropTypes from 'prop-types' import Drawer from '@mui/material/Drawer' import Box from '@mui/material/Box' import {SidebarNav} from './components' const Sidebar = ({open = false, pages, variant, onClose}) => { return ( <Drawer anchor="left" onClose={() => onClose()} open={open} variant={variant} sx={{ '& .MuiPaper-root': { width: '100%', maxWidth: 256, top: {xs: 0, md: 71}, height: {xs: '100%', md: 'calc(100% - 71px)'} } }} > <Box sx={{ height: '100%', padding: 1, paddingTop: {xs: 2, sm: 3} }} > <SidebarNav pages={pages} onClose={onClose} /> </Box> </Drawer> ) } Sidebar.propTypes = { onClose: PropTypes.func, open: PropTypes.bool.isRequired, variant: PropTypes.string.isRequired, pages: PropTypes.array.isRequired } export default Sidebar
package com.br.common.exception; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.JsonNode; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import org.apache.commons.lang3.RandomStringUtils; @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class ErrorResponse { private String id; private String error; private String message; private JsonNode description; public ErrorResponse(String error, String message) { this.id = RandomStringUtils.randomAlphabetic(6); this.error = error; this.message = message; } public ErrorResponse(String id, String error, String message) { this.id = id; this.error = error; this.message = message; } }
import React, { useState } from 'react' import { useEffect } from "react"; import { db } from "../../firebase-config"; import { addDoc, collection, deleteDoc, doc, getDocs, updateDoc } from "firebase/firestore"; import { Link, useNavigate } from 'react-router-dom'; import { useDispatch, useSelector } from 'react-redux'; function Home() { const dispatchAdd = useDispatch(); const students = useSelector((state) => state ); console.log(students); const navigate = useNavigate(); const [student, setStudent] = useState([]); const studentsCollectionReference = collection(db, "students"); // fetchb data when page is rendering useEffect(() => { const getStudent = async () => { const data = await getDocs(studentsCollectionReference); setStudent(data.docs.map((doc) => ({...doc.data(), id: doc.id}))); } getStudent(); }, []); // delete a document const deleteHandler = async ( stdId ) => { const studentDoc = doc(db, "students", stdId ) await deleteDoc(studentDoc); navigate("/"); } const editHandler = (id,Name,Address,DOB,GPA) => { localStorage.setItem('Id', id); localStorage.setItem('Name', Name); localStorage.setItem('Address', Address); localStorage.setItem('DOB', DOB); localStorage.setItem('GPA', GPA); // redux // dispatchAdd({ type : 'CREATE_STUDENT', payload : { id: id, Name: Name, Address: Address, DOB: DOB, GPA: GPA } }); } return ( <div className='container'> <div><Link to={'/modal'}><button type="button" class="btn btn-primary">Add New Student</button></Link></div> <table class="table table-dark table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">Address</th> <th scope="col">Birth Day</th> <th scope="col">GPA</th> <th scope="col">Action</th> </tr> </thead> <tbody> { student.map((std,key) => { return <tr key={key+1}> <th scope="row">{key}</th> <td>{std.Name}</td> <td>{std.Address}</td> <td>{std.DOB}</td> <td>{std.GPA}</td> <td> <Link to={'/edit'}> <button type="button" class="btn btn-primary" onClick={() => {editHandler(std.id,std.Name, std.Address, std.DOB, std.GPA)}} >Edit</button> </Link> &nbsp; <button type="button" class="btn btn-danger" onClick={() => {deleteHandler(std.id)}}>Delete</button> </td> </tr> }) } </tbody> </table> </div> ) } export default Home;
<!DOCTYPE html> <html> <head> <title>Business landing page</title> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="styles/general.css"> <link rel="stylesheet" href="styles/header.css"> <link rel="stylesheet" href="styles/main.css"> </head> <body> <div class="first-half"> <!-- creating a header --> <header class="header"> <div class="left-section"> LOGO </div> <div class="right-section"> <p>Home</p> <p>About</p> <p>Partners</p> <p>Faq</p> <p>Blog</p> </div> </header> <!-- creating a main content --> <div class="flex"> <div class="content1"> <p class="title">Dream Home is ready for </p> <p class="title">upcoming booking</p> <p class="title2">Here to help you own your future.</p> </div> <div class="content2"> <button class="book-now-button">Book Now</button> <p class="learn-more-link">Learn more</p> </div> </div> </div> <!-- wave --> <svg class="wave" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="white" fill-opacity="1" d="M0,128L80, 112C160,96,320,64,480,80C640,96,800,160, 960,165.3C1120,171,1280,117,1360,90.7L1440, 64L1440, 320L1360,320C1280,320,1120,320, 960,320C800,320,640,320,480,320C320,320,160,320,80,320L0,320Z"></path></svg> <div class="second-half"> <div class="our-partners-title"> Our Partners </div> <div class="partner-cards"> <div class="card"> <img class="partner-logo" src="images/Makemytrip_logo.svg"> </div> <div class="card"> <img class="partner-logo" src="images/agoda.png"> </div> <div class="card"> <img class="partner-logo" src="images/airbnb png.png"> </div> <div class="card"> <img class="partner-logo" src="images/skyscanner.png"> </div> </div> </div> <div class="statistics"> <div class="image-container"> <div class="stats-card-flex" > <div class="statistics-card"> <p class="count">66K <span>+</span></p> <p class="details">Property ready</p> </div> <div class="statistics-card"> <p class="count">696 <span>+</span></p> <p class="details">Award Winner</p> </div> <div class="statistics-card"> <p class="count">666K <span>+</span></p> <p class="details">Happy Customers</p> </div> <div class="statistics-card"> <p class="count">30 <span>+</span></p> <p class="details">New Projects</p> </div> </div> </div> </div> <div class="final-div1"> <div class="final-div1-grid"> <div > <img class="men-image" src="images/men.png"> </div> <div class="final-content1"> <p>Find Perfect Home for your Family</p> </div> </div> </div> <div class="final-div2"> <div class="company-name"> <p>COMPANY NAME</p> <div class="social-icons"> <p>Follow Us</p> <i class="fa-brands fa-square-instagram"></i> <i class="fa-brands fa-square-facebook"></i> <i class="fa-brands fa-square-twitter"></i> <i class="fa-brands fa-linkedin"></i> <i class="fa-brands fa-youtube"></i> </div> </div> <div class="useful-links"> <p class="quick-links">QUICK LINKS</p> <p class="links">Home</p> <p class="links">Ongoing Projects</p> <p class="links">Buyer's Guide</p> <p class="links">Privacy Policy</p> </div> <div class="company-contact"> <p class="contact">CONTACT</p> <p class="contact-number"><i class="fa-solid fa-phone"></i> 2222224448</p> <p class="contact-mailid"><i class="fa-solid fa-envelope"></i> companyname@gmail.com</p> </div> </div> </body> </html>
package pacman.ghosts; import pacman.ghosts.ghostStrategies.YellowGhostStrategy; /** * Class representing the Yellow Ghost in the Pac-Man game. * This class extends the Ghost class. */ public class YellowGhost extends Ghost { /** * Constructor to initialize the Yellow Ghost at a specific position. * * @param xPos The x position of the Yellow Ghost. * @param yPos The y position of the Yellow Ghost. */ public YellowGhost(int xPos, int yPos) { super(xPos, yPos, "YellowGhost.png"); setStrategy(new YellowGhostStrategy(this)); } /** * Create a clone of this Yellow Ghost. * * @return A clone of this Yellow Ghost. */ @Override public Ghost clone() { YellowGhost clonedGhost = (YellowGhost) super.clone(); clonedGhost.setStrategy(this.strategy.clone()); return clonedGhost; } }
// Library #include <FirebaseESP8266.h> #include <ESP8266WiFi.h> #include <DHT.h> #include <NTPClient.h> #include <WiFiUdp.h> // Mendefinisikan pin dan tipe sensor DHT #define DHTPIN D2 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); const long utcOffsetInSeconds = 25200; char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; // Define NTP Client to get time WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "id.pool.ntp.org", utcOffsetInSeconds); // Harus diisi #define FIREBASE_HOST "https://fir-miotdht11-default-rtdb.firebaseio.com/" #define FIREBASE_AUTH "B3YaLOcvPxvfc0Tk6Oy7rCiokCL26pUSx0wtoOHt" #define WIFI_SSID "Hujan" #define WIFI_PASSWORD "hujan293" // mendeklarasikan objek data dari FirebaseESP8266 FirebaseData firebaseData; void setup() { Serial.begin(115200); dht.begin(); // Koneksi ke Wifi WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("connecting"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("Connected with IP: "); Serial.println(WiFi.localIP()); Serial.println(); Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); timeClient.begin(); } void loop(){ //clock timeClient.update(); // Sensor DHT11 membaca suhu dan kelembaban float t = dht.readTemperature(); float h = dht.readHumidity(); // Memeriksa apakah sensor berhasil mambaca suhu dan kelembaban if (isnan(t) || isnan(h)) { Serial.println("Gagal membaca sensor DHT11"); return; } //menampilkan waktu Serial.print("hari: "); Serial.print(daysOfTheWeek[timeClient.getDay()]); Serial.print("jam: "); Serial.print(timeClient.getHours()); Serial.print("menit: "); Serial.print(timeClient.getMinutes()); Serial.print("detik: "); Serial.println(timeClient.getSeconds()); Serial.println(); // Menampilkan suhu dan kelembaban pada serial monitor Serial.print("suhu: "); Serial.print(t); Serial.println(" *C"); Serial.print("kelembapan: "); Serial.print(h); Serial.println(" %"); Serial.println(); // Memberikan status waktu kepada firebase if (Firebase.setString(firebaseData, "/Hasil_Pembacaan/hari", daysOfTheWeek[timeClient.getDay()])){ Serial.println("Hari terkirim"); } else{ Serial.println("Hari tidak terkirim"); Serial.println("Karena: " + firebaseData.errorReason()); } if (Firebase.setString(firebaseData, "/Hasil_Pembacaan/jam", timeClient.getHours())){ Serial.println("Jam terkirim"); } else{ Serial.println("Jam tidak terkirim"); Serial.println("Karena: " + firebaseData.errorReason()); } if (Firebase.setString(firebaseData, "/Hasil_Pembacaan/menit", timeClient.getMinutes())){ Serial.println("Menit terkirim"); } else{ Serial.println("Menit tidak terkirim"); Serial.println("Karena: " + firebaseData.errorReason()); } if (Firebase.setString(firebaseData, "/Hasil_Pembacaan/detik", timeClient.getSeconds())){ Serial.println("Detik terkirim"); } else{ Serial.println("Detik tidak terkirim"); Serial.println("Karena: " + firebaseData.errorReason()); } // Memberikan status suhu dan kelembaban kepada firebase if (Firebase.setFloat(firebaseData, "/Hasil_Pembacaan/suhu", t)){ Serial.println("Suhu terkirim"); } else{ Serial.println("Suhu tidak terkirim"); Serial.println("Karena: " + firebaseData.errorReason()); } if (Firebase.setFloat(firebaseData, "/Hasil_Pembacaan/kelembaban", h)){ Serial.println("Kelembaban terkirim"); Serial.println(); } else{ Serial.println("Kelembaban tidak terkirim"); Serial.println("Karena: " + firebaseData.errorReason()); } delay(1000); }
// Core import React from 'react'; // Views import { Base } from '../../views/base'; // Hooks import { useProfile } from '../../bus/user/hooks/useProfile'; import { useProfileInitializer } from '../../bus/user/hooks/useProfileInitializer'; import { useScoreInitializer } from '../../bus/tracker/hooks/useScoreInitializer'; import { useRecordInitializer } from '../../bus/tracker/hooks/useRecordInitializer'; import { useScore } from '../../bus/tracker/hooks/useScore'; import { useRecord } from '../../bus/tracker/hooks/useRecord'; // Components import { CustomQuestionSelector } from '../../elements/customQuestionSelector'; export const Coffee = () => { // Get profile from API useProfileInitializer(); useScoreInitializer(); useRecordInitializer('coffee'); const { score } = useScore(); const { record, updateRecord, createRecord, isLoading } = useRecord(); const { profile, logout, } = useProfile(); const variants = [ { title: 'Я не пил совсем', value: 'none' }, { title: 'Выпил 1 стакан', value: 'light' }, { title: 'Выпил 2 или больше стаканов', value: 'heavy' } ]; return ( <> <Base logout={logout} profile={profile} score={score} > <CustomQuestionSelector title="Ты сегодня пил кофе?" variants={variants} initial={record.coffee} update={updateRecord} create={createRecord} type="coffee" blocked={isLoading} /> </Base> </> ); };
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { environment } from './environment'; import { Food } from '../food/entities/food.entity'; @Module({ imports: [ TypeOrmModule.forRootAsync({ useFactory: () => ({ type: 'postgres', host: 'postgres', port: environment.dbPort, username: 'postgres', password: 'mysecretpassword', database: 'postgres', entities: [Food], synchronize: true, }), }), ], }) export class DatabaseModule { static createTypeOrmOptions() { return { type: 'postgres', host: 'localhost', port: environment.dbPort, username: 'postgres', password: 'mysecretpassword', database: 'postgres', entities: [Food], synchronize: true, }; } }
import { useHttpCall } from "common/hooks"; import Http from "common/http"; import { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { pickBy } from "lodash-es"; import toast from "react-hot-toast"; import { RootState } from "store"; import { useSelector } from "react-redux"; const ReportProblemVM = () => { const [isSubmissionSuccess, setIsSubmissionSuccess] = useState<boolean>(false); const user = useSelector((state: RootState) => state.auth.user); const form = useForm(); useEffect(() => { if (user) { form.reset({ name: user.name, email: user.email }); } else { form.reset({}); } }, [user]); const { execute: executeSendEmail, isLoading: isSendingMail } = useHttpCall(); const sendEmail = (data: any) => { const sanitizedValues = pickBy(data, (value) => { if (typeof value == "boolean") { return true; } return value?.length > 0; }); return executeSendEmail( () => Http.post("/v1/app-services/report_problem", sanitizedValues), { onSuccess: (res) => setIsSubmissionSuccess(true), onError: (e) => toast.error( "Something went wrong. Please try again later." ), } ); }; return { isSubmissionSuccess, sendEmail, isSendingMail, form }; }; export default ReportProblemVM;
from typing import Any, Dict from pyorient.orient import OrientDB from src.graph_database.orientdb.managers.abstract_manager import AbstractManager from src.graph_database.orientdb.query_builders import SchemaQueryBuilder class SchemaManager(AbstractManager): """ Concrete manager for handling `orientdb schema`. Implements abstract manager, providing methods to execute commands and queries on OrientDB related to the schema. """ def __init__(self, client: OrientDB): self.client = client self._query_builder = SchemaQueryBuilder() async def create(self, class_name: str, extends: str = None) -> Dict: """ Creates a new class in the schema. """ query = self._query_builder.query_create(class_name, extends) result = self.client.command(query) try: ret = result[0].__dict__ except AttributeError: ret = result return ret async def update(self, class_name: str, properties: Dict[str, Any] = None) -> Dict: """ Updates an existing class in the schema. """ query = self._query_builder.query_update(class_name, properties) result = self.client.command(query) return result[0].__dict__ async def delete(self, class_name: str) -> Any: """ Deletes a class from the schema. """ query = self._query_builder.query_delete(class_name) result = self.client.command(query) return result async def retrieve(self, name: str) -> Any: """ Retrieves all classes from the schema. """ query = self._query_builder.query_retrieve() result = self.client.query(query) return result async def class_exists(self, class_name: str) -> bool: """ Check if a class exists in the database. :param class_name: The name of the class to check. :return: True if the class exists, False otherwise. """ query = f"SELECT count(*) as count FROM (SELECT expand(classes) FROM metadata:schema) WHERE name = '{class_name}'" result = self.client.command(query) return bool(result and result[0].count > 0)
= Trac Installation Guide for 0.11 = [[TracGuideToc]] '''NOTE: this page is now for 0.11, which will be released soon. For installing previous Trac versions, please refer to wiki:0.10/TracInstall.''' Trac is written in the Python programming language and needs a database, [http://sqlite.org/ SQLite], [http://www.postgresql.org/ PostgreSQL], or [http://mysql.com/ MySQL]. For HTML rendering, Trac uses the [http://genshi.edgewall.org Genshi] templating system. What follows are generic instructions for installing and setting up Trac and its requirements. While you can find instructions for installing Trac on specific systems at TracInstallPlatforms on the main Trac site, please be sure to '''first read through these general instructions''' to get a good understanding of the tasks involved. == Short - Install a released version == For the quick install, make sure you have [http://python.org Python-2.5], [http://peak.telecommunity.com/DevCenter/EasyInstall#installing-easy-install easy_install] and SQlite-3.3.4 installed (or above). {{{ sudo easy_install Trac==0.11b2 }}} == Requirements - also older versions possible == To install Trac, the following software packages must be installed: * [http://www.python.org/ Python], version >= 2.3 * if using mod_python together with xml-related things, use python-2.5. expat is namespaced there and does not cause apache to crash any more(see [http://www.dscpl.com.au/wiki/ModPython/Articles/ExpatCausingApacheCrash here] for details). * For RPM-based systems you might also need the `python-devel` and `python-xml` packages. * See instructions in ["TracOnWindows/Python2.5"] * [http://peak.telecommunity.com/DevCenter/setuptools setuptools], version >= 0.6 * [http://genshi.edgewall.org/wiki/Download Genshi], version >= 0.4.1 * You also need a database system and the corresponding python drivers for it. The database can be either SQLite, PostgreSQL or ''MySQL (experimental)''. * optional if some plugins require it: [http://www.clearsilver.net/ ClearSilver] === For SQLite === * [http://www.sqlite.org/ SQLite], version 3.3.4 and above preferred. * If not using Python-2.5: [http://pysqlite.org/ PySQLite], version 1.x (for SQLite 2.x) or version 2.x (for SQLite 3.x), version 2.3.2 preferred. For details see PySqlite ''Note: It appears that PySQLite 2.x is required for Trac 0.9+/SQLite 3.x if you plan to use the 'trac-post-commit-hook.py' script available from the 'contrib' section of the source repository.'' ''Note: Users of Mac OS X please take care; the Apple-supplied SQLite contains additional code to support file locking on network filesystems like AFP or SMB. This is not presently (3.3.6) in the mainline sources, so if you build your own SQLite from source it will not function correctly on such filesystems - typically it gives the error "{{{database is locked}}}". [http://www.alastairs-place.net/2006/07/sqlite_and_mac/ A patch] is available for version 3.3.6, based on Apple's code, otherwise you're probably best off using the Apple supplied version (presently 3.1.3).'' === For PostgreSQL === * [http://www.postgresql.org/ PostgreSQL] * [http://initd.org/projects/psycopg2 psycopg2] or [http://pypgsql.sourceforge.net/ pyPgSQL] '''Warning''': PostgreSQL 8.3 uses a strict type checking mechanism. To use Trac with the 8.3 Version of PostgreSQL, you will need [http://trac.edgewall.org/changeset/6512 trac-0.11] or later. === For MySQL === '''Warning''': MySQL support is currently ''still'' experimental. That means it works for some people, but several issues remain, in particular regarding the use of unicode and the key length in the repository cache. See MySqlDb for more detailed information. * [http://mysql.com/ MySQL], version 4.1 or later * [http://sf.net/projects/mysql-python MySQLdb], version 1.2.1 or later === Optional Requirements === ==== Version Control System ==== '''Please note:''' if using Subversion, Trac must be installed on the '''same machine'''. Remote repositories are currently not supported. * [http://subversion.tigris.org/ Subversion], version >= 1.0. (versions recommended: 1.2.4, 1.3.2 or 1.4.2) and the '''''corresponding''''' Python bindings. For troubleshooting, check TracSubversion * Trac uses the [http://svnbook.red-bean.com/svnbook-1.1/ch08s02.html#svn-ch-8-sect-2.3 SWIG] bindings included in the Subversion distribution, '''not''' [http://pysvn.tigris.org/ PySVN] (which is sometimes confused with the standard SWIG bindings). * If Subversion was already installed without the SWIG bindings, on Unix you'll need to re-`configure` Subversion and `make swig-py`, `make install-swig-py`. * There are [http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91 pre-compiled bindings] available for win32. * Support for other version control systems is provided via third-parties. See PluginList and VersioningSystemBackend. ==== Web Server ==== * A CGI-capable web server (see TracCgi), or * a [http://www.fastcgi.com/ FastCGI]-capable web server (see TracFastCgi), or * [http://httpd.apache.org/ Apache] with [http://code.google.com/p/modwsgi/ mod_wsgi] (see [wiki:TracModWSGI]) * This should work with Apache 1.3, 2.0 or 2.2 and promises to deliver more performance than using mod_python. A little less mature than mod_python. * [http://httpd.apache.org/ Apache] with [http://www.modpython.org/ mod_python 3.1.3+] (see TracModPython) * When installing mod_python the development versions of Python and Apache are required (actually the libraries and header files) For those stuck with Apache 1.3, it is also possible to get Trac working with [http://www.modpython.org/ mod_python 2.7] (see [wiki:TracModPython2.7 TracModPython2.7]). This guide hasn't been updated since 0.84, so it may or may not work. ==== Other Python Utilities ==== * [http://docutils.sourceforge.net/ docutils], version >= 0.3.9 for WikiRestructuredText. * [http://pygments.pocoo.org Pygments] for [wiki:TracSyntaxColoring syntax highlighting], also [http://silvercity.sourceforge.net/ SilverCity] and/or [http://gnu.org/software/enscript/enscript.html Enscript] may still be used. * Note that !SilverCity 0.9.6 has a [http://sourceforge.net/tracker/index.php?func=detail&aid=1424436&group_id=45693&atid=443739 bug] that breaks Python syntax highlighting in Trac. Until an update is made available, we recommend using version 0.9.5. * [http://pytz.sf.net pytz] to get a complete list of time zones, otherwise Trac will fall back on a shorter list from an internal time zone implementation. '''Attention''': The various available versions of these dependencies are not necessarily interchangable, so please pay attention to the version numbers above. If you are having trouble getting Trac to work please double-check all the dependencies before asking for help on the MailingList or IrcChannel. Please refer to the documentation of these packages to find out how they are best installed. In addition, most of the [wiki:TracInstallPlatforms platform-specific instructions] also describe the installation of the dependencies. Keep in mind however that the information there ''probably concern older versions of Trac than the one you're installing'' (there are even some pages that are still talking about Trac 0.8!). == Installing Trac == One way to install Trac is using `setuptools`. With setuptools you can install Trac from the subversion repository; for example, to install release version 0.11b2 do: {{{ easy_install http://svn.edgewall.org/repos/trac/tags/trac-0.11b2 }}} But of course the python-typical setup at the top of the source directory also works: {{{ $ python ./setup.py install }}} ''Note: you'll need root permissions or equivalent for this step.'' This will byte-compile the python source code and install it as an .egg file or folder in the `site-packages` directory of your Python installation. The .egg will also contain all other resources needed by standard Trac, such as htdocs and templates. The script will also install the [wiki:TracAdmin trac-admin] command-line tool, used to create and maintain [wiki:TracEnvironment project environments], as well as the [wiki:TracStandalone tracd] standalone server. === Advanced Options === To install Trac to a custom location, or find out about other advanced installation options, run: {{{ easy_install --help }}} Also see [http://docs.python.org/inst/inst.html Installing Python Modules] for detailed information. Specifically, you might be interested in: {{{ easy_install --prefix=/path/to/installdir }}} or, if installing Trac to a Mac OS X system: {{{ easy_install --prefix=/usr/local --install-dir=/Library/Python/2.5/site-packages }}} The above will place your `tracd` and `trac-admin` commands into `/usr/local/bin` and will install the Trac libraries and dependencies into `/Library/Python/2.5/site-packages`, which is Apple's preferred location for third-party Python application installations. == Creating a Project Environment == A [wiki:TracEnvironment Trac environment] is the backend storage where Trac stores information like wiki pages, tickets, reports, settings, etc. An environment is basically a directory that contains a human-readable configuration file and various other files and directories. A new environment is created using [wiki:TracAdmin trac-admin]: {{{ $ trac-admin /path/to/myproject initenv }}} [wiki:TracAdmin trac-admin] will prompt you for the information it needs to create the environment, such as the name of the project, the type and the path to an existing [wiki:TracEnvironment#SourceCodeRepository source code repository], the [wiki:TracEnvironment#DatabaseConnectionStrings database connection string], and so on. If you're not sure what to specify for one of these options, just leave it blank to use the default value. The database connection string in particular will always work as long as you have SQLite installed. Leaving the path to the source code repository empty will disable any functionality related to version control, but you can always add that back when the basic system is running. Also note that the values you specify here can be changed later by directly editing the [wiki:TracIni] configuration file. ''Note: The user account under which the web server runs will require write permissions to the environment directory and all the files inside. On Linux, with the web server running as user apache and group apache, enter:'' chown -R apache.apache /path/to/myproject == Running the Standalone Server == After having created a Trac environment, you can easily try the web interface by running the standalone server [wiki:TracStandalone tracd]: {{{ $ tracd --port 8000 /path/to/myproject }}} Then, fire up a browser and visit `http://localhost:8000/`. You should get a simple listing of all environments that tracd knows about. Follow the link to the environment you just created, and you should see Trac in action. If you only plan on managing a single project with trac you can have the standalone server skip the environment list by starting it like this: {{{ $ tracd -s --port 8000 /path/to/myproject }}} == Running Trac on a Web Server == Trac provides three options for connecting to a "real" web server: [wiki:TracCgi CGI], [wiki:TracFastCgi FastCGI] and [wiki:TracModPython mod_python]. For decent performance, it is recommended that you use either FastCGI or mod_python. If you're not afraid of running development code, you can also try running Trac on [wiki:TracModWSGI mod_wsgi]. This should deliver even better performance than mod_python, but the module is not considered stable just yet. == Configuring Authentication == The process of adding, removing, and configuring user accounts for authentication depends on the specific way you run Trac. The basic procedure is described in the [wiki:TracCgi#AddingAuthentication "Adding Authentication"] section on the TracCgi page. To learn how to setup authentication for the frontend you're using, please refer to one of the following pages: * TracStandalone if you use the standalone server, `tracd`. * TracCgi if you use the CGI or FastCGI methods. * TracModPython if you use the mod_python method. == Trac 0.11 & SVN on Mac OS X Leopard (10.5) == * TracOnLeopardServer == Using Trac == Once you have your Trac site up and running, you should be able to browse your subversion repository, create tickets, view the timeline, etc. Keep in mind that anonymous (not logged in) users can by default access most but not all of the features. You will need to configure authentication and grant additional [wiki:TracPermissions permissions] to authenticated users to see the full set of features. '' Enjoy! '' [wiki:TracTeam The Trac Team] ---- See also: TracGuide, TracCgi, TracFastCgi, TracModPython, [wiki:TracModWSGI], TracUpgrade, TracPermissions
import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppRoutingModule} from './app-routing.module'; import {AppComponent} from './app.component'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {HttpClientModule} from '@angular/common/http'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {en_US, NZ_I18N} from 'ng-zorro-antd/i18n'; import {registerLocaleData} from '@angular/common'; import en from '@angular/common/locales/en'; import {LandingComponent} from './pages/landing/landing.component'; import {StartComponent} from './pages/start/start.component'; import {GameComponent} from './pages/game/game.component'; import {SharedModule} from './shared/shared.module'; import {PlayerAvatarComponent} from './pages/game/player-avatar/player-avatar.component'; import {ResultModalComponent} from './pages/game/result-modal/result-modal.component'; registerLocaleData(en); @NgModule({ declarations: [ AppComponent, LandingComponent, StartComponent, GameComponent, PlayerAvatarComponent, ResultModalComponent, ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, HttpClientModule, BrowserAnimationsModule, SharedModule, ], providers: [{provide: NZ_I18N, useValue: en_US}], bootstrap: [AppComponent] }) export class AppModule { }
import { IResolvers } from 'graphql-tools'; import { CHANGE_BOOKS } from '../../config/constants'; import { getBooks, getAuthors } from '../../lib/database-operation'; import { Datetime } from '../../lib/datetime'; async function sendNotificationBooks(pubsub: any, db: any) { pubsub.publish(CHANGE_BOOKS, { changeBooks: await getBooks(db)}); } const mutationBook: IResolvers = { Mutation: { async registerBook(_: void, { book }, { db, pubsub }): Promise<any> { const authors: [] = await getAuthors(db); for (const author of authors) { const { id } = author; if (id != book.author_id) { return { status: false, message: 'No existe un autor con ese ID para agregar al libro', }; } const lastBook = await db .collection('books') .find() .limit(1) .sort({ registerDate: -1 }) .toArray(); if (lastBook.length === 0) { book.id = 1; } else { book.id = lastBook[0].id + 1; } book.registerDate = new Datetime().getCurrentDateTime(); return await db .collection('books') .insertOne(book) .then((result: any) => { sendNotificationBooks(pubsub, db); return { status: true, message: `Libro ${book.name} añadido correctamente`, book, }; }) .catch((err: any) => { return { status: false, message: `Libro NO añadido correctamente`, book: null, }; }); } }, async updateBook(_: void, { id, updateBook }, { db, pubsub }) { const books = await getBooks(db); for (const book of books) { const { id: bookId } = book; if (bookId !== id) { return { status: false, message: 'No existe un libro con ese id', }; } return await db .collection('books') .updateOne( { id }, { $set: { name: updateBook.name, editorial: updateBook.editorial, author_id: updateBook.author_id, year: updateBook.year, language: updateBook.language, }, } ) .then(async () => { sendNotificationBooks(pubsub, db); return { status: true, message: 'Libro actualizado', book: updateBook, }; }) .catch(async () => { return { status: false, message: 'Falso', book: null, }; }); } }, async deleteBook(_: void, { id }, { db, pubsub }) { return await db .collection('books') .deleteOne({ id }) .then(async () => { sendNotificationBooks(pubsub, db); return { status: true, message: `El libro con el ID ${id} ha sido borrado`, }; }) .catch(async () => { return { status: false, message: `Ha ocurrido un error en la eliminación`, }; }); } }, }; export default mutationBook;
import Document, { Html, Head, Main, NextScript } from 'next/document'; import { ServerStyleSheet } from 'styled-components'; function withLog(Comp) { return (props) => { console.log(props); return <Comp {...props} /> } } class MyDocument extends Document { static async getInitialProps(ctx) { const sheet = new ServerStyleSheet(); const orginalRenderPage = ctx.renderPage; try { ctx.renderpage = () => { return ( orginalRenderPage({ enhanceApp: App => (props) => sheet.collectStyles(<App {...props}></App>), }) ) } const props = await Document.getInitialProps(ctx); return { ...props, styles: ( <> {props.styles} {sheet.getStyleElement()} </> ) } } finally { sheet.seal(); } } render() { return ( <Html> <Head> </Head> <body className="test"> <Main /> <NextScript /> </body> </Html> ) } } export default MyDocument;
@extends('layouts.app') @section('content') <div class="container"> <div class="card custom-card"> <div class="card-body"> <h2 class="card-title">Edit Item</h2> <form action="{{ route('items.update', $item->id) }}" method="POST" enctype="multipart/form-data"> @csrf @method('PUT') <div class="form-group mb-3"> <label for="name" class="form-label">Name</label> <input type="text" class="form-control" name="name" id="name" value="{{ $item->name }}" required> </div> <div class="form-group mb-3"> <label for="email" class="form-label">Email</label> <input type="email" class="form-control" name="email" id="email" value="{{ $item->email }}" required> </div> <div class="form-group mb-3"> <label for="content" class="form-label">Content</label> <textarea class="form-control" name="content" id="content" required>{{ $item->content }}</textarea> </div> <div class="form-group mb-3"> <label for="age" class="form-label">Age</label> <input type="number" step="0.1" min="2.5" max="99" class="form-control" name="age" id="age" value="{{ $item->age }}" required> </div> <div class="form-group mb-3"> <label for="image" class="form-label">Image</label> <input type="file" class="form-control-file" name="image" id="image"> </div> <div class="form-group mb-3"> @error('image') <div class="alert alert-danger mt-2">{{ $message }}</div> @enderror </div> <button type="submit" class="btn btn-primary">Update</button> </form> </div> </div> </div> </div> <style> .container { margin-top: 20px; } .form-group { margin-bottom: 20px; } .custom-card { background-color: #f4f4f4; border-radius: 10px; padding: 20px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); } .custom-card .card-title { text-align: left; font-size: 24px; margin-bottom: 20px; } .form-control { width: 20%; } </style> @endsection
y360c is a command line interface (cli) for Yandex 360, which uses the standard API to access the corresponding entities/actions in Yandex360. There is no need to install the application, just place the exe file anywhere and start working with it, like with any other console application. If necessary, you can add the path to the application to PATH. Before starting work, you will need to create an application with the necessary access rights in https://oauth.yandex.ru/, as well as obtain an auth token, which is necessary to access data in Yandex360. The token can be used in 2 ways: 1. by passing it explicitly in command using the flag `--token (-t)` 2. by saving the token for automatic use in the application configuration file, which is located here: `%USERPROFILE%\y360c.json` (created automatically when using the command `init` - i.e. `y360c init`). In addition to the token, most operations require the "Organization Id" parameter, which must be used similarly to the token: 1. can be passed explicitly in the parameters using the flag `--orgId (-o)` 2. can be saved for automatic use in the application configuration file. Examples: **List of organizations**: `y360c org ls` (if the token is specified in the config) or `y360c org ls --token <token>` **List of departments**: `y360c dept ls --orgId <organization id> --token <token>` or `y360c dept ls` (if the token and the organization id are specified in the config) **List of employees**: `y360c user ls` (if the token and the organization id are specified in the config) or `y360c user ls --orgId <organization id> --token <token>` or (export to csv-file) `y360c user ls --orgId <organization id> --token <token> --csv` or (search for a specific employee) `y360c user ls --orgId <organization id> --token <token> --id <employee id>` or (search by email) `y360c user ls --orgId <organization id> --token <token> --email aaa@vvv.cc` or (search by first/middle/last name) `y360c user ls --orgId <organization id> --token <token> --name vladimir`
<html> <head> <link href="/static/css/bootstrap.min.css" rel="stylesheet" media="screen"> <link href="/static/css/bootstrap-responsive.min.css" rel="stylesheet"> <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="/static/js/bootstrap.min.js"></script> <script src="/static/js/moment.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> function translate(sourceLang, destLang, sourceId, destId, loadingId){ $(destId).hide(); $(loadingId).show(); $.post('/translate', { text: $(sourceId).text(), sourceLang: sourceLang, destLang: destLang }).done(function(translated){ $(destId).text(translated['text']) $(loadingId).hide(); $(destId).show(); }).fail(function(){ $(destId).text(" {{ _('Error: could not contact the server') }}"); $(loadingId).hide(); $(destId).show(); }); } </script> {% if title %} <title>{{ title }}</title> {% else %} <title>TODO: Add title text</title> {% endif %} </head> <body> <div class="container"> <div class="navbar"> <div class="navbar-inner"> <a class="brand" href="/">Microblog:</a> <ul class="nav"> <li><a href="{{ url_for('index') }}"> {{ _('Home') }}</a></li> {% if g.user.is_authenticated %} <li><a href="{{ url_for('user', nickname=g.user.nickname) }}">{{ _('Your Profile') }}</a></li> <li><a href="{{ url_for('logout') }}">{{ _('Logout') }}</a></li> {% endif %} </ul> <div> {% if g.user.is_authenticated %} <form style="display: inline;" class="navbar-search pull-right" action="{{ url_for('search') }}" method="post" name="search"> {{ g.search_form.hidden_tag() }}{{ g.search_form.search(size=20, placeholder=_('Search'), class="search-query") }}</form> {% endif %} </div> </div> <div class="row"> <div class="span12"> {% block content %}{% endblock %} </div> </div> </div> </body> </html>
import "dotenv/config"; import { Router, Request, Response } from "express"; import { WalletsApi } from "../../client/generated/apis/wallets-api"; import { createEntitySecretCiphertext } from "../../client/custom/apis/createEntitySecretCiphertext"; const router = Router(); const walletsApi = new WalletsApi({ accessToken: process.env.API_KEY, isJsonMime: (mime: string) => mime.includes("json"), }); router.post("/user/wallets", async (req: Request, res: Response) => { if (req.header("X-User-Token")) { const xUserToken: string = req.header("X-User-Token")!; try { const response = await walletsApi.createUserWallet(xUserToken, req.body); delete response.headers['transfer-encoding']; res.header(response.headers).send(response.data); } catch (error) { res //@ts-ignore .status(error.response.status) //@ts-ignore .header(error.response.header) //@ts-ignore .send(error.response.data); } } else { res.send("Please add an X-User-Token to the header"); } }); router.post("/developer/wallets", async (req: Request, res: Response) => { try { const entitySecretCiphertext: string | undefined = await createEntitySecretCiphertext(); if (typeof entitySecretCiphertext === "string") { req.body.entitySecretCiphertext = entitySecretCiphertext!; const response = await walletsApi.createDeveloperWallet(req.body); delete response.headers['transfer-encoding']; res.header(response.headers).send(response.data); } } catch (error) { res //@ts-ignore .status(error.response.status) //@ts-ignore .header(error.response.header) //@ts-ignore .send(error.response.data); } }); router.get("/wallets", async (req: Request, res: Response) => { try { console.log(req.query.walletSetId); const response = await walletsApi.listWallets( req.header("X-User-Token"), //@ts-ignore req.query.address, req.query.blockchain, req.query.userId, req.query.walletSetId, req.query.from, req.query.to, req.query.pageBefore, req.query.pageAfter, req.query.pageSize ); delete response.headers['transfer-encoding']; res.header(response.headers).send(response.data); } catch (error) { res //@ts-ignore .status(error.response.status) //@ts-ignore .header(error.response.header) //@ts-ignore .send(error.response.data); } }); // Added X-User-Token to OAS file since I used developer controlled wallets router.get("/wallets/:id", async (req: Request, res: Response) => { try { const response = await walletsApi.getWallet( req.params.id, req.header("X-User-Token") ); delete response.headers['transfer-encoding']; res.header(response.headers).send(response.data); } catch (error) { res //@ts-ignore .status(error.response.status) //@ts-ignore .header(error.response.header) //@ts-ignore .send(error.response.data); } }); router.put("/wallets/:id", async (req: Request, res: Response) => { try { const response = await walletsApi.updateWallet( req.params.id, req.body, req.header("X-User-Token") ); delete response.headers['transfer-encoding']; res.header(response.headers).send(response.data); } catch (error) { res //@ts-ignore .status(error.response.status) //@ts-ignore .header(error.response.header) //@ts-ignore .send(error.response.data); } }); router.get("/wallets/:id/balances", async (req: Request, res: Response) => { try { const response = await walletsApi.listWalletBallance( req.params.id, req.header("X-User-Token"), //@ts-ignore req.query.includeAll, req.query.tokenAddress, req.query.tokenAddress, req.query.standard, req.query.from, req.query.to, req.query.pageBefore, req.query.pageAfter, req.query.pageSize ); // Temporary fix Content-Length and transfer-encoding collision. They are supposed to be mutually exclusive. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding#directives // Attempted to use express middle ware response.removeHeader() to fix this issue but it doesn't work for Content-Length delete response.headers['transfer-encoding']; res.header(response.headers).send(response.data); } catch (error) { res //@ts-ignore .status(error.response.status) //@ts-ignore .header(error.response.header) //@ts-ignore .send(error.response.data); } }); router.get("/wallets/:id/nfts", async (req: Request, res: Response) => { try { const response = await walletsApi.listWalletNfts( req.params.id, req.header("X-User-Token"), //@ts-ignore req.query.includeAll, req.query.tokenAddress, req.query.tokenAddress, req.query.standard, req.query.from, req.query.to, req.query.pageBefore, req.query.pageAfter, req.query.pageSize ); delete response.headers['transfer-encoding']; res.header(response.headers).send(response.data); } catch (error) { res //@ts-ignore .status(error.response.status) //@ts-ignore .header(error.response.header) //@ts-ignore .send(error.response.data); } }); export default router;
const express = require('express') const Post = require('../schemas/post') const Comment = require('../schemas/comment') const router = express.Router() router .route('/') .get(async (req, res, next) => { try { const posts = await Post.find({}) res.json(posts) } catch (err) { console.error(err) next(err) } }) .post(async (req, res, next) => { try { const post = await Post.create({ title: req.body.title, name: req.body.name, password: req.body.password, content: req.body.content, }) console.log(post) res.status(201).json(post) } catch (err) { console.error(err) next(err) } }) router .route('/:id') // 게시글 상세 조회 .get(async (req, res) => { const post = await Post.findOne({ _id: req.params.id, }) if (post) { // 입력 아이디값과 일치한 게시글 있으면 그 게시글 반환 res.json({ post }) } else { // 일치한 값 없으면 res.status(400).json({ errorMessage: '게시글 조회에 실패했습니다.' }) } }) .put(async (req, res, next) => { try { const editPost = await Post.updateOne( { _id: req.params.id, }, { title: req.body.title, name: req.body.name, password: req.body.password, content: req.body.content, } ) res.json(editPost) } catch (err) { console.error(err) next(err) } }) .delete(async (req, res, next) => { try { const deletePost = await Post.deleteOne({ _id: req.params.id }) res.json(deletePost) } catch (err) { console.error(err) } }) router.get('/:id/comments', async (req, res, next) => { try { const comments = await Comment.find({ postId: req.params.id }) console.log(comments) res.json(comments) } catch (err) { console.error(err) next(err) } }) module.exports = router
package com.racanaa.services.account.dto.request; import com.racanaa.services.account.constant.ApiConstant; import com.racanaa.services.account.persistance.model.Role; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; import lombok.Data; import java.util.Collection; /** * User Request DTO * * @author Manohar * @since 1.0 */ @Data public class UserRequestDto { @NotBlank(message = ApiConstant.VALIDATION_MESSAGE_NAME_MANDATORY) @Size(min = 2, message = ApiConstant.VALIDATION_MESSAGE_NAME_LENGTH) private String name; @NotBlank(message = ApiConstant.VALIDATION_MESSAGE_EMAIL_MANDATORY) @Email(message = ApiConstant.VALIDATION_MESSAGE_EMAIL_VALID) private String email; private String userName; private String password; private String countryCode; private String contact; private String contactMasked; private Collection<Role> roles; }
<!DOCTYPE html> <html> <head lang="en" dir="ltr"> <title>personal website</title> <!-- <link rel="preconnect" href="https://fonts.googleapis.com"> --> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap" rel="stylesheet"> <link rel="stylesheet" href="style.css" /> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link rel="shortcut icon" href="images/logo1.png" type="image/x-icon"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" /> </head> <body> <!------nav section start-----> <div id="header"> <div class="container"> <nav> <img src="images/logo1.png" alt="" class="logo"> <ul id="sidemenu"> <li><a href="#header">Home</a></li> <li><a href="#about">About</a></li> <!-- <li><a href="#services">Services</a></li> --> <li><a href="#portfolio">Portfolio</a></li> <li><a href="#contact">Contact</a></li> <!-- <i class="fa fa-window-close" aria-hidden="true" onclick="closemenu()"></i> --> </ul> <!-- <i class="fa-solid fa-bars" onclick="openmenu()"><i> --> </nav> <div class="header-text"> <p>FullStack Developer</p> <h1>Hi, I'm <span>Hikmat Raj</span> <br>Ghodasaini From Nepal</h1> </div> </div> </div> <!-- About section start --> <div id="about"> <div class="container"> <div class="row"> <div class="about-col-1"> <img src="images/main.JPG" /> </div> <div class="about-col-2"> <h1 class="sub-title">About Me</h1> <p> Welcome to my personal portfolio! I'm Hikmat Raj Ghodasaini, a passionate full-stack developer who dedicate to web development from start to finish immpressively.With a blend of creativity, technical expertise, and a commitment to excellence, I thrive in the dynamic world of web development. </p> <br> <p> As a FullStack Developer, I possess a diverse skill set that enables me to handle both the front-end and back-end aspects of web development from building responsive user interfaces to designing robust server-side architecture, I enjoy every aspect of the development process. </p> <br> <p> Explore my portfolio to see examples of my work and feel free to reach out if you'd like to collaborate on a project or discuss opportunities. </p> <div class="tab-titles"> <p class="tab-links active-link" onclick="opentab('skills')">Skills</p> <p class="tab-links" onclick="opentab('experience')">Experience</p> <p class="tab-links" onclick="opentab('education')">Education</p> </div> <div class="tab-contents active-tab" id="skills"> <ul> <li> <span>Javascript</span><br> </li> <li> <span>React.js</span><br> </li> <li> <span>Python</span><br> </li> <li> <span>Django</span><br> </li> <li> <span>HTML||CSS||Tailwind css</span><br> </li> <li> <span>GitHub</span><br> </li> <li> <span>SQL Server</span><br> </li> <li> <span>RESTful APIs</span><br> </li> </ul> </div> <div class="tab-contents" id="experience"> <ul> <li> <span>Teacher||2019-2020</span><br> Shree Krishna Saskrita Secondary School / Surkhet / july, 2019 - February, 2020 </li> <li> <span>Social Media and IT coordinator||2023-2024</span><br> Leo Club of Kathmandu Matribhumi / Kathmandu / May, 2023 - 2024</li> <li> <span>Data Entry||2023</span><br>Vesvusa / Kathmandu / April, 2023 - May, 2023 </li> </ul> </div> <div class="tab-contents" id="education"> <ul> <li> <span>Bachelor of Information Technology||2021-2024</span><br> Phoenix College of Management / Kathmandu / February, 2021 - Present </li> <li> <span>+2(NEB)/2018-2020</span><br> Shree Krishna Saskrita Secondary School / Surkhet </li> <li> <span>School Level||2008-2018</span><br>Shree laxmi Secondary school Sattala, Dailekh </li> </ul> </div> </div> </div> </div> </div> <!-- service section start --> <!-- <div id="services"> <div class="container"> <h1 class="sub-title">My Services</h1> <div class="services-list"> <div> <i class="fa-solid fa-bars"></i> <h2>Web Design</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore incidunt mollitia aliquam non facere sed recusandae, temporibus ut est harum deleniti, vel nostrum ipsam sit in delectus ad laboriosam similique.</p> <a href="#">learn more</a> </div> <div> <i class="fa-regular fa-user"></i> <h2>Web Design</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore incidunt mollitia aliquam non facere sed recusandae, temporibus ut est harum deleniti, vel nostrum ipsam sit in delectus ad laboriosam similique.</p> <a href="#">learn more</a> </div> <div> <i class="fa-regular fa-bell"></i> <h2>Web Design</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore incidunt mollitia aliquam non facere sed recusandae, temporibus ut est harum deleniti, vel nostrum ipsam sit in delectus ad laboriosam similique.</p> <a href="#">learn more</a> </div> </div> </div> --> <!-- fortfolio --> <div id="portfolio"> <div class="container"> <h1 class="sub-title">My Work</h1> <div class="work-list"> <div class="work"> <img src="images/b.jpg"> <div class="layer"> <h3>Teacher</h3> <p>Shree Krishna Saskrita Secondary School / Surkhet / july, 2019 - February, 2020</p> <a href="images/a.jpg"><i class="fa-solid fa-arrow-up-right-from-square"></i></a> </div> </div> <div class="work"> <img src="images/c.jpg"> <div class="layer"> <h3> Social Media and IT coordinator</h3> <p>Leo Club of Kathmandu Matribhumi / Kathmandu / May, 2023 - 2024</p> <a href="images/c.jpg"><i class="fa-solid fa-arrow-up-right-from-square"></i></a> </div> </div> <div class="work"> <img src="images/d.jpg"> <div class="layer"> <h3>Extra-Curricular Activities</h3> <p>Participated in Soap,mask and sanitizer distribution program to needy people during Covid pandemic with family members.</p> <a href="images/d.jpg"><i class="fa-solid fa-arrow-up-right-from-square"></i></a> </div> </div> </div> <a href="#" class="btn">See more</a> </div> </div> <!-- contact --> <div id="contact"> <div class="container"> <div class="row"> <div class="contact-left"> <h1 class="sub-title">Contact Me</h1> <p><i class="fa-solid fa-paper-plane"></i>ghodasinihikmat88@gmail.com</p> <p><i class="fa-sharp fa-solid fa-square-phone"></i>9848485494</p> <div class="social-icons"> <a href="https://www.facebook.com/wishikdommat?mibextid=ZbWKwL"><i class="fa-brands fa-facebook"></i></a> <a href="https://instagram.com/hik_mat88?igshid=ZDdkNTZiNTM="><i class="fa-brands fa-instagram"></i></a> <a href="https://twitter.com/RajGhodasaini?t=1oMBiYxKJbRLrninnSk0Fg&s=09"><i class="fa-brands fa-twitter"></i></a> <a href="https://www.linkedin.com/in/hikmat-ghodasaini-a61a1420b"><i class="fa-brands fa-linkedin"></i></a> </div> <a href="cv.pdf" download class="btn btn2">Download CV</a> </div> <div class="contact-right"> <form name="submit-to-google-sheet"> <input type="text" name="Name" id="name" placeholder="Your Name" autocomplete="name" required> <input type="email" name="Email" id="email" placeholder="Your Email" autocomplete="email" required> <textarea name="Message" id="message" rows="6" placeholder="Your Message" autocomplete="message"></textarea> <button type="submit" class="btn btn2">Submit</button> </form> <span id="msg"></span> </div> </div> </div> <div class="copyright"> <p>Copyright © Hikmat Raj Ghodasaini <i class="fa-solid fa-heart"></i> thank you so much for visit my portfolio </p> </div> </div> <script> var tablinks = document.getElementsByClassName('tab-links'); var tabcontents = document.getElementsByClassName('tab-contents'); function opentab(tabname) { for (tablink of tablinks) { tablink.classList.remove("active-link") } for (tabcontent of tabcontents) { tabcontent.classList.remove("active-tab") } event.currentTarget.classList.add("active-link") document.getElementById(tabname).classList.add("active-tab") } </script> <script> var sidemenu=document.getElementById("menuclose()"); function openmenu(){ sidemenu.style.right="0" } function closemenu(){ sidemenu.style.right="-200px" } </script> <script> const scriptURL = 'https://script.google.com/macros/s/AKfycbwzYh7FuscN2VHcmte70-IXRDRz08q8861LKHa5lKxS-El8Kl6LzTk0MXyo-SGxpo2bxA/exec' const form = document.forms['submit-to-google-sheet'] const msg = document.getElementById("msg") form.addEventListener('submit', e => { e.preventDefault() fetch(scriptURL, { method: 'POST', body: new FormData(form)}) .then(response => { msg.innerHTML="Message sent successfully" setTimeout(function(){ msg.innerHTML="" },3000) form.reset() }) .catch(error => console.error('Error!', error.message)) }) </script> </body> </html>
#include <iostream> using namespace std; class Complex { int real; int img; public: Complex() { real=img=0; cout<<"parameterless constructor"<<endl; } Complex (int _real) { real=_real; img=0; cout<<"1-parameter constructor"<<endl; } Complex(int _real,int _img) { real=_real; img=_img; cout<<"2-parameter constructor"<<endl; } Complex(Complex const & c) { real=c.real; img=c.img; cout<<"copy constructor"<<endl; } void setReal(int _real) { real=_real; } void setImg(int _img) { img=_img; } void setcomplex(int _real,int _img) { real=_real; img=_img; } int getReal() { return real; } int getImg() { return img; } void print() { if (img>0) cout<<real<<"+"<<img<<"J"<<endl; else if (img<0) cout<<real<<img<<"J"<<endl; else cout<<real<<endl; } Complex operator+ (Complex const &c) //complex+complex { Complex res; res.real=real+c.real; res.img=img+c.img; return res; } Complex operator+ (int x) //complex+int { Complex res; res.real=real+x; res.img=img; return res; } Complex operator+=(Complex const &c) //complex+=complex { real=real+c.real; img=img+c.img; return *this; } Complex operator++() //prefix { real++; return *this; } Complex operator++(int) //postfix { Complex res(real,img); real++; return res; } explicit operator int(){ return real; } int operator==(Complex const & c) { return real==c.real && img==c.img; } int operator!=(Complex const & c) { return !(*this==c); } ~Complex() { cout<<"object destruction"<<endl; } }; Complex operator+(int left,Complex right); int main() { Complex c1(1,2),c2(5,6),c3,c4(1,2),c5(3,4),c6(3,4); c3=c1+c2; c3.print(); c4+=c5; c4.print(); c3=c1+3; c3.print(); c3=c1++; c3.print(); c3=++c1; c3.print(); c3=3+c2; c3.print(); int x; x=(int)c2; cout<<x; if(c2!=c5) cout<<"\nnot equal"; if(c6==c5) cout<<"\nequal\n"; return 0; } Complex operator+(int left,Complex right) { return right+left; }
using System.Diagnostics; using System.Reflection.Metadata.Ecma335; using System.Runtime.InteropServices; using System.Text; class WindowInfo { private delegate bool CallBackPtr(IntPtr hwnd, int lParam); [DllImport("user32.dll")] private static extern int EnumWindows(CallBackPtr callPtr, int lPar); [DllImport("user32.dll")] private static extern int EnumChildWindows(IntPtr hWnd, CallBackPtr lpEnumFunc, int lparam); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetWindowModuleFileName(IntPtr hWnd, StringBuilder pszFileName, int cchFileNameMax); [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd); private static List<IntPtr> EnumWindows() { var result = new List<IntPtr>(); EnumWindows(new CallBackPtr((hwnd, lParam) => { result.Add(hwnd); return true; }), 0); return result; } private static List<IntPtr> EnumChildWindows(IntPtr parent) { var result = new List<IntPtr>(); EnumChildWindows(parent, new CallBackPtr((hwnd, lParam) => { result.Add(hwnd); return true; }), 0); return result; } private static string? GetWindowText(IntPtr window) { var title = new StringBuilder(256); if (GetWindowText(window, title, title.Capacity) != 0) return title.ToString(); return null; } private static string? GetWindowModuleFileName(IntPtr window) { var name = new StringBuilder(256); if (GetWindowModuleFileName(window, name, name.Capacity) != 0) return name.ToString(); return null; } [StructLayout(LayoutKind.Sequential)] public struct Rect { public int left; public int top; public int right; public int bottom; } [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr hWnd, ref Rect lpRect); [DllImport("user32.dll")] private static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); public enum Presence { Foreground, Present, Minimized, Hidden }; private static Presence GetWindowPresence(IntPtr window) { if (IsIconic(window)) return Presence.Minimized; if (window == GetForegroundWindow()) return Presence.Foreground; if (IsWindowVisible(window)) return Presence.Present; return Presence.Hidden; } public enum DisplaySignificance { Full, Most, Half, Small, Fractional }; private static double? GetWindowRatio(IntPtr window) { var display = new Rect(); var app = new Rect(); if (!GetClientRect(GetDesktopWindow(), ref display)) return null; if (!GetClientRect(window, ref app)) return null; double disp_area = (display.right - display.left) * (display.bottom - display.top); double app_area = (app.right - app.left) * (app.bottom - app.top); return app_area / disp_area; } private static DisplaySignificance SignificanceAsEnum(double ratio) => ratio switch { (>= 0.8) and (<= 1) => DisplaySignificance.Full, (>= 0.65) and (< 0.8) => DisplaySignificance.Most, (>= 0.35) and (< 0.65) => DisplaySignificance.Half, (>= 0.15) and (< 0.35) => DisplaySignificance.Small, < 0.15 => DisplaySignificance.Fractional, _ => DisplaySignificance.Fractional }; public readonly DisplaySignificance displaySignificance; public readonly Presence displayPresence; public readonly string title; public readonly IntPtr handle; public readonly double displayRatio; public readonly string path; private WindowInfo(string title, Presence presence, DisplaySignificance significance, IntPtr handle, double ratio, string path) { this.title = title; this.displayPresence = presence; this.displaySignificance = significance; this.handle = handle; this.displayRatio = ratio; this.path = path; } public override string ToString() { var presence = displayPresence switch { Presence.Foreground => "in focus ", Presence.Present => "open ", Presence.Minimized => "minimized", Presence.Hidden => "hidden" }; if (displayPresence == Presence.Foreground || displayPresence == Presence.Present) { presence += displaySignificance switch { DisplaySignificance.Full => "taking full screen", DisplaySignificance.Most => "taking up most of the screen", DisplaySignificance.Half => "taking up half the screen", DisplaySignificance.Small => "", DisplaySignificance.Fractional => "taking up very little of the screen" }; } return String.Format("- {0}, {1}", title, presence); } private static WindowInfo? AssembleInfo(IntPtr wnd) { string? title = GetWindowText(wnd); if (title is null) return null; var presence = GetWindowPresence(wnd); var ratio = GetWindowRatio(wnd); if (ratio is null) return null; var significance = SignificanceAsEnum((double)ratio); string? path = GetWindowModuleFileName(wnd); if (path is null) path = ""; return new WindowInfo((string)title, presence, significance, wnd, (double)ratio, path); } public static List<WindowInfo> GetWindows() { var allWindows = new HashSet<IntPtr>(); var parents = EnumWindows(); foreach (IntPtr w in parents) { allWindows.Add(w); allWindows.Concat(EnumChildWindows(w)); } var allInfos = new List<WindowInfo>(); foreach (IntPtr w in allWindows) { var info = AssembleInfo(w); if (info is not null) allInfos.Add(info); } return allInfos; } public static List<WindowInfo> GetMajorWindows() { var windows = GetWindows() .Where(w => w.displayPresence != Presence.Hidden) .Where(w => !w.path.Contains("C:\\Windows\\System32")) .Where(w => !w.title.Contains("sessionmgr")) .OrderBy(w => 1.0 - w.displayRatio) .DistinctBy(w => w.handle) .DistinctBy(w => w.title) .ToList(); return (List<WindowInfo>)windows; } }
# 生物学的プロセスに関する可視化アプリケーションの開発 ## 背景(なぜやるのか) システム生物学における数理モデルは、生物学的プロセスやシステムの動態を表現し、理解を深めるためのツールとして重要である。 これらのモデルは数学的な方程式やネットワーク構造で表現され、シミュレーションや解析によって、生物学的プロセスの探求を可能にする。 しかし、これらの数理モデルのみで、反応のダイナミクスを理解することは困難である。 ## 目的(何を達成するのか) - 既存のアプリケーションには存在しない機能の実装 - 非専門家でも扱いやすい - 科学的発見の可能性を向上させる - より多くの人が理解できる形で表現する ## 方法(どうやって達成するか) ### BioModelsについて モデルの開発は、データ科学者と実験科学者の分析において、ますます一般的かつ重要なツールになっているため、異なるユーザのコミュニティない及び、コミュニティ間でモデルの共有t再利用を可能にすることから重要になっている。 数理モデルの有用な共有と交換を促進するために必要な最初のステップは、数理モデルをエンコードできる標準的な手段であり、これはモデルをエンコードするための機械可読な言語である「SBML」や「CellML」によって達成された。 そして、これらのモデルを保存、及び共有するためのリポジトリが「BioModels」である。 BioModelsは2006年に作成された生物学的に興味深い定量的モデルを保存、交換、取得するための無料オープンソースリポジトリである。 BioModelsは2つの主要なブランチで構成されており、モデルが表現しようとしている生物学的プロセスへの対応と、対応する査読済み出版物に記載されているシミュレーション結果の再現性の両方を検証するために、大規模なモデルのセットが厳選されている。 1. 文献に由来するモデルで構成されたブランチ 2. 自動プロセスを通じて生成されたブランチ 下図が示すように、2014年時点で1200を超えるモデルに加え、経路リソースから自動的に生成された140,000oを超えるモデルをホストしている。 BioModelsへのモデル送信料は年々増加しており、これは同時にモデリング分野の拡大を示している。 ![m_gku1181fig1](https://github.com/take331/sbml-visualizer/assets/73569757/45e4467a-f062-4f3c-a8fb-e2b7ff48e96c) Systems Biology Format Converter (SBFC)は、SBMLモデルを複数のモデリング言語やプログラミング言語のスクリプトに変換するためのツール群である(Rodriguez et al., 2016)。 BioModels Databaseは、SBFCを使用して、SBMLモデルの大規模なライブラリを、ユーザーがダウンロードできる他の形式に自動変換している( ### Systems Biology Markup Language (SBML) SBMLは生物学的プロセスの計算モデルを通信及び保存するための、XMLに基づく表現形式である SBMLは代謝ネットワーク、細胞シグナル伝達経路、制御ネットワーク感染症などを含む、様々な種類の生物学的現象を表すことができる SBMLには、おおきく3つの目的がある - すべてのツールの特異なファイル形式に準拠するようにモデルを書き直すことなく、複数のソフトウェアツールを使用できるようにする - 異なるソフトウェア環境で作業している場合でも他の研究者が使用できる形式でモデルを共有及び公開できるようにする - モデルの作成に使用されたソフトウェアの寿命を超えてモデルが確実に存続するようにする 以上より、SBMLの目的は、計算モデルの重要な側面を伝達するために現在の様々なソフトウェアツールで使用される交換形式である共通語として機能することである。 ### SBMLtoODEpy SBMLtoODEpyはSBMLモデルをPythonクラスに変換するソフトウェアパッケージである これは、Pythonで記述された生物医学システムに迅速に組み込んだり、直接シミュレートして使用することが出来る SBMLtoODEpyによって、Pythonのクラスを使用するコードを生成し、独自のコードを書いてインターフェースを作成する ### lib #### PySimpleGUI ## Todo - [x] SBMLファイルの変換 - [x] inputs_modelフォルダ内のファイルを表示 - [x] Browseボタンから、任意のSBMLファイルを選択 - [ ] 数式の表示 - [ ] テーブルの作成 - [ ] ネットワーク図 - [ ] アニメーションの実装 ### Small Tasks - [ ] 画面の最大化&高画質化 ## Usage 1. SBMLファイルのダウンロード [BioModels](https://www.ebi.ac.uk/biomodels/)からSBMLファイルをダウンロードする ダウンロードしたファイルはinputs_model内または、任意のディレクトリから参照することが可能 2. モデルの可視化 Importボタンをクリックして、SBMLファイルを変換する 変換したファイルは、プログラムに対応していくつかの機能によって可視化される 3. パラメータの変更 パラメータを変更して、再度可視化を行う 4. 保存 結果を様々な形式で保存する ## References - [BioModels](https://www.ebi.ac.uk/biomodels/) - [BioModels Database: An enhanced, reated nd annotated resource for published quantitative](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2909940/) - [BioModels ten-year anniversary](https://academic.oup.com/nar/article/43/D1/D542/2439069) - [SBMLtoODEpy](https://github.com/AnabelSMRuggiero/sbmltoodepy) - [Modeling formalisms in Systems Biology](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3285092/) - [Systems Biology: A Brief Overview](https://www.science.org/doi/10.1126/science.1069492?url_ver=Z39.88-2003&rfr_id=ori:rid:crossref.org&rfr_dat=cr_pub%20%200pubmed) - [From functional genomics to systems biology: concepts and practices](https://www.sciencedirect.com/science/article/pii/S1631069103002300)
import React, {useState, useContext} from "react"; import Style from "./Model.module.css"; //INTERNAL IMPORT import Image from "next/image"; import {images} from "../../assets"; import { Loader } from "../../Components/index"; import { ChatAppContext } from "../../Context/ChatAppContext"; const Model = ({openBox, title, address, head , info , smallinfo, image, functionName,}) => { const [name, setName] = useState(""); const [AccountAddress, setAccountAddress] = useState(""); const {loading} = useContext(ChatAppContext); return (<div className={Style.Model}> <div className={Style.Model_box}> <div className={Style.Model_box_left}> <Image src = {image} alt="buddy" width={700} height={700}/> </div> <div className={Style.Model_box_right}> <h1>{title} <span>{head}</span></h1> <p>{info}</p> <small>{smallinfo}</small> {loading == true ? (<Loader/>) : (<div className={Style.Model_box_right_name}> <div className={Style.Model_box_right_name_info}> <Image src = {images.username} alt="user" width={30} height={30}/> <input type = 'text' placeholder="your name" onChange={(e)=> setName(e.target.value)}/> </div> <div className={Style.Model_box_right_name_info}> <Image src = {images.account} alt="user" width={30} height={30}/> <input type = 'text' placeholder={address || "Enter address.."} onChange={(e)=> setAccountAddress(e.target.value)}/> </div> <div className={Style.Model_box_right_name_btn}> <button onClick={()=> functionName({name,AccountAddress})}> {""} <Image src={images.send} alt="send" width={30} height={30}/> {""} Submit </button> <button onClick={()=> openBox(false)}> {""} <Image src={images.close} alt="close" width={30} height={30}/> {""} Cancel </button> </div> </div>) } </div> </div> </div>); }; export default Model;
import './Item.css' import 'react-accessible-accordion/dist/fancy-example.css' import { useState, useEffect, useCallback } from 'react' import { useDispatch, useSelector } from 'react-redux' import { updateItem, selectItems } from '../../redux/slices/itemsSlice' import axios from 'axios' import DatePicker from 'react-date-picker' const { REACT_APP_SERVER_PORT } = process.env function Item(props) { const [item, setItem] = useState(props.thisItem) const [startDt, setStartDt] = useState(() => { return props.thisItem.startDate === null ? null : new Date(props.thisItem.startDate) }) const [endDt, setEndDt] = useState(() => { return props.thisItem.endDate === null ? null : new Date(props.thisItem.endDate) }) const items = useSelector(selectItems) const { setExpand } = props const dispatch = useDispatch() useEffect(() => { setItem((prev) => { return { ...prev, startDate: startDt === null ? null : startDt.toISOString(), endDate: endDt === null ? null : endDt.toISOString() } }) }, [startDt, endDt]) useEffect(() => { const curItem = items.find(({ itemId }) => itemId === item.itemId) if ( !( curItem.textContent === item.textContent && curItem.startDate === item.startDate && curItem.endDate === item.endDate && curItem.dun === item.dun ) ) { dispatch(updateItem(item)) axios.put(`http://localhost:${REACT_APP_SERVER_PORT}/items`, item) } else { } }, [item, items, dispatch]) function hdlDunChng(eve) { setItem((prev) => { return { ...prev, dun: eve.target.checked } }) if (setExpand && eve.target.checked) { setExpand(false) } } const focusNew = useCallback( (itemText) => { if (itemText && item.newItem) { itemText.focus() } }, [item.newItem] ) return ( <div className="dunit-item"> <div className="dunit-text" contentEditable suppressContentEditableWarning onKeyDown={(eve) => { if (eve.key === 'Enter') { eve.preventDefault() document.activeElement.blur() props.parentPlus(eve) } }} onBlur={(eve) => { setItem((prev) => { return { ...prev, textContent: eve.target.textContent } }) }} ref={focusNew} > {item.textContent} </div> <div className="dates"> <label> Start Date <DatePicker className="date-picker" onChange={(eve) => { setStartDt(eve) }} value={startDt} /> </label> <label> Due Date <DatePicker className="date-picker" onChange={(eve) => { setEndDt(eve) }} value={endDt} /> </label> </div> <div className="checkbox-container"> <input type="checkbox" id={"custom-checkbox" + item.itemId} className="custom-checkbox" checked={item.dun} onChange={hdlDunChng} /> <label htmlFor={"custom-checkbox" + item.itemId} className="checkbox-label"></label> <span className="checkbox-text"></span> </div> </div> ) } export default Item
#ifndef _ruban_h_ #define _ruban_h_ /** * Structure de données permettant de stcoker le ruban d'une machine de * Turing. Le ruban de la machine est une liste doublement chainée de * cases permettant l'écriture des symboles. * symbole -> le symbole contenu dans la case courante du ruban * gauche -> pointeur vers la case gauche de la case courante * droite -> pointeur vers la case droite de la case courante */ struct ruban_s { char symbole; struct ruban_s* droite; struct ruban_s* gauche; }; typedef struct ruban_s* ruban; /** * Initialise une case du ruban * @param symbole : le symbole contenu dans la case * @return la case créée et Initialisée */ ruban init_case_ruban(char symbole); /** * Ajoute une case à la gauche de la case courante du ruban * @param r : liste doublement chainée représentant le ruban * @param s : le symbole à ajouter au ruban * @return un pointeur vers la case du ruban ajoutée, NULL en cas d'erreur */ ruban ruban_ajouter_gauche(ruban case_courante, char symbole); /** * Ajoute une case à la droite de la case courante du ruban * @param r : liste doublement chainée représentant le ruban * @param s : le symbole à ajouter au ruban * @return un pointeur vers la case du ruban ajoutée, NULL en cas * d'erreur */ ruban ruban_ajouter_droite(ruban case_courante, char symbole); /** * Initialise un ruban à partir d'un mot d'entrée * @param mot : le mot d'entrée * @return le ruban Initialisé */ ruban init_ruban(char *mot); /** * Affiche la configuration courante d'un ruban d'une machine de Turing * @param r : le ruban à afficher */ void afficher_ruban(ruban case_courante); /** * Libère l'espace mémoire allouée pour un ruban * @param r : l'espace mémoire à désallouer */ void free_ruban(ruban r); #endif
import { TwitterFollowCard } from "./components/TwitterFollowCard" const users = [ { id: 1, userName: 'midudev', name: 'Miguel Ángel Durán', isFollowing: true }, { id: 2, userName: 'Guillem_Frutem', name: 'Guillem The Frutem', isFollowing: false }, { id: 3, isFollowing: true }, { id: 4, userName: 'TMChein', name: 'Tomas', isFollowing: false } ] export function App() { const formatUserName = (userName) => `@${userName}` return ( <section className='App'> { users.map(({ id, userName, name, isFollowing }) => ( <TwitterFollowCard formatUserName={formatUserName} key={id} userName={userName} initialIsFollowing={isFollowing} > {name} </TwitterFollowCard> )) } </section> ) } // export function App() { // const formatUserName = (userName) => `@${userName}` // return ( // <div className="App"> // <TwitterFollowCard // formatUserName={formatUserName} // userName={"midudev"} // name={"midudev"} // initialIsFollowing={true} // /> // <TwitterFollowCard // formatUserName={formatUserName} // userName={"shanksfgc"} // name={"shanks"} // /> // <TwitterFollowCard // formatUserName={formatUserName} // userName={"Guillem_Frutem"} // name={"Guillem The Frutem"} // initialIsFollowing={true} // /> // <TwitterFollowCard // formatUserName={formatUserName} // /> // {/* Así se usan comentarios dentro de jsx */} // </div> // ) // }
import React, { useEffect, useRef, useState } from 'react'; import { ButtonDropdown } from '../button/button'; import { Checkbox, Radio, Space, Dropdown as AntDropdown, Select } from 'antd'; import PropTypes from 'prop-types'; import styles from './dropdown.module.css'; import Text from '../text/text'; import Label from '../label/label'; import { IconChevronDown } from '../icons'; import { Loader } from '../loader/loader'; /** * Radio Dropdown * @param options - Array: [{ name: string | number, value: string | number }] * @param label - string * @param value - Selected item * @param onChange - Callback * @param error - string * @param required - bool * @param name - string * @param placeholder - string * @param width - If not set, 100% by default */ export const RadioDropdown = ({ name, options, label, placeholder, width, onChange, error, required, labelInfo, value, ...props }) => { const [showDropdown, setShowDropdown] = useState(false); const [valueOption, setValueOption] = useState(); // onlu for story book test const [buttonText, setButtonText] = useState(null); const errorClass = error ? 'error-field' : ''; const menuRef = useRef(null); const menuButtonRef = useRef(null); const handleChange = (e) => { setValueOption(e.target.value); onChange(e); }; const handleBlurMenu = (event) => { if ( menuRef.current && menuButtonRef.current && !menuRef.current.contains(event.target) && !menuButtonRef.current.contains(event.target) ) { setShowDropdown(false); } }; useEffect(() => { document.addEventListener('click', handleBlurMenu); }, []); return ( <div style={{ width }}> <div className={'dropdown-container'}> {label && <Label label={label} required={required} info={labelInfo} />} <span ref={menuButtonRef}> <ButtonDropdown placeholder={placeholder} text={buttonText ? buttonText : value} onClick={(e) => { e.preventDefault(); setShowDropdown(!showDropdown); }} open={showDropdown} className={errorClass} {...props} /> </span> </div> {showDropdown && ( <div className={styles['radio-dropdown']} ref={menuRef}> <div className={styles['radio-dropdown-options']}> <Radio.Group defaultValue={value} onChange={handleChange} className="w-full" > <Space direction="vertical" className="w-full"> {options.map((option, index) => ( <Radio name={name} key={index} value={option.value} className={`${styles['dropdown-radio-item']} ${ option.value === valueOption && styles['checked'] }`} onChange={() => setButtonText(option.label)} > {option.label} </Radio> ))} </Space> </Radio.Group> </div> </div> )} {error && ( <Text variant={'paragraph-tiny'} className={'error-field-text'}> {error} </Text> )} </div> ); }; RadioDropdown.propTypes = {}; /** * Checkbox Dropdown * @param name * @param options - Array: [{ name: string | number, value: string | number }] * @param label - string * @param value - Selected items * @param onChange - Callback * @param width - If not set, 100% by default * @param props */ export const CheckboxDropdown = ({ name, error, options, label, onChange, value, width, required, placeholder, labelInfo, displayLabel, ...props }) => { const [showDropdown, setShowDropdown] = useState(false); const errorClass = error ? 'error-field' : ''; const menuRef = useRef(null); const menuButtonRef = useRef(null); const handleBlurMenu = (event) => { if ( menuRef.current && menuButtonRef.current && !menuRef.current.contains(event.target) && !menuButtonRef.current.contains(event.target) ) { setShowDropdown(false); } }; useEffect(() => { document.addEventListener('click', handleBlurMenu); return () => { document.removeEventListener('click', handleBlurMenu); }; }, []); const handleChange = (e) => { onChange(e); }; return ( <div style={{ width }}> {label && <Label label={label} required={required} info={labelInfo} />} <div className="" ref={menuButtonRef}> <ButtonDropdown placeholder={placeholder} text={ value.length && displayLabel ? ( <div className="flex-y-center gap-sm"> {value.map( (val) => options.find((opt) => opt.value === val).label )} </div> ) : ( value.join(', ') ) } onClick={(e) => { e.preventDefault(); setShowDropdown(!showDropdown); }} open={showDropdown} className={errorClass} data-testid={props['data-testid'] || 'checkbox-dropdown'} /> </div> {showDropdown && ( <div className={styles['radio-dropdown']}> <div className={styles['radio-dropdown-options']}> <Checkbox.Group className="w-full" onChange={handleChange} value={value} {...props} ref={menuRef} > <Space direction="vertical" className="w-full"> {options.map((option, index) => ( <Checkbox name={name} key={index} value={option.value} className={`${ styles['dropdown-radio-item'] } flex-y-center ${ value.includes(option.value) && styles['checked'] }`} checked={true} disabled={option.disabled} > {option.label} </Checkbox> ))} </Space> </Checkbox.Group> </div> </div> )} <div> {error && ( <Text variant={'paragraph-tiny'} className={'error-field-text text-left'} > {error} </Text> )} </div> </div> ); }; CheckboxDropdown.propTypes = { options: PropTypes.array.isRequired, label: PropTypes.string.isRequired, onChange: PropTypes.func, width: PropTypes.string, }; export default CheckboxDropdown; /** * Dropdown * @param name * @param items - Array: [{ name: string | number, value: string | number }] * @param label - string * @param value - Selected items * @param onChange - Callback * @param width - If not set, 100% by default * @param props */ export const Dropdown = ({ name, items, label = '', onChange, width, required, value, error, labelInfo, buttonClassName, hoverPrimary, ...props }) => { const [showDropdown, setShowDropdown] = useState(false); const handleChange = (key) => { onChange(key); setShowDropdown(false); }; const _items = items.map(({ label, key, disabled }) => { return { label: ( <button className={`w-full px-sm py-sm btn-dropdown-item`} onClick={() => handleChange(key)} data-testid={`dropdown-item-${key}`} disabled={disabled} > {label} </button> ), key: key, }; }); return ( <div style={{ width }}> {label && <Label label={label} required={required} info={labelInfo} />} <AntDropdown menu={{ items: _items, className: styles['radio-dropdown-options'], }} trigger={['click']} open={showDropdown} onOpenChange={() => setShowDropdown(!showDropdown)} overlayClassName={hoverPrimary ? 'hover-primary' : ''} > <ButtonDropdown placeholder={label} text={value} onClick={(e) => { e.preventDefault(); setShowDropdown(!showDropdown); }} open={showDropdown} style={{ border: error && '1px solid var(--red)' }} className={buttonClassName} {...props} /> </AntDropdown> <div> {error && ( <Text variant={'paragraph-tiny'} className={'error-field-text text-left'} > {error} </Text> )} </div> </div> ); }; Dropdown.propTypes = { items: PropTypes.array.isRequired, label: PropTypes.string, onChange: PropTypes.func, width: PropTypes.string, }; /** * Dropdown * @param name * @param items - Array: [{ name: string | number, value: string | number }] * @param label - string * @param value - Selected items * @param onChange - Callback * @param width - If not set, 100% by default * @param required * @param error * @param props */ export const DropdownSearch = ({ name, items, label, onChange, value, width, required, error, labelInfo, ...props }) => { const handleChange = (item) => { onChange(item); }; return ( <div style={{ width }}> {label && <Label label={label} required={required} info={labelInfo} />} <Select showSearch placeholder={label} data-testid={label} className={styles['select-dropdown-antd']} optionFilterProp="children" filterOption={(input, option) => (option?.label.toLowerCase() ?? '').includes(input.toLowerCase()) } filterSort={(optionA, optionB) => (optionA?.label ?? '') .toLowerCase() .localeCompare((optionB?.label ?? '').toLowerCase()) } options={items} suffixIcon={ <> {items.length === 0 && <Loader size={24} />} <IconChevronDown size={8} style={{ color: 'var(--dark)' }} /> </> } value={value || undefined} onChange={handleChange} {...props} /> <div> {error && ( <Text variant={'paragraph-tiny'} className={'error-field-text text-left'} > {error} </Text> )} </div> </div> ); }; DropdownSearch.propTypes = { items: PropTypes.array.isRequired, label: PropTypes.string.isRequired, onChange: PropTypes.func, width: PropTypes.string, };
import Component from '@glimmer/component'; interface ArgsInterface { index: number; // subject arguments subject: { uri: string; class: string; className: string; usedShape?: string; shapeName?: string; totalCount: number; properties: Array<object>; validCount?: number; }; } export default class RecursiveEntry extends Component<ArgsInterface> { get skin() { const { validCount, totalCount } = this.args.subject; return validCount !== undefined ? validCount! == totalCount! ? this.isCorrect ? 'success' : 'success' : 'error' : 'default'; } get isPdf() { return this.args.subject.uri.endsWith('.pdf'); } get classNames() { const { validCount, totalCount } = this.args.subject; return validCount === totalCount && 'au-c-pill--whole' && !this.isCorrect; } get pillMessage() { const { validCount, totalCount } = this.args.subject; return validCount !== undefined ? validCount! == totalCount! ? this.isCorrect ? 'Correct' : 'Volledig' : 'Onvolledig' : 'Niet gevalideerd'; } get formattedName() { const { shapeName, className } = this.args.subject; return className || shapeName || name || 'Unvalidated subject'; } get displayCounts() { const { validCount, totalCount } = this.args.subject; if (validCount !== undefined && totalCount !== undefined) { return `${validCount}/${totalCount}`; } else if (totalCount !== undefined) { return totalCount.toString(); } return ''; } get displayIndex() { if (this.args.index === undefined) return ''; return this.args.index + 1; } get isCorrect() { const { properties } = this.args.subject; // eslint-disable-next-line @typescript-eslint/no-explicit-any return properties ? properties.every((v: any) => v.valid === true) : true; } get displayURI() { return this.args.subject.uri || ''; } get hasURL() { return !!this.args.subject.uri; } get countText() { const { validCount, totalCount } = this.args.subject; // When validCount and totalCount are both available if (validCount !== undefined && totalCount !== undefined) { return `${validCount}/${totalCount}`; } // When only totalCount is available if (totalCount !== undefined && validCount === undefined) { return totalCount; } return ''; } }
const express = require('express') const router = express.Router() require('../../config/passport') const passport = require('passport') const requireAuth = passport.authenticate('jwt', { session: false }) const trimRequest = require('trim-request') const { roleAuthorization } = require('../controllers/auth') const { getAllRegiones, getRegiones, createRegion, getRegion, updateRegion, deleteRegion } = require('../controllers/regiones') const { validateCreateRegion, validateGetRegion, validateUpdateRegion, validateDeleteRegion } = require('../controllers/regiones/validators') /* * Cities routes */ /* * Get all items route */ router.get('/all', getAllRegiones) /* * Get items route */ router.get( '/', requireAuth, roleAuthorization(['admin']), trimRequest.all, getRegiones ) /* * Create new item route */ router.post( '/', requireAuth, roleAuthorization(['admin']), trimRequest.all, validateCreateRegion, createRegion ) /* * Get item route */ router.get( '/:id', requireAuth, roleAuthorization(['admin']), trimRequest.all, validateGetRegion, getRegion ) /* * Update item route */ router.patch( '/:id', requireAuth, roleAuthorization(['admin']), trimRequest.all, validateUpdateRegion, updateRegion ) /* * Delete item route */ router.delete( '/:id', requireAuth, roleAuthorization(['admin']), trimRequest.all, validateDeleteRegion, deleteRegion ) module.exports = router
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; error ReentrantCall(); /** * @title Reentrancy guard * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier available, which can be applied to functions to make sure there are no * nested (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as `nonReentrant` may not call one another. This can be worked around * by making those functions `private`, and then adding `external` `nonReentrant` entry points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways to protect against it, check out the blog post * [Reentrancy After Istanbul](https://blog.openzeppelin.com/reentrancy-after-istanbul/). */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full word because each write operation emits an extra SLOAD to first // read the slot's contents, replace the bits taken up by the boolean, and then write back. This is the compiler's defense against contract // upgrades and pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, but in exchange the refund on every call to nonReentrant will be lower // in amount. Since refunds are capped to a percentage of the total transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true if(_status == _ENTERED) revert ReentrantCall(); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // 26947/26935
<!-- Starting HTML code --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>RJ Portfolio</title> <!-- Link to the css code --> <link rel="stylesheet" href="style.css"> <!-- Link for custom fonts --> <script src="https://kit.fontawesome.com/c3585a39c9.js" crossorigin="anonymous"></script> </head> <!-- Main home page section --> <body> <div id="header"> <div id="home"> <header class="header"> <header class="navbar"> <!-- Declaring the nav bar at the top of the home page --> <nav class = bar2> <!-- Main logo for the portfolio --> <img src = "Images/MainLogo.png" class = "logo"> <!-- Nav bar sections --> <ul> <li> <a href="#home">Home</a> </li> <li> <a href="#about">About</a> </li> <li> <a href="#contact">Contact</a> </li> </ul> </nav> <!-- Welcome text --> <div class="header-text"> <p>Hi, I am Rupanjay Badoni </p> <div class="static-txt"> And I am a</div> <ul class = "dynamic-txts"> <li> <span> Student </span> </li> <li> <span> Programmer </span></li> <li> <span> Developer </span> </li> <li> <span> Youtuber </span></li> </ul> </div> <!-- Link for the CV --> <a href="Images/RJ CV.pdf" download class="btn">Download CV</a> </div> </div> </div> </div> <!-- About section --> <div id="about"> <div class="container"> <div class="row"> <!-- Defining the first section in the about page with the main image --> <div class="about1"> <img src="Images/AboutSection.png"> </div> <!-- Defining the section with all the text in the about page --> <div class="about2"> <h1 class="subtitle"> About Me </h1> <p> Welcome to my portfolio! I am a computing student from Bath Spa university on a mission to conquer the tech world. With a passion for problem-solving and creativity, I have been learning how to code and develop various projects. From software development to data analysis, I love it all. I believe technology can be a force for good, and I am determined to create solutions that improve lives. Collaboration is essential to innovation, and I thrive in team settings. Learning from my peers and mentors is a priority, as the tech world is always evolving. Thank you for being here, and I am excited to show you my journey and showcase my skills through this portfolio. </p> <!-- Adding two different nav bar for the about page --> <div class="tabtitles"> <p class="tab-links active-link" onclick="opentab('skills')">Skills</p> <p class="tab-links" onclick="opentab('education')"> Education</p> </div> <div class="tab-contents active-tab" id="skills"> <ul> <li><span>Programming Languages</span><br>Python,CSS,JavaScript,HTML</li> <li><span>Problem Solving</span><br> Using different logics and algorithms</li> <li><span>Web Developement</span><br>Learning to use web technologies like HTML,CSS and JavaScript</li> <li><span>User Interface Design</span><br>Familiar with designing user-friendly interfaces and user experience</li> </ul> </div> <!-- Defining the education tab in the About section --> <div class="tab-contents" id="education"> <ul> <li><span>2018-2020</span><br>GCSEs</li> <li><span>2020-2022</span><br>A-level</li> <li><span>2022-Present</span><br>BA in Computing</li> </ul> </div> </div> </div> </div> </div> <!-- Contact page section --> <div id="contact"> <div class="container"> <div class="row"> <!-- Defining the right side of the contact page --> <div class="contact-right"> <form action="https://formsubmit.co/30223571d9d068a279c9b6046abc4f02" method="POST"> <input type="text" name="Name" placeholder="Your Name" required> <input type="email" name="Email" placeholder="Your Email " required> <textarea name="message" rows="6" placeholder="Your Message"></textarea> <button type="submit" class="button">Submit</button> </form> </div> <!-- Defining the left side of the contact page --> <div class="contact-left"> <h1 class="subtitle">Contact Me</h1> <p>rupanjaybadoni@gmail.com</p> <p>0123456789</p> <div class="social-icons"> <a href=""><i class="fa-brands fa-facebook"></i></a> <a href=""><i class="fa-brands fa-twitter-square"></i></a> <a href=""><i class="fa-brands fa-instagram"></i></a> <a href=""><i class="fa-brands fa-linkedin"></i></a> </div> </div> </div> <!-- Copyright mark --> <div class="copyright"> <p> Copyright © RJ Badoni</p> </div> </div> </div> <!-- JavaScript for About section --> <script> var tablinks = document.getElementsByClassName("tab-links"); var tabcontents = document.getElementsByClassName("tab-contents"); function opentab(tabname){ for(tablink of tablinks){ tablink.classList.remove("active-link"); } for(tabcontent of tabcontents){ tabcontent.classList.remove("active-tab"); } event.currentTarget.classList.add("active-link"); document.getElementById(tabname).classList.add("active-tab"); } </script> <!-- JavaScript for scrolling --> <section class = "banner"></section> <script type="text/JavaScript"> window.addEventListener("scroll",function()){ var header = document.querySelector("header"); header.classList.toggle("sticky",window.scrollY > 0); } </script> <script src="https://smtpjs.com/v3/smtp.js"></script> <script> function sendEmail(){ Email.send({ Host : "smtp.gmail.com", Username : "kiethchilton@gmail.com", Password : "Rupanjay@123", To : 'rupanjaybadoni@gmail.com', From : document.getElementById("email").value, Subject : "New Contact Form Enquiry", Body : "Name" + document.getElementById("text").value + "<br> Email:" + document.getElementByID("email").value + "<br> Message:" + document.getElementByID("message").value }).then( message => alert("Message Sent Succesfully") ); } </script> </body> </html>
// Lprs - A local CLI vaults manager. For human and machine use // Copyright (C) 2024 Awiteb <a@4rs.nl> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>. use std::collections::BTreeMap; use std::{fs, path::PathBuf}; use inquire::{validator::Validation, Password, PasswordDisplayMode}; use passwords::{analyzer, scorer}; #[cfg(feature = "update-notify")] use reqwest::blocking::Client as BlockingClient; use sha2::Digest; use crate::vault::Vault; use crate::{LprsError, LprsResult}; /// Returns the local project dir joined with the given file name /// /// ## Errors /// - If the project dir can't be extracted from the OS /// - If the local project dir can't be created pub fn local_project_file(filename: &str) -> LprsResult<PathBuf> { let local_dir = directories::ProjectDirs::from("", "", "lprs") .map(|d| d.data_local_dir().to_path_buf()) .ok_or_else(|| { LprsError::ProjectDir("Can't extract the project_dir from this OS".to_owned()) })?; log::debug!("Local project dir: {:?}", local_dir.display()); if !local_dir.exists() { log::info!("Creating the local project dir: {:?}", local_dir.display()); fs::create_dir_all(&local_dir)?; } Ok(local_dir.join(filename)) } /// Returns the user secret if any /// /// - If the `secret` is `None` will return `None` /// - If the `secret` is `Some(None)` will ask the user for a secret in the /// stdin and return it /// - If the `secret` is `Some(Some(secret))` will return `Some(secret)` /// /// ## Errors /// - When failed to get the secret from stdin pub fn user_secret( secret: Option<Option<String>>, prompt_message: &str, confirmation: bool, ) -> LprsResult<Option<String>> { Ok(match secret { None => None, Some(Some(p)) => Some(p), Some(None) => { log::debug!("User didn't provide a secret, prompting it"); Some( Password { enable_confirmation: confirmation, ..Password::new(prompt_message) .with_formatter(&|p| "*".repeat(p.chars().count())) .with_display_mode(PasswordDisplayMode::Masked) } .prompt()?, ) } }) } /// Returns the default vaults json file /// /// ## Errors /// - If the project dir can't be extracted from the OS /// - If the vaults file can't be created pub fn vaults_file() -> LprsResult<PathBuf> { let vaults_file = local_project_file(crate::DEFAULT_VAULTS_FILE)?; if !vaults_file.exists() { fs::File::create(&vaults_file)?; } Ok(vaults_file) } /// Validate the password /// /// ## To pass /// - The length must be higher than 14 (>=15) /// - Its score must be greater than 80.0 /// /// ## Errors /// - There is no errors, just the return type of inquire validator must be /// Result<Validation, inquire::CustomUserError> pub fn password_validator(password: &str) -> Result<Validation, inquire::CustomUserError> { let analyzed = analyzer::analyze(password); Ok(if analyzed.length() < 15 { Validation::Invalid("The master password length must be beggier then 15".into()) } else if scorer::score(&analyzed) < 80.0 { Validation::Invalid("Your master password is not stronge enough".into()) } else { Validation::Valid }) } /// Ask the user for the master password, then returns it /// /// ## Errors /// - Can't read the password from the user /// /// Return's the password as 32 bytes after hash it (256 bit) pub fn master_password_prompt(is_new_vaults_file: bool) -> LprsResult<[u8; 32]> { inquire::Password { message: "Master Password:", enable_confirmation: is_new_vaults_file, validators: if is_new_vaults_file { vec![Box::new(password_validator)] } else { vec![] }, ..inquire::Password::new("") } .with_formatter(&|p| "*".repeat(p.chars().count())) .with_display_mode(PasswordDisplayMode::Masked) .prompt() .map(|p| sha2::Sha256::digest(p).into()) .map_err(Into::into) } /// Retuns the current lprs version from `crates.io` /// /// ## Errors /// - The project dir can't be extracted from the OS /// - If the last version check file can't be created #[cfg(feature = "update-notify")] pub fn lprs_version() -> LprsResult<Option<String>> { use std::time::SystemTime; let last_version_check_file = local_project_file(crate::LAST_VERSION_CHECK_FILE)?; let current_time = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .map_err(|_| LprsError::Other("The system time is before UNIX EPOCH!".to_owned()))? .as_secs(); let last_check: u64 = fs::read_to_string(&last_version_check_file) .unwrap_or_else(|_| current_time.to_string()) .parse() .map_err(|err| { LprsError::Other(format!( "Check update file content is invalid time `{}`: {err}", last_version_check_file.display() )) })?; fs::write(last_version_check_file, current_time.to_string())?; // Check if the last check is before one hour or not if (current_time - last_check) >= (60 * 60) || current_time == last_check { if let Ok(Ok(response)) = BlockingClient::new() .get("https://crates.io/api/v1/crates/lprs") .header( "User-Agent", format!("Lprs <{current_time}> (https://git.4rs.nl/awiteb/lprs)"), ) .send() .map(|r| r.text()) { let re = regex::Regex::new(r#""max_stable_version":"(?<version>\d+\.\d+\.\d+)""#) .expect("The regex is correct"); if let Some(cap) = re.captures(&response) { return Ok(cap.name("version").map(|m| m.as_str().to_string())); } } } Ok(None) } /// Returns the duplicated field from the custom field (unprocessed fields) pub fn get_duplicated_field(fields: &[(String, String)]) -> Option<&str> { fields.iter().find_map(|(key, _)| { if fields.iter().filter(|(k, _)| key == k).count() > 1 { return Some(key.as_str()); } None }) } /// Apply the edited fields to the vault fields. /// This will: /// - Add the field if it's not in the fields map. /// - Update the field if it's in the map. /// - Remove the field if its value is empty string. pub fn apply_custom_fields( fields: &mut BTreeMap<String, String>, edited_fields: Vec<(String, String)>, ) { for (key, value) in edited_fields { if fields.contains_key(&key) && value.is_empty() { fields.remove(&key); } else { // The field is not there or its value not empty, // so add it or update its value fields.insert(key, value); } } } /// Returns the vault with its index by its index or name /// /// ## Errors /// - If there is no vault with the given index or name pub fn vault_by_index_or_name<'a>( index_or_name: &str, vaults: &'a mut [Vault], ) -> LprsResult<(usize, &'a mut Vault)> { let parsed_index = index_or_name.parse::<usize>(); let Some((index, vault)) = (if let Ok(index) = parsed_index { index .checked_sub(1) .and_then(|zeroindex| vaults.get_mut(zeroindex).map(|v| (index, v))) } else { vaults .iter_mut() .enumerate() .find(|(_, v)| v.name == index_or_name) }) else { return Err(LprsError::Other(format!( "There is no vault with the given {} `{}`", if parsed_index.is_ok() { "index" } else { "name" }, index_or_name, ))); }; Ok((index, vault)) }
import { yupResolver } from "@hookform/resolvers/yup"; import FileUploader from "components/form/FileUploader"; import Input from "components/form/Input"; import Select from "components/form/Select"; import React, { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { useDispatch, useSelector } from "react-redux"; import { fetchBook, fetchBookCategory } from "store/bookSlice"; import { v4 as uuidv4 } from "uuid"; import moment from "moment"; import { downloadImage, insertTable, updateBook, uploadImage, } from "services/supabaseFunction"; import { useNavigate, useParams } from "react-router-dom"; import { bookSchema } from "constants/formSchema"; const AddEditBook = ({ isEdit }) => { const navigate = useNavigate(); const { book } = useSelector((state) => state.book); const [bookData, setBookData] = useState(null); const { book_category } = useSelector((state) => state.book); const [imagePreview, setImagePreview] = useState(""); const dispatch = useDispatch(); const params = useParams(); useEffect(() => { dispatch(fetchBookCategory()); dispatch(fetchBook()); // eslint-disable-next-line react-hooks/exhaustive-deps }, [dispatch]); useEffect(() => { if (isEdit) { const bookDetail = book.find((item) => item.id === +params.id); setBookData(bookDetail); if (bookData?.cover) downloadImage("cover", bookData.cover, setImagePreview); reset(bookData); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [book]); const { register, handleSubmit, setValue, reset, formState: { errors }, } = useForm({ resolver: yupResolver(bookSchema), }); const submitForm = (data) => { let fileName; if (data.cover instanceof File) { const file = data.cover; const fileExt = file.name.split(".").pop(); fileName = `${uuidv4()}.${fileExt}`; uploadImage("cover", fileName, file); } else { fileName = data.cover; } const slug = data.title.split(" ").join("-").toLowerCase(); const currentDate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss"); const newBookData = { ...data, slug, cover: fileName, created_at: isEdit ? bookData.created_at : currentDate, updated_at: currentDate, }; delete newBookData.book_category; if (isEdit) { updateBook(newBookData, params.id); } else { insertTable("book", newBookData); } console.log(newBookData) reset(); navigate("/dashboard/book"); }; const imageHandler = (e) => { const fileReader = new FileReader(); const file = e.target.files[0]; const fileType = file.type; const validExtensions = ["image/jpeg", "image/jpg", "image/png"]; if (validExtensions.includes(fileType)) { fileReader.onload = (e) => { const fileUrl = fileReader.result; setImagePreview(fileUrl); }; fileReader.readAsDataURL(file); } else { alert("file should be image"); } }; return ( <> <h1 className="text-2xl font-bold">Add Book</h1> <form onSubmit={handleSubmit(submitForm)}> <div className="flex gap-x-8 mt-4 mx-8 py-6 md:flex-row flex-col"> <div className="flex-[2]"> <h4 className="text-xl font-semibold mb-2">Book Cover</h4> <FileUploader {...register("cover")} name="cover" accept="image/*" onChange={(e) => { imageHandler(e); setValue("cover", e.target.files[0], { shouldValidate: true, }); }} image={imagePreview} errors={errors.cover?.message} /> <div className="mt-4"> <button type="submit" className="px-6 py-2 bg-primary rounded-md text-white font-semibold w-full cursor-pointer" > {isEdit ? 'Update Book' : 'Add Book'} </button> </div> </div> <div className="flex-[4]"> <Input {...register("title")} spacing={6} label="Title" type="text" placeholder="Enter book title" color="yellow-400" name="title" errors={errors.title?.message} rounded={+false} /> <Input {...register("release_year")} spacing={6} label="Release Year" type="text" placeholder="Enter book release" color="yellow-400" name="release_year" errors={errors.release_year?.message} rounded={+false} /> <Input {...register("author")} spacing={6} label="Author" type="text" placeholder="Enter book author" color="yellow-400" name="author" errors={errors.author?.message} rounded={+false} /> <div className="flex gap-x-8"> <Input {...register("price")} className="flex-[2]" spacing={6} label="Price" type="number" placeholder="Enter book price" color="yellow-400" name="price" errors={errors.price?.message} rounded={+false} /> <Input {...register("discount")} className="flex-[1]" spacing={6} label="Discount" type="number" placeholder="Enter book discount" color="yellow-400" name="discount" errors={errors.discount?.message} rounded={+false} step={0.1} /> <Input {...register("stock")} className="flex-[1]" spacing={6} label="Stock" type="number" placeholder="Enter book stock" color="yellow-400" name="stock" errors={errors.stock?.message} rounded={+false} /> </div> <div className="flex"> <Select {...register("book_category_id")} onChange={(e) => setValue("book_category_id", +e.target.value, { shouldValidate: true, }) } label="Book Category" name="book_category_id" spacing={6} optionheader="Select book category" options={book_category} errors={errors.book_category_id?.message} /> </div> </div> </div> </form> </> ); }; export default AddEditBook;
package com.scholarsync.server.controllers; import com.scholarsync.server.dtos.ProfileDTO; import com.scholarsync.server.entities.User; import com.scholarsync.server.repositories.UserRepository; import com.scholarsync.server.services.UserService; import java.io.IOException; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @RestController @RequestMapping("/api/v1/users") public class UserController { @Autowired private UserRepository userRepository; @Autowired private UserService userService; @GetMapping public List<User> getAllUsers() { return userRepository.findAll(); } @PostMapping("/get-id-by-username") public ResponseEntity<Object> getIdByUsernames(@RequestBody Map<String, String> username) { return userService.getIdByUsername(username); } @GetMapping("/profile/{id}") public ProfileDTO getProfileInfo(@PathVariable String id) { return userService.getProfileInfo(id); } @PostMapping("/update-profile-picture") public ResponseEntity<Object> updateProfilePicture( @RequestParam(name = "picture") MultipartFile picture, @RequestParam(name = "user_id") String userId) throws IOException { return userService.updateProfilePicture(picture, userId); } @GetMapping("/get-profile-picture") public ResponseEntity<Object> getProfilePicture(@RequestParam(name = "user_id") String userId) { return userService.getProfilePicture(userId); } }
import 'package:codingchef_getx_login_fb_lecture/controller/auth_controller.dart'; import 'package:codingchef_getx_login_fb_lecture/screens/signup.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:get/get.dart'; class LoginPage extends StatelessWidget { const LoginPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { var emailController = TextEditingController(); var passwordController = TextEditingController(); return Scaffold( backgroundColor: Colors.grey[300], body: SafeArea( child: Center( child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon( Icons.phone_android, size: 100, ), const SizedBox( height: 30, ), Text( 'Hello', style: GoogleFonts.bebasNeue(fontSize: 36.0), ), const SizedBox( height: 10, ), const Text( 'Welcome back', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), const SizedBox( height: 50, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 25.0), child: Container( decoration: BoxDecoration( color: Colors.grey[200], border: Border.all(color: Colors.white), borderRadius: BorderRadius.circular(12), ), child: Padding( padding: const EdgeInsets.only(left: 20.0), child: TextField( controller: emailController, decoration: const InputDecoration( border: InputBorder.none, hintText: 'Email'), ), ), ), ), const SizedBox( height: 10, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 25.0), child: Container( decoration: BoxDecoration( color: Colors.grey[200], border: Border.all(color: Colors.white), borderRadius: BorderRadius.circular(12)), child: Padding( padding: const EdgeInsets.only(left: 20.0), child: TextField( controller: passwordController, obscureText: true, decoration: const InputDecoration( border: InputBorder.none, hintText: 'Password'), ), ), ), ), const SizedBox( height: 10, ), GestureDetector( onTap: () { AuthController.instance.login( emailController.value.text.trim(), passwordController.value.text.trim()); }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 25.0), child: Container( padding: const EdgeInsets.all(20), decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(12)), child: const Center( child: Text( 'Sign in', style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold), ), ), ), ), ), const SizedBox( height: 25, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text('Not a member?'), GestureDetector( onTap: () => Get.to(() => const SignupPage()), child: const Text( ' Register Now!', style: TextStyle( color: Colors.blue, fontWeight: FontWeight.bold), ), ) ], ) ], ), ), ), ), ); } }
import React from 'react' import { graphql, StaticQuery } from "gatsby" const LocalBOB = ( { data } ) => ( <pre> {data.map((row) => { const { Impacted_Business_Name, Location__Zip_Code_, General_website, Donation_Website } = row.node return( ` <div style="text-align: left;"> <span style="font-size:18px"> <strong>Business Name:</strong> ${Impacted_Business_Name}<br /> <strong>Location:</strong> ${Location__Zip_Code_}<br /> <strong>News Article:</strong> <a href="${Donation_Website}" target="_blank">Click Here</a> <strong>Website:</strong> <a href="${General_website}" target="_blank">Click Here</a> </span> </div> ` ) })} </pre> ) export default props => ( <StaticQuery query={ImpactedBOBQuery} render={ data => <LocalBOB data={data.allImpactedBobCsv.edges} {...props} /> } /> ) export const ImpactedBOBQuery = graphql` query ImpactedBOBQuery { allImpactedBobCsv { edges { node { Impacted_Business_Name General_website Location__Zip_Code_ Donation_Website } } } } `
"use client"; import React, { useCallback } from "react"; import { useDropzone } from "react-dropzone"; import Papa from "papaparse"; const FileInput = ({ handleInput }: any) => { const onDrop = useCallback((acceptedFiles: any) => { const theCSV = acceptedFiles[0]; console.log("filename", theCSV.path); Papa.parse(theCSV, { complete: (result: any) => { // The parsed data is available in result.data // console.log("Parsed CSV data:", result.data); handleInput(result.data); // You can now handle the parsed data as needed }, header: true, // Assumes the first row is the header row }); }, []); const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop, accept: { "text/csv": [".csv"] }, }); return ( <div className="flex items-center justify-center w-full" {...getRootProps()} > <label htmlFor="dropzone-file" className="flex flex-col items-center justify-center w-full h-64 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50 dark:hover:bg-bray-800 dark:bg-gray-700 hover:bg-gray-100 dark:border-gray-600 dark:hover:border-gray-500 dark:hover:bg-gray-600" > <div className="flex flex-col items-center justify-center pt-5 pb-6"> <svg className="w-8 h-8 mb-4 text-gray-500 dark:text-gray-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 16" > <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 13h3a3 3 0 0 0 0-6h-.025A5.56 5.56 0 0 0 16 6.5 5.5 5.5 0 0 0 5.207 5.021C5.137 5.017 5.071 5 5 5a4 4 0 0 0 0 8h2.167M10 15V6m0 0L8 8m2-2 2 2" /> </svg> <p className="mb-2 text-sm text-gray-500 dark:text-gray-400"> {isDragActive ? ( <span> <span className="font-semibold">Drop here</span> </span> ) : ( <span> <span className="font-semibold">Click to upload</span> or drag and drop </span> )} </p> <p className="text-xs text-gray-500 dark:text-gray-400"> only a CSV file is supported{" "} </p> </div> <input {...getInputProps()} /> </label> </div> ); }; export default FileInput;
public abstract class Personagem { private double vida; private String nome; private String classe; private static int personagensCriados = 0; public Personagem (double vida, String nome, String classe){ this.classe = classe; this.vida = vida; this.nome = nome; personagensCriados++; } public abstract void entrarEmRaid(); public abstract void entrarEmPvP(); public abstract void mostraInfo(); public double getVida() { return vida; } public void setVida(double vida) { this.vida = vida; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getClasse() { return classe; } public void setClasse(String classe) { this.classe = classe; } public static int getPersonagensCriados() { return personagensCriados; } }
package hello.thymeleaf.basic; import lombok.Data; import org.springframework.boot.Banner; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/basic") public class BasicController { @GetMapping("text-basic") public String textBasic(Model model) { model.addAttribute("data", "Hello <b>Spring!</b>"); return "basic/text-basic"; } @GetMapping("text-unescaped") public String textUnescaped(Model model) { model.addAttribute("data", "Hello <b>Spring!</b>"); return "basic/text-unescaped"; } @GetMapping("/variable") public String variable(Model model){ User userA = new User("userA", 10); User userB = new User("userB", 10); List<User> list = new ArrayList<>(); list.add(userA); list.add(userB); Map<String, User> map = new HashMap<>(); map.put("userA", userA); map.put("userB", userB); model.addAttribute("user", userA); model.addAttribute("users", list); model.addAttribute("userMap", map); return "basic/variable"; } @GetMapping("/basic-objects") public String basicObjects(HttpSession session){ session.setAttribute("sessionData", "Hello Session"); return "basic/basic-objects"; } @Component("helloBean") static class Hello{ public String hello(String data){ return "hello " + data; } } @GetMapping("/date") public String date(Model model){ model.addAttribute("localDateTime", LocalDateTime.now()); return "basic/date"; } @GetMapping("/link") public String link(Model model){ model.addAttribute("param1", "data1"); model.addAttribute("param2", "data2"); return "basic/link"; } @GetMapping("literal") public String literal(Model model){ model.addAttribute("data","Spring!"); return "basic/literal"; } @GetMapping("/operation") public String operation(Model model){ model.addAttribute("nullData", null); model.addAttribute("data", "Spring!"); return "basic/operation"; } // 속성 값 @GetMapping("/attribute") public String attribute(){ return "basic/attribute"; } // 반복 @GetMapping("/each") public String each(Model model){ addUsers(model); return "basic/each"; } // 조건문 @GetMapping("/condition") public String condition(Model model){ addUsers(model); return "basic/condition"; } // 주석 @GetMapping("/comments") public String comments(Model model){ model.addAttribute("data", "spring!"); return "basic/comments"; } // th:block @GetMapping("/block") public String block(Model model){ addUsers(model); return "basic/block"; } // 자바스크립트 인라인 기능 @GetMapping("/javascript") public String javascript(Model model){ model.addAttribute("user", new User("userA", 10)); addUsers(model); return "basic/javascript"; } @Data static class User{ private String username; private int age; public User(String username, int age) { this.username = username; this.age = age; } } private void addUsers(Model model){ List<User> list = new ArrayList<>(); list.add(new User("userA", 10)); list.add(new User("userB", 20)); list.add(new User("userC", 30)); model.addAttribute("users", list); } }
package gen import ( "github.com/haxii/js-swagger-sdk-gen/model" "net/http" "os" "testing" ) func TestLoadJSONSpec(t *testing.T) { b, err := http.Get("https://petstore.swagger.io/v2/swagger.json") if err != nil { t.Fatal(err) } defer b.Body.Close() spec, err := LoadSpec(b.Body, model.SwaggerFileTypeJSON) if err != nil { t.Fatal(err) } t.Log(len(spec.Raw)) swagger, err := LoadSwagger(model.PackageInfo{}, spec) if err != nil { t.Fatal(err) } t.Log(swagger) pkgTmpl.Execute(os.Stdout, swagger) } func TestLoadYAMLSpec(t *testing.T) { b, err := http.Get("https://petstore.swagger.io/v2/swagger.yaml") if err != nil { t.Fatal(err) } defer b.Body.Close() spec, err := LoadSpec(b.Body, model.SwaggerFileTypeYAML) if err != nil { t.Fatal(err) } t.Log(spec) swagger, err := LoadSwagger(model.PackageInfo{}, spec) if err != nil { t.Fatal(err) } t.Log(swagger) swagger.GenConf.CommonJS = true indexTmpl.Execute(os.Stdout, swagger) } func TestGenYAMLSpec(t *testing.T) { b, err := http.Get("https://petstore.swagger.io/v2/swagger.yaml") if err != nil { t.Fatal(err) } defer b.Body.Close() spec, err := LoadSpec(b.Body, model.SwaggerFileTypeYAML) if err != nil { t.Fatal(err) } t.Log(spec) swagger, err := LoadSwagger(model.PackageInfo{ Name: "swagger-api", Homepage: "https://petstore.swagger.io/", }, spec) if err != nil { t.Fatal(err) } if err = swagger.SetUrlRefInComment(); err != nil { t.Fatal(err) } target, err := os.Create("/tmp/swagger-api.tgz") if err != nil { t.Fatal(err) } defer target.Close() if err = Generate(swagger, target); err != nil { t.Fatal(err) } } func TestEmbed(t *testing.T) { t.Log(indexTmplSrc) }
// URL da API Python que acessa o banco de dados const apiUrl = 'http://127.0.0.1:5000/api/music'; const studentsUrl = 'http://127.0.0.1:5000/api/students'; const addAtividadeUrl = 'http://127.0.0.1:5000/api/atividade'; // Função para obter músicas da API async function fetchMusic() { try { const response = await fetch(apiUrl); const musicData = await response.json(); musicData.forEach(music => { displayMusic(music); }); } catch (error) { console.error('Erro ao buscar músicas:', error); } } function displayMusic(music) { const musicList = document.getElementById("musicList"); const div = document.createElement("div"); div.classList.add("song"); div.innerHTML = ` <strong>${music.nome}</strong> ${music.compositor}<br> <a href="${music.link_traducao}" target="_blank">Link para música</a> <form class="atividadeForm"> <label for="dataEnvio">Data de Envio:</label> <input type="date" name="dataEnvio" required> <button type="button" onclick="submitAtividade(event, '${music.nome}', '${music.compositor}', '${music.link_traducao}')">Enviar</button> </form> `; musicList.appendChild(div); } // Função para buscar alunos da API async function fetchStudents() { try { const response = await fetch(studentsUrl); const studentsData = await response.json(); displayStudents(studentsData); } catch (error) { console.error('Erro ao buscar alunos:', error); } } // Função para exibir alunos no dropdown function displayStudents(students) { const studentSelect = document.getElementById("studentSelect"); students.forEach(student => { const option = document.createElement("option"); option.value = student.nome; // Assuming 'nome' is the student's name option.textContent = student.nome; studentSelect.appendChild(option); }); } // Função para enviar atividade async function submitAtividade(event, nomeMusica, compositor, linkMusica) { event.preventDefault(); const form = event.target.form; const dataEnvio = form.dataEnvio.value; const studentSelect = document.getElementById("studentSelect"); const nomeAluno = studentSelect.options[studentSelect.selectedIndex].text; const atividadeData = { data_envio: dataEnvio, nome_aluno: nomeAluno, nome_musica: nomeMusica, compositor: compositor, link_musica: linkMusica // Enviando o link corretamente }; console.log('Atividade Data:', atividadeData); // Adicione este log para verificar os dados try { const response = await fetch(addAtividadeUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(atividadeData) }); if (response.ok) { alert('Atividade enviada com sucesso!'); } else { const errorData = await response.json(); alert('Erro ao enviar atividade: ' + errorData.error); } } catch (error) { console.error('Erro ao enviar atividade:', error); alert('Erro ao enviar atividade: ' + error.message); } } // Chamar a função para buscar músicas ao carregar a página fetchMusic(); // Chamar a função para buscar alunos ao carregar a página fetchStudents();