text
stringlengths
184
4.48M
// define thông tin thiết bị trên Blynk #define BLYNK_TEMPLATE_ID "TMPLx-1agVFX" #define BLYNK_DEVICE_NAME "IoT 2" #define BLYNK_AUTH_TOKEN "VgNLc70ijF50ZGIvPHmEdmhstFbxxSmn" // Comment this out to disable prints and save space #define BLYNK_PRINT Serial #include <ESP8266WiFi.h> #include <BlynkSimpleEsp8266.h> #include <string.h> #include "DHT.h" #include <LiquidCrystal_I2C.h> #include <Wire.h> // Set the LCD address to 0x27 for a 16 chars and 2 line display LiquidCrystal_I2C lcd(0x27, 16, 2); char ssid[] = "realme5Pro"; // Tên wifi char pass[] = "00000001"; // Mật khẩu wifi char auth[] = "VgNLc70ijF50ZGIvPHmEdmhstFbxxSmn"; // Mã người dùng trên Blynk #define SR505_1 14 //D5 #define SR505_2 12 //D6 #define DHTPIN 13 //D7 #define OUTPUT_ON 5 //D1 #define OUTPUT_OFF 4 //D2 #define OUTPUT_TANG 0 //D3 #define OUTPUT_GIAM 2 //D4 #define LCD_SDA 9 #define LCD_SCL 10 #define DHTTYPE DHT22 // DHT 22 (AM2302) #define STEP 5000 // Thời gian lấy mẫu nhiệt độ #define TEMPERATURE 30 // Nhiệt độ làm mốc để bật tắt điều hòa DHT dht(DHTPIN, DHTTYPE); int TT_SR505_1 = 0; // Trạng thái trước của cảm biến 1 int TT_SR505_2 = 0; // Trạng thái trước của cảm biến 2 int so_nguoi = 0; // số lượn người trong phòng int so_nguoi_truoc = 0; // lưu số người có trong phòng trong lần lấy mẫu trước int TT_dieu_hoa = 0; // Trạng thái điều hòa (0- off, 1- on) int NhietDoDieuHoa = 27; // Nhiệt độ đang có trong điều hòa unsigned long tt_time=0; // Thời điểm lấy mẫu lần trước để tính toán lần lấy mẫu tiếp theo unsigned long tt_time1=0; // Thời điểm lấy mẫu nhiệt độ lần trước để tính toán lần lấy mẫu tiếp theo int tbn_system = 0; // Lấy dữ liệu điều kiển từ Blynk, 1- cho phép điều kiển, 0- tắt hệ thống điều kiển và tắt điều hòa nếu nó đang bật int TT_tbn_system = 0; // Lưu trạng thái của tbn_system trong vòng lặp trước (dùng để lấy xung lên) int t1 =35; // Tạo nhiệt độ ảo để thực hiện test hệ thống (khi triển khai sẽ xóa đi và thay bằng nhiệt độ đo được) void setup() { Serial.begin(9600); Wire.begin(LCD_SDA, LCD_SCL); // Setup chân nối LCD lcd.init(); // Bắt đầu màn hình LCD lcd.backlight(); // Bật đèn nền màn hình LCD lcd.home(); // Đưa con trỏ màn hình về vị trí 0,0 lcd.print("Connecting!!!"); // Hiển thị trạng thái đợi kết nối Blynk.begin(auth, ssid, pass); // Kết nối với wifi và Blynk bằng các thông tin define ở trên Serial.println("connected"); dht.begin(); // Setup cảm biến nhiệt độ, độ ẩm DHT // setup chân nối ESP8266 pinMode(SR505_1, INPUT); pinMode(SR505_2, INPUT); pinMode(OUTPUT_ON, OUTPUT); pinMode(OUTPUT_OFF, OUTPUT); pinMode(OUTPUT_TANG, OUTPUT); pinMode(OUTPUT_GIAM, OUTPUT); so_nguoi = 0; so_nguoi_truoc = 0; TT_dieu_hoa = 0; NhietDoDieuHoa = 28; tt_time=0; tt_time1=0; // Hiển thị form màn hình lcd.home(); // Đưa con trỏ đến cột 0 hàng 0 lcd.print("ND:00*C SN:0"); lcd.setCursor(0,1); // Đưa con trỏ đến cột 1 hàng 2 lcd.print("DA:00% DX:28*C"); lcd.display(); // Hiển thị lên màn hình. } BLYNK_WRITE(V0) { tbn_system = param.asInt(); } void loop() { Blynk.run(); // Người đi vào phòng // Nếu cảm biến 1 có xung lên và cảm biến 2 nhận giá trị 0 thì đang có người vào if (digitalRead(SR505_1) == HIGH && TT_SR505_1 == 0 && digitalRead(SR505_2) == LOW) { so_nguoi++; Blynk.virtualWrite(V5, so_nguoi); writeSoNguoi(so_nguoi); } // Người đi ra khỏi phòng // Nếu cảm biến 2 có xung lên và cảm biến 1 nhận giá trị 0 thì đang có người ra if (digitalRead(SR505_2) == HIGH && TT_SR505_2 == 0 && digitalRead(SR505_1) == LOW) { if(so_nguoi >0) so_nguoi--; // Tránh lỗi số người âm Blynk.virtualWrite(V5, so_nguoi); writeSoNguoi(so_nguoi); } // Update lại các trạng thái trước của cảm biến chuyển động TT_SR505_2 = digitalRead(SR505_2); TT_SR505_1 = digitalRead(SR505_1); if(millis()- tt_time1 >= STEP || millis()< tt_time1){ // Xác định lần lấy mẫu tiếp float h = dht.readHumidity(); // Đọc độ ẩm từ cảm biến float t = dht.readTemperature(); if (isnan(h) || isnan(t)) { // Kiểm tra null của nhiệt độ và độ ẩm Serial.println("Failed to read from DHT sensor!"); return; } Blynk.virtualWrite(V3, t); // Gửi độ ẩm lên Blynk writeTemperature(t); // In ra màn hình LCD Blynk.virtualWrite(V4, h); writeHumidity(h); tt_time1 = millis(); // Cập nhật lại thời gian lấy mẫu } Serial.print(digitalRead(SR505_2)); Serial.print(" "); Serial.print(digitalRead(SR505_1)); Serial.print(" "); Serial.print(so_nguoi); Serial.print(" "); Serial.print(TT_dieu_hoa); Serial.print(" "); Serial.print(NhietDoDieuHoa); Serial.print("\n"); if(tbn_system==1){ // Kiểm tra hệ thống có đang bật? if(millis()- tt_time >= STEP || millis()< tt_time){ // Xác định đã đến lần lấy mẫu tiếp theo chưa if(TT_dieu_hoa == 0){ // Kiểm tra trạng thái điều hòa if(t1>= TEMPERATURE && so_nguoi>0){ // Nếu điều kiện thỏa mãn thì bật điều hòa (t1 là nhiệt độ test) write_pulse(OUTPUT_ON); TT_dieu_hoa=1; } }else{ // Nếu điều hòa đã bật if(so_nguoi==0){ // Nếu không có ai if(so_nguoi_truoc==0){ // Và lần lấy mẫu trước cũng không có ai write_pulse(OUTPUT_OFF); // Thì tắt điều hòa TT_dieu_hoa=0; } }else{ // Nếu có người if(so_nguoi <3){ // Và số người ít hơn 3 // Điều chỉnh nhiệt độ về mốc 28*C if(NhietDoDieuHoa<28){ write_pulse(OUTPUT_TANG); NhietDoDieuHoa++; } if(NhietDoDieuHoa>28){ write_pulse(OUTPUT_GIAM); NhietDoDieuHoa--; } }else{ if(so_nguoi<5){ // Nếu số người lớn hơn bằng 3 và nhỏ hơn 5 // Điều chỉnh nhiệt độ về mốc 26*C if(NhietDoDieuHoa<26){ write_pulse(OUTPUT_TANG); NhietDoDieuHoa++; } if(NhietDoDieuHoa>26){ write_pulse(OUTPUT_GIAM); NhietDoDieuHoa--; } }else{ // Nếu số người >5 // Điều chỉnh nhiệt độ về mốc 24*C if(NhietDoDieuHoa>24){ write_pulse(OUTPUT_GIAM); NhietDoDieuHoa--; } if(NhietDoDieuHoa<24){ write_pulse(OUTPUT_TANG); NhietDoDieuHoa++; } } } } } so_nguoi_truoc = so_nguoi; // Update lại số người trước khi sang step mới tt_time = millis(); // Update lại thời gian step trước // Đẩy thông tin lên Blynk Blynk.virtualWrite(V1, TT_dieu_hoa); Blynk.virtualWrite(V2, NhietDoDieuHoa); writeNhietDoDieuHoa(NhietDoDieuHoa); } }else{ // Nếu hệ thống tắt if(TT_tbn_system==1){ // Và Trạng thái trước của hệ thống điều kiển là bật // Tắt điều hòa và update dữ liệu trên Blynk write_pulse(OUTPUT_OFF); TT_dieu_hoa=0; Blynk.virtualWrite(V1, TT_dieu_hoa); } } TT_tbn_system=tbn_system; // Lưu trạng thái trước của hệ thống điều kiển } void write_pulse(int pin){ // Hàm tạo xung điều khiển digitalWrite(pin, HIGH); delay(50); digitalWrite(pin, LOW); return; } void writeTemperature(float t){ // Cập nhật nhiệt độ lên LCD lcd.setCursor(3,0); lcd.print(round(t)); } void writeHumidity(float h){ // Cập nhật độ ẩm lên LCD lcd.setCursor(3,1); lcd.print(round(h)); } void writeSoNguoi(int sn){ // Cập nhật số người lên LCD lcd.setCursor(12,0); lcd.print(sn); } void writeNhietDoDieuHoa(int nddh){ // Cập nhật nhiệt độ điều hòa lên LCD lcd.setCursor(12,1); lcd.print(nddh); }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Music Player</title> <script src="https://kit.fontawesome.com/36a013a039.js" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="Assets/CSS/style1.css"> <link rel="shortcut icon" type="image/x-icon" href="Assets/Favicon.jpg"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body>̆ <!-- Top Row --> <div id="top-row"> <!-- Website Logo --> <div id="website-logo" class="inline-elements"> <span id="website-logo-image"> <i class="fas fa-compact-disc"></i> </span> <span id="website-logo-top-heading"> Sangeet </span> <span id="website-logo-bottom-heading"> Studio </span> </div> <!-- Favourites --> <div id="favourites" class="inline-elements"> <span id="favourites-text"> Favourites </span> <span id="favourites-replace"> <i class="fas fa-heart"></i> </span> </div> <!-- Search Box --> <div id="search-box" class="inline-elements"> <span id="search-icon"> <i class="fas fa-search"></i> </span> <span id="search-text"> <form> <input type="search-text" name="" placeholder="Search" id="search-text-input"> </form> </span> <span id="search-mic"> <i class="fas fa-microphone"></i> </span> </div> <!-- Notification --> <div id="notification-logo" class="inline-elements"> <i class="fas fa-bell"></i> <span id="notification-dot"></span> </div> <!-- Account Picture --> <div id="Account-Picture" class="inline-elements"> <img src="Assets/MY PIC.jpg" alt="Account-Picture"> </div> </div> <!-- Main Content --> <main> <content> <!-- Highlight --> <div id="highlight-section"> <div class="highlight-content" id="highlight-content1"> <img src="Assets/PLAY DATE.png" alt="Play Date"> </div> <div class="highlight-content" id="highlight-content2"> <img src="Assets/WOH DIN.png" alt="Woh Din"> </div> <div class="highlight-content" id="highlight-content3"> <img src="Assets/HOLD ON.png" alt="Hold On"> </div> </div> <!-- Latest Release --> <div id="latest-release-section"> <!-- Heading --> <div id="latest-release-section-heading" class="section-heading"> Latest Release </div> <div id="latest-right-arrow"> Swipe <i class="fas fa-angle-double-right"></i> </div> <div id="latest-release-content-main-div"> <!-- Latest Release Content --> <div id="latest-release-content-div"> <div id="latest-release-content1" class="latest-release-content"> <div class="latest-release-content-img"> <img src="Assets/HOLD ON.png" alt="Hold On"> </div> <div class="inline-elements"> <div class="latest-release-song-name"> HOLD ON </div> <div class="latest-release-song-date"> AUG 11,2021 </div> </div> <div class="inline-elements"> <div class="latest-release-song-option"> <div class="latest-release-song-option-logo"> <i class="fas fa-ellipsis-h"></i> </div> <div class="latest-release-song-option-dropdown"> <ul type="none"> <li> <i class="fas fa-play"></i> <span class="dropdown-text">Play Now</span> </li> <li> <i class="fas fa-plus"></i> <span class="dropdown-text">Add To Queue</span> </li> <li> <i class="fas fa-heart"></i> <span class="dropdown-text">Add To Favourites</span> </li> <li id="latest-release-song-option-dropdown-no-border"> <i class="fas fa-info-circle"></i> <span class="dropdown-text">Get Info</span> </li> </ul> </div> </div> <div class="latest-release-song-duration"> 4:22 </div> </div> </div> <div id="latest-release-content2" class="latest-release-content"> <div class="latest-release-content-img"> <img src="Assets/HAWAYEIN.png" alt="Hawayein"> </div> <div class="inline-elements"> <div class="latest-release-song-name"> HAWAYEIN </div> <div class="latest-release-song-date"> AUG 11,2021 </div> </div> <div class="inline-elements"> <div class="latest-release-song-option"> <div class="latest-release-song-option-logo"> <i class="fas fa-ellipsis-h"></i> </div> <div class="latest-release-song-option-dropdown"> <ul type="none"> <li> <i class="fas fa-play"></i> <span class="dropdown-text">Play Now</span> </li> <li> <i class="fas fa-plus"></i> <span class="dropdown-text">Add To Queue</span> </li> <li> <i class="fas fa-heart"></i> <span class="dropdown-text">Add To Favourites</span> </li> <li id="latest-release-song-option-dropdown-no-border"> <i class="fas fa-info-circle"></i> <span class="dropdown-text">Get Info</span> </li> </ul> </div> </div> <div class="latest-release-song-duration"> 4:22 </div> </div> </div> <div id="latest-release-content3" class="latest-release-content"> <div class="latest-release-content-img"> <img src="Assets/STEAL MY GIRL.png" alt="Steal My Girl"> </div> <div class="inline-elements"> <div class="latest-release-song-name"> Steal My Girl </div> <div class="latest-release-song-date"> AUG 11,2021 </div> </div> <div class="inline-elements"> <div class="latest-release-song-option"> <div class="latest-release-song-option-logo"> <i class="fas fa-ellipsis-h"></i> </div> <div class="latest-release-song-option-dropdown"> <ul type="none"> <li> <i class="fas fa-play"></i> <span class="dropdown-text">Play Now</span> </li> <li> <i class="fas fa-plus"></i> <span class="dropdown-text">Add To Queue</span> </li> <li> <i class="fas fa-heart"></i> <span class="dropdown-text">Add To Favourites</span> </li> <li id="latest-release-song-option-dropdown-no-border"> <i class="fas fa-info-circle"></i> <span class="dropdown-text">Get Info</span> </li> </ul> </div> </div> <div class="latest-release-song-duration"> 4:22 </div> </div> </div> <div id="latest-release-content4" class="latest-release-content"> <div class="latest-release-content-img"> <img src="Assets/RADHE.png" alt="Radhe"> </div> <div class="inline-elements"> <div class="latest-release-song-name"> Radhe </div> <div class="latest-release-song-date"> AUG 11,2021 </div> </div> <div class="inline-elements"> <div class="latest-release-song-option"> <div class="latest-release-song-option-logo"> <i class="fas fa-ellipsis-h"></i> </div> <div class="latest-release-song-option-dropdown"> <ul type="none"> <li> <i class="fas fa-play"></i> <span class="dropdown-text">Play Now</span> </li> <li> <i class="fas fa-plus"></i> <span class="dropdown-text">Add To Queue</span> </li> <li> <i class="fas fa-heart"></i> <span class="dropdown-text">Add To Favourites</span> </li> <li id="latest-release-song-option-dropdown-no-border"> <i class="fas fa-info-circle"></i> <span class="dropdown-text">Get Info</span> </li> </ul> </div> </div> <div class="latest-release-song-duration"> 4:22 </div> </div> </div> <div id="latest-release-content5" class="latest-release-content"> <div class="latest-release-content-img"> <img src="Assets/WOH DIN.png" alt="Woh Din"> </div> <div class="inline-elements"> <div class="latest-release-song-name"> Woh Din </div> <div class="latest-release-song-date"> AUG 11,2021 </div> </div> <div class="inline-elements"> <div class="latest-release-song-option"> <div class="latest-release-song-option-logo"> <i class="fas fa-ellipsis-h"></i> </div> <div class="latest-release-song-option-dropdown"> <ul type="none"> <li> <i class="fas fa-play"></i> <span class="dropdown-text">Play Now</span> </li> <li> <i class="fas fa-plus"></i> <span class="dropdown-text">Add To Queue</span> </li> <li> <i class="fas fa-heart"></i> <span class="dropdown-text">Add To Favourites</span> </li> <li id="latest-release-song-option-dropdown-no-border"> <i class="fas fa-info-circle"></i> <span class="dropdown-text">Get Info</span> </li> </ul> </div> </div> <div class="latest-release-song-duration"> 4:22 </div> </div> </div> <div id="latest-release-content6" class="latest-release-content"> <div class="latest-release-content-img"> <img src="Assets/ZINDAGI.png" alt="Zindagi"> </div> <div class="inline-elements"> <div class="latest-release-song-name"> Zindagi </div> <div class="latest-release-song-date"> AUG 11,2021 </div> </div> <div class="inline-elements"> <div class="latest-release-song-option"> <div class="latest-release-song-option-logo"> <i class="fas fa-ellipsis-h"></i> </div> <div class="latest-release-song-option-dropdown"> <ul type="none"> <li> <i class="fas fa-play"></i> <span class="dropdown-text">Play Now</span> </li> <li> <i class="fas fa-plus"></i> <span class="dropdown-text">Add To Queue</span> </li> <li> <i class="fas fa-heart"></i> <span class="dropdown-text">Add To Favourites</span> </li> <li id="latest-release-song-option-dropdown-no-border"> <i class="fas fa-info-circle"></i> <span class="dropdown-text">Get Info</span> </li> </ul> </div> </div> <div class="latest-release-song-duration"> 4:22 </div> </div> </div> </div> </div> </div> <!-- Popular Artist --> <div id="popular-artist-section"> <!-- Heading --> <div id="popular-artist-section-heading" class="section-heading"> Popular Artist </div> <!-- Popular-Artist-Content --> <div id="popular-artist-content-div"> <div id="popular-artist-content1" class="popular-artist-content"> <div class="popular-artist-img"> <a href="playlist.html" target="_blank"> <img src="https://assets.teenvogue.com/photos/56f48c62060ad49149eec62a/1:1/w_2163,h_2163,c_limit/GettyImages-450407021.jpg" alt="One Direction"> </a> </div> <div class="artist-name-content"> One Direction </div> </div> <div id="popular-artist-content2" class="popular-artist-content"> <div class="popular-artist-img"> <a href="playlist.html" target="_blank"> <img src="https://rollingstoneindia.com/wp-content/uploads/2017/03/rs_Pritam-3.jpg" alt="Pritam"> </a> </div> <div class="artist-name-content"> Pritam </div> </div> <div id="popular-artist-content3" class="popular-artist-content"> <div class="popular-artist-img"> <a href="playlist.html" target="_blank"> <img src="https://lh3.googleusercontent.com/pW7Jv2o8g0bkXFi11hrumm_N0e7KAf5pc5bawoSdD44uTLAYQi-Eeh1t1HileeiMx-9pXN6hQROW-OBEzWQWcEs2" alt="Justin Bieber"> </a> </div> <div class="artist-name-content"> Justin Bieber </div> </div> <div id="popular-artist-content1" class="popular-artist-content"> <div class="popular-artist-img"> <a href="playlist.html" target="_blank"> <img src="https://assets.teenvogue.com/photos/56f48c62060ad49149eec62a/1:1/w_2163,h_2163,c_limit/GettyImages-450407021.jpg" alt="One Direction"> </a> </div> <div class="artist-name-content"> One Direction </div> </div> <div id="popular-artist-content2" class="popular-artist-content"> <div class="popular-artist-img"> <a href="playlist.html" target="_blank"> <img src="https://rollingstoneindia.com/wp-content/uploads/2017/03/rs_Pritam-3.jpg" alt="Pritam"> </a> </div> <div class="artist-name-content"> Pritam </div> </div> <div id="popular-artist-content3" class="popular-artist-content"> <div class="popular-artist-img"> <a href="playlist.html" target="_blank"> <img src="https://lh3.googleusercontent.com/pW7Jv2o8g0bkXFi11hrumm_N0e7KAf5pc5bawoSdD44uTLAYQi-Eeh1t1HileeiMx-9pXN6hQROW-OBEzWQWcEs2" alt="Justin Bieber"> </a> </div> <div class="artist-name-content"> Justin Bieber </div> </div> </div> </div> <!-- Stations --> <div id="station-section"> <!-- Main Logo --> <div id="station-logo" class="inline-elements"> <img src="https://images-na.ssl-images-amazon.com/images/I/71nQ2cMmW9L.png" alt="station-image"> </div> <!-- Station Content --> <div id="station-content-div" class="inline-elements"> <div class="station-contents"> <div class="station-content-img"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRX2dR5_MiIhur2CEgMSlIxgO-xDvf9kiUPtA&usqp=CAU" alt="Love"> </div> <div class="station-contents-text"> Love </div> </div> <div class="station-contents"> <div class="station-content-img"> <img src="https://s3.ap-southeast-1.amazonaws.com/images.deccanchronicle.com/dc-Cover-8b2cnleddbftlnehq3e066ene3-20170508174432.Medi.jpeg" alt="Retro"> </div> <div class="station-contents-text"> Retro </div> </div> <div class="station-contents"> <div class="station-content-img"> <img src="https://images.unsplash.com/photo-1615912844755-bd8b6dd6789e?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Y2hpbGwlMjBtdXNpY3xlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&w=1000&q=80" alt="chill"> </div> <div class="station-contents-text"> Chill </div> </div> <div class="station-contents"> <div class="station-content-img"> <img src="https://i1.sndcdn.com/artworks-45jwFHE0w0M8jTRv-rIiLyg-t500x500.jpg" alt="Workout"> </div> <div class="station-contents-text"> Work<wbr>out </div> </div> <div class="station-contents"> <div class="station-content-img"> <img src="https://images.unsplash.com/photo-1498038432885-c6f3f1b912ee?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8cm9jayUyMG11c2ljfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80" alt="Rock"> </div> <div class="station-contents-text"> Rock </div> </div> <div class="station-contents"> <div class="station-content-img"> <img src="https://pyxis.nymag.com/v1/imgs/3a3/b1f/2141226b8ab1ae07afe4b541ee0d2b0825-11-yic-pop-essay.rsquare.w700.jpg" alt="Pop"> </div> <div class="station-contents-text"> Pop </div> </div> </div> </div> <!-- Moods Section --> <div id="mood-section"> <div class="mood-contents"> <div class="mood-img"> <img src="https://seda.college/blog/wp-content/uploads/2018/06/party.jpg" alt="Party"> </div> <div class="mood-text"> Party </div> </div> <div class="mood-contents"> <div class="mood-img"> <img src="https://media.istockphoto.com/photos/dj-playing-the-track-picture-id845367740?k=6&m=845367740&s=612x612&w=0&h=CYn7_c7sgvqPAT8nVdOQrWDHOcPCYWXx4sz3H48Qrx0=" alt="Electronic"> </div> <div class="mood-text"> Electronic </div> </div> <div class="mood-contents"> <div class="mood-img"> <img src="https://www.wandering-bird.com/wp-content/uploads/2018/07/songs2.jpg" alt="Road Trip"> </div> <div class="mood-text"> Road Trip </div> </div> </div> <!-- Latest English Section --> <div id="latest-english-hindi"> <!-- Heading --> <div id="latest-english-hindi-section-heading" class="section-heading"> Latest English </div> <div id="latest-english-hindi-content-div"> <div id="latest-english-hindi-content1" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/STEAL MY GIRL.png" alt="Infinity"> </div> <div class="english-hindi-name-content"> Infinity </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> <div id="latest-english-hindi-content2" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/YOU AND I.png" alt="You And I"> </div> <div class="english-hindi-name-content"> YOU AND I </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> <div id="latest-english-hindi-content3" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/PLAY DATE.png" alt="Play Date"> </div> <div class="english-hindi-name-content"> PLAY DATE </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> <div id="latest-english-hindi-content1" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/STEAL MY GIRL.png" alt="Infinity"> </div> <div class="english-hindi-name-content"> Infinity </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> <div id="latest-english-hindi-content2" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/YOU AND I.png" alt="You And I"> </div> <div class="english-hindi-name-content"> YOU AND I </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> <div id="latest-english-hindi-content3" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/PLAY DATE.png" alt="Play Date"> </div> <div class="english-hindi-name-content"> PLAY DATE </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> </div> </div> <!-- Latest Hindi Section --> <div id="latest-english-hindi"> <!-- Heading --> <div id="latest-english-hindi-section-heading" class="section-heading"> Latest Hindi </div> <div id="latest-english-hindi-content-div"> <div id="latest-english-hindi-content1" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/RADHE.png" alt="Radhe"> </div> <div class="english-hindi-name-content"> Radhe </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> <div id="latest-english-hindi-content2" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/WOH DIN.png" alt="Woh Din"> </div> <div class="english-hindi-name-content"> Woh Din </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> <div id="latest-english-hindi-content3" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/AASHIYAN.png" alt="Aashiyan"> </div> <div class="english-hindi-name-content"> AASHIYAN </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> <div id="latest-english-hindi-content1" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/RADHE.png" alt="Radhe"> </div> <div class="english-hindi-name-content"> Radhe </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> <div id="latest-english-hindi-content2" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/WOH DIN.png" alt="Woh Din"> </div> <div class="english-hindi-name-content"> Woh Din </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> <div id="latest-english-hindi-content3" class="latest-english-hindi-content"> <div class="latest-english-hindi-img"> <img src="Assets/AASHIYAN.png" alt="Aashiyan"> </div> <div class="english-hindi-name-content"> AASHIYAN </div> <div class="english-hindi-date-content"> AUG 11,2021 </div> </div> </div> </div> </content> <!-- Aside Section --> <div id="aside-section-main"> <!-- Left LightBox Arrow --> <div id="aside-hover-arrow"> <a href="#aside-section"> <i class="fas fa-caret-left"></i> </a> </div> <!-- Main Aside Section --> <aside id="aside-section"> <!-- Right LightBox Arrow --> <div id="light-box-close"> <a href="#"> <i class="fas fa-caret-right"></i> </a> </div> <!-- Aside Top Part --> <div id="aside-top-main-div"> <div id="aside-top"> <div id="aside-my-playlist-heading" class="inline-elements"> My Playlist </div> <div id="aside-queue-heading" class="inline-elements"> Queue </div> <div id="aside-down-heading" class="inline-elements"> <div id="aside-down-arrow"> <i class="fas fa-chevron-down"></i> </div> <div class="aside-down-heading-content"> <ul type="none"> <li> Playlist </li> <li id="aside-option-dropdown-no-border"> Favourite </li> </ul> </div> </div> </div> </div> <!-- Playlist Contents --> <div id="song-row"> <div class="extra-div-aside"></div> <div class="song-box"> <div class="serial-number inline-elements"> 01 </div> <div class="aside-song-img inline-elements"> <img src="Assets/AASHIYAN.png" alt="Aashiyan"> </div> <div class="aside-song-name inline-elements"> AASHIYAN </div> <div class="aside-song-artist inline-elements"> PRITAM </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements" id="serial-number-play"> <i class="fas fa-play"></i> </div> <div class="aside-song-img inline-elements"> <img src="Assets/ZINDAGI.png" alt="Zindagi"> </div> <div class="aside-song-name inline-elements"> ZINDAGI </div> <div class="aside-song-artist inline-elements"> JUBIN </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 03 </div> <div class="aside-song-img inline-elements"> <img src="Assets/HAWAYEIN.png" alt="Hawayein"> </div> <div class="aside-song-name inline-elements"> HAWAYEIN </div> <div class="aside-song-artist inline-elements"> ARIJIT </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 04 </div> <div class="aside-song-img inline-elements"> <img src="Assets/HOLD ON.png" alt="Hold On"> </div> <div class="aside-song-name inline-elements"> HOLD ON </div> <div class="aside-song-artist inline-elements"> JUSTIN </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 05 </div> <div class="aside-song-img inline-elements"> <img src="Assets/PLAY DATE.png" alt="Play Date"> </div> <div class="aside-song-name inline-elements"> PLAY DATE </div> <div class="aside-song-artist inline-elements"> Melanie </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 06 </div> <div class="aside-song-img inline-elements"> <img src="Assets/RADHE.png" alt="Radhe"> </div> <div class="aside-song-name inline-elements"> Radhe </div> <div class="aside-song-artist inline-elements"> SAJID </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 07 </div> <div class="aside-song-img inline-elements"> <img src="Assets/YOU AND I.png" alt="You And I"> </div> <div class="aside-song-name inline-elements"> YOU AND I </div> <div class="aside-song-artist inline-elements"> ONE DIRECTION </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 08 </div> <div class="aside-song-img inline-elements"> <img src="Assets/AASHIYAN.png" alt="Aashiyan"> </div> <div class="aside-song-name inline-elements"> AASHIYAN </div> <div class="aside-song-artist inline-elements"> PRITAM </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 09 </div> <div class="aside-song-img inline-elements"> <img src="Assets/ZINDAGI.png" alt="Zindagi"> </div> <div class="aside-song-name inline-elements"> ZINDAGI </div> <div class="aside-song-artist inline-elements"> JUBIN </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 10 </div> <div class="aside-song-img inline-elements"> <img src="Assets/HAWAYEIN.png" alt="Hawayein"> </div> <div class="aside-song-name inline-elements"> HAWAYEIN </div> <div class="aside-song-artist inline-elements"> ARIJIT </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 11 </div> <div class="aside-song-img inline-elements"> <img src="Assets/HOLD ON.png" alt="Hold On"> </div> <div class="aside-song-name inline-elements"> HOLD ON </div> <div class="aside-song-artist inline-elements"> JUSTIN </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 12 </div> <div class="aside-song-img inline-elements"> <img src="Assets/PLAY DATE.png" alt="Play Date"> </div> <div class="aside-song-name inline-elements"> PLAY DATE </div> <div class="aside-song-artist inline-elements"> Melanie </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 13 </div> <div class="aside-song-img inline-elements"> <img src="Assets/RADHE.png" alt="Radhe"> </div> <div class="aside-song-name inline-elements"> Radhe </div> <div class="aside-song-artist inline-elements"> SAJID </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 14 </div> <div class="aside-song-img inline-elements"> <img src="Assets/YOU AND I.png" alt="You And I"> </div> <div class="aside-song-name inline-elements"> YOU AND I </div> <div class="aside-song-artist inline-elements"> ONE DIRECTION </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 15 </div> <div class="aside-song-img inline-elements"> <img src="Assets/AASHIYAN.png" alt="Aashiyan"> </div> <div class="aside-song-name inline-elements"> AASHIYAN </div> <div class="aside-song-artist inline-elements"> PRITAM </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 16 </div> <div class="aside-song-img inline-elements"> <img src="Assets/ZINDAGI.png" alt="Zindagi"> </div> <div class="aside-song-name inline-elements"> ZINDAGI </div> <div class="aside-song-artist inline-elements"> JUBIN </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 17 </div> <div class="aside-song-img inline-elements"> <img src="Assets/HAWAYEIN.png" alt="Hawayein"> </div> <div class="aside-song-name inline-elements"> HAWAYEIN </div> <div class="aside-song-artist inline-elements"> ARIJIT </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 18 </div> <div class="aside-song-img inline-elements"> <img src="Assets/HOLD ON.png" alt="Hold On"> </div> <div class="aside-song-name inline-elements"> HOLD ON </div> <div class="aside-song-artist inline-elements"> JUSTIN </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 19 </div> <div class="aside-song-img inline-elements"> <img src="Assets/PLAY DATE.png" alt="Play Date"> </div> <div class="aside-song-name inline-elements"> PLAY DATE </div> <div class="aside-song-artist inline-elements"> Melanie </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 20 </div> <div class="aside-song-img inline-elements"> <img src="Assets/RADHE.png" alt="Radhe"> </div> <div class="aside-song-name inline-elements"> Radhe </div> <div class="aside-song-artist inline-elements"> SAJID </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> <div class="song-box"> <div class="serial-number inline-elements"> 21 </div> <div class="aside-song-img inline-elements"> <img src="Assets/YOU AND I.png" alt="You And I"> </div> <div class="aside-song-name inline-elements"> YOU AND I </div> <div class="aside-song-artist inline-elements"> ONE DIRECTION </div> <div class="aside-fav-logo-initial inline-elements"> <i class="far fa-heart"></i> </div> <div class="aside-fav-logo-hover inline-elements"> <i class="fas fa-heart"></i> </div> </div> </div> </aside> </div> </main> <!-- Player Box --> <footer> <div id="player-box"> <div id="player-contents"> <!-- Image --> <div id="player-img"> <img src="Assets/ZINDAGI.png" alt="Zindagi"> </div> <!-- Song Details --> <div id="player-song-name"> ZINDAGI </div> <div id="player-artist"> JUBIN </div> <!-- Functions --> <div id="player-favourite-initial"> <i class="far fa-heart"></i> </div> <div id="player-favourite-hover"> <i class="fas fa-heart"></i> </div> <div id="player-restriction"> <i class="fas fa-ban"></i> </div> <div id="player-suffle"> <i class="fas fa-random"></i> </div> <div id="player-previous"> <i class="fas fa-step-backward"></i> </div> <div id="player-seek-prev"> <i class="fas fa-backward"></i> </div> <div id="player-play"> <i class="fas fa-play"></i> </div> <div id="player-pause"> <i class="fas fa-pause"></i> </div> <div id="player-seek-next"> <i class="fas fa-forward"></i> </div> <div id="player-next"> <i class="fas fa-step-forward"></i> </div> <div id="player-repeat"> <i class="fas fa-redo-alt"></i> </div> <div id="left-duration"> 0:25 </div> <div id="player-time-strap"> <input type="range" min="0" max="50"> </div> <div id="right-duration"> 4:23 </div> <div id="playlist"> <div id="player-playlist-bars"> <i class="fas fa-bars"></i> </div> <div id="player-playlist-play"> <i class="fas fa-play"></i> </div> </div> <div id="airplay"> <i class="fas fa-desktop"></i> </div> <div id="volume"> <div id="volume-logo"> <i class="fas fa-volume-up"></i> </div> <div id="volume-strap"> <input type="range" min="0" max="10"> </div> </div> <div id="zoom-player"> <i class="fas fa-arrows-alt-v"></i> </div> </div> </div> </footer> </body> </html>
<?php /** * Upgrade API: Core_Upgrader class * * @package WordPress * @subpackage Upgrader * @since 4.6.0 */ /** * Core class used for updating core. * * It allows for WordPress to upgrade itself in combination with * the wp-admin/includes/update-core.php file. * * @since 2.8.0 * @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader.php. * * @see WP_Upgrader */ class Core_Upgrader extends WP_Upgrader { /** * Initialize the upgrade strings. * * @since 2.8.0 */ public function upgrade_strings() { $this->strings['up_to_date'] = __( 'WordPress is at the latest version.' ); $this->strings['locked'] = __( 'Another update is currently in progress.' ); $this->strings['no_package'] = __('Update package not available.'); /* translators: %s: Package URL. */ $this->strings['downloading_package'] = sprintf( __('Downloading update from %s&#8230;'), '<span class="code">%s</span>' ); $this->strings['unpack_package'] = __('Unpacking the update&#8230;'); $this->strings['copy_failed'] = __('Could not copy files.'); $this->strings['copy_failed_space'] = __( 'Could not copy files. You may have run out of disk space.' ); $this->strings['start_rollback'] = __( 'Attempting to roll back to previous version.' ); $this->strings['rollback_was_required'] = __( 'Due to an error during updating, WordPress has rolled back to your previous version.' ); } /** * Upgrade WordPress core. * * @since 2.8.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * @global callable $_wp_filesystem_direct_method * * @param object $current Response object for whether WordPress is current. * @param array $args { * Optional. Arguments for upgrading WordPress core. Default empty array. * * @type bool $pre_check_md5 Whether to check the file checksums before * attempting the upgrade. Default true. * @type bool $attempt_rollback Whether to attempt to rollback the chances if * there is a problem. Default false. * @type bool $do_rollback Whether to perform this "upgrade" as a rollback. * Default false. * } * @return string|false|WP_Error New WordPress version on success, false or WP_Error on failure. */ public function upgrade($current, $args = []) { global $wp_filesystem; require ABSPATH . WPINC . '/version.php'; // $wp_version; $start_time = time(); $defaults = [ 'pre_check_md5' => true, 'attempt_rollback' => false, 'do_rollback' => false, 'allow_relaxed_file_ownership' => false, ]; $parsed_args = wp_parse_args($args, $defaults); $this->init(); $this->upgrade_strings(); // Is an update available? if (!isset($current->response) || 'latest' === $current->response) { return new WP_Error('up_to_date', $this->strings['up_to_date']); } $res = $this->fs_connect( [ABSPATH, WP_CONTENT_DIR], $parsed_args['allow_relaxed_file_ownership'] ); if (!$res || is_wp_error($res)) { return $res; } $wp_dir = trailingslashit($wp_filesystem->abspath()); $partial = true; if ($parsed_args['do_rollback']) { $partial = false; } elseif ($parsed_args['pre_check_md5'] && !$this->check_files()) { $partial = false; } /* * If partial update is returned from the API, use that, unless we're doing * a reinstallation. If we cross the new_bundled version number, then use * the new_bundled zip. Don't though if the constant is set to skip bundled items. * If the API returns a no_content zip, go with it. Finally, default to the full zip. */ if ($parsed_args['do_rollback'] && $current->packages->rollback) { $to_download = 'rollback'; } elseif ( $current->packages->partial && 'reinstall' !== $current->response && $wp_version == $current->partial_version && $partial ) { $to_download = 'partial'; } elseif ( $current->packages->new_bundled && version_compare($wp_version, $current->new_bundled, '<') && (!defined('CORE_UPGRADE_SKIP_NEW_BUNDLED') || !CORE_UPGRADE_SKIP_NEW_BUNDLED) ) { $to_download = 'new_bundled'; } elseif ($current->packages->no_content) { $to_download = 'no_content'; } else { $to_download = 'full'; } // Lock to prevent multiple Core Updates occurring. $lock = WP_Upgrader::create_lock( 'core_updater', 15 * MINUTE_IN_SECONDS ); if (!$lock) { return new WP_Error('locked', $this->strings['locked']); } $download = $this->download_package( $current->packages->$to_download, true ); // Allow for signature soft-fail. // WARNING: This may be removed in the future. if ( is_wp_error($download) && $download->get_error_data('softfail-filename') ) { // Outout the failure error as a normal feedback, and not as an error: /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters('update_feedback', $download->get_error_message()); // Report this failure back to WordPress.org for debugging purposes. wp_version_check([ 'signature_failure_code' => $download->get_error_code(), 'signature_failure_data' => $download->get_error_data(), ]); // Pretend this error didn't happen. $download = $download->get_error_data('softfail-filename'); } if (is_wp_error($download)) { WP_Upgrader::release_lock('core_updater'); return $download; } $working_dir = $this->unpack_package($download); if (is_wp_error($working_dir)) { WP_Upgrader::release_lock('core_updater'); return $working_dir; } // Copy update-core.php from the new version into place. if ( !$wp_filesystem->copy( $working_dir . '/wordpress/wp-admin/includes/update-core.php', $wp_dir . 'wp-admin/includes/update-core.php', true ) ) { $wp_filesystem->delete($working_dir, true); WP_Upgrader::release_lock('core_updater'); return new WP_Error( 'copy_failed_for_update_core_file', __( 'The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.' ), 'wp-admin/includes/update-core.php' ); } $wp_filesystem->chmod( $wp_dir . 'wp-admin/includes/update-core.php', FS_CHMOD_FILE ); wp_opcache_invalidate(ABSPATH . 'wp-admin/includes/update-core.php'); require_once ABSPATH . 'wp-admin/includes/update-core.php'; if (!function_exists('update_core')) { WP_Upgrader::release_lock('core_updater'); return new WP_Error( 'copy_failed_space', $this->strings['copy_failed_space'] ); } $result = update_core($working_dir, $wp_dir); // In the event of an issue, we may be able to roll back. if ( $parsed_args['attempt_rollback'] && $current->packages->rollback && !$parsed_args['do_rollback'] ) { $try_rollback = false; if (is_wp_error($result)) { $error_code = $result->get_error_code(); /* * Not all errors are equal. These codes are critical: copy_failed__copy_dir, * mkdir_failed__copy_dir, copy_failed__copy_dir_retry, and disk_full. * do_rollback allows for update_core() to trigger a rollback if needed. */ if (false !== strpos($error_code, 'do_rollback')) { $try_rollback = true; } elseif (false !== strpos($error_code, '__copy_dir')) { $try_rollback = true; } elseif ('disk_full' === $error_code) { $try_rollback = true; } } if ($try_rollback) { /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters('update_feedback', $result); /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_feedback', $this->strings['start_rollback'] ); $rollback_result = $this->upgrade( $current, array_merge($parsed_args, ['do_rollback' => true]) ); $original_result = $result; $result = new WP_Error( 'rollback_was_required', $this->strings['rollback_was_required'], (object) [ 'update' => $original_result, 'rollback' => $rollback_result, ] ); } } /** This action is documented in wp-admin/includes/class-wp-upgrader.php */ do_action('upgrader_process_complete', $this, [ 'action' => 'update', 'type' => 'core', ]); // Clear the current updates. delete_site_transient('update_core'); if (!$parsed_args['do_rollback']) { $stats = [ 'update_type' => $current->response, 'success' => true, 'fs_method' => $wp_filesystem->method, 'fs_method_forced' => defined('FS_METHOD') || has_filter('filesystem_method'), 'fs_method_direct' => !empty( $GLOBALS['_wp_filesystem_direct_method'] ) ? $GLOBALS['_wp_filesystem_direct_method'] : '', 'time_taken' => time() - $start_time, 'reported' => $wp_version, 'attempted' => $current->version, ]; if (is_wp_error($result)) { $stats['success'] = false; // Did a rollback occur? if (!empty($try_rollback)) { $stats['error_code'] = $original_result->get_error_code(); $stats['error_data'] = $original_result->get_error_data(); // Was the rollback successful? If not, collect its error too. $stats['rollback'] = !is_wp_error($rollback_result); if (is_wp_error($rollback_result)) { $stats[ 'rollback_code' ] = $rollback_result->get_error_code(); $stats[ 'rollback_data' ] = $rollback_result->get_error_data(); } } else { $stats['error_code'] = $result->get_error_code(); $stats['error_data'] = $result->get_error_data(); } } wp_version_check($stats); } WP_Upgrader::release_lock('core_updater'); return $result; } /** * Determines if this WordPress Core version should update to an offered version or not. * * @since 3.7.0 * * @param string $offered_ver The offered version, of the format x.y.z. * @return bool True if we should update to the offered version, otherwise false. */ public static function should_update_to_version($offered_ver) { require ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z $current_branch = implode( '.', array_slice(preg_split('/[.-]/', $wp_version), 0, 2) ); // x.y $new_branch = implode( '.', array_slice(preg_split('/[.-]/', $offered_ver), 0, 2) ); // x.y $current_is_development_version = (bool) strpos($wp_version, '-'); // Defaults: $upgrade_dev = get_site_option('auto_update_core_dev', 'enabled') === 'enabled'; $upgrade_minor = get_site_option('auto_update_core_minor', 'enabled') === 'enabled'; $upgrade_major = get_site_option('auto_update_core_major', 'unset') === 'enabled'; // WP_AUTO_UPDATE_CORE = true (all), 'beta', 'rc', 'development', 'branch-development', 'minor', false. if (defined('WP_AUTO_UPDATE_CORE')) { if (false === WP_AUTO_UPDATE_CORE) { // Defaults to turned off, unless a filter allows it. $upgrade_dev = false; $upgrade_minor = false; $upgrade_major = false; } elseif ( true === WP_AUTO_UPDATE_CORE || in_array( WP_AUTO_UPDATE_CORE, ['beta', 'rc', 'development', 'branch-development'], true ) ) { // ALL updates for core. $upgrade_dev = true; $upgrade_minor = true; $upgrade_major = true; } elseif ('minor' === WP_AUTO_UPDATE_CORE) { // Only minor updates for core. $upgrade_dev = false; $upgrade_minor = true; $upgrade_major = false; } } // 1: If we're already on that version, not much point in updating? if ($offered_ver == $wp_version) { return false; } // 2: If we're running a newer version, that's a nope. if (version_compare($wp_version, $offered_ver, '>')) { return false; } $failure_data = get_site_option('auto_core_update_failed'); if ($failure_data) { // If this was a critical update failure, cannot update. if (!empty($failure_data['critical'])) { return false; } // Don't claim we can update on update-core.php if we have a non-critical failure logged. if ( $wp_version == $failure_data['current'] && false !== strpos($offered_ver, '.1.next.minor') ) { return false; } /* * Cannot update if we're retrying the same A to B update that caused a non-critical failure. * Some non-critical failures do allow retries, like download_failed. * 3.7.1 => 3.7.2 resulted in files_not_writable, if we are still on 3.7.1 and still trying to update to 3.7.2. */ if ( empty($failure_data['retry']) && $wp_version == $failure_data['current'] && $offered_ver == $failure_data['attempted'] ) { return false; } } // 3: 3.7-alpha-25000 -> 3.7-alpha-25678 -> 3.7-beta1 -> 3.7-beta2. if ($current_is_development_version) { /** * Filters whether to enable automatic core updates for development versions. * * @since 3.7.0 * * @param bool $upgrade_dev Whether to enable automatic updates for * development versions. */ if (!apply_filters('allow_dev_auto_core_updates', $upgrade_dev)) { return false; } // Else fall through to minor + major branches below. } // 4: Minor in-branch updates (3.7.0 -> 3.7.1 -> 3.7.2 -> 3.7.4). if ($current_branch == $new_branch) { /** * Filters whether to enable minor automatic core updates. * * @since 3.7.0 * * @param bool $upgrade_minor Whether to enable minor automatic core updates. */ return apply_filters( 'allow_minor_auto_core_updates', $upgrade_minor ); } // 5: Major version updates (3.7.0 -> 3.8.0 -> 3.9.1). if (version_compare($new_branch, $current_branch, '>')) { /** * Filters whether to enable major automatic core updates. * * @since 3.7.0 * * @param bool $upgrade_major Whether to enable major automatic core updates. */ return apply_filters( 'allow_major_auto_core_updates', $upgrade_major ); } // If we're not sure, we don't want it. return false; } /** * Compare the disk file checksums against the expected checksums. * * @since 3.7.0 * * @global string $wp_version The WordPress version string. * @global string $wp_local_package Locale code of the package. * * @return bool True if the checksums match, otherwise false. */ public function check_files() { global $wp_version, $wp_local_package; $checksums = get_core_checksums( $wp_version, isset($wp_local_package) ? $wp_local_package : 'en_US' ); if (!is_array($checksums)) { return false; } foreach ($checksums as $file => $checksum) { // Skip files which get updated. if ('wp-content' === substr($file, 0, 10)) { continue; } if ( !file_exists(ABSPATH . $file) || md5_file(ABSPATH . $file) !== $checksum ) { return false; } } return true; } }
'use strict'; // React import React from 'react'; // Components import Filter from '../Filter'; import Widget from '../Widget'; // Actions import ArticleActions from '../../../actions/ArticleActions'; // Stores import ArticleStore from '../../../stores/ArticleStore'; function getInitialState() { return { filters: {}, articles: [] }; } function getStateFromStores(parameters) { let article = ArticleStore.get(parameters.article.id); return (article == null) ? null : { isLoading: false, article: article }; } function fireActions(state, callback) { let parameters = { id: state.article.id, callback: callback }; ArticleActions.getArticle(parameters); } function filterOptions() { return { sort: [{ value: 'latest', label: 'Latest' },{ value: 'other', label: 'Other' }], category: [{ value: 'all', label: 'all' },{ value: 'other', label: 'Other' }], region: [{ value: 'singapore', label: 'Singapore' }, { value: 'malaysia', label: 'Malaysia' }] } } /** * Article List */ class List extends React.Component { constructor(props, context) { super(props, context); // NOTE: IntelliJ lints this as invalid. Ignore warning. this.onFilterChange = this.onFilterChange.bind(this); this.state = getInitialState(); /** * Event handler for 'change' events coming from the ArticleStore */ this.onChange = () => { let parameters = { article: { id: null } }; if (this.props.params != null) { if (this.props.params.id != null) { let articleId = parseInt(this.props.params.id); if (!isNaN(articleId)) { parameters.article.id = articleId; } } } let newState = getStateFromStores(parameters); if (newState != null) { this.setState(newState); } }; } onFilterChange(filters) { console.log('list filters', filters); // TO-DO fetch new data } componentDidMount() { ArticleStore.listen(this.onChange); } componentWillUnmount() { ArticleStore.unlisten(this.onChange); } componentWillReceiveProps(nextProps) { this.onChange(); } /** * @return {object} */ render() { return ( <div className='article-list'> <Filter options={filterOptions()} filterFunction={this.onFilterChange} /> <div className='container-fluid'> Content </div> </div> ); } /** * Static method to trigger data actions for server-side rendering. * * @param routerState * @param callback */ //static fetchData(routerState, callback) { // let state = getInitialState(); // // //fireActions(state, callback); //} static generateMetadata(routerState) { return { title: 'Articles', description: 'This is articles page' } } } export default List;
package services import ( "context" "github.com/volatiletech/sqlboiler/v4/boil" "graphql_server/graph/model" ) type Services interface { UserService } type UserService interface { GetUser(ctx context.Context, id string) (*model.User, error) GetUsers(ctx context.Context, limit int) ([]*model.User, error) CreateUser(ctx context.Context, name string) (*model.User, error) UpdateUser(ctx context.Context, id string, name string) (*model.User, error) DeleteUser(ctx context.Context, id string) (*model.User, error) ListUsersByID(ctx context.Context, IDs []string) ([]*model.User, error) } type services struct { *userService } func New(exec boil.ContextExecutor) Services { return &services{ userService: &userService{exec: exec}, } }
import { useState, useEffect } from 'react'; import { useParams, Link } from 'react-router-dom'; import axios from 'axios'; const DrinkPage = () => { const [drink, setDrink] = useState(''); const { id } = useParams(); useEffect(() => { const getDrink = async () => { try { const response = await axios.get(`https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=${id}`); setDrink(response.data.drinks[0]); console.log(response); } catch (error) { console.error('Error fetching drink:', error); } }; getDrink(); }, [id]); const drinkDetailsStyle = { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', marginTop: '20px', padding: '20px', backgroundColor: 'rgba(0, 0, 0, 0.5)', borderRadius: '5px', backdropFilter: 'blur(5px)', }; const drinkTitleStyle = { fontSize: '24px', marginBottom: '10px', color: 'white', }; const drinkImageStyle = { width: '200px', height: '200px', objectFit: 'cover', borderRadius: '5px', marginBottom: '10px', }; const drinkInfoStyle = { fontSize: '16px', color: 'white', marginBottom: '10px', }; const backButtonStyle = { textDecoration: 'none', color: 'white', }; return drink ? ( <div className="drinkDetailsPage" style={drinkDetailsStyle}> <h2 style={drinkTitleStyle}>{drink.strDrink}</h2> <img src={drink.strDrinkThumb} alt={drink.strDrink} style={drinkImageStyle} /> <h3 style={drinkInfoStyle}>{drink.strTags}</h3> <h3 style={drinkInfoStyle}>{drink.strCategory}</h3> {Object.entries(drink).map(([key, value]) => { if (key.includes('strIngredient') && value) { const measureKey = `strMeasure${key.slice(-1)}`; return ( <h5 key={key} style={drinkInfoStyle}> {drink[measureKey]} of {value} </h5> ); } return null; })} <h3 style={drinkInfoStyle}>{drink.strInstructions}</h3> <button> <Link to="/drinks" style={backButtonStyle}>Back to drinks</Link> </button> </div> ) : ( <h3>Making drink...</h3> ); }; export default DrinkPage;
<template> <v-container > <v-toolbar> <v-toolbar-title>Comunicados</v-toolbar-title> <v-spacer></v-spacer> <v-btn color="tertiary" dark :to="{ name: 'changePassword' }" class="mr-5" v-if="!$store.getters.currentUser" > Cambiar contraseña </v-btn> <span v-if="$store.getters.currentUser"> <v-btn color="tertiary" dark :to="{ name: 'iconIndex' }" v-if="$store.getters.currentUser.roles[0].name == 'admin'" > Íconos </v-btn> <v-btn color="tertiary" dark :to="{ name: 'groupIndex' }" v-if="$store.getters.currentUser.roles[0].name == 'admin'" > Grupos </v-btn> <v-btn color="tertiary" dark :to="{ name: 'userIndex' }" v-if="$store.getters.currentUser.roles[0].name == 'admin'" > Usuarios </v-btn> <v-btn color="tertiary" dark class="mr-5" :to="{ name: 'noticeIndex' }" v-if="$store.getters.currentUser.roles[0].name == 'admin'||$store.getters.currentUser.roles[0].name == 'secretaria'" > Comunicados </v-btn> </span> <v-divider class="mx-2" inset vertical ></v-divider> <v-toolbar-title> <v-text-field v-model="search" append-icon="search" label="Buscar" clearable single-line hide-details width="20px" ></v-text-field> </v-toolbar-title> <v-divider class="mx-2" inset vertical ></v-divider> <NoticeForm :contract="{}" :bus="bus"/> <RemoveItem :bus="bus"/> </v-toolbar> <v-data-table :headers="headers" :items="notices" :search="search" :rows-per-page-items="[10,20,30,{text:'TODO',value:-1}]" disable-initial-sort class="elevation-1"> <template slot="items" slot-scope="props"> <tr> <td class="text-xs-center"> {{ props.item.notice_type.name }} </td> <td class="text-xs-center"> {{ props.item.title }} </td> <td class="text-xs-center"> {{ props.item.origin }} </td> <td class="text-xs-center"> {{ props.item.correlative }} </td> <td class="text-xs-center"> {{ props.item.year }} </td> <td class="text-xs-center"> <v-switch v-model="props.item.active" color="info" @click.native="switchActive(props.item)" ></v-switch> </td> <td class="justify-center layout"> <v-tooltip top> <v-btn slot="activator" flat icon color="accent" @click="printItem(props.item)"> <v-icon>print</v-icon> </v-btn> <span>Imprimir</span> </v-tooltip> <v-tooltip top> <v-btn slot="activator" flat icon color="accent" @click="editItem(props.item, 'edit')"> <v-icon>edit</v-icon> </v-btn> <span>Editar</span> </v-tooltip> <v-tooltip top> <v-btn slot="activator" flat icon color="red darken-3" @click="removeItem(props.item)"> <v-icon>delete</v-icon> </v-btn> <span>Eliminar</span> </v-tooltip> </td> </tr> </template> <v-alert slot="no-results" :value="true" color="error"> La búsqueda de "{{ search }}" no encontró resultados. </v-alert> </v-data-table> </v-container> </template> <script type="text/javascript"> import Vue from "vue"; import NoticeForm from "./NoticeForm"; import RemoveItem from "../RemoveItem"; import { admin } from "../../menu.js"; export default { name: "noticeIndex", components: { NoticeForm, RemoveItem }, data: () => ({ toggle_one: 0, bus: new Vue(), headers: [ { text: "Tipo", value: "notice_type.name", align: "center" }, { text: "titulo", value: "title", align: "center" }, { text: "Origen", value: "origin", align: "center" }, { text: "correlativo", value: "correlative", align: "center" },{ text: "Gestión", value: "year", align: "center" }, { text: "Activo", value: "active", align: "center" }, { text: "Opciones", value: "", align: "center", sortable: false } ], notices: [], search: "", options: [] }), computed: { formTitle() { return this.selectedIndex === -1 ? "Nueva noticia" : "Editar noticia"; } }, async created() { this.getNotices(); this.bus.$on("closeDialog", () => { this.getNotices(this.active); }); // console.log(this.$store.getters.currentUser.roles[0].name); }, methods: { async getNotices() { try { let res = await axios.get(`/notice`); this.notices = res.data; } catch (e) { console.log(e); } }, editItem(item, mode) { this.bus.$emit("openDialog", $.extend({}, item, { mode: mode })); }, async switchActive(notice) { try { let res = await axios.patch(`/notice/${notice.id}`, { active: notice.active }); this.getNotices(); } catch (e) { console.log(e); } }, async printItem(item) { try { if (item.url_document) { printJS("uploads/COM12018"); } else { let res = await axios({ method: "GET", url: `/notice/print/${item.id}`, responseType: "arraybuffer" }); let blob = new Blob([res.data], { type: "application/pdf" }); printJS(window.URL.createObjectURL(blob)); } } catch (e) { console.log(e); } }, async removeItem(item) { this.bus.$emit("openDialogRemove", `/notice/${item.id}`); } } }; </script>
use super::quad_rat_general::QuadRatGeneral; use crate::macros::{degree_impl, has_child_impl, horner_monic, profile_imports}; profile_imports!(); // Maps of the form f_t(z) = (z^2+a_t)/(z^2+b_t), // with a fixed point at z0 = -t/2 of multiplier lambda // Critical points are 0 and infinity. #[derive(Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct QuadRatPer1Lambda { general_plane: QuadRatGeneral, multiplier: Cplx, tolerance: Real, } impl Default for QuadRatPer1Lambda { fn default() -> Self { let general_plane = QuadRatGeneral::default(); let tolerance = Self::compute_tolerance(ZERO); Self { general_plane, multiplier: ZERO, tolerance, } } } impl QuadRatPer1Lambda { fn compute_tolerance(multiplier: Cplx) -> Real { let err = multiplier.norm() - 1.; if err > 1e-3 { return 1e-12; } let err2 = -1e8 * err * err; err2.exp2().mul_add(1e-8, 1e-12) } } impl DynamicalFamily for QuadRatPer1Lambda { type Var = Cplx; type Param = CplxPair; type Deriv = Cplx; type MetaParam = Cplx; default_name!(); #[inline] fn max_iter(&self) -> IterCount { self.general_plane.max_iter } #[inline] fn max_iter_mut(&mut self) -> &mut IterCount { &mut self.general_plane.max_iter } #[inline] fn set_max_iter(&mut self, new_max_iter: IterCount) { self.general_plane.max_iter = new_max_iter; } #[must_use] fn with_max_iter(mut self, max_iter: IterCount) -> Self { self.general_plane.max_iter = max_iter; self } #[inline] fn point_grid(&self) -> &PointGrid { &self.general_plane.point_grid } #[inline] fn point_grid_mut(&mut self) -> &mut PointGrid { &mut self.general_plane.point_grid } fn with_point_grid(mut self, point_grid: PointGrid) -> Self { self.general_plane.point_grid = point_grid; self } #[inline] fn compute_mode(&self) -> ComputeMode { self.general_plane.compute_mode() } #[inline] fn compute_mode_mut(&mut self) -> &mut ComputeMode { self.general_plane.compute_mode_mut() } fn param_map(&self, t: Cplx) -> Self::Param { let alpha = 0.25 * t / self.multiplier; CplxPair { a: alpha * t * (t - self.multiplier + 2.), b: -alpha * (4. + (self.multiplier + 2.) * t), } } #[inline] fn map(&self, z: Self::Var, c: &Self::Param) -> Self::Var { self.general_plane.map(z, c) } #[inline] fn map_and_multiplier(&self, z: Self::Var, c: &Self::Param) -> (Self::Var, Self::Deriv) { self.general_plane.map_and_multiplier(z, c) } #[inline] fn start_point(&self, t: Cplx, c: &Self::Param) -> Self::Var { self.general_plane.start_point(t, c) } #[inline] fn start_point_d(&self, point: Cplx, c: &Self::Param) -> (Self::Var, Self::Deriv, Self::Deriv) { self.general_plane.start_point_d(point, c) } #[inline] fn get_param(&self) -> <Self::MetaParam as ParamList>::Param { self.multiplier } #[inline] fn periodicity_tolerance(&self) -> Real { self.tolerance } #[inline] fn set_param(&mut self, lambda: <Self::MetaParam as ParamList>::Param) { self.multiplier = lambda; self.tolerance = Self::compute_tolerance(lambda); } } impl FamilyDefaults for QuadRatPer1Lambda { fn default_bounds(&self) -> Bounds { Bounds::centered_square(4.0) } } has_child_impl!(QuadRatPer1Lambda); impl MarkedPoints for QuadRatPer1Lambda { #[inline] fn critical_points_child(&self, c: &Self::Param) -> Vec<Self::Var> { self.general_plane.critical_points_child(c) } #[inline] fn cycles_child(&self, c: &Self::Param, period: Period) -> Vec<Self::Var> { self.general_plane.cycles_child(c, period) } } // impl HasDynamicalCovers for QuadRatPer1Lambda // { // fn marked_cycle_curve(self, period: Period) -> CoveringMap<Self> // { // let param_map: fn(Cplx) -> Cplx; // let bounds: Bounds; // // match period // { // 1 => // { // param_map = |t| { // let u = -2. * self.multiplier; // u * (t + self.multiplier - 2.) / horner_monic!(t, u, self.multiplier) // }; // bounds = Bounds { // min_x: -2.5, // max_x: 2.5, // min_y: -2.5, // max_y: 2.5, // }; // } // _ => // { // param_map = |t| t; // bounds = self.point_grid().bounds.clone(); // } // }; // let grid = self.point_grid().new_with_same_height(bounds); // CoveringMap::new(self, param_map, grid) // } // // fn dynatomic_curve(self, period: Period) -> CoveringMap<Self> // { // let param_map: fn(Cplx) -> Cplx; // let bounds: Bounds; // // match period // { // 1 => return self.marked_cycle_curve(1), // 2 => // { // param_map = |t| todo!(); // bounds = Bounds { // min_x: -2.5, // max_x: 2.5, // min_y: -2.5, // max_y: 2.5, // }; // } // _ => // { // param_map = |t| t; // bounds = self.point_grid().bounds.clone(); // } // }; // let grid = self.point_grid().new_with_same_height(bounds); // CoveringMap::new(self, param_map, grid) // } // fn misiurewicz_curve(self, preperiod: Period, period: Period) -> CoveringMap<Self> // { // let param_map: fn(Cplx) -> Cplx; // let bounds: Bounds; // // match (preperiod, period) // { // (2, 1) => // { // param_map = |t| todo!(); // bounds = Bounds { // min_x: -2.5, // max_x: 2.5, // min_y: -2.5, // max_y: 2.5, // }; // } // (_, _) => // { // param_map = |t| t; // bounds = self.point_grid().bounds.clone(); // } // }; // let grid = self.point_grid().new_with_same_height(bounds); // CoveringMap::new(self, param_map, grid) // } // } #[derive(Clone, Debug)] pub struct QuadRatPer1LambdaParam { point_grid: PointGrid, compute_mode: ComputeMode, max_iter: IterCount, } impl QuadRatPer1LambdaParam { const DEFAULT_BOUNDS: Bounds = Bounds { min_x: -2.2, max_x: 4.2, min_y: -2.5, max_y: 2.5, }; } impl Default for QuadRatPer1LambdaParam { fn default() -> Self { let point_grid = PointGrid::new_by_res_y(1024, Self::DEFAULT_BOUNDS); Self { point_grid, compute_mode: ComputeMode::default(), max_iter: 1024, } } } impl DynamicalFamily for QuadRatPer1LambdaParam { parameter_plane_impl!(); #[inline] fn map(&self, z: Self::Var, l: &Self::Param) -> Self::Var { let a = -4. * l / horner_monic!(l, 8., 12., 6.); 1. + a / (z * z) } #[inline] fn map_and_multiplier(&self, z: Self::Var, l: &Self::Param) -> (Self::Var, Self::Deriv) { let a = -4. * l / horner_monic!(l, 8., 12., 6.); let z2 = z * z; (1. + a / z2, -2. * a / (z2 * z)) } #[inline] fn gradient(&self, z: Self::Var, l: &Self::Param) -> (Self::Var, Self::Deriv, Self::Deriv) { let a = -4. * l / horner_monic!(l, 8., 12., 6.); let u = (l + 2.).powi(-4); let z_i2 = z.powi(-2); (1. + a * z_i2, -2. * a * z_i2 / z, 8. * (l - 1.) * u * z_i2) } #[inline] fn start_point(&self, _point: Cplx, _c: &Self::Param) -> Self::Var { ONE } #[inline] fn start_point_d(&self, _point: Cplx, _c: &Self::Param) -> (Self::Var, Self::Deriv, Self::Deriv) { (ONE, ZERO, ZERO) } fn name(&self) -> String { "QuadRat Per(1, λ) λ-plane".to_owned() } } impl FamilyDefaults for QuadRatPer1LambdaParam { default_bounds!(); fn default_selection(&self) -> Cplx { ONE } } impl HasChild<QuadRatPer1Lambda> for QuadRatPer1LambdaParam { fn to_child_param( param: Self::Param, ) -> <<QuadRatPer1Lambda as DynamicalFamily>::MetaParam as ParamList>::Param { param } } impl MarkedPoints for QuadRatPer1LambdaParam { fn critical_points_child(&self, _param: &Self::Param) -> Vec<Self::Var> { vec![ZERO, ONE] } } impl From<QuadRatPer1LambdaParam> for QuadRatPer1Lambda { fn from(parent: QuadRatPer1LambdaParam) -> Self { let point = parent.default_selection(); let point_grid = parent.point_grid().clone(); let general_plane = QuadRatGeneral { point_grid, compute_mode: ComputeMode::default(), max_iter: parent.max_iter(), }; Self { general_plane, multiplier: point, tolerance: Self::compute_tolerance(point), } .with_default_bounds() } } // Maps of the form f_t(z) = (z^2+a_t)/(z^2+b_t), // with a fixed point at z0 = -t/2 of multiplier lambda // Critical points are 0 and infinity. #[derive(Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct QuadRatPer1_1 { general_plane: QuadRatGeneral, } impl Default for QuadRatPer1_1 { fn default() -> Self { let general_plane = QuadRatGeneral::default(); Self { general_plane } } } impl DynamicalFamily for QuadRatPer1_1 { type Var = Cplx; type Param = CplxPair; type Deriv = Cplx; type MetaParam = NoParam; default_name!(); #[inline] fn max_iter(&self) -> IterCount { self.general_plane.max_iter } #[inline] fn max_iter_mut(&mut self) -> &mut IterCount { &mut self.general_plane.max_iter } #[inline] fn set_max_iter(&mut self, new_max_iter: IterCount) { self.general_plane.max_iter = new_max_iter; } #[must_use] fn with_max_iter(mut self, max_iter: IterCount) -> Self { self.general_plane.max_iter = max_iter; self } #[inline] fn point_grid(&self) -> &PointGrid { &self.general_plane.point_grid } #[inline] fn point_grid_mut(&mut self) -> &mut PointGrid { &mut self.general_plane.point_grid } #[inline] fn with_point_grid(mut self, point_grid: PointGrid) -> Self { self.general_plane.point_grid = point_grid; self } #[inline] fn compute_mode(&self) -> ComputeMode { self.general_plane.compute_mode() } #[inline] fn compute_mode_mut(&mut self) -> &mut ComputeMode { self.general_plane.compute_mode_mut() } #[inline] fn map(&self, z: Self::Var, c: &Self::Param) -> Self::Var { self.general_plane.map(z, c) } fn param_map(&self, t: Cplx) -> Self::Param { let t = t.inv() - 2.; let alpha = 0.25 * t; CplxPair { a: alpha * t * (t + 1.), b: -alpha * (4. + 3. * t), } } #[inline] fn periodicity_tolerance(&self) -> Real { 1e-6 } #[inline] fn map_and_multiplier(&self, z: Self::Var, c: &Self::Param) -> (Self::Var, Self::Deriv) { self.general_plane.map_and_multiplier(z, c) } #[inline] fn start_point(&self, t: Cplx, c: &Self::Param) -> Self::Var { self.general_plane.start_point(t, c) } } default_bounds_impl!(QuadRatPer1_1, Bounds::centered_square(3.)); has_child_impl!(QuadRatPer1_1); impl MarkedPoints for QuadRatPer1_1 { #[inline] fn critical_points_child(&self, c: &Self::Param) -> Vec<Self::Var> { self.general_plane.critical_points_child(c) } #[inline] fn cycles_child(&self, c: &Self::Param, period: Period) -> Vec<Self::Var> { self.general_plane.cycles_child(c, period) } } degree_impl!(QuadRatPer1Lambda, 1, 1); degree_impl!(QuadRatPer1LambdaParam, 1, 1); degree_impl!(QuadRatPer1_1, 1, 1);
package aug.bueno; import io.github.bonigarcia.wdm.WebDriverManager; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import java.util.List; import java.util.concurrent.TimeUnit; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class SeleniumTest { @LocalServerPort private Integer port; private static WebDriver driver; @BeforeAll public static void beforeAll(){ WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); } @AfterAll public static void afterAll(){ driver.close(); } @Test public void testAnimalEndpoint() throws InterruptedException { //start the driver, open chrome to our target url driver.get("http://localhost:"+port+"/animal"); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); //find the fields we want by id and fill them in WebElement inputField = driver.findElement(By.id("animalText")); inputField.sendKeys("Manatee"); inputField = driver.findElement(By.id("adjective")); inputField.sendKeys("Whirling"); List<WebElement> trainingResults = driver.findElements(By.className("trainingMessage")); // The field-values don’t clear on submit for our simple app, so just submit it 5 times // However, the elements gets removed from the DOM structure after each submit. for(int i = 0; i < 5; i++) { // We are re-assigning the inputField because this element gets removed from the DOM structure after each iteration. // Otherwise, you'll get org.openqa.selenium.StaleElementReferenceException at runtime. inputField = driver.findElement(By.id("adjective")); inputField.submit(); System.out.println("trainingResults.size() = " + trainingResults.size()); } // then get the element by the class conclusionMessage and print it WebElement conclusionResult = driver.findElement(By.className("conclusionMessage")); System.out.println("conclusionResult.getText() = " + conclusionResult.getText()); Thread.sleep(5000); } }
<?php // $Id$ /** * Implementation of hook_install(). */ function og_member_profile_install() { drupal_install_schema('og_member_profile'); } /** * Implementation of hook_uninstall(). */ function og_member_profile_uninstall() { drupal_uninstall_schema('og_member_profile'); } /** * Implementation of hook_schema(). */ function og_member_profile_schema() { $schema['og_member_profile_question'] = array( 'description' => 'Stores a member profile questions', 'fields' => array( 'qid' => array( 'type' => 'serial', 'size' => 'medium', 'unsigned' => TRUE, 'not null' => TRUE, 'description' => t("The serial number for a question."), ), 'gid' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => "The group node nid {gid}", ), 'title' => array( 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', 'description' => 'The question title.', ), 'weight' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => "question order", ), ), 'primary key' => array('qid'), 'indexes' => array( 'qid' => array('qid'), ), ); $schema['og_member_profile_answer'] = array( 'description' => 'Stores each question answer value', 'fields' => array( 'aid' => array( 'type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE), 'qid' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0), 'answer' => array( 'type' => 'text', 'size' => 'normal'), 'uid' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => t("who answer this questions?"), ), ), 'primary key' => array('aid'), ); $schema['og_member_profile'] = array( 'description' => 'Stores each members profile contents', 'fields' => array( 'pid' => array( 'type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE), 'gid' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0), 'uid' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => t("who's profile for this group"), ), 'introduction' => array( 'type' => 'text', 'size' => 'normal', ), 'photo_fid' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => t("The photo file id fid "), ), 'show_photo' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 1, 'description' => t("if allow to show the photo in this group"), ), 'websiteurl' => array( 'description' => t('extra- website url'), 'type' => 'varchar', 'length' => 255, 'not null' => false, ), 'websitename' => array( 'description' => t('extra- website name'), 'type' => 'varchar', 'length' => 255, 'not null' => false, ), 'additional' => array( 'description' => t('extra- additional'), 'type' => 'text', 'size' => 'normal', ), 'notifyme' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => t("notify me status, 0 for not notify , 1 for notify me"), ), 'membertitle' => array( 'type' => 'varchar', 'length' => 255, 'description' => t("each group meber can be assigned a title"), ), 'social' => array( 'type' => 'varchar', 'length' => 255, 'description' => t("follow me on each social site ,such as qq, weibo"), ), 'status' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => t("profile status, 0 for not publish , 1 for publish"), ), ), 'primary key' => array('pid'), ); return $schema; }
// Procedures are not the only things that can be polymorphic. // We can also make data structures polymorphic, and in fact this is common. polymorphic_structs :: () { { // // Just like procedures, struct declarations can have argument lists. // These arguments can be used inside the body of the struct to determine // types and values of the struct's members. // // But, since this is a statically-typed, fully-compiled programming language, // all these decisions about the struct's members are made at compile-time, // because that is what allows programs to run efficiently. At compile-time, // the compiler bakes these struct declarations down into structs that have // no more parameters. // Let's look at a simple example: Holder :: struct ($T: Type, $N: s64) { array: [N] T; } // We can instantiate Holder with parameters, the same way we would call a procedure: floats: Holder(float, 5); vectors: Holder(Vector3, 3); print("floats: %\n", floats); print("vectors: %\n", vectors); // Holder(a, b) looks like a procedure call, syntactically. But it's a bit different // because the process of supplying the arguments and creating a baked-down version // of Holder happens completely at compile-time. Thus the arguments to Holder // must all be constant. // So, Holder(float, 5) is converted into a struct that would be exactly the same // as the following: Other_Holder :: struct { array: [5] float; } others: Other_Holder; print("type_of(floats) is %; size is %.\n", type_of(floats), size_of(type_of(floats))); print("type_of(others) is %; size is %.\n", type_of(others), size_of(type_of(others))); print("type_of(floats.array) is %.\n", type_of(floats.array)); print("type_of(others.array) is %.\n", type_of(others.array)); // type_of(floats) and type_of(others) are not the same, because all structs represent // types distinct from each other. But they are the same size and have members laid out // the same way. // type_of(floats.array) is the same as type_of(others.array), because these are just normal array types: print("type_of(floats.array) == type_of(others.array): %\n", type_of(floats.array) == type_of(others.array)); assert(type_of(floats.array) == type_of(others.array)); // But different polymorphs of the *same* parameter-taking struct will map to the same result type // if the parameters match: // Let's make another instantiation of Holder, but let's make it look different from the declaration // of 'floats' above. We can do this by supplying the parameters in a different order. // Struct parameters can be provided using names, in any order, just like procedure parameters: named_floats: Holder(N = 5, T = float); print("named_floats: %\n", named_floats); print("type_of(named_floats) is %\n", type_of(named_floats)); // And, just like with procedures, there's a guarantee that, if you // polymorph two versions of the same struct, with the same arguments, // those will map to exactly the same type. assert(type_of(floats) == type_of(named_floats)); // Even though we polymorphed them two different times! // Because the types are the same, we can assign one to the other: named_floats.array[1] = 42; floats = named_floats; // This is legal! print("floats: %\n", floats); assert(floats.array[1] == 42); } print("\n"); // In the above declaration of Holder, we put $ markers on our types, as would // be consistent with the procedures we saw in 115_auto_bakes. // // However, because struct parameters are all supplied at compile-time, there // is no possibility that they are non-constant. So the $ is superflous // and we can simply choose not to write it: { Holder :: struct (T: Type, N: s64) { // This does exactly the same thing as our prior 'Holder' example, with no $! array: [N] T; } floats: Holder(float, 5); vectors: Holder(Vector3, 3); print("floats: %\n", floats); print("vectors: %\n", vectors); print("\n"); // As we saw before, // a fully-specified struct type -- one that has all its parameters filled -- // is just a normal type like any other struct type. // Let's do some more things with a polymorphed Holder: Some_Type :: type_of(vectors); print("Some_Type is %\n", Some_Type); // We can instantiate it at will, without writing out the type parameters and // performing a polymorph process -- that process is already done! some: Some_Type; print("type_of(some) is %\n", type_of(some)); print("some = %\n", some); // If a struct has *not* had its parameters filled, you can't use it // to instantiate variables or do anything involving runtime code, // for exactly the same reason that a polymorphic procedure is not // a runtime value: because this is a compile-time statically-typed language, // the type of the entire thing must be known before any code is ever run. // So attempting to use a struct that hasn't had all its parameters supplied, // or a polymorphic procedure that hasn't had all its polymorphic parameters supplied, // is an error. // Here's an example of what it looks like if you forgot the struct takes parameters: // mistake: Holder; // Uncomment this to see Error: Attempt to use polymorphic struct 'Holder' ... // Not supplying all the parameters is also an error: // mistake2: Holder(float); // Uncomment this to see Error: Not enough struct arguments: Wanted 2, got 1. // mistake3: Holder(N = 111); // Uncomment this to see Error: Struct instantiation is missing argument 'T'. } { // Structs can provide default values for any of their arguments. Holder :: struct (T: Type = string, N: s64 = 3) { array: [N] T; } // Now that defaults are supplied, the previous instantiations, with fewer than two parameters, are no longer mistakes: non_mistake: Holder; print("type_of(non_mistake) is %\n", type_of(non_mistake)); // Not supplying all the parameters is also no longer an error: non_mistake2: Holder(float); non_mistake3: Holder(N = 111); print("type_of(non_mistake2) is %\n", type_of(non_mistake2)); print("type_of(non_mistake3) is %\n", type_of(non_mistake3)); // // This provides an interesting kind of forward-compatibility: You can start writing your code // using a struct that is non-polymorphic, and instantiates it that way, as 'non_mistake' above. // Then one day, if you decide it needs a parameter, then as long as you provide a default value, // you don't have to change the old code: it doesn't need to know it is handling a polymorphic struct. // This is strictly better than the template syntax of languages like C++, which doesn't let you // do this. // } } structs_as_procedure_parameters :: () { { // It's very common to write procedures that take any polymorph of a struct, // and operate on those generally. For example: Holder :: struct ($T: Type, $N: s64) { array: [N] T; } do_indices_match :: (holder: Holder($T, $N), i0: int, i1: int) -> bool { return holder.array[i0] == holder.array[i1]; } // This declaration of do_indices_match will work for any Holder whose array // elements can be compared via ==. floats: Holder(float, 5); for 0..floats.N-1 { // Note that we can use floats.N, because N is in the constants block of 'floats': floats.array[it] = cast(float)(it + 1); } print("floats.array is %\n", floats.array); matching := do_indices_match(floats, 0, 4); print("matching: %\n", matching); assert(matching == false); // Let's change index 4 to get a matching == true: floats.array[4] = 1.0; matching = do_indices_match(floats, 0, 4); print("matching: %\n", matching); assert(matching == true); // The way we wrote Holder($T, $N) in do_indices_match is optional. If we want, we can just say Holder, // without parameters; whereas in a declaration on the stack, that means "give me the default values of the parameters", // in a procedure header like this, it means "any values of the parameters match this type". This means you can // write procedures that look like their arguments are not polymorphic, which is convenient because you can // add or remove parameters over time without having to modify these procedures: do_indices_match2 :: (holder: Holder, i0: int, i1: int) -> bool { // When the user calls this routine, the type of whatever Holder they pass in // determines the type of 'holder'. In the previous version, where we wrote Holder($T, $N), // you have an easy way to refer to T and N. But it's tedious to maintain that over time, // so, instead you could dereference the struct to see the parameters: print("In do_indices_match2, T is % and N is %.\n", holder.T, holder.N); return holder.array[i0] == holder.array[i1]; } matching = do_indices_match2(floats, 0, 4); print("matching: %\n", matching); assert(matching == true); // This ability to write polymorphic structs without parameters, and have the type match, // works even if the struct is not the toplevel type: hello :: (p: *Holder) { print("<<p is %\n", << p); } hello(*floats); hello2 :: (p: *[..] *Holder) { print("<<p is %\n", << p); } array: [..] *type_of(floats); array_add(*array, *floats); hello2(*array); // Is it bad that, when reading program text, you don't necessarily know whether an argument // is a polymorphic type? Maybe. But this is a place where your editor or other kind of IDE // can highlight it to help you. In general, please don't get carried away making things polymorphic // if they do not need to be, and this hopefully won't be a huge problem. } } variables_in_the_type_slot :: () { /* We started this file with a declaration of Holder that put the $ in front of the variable name: Holder :: struct ($T: Type, $N: s64) { } then showed how to elide that $: Holder :: struct (T: Type, N: s64) { } but so far, these have all been auto-bake-style $ on the variable name (which is natural for structs, because, as we mentioned, all struct parameters are constant at compile-time, and compile-time-constant parameters are signalled by $ in procedures). But, just as with procedures, we can also put variables in the type slot of the parameter declarations: */ Thing :: struct (x: $T) { y := x; } thing1: Thing("Hello, Sailor"); thing2: Thing(main); print("thing1 = %\n", thing1); print("thing2 = %\n", thing2); // In 'thing' above, both 'x' and 'T' get baked at compile-time when you instantiate the struct type. // This works, just like procedures, if the type slot is more complex: Bling :: struct (x: [$N] $T) { y := x; } SimpleProcedure :: #type () -> (); // This declaration of SimpleProcedure helps make the following declaration more readable: bling1: Bling(SimpleProcedure.[polymorphic_structs, structs_as_procedure_parameters, limitation, main]); print("bling1 = %\n", bling1); } limitation :: () { // There's a limitation right now, with the interaction of polymorph variables // in the type slot, and parameter auto-bakes, which is that they need to all // be solved in one step, thus they can't depend on each other in the same // procedure declaration. So there are some procedure signatures you can't write. // We will probably fix this in the longer term. For now, here's an example: Thing :: struct (T: Type) { } foo :: ($T: Type, $ReturnType: Type = Thing(T)) -> ReturnType { a: ReturnType; return a; } // Uncomment this call to 'foo' to see the error. // foo(float); } reducing_polymorphism :: () { // // If lots of procedures in your program are polymoprhic, you pay for this in compile time, and // possibly also in understandability of the program. Polymorphism is powerful, but historically, // when people start writing code that is over-generic, it becomes hard to understand and modify. // // Sometimes you can break a struct into polymorphic and non-polymorphic parts, and have a core // set of procedures that operate on the non-polymorphic parts, which reduces the volume of code // that is polymorphic. // // Here's an example. // We're making a struct Holder, that takes a parameter X. But we'll also have HolderBase, // which stores some information common to any instantiation of Holder: Holder_Base :: struct { // Not polymorphic! type: Type; size: s64; } Holder :: struct ($X: Type) { // Polymorphic! #as using base: Holder_Base; // When initialized at runtime, assign these values to our member variables. // We store X as a runtime value so that it can be queried by someone who doesn't // know the polymorphic type. This takes memory, but lets us do runtime-dynamic things. base.type = X; base.size = size_of(X); instance: X; } holder1: Holder(string); holder2: Holder(u8); // The following 'set' is polymorphic in the type of 'holder'; because we want to make that obvious, for this example, // we'll write the argument $X, though we don't have to: set :: (holder: *Holder($X), value: X) { holder.instance = value; } set(*holder1, "Hello, Sailor"); set(*holder2, 42); print("holder1: %\n", holder1); print("holder2: %\n", holder2); // We can also call routines on these that require only Holder_Base: print_type_and_size :: (base: Holder_Base) { print("type %, size %.\n", base.type, base.size); } print_type_and_size(holder1); print_type_and_size(holder2); // Since we are storing the type in a runtime-readable way on Holder_Base, we can even do // dynamic-dispatch kinds of stuff: inspect :: (base: *Holder_Base) { if base.type == { case u8; casted := cast(*Holder(u8)) base; print("This Holder is storing a u8. Its u8 value is: %\n", casted.instance); case string; casted := cast(*Holder(string)) base; print("This Holder is storing a string. Its string value is: %\n", casted.instance); case; print("Error: Unknown type in Holder_Base!\n"); } } inspect(*holder1); inspect(*holder2); // You can tell that print_type_and_size and inspect are not polymorphic, because // you can assign them to runtime variables: a1 := print_type_and_size; a2 := inspect; print("a1 %, a2 %\n", a1, a2); // But you can't do this with 'set', for reasons discussed in 100_polymorphic_procedures. // a3 := set; // Uncomment to see Error: This declaration has a polymorphic type... } // That's all for now! main :: () { print("\n"); print("Polymorphic structs:\n"); print("\n"); polymorphic_structs(); print("\n"); print("Structs as Procedure Parameters:\n"); print("\n"); structs_as_procedure_parameters(); print("\n"); print("Variables in the Type Slot:\n"); print("\n"); variables_in_the_type_slot(); print("\n"); print("Limitation:\n"); print("\n"); limitation(); print("\n"); print("Reducing Polymorphism:\n"); print("\n"); reducing_polymorphism(); print("\n"); } #import "Basic"; #import "Math";
// ignore_for_file: public_member_api_docs import 'package:get/get.dart'; import 'package:i_attend_capture/_state/app_service.dart'; import '../_core/notification_utils.dart'; import '../_core/preference_utils.dart'; import '../_provider/event_provider.dart'; import '../_repository/event_repository.dart'; import '../screens/event_details/event_details.x.dart'; import '../screens/event_list/event_list.x.dart'; import '../screens/view_attendance/view_attendance.x.dart'; class EventService extends GetxService { static EventService get X => Get.find(); Future<void> fetchEvents({ DateTime? selectedDate, bool isSilent = false, }) async { try { if (!isSilent) { AppService.X.loaderRx(true); } final plusDays = PreferenceUtils.getSettings().syncEventDays + 3; final date = (selectedDate ?? DateTime.now()).subtract(const Duration(days: 3)); final savedIds = await EventRepository.X.getSavedScheduleIds(); final eventListModel = await EventProvider.X.fetchEventList( date: date, plusDays: plusDays, savedId: savedIds, ); if (eventListModel.isError ?? false) { NotificationUtils.showErrorSnackBar( message: eventListModel.errorMessage ?? "Something went wrong while signing in.".tr, ); return; } if ((eventListModel.events ?? []).isNotEmpty) { await EventRepository.X.addOrUpdate(eventListModel.events!); } if ((eventListModel.deletedIds ?? []).isNotEmpty) { await EventRepository.X.deleteByScheduleIds(eventListModel.deletedIds!); } } finally { if (Get.isRegistered<EventListX>()) { await Get.find<EventListX>().updateEventsToShow(); } if (Get.isRegistered<EventDetailsX>()) { Get.find<EventDetailsX>().revalidate(); } if (Get.isRegistered<ViewAttendanceX>()) { Get.find<ViewAttendanceX>().revalidate(); } if (!isSilent) { AppService.X.loaderRx(false); } } } Future<List<DateTime>> getEventDates({ required DateTime from, required DateTime till, }) async => EventProvider.X.fetchEventDates( from: from, till: till, ); }
import React from 'react'; import { Link, useNavigate } from 'react-router-dom'; const Friend = ({ friend }) => { const { id, name, username } = friend; const navigate = useNavigate(); const showFriendDetail = () => { const path = `/friend/${id}`; navigate(path); } return ( <div> <h2>Name: {name}</h2> <Link to={`/friend/${id}`}> Show Details </Link> <br /> <button onClick={showFriendDetail}>{username} id:{id}</button> </div> ); }; export default Friend;
<template> <div v-if="food"> <router-link to="/"> <div class="food-actions flex"> <button class="mr-[15px]"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-arrow-back-up" width="44" height="44" viewBox="0 0 24 24" stroke-width="1.5" stroke="#000" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <path d="M9 13l-4 -4l4 -4m-4 4h11a4 4 0 0 1 0 8h-1" /> </svg> Go back </button> <router-link :to="{path: `/edit/${food._id}`}"> <button class="mr-[15px]"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-pencil" width="44" height="44" viewBox="0 0 24 24" stroke-width="1.5" stroke="#000000" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <path d="M4 20h4l10.5 -10.5a1.5 1.5 0 0 0 -4 -4l-10.5 10.5v4" /> <line x1="13.5" y1="6.5" x2="17.5" y2="10.5" /> </svg> Edit </button> </router-link> <button @click="removeItem"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-trash" width="44" height="44" viewBox="0 0 24 24" stroke-width="1.5" stroke="#000000" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <line x1="4" y1="7" x2="20" y2="7" /> <line x1="10" y1="11" x2="10" y2="17" /> <line x1="14" y1="11" x2="14" y2="17" /> <path d="M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12" /> <path d="M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3" /> </svg> Delete </button> </div> </router-link> <div class="food-cover w-full h-[300px]"> <img src="https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fimg1.cookinglight.timeinc.net%2Fsites%2Fdefault%2Ffiles%2Fstyles%2Fmedium_2x%2Fpublic%2Fimage%2F2017%2F01%2Fmain%2Fdiner-style-scrambled-eggs.jpg%3Fitok%3DQ-A612IW" alt=""> </div> <h2 class="uppercase text-2xl font-bold mb-[20px]"> {{ food.title }} </h2> <div class="flex"> <div class="food-desc mr-[200px]"> <h2 class="mb-[10px] uppercase text-xl font-bold"> Description: </h2> <p> {{ food.description }} </p> </div> <div> <h2 class="mb-[10px] uppercase text-xl font-bold"> Ingredients: </h2> <ul> <li v-for="(ig, i) in food.ingredients" :key="i"> {{ig}} </li> </ul> </div> </div> </div> </template> <script> import axios from 'axios' export default { name: "c-food", props: ['id'], data() { return { food: null } }, created() { this.fetchSingleFood() }, methods: { async fetchSingleFood() { const food = await axios.get(`https://foodforthebestapi.herokuapp.com/api/recipes/${this.id}`) this.food = food.data.data }, removeItem() { const userYes = confirm('You sure to remove item?') if (userYes) { axios.delete(`https://foodforthebestapi.herokuapp.com/api/recipes/${this.id}`) } } } } </script> <style> .food-cover { overflow: hidden; margin-bottom: 20px; } .food-cover img { width: 100%; object-fit: cover; } </style>
package com.ingic.saeedni.ui.viewbinder; import android.app.Activity; import android.graphics.Typeface; import android.text.Html; import android.text.SpannableStringBuilder; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.ingic.saeedni.R; import com.ingic.saeedni.activities.DockActivity; import com.ingic.saeedni.entities.NavigationEnt; import com.ingic.saeedni.fragments.SideMenuFragment; import com.ingic.saeedni.helpers.BasePreferenceHelper; import com.ingic.saeedni.helpers.ClickableSpanHelper; import com.ingic.saeedni.interfaces.UpdateNotificationsCount; import com.ingic.saeedni.ui.viewbinders.abstracts.ViewBinder; import com.ingic.saeedni.ui.views.AnyTextView; import com.ingic.saeedni.ui.views.BadgeHelper; import butterknife.BindView; import butterknife.ButterKnife; /** * Created on 5/24/2017. */ public class NavigationItemBinder extends ViewBinder<NavigationEnt> implements UpdateNotificationsCount { DockActivity dockActivity; BadgeHelper badgeHelper; BasePreferenceHelper prefHelper; UpdateNotificationsCount count; int badgeCount; ImageView countView; public NavigationItemBinder(DockActivity activity, SideMenuFragment fragment, BasePreferenceHelper prefHelper) { super(R.layout.row_item_nav); this.dockActivity = activity; this.prefHelper = prefHelper; fragment.setInterface(this); } @Override public BaseViewHolder createViewHolder(View view) { return new NavViewHolder(view); } @Override public void bindView(NavigationEnt entity, int position, int grpPosition, View view, Activity activity) { NavViewHolder viewHolder = (NavViewHolder) view.getTag(); if (prefHelper.isLanguageArabic()){ viewHolder.rootLayout.setLayoutDirection(View.LAYOUT_DIRECTION_RTL); } else viewHolder.rootLayout.setLayoutDirection(View.LAYOUT_DIRECTION_LTR); viewHolder.txtLanguage.setVisibility(View.GONE); badgeHelper = new BadgeHelper(viewHolder.imgNotificationCount, (DockActivity) activity); if (entity.getItem_text().equals(activity.getResources().getString(R.string.home)) && !entity.getItem_text().equals(activity.getResources().getString(R.string.english))) { viewHolder.txtHome.setText(entity.getItem_text()); //viewHolder.imgUnselected.setImageResource(entity.getSelectedDrawable()); viewHolder.txtHome.setTextColor(activity.getResources().getColor(R.color.app_blue)); viewHolder.imgUnselected.setVisibility(View.VISIBLE); badgeHelper.hideBadge(); } else { viewHolder.imgSelected.setVisibility(View.GONE); viewHolder.imgUnselected.setVisibility(View.INVISIBLE); viewHolder.txtHome.setText(entity.getItem_text()); viewHolder.txtHome.setTextColor(activity.getResources().getColor(R.color.black)); badgeHelper.hideBadge(); if (entity.getItem_text().equals(activity.getResources().getString(R.string.notifications))) { badgeHelper.initBadge(activity); badgeHelper.addtoBadge(prefHelper.getBadgeCount()); badgeHelper.showBadge(); } else if (entity.getItem_text().equals(activity.getResources().getString(R.string.english)) && !entity.getItem_text().equals(activity.getResources().getString(R.string.home))) { viewHolder.txtLanguage.setVisibility(View.VISIBLE); viewHolder.txtHome.setText(activity.getResources().getString(R.string.language)); viewHolder.txtHome.setTextColor(activity.getResources().getColor(R.color.black)); if (prefHelper.isLanguageArabic()) { String sourceString = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b> <font color='#fcc739'>" + dockActivity.getResources().getString(R.string.ar) + "</font> </b> " + " |" + dockActivity.getResources().getString(R.string.eng); viewHolder.txtLanguage.setText(Html.fromHtml(sourceString)); viewHolder.txtLanguage.setGravity(Gravity.RIGHT); } else { String sourceString = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b><font color='#fcc739'>" + dockActivity.getResources().getString(R.string.eng) + "</font></b> " + " | " + dockActivity.getResources().getString(R.string.ar); viewHolder.txtLanguage.setText(Html.fromHtml(sourceString)); viewHolder.txtLanguage.setGravity(Gravity.LEFT); } } } } /* private void changeBadgeSide(int GravitySide, ImageView imgBadge) { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(imgBadge.getWidth(), imgBadge.getHeight()); params.addRule(GravitySide); imgBadge.setLayoutParams(params); } private void setSignupSpan(String text, String spanText, AnyTextView txtview) { SpannableStringBuilder stringBuilder = ClickableSpanHelper.initSpan(text); ClickableSpanHelper.setSpan(stringBuilder, text, spanText, new ClickableSpan() { @Override public void updateDrawState(TextPaint ds) { // ds.setColor(getResources().getColor(R.color.white)); // you can use custom color ds.setTypeface(Typeface.DEFAULT_BOLD); ds.setUnderlineText(false); // this remove the underline } @Override public void onClick(View widget) { if (prefHelper.isLanguageArabic()) { prefHelper.putLang(dockActivity, "en"); } else { prefHelper.putLang(dockActivity, "ar"); } } }); ClickableSpanHelper.setColor(stringBuilder, text, spanText, "#fcc739"); ClickableSpanHelper.setClickableSpan(txtview, stringBuilder); } private void LanguageChange(final View txtHome) { txtHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (prefHelper.isLanguageArabic()) { prefHelper.putLang(dockActivity, "en"); } else { prefHelper.putLang(dockActivity, "ar"); } } }); } */ @Override public void updateCount(int count) { badgeCount = count; badgeHelper.addtoBadge(count); badgeHelper.getImgNotificationCounter().invalidate(); badgeHelper.showBadge(); } public static class NavViewHolder extends BaseViewHolder { @BindView(R.id.img_selected) ImageView imgSelected; @BindView(R.id.img_unselected) ImageView imgUnselected; @BindView(R.id.txt_home) AnyTextView txtHome; @BindView(R.id.txt_language) AnyTextView txtLanguage; @BindView(R.id.txt_line) View txtLine; @BindView(R.id.ll_item_container) LinearLayout container; @BindView(R.id.imgNotificationCount) ImageView imgNotificationCount; @BindView(R.id.root_layout) LinearLayout rootLayout; NavViewHolder(View view) { ButterKnife.bind(this, view); } } }
<!DOCTYPE html> <html lang="en" data-theme="light"> <head> <meta charset="UTF-8" /> <meta name="viewport" contetickets nt="width=devtickets ice-width, initial-scale=1.0" /> <title>Smart Bus Ticketing</title> <link rel="stylesheet" href="styles/style.css" /> <!-- Tailwind and Daisy UI --> <link href="https://cdn.jsdelivr.net/npm/daisyui@4.7.2/dist/full.min.css" rel="stylesheet" type="text/css" /> <script src="https://cdn.tailwindcss.com"></script> </head> <body> <header class="lg:max-w-[1170px] lg:mx-auto mx-5"> <!-- Start Navbar Section --> <section class="py-9"> <div class="navbar bg-base-100 font-raleway"> <div class="navbar-start"> <div class="dropdown"> <div tabindex="0" role="button" class="btn btn-ghost lg:hidden"> <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path stroke-linecap="round" stroke-linejoin="round" strtickets oke-width="2" d="M4 6h16M4 12h8m-8 6h16" /> </svg> </div> <ul tabindex="0" class="menu menu-sm dropdown-content mt-3 z-[1] p-2 shadow bg-base-100 rounded-box w-52" > <li><a>Home</a></li> <li><a>About</a></li> <li><a>Destination</a></li> <li><a>Search</a></li> </ul> </div> <a class="text-4xl font-extrabold cursor-pointer">P-Ticket</a> </div> <div class="navbar-center hidden lg:flex"> <ul class="menu menu-horizontal px-1 text-[18px] font-medium"> <li><a>Home</a></li> <li><a>About</a></li> <li><a>Destination</a></li> <li><a>Search</a></li> </ul> </div> <div class="navbar-end"> <a class="flex gap-2 cursor-pointer text-xl text-[#1DD100] bg-[#1DD1001A] font-bold px-8 py-4 rounded-xl border-solid border-[#1DD10066] border-[1px]" >Bus <img src="images/bus-icon.png" alt="" /></a> </div> </div> </section> <!-- End Navbar Section --> <!-- Start Hero Section --> <section class="bg-[url('images/banner.png')] rounded-[32px] bg-no-repeat bg-cover bg-center lg:h-[550px] py-16 text-center font-inter flex flex-col justify-center items-center" > <!-- 1st Part --> <div class="space-y-6"> <h1 class="lg:text-[64px] text-5xl text-white font-extrabold"> End-to-End Travel With <br /> <span class="text-[#1DD100]">P Paribahan</span> </h1> <p class="text-white text-[18px]"> Yes, you can run unit tests and view the results directly within the <br />app. The integrated testing features allow for a streamlined . </p> <div class=""> <a href="#ph-paribahan" class="px-7 py-5 bg-[#1DD100] text-xl font-bold rounded-xl" > Buy Tickets </a> </div> </div> <!-- 2nd Part --> <div class="lg:max-w-[1000px] lg:mx-auto flex lg:flex-row flex-col gap-6 mt-16 lg:-mb-44" > <div class="flex py-8 px-10 bg-white gap-4 rounded-3xl items-center border-b-2 border-[#1DD100]" > <img src="images/people.png" alt="" /> <div class="text-start py-2"> <h3 class="text-4xl font-bold">500K+</h3> <p class="text-[18px]">Registered users</p> </div> </div> <div class="flex py-8 px-10 bg-white gap-4 rounded-3xl items-center border-b-2 border-[#1DD100]" > <img src="images/ticket-cupon.png" alt="" /> <div class="text-start py-2"> <h3 class="text-4xl font-bold">1.7 lacks</h3> <p class="text-[18px]">Tickets sold</p> </div> </div> <div class="flex py-8 px-10 bg-white gap-4 rounded-3xl items-center border-b-2 border-[#1DD100]" > <img src="images/stoppage.png" alt="" /> <div class="text-start py-2"> <h3 class="text-4xl font-bold">80K+</h3> <p class="text-[18px]">Rental partners</p> </div> </div> </div> </section> <!-- End Hero Section --> </header> <main class=""> <!-- Start Offer Section --> <section class="lg:mt-28 lg:mb-24 my-8 lg:max-w-[1170px] lg:mx-auto mx-5"> <div class="text-center"> <h2 class="text-[40px] font-bold font-raleway"> Best offers for you </h2> </div> <!-- Start Coupon Section --> <div class="font-inter my-10 text-[#030712CC] flex gap-6 justify-between lg:flex-row flex-col" > <div class="bg-[#FFBF0F] flex items-center gap-5 rounded-3xl px-12"> <div class=""> <h4 class="text-[40px] font-black">15% OFF</h4> <h6 class="text-xl font-semibold"> on your next purchase <br /><span class="text-[#03071233]" >use by January 2024</span > </h6> </div> <img src="images/cupon-devider.png" alt="" /> <div class=""> <h4 class="text-[40px] font-raleway font-black">NEW15</h4> <h6 class="text-xl text-[#03071233] font-semibold"> Coupon Code </h6> </div> </div> <div class="bg-[#F78C9C] flex items-center gap-5 rounded-3xl px-12"> <div class=""> <h4 class="text-[40px] font-black">20% OFF</h4> <h6 class="text-xl font-semibold"> on your next purchase <br /><span class="text-[#03071233]" >use by January 2024</span > </h6> </div> <img src="images/cupon-devider.png" alt="" /> <div class=""> <h4 class="text-[40px] font-raleway font-black">Couple 20</h4> <h6 class="text-xl text-[#03071233] font-semibold"> Coupon Code </h6> </div> </div> </div> <!-- End Coupon Section --> <div class="flex justify-center"> <button class="flex gap-2 cursor-pointer text-xl text-[#1DD100] font-bold px-8 py-4 rounded-xl border-solid border-[#1DD100] border-[1px]" > See All Offers </button> </div> </section> <!-- End Offer Section --> <!-- Start Offer Section --> <section class="py-28 bg-[#F7F8F8] border-t-2 border-[#1DD100] rounded-t-[88px] space-y-7" > <div class="lg:max-w-[1170px] lg:mx-auto mx-5"> <div class="text-center space-y-4 lg:mb-12 mb-6"> <h2 id="ph-paribahan" class="text-[40px] font-bold font-raleway"> P.H Paribahan </h2> <p class="text-[#03071299] text-[18px]"> Yes, you can run unit tests and view the results directly within the app. The integrated <br />testing features allow for a streamlined . </p> </div> <div class="flex justify-between bg-white rounded-3xl items-center px-8" > <div class="w-[800px] space-y-6"> <div class="flex justify-between items-center"> <div class="flex gap-4 items-center"> <img src="images/bus-logo.png" alt="" /> <div class=""> <h4 class="text-[#030712] text-[32px] font-bold"> Greenline Paribahan </h4> <p class="text-[18px] text-[#03071299]"> Coach-009-WEB ! AC_Business </p> </div> </div> <div class=""> <a class="flex gap-2 cursor-pointer text-[18px] text-[#1DD100] bg-[#1DD1001A] font-medium p-4 rounded-xl" ><img src="images/seat-green.png" alt="" /> <span id="total-seat">40</span> Seats left </a> </div> </div> <div class="p-8 bg-[#F7F8F8] rounded-3xl space-y-6"> <div class="font-raleway flex justify-between pb-6 border-dashed border-[#03071233] border-b-2" > <h5 class="text-[18px] text-[#03071299] font-semibold"> Route </h5> <h5 class="text-[18px] text-[#030712] font-semibold"> Dhaka - Sylhet </h5> </div> <div class="font-raleway flex justify-between pb-6 border-dashed border-[#03071233] border-b-2" > <h5 class="text-[18px] text-[#03071299] font-semibold"> Departure Time </h5> <h5 class="text-[18px] text-[#030712] font-semibold"> 9:00 PM </h5> </div> <div class="font-inter flex justify-between pb-6 border-dashed border-[#03071233] border-b-2 gap-6" > <h5 class="text-base text-[#030712CC] px-6 py-[18px] bg-[#0307120D] font-semibold rounded-xl" > Boarding Point - Laxmipur </h5> <h5 class="text-base text-[#030712CC] px-6 py-[18px] bg-[#0307120D] font-semibold rounded-xl" > Dropping Point - Bogura </h5> <h5 class="text-base text-[#030712CC] px-6 py-[18px] bg-[#0307120D] font-semibold rounded-xl" > Est. Time - 11 Hour </h5> </div> </div> </div> <img class="h-[490px]" src="images/info-devider.png" alt="" /> <div class="flex flex-col justify-center items-center pr-4"> <img src="images/fare.png" alt="" /> <h4 class="text-[32px] font-black">550 Taka</h4> <h6 class="text-[#03071299] text-[24px] font-semibold"> Per Seat </h6> </div> </div> </div> <div class="lg:max-w-[1170px] lg:mx-auto mx-5 bg-white rounded-3xl p-8 flex font-inter" > <div class="border-r-2 border-dashed border-[#0307124D] pr-8 space-y-6" > <div class="pb-6 border-b-2 border-dashed border-[#03071233]"> <h4 class="text-2xl font-semibold font-relaway"> Select Your Seat </h4> </div> <div class="pb-6 border-b-2 border-dashed border-[#03071233] flex justify-between" > <div class="flex gap-2"> <img src="images/seat-gray.png" alt="" /> <h4 class="text-lg text-[#03071280] font-medium font-relaway"> Available </h4> </div> <div class="flex gap-2"> <img src="images/seat-green-filled.png" alt="" /> <h4 class="text-lg text-[#1DD100] font-medium font-relaway"> Selected </h4> </div> </div> <div class="flex justify-end"> <button class="py-4 px-11 bg-[#0307121A] rounded-xl"> <img src="images/wheel.png" alt="" /> </button> </div> <div class="flex gap-16 items-center font-inter"> <div class="text-[#03071280] space-y-7"> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <h5>A</h5> <button class="tickets btn width">A1</button> <button class="tickets btn width">A2</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <h5>B</h5> <button class="tickets btn width">B1</button> <button class="tickets btn width">B2</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <h5>C</h5> <button class="tickets btn width">C1</button> <button class="tickets btn width">C2</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <h5>D</h5> <button class="tickets btn width">D1</button> <button class="tickets btn width">D2</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <h5>E</h5> <button class="tickets btn width">E1</button> <button class="tickets btn width">E2</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <h5>F</h5> <button class="tickets btn width">F1</button> <button class="tickets btn width">F2</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <h5>G</h5> <button class="tickets btn width">G1</button> <button class="tickets btn width">G2</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <h5>H</h5> <button class="tickets btn width">H1</button> <button class="tickets btn width">H2</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <h5>I</h5> <button class="tickets btn width">I1</button> <button class="tickets btn width">I2</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <h5>J</h5> <button class="tickets btn width">J1</button> <button class="tickets btn width">J2</button> </div> </div> <div class="text-[#03071280] space-y-7"> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <button class="tickets btn width">A3</button> <button class="tickets btn width">A4</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <button class="tickets btn width">B3</button> <button class="tickets btn width">B4</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <button class="tickets btn width">C3</button> <button class="tickets btn width">C4</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <button class="tickets btn width">D3</button> <button class="tickets btn width">D4</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <button class="tickets btn width">E3</button> <button class="tickets btn width">E4</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <button class="tickets btn width">F3</button> <button class="tickets btn width">F4</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <button class="tickets btn width">G3</button> <button class="tickets btn width">G4</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <button class="tickets btn width">H3</button> <button class="tickets btn width">H4</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <button class="tickets btn width">I3</button> <button class="tickets btn width">I4</button> </div> <div class="flex gap-7 items-center *:font-medium *:text-lg"> <button class="tickets btn width">J3</button> <button class="tickets btn width">J4</button> </div> </div> </div> </div> <div class="pl-8 w-full space-y-6"> <div class="pb-6 border-b-2 border-dashed border-[#03071233]"> <h4 class="text-2xl font-semibold font-relaway"> Select Your Seat </h4> </div> <div class="bg-[#F7F8F8] rounded-xl p-8 font-inter space-y-4"> <div class="text-[#030712] text-base font-semibold flex justify-between pb-4 border-b-2 border-dashed border-[#03071233]" > <h5> Seat <sup id="count" class="text-xs text-white rounded-md px-2 font-bold bg-[#1DD100]" >0</sup > </h5> <h5>Class</h5> <h5>Price</h5> </div> <div class="space-y-4 pb-4 border-b-2 border-[#03071233]"> <div id="title-container" class="text-[#03071299] text-base" ></div> </div> <div class="text-[#030712] text-base font-semibold flex justify-between" > <h5>Total Price</h5> <h5>BDT <span id="total-price">0</span></h5> </div> <div id="discount-hide" class="input flex items-center"> <input required id="input-field" type="text" class="grow" placeholder="Have any copupon?" /> <button name="input-field" id="apply-btn" class="px-[18px] py-[10px] cursor-pointer text-white font-semibold bg-[#1DD100] rounded-lg" > Apply </button> </div> <div class="text-[#030712] text-base font-semibold flex justify-between" > <h5>Grand Total</h5> <h5>BDT <span id="grand-total">0</span></h5> </div> </div> <div class="w-full"> <form class="space-y-4" action=""> <div class="space-y-4 text-base font-semibold"> <label for="name">Passenger Name*</label> <br /> <input class="w-full text-[#03071266] border-[1px] border-[#0307121A] rounded-xl p-6" required type="text" placeholder="Enter your name" id="name" /> </div> <div class="space-y-4 text-base font-semibold"> <label for="number">Phone Number*</label> <br /> <input class="w-full text-[#03071266] border-[1px] border-[#0307121A] rounded-xl p-6" required type="number" placeholder="Enter your phone number" id="number" /> </div> <div class="space-y-4 text-base font-semibold"> <label for="email">Email ID</label> <br /> <input class="w-full text-[#03071266] border-[1px] border-[#0307121A] rounded-xl p-6" type="email" placeholder="Enter your email id" id="email" /> </div> <div class="space-y-4 text-xl font-extrabold"> <button onclick="my_modal_5.showModal()" id="next-btn" class="cursor-pointer w-full text-white bg-[#a3a3a3] rounded-xl p-6" > Next </button> </div> </form> </div> <div class="flex justify-around *:text-base *:text-[#03071299] *:cursor-pointer *:underline" > <p>Terms and Conditions</p> <p>Cancellation Policys</p> </div> </div> </div> </section> <dialog id="my_modal_5" class="modal"> <div class="bg-white rounded-2xl text-center p-10 space-y-7 flex flex-col justify-center items-center"> <img class="items-center" src="images/success.png" alt=""> <h3 class="font-bold text-2xl text-[#27AE60]">SUCCESS</h3> <div class="space-y-3"> <h4 class="font-medium text-xl text-[#4A4A4A]">Thank you for Booking Our Bus Seats. <br>We are working hard to find the best service and deals for you.!</h4> <p class="text-[#4A4A4A] text-xl font-light">Shortly you will find a confirmation in your email.</p> </div> <form method="dialog"> <button class="py-4 px-20 text-xl font-semibold rounded-[32px] text-white bg-[#27AE60]">Continue</button> </form> </div> </dialog> <!-- End Offer Section --> </main> <footer class="bg-[#030712]"> <section class="max-w-[1170px] mx-auto text-white py-28 font-inter"> <div class="flex justify-between pb-12 border-b-2 border-[#FFFFFF4D] border-dashed" > <div class="space-y-4"> <h4 class="text-4xl font-extrabold font-relaway">P-Ticket</h4> <p class="text-[#FFFFFFCC] text-lg"> P-Ticket is a digital platform to make your <br /> daily commuting better. </p> </div> <div class="space-y-4"> <h4 class="text-xl font-semibold">Download our app</h4> <img class="cursor-pointer" src="images/palystore1.png" alt="" /> </div> </div> <div class="flex justify-between pt-8"> <p class="text-[#FFFFFFB3]"> @all rights reserved, P-Ticket services limited.2024 </p> <div class="flex gap-8 *:text-base font-medium"> <a href="">Terms & condition</a> <a href="">Return & refund policy</a> <a href="">Privacy policys</a> </div> </div> </section> </footer> <script src="script/ticket.js"></script> </body> </html>
import React from 'react'; import clsx from 'clsx'; import { View } from '@ray-js/ray'; import { useProps, useActions, DpBooleanAction } from '@ray-js/panel-sdk'; import { Icon } from '@/components/icon'; import { icons } from '@/res'; import styles from './index.module.less'; export interface Props { dpCode: string; } export const PowerButton = React.memo<Props>(props => { const { dpCode } = props; const value = useProps(dpState => dpState[dpCode]); const actions = useActions(); if (!dpCode || typeof value !== 'boolean') { return null; } const action = actions[dpCode] as DpBooleanAction; return ( <View className={styles['power-button']} onClick={action.toggle}> <View className={clsx(styles['power-button-content'], { [`${styles['power-button-off']}`]: !value, })} /> <Icon className={styles['power-button-icon']} d={icons.power} size="34px" fill={value ? '#ef550d' : '#ffffff'} /> </View> ); });
"""Functions for getting Sales Tax Data""" import requests from bs4 import BeautifulSoup def post_request(url, payload): """Post Request""" try: r = requests.post(url, data=payload, timeout=30) if r.status_code == 200: return r else: print(r.status_code) except Exception as e: print(e) class Arkansas: """Arkansas Tax Rate Functions""" def get(street: str, city: str, zip_code: str): # pylint: disable=no-self-argument """Get Arkansas Tax Rates get(street: str, city: str, zip: str)""" form_payload = { "Street": street, "City": city, "State": "AR", "State2": "AR", "ZIP": zip_code, } form_url = "https://gis.arkansas.gov/Lookup/Results.php" response = post_request(form_url, form_payload) soup = BeautifulSoup(response.text, "html.parser") taxable_state = soup.find(id="TableCell20").text state_tax_rate = soup.find(id="tblCStateRate").text taxable_county = soup.find(id="tblCOutCoName").text county_tax_rate = soup.find(id="tblCOutCoRate").text taxable_city = soup.find(id="tblCOutCiName").text city_tax_rate = soup.find(id="tblCOutCiRate").text tax_rate_data = { "taxable_state": taxable_state, "state_tax_rate": state_tax_rate, "is_state_taxable": state_tax_rate != "", "taxable_county": taxable_county, "county_tax_rate": county_tax_rate, "is_county_taxable": county_tax_rate != "", "taxable_city": taxable_city, "city_tax_rate": city_tax_rate, "is_city_taxable": city_tax_rate != "", } return tax_rate_data
--- title: Genel Özellik Sayfası (Proje) ms.date: 07/17/2019 f1_keywords: - VC.Project.VCConfiguration.IntermediateDirectory - VC.Project.VCConfiguration.ConfigurationType - VC.Project.VCConfiguration.ManagedExtensions - VC.Project.VCConfiguration.BuildBrowserInformation - VC.Project.VCConfiguration.BuildLogFile - VC.Project.VCConfiguration.PlatformToolset - VC.Project.VCConfiguration.TargetName - VC.Project.VCConfiguration. - VC.Project.VCConfiguration.TargetExt - VC.Project.VCConfiguration.ATLMinimizesCRunTimeLibraryUsage - VC.Project.VCConfiguration.ReferencesPath - VC.Project.VCConfiguration.DeleteExtensionsOnClean - VC.Project.VCConfiguration.useOfMfc - VC.Project.VCConfiguration.CharacterSet - VC.Project.VCGeneralMakefileSettings.ConfigurationType - VC.Project.VCConfiguration.OutputDirectory - VC.Project.VCConfiguration.AppSupport - VC.Project.VCConfiguration.ToolFiles - VC.Project.VCConfiguration.useOfATL helpviewer_keywords: - Clean Build option - output files, setting directory - Unicode, creating C++ build configuration ms.openlocfilehash: eb172e7bd76816458a0efff7b053d136f52076ab ms.sourcegitcommit: a673f6a54cc97e3d4cd032b10aa8dce7f0539d39 ms.translationtype: MT ms.contentlocale: tr-TR ms.lasthandoff: 02/28/2020 ms.locfileid: "78166764" --- # <a name="general-property-page-project"></a>Genel Özellik Sayfası (Proje) ::: moniker range=">=vs-2019" Bu konu, Windows için Visual Studio projelerine yöneliktir. Linux projeleri için bkz. [Linux C++ Özellik sayfası başvurusu](../../linux/prop-pages-linux.md). CMake projeleri için bkz. [Visual Studio 'Da CMake projeleri](../cmake-projects-in-visual-studio.md). Android projeleri için bkz. [genel proje özellikleri (Android C++)](/cpp/cross-platform/general-android-prop-page). Android derleme görevleri dosyası projeleri için bkz. [genel proje özellikleri C++ (Android makefile)](/cpp/cross-platform/general-makefile-android-prop-page) Çözüm Gezgini ' de bir proje düğümüne sağ tıklayıp **Özellikler**' i seçtiğinizde, sol bölmedeki **yapılandırma özellikleri** düğümü altındaki **genel** Özellik sayfası şu özellikleri görüntüler: - **Çıkış dizini** Bağlayıcı gibi araçların derleme işlemi sırasında oluşturulan tüm son çıktı dosyalarını yerleşen dizini belirtir. Genellikle, bu, bağlayıcı, kütüphaneian veya BSCMake gibi araçların çıktısını içerir. Varsayılan olarak, bu özellik makrolar $ (SolutionDir) $ (yapılandırma) ile belirtilen dizindir. Bu özelliğe programlı bir şekilde erişmek için bkz. <xref:Microsoft.VisualStudio.VCProjectEngine.VCConfiguration.OutputDirectory%2A>. - **Ara Dizin** Derleyici gibi araçların derleme işlemi sırasında oluşturulan tüm ara dosyaları yerleştireceğinizi belirten dizini belirtir. Genellikle, bu, C/C++ derleyici, MIDL ve kaynak derleyicisi gibi araçların çıktısını içerir. Varsayılan olarak, bu özellik, $ (yapılandırma) \ makrosu tarafından belirtilen dizindir. Bu özelliğe programlı bir şekilde erişmek için bkz. <xref:Microsoft.VisualStudio.VCProjectEngine.VCConfiguration.IntermediateDirectory%2A>. - **Hedef adı** Bu projenin oluşturduğu dosya adını belirtir. Varsayılan olarak bu özellik, Macro $ (ProjectName) tarafından belirtilen dosya adıdır. - **Yapılandırma türü** Aralarından seçim yapabileceğiniz birkaç yapılandırma türü vardır: - **Uygulama (. exe)** Bağlayıcı araç takımını (C/C++ derleyici, MIDL, kaynak derleyicisi, bağlayıcı, BSCMake, XML Web hizmeti proxy Oluşturucusu, özel derleme, ön derleme, ön bağlantı, postbuild olayları) görüntüler. - **Dinamik kitaplık (. dll)** Bağlayıcı araç takımını görüntüler,/DLL bağlayıcı seçeneğini belirtir ve _WINDLL tanımlar öğesini CL 'ye ekler. - **Dosyasının** Makefile araç takımını (NMake) görüntüler. - **Statik kitaplık (. lib)** Kütüphaneian araç takımını (bağlayıcı araç takımı ile aynı ve XML Web hizmeti proxy oluşturucusunu atla hariç) görüntüler. - **Utility** Utility araç takımını (MıDL, özel derleme, prebuild, postbuild olayları) görüntüler. Bu özelliğe programlı bir şekilde erişmek için bkz. <xref:Microsoft.VisualStudio.VCProjectEngine.VCConfiguration.ConfigurationType%2A>. - **Windows SDK sürümü** Windows hedef platformu için, bu, projenizin gerektirdiği Windows SDK sürümünü belirtir. Visual Studio yükleyicisi 'ni C++ kullanarak bir iş yükü yüklediğinizde, Windows SDK gerekli bölümleri de yüklenir. Bilgisayarınızda başka Windows SDK sürümleriniz varsa, yüklediğiniz SDK araçlarının her sürümü açılan menüde görünür. Windows 7 veya Windows Vista 'Yı hedeflemek için **8,1**değerini kullanın, çünkü Windows SDK 8,1 Bu platformlarla geriye dönük olarak uyumludur. Ayrıca, targetver. h içinde **_WIN32_WINNT** için uygun değeri tanımlamanız gerekir. Windows 7 için, bu 0x0601 ' dir. Bkz. [WINVER ve _WIN32_WINNT değiştirme](../../porting/modifying-winver-and-win32-winnt.md). Windows XP ve Windows 2003 Server projelerini derlemek için, kitaplıkların güncel sürümünü kullanmak üzere Visual Studio 'ya dahil edilen Windows XP platformu araç takımını yükleyebilirsiniz. Bu platform araç takımını edinme ve kullanma hakkında daha fazla bilgi için bkz. [WINDOWS XP Için programları yapılandırma](../configuring-programs-for-windows-xp.md). Platform araç takımını değiştirme hakkında daha fazla bilgi için bkz. [nasıl yapılır: hedef Framework ve platform araç takımını değiştirme](../how-to-modify-the-target-framework-and-platform-toolset.md). - **Platform araç takımı** Projenin, görsel C++ kitaplıkların ve derleyicinin farklı bir sürümünü hedeflemesini sağlar. Visual Studio C++ projeleri, Visual Studio tarafından yüklenen varsayılan araç takımını veya Visual Studio 'NUN Windows XP 'de çalışabilen araç kümeleri de dahil olmak üzere birkaç önceki sürümü tarafından yüklenen araç kümelerinden birini hedefleyebilir. Platform araç takımını değiştirme hakkında daha fazla bilgi için bkz. [nasıl yapılır: hedef Framework ve platform araç takımını değiştirme](../how-to-modify-the-target-framework-and-platform-toolset.md). - **C++Dil standardı** Hangi dil standardının kullanılacağını belirtir. Varsayılan değer/std: c++ 14 ' dir. C++ 17 özelliklerini kullanmak için/std: c++ 17 veya C++ 20 veya diğer deneysel özellikleri kullanmak için/std: c++ + latest ' ı belirtin. Daha fazla bilgi için bkz. [/std (dil standart sürümünü belirt)](std-specify-language-standard-version.md) ::: moniker-end ::: moniker range="<=vs-2017" Visual Studio 2015 ve Visual Studio 2017 ' de, **Çözüm Gezgini**' de bir proje düğümüne sağ tıklayıp **Özellikler**' i seçtiğinizde, sol bölmedeki **yapılandırma özellikleri** düğümü altındaki **genel** Özellik sayfası özelliklerin iki bölümünü görüntüler: - Genel - Proje Varsayılanları ## <a name="general"></a>Genel - **Hedef platform** Projenin çalışacağı platformu belirtir. Örneğin, Windows, Android veya iOS. **Windows 10** değeri, projenin Evrensel Windows platformu hedeflediği anlamına gelir. Windows 'un önceki sürümlerini hedefliyorsanız, sürüm listelenmez ve bu alandaki değer yalnızca **Windows**olarak görünür. Bu, bir proje oluşturduğunuzda ayarlanmış bir salt okunurdur. - **Hedef platform sürümü (Visual Studio 2015)** Projenin üzerinde çalışacağı platformun en düşük sürümünü belirtir. Bu özellik yalnızca proje türü destekliyorsa görüntülenir. Uygulamanız daha yeni bir Windows SDK sürümündeki özelliklerden yararlanabilir, ancak bu özellikler olmadan önceki sürümlerde çalışmaya devam edebilir, belki de bazı işlevsellik kaybı ile, bu iki özelliğin değeri farklı olabilir. Bu durumda, kodunuz çalışma zamanında çalıştığı platformun sürümünü denetlemelidir ve eski platform sürümünde kullanılamayan özellikleri kullanmayı denemez. C++ Proje sistemi bu seçeneği zorlamaz. , C# Ve JavaScript gibi diğer dillerle ve projenizi kullanan herkese yönelik bir kılavuz olarak mevcuttur. En C++ düşük sürümde kullanılamayan bir özellik kullanırsanız görsel hata oluşturmaz. - **Windows SDK sürümü (Visual Studio 2017)** Windows hedef platformu için, bu, projenizin gerektirdiği Windows SDK sürümünü belirtir. Visual Studio yükleyicisi 'ni C++ kullanarak bir iş yükü yüklediğinizde, Windows SDK gerekli bölümleri de yüklenir. Bilgisayarınızda başka Windows SDK sürümleriniz varsa, yüklediğiniz SDK araçlarının her sürümü açılan menüde görünür. Windows 7 veya Windows Vista 'Yı hedeflemek için **8,1**değerini kullanın, çünkü Windows SDK 8,1 Bu platformlarla geriye dönük olarak uyumludur. Ayrıca, targetver. h içinde **_WIN32_WINNT** için uygun değeri tanımlamanız gerekir. Windows 7 için, bu 0x0601 ' dir. Bkz. [WINVER ve _WIN32_WINNT değiştirme](../../porting/modifying-winver-and-win32-winnt.md). Windows XP ve Windows 2003 Server projelerini derlemek için, kitaplıkların güncel sürümünü kullanmak üzere Visual Studio 'ya dahil edilen Windows XP platformu araç takımını yükleyebilirsiniz. Bu platform araç takımını edinme ve kullanma hakkında daha fazla bilgi için bkz. [WINDOWS XP Için programları yapılandırma](../configuring-programs-for-windows-xp.md). Platform araç takımını değiştirme hakkında daha fazla bilgi için bkz. [nasıl yapılır: hedef Framework ve platform araç takımını değiştirme](../how-to-modify-the-target-framework-and-platform-toolset.md). - **Çıkış dizini** Bağlayıcı gibi araçların derleme işlemi sırasında oluşturulan tüm son çıktı dosyalarını yerleşen dizini belirtir. Genellikle, bu, bağlayıcı, kütüphaneian veya BSCMake gibi araçların çıktısını içerir. Varsayılan olarak, bu özellik makrolar $ (SolutionDir) $ (yapılandırma) ile belirtilen dizindir. Bu özelliğe programlı bir şekilde erişmek için bkz. <xref:Microsoft.VisualStudio.VCProjectEngine.VCConfiguration.OutputDirectory%2A>. - **Ara Dizin** Derleyici gibi araçların derleme işlemi sırasında oluşturulan tüm ara dosyaları yerleştireceğinizi belirten dizini belirtir. Genellikle, bu, C/C++ derleyici, MIDL ve kaynak derleyicisi gibi araçların çıktısını içerir. Varsayılan olarak, bu özellik, $ (yapılandırma) \ makrosu tarafından belirtilen dizindir. Bu özelliğe programlı bir şekilde erişmek için bkz. <xref:Microsoft.VisualStudio.VCProjectEngine.VCConfiguration.IntermediateDirectory%2A>. - **Hedef adı** Bu projenin oluşturduğu dosya adını belirtir. Varsayılan olarak bu özellik, Macro $ (ProjectName) tarafından belirtilen dosya adıdır. - **Hedef uzantısı** Bu projenin oluşturduğu dosya adı uzantısını belirtir; Örneğin,. exe veya. dll. - **Temizlemede Silinecek Uzantılar** **Temizleme** seçeneği (**derleme** menüsü), bir projenin yapılandırmasının oluşturulduğu ara dizindeki dosyaları siler. Bu özellik ile belirtilen uzantılara sahip dosyalar, **Temizleme** çalıştırıldığında veya yeniden derleme gerçekleştirdiğinizde silinir. Ara dizindeki bu uzantılara ait dosyaların yanı sıra, yapı sistemi, bulunduğu yere bakılmaksızın (. obj dosyaları gibi ara çıktılar dahil olmak üzere) her türlü bilinen çıktıyı da siler. Joker karakterler belirtebilirsiniz. Bu özelliğe programlı bir şekilde erişmek için bkz. <xref:Microsoft.VisualStudio.VCProjectEngine.VCConfiguration.DeleteExtensionsOnClean%2A>. - **Derleme günlüğü dosyası** Her proje oluşturduğunuzda oluşturulan günlük dosyası için varsayılan olmayan bir konum belirtmenizi sağlar. Varsayılan konum, makrolar $ (IntDir) $ (MSBuildProjectName). log tarafından belirtilir. Dizin konumunu değiştirmek için proje makroları kullanabilirsiniz. Bkz. [derleme komutları ve özellikleri Için ortak makrolar](common-macros-for-build-commands-and-properties.md). - **Platform araç takımı** Projenin, görsel C++ kitaplıkların ve derleyicinin farklı bir sürümünü hedeflemesini sağlar. Visual Studio C++ projeleri, Visual Studio tarafından yüklenen varsayılan araç takımını veya Visual Studio 'NUN Windows XP 'de çalışabilen araç kümeleri de dahil olmak üzere birkaç önceki sürümü tarafından yüklenen araç kümelerinden birini hedefleyebilir. Platform araç takımını değiştirme hakkında daha fazla bilgi için bkz. [nasıl yapılır: hedef Framework ve platform araç takımını değiştirme](../how-to-modify-the-target-framework-and-platform-toolset.md). - **Yönetilen artımlı derlemeyi etkinleştir** Yönetilen projeler için, bu, derlemeleri oluştururken dış görünürlüğü algılamayı mümkün bir şekilde sunar. Yönetilen bir projede yapılan bir değişiklik diğer projelere görünür değilse, bağımlı projeler yeniden oluşturulamaz. Bu, yönetilen projeler içeren çözümlerde derleme sürelerini önemli ölçüde iyileştirebilir. ## <a name="project-defaults"></a>Proje Varsayılanları Proje varsayılan bölümündeki özellikler, değiştirebileceğiniz varsayılan özellikleri temsil eder. Bu özelliklerin tanımı, \Vc\vcprojectdefaults. *yükleme dizinindeki*. props dosyalarında bulunabilir. - **Yapılandırma türü** Aralarından seçim yapabileceğiniz birkaç yapılandırma türü vardır: - **Uygulama (. exe)** Bağlayıcı araç takımını (C/C++ derleyici, MIDL, kaynak derleyicisi, bağlayıcı, BSCMake, XML Web hizmeti proxy Oluşturucusu, özel derleme, ön derleme, ön bağlantı, postbuild olayları) görüntüler. - **Dinamik kitaplık (. dll)** Bağlayıcı araç takımını görüntüler,/DLL bağlayıcı seçeneğini belirtir ve _WINDLL tanımlar öğesini CL 'ye ekler. - **Dosyasının** Makefile araç takımını (NMake) görüntüler. - **Statik kitaplık (. lib)** Kütüphaneian araç takımını (bağlayıcı araç takımı ile aynı ve XML Web hizmeti proxy oluşturucusunu atla hariç) görüntüler. - **Utility** Utility araç takımını (MıDL, özel derleme, prebuild, postbuild olayları) görüntüler. Bu özelliğe programlı bir şekilde erişmek için bkz. <xref:Microsoft.VisualStudio.VCProjectEngine.VCConfiguration.ConfigurationType%2A>. - **MFC kullanımı** MFC projesinin MFC DLL 'sine statik olarak mı yoksa dinamik olarak mı bağlantı yapıp olmayacağını belirtir. MFC olmayan projeler, MFC kullandığınızda dahil edilen çeşitli Win32 kitaplıklarına bağlantı sağlamak için **Standart Windows kitaplıklarını kullan** ' ı seçebilir. Bu özelliğe programlı bir şekilde erişmek için bkz. <xref:Microsoft.VisualStudio.VCProject.VCProjectConfigurationProperties.useOfMfc%2A>. - **Karakter kümesi** _UNICODE veya _MBCS ayarlanması gerekip gerekmediğini tanımlar. Ayrıca uygun yerlerde bağlayıcı giriş noktasını da etkiler. Bu özelliğe programlı bir şekilde erişmek için bkz. <xref:Microsoft.VisualStudio.VCProject.VCProjectConfigurationProperties.CharacterSet%2A>. - **Ortak dil çalışma zamanı desteği** [/Clr](clr-common-language-runtime-compilation.md) derleyici seçeneğinin kullanılmasına neden olur. Bu özelliğe programlı bir şekilde erişmek için bkz. <xref:Microsoft.VisualStudio.VCProject.VCProjectConfigurationProperties.ManagedExtensions%2A>. - **.NET hedef Framework sürümü** Yönetilen projelerde, hedeflenen .NET Framework sürümünü belirtir. - **Tüm program Iyileştirmesi** [/GL](gl-whole-program-optimization.md) derleyici seçeneğini ve [/LTCG](ltcg-link-time-code-generation.md) bağlayıcı seçeneğini belirtir. Bu, varsayılan olarak hata ayıklama yapılandırmalarında devre dışıdır ve perakende yapılandırmalarda etkinleştirilir. - **Windows Mağazası uygulama desteği** Bu projenin Windows Çalışma Zamanı (Evrensel Windows Platformu) uygulamalarını destekleyip desteklemediğini belirtir. Daha fazla bilgi için bkz. [/ZW (Windows çalışma zamanı derlemesi)](zw-windows-runtime-compilation.md)ve Windows Geliştirici Merkezi. ::: moniker-end ## <a name="see-also"></a>Ayrıca bkz. [C++Proje özellik sayfası başvurusu](property-pages-visual-cpp.md)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./assets/styles.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Red+Hat+Display:wght@500;700;900&display=swap" rel="stylesheet"> <style> .done { text-decoration: line-through; } </style> <title>Simple To-Do List</title> </head> <body> <main id="app"> <h3> {{title}} </h3> <form @submit.prevent= "addTodo"> <label for= "newTodo" >New To Do</label> <input v-model="newTodo" type="text" name="newTodo" id="newTodo" value="" required > <button type="submit" name="button" class="button-add">Add</button> </form> <button @click="allDone" type="button" name="All Done" class="button-all-done">Check All</button> <ul> <li v-for="todo in todos" > <input type="checkbox" v-model="todo.done"> <span :class="{ done: todo.done }">{{todo.title}}</span> <button @click="removeTodo(todo)" type="button" name="button" class="button-delete">delete</button> </li> </ul> </main> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="./assets/app.js"></script> </body> </html>
package org.jcyclone.core.internal; import org.jcyclone.core.fileconfig.SampleEvent; /** * Subclass of {@link SampleEvent} that contains the object plus * name of the thread that's processing the event * @author toli * @version $Id: ThreadSampleEvent.java,v 1.1 2006/09/27 01:37:25 tolikuznets Exp $ */ public class ThreadSampleEvent extends SampleEvent { private String producerThread; private String consumerThread; public ThreadSampleEvent(String inData) { super(inData); } public String getProducerThread() { return producerThread; } public void setProducerThread(String producerThread) { this.producerThread = producerThread; } public String getConsumerThread() { return consumerThread; } public void setConsumerThread(String consumerThread) { this.consumerThread = consumerThread; } public String toString() { StringBuffer buffer = new StringBuffer(500); buffer.append("[Value: ").append(getData()); buffer.append(", ").append(getProducerThread()); buffer.append(", ").append(getConsumerThread()).append("]"); return buffer.toString(); } }
--- title: "Worksheet 04 - Intro to R programming - NCBS MSc WL" author: "Akshay Surendra, Anand M Osuri" date: "October 2020" output: pdf_document: default html_document: default word_document: default --- ```{r setup, include=TRUE, echo=FALSE, eval=FALSE,fig.width=4,fig.height=4} knitr::opts_chunk$set(echo = TRUE) ``` This worksheet comprises explanatory text, worked examples and problems for solution. Please feel free to discuss any and all of it with your classmates, but do work independently on your solutions. **Topics covered**: **Interactive session 1**: 9th October 2020, 09:00AM -11:00AM IST **Interactive session 2**: 14th October 2020, 09:00AM -11:00AM IST **Submission deadline**: 15th October 2020, 11:59PM IST **Submission**: Save your final R script in the format ‘first name_last name_WS04.R’ and email this file to both Anand (\underline{aosuri@ncf-india.org}) and Akshay (\underline{akshaysurendra1@gmail.com}) by the given deadline. Throughout this worksheet, we will be using three datasets, all from one paper by [Davis et al 2018 (Ecology Letters)](https://onlinelibrary.wiley.com/doi/abs/10.1111/ele.13124). Two of the datasets can be found [here](https://datadryad.org/stash/dataset/doi:10.5061/dryad.7f9j57n) and the third is in the supplementary section. If you cannot access the paper, maybe try \underline{sci-hub.se} and paste the link in here and see what happens? Someone told us this works very well. Before we proceed, import the files `tab1_species.csv`, `tab2_cooccurence.csv` and `tab3_traits.csv` and assign them to objects **tab1**, **tab2** and **tab3** respectively. Use the `str()`, `head()`, `tail()` and `glimpse()` (what's this function? try it out!) functions to explore what each of the datasets are. ```{r message=FALSE} library(tidyverse) tab1 <- read_csv(file = "datasets/tab1_species.csv") tab2 <- read_csv(file = "datasets/tab2_cooccurence.csv") tab3 <- read_csv(file = "datasets/tab3_traits.csv") ``` About these data: These data are camera trap records from Nepal of 7 co-occurring mammals. `tab1` has a table of all 7 mammal species, `tab2` has information on 78 different sites within Nepal (`NEP01` to `NEP78`) - in each site, there are 21 (7C2 = 7x6/2) rows, for every possible pairwise combination within the 7 mammals. Each of the 21 rows per site have two columns indicating the code for each of the species (`SppCode1` and `SppCode2`), number of detections (sightings) of each species (`Spp1Det` for species 1, `Spp2Det` for species 2), and the number of trap nights (`num.nights`) that the camera trap was active. `tab3` has information on the traits of each species pair (i.e. 21 rows). In summary, these data together inform us of how often two species of mammal are photographed at the same camera trap location. ![Crisp morning in Bogd uul, Bogdkhan Uul Protected Area, Mongolia. Photo: Chagsaa Odonjavkhlan](spruceup/mongolia1_Chagsaa.jpeg) In this worksheet, we will learn: 1. Conditional statements 2. Joining data frames 3. Random number generation 4. Sampling 5. Looping statements ## 2.1 conditional statements We've learnt how to use relational operators to create a subset of the data: ```{r} library(tidyverse) set.seed(10) dat <- data.frame(col1 = rnorm(n = 100,mean = 0,sd = 2)) vec_A <- dat %>% filter(abs(col1) > 0.5) %>% pull(col1) vec_B <- log10(x = abs(vec_A)) ``` The above snippet of code filters all values in the column col1 of dataframe dat that are greater than 0.5 or less than -0.5 (how? using the `abs()` function - `abs()` takes the absolute value of the column, converting all negative numbers to positive temporarily while comparing with 0.5). We can then perform a particular task on that subset - in this case, we take a logarithm of base-10 of these data. [Q Why might we be taking an absolute value here again?] What if, however, we want to perform different tasks on different subsets of data? ```{r} datA <- tibble(colA = c("X","Y","X","Y","Y","X","X","Y","X"), colB = c(10, 17, 21, 99, 444, 87, 7, 33, 45)) ``` For example, in datA above, we may want to find the mean of `colB` if `colA` is X and the median of `colB` if `colA` is Y. We can do it this way - ```{r} r1 <- datA %>% filter(colA=="X") %>% summarize(res = mean(colB)) %>% pull(res) r2 <- datA %>% filter(colA=="Y") %>% summarize(res = median(colB)) %>% pull(res) c(r1,r2) ``` What if we have many conditions? For example - if A is true, do this; or if B is true, do that; or if C is true, do something else; or if D is TRUE, then do a fourth thing, and so on... This is where some key conditional statements come in: `if()`, `ifelse()` and `case_when()` 1. `if()` statement ```{r} temp <- c(5,6,6,5) chk <- temp==5 if(chk[1]==TRUE) { print("yep, chk[1] is five")} if(chk[2]==TRUE) { print("yep, chk[2] is five")} if(chk[3]) { print("yep, chk[3] is five")} if(chk[4]) { print("yep, chk[4] is five")} ``` An `if()` statement takes an input value that can be `TRUE` or `FALSE`. If `TRUE`, it implements the code contained within the curly braces *immediately* below the `if()` statement. If it's `FALSE`, it skips the *block of code* (the correct term for "whatever is between curly braces") right beneath In the above code, *"yep, chk[...] is five"* is only printed when `chk` is TRUE, or when `temp==5` - the block of code is not printed when `temp!=5` or `chk` is `FALSE` *\underline{Note: In R, `if(chk==TRUE)` is the same as `if(chk)`}* We usually don't store `TRUE` or `FALSE` values in an object (`chk`), we directly test that within an `if()` statement: `if(temp==0)`. We can rewrite the above conditional statement as: ```{r} if(temp[2]==6){ print("yep, it is a six") } ``` What if we want to do is run some other task when the condition is something else? We can then have two `if()` statements: ```{r} if(temp[1]==5){ print("yep, temp[1] is a five") } if(temp[3]!=5){ print("nope, temp[3] is not a five") } ``` Often, we may want to perform different tasks depending on whether a condition is TRUE or FALSE. For example, printing different outputs depending on whether a condition evaluates as TRUE (say `temp[1]==5`) or FALSE (say `temp[1]!=5`). In such cases, we use an `ifelse() {}` statement. *Remember, `!=` is the symbol to test NOT EQUAL TO just as `==` is the symbol to test EQUAL TO* The `ifelse()` syntax is a little different: ```{r} len <- 6 temp1 <- c(5,5,6,6,5,6) temp2 <- vector(mode = "character",length = len) # alit. way of defining a vector temp3 <- temp2 # creating another empty vector temp2[1] <- ifelse(test=(temp1[1]==5), yes="yes, it's 5", no="no, it's not 5") temp2[2] <- ifelse(test=(temp1[2]==5), yes="yes, it's 5", no="no, it's not 5") temp2[3] <- ifelse(test=(temp1[3]==5), yes="yes, it's 5", no="no, it's not 5") temp2[4] <- ifelse(test=(temp1[4]==5), yes="yes, it's 5", no="no, it's not 5") temp2[5] <- ifelse(test=(temp1[5]==5), yes="yes, it's 5", no="no, it's not 5") temp2[6] <- ifelse(test=(temp1[6]==5), yes="yes, it's 5", no="no, it's not 5") temp2 # vectorized: temp3 <- ifelse(test = (temp1==5),yes="yes, it's 5",no="no, it's not 5") temp3 ``` `ifelse()` takes three arguments, a test condition, and two tasks: one when the condition is `TRUE` (yes) and another when the condition is `FALSE` (no) If we have multiple conditions? What do we do then? *Nested* `ifelse()` statements: ```{r} len <- 21 temp6 <- vector(mode = "character",length = len) #alit. way of defining a vector temp5 <- c(rep(6,3),rep(7,9),rep(81,5),rep(44,4)) temp6 <- ifelse(test = (temp5==81), yes = "yep, it's an 81!", no = ifelse(test = (temp5==44), yes = "yep, it's 44!", no = "it's neither 44 nor 81 :(")) ``` As you can imagine, you can add many levels of nested `ifelse()` statements to implement tasks when certain conditions are true or not. It's easy to see that you need - 1. one `ifelse()` with two tasks 2. two `ifelse()` with three tasks ... or K `ifelse()` statements to do K+1 tasks In practice, beyond one level of nesting, it's often easier to implement a `case_when()` statement. The syntax for `case_when()` is: ```{r} # case_when( # <test1> ~ <task1>, # <test1> ~ <task2>, # <test1> ~ <task3>, # ...) # We can implement the above example with this syntax: temp6 <- case_when( temp5==81 ~ "yep, it's an 81!", temp5==44 ~ "yep, it's an 44!", temp5==7 ~ "yep, it's an 7!", temp5!=81 & temp5!=44 & temp5!=7 ~ "None of the above (NOTA)") temp6 ``` Because `case_when()` belongs to tidyverse, you can use these within pipes, say within a `mutate()` to create a new column based on certain sets of conditions. ![Gathering clouds in Lakshadweep, India. Photo: Mayukh Dey](spruceup/Lakshwadweep_Mayukh.jpeg) ## 2.2 Joining tables together In many instances, data that you will use in your analyses will be located across many different spreadsheets. For example: ![data frame A](spruceup/datA.PNG) ![data frame B](spruceup/datB.PNG) `data frame A` has information on birds seen per fragment, and `data frame B` has information on each fragment itself. It's useful to store data this way, but sometimes, we may want to use them together. For instance, we may want to plot and see how the number of Yellow-Browed Bulbul (in `data frame A`) varies with the size of fragment (in `data frame B`). To achieve this, we can **join** tibbles together using the `left_join()` function illustrated below: ```{r echo=TRUE,eval=TRUE} dat1 <- tibble(fragment = c("AK","AN","CA"), ybbulbul = c(18,11,29)) dat2 <- tibble(fragment = c("AK","AN","CA"), size = c(1145.5, 600,105)) dat3 <- left_join(x = dat1,y = dat2,by = "fragment") dat3 ``` The function `left_join()` takes three arguments: the first data frame (x), the second data frame (y) and the column name (*in quotes*) by which to join. R is smart, in that if you don't provide the column name, it will auto detect all common columns (by the name) and join by those. What if joining columns have different names, for instance, if dat1 is defined this way: ```{r} dat1 <- data.frame(location = c("AK","AN","CA"), ybbulbul = c(18,11,29)) #notice, that it is location and not fragment ``` In such a case, we use a slightly different syntax for joining: *`left_join(x = <firstdataframe>, y = <seconddataframe>, by=c("<columnname_1stdataframe>" = "<columnname_2nddataframe>"))`* ```{r} dat3 <- left_join(x = dat1,y = dat2,by = c("location" = "fragment")) ``` You will almost always encounter these two scenarios: 1) When matching columns that don't completely overlap, you will see - ```{r} dat1 <- data.frame(fragment = c("AK","AN","PM"), ybbulbul = c(18,11,29)) dat2 <- data.frame(fragment = c("AK","AN","CA"), size = c(1145.5, 600,105)) dat3 <- left_join(x = dat1,y = dat2,by = "fragment") dat3 ``` - how everything in dat1 has been retained, but only common elements from dat2 have been joined. What happens when you replace `left_join()` with `right_join()`? ```{r eval=TRUE} right_join(x = dat1,y = dat2,by = "fragment") ``` The opposite happens: all cases in y are retained and only matching cases from x are joined. What happens when you use `full_join()` instead? ```{r eval=TRUE} full_join(x = dat1,y = dat2,by = "fragment") ``` All cases are printed - those without matches in each other's data frame are replaced with NA 2) when one data frame has repeated values of one or more cases and the other doesn't Just as in scenario 1), you can intuit what happens. For e.g., consider two point counts in each fragment in `dat1`, and join this new `dat1` with the same dataframe `dat2`: ```{r} dat1 <- data.frame(fragment = c("AK","AK","CA","CA"), pointCount = c("AKP1","AKP2","CAP1","CAP2"), ybbulbul = c(18,11,29,34)) dat2 <- data.frame(fragment = c("AK","AN","CA"), size = c(1145.5, 600,105)) dat3 <- left_join(x = dat1,y = dat2,by = "fragment") dat3 ``` Here, all rows with the same case in `dat1` (either `AK` or `CA`) are matched with the fragment column (and other columns) in `dat2`: if you had more columns in dat2, those would get mapped on to `dat1` as well. Notice how `AN` in `dat2$fragment` has no matching case in `dat1` and therefore gets ignored. However, what happens instead when you replace `left_join()` with `full_join()`? #### Practice: (do not submit this, we can discuss in class) In the Nepal mammal occurrence datasets provided, `tab2` contains many rows for each species pair (`Spp1` or `Spp2`) and `tab1` contains information on each species. Our aim is to join these two datasets, such that the output is as long as `tab2`, and contains all columns from `tab2` and `tab1` a) Identify the column(s) with common cases in `tab1` and `tab2` b) Use the appropriate join function() and `by = ` argument to join `tab1` and `tab2` together c) what happens when you don't provide any `by = ` argument? What do the join function(s) join by? d) You realize that not all columns from `tab1` are needed in the final data frame. Can you select the weight and common name of each species in `tab1` alone & then join? Which other column from `tab1` is compulsory? e) Try the other 2 join functions (besides what you used in `b.` above) and see what you get ![Bleary evening in high-elevation Nilgiris, India. Photo: Rasikapriya Sriramamurthy](spruceup/Rasika_ooty.jpg) ## 2.3 Random numbers Of what use are random numbers? In ecology, as indeed in science in general, we can often understand something about patterns generated by a particular process by making comparisons against a null model, which correspond to patterns that we might expect in the absence of that process. It might not be practical to find these null models in the real world (e.g., in a study on climate change, to find a 'null' planet similar to Earth but one that is not experiencing climate change), leaving us no better option than to recreate them using computer simulations. Random number generation is fundamental to such procedures. In R, we generate random numbers from distributions. Two commonly used distributions are rnorm() (random-normal pronounced ar-norm) and runif() (random-uniform or ar-you-nif). `runif()` draws random numbers from a uniform distribution within a specified range. In a uniform distribution, all candidate numbers have an equal probability of getting selected (see the uniform distribution histogram below). runif() thus requires three arguments: `n =` number of random numbers to be drawn, and `min =` and `max =` define the range within which we want to select a random number. By default, `min = 0` and `max = 1`. rnorm() draws values from a normal or gaussian distribution, which is characterised by a central value (mean) and spread surrounding the central value (standard deviation) (see the lower panel below). Here, for a given spread of data, values that are closer to the mean have a greater probability of being selected than those farther away. ![.](spruceup/UniformDist.png) ![.](spruceup/NormalDist.png) To draw 45 random numbers from a uniform distribution between 8 and 900, we run: ```{r eval=TRUE} set.seed(20) obj1 <- runif(n = 45,min = 8,max = 900) obj1 ``` If you want to generate whole numbers only, you can simply round off to the nearest whole number with the `round()` function. A `round()` function takes two arguments, `x =` the object that needs to be rounded and `digits =` number of decimal digits to be rounded to; `digits = 0` (default) will return a whole a number: ```{r} set.seed(20) obj1 <- runif(n = 45,min = 8,max = 900) round(x = obj1) # same as round(x = obj1, digits = 0) ``` You can imagine that values between 0 and 0.5 become 0 and between 899.5 and 900 become 900, such that with a round() function, you'll get both `min=` and `max=` How will you generate random *whole numbers* that do **not** include (i) `min=` value (ii) `max=` value (hint: read up `ceiling()` and `floor()` functions) Each time you run `runif()` you will get a different set of numbers. This can be annoying, when you want to use the exact same set of random numbers. You can save those numbers in an object and use that object, and that object's contents won't change as long as you don't re-run the `runif()` statement. However, if you share your code with someone else or if you restart your RStudio session, you will get a new set of numbers. To prevent this, we can do what is called *setting seed*, using the `set.seed()` function: ```{r} set.seed(45) round(runif(4,min=0,max=5)) ``` You will get the exact same set of numbers, as long as the number within set.seed() function is the same (you can give any number within `set.seed()`. If you're curious, you can read more [here](https://stackoverflow.com/questions/13605271/reasons-for-using-the-set-seed-function). #### Practice: (do not submit this, we can discuss in class) Generate 50 random numbers between 5 and 10 that are whole numbers and store as C1. Generate another 50 numbers (5-10) rounded to 1 decimal place and store as C2. Repeat the above process to generate C3 and C4 respectively, except this time, exclude the minimum value 5 and set a common seed for both. Bind them together as a matrix and then convert it to a tibble. Now use `pivot_longer()` to transform the data and using the old column names (now IDs for each random sample), plot four histograms faceted into 4 sub plots in one row. ![Afternoon heat in the Nilgiris. Photo: Rasikapriya Sriramamurthy](spruceup/Rasika_ooty2.jpg) ## 2.2 Sampling While the previous section dealt with creating random samples based on some theoretical distributions, your analyses might sometimes require you to draw random samples from within your own dataset. In R, we sample or subsample data using the `sample()` function. It takes four arguments: 1. `x = `vector of elements from which to sample from (population), compulsory 2. `size = `number of elements to sample from **x**; if you don't supply size, it resorts to the default value: `size = length(x)` 3. `replace =` takes `TRUE` or `FALSE` values i.e. `with` or `without` replacement; default is `FALSE`; more on replacement [in this video](https://www.youtube.com/watch?v=dQ9r2S7NWLs) 4. `prob =` probability of each element in x; default value is equal probability for each element in x (this is usually what we want) ```{r} set.seed(567) sample(x = c(5:7)) ``` ```{r} set.seed(567) sample(x = round(runif(n = 5))) ``` In both examples above, size is default (length(x) = 3 or 5), replace is default (FALSE) and probabilities are equal. Each time you run this, all elements in x are returned, but in a different order (watch the video on sampling to make sense) ```{r} set.seed(567) sample(x = round(runif(n = 5),1),size = 3) # Same as: # sample(x = round(runif(n = 5),1),size = 3,replace = FALSE) ``` ```{r} set.seed(567) sample(x = round(runif(n = 5),1),size = 3,replace = TRUE) ``` We sample 3 numbers from a population of 5 numbers, and each time we get a different element in case one (can still be the same number if that number repeats) while we may get the *same element* in case two #### Practice: (do not submit this, we can discuss in class) In tab2, we have a column called site with information on 78 different sites (`NEP01` to `NEP78`). Select rows corresponding to site `NEP60` and store that data in an object `qsam1`. Then, filter out all rows with tiger or leopard in the `SppCode2` column (look up code in `tab1`) and store in `qsam2`. Then, sample the `Spp2Det` column in `qsam2`, with replacement and with `nrow` equal to the total number of rows in `qsam2`. Find the mean of this sample. Now repeat this sampling of the same `Spp2Det` column in `qsam2` another 6 times, and find the mean each time. Report a boxplot of those 7 values. ![Rain pauses in Middle Strait, Andaman Islands. Photo: Mayukh Dey](spruceup/Mayukh_Andaman.jpeg) ## 2.3 Looping The practice question in 2.2 was laborious. What if instead of 7 times, we wanted to repeat the sampling 50 times? 100 times? 1000 times? This is where looping comes in. *A loop is a way to repeat a set of statements many, many times.* Let's assign numbers 1 through 12 to a vector `vec1`: ```{r} vec1 <- vector(mode = "numeric",length = 12) vec1 <- c(1:12) ``` Here, R is automatically going through each element in vec1 and assigning the numbers 1 through 12 to the consecutive elements (vectorized operation). A loop generalizes this procedure, and when R cannot vectorize something, you can do it manually. Besides, loops let us do a lot more things. To repeat the above assignment, we can use a `for()` loop (for illustration only; generally there is no need to do this using a loop): ```{r} for(j in 1:12) { vec1[j] <- j } ``` What's happening here? - The set of lines enclosed in braces or curly brackets {} are repeated, with j holding a different value each time {...} is run - Immediately above the curly brackets is the `for()` *loop* (not a function even though it has parentheses) - The `for()` loop specifies the looping variable as `<indexobject> in <vector>` where `in` is a special text that is compulsory - On seeing a `for()` statement, R first identifies the looping variable (j) and the looping vector `(1:12)`. Then, R replaces j with the first element in the iteration vector, runs the block of code {}, moves j to the second element in the iteration vector, runs the same block of code {} but with *a different value of j*, moves j to the third element in the iteration vector... and so on. When it reaches the end of the vector sequence, it stops *looping* and exits this block of code. Let's see some examples: Example 1: Here, the output vector `vec2` holds some combination of the index variable - ```{r} vec1 <- vector(mode = "numeric",length = 9) # this is another way to define a vector: # mode specifies the data type in double-quotes, and # length specifies how many elements the vector contains # vec1 <- NULL # when you don't know how long your vector is, # we can do this as a safe option: note that vec3 is not a vector, # it's just an empty object for(j in 1:9) { vec1[j] <- j*2 } ``` Example 2: We're printing some combination of the looping variable, `vec2` is not required - ```{r} vec2 <- vector(mode = "numeric",length = 9) for(j in 1:9) { print(x = paste("Currently on",j,"th index and square-root of the index is",sqrt(j))) } ``` Q. What does the `paste()` function do? what about the `paste0()` function? Example 3: Here, contents of our output vector `vec2` is not related to the index variable; the looping variable is only used to extract the value from the index of another object, in this case, `random_nos` - ```{r} vec3 <- vector(mode = "numeric",length = 9) tmp1 <- runif(n = 9,min = 50,max = 52) random_nos <- round(x = tmp1,digits = 1) for(j in 1:9) { vec3[j] <- random_nos[j] } ``` Notice how `9` is repeated thrice: once when creating the output vector holder `vec3`, once when defining the input vector `random_nos`, and a third time in our loop. It's always good practice to provide this information programmatically like so: ```{r} len <- 9 vec3 <- vector(mode = "numeric",length = len) tmp1 <- runif(n = len,min = 50,max = 52) random_nos <- round(x = tmp1,digits = 1) for(j in 1:len) { vec3[j] <- random_nos[j] } ``` We can simply change the number assigned to object `len` and we will get a different output Example 4: Here, j runs through a sequence that *cannot* be used as an index element for any vector - ```{r} for(j in seq(from = 0.1,to = 0.9,by = 0.1)) { print("This is a rather contrived example",j) } ``` Why can't we use the looping variable here? Example 5: The iteration vector can be a character vector as well: ```{r} for(j in c("I","like","a","potato")) { print(j) } ``` Here's some reason to rethink our love for potatoes [video](https://ruralindiaonline.org/articles/the-potato-song/) Rule of thumb: If you're running a loop where the output has to be saved in successive elements in an object, use a sequential index starting from 1 and going up to the length of the object There are two other loops - `while() {}` and `repeat {}` - as well as two other loop controls (`break` and `next`) that are useful in some situations. Another related concept is nested loops - one loop within another. you can go over all of these [here](https://www.datacamp.com/community/tutorials/tutorial-on-loops-in-r). Of these, nested loops is the most useful additional concept and we can discuss that in class, while other topics are good to know but may be less important. #### Practice: (do not submit this, we can discuss in class) Practice joining data frames by joining tab3 with tab2, *using `Spp1` in `tab3` and `Spp1Code1` in `tab2`*. Then, run a loop over each row in the resulting data frame, and count how many rows have both Spp1Det and Spp2Det equal to zero. In each of those rows, add up the `MeanBodySize` while running the loop over each row of the dataframe (both these need counter variables: they are defined as zero outside the loop and in the loop, their value is updated each time: e.g., `counter = counter + 1` adds 1 to the counter each time the block of code is run). To identify what fraction of rows were zero and what the average `MeanBodySize` was, can divide both the counter variables by the number of iterations - i.e. the number of times the loop is run, length of the iteration vector. ![Warm shade in Bogd uul, Bogdkhan Uul Protected Area, Mongolia. Photo: Chagsaa Odonjavkhlan](spruceup/mongolia2_chagsaa.jpeg) \newpage # Problem Set The problem set is built around a dataset of tree species occurrences within three habitats. While the dataset itself is not real, it is inspired by real species and places. Import the file *`prob_set_data.csv`* and store it within an object named `treedat`. Each row corresponds to individual trees of different Species recorded within three Habitats -- `Type_1`, `Type_2` and `Type_3` 1. We need to add a column describing the year during which each habitat type was sampled. `Type_2` was sampled in 2017, and `Type_1` and `Type_3` during 2018. Can you add this information to the tibble using `mutate()` in conjunction with a conditional statement? Call the new column `Year_conditional` 2. Can you also achieve the above task using a join function? In this case, call the new column for year `Year_join` [hint: first, create a new tibble `Year_tib <- tibble(Habitat = c(“Type_1”, “Type_2”, “Type_3”), Year_join = c(2018, 2017, 2018)` ] 3. Using what you have learned previously in `dplyr`, generate a table reporting the number of trees recorded within each habitat type (i.e., the numbers of rows of data within each habitat type) [hint: `group_by()`, `summarize()`] 4. Again, using `dplyr` functions, generate a table reporting the number of species recorded in each habitat type. Also generate a bar graph showing the species richness of the three habitats. [hint: `n_distinct()`] Can you comment on which of the three habitats harbours the most species? Based on raw counts, you may notice that Habitat `Type_2` has the most species, followed by `Type_3` and then by `Type_1.` You may also notice a similar ranking in terms of overall counts of trees (`Type_2` > `Type_3` > `Type_1`). In making comparisons between habitats, sometimes we may be more interested in knowing the numbers of species for a given number of individuals in each habitat, than in the overall counts of species per habitat. This approach is called **individual-based rarefaction**. 5. Use `dplyr` tools to create a subset of the dataset comprising only data from habitat `Type_1`. Store this in an object `habitat_1`. From within `habitat_1`, select a random sample (without replacement) of 50 individuals, and count how many species this sample contains. Repeat the selection step five times, and as a comment in your code report the number of species present in each selection. Do you get the same number of species each time? 6. As above, create data subsets corresponding to habitat `Type_2` and `Type_3`, and name them `habitat_2` and `habitat_3`, respectively. Use a `for()` loop to perform 100 iterations of individual-based rarefactions for each habitat. In each iteration, draw a sample of 50 individuals and count the numbers of species contained within the sample for each habitat. Plot the comparison of rarefied species richness across the three habitats using a boxplot. Bonus question: Create a graph showing the rate of accumulation of species as more individuals are sampled in the three habitats. Use a `for()` loop with 100 iterations to estimate the average number of species obtained per 25, 50, and 75 individuals sampled in each habitat. Make a line graph showing the three species accumulation curves.
const fs = require('fs'); const { parse} = require('csv-parse'); //round a number to one decimal if it has more than one, //if dividing by 0, return 0 instead of null function roundOneDecimal(number) { return (number) ? Math.round(number * 10) / 10 : 0; } //if player hasn't got any stats just store new stats, //else update old stats (sum up every parameter of both) function update(array, data, playerFullName) { if (!(playerFullName in array)) array[playerFullName] = data; else for (let i= 0; i < data.length; ++i) array[playerFullName][i] += data[i]; return array; } //calculate statistics based on data from csv file function calculateStatistics(array) { const returnObject = {}; for (let key in array) { const curr = array[key]; const matchesPlayed = parseFloat(curr[11]); const points = curr[0] + curr[2] * 2 + curr[4] * 3; returnObject[key] = { "playerName": key, "gamesPlayed": matchesPlayed, "traditional": { "freeThrows": { "attempts": roundOneDecimal(curr[1] / matchesPlayed), "made": roundOneDecimal(curr[0] / matchesPlayed), "shootingPercentage": roundOneDecimal(curr[0] / parseFloat(curr[1]) * 100.0), }, "twoPoints": { "attempts": roundOneDecimal(curr[3] / matchesPlayed), "made": roundOneDecimal(curr[2] / matchesPlayed), "shootingPercentage": roundOneDecimal(curr[2] / parseFloat(curr[3]) * 100.0), }, "threePoints": { "attempts": roundOneDecimal(curr[5] / matchesPlayed), "made": roundOneDecimal(curr[4] / matchesPlayed), "shootingPercentage": roundOneDecimal(curr[4] / parseFloat(curr[5]) * 100.0), }, "points": roundOneDecimal(points / matchesPlayed), "rebounds": roundOneDecimal(curr[6] / matchesPlayed), "blocks": roundOneDecimal(curr[7] / matchesPlayed), "assists": roundOneDecimal(curr[8] / matchesPlayed), "steals": roundOneDecimal(curr[9] / matchesPlayed), "turnovers": roundOneDecimal(curr[10] / matchesPlayed) }, "advanced": { "valorization": roundOneDecimal(((points + curr[6] + curr[7] + curr[8] + curr[9]) - (curr[1] - curr[0] + curr[3] - curr[2] + curr[5] - curr[4] + curr[10])) / matchesPlayed), "effectiveFieldGoalPercentage": roundOneDecimal((curr[2] + 1.5 * curr[4]) / (curr[3] + curr[5]) * 100.0), "trueShootingPercentage": roundOneDecimal(points / (2 * (curr[3] + curr[5] + 0.475 * curr[1])) * 100.0), "hollingerAssistRatio": roundOneDecimal(curr[8] / (curr[3] + curr[5] + 0.475 * curr[1] + curr[8] + curr[10]) * 100.0) } }; } //final object - calculated stats ready for returning as a response return returnObject; } //start in-memory database const onServerStart = () => { return new Promise((resolve, reject) => { //store data from csv file here let startData = {}; //read csv file and store data in an object with {key, value} pairs //with key being playerFullName and value sum of every column, while //pushing an element at the end for counting total matches played fs.createReadStream("./L9HomeworkChallengePlayersInput.csv") .pipe(parse({delimiter: ",", from_line: 2})) .on("data", function (row) { const data = row.slice(2, 13).map(function (val) { return parseInt(val); }); //add match counter data.push(1); //update current player stats startData = update(startData, data, row[0]); }) .on("end", function () { //calculate stats before returning object const returnObject = calculateStatistics(startData); resolve(returnObject); }) .on("error", function (err) { reject(err); }); }); }; module.exports = { roundOneDecimal: roundOneDecimal, onServerStart: onServerStart, update: update, calculateStatistics: calculateStatistics };
import type { NextPage } from 'next'; import Head from 'next/head'; import { useRouter } from 'next/router'; import { useCountry } from '../../app/hooks/useCountry'; import styles from '../../styles/Home.module.css'; const Country: NextPage = () => { const { query } = useRouter(); const { isLoading, country, error } = useCountry(String(query?.id)); return ( <div className={styles.container}> <Head> <title>{country?.name}</title> <meta name='description' content='Generated by create next app' /> <link rel='icon' href='/favicon.ico' /> </Head> <main className={styles.main}> <h1>{country?.name}</h1> {error && <div style={{ color: 'red' }}>{(error as any).message}</div>} {isLoading ? ( <h1>Loading...</h1> ) : ( <div className={styles.grid}> <div className={styles.card}> <h2>{country?.name}</h2> <p>{country?.description}</p> </div> </div> )} </main> </div> ); }; export default Country;
<!DOCTYPE html> <html> <head> <title>Simple Map</title> <meta name="viewport" content="initial-scale=1.0"> <meta charset="utf-8"> <style> /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script> var citymap = { chicago: { center: {lat: 41.878, lng: -87.629}, population: 2714856 }, newyork: { center: {lat: 40.714, lng: -74.005}, population: 8405837 }, losangeles: { center: {lat: 34.052, lng: -118.243}, population: 3857799 }, vancouver: { center: {lat: 49.25, lng: -123.1}, population: 603502 } }; function initMap() { // Create the map. var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: {lat: 37.090, lng: -95.712}, mapTypeId: 'terrain' }); // Construct the circle for each value in citymap. // Note: We scale the area of the circle based on the population. for (var city in citymap) { // Add the circle for this city to the map. var cityCircle = new google.maps.Circle({ strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35, map: map, center: citymap[city].center, radius: Math.sqrt(citymap[city].population) * 100 }); setTimeout console.log(cityCircle); } } </script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAuku1HrMKyM4t9t7zYYkoPRCkR_o2EELg&callback=initMap" async defer></script> <script> $(document).ready(function(){ var map; var markerArr=[]; function initialize() { var mapOptions = { zoom: 9, mapTypeControl: false, center: new google.maps.LatLng(42.36, -71.06) }; map = new google.maps.Map(document.getElementById('map'), mapOptions); // image from external URL var myIcon ='https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/cheshire1-icon.png'; //preparing the image so it can be used as a marker //https://developers.google.com/maps/documentation/javascript/reference#Icon //includes hacky fix "size" to allow for wobble var catIcon = { url: myIcon, size: new google.maps.Size(100, 60), scaledSize: new google.maps.Size(70, 60), origin: new google.maps.Point(-15,0) } /* //If you want to do this without wobble animation no need for hacky fix var catIcon = { url: myIcon, size: new google.maps.Size(70, 60), scaledSize: new google.maps.Size(70, 60), origin: new google.maps.Point(0,0) }*/ //gets GeoJSON from external file $.getJSON( "https://codepen.io/kevinkononenko/pen/dMKzgG.js", function(data) { var length= data.features.length for (var i=0; i < length; i++){ var eachData = data.features[i].properties var latLng = new google.maps.LatLng(eachData.Latitude, eachData.Longitude); var marker = new google.maps.Marker({ position:latLng, map: map, // set the icon as catIcon declared above icon: catIcon, // must use optimized false for CSS optimized: false, title: markerArr.length.toString() }); markerArr.push(marker); //add a click handler that does nothing at the moment google.maps.event.addListener(marker, 'click', function() { var thisTitle= Number(this.title); //$('#markerLayer img').eq(thisTitle) }) } }); // Overlay view allows you to organize your markers in the DOM // https://developers.google.com/maps/documentation/javascript/reference#OverlayView var myoverlay = new google.maps.OverlayView(); myoverlay.draw = function () { // add an id to the layer that includes all the markers so you can use it in CSS this.getPanes().markerLayer.id='markerLayer'; }; myoverlay.setMap(map); } initialize(); // use jQuery to change the markers animation based on toggle button $('.btn').click(function(){ var type = $(this).data('anim'); $('#markerLayer img').css('animation', type+ ' 1s infinite alternate'); $('#markerLayer img').css('-webkit-animation', type+ ' 1s infinite alternate') }) }); </script> </body> </html>
document.addEventListener('DOMContentLoaded', function () { const mbtiPersonalityTypes = { ISTJ: "ISTJs are practical, responsible, and detail-oriented individuals who value tradition and strive for stability.", ISFJ: "ISFJs are warm-hearted, compassionate, and conscientious individuals who are dedicated to helping and supporting others.", INFJ: "INFJs are insightful, empathetic, and idealistic individuals who are deeply committed to personal growth and making a positive impact on the world.", INTJ: "INTJs are strategic, independent, and analytical individuals who possess a strong drive for achieving their goals and implementing their visions.", ISTP: "ISTPs are adaptable, logical, and hands-on individuals who excel in troubleshooting and mastering practical skills.", ISFP: "ISFPs are gentle, artistic, and sensitive individuals who value personal authenticity and have a deep appreciation for beauty and aesthetics.", INFP: "INFPs are compassionate, creative, and introspective individuals who are driven by their values and have a strong desire to make a difference.", INTP: "INTPs are curious, logical, and innovative individuals who enjoy exploring complex ideas and theories in depth.", ESTP: "ESTPs are energetic, outgoing, and action-oriented individuals who thrive in dynamic environments and enjoy taking risks.", ESFP: "ESFPs are spontaneous, fun-loving, and sociable individuals who bring joy and enthusiasm to their interactions and appreciate the present moment.", ENFP: "ENFPs are enthusiastic, empathetic, and imaginative individuals who are passionate about inspiring others and exploring new possibilities.", ENTP: "ENTPs are quick-witted, innovative, and intellectually curious individuals who enjoy debating ideas and exploring diverse perspectives.", ESTJ: "ESTJs are practical, organized, and responsible individuals who value efficiency, structure, and taking charge of situations.", ESFJ: "ESFJs are warm, caring, and conscientious individuals who are dedicated to the well-being of others and creating harmonious environments.", ENFJ: "ENFJs are charismatic, empathetic, and inspiring individuals who excel at understanding and supporting the needs of others.", ENTJ: "ENTJs are assertive, confident, and strategic individuals who are natural leaders and enjoy tackling complex challenges.", }; const modal = new bootstrap.Modal('#jobRecommendationModal', { keyboard: false }) function hideProgress() { const progressContainer = document.querySelector('.progress-container'); progressContainer.style.display = 'none'; } function showProgress() { const progressContainer = document.querySelector('.progress-container'); progressContainer.style.display = 'block'; } const fetchData = async function (id) { const url = '/resume-jobs/'; // Replace with your server's endpoint const csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0].value try { const response = await fetch(url, { method: 'POST', // Add any request headers if needed headers: { 'Content-Type': 'application/json', 'Accept': 'application/json; indent=4', 'X-CSRFToken': csrfToken }, credentials: 'include', // Include session cookies body: JSON.stringify({ resume_id: id, name: 'bob' }) }); if (!response.ok) { throw new Error('Request failed'); } const data = await response.json(); const mbti = data['mbti']; const ok = data['ok'] const divElement = document.getElementById('id40'); if (!ok) { setTimeout(function () { fetchData(id) }, 5000) console.log("Still waiting for server predicted mbti...") } else { hideProgress() document.getElementById('jobTable').style.display = 'table' divElement.textContent = mbti displayJobs(data['jobs']) document.getElementById('id41').textContent = mbtiPersonalityTypes[mbti]; } } catch (error) { console.error('Error:', error); } } function displayJobs(data) { const tableBody = document.getElementById('jobTableBody'); const modalTitle = document.getElementById('jobModalTitle'); const modalBody = document.getElementById('jobModalBody'); // a JavaScript function that takes a string as input, removes newline characters (\n), eliminates extra // spaces within the text, and returns the resulting string, // ensuring it contains a maximum of 200 characters: function processString(inputString) { // Ensure maximum of 200 characters if (inputString.length > 200) { inputString = inputString.substring(0, 200); inputString += " ..." } // Remove newline characters let processedString = inputString.replace(/\n/g, ''); // Remove extra spaces within the text processedString = processedString.replace(/ +/g, ' '); // Trim leading and trailing spaces processedString = processedString.trim(); return processedString; } data.forEach((job, index) => { const row = document.createElement('tr'); row.addEventListener('click', () => { showModal(job); }); row.style.cursor = 'pointer' const titleCell = document.createElement('td'); titleCell.textContent = job['title']; const descriptionCell = document.createElement('td'); descriptionCell.textContent = processString(job['description']); row.appendChild(titleCell); row.appendChild(descriptionCell); tableBody.appendChild(row); }); function showModal(job) { modalTitle.textContent = job['title']; modalBody.textContent = job['description']; const innerModal = new bootstrap.Modal(document.getElementById('jobModal')); innerModal.show(); } } function handleClick(event) { // Get the clicked element const clickedElement = event.currentTarget; // Read the attribute value const resumeId = clickedElement.getAttribute('data-resume-id'); const fileName = clickedElement.getAttribute('data-file-name'); const label = document.getElementById('jobRecommendationModalLabel'); label.innerText = fileName; // Clean the job recommendations table and the predicted personality display { const el = document.getElementById('jobTableBody'); el.innerHTML = ''; document.getElementById('jobTable').style.display = 'none' document.getElementById('id40').textContent = '' } modal.show() showProgress() fetchData(resumeId).then() // Simulate data retrieval delay // setTimeout(() => { // hideProgress(); // }, 50000000); } // Get all elements with the specified class const elements = document.querySelectorAll('.resume-card'); // Attach the onclick listener to each element elements.forEach(element => { element.addEventListener('click', handleClick); }); })
import 'package:flutter/material.dart'; class CustomFilledButton extends StatelessWidget { final VoidCallback? onPressed; final String buttonText; final Color? buttonColor; final Color? buttonTextColor; final double? width; final bool? isDisabled; const CustomFilledButton({ super.key, this.onPressed, required this.buttonText, this.buttonColor, this.buttonTextColor, this.width, this.isDisabled, }); @override Widget build(BuildContext context) { return SizedBox( width: width ?? double.infinity, height: 50, child: FilledButton( style: FilledButton.styleFrom( backgroundColor: buttonColor, ), onPressed: onPressed, child: Text( buttonText, style: TextStyle(color: buttonTextColor), ), ), ); } }
import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { PlayerService } from 'src/services/player.service'; @Component({ selector: 'app-bar', templateUrl: './bar.component.html', styleUrls: ['./bar.component.css'], }) export class BarComponent implements OnInit { name = ''; subscriptionPlayers: Subscription; data: any; dates: string[] = []; johnPoints: number[] = []; larryPoints: number[] = []; canvas; left: number; top: number; constructor( private playerService: PlayerService, private router: Router ) {} ngOnInit(): void { var num = 2; this.subscriptionPlayers = this.playerService .getPlayers() .subscribe((players) => { this.name = this.router.url.substring(1); //if it is not larry's or john's chart if (this.name != 'john' && this.name != 'larry') { this.router.navigate(['/']); } this.dates = players.data.DAILY.dates; this.johnPoints = players.data.DAILY.dataByMember.players.john.points; this.larryPoints = players.data.DAILY.dataByMember.players.larry.points; const canvas = <HTMLCanvasElement>document.getElementById('chart'); this.canvas = canvas; this.left = canvas.getBoundingClientRect().x; this.top = canvas.getBoundingClientRect().y; const context = canvas.getContext('2d'); context.fillStyle = '#262a33'; context.fillRect( 0, 0, this.playerService.config.chartWidth, this.playerService.config.chartHeight ); if (this.name == 'john') { num = 0; this.playerService.drawPlayer( context, this.johnPoints, this.dates, 'cyan' ); this.playerService.addTitleToChart(context, 'Johns Score'); } else if (this.name == 'larry') { num = 1; this.playerService.drawPlayer( context, this.larryPoints, this.dates, 'pink' ); this.playerService.addTitleToChart(context, 'Larrys Score'); } else { this.playerService.drawBarChart( context, this.johnPoints, this.larryPoints, this.dates ); this.playerService.addTitleToChart(context, 'John & Larry Score'); num = 2; } this.playerService.addHorizontalLines(context); canvas.addEventListener('click', (e) => { this.playerService.handleMouseMove( e, context, this.johnPoints, this.larryPoints, this.top, this.left, num ); }); }); } ngOnDestroy(): void { this.subscriptionPlayers.unsubscribe(); } }
import React from "react"; import { View, TouchableOpacity, Text, StyleSheet } from "react-native"; import { AddIcon, ShareIcon } from "../SvgAssets/SvgAssets"; const FloatingActionButton = ({ onPress, type, disabled }) => { const getIcon = () => { switch (type){ case 'add': return <AddIcon size={23} />; case 'share': return ( <View style={{marginBottom:5}}> <ShareIcon size={27}/> </View>) default : return (<AddIcon size={23} />) } }; return ( <TouchableOpacity style={styles.fab} onPress={onPress} disabled={disabled}> <View style={styles.fabContent}>{getIcon()}</View> </TouchableOpacity> ); }; FloatingActionButton.defaultProps = { type: "add", disabled: false }; const styles = StyleSheet.create({ fab: { position: "absolute", bottom: 16, right: 16, width: 56, height: 56, borderRadius: 28, backgroundColor: "#155CEF", alignItems: "center", justifyContent: "center", elevation: 6, }, fabContent: { alignItems: "center", justifyContent: "center", }, }); export default FloatingActionButton;
<div class="mat-elevation-z4"> <table mat-table [dataSource]="products"> <!-- Id Column --> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef>Id</th> <td mat-cell *matCellDef="let row">{{ row.id }}</td> </ng-container> <!-- Name Column --> <ng-container matColumnDef="nome"> <th mat-header-cell *matHeaderCellDef>Nome</th> <td mat-cell *matCellDef="let row">{{ row.nome }}</td> </ng-container> <!-- Quantidade Column --> <ng-container matColumnDef="quantidade"> <th mat-header-cell *matHeaderCellDef>Quantidade</th> <td mat-cell *matCellDef="let row">{{ row.quantidade }}</td> </ng-container> <!-- Fornecedor Column --> <ng-container matColumnDef="fornecedor"> <th mat-header-cell *matHeaderCellDef>Fornecedor</th> <td mat-cell *matCellDef="let row">{{ row.fornecedor }}</td> </ng-container> <!-- Validade Column --> <ng-container matColumnDef="validade"> <th mat-header-cell *matHeaderCellDef>Validade</th> <td mat-cell *matCellDef="let row">{{ row.validade }}</td> </ng-container> <!-- Categoria Column --> <ng-container matColumnDef="categoria"> <th mat-header-cell *matHeaderCellDef>Categoria</th> <td mat-cell *matCellDef="let row">{{ row.categoria }}</td> </ng-container> <!-- Action Column --> <ng-container matColumnDef="action"> <th mat-header-cell *matHeaderCellDef>Ações</th> <td mat-cell *matCellDef="let row"> <a routerLink="/products/update/{{ row.id }}" class="edit"> <i class="material-icons"> edit </i> </a> <a routerLink="/products/delete/{{ row.id }}" class="delete"> <i class="material-icons"> delete </i> </a> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr> </table> </div>
import React, { useState } from "react"; import { NavLink, useNavigate } from "react-router-dom"; import logo from '../assets/baby.png' import { Baby, Home, Menu, LogOut, LockKeyhole, CircleUser , BookOpen , UsersRound , Timer} from 'lucide-react'; import { authState } from "../recoil/index"; import { useRecoilState } from "recoil"; export default function AdminSideBar() { const [showNav, setShowNav] = useState(true); const [token, setToken] = useRecoilState(authState); const navigate = useNavigate(); const navClasses = ({ isActive }) => { const mainStyles = "flex items-center text-white border-2 p-2 w-full block rounded-xl justify-center "; if (isActive) return ( mainStyles + "shadow-md text-white border-mainRed bg-mainRed" ); else return ( mainStyles + " shadow-xl shadow-[1px_1px_10px_-5px] hover:text-mainRed hover:border-mainRed" ); }; const handleMenu = (e) => { setShowNav(!showNav); }; const handleLogout = (e) => { setToken(""); localStorage.removeItem("authadmin"); navigate("/admins/login"); }; return ( <div> <div className="m-2 p-1 fixed sm:hidden top-0 right-0 text-2xl cursor-pointer z-[2] bg-primaryColor rounded text-white" onClick={handleMenu} > {/* <AiOutlineMenu className=" text-white round"/> */} <Menu /> </div> <div className={`min-h-screen w-fit sm:max-w-min h-[100%] flex flex-col p-4 bg-primaryColor shadow-md hover:shadow-2xl z-[2] text-slate-800 font-bold overflow-hidden ${!showNav ? " sm:block hidden" : " sm:static fixed "}`} > <img src={logo} className="mb-10 w-24 mx-auto" /> {/* <Baby className="text-white mx-auto mb-10" size={40} /> */} <nav className="z-[2] whitespace-nowrap"> <ul className="flex flex-col h-full"> <li className="my-2 "> <NavLink to="/admins/dashboard/home" className={navClasses} > {/* <AiOutlineHome className="mx-2" /> */} <Home /> </NavLink> </li> <li className="my-2 "> <NavLink to="/admins/dashboard/admins" className={navClasses} > {/* <AiOutlineHome className="mx-2" /> */} <LockKeyhole /> </NavLink> </li> <li className="my-2 "> <NavLink to="/admins/dashboard/teachers" className={navClasses} > <CircleUser /> </NavLink> </li> <li className="my-2 "> <NavLink to="/admins/dashboard/courses" className={navClasses} > <BookOpen /> </NavLink> </li> <li className="my-2 "> <NavLink to="/admins/dashboard/users" className={navClasses} > <UsersRound /> </NavLink> </li> <li className="my-2 "> <NavLink to="/admins/dashboard/requests" className={navClasses} > <Timer /> </NavLink> </li> <li className="hover:cursor-pointer flex items-center text-white mt-8 p-2 w-full rounded-xl shadow-xl hover:border-mainRed hover:text-mainRed border-2" onClick={handleLogout} > {/* <FiLogOut className="mx-2 text-red-700" /> */} <LogOut /> </li> </ul> </nav> </div> </div> ); }
Milestone - #2 Full Name : Long Duc Hoang Student ID#: 122702228 Email : dhoang19@myseneca.ca Section : ZAA Date : 7/15/2023 Authenticity Declaration: I declare this submission is the result of my own work and has not been shared with any other student or 3rd party content provider. This submitted piece of work is entirely of my own creation. #ifndef MENU_H #define MENU_H #include <iostream> #include <cstring> const unsigned MAX_MENU_ITEMS = 20; namespace sdds { class MenuItem { char* m_content; friend class Menu; MenuItem(const char* content = nullptr); MenuItem(const MenuItem& other) = delete; MenuItem& operator=(const MenuItem& other) = delete; ~MenuItem(); operator bool() const; operator const char* () const; void display(std::ostream& ostr) const; }; class Menu { MenuItem m_title; MenuItem* m_menuItems[MAX_MENU_ITEMS]; int m_numOfItems; public: Menu(); Menu(const char* title); Menu(const Menu& other) = delete; Menu& operator=(const Menu& other) = delete; ~Menu(); std::ostream& viewTitle(std::ostream& ostr) const; std::ostream& viewMenu(std::ostream& ostr)const; unsigned int run() const; unsigned int operator~() const; Menu& operator<<(const char* menuitemConent); operator unsigned int() const; operator bool() const; const char* operator[](unsigned index) const; }; std::ostream& operator<<(std::ostream& os, const Menu& menu); } #endif
// src/components/AddTeacherForm.js import React, { useState } from 'react'; import { useStudentTeacherContext } from '../context/StudentTeacherContext'; function AddTeacherForm() { const { addTeacher } = useStudentTeacherContext(); const [newTeacher, setNewTeacher] = useState({ name: '', subject: '' }); const handleInputChange = (e) => { const { name, value } = e.target; setNewTeacher({ ...newTeacher, [name]: value }); }; const handleSubmit = (e) => { e.preventDefault(); addTeacher(newTeacher); setNewTeacher({ name: '', subject: '' }); }; return ( <div> <h2>Add Teacher</h2> <form onSubmit={handleSubmit}> <input type="text" name="name" placeholder="Name" value={newTeacher.name} onChange={handleInputChange} /> <input type="text" name="subject" placeholder="Subject" value={newTeacher.subject} onChange={handleInputChange} /> <button type="submit">Add</button> </form> </div> ); } export default AddTeacherForm;
import { FC } from 'react'; import { Container, decorate, injectable, METADATA_KEY } from 'inversify'; const container = new Container(); const reigstrars: { [symbol: string]: any[] } = {}; const iocContainer = { register: (symbol: string, implementor: any) => { if (container.isBound(symbol)) return; if (!Reflect.hasOwnMetadata(METADATA_KEY.PARAM_TYPES, implementor)) { decorate(injectable(), implementor); } container.bind(symbol).toFactory(implementor); }, get: <T>(symbol: string) => { return container.isBound(symbol) ? container.get<T>(symbol) : undefined; }, removeAll: () => { container.unbindAll(); }, onRegister: (symbol: any, event: any) => { if (reigstrars[symbol]) { reigstrars[symbol].push(event); } else { reigstrars[symbol] = [event]; } }, notifyRegistrars: () => { Object.entries(reigstrars).forEach(([_symbol, registrarFns]) => { registrarFns.forEach((fn) => fn()); }); }, }; const resolveDependencies = (deps: string[]) => { const resolved: any[] = []; deps.forEach((dep) => { if (!container.isBound(dep)) { throw new Error(`${dep} was not registered properly. Please make sure to register it into the container.`); } const resolvedDep: any = iocContainer.get(dep); resolved.push(resolvedDep); }); return resolved; }; export const withDependencies = <T, K>( factory: (deps: T) => FC<K>, deps: string[] ) => { return factory(resolveDependencies(deps) as any); }; export const withServiceDependencies = <T>(factory: (deps: any) => any, deps: string[]) => () => { return factory(resolveDependencies(deps) as any) as T; }; export default iocContainer;
import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Input, Dense from tensorflow.keras import initializers #y = 3*x1 + 5*x2 + 10 def gen_sequential_model(): model = Sequential([ Input(2, name='input_layer'), Dense(16, activation='sigmoid', name='hidden_layer1', kernel_initializer=initializers.RandomNormal(mean=0.0, stddev=0.05, seed=42)), Dense(1, activation='relu', name='output_layer', kernel_initializer=initializers.RandomNormal(mean=0.0, stddev=0.05, seed=42)) ]) model.summary() #print(model.layers[0].get_weights()) #print(model.layers[1].get_weights()) model.compile(optimizer='sgd', loss='mse') return model #y = w1*x1 + w2*x2 + b def gen_linear_regression_dateset(numofsamples=500, w1=3, w2=5, b=10): np.random.seed(42) X = np.random.rand(numofsamples, 2) print(X) print(X.shape) coef = np.array([w1, w2]) bias = b print(coef) print(coef.shape) y = np.matmul(X, coef.transpose()) + bias #X=(numofsamples, 2), coef.transpose() = (2,1) print(y) print(y.shape) return X, y def plot_loss_curve(history): import matplotlib.pyplot as plt plt.figure(figsize=(15, 10)) plt.plot(history.history['loss'][1:]) plt.plot(history.history['val_loss'][1:]) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper right') plt.show() def predict_new_sample(model, x, w1=3, w2=5, b=10): x = x.reshape(1,2) y_pred = model.predict(x)[0][0] y_actual = w1*x[0][0] + w2*x[0][1] + b print("y actual value = ", y_actual) print("y predicted value = ", y_pred) model = gen_sequential_model() X, y = gen_linear_regression_dateset(numofsamples=1000) history = model.fit(X, y, epochs=200, verbose=2, validation_split=0.3) plot_loss_curve(history) print("train loss=", history.history['loss'][-1]) print("test loss=", history.history['val_loss'][-1]) predict_new_sample(model, np.array([0.6, 0.3]))
""" This module handles users commands """ # pylint:disable=broad-except import inspect from aiogram import types from aiogram.types import ParseMode, CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup import aiogram.utils.markdown as md from aiogram.utils.exceptions import MessageCantBeDeleted from src.packages.bot.keyboards import buttons from src.packages.database import DatabaseException from src.packages.loaders import env_variables from src.packages.bot.filters import GroupMember, ChatWithABot from src.packages.bot.loader import dispatcher, bot from src.packages.database import UserTable, RideRequestTable from src.packages.logger import logger, Loggers def escape_md(text: str or int): # todo: найти аналог в библиотеке text = str(text) text = text.replace("_", "\\_") text = text.replace("*", "\\*") text = text.replace("`", "\\`") text = text.replace("~", "\\~") text = text.replace("|", "\\|") return text def refactor_str(str_input: str or int): """ This function refactor string """ str_input = str(str_input) return f"{str_input if len(str_input) == 2 else '0' + str_input}" def get_inline_delete_button(ride_request_id: int): return ( InlineKeyboardMarkup( row_width=2, inline_keyboard=[ [ InlineKeyboardButton(text="Удалить", callback_data=f"delete_ride_request|{ride_request_id}"), ] ], ), ) page = 0 all_ride_requests = [] @dispatcher.message_handler(ChatWithABot(), GroupMember(), text=["Мои заявки"]) async def my_ride_requests_start(message: types.Message): """ @param message: Message object """ try: global page global all_ride_requests page = 0 all_ride_requests = [] tg_user_id = message.from_user.id message_from_user = message.text name_func = inspect.getframeinfo(inspect.currentframe()).function logger.info_from_handlers(Loggers.INCOMING.value, tg_user_id, name_func, message_from_user) try: user = await UserTable.get_by_telegram_id(message.from_user.id) all_ride_requests = await RideRequestTable.get_user_ride_requests(user.id) if len(all_ride_requests) == 0: await bot.send_message(message.chat.id, "У вас нет созданных заявок.") return all_ride_requests.reverse() await show_requests(message) logger.info_from_handlers( Loggers.INCOMING.value, tg_user_id, name_func, message_from_user, "Показ пользователю списка заявок" ) except DatabaseException as error: logger.error_from_handlers(Loggers.INCOMING.value, tg_user_id, name_func, message_from_user, str(error)) await message.answer(text=str(error)) except Exception as ex: await message.answer( "По техническим причинам, мы не смогли обработать ваш запрос, попробуйте позже", reply_markup=buttons.main_menu_authorised, ) logger.critical(Loggers.APP.value, f"Ошибка {str(ex)}, функция: my_ride_requests_start") async def show_requests(message: types.Message): for i in range(5 * page, min(5 * (page + 1), len(all_ride_requests))): ride_request = all_ride_requests[i] await bot.send_message( message.chat.id, md.text( md.text( f'{md.bold("Дата и время: ")}{refactor_str(ride_request.date.day)}.' f"{refactor_str(ride_request.date.month)}.{ride_request.date.year} в " f"{refactor_str(ride_request.time.hour)}:{refactor_str(ride_request.time.minute)}" ), md.text( f"{md.bold('Условия довоза: ')}" f"{escape_md(ride_request.delivery_terms) if ride_request.delivery_terms != 'Дальше' and ride_request.delivery_terms is not None else 'Не указано'}" ), md.text( f'{md.bold("Место отправления: ")}{"" if ride_request.departure_place is None else escape_md(ride_request.departure_place)}' ), md.text( f'{md.bold("Место прибытия: ")}{"" if ride_request.destination_place is None else escape_md(ride_request.destination_place)}' ), md.text( f'{md.bold("Количество мест: ")}{"" if ride_request.seats_number is None else ride_request.seats_number}' ), sep="\n", ), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( row_width=2, inline_keyboard=[ [ InlineKeyboardButton(text="Удалить", callback_data=f"delete_ride_request|{ride_request.id}"), ] ], ), ) if len(all_ride_requests) > 5 * (page + 1): await bot.send_message( message.chat.id, "Вывести следующие заявки?", reply_markup=InlineKeyboardMarkup( row_width=2, inline_keyboard=[ [ InlineKeyboardButton(text="Да", callback_data="more_requests"), ] ], ), ) @dispatcher.callback_query_handler(lambda c: c.data == "more_requests") async def process_callback_more_requests(callback_query: types.CallbackQuery): global page page += 1 await show_requests(callback_query.message) @dispatcher.callback_query_handler(lambda call: "delete_ride_request" in call.data) async def send_message(call: CallbackQuery): """ Handler for the delete button. `call.data` is passed the id of the ride request to be deleted :param call: CallbackQuery object """ try: tg_user_id = dict(call).get("from").get("id") message_from_user = dict(call).get("data") name_func = inspect.getframeinfo(inspect.currentframe()).function ride_request_id = int(call.data.split("|")[1]) try: ride_request = await RideRequestTable.get_single_ride_request(ride_request_id) except DatabaseException: logger.warning_from_handlers( Loggers.INCOMING.value, tg_user_id, name_func, message_from_user, "Заявка не найдена в базе данных" ) channel_id = env_variables.get("CHANNEL_ID") try: await bot.delete_message(channel_id, ride_request.post_message_id) # todo: точно такое исключение должно быть? except UnboundLocalError as e: logger.warning_from_handlers( Loggers.INCOMING.value, tg_user_id, name_func, message_from_user, f"Удаление несуществующей заявки {e}" ) except MessageCantBeDeleted as e: logger.info_from_handlers( Loggers.INCOMING.value, tg_user_id, name_func, message_from_user, f"Сообщение с заявкой не получается удалить {e}", ) await call.answer( "С момента публикации вашей заявки прошло 48 часов, для удаления вам понадобится помощь администратора", show_alert=True, ) return try: await RideRequestTable.delete(ride_request_id) except DatabaseException: logger.warning_from_handlers( Loggers.INCOMING.value, tg_user_id, name_func, message_from_user, "Заявка не найдена в базе данных" ) await call.answer( "Заявка успешно удалена.\nДля просмотра обновленного списка заявок, вновь нажмите «Мои заявки»", show_alert=True, ) logger.info_from_handlers(Loggers.INCOMING.value, tg_user_id, name_func, message_from_user, "Заявка удалена") except Exception as ex: await call.answer("По техническим причинам, мы не смогли обработать ваш запрос, попробуйте позже") logger.critical(Loggers.APP.value, f"Ошибка {str(ex)}, функция: send_message(удаление авто)")
import React from 'react'; export const BUTTON_BASE_STYLE = 'inline-flex items-center justify-center rounded-md text-sm hover:shadow-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ring-offset-background'; export const BUTTON_VARIANTS = { variant: { primary: 'bg-rose-500 text-white hover:bg-rose-600', outline: 'border border-rose-500 text-rose-500 bg-white hover:bg-slate-100', secondary: 'bg-slate-100 hover:bg-slate-200', ghost: 'bg-transparent hover:bg-slate-100 opacity-80 hover:opacity-100', }, size: { base: 'h-10 py-2 px-4 rounded-xl', sm: 'h-9 px-3 rounded-xl', lg: 'h-10 px-8 rounded-2xl', }, }; export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { variant?: keyof (typeof BUTTON_VARIANTS)['variant']; size?: keyof (typeof BUTTON_VARIANTS)['size']; } const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( ({ className, variant = 'primary', size = 'base', ...rest }, ref) => { return ( <button {...rest} ref={ref} className={`${className} ${BUTTON_BASE_STYLE} ${BUTTON_VARIANTS.variant[variant]} ${BUTTON_VARIANTS.size[size]}`} /> ); } ); Button.displayName = 'Button'; export default Button;
import React from 'react'; import { aboutList, guideList, aboutDescriptions } from './Footer.data'; import { currency, language, location } from '../../constants/localeSetting'; import BeigeLine from '../../icons/BeigeLine'; import BlueLine from '../../icons/BlueLine'; import DarkBlueLine from '../../icons/DarkBlueLine'; import Eco from '../../icons/Eco'; import ToolTipTemplate from '../ToolTipTemplate'; import * as S from './Footer.style'; import COLORS from '../../styles/colors'; import BgAnimatedButton from '../BgAnimatedButton'; import SizeAnimatedButton from '../SizeAnimatedButton'; function Footer() { return ( <S.FooterContainer> <S.SVGWrapper top={0} left={0}> <BeigeLine width={1400} height={48} color={COLORS.white} /> </S.SVGWrapper> <S.AboutWrapper> <S.About> <S.AboutTitle>What is Etsy?</S.AboutTitle> <S.AboutLink>Read our wonderfully weird story</S.AboutLink> <S.AboutList> {aboutList.map(({ title, contents, extra }) => ( <S.AboutListContent key={title}> <S.ContentTitle>{title}</S.ContentTitle> <S.ContentParagraph> {contents} {extra && ( <> <S.ContentMoreSpan> {extra}</S.ContentMoreSpan> <ToolTipTemplate bgColor={COLORS.white} color={COLORS.mainFont} element={ <S.ToolTipUl> {aboutDescriptions.map(li => ( <S.ToolTipLi key={li}>{li}</S.ToolTipLi> ))} </S.ToolTipUl> } /> </> )} </S.ContentParagraph> </S.AboutListContent> ))} </S.AboutList> <S.AboutFootTitle> Have a question? Well, we’ve got some answers. </S.AboutFootTitle> <SizeAnimatedButton buttonLabel="Go to Help Center" bgColor="transparent" borderAttr="2px solid black" widthFit /> </S.About> </S.AboutWrapper> <S.Subscribe> <S.SVGWrapper top={-30} left={0}> <BlueLine width={1400} height={30} color={COLORS.lightBlue} /> </S.SVGWrapper> <S.SubscribeTitle> Yes! Send me exclusive offers, unique gift ideas, and personalized tips for shopping and selling on Etsy. </S.SubscribeTitle> <S.SubscribeForm> <S.Input type="email" placeholder="Enter your email" /> <S.SubscribeButton>Subscribe</S.SubscribeButton> </S.SubscribeForm> <S.SubscribeFooter> <S.SVGWrapper> <DarkBlueLine width={1400} height={48} color={COLORS.lightBlue} /> </S.SVGWrapper> <S.SubscribeFooterInfo> <Eco width={36} height={36} color={COLORS.white} /> <S.SubscribeFooterSpan> Etsy is powered by 100% renewable electricity. </S.SubscribeFooterSpan> </S.SubscribeFooterInfo> </S.SubscribeFooter> </S.Subscribe> <S.Guides> <S.GuidesWrapper> {guideList.map(({ title, list }, index) => ( <S.GuidesBox key={title}> <S.GuidesBoxTitle>{title}</S.GuidesBoxTitle> <S.GuidesBoxContents> {list.map(li => ( <S.Guide key={li}>{li}</S.Guide> ))} </S.GuidesBoxContents> {index === guideList.length - 1 && ( <S.HelpBox> <S.DownloadButton>Download the Etsy App</S.DownloadButton> <S.IconsBox>icons</S.IconsBox> </S.HelpBox> )} </S.GuidesBox> ))} </S.GuidesWrapper> </S.Guides> <S.FooterWrap> <S.FooterBox> <BgAnimatedButton buttonLabel={`${location} | ${language} | $ (${currency})`} textColor={COLORS.white} bgColor={COLORS.hoverWhite} /> <S.Policies> <span>2022 Etsy, Inc.</span> <S.PolicyList> {Array.from( ['Terms of use', 'Privacy', 'Interest-based ads'], li => ( <li key={li}>{li}</li> ) )} </S.PolicyList> </S.Policies> </S.FooterBox> </S.FooterWrap> </S.FooterContainer> ); } export default Footer;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta content="width=device-width, initial-scale=1" name="viewport" /> <title>Influencer Gears</title> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,400;1,100&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="style.css" /> </head> <body> <main> <section class="flexible-container"> <div class="header-section"> <div class="menu-icon"> <div></div> <div></div> <div></div> </div> <div class="header-section-logo"> <h2>Influencer products</h2> </div> <div class="navbar"> <ul class="nav-item"> <li>Home</li> <li>Products</li> <li>Sign up</li> <li>Log In</li> <li><i class="fa fa-search" style="font-size: 24px"></i></li> </ul> <span class="cart-icon"> <i class="fa fa-shopping-cart" style="font-size: 30px"></i> </span> </div> </div> </section> <section class="flexible-container"> <div class="heading-section"> <p class="heading-section-title">Start your Journey as Influencer</p> <p> The history of the Camera begins even before the introduction of photography. Cameras evolved from the camera obscura through many generations of photographic technology daguerreotypes, calotypes, dry plates, film to the modern day with digital cameras and camera phones. </p> <button class="primary-button button-redius"> Prebook now <i class="fa fa-long-arrow-right" style="font-size: 16px; margin-left: 5px" ></i> </button> </div> <div class="heading-section-image"> <img src="images/main-camera.png" alt="camera image" /> </div> </section> <section class="flexible-container"> <div class="partner-company"> <img src="logos/Alibaba.svg" alt="company logos" /> <img src="logos/Amazon.svg" alt="company logos" /> <img src="logos/Daraz.pk Logo.svg" alt="company logos" /> <img src="logos/Ebay.svg" alt="company logos" /> <img src="logos/Rakuten.svg" alt="company logos" /> <img src="logos/Walmart.svg" alt="company logos" /> <img src="logos/Target.svg" alt="company logos" /> </div> </section> <section class="flexible-container container-row"> <p class="section-heading">Popular Collection</p> <div class="card-grid"> <div class="card"> <img src="images/tripod.png" alt="card item" /> <p class="card-title">Flex Tripod</p> <p class="card-price">$50.48</p> <div class="card-rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star-half-o"></span> &nbsp; <strong>4.99</strong> </div> <div class="card-description"> <p>Wordwide shifting</p> <p>available</p> <p>Buyers protection possible!</p> </div> </div> <div class="card"> <img src="images/mic.png" alt="card item" /> <p class="card-title">microphone</p> <p class="card-price">$120.25</p> <div class="card-rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star-half-o"></span> &nbsp; <strong>4.99</strong> </div> <div class="card-description"> <p>Wordwide shifting</p> <p>available</p> <p>Buyers protection possible!</p> </div> </div> <div class="card"> <img src="images/airpod.png" alt="card item" /> <p class="card-title">Airbuds</p> <p class="card-price">$100</p> <div class="card-rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star-half-o"></span> &nbsp; <strong>4.99</strong> </div> <div class="card-description"> <p>Wordwide shifting</p> <p>available</p> <p>Buyers protection possible!</p> </div> </div> <div class="card"> <img src="images/drone.png" alt="card item" /> <p class="card-title">Drone</p> <p class="card-price">$980.25</p> <div class="card-rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star-half-o"></span> &nbsp; <strong>4.99</strong> </div> <div class="card-description"> <p>Wordwide shifting</p> <p>available</p> <p>Buyers protection possible!</p> </div> </div> <div class="card"> <img src="images/lights.png" alt="card item" /> <p class="card-title">Light Setup</p> <p class="card-price">$1200.00</p> <div class="card-rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star-half-o"></span> &nbsp; <strong>4.99</strong> </div> <div class="card-description"> <p>Wordwide shifting</p> <p>available</p> <p>Buyers protection possible!</p> </div> </div> <div class="card"> <img src="images/setup.png" alt="card item" /> <p class="card-title">Photoshoot set</p> <p class="card-price">$50.48</p> <div class="card-rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star-half-o"></span> &nbsp; <strong>4.99</strong> </div> <div class="card-description"> <p>Wordwide shifting</p> <p>available</p> <p>Buyers protection possible!</p> </div> </div> <div class="card"> <img src="images/camera.png" alt="card item" /> <p class="card-title">Vlogging Camera</p> <p class="card-price">$1800.80</p> <div class="card-rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star-half-o"></span> &nbsp; <strong>4.99</strong> </div> <div class="card-description"> <p>Wordwide shifting</p> <p>available</p> <p>Buyers protection possible!</p> </div> </div> <div class="card"> <img src="images/single-light.png" alt="card item" /> <p class="card-title">Green Screen</p> <p class="card-price">$25.48</p> <div class="card-rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star-half-o"></span> &nbsp; <strong>4.99</strong> </div> <div class="card-description"> <p>Wordwide shifting</p> <p>available</p> <p>Buyers protection possible!</p> </div> </div> <div class="card"> <img src="images/action.png" alt="card item" /> <p class="card-title">Action Camera</p> <p class="card-price">$380.00</p> <div class="card-rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star-half-o"></span> &nbsp; <strong>4.99</strong> </div> <div class="card-description"> <p>Wordwide shifting</p> <p>available</p> <p>Buyers protection possible!</p> </div> </div> </div> <button class="secondary-button"> See More <i class="fa fa-arrow-right" style="font-size: 16px; margin-left: 5px" ></i> </button> </section> <section class="flexible-container container-row"> <p class="section-heading">Today's Discount</p> <div class="product"> <ul class="top-product"> <li class="product-item"> <img src="images/drone.png" alt="card item" /> <div class="item"> <p class="item-name">Drone</p> <p class="item-price-old">$980.25</p> <p class="item-price">$900.00</p> <button class="buy-button">Buy Now</button> </div> </li> <li class="product-item"> <img src="images/camera.png" alt="card item" /> <div class="item"> <p class="item-name">Camera</p> <p class="item-price-old">$1800.80</p> <p class="item-price">$1500.50</p> <button class="buy-button">Buy Now</button> </div> </li> <li class="product-item"> <img src="images/action.png" alt="card item" /> <div class="item"> <p class="item-name">Action Camera</p> <p class="item-price-old">$380</p> <p class="item-price">$340.60</p> <button class="buy-button">Buy Now</button> </div> </li> <li class="product-item"> <img src="images/airpod.png" alt="card item" /> <div class="item"> <p class="item-name">Airbuds</p> <p class="item-price-old">$100</p> <p class="item-price">$91</p> <button class="buy-button">Buy Now</button> </div> </li> </ul> </div> </section> </main> <footer> <p class="footer-heading">Influencer products</p> <small>Copyright &copy; 2022 influencer products</small><br /> <small>All rights reserved</small> <div class="footer-icon"> <i class="fa fa-instagram"></i> <i class="fa fa-twitter-square"></i> <i class="fa fa-facebook-square"></i> <i class="fa fa-youtube"></i> </div> </footer> </body> </html>
#!/usr/bin/python3 """ This module contains the ORM for the course table """ from models.basemodel import Base from models.basemodel import Basemodel from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.orm import relationship from models.tables.course_tag import course_tag class Course(Basemodel, Base): """ Course ORM """ __tablename__ = "courses" tutor_id = Column(String(36), ForeignKey("tutors.id"), nullable=False) title = Column(String(256), nullable=False) about = Column(String(1027), nullable=False) price = Column(Integer, nullable=False, default=0) free = Column(Boolean, nullable=False, default=False) published = Column(Boolean, nullable=False, default=False) reviews = relationship("Review", backref="course", cascade="all, delete") videos = relationship("Video", backref="course", cascade="all, delete") tags = relationship("Tag", backref="courses", secondary=course_tag, cascade="all, delete", viewonly=False)
// // GameScene.swift // ApeOut // // Created by Atin Agnihotri on 31/08/21. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { weak var gameVC: GameViewController? var player1: SKSpriteNode! var player2: SKSpriteNode! var banana: SKSpriteNode! var currentPlayer = 1 { didSet { gameVC?.advanceTurn(to: currentPlayer) } } var player1Score = 0 { didSet { gameVC?.player1Score = player1Score if player1Score >= 3 { isGameOver = true } } } var player2Score = 0 { didSet { gameVC?.player2Score = player2Score if player2Score >= 3 { isGameOver = true } } } var isGameOver = false { didSet { if isGameOver { gameOver() } } } let BUILDING_LEFT_EDGE: CGFloat = -15 let BUILDING_RIGHT_EDGE: CGFloat = 1024 var BUILDING_RANDOM_WIDTH: Int { Int.random(in: 2...4) * 40 } var BUILDING_RANDOM_HEIGHT: Int { Int.random(in: 300...600) } var buildings = [BuildingNode]() override func didMove(to view: SKView) { setupEnvironment() print("Game loaded") } func setupEnvironment() { // Setup background backgroundColor = UIColor.BackgroundColor.backgroundColor physicsWorld.contactDelegate = self createBuildings() createPlayers() createRandomGustOfWind() } func createRandomGustOfWind() { switch Int.random(in: 0...4) { case 0: physicsWorld.gravity = SKPhysicsWorld.GustsOfWinds.zeroWind gameVC?.windLabel.text = "No Wind" case 1: physicsWorld.gravity = SKPhysicsWorld.GustsOfWinds.slightLeftWind gameVC?.windLabel.text = "Slight Left Wind" case 2: physicsWorld.gravity = SKPhysicsWorld.GustsOfWinds.strongLeftWind gameVC?.windLabel.text = "Strong Left Wind" case 3: physicsWorld.gravity = SKPhysicsWorld.GustsOfWinds.slightRightWind gameVC?.windLabel.text = "Slight Right Wind" default: physicsWorld.gravity = SKPhysicsWorld.GustsOfWinds.strongRightWind gameVC?.windLabel.text = "Strong Right Wind" } } func createBuildings() { var currentX = BUILDING_LEFT_EDGE while currentX < BUILDING_RIGHT_EDGE { let size = CGSize(width: BUILDING_RANDOM_WIDTH, height: BUILDING_RANDOM_HEIGHT) currentX += size.width + 2 // Little bit spacing bw building let buildingPosition = CGPoint(x: currentX - (size.width / 2), y: size.height / 2) let building = BuildingNode(color: .red, size: size) building.position = buildingPosition building.setup() addChild(building) buildings.append(building) } } func createPlayers() { player1 = createPlayer(number: 1, on: buildings[1]) player2 = createPlayer(number: 2, on: buildings[buildings.count - 2]) } func createPlayer(number: Int, on building: BuildingNode) -> SKSpriteNode { let player = SKSpriteNode(imageNamed: "player") player.name = "player\(number)" player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2) player.physicsBody?.categoryBitMask = CollisionTypes.player.rawValue player.physicsBody?.contactTestBitMask = CollisionTypes.banana.rawValue player.physicsBody?.collisionBitMask = CollisionTypes.banana.rawValue player.physicsBody?.isDynamic = false player.position = CGPoint(x: building.position.x, y: building.position.y + ((player.size.height + building.size.height) / 2)) addChild(player) return player } func launch(withAngle angle: Int, velocity: Int) { let speed = Double(velocity) / 10 let radAngle = deg2rad(degrees: angle) createBanana() setupBananaThrow() throwBanana(at: radAngle, with: speed) } func throwBanana(at angle: Double, with speed: Double) { banana.physicsBody?.angularVelocity = -20 var dx = speed * cos(angle) let dy = speed * sin(angle) if currentPlayer == 2 { dx *= -1 } let impulse = CGVector(dx: dx, dy: dy) banana.physicsBody?.applyImpulse(impulse) } func setupBananaThrow() { let throwAnimation = getThrowAnimation() if currentPlayer == 1 { banana.position = getBananaPosition(for: player1) player1.run(throwAnimation) } else { banana.position = getBananaPosition(for: player2) player2.run(throwAnimation) } } func getBananaPosition(for player: SKSpriteNode) -> CGPoint{ let xPos = player.position.x + ((currentPlayer == 1) ? -30 : 30) let yPos = player.position.y + 40 return CGPoint(x: xPos, y: yPos) } func getThrowAnimation() -> SKAction { let throwImage = "player\(currentPlayer)Throw" let raiseArm = SKAction.setTexture(SKTexture(imageNamed: throwImage)) let pause = SKAction.wait(forDuration: 0.15) let lowerArm = SKAction.setTexture(SKTexture(imageNamed: "player")) return SKAction.sequence([raiseArm, pause, lowerArm]) } func createBanana() { if banana != nil { banana.removeFromParent() banana = nil } banana = SKSpriteNode(imageNamed: "banana") banana.name = "banana" banana.physicsBody = SKPhysicsBody(circleOfRadius: banana.size.width / 2) banana.physicsBody?.categoryBitMask = CollisionTypes.banana.rawValue banana.physicsBody?.collisionBitMask = CollisionTypes.building.rawValue | CollisionTypes.player.rawValue banana.physicsBody?.contactTestBitMask = CollisionTypes.building.rawValue | CollisionTypes.player.rawValue banana.physicsBody?.usesPreciseCollisionDetection = true addChild(banana) } override func update(_ currentTime: TimeInterval) { guard banana != nil else { return } if abs(banana.position.y) > 1000 { banana.removeFromParent() banana = nil changePlayer() } } func didBegin(_ contact: SKPhysicsContact) { let firstBody: SKPhysicsBody let secondBody: SKPhysicsBody if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } guard let firstNode = firstBody.node else { return } guard let secondNode = secondBody.node else { return } if firstNode.name == "banana" && secondNode.name == "building" { bananaDidHit(building: secondNode, at: contact.contactPoint) } if firstNode.name == "banana" && secondNode.name == "player1" { bananaDidHit(player: player1) player2Score += 1 } if firstNode.name == "banana" && secondNode.name == "player2" { bananaDidHit(player: player2) player1Score += 1 } } func bananaDidHit(building: SKNode, at location: CGPoint) { guard let building = building as? BuildingNode else { return } createExplosion(at: location) let buildingContactPoint = convert(location, to: building) building.hit(at: buildingContactPoint) banana.name = "" // to prevent phantom collisions banana.removeFromParent() banana = nil changePlayer() } func bananaDidHit(player: SKNode) { createExplosion(for: player) banana.removeFromParent() player.removeFromParent() if !isGameOver { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { // No reference cycle here so no need of weak self self.changePlayer() self.instantiateNewScene() } } } func createExplosion(for player: SKNode) { if let explosion = SKEmitterNode(fileNamed: "hitPlayer") { explosion.position = player.position addChild(explosion) } } func createExplosion(at location: CGPoint) { if let explosion = SKEmitterNode(fileNamed: "hitBuilding") { explosion.position = location addChild(explosion) } } func deg2rad(degrees: Int) -> Double { Double(degrees) * .pi / 180 } func changePlayer() { if currentPlayer == 1 { currentPlayer = 2 } else { currentPlayer = 1 } } func instantiateNewScene() { let newScene = GameScene(size: self.size) newScene.gameVC = gameVC gameVC?.currentScene = newScene newScene.currentPlayer = currentPlayer newScene.player1Score = player1Score newScene.player2Score = player2Score let transition = SKTransition.doorway(withDuration: 1.5) // MARK: Check later view?.presentScene(newScene, transition: transition) } func gameOver() { let winner = (player1Score > player2Score) ? 1 : 2 gameVC?.showHUDControls(false) gameVC?.turnLabel.text = "GAME OVER: PLAYER \(winner) WINS" } }
"use client"; import { GET_CLIENTS } from "@/queries/clientQueries"; import { GET_PROJECTS } from "@/queries/projectQueries"; import { FaTrash } from "react-icons/fa"; const { useMutation } = require("@apollo/client"); const { DELETE_CLIENT } = require("../mutations/clientMutations"); export default function ClientRow({ client }) { const [deleteClient] = useMutation(DELETE_CLIENT, { variables: { id: client.id }, refetchQueries: [{ query: GET_CLIENTS }, { query: GET_PROJECTS }], // update(cache, { data: { deleteClient } }) { // const { clients } = cache.readQuery({ query: GET_CLIENTS }); // cache.writeQuery({ // query: GET_CLIENTS, // // filter out client id that matches the deleted client id // data: { clients: clients.filter((c) => c.id !== deleteClient.id) }, // }); // }, }); return ( <tr> <td>{client.name}</td> <td>{client.email}</td> <td>{client.phone}</td> <td> <button onClick={deleteClient} className="btn btn-outline-danger btn-sm" > <FaTrash /> </button> </td> </tr> ); }
package com.example.andreys.web; import com.example.andreys.model.dto.CreateProductDTO; import com.example.andreys.model.dto.ItemDTO; import com.example.andreys.service.ProductService; import com.example.andreys.service.UserService; import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class ProductController { private ProductService productService; private UserService userService; @Autowired public ProductController(ProductService productService, UserService userService) { this.productService = productService; this.userService = userService; } @ModelAttribute public CreateProductDTO init() { return new CreateProductDTO(); } @GetMapping("/products/add") public String addProduct() { if (!this.userService.isLogged()) { return "redirect:/"; } return "add-product"; } @PostMapping("/products/add") public String addProduct(@Valid CreateProductDTO createProductDTO, BindingResult bindingResult, RedirectAttributes redirectAttributes) { if (!this.userService.isLogged()) { return "redirect:/"; } if (bindingResult.hasErrors()) { redirectAttributes .addFlashAttribute("createProductDTO", createProductDTO); redirectAttributes .addFlashAttribute("org.springframework.validation.BindingResult.createProductDTO", bindingResult); return "redirect:/products/add"; } if (!this.productService.checkAvailable(createProductDTO)) { redirectAttributes .addFlashAttribute("createProductDTO", createProductDTO); redirectAttributes .addFlashAttribute("productExists",true); return "redirect:/products/add"; } this.productService.register(createProductDTO); return "redirect:/home"; } @GetMapping("/products/details/{name}") public String showItemDetails(@PathVariable String name, Model model) { if (!this.userService.isLogged()) { return "redirect:/"; } ItemDTO item = this.productService.getProduct(name); model.addAttribute("item", item); return "details-product"; } @Transactional @GetMapping("/products/delete/{name}") public String deleteItem(@PathVariable String name) { if (!this.userService.isLogged()) { return "redirect:/"; } this.productService.removeProduct(name); return "redirect:/home"; } }
# vrillar-f1 # Project overview Crawl data from https://www.formula1.com The project has two folders _crawling-f1_: Directory containing crawl data tool. In this part I used the tabletojson library. If the project is real I will create a fork but here I have intervened to modify the code of the library to suit the needs. So I included this module in the commit. _nest-f1_: Api server created with nestJS # Running projects Node and mongodb required. ## Run mongodb I use docker to run mongodb. Check out docker-compose.yml at _\vrillar-f1\crawling-f1\docker-compose.yml_ Note that the mongodb address mongodb://127.0.0.1:27017 has been hardcoded. ## Run crawling-f1 Install module and compile typescript ```javascript cd crawling-f1 npm install npx tsc ``` The crawl process consists of creating a Job saved to the database to check the status and step two executing and updating the completed status. There are two tables of data to be crawled in sequential order. In folder crawling-f1 Create Job ```bash node .\dist\src\createDataRacesJob.js ``` Run Job ```bash node .\dist\src\crawRacesInfo.js ``` If you see the message _all Done_, the job is done Do the next job In folder crawling-f1 Create Job ```bash node .\dist\src\createDataRacesResultJob.js ``` Run Job ```bash node .\dist\src\crawRacesResult.js ``` If you see the message _all Done_, the job is done Checking the data in the database will have document _raceresults_. That is the data we need to analyze and retrieve using the API. I have exported it to a json file: _vrillar-f1\nest-f1\nest-f1.rayceresults.json_ ## Run server API ```javascript cd nest-f1 npm install npm start ``` Open http://localhost:3000/api#/ Swagger interface can easily interact with API. # API info ## /Raceresults/{year}/races Overview of race results by year ## /Raceresults/{year}/drives Overview of racing results by year ## /Raceresults/{year}/teams Overview of racing teams by year ## /Raceresults/{year}/races/{raceName} Detailed results information by year by race name. Race name can be obtained from api _/Raceresults/{year}/races_ ## /Raceresults/{year}/drives/{deriveName} Detailed results information by year by derive name. Derive name can be obtained from api _/Raceresults/{year}/drives_ ## /Raceresults/{year}/teams/{teamName} Detailed results information by year by teamName. Team name can be obtained from api _/Raceresults/{year}/teams_ ## /Raceresults/{year}/rank/{teamName} Returns a team's rank by year. # Result video [![](./Demo.png)](./Demo.mp4)
<html> <head> <title>Rikchik Names</title> </head> <body> <h1>Rikchik Names</h1> A rikchik's name can have up to 5 different components. Each one is a phrase collected by the <em>Rikchik</em> glyph and relating to it a different way. All words inside a naming phrase have their forms set to <em>N</em> (name). <dl> <dt><em>Quality</em>: personal name. <img align=right src="images/5/rQuality.png"> <dd>A short (1-3 glyph) name belonging to that rikchik. Usually given by its parent. Common Quality-names include plants and animals (<em>Sky-Instrument-N-0 Fish-Quality-N-1</em>), descriptions (<em>Happy-Quality-N-0 Happy-Quality-N-1</em>), and almost any single word (<em>Spot-Quality-N-0</em>). <br clear=right> <dt><em>Source</em>: parent's name. <img align=right src="images/5/rSource.png"> <dd>The Quality-name of the rikchik's parent. <br clear=right> <dt><em>Includes</em>: home name. <img align=right src="images/5/rIncludes.png"> <dd>The name of the rikchik's home, chosen by the founders of the house. A &quot;single&quot; rikchik will have no home name. Homes tend to have more complicated or strange names, since each home in a city needs to have a unique name to avoid confusion. <br clear=right> <dt><em>Agent</em>: raising-home name. <img align=right src="images/5/rAgent.png"> <dd>The name of the home that the rikchik was raised by. Usually the same as the Includes-name of its parent. <br clear=right> <dt><em>Destination</em>: home-city name. <img align=right src="images/5/rDestination.png"> <dd>The name of the city the rikchik is from. Its home nation (and planet) can be used instead or added if necessary. This name changes when a rikchik moves to another city. Rikchiks with no spatial home (travelers, ship crews, etc.) usually use &quot;<em>All-Destination-N-0</em>&quot; as their Destination-name. <br clear=right> </dl> Example:<p> <img align=right alt="complicated name" src="../cgi-bin/riksmall.cgi?Happy-Quality-N-0.Insect-Agent-N-1.Pulser-Source-N-0.Sun-Quality-N-0.Grass-Destination-N-1.Box-Includes-N-0.Water-Includes-N-1.Sky-Patient-N-0.Eye-Quality-N-1.Rikchik-End-R-5"> <em> Happy-Quality-N-0<br> Insect-Agent-N-1<br> Pulser-Source-N-0<br> Sun-Quality-N-0<br> Grass-Destination-N-1<br> Box-Includes-N-0<br> Water-Includes-N-1<br> Sky-Patient-N-0<br> Eye-Quality-N-1<br> Rikchik-End-R-5<br> </em> Sky Watcher, house of Boxed Water, from Bright Grass city, child of Pulser, raised by Happy Insect house. (You may find it helpful to see this phrase <a href="../cgi-bin/rikparsesmallcolor.cgi?Happy-Quality-N-0.Insect-Agent-N-1.Pulser-Source-N-0.Sun-Quality-N-0.Grass-Destination-N-1.Box-Includes-N-0.Water-Includes-N-1.Sky-Patient-N-0.Eye-Quality-N-1.Rikchik-End-R-5"> parsed</a>.) <p> This rikchik would most likely only use this full name for official documents. In daily life it would probably be called <em>Sky-Patient-N-0 Eye-Quality-N-1 Rikchik-End-R-1</em> (Sky-Watcher), or <em>Box-Includes-N-0 Water-Includes-N-1 Sky-Patient-N-0 Eye-Quality-N-1 Rikchik-End-R-2</em> (Sky-Watcher Boxed-Water). <p> If Sky-Watcher was to leave the country, it would perhaps introduce itself as <em>Two-Quality-N-0 Sun-Destination-N-1 Sun-Quality-N-0 Grass-Destination-N-1 Sky-Patient-N-0 Eye-Quality-N-1 Rikchik-End-R-1</em> (Sky-Watcher, from Two-Suns, from Bright-Grass) or simply as <em>Two-Quality-N-0 Sun-Destination-N-1 Sky-Patient-N-0 Eye-Quality-N-1 Rikchik-End-R-1</em> (Sky-Watcher, from Two-Suns) if it doesn't expect to be confused with someone else from a different city in Two-Suns. The watcher (the rikchik being talked to) is expected to be able to distinguish between city names and country names, though there is no clear way to do so other than knowing all the country names. A city name is usually not also the name of a country. <br clear=right> <hr> <address> Last modified November 17, 1999 by <a href="/~dmm/dmm.html">Denis Moskowitz</a>. <a href="/~dmm/rikchik/intro.html">Rikchik culture and language</a> also by Denis. Word assembly program utilizes <a href="http://www.boutell.com/gd/">gd</a>, a graphics library, and <a href="http://www-genome.wi.mit.edu/ftp/pub/software/WWW/GD.html">GD.pm</a>, a perl interface to gd. gd is &copy; 1994, 1995, Quest Protein Database Center, Cold Spring Harbor Labs. GD.pm is &copy; 1995, Lincoln D. Stein. Both are used with permission. </address> </body> </html>
<template> <nav class="w-full lg:flex lg:w-auto"> <ul @click.prevent="changeCategoryHandler"> <li v-for="(cat, index) in categories" :key="index" class="no-underline block mt-4 lg:inline-block lg:mt-0 lg:mr-2 text-gray-lighter transition-colors duration-300 hover:text-white hover:bg-gray-600" > <a href="/" :data-category="cat" class="block text-center py-2 lg:px-2" :class="{ 'text-white bg-gray-700': cat === pickedCategory }" > {{ cat ? capitalizeFirstLetter(cat) : 'All' }} </a> </li> <li class="relative no-underline block mt-4 lg:inline-block lg:mt-0 lg:mr-2 text-gray-lighter transition-colors duration-300 hover:text-white hover:bg-gray-600" > <select v-model="pickedCountry" class="block appearance-none w-full bg-gray-200 border border-gray-200 text-gray-700 py-3 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500" @change="changeCountryHandler" > <option v-for="(country, index) in countries" :key="index" :value="country" > {{ country }} </option> </select> <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700" > <DownArrowSvg /> </div> </li> </ul> </nav> </template> <script> import { mapActions } from 'vuex' import { capitalizeFirstLetter } from '@/utils/capitalizeFirstLetter' import DownArrowSvg from '@/assets/icons/downArrow.svg?inline' export default { components: { DownArrowSvg, }, data() { return { pickedCategory: '', pickedCountry: 'gb', categories: [ '', 'business', 'entertainment', 'general', 'health', 'science', 'sports', 'technology', ], countries: [ 'ae', 'ar', 'at', 'au', 'be', 'bg', 'br', 'ca', 'ch', 'cn', 'co', 'cu', 'cz', 'de', 'eg', 'fr', 'gb', 'gr', 'hk', 'hu', 'id', 'ie', 'il', 'in', 'it', 'jp', 'kr', 'lt', 'lv', 'ma', 'mx', 'my', 'ng', 'nl', 'no', 'nz', 'ph', 'pl', 'pt', 'ro', 'rs', 'ru', 'sa', 'se', 'sg', 'si', 'sk', 'th', 'tr', 'tw', 'ua', 'us', 've', 'za', ], } }, methods: { ...mapActions(['setArticles']), changeCategoryHandler(e) { const targetCategory = e.target.dataset.category if ( typeof targetCategory === 'undefined' || targetCategory === this.pickedCategory ) return this.pickedCategory = targetCategory this.changeArticles() }, changeCountryHandler() { this.changeArticles() }, changeArticles() { this.setArticles({ country: this.pickedCountry, category: this.pickedCategory, }) this.$emit('close-main-menu') }, capitalizeFirstLetter(string) { return capitalizeFirstLetter(string) }, }, } </script>
package com.tasker.taskservice.controller; import com.tasker.taskservice.model.Task; import com.tasker.taskservice.model.TaskGroup; import com.tasker.taskservice.model.TaskItem; import com.tasker.taskservice.repository.TaskRepository; import com.tasker.taskservice.response.GeneralResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; @RestController @RequestMapping("/task") public class TaskController { private static final Logger LOGGER = LoggerFactory.getLogger(TaskController.class); @Autowired private TaskRepository repository; @CrossOrigin(origins = "http://localhost:3000") @PostMapping public ResponseEntity<GeneralResponse<Task>> add(@RequestBody Task task) { try { LOGGER.info("Task add: {}", task); Task savedTask = repository.save(task); return new ResponseEntity<>(new GeneralResponse<>("SUCCESS", savedTask), HttpStatus.CREATED); } catch (Exception e) { return new ResponseEntity(new GeneralResponse<>("FAILED", "Internal Server Error"), HttpStatus.INTERNAL_SERVER_ERROR); } } @CrossOrigin(origins = "*") @GetMapping public ResponseEntity<List<TaskGroup>> findAll() { try { List<Task> tasks = repository.findAll(); Map<String, String> statusMapping = Map.of( "ToDo", "Todo", "In-progress", "In-progress", "In-review", "In-review", "Done", "Done" ); List<String> statusOrder = List.of("Todo", "In-progress", "In-review", "Done"); Map<String, List<Task>> groupedTasks = tasks.stream() .collect(Collectors.groupingBy(task -> statusMapping.get(task.getStatus()))); List<TaskGroup> taskGroups = statusOrder.stream() .filter(groupedTasks::containsKey) .map(status -> { List<Task> taskList = groupedTasks.get(status); List<TaskItem> taskItems = taskList.stream() .map(task -> new TaskItem( task.getTaskId(), task.getPriority(), task.getTitle(), task.getDescription(), task.getDateTime() )) .collect(Collectors.toList()); return new TaskGroup(status, taskItems); }) .collect(Collectors.toList()); return new ResponseEntity<>(taskGroups, HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(List.of(new TaskGroup("FAILED", List.of(new TaskItem(null, null, "Internal Server Error", null, null)))), HttpStatus.INTERNAL_SERVER_ERROR); } } @CrossOrigin(origins = "*") @GetMapping("/{id}") public ResponseEntity<GeneralResponse<Task>> findById(@PathVariable Long id) { try { LOGGER.info("Tasks Find by ID: {}", id); Optional<Task> task = repository.findById(id); return task.map(value -> new ResponseEntity<>(new GeneralResponse<>("SUCCESS", value), HttpStatus.OK)) .orElseGet(() -> new ResponseEntity(new GeneralResponse<>("FAILED", "Not Found"), HttpStatus.NOT_FOUND)); } catch (Exception e) { return new ResponseEntity(new GeneralResponse<>("FAILED", "Internal Server Error"), HttpStatus.INTERNAL_SERVER_ERROR); } } @CrossOrigin(origins = "*") @PutMapping("/{id}") public ResponseEntity<GeneralResponse<Task>> update(@PathVariable Long id, @RequestBody Task updatedTask) { try { LOGGER.info("Updating Task with ID {}: {}", id, updatedTask); if (repository.existsById(id)) { updatedTask.setId(id); Task savedTask = repository.save(updatedTask); return new ResponseEntity<>(new GeneralResponse<>("SUCCESS", savedTask), HttpStatus.OK); } else { return new ResponseEntity(new GeneralResponse<>("FAILED", "Not Found"), HttpStatus.NOT_FOUND); } } catch (Exception e) { return new ResponseEntity(new GeneralResponse<>("FAILED", "Internal Server Error"), HttpStatus.INTERNAL_SERVER_ERROR); } } @CrossOrigin(origins = "*") @DeleteMapping("/{id}") public ResponseEntity<GeneralResponse<Void>> delete(@PathVariable Long id) { try { LOGGER.info("Deleting Task with ID: {}", id); if (repository.existsById(id)) { repository.deleteById(id); return new ResponseEntity(new GeneralResponse<>("SUCCESS", "Deleted"), HttpStatus.NO_CONTENT); } else { return new ResponseEntity(new GeneralResponse<>("FAILED", "Not Found"), HttpStatus.NOT_FOUND); } } catch (Exception e) { return new ResponseEntity(new GeneralResponse<>("FAILED", "Internal Server Error"), HttpStatus.INTERNAL_SERVER_ERROR); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using AutoMapper; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using ProductShop.Data; using ProductShop.DAtaTransferObjects; using ProductShop.Models; using Remotion.Linq.Clauses; namespace ProductShop { public class StartUp { private static IMapper mapper; public static void Main(string[] args) { var productShopContext = new ProductShopContext(); //productShopContext.Database.EnsureDeleted(); //productShopContext.Database.EnsureCreated(); //string userJson = File.ReadAllText("../../../Datasets/users.json"); //ImportUsers(productShopContext, userJson); //string productJson = File.ReadAllText("../../../Datasets/products.json"); //ImportProducts(productShopContext, productJson); //string categoryJson = File.ReadAllText("../../../Datasets/categories.json"); //ImportCategories(productShopContext, categoryJson); //string categoryProductJson = File.ReadAllText("../../../Datasets/categories-products.json"); var result = GetUsersWithProducts(productShopContext); Console.WriteLine(result); } public static string GetUsersWithProducts(ProductShopContext context) { var users = context.Users .Include(x => x.ProductsSold) .ToList() .Where(x => x.ProductsSold.Any(b => b.BuyerId != null)) .Select(u => new { firstName = u.FirstName, lastName = u.LastName, age = u.Age, soldProducts = new { count = u.ProductsSold.Where(x => x.BuyerId != null).Count(), products = u.ProductsSold.Where(x => x.BuyerId != null) .Select(p => new { name = p.Name, price = p.Price }) } }) .OrderByDescending(x => x.soldProducts.products.Count()) .ToList(); var resultObjects = new { usersCount = context.Users .Where(x => x.ProductsSold.Any(b => b.BuyerId != null)).Count(), users = users }; var jsonSerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; var resultJson = JsonConvert .SerializeObject(resultObjects, Formatting.Indented, jsonSerializerSettings); return resultJson; } public static string GetCategoriesByProductsCount(ProductShopContext context) { var categorisInfo = context.Categories .Select(x => new { category = x.Name, productsCount = x.CategoryProducts.Count, averagePrice = x.CategoryProducts.Average(a => a.Product.Price) .ToString("F2"), totalRevenue = x.CategoryProducts.Sum(s => s.Product.Price) .ToString("F2") }) .OrderByDescending(x => x.productsCount) .ToList(); var result = JsonConvert.SerializeObject(categorisInfo, Formatting.Indented); return result; } public static string GetSoldProducts(ProductShopContext context) { var users = context.Users .Where(x => x.ProductsSold.Any(y => y.BuyerId != null)) .Select(x => new { firstName = x.FirstName, lastName = x.LastName, soldProducts = x.ProductsSold.Where(p => p.BuyerId != null) .Select(p => new { name = p.Name, price = p.Price, buyerFirstName = p.Buyer.FirstName, buyerLastName = p.Buyer.LastName }) .ToList() }) .OrderBy( x => x.lastName) .ThenBy(x => x.firstName) .ToList(); var result = JsonConvert.SerializeObject(users, Formatting.Indented); return result; } public static string GetProductsInRange(ProductShopContext context) { var products = context.Products .Where(x => x.Price >= 500 && x.Price <= 1000) .Select(x => new { name = x.Name, price = x.Price, seller = x.Seller.FirstName + " " + x.Seller.LastName }) .OrderBy(x => x.price) .ToArray(); var result = JsonConvert.SerializeObject(products,Formatting.Indented); return result; } public static string ImportCategoryProducts(ProductShopContext context, string inputJson) { InitializeAutomapper(); var dtoCategoriesProducts = JsonConvert.DeserializeObject<IEnumerable<CategoryProductInputModel>>(inputJson); var categorProduct = mapper.Map<IEnumerable<CategoryProduct>>(dtoCategoriesProducts); context.CategoryProducts.AddRange(categorProduct); context.SaveChanges(); return $"Successfully imported {categorProduct.Count()}"; } public static string ImportCategories(ProductShopContext context, string inputJson) { InitializeAutomapper(); var dtoCategory = JsonConvert.DeserializeObject<IEnumerable<CategoryInputModel>>(inputJson).Where(c => c.Name != null) .ToList(); var category = mapper.Map<IEnumerable<Category>>(dtoCategory); context.Categories.AddRange(category); context.SaveChanges(); return $"Successfully imported {category.Count()}"; } public static string ImportProducts(ProductShopContext context, string inputJson) { InitializeAutomapper(); var dtoProducts = JsonConvert.DeserializeObject<IEnumerable<ProductInputModel>>(inputJson); var products = mapper.Map<IEnumerable<Product>>(dtoProducts); context.Products.AddRange(products); context.SaveChanges(); return $"Successfully imported {products.Count()}"; } public static string ImportUsers(ProductShopContext context, string inputJson) { InitializeAutomapper(); var dtoUsers = JsonConvert.DeserializeObject<IEnumerable<UserInputModel>>(inputJson); var users = mapper.Map<IEnumerable<User>>(dtoUsers); context.Users.AddRange(users); context.SaveChanges(); return $"Successfully imported {users.Count()}"; } private static void InitializeAutomapper() { var config = new MapperConfiguration(cfg => { cfg.AddProfile<ProductShopProfile>(); }); mapper = config.CreateMapper(); } } }
import React from 'react'; import { createContext, useContext } from 'react'; import rootStore from '../stores/rootStore'; const StoreContext = createContext(); export const StoreProvider = ({ children }) => { const RootStore = new rootStore(); return ( <StoreContext.Provider value={RootStore}> {children} </StoreContext.Provider> ); }; export const useStore = () => { const store = useContext(StoreContext); if (!store) { throw new Error("useStore must be used within a StoreProvider"); } return store; };
(define (make-account balance password) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch m given-password) (cond ((not (eq? password given-password)) (error "Incorrect password!")) ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request: MAKE-ACCOUNT" m)))) dispatch)
package com.sespmt.practicalproject.dto; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import org.hibernate.validator.constraints.br.CPF; import java.io.Serializable; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Objects; import java.util.Set; public class PersonDto implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty(access = JsonProperty.Access.READ_ONLY) private Long id; @Size(min = 5, max = 60, message = "Deve conter entre 5 e 60 caracteres") @NotBlank(message = "Campo requerido") private String name; private String rg; @Size(min = 11, max = 11, message = "Deve conter 11 caracteres válidos") @NotBlank(message = "Campo requerido") @CPF(message = "Número de CPF inválido") private String cpf; @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) @JsonFormat(pattern = "yyyy-MM-dd") @NotNull(message = "Campo requerido") private LocalDate birthDate; private String phoneNumber; @Size(min = 5, max = 60, message = "Deve conter entre 5 e 60 caracteres") @NotBlank(message = "Campo requerido") private String motherName; private String fatherName; @JsonSerialize(using = LocalDateTimeSerializer.class) @JsonDeserialize(using = LocalDateTimeDeserializer.class) @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") private LocalDateTime createdAt; @JsonSerialize(using = LocalDateTimeSerializer.class) @JsonDeserialize(using = LocalDateTimeDeserializer.class) @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") private LocalDateTime updatedAt; @Valid private Set<AddressDto> addresses = new HashSet<>(); public PersonDto() { } public PersonDto(Long id, String name, String rg, String cpf, LocalDate birthDate, String phoneNumber, String motherName, String fatherName, LocalDateTime createdAt, LocalDateTime updatedAt) { this.id = id; this.name = name; this.rg = rg; this.cpf = cpf; this.birthDate = birthDate; this.phoneNumber = phoneNumber; this.motherName = motherName; this.fatherName = fatherName; this.createdAt = createdAt; this.updatedAt = updatedAt; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRg() { return rg; } public void setRg(String rg) { this.rg = rg; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public LocalDate getBirthDate() { return birthDate; } public void setBirthDate(LocalDate birthDate) { this.birthDate = birthDate; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getMotherName() { return motherName; } public void setMotherName(String motherName) { this.motherName = motherName; } public String getFatherName() { return fatherName; } public void setFatherName(String fatherName) { this.fatherName = fatherName; } public LocalDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } public LocalDateTime getUpdatedAt() { return updatedAt; } public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; } public Set<AddressDto> getAddresses() { return addresses; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PersonDto person = (PersonDto) o; if (!Objects.equals(id, person.id)) return false; if (!Objects.equals(name, person.name)) return false; if (!Objects.equals(rg, person.rg)) return false; if (!Objects.equals(cpf, person.cpf)) return false; if (!Objects.equals(birthDate, person.birthDate)) return false; if (!Objects.equals(phoneNumber, person.phoneNumber)) return false; if (!Objects.equals(motherName, person.motherName)) return false; if (!Objects.equals(fatherName, person.fatherName)) return false; if (!Objects.equals(createdAt, person.createdAt)) return false; return Objects.equals(updatedAt, person.updatedAt); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (rg != null ? rg.hashCode() : 0); result = 31 * result + (cpf != null ? cpf.hashCode() : 0); result = 31 * result + (birthDate != null ? birthDate.hashCode() : 0); result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); result = 31 * result + (motherName != null ? motherName.hashCode() : 0); result = 31 * result + (fatherName != null ? fatherName.hashCode() : 0); result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0); result = 31 * result + (updatedAt != null ? updatedAt.hashCode() : 0); return result; } @Override public String toString() { return "PersonDto{" + "id=" + id + ", name='" + name + '\'' + ", rg='" + rg + '\'' + ", cpf='" + cpf + '\'' + ", birthDate=" + birthDate + ", phoneNumber='" + phoneNumber + '\'' + ", motherName='" + motherName + '\'' + ", fatherName='" + fatherName + '\'' + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + ", addresses=" + addresses + '}'; } }
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:linktopus_app/SplashScreen/getstarted.dart'; import 'package:linktopus_app/job_listing/jobsPage.dart'; import 'package:linktopus_app/login/mail_signup.dart'; import './selectRoles.dart'; import './login/landing_page.dart'; import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart'; import 'package:firebase_auth/firebase_auth.dart'; //import 'package:sign_in_with_apple/sign_in_with_apple.dart'; import 'package:linktopus_app/SignUp/codeverification.dart'; import 'package:linktopus_app/SignUp/googlesignin.dart'; import 'package:linktopus_app/SignUp/otplogin.dart'; import 'package:linktopus_app/profile.dart'; // import 'package:firebase_auth/firebase_auth.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final ThemeData themeData = ThemeData( primaryColor: Color(0xffEF5DA8), primarySwatch: MaterialColor(0xffEF5DA8, { 50: Color(0xFFFCE4F6), 100: Color(0xFFFFD1E2), 200: Color(0xFFFFACC6), 300: Color(0xFFFF85AA), 400: Color(0xFFFF5D8D), 500: Color(0xffEF5DA8), // primaryColor 600: Color(0xFFE54691), 700: Color(0xFFD73C80), 800: Color(0xFFC5326E), 900: Color(0xFFA71D54), }), ); var uid = FirebaseAuth.instance.currentUser?.uid; CollectionReference users = FirebaseFirestore.instance.collection('users'); if (uid == null) { return MaterialApp( debugShowCheckedModeBanner: false, color: Colors.white, title: 'Flutter Demo', theme: themeData, // home: EmailSignin(), home: const GetStarted(), ); } else { return FutureBuilder( future: users.doc(uid).get(), builder: (context, snapshot) { if (snapshot.data?.data() == null) { return MaterialApp( color: Colors.white, title: 'Flutter Demo', theme: themeData, home: Profile()); } else { return MaterialApp( debugShowCheckedModeBanner: false, color: Colors.white, title: 'Flutter Demo', theme: themeData, home: Jobs_page()); } }); } } } // // // var uid = FirebaseAuth.instance.currentUser?.uid; // CollectionReference users = FirebaseFirestore.instance.collection('users'); // // return FutureBuilder( // // future: users.doc(uid).get(), // // builder: (context, snapshot) { // // if (uid == null) { // // return MaterialApp( // // color: Colors.white, // // title: 'Flutter Demo', // // theme: themeData, // // home: EmailSignup()); // // } // // if (snapshot == null || !snapshot.data!.exists) { // // return MaterialApp( // // color: Colors.white, // // title: 'Flutter Demo', // // theme: themeData, // // home: Profile()); // // } // // // // return MaterialApp( // // color: Colors.white, // // title: 'Flutter Demo', // // theme: themeData, // // home: Jobs_page()); // // }); // // var uid = FirebaseAuth.instance.currentUser?.uid; // FirebaseFirestore db = FirebaseFirestore.instance; // // DocumentSnapshot doc = db.collection('users').doc(uid).get(); // // print(uid); // if (uid != null) { // return MaterialApp( // color: Colors.white, // title: 'Flutter Demo', // theme: themeData, // home: Jobs_page()); // } else if (uid != null) { // return MaterialApp( // color: Colors.white, // title: 'Flutter Demo', // theme: themeData, // home: Profile()); // } else { // return MaterialApp( // color: Colors.white, // title: 'Flutter Demo', // theme: themeData, // home: GetStarted());
import { useCallback, useEffect, useState } from "react"; import { toast } from "react-hot-toast"; import { Button, Modal, List, Form, Input, Card, Tabs } from "antd"; import Search from "antd/lib/transfer/search"; import api from "../../services/api"; import { PlusSquareFilled } from "@ant-design/icons"; const ModalGroups = () => { // MODAL const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const handleCancel = () => { setIsModalVisible(false); }; // TABS const { TabPane } = Tabs; function callback(key) { console.log(key); } // GROUPS - POST const token = JSON.parse(localStorage.getItem("@RunLikeaDev:token")) || ""; const createGroup = ({ name, description, category }) => { const newGroup = { name, description, category, }; api .post("/groups/", newGroup, { headers: { Authorization: `Bearer ${token}` }, }) .then((response) => { toast.success("Criado com sucesso"); getGroups(); }) .catch((err) => toast.error("Erro ao criar")); }; //GROUPS - GET const [groups, SetGroups] = useState([]); const [filterGroups, setFilterGroups] = useState(""); const getGroups = useCallback(() => { api .get("/groups/", { headers: { Authorization: `Bearer ${token}`, }, }) .then((response) => SetGroups(response.data.results)) .catch((err) => console.log(err)); }, [SetGroups, token]); const groupsFiltered = groups.filter((item) => item.name.toLowerCase().includes(filterGroups.toLowerCase()) ); useEffect(() => { getGroups(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); //GROUPS INSCRIBEDS - GET const [groupsInscribeds, SetgroupsInscribeds] = useState([]); const [filterGroupsInscribeds, setFilterGroupsInscribeds] = useState(""); const getGroupsInscrebeds = useCallback(() => { api .get("/groups/subscriptions/", { headers: { Authorization: `Bearer ${token}`, }, }) .then((response) => { SetgroupsInscribeds(response.data); }) .catch((err) => console.log(err)); }, [SetgroupsInscribeds, token]); const groupsInscribedsFiltered = groupsInscribeds.filter((item) => item.name.toLowerCase().includes(filterGroupsInscribeds.toLowerCase()) ); useEffect(() => { getGroupsInscrebeds(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [groupsInscribeds]); //DELETE const removeGroup = (id) => { api .delete(`/groups/${id}/`, { headers: { Authorization: `Bearer ${token}`, }, }) .then((response) => { getGroups(); toast.error("Deletado com sucesso"); }); }; //INSCRIÇÃO const subsUser = (id) => { api .post(`/groups/${id}/subscribe/`, "", { headers: { Authorization: `Bearer ${token}`, }, }) .then((response) => { toast.success("Inscrito com sucesso"); }) .catch((err) => { toast.error("Já é inscrito"); }); }; return ( <> <PlusSquareFilled onClick={showModal} style={{ cursor: "pointer", marginLeft: "20px" }} /> <Modal title="Grupos" visible={isModalVisible} onCancel={handleCancel} footer={null} > <Tabs defaultActiveKey="1" onChange={callback}> <TabPane tab="Criar Grupo" key="1"> <Form className="form" onFinish={createGroup}> <Form.Item name="name" label="Título"> <Input placeholder="Nome do Grupo" autoComplete="off" /> </Form.Item> <Form.Item name="description" label="Descrição do Grupo"> <Input placeholder="Descrição do Grupo" autoComplete="off" /> </Form.Item> <Form.Item name="category" label="Categoria"> <Input placeholder="Categoria" autoComplete="off" /> </Form.Item> <Button htmlType="submit">Criar Grupo</Button> </Form> </TabPane> <TabPane tab="Inscrever-se" key="2"> <Search value={filterGroups} onChange={(e) => setFilterGroups(e.target.value)} placeholder="Digite o nome do grupo" /> <List size="small" bordered style={{ color: "var(--black)" }} dataSource={groupsFiltered} pagination={{ position: "bottom", size: "small", pageSize: "3", }} renderItem={(item) => ( <List.Item key={item.id}> <Card size="small" title={item.name} style={{ width: 300 }}> <p>Descrição: {item.description}</p> <p>Categoria: {item.category}</p> <Button onClick={() => subsUser(item.id)}>Entrar</Button> </Card> </List.Item> )} /> </TabPane> <TabPane tab="Sair do grupo" key="3"> <Search value={filterGroupsInscribeds} onChange={(e) => setFilterGroupsInscribeds(e.target.value)} placeholder="Digite o nome do grupo" /> <List style={{ color: "white", paddingBottom: "50px" }} size="small" dataSource={groupsInscribedsFiltered} pagination={{ position: "bottom", size: "small", pageSize: "3", }} renderItem={(item) => ( <List.Item key={item.id} style={{ display: "flex" }}> <Card size="small" title={item.name} style={{ width: 300 }}> <Button onClick={() => removeGroup(item.id)}>Sair</Button> </Card> </List.Item> )} /> </TabPane> </Tabs> </Modal> </> ); }; export default ModalGroups;
<template> <VForm ref="form" :model="dataConfigs" :rules="rules" @keyup.enter="handleSubmit" > <FormItem prop="url" label="URL" class="col-12" > <VInput v-model="dataConfigs.url" type="text" size="large" placeholder="postgresql://username:password@localhost:5432/db_name" @update:model-value="assignFields" /> </FormItem> <Divider /> <RadioGroup v-model="dataConfigs.protocol" class="d-flex" @update:model-value="assignUrl" > <Radio v-for="(option, index) in dbTypeOptions" :key="option.value" :label="option.value" border size="large" :style="index !== 0 ? 'margin-left: 15px !important' : ''" class="my-1 me-0 w-100" > {{ option.label }} </Radio> </RadioGroup> <div class="row"> <FormItem prop="host" label="Host" class="col-12 col-md-6" > <VInput v-model="dataConfigs.host" type="text" placeholder="example.com" @update:model-value="assignUrl" /> </FormItem> <FormItem prop="port" label="Port" class="col-12 col-md-6" > <VInput v-model="dataConfigs.port" type="text" placeholder="5432" @update:model-value="assignUrl" /> </FormItem> <FormItem prop="username" label="Username" class="col-12 col-md-6" > <VInput v-model="dataConfigs.username" type="text" placeholder="admin" @update:model-value="assignUrl" /> </FormItem> <FormItem prop="password" label="Password" class="col-12 col-md-6" > <VInput v-model="dataConfigs.password" type="password" placeholder="**********" @update:model-value="assignUrl" /> </FormItem> <FormItem prop="database" label="Database" class="col-12" > <VInput v-model="dataConfigs.database" placeholder="db_name" @update:model-value="assignUrl" /> </FormItem> <FormItem v-if="dataConfigs.protocol === 'postgres'" prop="schema_search_path" label="Schemas" class="col-12" > <VInput v-model="dataConfigs.schema_search_path" placeholder="public, custom_schema" /> </FormItem> </div> <VButton type="primary" class="mt-1" size="large" long @click="handleSubmit" > {{ submitText }} </VButton> <Spin v-if="isLoading" fix /> </VForm> </template> <script> import api from 'application/api' import { databaseUrlToObject } from 'application/scripts/urls' export default { name: 'DatabaseForm', props: { configs: { type: Object, required: false, default: () => ({ protocol: 'postgres' }) }, submitText: { type: String, required: false, default: 'Submit' } }, emits: ['success', 'error'], data () { return { isLoading: false, dataConfigs: { ...this.configs } } }, computed: { rules () { return { url: [{ required: true }], host: [{ required: true }], port: [{ required: true }] } }, dbTypeOptions () { return [ { label: 'PostgreSQL', value: 'postgres' }, { label: 'MySQL', value: 'mysql2' }, { label: 'SQL Server', value: 'sqlserver' } ] } }, watch: { configs () { this.dataConfigs = { ...this.configs } } }, methods: { assignFields () { Object.assign(this.dataConfigs, databaseUrlToObject(this.dataConfigs.url)) }, assignUrl () { const { username, protocol, host, password, database, port } = this.dataConfigs if (host && port && database) { this.dataConfigs.url = `${protocol}://` if (username && !password) { this.dataConfigs.url += `${username}@` } else if (username && password) { this.dataConfigs.url += `${username}:${password}@` } this.dataConfigs.url += `${host}:${port}/${database}` } }, submit () { this.isLoading = true api.post('verify_db_connection', { url: this.dataConfigs.url }).then(() => { const dbConfig = { name: 'default', url: this.dataConfigs.url.replace('mysql://', 'mysql2://').replace('postgresql://', 'postgres://') } if (this.dataConfigs.schema_search_path?.match(/\w/)) { dbConfig.schema_search_path = this.dataConfigs.schema_search_path } api.post('encrypted_configs', { data: { key: 'database.credentials', value: [dbConfig] } }).then((result) => { this.$emit('success', result.data.data) }).catch((error) => { if (error.response?.data?.errors) { this.$refs.form.setErrors(error.response.data.errors) } else if (error.message) { this.$refs.form.setErrors([error.message]) } this.$emit('error', error) }).finally(() => { this.isLoading = false }) }).catch((error) => { if (error.response?.data?.errors) { this.$refs.form.setErrors(error.response.data.errors) } else if (error.message) { this.$refs.form.setErrors([error.message]) } this.$emit('error', error) this.isLoading = false }) }, handleSubmit () { this.$refs.form.validate((valid) => { if (valid) { this.submit() } }) } } } </script>
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Response } from '@angular/http'; import { Observable } from 'rxjs'; import { NgbActiveModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager, JhiAlertService } from 'ng-jhipster'; import { Profession } from './profession.model'; import { ProfessionPopupService } from './profession-popup.service'; import { ProfessionService } from './profession.service'; @Component({ selector: 'jhi-profession-dialog', templateUrl: './profession-dialog.component.html', styles: [ ` select{ height: 50px; font-size:15px; border:none; border-bottom:1.5px solid; } ` ] }) export class ProfessionDialogComponent implements OnInit { profession: Profession; authorities: any[]; isSaving: boolean; constructor( public activeModal: NgbActiveModal, private alertService: JhiAlertService, private professionService: ProfessionService, private eventManager: JhiEventManager ) {} ngOnInit() { this.isSaving = false; this.authorities = ['ROLE_USER', 'ROLE_ADMIN']; } clear() { this.activeModal.dismiss('cancel'); } save() { this.isSaving = true; if (this.profession.id !== undefined) { this.subscribeToSaveResponse( this.professionService.update(this.profession), false ); } else { this.subscribeToSaveResponse( this.professionService.create(this.profession), true ); } } private subscribeToSaveResponse( result: Observable<Profession>, isCreated: boolean ) { result.subscribe( (res: Profession) => this.onSaveSuccess(res, isCreated), (res: Response) => this.onSaveError(res) ); } private onSaveSuccess(result: Profession, isCreated: boolean) { this.alertService.success( isCreated ? 'carmesfnmserviceApp.profession.created' : 'carmesfnmserviceApp.profession.updated', { param: result.id }, null ); this.eventManager.broadcast({ name: 'professionListModification', content: 'OK' }); this.isSaving = false; this.activeModal.dismiss(result); } private onSaveError(error) { try { error.json(); } catch (exception) { error.message = error.text(); } this.isSaving = false; this.onError(error); } private onError(error) { this.alertService.error(error.message, null, null); } } @Component({ selector: 'jhi-profession-popup', template: '' }) export class ProfessionPopupComponent implements OnInit, OnDestroy { modalRef: NgbModalRef; routeSub: any; constructor( private route: ActivatedRoute, private professionPopupService: ProfessionPopupService ) {} ngOnInit() { this.routeSub = this.route.params.subscribe(params => { if (params['id']) { this.modalRef = this.professionPopupService.open( ProfessionDialogComponent as Component, params['id'] ); } else { this.modalRef = this.professionPopupService.open( ProfessionDialogComponent as Component ); } }); } ngOnDestroy() { this.routeSub.unsubscribe(); } }
// // ViewController.swift // TicTacToe // // Created by Brian W Thyfault on 11/18/16. // Copyright © 2016 Brian W Thyfault. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var gameBoard: UIView! @IBOutlet weak var r1c1: GridLabel! @IBOutlet weak var r1c2: GridLabel! @IBOutlet weak var r1c3: GridLabel! @IBOutlet weak var r2c1: GridLabel! @IBOutlet weak var r2c2: GridLabel! @IBOutlet weak var r2c3: GridLabel! @IBOutlet weak var r3c1: GridLabel! @IBOutlet weak var r3c2: GridLabel! @IBOutlet weak var r3c3: GridLabel! @IBOutlet weak var nameLabel: UILabel! var gameArray:[GridLabel] = [] var myGrid = GridLabel() override func viewDidLoad() { super.viewDidLoad() gameArray = [r1c1, r1c2, r1c3, r2c1, r2c2, r2c3, r3c1, r3c2, r3c3] } @IBAction func boardTapped(_ sender: AnyObject) { for label in gameArray { if(label.frame.contains(sender.location(in: gameBoard)) && label.text == "") { if(myGrid.xTurn == true) { label.text = "X" myGrid.xTurn = false } else { label.text = "O" myGrid.xTurn = true } myGrid.count += 1 } } checkWinner() } func clearBoard() { r1c1.text = "" r1c2.text = "" r1c3.text = "" r2c1.text = "" r2c2.text = "" r2c3.text = "" r3c1.text = "" r3c2.text = "" r3c3.text = "" myGrid.count = 0 } func winnerAlert(_ winner:String) { var alert = UIAlertController() if(winner == "count9") { alert = UIAlertController(title: "Cat's Game", message: nil, preferredStyle: UIAlertControllerStyle.alert) } else { alert = UIAlertController(title: "\(winner) Wins!", message: nil, preferredStyle: UIAlertControllerStyle.alert) } alert.addAction(UIAlertAction(title: "Reset Board", style: .default, handler: { (sender) in self.clearBoard() })) present(alert, animated: true, completion: nil) } func checkWinner() { if((r1c1.text == r1c2.text && r1c2.text == r1c3.text) && r1c1.text != "") { winnerAlert(r1c1.text!) } else if((r2c1.text == r2c2.text && r2c2.text == r2c3.text) && r2c1.text != "") { winnerAlert(r2c1.text!) } else if((r3c1.text == r3c2.text && r3c2.text == r3c3.text) && r3c1.text != "") { winnerAlert(r3c1.text!) } else if((r1c1.text == r2c1.text && r2c1.text == r3c1.text) && r1c1.text != "") { winnerAlert(r1c1.text!) } else if((r1c2.text == r2c2.text && r2c2.text == r3c2.text) && r1c2.text != "") { winnerAlert(r1c2.text!) } else if((r1c3.text == r2c3.text && r2c3.text == r3c3.text) && r3c3.text != "") { winnerAlert(r1c3.text!) } else if((r1c1.text == r2c2.text && r2c2.text == r3c3.text) && r1c1.text != "") { winnerAlert(r1c1.text!) } else if((r1c3.text == r2c2.text && r2c2.text == r3c1.text) && r1c3.text != "") { winnerAlert(r1c3.text!) } else if (myGrid.count >= 9) { winnerAlert("count9") } } @IBAction func resetButton(_ sender: AnyObject) { clearBoard() } }
--- Title: Как перехватить сообщения скроллирования в TScrollBox? Date: 01.01.2007 --- Как перехватить сообщения скроллирования в TScrollBox? ::: {.date} 01.01.2007 ::: Следующий пример перхватывает сообщения скроллирования в компоненте TScrollBox, тем самым синхронизируя два скролбара. Если один из скролбаров изменяет своё положение, то значение второго скролбара изменяется на такую же величину. Сообщения скролирования перехватываются путём сабклассинга оконной процедуры (WinProc) у скролбара. Пример: type {$IFDEF WIN32} WParameter = LongInt; {$ELSE} WParameter = Word; {$ENDIF} LParameter = LongInt; {Объявляем переменную для хранения подменённой оконной процедуры} var OldWindowProc : Pointer; function NewWindowProc(WindowHandle : hWnd; TheMessage : WParameter; ParamW : WParameter; ParamL : LParameter) : LongInt {$IFDEF WIN32} stdcall; {$ELSE} ; export; {$ENDIF} var TheRangeMin : integer; TheRangeMax : integer; TheRange : integer; begin if TheMessage = WM_VSCROLL then begin {Получаем минимальное и максимальное значения scroll box} GetScrollRange(WindowHandle, SB_HORZ, TheRangeMin, TheRangeMax); {Получаем вертикальную позицию scroll box} TheRange := GetScrollPos(WindowHandle, SB_VERT); {Проверим, чтобы не выйти за диапазон} if TheRange < TheRangeMin then TheRange := TheRangeMin else if TheRange > TheRangeMax then TheRange := TheRangeMax; {Устанавливаем горизонтальный scroll bar} SetScrollPos(WindowHandle, SB_HORZ, TheRange, true); end; if TheMessage = WM_HSCROLL then begin {Получаем мин. и макс. диапазон горизонтального scroll box} GetScrollRange(WindowHandle, SB_VERT, TheRangeMin, TheRangeMax); {Получаем позицию горизонтального scroll box} TheRange := GetScrollPos(WindowHandle, SB_HORZ); {Проверим, чтобы не выйти за диапазон} if TheRange < TheRangeMin then TheRange := TheRangeMin else if TheRange > TheRangeMax then TheRange := TheRangeMax; {Устанавливаем вертикальный scroll bar} SetScrollPos(WindowHandle, SB_VERT, TheRange, true); end; { Вызываем старую оконную процедуру } { чтобы обработались сообщения. } NewWindowProc := CallWindowProc(OldWindowProc, WindowHandle, TheMessage, ParamW, ParamL); end; procedure TForm1.FormCreate(Sender: TObject); begin { Устанавливаем новую оконную процедуру для контрола } { и запоминаем старую оконную процедуру. } OldWindowProc := Pointer(SetWindowLong(ScrollBox1.Handle, GWL_WNDPROC, LongInt(@NewWindowProc))); end; procedure TForm1.FormDestroy(Sender: TObject); begin { Возвращаем обратно старую оконную процедуру. } SetWindowLong(ScrollBox1.Handle, GWL_WNDPROC, LongInt(OldWindowProc)); end; Взято из <https://forum.sources.ru>
<!DOCTYPE html> <html lang="pt-br"> <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>seletores personalizados</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1 id="principal">criando sites com html e css</h1> <h1>aprendendo html</h1> <h2 class="basico">html basico</h2> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quod sunt odio tenetur illum labore in excepturi repudiandae hic ipsum repellendus saepe nemo harum ea atque, alias, neque impedit esse at.</p> <h2 class="intermediario">html intermediario</h2> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quod sunt odio tenetur illum labore in excepturi repudiandae hic ipsum repellendus saepe nemo harum ea atque, alias, neque impedit esse at.</p> <h2 class="avançado">html avançado</h2> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quod sunt odio tenetur illum labore in excepturi repudiandae hic ipsum repellendus saepe nemo harum ea atque, alias, neque impedit esse at.</p> <h1>aprendendo css</h1> <h2 class="basico">css basico</h2> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quod sunt odio tenetur illum labore in excepturi repudiandae hic ipsum repellendus saepe nemo harum ea atque, alias, neque impedit esse at.</p> <h2 class="intermediario">css internediario</h2> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quod sunt odio tenetur illum labore in excepturi repudiandae hic ipsum repellendus saepe nemo harum ea atque, alias, neque impedit esse at.</p> <h2 class="avançado">css avançado</h2> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quod sunt odio tenetur illum labore in excepturi repudiandae hic ipsum repellendus saepe nemo harum ea atque, alias, neque impedit esse at.</p> </body> </html>
--- title: "Learn French: Compound Prepositions" description: In this article, we'll explore the basics of compound prepositions in the French language and how to use them correctly. date: 2023-04-11 13:28:56 +0300 last_modified_at: 2023-04-11 13:28:56 +0300 slug: learn-french-compound-prepositions original: "Learn French: Compound Prepositions" --- As with any language, prepositions are an important part of French grammar. While simple prepositions are relatively straightforward, compound prepositions can be a little more challenging to master. In this article, we'll explore the basics of compound prepositions in the French language and how to use them correctly. ### What are compound prepositions? Unlike simple prepositions, which consist of a single word (such as "à", "sur", or "dans"), compound prepositions are made up of two or more words. These words can be prepositions on their own or they can be different parts of speech, such as adverbs or nouns. The most common examples of compound prepositions in French include: - En face de - À côté de - Au-dessus de - Au-dessous de - Au milieu de - Près de - Loin de ### How to use compound prepositions in French? Compound prepositions are used in the same way as simple prepositions, to indicate the relationship between two nouns or pronouns in a sentence. For example, if you want to say "the book is on the table" in French, you would use the compound preposition "sur" (on) and say "le livre est sur la table". If you wanted to say "the cat is under the chair", you would use the compound preposition "sous" (under) and say "le chat est sous la chaise". It's important to note that the ending of the compound preposition will change depending on the gender and number of the noun being referred to. For example, if you wanted to say "the glasses are on the counter", you would use the compound preposition "sur" (on) and say "les verres sont sur le comptoir". However, if you were talking about a feminine object, such as a vase, you would use the feminine form of the preposition and say "le vase est sur la table". ### Conclusion Compound prepositions are an important part of the French language, and mastering them can take some time and practice. However, with a little effort, you'll soon be able to use them correctly to indicate the relationships between different parts of your sentences.
<?php define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'sakila'); $link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); // Define variables and initialize with empty values $username = $password = $confirm_password = ""; $username_err = $password_err = $confirm_password_err = ""; // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Validate username if(empty(trim($_POST["username"]))){ $username_err = "Please enter a username."; } else{ // Prepare a select statement $sql = "SELECT username,password FROM telegraph WHERE username = ?"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "s", $param_username); // Set parameters $param_username = trim($_POST["username"]); // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ /* store result */ mysqli_stmt_store_result($stmt); if(mysqli_stmt_num_rows($stmt) == 1){ $username_err = "This username is already taken."; } else{ $username = trim($_POST["username"]); } } else{ echo "Oops! Something went wrong. Please try again later."; } // Close statement mysqli_stmt_close($stmt); } } // Validate password if(empty(trim($_POST["password"]))){ $password_err = "Please enter a password."; } elseif(strlen(trim($_POST["password"])) < 6){ $password_err = "Password must have atleast 6 characters."; } else{ $password = trim($_POST["password"]); } // Validate confirm password if(empty(trim($_POST["confirm_password"]))){ $confirm_password_err = "Please confirm password."; } else{ $confirm_password = trim($_POST["confirm_password"]); if(empty($password_err) && ($password != $confirm_password)){ $confirm_password_err = "Password did not match."; } } // Check input errors before inserting in database if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){ // Prepare an insert statement $sql = "insert into telegraph (username,password) values(?,?)"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password); // Set parameters $param_username = $username; $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ // Redirect to login page header("location: messagelogin.php"); } else{ echo "Something went wrong. Please try again later.".mysqli_error($link); } // Close statement mysqli_stmt_close($stmt); } } // Close connection mysqli_close($link); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> <link rel="icon" href="https://www.flaticon.com/svg/static/icons/svg/1411/1411824.svg"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"> <link rel="stylesheet" href="messagestyles.css"> <style type="text/css"> body{ font: 14px sans-serif; } .wrapper{ width: 350px; padding: 20px; } </style> </head> <body style="background-color:#90ccf4"> <div class="wraps"> <div class="multi_color_border"></div> <div class="top_nav"> <div class="left"> <div class="logo"><p><span>Simple Telegraph System</span></p></div> </div> <div class="right"> <ul> <li><a href="#" style="color: #90ccf4">Home</a> </li> <li><a href="messagelogin.php" style="color: #edb5bf">Login</a> </li> <li><a href="messageregister.php" style="color: #90ccf4">Register</a> </li> <li><a href="messageregister.php" style="color: #90ccf4">NOT REGISTERED</a> </li> </ul> </div> </div> <div class="bottom_nav"> </div> </div> <div class="wrapper"> <h2>Register</h2> <p>Please fill this form to create an account.</p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>"> <label>Username</label> <input type="text" name="username" class="form-control" value="<?php echo $username; ?>"> <span class="help-block"><?php echo $username_err; ?></span> </div> <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>"> <label>Password</label> <input type="password" name="password" class="form-control" value="<?php echo $password; ?>"> <span class="help-block"><?php echo $password_err; ?></span> </div> <div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>"> <label>Confirm Password</label> <input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>"> <span class="help-block"><?php echo $confirm_password_err; ?></span> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Submit"> </div> <p>Already have an account? <a href="messagelogin.php">Login here</a>.</p> </form> </div> </body> </html>
<template> <!--------------------- LEVEL 3 -----------------------------------> <div v-if="selectedLevel === 3" class="row" style="margin-left:3vw;margin-top:3vh;width:100%;" > <q-card class="my-card q-mb-lg q-pa-lg"> <q-card-section> <div class="text-h6">Smart contract and Klatyn IDE</div> <div class="text-subtitle2">Compile a smart contract using the Klatyn IDE.</div> </q-card-section> <q-markup-table bordered wrap-cells> <tbody> <!------------------------ Step 1 -------------------------> <tr> <td> <div class="text-h6">1</div> </td> <td class="instruction"> <p> <strong>Locate your exported keystore file</strong>. This was automatically downloaded when you created your account. </p> </td> <td/> </tr> <!------------------------ Step 2 -------------------------> <tr> <td> <div class="text-h6">2</div> </td> <td class="instruction"> <p> <strong>Go to the <a href="https://ide.klaytn.com/">Klatyn IDE</a></strong>. You will see the default Solidity file called "Untitled.sol" containing a smart contract called "Count". Klatyn uses solidity for smart contract development. </p> </td> <td/> </tr> <!------------------------ Step 3 -------------------------> <tr> <td> <div class="text-h6">3</div> </td> <td class="instruction"> <p> In the right panel in the IDE you can find the <strong>"Run"</strong> section. Here, ensure "Environment" is set to <strong>"BAOBAB" </strong> using the dropdown menu. </p> </td> <td/> </tr> <!------------------------ Step 4 -------------------------> <tr> <td> <div class="text-h6">4</div> </td> <td class="instruction"> <p> Click the (+) next to <strong>"Account"</strong>, go to the "Keystore" tab, and <strong>Upload your downloaded keystore file</strong> </p> </td> <td/> </tr> <!------------------------ Step 5 -------------------------> <tr> <td> <div class="text-h6">5</div> </td> <td class="instruction"> <p> Make sure your account is selected and <strong>click "Deploy"</strong>. </p> </td> <td/> </tr> <!------------------------ Step 6 -------------------------> <tr> <td> <div class="text-h6">6</div> </td> <td class="instruction"> <p> Below the Deploy button (still in the "Run" tab), you should now see "Count at 0x....." in the list of "Deployed Contracts" </p> </td> <td/> </tr> <!------------------------ Step 7 -------------------------> <tr> <td> <div class="text-h6">7</div> </td> <td class="instruction"> <p> <strong>Copy the contract address</strong> using the special small button located next to the address, and paste it below: </p> </td> <td/> </tr> <!------------------------ Step 8 -------------------------> <tr> <td> <div class="text-h6">8</div> </td> <td class="instruction"> <q-input square outlined label="Contract address" :disable="level > 3" :value="solution" @change="(event) => $emit('setValue', {level3solution: event.target.value})" /> </td> <td/> </tr> <tr><td colspan="3"> <level-submit-button :inputAttempts="inputAttempts" :level="level" :submissionProgress="submissionProgress" :buttonLevel="3" v-on:finish="$emit('finish')" /> </td></tr> </tbody> </q-markup-table> </q-card> </div> </template> <script> import { CAVER } from 'boot/caver' export default { components: { LevelSubmitButton: () => import('components/LevelSubmitButton.vue') }, props: { address: { type: String }, selectedLevel: { type: Number }, level: { type: Number }, solution: { type: String }, submissionProgress: { type: Number }, inputAttempts: { type: Number } }, data () { return {} }, methods: { isAddressValid (address) { return CAVER.utils.isAddress(address) } } } </script> <style> </style>
from typing import Union Or = Union class Account: id: int name: str balance: int def __init__(self, id: int, name: str, balance=0): self.id = id self.name = name self.balance = balance def credit(self, amount: int) -> int: self.balance += amount return self.balance def debit(self, amount: int) -> Or[int, str]: if amount <= self.balance: self.balance -= amount return self.balance return 'Amount exceeded balance' def info(self) -> str: return f'User {self.name} with account {self.id} has {self.balance} balance' account = Account(1234, "George", 1000) print(account.credit(500)) print(account.debit(1500)) print(account.info()) account = Account(5411256, "Peter") print(account.debit(500)) print(account.credit(1000)) print(account.debit(500)) print(account.info())
<script setup lang="ts"> import { useAxios } from '@vueuse/integrations/useAxios' import type { Result } from '~/api' import { instance, url } from '~/api' const props = defineProps<{ id: string }>() const userStore = useUserStore() const commentsPageNumber = ref(1) const commentsLoading = ref(true) const comments = ref<AnyObject[]>([]) const hasMoreComments = ref(false) const { data: post, isLoading: postLoading } = useAxios<Result<AnyObject>>(url.getPost, { params: { id: props.id, }, }, instance) const loadComments = () => { return useAxios<Result<AnyObject[]>>(url.listComment, { params: { limit: 20, page: commentsPageNumber.value, post_id: props.id, }, }, instance) } const reloadComments = async () => { commentsPageNumber.value = 1 commentsLoading.value = true const { data, isFinished } = await loadComments() if (isFinished) { comments.value = data.value?.data || [] hasMoreComments.value = comments.value.length < (data.value?.total || 0) commentsLoading.value = false } } const handleIntersect = async ($state: { loaded: () => void complete: () => void }) => { if (hasMoreComments.value) { commentsPageNumber.value++ const { data, isFinished } = await loadComments() if (isFinished) { comments.value.push(...(data.value?.data || [])) hasMoreComments.value = comments.value.length < (data.value?.total || 0) $state.loaded() } } else { $state.complete() } } const createComment = (values: AnyObject) => { return useAxios(url.createComment, { data: { ...values, post_id: props.id, }, }, instance) } const handleNewReply = (reply: AnyObject, commentIdx: number) => { comments.value[commentIdx] = { ...comments.value[commentIdx], reply_count: (comments.value[commentIdx].reply_count || 0) + 1, edges: { ...(comments.value[commentIdx].edges || []), comment_replies: [ ...(comments.value[commentIdx].edges.comment_replies || []), { ...reply, edges: { user: { nickname: userStore.info?.nickname, }, }, }, ], }, } } onMounted(async () => { const { data, isFinished } = await loadComments() if (isFinished) { commentsLoading.value = false if (data.value?.total) comments.value.push(...(data.value.data || [])) hasMoreComments.value = comments.value.length < (data.value?.total || 0) } }) </script> <template> <div v-if="postLoading" class="bg-#fff border-rd-4px relative p-20px"> <Skeleton /> </div> <PostItem v-else :data="post?.data || {}"> <template #header-extra> <NButton v-if="userStore.info?.id && userStore.info?.id !== post?.data?.user.id" strong secondary round type="primary"> <template #icon> <n-icon> <ICarbonAdd /> </n-icon> </template> 关注 </NButton> </template> </PostItem> <div v-if="commentsLoading" class="bg-#fff border-rd-4px relative p-20px m-t-16px"> <Skeleton /> </div> <div v-else class="bg-#fff border-rd-4px relative p-y-20px m-t-16px"> <div class="p-x-20px"> <Editor placeholder="输入评论" submit-button-text="发表评论" @submit="createComment" @submit-success="() => reloadComments()" /> </div> <NDivider /> <div class="p-x-20px"> <NSpace justify="space-between" align="center" class="p-b-2"> <span class="text-18px font-600 color-#252933"> 全部评论 </span> <NTabs v-if="comments.length" type="segment" size="small" class="w-30"> <NTab name="hot" tab="热门" /> <NTab name="new" tab="最新" /> </NTabs> </NSpace> <NList :show-divider="false"> <div v-if="!comments.length" class=" min-h-40 flex items-center justify-center"> <NEmpty size="large" description="一篇荒芜 :)" /> </div> <NListItem v-for="(comment, index) in comments" v-else :key="comment.id" :show-divider="false" > <CommentItem :data="comment" :index="index" @reply-success="handleNewReply" /> </NListItem> </NList> <InfiniteScroll v-if="!commentsLoading && comments.length" @intersect="handleIntersect" /> </div> </div> </template>
import { useForm } from "react-hook-form"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { useState } from "react"; import { X } from "lucide-react"; import { editServer } from "@/api"; import { useQueryClient } from "@tanstack/react-query"; import { useModalStore } from "@/hooks/use-modal-store"; import { useMutation } from "@tanstack/react-query"; import { useToast } from "@/components/ui/use-toast"; import { ApiError } from "@/utils"; const MAX_FILE_SIZE = 5000000; const ACCEPTED_IMAGE_TYPES = [ "image/png", "image/jpeg", "image/jpg", "image/webp", ]; type EditServerFormValues = { name?: string; image?: FileList; }; const EditServerModal = () => { const { isOpen, onClose, type, data } = useModalStore(); const form = useForm<EditServerFormValues>({}); const [imagePreview, setImagePreview] = useState<string | null>(null); const [showDeleteButton, setShowDeleteButton] = useState(false); const { server } = data; const { toast } = useToast(); const queryClient = useQueryClient(); const { mutateAsync: editServerMutation } = useMutation({ mutationFn: async (formData: FormData) => { return await editServer( queryClient.getQueryData(["accessToken"])!, server!.id, formData ); }, onError: (error) => { const apiError = error as ApiError; switch (apiError.status) { case 400: toast({ title: "Bad Request", description: "Please check your input and try again", variant: "destructive", }); break; case 401: toast({ title: "Unauthorized", description: "You are not authorized to perform this action", variant: "destructive", }); break; case 404: toast({ title: "Not Found", description: "The resource you are looking for does not exist", variant: "destructive", }); break; default: case 500: toast({ title: "Internal Server Error", description: "Something went wrong. Please try again later", variant: "destructive", }); } }, }); const isModalOpen = isOpen && type === "editServer"; const isLoading = form.formState.isSubmitting; const onSubmit = async (values: EditServerFormValues) => { try { console.log(values); if (!values.name && (!values.image || values.image.length === 0)) return; const editServerFormData = new FormData(); if (values.name) { editServerFormData.append("name", values.name); } if (values.image?.length === 1) { editServerFormData.append("image", values.image[0]); } await editServerMutation(editServerFormData); form.reset(); setImagePreview(null); setShowDeleteButton(false); await queryClient.invalidateQueries(["server", server!.id]); await queryClient.invalidateQueries(["servers"]); onClose(); } catch (error) { return; } }; const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => { if ( e.target.files && e.target.files.length > 0 && ACCEPTED_IMAGE_TYPES.includes(e.target.files[0].type) ) { const reader = new FileReader(); reader.onloadend = () => { setImagePreview(reader.result as string); }; reader.readAsDataURL(e.target.files[0]); setShowDeleteButton(true); } else { setImagePreview(null); setShowDeleteButton(false); } }; const handleDeleteImage = () => { form.setValue("image", null as any); // This sets the value of 'image' in react-hook-form to null setShowDeleteButton(false); setImagePreview(null); }; const handleClose = () => { form.reset(); setImagePreview(null); setShowDeleteButton(false); onClose(); }; return ( <Dialog open={isModalOpen} onOpenChange={handleClose}> <DialogContent className="bg-white text-black p-0 overflow-hidden"> <DialogHeader className="pt-8 px-6"> <DialogTitle className="text-2xl text-center font-bold"> Customize your server </DialogTitle> <DialogDescription className="text-center text-zinc-500"> Give your server a flavor with a name and an image. You can alway change it later. </DialogDescription> </DialogHeader> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8"> <div className="space-y-8 px-6"> <div> <div className={`${imagePreview && "invisible"}`}> <label className="uppercase text-xs font-bold text-zinc-500 dark:text-secondary/70" htmlFor="image" > New SERVER IMAGE </label> <Input {...form.register("image", { validate: { count: (files: FileList | undefined) => { if (!files || files.length === 0) return true; return files.length === 1 || "Please upload one file"; }, size: (files: FileList | undefined) => { if (!files || files.length === 0) return true; return ( files[0].size < MAX_FILE_SIZE || "File is too large" ); }, type: (files: FileList | undefined) => { if (!files || files.length === 0) return true; return ( ACCEPTED_IMAGE_TYPES.includes(files[0].type) || "File type not supported" ); }, }, })} type="file" name="image" id="image" className="bg-zinc-300/50 border-0 focus-visible:ring-0 text-black focus-visible:ring-offset-0" disabled={isLoading} onChange={handleImageChange} accept={ACCEPTED_IMAGE_TYPES.join(",")} /> </div> {imagePreview && ( <div className="relative h-28 w-28 mx-auto"> <img src={imagePreview} alt="Thumbnail" className="object-cover h-full w-full rounded-full border border-gray-100" /> {showDeleteButton && ( <button onClick={handleDeleteImage} className="bg-rose-500 text-white p-1 rounded-full absolute top-1 right-1 shadow-sm" type="button" disabled={isLoading} > <X className="h-4 w-4" /> </button> )} </div> )} {form.formState.errors.image && ( <p className={"text-sm font-medium text-destructive"}> {form.formState.errors.image.message} </p> )} </div> <div> <label className="uppercase text-xs font-bold text-zinc-500 dark:text-secondary/70" htmlFor="name" > New Server name </label> <Input {...form.register("name", {})} disabled={isLoading} className="bg-zinc-300/50 border-0 focus-visible:ring-0 text-black focus-visible:ring-offset-0" placeholder="Enter server name" id="name" /> {form.formState.errors.name && ( <p className={"text-sm font-medium text-destructive"}> {form.formState.errors.name.message} </p> )} </div> </div> <DialogFooter className="bg-gray-100 px-6 py-4"> <Button variant={"primary"} disabled={isLoading} type="submit"> Save </Button> </DialogFooter> </form> </DialogContent> </Dialog> ); }; export { EditServerModal };
package com.livingtechusa.reflexion.ui.settings import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.net.Uri import android.widget.Toast import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedCard import androidx.compose.material3.Scaffold import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import androidx.core.content.ContextCompat.startActivity import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import androidx.navigation.NavHostController import coil.compose.rememberAsyncImagePainter import coil.compose.rememberImagePainter import coil.request.ImageRequest import com.livingtechusa.reflexion.R import com.livingtechusa.reflexion.navigation.NavBarItems import com.livingtechusa.reflexion.ui.components.MaterialRadioButtonGroupComponent import com.livingtechusa.reflexion.ui.viewModels.SettingsViewModel import com.livingtechusa.reflexion.util.ResourceProviderSingleton import com.livingtechusa.reflexion.util.extensions.findActivity import com.livingtechusa.reflexion.util.sharedPreferences.UserPreferencesUtil const val SETTINGS = "settings" @Composable fun SettingsScreen( navHostController: NavHostController, viewModel: SettingsViewModel = hiltViewModel() ) { val lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current DisposableEffect(lifecycleOwner) { // Create an observer that triggers our remembered callbacks // for sending analytics events val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_CREATE) { viewModel.onTriggerEvent(SettingsEvent.GetIconImages) } } // Add the observer to the lifecycle lifecycleOwner.lifecycle.addObserver(observer) // When the effect leaves the Composition, remove the observer onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } val context = LocalContext.current val icons = NavBarItems.SettingsBarItems if (context.findActivity() != null) { CompactScreen(navHostController, icons, viewModel) } } @Composable fun IconImageCard( image: Bitmap, iconNumber: Int, totalIndices: Int, viewModel: SettingsViewModel ) { val context = LocalContext.current val screenPixelDensity = context.resources.displayMetrics.density val size = (512f / 2) / screenPixelDensity val selectedIconIndex by viewModel.iconSelected.collectAsState() val isSelected = (selectedIconIndex == iconNumber) val outlineColor = if (isSelected) { MaterialTheme.colorScheme.surface } else { MaterialTheme.colorScheme.primary } val imagePainter = rememberAsyncImagePainter( ImageRequest.Builder(LocalContext.current).data(data = image).apply(block = fun ImageRequest.Builder.() { allowHardware(false) }).build() ) OutlinedCard( shape = MaterialTheme.shapes.medium, modifier = Modifier .height(size.dp) .width(size.dp) .padding(4.dp), border = CardDefaults.outlinedCardBorder(isSelected), colors = CardDefaults.outlinedCardColors(containerColor = outlineColor) ) { Image( painter = imagePainter, contentDescription = "Icon Image", contentScale = ContentScale.FillBounds, modifier = Modifier .fillMaxSize() .clickable( onClick = { viewModel.icon = true viewModel.iconNumber = iconNumber viewModel.totalIndices = totalIndices viewModel.onTriggerEvent(SettingsEvent.SetIconSelected(iconNumber)) } ), alignment = Alignment.Center ) } } @Composable fun HorizontalScrollableIconRowComponent( list: List<Bitmap>, viewModel: SettingsViewModel ) { Column( modifier = Modifier .fillMaxWidth() .padding(4.dp) .background(MaterialTheme.colorScheme.primary), verticalArrangement = Arrangement.Center ) { LazyRow( modifier = Modifier .padding(4.dp) .fillMaxSize() .background(MaterialTheme.colorScheme.primary), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { items(list.size) { listitemIndex -> if (list.isEmpty().not()) { IconImageCard( list[listitemIndex], listitemIndex, list.size, viewModel = viewModel ) } } } } } fun showNewIconImage(context: Context, int: Int, totalIndices: Int) { val packageManager = context.packageManager // enable new icon packageManager.setComponentEnabledSetting( ComponentName( context, "com.livingtechusa.reflexion.MainActivityAlias${int.toString()}" ), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP ) var count = 0 while (count <= (totalIndices - 1)) { if (count != int) { // disable each other icon packageManager.setComponentEnabledSetting( ComponentName( context, "com.livingtechusa.reflexion.MainActivityAlias$count" ), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP ) } count++ } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsContent( paddingValues: PaddingValues, viewModel: SettingsViewModel ) { val apply by viewModel.apply.collectAsState() val bitmapList by viewModel.iconImages.collectAsState() val startMode: Int = if (UserPreferencesUtil.getCurrentUserModeSelection(LocalContext.current) != -1) { UserPreferencesUtil.getCurrentUserModeSelection(LocalContext.current) } else { if (isSystemInDarkTheme()) 1 else 0 } val context = LocalContext.current val resource = ResourceProviderSingleton Scaffold(Modifier.padding(paddingValues = paddingValues)) { if (apply) { if (viewModel.mode && viewModel.isDarkMode != null) { viewModel.isDarkMode?.let { isDark -> viewModel.ToggleLightDarkMode(isDark) } } viewModel.icon = false viewModel.iconNumber = null viewModel.theme = false viewModel.themeNumber = null viewModel.totalIndices = null viewModel.mode = false viewModel.isDarkMode = null viewModel.setApply(false) viewModel.restartApp() } Column( modifier = Modifier .fillMaxSize() .padding(paddingValues = it) .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(4.dp) ) { // Icons val screenPixelDensity = context.resources.displayMetrics.density val height = (768f / 2) / screenPixelDensity Row( Modifier .fillMaxHeight(.15f) .fillMaxWidth() .background(color = MaterialTheme.colorScheme.background), verticalAlignment = Alignment.Top ) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start ) { Row( modifier = Modifier .background(color = MaterialTheme.colorScheme.background) .fillMaxSize() ) {"Didi" val url: String = stringResource(R.string.https_sites_google_com_view_reflexionweb_home) Box( modifier = Modifier .fillMaxWidth() .padding(0.dp), contentAlignment = Alignment.Center ) { ElevatedCard( modifier = Modifier .fillMaxWidth() .padding(16.dp) .align(Alignment.Center), colors = CardDefaults.elevatedCardColors(containerColor = MaterialTheme.colorScheme.primary), shape = MaterialTheme.shapes.large, elevation = CardDefaults.elevatedCardElevation(4.dp) ) { Text( text = stringResource(R.string.import_directions), color = MaterialTheme.colorScheme.onPrimary, textAlign = TextAlign.Center, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold, modifier = Modifier .fillMaxSize() .clickable(onClick = { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) try { startActivity(context, intent, null) } catch (e: Exception) { Toast.makeText( context, R.string.error_did_you_grant_internet_access_permission, Toast.LENGTH_SHORT ).show() } }) ) } } } } } Row( modifier = Modifier .fillMaxWidth() .height(height.dp) .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Box( contentAlignment = Alignment.CenterStart ) { ElevatedCard( modifier = Modifier .fillMaxWidth() .padding(4.dp) .align(Alignment.Center), shape = MaterialTheme.shapes.medium, elevation = CardDefaults.elevatedCardElevation(4.dp) ) { Row( modifier = Modifier.background(MaterialTheme.colorScheme.secondaryContainer), verticalAlignment = Alignment.CenterVertically, ) { Column( modifier = Modifier .fillMaxWidth(.3f) .background(MaterialTheme.colorScheme.secondaryContainer), ) { Text( text = stringResource(R.string.app_icon_images), modifier = Modifier .padding(8.dp), //style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSecondaryContainer ) } Column( modifier = Modifier .fillMaxWidth(1f), verticalArrangement = Arrangement.Center ) { HorizontalScrollableIconRowComponent(bitmapList, viewModel) } } } } } // Theme Row( modifier = Modifier .fillMaxWidth() .height((height * 3).dp) .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Box( contentAlignment = Alignment.CenterStart, ) { ElevatedCard( modifier = Modifier .fillMaxWidth() .padding(4.dp) .align(Alignment.Center), shape = MaterialTheme.shapes.medium, elevation = CardDefaults.elevatedCardElevation(4.dp) ) { Row( modifier = Modifier.background(MaterialTheme.colorScheme.secondaryContainer), verticalAlignment = Alignment.CenterVertically, ) { Column(modifier = Modifier.fillMaxWidth(.3f)) { Text( text = stringResource(R.string.select_theme_color_restart_app), modifier = Modifier.padding(8.dp), color = MaterialTheme.colorScheme.onSecondaryContainer ) } val themeMap = mapOf<String, Int>( "Theme 1" to 1, "Theme 2" to 2, "Theme 3" to 3, "Theme 4" to 4, "Theme 5" to 5, "Theme 6" to 6, stringResource(R.string.default_derived_from_your_wallpaper_selection) to -1 ) MaterialRadioButtonGroupComponent(themeMap, viewModel::setTheme) } } } } // Light / Dark Toggle Row( modifier = Modifier .fillMaxWidth() .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Box( contentAlignment = Alignment.CenterStart, ) { ElevatedCard( modifier = Modifier .fillMaxWidth() .padding(4.dp) .align(Alignment.Center), shape = MaterialTheme.shapes.medium, elevation = CardDefaults.elevatedCardElevation(4.dp) ) { Row( modifier = Modifier.background(MaterialTheme.colorScheme.secondaryContainer), verticalAlignment = Alignment.CenterVertically, ) { val items = (0..1) var activeTabIndex by remember { mutableStateOf(startMode) } TabRow( selectedTabIndex = activeTabIndex, containerColor = Color.Transparent, indicator = { Box( Modifier .tabIndicatorOffset(it[activeTabIndex]) .fillMaxSize() .background(color = MaterialTheme.colorScheme.primary) .zIndex(-1F) ) }, ) { items.mapIndexed { i, _ -> Tab( selected = activeTabIndex == i, onClick = { viewModel.mode = true activeTabIndex = i } ) { if (i == 0) { val color = if (0 == activeTabIndex) { MaterialTheme.colorScheme.onPrimary } else { MaterialTheme.colorScheme.onSecondaryContainer } Text( modifier = Modifier.padding(4.dp), text = stringResource(R.string.light_theme), color = color ) if (0 == activeTabIndex) { viewModel.isDarkMode = false } Icon( painter = painterResource(id = R.drawable.baseline_camera_24), contentDescription = null, tint = color, modifier = Modifier.padding(vertical = 20.dp) ) } if (i == 1) { val color = if (1 == activeTabIndex) { MaterialTheme.colorScheme.onPrimary } else { MaterialTheme.colorScheme.onSecondaryContainer } Text( modifier = Modifier.padding(4.dp), text = stringResource(R.string.dark_theme), color = color ) if (1 == activeTabIndex) { viewModel.isDarkMode = true } Icon( painter = painterResource(id = R.drawable.baseline_camera_24), contentDescription = null, tint = color, modifier = Modifier.padding(vertical = 20.dp) ) } } } } } } } } // Apply Settings Row( modifier = Modifier .fillMaxWidth(), //.padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .fillMaxWidth() .padding(0.dp), contentAlignment = Alignment.Center ) { ElevatedCard( modifier = Modifier .fillMaxWidth() .padding(16.dp) .align(Alignment.Center), shape = MaterialTheme.shapes.large, colors = CardDefaults.elevatedCardColors(containerColor = MaterialTheme.colorScheme.primary), elevation = CardDefaults.elevatedCardElevation(4.dp) ) { Text( text = stringResource(R.string.apply_changes), color = MaterialTheme.colorScheme.onPrimary, textAlign = TextAlign.Center, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold, modifier = Modifier .fillMaxSize() .padding(8.dp) .clickable { if (viewModel.icon && (viewModel.iconNumber != null) && (viewModel.totalIndices != null)) { viewModel.iconNumber?.let { iconNum -> viewModel.totalIndices?.let { index -> showNewIconImage( context = context, int = iconNum, totalIndices = index ) } } } // Toggle for light/dark mode Set when collecting Apply State if (viewModel.theme && (viewModel.themeNumber != null)) { viewModel.themeNumber?.let { theme -> UserPreferencesUtil.setCurrentUserThemeSelection( context, theme ) } } viewModel.setApply(true) Toast .makeText( context, resource.getString(R.string.applying_changes_and_restarting), Toast.LENGTH_SHORT ) .show() } ) } } } // Reset settings Row( modifier = Modifier .fillMaxWidth(), //.padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .fillMaxWidth() .padding(0.dp), contentAlignment = Alignment.Center ) { ElevatedCard( modifier = Modifier .fillMaxWidth() .padding(16.dp) .align(Alignment.Center), colors = CardDefaults.elevatedCardColors(containerColor = MaterialTheme.colorScheme.primary), shape = MaterialTheme.shapes.large, elevation = CardDefaults.elevatedCardElevation(4.dp) ) { Text( text = stringResource(R.string.app_reset), color = MaterialTheme.colorScheme.onPrimary, textAlign = TextAlign.Center, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold, modifier = Modifier .fillMaxSize() .padding(8.dp) .clickable { UserPreferencesUtil.setCurrentUserModeSelection(context, -1) resetIconImage(context, bitmapList.size) UserPreferencesUtil.setCurrentUserThemeSelection(context, -1) viewModel.restartApp() Toast .makeText( context, resource.getString(R.string.applying_changes_and_restarting), Toast.LENGTH_SHORT ) .show() }) } } } } } } fun resetIconImage(context: Context, iconListSize: Int) { val packageManager = context.packageManager // enable default icon packageManager.setComponentEnabledSetting( ComponentName( context, "com.livingtechusa.reflexion.MainActivity" ), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP ) var count = 0 while (count <= (iconListSize - 1)) { // disable each other icon packageManager.setComponentEnabledSetting( ComponentName( context, "com.livingtechusa.reflexion.MainActivityAlias$count" ), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP ) count++ } Toast .makeText( context, context.getString(R.string.app_reset), Toast.LENGTH_LONG ) .show() }
import { createGlobalStyle } from "styled-components" const GlobalStyles = createGlobalStyle` :root { --mainColor: ${(props) => props.theme.colors.mainColor}; --secondaryColor: ${(props) => props.theme.colors.secondaryColor}; --borderColor: ${(props) => props.theme.colors.borderColor}; --mainText: ${(props) => props.theme.colors.mainText}; --secondaryText: ${(props) => props.theme.colors.secondaryText}; --themeDotBorder: ${(props) => props.theme.colors.themeDotBorder}; --previewBg: ${(props) => props.theme.colors.previewBg}; --previewShadow: ${(props) => props.theme.colors.previewShadow}; --buttonColor: ${(props) => props.theme.colors.buttonColor}; } html, body { padding: 0; margin: 0; scroll-behavior: smooth; } body * { transition: 0.3s; } h1, h2, h3, h4, h5, h6, strong { color: var(--mainText); font-family: "Russo One", sans-serif; font-weight: 500; } p, li, span, label, input, textarea { color: var(--secondaryText); font-family: "Roboto Mono", monospace; } a { text-decoration: none; color: #17a2b8; } ul { list-style: none; } h1 { font-size: 56px; } h2 { font-size: 36px; } h3 { font-size: 28px; } h4 { font-size: 24px; } h5 { font-size: 20px; } h6 { font-size: 16px; } li { padding: 0; margin: 0; } ` export default GlobalStyles
# Self-hosted Runner GitHub self-hosted runners play a crucial role in: - Kicking off deployment processes and accessing necessary virtual machines. - Executing GitHub Actions workflows, especially when GitHub-hosted runners fall short. ## Authenticating Self-hosted Runners Proper authentication is key. Avoid using personal access tokens for setting up self-hosted runners due to security risks. Instead, opt for GitHub Apps, offering a more secure alternative. <div class="warning"> **Important: Avoid Personal Access Tokens** Personal Access Tokens are linked to individual users, posing security risks if compromised. They often come with excessive privileges, leading to increased risk. Additionally, they require creating service accounts (resulting in additional license consumption) and are less secure compared to GitHub applications. </div> ### Creating a GitHub Application 1. Go to your GitHub organization: Settings -> Developer Settings -> GitHub Apps -> New GitHub app. 2. Enter the application name (e.g., `BIIP Workflows Self-hosted Runner`). 3. Provide any homepage URL. 4. Uncheck the "active" option for WebHooks. #### Permissions Choose between repository-scoped or organization-scoped runners. Set the following required permissions: **For Repository Runners:** - Actions (read) - Administration (read/write) - Checks (read) (if using Webhook Driven Scaling) - Metadata (read) **For Organization Runners:** - Actions (read) - Metadata (read) **Organization Permissions:** - Self-hosted runners (read/write) #### Private Key Download the private key file by clicking "Generate a private key" at the bottom of the GitHub App page. This file will be used later in the installation process. #### Installation 1. Go to the "Install App" tab on the left side of the page. 2. Install the GitHub App you created for your organization. 3. Select the repositories where you want to install the GitHub app and use self-hosted runners. <div class="warning"> **Important: Avoid Installing Self-hosted Runners on Public Repositories** GitHub recommends using self-hosted runners exclusively with private repositories. Public repository forks could potentially execute malicious code on your self-hosted runner machine through pull requests. For more information, refer to [GitHub's documentation](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners). </div> # Credits - Permissions list is based on [ocpdude/actions-runner-controller](https://github.com/ocpdude/actions-runner-controller/blob/main/README.md) documentation.
import pandas as pd import numpy as np import tensorflow as tf from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.utils import to_categorical from tensorflow.keras.models import Model from tensorflow.keras.layers import Embedding, SpatialDropout1D, Bidirectional, GRU, Dense from tensorflow.keras.callbacks import EarlyStopping from transformers import AutoTokenizer import re from tensorflow.keras.preprocessing.text import Tokenizer import pandas as pd import numpy as np import json import tensorflow as tf from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.utils import to_categorical from tensorflow.keras.models import Model from tensorflow.keras.layers import Embedding, SpatialDropout1D, Bidirectional, GRU, Dense from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from nltk.corpus import stopwords from nltk.stem.snowball import SnowballStemmer import nltk from sklearn.metrics import confusion_matrix, classification_report import matplotlib.pyplot as plt import seaborn as sns from nltk.corpus import stopwords from nltk.stem.snowball import SnowballStemmer import nltk from sklearn.metrics import confusion_matrix, classification_report import matplotlib.pyplot as plt import seaborn as sns # Configure GPU for training (if available) def configure_gpu(): gpus = tf.config.list_physical_devices('GPU') if gpus: try: for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) print(f"GPUs available: {gpus}") except RuntimeError as e: print(e) else: print("No GPU, using CPU.") # Download NLTK data for text preprocessing def download_nltk_data(): nltk.download('stopwords', quiet=True) # Function to preprocess text data def preprocess_text(text): stop_words = stopwords.words('russian') stemmer = SnowballStemmer('russian') text = text.lower() text = re.sub(r'[^\w\s]', '', text) text = re.sub(r'\d+', '', text) words = text.split() words = [word for word in words if word not in stop_words] words = [stemmer.stem(word) for word in words] return ' '.join(words) # Function to load and preprocess the dataset def load_and_preprocess_data(filepath): df = pd.read_csv(filepath) df['processed_text'] = df['text'].apply(preprocess_text) return df # Define the custom GRU model class class CustomGRUModel(Model): def __init__(self, vocab_size, embedding_dim, input_length, gru_units, dropout_rate, num_classes): super(CustomGRUModel, self).__init__() self.embedding = Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=input_length) self.spatial_dropout = SpatialDropout1D(dropout_rate) self.bidirectional_gru = Bidirectional(GRU(gru_units, return_sequences=False)) self.dense = Dense(num_classes, activation='softmax') # The call method defines the forward pass of the model. def call(self, inputs): x = self.embedding(inputs) x = self.spatial_dropout(x) x = self.bidirectional_gru(x) return self.dense(x) # Helper function to encode texts using the tokenizer. def encode_texts(tokenizer, texts): return tokenizer(texts, padding='max_length', truncation=True, max_length=200, return_tensors="np") # Training and evaluation function for the model. def train_and_evaluate_model(X_train, y_train, X_test, y_test): # Instantiate the model with the given hyperparameters. model = CustomGRUModel(vocab_size=5000, embedding_dim=128, input_length=200, gru_units=64, dropout_rate=0.2, num_classes=3) model.build(input_shape=(None, 200)) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() # Print a summary of the model. # Callback for early stopping to prevent overfitting early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True) # Train the model using the training data and validation data model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=64, callbacks=[early_stopping], verbose=2) # Evaluate the model's performance on the test set loss, accuracy = model.evaluate(X_test, y_test, verbose=2) print(f'Test Accuracy: {accuracy}') # Use the trained model to predict the test set predictions = model.predict(X_test, verbose=2) return model, y_test, predictions def main(): configure_gpu() # Set up GPU configuration download_nltk_data() # Ensure required NLTK data is downloaded # Load and preprocess the training data filepath = 'train_2.csv' df = load_and_preprocess_data(filepath) # Initialize and configure the Keras Tokenizer tokenizer = Tokenizer(num_words=5000, oov_token='<OOV>') tokenizer.fit_on_texts(df['processed_text']) sequences = tokenizer.texts_to_sequences(df['processed_text']) padded_sequences = pad_sequences(sequences, maxlen=200) # Encode labels into a binary (one-hot) representation encoder = LabelEncoder() df['sentiment_numeric'] = encoder.fit_transform(df['sentiment']) labels = to_categorical(df['sentiment_numeric']) # Train test split X_train, X_test, y_train, y_test = train_test_split(padded_sequences, labels, test_size=0.2, random_state=42) # Model training model = CustomGRUModel(vocab_size=5000, embedding_dim=128, input_length=200, gru_units=64, dropout_rate=0.2, num_classes=3) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=64, verbose=2) # Save the model and tokenizer model.save('gru_sentiment_model', save_format='tf') # Save tokenizer to JSON tokenizer_json = tokenizer.to_json() with open('tokenizer.json', 'w', encoding='utf-8') as f: f.write(json.dumps(tokenizer_json, ensure_ascii=False)) print("Tokenizer saved to tokenizer.json") if __name__ == "__main__": main()
%% MAP for Poisson Distribution % parameter λ represents the average rate of occurrences. % When we use a Gamma prior for λ, % it means we are expressing our prior belief that λ follows a Gamma distribution % with shape parameter α_prior and rate parameter β_prior. % The choice of these hyperparameters (α_prior and β_prior) depends on % the prior knowledge or assumptions about the rate of occurrences. % A Gamma distribution allows for a flexible range of prior beliefs, % as it can take on various shapes, including exponential and uniform distributions as special cases. % Sample data (count data following Poisson distribution) data = [3, 1, 4, 2, 5, 2, 6, 3, 5, 2]; n = length(data); %% % Define Prior distribution alpha_prior = 1; % Prior shape parameter % large means non-informative beta_prior = 1; %Prior rate parameter % large means non-informative prior = @(lambda) gampdf(lambda, alpha_prior, 1/beta_prior); % Define likelihood function likelihood = @(lambda) prod(poisspdf(data,lambda)); % Define Posterior and neg_log for minimization posterior = @(lambda) prior(lambda) * likelihood(lambda); neg_log_posterior = @(lambda) -log(posterior(lambda)); % Perform MAP initial_lambda = mean(data); estimated_lambda = fminsearch(neg_log_posterior,initial_lambda); disp(['Estimated Poisson Parameter (lambda): ' num2str(estimated_lambda)]) %% Plot x_values = linspace(0.01,20,1000); pmf_values = gampdf(x_values,estimated_lambda); %posterior_pdf = posterior(lambda_values); %normalized_posterior_pdf = posterior_pdf / trapz(lambda_values, posterior_pdf); figure(1),clf bar(x_values,pmf_values) xlabel('Count Values') ylabel('Probability') title('MAP for Poisson Distribution (PMF)')
#ifndef DB_H #define DB_H #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "globals.h" #include "trie.h" typedef struct { char id[MAX_ID_SIZE]; // Obrigatoriamente uma string de letras minusculas char fullName[MAX_FULL_NAME_SIZE]; // Nome completo da Pessoa int age; // Idade da pessoa } PersonRecord; typedef struct { TrieNode* trie; // Ponteiro para a estrutura de dados char staticPath[PATH_STRING_SIZE]; // Caminho para o arquivo do banco } DataBase; typedef struct { PersonRecord result; // Resultado do parsing int error; // 0 se não houver erros } ParseResult; /* Instancia um novo banco de dados ATENÇÃO: É necessário deletar esse Nodo. Com a função `deleteDataBase()` */ DataBase* createDataBase(char* staticPath); // Checa se um ID já existe e insere um novo PersonRecord ao banco de dados (Volátil) PersonRecord* insertNewRecord(DataBase* db, PersonRecord newRecord); // Procura no banco de dados um record pelo seu ID retorna NULL caso não encontre PersonRecord* findRecordById(DataBase* db, char id[MAX_ID_SIZE]); // Remove um PersonRecord por seu ID bool removeRecordById(DataBase* db, char id[MAX_ID_SIZE]); // Helper para criar um novo PersonRecord PersonRecord createPersonRecord(char id[MAX_ID_SIZE], char fullName[MAX_FULL_NAME_SIZE], int age); // Imprime os dados contidos em um PersonRecord PersonRecord* printPersonRecord(PersonRecord* record); // Imprime todos os elementos do banco de dados (Volátil) DataBase* printEntireDB(DataBase* db); // Função privada: Recursão para imprimir os elementos void _displayDBElement(TrieNode* node, int level); /* Libera a memória alocada ao banco de dados. Ao deletar o Banco de dados as estruturas de dados relacionadas também serão excluídas */ void deleteDataBase(DataBase* db); // Faz o parsing do input do usuário para um novo PersonRecord ParseResult parseData(char data[MAX_DATA_SIZE], size_t dataSize); // Inverte uma string void _invertString(char* str); // Carrega dados do disco a partir Path do db bool loadRecordsFromDisk(DataBase* db); // Salva dados ao disco, procura o arquivo explicito no path e caso não o encontre cria um novo arquivo bool saveRecordsToDisk(DataBase* db); // Função privada: Recursão para imprimir os elementos ao disco void _printToDiskRecursive(TrieNode* node, int level, FILE* fp); // Conta o número de Recordes no banco unsigned int countNumOfRecords(DataBase* db); #endif
import { Association, CreationOptional, DataTypes, HasManyGetAssociationsMixin, HasManySetAssociationsMixin, HasManyAddAssociationMixin, HasManyAddAssociationsMixin, HasManyCreateAssociationMixin, HasManyRemoveAssociationMixin, HasManyRemoveAssociationsMixin, HasManyHasAssociationMixin, HasManyHasAssociationsMixin, HasManyCountAssociationsMixin, InferCreationAttributes, InferAttributes, Model, NonAttribute, Sequelize } from 'sequelize' import type { ChatMessage } from './ChatMessage' import type { ChatRoomParticipant } from './ChatRoomParticipant' type ChatRoomAssociations = 'chatRoomParticipants' | 'chatMessages' export class ChatRoom extends Model< InferAttributes<ChatRoom, {omit: ChatRoomAssociations}>, InferCreationAttributes<ChatRoom, {omit: ChatRoomAssociations}> > { declare id: CreationOptional<number> declare createdAt: CreationOptional<Date> declare updatedAt: CreationOptional<Date> // ChatRoom hasMany ChatRoomParticipant declare chatRoomParticipants?: NonAttribute<ChatRoomParticipant[]> declare getChatRoomParticipants: HasManyGetAssociationsMixin<ChatRoomParticipant> declare setChatRoomParticipants: HasManySetAssociationsMixin<ChatRoomParticipant, number> declare addChatRoomParticipant: HasManyAddAssociationMixin<ChatRoomParticipant, number> declare addChatRoomParticipants: HasManyAddAssociationsMixin<ChatRoomParticipant, number> declare createChatRoomParticipant: HasManyCreateAssociationMixin<ChatRoomParticipant, 'roomId'> declare removeChatRoomParticipant: HasManyRemoveAssociationMixin<ChatRoomParticipant, number> declare removeChatRoomParticipants: HasManyRemoveAssociationsMixin<ChatRoomParticipant, number> declare hasChatRoomParticipant: HasManyHasAssociationMixin<ChatRoomParticipant, number> declare hasChatRoomParticipants: HasManyHasAssociationsMixin<ChatRoomParticipant, number> declare countChatRoomParticipants: HasManyCountAssociationsMixin // ChatRoom hasMany ChatMessage declare chatMessages?: NonAttribute<ChatMessage[]> declare getChatMessages: HasManyGetAssociationsMixin<ChatMessage> declare setChatMessages: HasManySetAssociationsMixin<ChatMessage, number> declare addChatMessage: HasManyAddAssociationMixin<ChatMessage, number> declare addChatMessages: HasManyAddAssociationsMixin<ChatMessage, number> declare createChatMessage: HasManyCreateAssociationMixin<ChatMessage, 'roomId'> declare removeChatMessage: HasManyRemoveAssociationMixin<ChatMessage, number> declare removeChatMessages: HasManyRemoveAssociationsMixin<ChatMessage, number> declare hasChatMessage: HasManyHasAssociationMixin<ChatMessage, number> declare hasChatMessages: HasManyHasAssociationsMixin<ChatMessage, number> declare countChatMessages: HasManyCountAssociationsMixin declare static associations: { chatRoomParticipants: Association<ChatRoom, ChatRoomParticipant>, chatMessages: Association<ChatRoom, ChatMessage> } static initModel(sequelize: Sequelize): typeof ChatRoom { ChatRoom.init({ id: { type: DataTypes.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false }, createdAt: { type: DataTypes.DATE }, updatedAt: { type: DataTypes.DATE } }, { sequelize }) return ChatRoom } }
# 새로운 할인 정책 개발 ## ✏️ 변경사항 - 할인 정책 변경 : 고정금액 할인 → 정률 할인 ## ✏️ 구현체 제작 정률 할인으로 바꾸기위해 정률 할인 기능을 하는 Class 제작 ```java package hello.core.discount; import hello.core.member.Grade; import hello.core.member.Member; public class RateDiscountPolicy implements DiscountPolicy { private final int discountPercent = 10; @Override public int discount(Member member, int price) { if (member.getGrade() == Grade.VIP) { return price * discountPercent / 100; } else { return 0; } } } ``` ### Test case 📍 VIP 등급일 경우 @DisplayName 는 Test 실행시 method 이름을 괄호 안의 내용으로 변경해줌 ```java package hello.core.discount; import hello.core.member.Grade; import hello.core.member.Member; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class RateDiscountPolicyTest { RateDiscountPolicy discountPolicy = new RateDiscountPolicy(); @Test @DisplayName("VIP 10% 할인 기능") void vip_o (){ Member member = new Member(1L, "MemberVIP", Grade.VIP); int discount = discountPolicy.discount(member, 10000); assertThat(discount).isEqualTo(1000); } } // VIP 10% 할인 기능 V ``` 📍 일반 회원일 경우 ```java @Test @DisplayName("일반회원 할인 적용 없음") void vip_x () { Member member = new Member(1L, "MemberBasic", Grade.BASIC); int discount = discountPolicy.discount(member, 10000); assertThat(discount).isEqualTo(0); } // 일반회원 할인 적용 없음 V ``` ## ✏️ 새로운 할인 정책 적용 Order Service Impl 에서 인스턴스를 변경해줘야한다. ```java public class OrderServiceImpl implements OrderService{ private final MemberRepository memberRepository = new MemoryMemberRepositry(); // private final DiscountPolicy discountPolicy = new FixDiscountPolicy(); private final DiscountPolicy discountPolicy = new RateDiscountPolicy(); ``` ### ❗️ 문제점 발견 - 역할과 구현 분리 ✅ - 다형성 활용과 인터페이스와 구현객체 분리 ✅ - DIP 원칙 준수 ❎ - 추상화인 interface 외에 구체화인 구현 Class 에도 의존하고 있다. - OCP 원칙 준수 ❎ - 기능의 확장시 기존 Class 의 변경을 하면 안되지만 DIP 를 위반했기 때문에 자연스럽게 Order Service Impl 의 코드를 수정했다.
import { Component, Input } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; import { NzModalRef } from 'ng-zorro-antd/modal'; import { NzNotificationService } from 'ng-zorro-antd/notification'; import { CategoryDto } from 'src/app/commons/dto/category'; import { MenuItemRequest } from 'src/app/commons/dto/menu-item'; import { CategoryService } from 'src/app/services/category.service'; import { MenuItemService } from 'src/app/services/menu-item.service'; @Component({ selector: 'app-modal-admin-update-menu-item', templateUrl: './modal-admin-update-menu-item.component.html', styleUrls: ['./modal-admin-update-menu-item.component.scss'] }) export class ModalAdminUpdateMenuItemComponent { @Input() menuItemId!: number; categories: CategoryDto[] = []; validateForm!: UntypedFormGroup; menuItemRequest: MenuItemRequest = new MenuItemRequest(); constructor( private modal: NzModalRef, private fb: UntypedFormBuilder, private categoryService: CategoryService, private menuItemService: MenuItemService, private notification: NzNotificationService ) { } ngOnInit(): void { this.validateForm = this.fb.group({ name: [null, [Validators.required]], description: [null, [Validators.required]], price: [null, [Validators.required]], categoryId: [null, [Validators.required]], }); this.getMenuItemById(); this.getAllCategory(); } getMenuItemById(): void { this.menuItemService.getMenuItemById(this.menuItemId).subscribe(response => { let data = response.data; this.validateForm = this.fb.group({ name: [data.name, [Validators.required]], description: [data.description, [Validators.required]], price: [data.price, [Validators.required]], categoryId: [data.categoryDto.id, [Validators.required]], }); }, error => { this.notification.create( 'error', 'Lỗi máy chủ', 'Có lỗi xảy ra vui lòng thử lại sau' ); }) } getAllCategory(): void { this.categoryService.getAllCategory().subscribe(response => { this.categories = response.data; }, error => { this.notification.create( 'error', 'Lỗi server', 'Lỗi truyền tải dữ liệu' ); }); } updateMenuItem(): void { if (this.validateForm.valid) { console.log('submit', this.validateForm.value); this.menuItemRequest = { name: this.validateForm.value.name, description: this.validateForm.value.description, price: this.validateForm.value.price, categoryId: this.validateForm.value.categoryId, } this.menuItemService.updateMenuItem(this.menuItemId, this.menuItemRequest).subscribe(response => { this.destroyModal(); this.notification.create( 'success', 'Thông báo', 'Cập nhật thông tin thực đơn thành công' ); }, error => { this.notification.create( 'error', 'Lỗi máy chủ', 'Có lỗi xảy ra vui lòng thử lại sau' ); }) } else { Object.values(this.validateForm.controls).forEach(control => { if (control.invalid) { control.markAsDirty(); control.updateValueAndValidity({ onlySelf: true }); } }); } } destroyModal(): void { this.modal.close(); } }
using Data.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Data.Configurations { public class UserConfiguration : IEntityTypeConfiguration<User> { public void Configure(EntityTypeBuilder<User> builder) { builder.HasKey(x => x.Id); builder.Property(x => x.Id) .ValueGeneratedOnAdd(); builder.Property(x => x.FirstName) .IsRequired() .HasMaxLength(64); builder.Property(x => x.LastName) .IsRequired() .HasMaxLength(64); builder.HasIndex(x => x.Email) .IsUnique(); builder.Ignore(x => x.FullName); } } }
""" For this challenge, forget how to add two numbers together. The best explanation on what to do for this function is this meme: ![Alternative Text](https://edabit-challenges.s3.amazonaws.com/caf.jpg) ### Examples meme_sum(26, 39) ➞ 515 # 2+3 = 5, 6+9 = 15 # 26 + 39 = 515 meme_sum(122, 81) ➞ 1103 # 1+0 = 1, 2+8 = 10, 2+1 = 3 # 122 + 81 = 1103 meme_sum(1222, 30277) ➞ 31499 ### Notes N/A """ def meme_sum(a, b): m = str(a) n = str(b) l = abs(len(m)-len(n)) if len(m)<len(n): m1 = l*'0'+ m lst1 = [int(i) for i in m1] lst2 = [int(i) for i in n] return int(''.join([str(i+j) for i,j in zip(lst1,lst2)])) else: n1 = l*'0'+ n lst1 = [int(i) for i in n1] lst2 = [int(i) for i in m] return int(''.join([str(i+j) for i,j in zip(lst1,lst2)]))
dt <- readRDS(file.choose()) dt <- subset(dt[-(1:2 && 21)]) colnames(dt) #Test for coxph library(survival) library(stargazer) library(ggplot2) library(survminer) res.cox <- coxph(Surv(time_to_treatmentsuccess_1, time_to_treatmentsuccess_2) ~., data = dt) stargazer(res.cox,type = 'text') # this test is good however the distribution of the data affects its use as dataset comprises of zeros #Normality test res_aov <- aov(time_to_treatmentsuccess_1 ~ time_to_treatmentsuccess_2, data = dt) summary(res_aov) #check normality visually par(mfrow=c(1,2)) #QQ_plot library(car) qqPlot(res_aov$residuals,id=FALSE) #histogram hist(res_aov$residuals) #Both the qqplot and the histogram indicates a non-normal data distribution #Test for Multicollinearity library(tidyverse) library(caret) # Split the data into training and test set set.seed(123) training.samples <- dt$time_to_treatmentsuccess_1 %>% createDataPartition(p = 0.8, list = FALSE) train.data <- dt[training.samples, ] test.data <- dt[-training.samples, ] train.data<-subset(train.data[-1]) test.data<-subset(test.data[-1]) #Creating a regression model model_1 <- lm(time_to_treatmentsuccess_1 ~., data = train.data) #predictions predictions <- model_1 %>% predict((test.data),na.omit=TRUE) # Performance of the model per_mod <- data.frame( RMSE = RMSE(predictions, test.data$time_to_treatmentsuccess_1), R2 = R2(predictions, test.data$time_to_treatmentsuccess_1) ) #Checking for multicollinearity car::vif(model_1)#Returning aliased coeficients error implying existence of multicollinearity #test for AFT library(dplyr) dt %>% sapply(levels) AFT <- survreg(Surv(time_to_treatmentsuccess_1,en_group2) ~., data = dt) # Accelerated failure rate models can not be used since; ##there are no column with valid survival times for the distribution ##No column with 2 or more levels, all are NULL #test for clustered standard error library(miceadds) m2 <- lm.cluster(time_to_treatmentsuccess_1~., cluster = 'patient_uuid', data = dt) m2coeffs <- data.frame(summary(m2)) m2coeffs[!startsWith(row.names(m2coeffs), 'patient_uuid'),] #test for omitted variable bias #this test can only be conducted if we are omitting certain variables within the dataset for a counter check,however the distribution of the dataset is an impediment to the test.
<template> <div> <form novalidate class="md-layout app-form" @submit.prevent="validateUser"> <md-card class="md-layout-item md-size-100 md-small-size-100"> <md-card-header> <div class="md-title">Team Member</div> </md-card-header> <md-card-content> <div class="md-layout md-gutter"> <div class="md-layout-item md-small-size-100"> <md-field :class="getValidationClass('firstName')"> <label for="first-name">First Name</label> <md-input name="first-name" id="first-name" autocomplete="given-name" v-model="form.firstName" :disabled="sending" /> <span class="md-error" v-if="!$v.form.firstName.required">The first name is required</span> <span class="md-error" v-else-if="!$v.form.firstName.minlength">Invalid first name</span> </md-field> </div> <div class="md-layout-item md-small-size-100"> <md-field :class="getValidationClass('lastName')"> <label for="last-name">Last Name</label> <md-input name="last-name" id="last-name" autocomplete="family-name" v-model="form.lastName" :disabled="sending" /> <span class="md-error" v-if="!$v.form.lastName.required">The last name is required</span> <span class="md-error" v-else-if="!$v.form.lastName.minlength">Invalid last name</span> </md-field> </div> </div> <div class="md-layout md-gutter"> <div class="md-layout-item md-small-size-100"> <md-field :class="getValidationClass('designation')"> <label for="designation">Designation</label> <md-select name="designation" id="designation" v-model="form.designation" md-dense :disabled="sending"> <md-option disabled></md-option> <md-option value="Consultant">CONSULTANT</md-option> <md-option value="Innovation Lead">INNOVATION LEAD</md-option> <md-option value="Strategist">STRATEGIST</md-option> <md-option value="Designer">DESIGNER</md-option> <md-option value="Back-end Developer">BACK-END DEVELOPER</md-option> <md-option value="Front-end Developer">FRONT-END DEVELOPER</md-option> <md-option value="Tech Team Lead">TECHNICAL TEAM LEAD</md-option> <md-option value="Project Manager">PROJECT MANAGER</md-option> </md-select> <span class="md-error">The designation is required</span> </md-field> </div> <div class="md-layout-item md-small-size-100"> <md-field :class="getValidationClass('number')"> <label for="number">Phone number</label> <md-input id="number" name="number" autocomplete="number" v-model="form.number" :disabled="sending" /> <span class="md-error" v-if="!$v.form.number.required">The number is required</span> <span class="md-error" v-else-if="!$v.form.number.maxlength">Invalid number</span> </md-field> </div> </div> <md-field :class="getValidationClass('email')"> <label for="email">Email</label> <md-input type="email" name="email" id="email" autocomplete="email" v-model="form.email" :disabled="sending" /> <span class="md-error" v-if="!$v.form.email.required">The email is required</span> <span class="md-error" v-else-if="!$v.form.email.email">Invalid email</span> </md-field> <md-field :class="getValidationClass('image')"> <label for="image">Image link address</label> <md-input name="image" id="image" autocomplete="image" v-model="form.image" :disabled="sending" /> <span class="md-error" v-if="!$v.form.image.required">The image is required</span> <span class="md-error" v-else-if="!$v.form.image.minlength">Invalid image</span> </md-field> <div class="md-layout md-gutter"> <div class="md-layout-item md-small-size-100"> <md-field :class="getValidationClass('background')"> <label for="background">Background</label> <md-textarea name="background" id="background" v-model="form.background" :disabled="sending" /> <span class="md-error" v-if="!$v.form.background.required">The background is required</span> <span class="md-error" v-else-if="!$v.form.background.minLength">Invalid background, must be at least 30 characters long</span> </md-field> </div> </div> </md-card-content> <md-progress-bar md-mode="indeterminate" v-if="sending" /> <md-card-actions> <md-button type="submit" class="md-primary" :disabled="sending">Save team member</md-button> </md-card-actions> </md-card> </form> </div> </template> <script> import { validationMixin } from 'vuelidate' import { required, email, minLength, maxLength } from 'vuelidate/lib/validators' export default { name: 'FormValidation', mixins: [validationMixin], props: { sending: { type: Boolean, required: true }, employee: { type: Object, required: false } }, data() { return { form: this.employee ? {...this.employee} : { firstName: null, lastName: null, designation: null, number: null, email: null, image: null, background: null }, } }, validations: { form: { firstName: { required, minLength: minLength(3) }, lastName: { required, minLength: minLength(3) }, number: { required, maxLength: maxLength(8) }, designation: { required }, email: { required, email }, image: { required, minLength: minLength(3) }, background: { required, maxLength: minLength(30) } } }, methods: { getValidationClass (fieldName) { const field = this.$v.form[fieldName] if (field) { return { 'md-invalid': field.$invalid && field.$dirty } } }, saveEmployee () { this.$emit('submit', this.form) }, validateUser () { this.$v.$touch() if (!this.$v.$invalid) { this.saveEmployee() } } } } </script> <style lang="scss" scoped> .md-progress-bar { position: absolute; top: 0; right: 0; left: 0; } </style>
import React from 'react'; import ReactDOM from 'react-dom'; import './App.scss'; import App from './App'; import { ChainId, DAppProvider } from '@usedapp/core'; import { createTheme, ThemeProvider, CssBaseline } from '@mui/material'; import { Contract, utils } from 'ethers'; import { CONTRACT_ABI, CONTRACT_ADDRESS } from './constants/commons'; const dAppProviderConfig = { supportedChainIds: [ChainId.Rinkeby], readOnlyChainId: ChainId.Rinkeby, readOnlyUrls: { [ChainId.Rinkeby]: 'https://rinkeby.infura.io/v3/1c20baa263d44a4bb7b3ee8a6f909147' }, notifications: { expirationPeriod: 6000, }, pollingInterval: 8000, }; const appUITheme = createTheme({ palette: { mode: 'dark', }, shape: { borderRadius: 50, }, }); window.__CONTRACT_INSTANCE__ = new Contract(CONTRACT_ADDRESS, new utils.Interface(CONTRACT_ABI)); ReactDOM.render( <DAppProvider config={dAppProviderConfig}> <ThemeProvider theme={appUITheme}> <CssBaseline /> <App /> </ThemeProvider> </DAppProvider>, document.getElementById('root'), );
import ApiError from "../../../errors/ApiError"; import httpStatus from "http-status"; import { StudentPortal } from "../studentPortal/studentPortal.modal"; import { IResult } from "./result.interface"; import { Result } from "./result.model"; import { Types } from "mongoose"; const createResult = async (payload: IResult): Promise<IResult | null> => { try { const result = await Result.create(payload); const selectedStudentPortalClassId = payload.class.toString(); const selectedStudentPortalClass = await StudentPortal.findById(selectedStudentPortalClassId); if (selectedStudentPortalClass) { if (Array.isArray(selectedStudentPortalClass.result)) { (selectedStudentPortalClass.result as Types.ObjectId[]).push(result?._id); selectedStudentPortalClass.save(); } } return result; } catch (error) { throw new ApiError(httpStatus.BAD_REQUEST, "Bad request"); } }; const getAllResult = async (): Promise<Array<IResult>> => { try { const results = await Result.find(); return results; } catch (error) { throw new ApiError( httpStatus.INTERNAL_SERVER_ERROR, "Internal server error" ); } }; const getResultById = async (id: string): Promise<IResult | null> => { try { const result = await Result.findOne({ _id: id }); if (!result) { throw new ApiError(httpStatus.NOT_FOUND, "Result not found"); } return result; } catch (error) { throw new ApiError( httpStatus.INTERNAL_SERVER_ERROR, "Internal server error" ); } }; const getResultsByClass = async (classes: string): Promise<Array<IResult>> => { try { const results = await Result.find({ class: classes }); return results; } catch (error) { throw new ApiError( httpStatus.INTERNAL_SERVER_ERROR, "Internal server error" ); } }; const updateResultById = async ( id: string, payload: IResult ): Promise<IResult | null> => { try { const result = await Result.findOneAndUpdate( { _id: id }, { ...payload }, { new: true, } ); return result; } catch (error) { throw new ApiError( httpStatus.INTERNAL_SERVER_ERROR, "Internal server error" ); } }; const deleteResultById = async (id: string): Promise<IResult | null> => { try { const result = await Result.findByIdAndDelete(id); return result; } catch (error) { throw new ApiError( httpStatus.INTERNAL_SERVER_ERROR, "Internal server error" ); } }; export const ResultService = { createResult, getAllResult, getResultById, updateResultById, deleteResultById, getResultsByClass, };
from constants import * class Timer: ''' How to use: 1: Set my duration 2: Call my update to start counting 3: When time is up, I will call your callback What will happen: 1: Timer is incremented on every frame 2: When reaches end, it will reset the timer to 0 ''' def __init__(self, duration): self.timer = 0 self.duration = duration # Callbacks self.listener_end = [] def add_event_listener(self, value, event): if event == "timer_end": self.listener_end.append(value) def reset(self): self.timer = 0 def update(self, dt): self.timer += dt if self.timer > self.duration: self.timer = 0 for callback in self.listener_end: callback()
import * as t from "io-ts"; import { pipe } from "fp-ts/function"; import * as RE from "fp-ts/lib/ReaderEither"; import { sequenceS } from "fp-ts/lib/Apply"; import { PdvTokenizerConfig, getPdvTokenizerConfigFromEnvironment, } from "@io-sign/io-sign/infra/pdv-tokenizer/config"; import { IOServicesConfig, getIoServicesConfigFromEnvironment, } from "@io-sign/io-sign/infra/io-services/config"; import { EventHubConfig, getEventHubsConfigFromEnvironment, } from "@io-sign/io-sign/infra/azure/event-hubs/config"; import { StorageConfig, getStorageConfigFromEnvironment, } from "../infra/azure/storage/config"; import { CosmosConfig, getCosmosConfigFromEnvironment, } from "../infra/azure/cosmos/config"; import { getSelfCareConfigFromEnvironment, SelfCareConfig, } from "../infra/self-care/config"; import { getSlackConfigFromEnvironment, SlackConfig, } from "../infra/slack/config"; import { getBackOfficeConfigFromEnvironment, BackOfficeConfig, } from "../infra/back-office/config"; export const Config = t.type({ azure: t.type({ storage: StorageConfig, cosmos: CosmosConfig, eventHubs: EventHubConfig, }), pagopa: t.type({ tokenizer: PdvTokenizerConfig, ioServices: IOServicesConfig, selfCare: SelfCareConfig, }), slack: SlackConfig, backOffice: BackOfficeConfig, }); export type Config = t.TypeOf<typeof Config>; export const getConfigFromEnvironment: RE.ReaderEither< NodeJS.ProcessEnv, Error, Config > = pipe( sequenceS(RE.Apply)({ storage: getStorageConfigFromEnvironment, cosmos: getCosmosConfigFromEnvironment, tokenizer: getPdvTokenizerConfigFromEnvironment, ioServices: getIoServicesConfigFromEnvironment, selfCare: getSelfCareConfigFromEnvironment, eventHubs: getEventHubsConfigFromEnvironment, slack: getSlackConfigFromEnvironment, backOffice: getBackOfficeConfigFromEnvironment, }), RE.map((config) => ({ azure: { storage: config.storage, cosmos: config.cosmos, eventHubs: config.eventHubs, }, pagopa: { tokenizer: config.tokenizer, ioServices: config.ioServices, selfCare: config.selfCare, }, slack: config.slack, backOffice: config.backOffice, })) );
import fs from 'fs/promises'; import { TRANSCODING_DIR, TRANSCODING_RESOLUTIONS } from '../config/videos'; import { ResolutionStatus as Status, ProcessingStatus } from '@prisma/client'; import { updatePreview, updateThumbnail, updateTranscodingStatus, updateProcessingStatus, updateDuration } from '../services/videos.service'; import ffmpeg from '../config/ffmpeg'; import { FfprobeData } from 'fluent-ffmpeg'; import s3 from '../config/s3'; import { PutObjectCommand } from '@aws-sdk/client-s3'; import env from '../config/env'; /* Transcode files to all available resolutions and update file status */ const transcodeVideo = async (inputFilePath: string, fileId: string) => { try { await fs.mkdir(`${TRANSCODING_DIR}/${fileId}`); await fs.writeFile( `${TRANSCODING_DIR}/${fileId}/master.m3u8`, '#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-PLAYLIST-TYPE:VOD\n' ); const duration = await getDuration(inputFilePath); await updateDuration(fileId, duration); await createThumbnail(inputFilePath, fileId); await uploadFile(fileId, 'thumbnail.png'); await updateThumbnail( fileId, `${env.AWS_S3_BUCKET}/videos/${fileId}/thumbnail.png` ); await createPreview(inputFilePath, fileId); await uploadFile(fileId, 'preview.mp4'); await updatePreview( fileId, `${env.AWS_S3_BUCKET}/videos/${fileId}/preview.mp4` ); const resolutions = await getAvailableReslutions(inputFilePath); for (const resolution of resolutions) { await updateTranscodingStatus(fileId, resolution, Status.NotStarted); } for (const resolution of resolutions) { try { await updateTranscodingStatus(fileId, resolution, Status.Transcoding); await transcodeSync(inputFilePath, fileId, resolution); await updateManifest(fileId, resolution); await updateTranscodingStatus(fileId, resolution, Status.Uploading); await uploadToS3(fileId); await uploadManifest(fileId); await updateTranscodingStatus(fileId, resolution, Status.Completed); } catch (e) { await updateTranscodingStatus(fileId, resolution, Status.Failed); throw new Error('Transcoding failed'); } } await uploadFile(fileId, 'master.m3u8'); await fs.rmdir(`${TRANSCODING_DIR}/${fileId}`); await updateProcessingStatus(fileId, ProcessingStatus.Completed); await fs.unlink(inputFilePath); console.log('Uploaded to S3'); } catch (e) { console.log(e); await updateProcessingStatus(fileId, ProcessingStatus.Failed); } }; /* Transcode video to specified resolution preserving aspect ratio, compress it, limit FPS to 30 and encode it to hls */ const transcodeSync = ( inputFilePath: string, fileId: string, resolution: number ) => { return new Promise((resolve, reject) => { ffmpeg(inputFilePath) .addOption('-f hls') .addOption('-hls_time 6') .addOption('-hls_list_size 0') .addOption('-vcodec libx264') .addOption('-g 30') .addOption('-preset ultrafast') .addOption('-crf 28') .addOption(`-vf scale=-2:${resolution}`) .output(`${TRANSCODING_DIR}/${fileId}/${resolution}p.m3u8`) .on('start', () => { console.log(`Transcoding ${inputFilePath} to ${resolution}p STARTED!`); }) .on('error', (err) => { console.log(`Transcoding to ${resolution}p ERROR!`); reject(err); }) .on('end', () => { console.log(`Transcoding ${inputFilePath} to ${resolution}p DONE!`); resolve(true); }) .on('progress', (progress) => { console.log( `progress: ${inputFilePath} to ${resolution}p`, progress.percent as number ); }) .run(); }); }; /* Take a screenshot from a video to create thumbnail */ const createThumbnail = async (inputFilePath: string, fileId: string) => { return new Promise((resolve, reject) => { ffmpeg(inputFilePath) .screenshot({ count: 1, folder: `${TRANSCODING_DIR}/${fileId}`, size: '480x270', filename: 'thumbnail.png' }) .on('error', (err) => { reject(err); }) .on('end', () => { resolve(true); }); }); }; const uploadFile = async (fileId: string, fileName: string) => { const filePath = `${TRANSCODING_DIR}/${fileId}/${fileName}`; const fileStream = await fs.readFile(filePath); const params = { Bucket: 'videos', Key: `videos/${fileId}/${fileName}`, Body: fileStream }; try { await s3.send(new PutObjectCommand(params)); } catch (e) { console.log(e); throw new Error('Upload to S3 failed'); } finally { await fs.unlink(`${TRANSCODING_DIR}/${fileId}/${fileName}`); } }; /* Get information about video */ export const probeFile = (inputFilePath: string): Promise<FfprobeData> => { return new Promise((resolve, reject) => { ffmpeg(inputFilePath).ffprobe(function (err, data) { if (err) reject(err); else resolve(data); }); }); }; /* Get list of available resolutions */ export const getAvailableReslutions = async ( inputFilePath: string ): Promise<number[]> => { const data = await probeFile(inputFilePath); const videoStream = data.streams.find((s) => s.codec_type === 'video'); if (!videoStream) throw new Error('Video stream not found'); const height = videoStream.height as number; return TRANSCODING_RESOLUTIONS.filter((r) => r <= height); }; export const getDuration = async (inputFilePath: string): Promise<number> => { const data = await probeFile(inputFilePath); const videoStream = data.streams.find((s) => s.codec_type === 'video'); if (!videoStream) throw new Error('Video stream not found'); const duration = parseInt(videoStream.duration as string); return duration; }; /* Append information about current resolution to master.m3u8 */ export const updateManifest = async (fileId: string, resolution: number) => { const outputProbeData = await probeFile( `${TRANSCODING_DIR}/${fileId}/${resolution}p.m3u8` ); const videoData = outputProbeData.streams[0]; await fs.appendFile( `${TRANSCODING_DIR}/${fileId}/master.m3u8`, `#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=${videoData.height}00,RESOLUTION=${videoData.width}x${videoData.height}\n${resolution}p.m3u8\n` ); }; /* Upload transcoded files to S3 */ const uploadToS3 = async (fileId: string) => { const files = await fs.readdir(`${TRANSCODING_DIR}/${fileId}`); for (const file of files) { if (file === 'master.m3u8') continue; await uploadFile(fileId, file); } }; const uploadManifest = async (fileId: string) => { const filePath = `${TRANSCODING_DIR}/${fileId}/master.m3u8`; const fileStream = await fs.readFile(filePath); const params = { Bucket: 'videos', Key: `videos/${fileId}/master.m3u8`, Body: fileStream }; try { await s3.send(new PutObjectCommand(params)); } catch (e) { console.log(e); throw new Error('Upload to S3 failed'); } }; /* Create preview */ const createPreview = (inputFilePath: string, fileId: string) => { return new Promise((resolve, reject) => { ffmpeg(inputFilePath) .inputOptions(['-ss 3']) .outputOptions(['-t 3']) .addOption('-vf scale=480:-2') .noAudio() .output(`${TRANSCODING_DIR}/${fileId}/preview.mp4`) .on('start', () => { console.log('Preview STARTED!'); }) .on('error', (err) => { console.log('Preview ERROR!'); reject(err); }) .on('end', () => { console.log('Preview DONE!'); resolve(true); }) .run(); }); }; export default transcodeVideo;
package xyz.stylianosgakis.shape.android.core.designsystem.icons import androidx.annotation.DrawableRes import androidx.compose.material3.Icon import androidx.compose.material3.LocalContentColor import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.painterResource sealed interface ShapeIcon { @Immutable class ImageVectorIcon(val imageVector: ImageVector) : ShapeIcon @Immutable class DrawableResourceIcon(@DrawableRes val id: Int) : ShapeIcon companion object { operator fun invoke(imageVector: ImageVector): ShapeIcon { return ImageVectorIcon(imageVector) } operator fun invoke(@DrawableRes id: Int): ShapeIcon { return DrawableResourceIcon(id) } } } @Composable fun ShapeIcon( icon: ShapeIcon, modifier: Modifier = Modifier, tint: Color = LocalContentColor.current, ) { when (icon) { is ShapeIcon.ImageVectorIcon -> Icon( imageVector = icon.imageVector, contentDescription = null, modifier = modifier, tint = tint, ) is ShapeIcon.DrawableResourceIcon -> Icon( painter = painterResource(icon.id), contentDescription = null, modifier = modifier, tint = tint, ) } }
package com.example.roomtodolist.domain.main_activity import android.util.Log import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.ui.graphics.Color import com.example.roomtodolist.R import com.example.roomtodolist.data.folder.FolderDAO import com.example.roomtodolist.data.folder.FolderTable import com.example.roomtodolist.data.task.TaskDAO import com.example.roomtodolist.data.task.TaskTable import kotlinx.coroutines.Job import kotlinx.coroutines.delay class TaskManager(private val folderDAO: FolderDAO,private val taskDAO: TaskDAO) { private var hasInitialized = false private val completedTasks = hashMapOf<Long, Job>() val tasks = mutableStateMapOf<Long, TaskTable>() val tasksPerFolder = mutableStateMapOf<FolderTable, SnapshotStateList<TaskTable>>() val folders : Map<Long, FolderTable> get() { val map = mutableMapOf<Long, FolderTable>() for (each in tasksPerFolder.keys) { map[each.id!!] = each } return map } var folderToUpdate: FolderTable? = null private set var taskToUpdate: TaskTable? = null private set suspend fun init() { if (hasInitialized) return hasInitialized = true for (folder in folderDAO.getFolders()) { val tasksInFolder = taskDAO.getTasksFromFolder(folder.id!!) folder.taskCounts = tasksInFolder.size tasksPerFolder[folder] = mutableStateListOf() tasksPerFolder[folder]!!.addAll(tasksInFolder) for (task in tasksInFolder) { tasks [task.id!!] = task } } } private fun getFolderByKey(folderId : Long) : FolderTable? { for (folder in tasksPerFolder.keys) if (folderId == folder.id) return folder return null } suspend fun addFolder(folder: FolderTable) : FolderTable { val generatedId = folderDAO.addFolder(folder) val newFolder = folder.copy(id = generatedId) tasksPerFolder[newFolder] = mutableStateListOf() return newFolder } fun setFolderToUpdate(folder: FolderTable) { folderToUpdate = folder } fun clearFolderToUpdate() { folderToUpdate = null } suspend fun updateFolder(folder: FolderTable) { folderDAO.updateFolder(folder) val oldFolder = getFolderByKey(folderId = folder.id!!) val oldTaskList = tasksPerFolder[oldFolder] tasksPerFolder.remove(oldFolder) tasksPerFolder[folder] = oldTaskList ?: mutableStateListOf() } suspend fun deleteFolder(folder: FolderTable) { folderDAO.deleteFolder(folderId = folder.id!!) val oldFolder = getFolderByKey(folder.id) tasksPerFolder.remove(oldFolder) } fun getFolderColors() = folderColors fun getFolderAssets() = folderAssets suspend fun addTask(task: TaskTable) : TaskTable { val generatedId = taskDAO.addTask(task) val newTask = task.copy(id = generatedId) tasks[generatedId] = newTask val folder = getFolderByKey(task.folder) val oldTasksInFolder = tasksPerFolder[folder] oldTasksInFolder!!.add(newTask) tasksPerFolder.remove(folder) folder!!.taskCounts ++ tasksPerFolder[folder] = oldTasksInFolder return newTask } fun setTaskToUpdate(task: TaskTable) { taskToUpdate = task } fun clearTaskToUpdate() { taskToUpdate = null } suspend fun updateTask(task: TaskTable) { taskDAO.updateTask(task) if (tasks[task.id]!!.folder == task.folder) { val folder = getFolderByKey(task.folder) for (taskIndex in tasksPerFolder[folder]!!.indices) { if (tasksPerFolder[folder]!![taskIndex].id == task.id) { tasksPerFolder[folder]!![taskIndex] = task break } } } else { val oldFolder = getFolderByKey(tasks[task.id!!]!!.folder) val oldList = tasksPerFolder[oldFolder]!! tasksPerFolder.remove(oldFolder) for (taskIndex in oldList.indices) { if (oldList[taskIndex].id == task.id) { oldList.removeAt(taskIndex) oldFolder!!.taskCounts -- tasksPerFolder[oldFolder] = oldList break } } val newFolder = getFolderByKey(task.folder) val newList = tasksPerFolder[newFolder]!! newList.add(task) tasksPerFolder.remove(newFolder) newFolder!!.taskCounts ++ tasksPerFolder[newFolder] = newList } tasks[task.id!!] = task } suspend fun deleteTask(task: TaskTable) { taskDAO.deleteTask(taskId = task.id!!) tasks.remove(task.id) val folder = getFolderByKey(task.folder) val oldTasksInFolder = tasksPerFolder[folder] oldTasksInFolder!!.remove(task) tasksPerFolder.remove(folder) folder!!.taskCounts -- tasksPerFolder[folder] = oldTasksInFolder } suspend fun selectTask(task: TaskTable, job: Job) { if (completedTasks.containsKey(task.id)) { completedTasks[task.id]!!.cancel() completedTasks.remove(task.id) } else { completedTasks[task.id!!] = job delay(5000) deleteTask(task) completedTasks.remove(task.id) } } private val folderColors: List<Color> = mutableListOf( Color(0xFFFF0000), Color(0xFFFF5100), Color(0xFF37FF00), Color(0xFF00FFFF), Color(0xFF0800FF), Color(0xFF9500FF), Color(0xFFFF0084), ) private val folderAssets: Map<Int, Int> = hashMapOf( R.drawable.yoga_asset to R.drawable.yoga_asset_primary, R.drawable.cooking_asset to R.drawable.cooking_asset_primary, R.drawable.working_asset to R.drawable.working_asset_primary, R.drawable.diy_asset to R.drawable.diy_asset_primary, R.drawable.shopping_asset to R.drawable.shopping_asset_primary, R.drawable.nature_asset to R.drawable.nature_asset_primary, R.drawable.choosing_asset to R.drawable.choosing_asset_primary, R.drawable.familly_asset to R.drawable.familly_asset_primary, R.drawable.diversity_asset to R.drawable.diversity_asset_primary, R.drawable.homework_asset to R.drawable.homework_asset_primary, ) }
import 'package:flutter/material.dart'; import 'package:food_mario/utils/extensions/extensions.dart'; import 'package:get/get.dart'; import 'package:sizer/sizer.dart'; import '../constants/colors.dart'; import '../utils/style/style.dart'; // ignore: must_be_immutable class CustomButtonModule extends StatelessWidget { Function() onPress; String labelText; Color buttonColor; Color textColor; double? labelSize; CustomButtonModule({ Key? key, required this.onPress, required this.labelText, this.buttonColor = AppColors.blackColor, this.textColor = AppColors.whiteColor, this.labelSize, }) : super(key: key); @override Widget build(BuildContext context) { return Center( child: SizedBox( // height: 50, width: Get.width, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: buttonColor, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30), ), ), onPressed: onPress, child: Text( labelText, style: TextStyleConfig.textStyle( textColor: textColor, fontSize: labelSize ?? 13.sp, ), ).commonSymmetricPadding(vertical: 10), ), ), ); } } class CustomSubmitButtonModule extends StatelessWidget { Function() onPress; String labelText; Color buttonColor; Color textColor; double? labelSize; CustomSubmitButtonModule({ Key? key, required this.onPress, required this.labelText, this.buttonColor = AppColors.blackColor, this.textColor = AppColors.whiteColor, this.labelSize, }) : super(key: key); @override Widget build(BuildContext context) { return Center( child: SizedBox( // height: 50, width: Get.width, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: buttonColor, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10), ), ), onPressed: onPress, child: Text( labelText, style: TextStyleConfig.textStyle( textColor: textColor, fontSize: labelSize ?? 14.sp, ), ).commonSymmetricPadding(vertical: 15), ), ), ); } }
import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterLink } from '@angular/router'; import { Store } from '@ngrx/store'; import { userActions } from '../../state/actions/user.action'; import { Observable } from 'rxjs'; import { User } from '../../../../../shared/interfaces/user.interface'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { LoaderComponent } from '../../../../../components/loader/loader.component'; import { requestConformation } from '../../../../../store/actions/confirm'; import { userFeature } from '../../state/features/user.feature'; @Component({ selector: 'app-users-view', standalone: true, imports: [CommonModule, RouterLink, MatButtonModule, MatIconModule, LoaderComponent], templateUrl: './users-view.component.html', styleUrls: ['./users-view.component.scss'] }) export class UsersViewComponent implements OnInit { users$: Observable<User[]> = this.store.select(userFeature.selectAllUsers); showLoader: Observable<boolean> = this.store.select(userFeature.selectUserListLoader); constructor(private readonly store: Store) { } ngOnInit(): void { this.store.dispatch(userActions.loadUsers()); } public addUser(): void { this.store.dispatch(userActions.openUserDialog({user: null})); } public editUser(user: User): void { this.store.dispatch(requestConformation({ titles: { title: 'Do you want to edit this User', btnConfirm: 'Yes Edit' }, confirm: userActions.openUserDialog({user: user })})); } public removeUser(id: number): void { this.store.dispatch(requestConformation({ titles: { title: 'Do you want to remove this User', btnConfirm: 'Yes Delete' }, confirm: userActions.removeUser({userId: id}) })); } }
import path from "path"; import { expect } from "chai"; import { describe, it } from "mocha"; import balanceReducer, { getInitialState, loadBalance, loadSingleWalletBalance } from "redux/slices/balanceSlice"; describe(path.relative(process.cwd(), __filename), () => { it("should return initial state", () => { expect(getInitialState("balance", "singleWalletBalance")).to.be.deep.equal({ balance: "balance", error: null, loading: false, singleWalletBalance: "singleWalletBalance", }); }); it("should update state when action type is `loadBalance.pending`", () => { expect(balanceReducer({}, loadBalance.pending())).to.be.deep.equal({ error: null, loading: true, }); }); it("should update state when action type is `loadBalance.rejected`", () => { expect(balanceReducer({}, loadBalance.rejected({ message: "message" }))).to.be.deep.equal({ error: "message", loading: false, }); }); it("should update state when action type is `loadBalance.fulfilled`", () => { expect( balanceReducer( { balance: "balance", error: "message", loading: true, }, loadBalance.fulfilled({ balance: "balance-1" }), ), ).to.be.deep.equal({ balance: "balance-1", error: null, loading: false, }); }); it("should update state when action type is `loadSingleWalletBalance.pending`", () => { expect(balanceReducer({}, loadSingleWalletBalance.pending())).to.be.deep.equal({ error: null, loading: true, }); }); it("should update state when action type is `loadSingleWalletBalance.rejected`", () => { expect(balanceReducer({}, loadSingleWalletBalance.rejected({ message: "message" }))).to.be.deep.equal({ error: "message", loading: false, }); }); it("should update state when action type is `loadSingleWalletBalance.fulfilled`", () => { expect( balanceReducer( { balance: "balance", error: "message", loading: true, singleWalletBalance: "singleWalletBalance", }, loadSingleWalletBalance.fulfilled({ singleWalletBalance: "singleWalletBalance-1" }), ), ).to.be.deep.equal({ balance: "balance", error: null, loading: false, singleWalletBalance: "singleWalletBalance-1", }); }); it("shouldn't update state when action type is `undefined`", () => { expect(balanceReducer({}, { type: undefined })).to.be.deep.equal({}); }); });
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QPushButton, QLabel, QSpacerItem, QSizePolicy from PyQt5.QtGui import QPalette, QColor, QIcon from PyQt5.QtCore import Qt class CustomTitleBar(QWidget): def __init__(self, parent=None): super().__init__(parent) self.setAutoFillBackground(True) palette = self.palette() palette.setColor(QPalette.Background, QColor(53, 53, 53)) self.setPalette(palette) self.m_mouse_down = False self.m_old_pos = None self.initUI() def initUI(self): self.setAutoFillBackground(True) self.setFixedHeight(32) layout = QHBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) self.title_label = QLabel('Tube Expansion Alpha') self.title_label.setStyleSheet("QLabel { color : white; }") btn_size = 32 # Cross Button self.btn_close = QPushButton('') self.btn_close.clicked.connect(self.btn_close_clicked) self.btn_close.setFixedSize(btn_size, btn_size) self.btn_close.setIcon(QIcon('GUI/Icons/cross_icon.png')) # Minimize Button self.btn_min = QPushButton('') self.btn_min.clicked.connect(self.btn_min_clicked) self.btn_min.setFixedSize(btn_size, btn_size) self.btn_min.setIcon(QIcon('GUI/Icons/minimize_icon.png')) # Maximize/Restore Button self.btn_max = QPushButton('') self.btn_max.clicked.connect(self.btn_max_clicked) self.btn_max.setFixedSize(btn_size, btn_size) self.btn_max.setIcon(QIcon('GUI/Icons/Maximize_icon.png')) self.max_icon = QIcon('GUI/Icons/Maximize_icon.png') self.restore_icon = QIcon('GUI/Icons/Restore_down_icon.png') self.btn_max.setIcon(self.max_icon) layout.addWidget(self.title_label) layout.addItem(QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)) layout.addWidget(self.btn_min) layout.addWidget(self.btn_max) layout.addWidget(self.btn_close) def btn_max_clicked(self): if self.parent().isMaximized(): self.parent().showNormal() self.btn_max.setIcon(self.max_icon) # Set icon to maximize else: self.parent().showMaximized() self.btn_max.setIcon(self.restore_icon) # Set icon to restore def mousePressEvent(self, event): self.m_old_pos = event.pos() self.m_mouse_down = event.button() == Qt.LeftButton # When mouse is pressed, record whether the window is maximized self.m_was_maximized = self.parent().isMaximized() if self.m_was_maximized: # Store global mouse position when the user starts dragging the window self.m_global_mouse_pos = event.globalPos() def mouseMoveEvent(self, event): x = event.x() y = event.y() if self.m_mouse_down: parent = self.parent() if self.m_was_maximized: # When the window is maximized and the user starts dragging, we should 'restore down' the window # and calculate the new position of the window. parent.showNormal() self.btn_max.setIcon(self.max_icon) # Set icon to maximize # Calculate ratio of mouse position in relation to window size ratio = self.m_old_pos.x()/self.width() # Calculate new x position for the window and ensure it's an integer # Now, instead of aligning the mouse to the old position in the title bar, # we align it to the center of the window new_x = int(event.globalPos().x() - self.width() / 2) new_y = int(event.globalPos().y() - self.m_old_pos.y()) parent.move(new_x, new_y) else: parent.move(parent.x() + x - self.m_old_pos.x(), parent.y() + y - self.m_old_pos.y()) def mouseReleaseEvent(self, event): self.m_mouse_down = False # If the mouse is released at the top of the screen, maximize the window if event.globalPos().y() == 0: self.parent().showMaximized() self.btn_max.setIcon(self.restore_icon) # Set icon to restore def btn_close_clicked(self): self.parent().close() def btn_min_clicked(self): self.parent().showMinimized()
package com.example.yevydpochynok.models import kotlinx.serialization.Serializable @Serializable data class Place ( val id: String, val name: String, val description: String, val rating: Float, val website: String?, val address: String, val contact: String?, val parking: Boolean, val animalsAllowed: Boolean, val paidVisit: Boolean, val wc: Boolean, val finePlaced: Boolean, val handicapAccessibility: Boolean, val hours: Array<Day>?, val images: Array<String>, val location: String, val longitude: String, val latitude: String, val city: String, val subscriptionPlan: String, val active: Boolean )
// // Date+Base.swift // // // Created by kim sunchul on 2022/05/26. // import Foundation public extension Date { init(from string: String, format: String, locale: Locale = .current) { let dateFormatter: DateFormatter = .init() dateFormatter.dateFormat = format dateFormatter.calendar = Calendar(identifier: .gregorian) dateFormatter.locale = locale guard let date = dateFormatter.date(from: string) else { self = .init() return } self = date } var year: Int { return Calendar.current.component(.year, from: self) } var month: Int { return Calendar.current.component(.month, from: self) } var day: Int { return Calendar.current.component(.day, from: self) } var hour: Int { return Calendar.current.component(.hour, from: self) } var second: Int { return Calendar.current.component(.second, from: self) } var isToday: Bool { return Calendar.current.isDateInToday(self) } var isYesterDay: Bool { return Calendar.current.isDateInYesterday(self) } func isGreaterThanDate(_ date: Date) -> Bool { return self.compare(date) == ComparisonResult.orderedDescending } func isLessThanDate(_ date: Date) -> Bool { return self.compare(date) == ComparisonResult.orderedAscending } func isEqualToDate(date: Date) -> Bool { return self.compare(date) == ComparisonResult.orderedSame } func formattedString(format: String, locale: Locale = .current) -> String { let dateFormatter: DateFormatter = .init() dateFormatter.dateFormat = format dateFormatter.calendar = .init(identifier: .gregorian) dateFormatter.locale = locale return dateFormatter.string(from: self) } func difference(endDate: Date) -> DateComponents { return Calendar.current.dateComponents( [.year,.month,.day,.hour, .second], from: self, to: endDate ) } }
import express from "express"; import dotenv from "dotenv"; import mongoose from "mongoose"; //---------------------------------------------------------- import authRoute from "./routes/auth.js"; import hotelsRoute from "./routes/hotels.js"; import roomsRoute from "./routes/rooms.js"; import usersRoute from "./routes/users.js"; //--------------------------------------------------------- const app = express() dotenv.config() const connect = async () => { try { await mongoose.connect(process.env.MONGO); console.log("Connected to mongo DB"); } catch (error) { throw error; } }; mongoose.connection.on("connected", ()=>{ console.log("Connected to backend with MONGO DB"); }) mongoose.connection.on("disconnected", ()=>{ console.log("Disconnected from MONGO DB, but connected to backend"); }) app.get("/", (req,res) =>{ res.send("Hello from request respopnse") }) app.get("/users", (req,res) =>{ res.send("Hello from request respopnse - by users") }) app.use(express.json()) app.use("/api/auth", authRoute) app.use("/api/users", usersRoute) app.use("/api/rooms", roomsRoute) app.use("/api/hotels", hotelsRoute) app.use((err, req, res, next)=>{ const errorStatus = err.status || 500 const errorMessage = err.message || "Something went wrong" return res.status(errorStatus).json({ success: false, status: errorStatus, message: errorMessage, stack: err.stack }); }); app.listen(8800, ()=>{ connect() console.log("Connected to backend with express"); })
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ChatService } from '../Services/chat.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { userForm : FormGroup = new FormGroup({}); submitted = false; apiErrorMessage: string[] = []; openChat = false; constructor(private formBuilder: FormBuilder, private chatService: ChatService) { } ngOnInit(): void { this.initialzeForm(); } initialzeForm(){ this.userForm = this.formBuilder.group({ name: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(15)]] }) } submitForm(){ this.submitted = true; this.apiErrorMessage = []; if (this.userForm.valid){ this.chatService.registerUser(this.userForm.value).subscribe({ next: () => { this.chatService.myName = this.userForm.get('name')?.value; this.openChat = true; this.userForm.reset(); this.submitted=false; }, error : error => { if (typeof (error.error) !== 'object') { this.apiErrorMessage.push(error.error); } } }) } } closeChat() { this.openChat = false; } }
import React, { useState } from "react"; import Link from "next/link"; import { useRouter } from "next/router"; import { AiOutlineShopping, AiOutlineSearch, AiOutlineMenu, handleDropdownToggle, } from "react-icons/ai"; import { Cart, Cartegories } from "./"; import { useStateContext } from "../context/StateContext"; const ScrollingNavbar = ({ visible, scrollTop }) => { const { showCart, setShowCart, totalQuantities, handleDropdownToggle, isDropdownOpen, setIsDropdownOpen, } = useStateContext(); return ( <div className={`${ scrollTop <= 250 ? "hidden" : "lg:block fixed top-0 left-0 w-full " }transition duration-500 ease-in-out bg-white w-full mt-0 hidden ${ visible ? "opacity-100 translate-y-0 absolute z-[9999]" : "opacity-0 translate-y-full" }`} > <div className="flex flex-col w-full "> <div className="flex items-center justify-between border-b border-gray-300 py-4 px-12"> <h1 className="logo text-2xl font-bold hover:scale-110 transition-all duration-300"> <Link href={"/"}>Detroit Store</Link> </h1> <div className="flex justify-between items-center "> <div className="flex gap-8 items-center links"> <Link href={"/kitchen"}> <h3 className="font-bold text-black text-sm hover:text-gray-700"> KITCHEN GADGETS </h3> </Link> <Link href={"/home-stuffs"} className="font-medium hover:text-gray-900" > <h3 className="font-bold text-black text-sm hover:text-gray-700"> HOME STUFFS </h3> </Link> <Link href={"/"} className="font-medium hover:text-gray-900"> <h3 className="font-bold text-black text-sm hover:text-gray-700"> GIFT IDEAS </h3> </Link> <Link href={"/car-accessories"} className="font-medium hover:text-gray-900" > <h3 className="font-bold text-black text-sm hover:text-gray-700"> CAR ACCESSORIES </h3> </Link> <Link href={"/dashboard"} className="font-medium hover:text-gray-900" > <h3 className="font-bold text-black text-sm hover:text-gray-700"> TRACK YOUR ORDER </h3> </Link> </div> </div> <div className="gap flex justify-center items-center "> <button type="button" className="cart-icon" onClick={() => setShowCart(!showCart)} > <AiOutlineShopping /> <span className="absolute text-[#eee] bg-[#f02d34] text-xs w-4 h-4 rounded-lg text-center font-semibold top-1 right-[-6px]"> {totalQuantities} </span> </button> </div> </div> </div> </div> ); }; export default ScrollingNavbar;
package com.cattsoft.baseplatform.func.sm.service; import java.sql.Timestamp; import java.util.List; import net.sf.json.JSONArray; import org.apache.commons.lang.StringUtils; import org.springframework.transaction.annotation.Transactional; import com.cattsoft.baseplatform.core.entity.PagingQueryBean; import com.cattsoft.baseplatform.core.entity.PagingResultBean; import com.cattsoft.baseplatform.core.exception.AuthenticationException; import com.cattsoft.baseplatform.core.exception.ServiceException; import com.cattsoft.baseplatform.core.util.DateUtil; import com.cattsoft.baseplatform.func.sm.component.FunctionComponent; import com.cattsoft.baseplatform.func.sm.component.SysUserComponent; import com.cattsoft.baseplatform.func.sm.entity.FuncNode; import com.cattsoft.baseplatform.func.sm.entity.FuncTree; import com.cattsoft.baseplatform.func.sm.entity.Staff; import com.cattsoft.baseplatform.func.sm.entity.SysUser; import com.cattsoft.baseplatform.func.sm.entity.query.SysUserQuery; import com.cattsoft.baseplatform.func.sm.util.SysConstants; @Transactional public class SysUserServiceImpl implements SysUserService { private SysUserComponent sysUserComponent; private FunctionComponent functionComponent; public void setSysUserComponent(SysUserComponent sysUserComponent) { this.sysUserComponent = sysUserComponent; } public void setFunctionComponent(FunctionComponent functionComponent) { this.functionComponent = functionComponent; } @Transactional(readOnly = true) @Override public List<FuncTree> loadFuncTree() { return this.functionComponent.initFuncTree(); } @Transactional(readOnly = true) @Override public PagingResultBean<List<SysUser>> getSysUserPaging(PagingQueryBean<SysUserQuery> qb) { SysUserQuery sysUserQuery = qb.getQueryBean(); if (StringUtils.isBlank(sysUserQuery.getOwnerType())) { throw new ServiceException("未指定用户使用者类型"); } if (!SysConstants.SysUser.OwnerType.DEPT.equals(sysUserQuery.getOwnerType()) && !SysConstants.SysUser.OwnerType.STAFF.equals(sysUserQuery.getOwnerType())) { throw new ServiceException("指定的用户使用者类型异常"); } // 将空串、空白串转为null,不影响mapper的判断 if (StringUtils.isBlank(sysUserQuery.getLoginName())) { sysUserQuery.setLoginName(null); } if (StringUtils.isBlank(sysUserQuery.getOwnerName())) { sysUserQuery.setOwnerName(null); } // 用户资料维护的隐式查询条件 sysUserQuery.setSts(SysConstants.Status.STS_A); sysUserQuery.setUserExpTime(DateUtil.getCurrentTimestamp()); return this.sysUserComponent.getSysUserPaging(qb); } @Override public Long createSysUser(SysUser sysUser, String ownerType, String ownerId, Staff staff) { if (!SysConstants.SysUser.OwnerType.DEPT.equals(ownerType) && !SysConstants.SysUser.OwnerType.STAFF.equals(ownerType)) { throw new ServiceException("用户使用者类型异常"); } if (!StringUtils.isBlank(ownerId) && staff != null) { throw new ServiceException("用户使用者为新员工,入参ownerId只能为空"); } Timestamp time = DateUtil.getCurrentTimestamp(); if (staff != null) { staff.setSts(SysConstants.Status.STS_A); staff.setStsTime(time); staff.setCreateTime(time); } // 只能创建普通用户 sysUser.setUserType(SysConstants.SysUser.UserType.COMMON); if (StringUtils.isBlank(sysUser.getPassword())) { sysUser.setPassword(SysConstants.INIT_PASSWORD); } if (null == sysUser.getPwdExpTime()) { sysUser.setPwdExpTime(DateUtil.addMonth(time, 3)); } sysUser.setSts(SysConstants.Status.STS_A); sysUser.setStsTime(time); sysUser.setCreateTime(time); return this.sysUserComponent.createSysUser(sysUser, ownerType, ownerId, staff); } @Transactional(readOnly = true) @Override public SysUser getSysUser(Long userId) { return this.sysUserComponent.getSysUser(userId); } @Transactional(readOnly = true) @Override public SysUser getSysUserByName(String loginName) { if (StringUtils.isBlank(loginName)) { throw new ServiceException("未指定登录名称,无法查询用户信息"); } return this.sysUserComponent.getSysUserByName(loginName); } @Transactional(readOnly = true) @Override public boolean loginNameBeenUsed(String loginName) { if (StringUtils.isBlank(loginName)) { throw new ServiceException("未指定登录名称,无需判定登录名称是否被使用"); } return this.sysUserComponent.loginNameBeenUsed(loginName); } @Override public void modifyUserExpTime(Long userId, Timestamp userExpTime) { this.sysUserComponent.modifyUserExpTime(userId, userExpTime); } @Override public void removeSysUser(Long userId) { this.sysUserComponent.removeSysUser(userId); } @Override public void modifyPassword(Long userId, String password, String newPassword) { if (StringUtils.isBlank(password)) { throw new ServiceException("旧密码为空,无法执行密码修改操作"); } if (StringUtils.isBlank(newPassword)) { throw new ServiceException("新密码为空,无法执行密码修改操作"); } this.sysUserComponent.modifyPassword(userId, password, newPassword); } @Override public void resetPassword(Long userId,String password) { this.sysUserComponent.resetPassword(userId,password); } @Transactional(readOnly = true) @Override public JSONArray loadRoleAuth(Long operUserId, Long userId) { return this.sysUserComponent.loadRoleAuth(operUserId, userId); } @Override public void saveUserRoleAuth(Long userId, JSONArray roleAuthInfos) { if (null == roleAuthInfos) { throw new ServiceException("未提交角色授权信息,无法保存"); } this.sysUserComponent.saveUserRoleAuth(userId, roleAuthInfos); } @Transactional(readOnly = true) @Override public JSONArray loadFuncAuth(Long operUserId, Long userId, Long nodeTreeId) { return this.sysUserComponent.loadFuncAuth(operUserId, userId, nodeTreeId); } @Override public void saveUserFuncAuth(Long userId, JSONArray funcAuthInfos) { if (null == funcAuthInfos) { throw new ServiceException("未提交功能及功能操作授权信息,无法保存"); } this.sysUserComponent.saveUserFuncAuth(userId, funcAuthInfos); } @Transactional(readOnly = true) @Override public SysUser authenticate(String loginName, String password) throws AuthenticationException { if (StringUtils.isBlank(loginName) || StringUtils.isBlank(password)) { throw new ServiceException("用户登录名称或登录密码为空,无法进行认证"); } return this.sysUserComponent.authenticate(loginName, password); } @Transactional(readOnly = true) @Override public List<FuncNode> getUserFuncInfos(Long userId) { return this.sysUserComponent.getUserFuncInfos(userId); } @Override public Long createUserShortcut(Long userId, Long funcNodeId) { if (null == userId) { throw new ServiceException("用户标识为空"); } if (null == funcNodeId) { throw new ServiceException("功能标识为空"); } return this.sysUserComponent.createUserShortcut(userId, funcNodeId); } @Override public void removeUserShortcut(Long userId, Long funcNodeId) { if (null == userId) { throw new ServiceException("用户标识为空"); } if (null == funcNodeId) { throw new ServiceException("功能标识为空"); } this.sysUserComponent.removeUserShortcut(userId, funcNodeId); } @Transactional(readOnly = true) @Override public PagingResultBean<List<SysUser>> getSysUserPaging4unfrozen( PagingQueryBean<SysUserQuery> qb) { SysUserQuery sysUserQuery = qb.getQueryBean(); if (StringUtils.isBlank(sysUserQuery.getOwnerType())) { throw new ServiceException("未指定用户使用者类型"); } if (!SysConstants.SysUser.OwnerType.DEPT.equals(sysUserQuery.getOwnerType()) && !SysConstants.SysUser.OwnerType.STAFF.equals(sysUserQuery.getOwnerType())) { throw new ServiceException("指定的用户使用者类型异常"); } // 将空串、空白串转为null,不影响mapper的判断 if (StringUtils.isBlank(sysUserQuery.getLoginName())) { sysUserQuery.setLoginName(null); } if (StringUtils.isBlank(sysUserQuery.getOwnerName())) { sysUserQuery.setOwnerName(null); } // 用户资料维护的隐式查询条件 sysUserQuery.setSts(SysConstants.Status.STS_A); /* 必须传空 */ sysUserQuery.setUserExpTime(null); return this.sysUserComponent.getSysUserPaging(qb); } @Override public void modifyUserExpTime(List<Long> userIds, Timestamp userExpTime) { for (Long userId : userIds) { this.sysUserComponent.modifyUserExpTime(userId, userExpTime); } } }
<?xml version="1.0" encoding="utf-8"?> <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/nav_view" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="0dp" android:layout_marginEnd="0dp" android:background="?android:attr/windowBackground" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:menu="@menu/bottom_nav_menu" /> <fragment android:id="@+id/nav_host_fragment_activity_main" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" app:layout_constraintBottom_toTopOf="@id/nav_view" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:navGraph="@navigation/mobile_navigation" /> <androidx.appcompat.widget.Toolbar android:id="@+id/toolBar" app:layout_constraintTop_toTopOf="parent" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:contentInsetStart="0dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:gravity="center_vertical"> <ImageButton android:id="@+id/drawerButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_menu_24" android:backgroundTint="?attr/colorPrimary" android:contentDescription="@string/open_drawer_button" /> <TextView android:id="@+id/title" android:layout_width="0dp" android:layout_height="wrap_content" android:text="@string/app_name" android:textStyle="bold" android:textSize="22sp" android:layout_weight="1" android:gravity="center"/> <AutoCompleteTextView android:id="@+id/autoCompleteTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Search..." android:visibility="gone" android:imeOptions="actionDone" android:singleLine="true"/> <ImageButton android:id="@+id/searchButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_search_24" android:background="?attr/selectableItemBackgroundBorderless" android:layout_gravity="end|center"/> </LinearLayout> </androidx.appcompat.widget.Toolbar> </androidx.constraintlayout.widget.ConstraintLayout> <com.google.android.material.navigation.NavigationView android:id="@+id/nav_drawer" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/drawer_container" android:layout_width="match_parent" android:layout_height="220dp"> <ImageView android:id="@+id/imageViewDrawer" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/background_image_login" android:scaleType="centerCrop"/> <TextView android:id="@+id/drawerTitle" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="@id/imageViewDrawer" android:gravity="center" android:text="Go4Lunch" android:textStyle="bold" android:textSize="45sp" android:textColor="#CCCCCC" android:layout_marginTop="24dp"/> <androidx.cardview.widget.CardView android:id="@+id/cardViewProfilePicture" app:layout_constraintBottom_toBottomOf="@id/imageViewDrawer" app:layout_constraintStart_toStartOf="parent" android:layout_marginBottom="24dp" android:layout_marginStart="12dp" android:layout_width="65dp" android:layout_height="65dp" android:elevation="12dp" app:cardCornerRadius="40dp" android:layout_gravity="center_horizontal" android:innerRadius="0dp" android:shape="ring" android:thicknessRatio="1.9"> <ImageView android:layout_height="match_parent" android:layout_width="match_parent" android:id="@+id/profilePictureImageView" android:layout_alignParentTop="true" android:layout_centerHorizontal="true"> </ImageView> </androidx.cardview.widget.CardView> <TextView android:id="@+id/profileName" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintStart_toEndOf="@+id/cardViewProfilePicture" app:layout_constraintTop_toTopOf="@id/cardViewProfilePicture" app:layout_constraintBottom_toTopOf="@id/textviewMail" android:layout_marginStart="8dp" android:textStyle="bold" android:textSize="20sp" android:textColor="#CCCCCC"/> <TextView android:id="@+id/textviewMail" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintStart_toEndOf="@+id/cardViewProfilePicture" app:layout_constraintTop_toBottomOf="@id/profileName" app:layout_constraintBottom_toBottomOf="@id/cardViewProfilePicture" android:layout_marginStart="8dp" android:textSize="12sp" android:textColor="#CCCCCC"/> </androidx.constraintlayout.widget.ConstraintLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/drawer_container" android:orientation="vertical"> <Button android:id="@+id/lunchButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="25dp" android:text="YOUR LUNCH"/> <Button android:id="@+id/settingButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="25dp" android:text="SETTINGS"/> <Button android:id="@+id/logoutButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="25dp" android:text="LOGOUT"/> </LinearLayout> </RelativeLayout> </com.google.android.material.navigation.NavigationView> </androidx.drawerlayout.widget.DrawerLayout>
import React, {useEffect, useState} from 'react'; import './App.module.css'; import {useAppDispatch, useAppSelector} from "./hooks/redux"; import {Todo} from "./components/Todo"; import s from './App.module.css' import {InputBlock} from "./components/InputBlock"; import {getTodos, postTodo} from "./store/redusers/todoAsyncTC"; import {ITodo} from "./store/redusers/todoTypes"; const App: React.FC = () => { const dispatch = useAppDispatch() const [isSuccessOpen, setIsSuccessOpen] = useState(true) const [isActiveOpen, setIsActiveOpen] = useState(true) const todoState = useAppSelector(state => state.todo) const todosSuccess: ITodo[] = todoState.todos.filter(todo => !todo.status) const todosActive: ITodo[] = todoState.todos.filter(todo => todo.status) const onAddTodo: (body: string) => void = async (body: string) => { await dispatch(postTodo(body)) setIsActiveOpen(true) } useEffect(() => { dispatch(getTodos()) }, []) if (todoState.isLoading) { return <div>Загрузка</div> } return ( <div className={s.App}> <div className={s.wrapper_app}> <div className={s.todos_wrapper}> <InputBlock placeHolderText={'Добавить задачу'} callbackFunction={onAddTodo}/> {todosActive.length > 0 && ( <div className={s.type}> <div onClick={() => setIsActiveOpen(!isActiveOpen)} className={s.type_name}> Активные </div> {isActiveOpen && todosActive.length > 0 && todosActive.map(todo => { return <Todo key={todo.id} todo={todo} setIsSuccessOpen={setIsSuccessOpen}/> })} </div> )} {todosSuccess.length > 0 && ( <div className={s.type}> <div onClick={() => setIsSuccessOpen(!isSuccessOpen)} className={s.type_name}> Выполненные </div> {isSuccessOpen && todosSuccess.length > 0 && todosSuccess.map(todo => { return <Todo key={todo.id} todo={todo} /> })} </div> )} </div> </div> {todoState.error && <div className={s.error}>{todoState.error}</div>} </div> ); } export default App;
// MIXINS @mixin linear-gradient($deg: -45deg, $clr-1: red, $clr-2: blue) { background-image: linear-gradient($deg, $clr-1, $clr-2); } @mixin pseudo-underline { width: 7rem; height: 1px; background-color: rgb(11, 11, 11); margin: 2rem auto; } @mixin ui-element($size, $color, $bg-color, $hover-color, $hover-bg-color) { padding: $size; color: $color; background-color: $bg-color; &:hover, &:focus { color: $hover-color; background-color: $hover-bg-color; } } body { font-family: system-ui; margin: 0; } .title { &::after { content: ""; display: block; @include pseudo-underline; } } .section-one, .section-two, .section-three { text-align: center; padding: 10vh 0; } .section-one { color: #fff; @include linear-gradient; } .section-two { color: #fff; @include linear-gradient($deg: -75deg, $clr-1: green, $clr-2: yellow); } .section-three { color: #fff; @include linear-gradient($deg: 45deg, $clr-1: purple, $clr-2: gold); } .button-one { @include ui-element(1em 3em, yellow, red, red, yellow); } .button-two { @include ui-element(0.75em 3em, blue, gray, gray, blue); } .badge-one { display: inline-block; @include ui-element(0.25em 0.75em, white, black, black, white); } .badge-two { display: inline-block; @include ui-element(0.5em 1.25em, black, white, white, black); }
import React from 'react' import { Breadcrumb, BreadcrumbItem, BreadcrumbLink } from '@chakra-ui/react' import { useRouter } from 'next/router' import { localize } from '@utils/lib/formatter' import { ChevronRightIcon } from '@components/atoms/icons' interface RoutePageDirectionProps { pagename?: string components?: any endpoint?: string } const RoutePageDirection: React.FC<RoutePageDirectionProps> = props => { const { pagename, components, endpoint } = props const router = useRouter() const { locale } = useRouter() return ( <Breadcrumb separator={<ChevronRightIcon />}> <BreadcrumbItem> <BreadcrumbLink onClick={() => router.push('/')} cursor="pointer"> {localize(locale, 'home')} </BreadcrumbLink> </BreadcrumbItem> <BreadcrumbItem> <BreadcrumbLink onClick={() => router.push(endpoint)}> {pagename} </BreadcrumbLink> </BreadcrumbItem> {components} </Breadcrumb> ) } export default RoutePageDirection
package watermill import ( "context" "fmt" "time" "cloud.google.com/go/pubsub" "github.com/Improwised/golang-api/config" "github.com/Improwised/golang-api/database" "github.com/Shopify/sarama" "github.com/ThreeDotsLabs/watermill" "github.com/ThreeDotsLabs/watermill-amqp/pkg/amqp" "github.com/ThreeDotsLabs/watermill-sql/v2/pkg/sql" "github.com/ThreeDotsLabs/watermill-googlecloud/pkg/googlecloud" "github.com/ThreeDotsLabs/watermill-kafka/v2/pkg/kafka" "github.com/ThreeDotsLabs/watermill-redisstream/pkg/redisstream" "github.com/ThreeDotsLabs/watermill/message" "github.com/ThreeDotsLabs/watermill/message/router/middleware" "github.com/ThreeDotsLabs/watermill/message/router/plugin" "github.com/redis/go-redis/v9" ) var logger watermill.LoggerAdapter type WatermillSubscriber struct { Subscriber message.Subscriber Router *message.Router } func InitSubscriber(cfg config.AppConfig, isDeadLetterQ bool) (*WatermillSubscriber, error) { logger = watermill.NewStdLogger(cfg.MQ.Debug, cfg.MQ.Track) if isDeadLetterQ { return initSqlSub(cfg) } switch cfg.MQ.Dialect { case "amqp": return initAmqpSub(cfg) case "redis": return initRedisSub(cfg) case "kafka": return initKafkaSub(cfg) case "googlecloud": return initGoogleCloudSub(cfg) case "sql": return initSqlSub(cfg) default: return nil, nil } } // InitRouter init router for add middleware,retry count,delay etc func (ws *WatermillSubscriber) InitRouter(cfg config.AppConfig, delayTime, MaxRetry int) (*WatermillSubscriber, error) { router, err := message.NewRouter(message.RouterConfig{}, logger) if err != nil { return nil, err } pub, err := InitPublisher(cfg, true) if err != nil { return nil, err } poq, err := middleware.PoisonQueue(pub.publisher, cfg.MQ.DeadLetterQ) if err != nil { return nil, err } router.AddPlugin(plugin.SignalsHandler) router.AddMiddleware( middleware.CorrelationID, poq, middleware.Retry{ MaxRetries: MaxRetry, Logger: logger, MaxInterval: time.Millisecond * time.Duration(delayTime), InitialInterval: time.Millisecond * time.Duration(delayTime), Multiplier: 1, }.Middleware, middleware.Recoverer, ) ws.Router = router return ws, nil } func (ws *WatermillSubscriber) Run(topic,handlerName string ,handlerFunc message.NoPublishHandlerFunc) error { if ws.Subscriber == nil { return fmt.Errorf("subscriber is nil") } if ws.Router == nil { router, err := message.NewRouter(message.RouterConfig{}, logger) if err != nil { return err } ws.Router = router } ws.Router.AddNoPublisherHandler( handlerName, topic, ws.Subscriber, handlerFunc, ) err := ws.Router.Run(context.Background()) return err } func initAmqpSub(cfg config.AppConfig) (*WatermillSubscriber, error) { amqpConfig := amqp.NewDurableQueueConfig(cfg.MQ.Amqp.AmqbUrl) subscriber, err := amqp.NewSubscriber( amqpConfig, logger, ) return &WatermillSubscriber{Subscriber: subscriber}, err } func initKafkaSub(cfg config.AppConfig) (*WatermillSubscriber, error) { saramaSubscriberConfig := kafka.DefaultSaramaSubscriberConfig() saramaSubscriberConfig.Consumer.Offsets.Initial = sarama.OffsetOldest subscriber, err := kafka.NewSubscriber( kafka.SubscriberConfig{ Brokers: cfg.MQ.Kafka.KafkaBroker, Unmarshaler: kafka.DefaultMarshaler{}, OverwriteSaramaConfig: saramaSubscriberConfig, ConsumerGroup: cfg.MQ.Kafka.ConsumerGroup, }, logger, ) if err != nil { return nil, err } return &WatermillSubscriber{Subscriber: subscriber}, err } func initRedisSub(cfg config.AppConfig) (*WatermillSubscriber, error) { subClient := redis.NewClient(&redis.Options{ Addr: cfg.MQ.Redis.RedisUrl, Username: cfg.MQ.Redis.UserName, Password: cfg.MQ.Redis.Password, }) subscriber, err := redisstream.NewSubscriber( redisstream.SubscriberConfig{ Client: subClient, Unmarshaller: redisstream.DefaultMarshallerUnmarshaller{}, ConsumerGroup: cfg.MQ.Redis.ConsumerGroup, }, logger, ) return &WatermillSubscriber{Subscriber: subscriber}, err } func initGoogleCloudSub(cfg config.AppConfig) (*WatermillSubscriber, error) { subscriptionName := func(string) string { return cfg.MQ.GoogleCloud.SubscriptionId } ackDeadline := 20 * time.Second subscriber, err := googlecloud.NewSubscriber( googlecloud.SubscriberConfig{ ProjectID: cfg.MQ.GoogleCloud.ProjectID, DoNotCreateTopicIfMissing: false, DoNotCreateSubscriptionIfMissing: false, InitializeTimeout: 30 * time.Second, GenerateSubscriptionName: subscriptionName, SubscriptionConfig: pubsub.SubscriptionConfig{ RetainAckedMessages: false, EnableMessageOrdering: false, AckDeadline: ackDeadline, RetentionDuration: 24 * time.Hour, }, Unmarshaler: googlecloud.DefaultMarshalerUnmarshaler{}, }, logger, ) if err != nil { panic(err) } return &WatermillSubscriber{Subscriber: subscriber}, err } func initSqlSub(cfg config.AppConfig) (*WatermillSubscriber, error) { switch cfg.MQ.Sql.Dialect { case "postgres": return initPostgresSub(cfg) case "mysql": return initMysqlSub(cfg) default: return nil, nil } } func initPostgresSub(cfg config.AppConfig) (*WatermillSubscriber, error) { db, err := database.PostgresDBConnection(cfg.MQ.Sql) if err != nil { return nil, err } subscriber, err := sql.NewSubscriber( db, sql.SubscriberConfig{ SchemaAdapter: database.PostgreSQLSchema{}, OffsetsAdapter: sql.DefaultPostgreSQLOffsetsAdapter{}, InitializeSchema: true, }, logger, ) if err != nil { return nil, err } return &WatermillSubscriber{Subscriber: subscriber}, err } func initMysqlSub(cfg config.AppConfig) (*WatermillSubscriber, error) { db, err := database.MysqlDBConnection(cfg.MQ.Sql) if err != nil { return nil, err } subscriber, err := sql.NewSubscriber( db, sql.SubscriberConfig{ SchemaAdapter: database.MySQLSchema{}, OffsetsAdapter: sql.DefaultMySQLOffsetsAdapter{}, InitializeSchema: true, }, logger, ) if err != nil { return nil, err } return &WatermillSubscriber{Subscriber: subscriber}, err }
const assert = require('assert'); const greetPeople = (people) => { let greeting = []; for (const person in people) { greeting[person] = `Hello ${people[person]}`; } return greeting; }; const parameter = ['Irina', 'Ashleigh', 'Elsa']; const result = ['Hello Irina', 'Hello Ashleigh', 'Hello Elsa']; const output = greetPeople(parameter); assert.strictEqual(typeof greetPeople, 'function', 'greetPeople precisa ser uma function'); assert.deepStrictEqual(output, result, 'A string não foi feita corretamente');