text
stringlengths
184
4.48M
package TriggerTest; import java.time.LocalTime; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import projectse.model.trigger.Trigger; import projectse.model.trigger.TriggerTime; /** * * @author group07 */ public class TriggerTimeTest { private TriggerTime trigger; @Before public void setUp() { trigger = new TriggerTime("10", "30"); } @Test public void testValidTriggerTime() { assertEquals("10", trigger.getHour()); assertEquals("30", trigger.getMinutes()); } @Test(expected = IllegalArgumentException.class) public void testInvalidHour() { new TriggerTime("25", "30"); // Ora non valida } @Test(expected = IllegalArgumentException.class) public void testInvalidMinutes() { new TriggerTime("10", "61"); // Minuti non validi } @Test(expected = IllegalArgumentException.class) public void testInvalidHourFormat() { new TriggerTime("abc", "30"); // Formato ora non valido } @Test(expected = IllegalArgumentException.class) public void testInvalidMinutesFormat() { new TriggerTime("10", "xyz"); // Formato minuti non valido } @Test public void testSetAndGetHour() { assertEquals("10", trigger.getHour()); trigger.setHour("12"); assertEquals("12", trigger.getHour()); } @Test public void testSetAndGetMinutes() { assertEquals("30", trigger.getMinutes()); trigger.setMinutes("45"); assertEquals("45", trigger.getMinutes()); } @Test public void testGetTrigger() { assertEquals("Time -> 10:30", trigger.getTrigger()); trigger.setHour("09"); trigger.setMinutes("15"); assertEquals("Time -> 09:15", trigger.getTrigger()); } @Test public void testCheckTrigger() { LocalTime now = LocalTime.now(); Trigger trigger = new TriggerTime(formatTime(now.getHour()), formatTime(now.getMinute())); assertTrue("Il trigger dovrebbe essere attivo", trigger.checkTrigger()); trigger = new TriggerTime(formatTime(now.getHour()), formatTime((now.getMinute() + 1) % 60)); assertFalse("Il trigger non dovrebbe essere attivo", trigger.checkTrigger()); } private String formatTime(int time) { return String.format("%02d", time); } }
window.dataLayer = window.dataLayer || []; pageView(); function pageView() { let width = window.innerWidth; let mediaquery = ""; if (width > 768) { mediaquery = 'desktop' } else { mediaquery = 'mobile' } window.dataLayer.push( { 'event': 'pageview', 'user': { 'logged_in': true, 'account_id': 'abcdef', 'type': 'consumer' }, 'application': { 'id': 'main', 'store': 'NL', 'version': '3.0' }, 'site': { 'language': 'nl-NL', 'mediaquery': mediaquery, 'environment': 'live' }, 'page': { 'type': window.location.pathname, } } ); } function viewItemList() { ecommerceReset(); window.dataLayer.push( { 'event': 'view_item_list', 'ecommerce': { 'items': items } } ) } function selectItem() { ecommerceReset(); window.dataLayer.push( { 'event': 'select_item', 'ecommerce': { 'items': [items[itemNumber()]] } } ) } function viewItem() { ecommerceReset(); let itemViewed = copyItem(); window.dataLayer.push( { 'event': 'view_item', 'ecommerce': { 'items': itemViewed, 'value': itemViewed[0].price } } ) } function addToCart() { ecommerceReset(); let itemAddedToCart = copyItem(); itemAddedToCart[0].quantity = quantity(); window.dataLayer.push( { 'event': 'add_to_cart', 'ecommerce': { 'currency': 'EUR', 'value': value(itemAddedToCart), 'items': itemAddedToCart } } ) } function addToWishlist() { ecommerceReset(); let itemAddedToWishlist = copyItem(); window.dataLayer.push( { 'event': 'add_to_wishlist', 'ecommerce': { 'currency': 'EUR', 'value': itemAddedToWishlist[0].price, 'items': itemAddedToWishlist } } ) } function removeFromCart() { ecommerceReset(); let itemRemovedFromCart = copyItem(); itemRemovedFromCart[0].quantity = quantity(); window.dataLayer.push( { 'event': 'remove_from_cart', 'ecommerce': { 'currency': 'EUR', 'value': value(itemRemovedFromCart), 'items': itemRemovedFromCart } } ) } function viewCart() { ecommerceReset(); let itemsInCart = copyItems(); window.dataLayer.push( { 'event': 'view_cart', 'ecommerce': { 'currency': 'EUR', 'value': value(itemsInCart), 'items': itemsInCart } } ) } function beginCheckout() { ecommerceReset(); let itemsInCart = copyItems(); window.dataLayer.push( { 'event': 'begin_checkout', 'ecommerce': { 'currency': 'EUR', 'value': value(itemsInCart), 'items': itemsInCart } } ) } function addPersonalInfo() { ecommerceReset(); let itemsInCart = copyItems(); window.dataLayer.push( { 'event': 'add_personal_info', 'ecommerce': { 'currency': 'EUR', 'value': value(itemsInCart), 'items': itemsInCart } } ) } function addShippingInfo(i) { ecommerceReset(); let itemsInCart = copyItems(); window.dataLayer.push( { 'event': 'add_shipping_info', 'ecommerce': { 'currency': 'EUR', 'value': value(itemsInCart), 'shipping_tier': 'PostNL', 'items': itemsInCart } } ) } function addPaymentInfo(i) { ecommerceReset(); let itemsInCart = copyItems(); window.dataLayer.push( { 'event': 'add_payment_info', 'ecommerce': { 'currency': 'EUR', 'value': value(itemsInCart), 'shipping_tier': 'PostNL', 'payment_type': 'IDEAL', 'items': itemsInCart } } ) } function purchase(i) { ecommerceReset(); let itemsInCart = copyItems(); window.dataLayer.push( { 'event': 'purchase', 'ecommerce': { 'currency': 'EUR', 'value': value(itemsInCart), 'shipping_tier': 'PostNL', 'payment_type': 'IDEAL', 'items': itemsInCart, 'transaction_id': transactionId(), 'shipping': 1.50, 'tax': value(itemsInCart) * 0.21 / 1.21 }, 'enhanced_conversion_data': enhancedConversionData } ) } function ecommerceReset() { window.dataLayer.push({ 'ecommerce': null }) } function contact() { window.dataLayer.push({ 'event': 'contact', 'method': 'email' }); } function footerClick() { window.dataLayer.push({ 'event': 'footer_click', 'navigation_text': 'Contact' }); } function login() { window.dataLayer.push({ 'event': 'login', 'account_id': 'abcdef', 'account_type': 'consumer', 'email': 'test@test.nl' }); } function navigationUse() { window.dataLayer.push({ 'event': 'navigation_use', 'navigation_text': 'Products', 'navigation_level': 2 }); } function newsletterSubscription() { window.dataLayer.push({ 'event': 'newsletter_subscription', 'form_id': 'footer', 'email': 'test@test.nl' }); } function popupClose() { window.dataLayer.push({ 'event': 'popup_close', 'popup_id': 'abc' }); } function popupCta() { window.dataLayer.push({ 'event': 'popup_cta', 'popup_id': 'abc' }); } function popupVisible() { window.dataLayer.push({ 'event': 'popup_visible', 'popup_id': 'abc' }); } function searchUse() { window.dataLayer.push({ 'event': 'search_use', 'search_action': 'search', 'search_query': 'Trui' }); } function signUp() { window.dataLayer.push({ 'event': 'sign_up', 'account_id': 'abcdef', 'account_type': 'consumer', 'email': 'test@test.nl' }); } function textMessage() { window.dataLayer.push({ 'event': 'text_message', 'message_text': 'Aanbieding 2 voor de prijs van 1' }); } function validationMessage() { window.dataLayer.push({ 'event': 'validation_message', 'validation_text': 'Invalid input', 'validation_field': 'email' }); } function photoLast() { window.dataLayer.push({ 'event': 'photo_last', 'product': items[itemNumber()].item_id }); } function photoNext() { window.dataLayer.push({ 'event': 'photo_next', 'product': items[itemNumber()].item_id }); } function photoPrevious() { window.dataLayer.push({ 'event': 'photo_previous', 'product': items[itemNumber()].item_id }); } function photoZoom() { window.dataLayer.push({ 'event': 'photo_zoom', 'product': items[itemNumber()].item_id, 'index': quantity() }); } function reviewSubmit() { window.dataLayer.push({ 'event': 'review_submit', 'product': items[itemNumber()].item_id, 'review_rating': quantity() }); } function filterUse() { window.dataLayer.push({ 'event': 'filter_use', 'filter_group': 'category', 'filter_option': 'Truien' }); } function sortUse() { window.dataLayer.push({ 'event': 'sort_use', 'sort_option': 'price_low_to_high' }); } function noSearchResults() { window.dataLayer.push({ 'event': 'no_search_results', 'search_query': 'ytiom' }); } function headerClick() { window.dataLayer.push({ 'event': 'header_click', 'navigation_text': 'logo' }); } function buttonClick() { window.dataLayer.push({ 'event': 'button_click', 'navigation_text': 'Ga verder' }); } function faqClose() { window.dataLayer.push({ 'event': 'faq_close', 'faq': 'Wat is de levertijd?' }); } function faqOpen() { window.dataLayer.push({ 'event': 'faq_open', 'faq': 'Wat is de levertijd?' }); } function videoStart() { window.dataLayer.push({ 'event': 'video_start', 'video': 'Tutorial' }); } function videoFinish() { window.dataLayer.push({ 'event': 'video_finish', 'faq': 'Tutorial' }); } function attachEventListenerById(id, handler) { let el = document.getElementById(id); if (el) { el.addEventListener('click', handler) } } attachEventListenerById('page_view', pageView); attachEventListenerById('view_item_list', viewItemList); attachEventListenerById('select_item', selectItem); attachEventListenerById('view_item', viewItem); attachEventListenerById('add_to_cart', addToCart); attachEventListenerById('add_to_wishlist', addToWishlist); attachEventListenerById('remove_from_cart', removeFromCart); attachEventListenerById('view_cart', viewCart); attachEventListenerById('begin_checkout', beginCheckout); attachEventListenerById('add_personal_info', addPersonalInfo); attachEventListenerById('add_shipping_info', addShippingInfo); attachEventListenerById('add_payment_info', addPaymentInfo); attachEventListenerById('purchase', purchase); attachEventListenerById('contact', contact); attachEventListenerById('footer_click', footerClick); attachEventListenerById('login', login); attachEventListenerById('navigation_use', navigationUse); attachEventListenerById('newsletter_subscription', newsletterSubscription); attachEventListenerById('popup_close', popupClose); attachEventListenerById('popup_cta', popupCta); attachEventListenerById('popup_visible', popupVisible); attachEventListenerById('search_use', searchUse); attachEventListenerById('sign_up', signUp); attachEventListenerById('text_message', textMessage); attachEventListenerById('validation_message', validationMessage); attachEventListenerById('photo_last', photoLast); attachEventListenerById('photo_next', photoNext); attachEventListenerById('photo_previous', photoPrevious); attachEventListenerById('photo_zoom', photoZoom); attachEventListenerById('review_submit', reviewSubmit); attachEventListenerById('filter_use', filterUse); attachEventListenerById('sort_use', sortUse); attachEventListenerById('no_search_results', noSearchResults); attachEventListenerById('header_click', headerClick); attachEventListenerById('button_click', buttonClick); attachEventListenerById('faq_open', faqOpen); attachEventListenerById('faq_close', faqClose); attachEventListenerById('video_start', videoStart); attachEventListenerById('video_finish', videoFinish); attachEventListenerById('email', contact); let items = [ { 'item_name': 'Broek', 'item_id': 'b123', 'currency': 'EUR', 'price': 50.00, 'item_variant': 'bleu', 'item_brand': 'HOEC', 'item_category': 'Kleding', 'item_category2': 'Broeken', 'item_category3': 'Jeans', 'item_list_id': 'PLP', 'item_list_name': 'Alle Kleding', 'index': 0, 'stock': true }, { 'item_name': 'Trui', 'item_id': 'T123', 'currency': 'EUR', 'price': 65.00, 'item_variant': 'red', 'item_brand': 'HOEC', 'item_category': 'Kleding', 'item_category2': 'Tops', 'item_category3': 'Truien', 'item_list_id': 'PLP', 'item_list_name': 'Alle Kleding', 'index': 1, 'stock': true }, { 'item_name': 'Schoen', 'item_id': 'S123', 'currency': 'EUR', 'price': 99.00, 'item_variant': '42', 'item_brand': 'HOEC', 'item_category': 'Kleding', 'item_category2': 'Schoenen', 'item_category3': 'Sneaker', 'item_list_id': 'PLP', 'item_list_name': 'Alle Kleding', 'index': 2, 'stock': true } ] let enhancedConversionData = { 'email': 'test@test.nl', 'phone_number': '+31655885858', 'address': { 'fist_name': 'Test', 'last_name': 'Test', 'street': 'Diagon Alley 713', 'city': 'London', 'region': 'London (Greater London)', 'postal_code': 'EC3V 1LU', 'country': 'UK' } } function copyItem() { let copyItem = Object.assign({}, items[itemNumber()]); delete copyItem.index; return [copyItem]; } function copyItems() { let copyItems = items.map(item => { let copyItem = Object.assign({}, item); delete copyItem.index; copyItem.quantity = quantity(); return copyItem; }); return copyItems; } function value(arr) { let value = 0; arr.forEach(obj => { value += obj.quantity * obj.price; }); return value; } function itemNumber() { return Math.floor(Math.random() * 3); } function quantity() { return Math.floor(Math.random() * 10) + 1; } function transactionId() { return Math.floor(Math.random() * 999999); }
import React from 'react'; import { Router } from 'react-router-dom'; import { createMemoryHistory } from 'history'; import { render } from '@testing-library/react'; /* Função desenvolvida conforme explicação do Icaro na aula ao vivo, visando contornar a "falha" do BrowserRouter no que diz respeito ao teste de rotas com RTL */ const renderWithRouter = (component) => { const history = createMemoryHistory(); return ({ ...render(<Router history={ history }>{component}</Router>), history, }); }; export default renderWithRouter;
/*************************************************************************** * Original Diku Mud copyright (C) 1990, 1991 by Sebastian Hammer, * * Michael Seifert, Hans Henrik St{rfeldt, Tom Madsen, and Katja Nyboe. * * * * Merc Diku Mud improvments copyright (C) 1992, 1993 by Michael * * Chastain, Michael Quan, and Mitchell Tse. * * * * In order to use any part of this Merc Diku Mud, you must comply with * * both the original Diku license in 'license.doc' as well the Merc * * license in 'license.txt'. In particular, you may not remove either of * * these copyright notices. * * * * Much time and thought has gone into this software and you are * * benefitting. We hope that you share your changes too. What goes * * around, comes around. * ***************************************************************************/ #if defined(macintosh) #include <types.h> #else #include <sys/types.h> #endif #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "merc.h" #include "colordef.h" /* Note Board system, (c) 1995-96 Erwin S. Andreasen, erwin@andreasen.org Basically, the notes are split up into several boards. The boards do not exist physically, they can be read anywhere and in any position. Each of the note boards has its own file. Each of the boards can have its own "rights": who can read/write. Each character has an extra field added, namele the timestamp of the last note read by him/her on a certain board. The note entering system is changed too, making it more interactive. When entering a note, a character is put AFK and into a special CON_ state. Everything typed goes into the note. For the immortals it is possible to purge notes based on age. An Archive options is available which moves the notes older than X days into a special board. The file of this board should then be moved into some other directory during e.g. the startup script and perhaps renamed depending on date. Note that write_level MUST be >= read_level or else there will be strange output in certain functions. Board DEFAULT_BOARD must be at least readable by *everyone*. */ #define L_SUP (MAX_LEVEL - 1) /* if not already defined */ BOARD_DATA boards[MAX_BOARD] = { {"Announce", "Announcements from Staff", 0, LEVEL_IMMORTAL, "all", DEF_NORMAL, 60, NULL, FALSE}, {"Newspaper", "The Los Angeles Times - In-Character News", 0, 1, "all", DEF_NORMAL, 30, NULL, FALSE}, {"General", "General Discussion and Game Ideas", 0, 2, "all", DEF_INCLUDE, 21, NULL, FALSE}, {"Bugs", "Innocence Lost Potential Bug Reports", 0, 1, "imm", DEF_NORMAL, 60, NULL, FALSE}, {"Typos", "Innocence Lost Typo/Grammar Reports", 0, 1, "imm", DEF_NORMAL, 60, NULL, FALSE}, {"Personal", "Personal Board Messages", 0, 1, "all", DEF_EXCLUDE, 28, NULL, FALSE}, {"Requests", "Request Notes for Staff Review", 0, 1, "all", DEF_EXCLUDE, 60, NULL, FALSE}, {"Staff", "General Staff Reports and Logs", LEVEL_IMMORTAL, LEVEL_IMMORTAL, "imm", DEF_NORMAL, 60, NULL, FALSE}, {"Enigma", "Enigma's Projects Board", LEVEL_IMMORTAL, LEVEL_IMMORTAL, "imm", DEF_NORMAL, 60, NULL, FALSE}, {"Jormungand", "Jormungand's Projects Board", LEVEL_IMMORTAL, LEVEL_IMMORTAL, "imm", DEF_NORMAL, 60, NULL, FALSE}, {"Nocker", "Nocker's Projects Board", LEVEL_IMMORTAL, LEVEL_IMMORTAL, "imm", DEF_NORMAL, 60, NULL, FALSE} }; /* The prompt that the character is given after finishing a note with @x or END */ const char *szFinishPrompt = "(" BOLD "C" NO_COLOR ")ontinue, (" BOLD "V" NO_COLOR ")iew, (" BOLD "S" NO_COLOR ")pellcheck it, (" BOLD "P" NO_COLOR ")ost or (" BOLD "F" NO_COLOR ")orget it?"; long last_note_stamp = 0; /* To generate unique timestamps on notes */ #define BOARD_NOACCESS -1 #define BOARD_NOTFOUND -1 static bool next_board (CHAR_DATA * ch); /* recycle a note */ void free_note (NOTE_DATA * note) { if (note->sender) free_string (note->sender); if (note->to_list) free_string (note->to_list); if (note->subject) free_string (note->subject); if (note->date) /* was note->datestamp for some reason */ free_string (note->date); if (note->text) free_string (note->text); note->next = note_free; note_free = note; } /* allocate memory for a new note or recycle */ NOTE_DATA *new_note () { NOTE_DATA *note; if (note_free) { note = note_free; note_free = note_free->next; } else note = alloc_mem (sizeof (NOTE_DATA)); /* Zero all the field - Envy does not guarantee zeroed memory */ note->next = NULL; note->sender = NULL; note->board = NULL; note->expire = 0; note->to_list = NULL; note->subject = NULL; note->date = NULL; note->date_stamp = 0; note->text = NULL; return note; } /* append this note to the given file */ static void append_note (FILE * fp, NOTE_DATA * note) { fprintf (fp, "Sender %s~\n", note->sender); fprintf (fp, "Date %s~\n", note->date); fprintf (fp, "Stamp %ld\n", note->date_stamp); fprintf (fp, "Expire %ld\n", note->expire); fprintf (fp, "To %s~\n", note->to_list); fprintf (fp, "Subject %s~\n", note->subject); fprintf (fp, "Text\n%s~\n\n", note->text); } /* Save a note in a given board */ void finish_note (BOARD_DATA * board, NOTE_DATA * note) { FILE *fp; NOTE_DATA *p; char filename[200]; char buf[MAX_STRING_LENGTH]; CHAR_DATA *ch; /* The following is done in order to generate unique date_stamps */ note->board = board; if (last_note_stamp >= current_time) note->date_stamp = ++last_note_stamp; else { note->date_stamp = current_time; last_note_stamp = current_time; } if (board->note_first) /* are there any notes in there now? */ { for (p = board->note_first; p->next; p = p->next) ; /* empty */ p->next = note; } else /* nope. empty list. */ board->note_first = note; /* append note to note file */ sprintf (filename, "%s%s", NOTE_DIR, board->short_name); fp = fopen (filename, "a"); if (!fp) { bug ("Could not open one of the note files in append mode", 0); board->changed = TRUE; /* set it to TRUE hope it will be OK later? */ return; } append_note (fp, note); fclose (fp); sprintf (buf, "#w%s #nposted #w%s#n on the #w%s#n board.#r]#n", note->sender, note->subject, board->short_name); do_info (ch, buf); } /* Find the number of a board */ int board_number (const BOARD_DATA * board) { int i; for (i = 0; i < MAX_BOARD; i++) if (board == &boards[i]) return i; return -1; } /* Find a board number based on a string */ int board_lookup (const char *name) { int i; for (i = 0; i < MAX_BOARD; i++) if (!str_cmp (boards[i].short_name, name)) return i; return -1; } /* Remove list from the list. Do not free note */ static void unlink_note (BOARD_DATA * board, NOTE_DATA * note) { NOTE_DATA *p; if (board->note_first == note) board->note_first = note->next; else { for (p = board->note_first; p && p->next != note; p = p->next); if (!p) bug ("unlink_note: could not find note.", 0); else p->next = note->next; } } /* Find the nth note on a board. Return NULL if ch has no access to that note */ static NOTE_DATA *find_note (CHAR_DATA * ch, BOARD_DATA * board, int num) { int count = 0; NOTE_DATA *p; for (p = board->note_first; p; p = p->next) if (++count == num) break; if ((count == num) && is_note_to (ch, p)) return p; else return NULL; } /* save a single board */ static void save_board (BOARD_DATA * board) { FILE *fp; char filename[200]; char buf[200]; NOTE_DATA *note; sprintf (filename, "%s%s", NOTE_DIR, board->short_name); fp = fopen (filename, "w"); if (!fp) { sprintf (buf, "Error writing to: %s", filename); bug (buf, 0); } else { for (note = board->note_first; note; note = note->next) append_note (fp, note); fclose (fp); } } /* Show one note to a character */ static void show_note_to_char (CHAR_DATA * ch, NOTE_DATA * note, int num) { char buf[4 * MAX_STRING_LENGTH]; /* FrankenMU* style --Merry */ sprintf (buf, "#g-------------------------------------------------------------------#GNote#g-#GContent#g-#n\r\n#g[#G%4d#g]#n #n%s Board#n\n\r" "#nNote was posted by: #w%s#n\n\r" "#nIn subject of:#w %s#n\n\r#nDate:#w %s#n\n\r#nTo :#w %s#n\n\r#g--------------------------------------------------------------------------------#n\n\r" "%s#g--------------------------------------------------------------------------------#n\n\r", num, note->board->short_name, note->sender, note->subject, note->date, note->to_list, note->text); page_to_char (buf, ch); } /* Save changed boards */ void save_notes () { int i; for (i = 0; i < MAX_BOARD; i++) if (boards[i].changed) /* only save changed boards */ save_board (&boards[i]); } /* Load a single board */ static void load_board (BOARD_DATA * board) { FILE *fp, *fp_archive; NOTE_DATA *last_note; char filename[200]; sprintf (filename, "%s%s", NOTE_DIR, board->short_name); fp = fopen (filename, "r"); /* Silently return */ if (!fp) return; /* Start note fetching. copy of db.c:load_notes() */ last_note = NULL; for (;;) { NOTE_DATA *pnote; char letter; do { letter = getc (fp); if (feof (fp)) { fclose (fp); return; } } while (isspace (letter)); ungetc (letter, fp); pnote = alloc_perm (sizeof (*pnote)); if (str_cmp (fread_word (fp), "sender")) break; pnote->sender = fread_string (fp); if (str_cmp (fread_word (fp), "date")) break; pnote->date = fread_string (fp); if (str_cmp (fread_word (fp), "stamp")) break; pnote->date_stamp = fread_number (fp); if (str_cmp (fread_word (fp), "expire")) break; pnote->expire = fread_number (fp); if (str_cmp (fread_word (fp), "to")) break; pnote->to_list = fread_string (fp); if (str_cmp (fread_word (fp), "subject")) break; pnote->subject = fread_string (fp); if (str_cmp (fread_word (fp), "text")) break; pnote->text = fread_string (fp); pnote->next = NULL; /* jic */ pnote->board = board; /* Should this note be archived right now ? */ if (pnote->expire < current_time) { char archive_name[200]; sprintf (archive_name, "%s%s.old", NOTE_DIR, board->short_name); fp_archive = fopen (archive_name, "a"); if (!fp_archive) bug ("Could not open archive boards for writing", 0); else { append_note (fp_archive, pnote); fclose (fp_archive); /* it might be more efficient to close this later */ } free_note (pnote); board->changed = TRUE; continue; } if (board->note_first == NULL) board->note_first = pnote; else last_note->next = pnote; last_note = pnote; } bug ("Load_notes: bad key word.", 0); return; /* just return */ } /* Initialize structures. Load all boards. */ void load_boards () { int i; for (i = 0; i < MAX_BOARD; i++) load_board (&boards[i]); } /* Returns TRUE if the specified note is address to ch */ bool is_note_to (CHAR_DATA * ch, NOTE_DATA * note) { if (board_number(note->board)+1 == 7) { if (get_trust(ch) >= LEVEL_JUDGE) return TRUE; if (IS_VAMPIRE(ch)|| IS_WEREWOLF(ch)) if (!str_cmp(ch->bloodline, note->to_list)) return TRUE; return FALSE; } if (!str_cmp (ch->name, note->sender)) return TRUE; if (is_full_name ("all", note->to_list)) return TRUE; if (IS_STORYTELLER(ch) && (is_full_name ("imm", note->to_list) || is_full_name ("imms", note->to_list) || is_full_name ("immortal", note->to_list) || is_full_name ("god", note->to_list) || is_full_name ("gods", note->to_list) || is_full_name ("immortals", note->to_list))) return TRUE; if ((get_trust (ch) == MAX_LEVEL) && (is_full_name ("imp", note->to_list) || is_full_name ("imps", note->to_list) || is_full_name ("implementor", note->to_list) || is_full_name ("implementors", note->to_list))) return TRUE; if (is_full_name (ch->name, note->to_list)) return TRUE; /* Allow a note to e.g. 40 to send to characters level 40 and above */ if (is_number (note->to_list) && get_trust (ch) >= atoi (note->to_list)) return TRUE; return FALSE; } /* Return the number of unread notes 'ch' has in 'board' */ /* Returns BOARD_NOACCESS if ch has no access to board */ int unread_notes (CHAR_DATA * ch, BOARD_DATA * board) { NOTE_DATA *note; time_t last_read; int count = 0; if (board->read_level > get_trust (ch)) return BOARD_NOACCESS; last_read = ch->pcdata->last_note[board_number (board)]; for (note = board->note_first; note; note = note->next) if (is_note_to (ch, note) && ((long) last_read < (long) note->date_stamp)) count++; return count; } /* * COMMANDS */ /* Start writing a note */ static void do_nwrite (CHAR_DATA * ch, char *argument) { char *strtime; char buf[200]; if (IS_NPC (ch)) /* NPC cannot post notes */ return; if (get_trust (ch) < ch->pcdata->board->write_level) { send_to_char ("You cannot post notes on this board.\n\r", ch); return; } /* continue previous note, if any text was written */ /* if (ch->pcdata->in_progress) if (!ch->pcdata->in_progress->text) { free_note (ch->pcdata->in_progress); ch->pcdata->in_progress = NULL; }*/ if (!ch->pcdata->in_progress) { ch->pcdata->in_progress = new_note (); ch->pcdata->in_progress->sender = str_dup (ch->name); /* convert to ascii. ctime returns a string which last character is \n, so remove that */ strtime = ctime (&current_time); strtime[strlen (strtime) - 1] = '\0'; ch->pcdata->in_progress->date = str_dup (strtime); } act (BOLD GREEN "#c$n starts writing a note. This is an OOC action.#n" NO_COLOR, ch, NULL, NULL, TO_ROOM); /* Begin writing the note ! */ sprintf (buf, "#nYou begin %s a new note on the " BOLD "#y%s #nboard.#n\n\r", ch->pcdata->in_progress->text ? "#wcontinuing#n" : "#wposting#n", ch->pcdata->board->short_name); send_to_char (buf, ch); sprintf (buf, BOLD YELLOW "#nFrom: #w%s#n\n\r\n\r", ch->name); send_to_char (buf, ch); if (!ch->pcdata->in_progress->text) /* Are we continuing an old note or not? */ { if (board_number(ch->pcdata->board)+1 == 7) { if (IS_VAMPIRE(ch) || IS_WEREWOLF(ch)) ch->pcdata->in_progress->to_list = str_dup(ch->bloodline); else ch->pcdata->in_progress->to_list = str_dup(ch->name); send_to_char ( BOLD YELLOW "\n\r#nSubject#n" NO_COLOR "#n: ", ch); ch->desc->connected = CON_NOTE_SUBJECT; } else { switch (ch->pcdata->board->force_type) { case DEF_NORMAL: sprintf (buf, "#nIf you press ENTER, default recipient \"" BOLD "#w%s" NO_COLOR "#c\" #nwill be chosen.#n\n\r", ch->pcdata->board->names); break; case DEF_INCLUDE: sprintf (buf, "#nThe recipient list MUST include \"" BOLD "#w%s" NO_COLOR "\". #nIf not, it will be added automatically.#n\n\r", ch->pcdata->board->names); break; case DEF_EXCLUDE: sprintf (buf, "#nThe recipient of this note must NOT include: \"" BOLD "#w%s" NO_COLOR "\".", ch->pcdata->board->names); break; } send_to_char (buf, ch); send_to_char ("\n\r" BOLD YELLOW "#nTo: #n", ch); ch->desc->connected = CON_NOTE_TO; } /* nanny takes over from here */ } else /* we are continuing, print out all the fields and the note so far */ { sprintf (buf, BOLD YELLOW "#nTo" NO_COLOR "#n: #w%s#n\n\r" BOLD YELLOW "#nExpires#n" NO_COLOR "#n:#w %s#n\n\r" BOLD YELLOW "#nSubject#n" NO_COLOR "#n:#w %s#n\n\r", ch->pcdata->in_progress->to_list, ctime (&ch->pcdata->in_progress->expire), ch->pcdata->in_progress->subject); send_to_char (buf, ch); send_to_char (BOLD GREEN "#nYour note so far:#n\n\r" NO_COLOR, ch); send_to_char (ch->pcdata->in_progress->text, ch); send_to_char ("#g--------------------------------------------------------------------------------\r\n#n Now editing a note. Enter #w@x#n on a new line to close the editor.\r\n#g--------------------------------------------------------------------------------\r\n\r\n>", ch); ch->desc->connected = CON_NOTE_TEXT; } } /* Read next note in current group. If no more notes, go to next board */ static void do_nread (CHAR_DATA * ch, char *argument) { NOTE_DATA *p; int count = 0, number; time_t *last_note = &ch->pcdata->last_note[board_number (ch->pcdata->board)]; if (!str_cmp (argument, "again")) { /* read last note again */ } else if (is_number (argument)) { number = atoi (argument); for (p = ch->pcdata->board->note_first; p; p = p->next) if (++count == number) break; if (!p || !is_note_to (ch, p)) send_to_char ("No such note.\n\r", ch); else { show_note_to_char (ch, p, count); *last_note = UMAX (*last_note, p->date_stamp); } } else /* just next one */ { char buf[200]; count = 1; for (p = ch->pcdata->board->note_first; p; p = p->next, count++) if ((p->date_stamp > *last_note) && is_note_to (ch, p)) { show_note_to_char (ch, p, count); /* Advance if new note is newer than the currently newest for that char */ *last_note = UMAX (*last_note, p->date_stamp); return; } send_to_char ("No new notes in this board.\n\r", ch); if (next_board (ch)) sprintf (buf, "Changed to next board, %s.\n\r", ch->pcdata->board->short_name); else sprintf (buf, "There are no more boards.\n\r"); send_to_char (buf, ch); } } /* Remove a note */ static void do_nremove (CHAR_DATA * ch, char *argument) { NOTE_DATA *p; if (!is_number (argument)) { send_to_char ("Remove which note?\n\r", ch); return; } p = find_note (ch, ch->pcdata->board, atoi (argument)); if (!p) { send_to_char ("No such note.\n\r", ch); return; } if (str_cmp (ch->name, p->sender) && (get_trust (ch) < MAX_LEVEL)) { send_to_char ("You are not authorized to remove this note.\n\r", ch); return; } unlink_note (ch->pcdata->board, p); free_note (p); send_to_char ("Note removed!\n\r", ch); save_board (ch->pcdata->board); /* save the board */ } /* Edit a note */ /*static void do_nedit (CHAR_DATA * ch, char *argument, char **pString) { NOTE_DATA *p; if (!is_number (argument)) { send_to_char ("Edit which note?\n\r", ch); return; } p = find_note (ch, ch->pcdata->board, atoi (argument)); if (!p) { send_to_char ("No such note.\n\r", ch); return; } if (str_cmp (ch->name, p->sender) && (get_trust (ch) < MAX_LEVEL)) { send_to_char ("You are not authorized to edit this note.\n\r", ch); return; } send_to_char ("This is the note editor!\n\r", ch); if (*pString == NULL) { *pString = str_dup (""); } send_to_char (*pString, ch); if (*(*pString + strlen (*pString) - 1) != '\r') send_to_char ("\n\r", ch); p = find_note (ch->pcdata->board, atoi (argument)) = pString; return; save_board (ch->pcdata->board); }*/ /* List all notes or if argument given, list N of the last notes */ /* Shows REAL note numbers! */ static void do_nlist (CHAR_DATA * ch, char *argument) { int count = 0, show = 0, num = 0, has_shown = 0; time_t last_note; NOTE_DATA *p; char buf[MAX_STRING_LENGTH]; if (is_number (argument)) /* first, count the number of notes */ { show = atoi (argument); for (p = ch->pcdata->board->note_first; p; p = p->next) if (is_note_to (ch, p)) count++; } sprintf (buf, "#g--------------------------------------------------------------------------------#n\n\r#nNotes on the " BOLD "#w%s Board#n.", ch->pcdata->board->short_name); send_to_char (buf, ch); send_to_char ("\r\n#g--------------------------------------------------------------------------------#n" "\n\r" "#nNum Author #wSubject#n\r\n#g--------------------------------------------------------------------------------#n" "\n\r", ch); last_note = ch->pcdata->last_note[board_number (ch->pcdata->board)]; for (p = ch->pcdata->board->note_first; p; p = p->next) { num++; if (is_note_to (ch, p)) { has_shown++; /* note that we want to see X VISIBLE note, not just last X */ if (!show || ((count - show) < has_shown)) { sprintf (buf, BOLD "#g%2d#y>#n #R%c#n%-26s #w%s#n\n\r#g--------------------------------------------------------------------------------\r\n#n", num, last_note < p->date_stamp ? '*' : ' ', p->sender, p->subject); send_to_char (buf, ch); } } } } /* catch up with some notes */ static void do_ncatchup (CHAR_DATA * ch, char *argument) { NOTE_DATA *p; /* Find last note */ for (p = ch->pcdata->board->note_first; p && p->next; p = p->next); if (!p) send_to_char ("Alas, there are no notes in that board.\n\r", ch); else { ch->pcdata->last_note[board_number (ch->pcdata->board)] = p->date_stamp; send_to_char ("All messages skipped.\n\r", ch); } } /* Dispatch function for backwards compatibility */ void do_note (CHAR_DATA * ch, char *argument) { char arg[MAX_INPUT_LENGTH]; if (IS_NPC (ch)) return; // if(ch->pcdata->board == NULL) // return; argument = one_argument (argument, arg); if ((!arg[0]) || (!str_cmp (arg, "read"))) /* 'note' or 'note read X' */ do_nread (ch, argument); else if (!str_cmp (arg, "list")) do_nlist (ch, argument); else if (!str_cmp (arg, "write")) do_nwrite (ch, argument); // else if (!str_cmp (arg, "edit")) // do_nedit (ch, argument); else if (!str_cmp (arg, "remove")) do_nremove (ch, argument); else if (!str_cmp (arg, "purge")) send_to_char ("Obsolete.\n\r", ch); else if (!str_cmp (arg, "archive")) send_to_char ("Obsolete.\n\r", ch); else if (!str_cmp (arg, "catchup")) do_ncatchup (ch, argument); else do_help (ch, "note"); } /* Show all accessible boards with their numbers of unread messages OR change board. New board name can be given as a number or as a name (e.g. board personal or board 4 */ void do_board (CHAR_DATA * ch, char *argument) { int i, count, number; char buf[200]; if (IS_NPC (ch)) return; if (ch->pcdata->board == NULL) return; if (!argument[0]) /* show boards */ { int unread; count = 1; send_to_char ("#g--------------------------------------------------------------------------------#n\r\n#n Innocence Lost RPI #y-#n MESSAGE BOARDS\r\n#g--------------------------------------------------------------------------------#n" "\n\r" " Num Name Unread Description" "\n\r" "#g--------+----------------+------+-----------------------------------------------#n" "\n\r",ch); for (i = 0; i < MAX_BOARD; i++) { unread = unread_notes (ch,&boards[i]); /* how many unread notes? */ if (unread != BOARD_NOACCESS) { sprintf (buf, " #g%2d" "#y>#n " "%15s" " #g[#n%s%4d" "#g]#n " "#w%s#n" "\n\r", count, boards[i].short_name, unread ? RED : GREEN, unread, boards[i].long_name); send_to_char (buf,ch); count++; } /* if has access */ } /* for each board */ sprintf (buf, "#g--------------------------------------------------------------------------------#n\n\r#n Your current board is " BOLD "#w%s#n.", ch->pcdata->board->short_name); send_to_char (buf, ch); /* Inform of rights */ if (ch->pcdata->board->read_level > get_trust (ch)) send_to_char ("#n You cannot read nor write notes on this board.#n\n\r#g--------------------------------------------------------------------------------#n", ch); else if (ch->pcdata->board->write_level > get_trust (ch)) send_to_char ("#n You can only read notes from this board.#n\n\r#g--------------------------------------------------------------------------------#n", ch); else send_to_char ("#n You can both read and write on this board.#n\n\r#g--------------------------------------------------------------------------------#n", ch); return; } /* if empty argument */ // if (ch->pcdata->in_progress) // { // send_to_char ("Please finish your interrupted note first.\n\r", ch); // return; // } /* Change board based on its number */ if (is_number (argument)) { count = 0; number = atoi (argument); for (i = 0; i < MAX_BOARD; i++) if (unread_notes (ch, &boards[i]) != BOARD_NOACCESS) if (++count == number) break; if (count == number) /* found the board.. change to it */ { ch->pcdata->board = &boards[i]; sprintf (buf, "#cCurrent board changed to " BOLD "%s" NO_COLOR ". %s.#n\n\r", boards[i].short_name, (get_trust (ch) < boards[i].write_level) ? "#cYou can only read here#n" : "#cYou can both read and write here#n"); send_to_char (buf, ch); } else /* so such board */ send_to_char ("No such board.\n\r", ch); return; } /* Non-number given, find board with that name */ for (i = 0; i < MAX_BOARD; i++) if (!str_cmp (boards[i].short_name, argument)) break; if (i == MAX_BOARD) { send_to_char ("No such board.\n\r", ch); return; } /* Does ch have access to this board? */ if (unread_notes (ch, &boards[i]) == BOARD_NOACCESS) { send_to_char ("No such board.\n\r", ch); return; } ch->pcdata->board = &boards[i]; sprintf (buf, "Current board changed to " BOLD "%s" NO_COLOR ". %s.\n\r", boards[i].short_name, (get_trust (ch) < boards[i].write_level) ? "You can only read here" : "You can both read and write here"); send_to_char (buf, ch); } /* Send a note to someone on the personal board */ void personal_message (const char *sender, const char *to, const char *subject, const int expire_days, const char *text) { make_note ("Personal", sender, to, subject, expire_days, text); } void make_note (const char *board_name, const char *sender, const char *to, const char *subject, const int expire_days, const char *text) { int board_index = board_lookup (board_name); BOARD_DATA *board; NOTE_DATA *note; char *strtime; if (board_index == BOARD_NOTFOUND) { bug ("make_note: board not found", 0); return; } if (strlen (text) > MAX_NOTE_TEXT) { bug ("make_note: text too long (%d bytes)", strlen (text)); return; } board = &boards[board_index]; note = new_note (); /* allocate new note */ note->sender = str_dup (sender); note->to_list = str_dup (to); note->subject = str_dup (subject); note->expire = current_time + expire_days * 60 * 60 * 24; note->text = str_dup (text); /* convert to ascii. ctime returns a string which last character is \n, so remove that */ strtime = ctime (&current_time); strtime[strlen (strtime) - 1] = '\0'; note->date = str_dup (strtime); finish_note (board, note); } /* tries to change to the next accessible board */ static bool next_board (CHAR_DATA * ch) { int i = board_number (ch->pcdata->board) + 1; while ((i < MAX_BOARD) && (unread_notes (ch, &boards[i]) == BOARD_NOACCESS)) i++; if (i == MAX_BOARD) return FALSE; else { ch->pcdata->board = &boards[i]; return TRUE; } } void handle_con_note_to (DESCRIPTOR_DATA * d, char *argument) { char buf[MAX_INPUT_LENGTH]; CHAR_DATA *ch = d->character; if (!ch->pcdata->in_progress) { d->connected = CON_PLAYING; bug ("nanny: In CON_NOTE_TO, but no note in progress", 0); return; } strcpy (buf, argument); smash_tilde (buf); /* change ~ to - as we save this field as a string later */ if (board_number(ch->pcdata->board)+1 != 7) { switch (ch->pcdata->board->force_type) { case DEF_NORMAL: /* default field */ if (!buf[0] && (board_number(ch->pcdata->board)+1 != 7)) /* empty string? */ { ch->pcdata->in_progress->to_list = str_dup (ch->pcdata->board->names); sprintf (buf, "#nAssumed default recipient:#n " BOLD "#w%s#n" NO_COLOR "\n\r", ch->pcdata->board->names); write_to_buffer (d, buf, 0); } else ch->pcdata->in_progress->to_list = str_dup (buf); break; case DEF_INCLUDE: /* forced default */ if (!is_full_name (ch->pcdata->board->names, buf)) { strcat (buf, " "); strcat (buf, ch->pcdata->board->names); ch->pcdata->in_progress->to_list = str_dup (buf); sprintf (buf, "\n\rYou did not specify %s as recipient, so it was automatically added.\n\r" BOLD YELLOW "New To" NO_COLOR " : %s\n\r", ch->pcdata->board->names, ch->pcdata->in_progress->to_list); write_to_buffer (d, buf, 0); } else ch->pcdata->in_progress->to_list = str_dup (buf); break; case DEF_EXCLUDE: /* forced exclude */ if (!buf[0]) { write_to_buffer (d, "You must specify a recipient.\n\r" BOLD YELLOW "To" NO_COLOR ": ", 0); return; } if (is_full_name (ch->pcdata->board->names, buf)) { sprintf (buf, "You are not allowed to send notes to %s on this board. Try again.\n\r" BOLD YELLOW "To" NO_COLOR ": ", ch->pcdata->board->names); write_to_buffer (d, buf, 0); return; /* return from nanny, not changing to the next state! */ } else ch->pcdata->in_progress->to_list = str_dup (buf); break; } } if (board_number(ch->pcdata->board)+1 == 7) { if (IS_VAMPIRE(ch) || IS_WEREWOLF(ch)) ch->pcdata->in_progress->to_list = str_dup(ch->bloodline); else ch->pcdata->in_progress->to_list = str_dup(ch->name); } write_to_buffer (d, BOLD YELLOW "\n\r#nSubject#n" NO_COLOR "#n:#n ", 0); d->connected = CON_NOTE_SUBJECT; } void handle_con_note_subject (DESCRIPTOR_DATA * d, char *argument) { char buf[MAX_INPUT_LENGTH]; CHAR_DATA *ch = d->character; if (!ch->pcdata->in_progress) { d->connected = CON_PLAYING; bug ("nanny: In CON_NOTE_SUBJECT, but no note in progress", 0); return; } strcpy (buf, argument); smash_tilde (buf); /* change ~ to - as we save this field as a string later */ /* Do not allow empty subjects */ if (!buf[0]) { write_to_buffer (d, "#nSubject cannot be empty.#n\n\r", 0); write_to_buffer (d, BOLD YELLOW "#nSubject#n" NO_COLOR "#n:#n ", 0); } else if (strlen (buf) > 60) { write_to_buffer (d, "No, no. This is just the Subject. You're note writing the note yet.\n\r", 0); } else /* advance to next stage */ { ch->pcdata->in_progress->subject = str_dup (buf); if (IS_IMMORTAL (ch)) /* immortals get to choose number of expire days */ { sprintf (buf, "\n\r#nHow many days until this note expires?#n\n\r" "#nPress RETURN for default value#n, " BOLD "#w%d#n" NO_COLOR " #ndays.#n\n\r" BOLD YELLOW "#nExpire#n" NO_COLOR "#n:#n ", ch->pcdata->board->purge_days); write_to_buffer (d, buf, 0); d->connected = CON_NOTE_EXPIRE; } else { ch->pcdata->in_progress->expire = current_time + ch->pcdata->board->purge_days * 24L * 3600L; sprintf (buf, "#cThis note will expire#C %s#n\r", ctime (&ch->pcdata->in_progress->expire)); write_to_buffer (d, buf, 0); d->connected = CON_NOTE_TEXT; } } } void handle_con_note_expire (DESCRIPTOR_DATA * d, char *argument) { CHAR_DATA *ch = d->character; char buf[MAX_STRING_LENGTH]; time_t expire; int days; if (!ch->pcdata->in_progress) { d->connected = CON_PLAYING; bug ("nanny: In CON_NOTE_EXPIRE, but no note in progress", 0); return; } /* Numeric argument. no tilde smashing */ strcpy (buf, argument); if (!buf[0]) /* assume default expire */ days = ch->pcdata->board->purge_days; else /* use this expire */ if (!is_number (buf)) { write_to_buffer (d, "Write the number of days!\n\r", 0); write_to_buffer (d, BOLD YELLOW "Expire" NO_COLOR ": ", 0); return; } else { days = atoi (buf); if (days <= 0) { write_to_buffer (d, "This is a positive MUD. Use positive numbers only! :)\n\r", 0); write_to_buffer (d, BOLD YELLOW "Expire" NO_COLOR ": ", 0); return; } } expire = current_time + (days * 24L * 3600L); /* 24 hours, 3600 seconds */ ch->pcdata->in_progress->expire = expire; /* note that ctime returns XXX\n so we only need to add an \r */ d->connected = CON_NOTE_TEXT; } void handle_con_note_text (DESCRIPTOR_DATA * d, char *argument) { CHAR_DATA *ch = d->character; char buf[MAX_STRING_LENGTH]; char letter[4 * MAX_STRING_LENGTH]; if (!ch->pcdata->in_progress) { d->connected = CON_PLAYING; bug ("nanny: In CON_NOTE_TEXT, but no note in progress", 0); return; } /* First, check for EndOfNote marker */ strcpy (buf, argument); if ((!str_cmp (buf, "@x")) || (!str_cmp (buf, "END"))) { write_to_buffer (d, "\n\r\n\r", 0); write_to_buffer (d, szFinishPrompt, 0); write_to_buffer (d, "\n\r", 0); d->connected = CON_NOTE_FINISH; return; } smash_tilde (buf); /* smash it now */ /* Check for too long lines. Do not allow lines longer than 80 chars */ if (strlen (buf) > MAX_LINE_LENGTH) { write_to_buffer (d, "Too long line rejected. Do NOT go over 80 characters!\n\r", 0); return; } /* Not end of note. Copy current text into temp buffer, add new line, and copy back */ /* How would the system react to strcpy( , NULL) ? */ if (ch->pcdata->in_progress->text) { strcpy (letter, ch->pcdata->in_progress->text); free_string (ch->pcdata->in_progress->text); ch->pcdata->in_progress->text = NULL; /* be sure we don't free it twice */ } else strcpy (letter, ""); /* Check for overflow */ if ((strlen (letter) + strlen (buf)) > MAX_NOTE_TEXT) { /* Note too long, take appropriate steps */ write_to_buffer (d, "#cNote too long!#n\n\r", 0); free_note (ch->pcdata->in_progress); ch->pcdata->in_progress = NULL; /* important */ d->connected = CON_PLAYING; return; } /* Add new line to the buffer */ strcat (letter, buf); strcat (letter, "\r\n"); /* new line. \r first to make note files better readable */ /* allocate dynamically */ ch->pcdata->in_progress->text = str_dup (letter); } void handle_con_note_finish (DESCRIPTOR_DATA * d, char *argument) { FILE *out; char *pf; char buf[MAX_STRING_LENGTH]; CHAR_DATA *ch = d->character; if (!ch->pcdata->in_progress) { d->connected = CON_PLAYING; bug ("nanny: In CON_NOTE_FINISH, but no note in progress", 0); return; } switch (tolower (argument[0])) { case 'c': /* keep writing */ write_to_buffer (d, "#cContinuing note...#n\n\r", 0); d->connected = CON_NOTE_TEXT; break; case 'v': /* view note so far */ if (ch->pcdata->in_progress->text) { write_to_buffer (d, GREEN "#CContent of your note so far:#n" NO_COLOR "\n\r", 0); write_to_buffer (d, ch->pcdata->in_progress->text, 0); } else write_to_buffer (d, "#CYou haven't written a thing!#n\n\r\n\r", 0); write_to_buffer (d, szFinishPrompt, 0); write_to_buffer (d, "\n\r", 0); break; case 'p': /* post note */ finish_note (ch->pcdata->board, ch->pcdata->in_progress); write_to_buffer (d, "#cNote posted.#n\n\r", 0); d->connected = CON_PLAYING; /* remove AFK status */ ch->pcdata->in_progress = NULL; act (BOLD GREEN "#c$n finishes $s note. This is an OOC action.#n" NO_COLOR, ch, NULL, NULL, TO_ROOM); break; case 's': #if defined(unix) out = fopen( ".tempnote", "w" ); fprintf( out, "%s\n", ch->pcdata->in_progress->text); fflush(out); fclose(out); out = popen( "ispell -l < .tempnote", "r" ); write_to_buffer( d, "#cThe following words are misspelled:#n\n\r",0); while ( fgets( buf, MAX_STRING_LENGTH - 1, out ) != NULL) { pf = format_string( str_dup( buf ) ); write_to_buffer( d, pf, 0 ); free_string( pf ); } pclose( out ); #else write_to_buffer( d, "#cUnix systems only.#n\n\r", 0 ); #endif write_to_buffer( d, "\n\r", 0); write_to_buffer( d, szFinishPrompt, 0); write_to_buffer( d, "\n\r", 0); break; case 'f': write_to_buffer (d, "#cNote canceled!#n\n\r", 0); free_note (ch->pcdata->in_progress); ch->pcdata->in_progress = NULL; d->connected = CON_PLAYING; /* remove afk status */ break; default: /* invalid response */ write_to_buffer (d, "#cHuh? Valid answers are:#n\n\r\n\r", 0); write_to_buffer (d, szFinishPrompt, 0); write_to_buffer (d, "\n\r", 0); } }
import React, { useState,useEffect } from 'react' import Contacts from "./components/Contacts/Contacts" const App = () => { // const [info,setInfo]=useState(""); // const fetchdata=fetch("https://jsonplaceholder.typicode.com/users").then(res=>res.json()).then(res=>{setInfo(res)}); // useEffect(() // =>{ // fetchdata() // },[]); // // console.log() // return ( // <> // <h1>{info.map(el=>el.name)}</h1> // </> // ) // const handleClick=(event)=>{ // event.preventDefault(); // console.log("Button is clicked") // } // const handleChange=(event)=>{ // console.log(event.target.value); // setInfo(event.target.value); // } const [newName,setNewName]=useState("") const [newEmail,setNewEmail]=useState("") const [contacts,setContacts]=useState([ {name:"Ram",email:"r@r.com"}, {name:"Sam",email:"s@r.com"}, {name:"Yam",email:"y@r.com"}, ]) // console.log(contacts); const handleNameChange=(event)=>{ setNewName(event.target.value); } const handleEmailChange=(event)=>{ setNewEmail(event.target.value); } const handleContactSubmit=()=>{ setContacts([...contacts,{name:newName,email:newEmail}]); setNewName(""); setNewEmail(""); } const handleDelete=(emailId)=>{ const newContacts=contacts.filter(item=>item.email!==emailId); setContacts(newContacts); } const handleEdit=(emailId)=>{ const newContacts=[...contacts]; const index=newContacts.findIndex(el=>el.email==emailId); newContacts[index]={name:newName,email:newEmail}; setContacts(newContacts); setNewName(""); setNewEmail(""); } // console.log(contacts); return( <> <div className="container"> <form> <div className="row"> <div className="col"> <input type="text" className="form-control" placeholder="Full Name" aria-label="Full name" onChange={handleNameChange} value={newName}/> </div> <div className="col"> <input type="text" className="form-control" placeholder="Email" aria-label="Email" onChange={handleEmailChange} value={newEmail} /> </div> </div> <button type="button" className="btn btn-primary mt-3" onClick={handleContactSubmit}>Add Contact</button> </form> </div> <Contacts contacts ={contacts} handleDelete={handleDelete} handleEdit={handleEdit}/> </> ) } export default App
import secrets from flask import Blueprint, request from flask_socketio import disconnect from .. import socketio from ..utils import * from ..database import * class Recovery: """ Recovery api class /api/recovery/ """ recovery = Blueprint("recovery", __name__) @recovery.route("/email", methods=["POST"]) @Decorators.manage_database @Decorators.ticket_auth def restore_email(db, user, option): if not option.startswith("email-old|"): return 403 email = option[10:].lower() if db.get_entry(USER_SETTING_TABLE, email, "email"): return ({"errors": {"email": "Email is already registered!"}}, 406) db.update_entry(USER_SETTING_TABLE, user.id, "email", email) socketio.emit("user_change", {"setting": "email", "content": email}, to=user.id) return ({"email": email}, 200) @recovery.route("/password", methods=["POST"]) @Decorators.manage_database @Decorators.ticket_auth def restore_password(db, user, option): if option != "passw": return 403 if not (password := request.json.get("password")): return ({"errors": {"password": "No password provided"}}, 400) if len(password) < 6: return ({"errors": {"password": "Password must have at least 6 characters"}}, 400) secret = secrets.token_hex(32) db.update_entry(USER_SECRET_TABLE, user.id, "password", Security.hash_passwd(password)) db.update_entry(USER_SECRET_TABLE, user.id, "secret", secret) db.update_entry(USER_SECRET_TABLE, user.id, "sent_time", None) if socketio.server.manager.rooms and socketio.server.manager.rooms["/"].get(user.id, {}): socketio.emit("logout", {"reason": "password changed"}, to=user.id) for sid in socketio.server.manager.rooms["/"].get(user.id, {}).copy(): disconnect(sid=sid, namespace="/") return ({"user_login": user.name}, 200) @recovery.route("/forgot-password", methods=["POST"]) @Decorators.manage_database def forgot_password(db): user = db.get_entry(USER_TABLE, request.json.get("login").lower(), "name") user_settings = ( db.get_entry(USER_SETTING_TABLE, user.id) if user else db.get_entry(USER_SETTING_TABLE, request.json.get("login").lower(), "email") ) if not user_settings: return ({"errors": {"login": "Login is invalid."}}, 400) user = user if user else db.get_entry(USER_TABLE, user_settings.id) user_secrets = db.get_entry(USER_SECRET_TABLE, user_settings.id) current_time = time.time() if ( int(current_time - (float(user_secrets.sent_time) if user_secrets.sent_time else 0)) < 300 ): # Only allow for resend after 5 minutes from earlier email; time in seconds return ({"errors": {"resend": "Wait 5 minutes from previous email!"}}, 406) Mailing.send_password_recovery( user_settings.email, user.name, Security.gen_token(user.id, user_secrets.secret, "passw") ) db.update_entry(USER_SECRET_TABLE, user.id, "sent_time", str(current_time)) return 200 @recovery.route("/mfa", methods=["POST"]) @Decorators.manage_database @Decorators.ticket_auth def restore_mfa(db, user, option): if option != "mfa-reset": return 403 user_settings = db.get_entry(USER_SETTING_TABLE, user.id) if not user_settings.mfa_enabled: return 200 db.update_entry(USER_SETTING_TABLE, user.id, "mfa_enabled", 0) db.update_entry(USER_SECRET_TABLE, user.id, "mfa_code", None) socketio.emit("user_change", {"setting": "mfa_enabled", "content": 0}, to=user.id) return 200 @recovery.route("/no-mfa-access", methods=["POST"]) @Decorators.manage_database @Decorators.ticket_auth def no_mfa_access(db, user, option): if option != "mfa": return 403 user_settings = db.get_entry(USER_SETTING_TABLE, user.id) if not user_settings.mfa_enabled: return ({"errors": {"mfa": "2FA is not enabled"}}, 406) user_secrets = db.get_entry(USER_SECRET_TABLE, user.id) current_time = time.time() if ( int(current_time - (float(user_secrets.sent_time) if user_secrets.sent_time else 0)) < 300 ): # Only allow for resend after 5 minutes from earlier email; time in seconds return ({"errors": {"resend": "Wait 5 minutes from previous email!"}}, 406) Mailing.send_mfa_reset( user_settings.email, user.name, Security.gen_token(user.id, user_secrets.secret, "mfa-reset") ) db.update_entry(USER_SECRET_TABLE, user.id, "sent_time", str(current_time)) return 200
-- What percentage of sales come through each type of store? -- The sales team wants to know which of the different store types is generated -- the most revenue so they know where to focus. -- Find out the total and percentage of sales coming from each of the different -- store types. -- The query should return: +-------------+-------------+---------------------+ | store_type | total_sales | percentage_total(%) | +-------------+-------------+---------------------+ | Local | 3440896.52 | 44.87 | | Web portal | 1726547.05 | 22.44 | | Super Store | 1224293.65 | 15.63 | | Mall Kiosk | 698791.61 | 8.96 | | Outlet | 631804.81 | 8.10 | +-------------+-------------+---------------------+ -- Experiment SELECT store_type, ROUND( SUM(product_price * product_quantity)::NUMERIC, 2 ) AS total_sales FROM orders_table JOIN dim_store_details ON dim_store_details.store_code = orders_table.store_code JOIN dim_products ON dim_products.product_code = orders_table.product_code GROUP BY dim_store_details.store_type ORDER BY total_sales DESC; -- Solution WITH cte_total_sales_by_store_type AS ( SELECT store_type, ROUND( SUM(product_price * product_quantity)::NUMERIC, 2 ) AS total_sales FROM orders_table JOIN dim_store_details ON dim_store_details.store_code = orders_table.store_code JOIN dim_products ON dim_products.product_code = orders_table.product_code GROUP BY dim_store_details.store_type ) SELECT store_type, total_sales, ROUND( (total_sales / SUM(total_sales) OVER ()) * 100, 2 ) AS "percentage_total(%)" FROM cte_total_sales_by_store_type ORDER BY total_sales DESC;
import 'package:story_app/model/user.dart'; import 'package:story_app/provider/auth_provider.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:story_app/themes/colors.dart'; class RegisterScreen extends StatefulWidget { final Function() onRegister; final Function() onLogin; const RegisterScreen({ Key? key, required this.onRegister, required this.onLogin, }) : super(key: key); @override State<RegisterScreen> createState() => _RegisterScreenState(); } class _RegisterScreenState extends State<RegisterScreen> { final nameController = TextEditingController(); final emailController = TextEditingController(); final passwordController = TextEditingController(); final formKey = GlobalKey<FormState>(); @override void dispose() { emailController.dispose(); passwordController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Register Screen"), ), body: Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 300), child: Form( key: formKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ TextFormField( controller: nameController, validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your name.'; } return null; }, decoration: const InputDecoration( hintText: "Name", ), ), const SizedBox(height: 8), TextFormField( controller: emailController, validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your email.'; } return null; }, decoration: const InputDecoration( hintText: "Email", ), ), const SizedBox(height: 8), TextFormField( controller: passwordController, obscureText: true, decoration: const InputDecoration( hintText: "Password", ), validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your password.'; } return null; }, ), const SizedBox(height: 8), context.watch<AuthProvider>().isLoadingRegister ? const Center(child: CircularProgressIndicator()) : ElevatedButton( onPressed: () async { if (formKey.currentState!.validate()) { final scaffoldMessenger = ScaffoldMessenger.of(context); final User user = User.register( name: nameController.text, email: emailController.text, password: passwordController.text, ); AuthProvider authRead = context.read<AuthProvider>(); final result = await authRead.register(user); if (result) widget.onRegister(); if (authRead.registerMessage.isNotEmpty) { scaffoldMessenger.showSnackBar( SnackBar( content: Text(authRead.registerMessage), ), ); } } }, child: const Text("REGISTER"), ), const SizedBox(height: 8), OutlinedButton( onPressed: () => widget.onLogin(), style: OutlinedButton.styleFrom( foregroundColor: primaryColor[950], ), child: const Text("LOGIN"), ), ], ), ), ), ), ); } }
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { IsNotEmpty, IsString, IsOptional, IsNumberString, } from 'class-validator'; export default class PageParamsDTO { @ApiProperty({ type: String, description: 'The Confluence space key', example: 'konviw', }) @IsNotEmpty() @IsString() spaceKey: string; @ApiProperty({ type: String, description: 'The ID for the page to render.', example: '98444', }) @IsNotEmpty() @IsNumberString() pageId: string; @ApiProperty({ type: String, description: 'The version of the page to render.', example: '9', }) @IsOptional() @IsNumberString() pageVersion: string; @ApiPropertyOptional({ type: String, required: false, description: 'Optional title of the page comes at the end of the URL.', }) @IsOptional() pageSlug: string; // Optional parameters for the blog post router @IsOptional() year: string; @IsOptional() month: string; @IsOptional() day: string; }
// // DefaultsUserInfoRepository.swift // Scoop // // Created by Jae hyuk Yim on 2023/08/24. // import Foundation import Firebase class DefaultsUserInfoRepository: UserInfoRepository { // 유저 정보 가져오기 func getUserInfo(userId: String, completion: @escaping (Result<UserInfo, Error>) -> Void) { let database = Firestore.firestore() database.collection("users").document(userId).getDocument { snapshot, error in if let error = error { completion(.failure(error)) return } guard let data = snapshot?.data(), let email = data["email"] as? String, let location = data["location"] as? String, let nickname = data["nickname"] as? String, let longitude = data["longitude"] as? String, let latitude = data["latitude"] as? String else { let error = NSError(domain: "FirestoreError", code: 0, userInfo: nil) completion(.failure(error)) return } let userInfo = UserInfo(email: email, password: "", location: location, nickname: nickname, longitude: longitude, latitude: latitude) completion(.success(userInfo)) } } // 변경된 닉네임 저장 func updateNickname(uid: String, newNickname: String, completion: @escaping (Result<Void, Error>) -> Void) { let database = Firestore.firestore() let userRef = database.collection("users").document(uid) userRef.updateData(["nickname": newNickname]) { error in if let error = error { completion(.failure(error)) } else { self.updatePostsForUser(uid: uid, newNickname: newNickname, completion: completion) } } } // 리뷰 업데이트 func updatePostsForUser(uid: String, newNickname: String, completion: @escaping (Result<Void, Error>) -> Void) { let database = Firestore.firestore() // "UserReviews" 컬렉션에서 해당 사용자(uid)가 작성한 게시물을 찾습니다. let query = database.collectionGroup("UserReviews") .whereField("authorUID", isEqualTo: uid) query.getDocuments { (querySnapshot, error) in if let error = error { completion(.failure(error)) return } let batch = database.batch() for document in querySnapshot?.documents ?? [] { let postReference = document.reference batch.updateData(["nickname": newNickname], forDocument: postReference) } batch.commit { error in if let error = error { completion(.failure(error)) } else { completion(.success(())) } } } } // 이메일 업데이트 func updateEmail(uid: String, newEmail: String, completion: @escaping (Result<Void, Error>) -> Void) { let database = Firestore.firestore() let userRef = database.collection("users").document(uid) userRef.updateData(["email": newEmail]) { error in if let error = error { completion(.failure(error)) } else { completion(.success(())) } } } // 유저 탈퇴(Auth, FireStore 사용자 데이터 삭제) func deleteUser(uid: String, completion: @escaping (Result<Void, Error>) -> Void) { let database = Firestore.firestore() let auth = Auth.auth() // "users" 컬렉션에서 사용자 문서 삭제 let userRef = database.collection("users").document(uid) userRef.delete { userError in if let userError = userError { completion(.failure(userError)) return } // Firebase Authentication에서 사용자 삭제 auth.currentUser?.delete { authError in if let authError = authError { completion(.failure(authError)) } else { completion(.success(())) } } } } }
import React from "react"; import Image from "next/image"; import Link from "next/link"; import { observer } from "mobx-react-lite"; import genreStore from "../mobx/GenreStore"; function GridGenreItem({ genre }) { return ( <Link href={`/genre/${genre._id}`} passHref> <button onClick={() => genreStore.setGenre(genre)} className={`w-44 h-44 rounded-lg flex overflow-hidden`} style={{ backgroundColor: genre.color }} > <h1 className="font-gotham text-white text-2xl p-4 font-bold"> {genre.title} </h1> <div className="absolute -bottom-7 -right-4 rotate-45 shadow-gray-700 shadow-md shad"> <Image alt="genre image" src={genre.cover} width={100} height={100} /> </div> </button> </Link> ); } export default observer(GridGenreItem);
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:goasbar/app/app.locator.dart'; import 'package:goasbar/data_models/chat_token_provider_model.dart'; import 'package:goasbar/services/chat_api_service.dart'; import 'package:goasbar/services/token_service.dart'; import 'package:stacked/stacked.dart'; import 'package:stacked_services/stacked_services.dart'; class ChatWithAgencyFromTripDetailViewModel extends FutureViewModel<ChatTokenProviderModel?> { ChatWithAgencyFromTripDetailViewModel({this.context, this.providerId}); BuildContext? context; int? providerId; final _navigationService = locator<NavigationService>(); final _chatApiService = locator<ChatApiService>(); final _tokenService = locator<TokenService>(); ChatTokenProviderModel? chatTokenProvider; int indexTab = 1; final _fireStore = FirebaseFirestore.instance; void navigateTo({view}) { _navigationService.navigateWithTransition(view, curve: Curves.easeIn, duration: const Duration(milliseconds: 300)); } void back() { _navigationService.back(); } void changeTab(int value) { indexTab = value; notifyListeners(); } Future<ChatTokenProviderModel?> getUserFireStoreTokenAndProviderChatId() async { String? token = await _tokenService.getTokenValue(); chatTokenProvider = await _chatApiService.getProviderFireStoreTokenAndChatId( context: context, token: token, providerId: providerId); notifyListeners(); return chatTokenProvider; } Future sendMessage({ String? meId, String? notMeId, TextEditingController? message, }) async { if (message!.text.isNotEmpty) { await _fireStore .collection("chats") .doc(chatTokenProvider!.chatId) .collection("messages") .doc() .set({ "createdAt": DateTime.now(), "receiverID": notMeId, "senderID": meId, "text": message.text, }); message.clear(); notifyListeners(); } } @override Future<ChatTokenProviderModel?> futureToRun() async { return await getUserFireStoreTokenAndProviderChatId(); } }
from flask import Flask, render_template, request, redirect, url_for import psycopg2 import plotly.graph_objs as go import plotly.io as pio import plotly import plotly.express import json app = Flask(__name__) def fetch_all_approval_data(): conn = psycopg2.connect(database="expense_entry", user="postgres", password="nethra14", host="localhost", port="5432") cur = conn.cursor() cur.execute(''' SELECT a.report_id, r.report_name, r.report_date, r.report_dept, a.status FROM approval a JOIN report r ON a.report_id = r.report_id WHERE a.status = 'Pending' ORDER BY r.report_date DESC LIMIT 3 ''') data = cur.fetchall() cur.close() conn.close() return data def fetch_expense_data(): conn = psycopg2.connect(database="expense_entry", user="postgres", password="nethra14", host="localhost", port="5432") cur = conn.cursor() cur.execute('''SELECT report_dept, SUM(expense_amt) AS total_expense FROM report JOIN expense ON report.report_id = expense.report_id GROUP BY report_dept''') data = cur.fetchall() cur.close() conn.close() return data def fetch_category_data(): conn = psycopg2.connect(database="expense_entry", user="postgres", password="nethra14", host="localhost", port="5432") cur = conn.cursor() cur.execute('''SELECT expense_ctgry, SUM(expense_amt) AS total_expense FROM expense GROUP BY expense_ctgry''') data = cur.fetchall() cur.close() conn.close() return data def fetch_all_expense_data(): conn = psycopg2.connect(database="expense_entry", user="postgres", password="nethra14", host="localhost", port="5432") cur = conn.cursor() cur.execute('''SELECT * FROM expense ORDER BY expense_date DESC LIMIT 5''') data = cur.fetchall() cur.close() conn.close() return data def fetch_all_report_data(): conn = psycopg2.connect(database="expense_entry", user="postgres", password="nethra14", host="localhost", port="5432") cur = conn.cursor() cur.execute('''SELECT * FROM report ORDER BY report_date DESC LIMIT 5''') data = cur.fetchall() cur.close() conn.close() return data def get_user_name(): conn = psycopg2.connect(database="expense_entry", user="postgres", password="nethra14", host="localhost", port="5432") cur = conn.cursor() cur.execute("SELECT name FROM user_sessions ORDER BY created_at DESC LIMIT 1") pname = cur.fetchone() cur.close() conn.close() return pname[0] if pname else 'None' @app.route('/') def index(): pname = get_user_name() all_approval_data = fetch_all_approval_data() all_expense_data = fetch_all_expense_data() data = fetch_expense_data() all_report_data = fetch_all_report_data() # Process data for plotting departments = [row[0] for row in data] total_expense = [row[1] for row in data] # Create Plotly bar graph bar_graph = go.Bar(x=departments, y=total_expense, marker = dict(color = 'rgb(82, 205, 255)')) # Plot layout layout = go.Layout(xaxis=dict(automargin = False), width = 720, plot_bgcolor='rgba(0,0,0,0)', xaxis_showgrid=False, yaxis_showgrid=True, yaxis_gridcolor='rgb(244,245,247)', xaxis_gridcolor='rgb(200,200,200)') # Combine data and layout into a figure graph = go.Figure(data=bar_graph, layout=layout) graphJSON = json.dumps(graph, cls = plotly.utils.PlotlyJSONEncoder) category_data = fetch_category_data() categories = [row[0] for row in category_data] category_expenses = [row[1] for row in category_data] # Create Plotly doughnut chart doughnut_graph = go.Pie(labels=categories, values=category_expenses, hole=0.3) # Plot layout for doughnut chart doughnut_layout = go.Layout(height = 400, width = 300, legend=dict(orientation="h", x=-0.5, y=2)) doughnut_fig = go.Figure(data=[doughnut_graph], layout=doughnut_layout) doughnut_graphJSON = json.dumps(doughnut_fig, cls=plotly.utils.PlotlyJSONEncoder) return render_template('index.html', pname = pname, graphJSON = graphJSON, doughnut_graphJSON=doughnut_graphJSON, all_expense_data=all_expense_data, all_report_data = all_report_data, all_approval_data = all_approval_data) if __name__ == '__main__': app.run(debug = True, port = 5001)
import { createClient } from "pexels"; import { useEffect, useRef, useState } from "react"; const credential = "563492ad6f9170000100000113f525316273470d9df782d184f60f54"; const client = createClient(credential); function App() { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const inputRef = useRef(); const fetchData = async () => { let response = await client.photos.curated(); setData(response); setLoading(false); }; const changehandler = async () => { if (inputRef.current.value === "") { fetchData(); return; } const query = inputRef.current.value; let response = await client.photos.search({ query, per_page: 15 }); setData(response); }; const prev = async (url) => { if (url) { let response = await fetch(url, { method: "GET", headers: { Authorization: credential, }, }); const data = await response.json(); setData(data); } }; const next = async (url) => { if (url) { let response = await fetch(url, { method: "GET", headers: { Authorization: credential, }, }); console.log(response); const data = await response.json(); setData(data); } }; useEffect(() => { fetchData(); }, []); return ( <div className="container"> <div className="header"> <h1>Pexels Curated</h1> <input type="text" ref={inputRef} onChange={changehandler} /> </div> {loading ? ( <h1>Loading . . .</h1> ) : ( <div className="images"> {data.photos ? ( data.photos.map((photo, index) => { return ( <a className="image" href={photo.url} key={index}> <img src={photo.src.portrait} alt="pexels" /> </a> ); }) ) : ( <h1>No Result Found.</h1> )} </div> )} <div className="footer"> <p onClick={() => prev(data.prev_page)} className={data.prev_page ? "" : "disable"}> &#8612; </p> <p onClick={() => next(data.next_page)} className={data.next_page ? "" : "disable"}> &#8614; </p> </div> </div> ); } export default App;
"use client"; import Link from "next/link"; import { LuPlus } from "react-icons/lu"; import { useLocalStorage } from "usehooks-ts"; import { useOrganization, useOrganizationList } from "@clerk/nextjs"; import { Button } from "@/components/ui/button"; import { Separator } from "@/components/ui/separator"; import { Skeleton } from "@/components/ui/skeleton"; import { Accordion } from "@/components/ui/accordion"; import NavItem, { Organization } from "./nav-item"; // the storage key is used inside the accordion, that is because the accordion can be expanded or collapsed, the accordion collapses itself after a rerender // so iam using the localStorage to store the key to keep track which accordion was opened type SidebarProps = { storageKey?: string; }; const Sidebar = ({ storageKey = "sidebar-state" }: SidebarProps) => { const [expanded, setExpanded] = useLocalStorage<Record<string, any>>( storageKey, {} ); const { organization: activeOrganization, isLoaded: isLoadedOrg } = useOrganization(); const { userMemberships, isLoaded: isLoadedOrgList } = useOrganizationList({ userMemberships: { infinite: true, }, }); const defaultAccordionValue: string[] = Object.keys(expanded).reduce( (acc: string[], key: string) => { if (expanded[key]) { acc.push(key); } return acc; }, [] ); //what this does is converting the expanded from {"org-id-123":true} to ["org-id-123"]. so it makes an array of the expanded accordion elements, because the accordion component from shadcn expects an array of strings const onExpand = (id: string) => { setExpanded((curr) => ({ ...curr, [id]: !expanded[id], })); }; if (!isLoadedOrg || !isLoadedOrgList || userMemberships.isLoading) { return ( <> <div className=" flex items-center justify-between mb-2"> <Skeleton className="h-10 w-[50%]" /> <Skeleton className="h-10 w-10" /> </div> <div className="space-y-2"> <NavItem.Skeleton /> <NavItem.Skeleton /> <NavItem.Skeleton /> </div> </> ); } return ( <> <div className="font-medium text-xs flex items-center mb-1"> <span className="pl-4">Workspaces</span> <Button asChild type="button" size={"icon"} variant={"ghost"} className="ml-auto" > <Link href={"/select-org"}> <LuPlus className="h-4 w-4" /> </Link> </Button> </div> <Accordion type="multiple" defaultValue={defaultAccordionValue} className="space-y-2" > {userMemberships.data.map(({ organization }) => ( <NavItem key={organization.id} id={organization.id} isActive={activeOrganization?.id === organization.id} isExpanded={!!expanded[organization.id]} organization={organization as Organization} onExpand={onExpand} /> ))} </Accordion> </> ); }; export default Sidebar;
<!DOCTYPE html> <html lang="zh_CN"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>元素层级</title> <link rel="stylesheet" type="text/css" href="../hello.css" /> <style type="text/css"> .box1{ width: 100px; height: 100px; background-color: red; } .box2{ width: 100px; height: 100px; background-color: green; position: relative; top: 50px; left: 10px; z-index: -2; } .box3{ width: 100px; height: 100px; background-color: blue; position: relative; z-index: -1; } .box4{ width: 100px; height: 100px; background-color: red; margin-top: 100px; } .box5{ width: 100px; height: 100px; background-color: green; position: relative; top: -50px; left: 50px; z-index: 2; opacity:0.5; filter:alpha(opacity=50) } .box6{ width: 100px; height: 100px; background-color: blue; position: relative; top: -100px; left: 100px; z-index: 3; opacity:0.8; /*兼容IE8及以下*/ filter:alpha(opacity=50) } </style> <head/> <body> <p class="lable"><span class="Keyword">z-index:</span> 为元素设置层级,指定一个整数作为值,改值将会作为当前元素的层级, 层级越高,越优先显示。 </p> <p class="lable"> 对于没有开启定位的元素,不能使用z-index设置层级, 设置了也无效。 </p> <p class="lable"> 父元素盖不住子元素,即使父元素层级比子元素高。 </p> <p class="lable"><span class="Keyword">opacity:</span> 可以用来设置元素的透明,它需要一个0-1之间的值,0表示完全透明,1表示完全不透明,0.5表示半透明。 </p> <p class="lable"> opacity属性在IE8及以下的浏览器中不支持, IE8及以下的浏览器需要使用如下属性代替: </p> <p class="lable"><span class="Keyword">filter:alpha(opacity=50)</span> 透明度在0-100之间,0表示完全透明,100表示完全不透明,50半透明。 这种方式支持IE6,但是这种效果在IE Tester中无法测试。 </p> <p class="sample">示例:</p> <xmp> <!--css--> <!--html--> </xmp> <p class="show">效果展示:</p> <div class="box1"></div> <div class="box2"></div> <div class="box3"></div> <div class="box4"></div> <div class="box5"></div> <div class="box6"></div> </body> <html/>
package controller import ( "fmt" "net/http" "os" "github.com/AshishKothariii/rentifybackend/services" "github.com/AshishKothariii/rentifybackend/utils" "github.com/gin-gonic/gin" "go.mongodb.org/mongo-driver/bson/primitive" ) type User struct { ID string `json:"_id,omitempty"` Username string `json:"username,omitempty"` } // UserController handles web requests related to Users type UserController struct { service services.UserService } // NewUserController creates a new UserController func NewUserController(s services.UserService) *UserController { return &UserController{service: s} } // RegisterUser handles POST /register endpoint func (uc *UserController) RegisterUser(c *gin.Context) { var userInfo struct { FirstName string `bson:"firstname" json:"firstname"` LastName string `bson:"lastname" json:"lastname"` Email string `bson:"email" json:"email"` MobileNo string `bson:"mobileno" json:"mobileno"` Password string `bson:"password" json:"password"` } if err := c.ShouldBindJSON(&userInfo); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"}) return } user, err := uc.service.CreateUser(c, userInfo.FirstName,userInfo.LastName,userInfo.MobileNo, userInfo.Email, userInfo.Password) if err != nil { c.JSON(http.StatusUnauthorized, gin.H{"error": "Failed to create user"}) return } token, err := utils.GenerateJWT(user.ID.Hex(), user.Email) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"}) return } c.SetSameSite(http.SameSiteNoneMode) c.SetCookie("token", token, 3600, "/", os.Getenv("CLIENT_URL"), true, true) c.JSON(http.StatusCreated, gin.H{"email":user.Email,"isLoggedin":true}) } // Login handles POST /login endpoint func (uc *UserController) Login(c *gin.Context) { var credentials struct { Email string `json:"email"` Password string `json:"password"` } if err := c.ShouldBindJSON(&credentials); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"}) return } user, err := uc.service.CheckUserCredentials(c, credentials.Email, credentials.Password) if err != nil { c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"}) return } token, err := utils.GenerateJWT(user.ID.Hex(), user.Email) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"}) return } c.SetSameSite(http.SameSiteNoneMode) c.SetCookie("token", token, 3600, "/", os.Getenv("CLIENT_URL"), true, true) c.JSON(http.StatusOK,gin.H{ "isLoggedin":true, "email":user.Email, }) } func (uc *UserController) Logout(c *gin.Context) { c.SetSameSite(http.SameSiteNoneMode) c.SetCookie("token", "", -1, "/", os.Getenv("CLIENT_URL"), true, true) c.JSON(http.StatusOK, gin.H{ "isLoggedin":false, }) } func (uc *UserController) GetProfile(c *gin.Context) { token, _ := c.Cookie("token") ans,_ := utils.ParseJWT(token) fmt.Println(ans) userid,_ :=primitive.ObjectIDFromHex(ans) user,err :=uc.service.GetUserByID(c,userid) if err!=nil{ fmt.Print(err) } c.JSON(http.StatusOK, gin.H{ "name": user.FirstName+" "+user.LastName, "mobileno": user.MobileNo, "email": user.Email, "avatar":user.Avatar, }) } func (uc *UserController) GetUserByUserName(c *gin.Context) { var requestData struct { Email string `json:"email"` } if err := c.ShouldBindJSON(&requestData); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } // Use the email from the request JSON email := requestData.Email user, err := uc.service.GetUserByEmail(c, email) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve user"}) return } // Check if user is found if user == nil { c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) return } // Return user details as JSON response c.JSON(http.StatusOK, gin.H{ "name": user.FirstName + " " + user.LastName, "mobileno": user.MobileNo, "Avatar": user.Avatar, "Email": user.Email, }) }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>键盘事件</title> <!-- 引入 Vue --> <script type="text/javascript" src="../js/vue.js"></script> <style> </style> </head> <body> <!-- 1.Vue中常用的按键别名: 回车 => enter 删除 => delete (捕获“删除”和“退格”键) 退出 => esc 空格 => space 换行 => tab (配合 keydown 使用) 上 => up 下 => down 左 => left 右 => right 2.Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case(短横线命名) 3.系统修饰键(用法特殊):ctrl、alt、shift、meta (1). 配合keyup使用:按下修饰键的同时,再按下其他键,随后释放其他键,事件才被触发。 (2). 配合keydown使用:正常触发事件。 4.也可以使用keyCode去指定具体的按键(不推荐)。 5. Vue.config.keyCodes.自定义键名 = 键码,可以去定制按键别名。 --> <!-- 准备好一个容器 --> <div id="root"> <h2>我是:{{name}}</h2> <input type="text" placeholder="按下回车,提示输入" @keyup.huiche="showInfo"/> <!-- //@keydown caps-lock @keyup.huiche.y 组合使用--> </div> <script type="text/javascript"> Vue.config.productionTip = false //以阻止 vue 在启动时生成生产提示。 Vue.config.keyCodes.huiche = 13 //定义了一个别名按键 const vm = new Vue({ el:'#root', data:{ name:'Jack', }, methods: { showInfo(e){ console.log(e.key,e.keyCode) // console.log(e.keyCode) // if(e.keyCode !== 13) return // console.log(e.target.value) } }, }) </script> </body> </html>
/* Roman to Integer [Easy] Roman numerals are represented by seven different symbols:I, V, X, L, C, D and M . Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example,2 is written as IIin Roman numeral, just two one's added together. 12 is written asXII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: * I can be placed before V (5) and X (10) to make 4 and 9. * X can be placed before L (50) and C (100) to make 40 and 90. * C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. Example 1: Input: s = "III" Output: 3 Example 2: Input: s = "IV" Output: 4 Example 3: Input: s = "IX" Output: 9 Example 4: Input: s = "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3. Example 5: Input: s = "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. Constraints: * 1 <= s.length <= 15 * s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). * It is guaranteedthat s is a valid roman numeral in the range [1, 3999]. */ ///<reference types="../../typings" /> const romanToInt = (s: string): number => { const [all, m, c, x, i] = s.match(/(M*)(C?M?D?C*)(X?C?L?X*)(I?X?V?I*)/); const tagMap: Record<string, Record<string, number>> = { i: { I: 1, II: 2, III: 3, IV: 4, V: 5, VI: 6, VII: 7, VIII: 8, IX: 9, '': 0, }, x: { X: 1, XX: 2, XXX: 3, XL: 4, L: 5, LX: 6, LXX: 7, LXXX: 8, XC: 9, '': 0, }, c: { C: 1, CC: 2, CCC: 3, CD: 4, D: 5, DC: 6, DCC: 7, DCCC: 8, CM: 9, '': 0, }, m: { M: 1, MM: 2, MMM: 3, '': 0, }, }; return tagMap.m[m] * 1000 + tagMap.c[c] * 100 + tagMap.x[x] * 10 + tagMap.i[i]; }; export default romanToInt;
import * as THREE from '../libs/three.module.js'; class Revolucion extends THREE.Object3D { constructor (gui, titleGui, perfil = []){ super(); this.createGUI(gui, titleGui); if (perfil.length == 0) { // cargar ejemplo de prueba perfil = [ new THREE.Vector3 (1, 0, 0), new THREE.Vector3 (2, 1, 0), new THREE.Vector3 (2, 2, 0), new THREE.Vector3 (2, 3, 0), new THREE.Vector3 (1, 4, 0), new THREE.Vector3 (1, 5, 0) ]; } this.revolucion = new THREE.Mesh( new THREE.LatheGeometry(perfil), new THREE.MeshPhongMaterial({color: 0xff0000}) ); this.add(this.revolucion); } createGUI(gui, titleGui){ this.guiControls = new function (){ // variables que queramos toquetear this.incrementoRotacion = 0; this.posX = 0; this.posZ = 0; } var folder = gui.addFolder(titleGui); folder.add(this.guiControls, 'incrementoRotacion', 0, 0.1, 0.01).name("Incrementar rotación: ").listen(); folder.add(this.guiControls, 'posX', -10, 10, 1).name("Posición en x: ").listen(); folder.add(this.guiControls, 'posZ', -10, 10, 1).name("Posición en Z: ").listen(); } update(){ this.rotation.y += this.guiControls.incrementoRotacion; this.revolucion.position.x = this.guiControls.posX; this.revolucion.position.z = this.guiControls.posZ; } }; export { Revolucion };
import { Injectable } from '@angular/core'; import { Quest } from '../models/quest.model'; @Injectable({ providedIn: 'root' }) export class QuestService { private quests: Quest[] = [ // Beispielquests { id: 1, title: 'Die Wissenssammler-Reise', description: 'Mutiger Abenteurer, deine Aufgabe ist es, das Reich des Wissens zu erforschen! Jeden Tag musst du 30 Seiten aus den uralten Büchern des Wissens lesen. Die Texte variieren täglich, sodass du dich auf eine Reise durch unterschiedlichste Welten und Epochen begibst.\n' + 'Dauer: 7 Tage, täglich wiederholbar\n' + 'Tägliche Ziele: Montag: Lese 30 Seiten eines historischen Romans. Belohnung: 20 Erfahrungspunkte + 1 goldener Wissensmünze.\n' + 'Dienstag: Lese 30 Seiten eines Wissenschaftsbuches. Belohnung: 25 Erfahrungspunkte + 2 Tränke der Klarheit.\n' + 'Mittwoch: Lese 30 Seiten Poesie. Belohnung: 15 Erfahrungspunkte + 1 Amulett der Eloquenz.\n' + 'Donnerstag: Lese 30 Seiten eines Fantasy-Romans. Belohnung: 30 Erfahrungspunkte + 1 Zauberstab der Fantasie.\n' + 'Freitag: Lese 30 Seiten eines Krimis. Belohnung: 20 Erfahrungspunkte + 1 Detektivlupe.\n' + 'Samstag: Lese 30 Seiten eines Sachbuchs. Belohnung: 25 Erfahrungspunkte + 1 Buch der Weisheit.\n' + 'Sonntag: Lese 30 Seiten deiner Wahl. Belohnung: 15 Erfahrungspunkte + 1 Geheimnisvolle Schriftrolle.\n' + 'Endbelohnung nach 7 Tagen: 150 Erfahrungspunkte + 1 Buch der Unendlichen Geschichten (spezieller Gegenstand, der dir erlaubt, an einem Tag deiner Wahl doppelt so viele Seiten zu lesen für doppelte Belohnungen).', experienceReward: 50, completed: false, items: [{name: '1x Buch der Unendlichen Geschichten ', description: 'Spezieller Gegenstand, der dir erlaubt, an einem Tag deiner Wahl doppelt so viele Seiten zu lesen für doppelte Belohnungen'}]} // Weitere Quests... ]; getQuests(): Quest[] { return this.quests; } completeQuest(questId: number): void { const quest = this.quests.find(q => q.id === questId); if (quest && !quest.completed) { quest.completed = true; // Hier könnte der LevelService aufgerufen werden, um Erfahrungspunkte hinzuzufügen. } } getQuestById(questId: number): Quest { return <Quest>this.quests.find(q => q.id === questId); } addQuest(quest: Quest): void { // Füge Logik zum Hinzufügen der Quest hinzu this.quests.push(quest); } }
import { useState, useContext } from 'react' // import { TodoContext } from '@/context/TodoContext' import useTodo from '@/hooks/useTodoContext' const TodoForm = () => { console.log('[TodoForm rerender]') // const { addTodo } = useContext(TodoContext) const { addTodo } = useTodo() const [todoContent, setTodoContent] = useState('') const handleSubmit = e => { e.preventDefault() if (!todoContent.trim()) { alert('請輸入待辦事項內容') return } addTodo(todoContent.trim()) setTodoContent('') } return ( <form onSubmit={handleSubmit} className="flex flex-col gap-2" > <div className="relative"> <input className="px-2 py-1 rounded" type="text" value={todoContent} onChange={e => setTodoContent(e.target.value)} placeholder="Type in Somethings ..." /> {todoContent && ( <span className="absolute -right-2 top-1/2 translate-x-full -translate-y-1/2"> Press Enter </span> )} </div> <button type="submit">Submit</button> </form> ) } export default TodoForm
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <title>HTML Academy: Кэт энерджи. Форма</title> </head> <body class="page"> <header class="page-header"> <a href="index.html" class="page-header__logo"> <img src="img/logotype.svg" width="191" height="38" alt="Cat energy"> </a> <button class="page-header__nav-toggle" type="button"><span class="visually-hidden">Открыть меню</span></button> <div class="main-nav__wrapper"> <nav class="main-nav main-nav--closed main-nav--nojs"> <ul class="main-nav__list site-list"> <li class="site-list__item site-list__item--active"><a href="index.html">Главная</a></li> <li class="site-list__item"><a href="catalog.html">Каталог продукции</a></li> <li class="site-list__item"><a href="#">Подбор программы</a></li> </ul> </nav> </div> </header> <main class="page-main"> <h1 class="page-main__title">Подбор программы</h1> <p class="page-main__text">Заполните анкету, и мы подберем программу питания для вашего кота</p> <section class="application"> <form class="application__form" method="post" action="https://echo.htmlacademy.ru"> <fieldset class="application__fieldset application__fieldset--cats-data"> <legend class="visually-hidden">Данные кота</legend> <ul class="application__list application__list--cats-data"> <li class="application__item application__item--cats-data"> <label class="application__label application__label--cats-data" for="name">Имя*:</label> <input class="application__input application__input--cats-data" type="text" name="cats-name" placeholder="Барсик" id="name" required> </li> <li class="application__item application__item--cats-data"> <label class="application__label application__label--cats-data" for="weight">Вес (кг):*</label> <input class="application__input application__input--cats-data" type="text" name="cats-weight" placeholder="7" id="weight" required> </li> <li class="application__item application__item--cats-data"> <label class="application__label application__label--cats-data" for="age">Возраст (лет):</label><input class="application__input application__input--cats-data" type="text" name="cats-age" placeholder="7" id="age"> </li> </ul> </fieldset> <fieldset class="application__fieldset application__fieldset--goals"> <legend class="visually-hidden">Цели</legend> <ul class="application__list application__list--goals"> <li class="application__item application__item--goals"> <input class="application__input application__input--goals" type="radio" name="goals" value="+" id="weight-loss" checked> <label class="application__label application__label--goals" for="weight-loss">похудение</label> </li> <li class="application__item application__item--goals"> <input class="application__input application__input--goals" type="radio" name="goals" value="-" id="weight-gain"> <label class="application__label application__label--goals" for="weight-gain">набор массы</label> </li> <li class="application__item application__item--goals"> <input class="application__input application__input--goals" type="radio" name="goals" value="0" id="unknown"> <label class="application__label application__label--goals" for="unknown">набор массы</label> </li> </ul> </fieldset> <fieldset class="application__fieldset application__fieldset--owner-contacts"> <legend class="application__title application__title--owner-contacts">Контактные данные (владельца кота)</legend> <ul class="application__list application__list--owner-contacts"> <li class="application__item application__item--owner-contacts"> <label class="application__label application__label--owner-contacts" for="owner-email">E-mail:*</label> <span class="application__input-wrapper application__input-wrapper--email"> <input class="application__input application__input--owner-contacts" type="email" name="email" placeholder="kuklachev@gmail.com" id="owner-email" required> </span> </li> <li class="application__item application__item--owner-contacts"> <label class="application__label application__label--owner-contacts" for="phone-number">Телефон:*</label> <span class="application__input-wrapper application__input-wrapper--phone"> <input class="application__input application__input--owner-contacts" type="tel" name="phone" placeholder="8 (960) 900-60-90" id="phone-number" required> </span> </li> </ul> </fieldset> <fieldset class="application__fieldset application__fieldset--comment"> <legend class="application__title application__title--comment">Комментарий</legend> <textarea class="application__textarea application__input" name="comment" placeholder="Расскажите обо всех повадках кота"></textarea> </fieldset> <fieldset class="application__fieldset application__fieldset--options"> <legend class="application__title application__title--options">Дополнительно</legend> <ul class="application__list application__list--options"> <li class="application__item application__item--options"> <input class="application__input application__input--options" type="checkbox" name="options" id="sweetener" checked> <label class="application__label application__label--options" for="sweetener">сахарозаменитель</label> </li> <li class="application__item application__item--options"> <input class="application__input application__input--options" type="checkbox" name="options" id="water"> <label class="application__label application__label--options" for="water">питьевая вода</label> </li> <li class="application__item application__item--options"> <input class="application__input application__input--options" type="checkbox" name="options" id="milk"> <label class="application__label application__label--options" for="milk">молоко</label> </li> <li class="application__item application__item--options"> <input class="application__input application__input--options" type="checkbox" name="options" id="vitamins"> <label class="application__label application__label--options" for="vitamins">витамины</label> </li> </ul> </fieldset> <div class="application__submit-wrapper"> <button class="application__button button-link button-link--form" type="submit">заказать</button> <p class="application__notification">* &mdash; Обязательные поля</p> </div> </form> </section> </main> <footer class="page-footer"> <section class="page-footer__address address"> <h2 class="visually-hidden">Адрес компании</h2> <div class="address__wrapper"> <p class="address__offer">приглашаем к сотрудничеству дилеров!</p> <p class="address__text">ул. Большая Конюшенная, д. 19/8 Санкт-Петербург</p> </div> <div class="address__marker"></div> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d1998.6037872533277!2d30.320858716096975!3d59.93871648187614!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4696310fca145cc1%3A0x42b32648d8238007!2z0JHQvtC70YzRiNCw0Y8g0JrQvtC90Y7RiNC10L3QvdCw0Y8g0YPQuy4sIDE5LzgsINCh0LDQvdC60YIt0J_QtdGC0LXRgNCx0YPRgNCzLCAxOTExODY!5e0!3m2!1sru!2sru!4v1614431945535!5m2!1sru!2sru" width="320" height="362" style="border:0;" allowfullscreen="" loading="lazy"></iframe> </section> <div class="page-footer__wrapper"> <a class="page-footer__logo" href="index.html"> <img src="img/footer-logo.svg" width="128" height="24" alt="Cat energy"> </a> <section class="page-footer__social social"> <ul class="social__list"> <li class="social__item"> <a class="social__link social__link--vk" href="https://vk.com/htmlacademy"> <span class="visually-hidden">Мы во Вконтакте</span> <svg class="social__icon" width="18" height="15"> <use xlink:href="#icon-vk"></use> </svg> </a> </li> <li class="social__item"> <a class="social__link social__link--instagram" href="https://www.instagram.com/htmlacademy"> <span class="visually-hidden">Мы в Инстаграме</span> <svg class="social__icon" width="9" height="19"> <use xlink:href="#icon-insta"></use> </svg> </a> </li> <li class="social__item"> <a class="social__link social__link--facebook" href="https://www.facebook.com/htmlacademy"> <span class="visually-hidden">Мы в Фейсбуке</span> <svg class="social__icon" width="20" height="14"> <use xlink:href="#icon-fb"></use> </svg> </a> </li> </ul> </div> <div class="page-footer__copyright copyright"> <a class="copyright__link" href="https://htmlacademy.ru/intensive/adaptive"> <p class="copyright__text">HTML Academy</p> <svg class="copyright__icon" width="27" height="34"> <use xlink:href="#htmlacademy"></use> </svg> </a> </div> </section> </footer> </body> </html>
class UserNotifierMailer < ApplicationMailer default :from => 'any_from_address@example.com' # send a signup email to the user, pass in the user object that contains the user's email address def send_confirmation_order(user) @user = user mail( :to => @user.email, :subject => 'Thanks for signing up for our amazing app' ) end private def user_params params.require(:user).permit(:email) end end
// // MobileVerificationViewController.swift // Pinely // import UIKit import CountryPickerView import libPhoneNumber_iOS class MobileVerificationViewController: ViewController { @IBOutlet weak var lblCountryCode: UILabel! @IBOutlet weak var ivFlag: UIImageView! @IBOutlet weak var lcCountryCodeOffset: NSLayoutConstraint! @IBOutlet weak var tfPhone: UITextField! @IBOutlet weak var vNextButtonContainer: UIView! @IBOutlet weak var lcNextButtonButton: NSLayoutConstraint! @IBOutlet weak var vPhoneContainer: UIView! var ipInfo: IpInfo? var countryCode: String! var locale: String! let phoneUtil = NBPhoneNumberUtil() override func viewDidLoad() { super.viewDidLoad() locale = ipInfo?.countryCode ?? "ES" let countries = CountrySelectView.shared.searchCountrys ?? [] let countryDict = countries.first(where: { $0.getString("locale") == locale }) countryCode = "+" + (countryDict?.getString("code") ?? "") ivFlag.image = UIImage(named: "CountryPicker.bundle/\(locale.uppercased())") showCountryCode(phone: tfPhone.text ?? "") NotificationCenter.default.addObserver( self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.tfPhone.becomeFirstResponder() } } deinit { NotificationCenter.default.removeObserver(self) } @objc func keyboardWillShow(notification: NSNotification) { let targetFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue let window = UIApplication.shared.windows[0] lcNextButtonButton.constant = (targetFrame?.height ?? 320) + 8 - window.safeAreaInsets.bottom view.layoutIfNeeded() } @objc func keyboardWillHide(notification: NSNotification) { lcNextButtonButton.constant = 8 } func countrySelected(countryDic: [String: Any]) { self.countryCode = "+" + (countryDic.getString("code") ?? "") var image = countryDic["countryImage"] as? UIImage if let locale = countryDic.getString("locale") { self.locale = locale if image == nil { image = UIImage(named: "CountryPicker.bundle/\(locale)") } } self.ivFlag.image = image self.showCountryCode(phone: self.tfPhone.text ?? "") DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.tfPhone.becomeFirstResponder() } } @IBAction func chooseCountry() { view.endEditing(true) self.performSegue(withIdentifier: "ChooseCountryCode", sender: self) } func showCountryCode(phone: String) { lblCountryCode.text = countryCode let fullText = countryCode + phone lcCountryCodeOffset.constant = -fullText.width(withConstrainedHeight: 24, font: lblCountryCode.font) / 2 vPhoneContainer.setNeedsLayout() vPhoneContainer.layoutIfNeeded() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let mobileVerificationConfirmationVC = segue.destination as? MobileVerificationConfirmationViewController { mobileVerificationConfirmationVC.phoneNumber = countryCode + (tfPhone.text ?? "") } } @IBAction func next() { view.endEditing(true) let mobilePhone = countryCode + (tfPhone.text ?? "") let loading = BlurryLoadingView.showAndStart() API.shared.sendSMSVerification(mobilePhone: mobilePhone) { (error) in loading.stopAndHide() if let error = error { self.show(error: error) } else { self.performSegue(withIdentifier: "MobileVerificationConfirmation", sender: self) } } } } extension MobileVerificationViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let text = textField.text, let textRange = Range(range, in: text) { let updatedText = text.replacingCharacters(in: textRange, with: string) if !updatedText.isEmpty && !updatedText.containsOnlyDigits { return false } showCountryCode(phone: updatedText) if (self.locale == "ES" && updatedText.count > 9) || updatedText.count > 16 { return false } } return true } }
using System.Web; using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace Quotations_Board_Backend.Controllers { [Route("api/[controller]")] [ApiController] // [Authorize(Roles = $"{CustomRoles.SuperAdmin}", AuthenticationSchemes = "Bearer")] public class InstitutionManagementController : ControllerBase { private readonly IMapper _mapper; private readonly IConfiguration _configuration; private readonly UserManager<PortalUser> _userManager; private readonly RoleManager<IdentityRole> _roleManager; public InstitutionManagementController( IMapper mapper, IConfiguration configuration, UserManager<PortalUser> userManager, RoleManager<IdentityRole> roleManager) { _mapper = mapper; _configuration = configuration; _userManager = userManager; _roleManager = roleManager; } [HttpGet("GetInstitutionUsers/{institutionId}")] public async Task<ActionResult<List<PortalUserDTO>>> GetInstitutionUsers(string institutionId) { LoginTokenDTO TokenContents = UtilityService.GetUserIdFromCurrentRequest(Request); List<PortalUserDTO> portalUserDTO = new List<PortalUserDTO>(); if (TokenContents == null) { return Unauthorized(); } var userId = UtilityService.GetUserIdFromToken(Request); using (var context = new QuotationsBoardContext()) { // get roles of curren logged in user if they are superAdmin, fetch all Institution and include Users var userRoles = await _userManager.GetRolesAsync(await _userManager.FindByIdAsync(userId)); if (institutionId == "index") { institutionId = TokenContents.InstitutionId; } List<Institution> institutions = context.Institutions .Include(i => i.PortalUsers) .Where(i => i.Id == institutionId) .ToList(); if (institutions.Count == 0) { return portalUserDTO; } //var mapper = new MapperConfiguration(cfg => cfg.CreateMap<PortalUser, PortalUserDTO>()).CreateMapper(); //var portalUsers = mapper.Map<List<PortalUserDTO>>(institution.PortalUsers); foreach (var institution in institutions) { foreach (var user in institution.PortalUsers) { var userRole = await _userManager.GetRolesAsync(user); if (userRole.Count > 0) { portalUserDTO.Add(new PortalUserDTO { Id = user.Id, FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, InstitutionId = user.InstitutionId, Role = userRole[0], IsActive = !user.LockoutEnabled, CreatedAt = institution.CreatedAt }); } } } return Ok(portalUserDTO); } } [HttpPost("AddInstitutionUser")] [Authorize(Roles = $"{CustomRoles.InstitutionAdmin}, {CustomRoles.SuperAdmin}, {CustomRoles.CapitalMarketsRegulator}, {CustomRoles.CentralBank}, {CustomRoles.NseSRO}", AuthenticationSchemes = "Bearer")] public async Task<ActionResult<PortalUserDTO>> AddInstitutionUser(NewPortalUser portalUserDTO) { LoginTokenDTO TokenContents = UtilityService.GetUserIdFromCurrentRequest(Request); if (TokenContents == null) { return Unauthorized(); } var userId = UtilityService.GetUserIdFromToken(Request); if (userId == null) { return Unauthorized(); } // what institution doe the user belong to? // Make sure they are institution admins too // var userRoles = await _userManager.GetRolesAsync(await _userManager.FindByIdAsync(userId)); // if (userRoles.Count == 0 || userRoles[0] != CustomRoles.InstitutionAdmin || TokenContents.InstitutionId != portalUserDTO.InstitutionId || userRoles[0] != CustomRoles.SuperAdmin) // { // return Unauthorized(); // } using (var context = new QuotationsBoardContext()) { var userAddingUser = await context.Users.FirstOrDefaultAsync(u => u.Id == userId); if (userAddingUser == null) { return Unauthorized(); } // role of the user adding the new user var userAddingUserRole = await _userManager.GetRolesAsync(userAddingUser); if (userAddingUserRole.Count == 0) { return Unauthorized(); } Institution? institution = await context.Institutions .Include(i => i.PortalUsers) .FirstOrDefaultAsync(i => i.Id == TokenContents.InstitutionId); if (institution == null) { return NotFound(); } // is the user superamin role contained in the many rols they may have if (userAddingUserRole.Contains(CustomRoles.SuperAdmin)) { // new user will also be a super admin portalUserDTO.Role = CustomRoles.SuperAdmin; } switch (institution.InstitutionType) { case "7": portalUserDTO.Role = CustomRoles.CentralBank; break; case "8": portalUserDTO.Role = CustomRoles.CapitalMarketsRegulator; break; case "9": portalUserDTO.Role = CustomRoles.NseSRO; break; default: portalUserDTO.Role = CustomRoles.InstitutionAdmin; break; } // check if user already exists PortalUser? existingUser = await _userManager.FindByEmailAsync(portalUserDTO.Email); if (existingUser != null) { // May exis but not verified/confirmed their email if (!await _userManager.IsEmailConfirmedAsync(existingUser)) { return BadRequest("User already exists but has not confirmed their email"); } return BadRequest("User already exists"); } var mapper = new MapperConfiguration(cfg => cfg.CreateMap<NewPortalUser, PortalUser>()).CreateMapper(); var portalUser = mapper.Map<PortalUser>(portalUserDTO); portalUser.InstitutionId = institution.Id; portalUser.UserName = portalUser.Email; portalUser.EmailConfirmed = false; context.Users.Add(portalUser); // Get the role var role = await _roleManager.FindByNameAsync(portalUserDTO.Role); if (role == null) { return BadRequest("Role does not exist"); } // add user to role // add user to role of InstitutionAdmin var userRole = new IdentityUserRole<string> { RoleId = role.Id, UserId = portalUser.Id }; context.UserRoles.Add(userRole); // Generate Email Confirmation Token var token = await _userManager.GenerateEmailConfirmationTokenAsync(portalUser); var encodedUserId = HttpUtility.UrlEncode(portalUser.Id); var encodedCode = HttpUtility.UrlEncode(token); var callbackUrl = $"{_configuration["FrontEndUrl"]}/complete-institution-setup?userId={encodedUserId}&code={encodedCode}"; // add user to institution // institution.PortalUsers.Add(portalUser); await context.SaveChangesAsync(); // send email to user string emailBody = $@" <html> <head> <style> body {{ font-family: Arial, sans-serif; background-color: #f5f5f5; padding: 20px; }} .container {{ max-width: 600px; margin: 0 auto; background-color: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }} a.button {{ display: inline-block; text-decoration: none; background-color: #0052CC; color: #ffffff; padding: 10px 20px; border-radius: 5px; font-weight: bold; }} a.button:hover {{ background-color: #003E7E; }} </style> </head> <body> <div class='container'> <p>Dear {portalUser.FirstName},</p> <p>Your account has been created on the Quotations Board Portal. Please follow the link below to complete your account setup:</p> <a href='{callbackUrl}' class='button'>Complete Account Setup</a> </div> </body> </html>"; await UtilityService.SendEmailAsync(portalUser.Email, "Quotations Board Portal Account Created", emailBody); // return user //PortalUserDTO portalUserDTOToReturn = _mapper.Map<PortalUserDTO>(portalUser); return Ok(); } } [HttpPost("GetInstitutionApiKey")] [Authorize(Roles = CustomRoles.InstitutionAdmin, AuthenticationSchemes = "Bearer")] public async Task<ActionResult> GetInstitutionApiKey() { LoginTokenDTO TokenContents = UtilityService.GetUserIdFromCurrentRequest(Request); if (TokenContents == null) { return Unauthorized(); } using (var context = new QuotationsBoardContext()) { Institution? institution = await context.Institutions .Include(i => i.PortalUsers) .FirstOrDefaultAsync(i => i.Id == TokenContents.InstitutionId); if (institution == null) { return NotFound(); } // is the api api access active? if (!institution.IsApiAccessEnabled) { return BadRequest("API access is inactive"); } // get hold of a user with the APIUser role var apiUser = await _userManager.GetUsersInRoleAsync(CustomRoles.APIUser); var existingApiUser = apiUser.FirstOrDefault(u => u.InstitutionId == institution.Id); if (existingApiUser == null) { return BadRequest("Seems like the API user does not exist"); } // generate a new API key var apiKey = Guid.NewGuid().ToString(); // API KEY ACTS AS THE PASSWORD SO UPDATE THE USER PASSWORD var result = await _userManager.RemovePasswordAsync(existingApiUser); if (!result.Succeeded) { return BadRequest(result.Errors); } result = await _userManager.AddPasswordAsync(existingApiUser, apiKey); if (!result.Succeeded) { return BadRequest(result.Errors); } string emailBody = $@" <html> <head> <style> body {{ font-family: Arial, sans-serif; background-color: #f5f5f5; padding: 20px; }} .container {{ max-width: 600px; margin: 0 auto; background-color: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }} .api-key {{ background-color: #f0f0f0; padding: 10px; border-radius: 5px; font-family: monospace; }} </style> </head> <body> <div class='container'> <p>Hello,</p> <p>Your Client Secret has been reset. Your new API key is:</p> <div class='api-key'>{apiKey}</div> </div> </body> </html>"; await UtilityService.SendEmailAsync(existingApiUser.Email, "Quotations Board Portal API Key Reset", emailBody); return Ok(apiKey); } } [HttpPut("UpdateInstitutionUser")] public async Task<ActionResult> UpdateInstitutionUser(EditPortalUser portalUserDTO) { LoginTokenDTO TokenContents = UtilityService.GetUserIdFromCurrentRequest(Request); if (TokenContents == null) { return Unauthorized(); } using (var context = new QuotationsBoardContext()) { Institution? institution = await context.Institutions .Include(i => i.PortalUsers) .FirstOrDefaultAsync(i => i.Id == TokenContents.InstitutionId); if (institution == null) { return NotFound(); } // check if user exists PortalUser? existingUser = await _userManager.FindByEmailAsync(portalUserDTO.Email); if (existingUser == null) { return BadRequest("User does not exist"); } // if user is assigend institution admin role, ensure there is at least one admin and grant the former admin role the role occupied by the new admin var UserToBeUpdatedCurrentRole = await _userManager.GetRolesAsync(existingUser); if (UserToBeUpdatedCurrentRole.Count > 0 && UserToBeUpdatedCurrentRole[0] != CustomRoles.InstitutionAdmin) { // What role is the user being assigned? var newRole = await _roleManager.FindByNameAsync(portalUserDTO.Role); // is it InstitutionAdmin? if (newRole.Name == CustomRoles.InstitutionAdmin) { // who holds the InstitutionAdmin role within the institution? var otherAdmins = await _userManager.GetUsersInRoleAsync(CustomRoles.InstitutionAdmin); // only interested in other admins within the same institution var existingSchoolAdmin = otherAdmins.FirstOrDefault(u => u.InstitutionId == institution.Id); if (existingSchoolAdmin == null) { return BadRequest("There must be at least one admin"); } // Get Inst Amin Role var existingSchoolAdminRole = await _userManager.GetRolesAsync(existingSchoolAdmin); if (existingSchoolAdminRole.Count > 0) { // Remove Exitinsg admin from current role await _userManager.RemoveFromRoleAsync(existingSchoolAdmin, existingSchoolAdminRole[0]); //Assign them the role previously held by the new admin await _userManager.AddToRoleAsync(existingSchoolAdmin, UserToBeUpdatedCurrentRole[0]); } } } // update user existingUser.FirstName = portalUserDTO.FirstName; existingUser.LastName = portalUserDTO.LastName; // update user role var existingRole = await _userManager.GetRolesAsync(existingUser); // Ensure user can only have one role at any given time if (existingRole.Count > 0) { await _userManager.RemoveFromRoleAsync(existingUser, existingRole[0]); } var result = await _userManager.AddToRoleAsync(existingUser, portalUserDTO.Role); if (!result.Succeeded) { return BadRequest(result.Errors); } // update user details if any have changed existingUser.FirstName = portalUserDTO.FirstName; existingUser.LastName = portalUserDTO.LastName; await _userManager.UpdateAsync(existingUser); // await context.SaveChangesAsync(); // return user return Ok(); } } // Disable User [HttpDelete("DisableInstitutionUser/{userId}")] public async Task<ActionResult> DisableInstitutionUser(string userId) { LoginTokenDTO TokenContents = UtilityService.GetUserIdFromCurrentRequest(Request); if (TokenContents == null) { return Unauthorized(); } using (var context = new QuotationsBoardContext()) { Institution? institution = await context.Institutions .Include(i => i.PortalUsers) .FirstOrDefaultAsync(i => i.Id == TokenContents.InstitutionId); if (institution == null) { return NotFound(); } // check if user exists PortalUser? existingUser = await _userManager.FindByIdAsync(userId); if (existingUser == null) { return BadRequest("User does not exist"); } var existingAdminRole = await _userManager.GetRolesAsync(existingUser); if (existingAdminRole.Count > 0 && existingAdminRole[0] == CustomRoles.InstitutionAdmin) { var otherAdmins = await _userManager.GetUsersInRoleAsync(CustomRoles.InstitutionAdmin); if (otherAdmins.Count == 1) { return BadRequest("Cannot disable the only admin"); } } existingUser.LockoutEnabled = true; existingUser.LockoutEnd = DateTime.Now.AddYears(100); await _userManager.UpdateAsync(existingUser); // await context.SaveChangesAsync(); // Send email to user notifying them that their account has been disabled string emailBody = $@" <html> <head> <style> body {{ font-family: Arial, sans-serif; background-color: #f5f5f5; padding: 20px; }} .container {{ max-width: 600px; margin: 0 auto; background-color: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }} .warning {{ color: #D9534F; /* Bootstrap 'danger' color */ font-weight: bold; }} </style> </head> <body> <div class='container'> <p>Dear {existingUser.FirstName},</p> <p class='warning'>Your account has been disabled on the Quotations Board Portal.</p> </div> </body> </html>"; await UtilityService.SendEmailAsync(existingUser.Email, "Quotations Board Portal Account Disabled", emailBody); return Ok(); } } // Enable User [HttpPut("EnableInstitutionUser/{userId}")] public async Task<ActionResult> EnableInstitutionUser(string userId) { LoginTokenDTO TokenContents = UtilityService.GetUserIdFromCurrentRequest(Request); if (TokenContents == null) { return Unauthorized(); } using (var context = new QuotationsBoardContext()) { Institution? institution = await context.Institutions .Include(i => i.PortalUsers) .FirstOrDefaultAsync(i => i.Id == TokenContents.InstitutionId); if (institution == null) { return NotFound(); } // check if user exists PortalUser? existingUser = await _userManager.FindByIdAsync(userId); if (existingUser == null) { return BadRequest("User does not exist"); } existingUser.LockoutEnabled = false; existingUser.LockoutEnd = null; await _userManager.UpdateAsync(existingUser); await context.SaveChangesAsync(); // Send email to user notifying them that their account has been enabled string emailBody = $@" <html> <head> <style> body {{ font-family: Arial, sans-serif; background-color: #f5f5f5; padding: 20px; }} .container {{ max-width: 600px; margin: 0 auto; background-color: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }} a.button {{ display: inline-block; text-decoration: none; background-color: #0052CC; color: #ffffff; padding: 10px 20px; border-radius: 5px; font-weight: bold; }} a.button:hover {{ background-color: #003E7E; }} </style> </head> <body> <div class='container'> <p>Dear {existingUser.FirstName},</p> <p>Your account has been enabled on the Quotations Board Portal. Please follow the link below to log in to your account:</p> <a href='{_configuration["FrontEndUrl"]}' class='button'>Login</a> </div> </body> </html>"; await UtilityService.SendEmailAsync(existingUser.Email, "Quotations Board Portal Account Enabled", emailBody); return Ok(); } } // Disable an Institution [HttpPost("DisableInstitution/{institutionId}")] [Authorize(Roles = CustomRoles.SuperAdmin, AuthenticationSchemes = "Bearer")] public async Task<ActionResult> DisableInstitution(string institutionId) { try { LoginTokenDTO TokenContents = UtilityService.GetUserIdFromCurrentRequest(Request); if (TokenContents == null) { return Unauthorized(); } Institution? institution; using (var context = new QuotationsBoardContext()) { institution = await context.Institutions .Include(i => i.PortalUsers) .FirstOrDefaultAsync(i => i.Id == institutionId); } if (institution == null) { return NotFound(); } var superAdmin = await _userManager.GetUsersInRoleAsync(CustomRoles.SuperAdmin); var superAdminInstitution = superAdmin.FirstOrDefault(u => u.InstitutionId == institution.Id); institution.Status = InstitutionStatus.Inactive; institution.DeactivatedAt = DateTime.Now; foreach (var user in institution.PortalUsers) { await DisableUser(user); } using (var context = new QuotationsBoardContext()) { context.Institutions.Update(institution); await context.SaveChangesAsync(); } var institutionAdmin = await _userManager.GetUsersInRoleAsync(CustomRoles.InstitutionAdmin); var institutionAdminInstitution = institutionAdmin.FirstOrDefault(u => u.InstitutionId == institution.Id); if (institutionAdminInstitution == null) { return BadRequest("Institution Admin not found"); } // Send email notification string emailBody = $@" <html> <head> <style> body {{ font-family: Arial, sans-serif; background-color: #f5f5f5; padding: 20px; }} .container {{ max-width: 600px; margin: 0 auto; background-color: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }} .warning {{ color: #D9534F; /* Bootstrap 'danger' color */ font-weight: bold; }} </style> </head> <body> <div class='container'> <p>Dear {institution.OrganizationName},</p> <p class='warning'>Your account has been disabled on the Quotations Board Portal.</p> </div> </body> </html>"; await UtilityService.SendEmailAsync(institutionAdminInstitution.Email, "Quotations Board Portal Account Disabled", emailBody); return Ok(); } catch (Exception Ex) { UtilityService.HandleException(Ex); return StatusCode(StatusCodes.Status500InternalServerError, Ex.Message); } } private async Task DisableUser(PortalUser user) { user.LockoutEnabled = true; user.LockoutEnd = DateTime.Now.AddYears(100); using (var context = new QuotationsBoardContext()) { context.Entry(user).State = EntityState.Modified; await context.SaveChangesAsync(); } } // Enable an Institution [HttpPost("EnableInstitution/{institutionId}")] [Authorize(Roles = CustomRoles.SuperAdmin, AuthenticationSchemes = "Bearer")] public async Task<ActionResult> EnableInstitution(string institutionId) { LoginTokenDTO TokenContents = UtilityService.GetUserIdFromCurrentRequest(Request); if (TokenContents == null) { return Unauthorized(); } Institution? institution; using (var context = new QuotationsBoardContext()) { institution = await context.Institutions .FirstOrDefaultAsync(i => i.Id == institutionId); } if (institution == null) { return NotFound(); } institution.Status = InstitutionStatus.Active; // institution.DeactivatedAt = DateTime.Now; // using (var context = new QuotationsBoardContext()) { context.Institutions.Update(institution); await context.SaveChangesAsync(); } await EnableAllUsersInInstitution(institutionId); // get user with InstitutionAdmin role and send them an email var institutionAdmin = await _userManager.GetUsersInRoleAsync(CustomRoles.InstitutionAdmin); var institutionAdminInstitution = institutionAdmin.FirstOrDefault(u => u.InstitutionId == institution.Id); if (institutionAdminInstitution == null) { return BadRequest("Institution Admin not found"); } // Send email notification string emailBody = $@" <html> <head> <style> body {{ font-family: Arial, sans-serif; background-color: #f5f5f5; padding: 20px; }} .container {{ max-width: 600px; margin: 0 auto; background-color: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }} a.button {{ display: inline-block; text-decoration: none; background-color: #0052CC; color: #ffffff; padding: 10px 20px; border-radius: 5px; font-weight: bold; }} a.button:hover {{ background-color: #003E7E; }} </style> </head> <body> <div class='container'> <p>Dear {institutionAdminInstitution.LastName},</p> <p>Your account has been enabled on the Quotations Board Portal. Please follow the link below to log in to your account:</p> <a href='{_configuration["FrontEndUrl"]}' class='button'>Login</a> </div> </body> </html>"; await UtilityService.SendEmailAsync(institutionAdminInstitution.Email, "Quotations Board Portal Account Enabled", emailBody); return Ok(); } private async Task EnableAllUsersInInstitution(string institutionId) { var users = await GetUsersInInstitutionAsync(institutionId); // Assuming such a method exists or can be implemented. foreach (var user in users) { user.LockoutEnabled = false; user.LockoutEnd = null; using (var context = new QuotationsBoardContext()) { context.Entry(user).State = EntityState.Modified; await context.SaveChangesAsync(); } } } private async Task<List<PortalUser>> GetUsersInInstitutionAsync(string institutionId) { using (var context = new QuotationsBoardContext()) { return await context.Users.Where(u => u.InstitutionId == institutionId).ToListAsync(); } } } }
import p5 from 'p5' export const mySketch = (p) => { // auxiliary const linspace = (vmin, vmax, n) => Array.from({ length: n }, (_, i) => vmin + ((vmax - vmin) * i) / n); // parameters // ... visual const SCALE = 1.0; // global scale // ... physics const PERIOD = 1.0; // spin period const OMEGA = (2.0 * Math.PI) / PERIOD; const CHI = 0.4; // inclination in radians const RLC = 200.0; // light-cylinder radius const RADIUS = 1.0; // neutron star radius // vectors const vOMEGA = new p5.Vector(0.0, 0.0, 1.0); // angular velocity unit vector const vMU = (t) => p.createVector( Math.cos(OMEGA * t) * Math.sin(CHI), Math.sin(OMEGA * t) * Math.sin(CHI), Math.cos(CHI) ); // magnetic moment vector (as a function of time) // ... A and B are the basis vectors in the rotating equatorial plane const vA = (t) => p5.Vector.div(p5.Vector.cross(vOMEGA, vMU(t)), Math.sin(CHI)); const vB = (t) => p5.Vector.cross(vA(t), vMU(t)); let model = undefined; const makeCurrentSheet = (rmax, nr, nphi) => new p5.Geometry( 1, 1, function createGeometry() { const phis = linspace(0.0, 2.0 * Math.PI, nphi); const radii = linspace(0.0, rmax, nr); const points = phis.map(ang => radii.map(t => p5.Vector.mult(p5.Vector.add(p5.Vector.mult(vA(-t), Math.cos(ang)), p5.Vector.mult(vB(-t), Math.sin(ang))), RLC * (1.0 + t)))); this.vertices.push( ...[].concat.apply([], points) ); const npoints = nr * nphi; for (let j = 0; j < nphi; j++) { for (let i = 0; i < nr - 1; i++) { let I = i + j * nr; this.faces.push([I % npoints, (I + 1) % npoints, (nr + I) % npoints]); this.faces.push([(nr + I) % npoints, (I + 1) % npoints, (nr + I + 1) % npoints]); } } this.computeNormals(); this.gid = 'tri'; } ); p.preload = () => { model = makeCurrentSheet(2.0, 1000, 100); } p.setup = () => { p.createCanvas(window.innerWidth, window.innerHeight, p.WEBGL); p.perspective(1.1, p.width / p.height, 0.1, 50000); } p.draw = () => { p.background(220); p.orbitControl(2, 1); // p.debugMode(); p.smooth(); p.push(); { p.rotateX(Math.PI / 2); p.noStroke(); p.ambientLight(255); p.directionalLight(255, 255, 255, -2000, -2000, 0); p.directionalLight(255, 255, 255, 2000, 2000, 1000); p.push(); { p.ambientMaterial(130, 50, 250); p.sphere(RADIUS, 32, 64); p.ambientMaterial(25, 50, 25); p.model(model); } p.pop(); } p.pop(); } p.windowResized = () => { p.resizeCanvas(window.innerWidth, window.innerHeight); p.perspective(1.2, p.width / p.height, 0.1, 10000); } }
--- title: gluestack-ui VStack Component | Installation, Usage, and API description: VStack aligns items vertically. Column is also an alias for VStack. pageTitle: VStack pageDescription: VStack aligns items vertically. Column is also an alias for VStack. showHeader: true --- import { Meta } from '@storybook/addon-docs'; <Meta title="components/Layout/VStack" /> import { VStack, Box } from './VStack'; import { transformedCode } from '../../../utils'; import { AppProvider, CodePreview, Table, TableContainer, Text, InlineCode, } from '@gluestack/design-system'; import Wrapper from '../../Wrapper'; ## Basic <AppProvider> <CodePreview showComponentRenderer={true} showArgsController={false} metaData={{ code: ` <VStack space="md"> <Box sx={{ w: 100, h: 100, bg: '$blue300' }} /> <Box sx={{ w: 100, h: 100, bg: '$blue400' }} /> <Box sx={{ w: 100, h: 100, bg: '$blue500' }} /> </VStack> `, transformCode: (code) => { return transformedCode(code); }, scope: { Wrapper, VStack, Box, }, argsType: {}, }} /> </AppProvider> <br /> ## Installation This command copies the `VStack` component to your project. ```bash npx gluestack-ui add vstack ``` ### Import ```bash // import the component from your components folder import { VStack } from './components'; ``` <br /> ### Anatomy The VStack component consists of the following parts: ```jsx export default () => ( <VStack> <Box>Box</Box> <Box>Box</Box> </VStack> ); ``` ### API Reference #### VStack It inherits all the properties of React Native's [View](https://reactnative.dev/docs/view#props) component. <AppProvider> <TableContainer> <Table> <Table.THead> <Table.TR> <Table.TH> <Table.TText>Prop</Table.TText> </Table.TH> <Table.TH> <Table.TText>Type</Table.TText> </Table.TH> <Table.TH> <Table.TText>Default</Table.TText> </Table.TH> <Table.TH> <Table.TText>Description</Table.TText> </Table.TH> </Table.TR> </Table.THead> <Table.TBody> <Table.TR> <Table.TD> <Table.TText> <InlineCode>space</InlineCode> </Table.TText> </Table.TD> <Table.TD> <Table.TText>{`number | string | undefined`}</Table.TText> </Table.TD> <Table.TD> <Table.TText>-</Table.TText> </Table.TD> <Table.TD> <Table.TText>{`It sets the space between children.`}</Table.TText> </Table.TD> </Table.TR> </Table.TBody> </Table> </TableContainer> </AppProvider> <br /> <br /> ### Examples #### VStack Reversed <AppProvider> <CodePreview showComponentRenderer={true} showArgsController={false} metaData={{ code: ` <VStack space="md" reversed> <Box sx={{ w: 100, h: 100, bg: '$blue300' }} /> <Box sx={{ w: 100, h: 100, bg: '$blue400' }} /> <Box sx={{ w: 100, h: 100, bg: '$blue500' }} /> </VStack> `, transformCode: (code) => { return transformedCode(code); }, scope: { Box, Wrapper, VStack }, argsType: {}, }} /> </AppProvider> <br /> ## Advanced ### Customizing the VStack We have a function called `createVStack` which can be used to create a custom VStack component. This function takes in a configuration object which contains the styled components that you want to use for the VStack. You can refer [dank.style](https://dank.style/) for more information on how to use styled components. #### Usage ```jsx // import the styles import { Root, Spacer } from '../components/vstack/styled-components'; // import the createVStack function import { createVStack } from '@gluestack-ui/vstack'; // Understanding the API const VStack = createVStack({ Root, Spacer, }); // Using the vstack component export default () => <VStack />; ``` Default styling of the component can be found in the `components/vstack` file. For reference, you can view the [source code](https://github.com/gluestack/gluestack-ui/blob/development/example/storybook/src/ui-components/VStack/index.tsx) of the styled `VStack` component.
import fs from 'fs' export const setVersions = (options: { fileResponse: string, currentYalcPath: string, packageName: string, version: string, currentYalcCopyPackages: string[] }): any => { const yalc = JSON.parse(options.fileResponse); // Setting the yalc with the current version if(yalc.packages[options.packageName]) { yalc.packages[options.packageName].replaced = options.version; console.log(`Setting ${options.packageName} to ${options.version}`) } else { console.error(`Package ${options.packageName} not found in external file`) } // Optional copyPackages, copies the version of the current yalc.lock to the input file if(options.currentYalcCopyPackages) { for(const item of options.currentYalcCopyPackages) { if(yalc.packages[item]) { const version = getVersionFromYalc({ currentYalcPath: options.currentYalcPath, packageName: item }) if(version) { yalc.packages[item].replaced = version console.log(`Copying version from current ${options.currentYalcPath} - Setting ${item} to ${version}`) } else { console.error(`No version found for ${item} in the current ${options.currentYalcPath}`) } } else { console.error(`${item} not found in the current ${options.currentYalcPath}`) } } } return yalc; } // Copy the current version defined in this project to the external project const getVersionFromYalc = (options: { currentYalcPath: string, packageName: string }): string | null => { const currentYalc = readCurrentYalc(options.currentYalcPath) if(!currentYalc) { console.error(`No could not read the current ${options.currentYalcPath}`) return null; } return currentYalc.packages?.[options.packageName]?.replaced } const readCurrentYalc = (currentYalcPath: string):any => { const buffer = fs.readFileSync(currentYalcPath) return JSON.parse(buffer.toString('utf8')) } export const generateCommitMessageFromYalc = (yalc: any) => { const items = []; for(const i in yalc.packages) { items.push(`Package: ${i} -- Version: ${yalc.packages[i].replaced}`) } return `Yalc.lock updated ${items.join(', ')}` }
# Batch 어플리케이션과 Spring Batch ## Batch 정의 **일괄 처리를 위한 오픈소스 프레임워크**이다. **로깅 / 추적, 트랜잭션 관리, 작업 처리 통계, 작업 재시작, 건너뛰기, 리소스 관리** 등 대용량 레코드 처리에 필수적인 재사용 가능한 기능을 제공한다. **최적화 및 파티셔닝 기술을 통해 대용량 및 고성능 배치 작업을 가능**하게 하는 고급 기술 서비스 및 기능을 제공한다. ## Batch 목적 및 사례 만약 매일 어제의 데이터를 집계해야 한다면? 웹이라면 톰캣 + spring mvc 로 뚜닥뚜닥 코드 + SQL 조합으로 어찌저찌해서 보내겠지만 집계 데이터가 너무 커서 읽는데 서버 부하가 많이 생긴다면? CPU, I/O 등의 자원을 다 써버리니… 부하가 올 수 밖에 없다. 그리고 이 집계 기능은 하루에 한 번밖에 수행하지 않는다. 근대 이 한번밖에 수행하지 않는 기능 때문에 API를 만드는건 너무 낭비가 아닐까? 또! 데이터가 너~~무 많아서 처리중에 실패가 났는데 한.. 5만번째에서 실패했다면, 5만 1번째부터 다시 실행할 수 있게 하면 얼마나 좋을까? 또! 누군가 같은 파라미터로 같은 함수를 실행하면 실패하게 하는 기능이 있다면 얼마나 좋을까? 이런 단발성 대용량 데이터를 처리하는 어플리케이션이 배치 어플리케이션이다. 즉, 배치 어플리케이션을 사용하면 위에서 말 한것들이 모두 가능해진다~! 배치 어플리케이션 중에서 Spring 진영의 Spring Batch를 알아보자. 배치 어플리케이션은 - ***대용량 데이터*** - ***자동화*** - ***견고성*** - ***신뢰성*** - ***성능*** 이 다섯가지 조건을 만족해야 한다. 대용량의 데이터를 처리할 수 있어야 하며, 사용자 개입 없이 자동화로 처리할 수 있어야 하며, 잘못된 데이터를 다뤄도 충돌이나 중단이 없어야 하고, 뭐가 잘못되었는지 로깅이나 알림으로 추적할 수 있어야 하며, 지정한 시간 안에 처리를 완료하거나, 다른 어플리케이션을 방해하지 않도록 수행되어야 한다! 많은 거래가 이루어지는 이커머스 사이트의 경우 하루 거래건이 최소 50 ~ 100만 정도이다. 이럴 경우 이와 관련된 데이터는 최소 100~200만 row 이상이고, 한 달이면 5000만 ~ 1억까지 된다. 이 많은 데이터를 실시간 집계 쿼리로 조회하기엔 서버 부하가 너무 심해진다. 그래서 **매일 새벽 전날의 매출 집계 데이터를 만들어서** **외부 요청이 올 경우 미리 만들어둔 집계 데이터를 바로 전달하면** **성능과 부하를 모두 잡을 수 있다.** ## Spring Batch Spring 프레임워크의 DI + AOP + 추상화 기능과 Accenture의 배치 노하우가 합쳐진 프래임워크이다. Spring Batch 4.0 (Spring Boot 2.0) 에서 지원하는 Reader & Writer는 아래와 같다. 참고로 Reader는 데이터를 읽어오는 모듈이며, Writer는 데이터를 쓰는 모듈이다. | DataSource | 기술 | 설명 | | --- | --- | --- | | Database | JDBC | 페이징, 커서, 일괄 업데이트 등 사용 가능 | | Database | Hibernate | 페이징, 커서 사용 가능 | | Database | JPA | 페이징 사용 가능 (현재 버전에선 커서 없음) | | File | Flat file | 지정한 구분자로 파싱 지원 | | File | XML | XML 파싱 지원 | ## Spring Batch 아키텍쳐 ![Untitled](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ba3fd116-ce8b-4d87-a12c-df8975af6b49/Untitled.png) ### Run Tier - Application의 scheduling, 실행을 담당한다. - 스프링 배치는 따로 스케쥴링 기능은 제공하지 않는다! - Quartz나 Cron을 이용하도록 권고함. ### Job Tier - 전체적인 Job의 수행을 책임진다. - Job 내의 각 Step을 정책에 따라 순차적으로 수행 ### Application Tier - Job을 수행하는데 필요한 Component ### Data Tier - Database, File 등 물리적 데이터소스 ## Spring Batch 와 스케쥴러의 차이 Spring Batch 를 통해 Batch Job을 만들었으면 이걸 주기적으로 돌려주는 무언가가 필요하다. 배치와 스케쥴러를 혼동하는 사람들이 종종 있는데 이것은 완전히 다른 개념이다. **배치는 실시간으로 처리를 하는것이 아닌일괄 처리를 뜻하며 보통은 특정 시간에 행**해진다. 이 **특정 시간을 정의해 주는 것은스케쥴러의 역할**이다. # ref --- [https://dalgun.dev/blog/2019-10-30/spring-batch](https://dalgun.dev/blog/2019-10-30/spring-batch) [https://www.youtube.com/watch?v=1xJU8HfBREY](https://www.youtube.com/watch?v=1xJU8HfBREY) [https://intrepidgeeks.com/tutorial/getting-started-with-spring-batch-example](https://intrepidgeeks.com/tutorial/getting-started-with-spring-batch-example) [https://medium.com/myrealtrip-product/spring-batch-처음부터-시작하기-3c6a5db0646d](https://medium.com/myrealtrip-product/spring-batch-%EC%B2%98%EC%9D%8C%EB%B6%80%ED%84%B0-%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0-3c6a5db0646d) [https://oingdaddy.tistory.com/38](https://oingdaddy.tistory.com/38) [https://jojoldu.tistory.com/324](https://jojoldu.tistory.com/324)
import { exec } from 'child_process' import { readFileSync } from 'fs' import semverSort from 'semver/functions/rsort' import { APP_FOLDER, DEFAULT_VERSION_LIST, PACKAGE_NAME, } from '../commands/constants' import chalk from 'chalk' export function getInstalledVersion(appDir: string) { let version = null try { const packageJson = readFileSync( `${appDir}/${APP_FOLDER}/package.json`, 'utf-8', ) version = JSON.parse(packageJson).version } catch (e) { // Do nothing } return version } export default async function getLatitudeVersions({ onFetch, }: { onFetch?: () => void } = {}) { const command = `npm view ${PACKAGE_NAME} versions --json` return new Promise<string[]>((resolve, reject) => { exec(command, (error, stdout, stderr) => { onFetch?.() if (error) reject(error) if (stderr) { console.log(chalk.yellow(stderr)) } let versions: string[] | undefined = undefined try { versions = JSON.parse(stdout) } catch (e) { reject(e) } const loose = false // Don't include pre-release versions if (!versions) return resolve(DEFAULT_VERSION_LIST) const sorted = semverSort(versions, loose).slice(0, 10) // Last 10 versions resolve(sorted) }) }) }
import axios from 'axios'; import React, { useEffect, useState } from 'react' import { Link, useNavigate, useParams } from 'react-router-dom'; export default function EditUsers() { const usedavigate = useNavigate(); React.useEffect(()=>{ if(!localStorage.getItem('auth')) usedavigate('/') },[]) let navigate = useNavigate(); const {id}=useParams(); const [user,setUser] = useState({ name:"", email:"", username:"", mobile:"" }) const{name,email,username,mobile} = user const onInputChange = (e) =>{ setUser({...user,[e.target.name]:e.target.value}); }; useEffect(() =>{ loadUsers(); },[] ) const onSubmit = async (e) => { e.preventDefault(); await axios.put(`http://localhost:8080/user/${id}`,user) navigate("/Home") }; const loadUsers = async (e)=>{ const result = await axios.get(`http://localhost:8080/user/${id}`) setUser(result.data); } return ( <div className='container'> <div className='row'> <div className='col-md-6 offset-md-3 border rounded p-4 mt-2 shadow'> <h2 className='text-center m-4'>Edit User</h2> <form onSubmit={(e) => onSubmit(e)}> <div className='mb-3'> <label htmlFor='Name' className='form-label'>Name</label> <input type='text' className='form-control' placeholder='Enter Your name' name ='name' value={name} onChange={(e)=>onInputChange(e)}></input> </div> <div className='mb-3'> <label htmlFor='Email' className='form-label'>Email</label> <input type='text' className='form-control' placeholder='Enter Your email' name ='email' value={email} onChange={(e)=>onInputChange(e)}></input> </div> <div className='mb-3'> <label htmlFor='User Name' className='form-label'>User Name</label> <input type='text' className='form-control' placeholder='Enter Your User Name' name ='username' value={username} onChange={(e)=>onInputChange(e)}></input> </div> <div className='mb-3'> <label htmlFor='Mobile' className='form-label'>Mobile</label> <input type='text' className='form-control' placeholder='Enter Your Mobile No' name ='mobile' value={mobile} onChange={(e)=>onInputChange(e)}></input> </div> <button type='submit' className='btn btn-outline-primary'>submit</button> <Link className='btn btn-outline-danger mx-2' to={"/Home"}>Cancel</Link> </form> </div> </div> </div> ) }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Clase 8 - Animaciones y mas</title> <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet"> <link rel="stylesheet" href="style.css"> </head> <body> <div class="cajitas"> <div class="cajita cajita1"> Cajita 1 </div> <div class="cajita cajita2"> Cajita 2 </div> <div class="cajita cajita3"> Cajita 3 </div> <div class="cajita cajita4"> Cajita 4 </div> </div> <div class="tarjetitas"> <div class="tarjetita tarjetita1"> <img src="https://via.placeholder.com/400x250" alt="Placeholder"> <div class="info"> <h4 class="titulo">Tarjetita 1</h4> <p class="descripcion">Lofl djhfh dhbdsh wdujwduhnud wunhweubeh weuhweueb webewubeu jqwnffnu fbhbfndu wiuwbuiw fiwuhfufb wfufuui fuibfuebi lol wubfiwbifw fwiufwiwufbif wfubwfiubfwifw wfufbiufwb wiufgjkbive uegibniujiweu uqfebiwbui wuwriubi rwunhwruif wfiniwo sidd.</p> </div> </div> <div class="tarjetita tarjetita2"> <img src="https://via.placeholder.com/400x250" alt="Placeholder"> <div class="info"> <h4 class="titulo">Tarjetita 2</h4> <p class="descripcion">Lofl djhfh dhbdsh wdujwduhnud wunhweubeh weuhweueb webewubeu jqwnffnu fbhbfndu wiuwbuiw fiwuhfufb wfufuui fuibfuebi lol wubfiwbifw fwiufwiwufbif wfubwfiubfwifw wfufbiufwb wiufgjkbive uegibniujiweu uqfebiwbui wuwriubi rwunhwruif wfiniwo sidd.</p> </div> </div> <div class="tarjetita tarjetita3"> <img src="https://via.placeholder.com/400x250" alt="Placeholder"> <div class="info"> <h4 class="titulo">Tarjetita 3</h4> <p class="descripcion">Lofl djhfh dhbdsh wdujwduhnud wunhweubeh weuhweueb webewubeu jqwnffnu fbhbfndu wiuwbuiw fiwuhfufb wfufuui fuibfuebi lol wubfiwbifw fwiufwiwufbif wfubwfiubfwifw wfufbiufwb wiufgjkbive uegibniujiweu uqfebiwbui wuwriubi rwunhwruif wfiniwo sidd.</p> </div> </div> </div> <div class="tarjetas"> <div class="tarjeta tarjeta1" data-aos="fade-up"> <img src="https://via.placeholder.com/400x250" alt="Placeholder"> <div class="info"> <h4 class="titulo">Tarjetita 1</h4> <p class="descripcion">Lofl djhfh dhbdsh wdujwduhnud wunhweubeh weuhweueb webewubeu jqwnffnu fbhbfndu wiuwbuiw fiwuhfufb wfufuui fuibfuebi lol wubfiwbifw fwiufwiwufbif wfubwfiubfwifw wfufbiufwb wiufgjkbive uegibniujiweu uqfebiwbui wuwriubi rwunhwruif wfiniwo sidd.</p> </div> </div> <div class="tarjeta tarjeta2" data-aos="flip-left"> <img src="https://via.placeholder.com/400x250" alt="Placeholder"> <div class="info"> <h4 class="titulo">Tarjetita 2</h4> <p class="descripcion">Lofl djhfh dhbdsh wdujwduhnud wunhweubeh weuhweueb webewubeu jqwnffnu fbhbfndu wiuwbuiw fiwuhfufb wfufuui fuibfuebi lol wubfiwbifw fwiufwiwufbif wfubwfiubfwifw wfufbiufwb wiufgjkbive uegibniujiweu uqfebiwbui wuwriubi rwunhwruif wfiniwo sidd.</p> </div> </div> <div class="tarjeta tarjeta3"> <img src="https://via.placeholder.com/400x250" alt="Placeholder"> <div class="info"> <h4 class="titulo">Tarjetita 3</h4> <p class="descripcion">Lofl djhfh dhbdsh wdujwduhnud wunhweubeh weuhweueb webewubeu jqwnffnu fbhbfndu wiuwbuiw fiwuhfufb wfufuui fuibfuebi lol wubfiwbifw fwiufwiwufbif wfubwfiubfwifw wfufbiufwb wiufgjkbive uegibniujiweu uqfebiwbui wuwriubi rwunhwruif wfiniwo sidd.</p> </div> </div> </div> <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script> <script> AOS.init(); </script> </body> </html>
import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class ExcelWrite { String filePath = "Movies.xlsx"; XSSFWorkbook workbook; XSSFSheet sheet; FileInputStream fileInputStream; { try { fileInputStream = new FileInputStream(filePath); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } @Before public void setUp() throws IOException { workbook = new XSSFWorkbook(fileInputStream); sheet = workbook.getSheet("Movies"); } @After public void tearDown() throws IOException{ FileOutputStream fileOutputStream = new FileOutputStream(filePath); workbook.write(fileOutputStream); fileOutputStream.close(); workbook.close(); fileInputStream.close(); } @Test public void excelCreateNewColumn(){ XSSFCell ratingRow = sheet.getRow(0).createCell(5); ratingRow.setCellValue("Rating"); } @Test public void excelWriteValueInNewColumn(){ int lastMovieRow = sheet.getLastRowNum(); //set values for first 2 rows XSSFCell rating1 = sheet.getRow(1).createCell(5); rating1.setCellValue(8.3); XSSFCell rating2 = sheet.getRow(2).createCell(5); rating2.setCellValue(7.2); //set value for last row XSSFCell ratingLast = sheet.getRow(lastMovieRow).createCell(5); ratingLast.setCellValue(7.4); /** * set value for middle row. Excel has row 0 with names of columns. It is mean I should * exclude row 0 for correct calculation from row's count. */ int rowCount = sheet.getPhysicalNumberOfRows(); if(rowCount%2 == 0){ int middleRow = rowCount / 2; XSSFCell middleRowValue = sheet.getRow(middleRow).createCell(5); middleRowValue.setCellValue(7.2); }else{ int middleRow1 = lastMovieRow / 2; XSSFCell middleRowValue1 = sheet.getRow(middleRow1).createCell(5); middleRowValue1.setCellValue(7.2); int middleRow2 = lastMovieRow / 2 + 1; XSSFCell middleRowValue2 = sheet.getRow(middleRow2).createCell(5); middleRowValue2.setCellValue(8); } } @Test public void excelWriteNewRow(){ int lastMovieRow = sheet.getLastRowNum(); XSSFRow newMovie = sheet.createRow(lastMovieRow); newMovie.createCell(0).setCellValue(15); newMovie.createCell(1).setCellValue("Inside Out"); newMovie.createCell(2).setCellValue("Pete Docter"); newMovie.createCell(3).setCellValue(2015); newMovie.createCell(4).setCellValue(95); } @Test public void excelDeleteRow(){ int lastMovieRow = sheet.getPhysicalNumberOfRows(); int rowNum = 5; XSSFRow rowForDelete = sheet.getRow(rowNum); sheet.removeRow(rowForDelete); } @Test public void excelDeleteColumn() { int colNumToRemove = 4; for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) { XSSFRow row = sheet.getRow(i); for (int j = 0; j < row.getLastCellNum(); j++) { if (j == colNumToRemove) { row.removeCell(row.getCell(j)); } } } } @Test public void excelDeleteAllDataExcludesColumnNames () { XSSFRow row; for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) { row = sheet.getRow(i); for (int j = 0; j < row.getLastCellNum(); j++) { row.removeCell(row.getCell(j)); } } } }
package arraymanipulation /** * [31. Next Permutation](https://leetcode.com/problems/next-permutation/description/) * * @Difficulty=Medium */ class NextPermutation { fun nextPermutation(nums: IntArray) { var i = nums.size - 2 // Step 1: Find the first pair (i, i+1) such that nums[i] < nums[i+1] while (i >= 0 && nums[i] >= nums[i + 1]) { i-- } // If such a pair exists if (i >= 0) { // Step 2: Find the smallest number greater than nums[i] var j = nums.size - 1 while (nums[j] <= nums[i]) { j-- } // Step 3: Swap nums[i] and nums[j] val temp = nums[i] nums[i] = nums[j] nums[j] = temp } // Step 4: Reverse the subarray from i+1 to the end var left = i + 1 var right = nums.size - 1 while (left < right) { val temp = nums[left] nums[left] = nums[right] nums[right] = temp left++ right-- } } } // Solution /** * @Time_Complexity= */
# from django.urls import path # from . import views # urlpatterns = [ # path('', views.home, name='home'), # path('home', views.home, name='home'), # path('register/', views.sign_up, name='registration'), # path('login/', views.login, name='login'), # path('logout/', views.logout, name='logout'), # path('post/create/', views.create_post, name='post-create'), # path('post/<int:post_id>/', views.post_detail, name='post-detail'), # ] from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import BlogPostViewSet, RegistrationView, LoginView, LogoutView, CommentCreateView, CommentListView,CommentUpdateView, CommentDeleteView, TagViewSet # Create a router and register the viewset with it. router = DefaultRouter() router.register('posts', BlogPostViewSet) urlpatterns = [ # Your other URL patterns go here path('register/', RegistrationView.as_view(), name='registration'), path('login/', LoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(), name='logout'), path('api/', include(router.urls)), path('api/post/<int:post_id>/comments/', CommentListView.as_view(), name='comment-list'), path('api/post/<int:post_id>/comment/', CommentCreateView.as_view(), name='comment-create'), path('api/post/<int:post_id>/comment/<int:comment_id>', CommentUpdateView.as_view(), name='comment-update'), path('api/post/<int:post_id>/comment/<int:comment_id>', CommentDeleteView.as_view(), name='comment-delete'), path('api/post/<int:post_id>/tags/', TagViewSet.as_view({'get':'list','put': 'update','delete': 'destroy'}), name='tag-list'), path('api/post/<int:post_id>/tags/<int:pk>', TagViewSet.as_view({'get':'retrieve', 'delete': 'destroy'}), name='tag-detail'), ]
<template> <CRow> <CCol col="12"> <CCard> <CCardHeader> <h2>Auditoria</h2> </CCardHeader> <CCardBody> <template v-for="(alerta, key) in alertas"> <CAlert :key="'alerta' + key" :color="alerta.color" closeButton :show="true" > {{alerta.message}} </CAlert> </template> <CRow class="card-option-table"> <CCol md="3" class="text-left"> <CSelect placeholder="Digite a sua busca:" label="Itens por página:" :value.sync="ItensPorPagina" :options="[10,20,50,100]" /> </CCol> <CCol md="3" class="text-left"> <CInput label="Data Inicio : " v-model="dataInicio" type="date" autocomplete="off" @keypress="(event) => keyPress(event)" > </CInput> </CCol> <CCol md="3" class="text-left"> <CInput label="Data Final : " v-model="dataFinal" type="date" autocomplete="off" @keypress="(event) => keyPress(event)" > </CInput> </CCol> <CCol md="3" class="text-left"> <label >Usuário</label> <multiselect v-model="user" :options="Users" placeholder="Usuário" selectLabel="Selecionar" deselectLabel="Remover" :close-on-select="true" label="Nome" :multiple="false" track-by="IdUsuario" /> </CCol> </CRow> <CDataTable hover sorter style="margin-top: 10px" :items="items" :fields="fields" :pagination="false" :noItemsView="{ noResults: 'Sem Resultado', noItems: ' ' }" :loading="loadPage" > <template #Inativo="data"> <td class="text-center"> <CBadge :color="getBadge(data.item.Inativo)"> {{ data.item.Inativo == 1 ? "Inativo" : "Ativo" }} </CBadge> </td> </template> <template #show_details="{item}"> <td class="py-2 text-center"> <CButton color="primary" variant="outline" class="uppercase" square size="sm" @click="navigate('/admin/residencia/editar/'+ item.IdResidencia)" > Editar </CButton> </td> </template> </CDataTable> <CPagination :activePage.sync="paginaAtual" :pages="totalPaginas" size="" align="center" /> </CCardBody> </CCard> </CCol> </CRow> </template> <script> import store from '../../../store/data.module'; import moment from 'moment'; import { freeSet } from '@coreui/icons'; import noty from "../../../store/index"; export default { data() { return { items: [], fields: [ { key: 'Id', label: '#' }, { key: 'Entidade', label: 'Entidade' }, { key: 'IdEntidade', label: 'IdEntidade' }, { key: 'DataHora', label: 'Data/Hora' }, { key: 'IdUsuario', label: 'IdUsuario' }, { key: 'Acao', label: 'Ação' }, { key: 'Sucesso', label: 'Sucesso' }, ], paginaAtual: 1, totalPaginas: null, loadPage: true, Busca: null, ItensPorPagina: 10, freeSet, collapseDuration: 0, dataInicio: null, dataFinal: null, Users: [], user: null, alertas: [] } }, name: 'listarResidencia', methods: { getBadge (status) { switch (status) { case 1: return 'danger' case 0: return 'primary' default: 'secondary' } }, keyPress(event) { if (event.key === "Enter") this.popularTabela(); }, async getUsers(){ const method = 'admin/usuario'; const data = { Page: this.paginaAtual, Size: this.ItensPorPagina, Search: this.Busca, RoleRestricted: 5 }; const result = await store.actions.getListPost(method, data); if (result.Registers) { result.Registers.forEach((item, index, array) => { array[index].DataHora = moment.utc(item.DataHora, 'YYYY-MM-DD').local().format('DD/MM/YYYY'); array[index].IdEntidade = item.IdEntidade ? item.IdEntidade : ''; }); this.Users = result.Registers; } else { noty.commit("addToaster", { text: result.Message, type: "Error" }); } this.loadPage = false; }, async popularTabela() { this.loadPage = true; const method = 'admin/log'; const data = { Page: this.paginaAtual, Size: this.ItensPorPagina, Search: this.Busca, Usuario: this.user ? this.user.IdUsuario : null, DataInicio: this.dataInicio ? moment(this.dataInicio).format('YYYY-MM-DD 00:00:00') : null, DataFinal: this.dataFinal ? moment(this.dataFinal).format('YYYY-MM-DD 23:59:59') : null }; const result = await store.actions.getListPost(method, data); if (result.Registers) { this.items = result.Registers.map((item, id) => { return {...item, id, DataHora: moment.utc(item.DataHora).local().format('DD/MM/YYYY HH:MM:ss')}}); this.totalPaginas = result.TotalPages; } else { noty.commit("addToaster", { text: result.Message, type: "Error" }); } this.loadPage = false; }, navigate(route) { this.$router.push(route); }, pageChange (val) { this.$router.push({ query: { page: val }}); }, toggleDetails (item) { this.$set(this.items[item.id], '_toggled', !item._toggled) this.collapseDuration = 350 this.$nextTick(() => { this.collapseDuration = 0}) } }, async mounted() { await this.getUsers(); await this.popularTabela(); }, watch: { async paginaAtual() { await this.popularTabela(); }, async dataInicio(){ await this.popularTabela(); }, async dataFinal(){ await this.popularTabela(); }, async ItensPorPagina(){ await this.popularTabela(); }, async user(){ await this.popularTabela(); } } } </script> <style scoped> .margin-bottom-10 { margin-bottom: 10px; } .margin-left { margin-left: 10px; } </style>
// Dart imports: import 'dart:async'; // Package imports: import 'package:flutter_riverpod/flutter_riverpod.dart'; // Project imports: import 'package:boorusama/boorus/providers.dart'; import 'package:boorusama/core/feats/settings/settings.dart'; final gridSizeSettingsProvider = Provider<GridSize>( (ref) => ref.watch(settingsProvider.select((value) => value.gridSize))); final imageListTypeSettingsProvider = Provider<ImageListType>((ref) => ref.watch(settingsProvider.select((value) => value.imageListType))); final pageModeSettingsProvider = Provider<PageMode>( (ref) => ref.watch(settingsProvider.select((value) => value.pageMode))); final gridSpacingSettingsProvider = Provider<double>((ref) => ref.watch( settingsProvider.select((value) => value.imageGridSpacing.toDouble()))); final imageBorderRadiusSettingsProvider = Provider<double>((ref) => ref.watch( settingsProvider.select((value) => value.imageBorderRadius.toDouble()))); class SettingsNotifier extends Notifier<Settings> { SettingsNotifier(this.initialSettings) : super(); final Settings initialSettings; @override Settings build() { return initialSettings; } Future<void> updateSettings(Settings settings) async { final currentSettings = state; final success = await ref.read(settingsRepoProvider).save(settings); if (success) { for (var i = 0; i < currentSettings.props.length; i++) { final cs = currentSettings.props[i]; final ns = settings.props[i]; if (cs != ns) { ref.read(loggerProvider).logI( 'Settings', 'Settings updated: ${cs.runtimeType} $cs -> $ns'); } } state = settings; } } } extension SettingsNotifierX on WidgetRef { Future<void> updateSettings(Settings settings) => read(settingsProvider.notifier).updateSettings(settings); Future<void> setGridSize(GridSize size) => updateSettings( read(settingsProvider).copyWith( gridSize: size, ), ); Future<void> setImageListType(ImageListType type) => updateSettings( read(settingsProvider).copyWith( imageListType: type, ), ); Future<void> setPageMode(PageMode mode) => updateSettings( read(settingsProvider).copyWith( pageMode: mode, ), ); Future<void> setPostListConfigHeaderStatus({ required bool active, }) => updateSettings( read(settingsProvider).copyWith( showPostListConfigHeader: active, ), ); Future<void> setBooruConfigOrder(List<int> configIds) => updateSettings( read(settingsProvider).copyWith( booruConfigIdOrders: configIds.join(' '), ), ); } extension SettingsNotifierProviderRef on NotifierProviderRef { Future<void> updateSettings(Settings settings) => read(settingsProvider.notifier).updateSettings(settings); Future<void> setBooruConfigOrder(List<int> configIds) => updateSettings( read(settingsProvider).copyWith( booruConfigIdOrders: configIds.join(' '), ), ); } extension SettingsProviderRef on ProviderRef { Future<void> updateSettings(Settings settings) => read(settingsProvider.notifier).updateSettings(settings); Future<void> setBooruConfigOrder(List<int> configIds) => updateSettings( read(settingsProvider).copyWith( booruConfigIdOrders: configIds.join(' '), ), ); }
package com.demoqa.tests; import com.demoqa.pages.RegistrationPage; import org.junit.jupiter.api.Test; public class RegistrationWithPageObjectsFormTests extends TestBase { RegistrationPage registrationPage = new RegistrationPage(); @Test void fillFormTest() { registrationPage.openPage() .setFirstName("TestName") .setLastName("TestSurname") .setUserEmail("testmail@randommail.com") .setGender("Male") .setUserNumber("9991234545") .setBirthDate("07", "September", "2023") .setSubject("Maths") .setSubject("Economics") .setHobbie("Sports") .setHobbie("Music") .uploadPicture("coala.jpg") .setAddress("Test Country\nTest City\nAddress line 1\nAddress line2") .setState("Uttar Pradesh") .setCity("Merrut") .submit() .checkResults(new String[][]{ {"Student Name", "TestName TestSurname"}, {"Student Email", "testmail@randommail.com"}, {"Gender", "Male"}, {"Mobile", "9991234545"}, {"Date of Birth", "07 September,2023"}, {"Subjects", "Maths, Economics"}, {"Hobbies", "Sports, Music"}, {"Picture", "coala.jpg"}, {"Address", "Test Country Test City Address line 1 Address line2"}, {"State and City", "Uttar Pradesh Merrut"} }); } }
<?php /** * Template Name: Все курсы * The template for displaying all courses * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site may use a * different template. * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/ * * @package UX_Mind_School */ get_header(); $page_queried_object = get_queried_object(); $page_id = $page_queried_object->ID; ?> <!-- Begin main --> <main class="main template category-template"> <div class="wrapper template__wrapper category-template__wrapper"> <div class="container"> <div class="row"> <div class="col-12 col-lg-9"> <div class="breadcrumbs template__breadcrumbs"> <?php bcn_display($return = false, $linked = true, $reverse = false, $force = false); ?> </div> <div class="template__header category-template__header"> <h1 class="title template__title">Ближайшие курсы</h1> </div> </div> <div class="col-12"> <div class="course-list template__course-list"> <header class="course-list__header tabs"> <button type="button" data-show-full="true" data-id="15,1,2,4,99,3" class="tabs__btn js-tabs__btn tabs__btn_active">Все курсы</button> <?php $courses_array = array( 'taxonomy'=>'category', 'include'=>'15,1,2,4,99,3', 'orderby'=>'include', 'hide_empty'=>true ); $courses_categories = get_categories($courses_array); if ($courses_categories): foreach ($courses_categories as $cat): ?> <button type="button" data-show-full="true" data-id="<?php echo $cat->term_id; ?>" class="tabs__btn js-tabs__btn"><?php echo $cat->name; ?></button> <?php endforeach; endif; ?> </header> <div class="course-list__grid"> <div class="course-list__wrapper"> <?php $courses_array = array( 'post_type'=>'post', 'cat'=>'15,1,2,4,99,3', 'post_status'=>'publish', 'posts_per_page'=>-1, 'meta_key'=>'ums_course_info_start', 'orderby'=>'meta_value', 'order'=>'ASC' ); $courses_query = new WP_Query($courses_array); $term_max_num_pages = $courses_query->max_num_pages; $counter = 0; if ($courses_query->have_posts()): while ($courses_query->have_posts()): $courses_query->the_post(); include(locate_template('template-parts/course-item.php', false, false)); endwhile; wp_reset_postdata(); endif; ?> </div> </div> </div> <?php get_template_part( 'template-parts/advantages' ); ?> </div> </div> </div> <div class="figure figure_position-bottom"> <img src="<?php echo get_template_directory_uri(); ?>/img/ums-help-figure.png" alt="<?php echo get_bloginfo('name'); ?>"> </div> </div> <section class="section help-section"> <div class="container"> <div class="row justify-content-center"> <div class="col-12 col-lg-8"> <h2 class="title title_style-dark title_size-m section__title help-section__title">Не можете выбрать&nbsp;курс?</h2> <p class="section__note help-section__note">Оставьте свой номер телефона, и&nbsp;мы поможем сделать правильный выбор-)</p> <?php echo do_shortcode('[contact-form-7 id="130" autocomplete="off" html_class="form help-section__form help-form" title="Помощь в выборе курса"]'); ?> <label class="checkbox privacy-checkbox help-section__checkbox"> <input type="checkbox" checked class="checkbox__input privacy-checkbox__input"> <p class="checkbox__name">Я согласен с условиями обработки <button type="button" data-modal="#personal-data-modal" class="link checkbox__link">персональных данных</button></p> </label> </div> </div> </div> </section> </main> <!-- End main --> <?php get_footer(); ?>
// // pages/admin/themes.js // "use client" // import { useEffect, useState } from 'react'; // import axios from 'axios'; // const Themes = () => { // const [themes, setThemes] = useState([]); // const [count, setCount] = useState(0); // const fetchThemes = async () => { // try { // const res = await axios.get('/api/themes/allthame'); // setThemes(res.data.themes); // setCount(res.data.count); // } catch (error) { // console.error('Failed to fetch themes:', error.response.data.message); // } // }; // const updateTheme = async (id, newData) => { // try { // await axios.put(`/api/admin/themes/${id}`, newData); // fetchThemes(); // console.log('Theme updated successfully'); // } catch (error) { // console.error('Failed to update theme:', error.response.data.message); // } // }; // const deleteTheme = async (id) => { // try { // await axios.delete(`/api/admin/themes/${id}`); // fetchThemes(); // console.log('Theme deleted successfully'); // } catch (error) { // console.error('Failed to delete theme:', error.response.data.message); // } // }; // useEffect(() => { // fetchThemes(); // }, []); // return ( // <div> // <h1>Themes</h1> // <p>Total Themes: {count}</p> // <ul> // {themes.map((theme) => ( // <li key={theme._id}> // {theme.name} - {theme.description} // <button onClick={() => updateTheme(theme._id, { name: 'Updated Name', description: 'Updated Description' })}> // Update // </button> // <button onClick={() => deleteTheme(theme._id)}>Delete</button> // </li> // ))} // </ul> // </div> // ); // }; // export default Themes; // pages/admin/allthame/page.js 'use client'; import { useState, useEffect } from 'react'; import axios from 'axios'; const AdminThemes = () => { const [themes, setThemes] = useState([]); const [count, setCount] = useState(0); const [notification, setNotification] = useState(''); const fetchThemes = async () => { let token = localStorage.getItem('token'); const refreshToken = localStorage.getItem('refreshToken'); if (!token || !refreshToken) { console.error('No token found'); return; } try { let res = await axios.get('/api/admin/themes', { headers: { 'Authorization': `Bearer ${token}`, }, }); setThemes(res.data.themes); setCount(res.data.count); } catch (error) { if (error.response.status === 403 && error.response.data.message === 'Token expired') { // Refresh the token try { const refreshRes = await axios.post('/api/auth/refresh', { refreshToken }); token = refreshRes.data.token; localStorage.setItem('token', token); // Retry the original request const retryRes = await axios.get('/api/admin/themes', { headers: { 'Authorization': `Bearer ${token}`, }, }); setThemes(retryRes.data.themes); setCount(retryRes.data.count); } catch (refreshError) { console.error('Failed to refresh token:', refreshError.response?.data?.message || refreshError.message); } } else { console.error('Failed to fetch themes:', error.response?.data?.message || error.message); } } }; useEffect(() => { fetchThemes(); }, []); // const updateTheme = async (id, updateData) => { // const token = localStorage.getItem('token'); // if (!token) { // console.error('No token found'); // return; // } // try { // await axios.put(`/api/admin/themes`, { id, updateData }, { // headers: { // 'Authorization': `Bearer ${token}`, // }, // }); // setNotification('Theme updated successfully'); // fetchThemes(); // Refresh themes after update // } catch (error) { // console.error('Failed to update theme:', error.response?.data?.message || error.message); // setNotification('Failed to update theme'); // } // }; // const deleteTheme = async (id) => { // const token = localStorage.getItem('token'); // if (!token) { // console.error('No token found'); // return; // } // try { // await axios.delete(`/api/admin/themes`, { // headers: { // 'Authorization': `Bearer ${token}`, // }, // data: { id } // }); // setNotification('Theme deleted successfully'); // fetchThemes(); // Refresh themes after deletion // } catch (error) { // console.error('Failed to delete theme:', error.response?.data?.message || error.message); // setNotification('Failed to delete theme'); // } // }; // <button onClick={() => updateTheme(theme._id, { /* updated data */ })}>Update</button> // <button onClick={() => deleteTheme(theme._id)}>Delete</button> return ( <div> <h1>Admin Themes</h1> {notification && <p>{notification}</p>} <p>Total Themes: {count}</p> <ul> {themes.map((theme) => ( <li key={theme._id}> {theme.name} - {theme.description} </li> ))} </ul> </div> ); }; export default AdminThemes;
"use strict"; var _require = require('apollo-server-express'), AuthenticationError = _require.AuthenticationError; var _require2 = require('../models'), User = _require2.User, _DIY = _require2.DIY, Comment = _require2.Comment, Like = _require2.Like; var _require3 = require('../utils/auth'), signToken = _require3.signToken; var _require4 = require('graphql-subscriptions'), PubSub = _require4.PubSub; var pubsub = new PubSub(); var resolvers = { Query: { // get a user by username me: function me(parent, args, context) { var userData; return regeneratorRuntime.async(function me$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!context.user) { _context.next = 5; break; } _context.next = 3; return regeneratorRuntime.awrap(User.findById(context.user._id).select('-__v -password').populate('DIYs').populate({ path: 'comments', populate: { path: 'DIY' } }).populate('likes') // Populate the likes field in users .populate('savedDIYs') // Populate the savedDIYs field in users .exec()); case 3: userData = _context.sent; return _context.abrupt("return", userData); case 5: throw new AuthenticationError('Not logged in'); case 6: case "end": return _context.stop(); } } }); }, // get all users users: function users() { var usersData; return regeneratorRuntime.async(function users$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.prev = 0; _context2.next = 3; return regeneratorRuntime.awrap(User.find().select('-__v -password').populate('DIYs').populate({ path: 'comments', populate: { path: 'DIY' } }).populate('likes') // Populate the likes field in users .populate('savedDIYs') // Populate the savedDIYs field in users .exec()); case 3: usersData = _context2.sent; return _context2.abrupt("return", usersData); case 7: _context2.prev = 7; _context2.t0 = _context2["catch"](0); console.error('Error fetching users data:', _context2.t0); throw new Error('Unable to fetch users data'); case 11: case "end": return _context2.stop(); } } }, null, null, [[0, 7]]); }, //get a single DIY by _id DIY: function DIY(parent, _ref) { var _id, DIYData; return regeneratorRuntime.async(function DIY$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _id = _ref._id; _context3.next = 3; return regeneratorRuntime.awrap(_DIY.findById(_id).populate('user').populate('comments').populate('likes').exec()); case 3: DIYData = _context3.sent; return _context3.abrupt("return", DIYData); case 5: case "end": return _context3.stop(); } } }); }, //this one filters by username //but if username is not provided, it will return all DIYs DIYs: function DIYs(parent, _ref2) { var username, params, DIYsData; return regeneratorRuntime.async(function DIYs$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: username = _ref2.username; params = username ? { username: username } : {}; _context4.next = 4; return regeneratorRuntime.awrap(_DIY.find(params).sort({ createdAt: -1 }).populate('user').populate('comments').populate('likes').exec()); case 4: DIYsData = _context4.sent; return _context4.abrupt("return", DIYsData); case 6: case "end": return _context4.stop(); } } }); }, //and here we get all DIYs without filtering any particular user allDIYs: function allDIYs() { var allDIYsData; return regeneratorRuntime.async(function allDIYs$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.prev = 0; _context5.next = 3; return regeneratorRuntime.awrap(_DIY.find().populate('user')); case 3: allDIYsData = _context5.sent; return _context5.abrupt("return", allDIYsData); case 7: _context5.prev = 7; _context5.t0 = _context5["catch"](0); console.error('Error fetching all DIYs:', _context5.t0); throw new Error('Unable to fetch DIYs data'); case 11: case "end": return _context5.stop(); } } }, null, null, [[0, 7]]); }, popular_DIYS: function popular_DIYS() { var popularDIYs; return regeneratorRuntime.async(function popular_DIYS$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.prev = 0; _context6.next = 3; return regeneratorRuntime.awrap(_DIY.aggregate([{ $lookup: { from: 'likes', localField: '_id', foreignField: 'DIYId', as: 'likes' } }, { $project: { _id: 1, title: 1, description: 1, images: 1, likes: { $size: '$likes' } // Count the number of likes } }, { $sort: { likes: -1 } // Sort in descending order of likes }, { $limit: 8 // Limit the result to the top 5 }])); case 3: popularDIYs = _context6.sent; return _context6.abrupt("return", popularDIYs); case 7: _context6.prev = 7; _context6.t0 = _context6["catch"](0); throw new Error('Failed to fetch popular DIYs: ' + _context6.t0.message); case 10: case "end": return _context6.stop(); } } }, null, null, [[0, 7]]); }, //search DIYs by title or description searchDIYs: function searchDIYs(parent, _ref3) { var searchTerm, searchResults, allDIYs; return regeneratorRuntime.async(function searchDIYs$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: searchTerm = _ref3.searchTerm; if (!searchTerm) { _context7.next = 6; break; } _context7.next = 4; return regeneratorRuntime.awrap(_DIY.find({ $or: [{ title: { $regex: searchTerm, $options: 'i' } }, { description: { $regex: searchTerm, $options: 'i' } }] }, null, { sort: { createdAt: -1 } }).populate('user')); case 4: searchResults = _context7.sent; return _context7.abrupt("return", searchResults); case 6: _context7.next = 8; return regeneratorRuntime.awrap(_DIY.find().populate('user')); case 8: allDIYs = _context7.sent; return _context7.abrupt("return", allDIYs); case 10: case "end": return _context7.stop(); } } }); }, getSavedDIYs: function getSavedDIYs(parent, args, context) { var user; return regeneratorRuntime.async(function getSavedDIYs$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: if (!context.user) { _context8.next = 5; break; } _context8.next = 3; return regeneratorRuntime.awrap(User.findById(context.user._id).populate('savedDIYs')); case 3: user = _context8.sent; return _context8.abrupt("return", user.savedDIYs); case 5: throw new AuthenticationError('Error!'); case 6: case "end": return _context8.stop(); } } }); }, //get all comments by DIY id getComments: function getComments(parent, _ref4) { var DIYId, comments; return regeneratorRuntime.async(function getComments$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: DIYId = _ref4.DIYId; _context9.prev = 1; _context9.next = 4; return regeneratorRuntime.awrap(Comment.find({ DIY: DIYId }).sort({ createdAt: -1 }).populate('user') // Populate the user field for each comment .exec()); case 4: comments = _context9.sent; return _context9.abrupt("return", comments); case 8: _context9.prev = 8; _context9.t0 = _context9["catch"](1); console.error('Error fetching comments:', _context9.t0); throw new Error('Unable to fetch comments'); case 12: case "end": return _context9.stop(); } } }, null, null, [[1, 8]]); }, //get all likes by DIY id getLikes: function getLikes(parent, _ref5) { var DIYId, likes; return regeneratorRuntime.async(function getLikes$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: DIYId = _ref5.DIYId; _context10.prev = 1; _context10.next = 4; return regeneratorRuntime.awrap(Like.find({ DIY: DIYId }).sort({ createdAt: -1 }).populate('user')); case 4: likes = _context10.sent; return _context10.abrupt("return", likes); case 8: _context10.prev = 8; _context10.t0 = _context10["catch"](1); console.error('Error fetching likes:', _context10.t0); throw new Error('Unable to fetch likes'); case 12: case "end": return _context10.stop(); } } }, null, null, [[1, 8]]); }, //get all users who liked a DIY getLikedUsers: function getLikedUsers(parent, _ref6) { var DIYId, likes, users; return regeneratorRuntime.async(function getLikedUsers$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: DIYId = _ref6.DIYId; _context11.prev = 1; _context11.next = 4; return regeneratorRuntime.awrap(Like.find({ DIY: DIYId }).sort({ createdAt: -1 }).populate('user')); case 4: likes = _context11.sent; users = likes.map(function (like) { return like.user; }); return _context11.abrupt("return", users); case 9: _context11.prev = 9; _context11.t0 = _context11["catch"](1); console.error('Error fetching liked users:', _context11.t0); throw new Error('Unable to fetch liked users'); case 13: case "end": return _context11.stop(); } } }, null, null, [[1, 9]]); } }, Mutation: { addUser: function addUser(parent, _ref7) { var username, email, password, user, token; return regeneratorRuntime.async(function addUser$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: username = _ref7.username, email = _ref7.email, password = _ref7.password; _context12.next = 3; return regeneratorRuntime.awrap(User.create({ username: username, email: email, password: password })); case 3: user = _context12.sent; token = signToken(user); return _context12.abrupt("return", { token: token, user: user }); case 6: case "end": return _context12.stop(); } } }); }, // login a user, sign a token login: function login(parent, _ref8) { var email, password, user, correctPw, token; return regeneratorRuntime.async(function login$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: email = _ref8.email, password = _ref8.password; _context13.next = 3; return regeneratorRuntime.awrap(User.findOne({ email: email })); case 3: user = _context13.sent; if (user) { _context13.next = 6; break; } throw new AuthenticationError('No user found with this email address'); case 6: _context13.next = 8; return regeneratorRuntime.awrap(user.isCorrectPassword(password)); case 8: correctPw = _context13.sent; if (correctPw) { _context13.next = 11; break; } throw new AuthenticationError('Incorrect credentials'); case 11: token = signToken(user); return _context13.abrupt("return", { token: token, user: user }); case 13: case "end": return _context13.stop(); } } }); }, addDIY: function addDIY(parent, args, context) { var title, description, materialsUsed, instructions, images, newDIY, createdDIY, populatedDIY; return regeneratorRuntime.async(function addDIY$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: if (!context.user) { _context14.next = 13; break; } title = args.title, description = args.description, materialsUsed = args.materialsUsed, instructions = args.instructions, images = args.images; newDIY = { title: title, description: description, materialsUsed: materialsUsed, instructions: instructions, images: images, user: context.user._id }; _context14.next = 5; return regeneratorRuntime.awrap(_DIY.create(newDIY)); case 5: createdDIY = _context14.sent; _context14.next = 8; return regeneratorRuntime.awrap(User.findByIdAndUpdate(context.user._id, { $push: { DIYs: createdDIY._id } })); case 8: _context14.next = 10; return regeneratorRuntime.awrap(_DIY.findById(createdDIY._id).populate('user').populate('comments').exec()); case 10: populatedDIY = _context14.sent; pubsub.publish('NEW_DIY', { newDIY: populatedDIY }); return _context14.abrupt("return", populatedDIY); case 13: throw new AuthenticationError('You need to be logged in!'); case 14: case "end": return _context14.stop(); } } }); }, addComment: function addComment(_, _ref9, context) { var DIYId, content, newComment, populatedComment; return regeneratorRuntime.async(function addComment$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: DIYId = _ref9.DIYId, content = _ref9.content; _context15.prev = 1; if (!context.user) { _context15.next = 15; break; } _context15.next = 5; return regeneratorRuntime.awrap(Comment.create({ content: content, user: context.user._id, DIY: DIYId })); case 5: newComment = _context15.sent; _context15.next = 8; return regeneratorRuntime.awrap(_DIY.findByIdAndUpdate(DIYId, { $push: { comments: newComment._id } })); case 8: _context15.next = 10; return regeneratorRuntime.awrap(User.findByIdAndUpdate(context.user._id, { $push: { comments: newComment._id } })); case 10: _context15.next = 12; return regeneratorRuntime.awrap(Comment.findById(newComment._id).populate('user').exec()); case 12: populatedComment = _context15.sent; //publish the new event pubsub.publish("NEW_COMMENT_".concat(DIYId), { newComment: populatedComment }); return _context15.abrupt("return", populatedComment); case 15: throw new AuthenticationError('You need to be logged in to add a comment.'); case 18: _context15.prev = 18; _context15.t0 = _context15["catch"](1); console.error('Failed to add the comment:', _context15.t0); throw new Error('Failed to add the comment.'); case 22: case "end": return _context15.stop(); } } }, null, null, [[1, 18]]); }, removeComment: function removeComment(_, _ref10, context) { var commentId, comment; return regeneratorRuntime.async(function removeComment$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: commentId = _ref10.commentId; _context16.prev = 1; if (!context.user) { _context16.next = 15; break; } _context16.next = 5; return regeneratorRuntime.awrap(Comment.findById(commentId)); case 5: comment = _context16.sent; if (!(comment.user.toString() === context.user._id.toString())) { _context16.next = 14; break; } _context16.next = 9; return regeneratorRuntime.awrap(_DIY.findByIdAndUpdate(comment.DIY, { $pull: { comments: commentId } })); case 9: _context16.next = 11; return regeneratorRuntime.awrap(Comment.findByIdAndRemove(commentId)); case 11: return _context16.abrupt("return", comment); case 14: throw new AuthenticationError('You are not authorized to remove this comment.'); case 15: throw new AuthenticationError('You need to be logged in to remove a comment.'); case 18: _context16.prev = 18; _context16.t0 = _context16["catch"](1); throw new UserInputError('Failed to remove the comment.', { errors: _context16.t0.errors }); case 21: case "end": return _context16.stop(); } } }, null, null, [[1, 18]]); }, saveDIY: function saveDIY(parent, _ref11, context) { var DIYId, updatedUser; return regeneratorRuntime.async(function saveDIY$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: DIYId = _ref11.DIYId; if (!context.user) { _context17.next = 6; break; } _context17.next = 4; return regeneratorRuntime.awrap(User.findOneAndUpdate({ _id: context.user._id }, { $push: { savedDIYs: DIYId } }, { "new": true }).populate('savedDIYs')); case 4: updatedUser = _context17.sent; return _context17.abrupt("return", updatedUser); case 6: throw new AuthenticationError('You need to be logged in!'); case 7: case "end": return _context17.stop(); } } }); }, removeDIY: function removeDIY(parent, _ref12, context) { var DIYId, DIYToRemove; return regeneratorRuntime.async(function removeDIY$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: DIYId = _ref12.DIYId; _context18.prev = 1; if (!context.user) { _context18.next = 15; break; } _context18.next = 5; return regeneratorRuntime.awrap(_DIY.findById(DIYId)); case 5: DIYToRemove = _context18.sent; if (!(DIYToRemove.user.toString() === context.user._id.toString())) { _context18.next = 14; break; } _context18.next = 9; return regeneratorRuntime.awrap(_DIY.findByIdAndRemove(DIYId)); case 9: _context18.next = 11; return regeneratorRuntime.awrap(User.findByIdAndUpdate(context.user._id, { $pull: { DIYs: DIYId } })); case 11: return _context18.abrupt("return", DIYToRemove); case 14: throw new AuthenticationError('You are not authorized to remove this DIY.'); case 15: throw new AuthenticationError('You need to be logged in to remove a DIY.'); case 18: _context18.prev = 18; _context18.t0 = _context18["catch"](1); throw new UserInputError('Failed to remove the DIY.', { errors: _context18.t0.errors }); case 21: case "end": return _context18.stop(); } } }, null, null, [[1, 18]]); }, removeSavedDIY: function removeSavedDIY(parent, _ref13, context) { var DIYId, DIYToRemove, user, hasSavedDIY; return regeneratorRuntime.async(function removeSavedDIY$(_context19) { while (1) { switch (_context19.prev = _context19.next) { case 0: DIYId = _ref13.DIYId; _context19.prev = 1; if (!context.user) { _context19.next = 17; break; } _context19.next = 5; return regeneratorRuntime.awrap(_DIY.findById(DIYId)); case 5: DIYToRemove = _context19.sent; if (DIYToRemove) { _context19.next = 8; break; } throw new Error('DIY not found'); case 8: _context19.next = 10; return regeneratorRuntime.awrap(User.findById(context.user._id)); case 10: user = _context19.sent; hasSavedDIY = user.savedDIYs.includes(DIYId); if (hasSavedDIY) { _context19.next = 14; break; } throw new Error('DIY is not saved by the user'); case 14: _context19.next = 16; return regeneratorRuntime.awrap(User.findByIdAndUpdate(context.user._id, { $pull: { savedDIYs: DIYId } })); case 16: return _context19.abrupt("return", DIYToRemove); case 17: throw new AuthenticationError('You need to be logged in to remove a saved DIY.'); case 20: _context19.prev = 20; _context19.t0 = _context19["catch"](1); throw new Error("Failed to remove the saved DIY: ".concat(_context19.t0.message)); case 23: case "end": return _context19.stop(); } } }, null, null, [[1, 20]]); }, addLike: function addLike(parent, args, context) { var DIYId, newLike; return regeneratorRuntime.async(function addLike$(_context20) { while (1) { switch (_context20.prev = _context20.next) { case 0: if (!context.user) { _context20.next = 13; break; } DIYId = args.DIYId; // Create a new Like document _context20.next = 4; return regeneratorRuntime.awrap(Like.create({ user: context.user._id, DIY: DIYId })); case 4: newLike = _context20.sent; _context20.next = 7; return regeneratorRuntime.awrap(_DIY.findOneAndUpdate({ _id: DIYId }, { $addToSet: { likes: newLike._id } })); case 7: _context20.next = 9; return regeneratorRuntime.awrap(User.findOneAndUpdate({ _id: context.user._id }, { $addToSet: { likes: newLike._id } })); case 9: //publish the new event pubsub.publish("NEW_LIKE_".concat(DIYId), { newLike: newLike }); _context20.next = 12; return regeneratorRuntime.awrap(_DIY.findById(DIYId).populate('likes')); case 12: return _context20.abrupt("return", _context20.sent); case 13: throw new AuthenticationError('You need to be logged in!'); case 14: case "end": return _context20.stop(); } } }); }, removeLike: function removeLike(parent, args, context) { var DIYId; return regeneratorRuntime.async(function removeLike$(_context21) { while (1) { switch (_context21.prev = _context21.next) { case 0: if (!context.user) { _context21.next = 11; break; } DIYId = args.DIYId; // Delete the Like document _context21.next = 4; return regeneratorRuntime.awrap(Like.findOneAndDelete({ user: context.user._id, DIY: DIYId })); case 4: _context21.next = 6; return regeneratorRuntime.awrap(_DIY.findOneAndUpdate({ _id: DIYId }, { $pull: { likes: { user: context.user._id } } })); case 6: _context21.next = 8; return regeneratorRuntime.awrap(User.findOneAndUpdate({ _id: context.user._id }, { $pull: { likes: { DIY: DIYId } } })); case 8: _context21.next = 10; return regeneratorRuntime.awrap(_DIY.findById(DIYId).populate('likes')); case 10: return _context21.abrupt("return", _context21.sent); case 11: throw new AuthenticationError('You need to be logged in!'); case 12: case "end": return _context21.stop(); } } }); }, uploadDIYImage: function uploadDIYImage(_, _ref14) { var file, DIYId, _ref15, createReadStream, filename, stream, urlPath, updatedDIY; return regeneratorRuntime.async(function uploadDIYImage$(_context22) { while (1) { switch (_context22.prev = _context22.next) { case 0: file = _ref14.file, DIYId = _ref14.DIYId; _context22.prev = 1; _context22.next = 4; return regeneratorRuntime.awrap(file); case 4: _ref15 = _context22.sent; createReadStream = _ref15.createReadStream; filename = _ref15.filename; // Destructure the file object returned from the client stream = createReadStream(); _context22.next = 10; return regeneratorRuntime.awrap(storeUpload({ stream: stream, filename: filename })); case 10: urlPath = _context22.sent; _context22.next = 13; return regeneratorRuntime.awrap(_DIY.findByIdAndUpdate(DIYId, { $push: { images: urlPath } }, { "new": true })); case 13: updatedDIY = _context22.sent; return _context22.abrupt("return", { filename: filename, urlPath: urlPath, updatedDIY: updatedDIY }); case 17: _context22.prev = 17; _context22.t0 = _context22["catch"](1); console.error(_context22.t0); throw new Error('Failed to upload DIY image.'); case 21: case "end": return _context22.stop(); } } }, null, null, [[1, 17]]); } }, //Subscription which will be used to notify the client when a new DIY is created/ or instant update Subscription: { newDIY: { subscribe: function subscribe(_, __, _ref16) { var pubsub = _ref16.pubsub; return pubsub.asyncIterator('NEW_DIY'); } }, newComment: { subscribe: function subscribe(_, _ref17, _ref18) { var DIYId = _ref17.DIYId; var pubsub = _ref18.pubsub; return pubsub.asyncIterator("NEW_COMMENT_".concat(DIYId)); } }, newLike: { subscribe: function subscribe(_, _ref19, _ref20) { var DIYId = _ref19.DIYId; var pubsub = _ref20.pubsub; return pubsub.asyncIterator("NEW_LIKE_".concat(DIYId)); } }, savedDIY: { subscribe: function subscribe(_, __, _ref21) { var pubsub = _ref21.pubsub; return pubsub.asyncIterator('SAVED_DIY'); } } } }; module.exports = resolvers;
import os import h5py import torch import numpy as np import pandas as pd from torch.utils.data import Dataset, DataLoader from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer import warnings class SurvivalBagDataset(Dataset): def __init__(self, df, data_dir, label_field='status', extra_df=None, csv_path=None, **kwargs): super(SurvivalBagDataset, self).__init__() self.data_dir = data_dir self.label_field = label_field self.extra_df = None # inverse censorship df.status = 1-df.status self.df = df def __len__(self): return len(self.df.values) def get_data_df(self): return self.df def get_id_list(self): return self.df['filename'].values def get_balance_weight(self): # for data balance label = self.df['status'].values label_np = np.array(label) classes = list(set(label)) N = len(self.df) num_of_classes = [(label_np==c).sum() for c in classes] c_weight = [N/num_of_classes[i] for i in range(len(classes))] weight = [0 for _ in range(N)] for i in range(N): c_index = classes.index(label[i]) weight[i] = c_weight[c_index] return weight def __getitem__(self, idx): if self.extra_df is None: label = self.df[self.label_field].values[idx] status = self.df['status'].values[idx] #patient_id = self.df['patient_id'].values[idx] if type(self.df['filename'])==np.float64: self.df['filename'] = self.df['filename'].astype(int) slide_id = str(self.df['filename'].values[idx]) time = self.df['time'].values[idx] # load from pt files if 'feature_path' in self.df.columns: full_path = self.df['feature_path'].values[idx] else: if os.path.exists(os.path.join(self.data_dir, 'patch_feature')): full_path = os.path.join(self.data_dir, 'patch_feature', slide_id if slide_id.endswith('.pt') else slide_id + '.pt') else: full_path = os.path.join(self.data_dir, slide_id if slide_id.endswith('.pt') else slide_id + '.pt') features = torch.load(full_path, map_location=torch.device('cpu')) res = { 'feature': features, 'label': torch.tensor([label]), 'time': torch.tensor(time), 'status': torch.tensor(status) } return res
import { makeSquare } from "./script_tool_images"; import AdmZip from "adm-zip"; import axios from "axios"; import fs from "fs"; const REPO_URL = "https://github.com/tchajed/botc-icons/archive/refs/heads/secret.zip"; async function downloadRepo(): Promise<AdmZip> { const { data } = await axios.get(REPO_URL, { responseType: "arraybuffer", responseEncoding: "binary", maxRate: 3000 * 1024, // 3MB/s }); return new AdmZip(data); } interface Icon { entry: AdmZip.IZipEntry; destPath: string; } function iconEntries(zip: AdmZip, iconsDir: string): Icon[] { const icons: Icon[] = []; for (const entry of zip.getEntries()) { if (!entry.entryName.endsWith(".png")) { continue; } const id = entry.name.replace(/\.png$/, "").replaceAll(/[-'_]/g, ""); const destPath = `${iconsDir}/Icon_${id}.webp`; if (fs.existsSync(destPath)) { continue; } icons.push({ entry, destPath, }); } return icons; } async function extractIconFiles(icons: Icon[]) { await Promise.all( icons.map(async (icon) => { const data: Buffer = icon.entry.getData(); const img = await makeSquare(data); await img.toFile(icon.destPath); }), ); } export async function downloadExtraIcons(iconsDir: string) { console.log("downloading extra icons"); const zip = await downloadRepo(); const icons = iconEntries(zip, iconsDir); if (icons.length == 0) { console.log("no extra icons to extract"); return; } console.log(`extracting ${icons.length} extra icons`); extractIconFiles(icons); }
# Binary Search ``` Python def binary_search(array) -> int: def condition(value) -> bool: pass left, right = 0, len(array) while left < right: mid = left + (right - left) // 2 if condition(mid): right = mid else: left = mid + 1 return left ``` The above code returns the minimum k such that condition(k) is True ``` Python def binary_search(array) -> int: def condition(value) -> bool: pass left, right = 0, len(array) while left < right: mid = left + (right - left) // 2 if condition(mid): right = mid else: left = mid + 1 return left - 1 ``` This is the same as the template expect we return the "left - 1". Doing this return maximum k such that condition(k) is False Problem : Search for target in sorted array. Return index of target, else -1 ``` Python def search(self, array: List[int], target: int) -> int: left, right = 0, len(array) - 1 while left < right: mid = left + (right - left) // 2 if array[mid] >= target: right = mid else: left = mid + 1 return left if array[left] == target else -1 ``` ## References 1. [leetcode comment](https://leetcode.com/problems/first-bad-version/discuss/769685/Python-Clear-explanation-Powerful-Ultimate-Binary-Search-Template.-Solved-many-problems.)
import { ReactNode } from "react"; import Bullet from "../../components/bullet/Bullet.component"; import Label from "../../components/label/Label.component"; import Person from "../../components/person/Person.component"; import Header from "./Header.component"; import { Container, EmptyContainer, List, Profile, ReadMoreBtn, TodoContainer, TodoItem, TodoMeta, TodoText, } from "./TodoList.component.styles"; import { ToDoItem } from "./TodoTypes.d"; interface ToDoListProps { list: ToDoItem[]; onViewAll: () => void; title: string; fullScreen?: boolean; headerIcon?: ReactNode; } const TodoList = ({ list, onViewAll, title, fullScreen, headerIcon, }: ToDoListProps) => ( <Container fullScreen={fullScreen}> <Header title={title} afterIcon={headerIcon} /> {list.length > 0 ? ( <List fullScreen={fullScreen}> {list.map(({ title: todoTitle, priority, assignedTo }) => ( <TodoContainer key={todoTitle}> <Bullet /> <TodoItem> <TodoText>{todoTitle}</TodoText> {fullScreen && ( <TodoMeta> <Label type={priority} /> <Profile> <TodoText>{assignedTo}</TodoText> <Person /> </Profile> </TodoMeta> )} </TodoItem> </TodoContainer> ))} </List> ) : ( <EmptyContainer>-- Nothing to show --</EmptyContainer> )} <ReadMoreBtn onClick={onViewAll}>View all</ReadMoreBtn> </Container> ); export default TodoList;
import React from "react"; const ActionProvider = ({ createChatBotMessage, setState, children }) => { const handlefirstkeyword = () => { const botMessage = createChatBotMessage( "Absolutely! How about a modern apartment in the heart of downtown? It boasts spacious rooms and is near top-rated schools." ); setState((prev) => ({ ...prev, messages: [...prev.messages, botMessage], })); }; const handlesecondkeyword = () => { const botMessage = createChatBotMessage( "This gem offers a gym, swimming pool, and a rooftop terrace with stunning city views." ); setState((prev) => ({ ...prev, messages: [...prev.messages, botMessage], })); }; const handlethirdkeyword = () => { const botMessage = createChatBotMessage( "Certainly! It falls within your budget range, providing excellent value for money." ); setState((prev) => ({ ...prev, messages: [...prev.messages, botMessage], })); }; const handlefourthkeyword = () => { const botMessage = createChatBotMessage( "Of course! I'll arrange it at your convenience. Let's find your dream home!" ); setState((prev) => ({ ...prev, messages: [...prev.messages, botMessage], })); }; const handlefifthkeyword = () => { const botMessage = createChatBotMessage( "Absolutely, I'll confirm that for you. Your pet's comfort is just as important as yours in finding the ideal home." ); setState((prev) => ({ ...prev, messages: [...prev.messages, botMessage], })); }; return ( <div> {React.Children.map(children, (child) => { return React.cloneElement(child, { actions: { handlefirstkeyword, handlesecondkeyword, handlethirdkeyword, handlefourthkeyword, handlefifthkeyword, }, }); })} </div> ); }; export default ActionProvider;
<?php require __DIR__ . '/../vendor/autoload.php'; include '../conn.php'; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; // Conectarse a la base de datos // Leer datos de la base de datos $sql = 'SELECT * FROM registroetapaproductiva'; $result = $conn->query($sql); // Crear un nuevo archivo de Excel $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $headerStyle = [ 'font' => [ 'bold' => true, 'color' => ['rgb' => 'FFFFFF'], // Blanco ], 'fill' => [ 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '0070C0'], // Azul ], ]; $DOS = [ 'font' => [ 'bold' => true, 'color' => ['rgb' => 'FFFFFF'], // Blanco ], 'fill' => [ 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => 'F34A00 '], // Azul ], ]; $TRES = [ 'font' => [ 'bold' => true, 'color' => ['rgb' => 'FFFFFF'], // Blanco ], 'fill' => [ 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => 'F34A00'], //ZAPOTE ], ]; // Aplicar estilos a la cabecera $sheet->getStyle('A1:V1')->applyFromArray($headerStyle); $sheet->getStyle('W1:AC1')->applyFromArray($TRES); $sheet->getStyle('AD1:AW1')->applyFromArray($headerStyle); $dataStyle = [ 'font' => [ 'color' => ['rgb' => '008000'], // Verde ], 'borders' => [ 'outline' => [ 'borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => '000000'], // Negro ], ], 'fill' => [ 'fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'C0FFC0'], // Verde claro ], ]; $columns = range('A', 'Z'); foreach ($columns as $column) { $sheet->getColumnDimension($column)->setWidth(20); // Establecer ancho de 20 unidades para todas las columnas } // Establecer ancho para la columna AA $sheet->getColumnDimension('AC')->setWidth(18); // Establecer el ancho de la columna AA en 25 unidades $sheet->getColumnDimension('AR')->setWidth(18); // Establecer el ancho de la columna AA en 25 unidades $sheet->getColumnDimension('AS')->setWidth(18); // Establecer el ancho de la columna AA en 25 unidades $sheet->getColumnDimension('AT')->setWidth(18); // Establecer el ancho de la columna AA en 25 unidades // Escribir encabezados de columna $sheet->setCellValue('A1', 'Fecha de Registro'); $sheet->setCellValue('B1', 'Número de Documento de Identidad'); $sheet->setCellValue('C1', 'Nombre Completo'); $sheet->setCellValue('D1', 'Número de Ficha'); $sheet->setCellValue('E1', 'Correo Electrónico'); $sheet->setCellValue('F1', 'Nivel Académico'); $sheet->setCellValue('G1', 'Programa de Formación'); $sheet->setCellValue('H1', 'Número de Celular'); $sheet->setCellValue('I1', 'Empresa donde inicia la etapa productiva'); $sheet->setCellValue('J1', 'Fecha de Inicio de la etapa productiva en la empresa'); $sheet->setCellValue('K1', 'Fecha de Fin de la etapa productiva en la empresa'); $sheet->setCellValue('L1', 'Nombre del Instructor Técnico en la etapa lectiva'); $sheet->setCellValue('M1', 'Dirección de la empresa'); $sheet->setCellValue('N1', 'Municipio o ciudad donde está realizando la etapa productiva'); $sheet->setCellValue('O1', 'Nombre del Jefe Inmediato'); $sheet->setCellValue('P1', 'Número de teléfono del Jefe Inmediato (supervisor)'); $sheet->setCellValue('Q1', 'Correo del Jefe Inmediato'); $sheet->setCellValue('R1', 'Tipo de Alternativa de Etapa Productiva'); $sheet->setCellValue('S1', 'INSTRUCTOR'); $sheet->setCellValue('T1', 'Documentos Entregados'); $sheet->setCellValue('U1', 'Respuesta Magna'); $sheet->setCellValue('V1', 'Registro de Etapa Productiva en Sena Sofia Plus'); $sheet->setCellValue('W1', 'Observaciones'); $sheet->setCellValue('X1', 'Fecha de Formalización'); $sheet->setCellValue('Y1', 'Fecha de Evaluación Parcial'); $sheet->setCellValue('Z1', 'Fecha de Evaluación Final'); $sheet->setCellValue('AA1', 'Fecha de Estado Por Certificar'); $sheet->setCellValue('AB1', 'Fecha Respuesta Certificación'); $sheet->setCellValue('AC1', 'URL del Formulario'); $sheet->setCellValue('AD1', 'Formato GFPI F023'); $sheet->setCellValue('AE1', 'Copia del Contrato'); $sheet->setCellValue('AF1', 'Formato GFPI F165'); $sheet->setCellValue('AG1', 'RUT o NIT'); $sheet->setCellValue('AH1', 'EPS'); $sheet->setCellValue('AI1', 'ARL'); $sheet->setCellValue('AJ1', 'Formato GFPI F023 Completo'); $sheet->setCellValue('AK1', 'Formato GFPI F147 Bitácoras'); $sheet->setCellValue('AL1', 'Certificación de Finalización'); $sheet->setCellValue('AM1', 'Estado Por Certificar'); $sheet->setCellValue('AN1', 'Copia de la Cédula'); $sheet->setCellValue('AO1', 'Pruebas y TyT'); $sheet->setCellValue('AP1', 'Destrucción de Carnet'); $sheet->setCellValue('AQ1', 'Certificado APE'); $sheet->setCellValue('AR1', 'Estado'); $sheet->setCellValue('AS1', 'Fecha de Solicitud de Paz y Salvo'); $sheet->setCellValue('AT1', 'Fecha de Respuesta del Coordinador'); $sheet->setCellValue('AU1', 'Observaciones de Seguimiento'); $sheet->setCellValue('AV1', 'ID de Usuario'); $sheet->setCellValue('AW1', 'ID del Instructor'); $sheet->getDefaultRowDimension()->setRowHeight(30); // Escribir datos de la base de datos $row = 2; while ($row_data = $result->fetch_assoc()) { $sheet->setCellValue('A' . $row, $row_data['FechaRegistro']); $sheet->setCellValue('B' . $row, $row_data['NumeroDocumentoIdentidad']); $sheet->setCellValue('C' . $row, $row_data['NombreCompleto']); $sheet->setCellValue('D' . $row, $row_data['NumeroFicha']); $sheet->setCellValue('E' . $row, $row_data['CorreoElectronico']); $sheet->setCellValue('F' . $row, $row_data['NivelAcademico']); $sheet->setCellValue('G' . $row, $row_data['ProgramaFormacion']); $sheet->setCellValue('H' . $row, $row_data['NumeroCelular']); $sheet->setCellValue('I' . $row, $row_data['EmpresaInicioEtapaProductiva']); $sheet->setCellValue('J' . $row, $row_data['FechaInicioEtapa']); $sheet->setCellValue('K' . $row, $row_data['FechaFinEtapa']); $sheet->setCellValue('L' . $row, $row_data['NombreInstructorLectivo']); $sheet->setCellValue('M' . $row, $row_data['DireccionEmpresa']); $sheet->setCellValue('N' . $row, $row_data['MunicipioCiudad']); $sheet->setCellValue('O' . $row, $row_data['NombreJefeInmediato']); $sheet->setCellValue('P' . $row, $row_data['TelefonoJefeInmediato']); $sheet->setCellValue('Q' . $row, $row_data['CorreoJefeInmediato']); $sheet->setCellValue('R' . $row, $row_data['TipoAlternativaEtapaProductiva']); $sheet->setCellValue('S' . $row, $row_data['InstructorSeguimiento']); $sheet->setCellValue('T' . $row, $row_data['DocumentosEntregados']); $sheet->setCellValue('U' . $row, $row_data['Respuesmagna']); $sheet->setCellValue('V' . $row, $row_data['Registroetapaproductiva']); $sheet->setCellValue('W' . $row, $row_data['observaciones']); $sheet->setCellValue('X' . $row, $row_data['FechaFormalizacion']); $sheet->setCellValue('Y' . $row, $row_data['FechaEvaluacionParcial']); $sheet->setCellValue('Z' . $row, $row_data['FechaEvaluacionFinal']); $sheet->setCellValue('AA' . $row, $row_data['FechaEstadoPorCertificar']); $sheet->setCellValue('AB' . $row, $row_data['FechaRespuestaCertificacion']); $sheet->setCellValue('AC' . $row, $row_data['URLFormulario']); $sheet->setCellValue('AD' . $row, $row_data['FormatoGFPIF023']); $sheet->setCellValue('AE' . $row, $row_data['CopiaContrato']); $sheet->setCellValue('AF' . $row, $row_data['FormatoGFPIF165']); $sheet->setCellValue('AG' . $row, $row_data['RUToNIT']); $sheet->setCellValue('AH' . $row, $row_data['EPS']); $sheet->setCellValue('AI' . $row, $row_data['ARL']); $sheet->setCellValue('AJ' . $row, $row_data['FormatoGFPIF023Completo']); $sheet->setCellValue('AK' . $row, $row_data['FormatoGFPIF147Bitacoras']); $sheet->setCellValue('AL' . $row, $row_data['CertificacionFinalizacion']); $sheet->setCellValue('AM' . $row, $row_data['EstadoPorCertificar']); $sheet->setCellValue('AN' . $row, $row_data['CopiaCedula']); $sheet->setCellValue('AO' . $row, $row_data['PruebasTyT']); $sheet->setCellValue('AP' . $row, $row_data['DestruccionCarnet']); $sheet->setCellValue('AQ' . $row, $row_data['CertificadoAPE']); $sheet->setCellValue('AR' . $row, $row_data['Estado']); $sheet->setCellValue('AS' . $row, $row_data['FechaSolicitudPazySalvo']); $sheet->setCellValue('AT' . $row, $row_data['FechaRespuestaCoordinador']); $sheet->setCellValue('AU' . $row, $row_data['ObservacionesSeguimiento']); $sheet->setCellValue('AV' . $row, $row_data['id_user']); $sheet->setCellValue('AW' . $row, $row_data['id_intructor']); $sheet->getStyle('A' . $row . ':AW' . $row)->applyFromArray($dataStyle); $sheet->getStyle('A' . $row . ':AW' . $row)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN)->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color('000000')); // Añadir bordes negros $row++; } // Guardar el archivo de Excel $writer = new Xlsx($spreadsheet); // Establecer las cabeceras para la descarga del archivo header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment; filename="datos.xlsx"'); // Enviar el archivo Excel al navegador $writer->save('php://output'); // Cerrar la conexión a la base de datos $conn->close(); ?>
package com.zurnov.restaurant.controller; import com.zurnov.restaurant.dto.restaurantTable.RestaurantTableDTO; import com.zurnov.restaurant.model.RestaurantTable; import com.zurnov.restaurant.service.RestaurantTableService; import com.zurnov.restaurant.util.PathHelper; import com.zurnov.restaurant.util.converter.dto.RestaurantTableDtoConverter; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping(PathHelper.BASE_PATH + PathHelper.RESTAURANT_TABLE_PATH) public class RestaurantTableController { private final RestaurantTableService restaurantTableService; @Autowired public RestaurantTableController(RestaurantTableService restaurantTableService) { this.restaurantTableService = restaurantTableService; } @GetMapping("/{restaurantTableId}") @Operation( tags = "Restaurant Table", operationId = "getRestaurantTableById", summary = "get RestaurantTable object by id", description = "Finds and returns RestaurantTable that corresponds to the given id" + " or else throws ApiRequestNotFoundException if none of them matches the restaurant table id.", parameters = @Parameter( name = "restaurantTableId", description = "id with which we want to filter all restaurant tables", example = "4" ), responses = { @ApiResponse( responseCode = "200", content = @Content( schema = @Schema(implementation = RestaurantTable.class), mediaType = MediaType.APPLICATION_JSON_VALUE), description = "Restaurant Table found" ), @ApiResponse( responseCode = "404", content = @Content( schema = @Schema(implementation = RestaurantTable.class), mediaType = MediaType.APPLICATION_JSON_VALUE), description = "Restaurant Table not found!" ) } ) public RestaurantTableDTO getRestaurantTableById(@PathVariable int restaurantTableId) { RestaurantTable restaurantTable = restaurantTableService.findById(restaurantTableId); return RestaurantTableDtoConverter.convertEntityToDto(restaurantTable); } @GetMapping() @Operation( tags = "Restaurant Table", operationId = "getRestaurantTableByTableNumber", summary = "get RestaurantTable object by table number", description = "Finds and returns RestaurantTable that corresponds to the tableNumber" + " or else list of all RestaurantTables", parameters = @Parameter( name = "tableNumber", description = "table number with which we want to filter all restaurant tables", example = "5" ), responses = @ApiResponse( responseCode = "200", content = @Content( schema = @Schema(implementation = RestaurantTable.class), mediaType = MediaType.APPLICATION_JSON_VALUE), description = "Success Response" ) ) public List<RestaurantTableDTO> getRestaurantTables(@RequestParam(name = "tableNumber", required = false) Integer restaurantTableNumber) { List<RestaurantTable> restaurantTables = restaurantTableService.findTables(restaurantTableNumber); return restaurantTables.stream() .map(RestaurantTableDtoConverter::convertEntityToDto) .collect(Collectors.toList()); } }
--- title: three.js中glsl写法整理01 date: 2021-07-15 20:58:26 categories: - 计算机图形学 tags: - threejs - 前端 - React - 图形学 --- 在web网页上写glsl是一件比较麻烦的事情,而且感觉网上比较缺乏一些glsl的文档, 所以本文结合three.js中shader的写法,对glsl中的语法进行整理。 <!-- more --> ## 📘three.js 内置的变量(uniforms)和属性 来源:https://threejs.org/docs/index.html#api/zh/renderers/webgl/WebGLProgram ### 顶点着色器(无条件的): ```glsl // = object.matrixWorld uniform mat4 modelMatrix; // = camera.matrixWorldInverse * object.matrixWorld uniform mat4 modelViewMatrix; // = camera.projectionMatrix uniform mat4 projectionMatrix; // = camera.matrixWorldInverse uniform mat4 viewMatrix; // = inverse transpose of modelViewMatrix uniform mat3 normalMatrix; // = camera position in world space uniform vec3 cameraPosition; ``` attribute: ```glsl // default vertex attributes provided by Geometry and BufferGeometry attribute vec3 position; attribute vec3 normal; attribute vec2 uv; ``` 注意,可以通过以下方式计算顶点着色器中顶点的位置: ```glsl gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); ``` 或者也可以这样: ```glsl gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4( position, 1.0 ); ``` ## 🔵向量的分量访问 glsl中的向量(vec2,vec3,vec4)往往有特殊的含义,比如可能代表了一个空间坐标(x,y,z,w),或者代表了一个颜色(r,g,b,a),再或者代表一个纹理坐标(s,t,p,q) 所以glsl提供了一些更人性化的分量访问方式. `vector.xyzw` 其中xyzw 可以任意组合 `vector.rgba` 其中rgba 可以任意组合 `vector.stpq` 其中rgba 可以任意组合 ```glsl vec4 v=vec4(1.0,2.0,3.0,1.0); float x = v.x; //1.0 float x1 = v.r; //1.0 float x2 = v[0]; //1.0 vec3 xyz = v.xyz; //vec3(1.0,2.0,3.0) vec3 xyz1 = vec(v[0],v[1],v[2]); //vec3(1.0,2.0,3.0) vec3 rgb = v.rgb; //vec3(1.0,2.0,3.0) vec2 xyzw = v.xyzw; //vec4(1.0,2.0,3.0,1.0); vec2 rgba = v.rgba; //vec4(1.0,2.0,3.0,1.0); ``` ## 🎈变量类型 ### 基本类型 ```html Type Meaning --------------------------------------------------------------------------------- void for functions that do not return a value bool a conditional type, taking on values of true or false int a signed integer uint an unsigned integer float a single floating-point scalar vec2 a two-component floating-point vector vec3 a three-component floating-point vector vec4 a four-component floating-point vector bvec2 a two-component Boolean vector bvec3 a three-component Boolean vector bvec4 a four-component Boolean vector ivec2 a two-component signed integer vector ivec3 a three-component signed integer vector ivec4 a four-component signed integer vector uvec2 a two-component unsigned integer vector uvec3 a three-component unsigned integer vector uvec4 a four-component unsigned integer vector mat2 a 2×2 floating-point matrix mat3 a 3×3 floating-point matrix mat4 a 4×4 floating-point matrix mat2x2 same as a mat2 mat2x3 a floating-point matrix with 2 columns and 3 rows mat2x4 a floating-point matrix with 2 columns and 4 rows mat3x2 a floating-point matrix with 3 columns and 2 rows mat3x3 same as a mat3 mat3x4 a floating-point matrix with 3 columns and 4 rows mat4x2 a floating-point matrix with 4 columns and 2 rows mat4x3 a floating-point matrix with 4 columns and 3 rows mat4x4 same as a mat4 ``` ### 浮点采样器类型 ```html Type Meaning --------------------------------------------------------------------------------- sampler1D a handle for accessing a 1D texture sampler2D a handle for accessing a 2D texture sampler3D a handle for accessing a 3D texture samplerCube a handle for accessing a cube mapped texture sampler2DRect a handle for accessing a rectangular texture sampler1DShadow a handle for accessing a 1D depth texture with comparison sampler2DShadow a handle for accessing a 2D depth texture with comparison sampler2DRectShadow a handle for accessing a rectangular texture with comparison sampler1DArray a handle for accessing a 1D array texture sampler2DArray a handle for accessing a 2D array texture sampler1DArrayShadow a handle for accessing a 1D array depth texture with comparison sampler2DArrayShadow a handle for accessing a 2D array depth texture with comparison samplerBuffer a handle for accessing a buffer texture ``` ### 有符号整数采样器类型 ```html Type Meaning --------------------------------------------------------------------------------- isampler1D a handle for accessing an integer 1D texture isampler2D a handle for accessing an integer 2D texture isampler3D a handle for accessing an integer 3D texture isamplerCube a handle for accessing an integer cube mapped texture isampler2DRect a handle for accessing an integer 2D rectangular texture isampler1DArray a handle for accessing an integer 1D array texture isampler2DArray a handle for accessing an integer 2D array texture isamplerBuffer a handle for accessing an integer buffer texture ``` ### 无符号整数采样器类型 ```html Type Meaning --------------------------------------------------------------------------------- usampler1D a handle for accessing an unsigned integer 1D texture usampler2D a handle for accessing an unsigned integer 2D texture usampler3D a handle for accessing an unsigned integer 3D texture usamplerCube a handle for accessing an unsigned integer cube mapped texture usampler2DRect a handle for accessing an unsigned integer rectangular texture usampler1DArray a handle for accessing an unsigned integer 1D array texture usampler2DArray a handle for accessing an unsigned integer 2D array texture usamplerBuffer a handle for accessing an unsigned integer buffer texture ``` ### 类型的一些例子 #### sampler3D 简述:3D 的纹理类型 使用例: ```glsl uniform sampler3D u_data; ... texture(u_data, texcoords.xyz).r ``` #### sampler2DArray 简述:2D 的纹理的列表 使用例: ```glsl uniform sampler2DArray diffuse; ... vec4 color = texture( diffuse, pos.xyz ); ``` ## 💙内置函数库 #### 纹理查询函数 实际上例如 texture2D 这种方法是已经被弃用了,但是在以前的代码里面可能很常见 **主要的** ```glsl gvec4 texture (gsampler1D sampler, float P [, float bias] ) gvec4 texture (gsampler2D sampler, vec2 P [, float bias] ) gvec4 texture (gsampler3D sampler, vec3 P [, float bias] ) ``` **其他的** ```glsl gvec4 texture (gsamplerCube sampler, vec3 P [, float bias] ) float texture (sampler1DShadow sampler, vec3 P [, float bias] ) float texture (sampler2DShadow sampler, vec3 P [, float bias] ) float texture (samplerCubeShadow sampler, vec4 P [, float bias] ) gvec4 texture (gsampler1DArray sampler, vec2 P [, float bias] ) gvec4 texture (gsampler2DArray sampler, vec3 P [, float bias] ) float texture (sampler1DArrayShadow sampler, vec3 P [, float bias] ) float texture (sampler2DArrayShadow sampler, vec4 P) gvec4 texture (gsampler2DRect sampler, vec2 P) float texture (sampler2DRectShadow sampler, vec3 P) ``` **解释:** Use the texture coordinate P to do a texture lookup in the texture currently bound to sampler. The last component of P is used as Dref for the shadow forms. For array forms, the array layer comes from the last component of P in the nonshadow forms, and the second to last component of P in the shadow forms. ## 来源 - GLSL 中文手册 :https://github.com/wshxbqq/GLSL-Card - The OpenGL Shading Language :https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.1.40.pdf
import { useState, useMemo, useEffect } from "react"; import * as Yup from "yup"; import { useNavigate } from "react-router-dom"; import { useLocales } from "src/locales"; import { Link as RouterLink } from "react-router-dom"; // form import { useForm } from "react-hook-form"; import { yupResolver } from "@hookform/resolvers/yup"; // data import { getMemberships, subjects_dk, subjects_es, interests_dk } from "../../assets/data"; import emojiPhone from "../../assets/thinkingphone.png"; import trustpilot5stars from "../../assets/trustpilot5stars.png"; import { phoneNumberValidation } from "../../utils/phoneValidation"; import { MuiTelInputInfo } from "mui-tel-input"; // Mixpanel import { Mixpanel } from "src/auth/Mixpanel"; // @mui import { Stack, Box, Link, CircularProgress, Step, Grid, Divider, Alert, Typography, Slide, Button, TextField, MobileStepper, Card, Fab, MenuItem, Select, OutlinedInput, FormControl, InputLabel } from "@mui/material"; import { LoadingButton } from "@mui/lab"; // auth import { useAuthContext } from "../../auth/useAuthContext"; import RoleBasedGuard from "src/auth/RoleBasedGuard"; // components import Iconify from "../../components/iconify"; import FormProvider, { RHFTextField, RHFTel } from "../../components/hook-form"; import Logo from "../../components/logo"; import TrustpilotWidget from "./TrustpilotWidget"; //utils import reCAPTCHA from "src/utils/recaptcha"; import { useTheme, alpha } from "@mui/material/styles"; import { useDispatch, useSelector } from "../../redux/store"; import { getCustomerUnprotected } from "src/redux/slices/customer"; import LanguagePopover from "src/layouts/dashboard/header/LanguagePopover"; // ---------------------------------------------------------------------- type FormValuesProps = { email: string | null; phone: string | null; firstName: string | null; lastName: string | null; afterSubmit?: string; market: string; }; export default function AuthRegisterForm({ email, phone, firstName, lastName, market }: FormValuesProps) { const { register } = useAuthContext(); const { translate } = useLocales(); const [activeStep, setActiveStep] = useState(0); const theme = useTheme(); const { customer, isLoading } = useSelector((state) => state.customer); const dispatch = useDispatch(); const RegisterSchema = Yup.object().shape({ firstName: Yup.string().required(`${translate("register.createAccount.errorFirst")}`), lastName: Yup.string().required(`${translate("register.createAccount.errorLast")}`), email: Yup.string() .required(`${translate("register.createAccount.errorEmail")}`) .email(`${translate("register.createAccount.errorCorrectEmail")}`), }); const defaultValues = { firstName: firstName || "", lastName: lastName || "", email: email || "", phone: phone || "", market: market, }; const navigate = useNavigate(); const methods = useForm<FormValuesProps>({ resolver: yupResolver(RegisterSchema), defaultValues, }); const [selectedSubjects, setSelectedSubjects] = useState<string[]>([]); const [school, setSchool] = useState(""); const [highschooltype, setHighschoolType] = useState(""); const [grade, setGrade] = useState(""); const [level, setLevel] = useState(""); const [selectedInterests, setSelectedInterests] = useState<string[]>([]); const memberships = useMemo(() => getMemberships(theme, translate), [theme, translate]); const [customerId, setCustomerId] = useState(""); console.log(selectedInterests); // Toggle selection of an interest const toggleInterestSelection = (interestLabel: string) => { if (selectedInterests.includes(interestLabel)) { setSelectedInterests(selectedInterests.filter((label) => label !== interestLabel)); } else { setSelectedInterests([...selectedInterests, interestLabel]); } }; // Toggle selection of an interest const toggleSubjectSelection = (subjectLabel: string) => { if (selectedSubjects.includes(subjectLabel)) { setSelectedSubjects(selectedSubjects.filter((label) => label !== subjectLabel)); } else { setSelectedSubjects([...selectedSubjects, subjectLabel]); } }; const [goals, setGoals] = useState(""); // State for search text const [searchText, setSearchText] = useState(""); const [searchTextSubject, setSearchTextSubject] = useState(""); // Filtered interests based on search text const filteredInterests = interests_dk.filter((interest) => interest.label.toLowerCase().includes(searchText.toLowerCase())); const subjects = subjects_dk.filter((subject) => subject.label.toLowerCase().includes(searchTextSubject.toLowerCase())); const { reset, setError, handleSubmit, setValue, watch, formState: { errors, isSubmitting, isSubmitSuccessful }, } = methods; const handleChange = (newPhone: string, info: MuiTelInputInfo) => { setValue("phone", info.numberValue || "", { shouldValidate: true }); }; const values = watch(); useEffect(() => { // Function to handle tab/browser close const handleTabClose = (event: BeforeUnloadEvent) => { // Mixpanel tracking Mixpanel.track("Registration Page Close", { email: values.email || "", firstName: values.firstName || "", lastName: values.lastName || "", phone: values.phone || "", school: school, selectedSubject: selectedSubjects, level: level, goals: goals, selectedInterests: selectedInterests, }); console.log("Close tab"); // Prevents the default 'Are you sure you want to leave?' dialog (optional) event.preventDefault(); }; console.log("Close tab"); // Attach event listener window.addEventListener("beforeunload", handleTabClose); // Cleanup function return () => { window.removeEventListener("beforeunload", handleTabClose); }; }, []); const steps = [ { label: `${translate("register.school.whatTypeOfSchool")}`, obligatory: false, marketingText: ( <div style={{ marginRight: "5%" }}> “Alle aftaler overholdt til punkt og prikke. Bedste anbefalinger herfra.” <img src="https://source.unsplash.com/featured/70x70" alt="placeholder" style={{ borderRadius: "35px" }} /> <Grid container> <Grid item xs={12} sx={{ mt: "-18%", ml: "20%" }}> <p style={{ fontSize: "18px", fontWeight: "bold" }}>-Hans Hansen via TrustPilot</p> </Grid> <Grid item xs={12} sx={{ mt: "-8%", ml: "20%" }}> <img src={trustpilot5stars} alt="" /> </Grid> </Grid> </div> ), field: ( <div style={{ margin: "auto", maxWidth: "750px", marginTop: "10%" }}> <Grid container sx={{ textAlign: "center" }}> <Grid item xs={12} lg={6} sx={{ "@media (max-width: 600px)": { marginBottom: "20px", margin: "auto", textAlign: "center", }, }} > <Button sx={{ backgroundColor: "transparent", "&:hover": { backgroundColor: "transparent", }, }} onClick={() => { setActiveStep(activeStep + 1); setSchool("highschool"); }} > <Box sx={{ backgroundColor: "#EDE7E2", border: "1px 1px 1px 1px", borderRadius: "16px", color: "black", boxShadow: "0px 4px 0px 0px #C8C3BF", maxHeight: "30%", width: "328px", height: "231px", "&:hover": { backgroundColor: "#D6FFCC", boxShadow: "0px 4px 0px 0px #329473", }, "@media (max-width: 600px)": { height: "auto", width: "300px", maxHeight: "unset", }, }} > <div style={{ width: "120px", height: "120px", borderRadius: "60px", background: "rgba(218, 213, 209, 0.65)", justifySelf: "center", textAlign: "center", margin: "auto", marginTop: "5%", }} > <Typography sx={{ fontSize: "96px", marginTop: "0", marginBottom: "0" }}>🎓</Typography> </div> <Typography sx={{ fontSize: "36px", color: "#000000", marginTop: "5%" }}>{`${translate("register.school.highschool")}`}</Typography> </Box> </Button> </Grid> <Grid item xs={12} lg={6}> <Button sx={{ backgroundColor: "transparent", "&:hover": { backgroundColor: "transparent", }, }} onClick={() => { setActiveStep(activeStep + 1); setSchool("middleschool"); }} > <Box sx={{ backgroundColor: "#EDE7E2", border: "1px 1px 1px 1px", borderRadius: "16px", color: "black", boxShadow: "0px 4px 0px 0px #C8C3BF", maxHeight: "30%", width: "328px", height: "231px", "&:hover": { backgroundColor: "#D6FFCC", boxShadow: "0px 4px 0px 0px #329473", }, "@media (max-width: 600px)": { height: "auto", width: "300px", maxHeight: "unset", }, }} > <div style={{ width: "120px", height: "120px", borderRadius: "60px", background: "rgba(218, 213, 209, 0.65)", justifySelf: "center", textAlign: "center", margin: "auto", marginTop: "5%", }} > <Typography sx={{ fontSize: "96px", marginTop: "0", marginBottom: "0" }}>🎒</Typography> </div> <Typography sx={{ fontSize: "36px", color: "#000000", marginTop: "5%" }}>{`${translate("register.school.middleschool")}`}</Typography> </Box> </Button> </Grid> </Grid> </div> ), }, { label: `${translate("register.grade.whatGrade")}`, obligatory: false, marketingText: <div>Here is social proofing</div>, field: ( <> {school === "highschool" ? ( <> { <div style={{ textAlign: "center" }}> <Typography sx={{ fontSize: "148px", mt: "5%", }} > 🤔 </Typography> <Box sx={{ maxWidth: "400px", margin: "auto", ta: "left", pt: "2%", "@media (max-width: 600px)": { margin: "5%", }, }} > <FormControl fullWidth> <InputLabel id="demo-simple-select-label" sx={{ ta: "left" }}> {`${translate("register.grade.chooseType")}`} </InputLabel> <Select sx={{ ta: "left" }} labelId="demo-simple-select-label" id="demo-simple-select" label="Choose type of highschool" value={highschooltype} onChange={(e) => { setHighschoolType((e.target as HTMLInputElement).value); }} > <MenuItem value="1">STX</MenuItem> <MenuItem value="2">HTX</MenuItem> <MenuItem value="3">HHX</MenuItem> <MenuItem value="4">HX</MenuItem> </Select> </FormControl> </Box> <Box sx={{ maxWidth: "400px", margin: "auto", ta: "left", pt: "2%", "@media (max-width: 600px)": { margin: "5%", }, }} > <FormControl fullWidth> <InputLabel id="demo-simple-select-label"> {`${translate("register.grade.chooseGrade")}`}</InputLabel> <Select sx={{ ta: "left" }} labelId="demo-simple-select-label" id="demo-simple-select" label="Choose grade" value={grade} onChange={(e) => { setGrade((e.target as HTMLInputElement).value); }} > <MenuItem value="1">1.G</MenuItem> <MenuItem value="2">2.G</MenuItem> <MenuItem value="3">3.G</MenuItem> </Select> </FormControl> </Box> </div> } </> ) : ( <> { <div style={{ textAlign: "center" }}> <Typography sx={{ fontSize: "148px", mt: "5%" }}>🤔</Typography> <Box sx={{ maxWidth: "400px", margin: "auto", ta: "left", "@media (max-width: 600px)": { margin: "5%", }, }} > <FormControl fullWidth> <InputLabel id="demo-simple-select-label">{`${translate("register.grade.chooseGrade")}`}</InputLabel> <Select sx={{ ta: "left" }} labelId="demo-simple-select-label" id="demo-simple-select" label="Choose grade" value={grade} onChange={(e) => { setGrade((e.target as HTMLInputElement).value); }} > <MenuItem value="1">0. klasse</MenuItem> <MenuItem value="2">1. klasse</MenuItem> <MenuItem value="3">2. klasse</MenuItem> <MenuItem value="4">3. klasse</MenuItem> <MenuItem value="5">4. klasse</MenuItem> <MenuItem value="6">5. klasse</MenuItem> <MenuItem value="7">6. klasse</MenuItem> <MenuItem value="8">7. klasse</MenuItem> <MenuItem value="9">8. klasse</MenuItem> <MenuItem value="10">9. klasse</MenuItem> </Select> </FormControl> </Box> </div> } </> )} </> ), }, { label: `${translate("register.subjects.whatSubjects")}`, obligatory: false, marketingText: <div>Et andet eksempel på text under social proof.</div>, field: ( <div style={{ marginTop: "1%", maxWidth: "700px", margin: "auto", paddingLeft: "0" }}> <TextField fullWidth label={`${translate("register.subjects.search")}`} variant="outlined" sx={{ marginBottom: 2, width: "98%", paddingLeft: "8px", "@media (max-width: 600px)": { width: "425px", }, "@media (max-width: 400px)": { width: "370px", }, }} // Adjust spacing as needed // Add onChange handler if needed for search functionality onChange={(e) => { // Your search logic here setSearchTextSubject(e.target.value); }} /> <Grid container spacing={1}> {subjects.map((subject, key) => { const isSelected = selectedSubjects.includes(subject.label); return ( <Grid key={key} item xs={6} lg={4}> <Button sx={{ backgroundColor: "transparent", "&:hover": { backgroundColor: "transparent", }, }} onClick={() => { toggleSubjectSelection(subject.label); }} > <Box sx={{ width: "14vw", height: "13vh", border: "1px 1px 1px 1px", borderRadius: "16px", color: "black", boxShadow: isSelected ? "0px 4px 0px 0px #329473" : "0px 4px 0px 0px #C8C3BF", backgroundColor: isSelected ? "lightgreen" : "#EDE7E2", "&:hover": { backgroundColor: "#D6FFCC", boxShadow: "0px 4px 0px 0px #329473", }, "@media (max-width: 600px)": { height: "auto", // Auto height on mobile width: "200px", // Limit maximum width }, "@media (max-width: 400px)": { height: "auto", width: "175px", }, }} > <Grid container> <Grid item xs={3} sx={{ marginTop: "13%", "@media (max-width: 600px)": { marginTop: "3%", }, }} > <div style={{ width: "55px", height: "55px", borderRadius: "28px", background: "rgba(218, 213, 209, 0.65)", marginLeft: "20%", justifySelf: "center", }} > <Typography sx={{ fontSize: "36px", paddingTop: "5%", }} > {subject.icon} </Typography> </div> </Grid> <Grid item xs={9}> <Typography sx={{ color: "#000000", marginTop: "25%", marginLeft: "15%", fontSize: "20px", textAlign: "left", "@media (max-width: 600px)": { marginTop: "10%", }, "@media (max-width: 400px)": { fontSize: "18px", marginTop: "14%", }, }} > {`${translate(subject.label)}`} </Typography> </Grid> </Grid> </Box> </Button> </Grid> ); })} </Grid> </div> ), }, { label: `${translate("register.level.whatIsYourCurrentLevel")}`, obligatory: false, field: ( <div style={{ margin: "auto" }}> {/* <Typography sx={{ margin: 'auto', fontStyle: 'italic', textAlign: 'center', opacity: '60%', marginTop: '2%', fontSize: '16px', }} > Test Lorem, ipsum dolor sit amet consectetur adipisicing elit. Asperiores, eveniet! </Typography> If we add some text under the main title. It could look something like this. */} <Grid container sx={{ textAlign: "center", marginTop: "10%", "@media (max-width: 600px)": { marginTop: "2%", height: "auto", // Auto height on mobile textAlign: "center", // Center align the content on mobile }, }} > <Grid item lg={4} md={4} xs={12}> <Button onClick={() => { setActiveStep(activeStep + 1); setLevel("low"); }} > <Box sx={{ width: "200px", height: "100%", "@media (max-width: 600px)": { // Apply styles for screens with a maximum width of 600px (mobile) width: "100%", // Full width on mobile height: "auto", // Auto height on mobile textAlign: "center", // Center align the content on mobile }, }} > <Typography sx={{ fontSize: "148px", "@media (max-width: 400px)": { fontSize: "100px", }, }} > 😢 </Typography> <Typography sx={{ fontSize: "36px", color: "#000000", marginTop: "-25%", "@media (max-width: 400px)": { fontSize: "26px", marginTop: "-16%", }, }} > {`${translate("register.level.notoptimal")}`} </Typography> </Box> </Button> </Grid> <Grid item lg={4} md={4} xs={12}> <Button onClick={() => { setActiveStep(activeStep + 1); setLevel("OK"); }} > <Box sx={{ width: "200px", height: "100%" }}> <Typography sx={{ fontSize: "148px", "@media (max-width: 400px)": { fontSize: "100px", }, }} > ☺️ </Typography> <Typography sx={{ fontSize: "36px", color: "#000000", marginTop: "-25%", "@media (max-width: 400px)": { fontSize: "26px", marginTop: "-16%", }, }} > {`${translate("register.level.good")}`} </Typography> </Box> </Button> </Grid> <Grid item lg={4} md={4} xs={12}> <Button onClick={() => { setActiveStep(activeStep + 1); setLevel("Good"); }} > <Box sx={{ width: "200px", height: "100%" }}> <Typography sx={{ fontSize: "148px", "@media (max-width: 400px)": { fontSize: "100px", }, }} > 😎 </Typography> <Typography sx={{ fontSize: "32px", color: "#000000", marginTop: "-25%", "@media (max-width: 400px)": { fontSize: "26px", marginTop: "-16%", }, }} > {`${translate("register.level.perfect")}`} </Typography> </Box> </Button> </Grid> </Grid> </div> ), }, { label: `${translate("register.goals.whatAreYourNeeds")}`, obligatory: false, marketingText: <div>Her er endnu et eksempel på ny text i social proof section.</div>, field: ( <div style={{ margin: "auto", marginTop: "5%", textAlign: "center", }} > <Grid container> <Grid item xs={12} sx={{ marginBottom: "2%", "@media (max-width: 600px)": { marginBottom: "30px", }, }} > <Button sx={{ width: "75%", height: "100%", backgroundColor: "#EDE7E2", border: "1px 1px 1px 1px", borderRadius: "16px", color: "black", boxShadow: "0px 4px 0px 0px #C8C3BF", "&:hover": { backgroundColor: "#D6FFCC", boxShadow: "0px 4px 0px 0px #329473", }, }} onClick={() => { setActiveStep(activeStep + 1); setGoals("Needs to catch-up"); }} > <Box sx={{ width: "100%", height: "100%" }}> <Stack direction={"row"}> <div style={{ width: "55px", height: "55px", borderRadius: "60px", background: "rgba(218, 213, 209, 0.65)", justifySelf: "center", textAlign: "center", margin: "3%", }} > <Typography sx={{ fontSize: "36px", marginTop: "8%" }}>⏱</Typography> </div> <Typography sx={{ fontSize: "32px", color: "#000000", marginTop: "4%", "@media (max-width: 600px)": { fontSize: "26px", }, "@media (max-width: 400px)": { fontSize: "22px", marginTop: "7%", }, }} > {`${translate("register.goals.needsToCatch")}`} </Typography> </Stack> </Box> </Button> </Grid> <Grid item xs={12} sx={{ marginBottom: "2%", "@media (max-width: 600px)": { marginBottom: "30px", }, }} > <Button sx={{ width: "75%", height: "100%", backgroundColor: "#EDE7E2", border: "1px 1px 1px 1px", borderRadius: "16px", color: "black", boxShadow: "0px 4px 0px 0px #C8C3BF", "&:hover": { backgroundColor: "#D6FFCC", boxShadow: "0px 4px 0px 0px #329473", }, }} onClick={() => { setActiveStep(activeStep + 1); setGoals("Better grades"); }} > <Box sx={{ width: "100%", height: "100%" }}> <Stack direction={"row"}> <div style={{ width: "55px", height: "55px", borderRadius: "60px", background: "rgba(218, 213, 209, 0.65)", justifySelf: "center", textAlign: "center", margin: "3%", }} > <Typography sx={{ fontSize: "36px", marginTop: "8%" }}>📝</Typography> </div> <Typography sx={{ fontSize: "32px", color: "#000000", marginTop: "4%", "@media (max-width: 600px)": { fontSize: "26px", }, "@media (max-width: 400px)": { fontSize: "22px", marginTop: "7%", }, }} > {`${translate("register.goals.betterGrades")}`} </Typography> </Stack> </Box> </Button> </Grid> <Grid item xs={12} sx={{ marginBottom: "2%", "@media (max-width: 600px)": { marginBottom: "30px", }, }} > <Button sx={{ width: "75%", height: "100%", backgroundColor: "#EDE7E2", border: "1px 1px 1px 1px", borderRadius: "16px", color: "black", boxShadow: "0px 4px 0px 0px #C8C3BF", "&:hover": { backgroundColor: "#D6FFCC", boxShadow: "0px 4px 0px 0px #329473", }, }} onClick={() => { setActiveStep(activeStep + 1); setGoals("Needs motivation"); }} > <Box sx={{ width: "100%", height: "100%" }}> <Stack direction={"row"}> <div style={{ width: "55px", height: "55px", borderRadius: "60px", background: "rgba(218, 213, 209, 0.65)", justifySelf: "center", textAlign: "center", margin: "3%", }} > <Typography sx={{ fontSize: "36px", marginTop: "8%" }}>🎯</Typography> </div> <Typography sx={{ fontSize: "32px", color: "#000000", marginTop: "4%", "@media (max-width: 600px)": { fontSize: "26px", }, "@media (max-width: 400px)": { fontSize: "22px", marginTop: "7%", }, }} > {" "} {`${translate("register.goals.needsMotivation")}`} </Typography> </Stack> </Box> </Button> </Grid> </Grid> </div> ), }, { label: `${translate("register.interests.whatAreYourSpecificInterests")}`, obligatory: false, marketingText: <div>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ratione, eveniet!</div>, field: ( <div style={{ maxWidth: "700px", margin: "auto" }}> {activeStep === 5 ? ( <div style={{ textAlign: "right" }}> <Button sx={{ color: "#000000", border: "1px solid #000000", marginRight: "4%", marginBottom: "1%", marginTop: "-2%", "@media (max-width: 600px)": { marginTop: "2.5%", }, // We could remove margin here, but I think it looks better with margin. }} onClick={() => { setActiveStep(activeStep + 1); }} variant="outlined" size="small" > {`${translate("register.interests.skip")}`} </Button> </div> ) : ( <></> )} <TextField fullWidth label={`${translate("register.interests.search")}`} variant="outlined" sx={{ marginBottom: 2, width: "96%", "@media (max-width: 600px)": { marginLeft: "11%", marginBottom: "2%", width: "300px", }, }} // Adjust spacing as needed // Add onChange handler if needed for search functionality onChange={(e) => { // Your search logic here setSearchText(e.target.value); }} /> <div style={{ height: "60vh", overflow: "auto" }}> <Grid container sx={{ maxWidth: "700px", margin: "auto", "@media (max-width: 600px)": { height: "20vh", width: "300px", maxHeight: "unset", margin: "auto", }, "@media (max-width: 400px)": { width: "275px", maxHeight: "unset", margin: "auto", }, }} > {filteredInterests.map((value, key) => { const isSelected = selectedInterests.includes(value.label); return ( <> <Grid item xs={12} lg={4} md={12}> <Button sx={{ width: "14vw", height: "13vh", border: "1px 1px 1px 1px", borderRadius: "16px", color: "black", boxShadow: isSelected ? "0px 4px 0px 0px #329473" : "0px 4px 0px 0px #C8C3BF", backgroundColor: isSelected ? "lightgreen" : "#EDE7E2", "&:hover": { backgroundColor: "#D6FFCC", boxShadow: "0px 4px 0px 0px #329473", }, marginBottom: "5%", "@media (max-width: 600px)": { width: "90%", height: "13vh", }, "@media (max-width: 1000px)and (min-width: 601px)": { width: "90%", height: "20vh", }, "@media (max-width: 400px)": { width: "100%", height: "17vh", }, // backgroundColor: isSelected ? 'lightgreen' : 'default', // Change color if selected }} onClick={() => toggleInterestSelection(value.label)} > <Box sx={{ width: "100%", height: "100%" }}> <Stack direction={"row"}> <div style={{ width: "55px", height: "55px", borderRadius: "60px", background: "rgba(218, 213, 209, 0.65)", justifySelf: "center", textAlign: "center", marginLeft: "5%", marginTop: "10%", }} > <Typography sx={{ fontSize: "36px", marginTop: "5%" }}> {value.icon} </Typography> </div> <Typography sx={{ fontSize: "20px", color: "#000000", marginTop: "17%", marginLeft: "5%", "@media (max-width: 1000px)and (min-width: 601px)": { marginTop: "4%", marginLeft: "5%", }, }} > {" "} {`${translate(value.label)}`} </Typography> </Stack> </Box> </Button> </Grid> </> ); })} </Grid> </div> {/* This button needs to be with the mobileStepper and appear two times. */} </div> ), }, { label: `${translate("register.createAccount.createYourAccount")}`, obligatory: true, marketingText: <div>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Velit, laboriosam! </div>, field: ( <div style={{ marginLeft: "5%", marginRight: "5%", marginTop: "10%", width: "90%", height: "90%", }} > {/* <Stack sx={{ marginBottom: '1%' }} direction={{ xs: 'column', sm: 'row' }} spacing={2}> */} <RHFTextField name="firstName" label={`${translate("register.createAccount.firstName")}`} sx={{ marginBottom: "2%", "@media (max-width: 600px)": { marginBottom: "4%", }, }} /> <RHFTextField name="lastName" label={`${translate("register.createAccount.lastName")}`} sx={{ marginBottom: "2%", "@media (max-width: 600px)": { marginBottom: "4%", }, }} /> {/* </Stack> */} <Stack sx={{ marginBottom: "1%", "@media (max-width: 600px)": { marginBottom: "2%", }, }} direction={{ xs: "column" }} spacing={2} > <RHFTel defaultCountry={market === "DK" ? "DK" : "ES"} name={`${translate("register.createAccount.phone")}`} label={String(translate("customer.phoneCustomer"))} onChange={handleChange} /> <RHFTextField type="email" name="email" label="Email" /> </Stack> {/* Showing all the steps */} <LoadingButton fullWidth color="inherit" type="submit" size="large" variant="contained" loading={isSubmitSuccessful || isSubmitting} sx={{ bgcolor: "#F75B2B", boxShadow: "0px 8px 0px 0px #EC3E09", fontSize: "22px", marginTop: "3%", borderRadius: "50px", color: (theme) => (theme.palette.mode === "light" ? "common.white" : "#F75B2B"), "&:hover": { bgcolor: "#E95526", boxShadow: "0px 8px 0px 0px #CE3507", color: (theme) => (theme.palette.mode === "light" ? "common.white" : "grey.800"), }, }} > <Typography sx={{ marginTop: "6px", fontSize: "24px" }}>{`${translate("register.createAccount.createAccount")}`}</Typography> </LoadingButton> <Typography component="div" sx={{ color: "text.secondary", mt: 3, typography: "caption", textAlign: "center" }}> {`${translate("register.createAccount.bySigningUp")}`} <Link underline="always" color="text.primary" href="https://www.toptutors.com/betingelser"> {`${translate("register.createAccount.termsAndConditions")}`} </Link> {`${translate("register.createAccount.and")}`} <Link underline="always" color="text.primary" href="https://www.toptutors.com/privatlivspolitik"> {`${translate("register.createAccount.privacyPolicy")}`} </Link> </Typography> </div> ), }, { label: `${translate("register.continue.howDoYouWantToContinue")}`, obligatory: false, marketingText: <div>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Numquam.</div>, field: ( <div style={{ margin: "auto", marginTop: "5%", textAlign: "center", }} > <h2> {`${translate("register.continue.startYourMembership")}`} </h2> <Grid container> <Grid item xs={12} sx={{ marginBottom: "2%", "@media (max-width: 600px)": { marginBottom: "30px", }, }} > <Button sx={{ width: "55%", height: "75%", bgcolor: "#F75B2B", boxShadow: "0px 8px 0px 0px #EC3E09", fontSize: "22px", marginTop: "1%", borderRadius: "50px", color: (theme) => (theme.palette.mode === "light" ? "common.white" : "#F75B2B"), "&:hover": { bgcolor: "#E95526", boxShadow: "0px 8px 0px 0px #CE3507", color: (theme) => (theme.palette.mode === "light" ? "common.white" : "grey.800"), }, }} onClick={() => { navigate(`/membership/order/${customer?.id}`); }} > <Typography sx={{ fontSize: "24px", color: "#fffff", marginTop: "2%", "@media (max-width: 600px)": { fontSize: "20px", }, "@media (max-width: 400px)": { fontSize: "18px", marginTop: "5%", marginBottom: "2%", }, }} > {`${translate("register.continue.customize")}`} </Typography> </Button> </Grid> <Grid item xs={12} sx={{ marginBottom: "2%", "@media (max-width: 600px)": { marginBottom: "30px", }, }} > <h2>{`${translate("register.continue.or")}`}</h2> </Grid> <Grid item xs={12} sx={{ marginBottom: "2%", "@media (max-width: 600px)": { marginBottom: "30px", }, }} > <h2 style={{ marginTop: "-2%", marginBottom: "1%" }}>{`${translate("register.continue.waitUpTo")}`}</h2> <Box sx={{ borderTop: "0.5px solid", borderRight: "0.5px solid", borderLeft: "0.5px solid", width: "75%", height: "100%", backgroundColor: "#f1f2f3", border: "1px 1px 1px 1px", borderRadius: "16px", color: "black", boxShadow: "0px 4px 0px 0px #C8C3BF", margin: "auto", }} > <Typography sx={{ fontSize: "28px", color: "#000000", pt: "3%", "@media (max-width: 600px)": { fontSize: "24px", }, "@media (max-width: 400px)": { fontSize: "22px", marginTop: "7%", }, }} > {`${translate("register.continue.getContacted")}`} </Typography> <Box sx={{ fontSize: "16px", color: "#000000", marginTop: "2%", width: "100%", textAlign: "left", ml: "5%", pb: "5%", "@media (max-width: 600px)": { fontSize: "18px", }, "@media (max-width: 400px)": { fontSize: "16px", marginTop: "7%", }, }} > <Grid container> <Grid item lg={8} xs={12}> <Typography sx={{ pt: "2%", pr: "10%", "@media (max-width: 600px)": { margin: "auto", }, }} > {`${translate("register.continue.copyContacted")}`} </Typography> </Grid> <Grid item xs={12} lg={4} sx={{ "@media (max-width: 600px)": { margin: "auto", mt: "5%", }, }} > <Box sx={{ "@media (max-width: 600px)": { width: "130px", margin: "auto", }, }} > <img src={emojiPhone} alt="emoji on the phone" style={{ width: "130px" }} /> </Box> </Grid> </Grid> </Box> </Box> </Grid> </Grid> </div> ), }, ]; const onSubmit = async (data: FormValuesProps) => { // try { // const response = await register( // data.email || '', // data.firstName || '', // data.lastName || '', // data.phone || '', // school, // selectedSubjects, // level, // goals, // selectedInterests, // data.market // ); // if (response) { // Mixpanel.track('New Customer Flow', { // email: data.email || '', // firstName: data.firstName || '', // lastName: data.lastName || '', // phone: data.phone || '', // school: school, // selectedSubject: selectedSubjects, // level: level, // goals: goals, // selectedInterests: selectedInterests, // }); // dispatch(getCustomerUnprotected(response)); setActiveStep(activeStep + 1); // } else { // reset(); // } // } catch (error) { // reset(); // } }; const handleNext = () => { setSearchText(""); setSearchTextSubject(""); setActiveStep((prevActiveStep) => prevActiveStep + 1); }; const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1); }; return ( <Grid container> <Grid item lg={4} xs={0} sx={{ "@media (max-width: 1199px)": { display: "none", }, }} > <Box sx={{ height: "100%", backgroundColor: theme.palette.primary.light, }} > <Box sx={{ paddingTop: "40%", display: "flex", justifyContent: "center", alignItems: "center", width: "100%", }} > {/* Container for the other two images positioned on the right */} {/* <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'start', mr: 5 }}> <Box component="img" src="/assets/trustpilot_logo.svg" sx={{ height: 50, mb: 1 }} /> <Box component="img" src="/assets/trustpilot_ratings_4halfstar.svg" sx={{ height: 50 }} /> </Box> */} <Grid container sx={{ margin: "auto", marginLeft: "5%" }}> <Grid item lg={12}> <Typography sx={{ color: "#FFFFFF", fontSize: "32px", }} > {steps[activeStep].marketingText} </Typography> </Grid> <Grid item lg={12} sx={{ paddingTop: "50%" }}> <a href="https://www.trustpilot.com/review/www.toptutors.com" style={{ textDecoration: "none" }}> <TrustpilotWidget></TrustpilotWidget> </a> </Grid> </Grid> </Box> </Box> </Grid> <Grid item lg={8} xs={12}> <Box sx={{ height: "100vh", }} > <div style={{ textAlign: "right" }}> {/* {activeStep === 4 ? ( <Button sx={{ color: '#000000', border: '1px solid #000000', marginRight: '3%', // We could remove margin here, but I think it looks better with margin. }} onClick={() => { setActiveStep(activeStep + 1); }} variant="outlined" size="small" > Skip </Button> ) : ( <></> )} */} <LanguagePopover /> </div> <MobileStepper variant="progress" steps={steps.length} position="static" activeStep={activeStep} sx={{ maxWidth: 400, flexGrow: 1, textAlign: "center", margin: "auto", marginTop: "2.5%", }} nextButton={ activeStep === 5 || activeStep == 2 || activeStep == 1 ? ( <Button color="warning" variant="contained" size="small" onClick={handleNext} sx={{ margin: "auto" }}> {`${translate("register.continueButton")}`} {theme.direction === "rtl" ? <Iconify icon={"mdi:arrow-left-thick"} /> : <Iconify icon={"mdi:arrow-right-thick"} />} </Button> ) : ( <> <div style={{ width: "65px", height: "30px", margin: "auto" }}></div> </> ) } backButton={ activeStep !== 0 && activeStep !== 7 ? ( <Button color="warning" variant="contained" size="small" onClick={handleBack} disabled={activeStep === 0} sx={{ margin: "auto" }}> {theme.direction === "rtl" ? <Iconify icon={"mdi:arrow-right-thick"} /> : <Iconify icon={"mdi:arrow-left-thick"} />} {`${translate("register.back")}`} </Button> ) : ( <> <div style={{ width: "65px", height: "30px", margin: "auto" }}></div> </> ) } /> {!!errors.afterSubmit && ( <Alert severity="error" sx={{ textAlign: "right", bgcolor: "grey", width: "400px" }}> Ups! Der opstod en fejl. Prøv igen. 🔄 </Alert> )} <Typography sx={{ marginTop: "2%", textAlign: "center" }} color={theme.palette.common.black} variant="h3" key={steps[activeStep].label}> {steps[activeStep].label} </Typography> <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}> <Stack spacing={2.5}> {steps.map((step, index: number) => { return ( activeStep === index && ( <Slide direction="left" in={activeStep === index} mountOnEnter unmountOnExit timeout={{ enter: 500, exit: 0 }}> <Step key={step.label}>{step.field}</Step> </Slide> ) ); })} </Stack> </FormProvider> <Logo sx={{ height: "50px", position: "absolute", right: 10, bottom: 5, color: theme.palette.common.black, ml: 5, // adjust this value as needed for left margin "@media (max-width: 1200px)": { display: "none", }, }} /> </Box> </Grid> </Grid> ); }
import {screen} from '@testing-library/react'; import {OrdersList} from '.'; import {render} from 'utils/test-utils'; import mock from './mock'; jest.mock('components/Empty', () => ({ __esModule: true, Empty: function Mock() { return <div data-testid="Mock Empty" />; }, })); jest.mock('components/GameItem', () => ({ __esModule: true, GameItem: function Mock({children}: {children: React.ReactNode}) { return <div data-testid="Mock GameItem">{children}</div>; }, })); describe('<OrdersList />', () => { it('should render the game items', () => { render(<OrdersList items={mock} />); expect( screen.getByRole('heading', {name: /my orders/i}), ).toBeInTheDocument(); expect(screen.getAllByTestId('Mock GameItem')).toHaveLength(2); }); it('should render empty state', () => { render(<OrdersList />); expect(screen.getByTestId('Mock Empty')).toBeInTheDocument(); }); });
package com.protsprog.highroad.compose.sideeffects.details /* READ https://developer.android.com/reference/kotlin/androidx/compose/runtime/package-summary#DisposableEffect(kotlin.Any,kotlin.Function1) https://developers.google.com/maps/documentation/android-sdk/maps-compose */ import android.os.Bundle import androidx.annotation.FloatRange import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import com.google.android.libraries.maps.GoogleMap import com.google.android.libraries.maps.MapView import com.protsprog.highroad.R /** * Remembers a MapView and gives it the lifecycle of the current LifecycleOwner */ @Composable fun rememberMapViewWithLifecycle(): MapView { val context = LocalContext.current // DisposableEffect step. Make MapView follow the lifecycle val mapView = remember { MapView(context).apply { id = R.id.map } } val lifecycle = LocalLifecycleOwner.current.lifecycle DisposableEffect(key1 = lifecycle, key2 = mapView) { val lifecycleObserver = getMapLifecycleObserver(mapView) lifecycle.addObserver(lifecycleObserver) onDispose { lifecycle.removeObserver(lifecycleObserver) } } return mapView } fun GoogleMap.setZoom( @FloatRange(from = MinZoom.toDouble(), to = MaxZoom.toDouble()) zoom: Float ) { resetMinMaxZoomPreference() setMinZoomPreference(zoom) setMaxZoomPreference(zoom) } private fun getMapLifecycleObserver(mapView: MapView): LifecycleEventObserver = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_CREATE -> mapView.onCreate(Bundle()) Lifecycle.Event.ON_START -> mapView.onStart() Lifecycle.Event.ON_RESUME -> mapView.onResume() Lifecycle.Event.ON_PAUSE -> mapView.onPause() Lifecycle.Event.ON_STOP -> mapView.onStop() Lifecycle.Event.ON_DESTROY -> mapView.onDestroy() else -> throw IllegalStateException() } }
import React, { useRef, useState } from 'react'; import BackgroundImage from '../../components/BackgroundImage/BackgroundImage'; import LastScreen from '../../components/LastScreen/LastScreen'; import MainScreen from '../../components/MainScreen/MainScreen'; import StartScreen from '../../components/StartScreen/StartScreen'; import SlideWrapper from '../../components/SlideWrapper/SlideWrapper'; import { useSlide } from '../../hooks/useSlide'; import { ScoreTestItems, ScoreTestResultFormItem } from './scoreTest.type'; import { SelectFormItems, TestDisposition, WeightedScore, WeightedScoreItem, } from '../../tests.types'; import { useFetcher } from '../../../../hooks/useFetcher'; interface ScoreTypeTestProps { testItems: ScoreTestItems; testDisposition?: TestDisposition; scoreResultItems?: ScoreTestResultFormItem[]; handleCloseTemporaryTest?: () => void; } const ScoreTypeTest = ({ testItems, scoreResultItems, testDisposition = 'real', handleCloseTemporaryTest, }: ScoreTypeTestProps): JSX.Element => { const { id, title, subTitle, explain, testType, isPublic, weightedScoreDictionary, personalityItems, } = testItems; const fetcher = useFetcher(); const [personalityTest] = useState<SelectFormItems[]>(personalityItems); const [lastSlide] = useState<number>(personalityTest.length); const [weightedScore, setWeightedScore] = useState<WeightedScore>( weightedScoreDictionary, ); const [resultItems, setResultItems] = useState<ScoreTestResultFormItem | null>(null); const { slideRef, nextSlide, resetSlide, isTransitioning } = useSlide(); const startClick = (): void => { nextSlide(); }; const raseScore = (weightedScoreItems: WeightedScoreItem[]) => { for (const { resultContent, score } of weightedScoreItems) { weightedScore[resultContent] += score; } setWeightedScore({ ...weightedScore }); }; const optionsButtonClick = ({ weightedScoreItems, currentSlide }): void => { raseScore(weightedScoreItems); if (currentSlide === lastSlide) { const res = getHighestScoreType(); if (testDisposition === 'real') { requestResult(res); } else { requestTempResult(res); } return; } nextSlide(); }; const getHighestScoreType = (): string => { const sortedWeightScore = Object.entries(weightedScore).sort( ([, a], [, b]) => (a > b ? -1 : 1), ); const [, sortedValue] = sortedWeightScore[0]; const shuffleWeightScore = sortedWeightScore .reduce( (array, [key, value]) => sortedValue === value ? [...array, key] : array, [], ) .sort(() => Math.random() - 0.5); return shuffleWeightScore[0]; }; const requestResult = async (result: string) => { const res = await fetcher( 'get', `/personality/${id}/${testType}/results/${result}`, ); if (res.success) { const { resultItems } = res.data; setResultItems(resultItems[0]); nextSlide(); } else { alert('서버 점검중입니다.\n잠시 후 다시 시도해주세요'); } }; const requestTempResult = async (result: string) => { const res = scoreResultItems.filter( ({ resultContent }) => resultContent === result, ); setResultItems(res[0]); nextSlide(); }; const lastBackgroundImgRef = useRef(null); const reStartClick = (): void => { resetSlide(); setResultItems(null); setWeightedScore(weightedScoreDictionary); lastBackgroundImgRef.current.scrollTop = 0; }; return ( <SlideWrapper ref={slideRef}> <BackgroundImage> <StartScreen title={title} subTitle={subTitle} onClick={startClick} /> </BackgroundImage> {personalityTest.map(({ question, optionItems }, index: number) => ( <BackgroundImage key={`p${index}`}> <MainScreen question={question} optionItems={optionItems} slideIndex={index} totalStep={personalityTest.length} onClick={optionsButtonClick} isTransitioning={isTransitioning} /> </BackgroundImage> ))} {resultItems && ( <BackgroundImage ref={lastBackgroundImgRef}> <LastScreen isPublic={isPublic} onClick={reStartClick} onClose={handleCloseTemporaryTest} resultContent={resultItems.resultContent} explanationContent={resultItems.explanationContent} resultImageUrl={ resultItems.resultImageUrl ? resultItems.resultImageUrl : '' } /> </BackgroundImage> )} </SlideWrapper> ); }; export default ScoreTypeTest;
<script setup lang="ts"> import { ref, reactive, computed, nextTick } from 'vue'; import type { FormInstance, FormRules } from 'element-plus'; const dialogVisible = ref(false); const formRef = ref<FormInstance>(); const editItem = ref<Record<string, any>>(); const formValue = reactive({ domainCode: '', domainName: '', domainDesc: '', }); const rules = reactive<FormRules>({ domainCode: [ { required: true, message: '请输入领域编码', trigger: 'blur' }, ], domainName: [ { required: true, message: '请输入领域名称', trigger: 'blur' }, ], }); const emit = defineEmits(['add', 'edit']); function onCancel () { dialogVisible.value = false; } async function onSubmit () { if (!formRef.value) return; const valid = await formRef.value.validate(() => {}); if (!valid) { return; } dialogVisible.value = false; if (editItem.value) { emit('edit', { ...editItem.value, ...formValue }); } else { emit('add', formValue); } } function open (item?: Record<string, any>) { editItem.value = item; dialogVisible.value = true; nextTick(() => { if (formRef.value) { formRef.value.resetFields(); } if (item) { formValue.domainCode = item.domainCode; formValue.domainName = item.domainName; formValue.domainDesc = item.domainDesc; } }); } const title = computed(() => { if (editItem.value) { return '编辑领域'; } return '新增领域'; }); defineExpose({ open }); </script> <template> <el-dialog v-model="dialogVisible" :title="title" width="400" > <div class="form"> <el-form ref="formRef" label-position="top" :model="formValue" :rules="rules" > <el-form-item label="领域代码" prop="domainCode"> <el-input v-model="formValue.domainCode" /> </el-form-item> <el-form-item label="领域名称" prop="domainName"> <el-input v-model="formValue.domainName" /> </el-form-item> <el-form-item label="领域描述" prop="domainDesc"> <el-input v-model="formValue.domainDesc" /> </el-form-item> </el-form> </div> <template #footer> <span class="dialog-footer"> <el-button @click="onCancel">取消</el-button> <el-button type="primary" @click="onSubmit">确定</el-button> </span> </template> </el-dialog> </template> <style scoped> .dialog-footer button:first-child { margin-right: 10px; } </style>
<script lang="ts" setup> import { onMounted, ref, provide } from 'vue'; import TestsModal from '@/components/templates/TestsModal.vue'; import MemberModal from '@/components/templates/MemberModal.vue'; import TaskModal from '@/components/templates/TaskModal.vue'; import SkillModal from '@/components/templates/SkillModal.vue'; const testModalOpenManager = ref(false); const memberModalOpenManager = ref(false); const taskModalOpenManager = ref(false); const skillModalOpenManager = ref(false); provide('testModalOpenManager', testModalOpenManager); provide('memberModalOpenManager', memberModalOpenManager); provide('taskModalOpenManager', taskModalOpenManager); provide('skillModalOpenManager', skillModalOpenManager); onMounted(() => { }); </script> <template> <div> <div class="toolbar flex row justify-start align-center"> <button @click="testModalOpenManager = true" class="toolbar__tool hoverable"><font-awesome-icon class="icon" icon="plus"/>&nbsp; Test</button> <div class="toolbar__divider"></div> <button @click="memberModalOpenManager = true" class="toolbar__tool hoverable"><font-awesome-icon class="icon" icon="cog"/>&nbsp; Opérateurs</button> <div class="toolbar__divider"></div> <button @click="taskModalOpenManager = true" class="toolbar__tool hoverable"><font-awesome-icon class="icon" icon="cog"/>&nbsp; Tâches</button> <div class="toolbar__divider"></div> <button @click="skillModalOpenManager = true" class="toolbar__tool hoverable"><font-awesome-icon class="icon" icon="cog"/>&nbsp; Compétences</button> </div> <TestsModal/> <MemberModal/> <TaskModal/> <SkillModal/> </div> </template> <style lang="scss" scoped> .toolbar { width: 100%; height: 3rem; background-color: lighten($shadowColor, 40%); border-radius: 6px; padding-inline: 1rem; gap: 1rem; } .toolbar__tool { padding: 0.5rem; border-radius: 6px; } .toolbar__divider { height: calc(100% - 1rem); width: 1px; background-color: $shadowColor; } </style>
#include "main.h" /** *_pow_recursion - calculate the power of a number *@x:Number to be raised *@y:The power *Return:The power of a value raised to a number */ int _pow_recursion(int x, int y) { if (y < 0) { return (-1); } if (y == 0) { return (1); } else { return(x * _pow_recursion(x, y - 1)); } }
import React,{useState,useCallback} from 'react' import { Table,Dropdown, Menu ,Collapse, message, Form, Upload, Modal, Button, Input} from 'antd'; import { SearchOutlined ,FilePdfOutlined,FileWordOutlined ,FileImageOutlined,FileExcelOutlined,FilePptOutlined,FileTextOutlined,InboxOutlined } from '@ant-design/icons' import './css/file.css'; import '@ant-design/compatible/assets/index.css'; import { ColumnProps } from 'antd/es/table'; import PlusButton from './svgs/PlusButton'; import CreateFileModal from './CreateFileModal'; import CreateLinkModal from './CreateLinkModal'; import DropDownFile from './DropdownFile'; import DropDownLink from './DropdownLink'; const tailLayout = { wrapperCol: { offset: 8, span: 16 }, }; const layout = { labelCol: { span: 8 }, wrapperCol: { span: 16 }, }; function MaterialList() { const [visible, showCreateFileModal] = useState(false) const [visible2, showCreateLinkModal] = useState(false) const statut = { name: 'file', multiple: true, action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76', onChange(info:any) { const { status } = info.file; if (status !== 'uploading') { console.log(info.file, info.fileList); } if (status === 'done') { message.success(`${info.file.name} file uploaded successfully.`); } else if (status === 'error') { message.error(`${info.file.name} file upload failed.`); } }, }; const [form] = Form.useForm(); const { Dragger } = Upload; var icone=<></> const { Panel } = Collapse; function callback(key:any) { console.log(key); } interface File { key: number, name:string, type: string, link:string, date:string, action:any; } const data: File[] = [ { key: 0, name:"controle", link:"test.pdf", type:"pdf", date:"05/05/2020 16:00", action:"", }, { key: 1, name:"controle2", link:"test.pdf", type:"doc", date:"04/05/2020 23:00", action:"", }, ]; const columnsFile: ColumnProps<File>[] = [{ title: 'name', dataIndex: 'name', key: 'name', render:(cell, row, index) => { var type:string[]; type=data[index].name.split(".") console.log(type) switch (type[1]) { case "pdf": icone=<FilePdfOutlined /> break; case "doc":icone=<FileWordOutlined /> break; case "jpg":icone=<FileImageOutlined /> break; case "xsl":icone=<FileExcelOutlined /> break; case"ppt":icone=<FilePptOutlined /> break; default:icone=<FileTextOutlined /> break; } return ( <div> {icone}{" "} {data[index].name} </div> ) } }, { title: 'type', dataIndex: 'type', key: 'type', }, { title: 'link', dataIndex: 'link', key: 'link', }, { title: 'Action', dataIndex: 'action', key: 'action', render:()=>( <DropDownFile></DropDownFile> ), }, ]; interface lien { key: number, title:string, link:string, date:string, action:any; } const mydata: lien[] = [ { key: 0, title:"controle", link:"www.test.ma", date:"05/05/2020 16:00", action:"", }, { key: 1, title:"controle", link:"www.test.ma", date:"04/05/2020 23:00", action:"", }, ]; const columnsLink: ColumnProps<lien>[] = [{ title: 'title', dataIndex: 'title', key: 'title', }, { title: 'link', dataIndex: 'link', key: 'link', }, { title: 'Action', dataIndex: 'action', key: 'action', render:()=>( <DropDownLink/> ), }, ]; return ( <div> <Collapse defaultActiveKey={['1']} onChange={callback} accordion> <Panel header="documentation" key="1"> <div style={{paddingBottom:"55px",position:"sticky"}}> <Input placeholder="Search" className="searchbar" prefix={<SearchOutlined />}/> </div> <Table<File> columns={columnsFile} dataSource={data} /> <PlusButton showModal={() => showCreateFileModal(!visible)} /> <CreateFileModal visible={visible} showModal = {showCreateFileModal}/> </Panel> <Panel header="liens" key="2"> <div style={{paddingBottom:"55px",position:"sticky"}}> <Input placeholder="Search" className="searchbar" prefix={<SearchOutlined />}/> </div> <Table<lien> columns={columnsLink} dataSource={mydata} /> <PlusButton showModal={() => showCreateLinkModal(!visible2)} /> <CreateLinkModal visible={visible2} showModal = {showCreateLinkModal}/> </Panel> </Collapse> </div>) }; export default MaterialList
import {Link} from "react-router-dom" import PropTypes from "prop-types"; import useForm from "../../../shared/hooks/useForm"; import TextField from "../../../shared/components/TextField"; import Button from "../../../shared/components/Button/Button"; import fields from "./fields"; import initialState from "./initialState"; import googleImg from "../../../assets/google.png"; import sprite from "../../../assets/svg/sprite.svg"; import style from "./loginForm.module.scss"; const LoginForm = ({ onSubmit, onClick }) => { const { state, handleChange, handleSubmit } = useForm({ onSubmit, initialState, }); const { email, password } = state; const handleClick = () => { onClick("register"); return; }; const pathGoogle = "//pro-test.onrender.com/api/users/google"; const pathFacebook = "//pro-test.onrender.com/api/users/facebook/callback"; return ( <> <p className={style.google_text}>You can login with:</p> <div className={style.google_wrap}> <a href={pathGoogle} className={style.google_btn} rel="noreferrer noopener" > {" "} <img alt="google icon" src={googleImg} width="84" height="18" /> </a> <a href={pathFacebook} className={style.facebook_btn} rel="noreferrer noopener" > {" "} <svg className={style.facebook_icon}> <use href={`${sprite}#icon-facebook`}></use> </svg> Facebook </a> </div> <p className={style.login_text}> Login to our app using e-mail and password: </p> <form className="" onSubmit={handleSubmit}> <TextField onChange={handleChange} value={email} {...fields.email} className={style.input} /> <TextField onChange={handleChange} value={password} {...fields.password} className={style.last_input} /> <Link to="/reset-password" className={style.pass_link}> Forgot password? </Link> <div className={style.wrap}> <Button text="Sign in" type="submit" active /> <Button text="Sign up" type="button" onClick={handleClick} /> </div> </form> </> ); }; LoginForm.defaultProps = { onSubmit: () => {}, onClick: () => {}, }; LoginForm.propTypes = { onSubmit: PropTypes.func.isRequired, onClick: PropTypes.func.isRequired, }; export default LoginForm;
// Copyright 2020 The Tint Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/ast/variable_decl_statement.h" #include "src/writer/hlsl/test_helper.h" namespace tint { namespace writer { namespace hlsl { namespace { using HlslGeneratorImplTest_VariableDecl = TestHelper; TEST_F(HlslGeneratorImplTest_VariableDecl, Emit_VariableDeclStatement) { auto* var = Global("a", ty.f32(), ast::StorageClass::kInput); auto* stmt = create<ast::VariableDeclStatement>(var); GeneratorImpl& gen = Build(); gen.increment_indent(); ASSERT_TRUE(gen.EmitStatement(out, stmt)) << gen.error(); EXPECT_EQ(result(), " float a;\n"); } TEST_F(HlslGeneratorImplTest_VariableDecl, Emit_VariableDeclStatement_Const) { auto* var = Const("a", ty.f32()); auto* stmt = create<ast::VariableDeclStatement>(var); WrapInFunction(stmt); GeneratorImpl& gen = Build(); gen.increment_indent(); ASSERT_TRUE(gen.EmitStatement(out, stmt)) << gen.error(); EXPECT_EQ(result(), " const float a;\n"); } TEST_F(HlslGeneratorImplTest_VariableDecl, Emit_VariableDeclStatement_Array) { auto* var = Global("a", ty.array<f32, 5>(), ast::StorageClass::kInput); auto* stmt = create<ast::VariableDeclStatement>(var); GeneratorImpl& gen = Build(); gen.increment_indent(); ASSERT_TRUE(gen.EmitStatement(out, stmt)) << gen.error(); EXPECT_EQ(result(), " float a[5];\n"); } TEST_F(HlslGeneratorImplTest_VariableDecl, Emit_VariableDeclStatement_Function) { auto* var = Global("a", ty.f32(), ast::StorageClass::kFunction); auto* stmt = create<ast::VariableDeclStatement>(var); GeneratorImpl& gen = Build(); gen.increment_indent(); ASSERT_TRUE(gen.EmitStatement(out, stmt)) << gen.error(); EXPECT_EQ(result(), " float a;\n"); } TEST_F(HlslGeneratorImplTest_VariableDecl, Emit_VariableDeclStatement_Private) { auto* var = Global("a", ty.f32(), ast::StorageClass::kPrivate); auto* stmt = create<ast::VariableDeclStatement>(var); GeneratorImpl& gen = Build(); gen.increment_indent(); ASSERT_TRUE(gen.EmitStatement(out, stmt)) << gen.error(); EXPECT_EQ(result(), " float a;\n"); } TEST_F(HlslGeneratorImplTest_VariableDecl, Emit_VariableDeclStatement_Initializer_Private) { Global("initializer", ty.f32(), ast::StorageClass::kInput); auto* var = Global("a", ty.f32(), ast::StorageClass::kPrivate, Expr("initializer")); auto* stmt = create<ast::VariableDeclStatement>(var); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.EmitStatement(out, stmt)) << gen.error(); EXPECT_EQ(result(), R"(float a = initializer; )"); } TEST_F(HlslGeneratorImplTest_VariableDecl, Emit_VariableDeclStatement_Initializer_ZeroVec) { auto* var = Var("a", ty.vec3<f32>(), ast::StorageClass::kFunction, vec3<f32>()); auto* stmt = create<ast::VariableDeclStatement>(var); WrapInFunction(stmt); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.EmitStatement(out, stmt)) << gen.error(); EXPECT_EQ(result(), R"(float3 a = float3(0.0f, 0.0f, 0.0f); )"); } TEST_F(HlslGeneratorImplTest_VariableDecl, Emit_VariableDeclStatement_Initializer_ZeroMat) { auto* var = Var("a", ty.mat2x3<f32>(), ast::StorageClass::kFunction, mat2x3<f32>()); auto* stmt = create<ast::VariableDeclStatement>(var); WrapInFunction(stmt); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.EmitStatement(out, stmt)) << gen.error(); EXPECT_EQ(result(), R"(float2x3 a = float2x3(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f); )"); } } // namespace } // namespace hlsl } // namespace writer } // namespace tint
import React, { useState, useEffect } from "react"; import moment from "moment"; import "react-big-calendar/lib/css/react-big-calendar.css"; import { Button, Modal, Label, Select } from "flowbite-react"; import FullCalendarComponent from "./FullCalendarComponent.js"; import { Box } from "@mui/material"; import "moment/locale/nb"; import Alert from "@mui/material/Alert"; import CircularProgress from "@mui/material/CircularProgress"; import WeeklyRunningVolume from "./WeeklyRunningVolume.js"; import IconButton from "@mui/material/IconButton"; import CloseIcon from "@mui/icons-material/Close"; import { AiOutlineLoading } from "react-icons/ai"; import { fetchWorkouts, handleSubmitEdit, handleSubmit, exportToGoogleCalendar, deleteWorkout, } from "./Hooks/workoutApi.js"; import authorizeGoogleOAuth from "../../services/GoogleServices/authorizeGoogleOAuth.js"; moment.locale("nb"); const UserWorkoutForm = () => { const [date, setDate] = useState(""); const [name, setName] = useState(""); const [time, setTime] = useState(""); const [description, setDescription] = useState(""); const [type, setType] = useState(""); const [distance, setDistance] = useState(""); const [duration, setDuration] = useState(""); const [zone, setZone] = useState(""); const [currentWeek, setCurrentWeek] = useState(moment().isoWeek()); const userStr = localStorage.getItem("user"); const user = userStr ? JSON.parse(userStr) : null; const [workouts, setWorkouts] = useState([]); const [selectedWorkout, setSelectedWorkout] = useState(""); // // Valgt treningsøkt i kalenderen const [exportingWorkout, setExportingWorkout] = useState(false); //for spinner/loader const [workoutExported, setWorkoutExported] = useState(false); //for å erstatte knap når ferdig' const [workoutNotExported, setWorkoutNotExported] = useState(false); //for å vise feilmelding const [exportingWeeklyWorkout, setExportingWeeklyWorkout] = useState(false); const [weeklyWorkoutExported, setWeeklyWorkoutExported] = useState(false); const [weeklyWorkoutNotExported, setWeeklyWorkoutNotExported] = useState(false); useEffect(() => { fetchWorkouts(null, user, setWorkouts); }, [user.login]); //ENDRES HVER GANG BRUKER-OBJEKTET const [openAddWorkoutModal, setOpenAddWorkoutModal] = useState(false); const [openViewWorkoutModal, setOpenViewWorkoutModal] = useState(false); const [openEditWorkoutModal, setOpenEditWorkoutModal] = useState(false); const formatDate = (date) => { return moment(date).format("YYYY-MM-DD HH:mm"); }; useEffect(() => { if (openAddWorkoutModal) { // Reset standardverdiene når modalen for å legge til ny trening åpnes setTime("12:00"); // Standardverdien for tid setName(""); setDescription(""); setType(""); setDistance(""); setDuration(""); setZone(""); } }, [openAddWorkoutModal]); useEffect(() => { if (openEditWorkoutModal && selectedWorkout) { // Sett feltene basert på verdiene i valgt treningsøkt setDate(moment(selectedWorkout.date).format("YYYY-MM-DD")); setTime(moment(selectedWorkout.date).format("HH:mm")); setName(selectedWorkout.name || ""); setDescription(selectedWorkout.description || ""); setType(selectedWorkout.type || ""); setDistance(selectedWorkout.distance || ""); setDuration(selectedWorkout.duration || ""); setZone(selectedWorkout.intensityZone || ""); } }, [selectedWorkout, openEditWorkoutModal]); useEffect(() => { setExportingWorkout(false); setWorkoutExported(false); setWorkoutNotExported(false); }, [openViewWorkoutModal]); useEffect(() => { setExportingWeeklyWorkout(false); setWeeklyWorkoutExported(false); setWeeklyWorkoutNotExported(false); }, [currentWeek]); const exportWeekToGoogleCalendar = () => { const weekWorkouts = workouts.filter( (workout) => moment(workout.date).isoWeek() === currentWeek ); weekWorkouts.forEach((workout) => { exportToGoogleCalendar( workout, user, setExportingWeeklyWorkout, setWeeklyWorkoutExported, setWeeklyWorkoutNotExported ); }); }; return ( <div> <label htmlFor="date">Date:</label> <FullCalendarComponent workouts={workouts} setDate={setDate} setTime={setTime} setOpenAddWorkoutModal={setOpenAddWorkoutModal} setOpenViewWorkoutModal={setOpenViewWorkoutModal} setSelectedWorkout={setSelectedWorkout} setCurrentWeek={setCurrentWeek} /> <Modal show={openAddWorkoutModal} onClose={() => setOpenAddWorkoutModal(false)} > <Modal.Header>Add Workout</Modal.Header> <Modal.Body> <div className="space-y-6"> <form onSubmit={(e) => { e.preventDefault(); const durationInSeconds = type === "Running" ? parseInt(duration, 10) * 60 : undefined; const dateTime = moment( `${date} ${time}`, "YYYY-MM-DD HH:mm" ).toISOString(); const workoutData = { date: dateTime, name, description, type, distance: type === "Running" ? parseFloat(distance) : undefined, durationSeconds: durationInSeconds, intensityZone: type === "Running" ? parseInt(zone, 10) : undefined, }; handleSubmit( e, null, user, setWorkouts, workoutData, setOpenAddWorkoutModal ); }} > {" "} <div className="max-w-md py-2"> <div className="mb-2 block"> <Label htmlFor="type">Type:</Label> </div> <Select id="type" value={type} required onChange={(e) => setType(e.target.value)} > <option value="">Choose a type</option> <option value="Running">Running</option> <option value="Strength">Strength</option> <option value="Cardio">General Cardio</option> </Select> <div className="max-w-sm py-2"> <label htmlFor="name" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Name: </label> <input type="text" required id="distance" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" value={name} onChange={(e) => setName(e.target.value)} /> </div> </div> {type === "Running" && ( <> <div className="max-w-sm py-2"> <label htmlFor="distance" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Distance (km): </label> <input type="number" id="distance" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" value={distance} onChange={(e) => setDistance(e.target.value)} /> </div> <div className="max-w-sm py-2"> <label htmlFor="duration" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Duration (minutes): </label> <input type="number" id="duration" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" value={duration} onChange={(e) => setDuration(e.target.value)} /> </div> <div className="max-w-sm py-2"> <label htmlFor="zone" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Choose Zone </label> <Select id="zone" value={zone} onChange={(e) => setZone(e.target.value)} > <option value="">Choose a zone</option> <option value="1">Zone 1</option> <option value="2">Zone 2</option> <option value="3">Zone 3</option> <option value="4">Zone 4</option> <option value="5">Zone 5</option> </Select> </div> </> )} <div className="max-w-sm py-2"> <label htmlFor="description" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Description: </label> <textarea id="description" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" value={description} onChange={(e) => setDescription(e.target.value)} /> </div> <div className="max-w-sm py-2"> <label htmlFor="date" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Date: </label> <input type="date" id="date" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" value={date} onChange={(e) => setDate(e.target.value)} /> </div> <div className="max-w-sm py-2"> <label htmlFor="time" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > Time: </label> <input type="time" id="time" value={time} className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" onChange={(e) => setTime(e.target.value)} // Antar at du har en setTime-funksjon i din useState hooks /> </div> <Button type="submit">Add Workout</Button> </form> </div> </Modal.Body> </Modal> <Modal show={openViewWorkoutModal} onClose={() => setOpenViewWorkoutModal(false)} > <IconButton aria-label="close" onClick={() => setOpenViewWorkoutModal(false)} sx={{ position: "absolute", right: 8, top: 8, color: (theme) => theme.palette.grey[500], }} > <CloseIcon /> </IconButton> <Modal.Body> {selectedWorkout && ( <div className="space-y-6"> <div className="max-w-md py-2"> <h2 className="mb-2 text-lg font-medium text-gray-900 dark:text-white"> {selectedWorkout.name} </h2> <p className="text-sm text-gray-900 dark:text-white"> Dato: {formatDate(selectedWorkout.date)} </p> <p className="text-sm text-gray-900 dark:text-white"> Type: {selectedWorkout.type} </p> {selectedWorkout.type === "Running" && ( <> <p className="text-sm text-gray-900 dark:text-white"> Duration: {selectedWorkout.duration} minutes </p> <p className="text-sm text-gray-900 dark:text-white"> Distance: {selectedWorkout.distance} km </p> <p className="text-sm text-gray-900 dark:text-white"> Intensity: Zone {selectedWorkout.intensityZone} </p> </> )} <p className="text-sm text-gray-900 dark:text-white"> Description: {selectedWorkout.description} </p> </div> </div> )} </Modal.Body> <Modal.Footer> <Button color="gray" onClick={() => { setOpenViewWorkoutModal(false); setOpenEditWorkoutModal(true); }} > Edit </Button> {exportingWorkout ? ( <CircularProgress /> ) : workoutExported ? ( <Alert severity="success">Workout exported successfully!</Alert> ) : workoutNotExported ? ( <Alert severity="error" sx={{ mt: 2 }}> Failed to export workout </Alert> ) : ( <Button color="blue" onClick={() => { if (selectedWorkout) { exportToGoogleCalendar( selectedWorkout, user, setExportingWorkout, setWorkoutExported, setWorkoutNotExported ); // Kall eksportfunksjonen når knappen klikkes } }} > Export to Google Calendar </Button> )} </Modal.Footer> </Modal> <Modal show={openEditWorkoutModal} onClose={() => setOpenEditWorkoutModal(false)} > <Modal.Header>Edit Workout</Modal.Header> <Modal.Body> <div className="space-y-6"> <form onSubmit={(e) => { e.preventDefault(); const durationInSeconds = type === "Running" ? parseInt(duration, 10) * 60 : undefined; const dateTime = moment( `${date} ${time}`, "YYYY-MM-DD HH:mm" ).toISOString(); const workoutData = { date: dateTime, name, description, type, distance: type === "Running" ? parseFloat(distance) : undefined, durationSeconds: durationInSeconds, // Bruk den konverterte varigheten i sekunder intensityZone: type === "Running" ? parseInt(zone, 10) : undefined, }; handleSubmitEdit( e, null, user, selectedWorkout, setOpenEditWorkoutModal, setWorkouts, workoutData ); }} > {" "} <div className="max-w-md py-2"> <div className="mb-2 block"> <Label htmlFor="type">Type:</Label> </div> <Select id="type" defaultValue={selectedWorkout.type} onChange={(e) => setType(e.target.value)} > <option value="">Choose a type</option> <option value="Running">Running</option> <option value="Strength">Strength</option> <option value="Cardio">General Cardio</option> </Select> <div className="max-w-sm py-2"> <label htmlFor="name" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Name: </label> <input type="text" required id="distance" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" value={name} onChange={(e) => setName(e.target.value)} /> </div> </div> {type === "Running" && ( <> <div className="max-w-sm py-2"> <label htmlFor="distance" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Distance (km): </label> <input type="number" id="distance" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" value={distance} onChange={(e) => setDistance(e.target.value)} /> </div> <div className="max-w-sm py-2"> <label htmlFor="duration" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Duration (minutes): </label> <input type="number" id="duration" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" value={duration} onChange={(e) => setDuration(e.target.value)} /> </div> <div className="max-w-sm py-2"> <label htmlFor="zone" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Choose Zone </label> <Select id="zone" value={zone} onChange={(e) => setZone(e.target.value)} > <option value="">Choose a zone</option> <option value="1">Zone 1</option> <option value="2">Zone 2</option> <option value="3">Zone 3</option> <option value="4">Zone 4</option> <option value="5">Zone 5</option> </Select> </div> </> )} <div className="max-w-sm py-2"> <label htmlFor="description" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Description: </label> <textarea id="description" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" value={description} onChange={(e) => setDescription(e.target.value)} /> </div> <div className="max-w-sm py-2"> <label htmlFor="date" className="block mb-2 text-sm font-medium-text-gray-900 dark:text-white" > Date: </label> <input type="date" id="date" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" value={date} onChange={(e) => setDate(e.target.value)} /> </div> <div className="max-w-sm py-2"> <label htmlFor="time" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > Time: </label> <input type="time" id="time" value={time} className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" onChange={(e) => setTime(e.target.value)} // Antar at du har en setTime-funksjon i din useState hooks /> </div> <Button type="submit">Submit Change</Button> </form> <Button color="red" onClick={() => { if (selectedWorkout) { deleteWorkout( selectedWorkout.id, null, user, setOpenEditWorkoutModal, setWorkouts ); } }} > Delete Workout </Button> </div> </Modal.Body> </Modal> <Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", margin: "20px 0", }} > {exportingWeeklyWorkout ? ( <Button size="md" isProcessing processingSpinner={ <AiOutlineLoading className="h-6 w-6 animate-spin" /> } > Export Selected Week to Google Calendar </Button> ) : weeklyWorkoutExported ? ( <Button disabled>Exported</Button> ) : weeklyWorkoutNotExported ? ( <Alert severity="error" sx={{ mb: 2 }}> Failed to export workouts </Alert> ) : user.isGoogleAuthenticated ? ( <Button onClick={() => exportWeekToGoogleCalendar()}> Export Selected Week to Google Calendar </Button> ) : null} </Box> <WeeklyRunningVolume client={user} week={currentWeek} workouts={workouts} /> {user && !user.isGoogleAuthenticated && ( <Box sx={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", }} > <Button onClick={() => authorizeGoogleOAuth()}>Google Auth</Button> </Box> )} </div> ); }; export default UserWorkoutForm;
<!DOCTYPE html> <html> <head> <style> th, td { text-align: left; } </style> <script type="module"> async function init() { // This could just be the number 32, but, apparently, if we want a mutable global, WebAssembly.Global needs to be used. const globalDexter = new WebAssembly.Global({value:'i32', mutable:false}, 32); const globalSinister = new WebAssembly.Global({value:'i32', mutable:true}, 128); var importObject = { mod: { dexter: globalDexter, sinister: globalSinister, }, }; const { instance } = await WebAssembly.instantiateStreaming( fetch("./test.wasm"), importObject ); const dexter = document.getElementById("dexter"); const sinister = document.getElementById("sinister"); const sinister2 = document.getElementById("sinister2"); dexter.innerHTML = ""+instance.exports.getDexter(); sinister.innerHTML = ""+instance.exports.getSinister(); globalSinister.value = 65536; sinister2.innerHTML = ""+instance.exports.getSinister(); } init(); </script> </head> <body> <div> <h3>Global Import Test</h3> <p>dexter = <span id="dexter"></span> <em>(Should be 32)</em></p> <p>sinister = <span id="sinister"></span> <em>(Should be 128)</em></p> <p>sinister modified = <span id="sinister2"></span> <em>(Should be 65536)</em></p> </div> </body> </html>
/*Copyright (C) 2024 Crawford Currie http://c-dot.co.uk License Apache 2.0. See README.md at the root of this distribution for full copyright and license information.*/ import { Area } from "./Area.js"; import { MatrixReader } from "./MatrixReader.js"; /** * A board is: * - an NxN array of cells, each of which has a set of possible * symbols that can go in that cell. * - a list of Areas, each of which is a list of cells included in * the area. * - an NxN map from cell to the list of areas that cell is contained in. */ class Board { /** * Construct a new board, either from a set of symbols or by cloning * another board. * @param {string} symbols symbols used to fill * in the puzzle, defaults to "123456789". */ constructor(symbols = "123456789") { /** * Dimension of the (square) board * @member {number} */ this.dim = symbols.length; /** * Symbols that are used in the board (usually 1..9) * @member {string} */ this.symbols = symbols; /** * List of the areas on the board where the Sudoku constraint applies. * Areas may overlap (killer!) * @member {Area[]} */ this.areas = []; /** * A list of possible symbols for each cell, indexed on row,col * @member {string[][][]} * @private */ this.possibilities = new Array(this.dim); /** * Mapping from row,column to a list of area indexes that the * cell at row,column is part of. * @member {number?[][]} */ this.rc2a = new Array(this.dim); for (let row = 0; row < this.dim; row++) { this.possibilities[row] = new Array(this.dim); this.rc2a[row] = new Array(this.dim); for (let col = 0; col < this.dim; col++) { // No areas yet this.rc2a[row][col] = []; // Anything is possible this.possibilities[row][col] = symbols; } } /** * Enable verbose debugging print for debugging. Override by * setting to console.debug. * @member {boolean} */ this.report = () => {}; } /** * Deep clone another board. * @param {Board} board the board to clone. * @return {Board} a new board that is an exact copy of board */ static clone(board) { const newBoard = new Board(board.symbols); for (let row = 0; row < newBoard.dim; row++) { for (let col = 0; col < newBoard.dim; col++) { newBoard.rc2a[row][col] = board.rc2a[row][col]; newBoard.possibilities[row][col] = board.possibilities[row][col]; } newBoard.areas = []; for (const a of board.areas) { const ca = new Area(a.id); for (const c of a.cells) { ca.addCell(c.row, c.col); } newBoard.areas.push(ca); } } return newBoard; } /** * Make a transpose of this board * @return {Board} the transposed board */ transposed() { const board = new Board(this.symbols); for (let row = 0; row < board.dim; row++) { for (let col = 0; col < board.dim; col++) { board.rc2a[row][col] = this.rc2a[col][row]; board.possibilities[row][col] = this.possibilities[col][row]; } board.areas = []; for (const a of this.areas) { const ca = new Area(a.id); for (const c of a.cells) { ca.addCell(c.col, c.row); } board.areas.push(ca); } } return board; } /** * Determine if the given symbol is a possible solution for the * given cell. * @param {string} sym symbol to check * @param {number} row row of cell * @param {number} col column of cell * @return {boolean} true if the symbol is possible in the cell */ couldBe(sym, row, col) { const poss = this.possibilities[row][col]; return poss.indexOf(sym) >= 0; } /** * Eliminate the given symbol as a possible solution for the * given cell. If the cell is left with only one possibility, * fix() it. * @param {string} sym symbol to eliminate * @param {number} row row of cell * @param {number} col column of cell * @return {number} the total number of cells that were fixed as a * result of this call. */ cantBeInCell(sym, row, col) { const poss = this.possibilities[row][col]; if (poss.length === 1) { if (poss === sym && this.report) throw new Error(`Insoluble; ${bid(row, col)} was set to ${this.possibilities[row][col]}, but now being told it can't be that`); return 0; // already fixed } let fixes = 0; const s = poss.replace(sym, ""); if (s != poss) { this.report(`\t\tRemoved "${sym}" from ${bid(row, col)}`); if (s.length === 1) fixes += this.fix(s, row, col); else // Not a fix, just an elimination this.possibilities[row][col] = s; } return fixes; } /** * Eliminate the given symbol as a possible solution for all * the cells in a row, except cells in not. * @param {string} sym symbol to eliminate * @param {number} col column * @param {number[]} keep cells not to eliminate the symbol from * @return {number} the total number of cells that were fixed as a * result of this call. */ cantBeInRow(sym, row, keep) { let fixes = 0; for (let cn = 0; cn < this.dim; cn++) if (keep.indexOf(cn) < 0) fixes += this.cantBeInCell(sym, row, cn); return fixes; } /** * Eliminate the given symbol as a possible solution for all * the cells in a row, except cells in not. * @param {string} sym symbol to eliminate * @param {number} col column * @param {number[]} keep cells not to eliminate the symbol from * @return {number} the total number of cells that were fixed as a * result of this call. */ cantBeInColumn(sym, col, keep) { let fixes = 0; for (let rn = 0; rn < this.dim; rn++) if (keep.indexOf(rn) < 0) fixes += this.cantBeInCell(sym, rn, col); return fixes; } /** * Eliminate the given symbol as a possible solution for all * the cells in a row, except cells in not. * @param {string} sym symbol to eliminate * @param {number} area area number * @param {number[]} keep cells not to eliminate the symbol from * @return {number} the total number of cells that were fixed as a * result of this call. */ cantBeInArea(sym, area, keep) { let fixes = 0; const a = this.areas[area]; for (let cn = 0; cn < a.cells.length; cn++) if (keep.indexOf(cn) < 0) fixes += this.cantBeInCell(sym, a.cells[cn].row, a.cells[cn].col); return fixes; } /** * Determine if two cells interact with eachother. Cells interact if * they are on the same row, in the same column, or in the same area. * @param {number} ar row of 1st cell * @param {number} ac col of 1st cell * @param {number} br row of 2nd cell * @param {number} bc col of 2nd cell * @return true if the cells see eachother */ interact(ar, ac, br, bc) { // Same row/col if (ar === br || ac === bc) return true; // Same area for (const ai of this.rc2a[ar][ac]) { for (const bi of this.rc2a[br][bc]) { if (ai === bi) return true; } } return false; } /** * Fix a symbol at the given location. * This will rule out the symbol elsewhere in the same row, column, * and each area the (row,col) is in. If the fix result * in a single legal symbol for a cell, then fix it recursively. * @param {string} sym the symbol to put in this cell * @param {number} row row of cell * @param {number} col column of cell * @return {number} number of cells fixed as a result of this fix */ fix(sym, row, col) { if (!this.couldBe(sym, row, col)) throw new Error(`Fixing "${sym}" to ${bid(row, col)} not possible, as it is has "${this.possibilities[row][col]}"`); if (this.possibilities[row][col].length === 1) return 0; // no fix necessary //this.report(this.savePossibilities()); this.report(`Fix "${sym}" to ${bid(row, col)} {`); // Only one remaining possibility this.possibilities[row][col] = sym; let fixes = 1; // Eliminate from rest of this row this.report(`\tEliminate "${sym}" from row ${row} except ${bid(row, col)}`); fixes += this.cantBeInRow(sym, row, [ col ]); //this.report(this.savePossibilities()); // Eliminate from rest of this col this.report(`\tEliminate "${sym}" from column ${col} except ${bid(row, col)}`); fixes += this.cantBeInColumn(sym, col, [ row ]); //this.report(this.savePossibilities()); // Eliminate from rest of containing areas for (const ai of this.rc2a[row][col]) { this.report(`\tEliminate "${sym}" from area ${ai} except ${bid(row, col)}`); for (const c of this.areas[ai].cells) if (!(c.row === row && c.col == col)) fixes += this.cantBeInCell(sym, c.row, c.col); //this.report(this.savePossibilities()); } this.report(`} fixed "${sym}" to ${bid(row, col)}`); return fixes; } /** * Determine if the given row observes the Sudoku constraint * There must be a tile on each cell in the row. * @param {number} row the row to check * @return {boolean} true if constraints are satisfied */ rowIsSolved(row) { let s = ""; for (let col = 0; col < this.dim; col++) { const t = this.possibilities[row][col]; if (t.length !== 1) return false; for (const sym of t) { if (s.indexOf(sym) >= 0) return false; // duplicate s += sym; } } return true; } /** * Determine if the given column observes the Sudoku constraint. * There must be a tile on each cell in the column. * @param {number} row the column to check * @return {boolean} true if constraints are satisfied */ columnIsSolved(col) { let s = ""; for (let row = 0; row < this.dim; row++) { const t = this.possibilities[row][col]; if (t.length !== 1) return false; for (const sym of t) { if (s.indexOf(sym) >= 0) return false; // duplicate s += sym; } } return true; } /** * Check if the board meets sudoku criteria for a solution. * @return <boolean} true if the board is solved */ isSolved() { for (let i = 0; i < this.dim; i++) { if (!this.rowIsSolved(i)) { //this.report(`Row ${i} is not solved`); return false; } if (!this.columnIsSolved(i)) { //this.report(`Column ${i} is not solved`); return false; } } for (const area of this.areas) { if (!area.isSolved(this)) { //this.report(`Area ${area.id} is not solved`); return false; } } return true; } /** * Read formatted setup data from a string. * The string is comprised of an (optional) single line containing a * set of symbols that are used when filling in the board, and two * square "pictures" of the board, the first giving the areas within * which constraints apply. The second gives the initial state of * the puzzle. A line starting with a hash "#" is treated as a * comment. Example: * ``` * # Symbols (optional) * 123456789 * # Areas * |0|0|0|0|1|1|1|2|2| * |0|3|0|1|1|2|2|2|2| * |3|3|0|1|1|4|2|5|2| * |3|0|0|1|1|4|2|5|5| * |3|3|4|4|4|4|4|5|5| * |3|3|6|4|7|7|8|8|5| * |6|3|6|4|7|7|8|5|5| * |6|6|6|6|7|7|8|5|8| * |6|6|7|7|7|8|8|8|8| * * # Initial board * | | | |4| |2|6|7| | * | |9| |7|5| |1| | | * |6| | | | |4| | | | * |5| | | | | | |3| | * | | | | | | | | | | * | |8| | | | | | |1| * | | | |3| | | | |7| * | | |2| |1|3| |6| | * | |5|4|2| |6| | | | * ``` * This specifies a 9x9 sudoku. Each area within the board is assigned a * unique number, and the first block used to define those areas. * The second block gives the initial state of the puzzle, with spaces * where numbers are unknown. * @param {string} s the board, as described * @param {boolean?} set true to make the process noisy * @return {Board} board (or a subclass) as loaded */ static loadPuzzle(s, verbose) { const reader = new MatrixReader(s); const l = reader.nextLine(); // Read symbols (if there are any) to establish dim // (there must be dim symbols) let symbols; if (/^\|.*\|$/.test(l)) { // Line looks like a matrix row, re-read it as a row to get dim reader.undo(); const mr = reader.nextRow(); const dim = mr.length; // Symbols must be 123..dim symbols = ""; for (let i = 1; i <= dim; i++) symbols += `${i}`; reader.undo(); } else // Otherwise it's a set of symbols symbols = l; // Construct arrays const board = new this(symbols, verbose); symbols = board.symbols; const dim = board.dim; // Read and construct areas const amat = reader.nextMatrix(dim); for (let row = 0; row < dim; row++) { const r = amat[row]; for (let col = 0; col < dim; col++) { board.possibilities[row][col] = symbols; let areas = r[col].split(""); for (let area of areas) { if (/\d/.test(area)) { area = Number(area); if (!board.areas[area]) board.areas[area] = new Area(area); board.areas[area].addCell(row, col); board.rc2a[row][col].push(area); } } } } // Check for (let a = 0; a < board.areas.length; a++) if (board.areas[a].cells.length !== dim) throw new Error( `Area ${a} has the wrong number of cells ${board.areas[a].cells.length} != ${dim}`); // Read and fill initial values const imat = reader.nextMatrix(dim); for (let row = 0; row < dim; row++) { let r = imat[row]; for (let col = 0; col < dim; col++) { if (/\S/.test(r[col])) { if (board.symbols.indexOf(r[col]) < 0) throw new Error(`Unexpected symbol at line ${reader.line-1} '${r[col]}`); board.possibilities[row][col] = r[col]; } } } return board; } /** * Load a classic Sudoku problem from a string. * The string consists of NxN characters that represent the N symbols in * cells, using "0" or " " to represent an empty cell. */ static loadClassic(s) { const dim = Math.round(Math.sqrt(s.length)); if (dim * dim !== s.length) throw new Error(`Classic must be square ${Math.sqrt(s.length)}`); const adim = Math.round(Math.sqrt(dim)); if (Math.floor(adim) !== adim) throw new Error(`Classic must have integer root ${Math.sqrt(s.length)}`); const syms = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".substr(0, dim); const board = new Board(syms); // Make areas for (let i = 0; i < adim; i++) { for (let j = 0; j < adim; j++) { let area = new Area(board.areas.length); for (let r = 0; r < adim; r++) { for (let c = 0; c < adim; c++) { const row = i * adim + r; const col = j * adim + c; area.addCell(row, col); board.rc2a[row][col].push(board.areas.length); } } board.areas.push(area); } } // Load the symbols into the right cells let r = 0, c = 0; for (const sym of s) { if (sym != '0') { if (board.symbols.indexOf(sym) < 0) throw new Error(`Illegal sym "${sym}" for classic`); board.possibilities[r][c] = sym; } if (++c === dim) { c = 0; r++; } } return board; } /** * For a just-loaded board, fix each cell that only has one possibility * @return {number} number of fixes completed */ firstFix() { let fixes = 0; for (let row = 0; row < this.dim; row++) { const r = this.possibilities[row]; for (let col = 0; col < this.dim; col++) { const syms = r[col]; if (syms.length === 1) { // Make the cell fixable by clearing the possibilities this.possibilities[row][col] = this.symbols; // -1 to discount the fix of this cell fixes += this.fix(syms, row, col) - 1; } } } return fixes; } /** * Create a string image of the of the board * for debugging/testing * @return {string} the image, in a format suitable for reading * by loadPuzzle */ saveBoard() { let rows = []; for (let row = 0; row < this.dim; row++) { let r = []; for (let col = 0; col < this.dim; col++) { r.push(this.possibilities[row][col].length === 1 ? this.possibilities[row][col] : " "); } rows.push(`|${r.join("|")}|`); } return rows.join("\n"); } /** * Create a string image of the areas of the board * for debugging/testing * @return {string} the image, in a format suitable for reading * by loadPuzzle */ saveAreas() { let rows = []; for (let row = 0; row < this.dim; row++) { let r = []; for (let col = 0; col < this.dim; col++) { r.push(this.rc2a[row][col].join("")); } rows.push(`|${r.join("|")}|`); } return rows.join("\n"); } /** * Load a possibilities matrix. The matrix must be * the correct dimension, there are no checks. */ loadPossibilities(s) { const reader = new MatrixReader(s); const mat = reader.nextMatrix(this.dim); for (let row = 0; row < this.dim; row++) { for (let col = 0; col < this.dim; col++) { let syms = mat[row][col].split("").filter(e => e !== " ").join(""); if (syms === "") syms = this.symbols; this.possibilities[row][col] = syms; } } } // Debug only checkPossibilities(s, fail) { const reader = new MatrixReader(s); const mat = reader.nextMatrix(this.dim); for (let row = 0; row < this.dim; row++) { for (let col = 0; col < this.dim; col++) { const syms = mat[row][col].split("").filter(e => e !== " ").join(""); for (const sym of syms) { if (!this.couldBe(sym, row, col)) fail(`Possibilities check at ${bid(row, col)} expected:${syms} actual:${this.possibilities[row][col]}`); } for (const sym of this.possibilities[row][col]) if (syms.indexOf(sym) < 0) fail(`Possibilities check at ${bid(row, col)} expected:${syms} actual:${this.possibilities[row][col]}`); } } } /** * Create a string image of the possibilities of the board * for debugging/testing * @param {number?} row if a number, dump a single row, otherwise * dump the whole board. * @return {string} the image, in a format suitable for reading * by loadPuzzle */ savePossibilities(row) { const possRow = row => { const r = []; for (let col = 0; col < this.dim; col++) { const p = this.possibilities[row][col]; const posses = []; for (const i of this.symbols) { if (p.length === 0) posses.push("X"); else if (p.indexOf(i) >= 0) posses.push(i); else posses.push(" "); } r.push(posses.join("")); } return `|${r.join("|")}|`; }; if (typeof row === "number") return possRow(row); const rows = []; for (let row = 0; row < this.dim; row++) rows.push(possRow(row)); return rows.join("\n"); } /** * Create a string image of the board in the form read by loadPuzzle * @return {string} the image, in a format suitable for reading !* by loadPuzzle */ savePuzzle() { return `# Symbols ${this.symbols} # Areas ${this.saveAreas()} # Board ${this.saveBoard()}`; } } /** * Show a row using letters * @return {string} "R" where R is a letter ("A" is the top row) */ function rid(row) { return `${String.fromCharCode('A'.charCodeAt(0) + row)}`; } /** * Show a row using letters * @return {string} "R" where R is a letter ("A" is the top row) */ function cid(col) { return `${col + 1}`; } /** * Show a board position using letters for rows and numbers for * columns. * @return {string} "RC" where R is a letter ("A" is the top row * and C is the column number (leftmost column is 1) */ function bid(row, col) { return `${rid(row)}${cid(col)}`; } export { Board, bid, cid, rid };
/* eslint-disable no-unused-vars */ import React, { createContext, useCallback, useContext, useState } from 'react'; interface IProductCategory { id: string; name: string; } export interface IProductPhoto { id: string; photo_url: string; } export interface IProduct { id: string; name: string; package: string; description: string; sale_price: number; categories: IProductCategory[]; photos: IProductPhoto[]; } interface IProductContext { products: IProduct[]; favoriteProducts: IProduct[]; updateProducts(productsRequest: IProduct[]): void; updateFavoriteProducts(productsRequest: IProduct[]): void; } const ProductContext = createContext<IProductContext>({} as IProductContext); const ProductProvider: React.FC = ({ children }) => { const [products, setProducts] = useState<IProduct[]>([] as IProduct[]); const [favoriteProducts, setFavoriteProducts] = useState<IProduct[]>( [] as IProduct[], ); const updateProducts = useCallback((productsRequest: IProduct[]) => { setProducts(productsRequest); }, []); const updateFavoriteProducts = useCallback((productsRequest: IProduct[]) => { setFavoriteProducts(productsRequest); }, []); return ( <ProductContext.Provider value={{ products, favoriteProducts, updateProducts, updateFavoriteProducts, }} > {children} </ProductContext.Provider> ); }; function useProduct(): IProductContext { const context = useContext(ProductContext); if (!context) { throw new Error('useCart must be used within an CartProvider'); } return context; } export { ProductProvider, useProduct };
<template> <div class="list"> <div class="list-head"></div> <div class="list-body"> <el-table :data="list" height="250" border style="width: 100%"> <el-table-column prop="name" label="接口名"> </el-table-column> <el-table-column prop="updateTime" label="更新时间" width="200"> </el-table-column> <el-table-column label="mock" width="100"> <template slot-scope="scope"> <el-switch v-model="scope.row.mock" @input="updateMock($event, scope.row)" active-color="#13ce66" inactive-color="#ff4949" > </el-switch> </template> </el-table-column> <el-table-column label="操作" width="200"> <template slot-scope="scope"> <el-button @click="edit(scope.row)"> 编辑 </el-button> </template> </el-table-column> </el-table> </div> <div class="list-footer"></div> <el-dialog title="提示" :visible.sync="dialogVisible" width="1000px" :before-close="handleClose" > <code-editor class="editor" ref="edit" v-model="view" :show-btns="false" :expanded-on-start="true" mode="code" lang="zh" /> <span slot="footer" class="dialog-footer"> <el-button @click="dialogVisible = false">取 消</el-button> <el-button type="primary" @click="updateApiData">确 定</el-button> </span> </el-dialog> </div> </template> <script> import { Table, Switch, Button, TableColumn, Dialog, Message, } from "element-ui"; import { getApiList, updateApiData, updateApiMock } from "../service"; import CodeEditor from "./code-editor"; export default { name: "api-list", components: { "el-table": Table, "el-switch": Switch, "el-button": Button, "el-table-column": TableColumn, "code-editor": CodeEditor, "el-dialog": Dialog, }, mounted() { this.refreshList(); }, data() { return { list: [], dialogVisible: false, view: {}, }; }, methods: { edit(row) { this.editRow = row; this.view = typeof row.data === "string" ? JSON.parse(row.data) : row.data; this.dialogVisible = true; }, handleClose() { this.dialogVisible = false; }, refreshList() { getApiList().then((data) => { this.list = (data || []).map((item) => { try { const data = JSON.parse(item.data); return { ...item, updateTime: data.time, data: data.data, }; } catch (error) { return item; } }); }); }, updateApiData() { this.editRow.data = this.view; updateApiData(this.editRow.name, this.view) .then((data) => { if (data.code !== 200) { Message.error("更新失败"); } else { Message.success("更新成功"); this.dialogVisible = false; } }) .catch(() => { Message.error("更新失败"); }); }, updateMock(mock, row) { updateApiMock(row.name, mock) .then((data) => { if (data.code !== 200) { Message.error("更新失败"); } else { Message.success("更新成功"); } }) .catch(() => { Message.error("更新失败"); }); }, }, }; </script> <style scoped> .editor { height: 400px; } </style>
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> <chapter id="user-manual-metadata"> <title>Metadata</title> <section> <title>Overview</title> <para> The BitBake task executor together with various types of configuration files form the OpenEmbedded Core. This section provides an overview of the BitBake task executor and the configuration files by describing what they are used for and how they interact. </para> <para> BitBake handles the parsing and execution of the data files. The data itself is of various types: <itemizedlist> <listitem><para><emphasis>Recipes:</emphasis> Provides details about particular pieces of software.</para></listitem> <listitem><para><emphasis>Class Data:</emphasis> An abstraction of common build information (e.g. how to build a Linux kernel).</para></listitem> <listitem><para><emphasis>Configuration Data:</emphasis> Defines machine-specific settings, policy decisions, etc. Configuration data acts as the glue to bind everything together.</para></listitem> </itemizedlist> What follows are a large number of examples of BitBake metadata. Any syntax which isn't supported in any of the aforementioned areas will be documented as such. </para> </section> <section id='basic-syntax'> <title>Basic Syntax</title> <section id='basic-variable-setting'> <title>Basic Variable Setting</title> <para> <literallayout class='monospaced'> VARIABLE = "value" </literallayout> In this example, <filename>VARIABLE</filename> is <filename>value</filename>. </para> </section> <section id='variable-expansion'> <title>Variable Expansion</title> <para> BitBake supports variables referencing one another's contents using a syntax which is similar to shell scripting </para> <para> <literallayout class='monospaced'> A = "aval" B = "pre${A}post" </literallayout> This results in <filename>A</filename> containing <filename>aval</filename> and <filename>B</filename> containing <filename>preavalpost</filename>. </para> </section> <section id='setting-a-default-value'> <title>Setting a default value (?=)</title> <para> <literallayout class='monospaced'> A ?= "aval" </literallayout> If <filename>A</filename> is set before the above is called, it will retain its previous value. If <filename>A</filename> is unset prior to the above call, <filename>A</filename> will be set to <filename>aval</filename>. <note> This assignment is immediate, so if there are multiple "?=" assignments to a single variable, the first of those will be used. </note> </para> </section> <section id='setting-a-weak-default-value'> <title>Setting a weak default value (??=)</title> <para> <literallayout class='monospaced'> A ??= "somevalue" A ??= "someothervalue" </literallayout> If <filename>A</filename> is set before the above, it will retain that value. If <filename>A</filename> is unset prior to the above, <filename>A</filename> will be set to <filename>someothervalue</filename>. This is a lazy or weak assignment in that the assignment does not occur until the end of the parsing process, so that the last, rather than the first, "??=" assignment to a given variable will be used. Any other setting of <filename>A</filename> using "=" or "?=" will, however, override the value set with "??=". </para> </section> <section id='immediate-variable-expansion'> <title>Immediate variable expansion (:=)</title> <para> The ":=" operator results in a variable's contents being expanded immediately, rather than when the variable is actually used: <literallayout class='monospaced'> T = "123" A := "${B} ${A} test ${T}" T = "456" B = "${T} bval" C = "cval" C := "${C}append" </literallayout> In this example, <filename>A</filename> would contain <filename>test 123</filename>, <filename>B</filename> would contain <filename>456 bval</filename>, and <filename>C</filename> would be <filename>cvalappend</filename>. </para> </section> <section id='appending-and-prepending'> <title>Appending (+=) and prepending (=+)</title> <para> <literallayout class='monospaced'> B = "bval" B += "additionaldata" C = "cval" C =+ "test" </literallayout> In this example, <filename>B</filename> is now <filename>bval additionaldata</filename> and <filename>C</filename> is <filename>test cval</filename>. </para> </section> <section id='appending-and-prepending-without-spaces'> <title>Appending (.=) and Prepending (=.) Without Spaces</title> <para> <literallayout class='monospaced'> B = "bval" B .= "additionaldata" C = "cval" C =. "test" </literallayout> In this example, <filename>B</filename> is now <filename>bvaladditionaldata</filename> and <filename>C</filename> is <filename>testcval</filename>. In contrast to the above appending and prepending operators, no additional space will be introduced. </para> </section> <section id='appending-and-prepending-override-style-syntax'> <title>Appending and Prepending (Override Style Syntax)</title> <para> <literallayout class='monospaced'> B = "bval" B_append = " additional data" C = "cval" C_prepend = "additional data " </literallayout> This example results in <filename>B</filename> becoming <filename>bval additional data</filename> and <filename>C</filename> becoming <filename>additional data cval</filename>. <note> The spaces in <filename>_append</filename>. Unlike the "+=" operator, additional space is not automatically added. You must take steps to add space yourself. </note> </para> </section> <section id='removing-override-style-syntax'> <title>Removing (Override Style Syntax)</title> <para> <literallayout class='monospaced'> FOO = "123 456 789 123456 123 456 123 456" FOO_remove = "123" FOO_remove = "456" </literallayout> In this example, <filename>FOO</filename> is now <filename>789 123456</filename>. </para> </section> <section id='variable-flags'> <title>Variable Flags</title> <para> Variables can have associated flags which provide a way of tagging extra information onto a variable. Several flags are used internally by BitBake but they can be used externally too if needed. The standard operations mentioned above also work on flags. <literallayout class='monospaced'> VARIABLE[SOMEFLAG] = "value" </literallayout> In this example, <filename>VARIABLE</filename> has a flag, <filename>SOMEFLAG</filename> that is set to <filename>value</filename>. </para> </section> <section id='inline-python-variable-expansion'> <title>Inline Python Variable Expansion</title> <para> <literallayout class='monospaced'> DATE = "${@time.strftime('%Y%m%d',time.gmtime())}" </literallayout> This would result in the <filename>DATE</filename> variable containing today's date. </para> </section> </section> <section id='conditional-syntax-overrides'> <title>Conditional Syntax (Overrides)</title> <section id='conditional-metadata'> <title>Conditional Metadata</title> <para> <filename>OVERRIDES</filename> is a “:” separated variable containing each item for which you want to satisfy conditions. So, if you have a variable that is conditional on “arm”, and “arm” is in <filename>OVERRIDES</filename>, then the “arm” specific version of the variable is used rather than the non-conditional version. Here is an example: <literallayout class='monospaced'> OVERRIDES = "architecture:os:machine" TEST = "defaultvalue" TEST_os = "osspecificvalue" TEST_condnotinoverrides = "othercondvalue" </literallayout> In this example, <filename>TEST</filename> would be <filename>osspecificvalue</filename>, due to the condition “os” being in <filename>OVERRIDES</filename>. </para> </section> <section id='conditional-appending'> <title>Conditional Appending</title> <para> BitBake also supports appending and prepending to variables based on whether something is in <filename>OVERRIDES</filename>. Here is an example: <literallayout class='monospaced'> DEPENDS = "glibc ncurses" OVERRIDES = "machine:local" DEPENDS_append_machine = "libmad" </literallayout> In this example, <filename>DEPENDS</filename> is set to "glibc ncurses libmad". </para> </section> <section id='variable-interaction-worked-examples'> <title>Variable Interaction: Worked Examples</title> <para> Despite the documentation of the different forms of variable definition above, it can be hard to work out what happens when variable operators are combined. </para> <para> Following are some common scenarios where variables interact that can confuse users. </para> <para> There is often confusion about which order overrides and the various "append" operators take effect: <literallayout class='monospaced'> OVERRIDES = "foo" A_foo_append = "X" </literallayout> In this case, <filename>X</filename> is unconditionally appended to the variable <filename>A_foo</filename>. Since foo is an override, <filename>A_foo</filename> would then replace <filename>A</filename>. <literallayout class='monospaced'> OVERRIDES = "foo" A = "X" A_append_foo = "Y" </literallayout> In this case, only when <filename>foo</filename> is in <filename>OVERRIDES</filename>, <filename>Y</filename> is appended to the variable <filename>A</filename> so the value of <filename>A</filename> would become <filename>XY</filename> (NB: no spaces are appended). <literallayout class='monospaced'> OVERRIDES = "foo" A_foo_append = "X" A_foo_append += "Y" </literallayout> This behaves as per the first case above, but the value of <filename>A</filename> would be "X Y" instead of just "X". <literallayout class='monospaced'> A = "1" A_append = "2" A_append = "3" A += "4" A .= "5" </literallayout> Would ultimately result in <filename>A</filename> taking the value "1 4523" since the "_append" operator executes at the same time as the expansion of other overrides. </para> </section> <section id='key-expansion'> <title>Key Expansion</title> <para> Key expansion happens at the data store finalization time just before overrides are expanded. <literallayout class='monospaced'> A${B} = "X" B = "2" A2 = "Y" </literallayout> So in this case <filename>A2</filename> would take the value of "X". </para> </section> </section> <section id='inheritance'> <title>Inheritance</title> <section id='inheritance-directive'> <title>Inheritance Directive</title> <note> This is only supported in <filename>.bb</filename> and <filename>.bbclass</filename> files. </note> <para> The inherit directive is a means of specifying what classes of functionality your <filename>.bb</filename> requires. It is a rudimentary form of inheritance. For example, you can easily abstract out the tasks involved in building a package that uses autoconf and automake, and put that into a bbclass for your packages to make use of. A given bbclass is located by searching for classes/filename.bbclass in <filename>BBPATH</filename>, where filename is what you inherited. </para> </section> <section id='inclusion-directive'> <title>Inclusion Directive</title> <para> This directive causes BitBake to parse whatever file you specify, and insert it at that location, which is not unlike Make. However, if the path specified on the include line is a relative path, BitBake will locate the first one it can find within <filename>BBPATH</filename>. </para> </section> <section id='requiring-inclusion'> <title>Requiring Inclusion</title> <para> In contrast to the include directive, require will raise a ParseError if the file to be included cannot be found. Otherwise it will behave just like the include directive. </para> </section> <section id='inherit-configuration-directive'> <title><filename>INHERIT</filename> Configuration Directive</title> <para> This configuration directive causes the named class to be inherited at this point during parsing. This variable is only valid in configuration files. </para> </section> </section> <section id='defining-python-functions-into-the-global-python-namespace'> <title>Defining Python Functions into the Global Python Namespace</title> <note> <para> This is only supported in <filename>.bb</filename> and <filename>.bbclass</filename> files. </para> <para> Python functions are in the global namespace so should use unique names. <literallayout class='monospaced'> def get_depends(d): if d.getVar('SOMECONDITION', True): return "dependencywithcond" else: return "dependency" SOMECONDITION = "1" DEPENDS = "${@get_depends(d)}" </literallayout> This would result in <filename>DEPENDS</filename> containing <filename>dependencywithcond</filename>. </para> </note> </section> <section id='functions'> <title>Functions</title> <note> This is only supported in <filename>.bb</filename> and <filename>.bbclass</filename> files. </note> <para> As with most languages, functions are the building blocks that define operations. Bitbake supports shell and Python functions. An example shell function definition is: <literallayout class='monospaced'> some_function () { echo "Hello World" } </literallayout> An example Python function definition is: <literallayout class='monospaced'> python some_python_function () { d.setVar("TEXT", "Hello World") print d.getVar("TEXT", True) } </literallayout> In python functions, the "bb" and "os" modules are already imported, there is no need to import those modules. The datastore, "d" is also a global variable and always available to these functions automatically. </para> <para> Bitbake will execute functions of this form using the <filename>bb.build.exec_func()</filename>, which can also be called from Python functions to execute other functions, either shell or Python based. Shell functions can only execute other shell functions. </para> <para> There is also a second way to declare python functions with parameters which takes the form: <literallayout class='monospaced'> def some_python_function(arg1, arg2): print arg1 + " " + arg2 </literallayout> The difference is that the second form takes parameters, the datastore is not available automatically and must be passed as a parameter and these functions are not called with the <filename>exec_func()</filename> but are executed with direct Python function calls. The "bb" and "os" modules are still automatically available and there is no need to import them. </para> </section> <section id='tasks'> <title>Tasks</title> <note> This is only supported in <filename>.bb</filename> and <filename>.bbclass</filename> files. </note> <para> A shell or Python function executable through the <filename>exec_func</filename> can be promoted to become a task. Tasks are the execution unit Bitbake uses and each step that needs to be run for a given <filename>.bb</filename> is known as a task. There is an <filename>addtask</filename> command to add new tasks and promote functions which by convention must start with “do_”. The <filename>addtask</filename> command is also used to describe intertask dependencies. <literallayout class='monospaced'> python do_printdate () { import time print time.strftime('%Y%m%d', time.gmtime()) } addtask printdate after do_fetch before do_build </literallayout> The above example defined a Python function, then adds it as a task which is now a dependency of <filename>do_build</filename>, the default task and states it has to happen after <filename>do_fetch</filename>. If anyone executes the <filename>do_build</filename> task, that will result in <filename>do_printdate</filename> being run first. </para> </section> <section id='running-a-task'> <title>Running a Task</title> <para> Tasks can either be a shell task or a Python task. For shell tasks, BitBake writes a shell script to <filename>${WORKDIR}/temp/run.do_taskname.pid</filename> and then executes the script. The generated shell script contains all the exported variables, and the shell functions with all variables expanded. Output from the shell script goes to the file <filename>${WORKDIR}/temp/log.do_taskname.pid</filename>. Looking at the expanded shell functions in the run file and the output in the log files is a useful debugging technique. </para> <para> For Python tasks, BitBake executes the task internally and logs information to the controlling terminal. Future versions of BitBake will write the functions to files similar to the way shell tasks are handled. Logging will be handled in a way similar to shell tasks as well. </para> <para> Once all the tasks have been completed BitBake exits. </para> <para> When running a task, BitBake tightly controls the execution environment of the build tasks to make sure unwanted contamination from the build machine cannot influence the build. Consequently, if you do want something to get passed into the build task's environment, you must take a few steps: <orderedlist> <listitem><para> Tell BitBake to load what you want from the environment into the data store. You can do so through the <filename>BB_ENV_EXTRAWHITE</filename> variable. For example, assume you want to prevent the build system from accessing your <filename>$HOME/.ccache</filename> directory. The following command tells BitBake to load <filename>CCACHE_DIR</filename> from the environment into the data store: <literallayout class='monospaced'> export BB_ENV_EXTRAWHITE="$BB_ENV_EXTRAWHITE CCACHE_DIR" </literallayout></para></listitem> <listitem><para> Tell BitBake to export what you have loaded into the environment store to the task environment of every running task. Loading something from the environment into the data store (previous step) only makes it available in the datastore. To export it to the task environment of every running task, use a command similar to the following in your <filename>local.conf</filename> or distribution configuration file: <literallayout class='monospaced'> export CCACHE_DIR </literallayout> <note> A side effect of the previous steps is that BitBake records the variable as a dependency of the build process in things like the shared state checksums. If doing so results in unnecessary rebuilds of tasks, you can whitelist the variable so that the shared state code ignores the dependency when it creates checksums. </note></para></listitem> </orderedlist> </para> </section> <section id='task-flags'> <title>Task Flags</title> <para> Tasks support a number of flags which control various functionality of the task. These are as follows: <itemizedlist> <listitem><para><emphasis>dirs:</emphasis> Directories which should be created before the task runs. </para></listitem> <listitem><para><emphasis>cleandirs:</emphasis> Directories which should created before the task runs but should be empty.</para></listitem> <listitem><para><emphasis>noexec:</emphasis> Marks the tasks as being empty and no execution required. These are used as dependency placeholders or used when added tasks need to be subsequently disabled.</para></listitem> <listitem><para><emphasis>nostamp:</emphasis> Do not generate a stamp file for a task. This means the task is always executed.</para></listitem> <listitem><para><emphasis>fakeroot:</emphasis> This task needs to be run in a fakeroot environment, obtained by adding the variables in <filename>FAKEROOTENV</filename> to the environment.</para></listitem> <listitem><para><emphasis>umask:</emphasis> The umask to run the task under.</para></listitem> </itemizedlist> For the 'deptask', 'rdeptask', 'depends', 'rdepends'and 'recrdeptask' flags, please see the dependencies section. </para> </section> <section id='parsing-and-execution'> <title>Parsing and Execution</title> <section id='parsing-overview'> <title>Parsing Overview</title> <para> BitBake parses configuration files, classes, and <filename>.bb</filename> files. </para> <para> The first thing BitBake does is look for the <filename>bitbake.conf</filename> file. This file resides in the within the <filename>conf/</filename> directory. BitBake finds it by examining its <filename>BBPATH</filename> environment variable and looking for the <filename>conf/</filename> directory. </para> <para> The <filename>bitbake.conf</filename> file lists other configuration files to include from a <filename>conf/</filename> directory below the directories listed in <filename>BBPATH</filename>. In general, the most important configuration file from a user's perspective is <filename>local.conf</filename>, which contains a user's customized settings for the build environment. Other notable configuration files are the distribution configuration file (set by the <filename>DISTRO</filename> variable) and the machine configuration file (set by the <filename>MACHINE</filename> variable). The <filename>DISTRO</filename> and <filename>MACHINE</filename> BitBake environment variables are both usually set in the <filename>local.conf file</filename>. Valid distribution configuration files are available in the <filename>conf/distro/</filename> directory and valid machine configuration files in the <filename>meta/conf/machine/</filename> directory. Within the <filename>conf/machine/include/</filename> directory are various <filename>tune-*.inc</filename> configuration files that provide common "tuning" settings specific to and shared between particular architectures and machines. </para> <para> After parsing of the configuration files, some standard classes are included. The <filename>base.bbclass</filename> file is always included. Other classes that are specified in the configuration using the <filename>INHERIT</filename> variable are also included. Class files are searched for in a classes subdirectory under the paths in <filename>BBPATH</filename> in the same way as configuration files. </para> <para> After classes are included, the variable <filename>BBFILES</filename> is set, usually in <filename>local.conf</filename>, and defines the list of places to search for <filename>.bb</filename> files. Adding extra content to <filename>BBFILES</filename> is best achieved through the use of BitBake layers as described in the Layers section below. </para> <para> BitBake parses each <filename>.bb</filename> file in <filename>BBFILES</filename> and stores the values of various variables. In summary, for each <filename>.bb</filename> file the configuration plus the base class of variables are set, followed by the data in the <filename>.bb</filename> file itself, followed by any inherit commands that <filename>.bb</filename> file might contain. </para> <para> Because parsing <filename>.bb</filename> files is a time consuming process, a cache is kept to speed up subsequent parsing. This cache is invalid if the timestamp of the <filename>.bb</filename> file itself changes, or if the timestamps of any of the include, configuration files or class files on which the <filename>.bb</filename> file depends change. </para> </section> <section id='configiguration-files'> <title>Configuration files</title> <para> The first kind of metadata in BitBake is configuration metadata. This metadata is global, and therefore affects all packages and tasks that are executed. </para> <para> BitBake will first search the current working directory for an optional <filename>conf/bblayers.conf</filename> configuration file. This file is expected to contain a <filename>BBLAYERS</filename> variable that is a space delimited list of 'layer' directories. For each directory in this list, a <filename>conf/layer.conf</filename> file will be searched for and parsed with the <filename>LAYERDIR</filename> variable being set to the directory where the layer was found. The idea is these files will setup <filename>BBPATH</filename> and other variables correctly for a given build directory automatically for the user. </para> <para> BitBake will then expect to find <filename>conf/bitbake.conf</filename> file somewhere in the user specified <filename>BBPATH</filename>. That configuration file generally has include directives to pull in any other metadata (generally files specific to architecture, machine, local and so on). </para> <para> Only variable definitions and include directives are allowed in <filename>.conf</filename> files. </para> <section id='layers'> <title>Layers</title> <para> Layers allow you to isolate different types of customizations from each other. You might find it tempting to keep everything in one layer when working on a single project. However, the more modular you organize your Metadata, the easier it is to cope with future changes. </para> <para> To illustrate how layers are used to keep things modular, consider machine customizations. These types of customizations typically reside in a special layer, rather than a general layer, called a Board Specific Package (BSP) Layer. Furthermore, the machine customizations should be isolated from recipes and Metadata that support a new GUI environment, for example. This situation gives you a couple of layers: one for the machine configurations, and one for the GUI environment. It is important to understand, however, that the BSP layer can still make machine-specific additions to recipes within the GUI environment layer without polluting the GUI layer itself with those machine-specific changes. You can accomplish this through a recipe that is a BitBake append (<filename>.bbappend</filename>) file, which is described later in this section. </para> <para> There are certain variable specific to layers, including: <itemizedlist> <listitem><para><filename>LAYERDEPENDS</filename></para></listitem> <listitem><para><filename>LAYERVERSION</filename></para></listitem> </itemizedlist> </para> </section> </section> <section id='metadata-classes'> <title>Classes</title> <para> BitBake classes are our rudimentary inheritance mechanism. As briefly mentioned in the metadata introduction, they're parsed when an inherit directive is encountered, and they are located in the <filename>classes/</filename> directory relative to the directories in <filename>BBPATH</filename>. </para> </section> <section id='bb-files'> <title><filename>.bb</filename> Files</title> <para> A BitBake (<filename>.bb</filename>) file is a logical unit of tasks to be executed. Normally this is a package to be built. Inter-<filename>.bb</filename> dependencies are obeyed. The files themselves are located via the <filename>BBFILES</filename> variable, which is set to a space separated list of <filename>.bb</filename> files, and does handle wildcards. </para> </section> </section> <section id='events'> <title>Events</title> <note> This is only supported in <filename>.bb</filename> and <filename>.bbclass</filename> files. </note> <para> BitBake allows installation of event handlers. Events are triggered at certain points during operation, such as the beginning of operation against a given <filename>.bb</filename>, the start of a given task, task failure, task success, and so forth. The intent is to make it easy to do things like email notification on build failure. <literallayout class='monospaced'> addhandler myclass_eventhandler python myclass_eventhandler() { from bb.event import getName from bb import data print("The name of the Event is %s" % getName(e)) print("The file we run for is %s" % data.getVar('FILE', e.data, True)) } </literallayout> This event handler gets called every time an event is triggered. A global variable "<filename>e</filename>" is defined. "<filename>e.data</filename>" contains an instance of "<filename>bb.data</filename>". With the <filename>getName(e)</filename> method one can get the name of the triggered event. </para> <para> The above event handler prints the name of the event and the content of the <filename>FILE</filename> variable. During a Build, the following common events occur: <itemizedlist> <listitem><para><filename>bb.event.ConfigParsed()</filename></para></listitem> <listitem><para><filename>bb.event.ParseStarted()</filename></para></listitem> <listitem><para><filename>bb.event.ParseProgress()</filename></para></listitem> <listitem><para><filename>bb.event.ParseCompleted()</filename></para></listitem> <listitem><para><filename>bb.event.BuildStarted()</filename></para></listitem> <listitem><para><filename>bb.build.TaskStarted()</filename></para></listitem> <listitem><para><filename>bb.build.TaskInvalid()</filename></para></listitem> <listitem><para><filename>bb.build.TaskFailedSilent()</filename></para></listitem> <listitem><para><filename>bb.build.TaskFailed()</filename></para></listitem> <listitem><para><filename>bb.build.TaskSucceeded()</filename></para></listitem> <listitem><para><filename>bb.event.BuildCompleted()</filename></para></listitem> <listitem><para><filename>bb.cooker.CookerExit()</filename></para></listitem> </itemizedlist> Other events that occur based on specific requests to the server: <itemizedlist> <listitem><para><filename>bb.event.TreeDataPreparationStarted()</filename></para></listitem> <listitem><para><filename>bb.event.TreeDataPreparationProgress</filename></para></listitem> <listitem><para><filename>bb.event.TreeDataPreparationCompleted</filename></para></listitem> <listitem><para><filename>bb.event.DepTreeGenerated</filename></para></listitem> <listitem><para><filename>bb.event.CoreBaseFilesFound</filename></para></listitem> <listitem><para><filename>bb.event.ConfigFilePathFound</filename></para></listitem> <listitem><para><filename>bb.event.FilesMatchingFound</filename></para></listitem> <listitem><para><filename>bb.event.ConfigFilesFound</filename></para></listitem> <listitem><para><filename>bb.event.TargetsTreeGenerated</filename></para></listitem> </itemizedlist> </para> </section> <section id='variants-class-extension-mechanism'> <title>Variants - Class Extension Mechanism</title> <para> Two BitBake features exist to facilitate the creation of multiple buildable incarnations from a single recipe file. </para> <para> The first is <filename>BBCLASSEXTEND</filename>. This variable is a space separated list of classes used to "extend" the recipe for each variant. Here is an example that results in a second incarnation of the current recipe being available. This second incarnation will have the "native" class inherited. <literallayout class='monospaced'> BBCLASSEXTEND = "native" </literallayout> The second feature is <filename>BBVERSIONS</filename>. This variable allows a single recipe to build multiple versions of a project from a single recipe file, and allows you to specify conditional metadata (using the <filename>OVERRIDES</filename> mechanism) for a single version, or an optionally named range of versions: <literallayout class='monospaced'> BBVERSIONS = "1.0 2.0 git" SRC_URI_git = "git://someurl/somepath.git" </literallayout> <literallayout class='monospaced'> BBVERSIONS = "1.0.[0-6]:1.0.0+ \ 1.0.[7-9]:1.0.7+" SRC_URI_append_1.0.7+ = "file://some_patch_which_the_new_versions_need.patch;patch=1" </literallayout> The name of the range will default to the original version of the recipe, so given OE, a recipe file of <filename>foo_1.0.0+.bb</filename> will default the name of its versions to <filename>1.0.0+</filename>. This is useful, as the range name is not only placed into overrides; it's also made available for the metadata to use in the form of the <filename>BPV</filename> variable, for use in <filename>file://</filename> search paths (<filename>FILESPATH</filename>). </para> </section> <section id='dependencies'> <title>Dependencies</title> <section id='dependencies-overview'> <title>Overview</title> <para> BitBake handles dependencies at the task level since to allow for efficient operation with multiple processes executing in parallel, a robust method of specifying task dependencies is needed. </para> </section> <section id='dependencies-internal-to-the-bb-file'> <title>Dependencies Internal to the <filename>.bb</filename> File</title> <para> Where the dependencies are internal to a given <filename>.bb</filename> file, the dependencies are handled by the previously detailed <filename>addtask</filename> directive. </para> </section> <section id='build-dependencies'> <title>Build Dependencies</title> <para> <filename>DEPENDS</filename> lists build time dependencies. The 'deptask' flag for tasks is used to signify the task of each item listed in <filename>DEPENDS</filename> which must have completed before that task can be executed. <literallayout class='monospaced'> do_configure[deptask] = "do_populate_staging" </literallayout> In the previous example, the <filename>do_populate_staging</filename> task of each item in <filename>DEPENDS</filename> must have completed before <filename>do_configure</filename> can execute. </para> </section> <section id='runtime-dependencies'> <title>Runtime Dependencies</title> <para> The <filename>PACKAGES</filename> variable lists runtime packages and each of these can have <filename>RDEPENDS</filename> and <filename>RRECOMMENDS</filename> runtime dependencies. The 'rdeptask' flag for tasks is used to signify the task of each item runtime dependency which must have completed before that task can be executed. <literallayout class='monospaced'> do_package_write[rdeptask] = "do_package" </literallayout> In the previous example, the <filename>do_package</filename> task of each item in <filename>RDEPENDS</filename> must have completed before <filename>do_package_write</filename> can execute. </para> </section> <section id='recursive-dependencies'> <title>Recursive Dependencies</title> <para> These are specified with the 'recrdeptask' flag which is used to signify the task(s) of dependencies which must have completed before that task can be executed. It works by looking though the build and runtime dependencies of the current recipe as well as any inter-task dependencies the task has, then adding a dependency on the listed task. It will then recurse through the dependencies of those tasks and so on. </para> <para> It may be desireable to recurse not just through the dependencies of those tasks but through the build and runtime dependencies of dependent tasks too. If that is the case, the taskname itself should be referenced in the task list (e.g. <filename>do_a[recrdeptask] = "do_a do_b"</filename>). </para> </section> <section id='inter-task-dependencies'> <title>Inter-Task Dependencies</title> <para> The 'depends' flag for tasks is a more generic form which allows an inter-dependency on specific tasks rather than specifying the data in <filename>DEPENDS</filename>. <literallayout class='monospaced'> do_patch[depends] = "quilt-native:do_populate_staging" </literallayout> In the previous example, the <filename>do_populate_staging</filename> task of the target quilt-native must have completed before the <filename>do_patch</filename> task can execute. </para> <para> The 'rdepends' flag works in a similar way but takes targets in the runtime namespace instead of the build-time dependency namespace. </para> </section> </section> <section id='accessing-variables-and-the-data-store-from-python'> <title>Accessing Variables and the Data Store from Python</title> <para> It is often necessary to manipulate variables within python functions and the Bitbake data store has an API which allows this. The operations available are: <literallayout class='monospaced'> d.getVar("X", expand=False) </literallayout> returns the value of variable "X", expanding the value if specified. <literallayout class='monospaced'> d.setVar("X", value) </literallayout> sets the value of "X" to "value". <literallayout class='monospaced'> d.appendVar("X", value) </literallayout> adds "value" to the end of variable X. <literallayout class='monospaced'> d.prependVar("X", value) </literallayout> adds "value" to the start of variable X. <literallayout class='monospaced'> d.delVar("X") </literallayout> deletes the variable X from the data store. <literallayout class='monospaced'> d.renameVar("X", "Y") </literallayout> renames variable X to Y. <literallayout class='monospaced'> d.getVarFlag("X", flag, expand=False) </literallayout> gets given flag from variable X but does not expand it. <literallayout class='monospaced'> d.setVarFlag("X", flag, value) </literallayout> sets given flag for variable X to value. <filename>setVarFlags</filename> will not clear previous flags. Think of this method as <filename>addVarFlags</filename>. <literallayout class='monospaced'> d.appendVarFlag("X", flag, value) </literallayout> Need description. <literallayout class='monospaced'> d.prependVarFlag("X", flag, value) </literallayout> Need description. <literallayout class='monospaced'> d.delVarFlag("X", flag) </literallayout> Need description. <literallayout class='monospaced'> d.setVarFlags("X", flagsdict) </literallayout> sets the flags specified in the <filename>dict()</filename> parameter. <literallayout class='monospaced'> d.getVarFlags("X") </literallayout> returns a <filename>dict</filename> of the flags for X. <literallayout class='monospaced'> d.delVarFlags </literallayout> deletes all the flags for a variable. </para> </section> </chapter>
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import { RootState } from "../../app/store"; import { IResponse } from "../../models/response"; import { IUser, IUserAuth, IUserRegister } from "../../models/user"; import { User } from "../../services/callApi"; export interface IUserSliceState { user: IUser loggedIn: boolean } export const loginToken = createAsyncThunk<IUserAuth, undefined>( 'user/loginToken', async(arg) => { const response = await User.status() return response } ) export const loginForm = createAsyncThunk<IUserAuth, {username: string, password: string}>( 'user/loginForm', async(body) => { const response = await User.login(body.username, body.password) return response } ) export const register = createAsyncThunk<IUserAuth, IUserRegister>( 'user/register', async (body, { rejectWithValue }) => { const response = await User.register(body) return response } ) const initialState: IUserSliceState = { user: { id: -1, userName: 'Guest', firstName: 'Guest', lastName: 'Guest', fullName: 'Guest', userType: 'User' }, loggedIn: false } export const userSlice = createSlice({ name: 'user', initialState, reducers: { logout: (state) => { state.loggedIn = false localStorage.removeItem('token') } }, extraReducers: (builder) => { builder .addCase(loginToken.fulfilled, (state, action) => { let res: IUserAuth = action.payload localStorage.setItem('token', res.token) state.user = res.user state.loggedIn = true console.log(res.token) }) .addCase(loginForm.fulfilled, (state, action) => { let res: IUserAuth = action.payload localStorage.setItem('token', res.token) state.user = res.user state.loggedIn = true console.log(res.token) }) .addCase(loginForm.rejected, (state, action) => { console.log(action.payload) }) .addCase(register.fulfilled, (state, action) => { state.loggedIn = true console.log(action.payload) }) .addCase(register.rejected, (state, action) => { console.log(action.payload) }) } }) export const { logout } = userSlice.actions export const isLoggedIn = (state: RootState) => state.user.loggedIn export const currentUser = (state: RootState) => state.user.user export default userSlice.reducer
import { useEffect, useState } from "react"; import styled from "styled-components"; import { useNavigate } from "react-router-dom"; const Wrapper = styled.div` padding: 20px; text-align: center; background-color: #fff3cd; border-left: 5px solid #ffcc00; margin: 20px auto; border-radius: 5px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); max-width: 900px; width: 90%; transition: all 0.3s ease; display: flex; flex-direction: column; align-items: center; @media (max-width: 768px) { padding: 15px; margin: 10px auto; } @media (max-width: 480px) { padding: 10px; margin: 5px auto; } `; const WarningContainer = styled.div` display: flex; justify-content: ${(props) => (props.hasBoth ? "space-between" : "center")}; align-items: center; width: 100%; max-width: 600px; @media (max-width: 768px) { flex-direction: column; } @media (max-width: 480px) { flex-direction: column; } `; const MessageWrapper = styled.div` margin: 10px; flex: 1; text-align: center; `; const Message = styled.p` margin: 20px 0; font-size: 1.125rem; color: #856404; @media (max-width: 768px) { font-size: 1rem; } @media (max-width: 480px) { font-size: 0.875rem; } `; const Button = styled.button` padding: 10px 20px; background-color: #dc3545; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 1rem; box-shadow: 0 4px 8px rgba(220, 53, 69, 0.3); transition: background-color 0.3s ease, transform 0.2s ease; margin: 10px; &:hover { background-color: #c82333; transform: translateY(-2px); } @media (max-width: 768px) { padding: 8px 15px; font-size: 0.875rem; } @media (max-width: 480px) { padding: 6px 10px; font-size: 0.75rem; } `; const LocationAndZoneWarning = () => { const [parkOwnerData, setParkOwnerData] = useState(null); const [loading, setLoading] = useState(true); const navigate = useNavigate(); useEffect(() => { const user_id = localStorage.getItem("user_id"); const token = localStorage.getItem("token"); const role = localStorage.getItem("role"); if (role === "park_owner") { fetch("https://parkspotter-backened.onrender.com/accounts/parkowner-list/", { headers: { Authorization: `Token ${token}`, }, }) .then((response) => response.json()) .then((data) => { const userData = data.find((item) => item.park_owner_id.id.toString() === user_id); setParkOwnerData(userData); setLoading(false); }) .catch((error) => { console.error("Error fetching park owner data:", error); setLoading(false); }); } else { setLoading(false); } }, []); if (loading) { return <Wrapper>Loading...</Wrapper>; } if (!parkOwnerData) { return <Wrapper>No data available.</Wrapper>; } const { capacity, latitude, longitude } = parkOwnerData; const showZoneWarning = capacity === "0"; const showLocationWarning = !latitude || !longitude; // If neither warning is needed, return null if (!showZoneWarning && !showLocationWarning) { return null; } const hasBoth = showZoneWarning && showLocationWarning; return ( <Wrapper> <WarningContainer hasBoth={hasBoth}> {showZoneWarning && ( <MessageWrapper> <Message>You have not created a zone yet.</Message> <Button onClick={() => navigate("/dashboard/Zones")}>Create Zone</Button> </MessageWrapper> )} {showLocationWarning && ( <MessageWrapper> <Message>You have not set the address of your parking lot on the map.</Message> <Button onClick={() => navigate("/dashboard/ParkOwnerLocation")}>Set Location</Button> </MessageWrapper> )} </WarningContainer> </Wrapper> ); }; export default LocationAndZoneWarning;
<script> import AppJumbo from './AppJumbo.vue'; import AppCardComic from './AppCardComic.vue'; export default { name: 'AppMain', components: { AppJumbo, AppCardComic, }, data() { return { comics: [ { "thumb": "https://www.coverbrowser.com/image/action-comics/1-1.jpg", "price": "$19.99", "series": "Action Comics", "type": "comic book", }, { "thumb": "https://www.panini.it/media/catalog/product/cache/a5b5dd3adfe0d321084804c738f29601/M/1/M1BLLA015ISBN_0.jpg", "price": "$3.99", "series": "American Vampire 1976", "type": "comic book", }, { "thumb": "https://media.wired.com/photos/593384dad80dd005b42b2817/master/w_2560%2Cc_limit/Aquaman-16.jpg", "price": "$16.99", "series": "Aquaman", "type": "graphic novel", }, { "thumb": "https://d29xot63vimef3.cloudfront.net/image/batgirl/1-1.jpg", "price": "$2.99", "series": "Batgirl", "type": "comic book", }, { "thumb": "https://static.posters.cz/image/750/locandine-film-in-plexiglass-batman-prowl-comic-cover-i69653.jpg", "price": "$3.99", "series": "Batman", "type": "comic book", }, { "thumb": "https://static.wikia.nocookie.net/marvel_dc/images/5/50/Batman_Beyond_v.1_1.jpg", "price": "$2.99", "series": "Batman Beyond", "type": "comic book", }, { "thumb": "https://static.wikia.nocookie.net/marvel_dc/images/0/0d/Batman_Superman_Vol_1_1.jpg", "price": "$3.99", "series": "Batman/Superman", "type": "comic book", }, { "thumb": "https://static.wikia.nocookie.net/marvel_dc/images/c/cf/Batman_Superman_Annual_Vol_2_1.jpg", "price": "$4.99", "series": "Batman/Superman Annual", "type": "comic book", }, { "thumb": "https://static.wikia.nocookie.net/marvel_dc/images/5/54/Batman_The_Joker_War_Zone_Vol_1_1.jpg", "price": "$5.99", "series": "Batman: The Joker War Zone", "type": "comic book", }, { "thumb": "https://static.wikia.nocookie.net/marvel_dc/images/6/64/Batman_Three_Jokers_Collected.jpg", "price": "$6.99", "series": "Batman: Three Jokers", "type": "comic book", }, { "thumb": "https://static.wikia.nocookie.net/marvel_dc/images/f/f8/Batman_White_Knight_Presents_Harley_Quinn_Vol_1_1.jpg", "price": "$4.99", "series": "Batman: White Knight Presents: Harley Quinn", "type": "comic book", }, { "thumb": "https://static.wikia.nocookie.net/marvel_dc/images/c/c8/Catwoman_Vol_2_1.jpg", "price": "$16.99", "series": "Catwoman", "type": "graphic novel", }, ] } }, } </script> <template> <main> <AppJumbo /> <div class="container my-p position-relative"> <div class="plate">CURRENT SERIES</div> <div class="my-row"> <AppCardComic v-for="item in comics" :comic="item"/> </div> <div class="text-center pt-4"> <button class="my-btn">LOAD MORE</button> </div> </div> </main> </template> <style lang="scss" scoped> @use '../styles/partials/_variables.scss' as *; main{ background-color: #1c1c1c; .my-p{ padding: 50px 0px 15px 0px; } .plate{ position: absolute; bottom: 97%; cursor: default; background-color: $my-blue; color: #fff; font-size: large; font-weight: 900; padding: 8px 25px; } .my-row{ padding: 0 20px; display: flex; justify-content: space-between; flex-wrap: wrap; gap: 20px 5px; } .my-btn{ background-color: $my-blue; border: 0; padding: 5px 40px; color: #fff; font-weight: 600; font-size: small; &:hover{ transform:scale(1.1); } } } </style>
import { border } from '@mui/system'; import { View, StyleSheet } from 'react-native'; import Text from './Text'; import moment from 'moment/moment'; const cardHeaderStyles = StyleSheet.create({ container: { flexDirection: 'row', flexGrow: 1, alignItems: 'flex-start', }, rating: { color: "blue", fontWeight: "bold" }, ratingContainer: { width: 45, height: 45, marginRight: 5, borderRadius: 22, borderColor: 'blue', borderWidth: 3, alignItems: "center", justifyContent: "center" }, infoContainer: { flexGrow: 1, flexDirection: "column", marginRight: 10 }, textContainer: { alignContent: "flex-start" } }); const cardStyles = StyleSheet.create({ container: { flexDirection: "column", padding: 20, backgroundColor: 'white' }, }); const Card = ({ item }) => { const date = moment(item.createdAt).calendar() return( <View style={cardHeaderStyles.container}> <View style={cardHeaderStyles.ratingContainer}> <Text style={cardHeaderStyles.rating}>{item.rating}</Text> </View> <View style={cardHeaderStyles.infoContainer}> <Text fontWeight="bold" fontSize="subheading">{item.user.username}</Text> <Text color="textSecondary">{date}</Text> <Text>{item.text}</Text> </View> </View> ) } const Review = ({item}) => { //console.log(item, "review") return( <View style={cardStyles.container}> <Card item={item} /> </View> ) } export default Review
import React from 'react'; import ReactDOM from 'react-dom'; import { connect, Provider } from 'react-redux'; import { createStore, combineReducers ,applyMiddleware} from 'redux'; // constants const GET_MESSAGE_LIST = 'GET_MESSAGE_LIST'; const ADD_MESSAGE = 'ADD_MESSAGE'; const DELETE_MESSAGE = 'DELETE_MESSAGE'; // reduce let time = new Date().getTime(); const messagesReducer = (state = [{ id: time, name: `name${time}` }], action) => { switch (action.type) { case GET_MESSAGE_LIST: return state; case ADD_MESSAGE: return [{ id: action.addTime, name: `name${action.addTime}` }, ...state]; case DELETE_MESSAGE: const [a, ...newList] = state; return newList; default: return state } } const reducer = combineReducers({ messages: messagesReducer }); const logger1 = (store) => (next) => (action) => { console.log('dispatching logger1', action); next(action); console.log('next state logger1', store.getState()); } let createStoreWithMiddleware = applyMiddleware(logger1)(createStore); let store = createStoreWithMiddleware(reducer); // actions const getMessageListAction = () => { return { type: GET_MESSAGE_LIST } } const addMessageAction = (addTime) => { return { type: ADD_MESSAGE, addTime } } const deleteMessageAction = () => { return { type: DELETE_MESSAGE } } // component // UI 组件 class MessageList extends React.Component { constructor(props) { super(props); this.addHandle = this.addHandle.bind(this); this.deleteHandle = this.deleteHandle.bind(this); } render() { const { messages } = this.props; const str = messages.map(obj => <p key={obj.id}> <strong>id:</strong><span style={{ 'marginRight': '50px' }}>{obj.id}</span> <strong>name:</strong><span>{obj.name}</span> </p> ); return ( <div> {str} <button onClick={this.addHandle}>add</button> <button onClick={this.deleteHandle}>delete</button> </div> ) } addHandle() { const { addMessage } = this.props; addMessage(); } deleteHandle() { const { deleteMessage } = this.props; deleteMessage(); } } const mapStateToProps = (state, ownProps) => { return { messages: state.messages } } const mapDispacthToProps = dispatch => { return { getMessages() { dispatch(getMessageListAction()); }, addMessage() { dispatch(addMessageAction(new Date().getTime())); }, deleteMessage() { dispatch(deleteMessageAction()); } } } const MessageListWrapper = connect(mapStateToProps, mapDispacthToProps)(MessageList); class App extends React.Component { render() { return ( <div> <MessageListWrapper></MessageListWrapper> </div> ) } } ReactDOM.render( <Provider store={store}> <App></App> </Provider>, document.getElementById('root') )
import React, { useEffect } from 'react' import classNames from 'classnames' import { Chapter, CHAPTERS } from '../../helpers/constants' import useOnScreen from '../../helpers/useOnScreenHook' import classes from './GeneralInfo.module.scss' import * as language from './GeneralInfo_lang' interface Props { setCurrentChapter: (chapter: Chapter) => void } const GeneralInfo = (props: Props) => { // Used to identify the chapter // Also add this to the Chapter type and add corresponding data in the CHAPTERS map // (see constants.ts) const CHAPTER_ID: Chapter = 'GENERAL_INFO' // Refs for the elements that we want to detect whether on screen const topRef = React.useRef<HTMLInputElement>(null) const bottomRef = React.useRef<HTMLInputElement>(null) // Call the hooks passing in ref and root margin // Only considered onScreen if more than 350px of element is visible. const topOnScreen = useOnScreen(topRef, '-350px') const bottomOnScreen = useOnScreen(bottomRef, '-350px') // Set current chapter state in App every time onScreen changes // (also on every rerender, which should hopefully be fine) useEffect(() => { topOnScreen && props.setCurrentChapter(CHAPTER_ID) }, [topOnScreen]) useEffect(() => { bottomOnScreen && props.setCurrentChapter(CHAPTER_ID) }, [bottomOnScreen]) return ( <div id={CHAPTER_ID} className={classes.heading}> <div ref={topRef} className={'header-outer'}> <div className='header-inner'> <h2 className={classNames(classes.heading, 'chapter-heading')}> {CHAPTERS.get(CHAPTER_ID)?.title} </h2> </div> </div> <div className={classNames(classes.content)}> <div className='chapter-body-wrapper'> <div className={classNames(classes.sectionColumn2)}> <p className={classNames(classes.headerText)}>{language.header1}</p> <p className={classNames(classes.text)}> {language.allgemeineInfos}</p> </div> <div className={classNames(classes.sectionColumn1)}> <p className={classNames(classes.headerText)}>{language.header2}</p> <p className={classNames(classes.text)}>{language.warning}</p> </div> </div> </div> <div ref={bottomRef}></div> </div> ) } export default GeneralInfo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .square-form{ background-color:grey; width:1280px; height:1000px; border: 1px solid black; } .content p, a{ text-align: center; font-size: larger; } h1{ text-align: center; } </style> </head> <body> <form action="" class="square-form"> <div class="content"> <h1>User Interface (UI) Design </h1> <p> User interface (UI) design refers to the visual design of a products digital interface, such as an app screen or website. It’s the process of designing the visual and interactive properties of a visual experience, ensuring the interface is both clear for the user to navigate and overall aesthetically pleasing. UI design is a multidisciplinary field involving various elements from visual design, UX design, and graphic design. <br> Users have become familiar with certain layouts and patterns. From the typography to the color, every aspect of a digital screen influences the users interaction, and satisfaction, with the app or website. UI design involves the complex art of arranging these elements to guide the user and keep cognitive load to a minimum while creating beautiful, unique experiences that bring the product to life. <br> UI design is so much more than making things look pretty—especially in todays digitally-led landscape. Most good businesses recognize that exceptional UI design is vital for fostering brand loyalty, recognition, and trust. Customers no longer enjoy well-designed digital experiences; they expect it. In the absence of good design, users will inevitably flee to a competitor. <br> </p> <br> <h3>Future of UI Design</h3> <ul> <li>Minimalism and Simplicity: UI design has been leaning towards simplicity and minimalism, focusing on clean, uncluttered interfaces that are easy to navigate and understand. This trend is likely to continue as users appreciate intuitive and straightforward experiences. </li> <li>Responsive and Adaptive Design: With the increasing use of various devices and screen sizes, responsive and adaptive design principles have become crucial. UI designers are expected to create interfaces that work seamlessly across a range of devices, from smartphones and tablets to desktops and beyond. </li> <li>Microinteractions: Microinteractions are subtle animations and feedback that provide a more engaging and delightful user experience. As technology advances, we can expect more creative and immersive microinteractions in UI design. </li> <li>Voice User Interfaces (VUI) and Conversational UI: With the rise of voice assistants and smart devices, UI designers will need to adapt to VUI and conversational UI design. These interfaces will require natural language interactions and user-friendly conversational flows. </li> <li>Augmented Reality (AR) and Virtual Reality (VR) UI: As AR and VR technologies become more prevalent, UI designers will face the challenge of creating immersive and interactive experiences in virtual environments. </li> <li>Data Visualization and Infographics: In an increasingly data-driven world, UI designers will continue to play a crucial role in presenting complex data and information in a visually appealing and understandable way. </li> <li>Accessibility and Inclusivity: UI designers will focus more on creating accessible and inclusive designs to cater to users with diverse abilities and needs. </li> <li>Dark Mode: Dark mode has gained popularity due to its visual appeal and reduced eye strain. It is likely to remain a prominent feature in UI design, offering users more choices for customization. </li> <li>Artificial Intelligence (AI) in UI Design: AI technologies may play a role in automating certain aspects of UI design, such as generating layouts, color schemes, and personalized content based on user preferences.</li> <li>Gesture-Based and Touchless Interactions: With the advancement of touchless technologies, UI designers will explore new ways of interaction, including gesture-based and touchless interfaces.</li> </ul> <a href="index2.html">Back to Home</a> </div> </form> </body> </html>
package com.bcc.spr.experian.service; import com.bcc.spr.experian.model.entity.StrategyLogExcel; import lombok.val; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; public class ExcelGenerator { public static ByteArrayInputStream logExcelReport(Iterable<StrategyLogExcel> strategyLogs) throws Exception{ String[] COLUMNs ={"id", "businessKey", "date_insert", "decision_code", "id_req", "name", "reason_code", "source_code", "taxcode", "max_credit_sum", "design_income", "dcl_code", "is_new_kls_acc"}; Workbook workbook = new XSSFWorkbook(); CreationHelper createHelper = workbook.getCreationHelper(); //Sheet sheet = workbook.getSheet(0); Sheet sheet = workbook.createSheet("List"); val headerFont = workbook.createFont(); headerFont.setBold(true); headerFont.setColor(IndexedColors.BLUE.getIndex()); val headerCellStyle = workbook.createCellStyle(); headerCellStyle.setFont(headerFont); // Row for Header val headerRow = sheet.createRow(0); //Header for(int i=0; i<COLUMNs.length; i++) { Cell cell = headerRow.createCell(i); cell.setCellValue(COLUMNs[i]); cell.setCellStyle(headerCellStyle); } // CellStyle for Age val ageCellStyle = workbook.createCellStyle(); ageCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("#")); int rowIdx = 1; for (StrategyLogExcel item : strategyLogs) { val row = sheet.createRow(rowIdx++); row.createCell(0).setCellValue(item.getId().toString()); row.createCell(1).setCellValue(item.getBusiness_key()); row.createCell(2).setCellValue(item.getDate_insert().toString()); row.createCell(3).setCellValue(item.getDecision_code()!=null ? item.getDecision_code() : ""); row.createCell(4).setCellValue(item.getId_req()!=null ? item.getId_req(): ""); row.createCell(5).setCellValue(item.getName()!=null ? item.getName() : ""); row.createCell(6).setCellValue(item.getReason_code()!=null ? item.getReason_code() : ""); //row.createCell(6).setCellValue(item.getRequest()!=null ? item.getRequest() : ""); //row.createCell(7).setCellValue(item.getResponse()!=null ? item.getResponse() : ""); row.createCell(7).setCellValue(item.getSource_code()!=null ? item.getSource_code() : ""); row.createCell(8).setCellValue(item.getTaxcode()!=null ? item.getTaxcode() : ""); row.createCell(9).setCellValue(item.getMax_credit_sum()!=null ? new String(item.getMax_credit_sum()) : ""); row.createCell(10).setCellValue(item.getDesign_income()!=null ? item.getDesign_income() : ""); row.createCell(11).setCellValue(item.getDcl_code()!=null ? item.getDcl_code() : ""); row.createCell(12).setCellValue(item.getIs_new_kls_acc()!=null ? item.getIs_new_kls_acc() : ""); } ByteArrayOutputStream out = new ByteArrayOutputStream(); workbook.write(out); workbook.close(); return new ByteArrayInputStream(out.toByteArray()); } }
package org.dc.cc.GameObjects.Chessboard; import org.dc.cc.Engine.IncorrectMovementError; import org.dc.cc.GameObjects.ChessPieces.ChessPiece; import org.dc.cc.GameObjects.ChessPieces.IChessPiece; import org.dc.cc.GameObjects.Players.Player; import org.dc.cc.Utilities.FieldMapper; import org.dc.cc.View.View; import java.io.File; import java.util.*; public class Board { List<Field> fields; public Board() { create(); } void create(){ fields = new ArrayList<>(); for (FilesEnum column : FilesEnum.values()){ for(RanksEnum row : RanksEnum.values()){ fields.add(new Field(column, row)); } } } public Field getField(FilesEnum column, RanksEnum row) throws NullPointerException { for (int i = 0; i < fields.size(); i++) { if (fields.get(i).getColumn() == column && fields.get(i).getRow() == row) { return fields.get(i); } } return null; } public Field getField(String column, String row) throws NullPointerException { FieldMapper fm = new FieldMapper(); return fm.mapField(column.toUpperCase(), row, this); } public Field getField(String cr) throws NullPointerException, IllegalArgumentException { if (cr.length() != 2){ throw new IllegalArgumentException(); } FieldMapper fm = new FieldMapper(); String column = cr.substring(0,1).toUpperCase(); String row = cr.substring(1,2); return fm.mapField(column, row, this); } public void showBoard(){ View.showBoard(this); } public void moveChessPiece(Field fromField, Field toField) throws IncorrectMovementError{ if (!fromField.hasChessPiece()){ throw new IncorrectMovementError("No chesspiece on a field"); } if (!fromField.getChessPiece().isMoveValid(fromField, toField)){ throw new IncorrectMovementError("Illegal movement."); } IChessPiece piece = fromField.getChessPiece(); fromField.removeChessPiece(); toField.setChessPiece(piece); } public void moveChessPiece(FilesEnum fromColumn, RanksEnum fromRow, FilesEnum toColumn, RanksEnum toRow) throws IncorrectMovementError { Field fromField = getField(fromColumn, fromRow); Field toField = getField(toColumn, toRow); moveChessPiece(fromField, toField); } public void moveChessPiece(String fromField, String toField) throws IncorrectMovementError{ moveChessPiece(getField(fromField), getField(toField)); } public void putChessPiece(Field field, IChessPiece chessPiece) { field.setChessPiece(chessPiece); } public void putChessPiece(String fieldString, IChessPiece chessPiece) { Field field = getField(fieldString); putChessPiece(field, chessPiece); } public Map<IChessPiece, Field> getChessPieceForPlayerList(Player player){ Map<IChessPiece, Field> chessPiecesForPlayer = new HashMap<>(); for (Field field : fields){ if (field.hasChessPiece() && field.getChessPiece().getPlayer() == player){ chessPiecesForPlayer.put(field.getChessPiece(), field); } } return chessPiecesForPlayer; } public void showPiecesOfPlayer(Player player){ Map<IChessPiece, Field> chessPiecesForPlayer = getChessPieceForPlayerList(player); for (Map.Entry<IChessPiece, Field> piece: chessPiecesForPlayer.entrySet()){ System.out.print(piece.getKey().getType()); System.out.print(": "); System.out.print(piece.getValue().getColumn()); System.out.print(piece.getValue().getRow().ordinal()+1); System.out.println(); } } }
--- title: Loaders in Angular date: 2023-04-19 draft: false description: 'Exploring the concept of Remix loaders in the Tour of Heroes and explain what would come closest to a loader in Angular.' --- ## Data fetching in meta frameworks All frontend javascript meta frameworks have it these days: a mechanism for data fetching. They come in many forms, but mostly as a convention-based named `export`, for example [the loader export from Remix](https://remix.run/docs/en/1.15.0/route/loader): ```typescript import { json } from '@remix-run/node'; export const loader = async () => { return json({ myData: 'is the best' }); }; ``` Loaders are executed on the server and fetch the data for a route, potentially in parallel, to make it available for the template of the route component. In Remix you would use the [`useLoaderData`](https://remix.run/docs/en/1.15.0/hooks/use-loader-data) hook to get access to the fetched data: ```typescript import { useLoaderData } from "@remix-run/react"; export default function SomeRoute() { const data = useLoaderData<typeof loader>(); // access myData using data.myData ... } ``` Some other examples of meta frameworks that provide a data fetching mechanism are: - [Next.js](https://nextjs.org/docs/basic-features/data-fetching/overview) - [SvelteKit](https://kit.svelte.dev/docs/load) - [Nuxt](https://nuxt.com/docs/getting-started/data-fetching) - [Qwik City](https://qwik.builder.io/docs/route-loader/) - [SolidStart](https://start.solidjs.com/core-concepts/data-loading) - and maybe it's coming to Angular with [Analogjs](https://github.com/analogjs/analog/issues/197) A data fetching feature is a must have for projects that need server-side rendering. Not all projects have that need though, so maybe SEO is not that important for you. Sometimes a good old SPA is good enough, i.e. for internal applications. Adding a meta framework only adds unnecessary complexity since all of a sudden you have a server to care about and manage. ## Bringing loaders to the SPA 🛀 The Remix team brought the `loader` concept to the Single Page Application with React Router's [loader](https://reactrouter.com/en/main/route/loader). A loader in Remix is (almost) equivalent to a loader in React Router. In comparison, React Router doesn't use file-based routing but [a router config](https://reactrouter.com/en/main/routers/create-browser-router): ```typescript import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { createBrowserRouter, RouterProvider } from 'react-router-dom'; import Root, { rootLoader } from './routes/root'; import Team, { teamLoader } from './routes/team'; const router = createBrowserRouter([ { path: '/', element: <Root />, loader: rootLoader, children: [ { path: 'team', element: <Team />, loader: teamLoader, }, ], }, ]); ReactDOM.createRoot(document.getElementById('root')).render(<RouterProvider router={router} />); ``` Another difference is that React Router does not provide a type-safe API (yet) using a generic argument, so a typecast will be needed to make Typescript happy. [There is an ongoing discussion about that](https://github.com/remix-run/react-router/discussions/9854). React Router uses the same mechanism for **using** the data as Remix, via the [`useLoaderData`](https://reactrouter.com/en/main/hooks/use-loader-data) hook: ```typescript import { useLoaderData } from 'react-router-dom'; export default function Team() { const team = useLoaderData(); // ... } ``` The `loader` concept brings a big win in terms of separation of concerns, maintainability, readability and preventing [those pesky race condition bugs](https://react.dev/learn/you-might-not-need-an-effect#fetching-data) when using `useEffect` in the component itself. There are other alternatives to do data fetching like [React Query](https://tanstack.com/query/latest/docs/react/overview) or Redux (which each come with their own additional complexity). But the `loader` concept is simple and easy to understand. ## Angular must be missing a loader 👼 At first sight the Angular router ([`@angular/router`](https://angular.io/guide/router)) doesn't promote a `loader` concept similar to React Router. There is no evident 'data fetching' section in the docs. That doesn't mean it can't be done using the tools at hand. Let's use the 'Hello World' tutorial of angular.io [Tour of Heroes](https://angular.io/tutorial/tour-of-heroes) as a showcase application to apply solutions on. ## Tour of Heroes The setup is pretty simple, it's an application with the goal of showing/managing some heroes. It has a couple of components, let's go over them shortly. ### DashboardComponent This is the homepage of the application. When the user navigates to the root he'll be redirected here. A subset of the heroes (top heroes) are displayed here and the user can search. ![DashboardComponent](https://ik.imagekit.io/joepkockelkorn/tr:w-768,f-auto/angular-state-guards/dashboard.png) ### HeroesComponent All heroes are shown here. We can navigate to a hero as well. ![HeroesComponent](https://ik.imagekit.io/joepkockelkorn/tr:w-768,f-auto/angular-state-guards/heroes.png) ### HeroDetailComponent This shows a single hero. We can update the hero's name as well. ![HeroDetailComponent](https://ik.imagekit.io/joepkockelkorn/tr:w-768,f-auto/angular-state-guards/hero-detail.png) ### Routing setup The routing setup is pretty straightforward: ```typescript import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { DashboardComponent } from './dashboard/dashboard.component'; import { HeroesComponent } from './heroes/heroes.component'; import { HeroDetailComponent } from './hero-detail/hero-detail.component'; const routes: Routes = [ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'dashboard', component: DashboardComponent }, { path: 'heroes', component: HeroesComponent }, { path: 'detail/:id', component: HeroDetailComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {} ``` No lazy loading, just one route config for the whole application. Can't get much simpler. ### Data fetching strategy The data is fetched in the component themselves. This is done similarly in all components. For example, this is the `HeroDetailComponent`: ```typescript import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Hero } from '../hero'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-hero-detail', templateUrl: './hero-detail.component.html', styleUrls: ['./hero-detail.component.css'], }) export class HeroDetailComponent implements OnInit { hero: Hero | undefined; constructor( private route: ActivatedRoute, private heroService: HeroService, ) {} ngOnInit(): void { this.getHero(); } // 🔽🔽🔽 data fetching done here 🔽🔽🔽 getHero(): void { const id = parseInt(this.route.snapshot.paramMap.get('id')!, 10); this.heroService.getHero(id).subscribe((hero) => (this.hero = hero)); } // ... } ``` For the rest of this blog post I'll focus on this component to apply possible solutions on. ## Tour of Heroes in review For experienced Angular developers it might not be a shock that the Tour of Heroes is not exactly world class code that should be used in production. It is not promoted as such. But it can still be useful for this blog post, to see how we would improve and potentially use the concept of loaders in Angular. Let's take a detailed look at the `HeroDetailComponent`. ### HeroDetailComponent A couple of things come to mind when looking at both the code and the UX. From a **UX** perspective, we have: - A jumpy experience. When the user navigates to this route, the UI changes twice. This happens because the old route component is being destroyed, then the new one is being rendered (partly), and then the UI is updated again after the hero has loaded. - A missing 404 experience. When the user navigates to URL for a hero that does not exist, there is no redirect or 'whoops not found' experience shown. From a **code** perspective we have: - No separation of concerns. Data fetching logic is mixed with navigation and form logic. - Conditional logic. It could be the case the hero it not loaded yet. Or the fetching could be done but the hero does not exist. This also leads to code duplication for any 'loading' logic, every component needs it, **again**. ## Bringing loaders to Angular So it's obvious there's a lot to improve. Let's explore potential solutions and see what might be the closest thing to a `loader` in Angular. Well, let me just call it out: it's **Guards**. It might seem a bit hidden in plain sight, but on the [Common Routing Tasks](https://angular.io/guide/router) page of angular.io, there's a section devoted to guards. You can find it under the heading [Preventing unauthorized access](https://angular.io/guide/router#preventing-unauthorized-access), which is a heavy understatement: guards can be used for much more than just authorization checks. ### Guards introduction At the end of the section mentioned above is [a link to the Tour of Heroes router tutorial](https://angular.io/guide/router-tutorial-toh#milestone-5-route-guards), called: **Route guards**. I'm just going to borrow their explanation of route guards: > At the moment, any user can navigate anywhere in the application any time, but sometimes you need to control access to different parts of > your application for various reasons, some of which might include the following: > > - Perhaps the user is not authorized to navigate to the target component > - Maybe the user must login (authenticate) first > - Maybe you should fetch some data before you display the target component > - You might want to save pending changes before leaving a component > - You might ask the user if it's okay to discard pending changes rather than save them > > You add guards to the route configuration to handle these scenarios. From this list it becomes clear: guards are not only useful for authorization. For the sake of this blog post, bullet point #3 sounds very interesting. > Maybe you should **fetch** some data **before** you display the target component Actually, it sounds precisely like a loader. That's what we're looking for! ## Guard types Now, which one to pick... These are the possible guard types: - canActivate - canActivateChild - canDeactivate - canLoad - canMatch - resolve Let's explain them: - [CanActivateFn](https://angular.io/api/router/CanActivateFn) is called before a route is activated. - [CanActivateChildFn](https://angular.io/api/router/CanActivateChildFn) does the same as CanActivateFn but for any of the route's children. - [CanDeactivateFn](https://angular.io/api/router/CanDeactivateFn) is called whenever a user exits a route, so is unfit for data fetching before navigation. - [CanLoadFn](https://angular.io/api/router/CanLoadFn) is called before a lazy loaded route component or module is loaded. - [CanMatchFn](https://angular.io/api/router/CanMatchFn) is called before a route is matched. - [ResolveFn](https://angular.io/api/router/ResolveFn) is called before a route is activated. But this one is different than `CanActivateFn`, because it's purpose is exclusively for data fetching. !!! info `CanMatchFn` vs `CanLoadFn` vs `CanActivateFn` Since in Angular version 14.1 the [CanMatchFn](https://angular.io/api/router/CanMatchFn) was added, the `CanLoadFn`, `CanActivateFn` and `CanActivateChildFn` seems to be less useful for data fetching, because with `CanMatchFn` you can prevent a route from being matched at all. And routes that are not going to be matched **will not be loaded or activated**. So `CanMatchFn` is more powerful than the `CanLoadFn` and `CanActivate(Child)Fn` because it's evaluated sooner. But its downside is that the `route` parameter is not yet a fully qualified `ActivatedRouteSnapshot`, so getting url params is not easy ([see explanation](https://github.com/angular/angular/issues/49309#issuecomment-1453863052)). So therefore, `CanMatchFn` is currently not a good fit for data fetching. `CanLoadFn` is also not a good fit for data fetching, because it's only called for lazy loaded components or modules, not for **every** route. !!! Let's look at the canActivate and resolve guards more in detail and how they could be used for data fetching. ### canActivate A canActivate guard comes in two forms. The first is the deprecated [`CanActivate`](https://angular.io/api/router/CanActivate) interface. The second is it's newer equivalent, the [`CanActivateFn`](https://angular.io/api/router/CanActivateFn). A guard can only return two types of values, a `boolean` or a `UrlTree`. When returning `true`, the navigation succeeds. When returning `false`, navigation is cancelled (as if nothing happened). When returning a `UrlTree`, the router will navigate to that `UrlTree` instead. You could see it as a redirect. More often than not, the value you need to determine the result for the guard to return is coming from either a HTTP request or some data store. So, in order to make the guard asynchronous, you can return an `Observable<boolean | UrlTree>` or a `Promise<boolean | UrlTree>` as well. Now that we've cleared that up, let's look at how we would solve the Tour of Heroes issues with `CanActivateFn`. ```typescript // hero-loader.ts import { inject } from '@angular/core'; import { Router, CanActivateFn } from '@angular/router'; import { BehaviorSubject, map } from 'rxjs'; import { Hero } from './hero'; import { HeroService } from './hero.service'; declare global { var hero: BehaviorSubject<null | Hero>; } window.hero = new BehaviorSubject<Hero | null>(null); export const heroLoader: CanActivateFn = (route) => { const id = Number(route.paramMap.get('id')!); const router = inject(Router); const heroService = inject(HeroService); return heroService.getHero(id).pipe( map((hero) => { window.hero.next(hero); return Boolean(hero) || router.createUrlTree(['/not-found']); }), ); }; ``` Here we define a loader function which implements the `CanActivateFn` interface. It mainly comprises of three parts: - get some data from the route (the `id` param value) - use it to fetch the hero and save it in a global variable for later use (here `Window`) - handle the edge case (i.e. navigation to a 'Not found' page in case the hero can't be found) Then, we use this function in the router config: ```typescript + import { heroLoader } from './hero-loader'; const routes: Routes = [ // ... { path: 'detail/:id', component: HeroDetailComponent, // 🔽🔽🔽 canActivate config added here 🔽🔽🔽 + canActivate: [heroLoader], }, // ... ]; ``` And remove the data fetching logic from the `HeroDetailComponent`: ```typescript import { Component } from '@angular/core'; import { Location } from '@angular/common'; import { Hero } from '../hero'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-hero-detail', templateUrl: './hero-detail.component.html', styleUrls: ['./hero-detail.component.css'], }) export class HeroDetailComponent { hero$ = window.hero!; constructor( private heroService: HeroService, private location: Location, ) {} goBack(): void { this.location.back(); } save(hero: Hero): void { this.heroService.updateHero(hero).subscribe(() => this.goBack()); } } ``` Now that the hero property is an `Observable<Hero | null>` instead of `Hero | undefined` we have to change the template a bit: ```html <!-- need to use async pipe 🔽 --> <div *ngIf="hero$ | async as hero"> <h2>{{hero.name | uppercase}} Details</h2> <div><span>id: </span>{{hero.id}}</div> <div> <label for="hero-name">Hero name: </label> <input id="hero-name" [(ngModel)]="hero.name" placeholder="Hero name" /> </div> <button type="button" (click)="goBack()">go back</button> <!-- and pass the hero here 🔽 --> <button type="button" (click)="save(hero)">save</button> </div> ``` [See a working example on Stackblitz here.](https://stackblitz.com/edit/angular-loaders-canactivate?file=src/app/hero-loader.ts) ### resolve Last on the list, but not least is the resolve guard. A resolve guard comes in two forms. The first is the deprecated [`Resolve`](https://angular.io/api/router/Resolve) interface. The second is it's newer equivalent, the [`ResolveFn`](https://angular.io/api/router/ResolveFn). Resolve guards are a little different in usage and API than the other guards. Let's review how a resolve might solve our data fetching issues in the Tour of Heroes. Looking at some code: ```typescript // hero-resolver.ts import { inject } from '@angular/core'; import { ActivatedRouteSnapshot, ResolveFn, Router } from '@angular/router'; import { EMPTY, of } from 'rxjs'; import { mergeMap } from 'rxjs/operators'; import { Hero } from './hero'; import { HeroService } from './hero.service'; export const heroResolver: ResolveFn<Hero> = (route: ActivatedRouteSnapshot) => { const id = Number(route.paramMap.get('id')!); const router = inject(Router); const heroService = inject(HeroService); return heroService.getHero(id).pipe( mergeMap((hero) => { if (hero) { return of(hero); } else { // hero not found router.navigate(['/not-found']); return EMPTY; } }), ); }; ``` Here we define a function which implements the `ResolveFn` interface. It mainly comprises of three parts: - get some data from the route (the `id` param value) - use it to fetch the hero and return it - handle the edge case (i.e. navigation to a 'Not found' page in case the hero can't be found) Then, we use this function in the router config: ```typescript + import { heroResolver } from './hero-resolver'; const routes: Routes = [ // ... { path: 'detail/:id', component: HeroDetailComponent, // 🔽🔽🔽 resolve config added here 🔽🔽🔽 + resolve: { hero: heroResolver }, }, // ... ]; ``` And remove the data fetching logic from the `HeroDetailComponent`: ```typescript import { Component } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Location } from '@angular/common'; import { Observable, map } from 'rxjs'; import { Hero } from '../hero'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-hero-detail', templateUrl: './hero-detail.component.html', styleUrls: ['./hero-detail.component.css'], }) export class HeroDetailComponent { hero$: Observable<Hero> = this.route.data.pipe(map((data) => data['hero'])); constructor( private route: ActivatedRoute, private heroService: HeroService, private location: Location, ) {} goBack(): void { this.location.back(); } save(hero: Hero): void { this.heroService.updateHero(hero).subscribe(() => this.goBack()); } } ``` !!! info Typecasting Note we still have to pluck the hero from the route data. The plucking requires a type annotation or a typecast because by default any property on `Data` resolves to `any`: ```typescript type Data = { [key: string | symbol]: any; }; ``` This typecasting issue is also there in Remix. In Remix we also have to help typescript to infer the type of the loader using `useLoaderData<typeof loader>()`. !!! Now that the hero property is an `Observable<Hero>` instead of `Hero | undefined` we have to change the template a bit: ```html <!-- need to use async pipe 🔽 --> <div *ngIf="hero$ | async as hero"> <h2>{{hero.name | uppercase}} Details</h2> <div><span>id: </span>{{hero.id}}</div> <div> <label for="hero-name">Hero name: </label> <input id="hero-name" [(ngModel)]="hero.name" placeholder="Hero name" /> </div> <button type="button" (click)="goBack()">go back</button> <!-- and pass the hero here 🔽 --> <button type="button" (click)="save(hero)">save</button> </div> ``` [See a working example on Stackblitz here.](https://stackblitz.com/edit/angular-loaders-resolve?file=src/app/hero-resolver.ts) ## Solutions in review ### General guard data fetching experience After applying the resolve or canActivate guard there's a change in UX: - When we click on a hero from the dashboard we stay on the same page. - In the background the hero is fetched. - When fetching is done, we see the `HeroDetailComponent` instantly. To improve the UX we could introduce a global loading indicator using the logic explained [in this tutorial by Todd Motto](https://ultimatecourses.com/blog/angular-loading-spinners-with-router-events). This brings additional benefits, because we only have to build the loading logic once instead of into each template of several other components! ### canActivate guard While having the possibility to do a redirect using `UrlTree` is great, canActivate is not perfect. The ugly part is the extra 'state' management we have to do. It's not even actual state, it's more of a temporary cache which we have to keep up to date. If there were more instances of the same component using the same hero variable, we'd have to resort to a more sophisticated state management solution like NgRx to organize it, because it can get messy quickly. ### resolve guard Compared to the canActivate guard, a resolve guard solves the extra state management we have to do. But a resolve guard also has downsides compared to a canActivate guard. In case the user navigates to a hero that can't be found, the edge case logic kicks in, leading to a `router.navigate`. Doing that from a resolve guard triggers a `NavigationCancel` event. There's [a long-running open github issue](https://github.com/angular/angular/issues/29089) about this, but in a nutshell a `NavigationCancel` event confuses the router. It also messes up the loading indicator logic mentioned above, possibly leading to a slight flicker of the loader (depending on how it's implemented). ## Conclusion In this article we've seen how to use the `canActivate` and `resolve` guards to fetch data for a component, Remix loader style. We've seen they both have their up- and downsides, but in general they can both get the job done. While being pretty feature-complete, the Angular team is still actively working on the router. [For example see this issue](https://github.com/angular/angular/issues/42953), saying the architecture is problematic (in 2021). I still expect to see more improvements in the future. But for now, resolve or canActivate guards are the closest thing we have to a loader in SPA Angular land.
@model CrimeAlert.Models.user_crimeAlert @{ ViewData["Title"] = "Add Alert"; } <!DOCTYPE html> <html> <head> <title>Crime Reporting App</title> <link rel="stylesheet" type="text/css" href="~/css/crimealert.css"> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" /> </head> <body> @if (ViewData["isAdmin"] != null && (int)ViewData["isAdmin"] == 1) { <p>Welcome, Admin!</p> } else { <p>Welcome, User!</p> } <div class="container"> <h1> @if (ViewData["isAdmin"] != null && (int)ViewData["isAdmin"] == 1) { <h1>Welcome, Admin!</h1> } else { <h1>Welcome, User!</h1> } </h1> <div class="form-box"> <br /> <a asp-action="Index" id="list">Back to Crime List</a> <h1>CRIME ALERT</h1> <form asp-action="Create"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <div class="input-field"> <i class="fa-solid fa-user"></i> @*<label asp-for="CrimeType" class="control-label"></label>*@ <input asp-for="CrimeType" type="text" placeholder="Crime Type"> <span asp-validation-for="CrimeType" class="text-danger"></span> </div> <div class="input-field"> <i class="fa-regular fa-calendar-days"></i> @*<label asp-for="Time" class="control-label"></label>*@ <input type="datetime-local" asp-for="TimeNew" placeholder="Time"> <span asp-validation-for="TimeNew" class="text-danger"></span> </div> <br /> <div class="input-field"> <label asp-for="Gender" class="control-label"></label> <span asp-validation-for="Gender" class="text-danger"></span> <select name="Gender" asp-for="Gender" class="form-control" placeholder="Criminal-Gender"> <option value="Male">Male</option> <option value="Female">Female</option> <option value="Unknown">Unknown</option> </select> <br /> </div> <div class="input-field"> <i class="fa-solid fa-user"></i> @* <label asp-for="CrimeDescription" class="control-label"></label>*@ <input asp-for="CrimeDescription" type="text" placeholder="Describe in short"> <span asp-validation-for="CrimeDescription"></span> </div> <div class="input-field"> <i class="fa-solid fa-user"></i> @*<label asp-for="Location" class="control-label"></label>*@ <input type="text" asp-for="Location" placeholder="Location co ords" id="crimeloc"> <span asp-validation-for="Location"></span> </div> <section class="map"> <h4>Select Location on Map</h4> <div id="crime-map"> </div> <div class="btn-field"> <input type="submit" id="submit" value="Create" class="btn btn-primary" /> </div> </section> </div> </form> <div> </div> </div> </div> <!-- ... --> <!-- ... --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <script src="script.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="~/js/crimealert.js"></script> <script src="CrimeAlert.js"></script> </body> </html> @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } }
const player1 = { NOME: "Mario", VELOCIDADE: 4, MANOBRABILIDADE: 3, PODER: 3, PONTOS: 0, }; const player2 = { NOME: "Luigi", VELOCIDADE: 3, MANOBRABILIDADE: 4, PODER: 4, PONTOS: 0, }; async function rollDice() { return Math.floor(Math.random() * 6) + 1; } async function getRandomBlock() { let random = Math.random(); let result; switch (true) { case random < 0.33: result = "RETA"; break; case random < 0.66: result = "CURVA"; default: result = "CONFRONTO"; break; } return result; } async function logRollResult(characterName, block, direResult, attribute) { console.log( `${characterName} rolou um dado de ${block} ${direResult}+${attribute} = ${ direResult + attribute }` ); } async function playRaceEngine(character1, character2) { for (let round = 1; round <= 5; round++) { console.log(`Rodada ${round}`); // Sortear bloco let block = await getRandomBlock(); console.log(`Bloco: ${block}`); // Rolar os dados let diceResult1 = await rollDice(); let diceResult2 = await rollDice(); // Teste de habilidade let totalSkill1 = 0; let totalSkill2 = 0; if (block === "RETA") { totalSkill1 = diceResult1 + character1.VELOCIDADE; totalSkill2 = diceResult2 + character2.VELOCIDADE; await logRollResult( character1.NOME, "velocidade", diceResult1, character1.VELOCIDADE ); await logRollResult( character2.NOME, "velocidade", diceResult2, character2.VELOCIDADE ); } if (block === "CURVA") { totalSkill1 = diceResult1 + character1.MANOBRABILIDADE; totalSkill2 = diceResult2 + character2.MANOBRABILIDADE; await logRollResult( character1.NOME, "manobrabilidade", diceResult1, character1.MANOBRABILIDADE ); await logRollResult( character2.NOME, "manobrabilidade", diceResult2, character2.MANOBRABILIDADE ); } if (block === "CONFRONTO") { let powerResult1 = diceResult1 + character1.PODER; let powerResult2 = diceResult2 + character2.PODER; console.log(`${character1.NOME} confrontou com ${character2.NOME}`); await logRollResult( character1.NOME, "poder", diceResult1, character1.PODER ); await logRollResult( character2.NOME, "poder", diceResult2, character2.PODER ); if (powerResult1 > powerResult2 && character2.PONTOS > 0) { character2.PONTOS--; console.log( `${character1.NOME} venceu o confronto! ${character2.NOME} perdeu 1 ponto` ); } if (powerResult2 > powerResult1 && character1.PONTOS > 0) { character1.PONTOS--; console.log( `${character2.NOME} venceu o confronto! ${character1.NOME} perdeu 1 ponto` ); } console.log( powerResult2 === powerResult1 ? "Confronto empatado! Nenhum ponto foi perdido" : "" ); } // Vericar o vencedor if (totalSkill1 > totalSkill2) { console.log(`${character1.NOME} marcou um ponto`); character1.PONTOS++; } else if (totalSkill2 > totalSkill1) { console.log(`${character2.NOME} marcou um ponto`); character2.PONTOS++; } console.log( "----------------------------------------------------------------" ); } } async function declareWinner(character1, character2) { console.log("Resultado final:"); console.log(`${character1.NOME} : ${character1.PONTOS} ponto(s)`); console.log(`${character2.NOME} : ${character2.PONTOS} ponto(s)`); if (character1.PONTOS > character2.PONTOS) console.log(`\n${character1.NOME} venceu a corrida! Parabéns`); else if (character2.PONTOS > character1.PONTOS) console.log(`\n${character2.NOME} venceu a corrida! Parabéns`); else console.log("A corrida terminou em empate"); } (async function main() { console.log(`Corrida entre ${player1.NOME} e ${player2.NOME} começando...\n`); await playRaceEngine(player1, player2); await declareWinner(player1, player2); })();
import React, { useState, useMemo, useContext, useEffect } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import UpcomingSeasons from './upcoming-seasons'; import SeasonPage from './season-page'; import axios from 'axios'; import Header from '../container/header'; import SignUp from './signup'; import AccountPage from './account-page'; import Login from './login'; import { UserContext } from '../context/user-context'; import { ThemeContext} from '../context/theme-context'; import EditSummaries from './edit-summaries'; export default function App(props) { const [user, setUser] = useState(JSON.parse(window.localStorage.getItem('userData')) || null); const [seasons, setSeasons] = useState(null); const getSeasons = async () => { const response = await axios.get('api/seasons'); setSeasons(response.data.seasons); }; useEffect(() => { getSeasons(); }, []); const userProviderVal = useMemo(() => ({ user, setUser }), [user, setUser]); return ( <Router> <UserContext.Provider value={userProviderVal}> <Header /> <Switch> <Route exact path="/" render={props => <UpcomingSeasons {...props} seasons={seasons} />} /> <Route exact path="/season/:id" render={props => <SeasonPage {...props} />} /> <Route exact path="/edit/:id" render={props => <EditSummaries {...props} />} /> <Route exact path="/signup" render={props => <SignUp {...props} />} /> <Route exact path="/account" render={props => <AccountPage {...props} />} /> <Route exact path="/login" render={props => <Login {...props} />} /> </Switch> </UserContext.Provider> </Router> ); }
@extends('layouts.master') @section('title', 'Edit User') @section('content') <div class="container mt-5 mb-5"> <div class="d-md-flex justify-content-between"> <p class="fs-2 text-danger fw-bold border-bottom border-danger border-3">UPDATE USER</p> <a href="{{ url('admin/users') }}"> <button class="btn btn-danger"> Go Back </button> </a> </div> <div class="card-body"> <div class="mb-3"> <label for="">Full Name</label> <input type="text" class="form-control" value="{{ $user->name }}" readonly> </div> <div class="mb-3"> <label for="">Email Id</label> <input type="text" class="form-control" value="{{ $user->email }}"readonly> </div> <div class="mb-3"> <label for="">Created At</label> <input type="text" class="form-control" value="{{ $user->created_at->format('d/m/y') }}"readonly> </div> <form action="{{ url('admin/update-user/' . $user->id) }}" method="POST"> @csrf @method('PUT') <div class="mb-3"> <label for="">Role As</label> <select name="role_as" class="form-control"> <option value="1" {{ $user->role_as == '1' ? 'selected' : '' }}>Admin</option> <option value="0" {{ $user->role_as == '0' ? 'selected' : '' }}>User</option> <option value="2" {{ $user->role_as == '2' ? 'selected' : '' }}>Blogger</option> </select> </div> <div class="mb-3 text-end"> <button type="submit" class="btn btn-danger">Update User Role</button> </div> </form> </div> </div> @endsection
from django.test import TestCase from blog.models import Post, Comment class PostModelTest(TestCase): def setUp(self): self.post = Post.objects.create(title="Test Post", body="This is a test post.") def test_post_creation(self): self.assertTrue(isinstance(self.post, Post)) def test_post_fields(self): self.assertEqual(self.post.title, "Test Post") self.assertEqual(self.post.body, "This is a test post.") def test_post_str(self): expected_object_name = f"Post - {self.post.pk}: {self.post.title}" self.assertEqual(str(self.post), expected_object_name) class CommentModelTest(TestCase): def setUp(self): self.post = Post.objects.create(title="Test Post", body="This is a test post.") self.comment = Comment.objects.create( post=self.post, name="Tester", email="tester@example.com", body="This is a test comment.", ) def test_comment_creation(self): self.assertTrue(isinstance(self.comment, Comment)) def test_comment_fields(self): self.assertEqual(self.comment.name, "Tester") self.assertEqual(self.comment.email, "tester@example.com") self.assertEqual(self.comment.body, "This is a test comment.") def test_comment_post_relation(self): self.assertEqual(self.comment.post, self.post) def test_comment_str(self): expected_object_name = f"Comment - {self.comment.pk}: {self.comment.name}" self.assertEqual(str(self.comment), expected_object_name)
'use client' import React from 'react' import { useProductList } from './useProductList.hook' import ProductTable from './Components/ProductTable' import TitleSearch from './Components/TitleSearch' import { useRouterGuard } from '@/hook/useRouterGuard.hook' import { Button } from '@nextui-org/react' import { useRouter } from 'next/navigation' import Link from 'next/link' import { TokenConstant } from '@/types/Token.constant' import { toast } from 'react-toastify' import { useIsReviewListFilter } from './useIsReviewListFilter.hook' const page = () => { const [UserPayLoad] = useRouterGuard() const router = useRouter() const [isReviewList, isReview, SelectStatusChange] = useIsReviewListFilter() const [ ProductList, TotalListConount, setinitPageNumber, isProductListLoading, setisProductListLoading, ] = useProductList(isReview) const changeProductStaus = async ( productId: string, isShelvesShow: boolean ) => { const token = localStorage.getItem(TokenConstant) || '' const res = await fetch( `${ process.env.NEXT_PUBLIC_API_Backed }/shop/changeProductStatus?isShelvesShow=${ isShelvesShow ? 1 : 0 }&productId=${productId}`, { method: 'POST', headers: { 'Content-Type': 'application/json', authorization: token, }, } ) toast('修改成功') setisProductListLoading(true) } return ( <div> <div className="mx-auto box-border w-[95%] p-3"> <div className="flex items-center justify-between"> <Button as={Link} href="/productlist/addproductItem"> 新增菜品 </Button> <TitleSearch isReview={isReview} isReviewList={isReviewList} onSelectionChange={SelectStatusChange} /> </div> </div> <div className=" box-border max-h-[calc(100vh-80px)] flex-1 overflow-scroll p-3"> <ProductTable changeProductStaus={changeProductStaus} ProductList={ProductList} total={TotalListConount} SetPage={setinitPageNumber} isLoading={isProductListLoading} /> </div> </div> ) } export default page
package org.labkey.experiment.api; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.DataColumn; import org.labkey.api.data.DisplayColumn; import org.labkey.api.data.DisplayColumnFactory; import org.labkey.api.data.RenderContext; import org.labkey.api.query.FieldKey; import org.labkey.api.util.HtmlString; import java.util.Set; /** * Display column for fields that go through an Ancestor (Lineage) lookup via the ClosureQuery. * When an entity has more than one ancestor of a particular type the ClosureQuery value is * the negative of the number of ancestors of that type. We take advantage of this to display * a more informative message about why users don't see actual data in the column. * * This currently supports only the first level of lookups. If the data being * displayed is from a lookup that comes from another ancestor lookup, we don't * have the foreign key for the original ancestor lookup to be able to find out * if that original ancestor type had more than one value. */ public class AncestorLookupDisplayColumn extends DataColumn { private final ColumnInfo _lookupCol; private final FieldKey _lookupFK; private final DisplayColumn _dc; public AncestorLookupDisplayColumn(ColumnInfo currentCol) { this(null, currentCol, null); } public AncestorLookupDisplayColumn(@Nullable ColumnInfo lookupCol, ColumnInfo currentCol, @Nullable DisplayColumnFactory displayColumnFactory) { super(currentCol); _lookupCol = lookupCol == null ? currentCol : lookupCol; _lookupFK = lookupCol == null ? null : lookupCol.getFieldKey(); _dc = displayColumnFactory != null ? displayColumnFactory.createRenderer(currentCol) : null; } @Override public void setFormatString(String formatString) { super.setFormatString(formatString); if (_dc != null) _dc.setFormatString(formatString); } @Override public @NotNull HtmlString getFormattedHtml(RenderContext ctx) { Integer lookupKey = getLookupId(ctx); if (lookupKey != null && lookupKey < 0) return HtmlString.unsafe("<span style=\"color: gray;\"><"+ (-lookupKey) + " values></span>"); if (_dc != null) return _dc.getFormattedHtml(ctx); return super.getFormattedHtml(ctx); } @Override public Object getDisplayValue(RenderContext ctx) { Integer lookupKey = getLookupId(ctx); if (lookupKey != null && lookupKey < 0) return (-lookupKey) + " values"; if (_dc != null) return _dc.getDisplayValue(ctx); return super.getDisplayValue(ctx); } @Override @Nullable public String getFormattedText(RenderContext ctx) { Integer lookupKey = getLookupId(ctx); if (lookupKey != null && lookupKey < 0) return (-lookupKey) + " values"; if (_dc != null) return _dc.getFormattedText(ctx); return super.getFormattedText(ctx); } @Override public Object getValue(RenderContext ctx) { Integer lookupKey = getLookupId(ctx); if (lookupKey != null && lookupKey < 0) return lookupKey; Object value = null; if (_dc != null) value = _dc.getValue(ctx); if (value == null) value = super.getValue(ctx); return value; } @Override public String renderURL(RenderContext ctx) { Integer lookupKey = getLookupId(ctx); if (lookupKey != null && lookupKey < 0) return null; if (_dc != null) return _dc.renderURL(ctx); return super.renderURL(ctx); } @Override public void addQueryFieldKeys(Set<FieldKey> keys) { super.addQueryFieldKeys(keys); if (_lookupFK != null) keys.add(_lookupFK); } private Integer getLookupId(RenderContext ctx) { return (Integer) _lookupCol.getValue(ctx); } }
import React, { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import Base from "../core/Base"; import { isAutheticated } from "../auth/helper"; import { getProducts, deleteProduct } from "./helper/adminapicall"; const ManageProducts = () => { const [products, setProducts] = useState([]); const { user, authToken } = isAutheticated(); const preload = () => { getProducts().then((data) => { if (data.error) { console.log(data.error); } else { setProducts(data); } }); }; useEffect(() => { preload(); }, []); const deleteThisProduct = (productId) => { deleteProduct(user._id, authToken, productId).then((data) => { if (data.error) { console.log(data.error); } else { preload(); } }); }; const goBack = () => ( <div> <Link className="btn btn-sm btn-light formbtn" to="/admin/dashboard"> Back to Menu </Link> </div> ); const manageProductUI = () => { return ( <div className="container"> <h3 className="middlefonts">ALL PRODUCTS:</h3> <div className="row"> <div className="col-12"> <h2 className="text-center text-white my-3">Total 3 products</h2> {products.map((product, index) => { return ( <div key={index} className="row text-center mb-2 "> <div className="col-4"> <h4 className="middlefonts">{product.name}</h4> </div> <div className="col-4"> <Link className="btn btn-md btn-info formbtn" to={`/admin/product/update/${product._id}`} > <span className="">Update</span> </Link> </div> <div className="col-4"> <button onClick={() => { deleteThisProduct(product._id) }} className="btn btn-md btn-danger formbtn" > Delete </button> </div> </div> ); })} </div> </div> </div> ); }; return ( <Base> {manageProductUI()} <hr></hr> {goBack()} </Base> ); }; export default ManageProducts;
package com.score3; public class ScoreVO { //Value Object //DTO : 계층 간 데이터 교환을 하기 위해 사용하는 객체로 //DTO는 로직을 가지지 않는 순수한 데이터 객체. private String hak; //처음엔 무조건 private으로 변수 선언하기 private String name; private int kor; private int eng; private int mat; private int tot; //우회도로 만들었다. //getter/setter public String getHak() { return hak; } public void setHak(String hak) { this.hak = hak; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getKor() { return kor; } public void setKor(int kor) { this.kor = kor; } public int getEng() { return eng; } public void setEng(int eng) { this.eng = eng; } public int getMat() { return mat; } public void setMat(int mat) { this.mat = mat; } public int getTot() { return kor+eng+mat; } public void setTot(int tot) { this.tot = tot; } @Override public String toString() { if(hak==null||hak.equals("")) { return null; } String str = String.format("%5s %6s %4d %4d %4d %4d %4.1f", hak, name,kor,eng,mat,getTot(), getTot()/3.0); return str; } }
<template> <div id="big"> <div id="main"> <div id='register_page'> <el-row> <el-col :span="18"> <div id="title_setup"> <b><a href="/">SUSTech Regency</a> </b> </div> </el-col> <el-col span> <div id="icon1"> <img src="../images/hotel.png" id='hotel_img' /> </div> </el-col> </el-row> <el-scrollbar id="bar" height="62%"> <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm"> <div class="input_area"> <p class="text_area">用户名</p> <el-form-item prop="name"> <el-input class="input" size='large' v-model="ruleForm.name" autocomplete="off" placeholder="Please input"> <template #prefix> <el-icon> <User /> </el-icon> </template> </el-input> </el-form-item> </div> <div class="input_area"> <p class="text_area">邮箱</p> <el-form-item prop="mail"> <el-input class="input" size='large' v-model="ruleForm.mail" autocomplete="off" placeholder="Please input"> <template #prefix> <el-icon> <Message /> </el-icon> </template> </el-input> </el-form-item> </div> <div class="input_area" v-show="false"> <p class="text_area">手机</p> <el-form-item prop="phone"> <el-input class="input" size='large' v-model="ruleForm.phone" autocomplete="off" placeholder="Please input"> <template #prefix> <el-icon> <Iphone /> </el-icon> </template> </el-input> </el-form-item> </div> <div class="input_area"> <p class="text_area">密码</p> <el-form-item prop="password"> <el-input class="input" size='large' v-model="ruleForm.password" type="password" autocomplete="off" placeholder="Please input password"> <template #prefix> <el-icon> <Lock /> </el-icon> </template> </el-input> <span style="font-size: 1px;">包含大小写数字特殊字符,8-30位</span> </el-form-item> </div> <div class="input_area"> <p class="text_area">再次输入</p> <el-form-item prop="checkPassword"> <el-input class="input" size='large' v-model="ruleForm.checkPassword" type="password" autocomplete="off" placeholder="Please input password again"> <template #prefix> <el-icon> <Lock /> </el-icon> </template> </el-input> </el-form-item> </div> <div class="input_area" v-show=false> <p class="text_area">手机验证码</p> <el-form-item prop="verify_phone"> <el-input class="input" size='large' v-model="ruleForm.verify_phone" autocomplete="off" placeholder="Please input"> <template #prefix> <el-icon> <Iphone /> </el-icon> </template> </el-input> <!-- <el-button @click="send_phone" size="small" id="verify" type="success" round>发送验证码 --> <!-- </el-button> --> </el-form-item> </div> <div class="input_area"> <p class="text_area">邮箱验证码</p> <el-form-item prop="verify_mail"> <el-input class="input" size='large' v-model="ruleForm.verify_mail" autocomplete="off" placeholder="Please input"> <template #prefix> <el-icon> <Message /> </el-icon> </template> </el-input> <el-button :disabled="isDisabled" @click="send_mail" size="small" id="verify" type="success" round> {{ button_msg }} </el-button> </el-form-item> </div> </el-form> <div class="input_area"> <el-radio-group v-model="UserOrmerchant" class="ml-4"> <el-radio label="1" size="large">用户</el-radio> <el-radio label="2" size="large">商家</el-radio> </el-radio-group> </div> </el-scrollbar> <el-button @click="signup" id="signup_button" size="large" type="primary" round>注册</el-button> <el-link id="link_login" type="primary" href="./#/login">已有账号?点击这里</el-link> </div> <div class='page'> <!-- <img src="https://picx.zhimg.com/v2-fe2d9ef609280bad61b9be01314de881_r.jpg"> --> </div> </div> </div> </template> <style lang="scss" scoped> #big { width: 100vw; height: 106vh; background: url('../images/gray.png') 0% 0% /cover no-repeat; } #register_page { overflow: hidden; margin: 0 0; background: hsl(0, 0%, 100%); width: 38%; height: 100%; position: relative; border-radius: 25px 25px 25px 25px; box-shadow: 10px 10px 5px #888888; } #main { border-radius: 25px; position: absolute; width: 64.5%; height: 90%; top: 8%; left: 20%; display: flex; align-items: flex-start; // box-shadow: 10px 10px 5px #888888; } .page { width: 60%; height: 100%; // margin: 0 0; border-radius: 0px 25px 25px 0px; position: relative; left: -2%; box-shadow: 10px 10px 5px #888888; background: url('../images/background.png') 0% 0% / cover no-repeat; // background-image: url('../images/background.png'); } #bar { position: relative; top: 6%; } @media screen and (min-width: 950px) { .page { width: 60%; } } @media screen and (max-width: 950px) { .page { display: none; } #register_page { width: 100%; } } #title_setup { font-family: "Lucida Calligraphy", cursive, serif, sans-serif; text-indent: 30px; position: relative; font-size: 25px; top: 35px; } #signup_button { position: absolute; left: 50px; // top: 530px; top: 82%; width: 90px; } // #verify { // position: absolute; // left: 50px; // top: 480px; // width: 90px; // } #link_login { position: absolute; left: 150px; top: 84%; // width: 130px; } .input_area { // display: flex; align-items: center; justify-content: center; height: 70px; margin: 30px; // text-align: center; border-radius: 4px; // background: var(--el-color-primary-light-9); color: var(--el-color-primary); } #hotel_img { height: 50px; height: 50px; position: absolute; // top: 25px; top: 40%; // left: 290px; left: 75%; } </style> <script lang="ts" setup> import { ref, reactive } from 'vue' import { h } from 'vue' import request from '../utils/request' import { formContextKey, FormInstance } from 'element-plus' import { ElNotification } from 'element-plus' import { User, Lock, Message, Iphone } from '@element-plus/icons-vue' import axios from 'axios' import router from '../router/index' const UserOrmerchant = ref('') const ruleForm = reactive({ name: '', password: '', checkPassword: '', mail: '', phone: '', verify_mail: '', verify_phone: '' }) var IsComplete = { name: 0, password: 0, checkPassword: 0, mail: 0, phone: 0, verify_mail: 0, verify_phone: 0, user: 0 } const isDisabled = ref(false) const button_msg = ref('发送验证码') const ruleFormRef = ref<FormInstance>() const checkName = (rule: any, value: any, callback: any) => { if (value === '') { callback(new Error('Please input your name')) } else { IsComplete.name = 1; callback() } } const checkPassword = (rule: any, value: any, callback: any) => { if (value === '') { callback(new Error('Please input the password')) } else { const reg = new RegExp('(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{8,30}'); if (!reg.test(value)) { callback(new Error('Your password is too simple')) } else { IsComplete.password = 1; callback() } } } const checkPassword2 = (rule: any, value: any, callback: any) => { if (value === '') { callback(new Error('Please input the password again')) } else if (value !== ruleForm.password) { callback(new Error("Two inputs don't match!")) } else { IsComplete.checkPassword = 1; callback() } } const checkMail = (rule: any, value: any, callback: any) => { if (value === '') { callback(new Error('Please input your mail')) } else { IsComplete.mail = 1; callback() } } const checkPhone = (rule: any, value: any, callback: any) => { const reg = /^[1-9][0-9]+$/gi; if (value === '') { callback(new Error('Please input your phone number')) } else if (!reg.test(value)) { callback(new Error('Please input a number')) } else { IsComplete.phone = 1; callback() } } const checkPhone_verify = (rule: any, value: any, callback: any) => { if (value === '') { callback(new Error('Please input verification code')) } else { IsComplete.verify_phone = 1; callback() } } const checkMail_verify = (rule: any, value: any, callback: any) => { if (value === '') { callback(new Error('Please input verification code')) } else { IsComplete.verify_mail = 1; callback() } } const rules = reactive({ password: [{ validator: checkPassword, trigger: 'blur' }], checkPassword: [{ validator: checkPassword2, trigger: 'blur' }], name: [{ validator: checkName, trigger: 'blur' }], mail: [{ validator: checkMail, trigger: 'blur' }], phone: [{ validator: checkPhone, trigger: 'blur' }], verify_phone: [{ validator: checkPhone_verify, trigger: 'blur' }], verify_mail: [{ validator: checkMail_verify, trigger: 'blur' }], }) const send_mail = () => { if (ruleForm.mail != '') { request.post('/user/send-verification-code?email=' + ruleForm.mail) .then(function (response) { if (response.data.code == 200) { ElNotification({ title: 'Success', message: h('i', { style: 'color: teal' }, 'You will receive an E-mail for verification'), }) let timer = ref<number>(60) isDisabled.value = true const T = setInterval(function () { { timer.value--; button_msg.value = `${timer.value}s后重新获取`; if (timer.value == 0) { isDisabled.value = false; button_msg.value = "获取验证码"; clearInterval(T); } } }, 1000); } else { ElNotification({ title: 'Error', message: h('i', { style: 'color: red' }, response.data.message), }) } }) } else { ElNotification({ title: 'Error', message: h('i', { style: 'color: red' }, 'Please input correct email'), }) } } const signup = () => { if (UserOrmerchant.value != '' && IsComplete.name == 1 && IsComplete.password == 1 && IsComplete.checkPassword == 1 && IsComplete.mail == 1 && IsComplete.verify_mail == 1) { var id = 1; if (UserOrmerchant.value == '2') { id = 2; } request.post('/user/register', { roleId: id, email: ruleForm.mail, verificationCode: ruleForm.verify_mail, username: ruleForm.name, password: ruleForm.password, }) .then(function (response) { if (response.data.code === 200) { ElNotification({ title: 'Success', message: h('i', { style: 'color: green' }, "Register Success") }) router.push('/login') } else { ElNotification({ title: 'Fail ', message: h('i', { style: 'color: red' }, response.data.message) }) } }) } else { ElNotification({ title: 'Fail', message: h('i', { style: 'color: red' }, "Please complete your infomation") }) } } </script>
package org.solutions.usingAbstractClass; import lombok.AllArgsConstructor; import lombok.Getter; import org.solutions.singleClass.models.PenType; import org.solutions.usingStrategiesPattern.WrittingStrategy.WritingStrategy; @Getter @AllArgsConstructor public abstract class Pen { //NOTE 14: Basic Pen structure private String brand; private String name; private PenType type; private Double price; private WritingStrategy writingStrategy; // where write method is with writingStrategy public void write() { writingStrategy.write(); } }
import { useCallback, useState, useEffect, useMemo } from 'react'; import { SmartForm } from '../SmartForm'; import './styles.css'; interface FieldConfig { id: string; type: 'inputText' | 'inputEmail' | 'inputPassword'; label?: string; defaultValue?: string; required?: boolean; placeholder?: string; } export const AuthForm = () => { const fieldsConfig: FieldConfig[] = useMemo( () => [ { id: 'first_name', type: 'inputText', defaultValue: 'Ivan', placeholder: 'Введите имя', }, { id: 'last_name', type: 'inputText', defaultValue: 'Ivanov', placeholder: 'Введите фамилию ', }, { id: 'email', type: 'inputEmail', placeholder: 'Введите адрес эл. почты', required: true, }, { id: 'password', type: 'inputPassword', placeholder: 'Введите пароль', required: true, }, ], [] ); const [fieldValues, setFieldValues] = useState<{ [key: string]: string }>( () => { const initialValues = fieldsConfig.reduce((acc, field) => { if (field.defaultValue) { acc[field.id] = field.defaultValue; } return acc; }, {} as { [key: string]: string }); return initialValues; } ); const [isSubmitEnabled, setIsSubmitEnabled] = useState<boolean>(false); const [isSubmitted, setIsSubmitted] = useState<boolean>(false); const [emailIsValid, setEmailIsValid] = useState<boolean>(true); const isFormValid = ( config: FieldConfig[], values: { [key: string]: string } ) => { return config.every( (field: FieldConfig) => !field.required || !!values[field.id] ); }; const isEmailValid = (email: string) => { const re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; return re.test(email); }; useEffect(() => { if (!!fieldValues['email']) { setEmailIsValid(isEmailValid(fieldValues['email'])); } setIsSubmitEnabled(isFormValid(fieldsConfig, fieldValues) && emailIsValid); }, [fieldValues, emailIsValid, fieldsConfig]); const handleChange = useCallback((id: string, newValue: string) => { setFieldValues((prevValues) => ({ ...prevValues, [id]: newValue })); }, []); const handleSubmit = useCallback(() => { console.log('Submitted values:', fieldValues); setIsSubmitted(true); }, [fieldValues]); return ( <div className="formContainer"> {isSubmitted ? ( <> <h1 className="emoji">🙋🏻‍♀️</h1> <h1 className="title"> {`С возвращением, ${fieldValues.first_name} ${fieldValues.last_name}!`} </h1> </> ) : ( <> <h1 className="emoji">💁🏻‍♀️</h1> <h1 className="title">Авторизация</h1> <p className="subtitle"> Для доступа к личному кабинету вашей комании авторизуйтесь на сайте </p> <SmartForm config={fieldsConfig} onChange={handleChange} error={ !emailIsValid ? 'Упс, некорректный адрес эл. почты' : undefined } /> <button onClick={handleSubmit} disabled={!isSubmitEnabled} className="submit" type="submit"> Войти </button> </> )} </div> ); };
"use client" import { NavigationMenu, NavigationMenuContent, NavigationMenuItem, NavigationMenuLink, NavigationMenuList, NavigationMenuTrigger } from "@/components/ui/navigation-menu"; import { cn } from "@/lib/utils"; import React from "react"; const components: { componentName: string; item: { title: string; href: string; description: string }[] }[] = [ { componentName: "Getting started", item: [ { title: "introduction", href: "/", description: "Re-usable components built using Radix UI and Tailwind CSS." } ] }, { componentName: "Components", item: [ { title: "Alert Dialog", href: "/docs/primitives/alert-dialog", description: "A modal dialog that interrupts the user with important content and expects a response.", }, { title: "Hover Card", href: "/docs/primitives/hover-card", description: "For sighted users to preview content available behind a link.", }, { title: "Progress", href: "/docs/primitives/progress", description: "Displays an indicator showing the completion progress of a task, typically displayed as a progress bar.", }, { title: "Scroll-area", href: "/docs/primitives/scroll-area", description: "Visually or semantically separates content.", }, { title: "Tabs", href: "/docs/primitives/tabs", description: "A set of layered sections of content—known as tab panels—that are displayed one at a time.", }, { title: "Tooltip", href: "/docs/primitives/tooltip", description: "A popup that displays information related to an element when the element receives keyboard focus or the mouse hovers over it.", } ] } ] export function MainNav() { return ( <NavigationMenu className="max-lg:hidden"> <NavigationMenuList> <> { components.map((component) => ( <NavigationMenuItem key={component.componentName}> <NavigationMenuTrigger>{component.componentName}</NavigationMenuTrigger> <NavigationMenuContent> <ul className="grid w-[400px] gap-3 p-4 md:w-[500px] md:grid-cols-2 lg:w-[600px]"> <> { component.item.map(({ title, href, description }, index) => ( <ListItem key={index} title={title} href={href} > {description} </ListItem> )) } </> </ul> </NavigationMenuContent> </NavigationMenuItem> )) } </> </NavigationMenuList> </NavigationMenu> ) } const ListItem = React.forwardRef< React.ElementRef<"a">, React.ComponentPropsWithoutRef<"a"> >(({ className, title, children, ...props }, ref) => { return ( <li> <NavigationMenuLink asChild> <a ref={ref} className={cn( "block select-none space-y-1 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground", className )} {...props} > <div className="text-sm font-medium leading-none">{title}</div> <p className="line-clamp-2 text-sm leading-snug text-muted-foreground"> {children} </p> </a> </NavigationMenuLink> </li> ) }) ListItem.displayName = "ListItem"
import Web3 from "web3"; const getWeb3 = async () =>{ // Wait for loading completion to avoid race conditions with web3 injection timing. await new Promise((resolve)=>{ window.addEventListener("load", async () => { resolve() }) }) // Modern dapp browsers... if (window.ethereum) { const web3 = new Web3(window.ethereum); try { // Request account access if needed await window.ethereum.request({ method: 'eth_requestAccounts' }); // Accounts now exposed return web3; } catch (error) { return error; } } // Fallback to localhost; use dev console port by default... else { const provider = new Web3.providers.HttpProvider( "http://127.0.0.1:7545" ); const web3 = new Web3(provider); console.log("No web3 instance injected, using Local web3."); return web3; } }; export default getWeb3;
import { ShipAbiModel } from './ship-abi.types'; /** * Represents an ABI associated with a StateHistoryPlugin (SHIP). * This class holds information about the version, ABI, and last modified timestamp of the SHIP abi. * The last modified timestamp is used to track when changes to the ABI were made. * * @class */ export class ShipAbi { /** * Create a `ShipAbi` object from its JSON representation. * * @static * @param {ShipAbiModel} model - The JSON representation of the `ShipAbi` object. * @returns {ShipAbi} The created `ShipAbi` object. */ public static create(model: ShipAbiModel): ShipAbi { const { abi, version, last_modified_timestamp } = model; return new ShipAbi(abi, version, last_modified_timestamp); } /** * Create a `ShipAbi` object. * * @param {string} abi - The ABI hex. * @param {string} version - The version of the ABI. * @param {Date} lastModifiedTimestamp - The last modified timestamp of the ABI. */ constructor( public readonly abi: string, public readonly version: string, public readonly lastModifiedTimestamp: Date ) {} /** * Convert the `ShipAbi` object to its JSON representation. * * @returns {ShipAbiModel} The JSON representation of the `ShipAbi` object. */ public toJSON(): ShipAbiModel { const { abi, version, lastModifiedTimestamp: last_modified_timestamp } = this; return { abi, version, last_modified_timestamp, }; } }
<template> <ion-page> <ion-header> <ion-toolbar> <ion-title>Vorrat & Filter</ion-title> </ion-toolbar> </ion-header> <ion-content :fullscreen="true"> <ion-header collapse="condense"> <ion-toolbar> <ion-title size="large">Vorrat & Filter</ion-title> </ion-toolbar> </ion-header> <div class="eatable-content-wrapper"> <h3>Vorrat</h3> <p style="font-size:12px; line-height: 1.5em; opacity: 0.75; margin: 24px 0 48px 0;"> Bald wird es bei eatable die Möglichkeit geben, vorhandene Zutaten zu speichern. So kann man verhindern, dass Lebensmittel vergessen gehen und die Rezeptsuche lässt sich automatisch auf den eigenen Vorrat abstimmen. </p> <h3>Filter</h3> <ion-item> <ion-label>Kategorie</ion-label> <ion-select v-if="categoryFilterActive" interface="alert" multiple ok-text="filtern" cancel-text="abbrechen" placeholder="auswählen" v-model="activeRecipeCategoryIds" > <ion-select-option v-for="category in activeRecipeCategoryData" :key="category.id" :value="category.id" :selected="activeRecipeCategoryIds.includes(JSON.stringify(category.id)) ? true : null" >{{ category.title }}</ion-select-option > </ion-select> </ion-item> <ion-item> <ion-label>Ernährung</ion-label> <ion-select v-if="tagFilterActive" interface="alert" multiple ok-text="filtern" cancel-text="abbrechen" placeholder="auswählen" v-model="activeRecipeTagIds" > <ion-select-option v-for="tag in activeRecipeTagData" :key="tag.id" :value="tag.id" :selected="activeRecipeTagIds.includes(JSON.stringify(tag.id)) ? true : null" >{{ tag.title }}</ion-select-option > </ion-select> </ion-item> <!-- <h3>Partner</h3> <p v-for="partner in activeRecipePartnerData" :key="partner.id">{{ partner.title }}</p> --> <PlaceholderIndicator v-if="false" title="Diese Seite ist in Erstellung" text="Hier entsteht ein Ort, wo man sich selbst an zu verwendende Zutaten erinnern kann (und eine Art Foodwaste Tagebuch hat)." linkText="Rezepte finden" link="/kochen/rezepte" /> </div> </ion-content> <ion-footer> <ion-toolbar> <ion-button expand="block" fill="solid" routerLink="/kochen/rezepte">Rezepte finden</ion-button> </ion-toolbar> </ion-footer> </ion-page> </template> <script lang="ts"> import { defineComponent } from 'vue'; import { IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonFooter, IonButton, IonItem, IonLabel, IonSelect, IonSelectOption, } from '@ionic/vue'; import PlaceholderIndicator from '@/components/PlaceholderIndicator.vue'; import { SingleRecipePartner, SingleRecipeTag, SingleRecipeCategory } from '@/types/TaxonomyTypes'; import axios from 'axios'; import store from '@/store'; import { RecipeFilter } from '@/types/recipeTypes'; import { tblVars } from '@/variables/environmentVariables'; export default defineComponent({ name: 'KochenVorrat', components: { IonHeader, IonToolbar, IonTitle, IonContent, IonPage, IonButton, IonFooter, IonItem, IonLabel, IonSelect, IonSelectOption, PlaceholderIndicator, }, data() { return { // activeRecipePartnerIds: [1], activeRecipePartnerData: [] as Array<SingleRecipePartner>, tagFilterActive: false, activeRecipeTagIds: [] as Array<string>, activeRecipeTagData: [] as Array<SingleRecipeTag>, categoryFilterActive: false, activeRecipeCategoryIds: [] as Array<string>, activeRecipeCategoryData: [] as Array<SingleRecipeCategory>, activeRecipeFilters: { ingredientStock: { filterInclude: false, ingredients: [393, 351, 49], }, categories: [], tags: [], } as RecipeFilter, }; }, watch: { activeRecipeTagIds: { handler(newVal) { const numberArray = newVal.map((id: string) => parseInt(id)); this.activeRecipeFilters.tags = numberArray; }, }, activeRecipeCategoryIds: { handler(newVal) { const numberArray = newVal.map((id: string) => parseInt(id)); this.activeRecipeFilters.categories = numberArray; }, }, activeRecipeFilters: { handler(newVal) { this.$eatableStorage.set('recipeFilter', JSON.stringify(newVal)); store.dispatch('setFilters', newVal); }, deep: true, }, }, mounted() { this.getRecipeCategories(); this.getRecipeTags(); this.$eatableStorage .get('recipeFilter') .then(response => { if (!response) return; const recipeFilterObject = JSON.parse(response); this.activeRecipeCategoryIds = recipeFilterObject.categories.map((id: number) => id.toString()); this.activeRecipeTagIds = recipeFilterObject.tags.map((id: number) => id.toString()); }) .catch(error => { console.error(error); }); }, methods: { getRecipeTags() { axios .post(`${tblVars.baseApiUrl}/index.php`, { action: 'bigSearch', limit: `0,1000000`, orderby: 'title', searchTable: 'tags', searchColumn: 'id', sort: 'ASC', term: '', }) .then(response => { this.activeRecipeTagData = response.data; this.tagFilterActive = true; }) .catch(error => { console.error(error); }); }, getRecipeCategories() { axios .post(`${tblVars.baseApiUrl}/index.php`, { action: 'bigSearch', limit: `0,1000000`, orderby: 'title', searchTable: 'categories', searchColumn: 'id', sort: 'ASC', term: '', }) .then(response => { this.activeRecipeCategoryData = response.data; this.categoryFilterActive = true; }) .catch(error => { console.error(error); }); }, }, }); </script> <style scoped> .eatable-content-wrapper { padding: 24px 16px; } ion-footer ion-toolbar { --background: var(--ion-background-color); --border-color: transparent; box-shadow: 0px 0px 20px 20px var(--ion-background-color); } ion-item { --padding-start: 0; } </style>
@extends('recruiter.layout.layout') @section('content') <style> .invalid-feedback { display: block; width: 100%; margin-top: .25rem; font-size: 87.5%; color: #ff382b; } .form-group { margin-bottom: 25px; } </style> <div class="app-content"> <div class="side-app"> <div class="page-header"> <h4 class="page-title">Post New Job</h4> </div> <div class="row "> <div class="row row-cards"> <div class="col-md-12 "> <form class="card" action="{{ route('recruiter.createjob')}}" method="POST" enctype="multipart/form-data"> @csrf <div class="card-header"> <h3 class="card-title">Add New Job</h3> </div> @if (\Session::has('error')) <div class="alert alert-danger"> <ul> <li>{!! \Session::get('error') !!}</li> </ul> </div> @endif @if (\Session::has('success')) <div class="alert alert-success"> <ul> <li>{!! \Session::get('success') !!}</li> </ul> </div> @endif <div class="card-body"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label class="form-label">Job Description</label> <input type="text" class="form-control" value=" {{ old('job_title') }} " name="job_title" placeholder="Job Description"> @error('job_title') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-sm-6 col-md-4"> <div class="form-group"> <label class="form-label">Job Role</label> <select name="job_role" class="form-control select2" style="width: 100%"> <option value="" selected> select </option> @foreach ($positions as $item) <option value="{{ $item->id }}" @if(old('job_role')==$item->id) selected @endif > {{ $item->name }} </option> @endforeach </select> @error('job_role') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-sm-6 col-md-4"> <div class="form-group"> <label class="form-label">Industry</label> <select name="job_industry" class="form-control select2" style="width: 100%"> <option value="" selected> select </option> @foreach ($industry as $item) <option value="{{ $item->id }}" @if(old('job_industry')==$item->id) selected @endif > {{ $item->name }} </option> @endforeach </select> @error('job_industry') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-sm-6 col-md-4"> <div class="form-group"> <label class="form-label">Job Type</label> <select name="job_type" id="job_type" class="form-control"> <option value="" selected> select </option> <option value="Full Time" {{ old('job_type') == 'Full Time' ? 'selected' : '' }}> Full Time </option> <option value="Part Time" {{ old('job_type') == 'Part Time' ? 'selected' : '' }}> Part Time </option> <option value="Freelancer" {{ old('job_type') == 'Freelancer' ? 'selected' : '' }}> Freelancer </option> </select> @error('job_type') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-sm-6 col-md-6"> <div class="form-group"> <label class="form-label text-dark">Salary Min/Max(In Thousand)</label> <div class="row gutters-xs"> <div class="col-6"> <div class="input-group"> <input type="number" name="min_salary" value="{{ old('min_salary') }}" class="form-control" placeholder="Min Salary" > <div class="input-group-prepend"> <div class="input-group-text"> <i class="fa fa-inr tx-16 lh-0 op-6"></i> </div> </div> @error('min_salary') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-6"> <div class="input-group"> <input type="number" name="max_salary" value="{{ old('max_salary') }}" class="form-control" placeholder="Max Salary" > <div class="input-group-prepend"> <div class="input-group-text"> <i class="fa fa-inr tx-16 lh-0 op-6"></i> </div> </div> @error('max_salary') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-6"> <div class="form-group"> <label class="form-label text-dark">Experiance Required (Min/Max)</label> <div class="row gutters-xs"> <div class="col-6"> <select class="form-control" name="min_exp" value={{ old('min_exp')}} data-placeholder="Choose one (with searchbox)"> <option value="-1" selected>Year</option> <option value="0" {{ old('min_exp') == 0 ? 'selected' : '' }}>0 Year</option> <option value="1" {{ old('min_exp') == 1 ? 'selected' : '' }}>1 Year</option> <option value="2" {{ old('min_exp') == 2 ? 'selected' : '' }}>2 Year</option> <option value="3" {{ old('min_exp') == 3 ? 'selected' : '' }}>3 Year</option> <option value="4" {{ old('min_exp') == 4 ? 'selected' : '' }}>4 Year</option> <option value="5" {{ old('min_exp') == 5 ? 'selected' : '' }}>5 Year</option> <option value="6" {{ old('min_exp') == 6 ? 'selected' : '' }}>6 Year</option> <option value="7" {{ old('min_exp') == 7 ? 'selected' : '' }}>7 Year</option> <option value="8" {{ old('min_exp') == 8 ? 'selected' : '' }}>8 Year</option> <option value="9" {{ old('min_exp') == 9 ? 'selected' : '' }}>9 Year</option> <option value="10" {{ old('min_exp') == 10 ? 'selected' : '' }}>10 Year</option> </select> @error('min-exp') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div class="col-6"> <select class="form-control" name="max_exp" value={{old('max_exp')}} data-placeholder="Choose one (with searchbox)"> <option value="-1" selected>Year</option> <option value="1" {{ old('max_exp') == 1 ? 'selected' : '' }}>1 Year</option> <option value="2" {{ old('max_exp') == 2 ? 'selected' : '' }}>2 Year</option> <option value="3" {{ old('max_exp') == 3 ? 'selected' : '' }}>3 Year</option> <option value="4"{{ old('max_exp') == 4 ? 'selected' : '' }}>4 Year</option> <option value="5"{{ old('max_exp') == 5 ? 'selected' : '' }}>5 Year</option> <option value="6"{{ old('max_exp') == 6 ? 'selected' : '' }}>6 Year</option> <option value="7"{{ old('max_exp') == 7 ? 'selected' : '' }}>7 Year</option> <option value="8"{{ old('max_exp') == 8 ? 'selected' : '' }}>8 Year</option> <option value="9"{{ old('max_exp') == 9 ? 'selected' : '' }}>9 Year</option> <option value="10"{{ old('max_exp') == 10 ? 'selected' : '' }}>10 Year</option> <option value="11"{{ old('max_exp') == 11 ? 'selected' : '' }}>11 Year</option> <option value="12"{{ old('max_exp') == 12 ? 'selected' : '' }}>12 Year</option> <option value="13"{{ old('max_exp') == 13 ? 'selected' : '' }}>13 Year</option> <option value="14"{{ old('max_exp') == 14 ? 'selected' : '' }}>14 Year</option> <option value="15+"{{ old('max_exp') == '15+' ? 'selected' : '' }}>15+ Year</option> </select> @error('max_exp') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> </div> </div> <div class="col-md-4"> <div class="form-group"> <label class="form-label">Location</label> <select name="job_location" class="form-control select2" style="width: 100%"> <option value="" selected> select </option> @foreach ($city as $item) <option value="{{ $item->id }}" @if(old('job_location')==$item->id) selected @endif > {{ $item->name }} </option> @endforeach </select> @error('job_location') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-md-4"> <div class="form-group"> <label class="form-label">Eligibility</label> <input type="text" name="job_eligibility" value="{{ old('job_eligibility') }}" class="form-control" placeholder="Any Graduate" > @error('job_eligibility') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-md-4"> <div class="form-group"> <label class="form-label">No of Positions(Opening)</label> <input type="number" name="job_tot_positions" value="{{ old('job_tot_positions') }}" class="form-control" placeholder="Total Positions" > @error('job_tot_positions') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-md-12"> <div class="form-group mb-0"> <label class="form-label">Job Descriptions</label> <textarea class="content form-control" value="{{ old('job_desc') }}" name="job_desc" id="job_desc"></textarea> @error('job_desc') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> </div> </div> <div class="card-footer text-right"> <button type="submit" class="btn btn-primary">Create Job</button> </div> </form> </div> </div> </div> </div> </div> @endsection @section('scripts') <script src="https://cdn.ckeditor.com/4.16.0/standard/ckeditor.js"></script> <script type="text/javascript"> CKEDITOR.replace('job_desc'); CKEDITOR.instances['job_desc'].updateElement(); </script> @endsection
from typing import TypeVar, Generic, List T = TypeVar('T') class Stack(Generic[T]): def __init__(self) -> None: self._container: List[T] = [] def push(self, item: T) -> None: self._container.append(item) def pop(self) -> T: return self._container.pop() @property def empty(self) -> bool: return not self._container def __repr__(self): return repr(self._container)
import 'package:flutter/material.dart'; import 'package:mgramseva/model/transaction/update_transaction.dart'; import 'package:mgramseva/model/success_handler.dart'; import 'package:mgramseva/providers/transaction_update_provider.dart'; import 'package:mgramseva/utils/constants/i18_key_constants.dart'; import 'package:mgramseva/widgets/no_login_success_page.dart'; import 'package:provider/provider.dart'; import '../../model/localization/language.dart'; import '../../providers/language.dart'; import '../../routers/routers.dart'; import '../../utils/localization/application_localizations.dart'; import '../../utils/loaders.dart'; import '../../utils/notifiers.dart'; import '../../widgets/no_login_failure_page.dart'; class PaymentSuccess extends StatefulWidget { final Map<String, dynamic> query; PaymentSuccess({Key? key, required this.query}); @override State<StatefulWidget> createState() { return _PaymentSuccessState(); } } class _PaymentSuccessState extends State<PaymentSuccess> { List<StateInfo>? stateList; Languages? selectedLanguage; @override void initState() { WidgetsBinding.instance.addPostFrameCallback((_) => afterViewBuild()); super.initState(); } afterViewBuild() async { var transactionUpdateProvider = Provider.of<TransactionUpdateProvider>(context, listen: false); var languageProvider = Provider.of<LanguageProvider>(context, listen: false); await languageProvider .getLocalizationData(context) .then((value) => callNotifyer()); await transactionUpdateProvider .updateTransaction(widget.query, context) .then((value) => callNotifyer()); } @override Widget build(BuildContext context) { var transactionProvider = Provider.of<TransactionUpdateProvider>(context, listen: false); var languageProvider = Provider.of<LanguageProvider>(context, listen: false); UpdateTransactionDetails? transactionDetails; return Scaffold( appBar: AppBar( titleSpacing: 0, title: Text('mGramSeva'), automaticallyImplyLeading: false, ), body: StreamBuilder( stream: languageProvider.streamController.stream, builder: (context, AsyncSnapshot languageSnapshot) { if (languageSnapshot.hasData) { var stateData = languageSnapshot.data as List<StateInfo>; stateList = stateData; var index = stateData.first.languages ?.indexWhere((element) => element.isSelected); if (index != null && index != -1) { selectedLanguage = stateData.first.languages?[index]; } else { selectedLanguage = stateData.first.languages?.first; } return StreamBuilder( stream: transactionProvider.transactionController.stream, builder: (context, AsyncSnapshot snapshot) { if (snapshot.hasData) { transactionDetails = snapshot.data; return _buildPaymentSuccessPage(snapshot.data, context); } else if (snapshot.hasError) { return Notifiers.networkErrorPage( context, () => transactionProvider.updateTransaction( widget.query, context)); } else { switch (snapshot.connectionState) { case ConnectionState.waiting: return Loaders.circularLoader(); case ConnectionState.active: return Loaders.circularLoader(); default: return Container(); } } }); } else if (languageSnapshot.hasError) { return Notifiers.networkErrorPage( context, () => languageProvider.getLocalizationData(context)); } else { switch (languageSnapshot.connectionState) { case ConnectionState.waiting: return Loaders.circularLoader(); case ConnectionState.active: return Loaders.circularLoader(); default: return Container(); } } }), ); } Widget _buildPaymentSuccessPage( UpdateTransactionDetails transactionObject, BuildContext context) { var transactionProvider = Provider.of<TransactionUpdateProvider>(context, listen: false); return transactionObject.transaction?.first.txnStatus != "FAILURE" ? NoLoginSuccess( SuccessHandler( i18.common.PAYMENT_COMPLETE, '${ApplicationLocalizations.of(context).translate(i18.payment.RECEIPT_REFERENCE_WITH_MOBILE_NUMBER)} (+91 ${transactionObject.transaction?.first.user?.mobileNumber})', '', Routes.PAYMENT_SUCCESS, subHeader: '${ApplicationLocalizations.of(context).translate(i18.payment.TRANSACTION_ID)} \n ${widget.query['eg_pg_txnid']}', downloadLink: i18.common.RECEIPT_DOWNLOAD, whatsAppShare: i18.common.SHARE_RECEIPTS, downloadLinkLabel: i18.common.RECEIPT_DOWNLOAD, subtitleFun: () => getSubtitleDynamicLocalization( context, transactionObject.transaction!.first.user!.mobileNumber .toString()), ), callBackDownload: () => transactionProvider.downloadOrShareReceiptWithoutLogin( context, transactionObject, false), callBackWhatsApp: () => transactionProvider.downloadOrShareReceiptWithoutLogin( context, transactionObject, true), backButton: false, isWithoutLogin: true, isConsumer: true, amount: '${transactionObject.transaction!.first.txnAmount! ?? '0'}', ) : NoLoginFailurePage(i18.payment.PAYMENT_FAILED); } callNotifyer() async { await Future.delayed(Duration(seconds: 2)); } Widget _buildDropDown() { return Padding( padding: const EdgeInsets.symmetric(horizontal: 5), child: DropdownButton( value: selectedLanguage != null ? selectedLanguage : Languages(label: 'ENGLISH', value: 'en_IN', isSelected: true), style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 16), items: dropDownItems, onChanged: onChangeOfLanguage), ); } get dropDownItems { return stateList?.first.languages!.map((value) { return DropdownMenuItem( value: value, child: Text('${value.label}'), ); }).toList(); } void onChangeOfLanguage(value) { selectedLanguage = value; var languageProvider = Provider.of<LanguageProvider>(context, listen: false); languageProvider.onSelectionOfLanguage( value!, stateList?.first.languages ?? []); } String getSubtitleDynamicLocalization( BuildContext context, String mobileNumber) { String localizationText = ''; localizationText = '${ApplicationLocalizations.of(context).translate(i18.payment.RECEIPT_REFERENCE_WITH_MOBILE_NUMBER)}'; localizationText = localizationText.replaceFirst('{Number}', '(+91 - $mobileNumber)'); return localizationText; } }
# coding=utf-8 # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # pylint: disable=logging-format-interpolation # pylint: disable=unused-import # pylint: disable=g-direct-tensorflow-import # pylint: disable=protected-access r"""Models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from npu_bridge.npu_init import * import sys from absl import logging import numpy as np import tensorflow.compat.v1 as tf import modeling_utils as ops class ResNet50(object): """Bottleneck ResNet.""" def __init__(self, data_format, name='', include_top=True, pooling=None, block3_strides=False, average_pooling=True, classes=1000, gem_power=3.0, embedding_layer=False, embedding_layer_dim=2048): self.name = name self.data_format = data_format valid_channel_values = ('channels_first', 'channels_last') if data_format not in valid_channel_values: raise ValueError('Unknown data_format: %s. Valid values: %s' % (data_format, valid_channel_values)) self.include_top = include_top self.block3_strides = block3_strides self.average_pooling = average_pooling self.pooling = pooling self.embedding_layer_dim = embedding_layer_dim logging.info(f'Build `resnet-50` under scope `{self.name}`') def build__call(self, x, training=True, intermediates_dict=None): """Building the ResNet50 model. Args: x: Images to compute features for. training: Whether model is in training phase. intermediates_dict: `None` or dictionary. If not None, accumulate feature maps from intermediate blocks into the dictionary. "" Returns: Tensor with featuremap. """ def _block_fn(inputs, num_out_filters, stride, name): return ops.resnet_block(inputs, num_out_filters=num_out_filters, stride=stride, training=training, name=name) with tf.variable_scope(self.name, reuse=tf.AUTO_REUSE): x = ops.conv2d(x, 7, 64, 2, data_format=self.data_format, padding='SAME', name='conv1') x = ops.batch_norm(x, training, name='bn_conv1') x = ops.relu(x, leaky=0.) if intermediates_dict is not None: intermediates_dict['block0'] = x x = ops.max_pool(x, 3, 2, data_format=self.data_format) if intermediates_dict is not None: intermediates_dict['block0mp'] = x # Block 1 (equivalent to "conv2" in Resnet paper). x = _block_fn(x, 256, 1, name='block1_a') x = _block_fn(x, 256, 1, name='block1_b') x = _block_fn(x, 256, 1, name='block1_c') if intermediates_dict is not None: intermediates_dict['block1'] = x # Block 2 (equivalent to "conv3" in Resnet paper). x = _block_fn(x, 512, 2, name='block2_a') x = _block_fn(x, 512, 1, name='block2_b') x = _block_fn(x, 512, 1, name='block2_c') x = _block_fn(x, 512, 1, name='block2_d') if intermediates_dict is not None: intermediates_dict['block2'] = x # Block 3 (equivalent to "conv4" in Resnet paper). x = _block_fn(x, 1024, 2, name='block3_a') x = _block_fn(x, 1024, 1, name='block3_b') x = _block_fn(x, 1024, 1, name='block3_c') x = _block_fn(x, 1024, 1, name='block3_d') x = _block_fn(x, 1024, 1, name='block3_e') x = _block_fn(x, 1024, 1, name='block3_f') if self.block3_strides: ### x = self.subsampling_layer(x) x = ops.max_pool(x, 1, 2, data_format=self.data_format) if intermediates_dict is not None: intermediates_dict['block3'] = x x = _block_fn(x, 2048, 1, name='block_a') else: if intermediates_dict is not None: intermediates_dict['block3'] = x x = _block_fn(x, 2048, 2, name='block_a') x = _block_fn(x, 2048, 1, name='block_b') x = _block_fn(x, 2048, 1, name='block_c') if self.average_pooling: x = ops.avg_pool(x, 7, 7, data_format=self.data_format) if intermediates_dict is not None: intermediates_dict['block4'] = x else: if intermediates_dict is not None: intermediates_dict['block4'] = x x = tf.reduce_mean(x, axis=[1, 2], name='global_avg_pool') # x = ops.dropout(x, params.dense_dropout_rate, training) # x = ops.dense(x, self.embedding_layer_dim) # embedding_layer is false # x = tf.cast(x, dtype=tf.float32, name='logits') return x
# get start 简单介绍 lua的环境安装推荐用官网上推荐的源码编译方式 ## chunk lua中的chunk,就是代码块,可以小到一条语句, 也可以大到一个文件,几MB很正常 lua -i xxx,表示先执行xxx chunk,再进入交互模式; 除此之外,还有一种导入chunk的方式:dofile ## 词法约定 * 标识符(名字)是字符串,由数字字母下划线组合, 不能以数字开头,和c++的变量名类似, 系统保留的是_开头,后接大写字母,最好不要自己用 * --开头表示单行注释; --[[ 开头]]结尾 表示多行注释; ---[[ 不符合多行注释语法,只符合单行注释的语法; * 在多条语句中不需要分隔符,也可以用分号分割 ## 全局变量 未初始化变量的值是nil ## 类型和值
/** @jsx jsx */ import { Component, memo } from 'react'; import { withRouter, Route, Link } from 'react-router-dom'; import PropToggle from 'react-prop-toggle'; import styled from '@emotion/styled'; import { jsx } from '@emotion/core'; import { ChevronLeftIcon, ChevronRightIcon } from '@arch-ui/icons'; import { colors, gridSize } from '@arch-ui/theme'; import { PrimaryNav, PrimaryNavItem, PrimaryNavScrollArea, PRIMARY_NAV_GUTTER, } from '@arch-ui/navbar'; import { Title } from '@arch-ui/typography'; import Tooltip from '@arch-ui/tooltip'; import { FlexGroup } from '@arch-ui/layout'; import { useAdminMeta } from '../../providers/AdminMeta'; import ResizeHandler, { KEYBOARD_SHORTCUT } from './ResizeHandler'; import { NavIcons } from './NavIcons'; import ScrollQuery from '../ScrollQuery'; const TRANSITION_DURATION = '220ms'; function camelToKebab(string) { return string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); } const Col = styled.div({ alignItems: 'flex-start', display: 'flex', flex: 1, flexFlow: 'column nowrap', justifyContent: 'flex-start', overflow: 'hidden', width: '100%', }); const Inner = styled(Col)({ height: ' 100vh', }); const Page = styled.div({ flex: 1, minHeight: '100vh', position: 'relative', }); const PageWrapper = styled.div({ display: 'flex', }); const Relative = styled(Col)({ height: ' 100%', position: 'relative', }); const GrabHandle = styled.div({ background: `linear-gradient(to left, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0))`, // drop-shadow bottom: 0, cursor: 'col-resize', position: 'absolute', right: 0, top: 0, opacity: 0.6, transition: 'opacity 220ms linear', width: 3, ':hover, :active': { opacity: 1, transitionDelay: '100ms', // avoid inadvertent mouse passes }, // hairline ':after': { background: `rgba(0, 0, 0, 0.125)`, bottom: 0, content: '" "', pointerEvents: 'none', position: 'absolute', top: 0, right: 0, width: 1, }, // increase hit-area ':before': { bottom: -gridSize, content: '" "', left: -gridSize, position: 'absolute', right: -gridSize, top: -gridSize, }, }); const CollapseExpand = styled.button(({ isCollapsed, isVisible }) => { const SIZE = isCollapsed ? 48 : 24; const GUTTER = isCollapsed ? 12 : 24; const boxShadow = isCollapsed ? '0 2px 4px 1px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.1)' : '0 1px 3px 1px rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.06)'; return { alignItems: 'center', background: 'white', border: 0, borderRadius: '50%', boxShadow, color: colors.N60, cursor: 'pointer', display: 'flex', height: SIZE, justifyContent: 'center', right: -SIZE / 2, opacity: isVisible ? 1 : 0, outline: 0, padding: 0, position: 'absolute', transition: ` opacity ${TRANSITION_DURATION}, right ${TRANSITION_DURATION}, transform 50ms, visibility ${TRANSITION_DURATION} `, visibility: isVisible ? 'visible' : 'hidden', width: SIZE, top: GUTTER, '> svg': { position: 'relative', right: isCollapsed ? -9 : 1, transition: `right ${TRANSITION_DURATION}`, }, ':hover': { transform: 'scale(1.12)', }, ':active': { transform: 'scale(1)', }, }; }); const TooltipContent = ({ kbd, children }) => ( <FlexGroup align="center" growIndexes={[0]}> <span key="children">{children}</span> <kbd key="kbd" css={{ backgroundColor: 'rgba(255, 255, 255, 0.2)', borderRadius: 2, display: 'inline-block', fontWeight: 'bold', height: 14, lineHeight: 1, paddingBottom: 1, paddingLeft: 4, paddingRight: 4, }} > {kbd} </kbd> </FlexGroup> ); function getPath(str) { const arr = str.split('/'); return `/${arr[1]}/${arr[2]}`; } function PrimaryNavItems() { let { adminPath, getListByKey, sortListsAlphabetically, listKeys: _listKeys } = useAdminMeta(); const listKeys = sortListsAlphabetically ? [..._listKeys].sort() : _listKeys; return ( <Relative> <Route> {({ location }) => ( <ScrollQuery isPassive={false}> {(ref, snapshot) => ( <PrimaryNavScrollArea ref={ref} {...snapshot}> <PrimaryNavItem to={adminPath} isSelected={location.pathname === adminPath}> Dashboard </PrimaryNavItem> {listKeys.map(key => { const list = getListByKey(key); let href = `${adminPath}/${list.path}`; const path = getPath(location.pathname); const isSelected = href === path; const maybeSearchParam = list.getPersistedSearch(); if (maybeSearchParam) { href += maybeSearchParam; } return ( <PrimaryNavItem key={key} id={`ks-nav-${list.path}`} isSelected={isSelected} to={href} > {list.label} </PrimaryNavItem> ); })} </PrimaryNavScrollArea> )} </ScrollQuery> )} </Route> </Relative> ); } let PrimaryNavContent = memo( function PrimaryContent() { let { adminPath, name } = useAdminMeta(); return ( <Inner> <Title as={Link} to={adminPath} margin="both" crop css={{ color: colors.N90, textDecoration: 'none', alignSelf: 'stretch', marginLeft: PRIMARY_NAV_GUTTER, marginRight: PRIMARY_NAV_GUTTER, }} > {name} </Title> <PrimaryNavItems /> <NavIcons /> </Inner> ); }, () => true ); class Nav extends Component { state = { mouseIsOverNav: false }; handleMouseEnter = () => { this.setState({ mouseIsOverNav: true }); }; handleMouseLeave = () => { this.setState({ mouseIsOverNav: false }); }; render() { const { children } = this.props; const { mouseIsOverNav } = this.state; return ( <ResizeHandler> {(resizeProps, clickProps, { isCollapsed, isDragging, width }) => { const navWidth = isCollapsed ? 0 : width; const makeResizeStyles = key => { const pointers = isDragging ? { pointerEvents: 'none' } : null; const transitions = isDragging ? null : { transition: `${camelToKebab( key )} ${TRANSITION_DURATION} cubic-bezier(0.25, 0, 0, 1)`, }; return { [key]: navWidth, ...pointers, ...transitions }; }; return ( <PageWrapper> <PropToggle isActive={isDragging} styles={{ cursor: 'col-resize', '-moz-user-select': 'none', '-ms-user-select': 'none', '-webkit-user-select': 'none', 'user-select': 'none', }} /> <PrimaryNav onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} style={makeResizeStyles('width')} > <PrimaryNavContent /> {isCollapsed ? null : <GrabHandle {...resizeProps} />} <Tooltip content={ <TooltipContent kbd={KEYBOARD_SHORTCUT}> {isCollapsed ? 'Click to Expand' : 'Click to Collapse'} </TooltipContent> } placement="right" hideOnMouseDown hideOnKeyDown delay={600} > {ref => ( <CollapseExpand {...clickProps} ref={ref} isCollapsed={isCollapsed} isVisible={isCollapsed || mouseIsOverNav} > {isCollapsed ? <ChevronRightIcon /> : <ChevronLeftIcon />} </CollapseExpand> )} </Tooltip> </PrimaryNav> <Page style={makeResizeStyles('marginLeft')}>{children}</Page> </PageWrapper> ); }} </ResizeHandler> ); } } export default withRouter(Nav);
package main import ( "fmt" "sort" ) //LeetCode 49. 字母异位词分组 //给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 //字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。 //示例 1: //输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"] //输出: [["bat"],["nat","tan"],["ate","eat","tea"]] // 方法一:排序-官方-手写下,推荐 // 由于互为字母异位词的两个字符串包含的字母相同,因此对两个字符串分别进行排序之后得到的字符串一定是相同的, // 故可以将排序之后的字符串作为哈希表的键。 // 时间复杂度:O(nklogk),其中 n 是 strs 中的字符串的数量,k 是 strs 中的字符串的的最大长度。需要遍历 n 个字符串, // 对于每个字符串,需要 O(klogk) 的时间进行排序以及 O(1) 的时间更新哈希表,因此总时间复杂度是 O(nklogk)。 // 空间复杂度:O(nk),其中 n 是 strs 中的字符串的数量,k 是 strs 中的字符串的的最大长度。需要用哈希表存储全部字符串。 func groupAnagrams1(strs []string) [][]string { mp := map[string][]string{} for _, str := range strs { s := []byte(str) sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) sortedStr := string(s) mp[sortedStr] = append(mp[sortedStr], str) } ans := make([][]string, 0, len(mp)) for _, v := range mp { ans = append(ans, v) } return ans } // 方法2:计数-官方-手写下-todo // 时间复杂度:O(n(k+∣Σ∣)),其中 n 是 strs 中的字符串的数量,k 是 strs 中的字符串的的最大长度,Σ 是字符集, // 在本题中字符集为所有小写字母,∣Σ∣=26。需要遍历 n 个字符串,对于每个字符串,需要 O(k) 的时间计算每个字母出现的次数, // O(∣Σ∣) 的时间生成哈希表的键,以及 O(1) 的时间更新哈希表,因此总时间复杂度是 O(n(k+∣Σ∣))。 // 空间复杂度:O(n(k+∣Σ∣)),其中 n 是 strs 中的字符串的数量,k 是 strs 中的字符串的最大长度,Σ 是字符集, // 在本题中字符集为所有小写字母,∣Σ∣=26。需要用哈希表存储全部字符串,而记录每个字符串中每个字母出现次数的数组需要的空间 // 为 O(∣Σ∣),在渐进意义下小于 O(n(k+∣Σ∣)),可以忽略不计。 func groupAnagrams(strs []string) [][]string { mp := map[[26]int][]string{} for _, str := range strs { cnt := [26]int{} for _, b := range str { cnt[b-'a']++ } mp[cnt] = append(mp[cnt], str) } ans := make([][]string, 0, len(mp)) for _, v := range mp { ans = append(ans, v) } return ans } func main() { scoreMap := map[string]int{} scoreMap["张三"] = 90 scoreMap["张"] = 90 fmt.Println(scoreMap) }
//Class Declarations Example: Re-declaring Class //A class can be declared once only. If we try to declare class more than one time, it throws an error. //Declaring class class Employee { //Initializing an object constructor(id,name) { this.id=id; this.name=name; } detail() { console.log(this.id+" "+this.name+"<br>") } } //passing object to a variable var e1=new Employee(101,"Martin Roy"); var e2=new Employee(102,"Duke William"); e1.detail(); //calling method e2.detail(); //Re-declaring class class Employee { }