text
stringlengths
184
4.48M
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Member Registration</title> <link rel="icon" type="image/png" href="images/Logos/lwb_favicon.png"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <nav> <ul> <li class="navbar-logo"> <a href="index.html"> <img src="images/Logos/lwb_at_nyp_logo.png" alt="index.html"> </a> </li> <li> <a href="menu.html"> <span>Menu</span> </a> </li> <li> <a href="order.html"> <span>Order</span> </a> </li> <li> <a href="registration.html" class="navlink-active"> <span>Register</span> </a> </li> <li> <a href="about.html"> <span>About Us</span> </a> </li> </ul> </nav> <main> <form method="post" action="https://jkorpela.fi/cgi-bin/echo.cgi" class="registration-form"> <fieldset class="personal-details-fieldset"> <legend>Personal Details</legend> <div class="form-input"> <label for="name"> <img src="images/Icons/icons8-person-96.png"> <span>Name</span> </label> <input id="name" name="name" type="text" pattern="[a-z A-Z]{2,}" required> </div> <div class="gender-option"> <input id="male" name="gender" value="male" type="radio" checked> <label for="male"> <span>Male</span> </label> <input id="female" name="gender" value="female" type="radio"> <label for="female"> <span>Female</span> </label> </div> <div class="form-input"> <label for="email"> <img src="images/Icons/icons8-email-96.png"> <span>Email</span> </label> <input id="email" name="email" type="email" required> </div> <div class="form-input"> <label for="phoneNumber"> <img src="images/Icons/icons8-phone-96.png"> <span>Phone</span> </label> <input id="phoneNumber" name="phoneNumber" type="tel" pattern="[89]\d{3}\s?\d{4}" title="Enter a Singaporean phone number." required> </div> <div class="form-input"> <label for="homeAddress"> <img src="images/Icons/icons8-address-96.png"> <span>Home Address</span> </label> <input id="homeAddress" name="homeAddress" type="text" required> <label for="postalCode"> <span>Postal Code</span> </label> <input id="postalCode" name="postalCode" type="text" pattern="\d{3}\s?\d{3}" required> </div> <div class="form-input"> <label for="favouriteFood"> <img src="images/Icons/icons8-rice-bowl-96.png"> <span>Favourite Food</span> </label> <input id="favouriteFood" name="favouriteFood" type="text" required> </div> </fieldset> <fieldset class="account-details-fieldset"> <legend>Account Details</legend> <div class="form-input"> <label for="loginID"> <img src="images/Icons/icons8-key-96.png"> <span>Login ID</span> </label> <input id="loginID" name="loginID" type="text" pattern="\w{3,}" title="Minimum 3 alphanumeric characters." required> </div> <div class="form-input"> <label for="password"> <img src="images/Icons/icons8-password-96.png"> <span>Password</span> </label> <input id="password" name="password" type="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.* ).{8,}" title="Minimum 8 characters. At least 1 lowercase, uppercase and number." required> </div> <button type="submit">Register!</button> </fieldset> </form> </main> <div class="footer-padding"></div> <footer> <p>Copyright &copy; 2023-2024 Maverick Chin. All rights reserved.</p> </footer> </body> </html>
package com.example.model.tama; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.json.simple.JSONObject; import com.example.model.Lieu; import com.example.model.NomLieu; import com.example.model.Session; import com.example.model.TypeTamagotchi; import com.example.model.utils.ActionConstant; import com.example.model.utils.AttributeConstant; import com.example.model.utils.Utility; public abstract class Tamagotchi { protected Map<String,String> attributes = new HashMap<>(); protected Map<String,Runnable> actions = new HashMap<>(); protected String actionEnCours; protected int life; private Session maSessions; protected TypeTamagotchi typeTamagotchi; protected Lieu lieuActuel; protected int reduce_life_by = 0; public void init_new_tamagothi(){ this.life = ActionConstant.LIFE_MAX; this.actionEnCours = "Pas d'action en cours"; this.lieuActuel = new Lieu(NomLieu.HOME); // the sessions is affected using the setSessions this is why we don't find it here } public void updateState(){ this.life = Math.min(Math.max(this.life += reduce_life_by,0),100); // can change for each update reduce_life_by = 0; replace_new_attributes_values(); } public void loadAction(){ /// peut etr eyaura } public void addAttributes(){ this.attributes.put(AttributeConstant.LIFE, String.valueOf(this.life)); this.attributes.put(AttributeConstant.ONGOING_ACTION, actionEnCours); this.attributes.put(AttributeConstant.TAMAGOTCHI_TYPE, typeTamagotchi.name()); this.attributes.put(AttributeConstant.ACTUAL_LOCATION, lieuActuel.getNomLieu().name()); } public void replace_new_attributes_values(){ attributes.replace(AttributeConstant.LIFE, String.valueOf(this.life)); attributes.replace(AttributeConstant.ONGOING_ACTION, actionEnCours); attributes.replace(AttributeConstant.TAMAGOTCHI_TYPE, typeTamagotchi.name()); attributes.replace(AttributeConstant.ACTUAL_LOCATION, lieuActuel.getNomLieu().name()); } public void setSession(Session session){ this.maSessions = session; } public Map<String, Runnable> getActions(){ return this.actions; } public Map<String,String> getAttributes(){ return this.attributes; } public Session getSession(){ return maSessions; } public void doAction(String actionName){ this.actions.get(actionName).run(); } public TypeTamagotchi getTypeTamagotchi(){ return typeTamagotchi; } public int getLife(){ return this.life; } public void setTypeTamagotchi(TypeTamagotchi typeTamagotchi){ this.typeTamagotchi = typeTamagotchi; } public String toString(){ StringBuilder ret = new StringBuilder(); // Use StringBuilder for efficient string concatenation for (Map.Entry<String, String> entry : attributes.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); ret.append(key).append(": ").append(value).append(",").append("\n"); } return ret.toString(); } public void loadTamaFromDatabase(JSONObject tama){ this.life = Integer.parseInt((String) tama.get(AttributeConstant.LIFE)); this.actionEnCours = (String) tama.get(AttributeConstant.ONGOING_ACTION); this.lieuActuel = new Lieu(Utility.fromStringToNomLieu((String) tama.get(AttributeConstant.ACTUAL_LOCATION))); this.typeTamagotchi = Utility.fromStringToTamgotchiType((String) tama.get(AttributeConstant.TAMAGOTCHI_TYPE)); } public String getActionEnCours() { return actionEnCours; } public void setActionEnCours(String actionEnCours) { this.actionEnCours = actionEnCours; } public void setLife(int life) { this.life = life; } public Session getMaSessions() { return maSessions; } public void setMaSessions(Session maSessions) { this.maSessions = maSessions; } public Lieu getLieuActuel() { return lieuActuel; } public void setLieuActuel(Lieu lieuActuel) { this.lieuActuel = lieuActuel; } public ArrayList<String> printAttributes(){ ArrayList<String> res = new ArrayList<>(); res.add(AttributeConstant.LIFE + " " + this.life + "%"); return res; } }
import React from 'react' import { IPost } from '../models/IPost' interface PostItemProps { post: IPost, remove: (post: IPost) => void, update: (post: IPost) => void, } export const PostItem: React.FC<PostItemProps> = ({ post, remove, update }) => { const handleRemove = (event: React.MouseEvent) => { event.stopPropagation() remove(post) } const handleUpdate = () => { const text = prompt() || '' const newPost = {...post, title: text} console.log(newPost); update(newPost) } return ( <div className="post" onClick={handleUpdate}> <div className="post__title"> {post.title} </div> <div className="post__body"> {post.body} </div> <button onClick={handleRemove}>Delete</button> </div> ) }
import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:foodgasm/screens/login.dart'; import 'package:hexcolor/hexcolor.dart'; class SignupPage extends StatefulWidget { // const SignupPage({ Key? key }) : super(key: key); @override _SignupPageState createState() => _SignupPageState(); } class _SignupPageState extends State<SignupPage> { @override Widget build(BuildContext context) { double screenWidth = MediaQuery.of(context).size.width; double screenHeight = MediaQuery.of(context).size.height; return Scaffold( backgroundColor: Colors.white, body: SingleChildScrollView( // controller: controller, child: Opacity( opacity: 1.0, child: Container( width: screenWidth, height: screenHeight, decoration: BoxDecoration( image: DecorationImage( image: NetworkImage( 'https://images.unsplash.com/photo-1579584425555-c3ce17fd4351?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8c3VzaGl8ZW58MHx8MHx8&ixlib=rb-1.2.1&w=1000&q=80'), fit: BoxFit.fitHeight, colorFilter: ColorFilter.mode( Colors.black.withOpacity(0.6), BlendMode.darken, ), ), ), child: Padding( padding: EdgeInsets.symmetric( horizontal: screenWidth * 0.04, ), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: screenHeight * 0.1, ), Center( child: Stack( children: [ Material( elevation: 5.0, borderRadius: BorderRadius.circular(100.0), child: CircleAvatar( backgroundColor: HexColor('#54626B').withOpacity(1), maxRadius: 63.0, child: FaIcon( FontAwesomeIcons.user, color: Colors.white, size: 40.0, ), ), ), Positioned( top: screenHeight * 0.11, left: screenWidth * 0.2, child: CircleAvatar( maxRadius: 20.0, backgroundColor: Colors.white, child: CircleAvatar( maxRadius: 18.0, backgroundColor: HexColor('#FF4709'), child: FaIcon(FontAwesomeIcons.arrowUp), ), ), ), ], ), ), SizedBox( height: screenHeight * 0.1, ), Form( child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ TextFormField( // controller: _emailController, keyboardType: TextInputType.text, decoration: InputDecoration( prefixIcon: Padding( padding: EdgeInsets.symmetric( vertical: screenHeight * 0.02, horizontal: screenWidth * 0.04, ), child: FaIcon( FontAwesomeIcons.user, size: 20.0, color: Colors.white, ), ), filled: true, fillColor: Colors.white.withOpacity(0.4), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide.none, ), hintText: 'Name', hintStyle: TextStyle( color: Colors.grey[400], fontFamily: 'Prompt', fontSize: 18.0, fontWeight: FontWeight.bold, ), contentPadding: EdgeInsets.symmetric( vertical: screenHeight * 0.02, horizontal: screenWidth * 0.08, ), ), style: TextStyle( color: HexColor('#FFFFFF'), // fontFamily: 'Prompt', fontSize: 18.0, ), ), SizedBox( height: screenHeight * 0.02, ), TextFormField( // controller: _emailController, keyboardType: TextInputType.emailAddress, decoration: InputDecoration( prefixIcon: Padding( padding: EdgeInsets.symmetric( vertical: screenHeight * 0.02, horizontal: screenWidth * 0.04, ), child: FaIcon( FontAwesomeIcons.envelope, size: 20.0, color: Colors.white, ), ), filled: true, fillColor: Colors.white.withOpacity(0.4), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide.none, ), hintText: 'E-mail', hintStyle: TextStyle( color: Colors.grey[400], fontFamily: 'Prompt', fontSize: 18.0, fontWeight: FontWeight.bold, ), contentPadding: EdgeInsets.symmetric( vertical: screenHeight * 0.02, horizontal: screenWidth * 0.08, ), ), style: TextStyle( color: HexColor('#FFFFFF'), // fontFamily: 'Prompt', fontSize: 18.0, ), ), SizedBox( height: screenHeight * 0.02, ), TextFormField( // controller: _emailController, obscureText: true, obscuringCharacter: '*', keyboardType: TextInputType.text, decoration: InputDecoration( prefixIcon: Padding( padding: EdgeInsets.symmetric( vertical: screenHeight * 0.02, horizontal: screenWidth * 0.04, ), child: FaIcon( FontAwesomeIcons.lock, size: 20.0, color: Colors.white, ), ), filled: true, fillColor: Colors.white.withOpacity(0.4), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide.none, ), hintText: 'Password', hintStyle: TextStyle( color: Colors.grey[400], fontFamily: 'Prompt', fontSize: 18.0, fontWeight: FontWeight.bold, ), contentPadding: EdgeInsets.symmetric( vertical: screenHeight * 0.02, horizontal: screenWidth * 0.08, ), ), style: TextStyle( color: HexColor('#FFFFFF'), // fontFamily: 'Prompt', fontSize: 18.0, ), ), SizedBox( height: screenHeight * 0.02, ), TextFormField( // controller: _emailController, keyboardType: TextInputType.text, obscuringCharacter: '*', obscureText: true, decoration: InputDecoration( prefixIcon: Padding( padding: EdgeInsets.symmetric( vertical: screenHeight * 0.02, horizontal: screenWidth * 0.04, ), child: FaIcon( FontAwesomeIcons.lock, size: 20.0, color: Colors.white, ), ), filled: true, fillColor: Colors.white.withOpacity(0.4), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide.none, ), hintText: 'Confirmed Password', hintStyle: TextStyle( color: Colors.grey[400], fontFamily: 'Prompt', fontSize: 18.0, fontWeight: FontWeight.bold, ), contentPadding: EdgeInsets.symmetric( vertical: screenHeight * 0.02, horizontal: screenWidth * 0.08, ), ), style: TextStyle( color: HexColor('#FFFFFF'), // fontFamily: 'Prompt', fontSize: 18.0, ), ), SizedBox( height: screenHeight * 0.05, ), SizedBox( width: screenWidth, height: screenHeight * 0.08, child: ElevatedButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => LoginPage(), ), ); }, child: Text( 'Register', style: TextStyle( color: Colors.white, fontSize: 16.0, ), ), style: ElevatedButton.styleFrom( primary: HexColor('#FF4709'), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), ), ), ), ], ), ), SizedBox( height: screenHeight * 0.08, ), Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( 'Already have an account?', style: TextStyle( color: Colors.white, ), ), TextButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => LoginPage(), ), ); }, child: Text( 'Login', style: TextStyle( color: HexColor('#FF4709'), ), ), ), ], ), ], ), ), ), ), ), ); } }
#include <gtest/gtest.h> #include "ListTable.h" using namespace std; TEST(ListTable, Get_size) { ListTable<string, int> table; ASSERT_EQ(0, table.GetDataCount()); ASSERT_NO_THROW(table.Insert("r1", 1234)); ASSERT_EQ(1, table.GetDataCount()); } TEST(ListTable, Is_empty) { ListTable<string, int> table; ASSERT_EQ(true, table.IsEmpty()); ASSERT_NO_THROW(table.Insert("r1", 1234)); ASSERT_EQ(false, table.IsEmpty()); } TEST(ListTable, Is_full) { ListTable<string, int> table(1); ASSERT_EQ(false, table.IsFull()); ASSERT_NO_THROW(table.Insert("r1", 1234)); ASSERT_EQ(true, table.IsFull()); } TEST(ListTable, Insert) { ListTable<string, int> table; ASSERT_NO_THROW(table.Insert("r1", 1234)); ASSERT_EQ(1, table.GetDataCount()); } TEST(ListTable, Delete_exist_record) { ListTable<string, int> table; ASSERT_NO_THROW(table.Insert("r1", 1234)); ASSERT_NO_THROW(table.Delete("r1")); ASSERT_EQ(0, table.GetDataCount()); } TEST(ListTable, Delete_not_exist_record) { ListTable<string, int> table; ASSERT_THROW(table.Delete("r1"), std::runtime_error); } TEST(ListTable, Find_exist_record) { ListTable<string, int> table; ASSERT_NO_THROW(table.Insert("r1", 1234)); int* val; ASSERT_NO_THROW(val = table.Find("r1")); ASSERT_EQ(1234, *val); } TEST(ListTable, Find_not_exist_record) { ListTable<string, int> table; ASSERT_THROW(table.Find("r1"), std::runtime_error); } TEST(ListTable, Reset) { ListTable<string, int> table; ASSERT_EQ(0, table.Reset()); } TEST(ListTable, Is_table_ended) { ListTable<string, int> table; ASSERT_NO_THROW(table.Insert("r1", 1234)); ASSERT_EQ(false, table.IsTabEnded()); ASSERT_NO_THROW(table.GoNext()); ASSERT_EQ(true, table.IsTabEnded()); } TEST(ListTable, Go_next) { ListTable<string, int> table; ASSERT_NO_THROW(table.Insert("r1", 1234)); ASSERT_NO_THROW(table.Insert("r2", 1234)); ASSERT_EQ(1, table.GoNext()); ASSERT_EQ(0, table.GoNext()); } TEST(ListTable, Get_key) { ListTable<string, int> table; ASSERT_NO_THROW(table.Insert("r1", 1234)); ASSERT_EQ("r1", table.GetKey()); } TEST(ListTable, Get_key_from_empty_table) { ListTable<string, int> table; ASSERT_THROW(table.GetKey(), std::runtime_error); } TEST(ListTable, Get_value) { ListTable<string, int> table; ASSERT_NO_THROW(table.Insert("r1", 1234)); ASSERT_EQ(1234, *table.GetValuePtr()); } TEST(ListTable, Get_value_from_empty_table) { ListTable<string, int> table; ASSERT_THROW(table.GetValuePtr(), std::runtime_error); }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page trimDirectiveWhitespaces="true" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <!doctype html> <html lang="ko"> <head> <%@ include file="/WEB-INF/views/inc/head.jsp"%> <title>상품등록 - 사이다마켓</title> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/assets/css/user/item_reg.css" /> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/assets/plugins/ajax/ajax_helper.css" /> </head> <body> <div class='gray_layer' id='background'> <div id="modal_name">태그입력</div> <div id="modal_content"> <form role="form"> <div class="form-group"> <span class="help-block">- 특수문자와 공백은 입력하실 수 없습니다.</span> <span class="help-block">- 각 태그는 최대 10자까지 입력할 수 있습니다.</span> <span class="help-block">- 판매하는 상품과 연관없는 태그 입력시 제재를 받을 수 있습니다.</span> <div class="input-group"> <input type="text" maxlength="10" id="tag_input" class="form-control" placeholder="태그를 입력해 주세요" /> </div> <div class="modal_btn"> <button id="tag_ok" type="button" class="btn btn-primary">확인</button> <button id="tag_cancle" type="button" class="btn btn-info">취소</button> </div> </div> </form> </div> </div> <!-- 헤더 영역 --> <%@ include file="/WEB-INF/views/inc/header.jsp"%> <section> <div class="container"> <div id="reg_subject"> 상품 등록 </div> <!-- 입력 양식 --> <form id="item_img_group" class="form-horizontal" enctype=“multipart/form-data” role="form" action="${pageContext.request.contextPath}/Item_index"> <div id="reg_cont"> <div class="reg_name">상품사진</div> <div id="item_img1" class="col-xs-3 item-img"> <div id=first_img>대표</div><input type="file" id="image0" name="image0" class="image_plus" accept="image/*" /> <a class="remove_img" href="#" title="삭제"><i class="glyphicon glyphicon-remove"></i></a> </div> <div id="item_img2" class="col-xs-3 item-img"><input type="file" id="image1" name="image1" class="image_plus " accept="image/*" /> <a class="remove_img" href="#" title="삭제"><i class="glyphicon glyphicon-remove"></i></a> </div> <div id="item_img3" class="col-xs-3 item-img"><input type="file" id="image2" name="image2" class="image_plus " accept="image/*" /> <a class="remove_img" href="#" title="삭제"><i class="glyphicon glyphicon-remove"></i></a> </div> <div id="item_img4" class="col-xs-3 item-img"><input type="file" id="image3" name="image3" class="image_plus " accept="image/*" /> <a class="remove_img" href="#" title="삭제"><i class="glyphicon glyphicon-remove"></i></a> </div> <div id="item_img5" class="col-xs-3 item-img"><input type="file" id="image4" name="image4"class="image_plus " accept="image/*" /> <a class="remove_img" href="#" title="삭제"><i class="glyphicon glyphicon-remove"></i></a> </div> <div id="item_img6" class="col-xs-3 item-img"><input type="file" id="image5" name="image5" class="image_plus " accept="image/*" /> <a class="remove_img" href="#" title="삭제"><i class="glyphicon glyphicon-remove"></i></a> </div> <div id="item_img7" class="col-xs-3 item-img"><input type="file" id="image6" name="image6" class="image_plus " accept="image/*" /> <a class="remove_img" href="#" title="삭제"><i class="glyphicon glyphicon-remove"></i></a> </div> <div id="item_img8" class="col-xs-3 item-img"><input type="file" id="image7" name="image7" class="image_plus " accept="image/*" /> <a class="remove_img" href="#" title="삭제"><i class="glyphicon glyphicon-remove"></i></a> </div> </div> <div id="reg_info"> <div class="reg_name">상품정보</div> <fieldset> <div class="form-group"> <label for="item_subject" class="col-sm-2 control-label">제목</label> <div class="col-sm-10"> <input type="text" class="form-control" id="item_subject" name="item_subject" placeholder="상품 제목을 입력해주세요."> </div> </div> <div class="form-group"> <label for="item_category" class="col-sm-2 control-label">카테고리</label> <div class="col-sm-5"> <select class="form-control" id="item_category" name="item_category"> <option selected value="" >카테고리</option> <%--조회 결과에 따른 반복 처리 --%> <c:forEach var="item" items="${output}" varStatus="status"> <option value="${item.cateno}">${item.name}</option> </c:forEach> </select> </div> </div> <div class="form-group"> <label for="item_content" class="col-sm-2 control-label">설명</label> <div class="col-sm-10"> <textarea id="item_content" name="item_content" class="form-control ckeditor" rows="5" placeholder="상품 설명을 입력해주세요."></textarea> </div> </div> <div class="form-group"> <label for="item_tag" class="col-sm-2 control-label">연관태그<small>(선택)</small></label> <input type="hidden" id="hash1" name="hash1" value="" /> <input type="hidden" id="hash2" name="hash2" value="" /> <input type="hidden" id="hash3" name="hash3" value="" /> <input type="hidden" id="hash4" name="hash4" value="" /> <input type="hidden" id="hash5" name="hash5" value="" /> <div class="col-sm-10"> <button id="item_tag" class="btn btn-info">태그입력</button> <ul class="list-inline tag_list"> </ul> </div> </div> <div class="form-group"> <label for="item_stat" class="col-sm-2 control-label">상태</label> <input type="hidden" id="item_prodcon" name="item_prodcon" value="N" /> <div class="col-sm-10" id="item_con"> <button class="btn btn-info btn-list active" data-con="N">새상품</button> <button class="btn btn-info btn-list" data-con="A">거의새것</button> <button class="btn btn-info btn-list" data-con="U">중고</button> </div> </div> <div class="form-group"> <label for="item_price" class="col-sm-2 control-label">가격</label> <div class="col-sm-10"> <input type="number" class="form-control" id="item_price" name="item_price" placeholder="가격을 입력해주세요."> <div class="won">원</div> <p>*가격을 입력하지 않는 경우 무료나눔로 설정됩니다.</p> </div> </div> <div class="form-group"> <label for="optionsRadios1" class="col-sm-2 control-label">거래방법</label> <div class="col-sm-10"> <label class="radio-inline"> <input type="radio" class="radio_check" name="optionsRadios" id="optionsRadios1" value="T" checked> 택배거래 </label> <label class="radio-inline"> <input type="radio" class="radio_check" name="optionsRadios" id="optionsRadios2" value="J"> 직거래 </label> <label class="radio-inline"> <input type="radio" class="radio_check" name="optionsRadios" id="optionsRadios3" value="X"> 상관 없음 </label> </div> </div> <div class="form-group"> <label for="item_delfee" class="col-sm-2 control-label">배송비</label> <div class="col-sm-10"> <input type="number" class="form-control" id="item_delfee" name="item_delfee" placeholder="배송비를 입력해주세요."> <div class="won">원</div> <p>*배송비를 입력하지 않는 경우 배송비는 무료로 설정됩니다.</p> </div> </div> <input type="hidden" name="seller" value="${myNum}"> </fieldset> </div> <div id="final"> <fieldset> <button id="allow" type="submit" class="btn btn-primary btn-block" onClick="CKupdate();"> 상 품 등 록 </button> </fieldset> </div> </form> <!-- //입력양식 --> </div> <div id="anou"> <p>(주)사이다마켓은 통신판매중개자로서 거래당사자가 아니며, <br /> 판매자가 등록한 상품정보 및 거래에 대해 (주)사이다마켓은 일체 책임을 지지 않습니다 </p> </div> </section> <!-- 푸터 영역 --> <%@ include file="/WEB-INF/views/inc/footer.jsp"%> <script id="tag_list_tmpl" type="text/x-handlebars-template"> <li>{{content}}<a class="remove_tag" href="#"><i class="glyphicon glyphicon-remove"></i></a></li> </script> <!-- Javascript --> <script src="${pageContext.request.contextPath}/assets/js/bootstrap.min.js"></script> <script src="${pageContext.request.contextPath}/assets/js/asidebar.jquery.js"></script> <!-- jQeury Ajax Form plugin CDN --> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js"></script> <!-- ajax-helper --> <script src="${pageContext.request.contextPath}/assets/plugins/ajax/ajax_helper.js"></script> <!-- handlebar plugin --> <script src="${pageContext.request.contextPath}/assets/plugins/handlebars/handlebars-v4.7.6.js"></script> <!-- CKEditor CDN --> <script src="//cdn.ckeditor.com/4.16.0/basic/ckeditor.js"></script> <script type="text/javascript"> function CKupdate(){ for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement(); } $(function () { // 직거래 선택시 배송비 입력칸 비활성화 $(".radio_check").click(function () { if($("#optionsRadios2").is(":checked")){ $("#item_delfee").val(""); $("#item_delfee").attr("placeholder", "직거래 선택 시 배송비는 없습니다."); $("#item_delfee").attr("disabled", true); } else{ $("#item_delfee").attr("disabled", false); $("#item_delfee").attr("placeholder", "배송비를 입력해주세요."); } }); //사진 등록 // 버튼 토글 $(".btn-list").click(function (e) { e.preventDefault(); $(".btn-list").not(this).removeClass('active'); $(this).toggleClass('active'); for(var i = 0 ; i<3 ; i++){ var con = $("#item_con>button").eq(i) if(con.hasClass("active")){ $("#item_prodcon").val(con.data("con")); } } }); // 등록 이미지 등록 미리보기 function readInputFile(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $(input).css('background-image', 'url(\"' + e.target.result + '\")'); $(input).next().css('display', 'block'); } reader.readAsDataURL(input.files[0]); } } $(".image_plus").on('change', function () { readInputFile(this); }); //등록 이미지 삭제 function resetInputFile($input) { var agent = navigator.userAgent.toLowerCase(); if ((navigator.appName == 'Netscape' && navigator.userAgent.search('Trident') != -1) || (agent.indexOf("msie") != -1)) { // ie 일때 $input.replaceWith($input.clone(true)); } else { //other $input.val(""); } } $(".remove_img").click(function (e) { e.preventDefault(); var ok = confirm("사진을 삭제하시겠습니까?"); if (ok) { $(this).css('display', 'none'); $(this).prev().css('background-image', 'url("${pageContext.request.contextPath}/upload/img_plus.png")'); var $input = $(this).prev(); resetInputFile($input); } }); $("#tag_input").keyup(function (e) { // 특수문자 정규식 변수(공백 포함) var replaceChar = /[~!@\#$%^&*\()\-=+_'\;<>\/.\`:\"\\,\[\]?|{}\s]/gi; var input = $("#tag_input").val(); if (input.match(replaceChar)) { alert("특수문자 및 공백은 사용하실 수 없습니다."); $("#tag_input").val(input.replace(replaceChar, '')); } }); $("#tag_ok").click(function (e) { e.preventDefault(); var input = $("#tag_input").val(); if (!input) { alert("태그를 입력해 주세요"); $("#tag_input").focus(); $("#tag_input").val(''); return false; } var replaceChar = /[~!@\#$%^&*\()\-=+_'\;<>\/.\`:\"\\,\[\]?|{}\s]/gi; if (input.match(replaceChar)) { alert("특수문자 및 공백은 사용하실 수 없습니다."); $("#tag_input").focus(); $("#tag_input").val(input.replace(replaceChar, '')); return false; } for (var i = 0; i < 5; i++) { var tag_val = $(".tag_list>li").eq(i).html(); input_chk = input + "<a class=\"remove_tag\" href=\"#\"><i class=\"glyphicon glyphicon-remove\"></i></a>" if (input_chk == tag_val) { alert("중복된 태그입니다."); $("#tag_input").focus(); $("#tag_input").val(''); return false; } } if ($(".tag_list>li").length >= 5) { alert("태그는 최대 5개까지만 입력 가능합니다."); return false; } var li = { content: input }; var template = Handlebars.compile($("#tag_list_tmpl").html()); var html = template(li); $(".tag_list").append(html); $("#tag_input").val(''); $("#background").fadeOut(300); for(var i = 1; i < 6; i++){ if(!$("#hash"+i+"").val()){ $("#hash"+i+"").val(input); break; } } }); $(document).on("click", ".remove_tag", function (e) { e.preventDefault(); var target = $(this).parent().text(); for(var i = 1; i < 6; i++){ if($("#hash"+i+"").val()==target){ $("#hash"+i+"").val(""); } } $(this).parent().remove(); }); $("#item_tag").click(function (e) { e.preventDefault(); $("#background").fadeIn(300); $("#tag_input").focus(); }); $("#tag_cancle").click(function (e) { $("#tag_input").val(''); $("#background").fadeOut(300); }); $("#tag_input").keydown(function(e){ if(e.keyCode==13){ e.preventDefault(); $("#tag_ok").click(); } }); // #item_img_group에 대한 submit이벤트를 가로채서 Ajax요청을 전송한다. $("#item_img_group").ajaxForm({ // 전송 메서드 지정 method: "POST", // 서버에서 200 응답을 전달한 경우 실행됨 success: function(json) { console.log(json); // json에 포함된 데이터를 활용하여 상세페이지로 이동한다. if (json.rt == "OK") { alert("상품 등록이 완료되었습니다."); window.location="${pageContext.request.contextPath}/item_index.cider?prodno="+json.item.prodno; } } }); }); </script> </body> </html>
### testing GENERA <- unique(TABLE.TT$Genus) GENUS.LIST <- c() PVALUES <- c() INDEX <- 1 for (GENUS in GENERA){ GENUS.TABLE <- filter( TABLE.TT, Genus == GENUS ) if (length(unique(GENUS.TABLE$location)) > 1){ KW <- kruskal.test( clr~location, data = GENUS.TABLE ) GENUS.LIST[[INDEX]] <- c(GENUS) PVALUES[[INDEX]] <- c(KW$p.value) INDEX <- INDEX + 1 } } KW.DF <- data.frame(GENUS.LIST,PVALUES) ############################################################################### # Conserved And Variable Microbiota RA ############################################################################### #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # generate TT Table #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # calculate RA for each plate # remove unknown genus, time 0's # select common columns # create genus table for each plate # plate 1 PLATE1.RA <- calculateRA_4_q2table("ducitaplate1-table.tsv") PLATE1.RA.META <- addtax_addmeta( PLATE1.RA, "ducitaplate1-ggBLAST_taxonomy.tsv", "ducitaplate1-metadata.tsv", sep = TRUE, value = "RA" ) PLATE1.FILTERED <- filter( PLATE1.RA.META, time != 0 ) PLATE1.TABLE <- select( PLATE1.FILTERED, sample_id, Phylum, Family, Genus, tissue, type, RA ) colnames(PLATE1.TABLE)[5:6] <- c( "host_species", "sample_type" ) PLATE1.GENUS <- ddply( PLATE1.TABLE, ~sample_id+Phylum+Family+Genus+host_species+sample_type, summarise, RA = sum(RA) ) PLATE1.GENUS$location <- rep( "PM_year1", nrow(PLATE1.GENUS) ) CH_PP.RA <- calculateRA_4_q2table("ch_pp-filtered_table.tsv") CH_PP.RA.META <- addtax_addmeta( CH_PP.RA, "ducitaplate2-ggBLAST_taxonomy.tsv", "ducitaplate2-metadata.tsv", sep = TRUE, value = "RA" ) CH_PP.TABLE <- select( CH_PP.RA.META, sample_id, Phylum, Family, Genus, species, type, RA, location ) colnames(CH_PP.TABLE)[5:6] <- c( "host_species", "sample_type" ) CH_PP.GENUS <- ddply( CH_PP.TABLE, ~sample_id+Phylum+Family+Genus+host_species+sample_type+location, summarise, RA = sum(RA) ) PLATES4_5.RA <- calculateRA_4_q2table("ducitaplates4_5-table.tsv") PLATES4_5.RA.META <- addtax_addmeta( PLATES4_5.RA, "ducitaplates4_5-ggBLAST_taxonomy.tsv", "ducitaplates4_5-metadata.tsv", sep = TRUE, value = "RA" ) PLATES4_5.FILTERED <- filter( PLATES4_5.RA.META, time != 0 ) PLATES4_5.TABLE <- select( PLATES4_5.FILTERED, sample_id, Phylum, Family, Genus, tissue, type, RA ) colnames(PLATES4_5.TABLE)[5:6] <- c( "host_species", "sample_type" ) PLATES4_5.GENUS <- ddply( PLATES4_5.TABLE, ~sample_id+Phylum+Family+Genus+host_species+sample_type, summarise, RA = sum(RA) ) PLATES4_5.GENUS$location <- rep( "PM_year2", nrow(PLATES4_5.GENUS) ) CHINA.RA <- calculateRA_4_q2table("china_microbiome-filtered_table.tsv") CHINA.RA.META <- addtax_addmeta( CHINA.RA, "china_microbiome-ggBLAST_taxonomy.tsv", "china_microbiome-duckweed_metadata.tsv", sep = TRUE, value = "RA" ) CHINA.TABLE <- select( CHINA.RA.META, sample_id, Phylum, Family, Genus, species, type, RA, location ) colnames(CHINA.TABLE)[5:6] <- c( "host_species", "sample_type" ) CHINA.GENUS <- ddply( CHINA.TABLE, ~sample_id+Phylum+Family+Genus+host_species+sample_type+location, summarise, RA = sum(RA) ) ALLTABLES<- do.call( "rbind", list( PLATE1.GENUS, CH_PP.GENUS, PLATES4_5.GENUS, CHINA.GENUS ) ) # get table for tissue otus SAMPLE_TYPES <- c( "treated_tissue", "rinsed_tissue", "ambient_water" ) TABLE.TT <- filter( ALLTABLES, sample_type %in% SAMPLE_TYPES ) # get table for tissue otus TABLE.TT <- filter( ALLTABLES, sample_type == "treated_tissue" | sample_type == "rinsed_tissue" ) TABLE.TT <- filter( TABLE.TT, RA > 0 ) TABLE.TT$Genus <- gsub( "Candidatus Amoebophilus", "C. Amoebophilus", paste(TABLE.TT$Genus) ) TABLE.TT$group <- sapply( TABLE.TT$Genus, function(x) if (x %in% CONSERVED.GENERA){ "conserved" } else{ "variable" } ) PLOT <- ggplot( TABLE.TT, aes( sample_id, RA, fill = group ) ) PLOT + geom_bar( stat="identity", color = "black", width = 1 ) + theme(axis.title = element_text( size = 16, face = "bold" ), axis.text.x = element_blank(), axis.line.x = element_blank(), axis.text.y = element_text( face = "bold", size = 10, color = "black" ), legend.key = element_blank(), legend.title = element_text( face = "bold", size = 14 ), legend.text = element_text( face = "bold", size = 10 ), strip.background = element_rect( fill = NA, color = "black" ), strip.text = element_text( face = "bold", color = "black", size = 10 ), panel.background = element_blank() ) + facet_grid( .~location, space = "free_x", scale = "free_x" )
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" /> <link rel="stylesheet" href="style.css" /> <title>Web Development Roadmap</title> </head> <body> <header id="main-header" class="main-header"> <div class="container"> <h1><i class="fas fa-code"></i> Web Development Path</h1> <h2><i class="fas fa-user"></i> Alex Farnes</h2> </div> </header> <section id="timeline" class="timeline"> <ul class="timeline__list"> <li class="timeline__item"> <div class="timeline__box"> <h3> <i class="fas fa-chevron-right"></i> HTML <i class="fab fa-html5"></i> & CSS <i class="fab fa-css3-alt"></i> </h3> <p>Courses:</p> </div> </li> <li class="timeline__item"> <div class="timeline__box"> <h3> <i class="fas fa-chevron-right"></i> JavaScript <i class="fab fa-js"></i> </h3> <p>Courses:</p> </div> </li> <li class="timeline__item"> <div class="timeline__box"> <h3> <i class="fas fa-chevron-right"></i> Sass <i class="fab fa-sass"></i> </h3> <p>Courses:</p> </div> </li> <li class="timeline__item"> <div class="timeline__box"> <h3> <i class="fas fa-chevron-right"></i> Version Control <i class="fab fa-github"></i> </h3> <p>Courses:</p> </div> </li> <li class="timeline__item"> <div class="timeline__box"> <h3> <i class="fas fa-chevron-right"></i> Package Manager <i class="fab fa-npm"></i> </h3> <p>Courses:</p> </div> </li> <li class="timeline__item"> <div class="timeline__box"> <h3> <i class="fas fa-chevron-right"></i> Design <i class="fas fa-palette"></i> </h3> <p>Courses:</p> </div> </li> <li class="timeline__item"> <div class="timeline__box"> <h3> <i class="fas fa-chevron-right"></i> React <i class="fab fa-react"></i> </h3> <p>Courses:</p> </div> </li> <li class="timeline__item"> <div class="timeline__box"> <h3> <i class="fas fa-chevron-right"></i> Node.js <i class="fab fa-node"></i> </h3> <p>Courses:</p> </div> </li> </ul> </section> <script src="main.js"></script> </body> </html>
import React, {useState} from 'react' import MinistryData from '../../components/ministrydata/MinistryData' import Tab from '../../components/tab/Tab' import './ministries.css' import { axiosInstance } from '../../config' function Ministries() { const [showRegModel, setShowRegModel] = useState(false) const [name, setName] = useState('') const [phone, setPhone] = useState('') const [ministry, setMinistry] = useState('') const handleSubmit = async () => { if(name ==='' && phone ==='' && ministry ===''){ alert('Please fill all the fields') } else{ const {data} = await axiosInstance.post('api/ministry/', { name, phone, ministry }); console.log(data) setName('') setPhone('') setMinistry('') setShowRegModel(false) } } return ( <div className='ministries'> <div className='about-top flex flex-col items-center justify-center bg-green-700'> <div className='container flex flex-col py-10 px-4'> <p className='text-white text-2xl font-bold '>Moi University Annex Campus Christian Union Ministries</p> <p className='text-white'>All members are warmly invited to participate in our various church ministries.</p> <button onClick={() => setShowRegModel(true)} className='ministry-btn border-2 py-2 rounded-md text-white hover:bg-red-700 mt-1'>Join ministry</button> </div> </div> <MinistryData/> {showRegModel && ( <div className='modal flex items-center justify-center'> <div className='register-ministry flex flex-col items-center justify-center rounded-md p-3'> <p onClick={() => setShowRegModel(false)} className='text-red-700 cursor-pointer text-2xl '><i class="fa-solid fa-circle-xmark"></i></p> <p>Fill in the fields to continue</p> <Tab/> <input value={name} onChange={(e) => setName(e.target.value)} className='ministry-inputs border-2 py-3 px-1 mt-4 mb-2 rounded-md outline-green-100' type='text' placeholder='Enter name'/> <input value={phone} onChange={(e) => setPhone(e.target.value)} className='ministry-inputs border-2 py-3 px-1 mb-2 rounded-md outline-green-100' type='text' placeholder='Enter phone'/> <select value={ministry} onChange={(e) => setMinistry(e.target.value)} className='ministry-inputs border-2 py-3 px-1 mb-2 rounded-md outline-green-100'> <option>--Select--</option> <option value='praise'>Praise & Worship</option> <option value='media'>Media Ministry</option> <option value='hospitality'>Hospitality</option> <option value='prayer'>Prayer Ministry</option> </select> <button onClick={() => handleSubmit()} className='ministry-reg-btn font-medium border-2 py-2 px-4 text-white rounded-md bg-green-700 hover:bg-green-800'>Register</button> </div> </div> )} </div> ) } export default Ministries
library(sf) library(ggplot2) library(viridis) ### Cancer risk prediction nc <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE ) ggplot(data = nc, aes(fill = SID74)) + geom_sf() + scale_fill_viridis() + theme_bw() ### Rainfall Prediction ## library(geoR) ggplot(data.frame(cbind(parana$coords, Rainfall = parana$data)))+ geom_point(aes(east, north, color = Rainfall), size = 2) + coord_fixed(ratio = 1) + scale_color_gradient(low = "blue", high = "orange") + geom_path(data = data.frame(parana$border), aes(east, north)) + theme_bw() ### pOINT Pattern ### library(cholera) rng <- mapRange() plot(fatalities[, c("x", "y")], pch = 15, col = "black", cex = 0.5, xlim = rng$x, ylim = rng$y, asp = 1, frame.plot = FALSE, axes = FALSE, xlab = "", ylab = "" ) addRoads() ### Get Shape file ### # read shapefile with readOGR() # name of the shapefile of North Carolina of the sf package nameshp <- system.file("shape/nc.shp", package = "sf") nameshp library(rgdal) map <- readOGR(nameshp, verbose = FALSE) class(map) head(map@data) ### Plot the map of North Carolina ## plot(map) ## Read in some shape file ## # read shapefile with st_read() library(sf) map <- st_read(nameshp, quiet = TRUE) class(map) head(map) plot(map) ### Static Map of NC with ggplot2 ### library(ggplot2) map <- st_as_sf(map) ggplot(map) + geom_sf(aes(fill = SID74)) + theme_bw() library(viridis) map <- st_as_sf(map) ggplot(map) + geom_sf(aes(fill = SID74)) + scale_fill_viridis() + theme_bw() png("plot.png") ggplot(map) + geom_sf(aes(fill = SID74)) + scale_fill_viridis() + theme_bw() dev.off() ### Get the crs for the map ### st_crs(map) ## Transform the crs map <- st_transform(map, 4326) ### Interractive Map with Leaflet ### library(leaflet) pal <- colorNumeric("YlOrRd", domain = map$SID74) p=leaflet(map) %>% addTiles() %>% addPolygons( color = "white", fillColor = ~ pal(SID74), fillOpacity = 1 ) %>% addLegend(pal = pal, values = ~SID74, opacity = 1) ### Map view demo ### library(mapview) mapview(map, zcol = "SID74") ### Modify the map background ### library(RColorBrewer) pal <- colorRampPalette(brewer.pal(9, "YlOrRd")) mapview(map, zcol = "SID74", map.types = "CartoDB.DarkMatter", col.regions = pal ) ### Faceted map for comparism ### m74 <- mapview(map, zcol = "SID74") m79 <- mapview(map, zcol = "SID79") m <- leafsync::sync(m74, m79) m ### Thematic map with tmap ### library(tmap) tmap_mode("view") tm_shape(map) + tm_polygons("SID74")
import type { GetContactParams, GetContactResponse, CreateContactResponse, UpdateContactResponse, ShowContactResponse, DeleteContactResponse, CreateContactAttributes, CreateContactRelationships, } from "./contacts"; import type { ArchiveSalesInvoicesResponse, CreateSalesInvoicesAttributes, CreateSalesInvoicesRelationships, CreateSalesInvoicesResponse, ShowSalesInvoicesResponse, DeleteSalesInvoicesResponse, CancelSalesInvoicesResponse, GetSalesInvoicesParams, GetSalesInvoicesResponse, RecoverSalesInvoicesResponse, UnarchiveSalesInvoicesResponse, UpdateSalesInvoicesResponse, } from "./sales_invoices"; import Contacts from "./contacts"; import SalesInvoices from "./sales_invoices"; export default class Sales { public contacts: Contacts = new Contacts(); public sales_invoices: SalesInvoices = new SalesInvoices(); /** * @param params {@link GetContactParams} * @returns Promise<{@link GetContactResponse}> */ async getContacts(params?: GetContactParams): Promise<GetContactResponse> { return this.contacts.retrieve(params); } /** * @param params.attributes {@link CreateContactAttributes} * @param params.relationships {@link CreateContactRelationships} * @returns Promise<{@link CreateContactResponse}> * @example * const attributes = { * name: "John Doe", * account_type: "customer", * email?: "john@doe.com", * short_name?: "John", * contact_type?: "person", * tax_office?: "İstanbul", * tax_number?: "1234567890", * district?: "Kartal", * city?: "İstanbul", * country?: "Türkiye", * address?: "Kartal", * phone?: "1234567890", * fax?: "1234567890", * is_abroad?: false, * archived?: false, * iban?: "TR1234567890", * untrackable?: false, * }; * const relationships = { * category?: { * data: { * id: "1", * type: "item_categories", * }, * }, * contact_people?: { * data: [ * { * id: "1", * type: "contact_people", * attributes?: { * name?: "John Doe", * email?: "john@doe.com", * phone?: "1234567890", * notes?: "John Doe", * }, * }, * ], * }, * }; * const response = await client.sales.createContact({ attributes, relationships }); * console.log(response); */ async createContact(params: { attributes: CreateContactAttributes; relationships?: CreateContactRelationships; }): Promise<CreateContactResponse> { const { attributes, relationships } = params; return this.contacts.create({ data: { type: "contacts", attributes, relationships, }, }); } /** * @param id string * @returns Promise<{@link ShowContactResponse}> * @example * const response = await client.sales.showContact("1"); * console.log(response); */ async showContact(id: string): Promise<ShowContactResponse> { return this.contacts.show(id); } /** * @param params.id string * @param params.attributes {@link CreateContactAttributes} * @param params.relationships {@link CreateContactRelationships} * @returns Promise<{@link UpdateContactResponse}> * @example * const attributes = { * name: "John Doe", * account_type: "customer", * email?: "john@doe.com", * short_name?: "John", * contact_type?: "person", * tax_office?: "İstanbul", * tax_number?: "1234567890", * district?: "Kartal", * city?: "İstanbul", * country?: "Türkiye", * address?: "Kartal", * phone?: "1234567890", * fax?: "1234567890", * is_abroad?: false, * archived?: false, * iban?: "TR1234567890", * untrackable?: false, * }; * const relationships = { * category?: { * data: { * id: "1", * type: "item_categories", * }, * }, * contact_people?: { * data: [ * { * id: "1", * type: "contact_people", * attributes?: { * name?: "John Doe", * email?: "john@doe.com", * phone?: "1234567890", * notes?: "John Doe", * }, * }, * ], * }, * }; * const response = await client.sales.updateContact({ id: "1", attributes, relationships }); * console.log(response); */ async updateContact(params: { id: string; attributes: CreateContactAttributes; relationships?: CreateContactRelationships; }): Promise<UpdateContactResponse> { const { id, attributes, relationships } = params; return this.contacts.update(id, { data: { id, type: "contacts", attributes, relationships, }, }); } /** * @param id string * @returns Promise<{@link DeleteContactResponse}> * @example * const response = await client.sales.deleteContact("1"); * console.log(response); */ async deleteContact(id: string): Promise<DeleteContactResponse> { return this.contacts.delete(id); } /** * @param params {@link GetSalesInvoicesParams} * @returns Promise<{@link GetSalesInvoicesResponse}> * @example * const response = await client.sales.getSalesInvoices(); * console.log(response); * @example * const response = await client.sales.getSalesInvoices({ page: { size: 10, number: 1 } }); * console.log(response); * @example * const response = await client.sales.getSalesInvoices({ filter: { contact_id: "1" } }); * console.log(response); * @example * const response = await client.sales.getSalesInvoices({ include: "contact" }); * console.log(response); * @example * const response = await client.sales.getSalesInvoices({ sort: "issue_date" }); * console.log(response); */ async getSalesInvoices( params?: GetSalesInvoicesParams ): Promise<GetSalesInvoicesResponse> { return this.sales_invoices.retrieve(params); } /** * @param params.attributes {@link CreateSalesInvoicesAttributes} * @param params.relationships {@link CreateSalesInvoicesRelationships} * @returns Promise<{@link CreateSalesInvoicesResponse}> * @example * const attributes = { * item_type: "invoice", * description?: "John Doe", * issue_date: "2021-01-01", * due_date?: "2021-01-01", * invoice_series?: "A", * invoice_id?: 1, * currency?: "TRL", * exchange_rate?: 1, * withholding_rate?: 1, * vat_withholding_rate?: 1, * invoice_discount_type?: "percentage", * invoice_discount?: 1, * billing_address?: "İstanbul", * billing_phone?: "1234567890", * billing_fax?: "1234567890", * tax_office?: "İstanbul", * tax_number?: "1234567890", * country?: "Türkiye", * city?: "İstanbul", * district?: "Kartal", * is_abroad?: false, * order_no?: "1234567890", * order_date?: "2021-01-01", * shipment_addres?: "İstanbul", * shipment_included?: false, * cash_sale?: false, * payment_account_id?: 1, * payment_date?: "2021-01-01", * payment_description?: "John Doe", * }; * const relationships = { * details?: { * data: [ * { * id?: "1", * type: "sales_invoice_details", * attributes: { * quantity: 1, * unit_price: 1, * vat_rate: 1, * discount_type?: "percentage", * discount_value?: 1, * excise_duty_type?: "percentage", * excise_duty_value?: 1, * communications_tax_rate?: 1, * description?: "John Doe", * delivery_method?: "CFR", * shipping_method?: "Belirtilmedi", * }, * relationships?: { * product?: { * data: { * id: "1", * type: "products", * }, * }, * warehouse?: { * data: { * id: "1", * type: "warehouses", * }, * }, * }, * }, * ], * }, * contact?: { * data: { * id: "1", * type: "contacts", * }, * }, * category?: { * data: { * id: "1", * type: "item_categories", * }, * }, * tags?: { * data: [ * { * id: "1", * type: "tags", * }, * ], * }, * sales_offer?: { * data: { * id: "1", * type: "sales_offers", * }, * }, * }; * const response = await client.createSalesInvoices({ attributes, relationships }); * console.log(response); */ async createSalesInvoice(params: { attributes: CreateSalesInvoicesAttributes; relationships?: CreateSalesInvoicesRelationships; }): Promise<CreateSalesInvoicesResponse> { const { attributes, relationships } = params; return this.sales_invoices.create({ data: { type: "sales_invoices", attributes, relationships, }, }); } /** * @param id string * @param include string (category, contact, details, details.product, details.warehouse, payments, payments.transaction, tags, sharings, recurrence_plan, active_e_document) * @returns Promise<{@link ShowSalesInvoicesResponse}> * @example * const response = await client.sales.showSalesInvoice("1"); * console.log(response); * @example * const response = await client.sales.showSalesInvoice("1", "category"); * console.log(response); * @example * const response = await client.sales.showSalesInvoice("1", "contact,details"); * console.log(response); */ async showSalesInvoice( id: string, include?: string ): Promise<ShowSalesInvoicesResponse> { return this.sales_invoices.show(id, include); } /** * @param params.id string * @param params.attributes {@link CreateSalesInvoicesAttributes} * @param params.relationships {@link CreateSalesInvoicesRelationships} * @returns Promise<{@link UpdateSalesInvoicesResponse}> * @example * const attributes = { * item_type: "invoice", * description?: "John Doe", * issue_date: "2021-01-01", * due_date?: "2021-01-01", * invoice_series?: "A", * invoice_id?: 1, * currency?: "TRL", * exchange_rate?: 1, * withholding_rate?: 1, * vat_withholding_rate?: 1, * invoice_discount_type?: "percentage", * invoice_discount?: 1, * billing_address?: "İstanbul", * billing_phone?: "1234567890", * billing_fax?: "1234567890", * tax_office?: "İstanbul", * tax_number?: "1234567890", * country?: "Türkiye", * city?: "İstanbul", * district?: "Kartal", * is_abroad?: false, * order_no?: "1234567890", * order_date?: "2021-01-01", * shipment_addres?: "İstanbul", * shipment_included?: false, * cash_sale?: false, * payment_account_id?: 1, * payment_date?: "2021-01-01", * payment_description?: "John Doe", * }; * const relationships = { * details?: { * data: [ * { * id?: "1", * type: "sales_invoice_details", * attributes: { * quantity: 1, * unit_price: 1, * vat_rate: 1, * discount_type?: "percentage", * discount_value?: 1, * excise_duty_type?: "percentage", * excise_duty_value?: 1, * communications_tax_rate?: 1, * description?: "John Doe", * delivery_method?: "CFR", * shipping_method?: "Belirtilmedi", * }, * relationships?: { * product?: { * data: { * id: "1", * type: "products", * }, * }, * warehouse?: { * data: { * id: "1", * type: "warehouses", * }, * }, * }, * }, * ], * }, * contact?: { * data: { * id: "1", * type: "contacts", * }, * }, * category?: { * data: { * id: "1", * type: "item_categories", * }, * }, * tags?: { * data: [ * { * id: "1", * type: "tags", * }, * ], * }, * sales_offer?: { * data: { * id: "1", * type: "sales_offers", * }, * }, * }; * const response = await client.updateSalesInvoices({ * id: "1", * attributes, * relationships, * }); * console.log(response); */ async updateSalesInvoice(params: { id: string; attributes: CreateSalesInvoicesAttributes; relationships?: CreateSalesInvoicesRelationships; }): Promise<UpdateSalesInvoicesResponse> { const { id, attributes, relationships } = params; return this.sales_invoices.update(id, { data: { type: "sales_invoices", attributes, relationships, }, }); } /** * @param id string * @returns Promise<{@link DeleteSalesInvoicesResponse}> * @example * const response = await client.deleteSalesInvoice("1"); * console.log(response); */ async deleteSalesInvoice(id: string): Promise<DeleteSalesInvoicesResponse> { return this.sales_invoices.delete(id); } /** * @param id string * @param include string (category, contact, details, details.product, details.warehouse, payments, payments.transaction, tags, sharings, recurrence_plan, active_e_document) * @returns Promise<{@link CancelSalesInvoicesResponse}> * @example * const response = await client.sales.cancelSalesInvoices("1"); * console.log(response); * @example * const response = await client.sales.cancelSalesInvoices("1", "contact"); * console.log(response); */ async cancelSalesInvoice( id: string, include?: string ): Promise<CancelSalesInvoicesResponse> { return this.sales_invoices.cancel(id, include); } /** * @param id string * @returns Promise<{@link RecoverSalesInvoicesResponse}> * @example * const response = await client.recoverSalesInvoice("1"); * console.log(response); */ async recoverSalesInvoice(id: string): Promise<RecoverSalesInvoicesResponse> { return this.sales_invoices.recover(id); } /** * @param id string * @returns Promise<{@link ArchiveSalesInvoicesResponse}> * @example * const response = await client.archiveSalesInvoice("1"); * console.log(response); */ async archiveSalesInvoice(id: string): Promise<ArchiveSalesInvoicesResponse> { return this.sales_invoices.archive(id); } /** * @param id string * @returns Promise<{@link UnarchiveSalesInvoicesResponse}> * @example * const response = await client.unarchiveSalesInvoice("1"); * console.log(response); */ async unarchiveSalesInvoice( id: string ): Promise<UnarchiveSalesInvoicesResponse> { return this.sales_invoices.unarchive(id); } } export type { GetContactParams, GetContactAttributes, GetContactRelationships, GetContactResponse, CreateContactParams, CreateContactAttributes, CreateContactRelationships, CreateContactResponse, ShowContactResponse, UpdateContactParams, UpdateContactResponse, DeleteContactResponse, } from "./contacts"; export type { GetSalesInvoicesParams, GetSalesInvoicesAttributes, GetSalesInvoicesRelationships, GetSalesInvoicesResponse, CreateSalesInvoicesParams, CreateSalesInvoicesAttributes, CreateSalesInvoicesRelationships, CreateSalesInvoicesResponse, ShowSalesInvoicesResponse, UpdateSalesInvoicesParams, UpdateSalesInvoicesResponse, DeleteSalesInvoicesResponse, CancelSalesInvoicesResponse, RecoverSalesInvoicesResponse, ArchiveSalesInvoicesResponse, UnarchiveSalesInvoicesResponse, } from "./sales_invoices";
<div class="container"> <h1 class="mt-3">Edit BlogPost</h1> <ng-container *ngIf="model"> <form ngForm (ngSubmit)="onFormSubmit()"> <div class="mt-2 mb-5"> <div class="mt-3"> <label for="title" class="form-label">Title</label> <input type="text" class="form-control" name="title" id="title" [(ngModel)]="model.title"> </div> <div class="mt-3"> <label for="urlHandle" class="form-label">Url Handle</label> <input type="text" class="form-control" name="urlHandle" id="urlHandle"> </div> <div class="mt-3"> <label for="shortDescription" class="form-label">Short Description</label> <input type="text" class="form-control" name="shortDescription" id="shortDescription" [(ngModel)]="model.shortDescription"> </div> <div class="mt-3"> <label for="content" class="form-label">Content</label> <div class="d-flex flex-row"> <div class="col-6 p-2"> <textarea name="content" id="content" class="form-control" [(ngModel)]="model.content"> </textarea> </div> <div id="contentScroll" class="col-6 p-2"> <markdown [data]="model.content"></markdown> </div> </div> </div> <div class="mt-3"> <label for="featuredImageUrl" class="form-label">Featured Image Url</label> <button type="button" class="btn btn-light" (click)="this.isVisibleImageSelector = true"> Select Image </button> <ng-container *ngIf="model.featuredImageUrl !== ''"> <div> <img id="featuredImage" class="my-2" [src]="model.featuredImageUrl" alt="imagePreview"> </div> </ng-container> <input type="text" class="form-control" name="featuredImageUrl" id="featuredImageUrl" [(ngModel)]="model.featuredImageUrl"> </div> <div class="mt-3"> <label for="publishedDate" class="form-label">Published Date</label> <input type="date" class="form-control" name="publishedDate" id="publishedDate" value="{{model.publicationDate}}" [ngModel]="model.publicationDate | date: 'yyy-MM-dd'" (ngModelChange)="model.publicationDate = $event"> </div> <div class="mt-3"> <label for="author" class="form-label">Author</label> <input type="text" class="form-control" name="author" id="author" [(ngModel)]="model.author"> </div> <div class="form-check mt-3"> <input class="form-check-input" type="checkbox" name="isVisible" id="isVisible" [(ngModel)]="model.isVisible"> <label class="form-check-label" for="isVisible"> Is Visible? </label> </div> <div class="mt-3"> <label for="categories" class="form-label">Categories</label> <ng-container *ngIf="categories$ | async as categories"> <select name="categories" id="categories" class="form-control" multiple [(ngModel)]="selectedCategories"> <option *ngFor="let category of categories" [value]="category.id"> {{category.name}} </option> </select> </ng-container> </div> <div class="mt-3 d-flex"> <button class="btn btn-primary" type="submit">Save</button> <button class="btn btn-danger ms-3" type="button" (click)="onDelete()">Delete</button> </div> </div> </form> </ng-container> </div> <div class="images-container-modal" [ngClass]="{'d-block': isVisibleImageSelector, 'd-none': !isVisibleImageSelector}"> <button type="button" class="btn btn-light" id="image-modal-close-button" (click)="this.isVisibleImageSelector = false"> X </button> <app-image-selector></app-image-selector> </div>
import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import sys from typing import List plt.rcParams["font.family"] = "Times New Roman" prefix = os.path.expanduser("~") + "/cvy_ws/src/convoy_ros" if sys.platform == "darwin": prefix = os.path.expanduser("~") + "/projects/convoy_ros" data_loc = prefix + "/convoy_data/data/" save_file_exp = prefix + "/data_analysis/figures/iser_platoon_exp.pdf" save_file_rms = prefix + "/data_analysis/figures/iser_rms_fig.pdf" title_size = 10 subtitle_size = 8 axes_size = 7 legend_title_size = 8 legend_font_size = 7 tick_label_size = 7 linewidth = 0.8 linestyle = "solid" alphas = [0.7, 0.8, 0.8, 0.8] scatter_size = 6 def remove_zero_vel(df: pd.DataFrame): lead_veh_df = df[df["veh_ind"] == 0] times = lead_veh_df[lead_veh_df["pred_speed"] > 0]["time"].to_numpy() start_time = times[0] - 2.0 end_time = times[-1] + 2.0 df = df[df["time"] > start_time] df = df[df["time"] < end_time] df["time"] -= start_time return df def add_position_column(df: pd.DataFrame): veh_ind = df["veh_ind"].to_numpy() time = df["time"].to_numpy() speed = df["ego_speed"].to_numpy() dist = df["pred_dist"].to_numpy() position = [] # we will fill this out for each row in df # initialize vehicle positions and get init time for veh 0 n_vehicles = max(veh_ind) + 1 veh_pos = [0.0] for k in range(0, n_vehicles): if k == 0: for i, t in enumerate(time): if veh_ind[i] == k: prev_time = time[i] break else: for i, d in enumerate(dist): if veh_ind[i] == k: veh_pos.append(veh_pos[k - 1] - d) break for k, ind in enumerate(veh_ind): if ind == 0: dt = time[k] - prev_time veh_pos[ind] += dt * speed[k] prev_time = time[k] position.append(veh_pos[ind]) else: veh_pos[ind] = veh_pos[ind - 1] - dist[k] position.append(veh_pos[ind]) df["ego_position"] = position return df def plot_quad_l1_lfbk(quad_df, l1_df, lfbk_df): veh_inds = [i for i in range(max(quad_df["veh_ind"]) + 1)] fig, ax = plt.subplots(2, 3, sharex="col", sharey="row", figsize=(4.7, 2.5)) fig.subplots_adjust(0.1, 0.15, 0.89, 0.83, 0.07, 0.09) fig.suptitle( f"Platoon trajectories: Hardware comparison with {max(veh_inds) + 1} vehicles", fontsize=title_size, ) ax[0, 0].set_title(rf"$\|\|\cdot\|\|_2^2$ DMPC", fontsize=subtitle_size) ax[0, 1].set_title(rf"$\|\|\cdot\|\|_1$ DMPC", fontsize=subtitle_size) ax[0, 2].set_title("Linear feedback", fontsize=subtitle_size) for i in veh_inds: quad_pfmpc_veh = quad_df[quad_df["veh_ind"] == i] l1_pfmpc_veh = l1_df[l1_df["veh_ind"] == i] lfbk_veh = lfbk_df[lfbk_df["veh_ind"] == i] ax[0, 0].plot( quad_pfmpc_veh["time"].to_numpy(), quad_pfmpc_veh["ego_position"].to_numpy(), label=f"{i}", zorder=max(veh_inds) - i, color="C{}".format(i), linewidth=linewidth, linestyle=linestyle, alpha=alphas[i], ) ax[0, 1].plot( l1_pfmpc_veh["time"].to_numpy(), l1_pfmpc_veh["ego_position"].to_numpy(), label=f"{i}", zorder=max(veh_inds) - i, color="C{}".format(i), linewidth=linewidth, linestyle=linestyle, alpha=alphas[i], ) ax[0, 2].plot( lfbk_veh["time"].to_numpy(), lfbk_veh["ego_position"].to_numpy(), label=f"{i}", zorder=max(veh_inds) - i, color="C{}".format(i), linewidth=linewidth, linestyle=linestyle, alpha=alphas[i], ) ax[1, 0].plot( quad_pfmpc_veh["time"].to_numpy(), quad_pfmpc_veh["ego_speed"].to_numpy(), label=f"{i}", zorder=max(veh_inds) - i, color="C{}".format(i), linewidth=linewidth, linestyle=linestyle, alpha=alphas[i], ) ax[1, 1].plot( l1_pfmpc_veh["time"].to_numpy(), l1_pfmpc_veh["ego_speed"].to_numpy(), label=f"{i}", zorder=max(veh_inds) - i, color="C{}".format(i), linewidth=linewidth, linestyle=linestyle, alpha=alphas[i], ) ax[1, 2].plot( lfbk_veh["time"].to_numpy(), lfbk_veh["ego_speed"].to_numpy(), label=f"{i}", zorder=max(veh_inds) - i, color="C{}".format(i), linewidth=linewidth, linestyle=linestyle, alpha=alphas[i], ) ax[0, 0].set_ylabel("position [m]", fontsize=axes_size) ax[1, 0].set_ylabel("velocity [m/s]", fontsize=axes_size) ax[1, 0].set_xlabel("time [s]", fontsize=axes_size) ax[1, 1].set_xlabel("time [s]", fontsize=axes_size) ax[1, 2].set_xlabel("time [s]", fontsize=axes_size) for a in ax.flat: a.grid() a.tick_params(axis="both", labelsize=tick_label_size) for a in ax[1, :]: a.set_yticks([0.0, 2.0, 3.5]) ax[1, 2].legend( bbox_to_anchor=(0.99, 1.1), loc="center left", title="vehicle", title_fontsize=legend_title_size, fontsize=legend_font_size, ) plt.show() fig.savefig(save_file_exp, bbox_inches="tight") def get_rms_errors(dfs: List[pd.DataFrame]): veh_inds = [i for i in range(1, max(dfs[0]["veh_ind"]) + 1)] n_vehicles = len(veh_inds) dist_rms_errors = [[] for _ in veh_inds] speed_rms_errors = [[] for _ in veh_inds] for df in dfs: for k, i in enumerate(veh_inds): veh_df = df[df["veh_ind"] == i] dist_err = veh_df["dist_err"].to_numpy() speed_err = veh_df["speed_err"].to_numpy() dist_rms_errors[k].append( np.sqrt(np.sum(np.square(dist_err)) / len(dist_err)) ) speed_rms_errors[k].append( np.sqrt(np.sum(np.square(speed_err)) / len(speed_err)) ) dist_rms_means = np.array([np.mean(dist_rms_errors[i]) for i in range(n_vehicles)]) dist_rms_stds = np.array( [np.std(dist_rms_errors[i], ddof=1) for i in range(n_vehicles)] ) speed_rms_means = np.array( [np.mean(speed_rms_errors[i]) for i in range(n_vehicles)] ) speed_rms_stds = np.array( [np.std(speed_rms_errors[i], ddof=1) for i in range(n_vehicles)] ) return ( dist_rms_errors, speed_rms_errors, dist_rms_means, dist_rms_stds, speed_rms_means, speed_rms_stds, ) def plot_mean_std_rms_error( df_list_of_lists: List[List[pd.DataFrame]], method_names: List[str] ): assert len(df_list_of_lists) == len(method_names) fig, ax = plt.subplots(1, 2, sharey="row", figsize=(4.7, 1.75)) fig.subplots_adjust(0.09, 0.23, 0.77, 0.79, 0.08, 0.1) fig.suptitle("Mean RMSE with 95% confidence intervals", fontsize=title_size) ax[0].set_title("Spacing error", fontsize=subtitle_size) ax[1].set_title("Velocity error", fontsize=subtitle_size) for i, method in enumerate(method_names): rms_results = get_rms_errors(df_list_of_lists[i]) dist_rms_errors, speed_rms_errors = rms_results[:2] dist_rms_means, dist_rms_stds, speed_rms_means, speed_rms_stds = rms_results[2:] veh_inds = range(1, len(dist_rms_means) + 1) # for j in range(len(veh_inds)): # ax[0].scatter((j+1)*np.ones(len(dist_rms_errors[j])), dist_rms_errors[j], # color="C{}".format(i), s=scatter_size) # ax[1].scatter((j+1)*np.ones(len(speed_rms_errors[j])), speed_rms_errors[j], # color="C{}".format(i), s=scatter_size) ax[0].plot(veh_inds, dist_rms_means, color="C{}".format(i), label=method) ax[0].fill_between( veh_inds, dist_rms_means - dist_rms_stds / np.sqrt(10), dist_rms_means + dist_rms_stds / np.sqrt(10), alpha=0.4, ) ax[1].plot(veh_inds, speed_rms_means, color="C{}".format(i), label=method) ax[1].fill_between( veh_inds, speed_rms_means - speed_rms_stds / np.sqrt(10), speed_rms_means + speed_rms_stds / np.sqrt(10), alpha=0.4, ) ax[1].legend( bbox_to_anchor=(1.0, 0.5), loc="center left", fontsize=legend_font_size, title="Method", title_fontsize=legend_title_size, ) ax[0].set_ylabel("RMSE", fontsize=axes_size) ax[0].set_xlabel("Vehicle index", fontsize=axes_size) ax[1].set_xlabel("Vehicle index", fontsize=axes_size) for a in ax: a.grid() a.set_xticks([1, 2, 3]) a.tick_params(axis="both", labelsize=tick_label_size) plt.show() fig.savefig(save_file_rms, bbox_inches="tight") if __name__ == "__main__": data_files = os.listdir(data_loc) data_files.sort() quad_pfmpc_files = [file for file in data_files if "quad_pfmpc" in file] l1_pfmpc_files = [file for file in data_files if "l1_pfmpc" in file] lfbk_files = [file for file in data_files if "lfbk" in file] lfbk_dfs = [] quad_pfmpc_dfs = [] l1_pfmpc_dfs = [] for file in lfbk_files: df = pd.read_csv(data_loc + file) df = remove_zero_vel(df) df = add_position_column(df) lfbk_dfs.append(df) for file in quad_pfmpc_files: df = pd.read_csv(data_loc + file) df = remove_zero_vel(df) df = add_position_column(df) quad_pfmpc_dfs.append(df) for file in l1_pfmpc_files: df = pd.read_csv(data_loc + file) df = remove_zero_vel(df) df = add_position_column(df) l1_pfmpc_dfs.append(df) lfbk_plot_ind = 2 quad_pfmpc_plot_ind = 3 l1_pfmpc_plot_ind = 7 quad_pfmpc_plot_df = quad_pfmpc_dfs[quad_pfmpc_plot_ind] l1_pfmpc_plot_df = l1_pfmpc_dfs[l1_pfmpc_plot_ind] lfbk_plot_df = lfbk_dfs[lfbk_plot_ind] plot_quad_l1_lfbk(quad_pfmpc_plot_df, l1_pfmpc_plot_df, lfbk_plot_df) plot_mean_std_rms_error( [quad_pfmpc_dfs, l1_pfmpc_dfs, lfbk_dfs], method_names=[ rf"$\|\|\cdot\|\|_2^2$ DMPC", "$\|\|\cdot\|\|_1$ DMPC", "Linear feedback", ], )
/* Copyright (C) 2000-2005 SKYRIX Software AG This file is part of SOPE. SOPE is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. SOPE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with SOPE; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "NSObject+QPEval.h" #include "common.h" @interface NSObject(QPEvalPrivates) - (NSArray *)evaluateQueryPathComponent:(NSString *)_pc inContext:(id)_ctx; - (NSArray *)evaluateQueryPathComponents:(NSArray *)_pcs; - (void)takeValue:(id)_value forQueryPath:(NSString *)_qp; - (id)valueForQueryPath:(NSString *)_qp; - (NSException *)setQueryPathValue:(id)_value; - (id)queryPathValue; @end /* NSObject(QPEval) */ @implementation NSString(QP) - (NSArray *)queryPathComponents { NSMutableArray *pc; unsigned i, len, s; if ([self rangeOfString:@"/"].length == 0) return [NSArray arrayWithObject:self]; if ([self isEqualToString:@"/"]) return [NSArray arrayWithObject:self]; pc = [NSMutableArray arrayWithCapacity:8]; len = [self length]; i = 0; /* add root, if absolute path */ if ([self characterAtIndex:0] == '/') { i++; [pc addObject:@"/"]; } for (s = i; i < len; i++) { if ([self characterAtIndex:i] == '/') { unsigned plen; NSString *p; plen = (i - s); p = [self substringWithRange:NSMakeRange(s, plen)]; [pc addObject:p]; s = (i + 1); /* next component begins at idx right after '/' .. */ } else if ([self characterAtIndex:i] == '{') { unsigned j; for (j = (i + 1); j < len; j++) { if ([self characterAtIndex:j] == '}') { /* continue after closing brace .. */ i = j; break; } } } } if (s < i) { NSString *p; p = [self substringWithRange:NSMakeRange(s, (i - s))]; [pc addObject:p]; } return pc; } @end /* NSString(QP) */ @implementation NSObject(QPEval) /* special expressions */ - (id)queryPathRootObjectInContext:(id)_ctx { return self; } /* query path evaluation */ - (NSArray *)evaluateQueryPathComponent:(NSString *)_pc inContext:(id)_ctx { unsigned len; NSArray *result; result = nil; if ((len = [_pc length]) == 0) return nil; else if (len == 1) { unichar c; c = [_pc characterAtIndex:0]; if (c == '/') { id root = [self queryPathRootObjectInContext:_ctx]; result = root ? [NSArray arrayWithObject:root] : nil; } else if (c == '.') result = [NSArray arrayWithObject:self]; } else { } NSLog(@"0x%p<%@> eval QP '%@': %@", self, NSStringFromClass([self class]), _pc, result); return result; } - (NSArray *)queryPathCursorArray { return [NSArray arrayWithObject:self]; } - (NSArray *)evaluateQueryPathComponents:(NSArray *)_pcs { NSEnumerator *pcs; NSString *pc; NSAutoreleasePool *pool; NSArray *array; NSMutableDictionary *ctx; pool = [[NSAutoreleasePool alloc] init]; ctx = [NSMutableDictionary dictionaryWithCapacity:16]; NSLog(@"eval PCs: %@", _pcs); array = [self queryPathCursorArray]; pcs = [_pcs objectEnumerator]; while ((array != nil) && (pc = [pcs nextObject])) { if ((array = [array evaluateQueryPathComponent:pc inContext:ctx]) == nil) break; } array = [array retain]; [pool release]; return [array autorelease]; } - (NSArray *)evaluateQueryPath:(NSString *)_path { if ([_path rangeOfString:@"/"].length == 0) return [self evaluateQueryPathComponents:[NSArray arrayWithObject:_path]]; if ([_path isEqualToString:@"/"]) { static NSArray *rootElem = nil; if (rootElem == nil) rootElem = [NSArray arrayWithObject:@"/"]; return [self evaluateQueryPathComponents:rootElem]; } return [self evaluateQueryPathComponents:[_path queryPathComponents]]; } /* query KVC */ - (NSException *)setQueryPathValue:(id)_value { if (_value == self) return nil; return [NSException exceptionWithName:@"QueryPathEvalException" reason:@"cannot set query-path value on object" userInfo:nil]; } - (id)queryPathValue { return self; } - (void)takeValue:(id)_value forQueryPath:(NSString *)_qp { [[[self evaluateQueryPath:_qp] setQueryPathValue:_value] raise]; } - (id)valueForQueryPath:(NSString *)_qp { return [[self evaluateQueryPath:_qp] queryPathValue]; } @end /* NSObject(QPEval) */ @implementation NSArray(QPEval) - (NSArray *)queryPathCursorArray { return self; } - (NSArray *)evaluateQueryPathComponent:(NSString *)_pc inContext:(id)_ctx { unsigned i, j, count; NSArray *array; id *objs; if ((count = [self count]) == 0) return [NSArray array]; objs = calloc(count + 1, sizeof(id)); for (i = 0, j = 0; i < count; i++) { id obj; obj = [self objectAtIndex:i]; obj = [obj evaluateQueryPathComponent:_pc inContext:_ctx]; if (obj) { objs[j] = obj; j++; } } array = [NSArray arrayWithObjects:objs count:j]; if (objs) free(objs); return array; } @end /* NSArray(QPEval) */ @implementation NSSet(QPEval) - (NSArray *)evaluateQueryPathComponent:(NSString *)_pc inContext:(id)_ctx { return [[self allObjects] evaluateQueryPathComponent:_pc inContext:(id)_ctx]; } - (NSArray *)evaluateQueryPathComponents:(NSArray *)_pcs { return [[self allObjects] evaluateQueryPathComponents:_pcs]; } @end /* NSSet(QPEval) */
<template> <div class="container mt-3"> <div class="row"> <div class="col-md-12"> <div v-if="error" class="text-danger"> <h2>{{error}}</h2> </div> <div v-if="deleteError" class="text-danger"> <h2>{{deleteError}}</h2> </div> <div v-if="post"> <div class="card border-secondary mb-3"> <div class="card-header text-success"><strong>{{post.title}}</strong></div> <div class="card-body"> <div> <span class="badge bg-success me-1 mb-3" v-for="tag in post.tags" :key="tag"> <router-link :to="{name:'Tag',params:{tag:tag}}" class="link-light">{{tag}}</router-link> </span> </div> <p class="card-text">{{post.body}}</p> </div> <div class="card-footer d-flex justify-content-between"> <router-link :to="{name:'EditPost',params:{id:post.id}}" class="btn btn-outline-success d-flex"> <span class="me-3"><strong>Edit</strong></span> <span class="material-icons">edit</span> </router-link> <button class="btn btn-outline-danger d-flex" @click="deletePost"> <span class="me-3"><strong>Delete</strong></span> <span class="material-icons">delete</span> </button> </div> </div> </div> <div v-else> <Spinner></Spinner> </div> </div> </div> </div> </template> <script> import { ref } from '@vue/reactivity' import Spinner from '../components/Spinner' import getPost from "../composables/getPost" import { useRouter } from "vue-router" import {db} from "../firebase/config" export default { components: { Spinner }, props:['id'], setup(props){ let deleteError = ref(""); let router = useRouter(); let {error, post, load} = getPost(props.id); load(); let deletePost = async() =>{ try{ let res = await db.collection('posts').doc(props.id).delete(); router.push({name:'Home'}); }catch(err){ deleteError.value = err.message; } } return {error ,deleteError , post, deletePost} } } </script> <style> </style>
import React from "react"; import {Form, Input, Button, Select, InputNumber, message} from 'antd'; import {dep} from "../../logic/Store"; const serverUrl = 'http://localhost:8080'; const serverGetWalletsUrlSelector = '/wallets/getWalletsFroSelector'; const serverGetWalletsUrl = '/wallets/getWalletsWithBalances'; const { Option } = Select; const layout = { labelCol: { span: 8, }, wrapperCol: { span: 16, }, }; const tailLayout = { wrapperCol: { offset: 8, span: 16, }, }; class Demo extends React.Component { constructor(props) { super(props); this.state = { error: null, isLoaded: false, items: [], wallets: [] }; this.componentDidMount = this.componentDidMount.bind(this); } componentDidMount() { fetch(serverUrl + serverGetWalletsUrlSelector) .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, items: result }); }, (error) => { this.setState({ isLoaded: true, error }); } ) fetch(serverUrl + serverGetWalletsUrl) .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, wallets: result }); }, (error) => { this.setState({ isLoaded: true, error }); } ) } formRef = React.createRef(); onFinish = (values) => { if (values.from === values.to) { var resultMessage = 'Харош, зачем тебе перевод на тот же кошелек?'; message.warn(resultMessage); } else if (this.state.wallets[values.from].balance === -404 && this.state.wallets[values.to].balance === -404) { var resultMessage = 'Оба кошелька невалидны, проверьте токены, номера телефонов. Удостоверьтесь в том что токены обладает полными правами.'; message.warn(resultMessage); } else if (this.state.wallets[values.from].balance === -404) { var resultMessage = 'Кошелек отправителя невалидный, проверьте токен, номер телефона. Удостоверьтесь в том что токен обладает полными правами.'; message.warn(resultMessage); } else if (this.state.wallets[values.to].balance === -404) { var resultMessage = 'Кошелек получателя невалидный, проверьте токен, номер телефона. Удостоверьтесь в том что токен обладает полными правами.'; message.warn(resultMessage); } else if (this.state.wallets[values.from].balance < values.amount) { var resultMessage = 'Недостаточно средств для перевода. На кошельке отправителя ' + this.state.wallets[values.from].balance + ' руб.'; message.warn(resultMessage); } else { dep(values); var resultMessage = 'Успешный перевод с ' + this.state.wallets[values.from].phone + ' на ' + this.state.wallets[values.to].phone + ' на сумму: ' + values.amount + ' руб.'; message.success(resultMessage); this.componentDidMount(); this.formRef.current.resetFields(); } }; onReset = () => { this.formRef.current.resetFields(); }; render() { const {error, isLoaded, items} = this.state; if (error) { return <div>Ошибочка: У вас пока что нет сохраненных кошельков.</div>; } else if (!isLoaded) { return <div>Loading...</div>; } else { return ( <Form {...layout} ref={this.formRef} name="control-ref" onFinish={this.onFinish}> <Form.Item name="from" label="Откуда" rules={[ { required: true, }, ]} > <Select showSearch style={{ width: '90%' }} placeholder="Search to Select" optionFilterProp="children" filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } filterSort={(optionA, optionB) => optionA.children.toLowerCase().localeCompare(optionB.children.toLowerCase()) } key={'from'} > {items.map((value, index) => <Option value={index}>{value}</Option>)} </Select> </Form.Item> <Form.Item name="to" label="Куда" rules={[ { required: true, }, ]} > <Select showSearch style={{ width: '90%' }} placeholder="Search to Select" optionFilterProp="children" filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } filterSort={(optionA, optionB) => optionA.children.toLowerCase().localeCompare(optionB.children.toLowerCase()) } key={'to'} > {items.map((value, index) => <Option value={index}>{value}</Option>)} </Select> </Form.Item> <Form.Item name="amount" label="Сколько:" rules={[ { required: true, }, ]}> <InputNumber key={'amount'} size={"large"} min={0} step={1000}/> </Form.Item> <Form.Item {...tailLayout}> <Button type="primary" htmlType="submit"> Перевести </Button> <Button type="link" htmlType="button" onClick={this.onReset}> Сбросить </Button> </Form.Item> </Form> ); } } } export default Demo;
<template> <v-dialog v-model="showDialog" width="600"> <template v-slot:activator="{ props }"> <v-btn icon="mdi-plus" size="x-large" density="comfortable" elevation="6" :disabled="isLocked" class="fixed-btn" v-bind="props"> </v-btn> </template> <v-card> <v-card-title class="text-h5"> Add Order </v-card-title> <v-tabs v-model="tabs" color="accent"> <v-tab>Sell</v-tab> <v-tab>Buy</v-tab> </v-tabs> <v-window v-model="tabs"> <v-window-item> <v-card-text> <order-form :onClose="() => showDialog = false" :onProcessingUpdate="onProcessingUpdate" orderType="Sell" /> </v-card-text> </v-window-item> <v-window-item> <v-card-text> <order-form :onClose="() => showDialog = false" :onProcessingUpdate="onProcessingUpdate" orderType="Buy" /> </v-card-text> </v-window-item> </v-window> <v-progress-linear v-if="isProcessing" indeterminate/> </v-card> </v-dialog> </template> <script lang="ts" setup> import { computed } from 'vue' import { useAuth } from '@/stores/auth' const authStore = useAuth() const isLocked = computed(() => authStore.isLocked) </script> <script lang="ts"> export default { data() { return { showDialog: false, isProcessing: false, tabs: null } }, methods: { onProcessingUpdate(processing: boolean) { this.isProcessing = processing } } } </script> <style scoped> .fixed-btn { position: fixed; bottom: 2.5em; right: 24px; } </style>
######################################################### # Economic forecasting and analysis # Shiny App - # ########################################################## # load libraries library(shiny) library(fpp2) library(quantmod) library(shinythemes) library(urca) options(rsconnect.max.bundle.size=9368709120) # load data from FRED symbols <- c( "MRTSSM44X72USS","MRTSSM7225USN","MRTSSM4453USS" ) m = length(symbols) getSymbols(symbols,src="FRED") # Define UI ui <- fluidPage(shinythemes::themeSelector(),pageWithSidebar( # Application title headerPanel(h1("Retail Sales Forecasting", align='center')), # Sidebar with controls to select the dataset and forecast ahead duration sidebarPanel( # Select variable selectInput("variable", "Variable:", list("Food Services" = "MRTSSM44X72USS", "Restaurants" = "MRTSSM7225USN", "Alcohol" = "MRTSSM4453USS")), sliderInput("ahead", "Periods to Forecast Ahead:",min=0, max=36, value= 12, step = 2), numericInput("start", "Starting year:", 2010), submitButton("Update View") ), # Show the caption and forecast plots mainPanel( h3(textOutput("caption")), tabsetPanel( tabPanel("Timeseries plot", plotOutput("tsPlot")), tabPanel("Timeseries Decomposition", plotOutput("dcompPlot")), tabPanel("ETS Forecast", plotOutput("etsForecastPlot"), verbatimTextOutput("etsForecastTable")), tabPanel("Arima Forecast", plotOutput("arimaForecastPlot"), verbatimTextOutput("arimaForecastTable")), tabPanel("nnetar Forecast", plotOutput("nnetarForecastPlot"), verbatimTextOutput("nnetarForecastTable")), tabPanel("STL Forecast", plotOutput("STLForecastPlot"), verbatimTextOutput("STLForecastTable")), tabPanel("TBATS Forecast", plotOutput("tbatsForecastPlot"), verbatimTextOutput("tbatsForecastTable")), tabPanel("Average (All Five) forecasts", verbatimTextOutput("averageForecastTable")), tabPanel("Unit Root Test (Test for Stationarity)", verbatimTextOutput ("unitroot")), ) ) )) server <- (function(input, output) { getDataset <- reactive({ if (input$variable=="MRTSSM44X72USS") { return(MRTSSM44X72USS) } else if (input$variable=="MRTSSM7225USN") { return(MRTSSM7225USN) } else { return(MRTSSM4453USS) } }) output$caption <- renderText({ paste("Dataset: ", input$variable) }) output$tsPlot <- renderPlot({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) p1 = autoplot(y) + ylab("values") + geom_line(col="red", size=1.5) p2 = ggAcf(y) gridExtra::grid.arrange(p1, p2, nrow=2) }) output$dcompPlot <- renderPlot({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) f <- decompose(y) plot(f) }) output$arimaForecastPlot <- renderPlot({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) fit <- auto.arima(y) autoplot(forecast(fit, h=input$ahead)) + ylab("sales") }) output$unitroot <- renderPrint({ y <- getDataset() date.start = input$start y <- ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) u <- ur.pp(y) print(summary(u)) }) output$arimaForecastTable <- renderPrint({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) fit <- auto.arima(y) forecast(fit, h=input$ahead) }) output$etsForecastPlot <- renderPlot({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) fit <- ets(y) autoplot(forecast(fit, h=input$ahead)) + ylab('sales') }) output$etsForecastTable <- renderPrint({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) fit <- ets(y) forecast(fit, h=input$ahead) }) output$nnetarForecastPlot <- renderPlot({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) fit <- nnetar(y, lambda = 0) autoplot(forecast(fit, h=input$ahead)) + ylab('sales') }) output$nnetarForecastTable <- renderPrint({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) fit <- nnetar(y, lambda = 0) forecast(fit, h=input$ahead) }) output$STLForecastPlot<- renderPlot({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) fit <- stlf(y) autoplot(forecast(fit, h=input$ahead)) + ylab('sales') }) output$STLForecastTable <- renderPrint({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) fit <- stlf(y) forecast(fit, h=input$ahead) }) output$tbatsForecastPlot <- renderPlot({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) fit <- tbats(y) autoplot(forecast(fit, h=input$ahead)) + ylab('sales') }) output$tbatsForecastTable <- renderPrint({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) fit <- tbats(y) forecast(fit, h=input$ahead) }) output$averageForecastTable <- renderPrint({ y <- getDataset() date.start = input$start y = ts(y[paste(date.start,end(y),sep="/")], start=date.start, freq=12 ) fit1 <- ets(y) fc1 = forecast(fit1, h=input$ahead) fit2 = auto.arima(y) fc2 = forecast(fit2, h=input$ahead) fit3 <- tbats(y) fc3 <- forecast(fit3, h=input$ahead) fit4 <- nnetar(y,lamda=0) fc4 <- forecast(fit4, h=input$ahead) fit5 <- stlf(y) fc5 <- forecast(fit5, h=input$ahead) fc = (fc1$mean + fc2$mean + fc4$mean + fc4$mean + fc5$mean)/5 fc }) }) # Run the application shinyApp(ui = ui, server = server)
from io import BytesIO, TextIOWrapper from unittest import mock from storage.csv_file_storage import CsvFileStorage from storage.sqlite_storage import SqliteStorage from storage.storage_factory import StorageFactory @mock.patch('configparser.open') def test_Storage_Factory_Should_Return_Correct_Storage_For_Csv( mock_file_open: mock.MagicMock): mock_file_open.return_value = TextIOWrapper(BytesIO(b"""[DATA_STORAGE] StorageType = csv CsvHabitStorageFilePath = Data/HabitDefinitions.csv CsvCheckedOutHabitStorageFilePath = Data/CheckedoutHabits.csv [BACKEND_CLIENT] ClientType = InProcess""")) storage = StorageFactory.create_storage() assert type(storage) == CsvFileStorage @mock.patch('configparser.open') def test_Storage_Factory_Should_Return_Correct_Storage_For_Sqlite( mock_file_open: mock.MagicMock): mock_file_open.return_value = TextIOWrapper(BytesIO(b"""[DATA_STORAGE] StorageType = sqlite SqliteDbPath = Data/Data.sqlite [BACKEND_CLIENT] ClientType = InProcess""")) storage = StorageFactory.create_storage() assert type(storage) == SqliteStorage
<?xml version="1.0" encoding="UTF-8" ?> <!-- **********************************************************************--> <!-- Copyright 2012-2017 --> <!-- Matthew Boelkins --> <!-- --> <!-- This file is part of Active Calculus. --> <!-- --> <!-- Permission is granted to copy, distribute and/or modify this document --> <!-- under the terms of the Creative Commons BY-NC-SA license. The work --> <!-- may be used for free by any party so long as attribution is given to --> <!-- the author(s), the work and its derivatives are used in the spirit of --> <!-- "share and share alike"; no party may sell this work or any of its --> <!-- derivatives for profit. All trademarks are the registered marks of --> <!-- their respective owners. --> <!-- **********************************************************************--> <activity xmlns:xi="http://www.w3.org/2001/XInclude" xml:id="act-6-2-3"> <statement> <p> In each of the following questions, draw a careful, labeled sketch of the region described, as well as the resulting solid that results from revolving the region about the stated axis. In addition, draw a representative slice and state the volume of that slice, along with a definite integral whose value is the volume of the entire solid. It is not necessary to evaluate the integrals you find. For each prompt, use the finite region <m>S</m> in the first quadrant bounded by the curves <m>y = 2x</m> and <m>y = x^3</m>. <ol label="a." cols="2"> <li> <p> Revolve <m>S</m> about the line <m>y = -2</m>. </p> </li> <li> <p> Revolve <m>S</m> about the line <m>y = 4</m>. </p> </li> <li> <p> Revolve <m>S</m> about the line <m>x=-1</m>. </p> </li> <li> <p> Revolve <m>S</m> about the line <m>x = 5</m>. </p> </li> </ol> </p> </statement> <hint> <p> <ol label="a."> <li> <p> Note that the two curves intersect in the first quadrant at <m>(0,0)</m> and <m>(\sqrt{2}, 2\sqrt{2})</m>. </p> </li> <li> <p> The outer radius is <m>R(x) = 4 - x^3</m>. </p> </li> <li> <p> Solve the equations governing the two curves for <m>x</m> in terms of <m>y</m>. </p> </li> <li> <p> The inner radius is <m>R(y) = 5 - y^{1/3}</m>. </p> </li> </ol> </p> </hint> <answer> <p> <ol label="a."> <li> <p> T <me> V = \int_{0}^{\sqrt{2}} \pi ( (2x+2)^2 - (x^3 + 2)^2 ) \, dx = \frac{4}{21}(21+8\sqrt{2}) \pi \approx 19.336 </me>. </p> </li> <li> <p> <me> V = \int_{0}^{\sqrt{2}} \pi ( (4 - x^3)^2 - (4-2x)^2 ) \, dx = \left( 8-\frac{32\sqrt{2}}{21} \right)\pi \approx 18.3626 </me>. </p> </li> <li> <p> <me> V = \int_{0}^{2\sqrt{2}} \pi( (y^{1/3} + 1)^2 - (\frac{1}{2}y + 1)^2 ) \, dy = \frac{2}{15}(15 + 8\sqrt{2}) \pi \approx 11.022 </me>. </p> </li> <li> <p> <me> V = \int_{0}^{2\sqrt{2}} \pi( (5 - \frac{1}{2}y)^2 - (5 - y^{1/3})^2 ) \, dy = \frac{2}{15}(75-8\sqrt{2})\pi \approx 26.677 </me>. </p> </li> </ol> </p> </answer> <solution> <p> <ol label="a."> <li> <p> The two curves intersect in the first quadrant at <m>(0,0)</m> and <m>(\sqrt{2}, 2\sqrt{2})</m>. Revolving the region <m>S</m> about the line <m>y = -2</m>, we see that a typical slice is a washer with thickness <m>\Delta x</m>, outer radius <m>R(x) = 2x + 2</m>, and inner radius <m>r(x) = x^3 + 2</m>. It follows by the washer method that <me> V = \int_{0}^{\sqrt{2}} \pi ( (2x+2)^2 - (x^3 + 2)^2 ) \, dx = \frac{4}{21}(21+8\sqrt{2}) \pi \approx 19.336 </me>. </p> </li> <li> <p> In this situation, revolving about <m>y = 4</m>, we see that the outer radius of a typical washer is <m>R(x) = 4 - x^3</m>, while the inner radius is <m>r(x) = 4 - 2x</m>, and thus the volume is <me> V = \int_{0}^{\sqrt{2}} \pi ( (4 - x^3)^2 - (4-2x)^2 ) \, dx = \left( 8-\frac{32\sqrt{2}}{21} \right)\pi \approx 18.3626 </me>. </p> </li> <li> <p> Because we are revolving about <m>x = -1</m>, when we slice perpendicular to this we get washers of thickness <m>\Delta y</m>, and thus we need to write the two curves as functions of <m>y</m> in order to determine the radii of the slices as functions of <m>y</m>, we note that the line can be expressed as <m>x = \frac{1}{2}y</m> and the cubic curve can be rewritten in the form <m>x = y^{1/3}</m>. The outer radius of a typical slice is thus <m>R(y) = y^{1/3} + 1</m> and the inner radius is <m>r(y) = \frac{1}{2}y + 1</m>. It follows that the volume of the solid is <me> V = \int_{0}^{2\sqrt{2}} \pi( (y^{1/3} + 1)^2 - (\frac{1}{2}y + 1)^2 ) \, dy = \frac{2}{15}(15 + 8\sqrt{2}) \pi \approx 11.022 </me>. </p> </li> <li> <p> Here, the outer radius is <m>R(y) = 5 - \frac{1}{2}y</m> and the inner radius is <m>r(y) = 5 - y^{1/3}</m>, so the total volume of the solid is <me> V = \int_{0}^{2\sqrt{2}} \pi( (5 - \frac{1}{2}y)^2 - (5 - y^{1/3})^2 ) \, dy = \frac{2}{15}(75-8\sqrt{2})\pi \approx 26.677 </me>. </p> </li> </ol> </p> </solution> </activity>
/* * Copyright 2023 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.pensionschemereturn.connectors import com.github.tomakehurst.wiremock.client.WireMock import com.github.tomakehurst.wiremock.client.WireMock._ import play.api.http.Status.{BAD_REQUEST, CREATED} import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.json.{JsObject, Json} import play.api.mvc.RequestHeader import play.api.test.FakeRequest import play.api.test.Helpers.{await, defaultAwaitTimeout} import uk.gov.hmrc.http.{BadRequestException, HeaderCarrier, HttpResponse} import uk.gov.hmrc.pensionschemereturn.connectors.PsrConnectorSpec.{ sampleSippPsrResponseAsJsonString, sampleStandardPsrResponseAsJsonString } import uk.gov.hmrc.pensionschemereturn.models.response.{PsrSubmissionEtmpResponse, SippPsrSubmissionEtmpResponse} import scala.concurrent.ExecutionContext.Implicits.global class PsrConnectorSpec extends BaseConnectorSpec { implicit val hc: HeaderCarrier = HeaderCarrier() private implicit lazy val rh: RequestHeader = FakeRequest("", "") override lazy val applicationBuilder: GuiceApplicationBuilder = super.applicationBuilder.configure("microservice.services.if-hod.port" -> wireMockPort) private def createJsonObject(msg: String = "Sample Response"): JsObject = Json.obj( "msg" -> msg ) private lazy val connector: PsrConnector = applicationBuilder.injector().instanceOf[PsrConnector] "submitStandardPsr" should { "return 201 - created" in { stubPost( "/pension-online/psr/standard", Json.stringify(createJsonObject()), created() ) whenReady(connector.submitStandardPsr(createJsonObject())) { result: HttpResponse => WireMock.verify( postRequestedFor(urlEqualTo("/pension-online/psr/standard")) ) result.status mustBe CREATED } } } "getStandardPsr" should { "return a standard PSR value with only fbNumber" in { stubGet( "/pension-online/psr/standard/testPstr?fbNumber=testFbNumber", ok(sampleStandardPsrResponseAsJsonString) ) whenReady(connector.getStandardPsr("testPstr", Some("testFbNumber"), None, None)) { result: Option[PsrSubmissionEtmpResponse] => WireMock.verify( getRequestedFor(urlEqualTo("/pension-online/psr/standard/testPstr?fbNumber=testFbNumber")) ) result mustBe Some(samplePsrSubmissionEtmpResponse) } } "return a standard PSR value with periodStartDate and psrVersion" in { stubGet( "/pension-online/psr/standard/testPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion", ok(sampleStandardPsrResponseAsJsonString) ) whenReady(connector.getStandardPsr("testPstr", None, Some("testPeriodStartDate"), Some("testPsrVersion"))) { result: Option[PsrSubmissionEtmpResponse] => WireMock.verify( getRequestedFor( urlEqualTo( "/pension-online/psr/standard/testPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion" ) ) ) result mustBe Some(samplePsrSubmissionEtmpResponse) } } "return 404 NotFound when pstr not found in etmp" in { stubGet( "/pension-online/psr/standard/notFoundTestPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion", notFound() ) whenReady(connector.getStandardPsr("notFoundTestPstr", None, Some("testPeriodStartDate"), Some("testPsrVersion"))) { result: Option[_] => WireMock.verify( getRequestedFor( urlEqualTo( "/pension-online/psr/standard/notFoundTestPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion" ) ) ) result mustBe None } } "return 400 BadRequest when etmp returns badRequest" in { stubGet( "/pension-online/psr/standard/invalidTestPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion", badRequest().withBody("INVALID_PAYLOAD") ) val thrown = intercept[BadRequestException] { await(connector.getStandardPsr("invalidTestPstr", None, Some("testPeriodStartDate"), Some("testPsrVersion"))) } WireMock.verify( getRequestedFor( urlEqualTo( "/pension-online/psr/standard/invalidTestPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion" ) ) ) thrown.responseCode mustBe BAD_REQUEST thrown.message must include(s"Response body 'INVALID_PAYLOAD'") } "return 400 BadRequest when missing parameters" in { val thrown = intercept[BadRequestException] { await(connector.getStandardPsr("testPstr", None, None, None)) } thrown.responseCode mustBe BAD_REQUEST thrown.message mustEqual "Missing url parameters" } } "submitSippPsr" should { "return 201 - created" in { stubPost( "/pension-online/psr/sipp", Json.stringify(createJsonObject()), created() ) whenReady(connector.submitSippPsr(createJsonObject())) { result: HttpResponse => WireMock.verify( postRequestedFor(urlEqualTo("/pension-online/psr/sipp")) ) result.status mustBe CREATED } } } "getSippPsr" should { "return a SIPP PSR value with only fbNumber" in { stubGet( "/pension-online/psr/sipp/testPstr?fbNumber=testFbNumber", ok(sampleSippPsrResponseAsJsonString) ) whenReady(connector.getSippPsr("testPstr", Some("testFbNumber"), None, None)) { result: Option[SippPsrSubmissionEtmpResponse] => WireMock.verify( getRequestedFor(urlEqualTo("/pension-online/psr/sipp/testPstr?fbNumber=testFbNumber")) ) result mustBe Some(sampleSippPsrSubmissionEtmpResponse) } } "return a SIPP PSR value with periodStartDate and psrVersion" in { stubGet( "/pension-online/psr/sipp/testPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion", ok(sampleSippPsrResponseAsJsonString) ) whenReady(connector.getSippPsr("testPstr", None, Some("testPeriodStartDate"), Some("testPsrVersion"))) { result: Option[SippPsrSubmissionEtmpResponse] => WireMock.verify( getRequestedFor( urlEqualTo( "/pension-online/psr/sipp/testPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion" ) ) ) result mustBe Some(sampleSippPsrSubmissionEtmpResponse) } } "return 404 NotFound when pstr not found in etmp" in { stubGet( "/pension-online/psr/sipp/notFoundTestPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion", notFound() ) whenReady(connector.getSippPsr("notFoundTestPstr", None, Some("testPeriodStartDate"), Some("testPsrVersion"))) { result: Option[_] => WireMock.verify( getRequestedFor( urlEqualTo( "/pension-online/psr/sipp/notFoundTestPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion" ) ) ) result mustBe None } } "return 400 BadRequest when etmp returns badRequest" in { stubGet( "/pension-online/psr/sipp/invalidTestPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion", badRequest().withBody("INVALID_PAYLOAD") ) val thrown = intercept[BadRequestException] { await(connector.getSippPsr("invalidTestPstr", None, Some("testPeriodStartDate"), Some("testPsrVersion"))) } WireMock.verify( getRequestedFor( urlEqualTo( "/pension-online/psr/sipp/invalidTestPstr?periodStartDate=testPeriodStartDate&psrVersion=testPsrVersion" ) ) ) thrown.responseCode mustBe BAD_REQUEST thrown.message must include(s"Response body 'INVALID_PAYLOAD'") } "return 400 BadRequest when missing parameters" in { val thrown = intercept[BadRequestException] { await(connector.getSippPsr("testPstr", None, None, None)) } thrown.responseCode mustBe BAD_REQUEST thrown.message mustEqual "Missing url parameters" } } } object PsrConnectorSpec { val sampleStandardPsrResponseAsJsonString: String = """ |{ | "schemeDetails": { | "pstr": "12345678AA", | "schemeName": "My Golden Egg scheme" | }, | "psrDetails": { | "fbVersion": "001", | "fbstatus": "Compiled", | "periodStart": "2023-04-06", | "periodEnd": "2024-04-05", | "compilationOrSubmissionDate": "2023-12-17T09:30:47Z" | }, | "accountingPeriodDetails": { | "recordVersion": "002", | "accountingPeriods": [ | { | "accPeriodStart": "2022-04-06", | "accPeriodEnd": "2022-12-31" | }, | { | "accPeriodStart": "2023-01-01", | "accPeriodEnd": "2023-04-05" | } | ] | }, | "schemeDesignatory": { | "recordVersion": "002", | "openBankAccount": "Yes", | "noOfActiveMembers": 5, | "noOfDeferredMembers": 2, | "noOfPensionerMembers": 10, | "totalAssetValueStart": 10000000, | "totalAssetValueEnd": 11000000, | "totalCashStart": 2500000, | "totalCashEnd": 2800000, | "totalPayments": 2000000 | }, | "membersPayments": { | "recordVersion": "002", | "employerContributionMade": "Yes", | "unallocatedContribsMade": "No", | "memberContributionMade": "Yes", | "schemeReceivedTransferIn": "Yes", | "schemeMadeTransferOut": "Yes", | "lumpSumReceived": "Yes", | "pensionReceived": "Yes", | "surrenderMade": "Yes", | "memberDetails": [ | { | "memberStatus": "Changed", | "memberPSRVersion": "001", | "personalDetails": { | "foreName": "Ferdinand", | "middleName": "Felix", | "lastName": "Bull", | "nino": "EB103145A", | "dateOfBirth": "1960-05-31" | }, | "noOfContributions": 2, | "memberEmpContribution": [ | { | "orgName": "Acme Ltd", | "organisationIdentity": { | "orgType": "01", | "idNumber": "AC123456" | }, | "totalContribution": 20000 | }, | { | "orgName": "UK Company Ltd", | "organisationIdentity": { | "orgType": "01", | "idNumber": "AC123456" | }, | "totalContribution": 10000 | } | ], | "totalContributions": 30000, | "noOfTransfersIn": 2, | "memberTransfersIn": [ | { | "dateOfTransfer": "2022-08-08", | "schemeName": "The Happy Retirement Scheme", | "transferSchemeType": { | "schemeType": "02", | "refNumber": "Q123456" | }, | "transferValue": 10000, | "transferIncludedAsset": "No" | }, | { | "dateOfTransfer": "2022-11-27", | "schemeName": "The Happy Retirement Scheme", | "transferSchemeType": { | "schemeType": "02", | "refNumber": "Q123456" | }, | "transferValue": 8000, | "transferIncludedAsset": "No" | } | ], | "noOfTransfersOut": 2, | "memberTransfersOut": [ | { | "dateOfTransfer": "2022-09-30", | "schemeName": "The Golden Egg Scheme", | "transferSchemeType": { | "schemeType": "01", | "refNumber": "76509173AA" | } | }, | { | "dateOfTransfer": "2022-12-20", | "schemeName": "The Golden Egg Scheme", | "transferSchemeType": { | "schemeType": "01", | "refNumber": "76509173AB" | } | } | ], | "memberLumpSumReceived": [ | { | "lumpSumAmount": 1000, | "designatedPensionAmount": 100000 | }, | { | "lumpSumAmount": 2000, | "designatedPensionAmount": 99000 | } | ], | "pensionAmountReceived": 12000, | "memberPensionSurrender": [ | { | "totalSurrendered": 1000, | "dateOfSurrender": "2022-12-19", | "surrenderReason": "ABC" | }, | { | "totalSurrendered": 2000, | "dateOfSurrender": "2023-02-08", | "surrenderReason": "I felt like giving money away..." | } | ] | }, | { | "memberStatus": "Changed", | "memberPSRVersion": "001", | "personalDetails": { | "foreName": "Johnny", | "middleName": "Be", | "lastName": "Quicke", | "reasonNoNINO": "Could not find it on record.", | "dateOfBirth": "1940-10-31" | }, | "noOfContributions": 2, | "memberEmpContribution": [ | { | "orgName": "Sofa Inc.", | "organisationIdentity": { | "orgType": "03", | "otherDescription": "Found it down back of my sofa" | }, | "totalContribution": 10000 | }, | { | "orgName": "UK Company XYZ Ltd.", | "organisationIdentity": { | "orgType": "01", | "idNumber": "CC123456" | }, | "totalContribution": 10000 | } | ], | "totalContributions": 20000, | "noOfTransfersIn": 2, | "memberTransfersIn": [ | { | "dateOfTransfer": "2022-12-02", | "schemeName": "Golden Years Pension Scheme", | "transferSchemeType": { | "schemeType": "01", | "refNumber": "88390774ZZ" | }, | "transferValue": 50000, | "transferIncludedAsset": "Yes" | }, | { | "dateOfTransfer": "2022-10-30", | "schemeName": "Golden Goose Egg Laying Scheme", | "transferSchemeType": { | "schemeType": "02", | "refNumber": "Q654321" | }, | "transferValue": 2000, | "transferIncludedAsset": "No" | } | ], | "noOfTransfersOut": 2, | "memberTransfersOut": [ | { | "dateOfTransfer": "2022-05-30", | "schemeName": "Dodgy Pensions Ltd", | "transferSchemeType": { | "schemeType": "03", | "otherDescription": "Unknown identifier" | } | }, | { | "dateOfTransfer": "2022-07-31", | "schemeName": "My back pocket Pension Scheme", | "transferSchemeType": { | "schemeType": "02", | "refNumber": "Q000002" | } | } | ] | } | ] | }, | "loans": { | "recordVersion": "003", | "schemeHadLoans": "Yes", | "noOfLoans": 1, | "loanTransactions": [ | { | "dateOfLoan": "2023-03-30", | "loanRecipientName": "Electric Car Co.", | "recipientIdentityType": { | "indivOrOrgType": "01", | "otherDescription": "Identification not on record." | }, | "recipientSponsoringEmployer": "No", | "connectedPartyStatus": "01", | "loanAmount": 10000, | "loanInterestAmount": 2000, | "loanTotalSchemeAssets": 2000, | "loanPeriodInMonths": 24, | "equalInstallments": "Yes", | "loanInterestRate": 5.55, | "securityGiven": "Yes", | "securityDetails": "Japanese ming vase #344343444.", | "capRepaymentCY": 5000, | "intReceivedCY": 555, | "arrearsPrevYears": "No", | "amountOutstanding": 5000 | } | ] | }, | "shares": { | "recordVersion": "001", | "sponsorEmployerSharesWereHeld": "Yes", | "noOfSponsEmplyrShareTransactions": 1, | "unquotedSharesWereHeld": "No", | "noOfUnquotedShareTransactions": 1, | "connectedPartySharesWereHeld": "Yes", | "noOfConnPartyTransactions": 1, | "sponsorEmployerSharesWereDisposed": "Yes", | "unquotedSharesWereDisposed": "Yes", | "connectedPartySharesWereDisposed": "Yes", | "shareTransactions": [ | { | "typeOfSharesHeld": "01", | "shareIdentification": { | "nameOfSharesCompany": "AppleSauce Inc.", | "reasonNoCRN": "Not able to locate Company on Companies House", | "classOfShares": "Ordinary Shares" | }, | "heldSharesTransaction": { | "methodOfHolding": "01", | "dateOfAcqOrContrib": "2022-10-29", | "totalShares": 200, | "acquiredFromName": "Fredd Bloggs", | "acquiredFromType": { | "indivOrOrgType": "01", | "idNumber": "JE123176A" | }, | "connectedPartyStatus": "02", | "costOfShares": 10000, | "supportedByIndepValuation": "Yes", | "totalAssetValue": 2000, | "totalDividendsOrReceipts": 500 | }, | "disposedSharesTransaction": [ | { | "methodOfDisposal": "01", | "salesQuestions": { | "dateOfSale": "2023-02-16", | "noOfSharesSold": 50, | "amountReceived": 8000, | "nameOfPurchaser": "Sharebuyers Inc.", | "purchaserType": { | "indivOrOrgType": "01", | "idNumber": "0008503350" | }, | "connectedPartyStatus": "02", | "supportedByIndepValuation": "Yes" | }, | "totalSharesNowHeld": 150 | }, | { | "methodOfDisposal": "02", | "redemptionQuestions": { | "dateOfRedemption": "2023-03-06", | "noOfSharesRedeemed": 50, | "amountReceived": 7600 | }, | "totalSharesNowHeld": 100 | } | ] | }, | { | "typeOfSharesHeld": "03", | "shareIdentification": { | "nameOfSharesCompany": "Pear Computers Inc.", | "crnNumber": "LP289157", | "classOfShares": "Preferred Shares" | }, | "heldSharesTransaction": { | "methodOfHolding": "01", | "dateOfAcqOrContrib": "2023-02-23", | "totalShares": 10000, | "acquiredFromName": "Golden Investments Ltd.", | "acquiredFromType": { | "indivOrOrgType": "03", | "idNumber": "28130262" | }, | "connectedPartyStatus": "02", | "costOfShares": 50000, | "supportedByIndepValuation": "Yes", | "totalAssetValue": 40000, | "totalDividendsOrReceipts": 200 | }, | "disposedSharesTransaction": [ | { | "methodOfDisposal": "01", | "salesQuestions": { | "dateOfSale": "2022-10-31", | "noOfSharesSold": 1100, | "amountReceived": 30000, | "nameOfPurchaser": "Share Acquisitions Inc.", | "purchaserType": { | "indivOrOrgType": "01", | "idNumber": "JJ507888A" | }, | "connectedPartyStatus": "02", | "supportedByIndepValuation": "Yes" | }, | "totalSharesNowHeld": 8000 | }, | { | "methodOfDisposal": "02", | "redemptionQuestions": { | "dateOfRedemption": "2022-12-20", | "noOfSharesRedeemed": 900, | "amountReceived": 27005.78 | }, | "totalSharesNowHeld": 8000 | } | ] | }, | { | "typeOfSharesHeld": "03", | "shareIdentification": { | "nameOfSharesCompany": "Connected Party Inc.", | "crnNumber": "LP289157", | "classOfShares": "Convertible Preference Shares" | }, | "heldSharesTransaction": { | "methodOfHolding": "02", | "dateOfAcqOrContrib": "2023-02-23", | "totalShares": 1000, | "acquiredFromName": "Investec Inc.", | "acquiredFromType": { | "indivOrOrgType": "02", | "idNumber": "0000123456" | }, | "connectedPartyStatus": "02", | "costOfShares": 120220.34, | "supportedByIndepValuation": "Yes", | "totalAssetValue": 10000, | "totalDividendsOrReceipts": 599.99 | }, | "disposedSharesTransaction": [ | { | "methodOfDisposal": "02", | "redemptionQuestions": { | "dateOfRedemption": "2022-11-03", | "noOfSharesRedeemed": 200, | "amountReceived": 50000 | }, | "totalSharesNowHeld": 800 | }, | { | "methodOfDisposal": "01", | "salesQuestions": { | "dateOfSale": "2022-12-31", | "noOfSharesSold": 200, | "amountReceived": 52000, | "nameOfPurchaser": "Sam Smithsonian", | "purchaserType": { | "indivOrOrgType": "01", | "idNumber": "JE443364A" | }, | "connectedPartyStatus": "01", | "supportedByIndepValuation": "Yes" | }, | "totalSharesNowHeld": 400 | } | ] | } | ], | "totalValueQuotedShares": 5600000 | }, | "assets": { | "landOrProperty": { | "recordVersion": "001", | "heldAnyLandOrProperty": "Yes", | "disposeAnyLandOrProperty": "No", | "noOfTransactions": 1, | "landOrPropertyTransactions": [ | { | "propertyDetails": { | "landOrPropertyInUK": "Yes", | "addressDetails": { | "addressLine1": "testAddressLine1", | "addressLine2": "testAddressLine2", | "addressLine3": "testAddressLine3", | "ukPostCode": "GB135HG", | "countryCode": "GB" | }, | "landRegistryDetails": { | "landRegistryReferenceExists": "Yes", | "landRegistryReference": "landRegistryTitleNumberValue" | } | }, | "heldPropertyTransaction": { | "methodOfHolding": "01", | "dateOfAcquisitionOrContribution": "2023-10-19", | "propertyAcquiredFromName": "PropertyAcquiredFromName", | "propertyAcquiredFrom": { | "indivOrOrgType": "02", | "idNumber": "idNumber" | }, | "connectedPartyStatus": "01", | "totalCostOfLandOrProperty": 1.7976931348623157E+308, | "indepValuationSupport": "Yes", | "residentialSchedule29A": "Yes", | "landOrPropertyLeased": "Yes", | "leaseDetails": { | "lesseeName": "lesseeName", | "connectedPartyStatus": "01", | "leaseGrantDate": "2023-10-19", | "annualLeaseAmount": 1.7976931348623157E+308 | }, | "totalIncomeOrReceipts": 1.7976931348623157E+308 | }, | "disposedPropertyTransaction": [ | { | "methodOfDisposal": "01", | "dateOfSale": "2022-10-19", | "nameOfPurchaser": "Victor Enterprises Inc.", | "purchaseOrgDetails": { | "indivOrOrgType": "02", | "idNumber": "24896221" | }, | "saleProceeds": 1500000, | "connectedPartyStatus": "01", | "indepValuationSupport": "No", | "portionStillHeld": "No" | } | ] | } | ] | }, | "borrowing": { | "recordVersion": "164", | "moneyWasBorrowed": "No", | "noOfBorrows": 1, | "moneyBorrowed": [ | { | "dateOfBorrow": "2022-10-18", | "amountBorrowed": 2000, | "schemeAssetsValue": 0, | "interestRate": 5.55, | "borrowingFromName": "Loans R Us", | "connectedPartyStatus": "02", | "reasonForBorrow": "We needed the money." | } | ] | }, | "bonds": { | "recordVersion": "528", | "bondsWereAdded": "No", | "bondsWereDisposed": "No", | "noOfTransactions": 2, | "bondTransactions": [ | { | "nameOfBonds": "Xenex Bonds", | "methodOfHolding": "01", | "dateOfAcqOrContrib": "2022-10-06", | "costOfBonds": 10234.56, | "connectedPartyStatus": "02", | "bondsUnregulated": "No", | "totalIncomeOrReceipts": 50, | "bondsDisposed": [ | { | "methodOfDisposal": "01", | "dateSold": "2022-11-30", | "amountReceived": 12333.59, | "bondsPurchaserName": "Happy Bond Buyers Inc.", | "connectedPartyStatus": "02", | "totalNowHeld": 120 | } | ] | }, | { | "nameOfBonds": "Really Goods Bonds ABC", | "methodOfHolding": "03", | "dateOfAcqOrContrib": "2022-07-30", | "costOfBonds": 2000.5, | "connectedPartyStatus": "02", | "bondsUnregulated": "No", | "totalIncomeOrReceipts": 300, | "bondsDisposed": [ | { | "methodOfDisposal": "01", | "dateSold": "2022-08-31", | "amountReceived": 3333.33, | "bondsPurchaserName": "Bonds Buyers (PTY) Ltd", | "connectedPartyStatus": "01", | "totalNowHeld": 50 | } | ] | } | ] | }, | "otherAssets": { | "recordVersion": "002", | "otherAssetsWereHeld": "No", | "otherAssetsWereDisposed": "No", | "noOfTransactions": 2, | "otherAssetTransactions": [ | { | "assetDescription": "Box of matches", | "methodOfHolding": "02", | "dateOfAcqOrContrib": "2022-09-30", | "costOfAsset": 100000, | "acquiredFromName": "Dodgy Den Match Co.", | "acquiredFromType": { | "indivOrOrgType": "04", | "idNumber": "TS315528" | }, | "connectedStatus": "01", | "supportedByIndepValuation": "No", | "movableSchedule29A": "No", | "totalIncomeOrReceipts": 0, | "assetsDisposed": [ | { | "methodOfDisposal": "01", | "dateSold": "2022-12-30", | "purchaserName": "Acme Express Ltd.", | "purchaserType": { | "indivOrOrgType": "04", | "otherDescription": "Foreign purchaser" | }, | "totalAmountReceived": 150000, | "connectedStatus": "02", | "supportedByIndepValuation": "Yes", | "fullyDisposedOf": "Yes" | } | ] | }, | { | "assetDescription": "10kg Gold bars", | "methodOfHolding": "03", | "dateOfAcqOrContrib": "2023-04-30", | "costOfAsset": 2400000, | "acquiredFromName": "GoldBullion.co.uk", | "acquiredFromType": { | "indivOrOrgType": "02", | "idNumber": "SC123456" | }, | "connectedStatus": "02", | "supportedByIndepValuation": "No", | "movableSchedule29A": "No", | "totalIncomeOrReceipts": 0 | } | ] | } | } |} |""".stripMargin val sampleSippPsrResponseAsJsonString: String = """ |{ | "reportDetails": { | "pstr": "12345678AA", | "schemeName": "PSR Scheme", | "psrVersion": "001", | "status": "Compiled", | "periodStart": "2022-04-06", | "periodEnd": "2023-04-05", | "memberTransactions": "Yes" | }, | "accountingPeriodDetails": { | "version": "002", | "accountingPeriods": [ | { | "accPeriodStart": "2022-04-06", | "accPeriodEnd": "2022-12-31" | }, | { | "accPeriodStart": "2023-01-01", | "accPeriodEnd": "2023-04-05" | } | ] | }, | "memberAndTransactions": [ | { | "status": "New", | "version": "000", | "memberDetails": { | "personalDetails": { | "firstName": "Dave", | "middleName": "K", | "lastName": "Robin", | "nino": "AA200000A", | "dateOfBirth": "1900-03-14" | }, | "isUKAddress": "Yes", | "addressDetails": { | "addressLine1": "Brignton", | "addressLine2": "Brignton2", | "addressLine3": "Brignton3", | "addressLine4": "Brignton4", | "addressLine5": "Brignton5", | "ukPostCode": "BN12 4XL", | "countryCode": "GB" | } | }, | "landConnectedParty": { | "noOfTransactions": 1, | "transactionDetails": [ | { | "acquisitionDate": "2023-03-14", | "landOrPropertyinUK": "Yes", | "addressDetails": { | "addressLine1": "London1", | "addressLine2": "London2", | "addressLine3": "London3", | "addressLine4": "London4", | "addressLine5": "London5", | "ukPostCode": "LH3 4DG", | "countryCode": "GB" | }, | "registryDetails": { | "registryRefExist": "No", | "registryReference": "Lost" | }, | "acquiredFromName": "SUN Ltd", | "acquiredFromType": { | "indivOrOrgType": "02", | "idNumber": "CRN123456" | }, | "totalCost": 1234.99, | "independentValution": "No", | "jointlyHeld": "Yes", | "noOfPersons": 1, | "jointPropertyPersonDetails": [ | { | "personName": "Tom K", | "nino": "AA230000A" | } | ], | "residentialSchedule29A": "No", | "isLeased": "Yes", | "lesseeDetails": [ | { | "lesseeName": "Google Ltd ", | "lesseeConnectedParty": "01", | "leaseGrantedDate": "2023-03-14", | "annualLeaseAmount": 9999.99 | } | ], | "totalIncomeOrReceipts": 999999.99, | "isPropertyDisposed": "Yes", | "disposalDetails": { | "disposedPropertyProceedsAmt": 2000.99, | "independentValutionDisposal": "No", | "propertyFullyDisposed": "No", | "purchaserDetails": [ | { | "purchaserConnectedParty": "01", | "purchaserName": "Micheal K" | } | ] | } | } | ] | }, | "otherAssetsConnectedParty": { | "noOfTransactions": 1, | "transactionDetails": [ | { | "acquisitionDate": "2023-03-14", | "assetDescription": "Tesco store", | "acquisitionOfShares": "No", | "acquiredFromName": "Morrisons XYZ", | "acquiredFromType": { | "indivOrOrgType": "01", | "idNumber": "AA200000A" | }, | "totalCost": 99999999.99, | "independentValution": "No", | "tangibleSchedule29A": "No", | "totalIncomeOrReceipts": 9999.99, | "isPropertyDisposed": "No", | "disposalDetails": { | "disposedPropertyProceedsAmt": 9999999.99, | "independentValutionDisposal": "No", | "propertyFullyDisposed": "No", | "purchaserDetails": [ | { | "purchaserConnectedParty": "01", | "purchaserName": "Morris K" | } | ] | }, | "disposalOfShares": "No", | "noOfSharesHeld": 0 | } | ] | }, | "landArmsLength": { | "noOfTransactions": 1, | "transactionDetails": [ | { | "acquisitionDate": "2023-03-14", | "landOrPropertyinUK": "Yes", | "addressDetails": { | "addressLine1": "Brighton1", | "addressLine2": "Brighton2", | "addressLine3": "Brighton3", | "addressLine4": "Brighton4", | "addressLine5": "Brighton5", | "ukPostCode": "BN12 4XL", | "countryCode": "GB" | }, | "registryDetails": { | "registryRefExist": "Yes", | "registryReference": "1234XDF" | }, | "acquiredFromName": "Willco", | "acquiredFromType": { | "indivOrOrgType": "02", | "idNumber": "CRN678901" | }, | "totalCost": 999999.99, | "independentValution": "No", | "jointlyHeld": "No", | "residentialSchedule29A": "No", | "isLeased": "No", | "totalIncomeOrReceipts": 2000.99, | "isPropertyDisposed": "No" | } | ] | }, | "tangibleProperty": { | "noOfTransactions": 1, | "transactionDetails": [ | { | "assetDescription": "Ice Cream Machine", | "acquisitionDate": "2023-03-14", | "totalCost": 999999.99, | "acquiredFromName": "Rambo M", | "acquiredFromType": { | "indivOrOrgType": "01", | "idNumber": "AA250000A" | }, | "independentValution": "No", | "totalIncomeOrReceipts": 9999.99, | "costOrMarket": "Cost Value", | "costMarketValue": 99999.99, | "isPropertyDisposed": "No", | "disposalDetails": { | "disposedPropertyProceedsAmt": 9999.99, | "independentValutionDisposal": "No", | "propertyFullyDisposed": "No", | "purchaserDetails": [ | { | "purchaserConnectedParty": "01", | "purchaserName": "Michel K" | } | ] | } | } | ] | }, | "loanOutstanding": { | "noOfTransactions": 1, | "transactionDetails": [ | { | "loanRecipientName": "Loyds Ltd", | "indivOrOrgIdentityDetails": { | "indivOrOrgType": "02", | "idNumber": "CRN123456" | }, | "dateOfLoan": "2023-03-14", | "amountOfLoan": 999.99, | "loanConnectedParty": "01", | "repayDate": "2023-03-14", | "interestRate": 10, | "loanSecurity": "No", | "capitalRepayments": 99999.99, | "interestPayments": 99999.99, | "arrearsOutstandingPrYears": "No", | "arrearsOutstandingPrYearsAmt": 999999.99, | "outstandingYearEndAmount": 9999.99 | } | ] | }, | "unquotedShares": { | "noOfTransactions": 1, | "transactionDetails": [ | { | "sharesCompanyDetails": { | "companySharesName": "Boeing", | "companySharesCRN": "CRN456789", | "sharesClass": "Primary", | "noOfShares": 100 | }, | "acquiredFromName": "HL Ltd", | "acquiredFromType": { | "indivOrOrgType": "02", | "idNumber": "CRN345345" | }, | "totalCost": 9999.99, | "independentValution": "No", | "noOfSharesSold": 10, | "totalDividendsIncome": 999.99, | "sharesDisposed": "Yes", | "sharesDisposalDetails": { | "disposedShareAmount": 9999.99, | "disposalConnectedParty": "01", | "purchaserName": "Dave SS", | "independentValutionDisposal": "No" | } | } | ] | } | } | ], | "psrDeclaration": { | "submittedBy": "PSP", | "submitterID": "20000019", | "psaID": "A0000023", | "pspDeclaration": { | "declaration1": true, | "declaration2": true | } | } |} |""".stripMargin }
import React, { Component } from "react"; import Auxiliary from "../../auxillary/Auxillary.jsx"; import { Button, Modal, FormControl, InputGroup } from "react-bootstrap"; import "../../../public/css/Modal.css"; import JqxNotification from "jqwidgets-scripts/jqwidgets-react-tsx/jqxnotification"; import $ from "jquery"; class modal extends Component { constructor(props) { super(props); this.state = { show: false }; } handleClose = () => { this.setState({ show: false }); }; handleShow = () => { this.setState({ show: true }); }; AddAndClose = () => { let editData = {}; delete this.props.editSubData["subcategory"]; editData._id = this.props.editSubData["_id"]["$oid"]; editData.parentCategoryId = this.props.editSubData["parentCategoryId"]; editData.subcategory = document.getElementById("editsubcategory").value; if (!editData.subcategory.trim()) { document.getElementById("editsubcat_error_message").innerHTML = "This field can't be empty!"; this.refs.msgNotificationError.open(); return; } console.log(editData); $.ajax({ url: "http://localhost:8000/updatesubcategory", type: "PUT", data: editData, success: function(response) { if (response === "1") { this.props.isUpdated(true); this.handleClose(); } else { console.log("no response"); } }.bind(this), error: function(response) { console.log(response); } }); document.getElementById("editsubcat_success_message").innerHTML = "Subcategory updated Successfully!"; this.refs.msgNotificationSuccess.open(); return; }; render() { return ( <Auxiliary> <JqxNotification ref={"msgNotificationError"} width={250} position={"top-right"} opacity={0.9} autoOpen={false} autoClose={true} animationOpenDelay={800} autoCloseDelay={3000} template={"error"} > <div id="editsubcat_error_message"></div> </JqxNotification> <JqxNotification ref={"msgNotificationSuccess"} width={250} position={"top-right"} opacity={0.9} autoOpen={false} autoClose={true} animationOpenDelay={800} autoCloseDelay={3000} template={"success"} > <div id="editsubcat_success_message">Welcome to our website.</div> </JqxNotification> <Modal show={this.state.show} onHide={this.handleClose}> <Modal.Header closeButton> <Modal.Title>Update SubCategory</Modal.Title> </Modal.Header> <Modal.Body> <InputGroup className="mb-3"> <input type="text" id="editsubcategory" placeholder="Category Name" /> </InputGroup> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={this.handleClose}> Cancel </Button> <Button variant="primary" onClick={this.AddAndClose}> Update SubCategory </Button> </Modal.Footer> </Modal> </Auxiliary> ); } } export default modal;
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace OrderService.Domain.SeedWork { public abstract class Enumeration : IComparable { public string Name { get; set; } public int Id { get; private set; } protected Enumeration(int id, string name) => (Id, Name) = (id, name); public override string ToString() { return Name; } public static IEnumerable<T> GetAll<T>() where T : Enumeration => typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) .Select(x => x.GetValue(null)) .Cast<T>(); public override bool Equals(object? obj) { if (obj is not Enumeration otherValue) return false; var typeMatches = GetType().Equals(obj.GetType()); var valueMatches = Id.Equals(otherValue.Id); return typeMatches && valueMatches; } public override int GetHashCode() => Id.GetHashCode(); public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue) { var absouluteDifference = Math.Abs(firstValue.Id - secondValue.Id); return absouluteDifference; } public static T FromValue<T>(int value) where T : Enumeration { var matchingItem = Parse<T, int>(value, "value", item => item.Id == value); return matchingItem; } public static T FromDisplayName<T>(string displayName) where T : Enumeration { var matchingItem = Parse<T, string>(displayName, "display name", item => item.Name == displayName); return matchingItem; } private static T Parse<T, T1>(T1 value, string description, Func<object, bool> predicate) where T : Enumeration { var matchingItem = GetAll<T>().FirstOrDefault(predicate); if (matchingItem == null) throw new InvalidOperationException($"'{value}' is not a valid {description} in {typeof(T)}"); return (T)matchingItem; } public int CompareTo(object obj) { return Id.CompareTo(((Enumeration)obj).Id); } } }
import { useTranslation } from "react-i18next"; import { hover_transition } from "../../../constants/styles/transitions.style"; interface CurrentComponentProp { text: string; successText: string; icon: string; color?: string; isSubmitting: boolean; isSuccess: boolean; disabled?: boolean; onClickFunction: () => void; } const Info_submit_button = (props: CurrentComponentProp) => { const { text, successText, icon, color, isSubmitting, isSuccess, disabled, onClickFunction, } = props; const { t } = useTranslation(); return ( <button type="button" disabled={disabled ?? (isSubmitting || isSuccess)} className={`${ disabled || isSubmitting ? "border-gray-500 bg-gray-500 text-white" : isSuccess ? "border-green-500 text-green-500" : `${ color ?? "border-primary hover:bg-primary text-primary" } hover:text-white` } border rounded-full px-6 py-2 ${hover_transition}`} onClick={() => { onClickFunction(); }}> {isSubmitting ? ( <> <i className="fa-solid fa-spinner me-2 animate-spin"></i>{t("Info_submit_button_submitting_message")}... </> ) : ( <> <i className={`${isSuccess ? "fa-solid fa-circle-check" : icon} me-4`} /> {isSuccess ? successText : text} </> )} </button> ); }; export default Info_submit_button;
package com.thong.databaseMysql.domain.entities; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @Builder @JsonIgnoreProperties(ignoreUnknown = true) @Entity @Table(name = "supplier") public class SupplierEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "SupplierID") private Integer id; @Column(name = "CompanyName", columnDefinition = "TEXT") private String companyName; @Column(name = "Address") private String address; @Column(name = "City") private String city; @Column(name = "State") private String state; @Column(name = "Zipcode") private String zipcode; @Column(name = "Country") private String country; @Column(name = "ContactPerson") private String contactPerson; @Column(name = "ContactNumber") private String contactNumber; @Column(name = "ContactEmail") private String contactEmail; @Column(name = "ContactFax") private String contactFax; @Column(name = "IsActive") private Boolean isActive; }
#include <stdlib.h> #include "initialization_2D.h" #include "global_parameters.h" void initialize_foreground_random(struct ForegroundVariables2D *fg, struct BackgroundVariables *bg , struct GridInfo2D *grid_info) { /* Initializes the foreground struct with random values. Parameters ---------- fg : ForegroundVariables2D A pointer to the ForegroundVariables2D struct. bg : BackgroundVariables A pointer to the BackgroundVariables struct. grid_info : GridInfo2D A pointer to the GridInfo2D struct. mpi_info : MpiInfo A pointer to the MpiInfo struct. */ initialize_foreground_zeros(fg, grid_info); // Start by setting everyhing to zero // Getting grid info int ny = grid_info->ny; int nz_full = grid_info->nz_full; int nz_ghost = grid_info->nz_ghost; // Inside the grid we pick random values for p1 and s1 and let the boundaries stay zero for (int i = nz_ghost; i < nz_full-nz_ghost-1; i++) { for (int j = 0; j < ny; j++) { fg->p1[i][j] = (2.0 * (rand() / (FLOAT_P)RAND_MAX) - 1.0) * 1e-5; // random between -1e-5 to 1e-5 fg->s1[i][j] = (2.0 * (rand() / (FLOAT_P)RAND_MAX) - 1.0) * 20000; // random between -20000 to 20000 } } // Solving first law of thermodynamics and equation of state to find rho1 and T1 first_law_thermodynamics(fg, bg, grid_info); equation_of_state(fg, bg, grid_info); }
<div> <h2 id="page-heading"> <span>Examples</span> <button id="jh-create-entity" class="btn btn-primary float-right jh-create-entity create-example" [routerLink]="['/example/new']"> <fa-icon [icon]="'plus'"></fa-icon> <span > Create new Example </span> </button> </h2> <jhi-alert></jhi-alert> <br/> <div class="table-responsive" *ngIf="examples"> <table class="table table-striped"> <thead> <tr> <th><span>ID</span></th> <th><span>Example Text</span></th> <th><span>Word</span></th> <th></th> </tr> </thead> <tbody> <tr *ngFor="let example of examples ;trackBy: trackId"> <td><a [routerLink]="['/example', example.id, 'view' ]">{{example.id}}</a></td> <td>{{example.exampleText}}</td> <td> <div *ngIf="example.word"> <a [routerLink]="['../word', example.word?.id, 'view' ]" >{{example.word?.id}}</a> </div> </td> <td class="text-right"> <div class="btn-group flex-btn-group-container"> <button type="submit" [routerLink]="['/example', example.id, 'view' ]" class="btn btn-info btn-sm"> <fa-icon [icon]="'eye'"></fa-icon> <span class="d-none d-md-inline">View</span> </button> <button type="submit" [routerLink]="['/example', example.id, 'edit']" class="btn btn-primary btn-sm"> <fa-icon [icon]="'pencil-alt'"></fa-icon> <span class="d-none d-md-inline">Edit</span> </button> <button type="submit" [routerLink]="['/', { outlets: { popup: 'example/'+ example.id + '/delete'} }]" replaceUrl="true" queryParamsHandling="merge" class="btn btn-danger btn-sm"> <fa-icon [icon]="'times'"></fa-icon> <span class="d-none d-md-inline">Delete</span> </button> </div> </td> </tr> </tbody> </table> </div> </div>
package com.TubesDiKaosan.ecommerce.controllers; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.TubesDiKaosan.ecommerce.models.Roles; import com.TubesDiKaosan.ecommerce.models.Users; import com.TubesDiKaosan.ecommerce.payloads.requests.UserRequest; import com.TubesDiKaosan.ecommerce.payloads.response.Response; import com.TubesDiKaosan.ecommerce.services.ActorServices.CustomerService; import com.TubesDiKaosan.ecommerce.services.ActorServices.UsersService; import jakarta.servlet.http.HttpSession; import jakarta.validation.Valid; @Controller public class AuthController { @Autowired private List<UsersService> usersServices; @RequestMapping("/login") public String login(Model model, HttpSession session) throws SQLException { model.addAttribute("title", "Login"); if (session.getAttribute("user") != null) { Users user = (Users) session.getAttribute("user"); if (user.getRole().getRole_name().equals("ADMIN")) { return "redirect:/dashboard"; } else if (user.getRole().getRole_name().equals("CUSTOMER")) { return "redirect:/"; } } return "pages/login"; } @RequestMapping("/register") public String register(Model model, HttpSession session) throws SQLException { model.addAttribute("title", "Register"); return "pages/register"; } // REGISTER FOR CUSTOMER @PostMapping("/registration") public String registration(@Valid UserRequest UserRequest, Model model, HttpSession session,RedirectAttributes redirectAttributes) throws SQLException { UserRequest.setRole(-1); for (UsersService userService : usersServices) { if (userService instanceof CustomerService) { Roles role_id = (Roles) ((CustomerService) userService).getRolesCustomer().getData(); UserRequest.setRole(role_id.getRole_id()); Response response = ((CustomerService) userService).createData(UserRequest); if (response.getMessage().equals("Email already exist")) { redirectAttributes.addFlashAttribute("alert", "Email sudah terdaftar"); return "pages/register"; } redirectAttributes.addFlashAttribute("alert", "Registrasi berhasil"); return "redirect:/"; } } return "redirect:/"; } // auth login @PostMapping("/authentication") public String authtentication( RedirectAttributes redirectAttributes, @RequestParam("Email") String Email, @RequestParam("password") String password, Model model, HttpSession session) throws SQLException { for (UsersService userService : usersServices) { if (userService instanceof UsersService) { Response response = ((UsersService) userService).login(Email, password); if (response.getMessage().equals("success")) { Users user = (Users) response.getData(); session.setAttribute("user", user); if (user.getRole().getRole_name().equals("ADMIN")) { return "redirect:/dashboard"; } else if (user.getRole().getRole_name().equals("CUSTOMER")) { return "redirect:/"; } } else { redirectAttributes.addFlashAttribute("alert", "salah password atau email ^_^"); return "redirect:/"; } } } return "redirect:/login"; } @PostMapping("/update-password") public String updatePassword(@RequestParam("oldPass") String oldPass, @RequestParam("newPass") String newPass, @RequestParam("confirmPass") String confirmPass, @RequestParam("user_id") String user_id, Model model, HttpSession session, RedirectAttributes redirectAttributes) throws SQLException { for (UsersService userService : usersServices) { if (userService instanceof UsersService) { Response response = ((UsersService) userService).findDataByID(user_id); if (!response.getMessage().equals("Data not found")) { Users user = (Users) response.getData(); if (user.getPassword().equals(oldPass)) { if (newPass.equals(confirmPass)) { user.setPassword(newPass); UserRequest userRequest = new UserRequest(); userRequest.setFirst_name(user.getFirst_name()); userRequest.setLast_name(user.getLast_name()); userRequest.setEmail(user.getEmail()); userRequest.setPassword(newPass); userRequest.setRole(user.getRole_id()); Response update_response = ((UsersService) userService).updateDataById(user_id, userRequest); if (update_response.getStatus() == 200) { session.setAttribute("user", user); redirectAttributes.addFlashAttribute("alert", "Password berhasil dirubah"); return "redirect:/"; } redirectAttributes.addFlashAttribute("alert", "Password gagal dirubah"); return "redirect:/"; } else { // password not match redirectAttributes.addFlashAttribute("alert", "Password yang baru tidak sesuai ^_^"); return "redirect:/"; } } else { // old password not match redirectAttributes.addFlashAttribute("alert", "Password yang lama tidak sesuai ^_^"); return "redirect:/"; } } } } return "redirect:/"; } @RequestMapping("/logout") public String logout(HttpSession session) { if (session.getAttribute("user") != null) { session.removeAttribute("user"); session.invalidate(); return "redirect:/"; } return "redirect:/"; } }
/* ! tailwindcss v3.2.4 | MIT License | https://tailwindcss.com */ /* 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) 2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) */ *, ::before, ::after { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ border-color: #e5e7eb; /* 2 */ } ::before, ::after { --tw-content: ''; } /* 1. Use a consistent sensible line-height in all browsers. 2. Prevent adjustments of font size after orientation changes in iOS. 3. Use a more readable tab size. 4. Use the user's configured `sans` font-family by default. 5. Use the user's configured `sans` font-feature-settings by default. */ html { line-height: 1.5; /* 1 */ -webkit-text-size-adjust: 100%; /* 2 */ -moz-tab-size: 4; /* 3 */ -o-tab-size: 4; tab-size: 4; /* 3 */ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; /* 4 */ font-feature-settings: normal; /* 5 */ } /* 1. Remove the margin in all browsers. 2. Inherit line-height from `html` so users can set them as a class directly on the `html` element. */ body { margin: 0; /* 1 */ line-height: inherit; /* 2 */ } /* 1. Add the correct height in Firefox. 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) 3. Ensure horizontal rules are visible by default. */ hr { height: 0; /* 1 */ color: inherit; /* 2 */ border-top-width: 1px; /* 3 */ } /* Add the correct text decoration in Chrome, Edge, and Safari. */ abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } /* Remove the default font size and weight for headings. */ h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } /* Reset links to optimize for opt-in styling instead of opt-out. */ a { color: inherit; text-decoration: inherit; } /* Add the correct font weight in Edge and Safari. */ b, strong { font-weight: bolder; } /* 1. Use the user's configured `mono` font family by default. 2. Correct the odd `em` font sizing in all browsers. */ code, kbd, samp, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; /* 1 */ font-size: 1em; /* 2 */ } /* Add the correct font size in all browsers. */ small { font-size: 80%; } /* Prevent `sub` and `sup` elements from affecting the line height in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } /* 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) 3. Remove gaps between table borders by default. */ table { text-indent: 0; /* 1 */ border-color: inherit; /* 2 */ border-collapse: collapse; /* 3 */ } /* 1. Change the font styles in all browsers. 2. Remove the margin in Firefox and Safari. 3. Remove default padding in all browsers. */ button, input, optgroup, select, textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 1 */ font-weight: inherit; /* 1 */ line-height: inherit; /* 1 */ color: inherit; /* 1 */ margin: 0; /* 2 */ padding: 0; /* 3 */ } /* Remove the inheritance of text transform in Edge and Firefox. */ button, select { text-transform: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Remove default button styles. */ button, [type='button'], [type='reset'], [type='submit'] { -webkit-appearance: button; /* 1 */ background-color: transparent; /* 2 */ background-image: none; /* 2 */ } /* Use the modern Firefox focus style for all focusable elements. */ :-moz-focusring { outline: auto; } /* Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) */ :-moz-ui-invalid { box-shadow: none; } /* Add the correct vertical alignment in Chrome and Firefox. */ progress { vertical-align: baseline; } /* Correct the cursor style of increment and decrement buttons in Safari. */ ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } /* 1. Correct the odd appearance in Chrome and Safari. 2. Correct the outline style in Safari. */ [type='search'] { -webkit-appearance: textfield; /* 1 */ outline-offset: -2px; /* 2 */ } /* Remove the inner padding in Chrome and Safari on macOS. */ ::-webkit-search-decoration { -webkit-appearance: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Change font properties to `inherit` in Safari. */ ::-webkit-file-upload-button { -webkit-appearance: button; /* 1 */ font: inherit; /* 2 */ } /* Add the correct display in Chrome and Safari. */ summary { display: list-item; } /* Removes the default spacing and border for appropriate elements. */ blockquote, dl, dd, h1, h2, h3, h4, h5, h6, hr, figure, p, pre { margin: 0; } fieldset { margin: 0; padding: 0; } legend { padding: 0; } ol, ul, menu { list-style: none; margin: 0; padding: 0; } /* Prevent resizing textareas horizontally by default. */ textarea { resize: vertical; } /* 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) 2. Set the default placeholder color to the user's configured gray 400 color. */ input::-moz-placeholder, textarea::-moz-placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } input::placeholder, textarea::placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } /* Set the default cursor for buttons. */ button, [role="button"] { cursor: pointer; } /* Make sure disabled buttons don't get the pointer cursor. */ :disabled { cursor: default; } /* 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) This can trigger a poorly considered lint error in some tools but is included by design. */ img, svg, video, canvas, audio, iframe, embed, object { display: block; /* 1 */ vertical-align: middle; /* 2 */ } /* Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) */ img, video { max-width: 100%; height: auto; } /* Make elements with the HTML hidden attribute stay hidden by default */ [hidden] { display: none; } *, ::before, ::after { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } ::backdrop { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } .container { width: 100%; } @media (min-width: 640px) { .container { max-width: 640px; } } @media (min-width: 768px) { .container { max-width: 768px; } } @media (min-width: 1024px) { .container { max-width: 1024px; } } @media (min-width: 1280px) { .container { max-width: 1280px; } } @media (min-width: 1536px) { .container { max-width: 1536px; } } .fixed { position: fixed; } .relative { position: relative; } .col-span-1 { grid-column: span 1 / span 1; } .col-span-6 { grid-column: span 6 / span 6; } .m-0 { margin: 0px; } .m-4 { margin: 1rem; } .mx-16 { margin-left: 4rem; margin-right: 4rem; } .my-14 { margin-top: 3.5rem; margin-bottom: 3.5rem; } .mx-4 { margin-left: 1rem; margin-right: 1rem; } .mx-14 { margin-left: 3.5rem; margin-right: 3.5rem; } .my-2 { margin-top: 0.5rem; margin-bottom: 0.5rem; } .my-20 { margin-top: 5rem; margin-bottom: 5rem; } .my-1 { margin-top: 0.25rem; margin-bottom: 0.25rem; } .mx-6 { margin-left: 1.5rem; margin-right: 1.5rem; } .mt-14 { margin-top: 3.5rem; } .mt-20 { margin-top: 5rem; } .mb-4 { margin-bottom: 1rem; } .mb-5 { margin-bottom: 1.25rem; } .mb-2 { margin-bottom: 0.5rem; } .mr-2 { margin-right: 0.5rem; } .mb-6 { margin-bottom: 1.5rem; } .mt-6 { margin-top: 1.5rem; } .mt-1 { margin-top: 0.25rem; } .mr-0 { margin-right: 0px; } .ml-0 { margin-left: 0px; } .ml-2 { margin-left: 0.5rem; } .mt-3 { margin-top: 0.75rem; } .ml-6 { margin-left: 1.5rem; } .block { display: block; } .inline-block { display: inline-block; } .flex { display: flex; } .table { display: table; } .grid { display: grid; } .contents { display: contents; } .hidden { display: none; } .h-6 { height: 1.5rem; } .h-48 { height: 12rem; } .h-screen { height: 100vh; } .h-5 { height: 1.25rem; } .h-4 { height: 1rem; } .h-40 { height: 10rem; } .h-full { height: 100%; } .max-h-fit { max-height: -moz-fit-content; max-height: fit-content; } .w-6 { width: 1.5rem; } .w-full { width: 100%; } .w-4 { width: 1rem; } .w-screen { width: 100vw; } .w-10 { width: 2.5rem; } .w-5 { width: 1.25rem; } .w-12 { width: 3rem; } .w-8 { width: 2rem; } .min-w-0 { min-width: 0px; } .min-w-fit { min-width: -moz-fit-content; min-width: fit-content; } .max-w-sm { max-width: 24rem; } .max-w-md { max-width: 28rem; } .flex-auto { flex: 1 1 auto; } .transform { transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .cursor-pointer { cursor: pointer; } .grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } .grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); } .grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .flex-col { flex-direction: column; } .items-center { align-items: center; } .items-stretch { align-items: stretch; } .justify-end { justify-content: flex-end; } .justify-center { justify-content: center; } .justify-between { justify-content: space-between; } .gap-10 { gap: 2.5rem; } .gap-1 { gap: 0.25rem; } .gap-2 { gap: 0.5rem; } .gap-4 { gap: 1rem; } .gap-3 { gap: 0.75rem; } .gap-6 { gap: 1.5rem; } .gap-9 { gap: 2.25rem; } .overflow-hidden { overflow: hidden; } .overflow-x-auto { overflow-x: auto; } .overflow-x-hidden { overflow-x: hidden; } .whitespace-nowrap { white-space: nowrap; } .rounded { border-radius: 0.25rem; } .rounded-lg { border-radius: 0.5rem; } .rounded-full { border-radius: 9999px; } .rounded-md { border-radius: 0.375rem; } .border-4 { border-width: 4px; } .border { border-width: 1px; } .border-b { border-bottom-width: 1px; } .border-t { border-top-width: 1px; } .border-solid { border-style: solid; } .border-gray-300 { --tw-border-opacity: 1; border-color: rgb(209 213 219 / var(--tw-border-opacity)); } .border-slate-300 { --tw-border-opacity: 1; border-color: rgb(203 213 225 / var(--tw-border-opacity)); } .border-primary { --tw-border-opacity: 1; border-color: rgb(9 9 121 / var(--tw-border-opacity)); } .border-black { --tw-border-opacity: 1; border-color: rgb(0 0 0 / var(--tw-border-opacity)); } .bg-white { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)); } .bg-blue-600 { --tw-bg-opacity: 1; background-color: rgb(37 99 235 / var(--tw-bg-opacity)); } .bg-gray-50 { --tw-bg-opacity: 1; background-color: rgb(249 250 251 / var(--tw-bg-opacity)); } .bg-gray-200 { --tw-bg-opacity: 1; background-color: rgb(229 231 235 / var(--tw-bg-opacity)); } .bg-gray-100 { --tw-bg-opacity: 1; background-color: rgb(243 244 246 / var(--tw-bg-opacity)); } .bg-mycolor-100 { --tw-bg-opacity: 1; background-color: rgb(13 76 146 / var(--tw-bg-opacity)); } .bg-red-400 { --tw-bg-opacity: 1; background-color: rgb(248 113 113 / var(--tw-bg-opacity)); } .bg-blue-500 { --tw-bg-opacity: 1; background-color: rgb(59 130 246 / var(--tw-bg-opacity)); } .bg-gray-400 { --tw-bg-opacity: 1; background-color: rgb(156 163 175 / var(--tw-bg-opacity)); } .bg-blue-400 { --tw-bg-opacity: 1; background-color: rgb(96 165 250 / var(--tw-bg-opacity)); } .bg-red-700 { --tw-bg-opacity: 1; background-color: rgb(185 28 28 / var(--tw-bg-opacity)); } .bg-blue-700 { --tw-bg-opacity: 1; background-color: rgb(29 78 216 / var(--tw-bg-opacity)); } .bg-red-500 { --tw-bg-opacity: 1; background-color: rgb(239 68 68 / var(--tw-bg-opacity)); } .bg-footer { --tw-bg-opacity: 1; background-color: rgb(63 61 61 / var(--tw-bg-opacity)); } .bg-clip-padding { background-clip: padding-box; } .object-cover { -o-object-fit: cover; object-fit: cover; } .p-2\.5 { padding: 0.625rem; } .p-2 { padding: 0.5rem; } .px-11 { padding-left: 2.75rem; padding-right: 2.75rem; } .py-12 { padding-top: 3rem; padding-bottom: 3rem; } .px-4 { padding-left: 1rem; padding-right: 1rem; } .px-3 { padding-left: 0.75rem; padding-right: 0.75rem; } .py-1\.5 { padding-top: 0.375rem; padding-bottom: 0.375rem; } .py-1 { padding-top: 0.25rem; padding-bottom: 0.25rem; } .px-6 { padding-left: 1.5rem; padding-right: 1.5rem; } .py-2\.5 { padding-top: 0.625rem; padding-bottom: 0.625rem; } .py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; } .px-12 { padding-left: 3rem; padding-right: 3rem; } .py-4 { padding-top: 1rem; padding-bottom: 1rem; } .px-2 { padding-left: 0.5rem; padding-right: 0.5rem; } .py-3 { padding-top: 0.75rem; padding-bottom: 0.75rem; } .px-1 { padding-left: 0.25rem; padding-right: 0.25rem; } .px-5 { padding-left: 1.25rem; padding-right: 1.25rem; } .px-10 { padding-left: 2.5rem; padding-right: 2.5rem; } .py-8 { padding-top: 2rem; padding-bottom: 2rem; } .px-16 { padding-left: 4rem; padding-right: 4rem; } .px-28 { padding-left: 7rem; padding-right: 7rem; } .py-14 { padding-top: 3.5rem; padding-bottom: 3.5rem; } .py-20 { padding-top: 5rem; padding-bottom: 5rem; } .pt-1 { padding-top: 0.25rem; } .pt-4 { padding-top: 1rem; } .pb-2 { padding-bottom: 0.5rem; } .pt-0 { padding-top: 0px; } .pt-12 { padding-top: 3rem; } .pl-16 { padding-left: 4rem; } .pb-1 { padding-bottom: 0.25rem; } .text-left { text-align: left; } .text-center { text-align: center; } .text-end { text-align: end; } .indent-8 { text-indent: 2rem; } .font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; } .font-serif { font-family: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif; } .text-base { font-size: 1rem; line-height: 1.5rem; } .text-xs { font-size: 0.75rem; line-height: 1rem; } .text-sm { font-size: 0.875rem; line-height: 1.25rem; } .text-xl { font-size: 1.25rem; line-height: 1.75rem; } .text-lg { font-size: 1.125rem; line-height: 1.75rem; } .text-2xl { font-size: 1.5rem; line-height: 2rem; } .text-4xl { font-size: 2.25rem; line-height: 2.5rem; } .font-normal { font-weight: 400; } .font-medium { font-weight: 500; } .font-bold { font-weight: 700; } .font-semibold { font-weight: 600; } .uppercase { text-transform: uppercase; } .italic { font-style: italic; } .leading-tight { line-height: 1.25; } .tracking-wider { letter-spacing: 0.05em; } .text-slate-500 { --tw-text-opacity: 1; color: rgb(100 116 139 / var(--tw-text-opacity)); } .text-gray-700 { --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity)); } .text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .text-gray-900 { --tw-text-opacity: 1; color: rgb(17 24 39 / var(--tw-text-opacity)); } .text-gray-500 { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } .text-slate-700 { --tw-text-opacity: 1; color: rgb(51 65 85 / var(--tw-text-opacity)); } .text-primary { --tw-text-opacity: 1; color: rgb(9 9 121 / var(--tw-text-opacity)); } .placeholder-slate-400::-moz-placeholder { --tw-placeholder-opacity: 1; color: rgb(148 163 184 / var(--tw-placeholder-opacity)); } .placeholder-slate-400::placeholder { --tw-placeholder-opacity: 1; color: rgb(148 163 184 / var(--tw-placeholder-opacity)); } .shadow-md { --tw-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-lg { --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-sm { --tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); --tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow { --tw-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .blur { --tw-blur: blur(8px); filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .grayscale { --tw-grayscale: grayscale(100%); filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .invert { --tw-invert: invert(100%); filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .sepia { --tw-sepia: sepia(100%); filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .filter { filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .backdrop-filter { -webkit-backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); } .transition { transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, -webkit-backdrop-filter; transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .transition-opacity { transition-property: opacity; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .duration-150 { transition-duration: 150ms; } .duration-500 { transition-duration: 500ms; } .ease-in-out { transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } .ease-out { transition-timing-function: cubic-bezier(0, 0, 0.2, 1); } .btn { cursor: pointer; border-radius: 9999px; padding-top: 0.5rem; padding-bottom: 0.5rem; padding-left: 0.75rem; padding-right: 0.75rem; font-size: 0.75rem; line-height: 1rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; } :root { --error-color: #dc3545; } .form-field.error input { border-color: var(--error-color) } .form-field.error input:focus { --tw-border-opacity: 1; border-color: rgb(220 38 38 / var(--tw-border-opacity)); outline: 2px solid transparent; outline-offset: 2px; --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); --tw-ring-opacity: 1; --tw-ring-color: rgb(220 38 38 / var(--tw-ring-opacity)); } .form-field.success input { --tw-border-opacity: 1; border-color: rgb(14 165 233 / var(--tw-border-opacity)); } .form-field.success input:focus { --tw-border-opacity: 1; border-color: rgb(14 165 233 / var(--tw-border-opacity)); outline: 2px solid transparent; outline-offset: 2px; --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); --tw-ring-opacity: 1; --tw-ring-color: rgb(14 165 233 / var(--tw-ring-opacity)); } .form-field small { color: var(--error-color); } .form-dynamique-border { border-top-width: 1px; --tw-border-opacity: 1; border-color: rgb(203 213 225 / var(--tw-border-opacity)); } .inputHide { margin-bottom: 1.5rem; width: 100%; border-radius: 0.5rem; border-width: 1px; --tw-border-opacity: 1; border-color: rgb(209 213 219 / var(--tw-border-opacity)); --tw-bg-opacity: 1; background-color: rgb(249 250 251 / var(--tw-bg-opacity)); padding: 0.5rem; font-size: 0.875rem; line-height: 1.25rem; --tw-text-opacity: 1; color: rgb(17 24 39 / var(--tw-text-opacity)); } .inputHide:focus { --tw-border-opacity: 1; border-color: rgb(59 130 246 / var(--tw-border-opacity)); --tw-ring-opacity: 1; --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity)); } @media (prefers-color-scheme: dark) { .inputHide { --tw-border-opacity: 1; border-color: rgb(75 85 99 / var(--tw-border-opacity)); --tw-bg-opacity: 1; background-color: rgb(55 65 81 / var(--tw-bg-opacity)); --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .inputHide::-moz-placeholder { --tw-placeholder-opacity: 1; color: rgb(156 163 175 / var(--tw-placeholder-opacity)); } .inputHide::placeholder { --tw-placeholder-opacity: 1; color: rgb(156 163 175 / var(--tw-placeholder-opacity)); } .inputHide:focus { --tw-border-opacity: 1; border-color: rgb(59 130 246 / var(--tw-border-opacity)); --tw-ring-opacity: 1; --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity)); } } .after\:ml-0\.5::after { content: var(--tw-content); margin-left: 0.125rem; } .after\:ml-0::after { content: var(--tw-content); margin-left: 0px; } .after\:text-red-500::after { content: var(--tw-content); --tw-text-opacity: 1; color: rgb(239 68 68 / var(--tw-text-opacity)); } .after\:content-\[\'\*\'\]::after { --tw-content: '*'; content: var(--tw-content); } .hover\:cursor-pointer:hover { cursor: pointer; } .hover\:bg-blue-700:hover { --tw-bg-opacity: 1; background-color: rgb(29 78 216 / var(--tw-bg-opacity)); } .hover\:bg-slate-200:hover { --tw-bg-opacity: 1; background-color: rgb(226 232 240 / var(--tw-bg-opacity)); } .hover\:bg-red-500:hover { --tw-bg-opacity: 1; background-color: rgb(239 68 68 / var(--tw-bg-opacity)); } .hover\:bg-blue-600:hover { --tw-bg-opacity: 1; background-color: rgb(37 99 235 / var(--tw-bg-opacity)); } .hover\:bg-gray-600:hover { --tw-bg-opacity: 1; background-color: rgb(75 85 99 / var(--tw-bg-opacity)); } .hover\:bg-red-800:hover { --tw-bg-opacity: 1; background-color: rgb(153 27 27 / var(--tw-bg-opacity)); } .hover\:bg-blue-800:hover { --tw-bg-opacity: 1; background-color: rgb(30 64 175 / var(--tw-bg-opacity)); } .hover\:bg-red-600:hover { --tw-bg-opacity: 1; background-color: rgb(220 38 38 / var(--tw-bg-opacity)); } .hover\:bg-red-400:hover { --tw-bg-opacity: 1; background-color: rgb(248 113 113 / var(--tw-bg-opacity)); } .hover\:bg-primary:hover { --tw-bg-opacity: 1; background-color: rgb(9 9 121 / var(--tw-bg-opacity)); } .hover\:bg-blue-400:hover { --tw-bg-opacity: 1; background-color: rgb(96 165 250 / var(--tw-bg-opacity)); } .hover\:text-slate-300:hover { --tw-text-opacity: 1; color: rgb(203 213 225 / var(--tw-text-opacity)); } .hover\:text-white:hover { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .hover\:text-red-500:hover { --tw-text-opacity: 1; color: rgb(239 68 68 / var(--tw-text-opacity)); } .hover\:shadow-lg:hover { --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .focus\:border-blue-600:focus { --tw-border-opacity: 1; border-color: rgb(37 99 235 / var(--tw-border-opacity)); } .focus\:border-blue-500:focus { --tw-border-opacity: 1; border-color: rgb(59 130 246 / var(--tw-border-opacity)); } .focus\:border-sky-500:focus { --tw-border-opacity: 1; border-color: rgb(14 165 233 / var(--tw-border-opacity)); } .focus\:bg-white:focus { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)); } .focus\:bg-blue-700:focus { --tw-bg-opacity: 1; background-color: rgb(29 78 216 / var(--tw-bg-opacity)); } .focus\:text-gray-700:focus { --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity)); } .focus\:shadow-lg:focus { --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .focus\:outline-none:focus { outline: 2px solid transparent; outline-offset: 2px; } .focus\:ring-0:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .focus\:ring-4:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .focus\:ring-1:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .focus\:ring-blue-500:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity)); } .focus\:ring-red-300:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(252 165 165 / var(--tw-ring-opacity)); } .focus\:ring-blue-300:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(147 197 253 / var(--tw-ring-opacity)); } .focus\:ring-sky-500:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(14 165 233 / var(--tw-ring-opacity)); } .focus\:ring-offset-gray-100:focus { --tw-ring-offset-color: #f3f4f6; } .focus\:ring-offset-blue-100:focus { --tw-ring-offset-color: #dbeafe; } .active\:bg-blue-800:active { --tw-bg-opacity: 1; background-color: rgb(30 64 175 / var(--tw-bg-opacity)); } .active\:shadow-lg:active { --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } @media (prefers-color-scheme: dark) { .dark\:border-gray-600 { --tw-border-opacity: 1; border-color: rgb(75 85 99 / var(--tw-border-opacity)); } .dark\:bg-gray-700 { --tw-bg-opacity: 1; background-color: rgb(55 65 81 / var(--tw-bg-opacity)); } .dark\:bg-red-600 { --tw-bg-opacity: 1; background-color: rgb(220 38 38 / var(--tw-bg-opacity)); } .dark\:bg-blue-600 { --tw-bg-opacity: 1; background-color: rgb(37 99 235 / var(--tw-bg-opacity)); } .dark\:bg-gray-800 { --tw-bg-opacity: 1; background-color: rgb(31 41 55 / var(--tw-bg-opacity)); } .dark\:text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .dark\:text-gray-400 { --tw-text-opacity: 1; color: rgb(156 163 175 / var(--tw-text-opacity)); } .dark\:placeholder-gray-400::-moz-placeholder { --tw-placeholder-opacity: 1; color: rgb(156 163 175 / var(--tw-placeholder-opacity)); } .dark\:placeholder-gray-400::placeholder { --tw-placeholder-opacity: 1; color: rgb(156 163 175 / var(--tw-placeholder-opacity)); } .dark\:hover\:bg-red-700:hover { --tw-bg-opacity: 1; background-color: rgb(185 28 28 / var(--tw-bg-opacity)); } .dark\:hover\:bg-blue-700:hover { --tw-bg-opacity: 1; background-color: rgb(29 78 216 / var(--tw-bg-opacity)); } .dark\:focus\:border-blue-500:focus { --tw-border-opacity: 1; border-color: rgb(59 130 246 / var(--tw-border-opacity)); } .dark\:focus\:ring-blue-500:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity)); } .dark\:focus\:ring-red-900:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(127 29 29 / var(--tw-ring-opacity)); } .dark\:focus\:ring-blue-800:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(30 64 175 / var(--tw-ring-opacity)); } } @media (min-width: 640px) { .sm\:flex { display: flex; } .sm\:hidden { display: none; } .sm\:grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .sm\:justify-end { justify-content: flex-end; } .sm\:gap-2 { gap: 0.5rem; } .sm\:rounded-lg { border-radius: 0.5rem; } .sm\:text-sm { font-size: 0.875rem; line-height: 1.25rem; } } @media (min-width: 768px) { .md\:mx-40 { margin-left: 10rem; margin-right: 10rem; } .md\:my-10 { margin-top: 2.5rem; margin-bottom: 2.5rem; } .md\:mr-1 { margin-right: 0.25rem; } .md\:ml-1 { margin-left: 0.25rem; } .md\:inline { display: inline; } .md\:h-full { height: 100%; } .md\:grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .md\:border-2 { border-width: 2px; } .md\:px-16 { padding-left: 4rem; padding-right: 4rem; } .md\:px-0 { padding-left: 0px; padding-right: 0px; } } @media (min-width: 1024px) { .lg\:static { position: static; } .lg\:fixed { position: fixed; } .lg\:col-span-2 { grid-column: span 2 / span 2; } .lg\:mx-24 { margin-left: 6rem; margin-right: 6rem; } .lg\:my-4 { margin-top: 1rem; margin-bottom: 1rem; } .lg\:mt-0 { margin-top: 0px; } .lg\:block { display: block; } .lg\:grid { display: grid; } .lg\:w-96 { width: 24rem; } .lg\:w-44 { width: 11rem; } .lg\:w-16 { width: 4rem; } .lg\:grid-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); } .lg\:grid-cols-7 { grid-template-columns: repeat(7, minmax(0, 1fr)); } .lg\:grid-cols-none { grid-template-columns: none; } .lg\:flex-col { flex-direction: column; } .lg\:items-center { align-items: center; } .lg\:gap-60 { gap: 15rem; } .lg\:gap-2\.5 { gap: 0.625rem; } .lg\:gap-2 { gap: 0.5rem; } .lg\:gap-0 { gap: 0px; } .lg\:px-36 { padding-left: 9rem; padding-right: 9rem; } .lg\:py-10 { padding-top: 2.5rem; padding-bottom: 2.5rem; } .lg\:px-10 { padding-left: 2.5rem; padding-right: 2.5rem; } .lg\:px-0 { padding-left: 0px; padding-right: 0px; } .lg\:pt-0 { padding-top: 0px; } .lg\:pl-4 { padding-left: 1rem; } .lg\:pt-16 { padding-top: 4rem; } .lg\:pt-5 { padding-top: 1.25rem; } }
package neetcode.kotlin import java.util.* import kotlin.math.abs class _41FirstMissingPositive { fun firstMissingPositive(nums: IntArray): Int { var c = 1 val len = nums.size Arrays.sort(nums) for (i in 0 until len) { if (nums[i] < 1) continue if (i > 0 && nums[i - 1] >= nums[i]) continue if (c == nums[i]) c++ else return c } return c } fun firstMissingPositive1(nums: IntArray): Int { for (i in nums.indices) if (nums[i] < 0) nums[i] = 0 for (i in nums.indices) { var ind = abs(nums[i].toDouble()).toInt() if (ind > 0 && ind <= nums.size) { ind-- if (nums[ind] > 0) nums[ind] *= -1 else if (nums[ind] == 0) nums[ind] = ((nums.size) + 1) * -1 } } for (i in nums.indices) if (nums[i] >= 0) return i + 1 return nums.size + 1 } fun firstMissingPositive2(nums: IntArray): Int { val dp = IntArray(nums.size + 1) for (i in nums) { if (i > 0 && i <= nums.size) { dp[i]++ } } for (i in 1 until nums.size + 1) { if (dp[i] == 0) { return i } } return nums.size + 1 } companion object { @JvmStatic fun main(args: Array<String>) { val obj = _41FirstMissingPositive() run { val num = intArrayOf(1, 2, 0) println(obj.firstMissingPositive(num)) } run { val num = intArrayOf(3, 4, -1, 2) println(obj.firstMissingPositive(num)) } run { val num = intArrayOf(7, 8, 9, 11, 12) println(obj.firstMissingPositive(num)) } run { val num = intArrayOf(0, 2, 2, 1, 1) println(obj.firstMissingPositive(num)) } println("\n\n\n") run { val num = intArrayOf(1, 2, 0) println(obj.firstMissingPositive1(num)) } run { val num = intArrayOf(3, 4, -1, 2) println(obj.firstMissingPositive1(num)) } run { val num = intArrayOf(7, 8, 9, 11, 12) println(obj.firstMissingPositive1(num)) } run { val num = intArrayOf(0, 2, 2, 1, 1) println(obj.firstMissingPositive1(num)) } println("\n\n\n") run { val num = intArrayOf(1, 2, 0) println(obj.firstMissingPositive2(num)) } run { val num = intArrayOf(3, 4, -1, 2) println(obj.firstMissingPositive2(num)) } run { val num = intArrayOf(7, 8, 9, 11, 12) println(obj.firstMissingPositive2(num)) } run { val num = intArrayOf(0, 2, 2, 1, 1) println(obj.firstMissingPositive2(num)) } } } }
<template> <div class="admin-dashboard"> <h2>Admin Dashboard</h2> <!-- Instructions Section --> <div class="instructions"> <h3>Instructions</h3> <ul> <li> <strong>Add a Mineral:</strong> Go to 'Add Mineral' to add a new mineral to the database. You will have the option to set it as an auction piece or a for sale piece. </li> <li> <strong>Add an Auction:</strong> After adding a mineral, you can create an auction. Go to 'Add Auction' and select the mineral you just added from the dropdown. </li> </ul> <p>Hit me up with any questions.</p> </div> <div class="tools-container"> <div class="tool-card"> <router-link :to="{ name: 'admin-add-mineral' }" class="card-link"> <h3>Add Mineral</h3> <p>Add new minerals to the database for auctioning.</p> </router-link> </div> <!-- Manage Minerals Section --> <div class="tool-card"> <h3>Manage Minerals</h3> <div class="minerals-list"> <div v-for="mineral in minerals" :key="mineral.id" class="mineral-item" > <div class="mineral-content"> <img v-if="mineral.imageURL" :src="mineral.imageURL" class="mineral-thumbnail" alt="Mineral Image" /> <h4>Mineral Name: {{ mineral.name }}</h4> <h4>MineralID: {{ mineral.id }}</h4> <h4 v-if="mineral.status == 0">Status: Available</h4> <h4 v-if="mineral.status == 1">Status: Sold</h4> <h4 v-if="mineral.isAuctionItem">Sale or Auction: AUCTION</h4> <h4 v-else>Sale or Auction: SALE</h4> <!-- Add a link to the Edit Mineral page --> <button @click="navigateToEditMineral(mineral.id)" class="edit-button" > Edit </button> <!-- Delete Button --> <button @click=" confirmAndDeleteMineral(mineral.id, mineral.isAuctionItem) " class="delete-button" > Delete </button> <!-- Show Details Button for for-sale minerals --> <router-link v-if="!mineral.isAuctionItem" :to="{ name: 'mineral-detail', params: { id: mineral.id } }" class="details-button" > Show Details </router-link> <!-- Go to Auction Button for auction items --> <router-link v-if=" mineral.isAuctionItem && getAuctionIdByMineralId(mineral.id) " :to="{ name: 'auction-detail', params: { id: getAuctionIdByMineralId(mineral.id) }, }" class="auction-button" > Go to Auction </router-link> </div> </div> </div> </div> <div class="tool-card"> <router-link :to="{ name: 'admin-add-auction' }" class="card-link"> <h3>Add Auction</h3> <p>Create a new auction for buyers to place their bids.</p> </router-link> </div> <div class="tool-card"> <h3>Update Auction</h3> <div class="auctions-list"> <div v-for="auction in auctions" :key="auction.id" class="auction-item" > <router-link :to="{ name: 'admin-update-auction', params: { id: auction.id } }" class="auction-link" > <div class="auction-content"> <h4>{{ auction.title }}</h4> <p>Start: {{ new Date(auction.startTime).toLocaleString() }}</p> <p>End: {{ new Date(auction.endTime).toLocaleString() }}</p> <p> Highest Bid: {{ auction.currentHighestBid && auction.currentHighestBid.winningBid ? `$${auction.currentHighestBid.winningBid.amount}` : "No bids yet" }} </p> </div> </router-link> </div> </div> </div> <div class="tool-card"> <div class="inquiry-dashboard-section"> <AdminInquiryDashboard @inquirySelected="handleInquirySelected" /> </div> <div v-if="selectedInquiry" class="inquiry-response-section"> <InquiryResponseForm v-if="selectedInquiry" :inquiryId="selectedInquiry.id" @close="selectedInquiry = null" /> </div> </div> </div> </div> </template> <script> // import AddMineralForm from "../components/AddMineralForm.vue"; // import AddAuctionForm from "../components/AddAuctionForm.vue"; // import UpdateAuctionForm from "../components/UpdateAuctionForm.vue"; import AuctionService from "../services/AuctionService"; import BidService from "../services/BidService"; import AdminInquiryDashboard from "../components/AdminInquiryDashboard.vue"; import InquiryResponseForm from "../components/InquiryResponseForm.vue"; import MineralService from "../services/MineralService"; import { mapGetters } from "vuex"; export default { // components: { // AddMineralForm, // AddAuctionForm, // UpdateAuctionForm, // }, computed: { ...mapGetters({ inquiries: "correspondence/inquiries", }), }, components: { AdminInquiryDashboard, InquiryResponseForm, }, data() { return { auctions: [], minerals: [], selectedInquiry: null, }; }, created() { this.fetchAuctions(); this.fetchMinerals(); }, beforeRouteEnter(to, from, next) { next((vm) => { if (vm.$store.getters.isAdmin) { next(); } else { next("/"); } }); }, methods: { handleInquirySelected(inquiryId) { this.selectedInquiry = this.inquiries.find( (inquiry) => inquiry.id === inquiryId ); }, handleInquiryResponded(inquiryId) { // Remove the responded inquiry from the list this.inquiries = this.inquiries.filter( (inquiry) => inquiry.id !== inquiryId ); // Optionally, you can also refresh the inquiries list from the server // this.fetchAllInquiries(); }, async fetchAuctions() { try { const fetchedAuctions = await AuctionService.getAuctions(); this.auctions = await Promise.all( fetchedAuctions.map(async (auction) => { const currentHighestBid = await BidService.getCurrentWinningBidForAuction(auction.id); auction.currentHighestBid = currentHighestBid; console.log("Current Highest Bid: " + auction.currentHighestBid); return auction; }) ); } catch (error) { console.error("Failed to fetch auctions:", error); } }, getAuctionIdByMineralId(mineralId) { const auction = this.auctions.find( (auction) => auction.mineralId === mineralId ); if (!auction) { return null; } return auction.id; }, formatDate(dateString) { const options = { year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "numeric", }; return new Date(dateString).toLocaleDateString(undefined, options); }, async fetchMinerals() { try { const fetchedMinerals = await MineralService.getMinerals(); // Sort the minerals by ID in descending order this.minerals = fetchedMinerals.sort((a, b) => b.id - a.id); } catch (error) { console.error("Failed to fetch minerals:", error); } }, navigateToEditMineral(mineralId) { this.$router.push({ name: "admin-edit-mineral", params: { id: mineralId }, }); }, async confirmAndDeleteMineral(mineralId, isAuctionItem) { let confirmationMessage = `Are you sure you want to delete Mineral ID: ${mineralId}?`; let auctionId = null; if (isAuctionItem) { auctionId = this.getAuctionIdByMineralId(mineralId); if (auctionId) { confirmationMessage += ` This will also delete the associated Auction ID: ${auctionId}.`; } else { console.error(`No auction found for Mineral ID: ${mineralId}`); confirmationMessage += " No associated auction found."; } } if (confirm(confirmationMessage)) { try { if (isAuctionItem && auctionId) { await this.deleteAssociatedAuction(auctionId); } await MineralService.deleteMineral(mineralId); this.minerals = this.minerals.filter( (mineral) => mineral.id !== mineralId ); alert( "Mineral deleted successfully." + // eslint-disable-next-line prettier/prettier (auctionId ? " Auction deleted successfully." : "") ); } catch (error) { console.error("Error deleting mineral:", error); alert("Failed to delete mineral. Please try again."); } } }, async deleteAssociatedAuction(auctionId) { if (!auctionId) { console.error("Auction ID is null, cannot delete auction."); return; } try { await AuctionService.deleteAuction(auctionId); console.log(`Auction with ID: ${auctionId} deleted successfully.`); } catch (error) { console.error(`Error deleting auction with ID: ${auctionId}:`, error); throw error; // Rethrow the error to handle it in the calling method } }, mounted() { this.$root.$on("inquiryResponded", this.handleInquiryResponded); }, beforeDestroy() { this.$root.$off("inquiryResponded", this.handleInquiryResponded); }, }, }; </script> <style scoped> .admin-dashboard { padding: 16px; } .instructions { padding: 16px; margin-bottom: 20px; /* Spacing between instructions and tools */ } ul { list-style-type: none; } .instructions h3 { margin-top: 0; } .instructions ol { margin-left: 20px; } .tools-container { display: flex; flex-wrap: wrap; gap: 16px; } .tool-card { flex: 1; min-width: 300px; /* Adjust as needed */ border: 1px solid #ccc; border-radius: 8px; padding: 16px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .card-link { text-decoration: none; color: inherit; } .auctions-list { display: flex; flex-direction: column; gap: 10px; } .auction-item { border: 1px solid #ccc; border-radius: 10px; overflow: hidden; transition: box-shadow 0.3s; } .auction-item:hover { box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); } .auction-link { text-decoration: none; color: inherit; display: block; padding: 10px; } .auction-content h4 { margin-top: 0; } .mineral-content { border: 1px solid #ccc; /* Light grey border */ border-radius: 8px; /* Rounded corners */ padding: 16px; /* Spacing inside the box */ margin-bottom: 16px; /* Spacing between each mineral content box */ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* Subtle shadow for depth */ background-color: #fff; /* White background */ } .edit-button, .delete-button, .details-button, .auction-button { background-color: black; /* Black background */ color: white; /* White text */ padding: 10px 20px; /* Padding */ margin: 5px; /* Margin to separate buttons */ border: none; /* No border */ border-radius: 5px; /* Rounded edges */ cursor: pointer; /* Pointer cursor on hover */ text-decoration: none; /* Remove text decoration */ display: inline-block; /* Align buttons inline */ } .edit-button:hover, .delete-button:hover, .details-button:hover, .auction-button:hover { background-color: #333; /* Darken background on hover */ } /* Optional: Add a class for disabled buttons if needed */ .disabled-button { background-color: #ccc; /* Grey background for disabled state */ color: #666; /* Dark grey text for disabled state */ cursor: not-allowed; /* Not-allowed cursor for disabled state */ } .minerals-list { display: flex; flex-direction: column; gap: 16px; /* Adjust the gap if necessary */ } .mineral-thumbnail { width: 100px; /* Adjust as needed */ height: 100px; /* Adjust as needed */ object-fit: cover; /* This will cover the area without stretching the image */ border-radius: 5px; /* Optional: if you want rounded corners */ margin-right: 10px; /* Adjust as needed */ } .mineral-content { /* Align items in a row */ align-items: center; /* Center items vertically */ /* ... rest of your code ... */ } /* Responsive Tool Cards */ @media (max-width: 768px) { .tool-card { flex: 1 1 100%; /* Take full width on smaller screens */ max-width: 100%; /* Ensure it doesn't exceed the screen width */ } } /* Responsive Mineral Items */ @media (max-width: 768px) { .mineral-content { flex-direction: column; /* Stack items vertically */ align-items: flex-start; /* Align items to the start */ } .mineral-thumbnail { width: 80px; /* Adjust size for smaller screens */ height: 80px; /* Adjust size for smaller screens */ margin-bottom: 10px; /* Add some space below the image */ } .edit-button, .delete-button { margin-top: 10px; /* Add some space above the buttons */ } } /* General Layout Adjustments */ .tools-container { flex-direction: column; /* Stack cards vertically on smaller screens */ } @media (min-width: 769px) { .tools-container { flex-direction: row; /* Align cards in a row on larger screens */ } } /* Adjust padding and margins for smaller screens */ @media (max-width: 768px) { .admin-dashboard { padding: 8px; } .instructions, .tool-card { padding: 8px; } .mineral-content { padding: 8px; } } </style>
// // GuessTheFlag.swift // MyCodes // // Created by Htet Moe Phyu on 28/06/2023. // import SwiftUI struct GuessTheFlag: View { @State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Monaco", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled() @State private var correctAnswer = Int.random(in: 0...2) @State private var showingScore = false @State private var scoreTitle = "" //score @State private var score = 0 @State private var isCorrect = false @State private var selectedFlag = "" @State private var questionCount = 0 var body: some View { ZStack { //LinearGradient(colors: [.blue, .black], startPoint: .top, endPoint: .bottom).ignoresSafeArea() RadialGradient(stops: [ .init(color: Color(red: 0.1, green: 0.2, blue: 0.45), location: 0.3), .init(color: Color(red: 0.76, green: 0.15, blue: 0.26), location: 0.3) ], center: .top, startRadius: 200, endRadius: 700) .ignoresSafeArea() VStack { Spacer() Text("Guess the Flag") .font(.largeTitle.weight(.bold)) .foregroundColor(.white) VStack(spacing : 15){ //demand VStack { Text("Tap the flag of") .font(.subheadline.weight(.heavy)) .foregroundColor(.secondary) Text(countries[correctAnswer]) .font(.largeTitle.weight(.semibold)) } //showing 3 flags ForEach(0..<3) { number in Button { questionCount += 1 selectedFlag = countries[number] flagTapped(number) } label: { Image(countries[number]) .renderingMode(.original) .clipShape(Capsule()) .shadow(radius: 5) } } } .frame(maxWidth : .infinity) .padding(.vertical, 20) .background(.regularMaterial) .clipShape(RoundedRectangle(cornerRadius: 20)) .padding() Spacer() Spacer() Text("Score : \(score)") .foregroundColor(.white) .font(.title.bold()) Spacer() } } .alert(scoreTitle, isPresented: $showingScore) { let title = questionCount < 8 ? "Continue" : "Restart?" Button(title, action: questionCount < 8 ? askQuestion : restart) } message: { let msg = questionCount < 8 ? (isCorrect ? "Your score is \(score)" : "Wrong! That’s the flag of \(selectedFlag)") : "Restart the game." Text(msg) } } //check answer func flagTapped(_ number: Int) { if number == correctAnswer { scoreTitle = "Correct" score += 1 isCorrect = true } else { scoreTitle = "Wrong" isCorrect = false } showingScore = true } //ask question func askQuestion() { countries.shuffle() correctAnswer = Int.random(in: 0...2) } func restart(){ score = 0 questionCount = 0 } } struct GuessTheFlag_Previews: PreviewProvider { static var previews: some View { GuessTheFlag() } }
'use client' import styles from './sidebar.module.scss' import { Image, Button, Modal, message, Upload, Avatar, Input } from 'antd'; import Cookies from 'js-cookie'; import { usePathname, useRouter } from 'next/navigation'; import { useEffect, useState } from 'react'; import type { GetProp, UploadProps, UploadFile } from 'antd'; import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'; import { useTranslations } from 'next-intl'; import CustomModal from './custommodal.jsx'; import { useSelector, useDispatch } from 'react-redux'; import { setUsername, setEmail, setImage, setUser } from '@/redux/reducer/userSlice'; export default function SideBar() { const t = useTranslations(); const router = useRouter(); const pathname = usePathname().split('/'); const dispatch = useDispatch(); const [avatar, setAvatar] = useState<string>('/avatar.png'); const [isOpenModal, setIsOpen] = useState(false); const [newUsername, setNewUsername] = useState<string>(''); const [newEmail, setNewEmail] = useState<string>(''); const [newImage, setNewImage] = useState<string>(avatar); type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0]; const username = useSelector((state: any) => state.user.username); const email = useSelector((state: any) => state.user.email); const img = useSelector((state: any) => state.user.image); useEffect(() => { setNewUsername(username); setNewEmail(email); setNewImage(img); }, [username, email, img]); const logOut = () => { Cookies.remove('token'); router.push(`${pathname[1]}/login`); }; const handleEditAvatar = () => { setIsOpen(true); }; const [previewOpen, setPreviewOpen] = useState(false); const [previewImage, setPreviewImage] = useState(''); const [fileList, setFileList] = useState<UploadFile[]>([]); const getBase64 = (file: FileType): Promise<string> => new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result as string); reader.onerror = (error) => reject(error); }); const handlePreview = async (file: UploadFile) => { if (!file.url && !file.preview) { file.preview = await getBase64(file.originFileObj as FileType); } setPreviewImage(file.url || (file.preview as string)); setPreviewOpen(true); }; const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => setFileList(newFileList); const uploadButton = ( <button style={{ border: 0, background: 'none' }} type="button"> <PlusOutlined /> <div style={{ marginTop: 8 }}>{t('sidebar.upload')}</div> </button> ); const handleOk = () => { setAvatar(previewImage || newImage); setPreviewImage(''); setFileList([]); setIsOpen(false); dispatch(setUsername(newUsername)); dispatch(setEmail(newEmail)); dispatch(setImage(previewImage || newImage)); }; const [isModalVisible, setIsModalVisible] = useState(false); const [isMobile, setIsMobile] = useState(false); useEffect(() => { const handleResize = () => { setIsMobile(window.innerWidth <= 767); }; handleResize(); window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); const showModal = () => { setIsModalVisible(true); }; const handleModalClose = () => { setIsModalVisible(false); }; const sidebarContent = ( <div className={styles.sidebar}> <div className="info"> <div className={styles.sidebar__avatar}> <Avatar src={avatar} /> </div> <div className={styles.user_info}> <p className="username">{t('sidebar.user')}:{username}</p> <p className="point">Email:{email} </p> </div> </div> <div className={styles.sidebar__btn}> <Button type="text" className={styles.btn__logout + ' uppercase'} onClick={handleEditAvatar}> {t('sidebar.editAvatar')} </Button> <Button type="text" htmlType="submit" className={styles.btn__logout + ' mt-5 uppercase'} onClick={logOut}> {t('sidebar.logout')} </Button> </div> </div> ); return ( <> {isMobile ? ( <div className={styles.buttonmenu}> <Button type="text" onClick={showModal}> <img src="/buttonmenu.png" alt="Menu" /> </Button> <CustomModal isVisible={isModalVisible} onClose={handleModalClose}> {sidebarContent} </CustomModal> </div> ) : ( sidebarContent )} <CustomModal isVisible={isOpenModal} onClose={() => setIsOpen(false)}> <Modal open={isOpenModal} title="Edit Info" onOk={handleOk} onCancel={() => setIsOpen(false)} footer={[ <Button key="back" onClick={() => setIsOpen(false)}> {t('sidebar.cancel')} </Button>, <Button key="submit" type="primary" onClick={handleOk}> Save </Button>, ]} > <div className={styles.modal}> <div style={{ marginBottom: '50px' }}> <Upload action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload" listType="picture-circle" fileList={fileList} onPreview={handlePreview} onChange={handleChange} beforeUpload={file => { const reader = new FileReader(); const fileUrl = URL.createObjectURL(file); reader.readAsText(file); setPreviewImage(fileUrl); return false; }} > {fileList.length > 0 ? null : uploadButton} </Upload> </div> <Input value={newUsername} onChange={(e) => setNewUsername(e.target.value)} placeholder={"Username"} style={{ marginBottom: '50px' }} /> <Input value={newEmail} onChange={(e) => setNewEmail(e.target.value)} placeholder={"Email"} /> {previewImage && ( <Image wrapperStyle={{ display: 'none' }} preview={{ visible: previewOpen, onVisibleChange: (visible) => setPreviewOpen(visible), afterOpenChange: (visible) => !visible, }} src={previewImage} /> )} </div> </Modal> </CustomModal> </> ); }
class Person: def __init__(self): # The constructor print("Calling constructor of class Person") self.name = "" # name will be an instance variable due to ’self’ keyword self.email_address = "" language = "French" # language will be a class variable (no self.) @staticmethod # get_language will be a class method using @staticmethod annotation def get_language(): return Person.language # print(get_language()) @classmethod def set_language(cls,language): cls.language=language def get_name(self): return self.name def get_email_adress(self): return self.email_address def set_email_adress(self,email): self.email_address=email def display_data(self): print("Email for {} is {}".format(self.get_name(),self.get_email_adress())) print("Native spoken language is {}".format(self.language)) p1=Person() p1.name="Anas" p1.email_address="A.gmail.com" print(p1.display_data()) #Classe et héritage : syntaxe par l’exemple avec le compte bancaire # • Compte basique avec les opérations déposer et retirer un montant, connaitre le solde # • Compte courant, dérivé du compte basique # avec un découvert possible spécifique à chaque compte crée # avec re-définition de l’opération ’retirer un montant’, tenant compte du découvert possible class BankAccount(): def __init__(self, owner): # create account with a unique id,no amount self.id = id self.amount = 0 self.owner = owner return # for readability def deposit(self, amount): self.amount += amount return def withdraw(self, amount): self.amount -= amount return def get_id(self): return(self.id) def get_amount(self): return(self.amount) def get_owner(self): return(self.owner) a1=BankAccount("anas") print(a1.amount) deposit(a1,1000) deposit(a1,1000) withdraw(a1,500) print(a1.amount) print(get_owner(a1)) # Heritage class CurrentAccount(BankAccount): # *** CurrentAccount extends BankAccount # new withdraw implementation according to min_amount allowed # *** # this is the constructor def __init__(self, owner): # invoke constructor from super class BankAccount.__init__(self, owner) # a new field specific to CurrentAccount self.min_amount = 0 return def set_min_amount(self,min_amount): self.min_amount=min_amount def get_min_amount(self): return self.min_amount """ withdraw allowed only if min amount is not reached """ # just to show : min_amount has a local scope def withdraw(self, amount): min_amount = self.amount - amount if (min_amount < self.min_amount): print("withdraw operation of {} Euros is denied since" " the low threshold of {} Euros " "would be reached !".format(amount, self.get_min_amount())) else: # case ok, invoke super class’s method BankAccount.withdraw(self, amount) return "retrait accepté, compte actuel {} ".format(self.amount-amount) # end of class CurrentAccount() def main(): bank_account=CurrentAccount("Amine") bank_account.set_min_amount(-20) # print("Bank account for {} is created with a low threshold of {} Euros" \ # .format(CurrentAccount.get_owner(), BankAccount.get_min_amount())) print("Bank account for {} is created with a low threshold of {} Euros" \ .format(get_owner(bank_account), bank_account.get_min_amount())) deposit(bank_account,123) print("Current amount is {} Euros".format(get_amount(bank_account))) withdraw(bank_account,100) print("Current amount is {} Euros".format(get_amount(bank_account))) withdraw(bank_account,50) print("Current amount is {} Euros".format(get_amount(bank_account))) if __name__=="__main__": main() # bank_account=CurrentAccount("Amine") # bank_account.set_min_amount(-20) # # print("Bank account for {} is created with a low threshold of {} Euros" \ # # .format(CurrentAccount.get_owner(), BankAccount.get_min_amount())) # print("Bank account for {} is created with a low threshold of {} Euros" \ # .format(get_owner(bank_account), bank_account.get_min_amount())) # deposit(bank_account,123) # print("Current amount is {} Euros".format(get_amount(bank_account))) # withdraw(bank_account,100) # print("Current amount is {} Euros".format(get_amount(bank_account))) # withdraw(bank_account,50) # print("Current amount is {} Euros".format(get_amount(bank_account)))
'use client'; import { ContainerOutlined, HomeOutlined, LeftCircleOutlined, ProjectOutlined, RightCircleOutlined, SettingOutlined, UserOutlined, } from '@ant-design/icons'; import logoSrc from '@lib/assets/images/logo.svg'; import { Button } from 'antd'; import Image from 'next/image'; import Link from 'next/link'; import { usePathname } from 'next/navigation'; import React, { memo, useCallback, useMemo } from 'react'; import { EMPTY_STRING } from '@shared/configs/constants'; import styles from './styles.module.scss'; const Sidebar = ({ open, onToggle }: any) => { // Hooks const pathName = usePathname(); const linkContainerStyles = open ? styles.open : EMPTY_STRING; const toggleSidebar = useCallback(() => onToggle(!open), [onToggle, open]); const toggleIcon = useMemo(() => { const iconStyle = { fontSize: '1.125rem' }; return open ? <LeftCircleOutlined style={iconStyle} /> : <RightCircleOutlined style={iconStyle} />; }, [open]); const renderRoutes = useMemo(() => { const routes = [ { label: 'Home', icon: <HomeOutlined />, path: '/dashboard/home' }, { label: 'Posts', icon: <ContainerOutlined />, path: '/dashboard/posts' }, { label: 'Tasks', icon: <ProjectOutlined />, path: '/dashboard/tasks' }, { label: 'Accounts', icon: <UserOutlined />, path: '/dashboard/accounts' }, { label: 'Settings', icon: <SettingOutlined />, path: '/dashboard/settings' }, ]; return routes.map(({ label, icon, path }) => { const activeClass = pathName && (pathName as string).startsWith(path) ? styles.active : EMPTY_STRING; return ( <Link href={path} key={path}> <li className={`ease-in duration-200 rounded-sm mb-1 text-slate-600 cursor-pointer py-2 px-3 hover:bg-primary hover:text-white ${activeClass}`}> <div className="capitalize flex items-center"> <span className="mr-4">{icon}</span> {label} </div> </li> </Link> ); }); }, [pathName]); return ( <div className="relative"> <div className="absolute -right-4 top-1/2 z-20 drop-shadow-md"> <Button shape="circle" className="bg-white text-slate-400 flex items-center justify-center" type="text" onClick={toggleSidebar} icon={toggleIcon} /> </div> <div className="h-14 bg-white truncate flex items-center justify-center"> <Image src={logoSrc} width={32} height={32} alt="page logo" /> </div> <ul className={`${styles.container} ${linkContainerStyles} ease-in duration-150 bg-white h-full border-r border-slate-100 relative overflow-x-hidden p-1`}> {renderRoutes} </ul> </div> ); }; export default memo(Sidebar);
import 'package:flutter/material.dart'; import 'package:minimal_ecommerce_app/components/my_drawer.dart'; import 'package:minimal_ecommerce_app/components/my_product_tile.dart'; import 'package:minimal_ecommerce_app/models/shop.dart'; import 'package:provider/provider.dart'; class ShopPage extends StatelessWidget { const ShopPage({super.key}); @override Widget build(BuildContext context) { // access the products in shop final products = context.watch<Shop>().shop; return Scaffold( appBar: AppBar( title: const Text('Shop Page'), backgroundColor: Colors.transparent, elevation: 0, foregroundColor: Theme.of(context).colorScheme.inversePrimary, actions: [ // go to cart button IconButton( icon: const Icon(Icons.shopping_cart_outlined), onPressed: () { Navigator.pushNamed(context, '/cart_page'); }, ), ], ), drawer: const MyDrawer(), backgroundColor: Theme.of(context).colorScheme.background, body: ListView( children: [ const SizedBox(height: 25), // shop subtitle Center( child: Text( "Pick from a selected list of premium products", style: TextStyle( color: Theme.of(context).colorScheme.inversePrimary, ), ), ), // product list SizedBox( height: 550, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: products.length, itemBuilder: (context, index) { // get each individual product from the shop final product = products[index]; // return as a product tile UI return MyProductTile(product: product); }, padding: const EdgeInsets.all(15), ), ), ], ), ); } }
package hw02unpackstring import ( "testing" "github.com/stretchr/testify/require" ) func TestUnpack(t *testing.T) { tests := []struct { input string expected string }{ {input: "a4bc2d5e", expected: "aaaabccddddde"}, {input: "abccd", expected: "abccd"}, {input: "", expected: ""}, {input: "aaa0b", expected: "aab"}, {input: "d\n5abc", expected: "d\n\n\n\n\nabc"}, {input: "foo0", expected: "fo"}, // uncomment if task with asterisk completed // {input: `qwe\4\5`, expected: `qwe45`}, // {input: `qwe\45`, expected: `qwe44444`}, // {input: `qwe\\5`, expected: `qwe\\\\\`}, // {input: `qwe\\\3`, expected: `qwe\3`}, } for _, tc := range tests { tc := tc t.Run(tc.input, func(t *testing.T) { result, err := Unpack(tc.input) require.NoError(t, err) require.Equal(t, tc.expected, result) }) } } /*func TestUnpackInvalidString(t *testing.T) { invalidStrings := []string{"3abc", "45", "aaa10b"} for _, tc := range invalidStrings { tc := tc t.Run(tc, func(t *testing.T) { _, err := Unpack(tc) require.Truef(t, errors.Is(err, ErrInvalidString), "actual error %q", err) }) } }*/ func TestUnpackInvalidFirstElement(t *testing.T) { invalidStrings := []string{"3abc", "45"} for _, tc := range invalidStrings { tc := tc t.Run(tc, func(t *testing.T) { _, err := Unpack(tc) require.ErrorIs(t, err, ErrInvalidFirstElement, "actual error %q", err) }) } } func TestUnpackInvalidNumberElements(t *testing.T) { invalidStrings := []string{"aaa10b"} for _, tc := range invalidStrings { tc := tc t.Run(tc, func(t *testing.T) { _, err := Unpack(tc) require.ErrorIs(t, err, ErrInvalidNumberElements, "actual error %q", err) }) } }
import React from 'react'; import '../src/Assets/css/style.css'; import '../src/Assets/css/style.min.css'; import './App.css'; import { useEffect, useState } from 'react'; import axios from 'axios'; import { Link, navigate } from 'react-router-dom'; function Home() { const [view, setView] = useState([]); const getproduct = () => { axios.get('http://localhost:5000/addproduct/Showproduct') .then(function (response) { console.log(response.data.data); setView(response.data.data); }) .catch(function (error) { console.log(error); }) } useEffect(() => { getproduct(); }, []); return ( <> <div className="container-fluid p-0 nav-bar"> <nav className="navbar navbar-expand-lg bg-none navbar py-3"> <Link to={`#`} className="navbar-brand px-lg-4 m-0"> <h1 className="m-0 display-4 text-uppercase text-white logo">KOPPEE</h1> </Link> <button type="button" className="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse" > <span className="navbar-toggler-icon" /> </button> <div className="collapse navbar-collapse justify-content-between" id="navbarCollapse" > <div className="navbar-nav text-text ml-auto p-4 "> <Link to={`#`} className="nav-item nav-link active"> Home </Link> <Link to={`/About`} className="nav-item nav-link"> About </Link> <Link to={`/Service`} className="nav-item nav-link"> Service </Link> <Link to={`/Menu`} className="nav-item nav-link"> Menu </Link> <div className="nav-item dropdown"> <a href="#" className="nav-link dropdown-toggle" data-toggle="dropdown" > Pages </a> <div className="dropdown-menu text-capitalize"> <a href="reservation" className="dropdown-item"> Reservation </a> <a href="testimonial" className="dropdown-item"> Testimonial </a> </div> </div> <Link to={`/Contact`} className="nav-item nav-link"> Contact </Link> </div> </div> </nav> </div> {/* Carousel Start */} <div className="container-fluid p-0 mb-5"> <div id="blog-carousel" className="carousel slide overlay-bottom" data-ride="carousel" > <div className="carousel-inner"> <div className="carousel-item active"> <img className="w-100" src={require('../src/Assets/img/carousel-1.jpg')} alt="Image" /> <div className="carousel-caption d-flex flex-column align-items-center justify-content-center"> <h2 className="text-primary font-weight-medium m-0"> We Have Been Serving </h2> <h1 className="display-1 text-white m-0">COFFEE</h1> <h2 className="text-white m-0">* SINCE 1950 *</h2> </div> </div> <div className="carousel-item"> <img className="w-100" src={require('../src/Assets/img/carousel-2.jpg')} alt="Image" /> <div className="carousel-caption d-flex flex-column align-items-center justify-content-center"> <h2 className="text-primary font-weight-medium m-0"> We Have Been Serving </h2> <h1 className="display-1 text-white m-0">COFFEE</h1> <h2 className="text-white m-0">* SINCE 1950 *</h2> </div> </div> </div> <a className="carousel-control-prev" href="#blog-carousel" data-slide="prev" > <span className="carousel-control-prev-icon" /> </a> <a className="carousel-control-next" href="#blog-carousel" data-slide="next" > <span className="carousel-control-next-icon" /> </a> </div> </div> {/* Carousel End */} {/* About Start */} <div className="container-fluid py-5"> <div className="container"> <div className="section-title"> <h4 className="text-primary text-uppercase" style={{ letterSpacing: 5 }} > About Us </h4> <h1 className="display-4">Serving Since 1950</h1> </div> <div className="row"> <div className="col-lg-4 py-0 py-lg-5"> <h1 className="mb-3">Our Story</h1> <h5 className="mb-3"> Eos kasd eos dolor vero vero, lorem stet diam rebum. Ipsum amet sed vero dolor sea </h5> <p> Takimata sed vero vero no sit sed, justo clita duo no duo amet et, nonumy kasd sed dolor eos diam lorem eirmod. Amet sit amet amet no. Est nonumy sed labore eirmod sit magna. Erat at est justo sit ut. Labor diam sed ipsum et eirmod </p> <a href="" className="btn btn-secondary font-weight-bold py-2 px-4 mt-2" > Learn More </a> </div> <div className="col-lg-4 py-5 py-lg-0" style={{ minHeight: 500 }}> <div className="position-relative h-100"> <img className="position-absolute w-100 h-100" src={require('../src/Assets/img/about.png')} style={{ objectFit: "cover" }} /> </div> </div> <div className="col-lg-4 py-0 py-lg-5"> <h1 className="mb-3">Our Vision</h1> <p> Invidunt lorem justo sanctus clita. Erat lorem labore ea, justo dolor lorem ipsum ut sed eos, ipsum et dolor kasd sit ea justo. Erat justo sed sed diam. Ea et erat ut sed diam sea ipsum est dolor </p> <h5 className="mb-3"> <i className="fa fa-check text-primary mr-3" /> Lorem ipsum dolor sit amet </h5> <h5 className="mb-3"> <i className="fa fa-check text-primary mr-3" /> Lorem ipsum dolor sit amet </h5> <h5 className="mb-3"> <i className="fa fa-check text-primary mr-3" /> Lorem ipsum dolor sit amet </h5> <a href="" className="btn btn-primary font-weight-bold py-2 px-4 mt-2" > Learn More </a> </div> </div> </div> </div> {/* About End */} {/* ................................................................................................... */} <div className="container-fluid pt-5 pb-3"> <h2 className="section-title position-relative text-uppercase mx-xl-5 mb-4"> <span className="bg-secondary pr-3 featured">Featured Products</span> </h2> <div className="row px-xl-5 d-flex"> { view.map((val, i) => { return ( <div className="col-lg-3 col-md-4 col-sm-6 pb-1"> <div className="product-item bg-light mb-4 "> <div className="product-img position-relative overflow-hidden"> < img className="img-fluid-products w-100 h-275" src={val.image} alt="" /> <div className="product-action cart-1"> {/* <a className="btn btn-outline-dark btn-square" href="" > <i className="fa fa-shopping-cart" /> </a> <a className="btn btn-outline-dark btn-square" href=""> <i className="far fa-heart" /> </a> <a className="btn btn-outline-dark btn-square" href=""> <i className="fa fa-sync-alt" /> </a> <a className="btn btn-outline-dark btn-square" href=""> <i className="fa fa-search" /> </a> */} </div> </div> <div className="text-center py-4"> <a className="h1 text-decoration-none text-text-color text-truncate" href=""> {val.name} </a> <div className="d-flex align-items-center justify-content-center mt-2"> <h5>${val.price}</h5> <h6 className="text-muted ml-2"> {/* <del>$12300.00</del> */} </h6> </div> <div className="d-flex align-items-center justify-content-center mb-1"> <small className="fa fa-star text-primary mr-1" /> <small className="fa fa-star text-primary mr-1" /> <small className="fa fa-star text-primary mr-1" /> <small className="fa fa-star text-primary mr-1" /> <small className="fa fa-star text-primary mr-1" /> <small>(99)</small> </div> <Link to={`/ShowoneProduct/${val._id}`} className='mt-3 btn show-hover btn-success' style={{ border: '3px solid', borderColor: 'black', padding: '6px 25px', margin: '9px 2px 30px 11px' }} onClick>SHOW MORE</Link> </div> </div> </div> ) }) } </div> </div> {/* Service Start */} <div className="container-fluid pt-5"> <div className="container"> <div className="section-title"> <h4 className="text-primary text-uppercase" style={{ letterSpacing: 5 }} > Our Services </h4> <h1 className="display-4">Fresh &amp; Organic Beans</h1> </div> <div className="row"> <div className="col-lg-6 mb-5"> <div className="row align-items-center"> <div className="col-sm-5"> <img className="img-fluid mb-3 mb-sm-0" src={require('../src/Assets/img/service-1.jpg')} alt="" /> </div> <div className="col-sm-7"> <h4> <i className="fa fa-truck service-icon" /> Fastest Door Delivery </h4> <p className="m-0"> Sit lorem ipsum et diam elitr est dolor sed duo. Guberg sea et et lorem dolor sed est sit invidunt, dolore tempor diam ipsum takima erat tempor </p> </div> </div> </div> <div className="col-lg-6 mb-5"> <div className="row align-items-center"> <div className="col-sm-5"> <img className="img-fluid mb-3 mb-sm-0" src={require('../src/Assets/img/service-2.jpg')} alt="" /> </div> <div className="col-sm-7"> <h4> <i className="fa fa-coffee service-icon" /> Fresh Coffee Beans </h4> <p className="m-0"> Sit lorem ipsum et diam elitr est dolor sed duo. Guberg sea et et lorem dolor sed est sit invidunt, dolore tempor diam ipsum takima erat tempor </p> </div> </div> </div> <div className="col-lg-6 mb-5"> <div className="row align-items-center"> <div className="col-sm-5"> <img className="img-fluid mb-3 mb-sm-0" src={require('../src/Assets/img/service-3.jpg')} alt="" /> </div> <div className="col-sm-7"> <h4> <i className="fa fa-award service-icon" /> Best Quality Coffee </h4> <p className="m-0"> Sit lorem ipsum et diam elitr est dolor sed duo. Guberg sea et et lorem dolor sed est sit invidunt, dolore tempor diam ipsum takima erat tempor </p> </div> </div> </div> <div className="col-lg-6 mb-5"> <div className="row align-items-center"> <div className="col-sm-5"> <img className="img-fluid mb-3 mb-sm-0" src={require('../src/Assets/img/service-4.jpg')} alt="" /> </div> <div className="col-sm-7"> <h4> <i className="fa fa-table service-icon" /> Online Table Booking </h4> <p className="m-0"> Sit lorem ipsum et diam elitr est dolor sed duo. Guberg sea et et lorem dolor sed est sit invidunt, dolore tempor diam ipsum takima erat tempor </p> </div> </div> </div> </div> </div> </div> {/* Service End */} {/* .................................................................................................... */} <> {/* Offer Start */} <div className="offer container-fluid my-5 py-5 text-center position-relative overlay-top overlay-bottom"> <div className="container py-5"> <h1 className="display-3 text-primary mt-3">50% OFF</h1> <h1 className="text-white mb-3">Sunday Special Offer</h1> <h4 className="text-white font-weight-normal mb-4 pb-3"> Only for Sunday from 1st Jan to 30th Jan 2045 </h4> <form className="form-inline justify-content-center mb-4"> <div className="input-group"> <input type="text" className="form-control p-4" placeholder="Your Email" style={{ height: 60 }} /> <div className="input-group-append"> <button className="btn btn-primary font-weight-bold px-4" type="submit" > Sign Up </button> </div> </div> </form> </div> </div> {/* Offer End */} {/* ........................................................................................... */} {/* Menu Start */} <div className="container-fluid pt-5"> <div className="container"> <div className="section-title"> <h4 className="text-primary text-uppercase" style={{ letterSpacing: 5 }} > Menu &amp; Pricing </h4> <h1 className="display-4">Competitive Pricing</h1> </div> <div className="row"> <div className="col-lg-6"> <h1 className="mb-5">Hot Coffee</h1> <div className="row align-items-center mb-5"> <div className="col-4 col-sm-3"> <img className="w-100 rounded-circle mb-3 mb-sm-0" src={require('../src/Assets/img/menu-1.jpg')} alt="" /> <h5 className="menu-price">$5</h5> </div> <div className="col-8 col-sm-9"> <h4>Black Coffee</h4> <p className="m-0"> Sit lorem ipsum et diam elitr est dolor sed duo guberg sea et et lorem dolor </p> </div> </div> <div className="row align-items-center mb-5"> <div className="col-4 col-sm-3"> <img className="w-100 rounded-circle mb-3 mb-sm-0" src={require('../src/Assets/img/menu-2.jpg')} alt="" /> <h5 className="menu-price">$7</h5> </div> <div className="col-8 col-sm-9"> <h4>Chocolete Coffee</h4> <p className="m-0"> Sit lorem ipsum et diam elitr est dolor sed duo guberg sea et et lorem dolor </p> </div> </div> <div className="row align-items-center mb-5"> <div className="col-4 col-sm-3"> <img className="w-100 rounded-circle mb-3 mb-sm-0" src={require('../src/Assets/img/menu-3.jpg')} alt="" /> <h5 className="menu-price">$9</h5> </div> <div className="col-8 col-sm-9"> <h4>Coffee With Milk</h4> <p className="m-0"> Sit lorem ipsum et diam elitr est dolor sed duo guberg sea et et lorem dolor </p> </div> </div> </div> <div className="col-lg-6"> <h1 className="mb-5">Cold Coffee</h1> <div className="row align-items-center mb-5"> <div className="col-4 col-sm-3"> <img className="w-100 rounded-circle mb-3 mb-sm-0" src={require('../src/Assets/img/menu-1.jpg')} alt="" /> <h5 className="menu-price">$5</h5> </div> <div className="col-8 col-sm-9"> <h4>Black Coffee</h4> <p className="m-0"> Sit lorem ipsum et diam elitr est dolor sed duo guberg sea et et lorem dolor </p> </div> </div> <div className="row align-items-center mb-5"> <div className="col-4 col-sm-3"> <img className="w-100 rounded-circle mb-3 mb-sm-0" src={require('../src/Assets/img/menu-2.jpg')} alt="" /> <h5 className="menu-price">$7</h5> </div> <div className="col-8 col-sm-9"> <h4>Chocolete Coffee</h4> <p className="m-0"> Sit lorem ipsum et diam elitr est dolor sed duo guberg sea et et lorem dolor </p> </div> </div> <div className="row align-items-center mb-5"> <div className="col-4 col-sm-3"> <img className="w-100 rounded-circle mb-3 mb-sm-0" src={require('../src/Assets/img/menu-3.jpg')} alt="" /> <h5 className="menu-price">$9</h5> </div> <div className="col-8 col-sm-9"> <h4>Coffee With Milk</h4> <p className="m-0"> Sit lorem ipsum et diam elitr est dolor sed duo guberg sea et et lorem dolor </p> </div> </div> </div> </div> </div> </div> {/* Menu End */} {/* ........................................................................................ */} {/* Reservation Start */} <div className="container-fluid my-5"> <div className="container"> <div className="reservation position-relative overlay-top overlay-bottom"> <div className="row align-items-center"> <div className="col-lg-6 my-5 my-lg-0"> <div className="p-5"> <div className="mb-4"> <h1 className="display-3 text-primary">30% OFF</h1> <h1 className="text-white">For Online Reservation</h1> </div> <p className="text-white"> Lorem justo clita erat lorem labore ea, justo dolor lorem ipsum ut sed eos, ipsum et dolor kasd sit ea justo. Erat justo sed sed diam. Ea et erat ut sed diam sea </p> <ul className="list-inline text-white m-0"> <li className="py-2"> <i className="fa fa-check text-primary mr-3" /> Lorem ipsum dolor sit amet </li> <li className="py-2"> <i className="fa fa-check text-primary mr-3" /> Lorem ipsum dolor sit amet </li> <li className="py-2"> <i className="fa fa-check text-primary mr-3" /> Lorem ipsum dolor sit amet </li> </ul> </div> </div> <div className="col-lg-6"> <div className="text-center p-5" style={{ background: "rgba(51, 33, 29, .8)" }} > <h1 className="text-white mb-4 mt-5">Book Your Table</h1> <form className="mb-5"> <div className="form-group"> <input type="text" className="form-control bg-transparent border-primary p-4" placeholder="Name" required="required" /> </div> <div className="form-group"> <input type="email" className="form-control bg-transparent border-primary p-4" placeholder="Email" required="required" /> </div> <div className="form-group"> <div className="date" id="date" data-target-input="nearest"> <input type="text" className="form-control bg-transparent border-primary p-4 datetimepicker-input" placeholder="Date" data-target="#date" data-toggle="datetimepicker" /> </div> </div> <div className="form-group"> <div className="time" id="time" data-target-input="nearest"> <input type="text" className="form-control bg-transparent border-primary p-4 datetimepicker-input" placeholder="Time" data-target="#time" data-toggle="datetimepicker" /> </div> </div> <div className="form-group"> <select className="custom-select bg-transparent border-primary px-4" style={{ height: 49 }} > <option selected="">Person</option> <option value={1}>Person 1</option> <option value={2}>Person 2</option> <option value={3}>Person 3</option> <option value={3}>Person 4</option> </select> </div> <div> <button className="btn btn-primary btn-block font-weight-bold py-3" type="submit" > Book Now </button> </div> </form> </div> </div> </div> </div> </div> </div> {/* Reservation End */} {/* ............................................................................................ */} <> {/* Testimonial Start */} {/* <div className="container-fluid py-5"> <div className="container"> <div className="section-title"> <h4 className="text-primary text-uppercase" style={{ letterSpacing: 5 }} > Testimonial </h4> <h1 className="display-4">Our Clients Say</h1> </div> <div className="owl-carousel testimonial-carousel"> <div className="testimonial-item"> <div className="d-flex align-items-center mb-3"> <img className="img-fluid" src={require('../src/Assets/img/testimonial-4.jpg')} alt="" /> <div className="ml-3"> <h4>Client Name</h4> <i>Profession</i> </div> </div> <p className="m-0"> Sed ea amet kasd elitr stet, stet rebum et ipsum est duo elitr eirmod clita lorem. Dolor tempor ipsum sanct clita </p> </div> <div className="testimonial-item"> <div className="d-flex align-items-center mb-3"> <img className="img-fluid d-flex" src={require('../src/Assets/img/testimonial-1.jpg')} alt="" /> <div className="ml-3"> <h4>Client Name</h4> <i>Profession</i> </div> </div> <p className="m-0"> Sed ea amet kasd elitr stet, stet rebum et ipsum est duo elitr eirmod clita lorem. Dolor tempor ipsum sanct clita </p> </div> <div className="testimonial-item"> <div className="d-flex align-items-center mb-3"> <img className="img-fluid" src={require('../src/Assets/img/testimonial-2.jpg')} alt="" /> <div className="ml-3"> <h4>Client Name</h4> <i>Profession</i> </div> </div> <p className="m-0"> Sed ea amet kasd elitr stet, stet rebum et ipsum est duo elitr eirmod clita lorem. Dolor tempor ipsum sanct clita </p> </div> <div className="testimonial-item"> <div className="d-flex align-items-center mb-3"> <img className="img-fluid" src={require('../src/Assets/img/testimonial-3.jpg')} alt="" /> <div className="ml-3"> <h4>Client Name</h4> <i>Profession</i> </div> </div> <p className="m-0"> Sed ea amet kasd elitr stet, stet rebum et ipsum est duo elitr eirmod clita lorem. Dolor tempor ipsum sanct clita </p> </div> </div> </div> </div> */} {/* Testimonial End */} {/* Footer Start */} <div className="container-fluid footer text-white mt-5 pt-5 px-0 position-relative overlay-top"> <div className="row mx-0 pt-5 px-sm-3 px-lg-5 mt-4"> <div className="col-lg-3 col-md-6 mb-5"> <h4 className="text-white text-uppercase mb-4" style={{ letterSpacing: 3 }} > Get In Touch </h4> <p> <i className="fa fa-map-marker-alt mr-2" /> 123 Street, New York, USA </p> <p> <i className="fa fa-phone-alt mr-2" /> +012 345 67890 </p> <p className="m-0"> <i className="fa fa-envelope mr-2" /> info@example.com </p> </div> <div className="col-lg-3 col-md-6 mb-5"> <h4 className="text-white text-uppercase mb-4" style={{ letterSpacing: 3 }} > Follow Us </h4> <p>Amet elitr vero magna sed ipsum sit kasd sea elitr lorem rebum</p> <div className="d-flex justify-content-start"> <a className="btn btn-lg btn-outline-light btn-lg-square mr-2" href="#" > <i className="fab fa-twitter" /> </a> <a className="btn btn-lg btn-outline-light btn-lg-square mr-2" href="#" > <i className="fab fa-facebook-f" /> </a> <a className="btn btn-lg btn-outline-light btn-lg-square mr-2" href="#" > <i className="fab fa-linkedin-in" /> </a> <a className="btn btn-lg btn-outline-light btn-lg-square" href="#"> <i className="fab fa-instagram" /> </a> </div> </div> <div className="col-lg-3 col-md-6 mb-5"> <h4 className="text-white text-uppercase mb-4" style={{ letterSpacing: 3 }} > Open Hours </h4> <div> <h6 className="text-white text-uppercase">Monday - Friday</h6> <p>8.00 AM - 8.00 PM</p> <h6 className="text-white text-uppercase">Saturday - Sunday</h6> <p>2.00 PM - 8.00 PM</p> </div> </div> <div className="col-lg-3 col-md-6 mb-5"> <h4 className="text-white text-uppercase mb-4" style={{ letterSpacing: 3 }} > Newsletter </h4> <p>Amet elitr vero magna sed ipsum sit kasd sea elitr lorem rebum</p> <div className="w-100"> <div className="input-group"> <input type="text" className="form-control border-light" style={{ padding: 25 }} placeholder="Your Email" /> <div className="input-group-append"> <button className="btn btn-primary font-weight-bold px-3"> Sign Up </button> </div> </div> </div> </div> </div> <div className="container-fluid text-center text-white border-top mt-4 py-4 px-sm-3 px-md-5" style={{ borderColor: "rgba(256, 256, 256, .1) !important" }} > <p className="mb-2 text-white"> Copyright ©{" "} <a className="font-weight-bold" href="#"> Domain </a> . All Rights Reserved. </p> <p className="m-0 text-white"> Designed by{" "} <a className="font-weight-bold" href="https://htmlcodex.com"> HTML Codex </a> </p> </div> </div> {/* Footer End */} </> </> </> ) } export default Home;
const mongoose = require("mongoose"); // user schema data const UserSchema = mongoose.Schema({ name: { type: String, required: true, min: 6, max: 255 }, email: { type: String, required: true, min: 6, max: 1024 }, password: { type: String, required: true, minlength: 6 }, docnum: { type: Number, required: true }, isLocked: { type: Boolean, default: false }, failedLoginAttempts: { type: Number, default: 0 }, unity: { type: String, required: true }, role: { type: String, default: 'admin' }, date: { type: Date, default: Date.now }, tempCode: { type: String, default: null }, codeTimestamp: { type: Number, default: 0 } }) module.exports = mongoose.model('User', UserSchema);
<!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="icon" href="assets/images/D & B1.jpg" type="image/gif" sizes="16x16"> <title>EarStore</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="assets/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/css/main.css"> <link href="https://fonts.googleapis.com/css2?family=Yellowtail&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Alegreya+Sans:ital,wght@1,300;1,400&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Poppins:100,200,300,400,500,600,700,900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="assets/css/all.css"> <script type="text/javascript" src="assets/js/jquery-3.5.1.min.js"></script> <script type="text/javascript" src="assets/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" crossorigin="anonymous"></script> <script defer src="assets/js/all.js"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> </head> <body> <nav class="navbar navbar-expand-lg navbar-light navbar-transparent fixed-top" id="scrolled"> <div class="container"> <a class="navbar-brand" href="index.html"><h1><i class="fas fa-shopping-bag"></i></h1></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse topnav" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="category.html">duffles</a> </li> <li class="nav-item"> <a class="nav-link" href="category.html">backpacks</a> </li> <li class="nav-item"> <a class="nav-link" href="#">accessories</a> </li> <li class="nav-item"> <a class="nav-link" href="#">brands</a> </li> <li class="nav-item"> <a class="nav-link" href="#">support</a> </li> </ul> </div> <div class="collapse navbar-collapse w-100 order-3 left-align-navbar topnav" id="navbarNav"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <div class="search-container"> <form action="#" method="get"> <input class="search expand-right" id="search-right" type="search" name="q" placeholder="Search"> <label class="button search-button" for="search-right"><span class="search-icon">&#9906;</span></label> </form> </div> </li> <li class="nav-item"> <a class="nav-link" href="cart.html"><h1><i class="fa fa-shopping-cart"></i><span class="badge badge-light">2</span></h1></a> </li> <li class="nav-item"> <a class="nav-link" href="wishlist.html"><h1><i class="far fa-heart"></i><span class="badge badge-light">4</span></h1></a> </li> <li class="nav-item"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"><h1><i class="fas fa-user"></i></h1></a> <div class="dropdown-menu"> <a class="dropdown-item" href="login.html">Login</a> <a class="dropdown-item" href="profile.html">Profile</a> </div> </li> </li> </ul> </div> </div> </nav> <section class="site-section"> <div class="col-md-12 col-sm-12"> <div class="container checkout"> <!-- <h3 class="page-header">Checkout</h3> --> <div class="row"> <div class="col-md-8 col-sm-12 offset-md-2"> <!-- <div class="row col-md-12 col-sm-12"> --> <h4>Customer Information</h4> <div class="card"> <form> <div class="row"> <div class="col-md-6 col-sm-12"> <div class="form-group"> <label for="exampleInputEmail1">first name</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <label for="exampleInputEmail1">last name</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> </div> <div class="col-md-12 col-sm-12"> <div class="form-group"> <label for="exampleInputEmail1">address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <label for="exampleInputEmail1">country</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <label for="exampleInputEmail1">city</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <label for="exampleInputEmail1">phone</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <label for="exampleInputEmail1">email</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> </div> </div> <a href="#shipping" class="shipping-btn">shipping info</a> </form> </div> <!-- </div> --> <div id="shipping"> <h4>Shipping Info</h4> <div class="card"> <form> <div class="row"> <div class="col-md-6 col-sm-12 shipping"> <div class="card"> <div class="form-group"> <h5>Isaac Nabil</h5> <h5>nabil@gmail.com</h5> <h5>23 Dantu ave North Kaneshie</h5> <h5>Ghana</h5> <h5>0544 127 349</h5> <a href="#" class="address-btn" data-toggle="modal" data-target="#staticBackdrop">Edit Address</a> <a href="#" class="address-btn" data-toggle="modal" data-target="#staticBackdrop">Add New</a> </div> </div> </div> <div class="col-md-6 col-sm-12 shipping"> <div class="mapouter"> <div class="gmap_canvas"> <iframe width="270" height="175" id="gmap_canvas" src="https://maps.google.com/maps?q=Accra&t=&z=13&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"> </iframe> <a href="https://www.whatismyip-address.com">https://www.whatismyip-address.com</a> </div> </div> </div> <div class="col-md-12 col-sm-12"> <h4>Shipping Method</h4> </div> <div class="col-md-6 col-sm-12 shipping"> <div class="card"> <div class="form-group form-check"> <input type="radio" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Standard Delivery</label> <h6>Free</h6> <p>Estimated 14 - 20 Day Shipping<br>(Duties and taxes may be due<br> upon delivery)</p> </div> </div> </div> <div class="col-md-6 col-sm-12 shipping"> <div class="card"> <div class="form-group form-check"> <input type="radio" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Fast Delivery</label> <h6>$8.00</h6> <p>Estimated 2 - 5 Day Shipping<br>(Duties and taxes may be due<br> upon delivery)</p> </div> </div> </div> </div> <a href="#payment" class="shipping-btn">payment info</a> </form> </div> </div> <div id="payment"> <h4>Payment Selection</h4> <div class="card"> <form> <div class="row payment"> <div class="col-md-12 col-sm-12 shipping"> <input type="radio" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Credit Card</label> <h1> <!-- <img src="assets/images/visa_logo.png"> <img src="assets/images/mastercard_logo.png"> --> </i> <i class="fab fa-cc-visa"></i> <i class="fab fa-cc-mastercard"></i> <i class="fab fa-cc-discover"></i> <!-- <i class="fab fa-cc-amex"></i>s --> </h1> <p>Safe money transfer using your bank account. Visa, Maestro, Discover, American Express</p> </div> <div class="col-md-12 col-sm-12"> <div class="form-group"> <label for="card_number">card number</label> <input type="text" class="form-control" id="card_number" id="icon" placeholder="0000 0000 0000 0000"> </div> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <label for="card_number">name on card</label> <input type="text" class="form-control" id="card_number" id="icon" placeholder="eg: Emrade Ambrose"> </div> </div> <div class="col-md-3 col-sm-12"> <div class="form-group"> <label for="card_number">expiry date</label> <input type="text" class="form-control" id="card_number" id="icon" placeholder="MM/YY"> </div> </div> <div class="col-md-3 col-sm-12"> <div class="form-group"> <label for="card_number">cvv code</label> <input type="password" class="form-control" id="card_number" id="icon" placeholder="255"> </div> </div> </div> <div class="row payment"> <a href="#"> <div class="col-md-12 col-sm-12 shipping mt-5"> <input type="radio" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Paypal</label> <h1> <i class="fab fa-paypal"></i> </h1> <p>You will be redirected to the paypal website to complete your purchase securely</p> </div> </a> </div> <a href="#" onclick="buybtn()" class="shipping-btn" type="button">complete order</a> </form> </div> </div> </div> <!-- <div class="col-md-4 col-sm-12"> <div class="show-item"> </div> </div> --> </div> </div> </div> </section> <section> <div class="footer"> <div class="col-md-12 col-sm-12"> <h1><i class="fas fa-shopping-bag"></i></h1> <div class="row"> <div class="col-md-3"> <h3>let us help you</h3> <li><a href="#">Help Center</a></li> <li><a href="#">Contact us</a></li> <li><a href="#">How to buy on D & B</a></li> <li><a href="#">Delivery timelines and fees</a></li> <li><a href="#">Return policy</a></li> </div> <div class="col-md-3"> <h3>payment methods</h3> <a href="#"><h6><i class="fab fa-cc-visa"></i></h6></a> <a href="#"><h6><i class="fab fa-cc-mastercard"></i></h6></a> <a href="#"><h6><i class="fab fa-paypal"></i></h6></a> <a href="#"><h6><i class="fab fa-google-pay"></i></h6></a> </div> <div class="col-md-3"> <h3>about us</h3> <li><a href="#">About us</a></li> <li><a href="#">Testimonials</a></li> <li><a href="#">D & B careers</a></li> <li><a href="#">Terms and conditions</a></li> <li><a href="#">Privacy policy</a></li> </div> <div class="col-md-3"> <h3>We're friendly, follow us</h3> <a href="#"><h6><i class="fab fa-facebook-f"></i></h6></a> <a href="#"><h6><i class="fab fa-instagram"></i></h6></a> <a href="#"><h6><i class="fab fa-twitter"></i></h6></a> <a href="#"><h6><i class="fab fa-tiktok"></i></h6></a> </div> </div> </div> </div> </section> <!-- Modal --> <div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Address</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="row"> <div class="col-md-6 col-sm-12"> <div class="form-group"> <label for="name">full name</label> <input type="text" class="form-control" id="name"> </div> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <label for="email">email</label> <input type="email" class="form-control" id="email" aria-describedby="emailHelp"> </div> </div> <div class="col-md-12 col-sm-12"> <div class="form-group"> <label for="address">Address</label> <input type="text" class="form-control" id="address"> </div> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <label for="country">country</label> <input type="text" class="form-control" id="country"> </div> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <label for="phone">phone</label> <input type="tel" class="form-control" id="phone"> </div> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger shadow-none" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary shadow-none">Save</button> </div> </div> </div> </div> <script> function buybtn() { swal("Order Completed!", "Thanks for shopping with us!", "success"); } $(document).ready(function(){ var scrollTop = 0; $(window).scroll(function(){ scrollTop = $(window).scrollTop(); $('.counter').html(scrollTop); if (scrollTop >= 100) { $('#scrolled').addClass('scrolled-nav'); } else if (scrollTop < 100) { $('#scrolled').removeClass('scrolled-nav'); } }); }); </script> </body> </html>
import { combineReducers, configureStore } from "@reduxjs/toolkit"; import toolkitSlice from "./toolkitSlice"; import catalogSlice from "./catalogSlice"; import { persistStore, persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER, } from 'redux-persist' import storage from 'redux-persist/lib/storage' //redux-persist - для взаимодействи я с localStorege const rootReducer = combineReducers( {toolkit: toolkitSlice, catalog: catalogSlice, } ); const persistConfig = { key: 'root', storage, blacklist: ['catalog'] // этот слайс не добавляется в локалсторедж } const persistedReducer = persistReducer(persistConfig, rootReducer); const store = configureStore( { reducer: persistedReducer, middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: { ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER], }, }), }); export const persistor = persistStore(store); export default store;
//SPDX-License-Identifier: MIT pragma solidity ^0.8.7; /** * 1.捐款實作 * 2.限定最低捐款金額 * 3.儲存捐贈者名單及捐贈金額 */ contract Donation { mapping(address => uint) public ledger; mapping(address => bool) public donors; address[] public donorList; function isDonor(address addr) public view returns(bool) { return donors[addr]; } function donate() public payable { if(msg.value >= 0.5 ether) { if(!isDonor(msg.sender)) { donors[msg.sender] = true; donorList.push(msg.sender); } ledger[msg.sender] += msg.value; } else revert("< 0.5 ETH."); } function withdraw(uint amount) public { payable(msg.sender).transfer(amount * 1 ether); } }
import { useState, useRef } from "react"; import { TextField } from "../atom/TextField"; import { ErrorMessage } from "../atom/ErrorMessage"; import { ButtonConfirmModal } from "../atom/ButtonConfirmModal"; import { commentsUrl } from "../../lib/api-url"; export const CommentForm = ({ addComment }) => { const errorMessage = useRef({ username: "", comment: "", }); const [errorSending, setErrorSending] = useState(false); const handleSubmit = (e) => { e.preventDefault(); const username = e.target.username.value; const comment = e.target.comment.value; errorMessage.current.comment = ""; errorMessage.current.username = ""; // if username is less than 3 characters return an error if (username.length < 3) { errorMessage.current.username = "Username must be at least 3 characters"; } if (username.length > 20) { errorMessage.current.username = "Username must be less than 20 characters"; } // if comment is less than 10 characters return an error if (comment.length < 10) { errorMessage.current.comment = "Comment must be at least 10 characters"; } if (comment.length > 200) { errorMessage.current.comment = "Comment must be less than 200 characters"; } if (errorMessage.current.username || errorMessage.current.comment) { setErrorSending("Please correct the error(s) below"); return false; } // send the form in POST request to the commentsUrl addComment({ username, comment }) .then(() => { setErrorSending(null); e.target.reset(); }) .catch((error) => { setErrorSending("Something wrong happend: " + error.error); }); }; return ( // send the form in POST request to the commentsUrl <form action={commentsUrl} id="commentForm" method="POST" className="flex w-full flex-col gap-4 md:px-8" onSubmit={(e) => handleSubmit(e)} > {errorSending && <ErrorMessage> {errorSending} </ErrorMessage>} <TextField label="Username" id="username" type="text" placeholder="Username" /> {errorMessage.current.username && ( <ErrorMessage> {errorMessage.current.username} </ErrorMessage> )} <TextField label="Commentaire" id="comment" type="text" placeholder="Commentaire" component="textarea" /> {errorMessage.current.comment && ( <ErrorMessage> {errorMessage.current.comment} </ErrorMessage> )} <ButtonConfirmModal value="Submit" type="submit"> Your comment has been sent ! </ButtonConfirmModal> </form> ); };
from django.db import models from versatileimagefield.fields import VersatileImageField from tinymce.models import HTMLField from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class Category(models.Model): image=VersatileImageField(upload_to='product_images/') name = models.CharField(max_length=50) def __str__(self): return self.name class Product(models.Model): cover_image=VersatileImageField(upload_to='product_images/') name = models.CharField(max_length=50) price = models.IntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) description = HTMLField() def __str__(self): return self.name class Product_images(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = VersatileImageField(upload_to='product_images/') class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=50) email = models.EmailField(null=True, blank=True) comment = models.TextField() rating = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)] ) created_at = models.DateField(auto_now_add=True) def __str__(self): return f"Review by {self.name} for {self.product.name}"
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCompaniesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('companies', function (Blueprint $table) { $table->id(); $table->integer('company_id')->unsigned()->unique(); $table->text('name'); $table->text('description'); $table->timestamps(); $table->index('company_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('companies'); } }
use std::{env, thread, time::Duration}; use diesel::{ r2d2::{self, ConnectionManager, Pool}, PgConnection, }; use flume::Sender; use rocket::{get, post, routes, serde::json::Json, State}; use search::{ db, index::{FragmentIndex, FragmentWriter}, model::{FragmentInfo, SearchOperation}, }; mod logging; const DATABASE_URL: &str = "DATABASE_URL"; const INDEX_DIRECTORY: &str = "INDEX_DIRECTORY"; #[rocket::main] async fn main() -> Result<(), rocket::Error> { dotenvy::dotenv().ok(); logging::initialize(); let manager = r2d2::ConnectionManager::<PgConnection>::new(env::var(DATABASE_URL).unwrap()); let pool = r2d2::Pool::builder().build(manager).unwrap(); let (tx, rx) = flume::unbounded::<SearchOperation>(); let index = FragmentIndex::new(env::var(INDEX_DIRECTORY).unwrap()).unwrap(); let mut writer = index.writer().unwrap(); // In theory, this results in single-threaded indexing, except that I believe the IndexWriter // itself manages a queue and threadpool. In any case, the actual load on this application is // expected to light, so it hardly matters. let _receiver = thread::spawn(move || { for op in rx { match op { SearchOperation::Commit => { if let Err(e) = writer.commit() { tracing::error!(error = ?e, "failed to commit changes"); } } SearchOperation::Index(id) => { if let Err(e) = update_fragment(id, &mut writer, &pool) { tracing::error!(error = ?e, "failed to update fragment id:{id}"); } } SearchOperation::Remove(id) => { if let Err(e) = remove_fragment(id, &mut writer) { tracing::error!(error = ?e, "failed to remove fragment id:{id}"); } } } } }); let commit_tx = tx.clone(); let _commiter = thread::spawn(move || loop { thread::sleep(Duration::from_secs(90)); commit_tx.send(SearchOperation::Commit).unwrap(); }); let _rocket = rocket::build() .manage(tx) .manage(index) .mount("/", routes![add_remove, query]) .launch() .await?; Ok(()) } #[get("/?<q>&<p>")] fn query(q: String, p: Option<usize>, index: &State<FragmentIndex>) -> Json<Vec<FragmentInfo>> { let results = index.search(&q, p.unwrap_or(0)).unwrap(); Json(results) } #[post("/?<a>&<r>")] fn add_remove(a: Option<i64>, r: Option<i64>, sender: &State<Sender<SearchOperation>>) { if let Some(id) = r { sender.send(SearchOperation::Remove(id)).unwrap(); } if let Some(id) = a { sender.send(SearchOperation::Index(id)).unwrap(); } } fn update_fragment( id: i64, writer: &mut FragmentWriter, pool: &Pool<ConnectionManager<PgConnection>>, ) -> anyhow::Result<()> { tracing::debug!("update fragment id:{id}"); let cx = pool.get()?; if let Some(fragment) = db::by_id(id, cx) { writer.update(&fragment)?; } Ok(()) } fn remove_fragment(id: i64, writer: &mut FragmentWriter) -> anyhow::Result<()> { tracing::debug!("remove fragment id:{id}"); writer.remove(id)?; Ok(()) }
/* eslint-disable import/prefer-default-export */ import axios from "@/utils/axios"; import { roleEnabledState } from "@/utils/dict"; import type { AxiosResultPromise } from "@/utils/axios"; export type Role = { id: string; roleName: string; description: string; status: (typeof roleEnabledState.options)[number]["value"]; createTime: string; }; /** * 分页获取角色列表 * @param params - 查询参数 * @param pageIndex - 页码 默认: 1 * @param pageSize - 页大小 默认:10 */ export const getRoleList: ( params: any, pageIndex: number, pageSize: number ) => AxiosResultPromise<{ records: Role[]; total: number; pageIndex: number; }> = (params, pageIndex = 1, pageSize = 10) => { return axios.post("/api/role/page", { params, pageIndex, pageSize }); }; /** * 通过id更新角色状态 * @param id - id * @param status - 角色状态 */ export const updateRoleStatusById: ( id: Role["id"], status: Role["status"] ) => AxiosResultPromise<any> = (id, status) => { return axios.post("/api/role/status/update", { id, status }); }; /** * 通过id删除角色 * @param id - id */ export const removeRole: (id: string) => AxiosResultPromise<any> = (id) => axios.post("/api/role/remove", { id }); /** * 角色授权 * @param params */ export const authRole: (params: any[]) => AxiosResultPromise<any> = (params) => axios.post("/api/role/auth", params); /** * 获取角色选择器 */ export const getRoleSelect: () => AxiosResultPromise< { value: string; label: string }[] > = () => axios.get("/api/role/select");
package nl.ritense.demo.web.rest; import static nl.ritense.demo.domain.VerzuimAsserts.*; import static nl.ritense.demo.web.rest.TestUtil.createUpdateProxyForBean; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.persistence.EntityManager; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; import nl.ritense.demo.IntegrationTest; import nl.ritense.demo.domain.Verzuim; import nl.ritense.demo.repository.VerzuimRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; /** * Integration tests for the {@link VerzuimResource} REST controller. */ @IntegrationTest @AutoConfigureMockMvc @WithMockUser class VerzuimResourceIT { private static final String DEFAULT_DATUMTIJDEINDE = "AAAAAAAAAA"; private static final String UPDATED_DATUMTIJDEINDE = "BBBBBBBBBB"; private static final String DEFAULT_DATUMTIJDSTART = "AAAAAAAAAA"; private static final String UPDATED_DATUMTIJDSTART = "BBBBBBBBBB"; private static final String ENTITY_API_URL = "/api/verzuims"; private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; private static Random random = new Random(); private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); @Autowired private ObjectMapper om; @Autowired private VerzuimRepository verzuimRepository; @Autowired private EntityManager em; @Autowired private MockMvc restVerzuimMockMvc; private Verzuim verzuim; /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Verzuim createEntity(EntityManager em) { Verzuim verzuim = new Verzuim().datumtijdeinde(DEFAULT_DATUMTIJDEINDE).datumtijdstart(DEFAULT_DATUMTIJDSTART); return verzuim; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Verzuim createUpdatedEntity(EntityManager em) { Verzuim verzuim = new Verzuim().datumtijdeinde(UPDATED_DATUMTIJDEINDE).datumtijdstart(UPDATED_DATUMTIJDSTART); return verzuim; } @BeforeEach public void initTest() { verzuim = createEntity(em); } @Test @Transactional void createVerzuim() throws Exception { long databaseSizeBeforeCreate = getRepositoryCount(); // Create the Verzuim var returnedVerzuim = om.readValue( restVerzuimMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(verzuim))) .andExpect(status().isCreated()) .andReturn() .getResponse() .getContentAsString(), Verzuim.class ); // Validate the Verzuim in the database assertIncrementedRepositoryCount(databaseSizeBeforeCreate); assertVerzuimUpdatableFieldsEquals(returnedVerzuim, getPersistedVerzuim(returnedVerzuim)); } @Test @Transactional void createVerzuimWithExistingId() throws Exception { // Create the Verzuim with an existing ID verzuim.setId(1L); long databaseSizeBeforeCreate = getRepositoryCount(); // An entity with an existing ID cannot be created, so this API call must fail restVerzuimMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(verzuim))) .andExpect(status().isBadRequest()); // Validate the Verzuim in the database assertSameRepositoryCount(databaseSizeBeforeCreate); } @Test @Transactional void getAllVerzuims() throws Exception { // Initialize the database verzuimRepository.saveAndFlush(verzuim); // Get all the verzuimList restVerzuimMockMvc .perform(get(ENTITY_API_URL + "?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(verzuim.getId().intValue()))) .andExpect(jsonPath("$.[*].datumtijdeinde").value(hasItem(DEFAULT_DATUMTIJDEINDE))) .andExpect(jsonPath("$.[*].datumtijdstart").value(hasItem(DEFAULT_DATUMTIJDSTART))); } @Test @Transactional void getVerzuim() throws Exception { // Initialize the database verzuimRepository.saveAndFlush(verzuim); // Get the verzuim restVerzuimMockMvc .perform(get(ENTITY_API_URL_ID, verzuim.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(verzuim.getId().intValue())) .andExpect(jsonPath("$.datumtijdeinde").value(DEFAULT_DATUMTIJDEINDE)) .andExpect(jsonPath("$.datumtijdstart").value(DEFAULT_DATUMTIJDSTART)); } @Test @Transactional void getNonExistingVerzuim() throws Exception { // Get the verzuim restVerzuimMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test @Transactional void putExistingVerzuim() throws Exception { // Initialize the database verzuimRepository.saveAndFlush(verzuim); long databaseSizeBeforeUpdate = getRepositoryCount(); // Update the verzuim Verzuim updatedVerzuim = verzuimRepository.findById(verzuim.getId()).orElseThrow(); // Disconnect from session so that the updates on updatedVerzuim are not directly saved in db em.detach(updatedVerzuim); updatedVerzuim.datumtijdeinde(UPDATED_DATUMTIJDEINDE).datumtijdstart(UPDATED_DATUMTIJDSTART); restVerzuimMockMvc .perform( put(ENTITY_API_URL_ID, updatedVerzuim.getId()) .contentType(MediaType.APPLICATION_JSON) .content(om.writeValueAsBytes(updatedVerzuim)) ) .andExpect(status().isOk()); // Validate the Verzuim in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); assertPersistedVerzuimToMatchAllProperties(updatedVerzuim); } @Test @Transactional void putNonExistingVerzuim() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); verzuim.setId(longCount.incrementAndGet()); // If the entity doesn't have an ID, it will throw BadRequestAlertException restVerzuimMockMvc .perform(put(ENTITY_API_URL_ID, verzuim.getId()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(verzuim))) .andExpect(status().isBadRequest()); // Validate the Verzuim in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void putWithIdMismatchVerzuim() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); verzuim.setId(longCount.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restVerzuimMockMvc .perform( put(ENTITY_API_URL_ID, longCount.incrementAndGet()) .contentType(MediaType.APPLICATION_JSON) .content(om.writeValueAsBytes(verzuim)) ) .andExpect(status().isBadRequest()); // Validate the Verzuim in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void putWithMissingIdPathParamVerzuim() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); verzuim.setId(longCount.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restVerzuimMockMvc .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(verzuim))) .andExpect(status().isMethodNotAllowed()); // Validate the Verzuim in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void partialUpdateVerzuimWithPatch() throws Exception { // Initialize the database verzuimRepository.saveAndFlush(verzuim); long databaseSizeBeforeUpdate = getRepositoryCount(); // Update the verzuim using partial update Verzuim partialUpdatedVerzuim = new Verzuim(); partialUpdatedVerzuim.setId(verzuim.getId()); partialUpdatedVerzuim.datumtijdeinde(UPDATED_DATUMTIJDEINDE).datumtijdstart(UPDATED_DATUMTIJDSTART); restVerzuimMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedVerzuim.getId()) .contentType("application/merge-patch+json") .content(om.writeValueAsBytes(partialUpdatedVerzuim)) ) .andExpect(status().isOk()); // Validate the Verzuim in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); assertVerzuimUpdatableFieldsEquals(createUpdateProxyForBean(partialUpdatedVerzuim, verzuim), getPersistedVerzuim(verzuim)); } @Test @Transactional void fullUpdateVerzuimWithPatch() throws Exception { // Initialize the database verzuimRepository.saveAndFlush(verzuim); long databaseSizeBeforeUpdate = getRepositoryCount(); // Update the verzuim using partial update Verzuim partialUpdatedVerzuim = new Verzuim(); partialUpdatedVerzuim.setId(verzuim.getId()); partialUpdatedVerzuim.datumtijdeinde(UPDATED_DATUMTIJDEINDE).datumtijdstart(UPDATED_DATUMTIJDSTART); restVerzuimMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedVerzuim.getId()) .contentType("application/merge-patch+json") .content(om.writeValueAsBytes(partialUpdatedVerzuim)) ) .andExpect(status().isOk()); // Validate the Verzuim in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); assertVerzuimUpdatableFieldsEquals(partialUpdatedVerzuim, getPersistedVerzuim(partialUpdatedVerzuim)); } @Test @Transactional void patchNonExistingVerzuim() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); verzuim.setId(longCount.incrementAndGet()); // If the entity doesn't have an ID, it will throw BadRequestAlertException restVerzuimMockMvc .perform( patch(ENTITY_API_URL_ID, verzuim.getId()).contentType("application/merge-patch+json").content(om.writeValueAsBytes(verzuim)) ) .andExpect(status().isBadRequest()); // Validate the Verzuim in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithIdMismatchVerzuim() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); verzuim.setId(longCount.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restVerzuimMockMvc .perform( patch(ENTITY_API_URL_ID, longCount.incrementAndGet()) .contentType("application/merge-patch+json") .content(om.writeValueAsBytes(verzuim)) ) .andExpect(status().isBadRequest()); // Validate the Verzuim in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithMissingIdPathParamVerzuim() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); verzuim.setId(longCount.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restVerzuimMockMvc .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(om.writeValueAsBytes(verzuim))) .andExpect(status().isMethodNotAllowed()); // Validate the Verzuim in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void deleteVerzuim() throws Exception { // Initialize the database verzuimRepository.saveAndFlush(verzuim); long databaseSizeBeforeDelete = getRepositoryCount(); // Delete the verzuim restVerzuimMockMvc .perform(delete(ENTITY_API_URL_ID, verzuim.getId()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); // Validate the database contains one less item assertDecrementedRepositoryCount(databaseSizeBeforeDelete); } protected long getRepositoryCount() { return verzuimRepository.count(); } protected void assertIncrementedRepositoryCount(long countBefore) { assertThat(countBefore + 1).isEqualTo(getRepositoryCount()); } protected void assertDecrementedRepositoryCount(long countBefore) { assertThat(countBefore - 1).isEqualTo(getRepositoryCount()); } protected void assertSameRepositoryCount(long countBefore) { assertThat(countBefore).isEqualTo(getRepositoryCount()); } protected Verzuim getPersistedVerzuim(Verzuim verzuim) { return verzuimRepository.findById(verzuim.getId()).orElseThrow(); } protected void assertPersistedVerzuimToMatchAllProperties(Verzuim expectedVerzuim) { assertVerzuimAllPropertiesEquals(expectedVerzuim, getPersistedVerzuim(expectedVerzuim)); } protected void assertPersistedVerzuimToMatchUpdatableProperties(Verzuim expectedVerzuim) { assertVerzuimAllUpdatablePropertiesEquals(expectedVerzuim, getPersistedVerzuim(expectedVerzuim)); } }
import MFoldable from './MFoldable.vue'; import { Meta, StoryFn } from '@storybook/vue3' export default { title: 'molecules/MFoldable', component: MFoldable, } as Meta<typeof MFoldable> const Template:StoryFn<typeof MFoldable> = (args) => ({ components: { MFoldable }, setup() { return { args, } }, template: ` <MFoldable> <template #header> <h2 class="ma-0">주식회사 TEST보로노이 법인 설립 신청 내역</h2> </template> <template #content> <ul> <li>Content 1</li> <li>Content 2</li> <li>Content 3</li> </ul> </template> </MFoldable> `, }) export const FoldableExample = Template.bind({})
import { Injectable } from '@angular/core'; import { Project } from './projectModel'; @Injectable({ providedIn: 'root', }) export class ProjectsService { createEmptyProjectsItem() { const newProjectArray: Project[] = []; localStorage.setItem('projects', JSON.stringify(newProjectArray)); } // Read getProjects(): Project[] { if (!localStorage.getItem('projects')) { this.createEmptyProjectsItem(); } const projects: Project[] = JSON.parse(localStorage.getItem('projects')!); return projects; } getProject(projectName: string): Project | void { if (!localStorage.getItem('projects')) { this.createEmptyProjectsItem(); } let project: Project | null = null; const projects: Project[] = JSON.parse(localStorage.getItem('projects')!); projects.forEach((pr: Project) => { if (projectName === pr.name) { project = pr; return; } }); if (project) return project; alert(`Project of the name '${projectName}' not found`); } // Create createProject(project: Project) { if (this.hasDuplicates(project)) { return; } if (!localStorage.getItem('projects')) { this.createEmptyProjectsItem(); } let projects: Project[] = this.getProjects(); projects.push(project); localStorage.setItem('projects', JSON.stringify(projects)); } hasDuplicates(project: Project): boolean { let projects = this.getProjects(); let duplicatesExist: boolean = false; projects.forEach((pr: Project) => { if (pr.name === project.name) { alert('Project names must be unique'); duplicatesExist = true; return; } }); return duplicatesExist; } // Update updateProject(project: Project, oldName: string) { const projects = this.getProjects(); let index: number = -1; projects.forEach((pr: Project, i) => { if(pr.name === oldName) { index = i; } }) if (index == -1) { return; } const updatedProjects = [...projects.slice(0,index), project, ...projects.slice(index + 1)] localStorage.setItem('projects', JSON.stringify(updatedProjects)); } // Delete deleteProject(projectName: string) { const projects = this.getProjects(); let index: number = -1; projects.forEach((pr: Project, i) => { if(pr.name === projectName) { index = i; } }) if (index == -1) { return; } const updatedProjects = [...projects.slice(0,index), ...projects.slice(index + 1)] localStorage.setItem('projects', JSON.stringify(updatedProjects)); } }
package _03_Intro_to_Enums; import java.util.Random; import javax.swing.JOptionPane; enum Elements { /* * enums (short for enumerated type) are a class-like structure that can contain * a set of specific data values. */ // Note: Every entry must be unique. AIR, EARTH, FIRE, METAL, WATER, WOOD } public class IntroToEnums { public static void main(String[] args) { // 1. In your package explorer, create a new enum file called StatesOfMatter. // Hint: This is very similar to how you create a new class file. // 2. Give the enum the following values: // SOLID, LIQUID, GAS // 3. Create an array of StatesOfMatter with all the values using .values(). // Hint: Use "StatesOfMatter." as if it were a static method. StatesOfMatter[] som =StatesOfMatter.values(); // 4. Ask the user for a state of matter. String answer = JOptionPane.showInputDialog("CHOOSE A STATE OF MATTER"); // 5. Iterate through the array and find what the user entered. // Hint: .name() or .toString for (int i = 0; i < som.length; i++) { if((som[i].name()).equalsIgnoreCase(answer)) { System.out.println(som[i].ordinal()); } } // 6. Print outs its ordinal(order in the enum list) // Hint: .ordinal() // 7. Add a celsiusTemp member variable to StatesOfMatter. // Note: Make sure to encapsulate it. // 8. Give it a default value of the temperature each state occurs in water. // Hint: Gas = 100, Liquid(room temp) = 25.55, Solid = 0 // Example // enum Months{ // // JAN(31),FEB(28),MAR(31),APR(30),MAY(31),JUN(30),JUL(31),AUG(31),SEP(30), // OCT(31),NOV(30),DEC(31); // // int daysInMonth; // // private Months(int daysInMonth) { // this.daysInMonth = daysInMonth; // } // 9. Add a convertToFahrenheit method to StatesOfMatter // Hint: Return the conversion: F = (C * 9/5) + 32 Random rand = new Random(); StatesOfMatter test= null; // 10. Create a variable of the StatesOfMatter type and initialize it randomly. switch(rand.nextInt(2)) { case 0: test = StatesOfMatter.GAS; break; case 1: test = StatesOfMatter.LIQUID; break; case 2: test = StatesOfMatter.SOLID; break; } // 11. Print outs both of its temperatures. System.out.println(test.getCelsiusTemp(test)); System.out.println(test.convertToFarenheit(test)); // 11. Create a switch statement that switches on the variable you created. // Note: When creating the cases, you can omit the "StatesOfMatter." switch (test) { case GAS: System.out.println("Pasta"); break; case LIQUID: System.out.println("Water"); break; case SOLID: System.out.println("Ice Cream"); break; } // 12. For each case, print your favorite food or drink that uses that state. // e.g. Gas/Boiling for Pasta, Solid/Ice for Popsicles, Liquid for Soda } }
(function () { 'use strict'; describe('Ingredients Controller Tests', function () { // Initialize global variables var IngredientsController, $scope, $httpBackend, $state, Authentication, IngredientsService, mockIngredient; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function () { jasmine.addMatchers({ toEqualData: function (util, customEqualityTesters) { return { compare: function (actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _IngredientsService_) { // Set a new global scope $scope = $rootScope.$new(); // Point global variables to injected services $httpBackend = _$httpBackend_; $state = _$state_; Authentication = _Authentication_; IngredientsService = _IngredientsService_; // create mock Ingredient mockIngredient = new IngredientsService({ _id: '525a8422f6d0f87f0e407a33', name: 'Ingredient Name' }); // Mock logged in user Authentication.user = { roles: ['user'] }; // Initialize the Ingredients controller. IngredientsController = $controller('IngredientsController as vm', { $scope: $scope, ingredientResolve: {} }); //Spy on state go spyOn($state, 'go'); })); describe('vm.save() as create', function () { var sampleIngredientPostData; beforeEach(function () { // Create a sample Ingredient object sampleIngredientPostData = new IngredientsService({ name: 'Ingredient Name' }); $scope.vm.ingredient = sampleIngredientPostData; }); it('should send a POST request with the form input values and then locate to new object URL', inject(function (IngredientsService) { // Set POST response $httpBackend.expectPOST('api/ingredients', sampleIngredientPostData).respond(mockIngredient); // Run controller functionality $scope.vm.save(true); $httpBackend.flush(); // Test URL redirection after the Ingredient was created expect($state.go).toHaveBeenCalledWith('ingredients.view', { ingredientId: mockIngredient._id }); })); it('should set $scope.vm.error if error', function () { var errorMessage = 'this is an error message'; $httpBackend.expectPOST('api/ingredients', sampleIngredientPostData).respond(400, { message: errorMessage }); $scope.vm.save(true); $httpBackend.flush(); expect($scope.vm.error).toBe(errorMessage); }); }); describe('vm.save() as update', function () { beforeEach(function () { // Mock Ingredient in $scope $scope.vm.ingredient = mockIngredient; }); it('should update a valid Ingredient', inject(function (IngredientsService) { // Set PUT response $httpBackend.expectPUT(/api\/ingredients\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality $scope.vm.save(true); $httpBackend.flush(); // Test URL location to new object expect($state.go).toHaveBeenCalledWith('ingredients.view', { ingredientId: mockIngredient._id }); })); it('should set $scope.vm.error if error', inject(function (IngredientsService) { var errorMessage = 'error'; $httpBackend.expectPUT(/api\/ingredients\/([0-9a-fA-F]{24})$/).respond(400, { message: errorMessage }); $scope.vm.save(true); $httpBackend.flush(); expect($scope.vm.error).toBe(errorMessage); })); }); describe('vm.remove()', function () { beforeEach(function () { //Setup Ingredients $scope.vm.ingredient = mockIngredient; }); it('should delete the Ingredient and redirect to Ingredients', function () { //Return true on confirm message spyOn(window, 'confirm').and.returnValue(true); $httpBackend.expectDELETE(/api\/ingredients\/([0-9a-fA-F]{24})$/).respond(204); $scope.vm.remove(); $httpBackend.flush(); expect($state.go).toHaveBeenCalledWith('ingredients.list'); }); it('should should not delete the Ingredient and not redirect', function () { //Return false on confirm message spyOn(window, 'confirm').and.returnValue(false); $scope.vm.remove(); expect($state.go).not.toHaveBeenCalled(); }); }); }); })();
import React, { useState, useEffect } from "react"; import { View, StyleSheet, ScrollView } from "react-native"; import { IconButton, Searchbar } from "react-native-paper"; import { SafeAreaView } from "react-native-safe-area-context"; import { startCase } from "lodash"; import { fetchLeaguesByUserId } from "../../utils/api"; import { useAuth } from "../../contexts/AuthContext"; import LogoInverse from "../../../assets/images/logoInverse.png"; import LeagueCard from "../../components/LeagueCard/LeagueCard"; import { ActivityIndicator, Text } from "react-native-paper"; const LeaguesScreen = ({ navigation }) => { const { user } = useAuth(); const [leagues, setLeagues] = useState([]); const [loading, setLoading] = useState(true); const [searchQuery, setSearchQuery] = useState(""); const [expiredDropdownPressed, setExpiredDropdownPressed] = useState(false); const [currentDropdownPressed, setCurrentDropdownPressed] = useState(true); useEffect(() => { fetchLeaguesByUserId(user.userId, user.exp) .then((leagues) => { setLeagues(leagues); setLoading(false); }) .catch((error) => { console.log(error); setLoading(false); }); }, []); const firstName = startCase(user.name.split(" ")[0]); const navigateToIndividualLeague = (leagueId) => { navigation.navigate("IndividualNavigator", { leagueId }); }; const currentLeagues = leagues.filter((league) => { return new Date(league.end_date) > new Date(); }); const oldLeagues = leagues.filter((league) => { return new Date(league.end_date) < new Date(); }); const handleExpiredDropdown = () => { setExpiredDropdownPressed(!expiredDropdownPressed); }; const handleCurrentDropdown = () => { setCurrentDropdownPressed(!currentDropdownPressed); }; return ( <ScrollView> <SafeAreaView> <View style={styles.root}> <View style={styles.contentContainer}> {/* <Image source={LogoInverse} style={[styles.logo]} resizeMode="contain" /> */} <Text variant="labelLarge" style={styles.header}> u/{user.username} </Text> <View style={styles.search}> <Searchbar style={styles.searchBar} placeholder="Search for a league" onChangeText={setSearchQuery} value={searchQuery} /> </View> <View style={styles.row}> <View style={styles.expiredLeagues}> <Text style={[styles.header, styles.leagueHeader]}> Ongoing Leagues </Text> </View> {currentDropdownPressed ? ( <IconButton icon="arrow-down-drop-circle" iconColor="#2B2D42" size={20} onPress={handleCurrentDropdown} /> ) : ( <IconButton icon="arrow-up-drop-circle" iconColor="#2B2D42" size={20} onPress={handleCurrentDropdown} /> )} </View> {currentDropdownPressed ? ( loading ? ( <ActivityIndicator animating={true} /> ) : currentLeagues.length === 0 ? ( <View style={[styles.leagueCard, styles.centre]}> <Text style={styles.noLeagueMessage}> No current leagues... </Text> </View> ) : ( <> {currentLeagues.map((league) => ( <View style={styles.leagueCard} key={league.league_id}> <LeagueCard leagueId={league.league_id} leagueName={league.name} clubId={league.club_id} startDate={league.start_date} endDate={league.end_date} format={league.format} adminId={league.admin} userId={user.userId} exp={user.exp} onPress={() => navigateToIndividualLeague(league.league_id) } /> </View> ))} </> ) ) : null} <View style={styles.row}> <View style={styles.expiredLeagues}> <Text style={[styles.header, styles.leagueHeader]}> Expired Leagues </Text> </View> {expiredDropdownPressed ? ( <IconButton icon="arrow-down-drop-circle" iconColor="#2B2D42" size={20} onPress={handleExpiredDropdown} /> ) : ( <IconButton icon="arrow-up-drop-circle" iconColor="#2B2D42" size={20} onPress={handleExpiredDropdown} /> )} </View> {expiredDropdownPressed ? ( loading ? ( <ActivityIndicator animating={true} /> ) : ( <> {oldLeagues.map((league) => ( <View style={[styles.leagueCard, styles.faded]} key={league.league_id} > <LeagueCard leagueId={league.league_id} leagueName={league.name} clubId={league.club_id} startDate={league.start_date} endDate={league.end_date} format={league.format} adminId={league.admin} userId={user.userId} exp={user.exp} onPress={() => navigateToIndividualLeague(league.league_id) } /> </View> ))} </> ) ) : null} </View> </View> </SafeAreaView> </ScrollView> ); }; export default LeaguesScreen; const styles = StyleSheet.create({ root: { paddingHorizontal: 20, justifyContent: "space-between", flex: 1, }, contentContainer: {}, search: { marginVertical: 10, }, logo: { width: "100%", maxWidth: 500, maxHeight: 80, }, header: { fontSize: 20, paddingBottom: 5, textAlign: "left", color: "#2B2D42", }, leagueHeader: { fontSize: 24, fontWeight: "bold", }, leagueCard: { paddingBottom: 10, marginVertical: 5 }, centre: { flex: 1, justifyContent: "center", alignItems: "center", }, noLeagueMessage: { color: "#2B2D42", fontSize: 20, }, faded: { opacity: 0.5, }, searchBar: { backgroundColor: "white", borderRadius: 15, borderWidth: 1, borderColor: "#2B2D42", }, row: { flexDirection: "row", }, expiredLeagues: { justifyContent: "center", }, });
# Common Lisp and Prolog URI parser Project made for the exam of the Programming Languages course (academic year 2021-2022) at UniMiB. The purpose of the project was to create a Common Lisp and Prolog library that can build structures, internally representing **URI**s (Uniform Resource Identifiers), starting from their representations as strings. Parsing requires analyzing and decomposing the input string in sequence, character from character from left to right, in order to build a proper structure that stores its seven components. Check [Lisp README.md](/Lisp/README.md) for Common Lisp usage. Check [Prolog README.md](/Prolog/README.md) for Prolog usage. ## What is an URI? A Uniform Resource Identifier (URI) is a unique sequence of characters that identifies a logical or physical resource used by web technologies. URIs may be used to identify anything, including real-world objects, such as people and places, concepts, or information resources such as web pages and books. [source: https://en.wikipedia.org/wiki/Uniform_Resource_Identifier] ## What Request for Comments was used as a reference? A simplified version of **[RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986)**: ``` URI ::= URI1 | URI2 URI1 ::= scheme ‘:’ [authorithy] [[‘/’] [path] [‘?’ query] [‘#’ fragment]] URI2 ::= scheme ‘:’ scheme-syntax scheme ::= <identifier> authorithy ::= ‘//’ [ userinfo ‘@’ ] host [‘:’ port] userinfo ::= <identifier> host ::= <host-identifier> [‘.’ <host-identifier>]* | IP-address port ::= <digit>+ IP-address ::= <NNN.NNN.NNN.NNN – N is a digit> path ::= <identifier> [‘/’ <identifier>]* [‘/’] query ::= <characters without ‘#’>+ fragment ::= <characters>+ <identifier> ::= <characters without ‘/’, ‘?’, ‘#’, ‘@’, or ‘:’>+ <host-identifier> ::= <characters without ‘.’, ‘/’, ‘?’, ‘#’, ‘@’, or ‘:’>+ <digit> ::= ‘0’ |‘1’ |‘2’ |‘3’ |‘4’ |‘5’ |‘6’ |‘7’ |‘8’ |‘9’ scheme-syntax ::= <special syntaxes - see below> ``` **Special syntaxes:** ``` Mailto: scheme ::= "mailto" -> scheme-syntax ::= [userinfo [‘@’ host]] News: scheme ::= "news" -> scheme-syntax ::= [host] Tel/fax: scheme ::= "tel" | "fax" -> scheme-syntax ::= [userinfo] Zos: scheme ::= "zos" -> URI1 ::= scheme ‘:’ [authorithy] [[‘/’] [path] [‘?’ query] [‘#’ fragment]] In this case, path is quite different, but the other fields need to be checked like usual. path ::= <id44> [‘(’ <id8> ‘)’] id44 ::= (<alphanum> | ‘.’)+ (max. length = 44 characters. Can not end with a ‘.’) id8 ::= (<alphanum>)+ (max. length = 8 characters) alphanum ::= <alphabetic characters and digits> ```
package witharraylist; public class Customer { //private은 외부클래스에서 볼 수 없음(접근 못함 == 가시성(visibility)없음) //외부클래스에서는 볼 수 없고 상속관계(package 달라도 OK)에서만 접근할 수 있도록 접근제어자 protected 사용 //protected는 같은 package에서는 보임 protected int customerID; protected String customerName; protected String customerGrade; int bonusPoint; double bonusRatio; /* public Customer() { customerGrade = "SILVER"; bonusRatio = 0.01; }*/ public Customer(int customerID, String customerName) { this.customerID = customerID; this.customerName = customerName; customerGrade = "SILVER"; bonusRatio = 0.01; System.out.println("Customer(int, String) 호출"); } public int calPrice(int price) { if (customerGrade == "SILVER") { bonusPoint += price * bonusRatio; } return price; } public String showCustomerInfo() { return customerName + "님의 등급 : " + customerGrade + ", 보너스 포인트 : " + bonusPoint; } public int getCustomerID() { return customerID; } public void setCustomerID(int customerID) { this.customerID = customerID; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getCustomerGrade() { return customerGrade; } public void setCustomerGrade(String customerGrade) { this.customerGrade = customerGrade; } }
package com.gof.behavior.templateMethod.internet2; public class StringDisplay extends AbstractDisplay { private String string ; private int width ; public StringDisplay(String string) { this.string = string; this.width = string.getBytes().length; // 생성자로 전달된 문자열의 바이트 길이를 할당 } @Override public void open() { printLine(); } @Override public void print() { System.out.println("|" + string + "|"); } @Override public void close() { printLine(); } // 클래스 안에서만 호출되는 메서드 private void printLine() { System.out.print("+"); for (int i = 0; i < width; i++) { System.out.print("-"); } System.out.println("+"); } }
// ------------------------------------------------------- // Activity.m // // Copyright (c) 2009 Jakub Suder <jakub.suder@gmail.com> // Licensed under MIT license // ------------------------------------------------------- #import "ApplicationDelegate.h" #import "ServerConnector.h" #import "Activity.h" #import "ActivityDateFormatter.h" #import "Project.h" #import "ActivityType.h" #import "User.h" #import "Utils.h" @implementation Activity @synthesize dateAsString; PSModelProperties(date, comments, project, user, activityType, minutes, locked); PSReleaseOnDealloc(date, comments, project, user, activityType, dateAsString); - (id) init { self = [super init]; if (self) { self.comments = @""; self.date = [NSDate date]; } return self; } - (NSString *) hourString { return PSFormat(@"%d:%02d", minutes / 60, minutes % 60); } - (void) setDate: (id) newDate { if ([newDate isKindOfClass: [NSString class]]) { [self setDateAsString: newDate]; } else { [self setDateAsDate: newDate]; } } - (void) setDateAsDate: (NSDate *) newDate { [date release]; date = [newDate copy]; [dateAsString release]; dateAsString = [[[ActivityDateFormatter sharedFormatter] formatDate: date withAliases: YES] retain]; } - (void) setDateAsString: (NSString *) dateString { self.date = [[ActivityDateFormatter sharedFormatter] parseDate: dateString]; } - (BOOL) isEqualToActivity: (Activity *) other { return other && other.minutes == self.minutes && other.project == self.project && [other.recordId isEqual: self.recordId] && [other.date isEqualToDate: self.date] && [other.comments isEqualToString: self.comments]; } - (NSString *) encodeToPostData { NSString *activityTypeField = self.activityType.isSubtype ? @"sub_activity_type_id" : @"main_activity_type_id"; NSString *activityTypeValue = self.activityType ? [self.activityType.recordId description] : @""; NSDictionary *fields = PSHash( @"date", [[ActivityDateFormatter sharedFormatter] formatDateForRequest: date], @"comments", [self.comments psStringWithPercentEscapesForFormValues], @"hours", [self hourString], @"project_id", self.project.recordId, activityTypeField, activityTypeValue ); return [NSString psStringWithFormEncodedFields: fields ofModelNamed: @"activity"]; } @end
import { z } from "zod"; // Creating an object schema export const RegisterFormSchema = z .object({ name: z.string().min(1, { message: "Name is required" }), age: z.coerce.number().min(1, { message: "Age is required" }), password: z .string() .min(6, { message: "Password min length of 6 characters" }) .max(12, { message: "Password max length of 12 characters" }), confirmPassword: z .string() .min(6, { message: "Confirm Password min length of 6 characters" }) .max(12, { message: "Confirm Password max length of 12 characters" }), email: z .string() .min(1, { message: "Email is required" }) .email("Invalid email address"), }) .required() .refine((data) => data.password === data.confirmPassword, { path: ["confirmPassword"], message: "Password don't match", }); export const LoginFormSchema = z.object({ email: z .string() .min(1, { message: "Email is required" }) .email("Invalid email adress"), password: z.string().min(6, { message: "Password is required" }), }); export const AddFoodFormSchema = z .object({ name: z.string().min(1, { message: "Food name is required" }), calories: z.coerce.number().min(1, { message: "Calories is required" }), carbohydrates: z.coerce .number() .min(1, { message: "Carbohydrates is required" }), fat: z.coerce.number().min(1, { message: "Fat is required" }), protein: z.coerce.number().min(1, { message: "Protein is required" }), fiber: z.coerce.number().min(1, { message: "Fiber is required" }), }) .required();
function [th,par,dth] = param2th_I2(par,s,n,ds,restrict); % converts parameters into th structures via system matrices. % same as param2syst_I2 but without D, Omega. % % SYNTAX: [th,par,dth] = param2th_I2(par,s,n,ds,restrict); % % INPUT: param ... dx1 parameter vector. % s ... integer; dimension of endogenous vars. % n ... integer; state dimension. % ds ... pair of integers; number of common trends: ds(1) I(2), % ds(2) additional I(1) trends. % restrict ... structure describing the restrictions. % % OUTPUT: th ... theta structure corresponding to state space system. % par ... remaining parameters for D. % dth ... if wanted in the output contains the derivative of % the system matrices with respect to the parameters. % Array: dth.A: array nxnxd of derivatives of A w.r.t. % the parameters. % % REMARK: uses the parameterization corr. to the param paper. % par ... [parc,park,parbullet,parD,parOmega]. % % AUTHOR: dbauer, 6.2.2020. if nargin<5 restrict = []; end if nargout>2 np =length(par); dA = zeros(n,n,np); dK = zeros(n,s,np); dC = zeros(s,n,np); end c = 2*ds(1)+ds(2); % --- find number of params in C1, C2, C3 --- % --- C1 --- nparc1 = s*ds(1)-ds(1)*(ds(1)+1)/2; parc1 = par(1:nparc1); par(1:nparc1)=[]; [C1,QL] = par2ortho_LR(parc1,s,ds(1)); if nargout>2 for j=1:length(parc1) dC(:,1:c,j) = dpar2ortho_LR(parc1,s,c,j); end end % --- C3: C3'C1 = 0, C3'C3 = I --- nparc3 = (s-ds(1))*ds(2)-ds(2)*(ds(2)+1)/2; parc3 = par(1:nparc3); par(1:nparc3)=[]; [C3h,QL2] = par2ortho_LR(parc3,s-ds(1),ds(2)); C3 = QL*[zeros(ds(1),ds(2));C3h]; % --- C2: C2'[C1,C3]=0 --- nparc2 = ds(1)*(s-sum(ds)); parc2 = par(1:nparc2); par(1:nparc2)=[]; Lambda= reshape(parc2,s-sum(ds),ds(1)); C2 = QL*[zeros(ds(1),ds(1));[QL2*[zeros(ds(2),ds(1));Lambda]]]; % --- count params --- cur =nparc1+nparc2+nparc3; % --- K1, K2, K3 --- npark1 = s*ds(1); park1 = par(1:npark1); par(1:npark1)=[]; npark2 = s*ds(1) - ds(1)*(ds(1)-1)/2; park2 = par(1:npark2); par(1:npark2)=[]; npark3 = s*ds(2) - ds(2)*(ds(2)-1)/2; park3 = par(1:npark3); par(1:npark3)=[]; K1 = reshape(park1,ds(1),s); K2 = K1*0; for j=1:ds(1) K2(j,j:end)=park2(1:(s-j+1)); park2(1:(s-j+1))=[]; end K3 = zeros(ds(2),s); for j=1:ds(2) K3(j,j:end)=park3(1:(s-j+1)); park3(1:(s-j+1))=[]; end Ku = [K1;K2;K3]; cur =npark1+npark2+npark3; % --- remaining parameters for stationary part --- parbull = par(1:(n-c)*s*2); if nargout>2 [Abull,Kbull,Cbull,dAKC]= param2mat_bull(parbull,s,n-c); else [Abull,Kbull,Cbull]= param2mat_bull(parbull,s,n-c); end par(1:(n-c)*s*2)=[]; % --- fill in the submatrices --- A = [eye(ds(1)),eye(ds(1)),zeros(ds(1),n-2*ds(1));zeros(ds(1)+ds(2),ds(1)),eye(ds(1)+ds(2)),zeros(ds(1)+ds(2),n-c);zeros(n-c,c),Abull]; K = [Ku;Kbull]; C = [C1,C2,C3,Cbull]; % --- fill into theta structure --- th = theta_urs(); th.which = 'SS'; th.A = A; th.K=K; th.C=C; th.ur = 'I(2)'; if nargout>2 % fill in for j=(cur+1):(np-length(par)) dA(:,:,j) = [zeros(c,n);zeros(n-c,c),squeeze(dAKC.A(:,:,j-cur))]; dC(:,:,j) = [zeros(s,c),squeeze(dAKC.C(:,:,j-cur))]; dK(:,:,j)= [zeros(c,s);squeeze(dAKC.K(:,:,j-cur))]; end % write into dth dth.A = dA; dth.K = dK; dth.C = dC; end
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ const sumNumbers = root => { let sum = 0; const dfs = (node, accumulator) => { if (node === null) { return; } accumulator = accumulator * 10 + node.val; if (!node.left && !node.right) { sum += parseInt(accumulator); } else { dfs(node.left, accumulator); dfs(node.right, accumulator); } }; dfs(root, 0); return sum; };
import type { V2_MetaFunction } from "@remix-run/cloudflare"; import { json } from "@remix-run/cloudflare"; import { Link, Outlet, useLoaderData } from "@remix-run/react"; import styles from "~/styles/_index.css"; import { getModules, getObjectLink } from "~/dataforged/dataforged"; import { marked } from "marked"; export const meta: V2_MetaFunction = () => { return [ { title: "Ironsworn:Starforged - Rules" }, { name: "description", content: "All rules form Ironsworn:Starforged by Shawn Tomkin", }, ]; }; export function links() { return [{ rel: "stylesheet", href: styles }]; } export function loader() { const modules = getModules(); return json({ modules }); } export default function Index() { const data = useLoaderData<typeof loader>(); return ( <div className="container"> <nav> <ul> {data.modules.map((module) => ( <li key={`nav-{module.$id}`}> <Link to={getObjectLink(module)}>{module.Name}</Link> </li> ))} </ul> </nav> <Outlet /> </div> ); }
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Product } from './schemas/product.schema'; import { Model } from 'mongoose'; import { ProductDto } from './dtos/product.dto'; import moment from 'moment'; @Injectable() export class ProductService { constructor( @InjectModel(Product.name) private productModel: Model<Product>, ) {} async deleteProduct(id: string): Promise<Product> { try { const deletedProduct = await this.productModel.findByIdAndDelete(id); if (!deletedProduct) { throw new HttpException( 'Erro ao deletar o produto', HttpStatus.INTERNAL_SERVER_ERROR, ); } return deletedProduct; } catch (error) { return error; } } async addNewProduct(product: ProductDto): Promise<any> { try { const newProduct = await this.productModel.create(product); if (!newProduct) throw new HttpException( 'Erro criando o produto', HttpStatus.INTERNAL_SERVER_ERROR, ); return newProduct; } catch (E) { return E; } } async homePageProducts(): Promise<any> { try { const findAllProducts = await this.productModel .find({}) .sort({ timestamp: -1 }); // -1 for descending order if (!findAllProducts || findAllProducts.length === 0) { throw new HttpException( 'Erro ao buscar os produtos', HttpStatus.I_AM_A_TEAPOT, ); } const productsArray: any = { categoryName: 'PRODUTOS', products: findAllProducts, }; return productsArray; } catch (error) { return error; } } async searchById(id: string): Promise<any> { try { const productModel = await this.productModel.findById(id).exec(); if (!productModel) { throw new HttpException( "Product wasn't found...", HttpStatus.NOT_FOUND, ); } return productModel; } catch (error) { return 'Error: ' + error; } } }
import os import csv from pathlib import Path from typing import List, Dict, Union import pkg_resources PHUM_TSV_PATH: str = pkg_resources.resource_filename('pykhmernlp', 'address/address_data/phum.tsv') KHUM_TSV_PATH: str = pkg_resources.resource_filename('pykhmernlp', 'address/address_data/khum.tsv') SROK_TSV_PATH: str = pkg_resources.resource_filename('pykhmernlp', 'address/address_data/srok.tsv') PROVINCE_PATH: str = pkg_resources.resource_filename('pykhmernlp', 'address/address_data/province.txt') def _load_tsv_data(tsv_path: str) -> Dict[str, List[str]]: data: Dict[str, List[str]] = {} with open(tsv_path, 'r', encoding='utf-8') as tsv_file: reader = csv.reader(tsv_file, delimiter='\t') next(reader) # Skip header for row in reader: file_base_name, line = row if file_base_name not in data: data[file_base_name] = [] data[file_base_name].append(line) return data PHUM_DATA: Dict[str, List[str]] = _load_tsv_data(PHUM_TSV_PATH) KHUM_DATA: Dict[str, List[str]] = _load_tsv_data(KHUM_TSV_PATH) SROK_DATA: Dict[str, List[str]] = _load_tsv_data(SROK_TSV_PATH) def _list_data(data: Dict[str, List[str]], province: str = 'all') -> List[str]: """ Helper function to list all data from a specified path and filter by province name. Args: data (dict): The data dictionary to list data from. province (str): The province name to filter by. If 'all', list all data. Returns: List[str]: A list of data. """ if province == 'all': result: List[str] = [] for lines in data.values(): result.extend(lines) return result else: if province in data: return data[province] else: raise ValueError(f"No data available for the province: {province}") def km_villages(province: str = 'all') -> List[str]: """ List all data from the phum data and filter by province name. Args: province (str): The province name to filter by. If 'all', list all data. Returns: List[str]: A list of villages. """ return _list_data(PHUM_DATA, province) def km_commune(province: str = 'all') -> List[str]: """ List all data from the khum data and filter by province name. Args: province (str): The province name to filter by. If 'all', list all data. Returns: List[str]: A list of communes. """ return _list_data(KHUM_DATA, province) def km_districts(province: str = 'all') -> List[str]: """ List all data from the srok data and filter by province name. Args: province (str): The province name to filter by. If 'all', list all data. Returns: List[str]: A list of districts. """ return _list_data(SROK_DATA, province) def km_provinces() -> List[str]: """ List all provinces from the province data. Returns: List[str]: A list of provinces. """ with open(PROVINCE_PATH, 'r', encoding='utf-8-sig') as file: provinces: List[str] = [line.strip() for line in file if line.strip()] return provinces
<!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"> <meta name="description" content="Award-Winning Web Designer and Developer Based in Montreal. I want to help you take the web content you dream about, and bring it to life!"> <meta name="keywords" content="award, winning, web, designer, developer, front end, portfolio, charlie, brecht, cphotography"> <title>Charlie's Portfolio</title> <link rel="shortcut icon" href="./img/favi2.ico" type="image/x-icon"> <link rel="icon" href="./img/favi2.ico" type="image/x-icon"> <!-- Bootstrap Core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <!-- Plugin CSS --> <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet"> <!-- Theme CSS --> <link href="css/creative.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body id="page-top"> <nav id="mainNav" class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i> </button> <a class="navbar-brand page-scroll" href="#page-top">Charlie's Portfolio</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <a class="page-scroll" href="#about">About</a> </li> <li> <a class="page-scroll" href="#services">Services</a> </li> <li> <a class="page-scroll" href="#portfolio">Portfolio</a> </li> <li> <a class="page-scroll" href="#contact">Contact</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <header> <div class="header-content"> <div class="header-content-inner"> <h1 id="homeHeading">Award-Winning Web Designer and Developer Based in Montreal</h1> <hr> <p>I want to help you take the web content you dream about, and bring it to life!</p> <a href="#about" class="btn btn-primary btn-xl page-scroll">Find Out More</a> </div> </div> </header> <section class="bg-primary" id="about"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <h2 class="section-heading">My Specialties</h2> <hr class="light"> <p class="text-faded">I am a passionate Web-Designer and Front-End Web Developer evolving between the fields of programming, typography, UX/UI Design and creative problem solving. I've always been motivated about learning new technologies and mastering new softwares.</p> <a href="#services" class="page-scroll btn btn-default btn-xl sr-button">Why Them?</a> </div> </div> </div> </section> <section id="services"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Why Choose Charlie?</h2> <hr class="primary"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-3 col-md-6 text-center"> <div class="service-box"> <i class="fa fa-4x fa-eye text-primary sr-icons"></i> <h3>Design Eye</h3> <p class="text-muted">I can't sleep at night if the pixels are out of place.</p> </div> </div> <div class="col-lg-3 col-md-6 text-center"> <div class="service-box"> <i class="fa fa-4x fa-rocket text-primary sr-icons"></i> <h3>Self-Motivated</h3> <p class="text-muted">I've worked my way up to managing my own business.</p> </div> </div> <div class="col-lg-3 col-md-6 text-center"> <div class="service-box"> <i class="fa fa-4x fa-users text-primary sr-icons"></i> <h3>Teamwork</h3> <p class="text-muted">Whether it's with 1 person or 200 people, I love collaborating.</p> </div> </div> <div class="col-lg-3 col-md-6 text-center"> <div class="service-box"> <i class="fa fa-4x fa-heart text-primary sr-icons"></i> <h3>Made with Love</h3> <p class="text-muted">Together we can make websites people love coming back to.</p> </div> </div> </div> </div> </section> <section class="no-padding" id="portfolio"> <div class="container-fluid"> <div class="row no-gutter popup-gallery"> <div class="col-lg-4 col-sm-6"> <a href="https://github.com/coco-moloko" target="_blank" class="portfolio-box"> <img src="img/portfolio/thumbnails/1-8.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-name"> Github </div> </div> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a href="https://www.behance.net/cocobrecht" target="_blank" class="portfolio-box"> <img src="img/portfolio/thumbnails/2-3.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-name"> Design </div> </div> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a href="https://www.instagram.com/cocobrechtphotography/" target="_blank" class="portfolio-box"> <img src="img/portfolio/thumbnails/3-2.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-name"> Photography </div> </div> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a href="www.linkedin.com/in/c-brecht" target="_blank" class="portfolio-box"> <img src="img/portfolio/thumbnails/4-2.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-name"> LinkedIn </div> </div> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a href="https://www.facebook.com/CocoBrechtMedia/" target="_blank" class="portfolio-box"> <img src="img/portfolio/thumbnails/5-2.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-name"> Social Media </div> </div> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a href="https://twitter.com/Coco__Moloko" target="_blank" class="portfolio-box"> <img src="img/portfolio/thumbnails/6-2.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-name"> Twitter </div> </div> </div> </a> </div> </div> </div> </section> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <h2 class="section-heading">Let's Get In Touch!</h2> <hr class="primary"> <p>Ready to start your next project with me? That's great! Send me an email and I'll get back to you as soon as possible!</p> </div> <div class="col-lg-12 text-center"> <i class="fa fa-envelope-o fa-3x sr-contact"></i> <p><a href="mailto:cocobrecht@gmail.com">cocobrecht@gmail.com</a></p> </div> </div> </div> </section> <!-- jQuery --> <script src="vendor/jquery/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="vendor/bootstrap/js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="vendor/scrollreveal/scrollreveal.min.js"></script> <script src="vendor/magnific-popup/jquery.magnific-popup.min.js"></script> <!-- Theme JavaScript --> <script src="js/creative.js"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-93706403-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
import pygame import numpy as np import itertools import sys import networkx as nx import collections from pygame import gfxdraw import random # Game constants BOARD_BROWN = (199, 105, 42) BOARD_WIDTH = 900 BOARD_BORDER = 75 STONE_RADIUS = 18 WHITE = (255, 255, 255) BLACK = (0, 0, 0) TURN_POS = (BOARD_BORDER, 20) SCORE_POS = (BOARD_BORDER, BOARD_WIDTH - BOARD_BORDER + 30) DOT_RADIUS = 4 def make_grid(size): """Return list of (start_point, end_point pairs) defining gridlines Args: size (int): size of grid Returns: Tuple[List[Tuple[float, float]]]: start and end points for gridlines """ start_points, end_points = [], [] # vertical start points (constant y) xs = np.linspace(BOARD_BORDER, BOARD_WIDTH - BOARD_BORDER, size) ys = np.full((size), BOARD_BORDER) start_points += list(zip(xs, ys)) # horizontal start points (constant x) xs = np.full((size), BOARD_BORDER) ys = np.linspace(BOARD_BORDER, BOARD_WIDTH - BOARD_BORDER, size) start_points += list(zip(xs, ys)) # vertical end points (constant y) xs = np.linspace(BOARD_BORDER, BOARD_WIDTH - BOARD_BORDER, size) ys = np.full((size), BOARD_WIDTH - BOARD_BORDER) end_points += list(zip(xs, ys)) # horizontal end points (constant x) xs = np.full((size), BOARD_WIDTH - BOARD_BORDER) ys = np.linspace(BOARD_BORDER, BOARD_WIDTH - BOARD_BORDER, size) end_points += list(zip(xs, ys)) return (start_points, end_points) def xy_to_colrow(x, y, size): """Convert x,y coordinates to column and row number Args: x (float): x position y (float): y position size (int): size of grid Returns: Tuple[int, int]: column and row numbers of intersection """ inc = (BOARD_WIDTH - 2 * BOARD_BORDER) / (size - 1) x_dist = x - BOARD_BORDER y_dist = y - BOARD_BORDER col = int(round(x_dist / inc)) row = int(round(y_dist / inc)) return col, row def colrow_to_xy(col, row, size): """Convert column and row numbers to x,y coordinates Args: col (int): column number (horizontal position) row (int): row number (vertical position) size (int): size of grid Returns: Tuple[float, float]: x,y coordinates of intersection """ inc = (BOARD_WIDTH - 2 * BOARD_BORDER) / (size - 1) x = int(BOARD_BORDER + col * inc) y = int(BOARD_BORDER + row * inc) return x, y def has_no_liberties(board, group): """Check if a stone group has any liberties on a given board. Args: board (object): game board (size * size matrix) group (List[Tuple[int, int]]): list of (col,row) pairs defining a stone group Returns: [boolean]: True if group has any liberties, False otherwise """ for x, y in group: if x > 0 and board[x - 1, y] == 0: return False if y > 0 and board[x, y - 1] == 0: return False if x < board.shape[0] - 1 and board[x + 1, y] == 0: return False if y < board.shape[0] - 1 and board[x, y + 1] == 0: return False return True def get_stone_groups(board, color): """Get stone groups of a given color on a given board Args: board (object): game board (size * size matrix) color (str): name of color to get groups for Returns: List[List[Tuple[int, int]]]: list of list of (col, row) pairs, each defining a group """ size = board.shape[0] color_code = 1 if color == "black" else 2 xs, ys = np.where(board == color_code) graph = nx.grid_graph(dim=[size, size]) stones = set(zip(xs, ys)) all_spaces = set(itertools.product(range(size), range(size))) stones_to_remove = all_spaces - stones graph.remove_nodes_from(stones_to_remove) return nx.connected_components(graph) def is_valid_move(col, row, board): """Check if placing a stone at (col, row) is valid on board Args: col (int): column number row (int): row number board (object): board grid (size * size matrix) Returns: boolean: True if move is valid, False otherewise """ # TODO: check for ko situation (infinite back and forth) if col < 0 or col >= board.shape[0]: return False if row < 0 or row >= board.shape[0]: return False return board[col, row] == 0 def handle_capture(board, color, prisoners): """Handle the capture of stones on the board. Args: board (np.array): The game board. color (str): The color of the stones to check for capture. prisoners (dict): The prisoners dictionary to update captures. Returns: bool: True if a capture occurred, False otherwise. """ capture_happened = False for group in list(get_stone_groups(board, color)): if has_no_liberties(board, group): capture_happened = True for i, j in group: board[i, j] = 0 # Remove the captured stones from the board prisoners[color] += len(group) # Update the prisoners count return capture_happened def handle_invalid_placement(board, col, row, color): """Handle the invalid placement of a stone on the board. Args: board (np.array): The game board. col (int): Column number where the stone is placed. row (int): Row number where the stone is placed. color (str): The color of the stone placed. Returns: bool: True if the placement is invalid and the stone was removed, False otherwise. """ for group in get_stone_groups(board, color): if (col, row) in group: break if has_no_liberties(board, group): board[col, row] = 0 # Remove the invalid stone return True # Invalid placement, stone removed def simulate_move(self, col, row, self_color, other_color, prisoners): legal_move = False simulated_board = np.copy(self.board) # Update board array with the current player's color simulated_board[col, row] = 1 if self_color=="black" else 2 # Simulate capture capture_happened = handle_capture(simulated_board, other_color, prisoners) if not capture_happened: legal_move = handle_invalid_placement(simulated_board, col, row, self_color) #compare the simulated board to the previous board if self.prev_board is not None and np.array_equal(simulated_board, self.prev_board): legal_move = True return simulated_board, legal_move def count_territory(board, prisoners): # Initialize scores for black and white black_score = 0 white_score = 6.5 # Komi black_score -= prisoners['black'] white_score -= prisoners['white'] # Return the scores return black_score, white_score class Game: def __init__(self, size): self.board = np.zeros((size, size)) self.size = size self.black_turn = True self.prisoners = collections.defaultdict(int) self.start_points, self.end_points = make_grid(self.size) self.running = True self.pass_counter = 0 # initialize the pass counter self.prev_board = None # Initialize prev_board self.undo_count = 0 # Initialize undo_count def init_pygame(self): pygame.init() screen = pygame.display.set_mode((BOARD_WIDTH, BOARD_WIDTH)) self.screen = screen self.ZOINK = pygame.mixer.Sound("wav/zoink.wav") self.CLICK = pygame.mixer.Sound("wav/click.wav") self.font = pygame.font.SysFont("arial", 30) def clear_screen(self): # fill board and add gridlines self.screen.fill(BOARD_BROWN) for start_point, end_point in zip(self.start_points, self.end_points): pygame.draw.line(self.screen, BLACK, start_point, end_point) # add guide dots guide_dots = [3, self.size // 2, self.size - 4] for col, row in itertools.product(guide_dots, guide_dots): x, y = colrow_to_xy(col, row, self.size) gfxdraw.aacircle(self.screen, x, y, DOT_RADIUS, BLACK) gfxdraw.filled_circle(self.screen, x, y, DOT_RADIUS, BLACK) pygame.display.flip() def pass_move(self): self.black_turn = not self.black_turn self.draw() self.pass_counter += 1 # Increment the pass counter on each pass # Check if there have been two consecutive passes if self.pass_counter >= 2: self.end_game() # Handle the end of the game def handle_click(self): # Get board position from mouse click x, y = pygame.mouse.get_pos() col, row = xy_to_colrow(x, y, self.size) if not is_valid_move(col, row, self.board): self.ZOINK.play() # Play sound if move is not valid return # Determine the colors for the current and opponent player self_color = "black" if self.black_turn else "white" other_color = "white" if self.black_turn else "black" simulated_board, legal_move = simulate_move(self, col, row, self_color, other_color, self.prisoners) if legal_move: self.ZOINK.play() # Play sound if move is not valid return self.CLICK.play() # Play sound for valid placement self.prev_board = np.copy(self.board) # Make a deep copy of the board self.board = simulated_board self.black_turn = not self.black_turn self.pass_counter = 0 # Reset the pass counter whenever a move is made self.undo_count = 0 # Reset undo_count after a new move is made self.draw() # Redraw the board with the new stone def ai_make_move(self): valid_move_found = False while not valid_move_found: # Generate a random move col = random.randint(0, self.size - 1) row = random.randint(0, self.size - 1) # Check if the move is valid if is_valid_move(col, row, self.board): valid_move_found = True # Determine the colors for the current and opponent player self_color = "black" if self.black_turn else "white" other_color = "white" if self.black_turn else "black" # Simulate and apply the move simulated_board, legal_move = simulate_move(self, col, row, self_color, other_color, self.prisoners) if not legal_move: self.prev_board = np.copy(self.board) # Make a deep copy of the board self.board = simulated_board self.black_turn = not self.black_turn self.pass_counter = 0 # Reset the pass counter whenever a move is made self.undo_count = 0 # Reset undo_count after a new move is made self.draw() # Redraw the board with the new stone else: valid_move_found = False # The randomly chosen move was invalid, try again def draw(self): # draw stones - filled circle and antialiased ring self.clear_screen() for col, row in zip(*np.where(self.board == 1)): x, y = colrow_to_xy(col, row, self.size) gfxdraw.aacircle(self.screen, x, y, STONE_RADIUS, BLACK) gfxdraw.filled_circle(self.screen, x, y, STONE_RADIUS, BLACK) for col, row in zip(*np.where(self.board == 2)): x, y = colrow_to_xy(col, row, self.size) gfxdraw.aacircle(self.screen, x, y, STONE_RADIUS, WHITE) gfxdraw.filled_circle(self.screen, x, y, STONE_RADIUS, WHITE) # text for score and turn info score_msg = ( f"Black's Prisoners: {self.prisoners['black']}" + f" White's Prisoners: {self.prisoners['white']}" ) txt = self.font.render(score_msg, True, BLACK) self.screen.blit(txt, SCORE_POS) turn_msg = ( f"{'Black' if self.black_turn else 'White'} to move. " + "Click to place stone, press P to pass, U to undo." ) txt = self.font.render(turn_msg, True, BLACK) self.screen.blit(txt, TURN_POS) pygame.display.flip() def update(self): events = pygame.event.get() for event in events: if event.type == pygame.MOUSEBUTTONUP: self.handle_click() elif event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYUP: if event.key == pygame.K_p: self.pass_move() elif event.key == pygame.K_u: if self.prev_board is not None and self.undo_count==0: self.board=self.prev_board self.black_turn = not self.black_turn self.draw() # Redraw the board with the undone state self.undo_count +=1 else: self.ZOINK.play() # Play sound if move is not valid return elif event.key == pygame.K_i: self.ai_make_move() def end_game(self): # Display the final score or a game over message black_score, white_score = count_territory(self.board, self.prisoners) print(f"Game over. Final score - Black: {black_score}, White: {white_score}") #print("Game over. Final score - Black's Prisoners: {}, White's Prisoners: {}".format(self.prisoners['black'], self.prisoners['white'])) self.running = False if __name__ == "__main__": g = Game(size=19) g.init_pygame() g.clear_screen() g.draw() while g.running: # Check if the game is still running g.update() pygame.time.wait(100) pygame.quit() # Ensure pygame quits after the loop exits
import React, { useState } from 'react'; import { View, Text, Pressable } from 'react-native'; import Voice from 'react-native-voice'; const App = () => { const [result, setResult] = useState(''); const [error, setError] = useState(''); const [isRecording, setRecording] = useState(false); const [timeoutId, setTimeoutId] = useState<number | null>(null); Voice.onSpeechStart = () => { setRecording(true); if (timeoutId) clearTimeout(timeoutId); }; Voice.onSpeechEnd = () => { setRecording(false); setTimeoutId(setTimeout(stopRecording, 1000)); }; Voice.onSpeechError = (err: any) => setError(err?.error); Voice.onSpeechResults = (res: any) => setResult(res?.value?.[0]); Voice.onSpeechPartialResults = (res: any) => { const partialResult = res?.value?.[0]; if (partialResult && !timeoutId) { setTimeoutId(setTimeout(stopRecording, 1000)); } }; const startRecording = async () => { try { await Voice.start('en-US'); } catch (err: any) { setError(err); } }; const stopRecording = async () => { try { await Voice.stop(); setTimeoutId(null); } catch (err: any) { setError(err); } }; return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', }} > <Text>{result}</Text> <Text>{error}</Text> <Pressable onPress={isRecording ? stopRecording : startRecording}> <Text style={{ color: 'red' }}> {isRecording ? 'STOP' : 'START'} </Text> </Pressable> </View> ); }; export default App;
import { Box, Flex, Heading, Link, ListItem, SimpleGrid, Text, UnorderedList, } from "@chakra-ui/react"; import React from "react"; import styles from "./Style/Footer.module.css"; import { FaFacebookF, FaLinkedinIn, FaTwitter } from "react-icons/fa"; const Footer = () => { const year = new Date().getFullYear(); return ( <> <SimpleGrid columns={[1, 2, 3, 4, 6]} textAlign={["center", "center", "left"]} spacing="40px" className={styles.grid_container} > <Box className={styles.common_container}> <Heading as="h2" size="md" color={"gray.600"}> Product </Heading> <UnorderedList> <Link href="/time-tracking/" style={{ textDecoration: "none" }}> <ListItem>Features</ListItem> </Link> <Link href="/integrations/" style={{ textDecoration: "none" }}> <ListItem>Integrations</ListItem> </Link> <Link href="/applications/" style={{ textDecoration: "none" }}> <ListItem>Applications</ListItem> </Link> <Link href="/product-updates/" style={{ textDecoration: "none" }}> <ListItem>Products Updates</ListItem> </Link> <Link href="/customer-stories/" style={{ textDecoration: "none" }}> <ListItem>Customer Stories</ListItem> </Link> <Link href="/self-hosting/" style={{ textDecoration: "none" }}> <ListItem>Self-Hosting</ListItem> </Link> </UnorderedList> </Box> <Box className={styles.common_container}> <Heading as="h2" size="md" color={"gray.600"}> Support </Heading> <UnorderedList> <Link href="/support/" style={{ textDecoration: "none" }}> <ListItem>Support</ListItem> </Link> <Link href="/knowledge-base/" style={{ textDecoration: "none" }}> <ListItem>Knowledge base</ListItem> </Link> <Link href="/developer-api/" style={{ textDecoration: "none" }}> <ListItem>Developers API</ListItem> </Link> <Link href="/server-status/" style={{ textDecoration: "none" }}> <ListItem>Server Status</ListItem> </Link> </UnorderedList> </Box> <Box className={styles.common_container}> <Heading as="h2" size="md" color={"gray.600"}> Integrations </Heading> <UnorderedList> <Link href="/integrations/trello-time-tracking/" style={{ textDecoration: "none" }} > <ListItem>Trello</ListItem> </Link> <Link href="/integrations/monday-com-time-tracking/" style={{ textDecoration: "none" }} > <ListItem>Monday.com</ListItem> </Link> <Link href="/integrations/google-calender-time-tracking/" style={{ textDecoration: "none" }} > <ListItem>Google Calender</ListItem> </Link> <Link href="/integrations/asana-time-tracking/" style={{ textDecoration: "none" }} > <ListItem>Asana</ListItem> </Link> <Link href="/integrations/jira-time-tracking/" style={{ textDecoration: "none" }} > <ListItem>Jira</ListItem> </Link> <Link href="/integrations/all-integrations-time-tracking/" style={{ textDecoration: "none" }} > <ListItem>All integrations</ListItem> </Link> </UnorderedList> </Box> <Box className={styles.common_container}> <Heading as="h2" size="md" color={"gray.600"}> Resources </Heading> <UnorderedList> <Link href="/contact/" style={{ textDecoration: "none" }}> <ListItem>Contact</ListItem> </Link> <Link href="/heyspace/" style={{ textDecoration: "none" }}> <ListItem>HeySpace</ListItem> </Link> <Link href="/about/" style={{ textDecoration: "none" }}> <ListItem>About us</ListItem> </Link> <Link href="/press/" style={{ textDecoration: "none" }}> <ListItem>Press</ListItem> </Link> <Link href="/partner/" style={{ textDecoration: "none" }}> <ListItem>Become a Partner</ListItem> </Link> </UnorderedList> </Box> <Box className={styles.common_container}> <Heading as="h2" size="md" color={"gray.600"}> Calculators </Heading> <UnorderedList> <Link href="/resources/pmc/profit-margin-calculator/" style={{ textDecoration: "none" }} > <ListItem>Pofit margin Calculator</ListItem> </Link> <Link href="/resources/pmc/online-timer/" style={{ textDecoration: "none" }} > <ListItem>Online Timer</ListItem> </Link> <Link href="/resources/pmc/overtime-calculator/" style={{ textDecoration: "none" }} > <ListItem>Overtime Calculator</ListItem> </Link> <Link href="/resources/pmc/roi-calculator/" style={{ textDecoration: "none" }} > <ListItem>ROI Calculator</ListItem> </Link> <Link href="/resources/pmc/time-card-calculator/" style={{ textDecoration: "none" }} > <ListItem>Time Card Calculator</ListItem> </Link> </UnorderedList> </Box> <Box className={styles.common_container}> <Heading as="h2" size="md" color={"gray.600"}> Legal </Heading> <UnorderedList> <Link href="/terms-conditions/" style={{ textDecoration: "none" }}> <ListItem>Terms</ListItem> </Link> <Link href="/privacy/" style={{ textDecoration: "none" }}> <ListItem>Privacy</ListItem> </Link> <Link href="/security/" style={{ textDecoration: "none" }}> <ListItem>Security</ListItem> </Link> </UnorderedList> </Box> </SimpleGrid> <Box className={styles.contact_div}> <Flex w={["25%","20%","10%"]} justifyContent={"space-between"} margin="30px auto"> <Link href="https://www.facebook.com/timecamp/" isExternal> <FaFacebookF /> </Link> <Link href="https://www.linkedin.com/company/timecamp/" isExternal> <FaLinkedinIn /> </Link> <Link href="https://twitter.com/timecamp/" isExternal> <FaTwitter /> </Link> </Flex> <Text color={'gray.400'} fontSize="12px">Copyright &#169; {year} TimeCamp. Inc.</Text> <Text color={'gray.400'} fontSize="11px">We use cookies. Click here to learn more</Text> </Box> </> ); }; export default Footer;
// Copyright (c) Dennis Shevtsov. All rights reserved. // Licensed under the MIT License. // See LICENSE in the project root for license information. using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; namespace SurveyApp.SurveyTemplate.Data; public sealed class SurveyTemplateRepository : ISurveyTemplateRepository { private readonly DbContext _dbContext; public SurveyTemplateRepository(DbContext dbContext) { _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); } public Task<SurveyTemplateEntity?> GetSurveyTemplateAsync(Guid surveyTemplateId, CancellationToken cancellationToken) => _dbContext.Set<SurveyTemplateEntity>() .AsNoTracking() .Where(entity => entity.SurveyTemplateId == surveyTemplateId) .FirstOrDefaultAsync(cancellationToken); public async Task<SurveyTemplateEntity> AddSurveyTemplateAsync(SurveyTemplateEntity surveyTemplateEntity, CancellationToken cancellationToken) { EntityEntry<SurveyTemplateEntity> surveyTemplateEntityEntry = _dbContext.Entry(surveyTemplateEntity); surveyTemplateEntityEntry.State = EntityState.Added; await _dbContext.SaveChangesAsync(cancellationToken); surveyTemplateEntityEntry.State = EntityState.Detached; return surveyTemplateEntity; } public async Task UpdateSurveyTemplateAsync(SurveyTemplateEntity surveyTemplateEntity, CancellationToken cancellationToken) { EntityEntry<SurveyTemplateEntity> surveyTemplateEntityEntry = _dbContext.Entry(surveyTemplateEntity); surveyTemplateEntityEntry.State = EntityState.Modified; await _dbContext.SaveChangesAsync(cancellationToken); surveyTemplateEntityEntry.State = EntityState.Detached; } public async Task DeleteSurveyTemplateAsync(Guid surveyTemplateId, CancellationToken cancellationToken) { await _dbContext.Set<SurveyTemplateEntity>() .Where(entity => entity.SurveyTemplateId == surveyTemplateId) .ExecuteDeleteAsync(cancellationToken); } }
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router, ActivatedRoute } from '@angular/router'; import { LoadingController } from '@ionic/angular'; import { ActionSheetController, NavController } from '@ionic/angular'; import { ToastService } from 'src/app/services/toast/toast.service'; import { CustomerService } from 'src/app/services/customer/customerservice'; @Component({ selector: 'app-edit', templateUrl: './edit.page.html', styleUrls: ['./edit.page.scss'], }) export class EditPage implements OnInit { customer: any; imgProfile: any; edit_profile_form: FormGroup; submit_attempt: boolean = false; constructor( private route: Router, private activeRoute: ActivatedRoute, private formBuilder: FormBuilder, private toastService: ToastService, private navController: NavController, private actionSheetController: ActionSheetController, private customerService: CustomerService, private loadingController: LoadingController, ) { } ngOnInit() { this.getCustomer(); // Setup form this.edit_profile_form = this.formBuilder.group({ first_name: ['', Validators.required], last_name: ['', Validators.required], email: ['', { disabled: true }], phone: ['', [Validators.required, Validators.pattern('^[0-9]+$'), Validators.minLength(10), Validators.maxLength(10)]], }); // // DEBUG: Prefill inputs // this.edit_profile_form.get('full_name').setValue('ชัยยันต์ แจ้งกระจ่าง'); // this.edit_profile_form.get('full_name').setValue('ชัยยันต์ แจ้งกระจ่าง'); // this.edit_profile_form.get('email').setValue('chaiyun@hotmail.com'); // this.edit_profile_form.get('tel_phone').setValue('061 235 4665'); } // Update profile picture async updateProfilePicture() { const actionSheet = await this.actionSheetController.create({ header: 'Choose existing picture or take new', cssClass: 'custom-action-sheet', buttons: [ { text: 'Choose from gallery', icon: 'images', handler: () => { // Put in logic ... } }, { text: 'Take picture', icon: 'camera', handler: () => { // Put in logic ... } }, { text: 'Cancel', icon: 'close', role: 'cancel' }] }); await actionSheet.present(); } async getCustomer() { this.customer = JSON.parse(await this.customerService.getCustomer()); this.imgProfile = this.customer.avatar_url; this.edit_profile_form.get('first_name').setValue(this.customer.first_name); this.edit_profile_form.get('last_name').setValue(this.customer.last_name); this.edit_profile_form.get('email').setValue(this.customer.email); this.edit_profile_form.get('phone').setValue(this.customer.billing.phone); } // Submit form async submit() { // Proceed with loading overlay const loading = await this.loadingController.create({ cssClass: 'default-loading', message: 'Recording....', spinner: 'crescent' }); await loading.present(); this.submit_attempt = true; // If form valid if (this.edit_profile_form.valid) { const profileData = { first_name: this.edit_profile_form.value.first_name, last_name: this.edit_profile_form.value.last_name, email: this.edit_profile_form.value.email, billing: { first_name: this.customer.billing.first_name, last_name: this.customer.billing.last_name, company: this.customer.billing.company, address_1: this.customer.billing.address_1, address_2: this.customer.billing.address_2, city: this.customer.billing.city, postcode: this.customer.billing.postcode, country: this.customer.billing.country, state: this.customer.billing.state, email: this.edit_profile_form.value.email, phone: this.edit_profile_form.value.phone, }, } // Save form ... await this.customerService.updateProfile(this.customer.id, profileData).then(data => { loading.dismiss(); // Display success message and go back this.toastService.presentToast('Success', 'Profile saved', 'middle', 'success', 2000); // this.navController.back(); this.route.navigate(['/settings/profile']); }).catch(e => { console.log(e) }); } else { // Display error message this.toastService.presentToast('Error', 'Please fill in all required fields', 'top', 'danger', 2000); } } }
import { Routes, RouterModule } from '@angular/router'; import { NgModule } from '@angular/core'; import { ListaComponent } from './pages/lista/lista.component'; import { AgregarComponent } from './pages/agregar/agregar.component'; import { BuscarComponent } from './pages/buscar/buscar.component'; import { HeroeComponent } from './pages/heroe/heroe.component'; import { HomeComponent } from './pages/home/home.component'; const routes: Routes = [ { path: '', component: HomeComponent, children: [ { path: 'lista', component: ListaComponent, }, { path: 'agregar', component: AgregarComponent, }, { path: 'editar/:id', component: AgregarComponent, }, { path: 'buscar', component: BuscarComponent, }, { path: ':id', component: HeroeComponent, }, { path: '**', redirectTo: 'lista', }, ], }, ]; @NgModule({ declarations: [], imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class HeroesRoutingModule {}
import Redis from "ioredis"; class RedisClient { constructor() { this.redisConfig = { port: process.env.REDIS_PORT, host: process.env.REDIS_HOST, username: process.env.REDIS_USERNAME, password: process.env.REDIS_PASSWORD, }; } async getGameWithLock(gameId, sessionId) { while (true) { try { const game = await this.getGame(gameId); if (!game.lock) { console.log(`Locking game ${gameId} for session: ${sessionId}`); await this.updateGame(gameId, { ...game, lock: sessionId }); game.lock = sessionId; return game; // Lock acquired successfully } else if (game.lock === sessionId) { console.log(`Game already locked by this session: {sessionId}`); return game; // Already locked by this session } } catch (error) { // Handle errors appropriately } console.log( `Session ${sessionId} waiting for lock ${game.lock} to release` ); await new Promise((r) => setTimeout(r, 1000)); // Retry with delay } } async getGame(gameId) { let game = {}; const redisClient = new Redis(this.redisConfig); try { const gameData = await redisClient.get(gameId); game = JSON.parse(gameData); } catch (error) { console.error(error); throw new Error("Failed to fetch game data"); } finally { await redisClient.quit(); } return game; } async updateGame(gameId, game) { const redisClient = new Redis(this.redisConfig); console.log(`Releasing lock ${game.lock} and updating game ${gameId}`); try { game.lock = null; const gameString = JSON.stringify(game); await redisClient.set(gameId, gameString); } catch (error) { console.error(error); throw new Error("Failed to update game data"); } finally { await redisClient.quit(); } return game; } async getGameSessionWithLock(gameId, sessionId) { let game = await this.getGameWithLock(gameId, sessionId); const session = game.players.find( (player) => player.playerId === sessionId ); return session; } async updateGameSession(gameId, sessionId, updatedSession) { let game = await this.getGameWithLock(gameId, sessionId); // replace session with the updated session game.players = game.players.map((player) => { if (player.playerId === sessionId) { player = updatedSession; } return player; }); await this.updateGame(gameId, game); return updatedSession; } } export default RedisClient;
package seleniumsessions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class SelectDropDownWithOptionsMethod { static WebDriver driver; public static void main(String[] args) { driver = new ChromeDriver(); driver.get("https://www.orangehrm.com/orangehrm-30-day-trial/"); By country = By.id("Form_getForm_Country"); System.out.println(getDropDownOptionsCount(country)); if(getDropDownTextList(country).contains("India")) { System.out.println("PASS"); } List<String> expectedCountryList = Arrays.asList("India", "Andorra", "Angola"); if(getDropDownTextList(country).containsAll(expectedCountryList)) { System.out.println(expectedCountryList+ "are avaialble"); } // Select select = new Select(driver.findElement(country)); // // List<WebElement> listOfCountries = select.getOptions(); // // System.out.println(listOfCountries.size()); // // for (WebElement e : listOfCountries) { // String text = e.getText(); // if (text.equals("India")) { // e.click(); // break; // } // } } public static WebElement getElement(By locator) { return driver.findElement(locator); } public static int getDropDownOptionsCount(By locator) { Select select = new Select(getElement(locator)); return select.getOptions().size(); } public static List<String> getDropDownTextList(By locator) { Select select = new Select(getElement(locator)); List<WebElement> optionsList = select.getOptions(); List<String> optionsTextList = new ArrayList<String>(); for(WebElement e: optionsList) { String text = e.getText(); optionsTextList.add(text); } return optionsTextList; } }
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import RefreshTokenSerializer class LoginView(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(): email = serializer.validated_data["email"] password = serializer.validated_data["password"] result = supabase.auth.sign_in_with_password(email=email, password=password) if "user" in result: request.session["jwt"] = result[ "access_token" ] # Storing JWT in session return Response( {"message": "Logged in successfully"}, status=status.HTTP_200_OK ) else: return Response( {"error": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED, ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class RefreshTokenView(APIView): def post(self, request): serializer = RefreshTokenSerializer(data=request.data) if serializer.is_valid(): refresh_token = serializer.validated_data["refresh_token"] result = supabase.auth.refresh_session(refresh_token=refresh_token) request.session["jwt"] = result["access_token"] # Update the JWT in session return Response( {"message": "Token refreshed successfully"}, status=status.HTTP_200_OK ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class LogoutView(APIView): def post(self, request): jwt = request.session.pop("jwt", None) if jwt: supabase.auth.sign_out(jwt=jwt) # Server-side JWT management if necessary return Response( {"message": "Logged out successfully"}, status=status.HTTP_200_OK ) return Response( {"error": "User not logged in"}, status=status.HTTP_401_UNAUTHORIZED )
<?php namespace Ampc\Asaas\Entity; /** * Standard page AbstractEntity Entity for Assas * * @version 1.0 * @package API * @author Antonio M P Castro * @copyright Copyright (c) 2023 * @license - */ abstract class AbstractEntity{ /** * Constructor * * @param \stdClass|array|null $parameters (optional) Entity parameters */ public function __construct($parameters = null) { if(!$parameters) { return; } if($parameters instanceof \stdClass) { $parameters = get_object_vars($parameters); } $this->build($parameters); } /** * Fill entity with parameters data * * @param array $parameters Entity parameters */ public function build(array $parameters) { foreach($parameters as $property => $value) { if(property_exists($this, $property)) { $this->$property = $value; // Apply mutator $mutator = 'set' . ucfirst(static::convertToCamelCase($property)); if(method_exists($this, $mutator)) { call_user_func_array(array($this, $mutator), [$value]); } } } } /** * Convert date string do DateTime Object * * @param string|null $date DateTime string * @return \DateTime|null */ protected static function convertDateTime($date) { if(!$date) { return; } $date = \DateTime::createFromFormat('d/m/Y', $date); if(!$date) { return; } return $date; } /** * Convert to CamelCase * * @param string $str Snake case string * @return string Camel case string */ protected static function convertToCamelCase($str) { $callback = function($match) { return strtoupper($match[2]); }; return lcfirst(preg_replace_callback('/(^|_)([a-z])/', $callback, $str)); } }
1. **Node.js Core Principles:** - Explain the event loop in Node.js and how it facilitates non-blocking I/O. How does it contribute to the scalability of Node.js applications? 2. **Express.js Internals:** - Describe the middleware concept in Express.js. How does middleware execution flow work, and how can you implement custom middleware to modify request and response objects? 3. **Database Design and Optimization:** - Compare and contrast the indexing strategies for SQL and NoSQL databases. In what scenarios would you choose one type of database over the other, considering indexing and optimization? 4. **RESTful API Design:** - Discuss the differences between PUT and PATCH HTTP methods in the context of RESTful APIs. Provide examples of when to use each and the potential implications on data integrity. 5. **Authentication and Authorization:** - Explain the differences between OAuth 2.0 and OpenID Connect. How can these standards be used together to provide both authentication and authorization in a Node.js application? 6. **Debugging in Node.js:** - Describe the use of the Node.js built-in debugger. How would you set breakpoints, inspect variables, and step through code to troubleshoot a complex issue in a production Node.js application? 7. **Advanced Node.js Concepts:** - Discuss the concept of streams in Node.js. Provide a practical example of how streams can be used to optimize the processing of large datasets in a web application. 8. **Express.js Routing and Controllers:** - Explain the differences between using traditional routing and using controllers in an Express.js application. When would you choose one approach over the other, and what are the potential benefits? 9. **Database Transactions:** - Describe the importance of transactions in database operations. How would you implement and manage transactions in a Node.js application, considering both SQL and NoSQL databases? 10. **Performance Optimization:** - Discuss strategies for optimizing the performance of a Node.js application, considering factors such as code execution, network latency, and database queries. Provide specific examples of tools and techniques you might use in a real-world scenario. Certainly! Here are the answers to the questions: 1. **Node.js Core Principles:** - Answer: The event loop in Node.js is a mechanism that allows asynchronous, non-blocking I/O operations. It enables Node.js to handle many connections concurrently. The event loop continuously checks the message queue and executes callback functions when an event occurs, making Node.js highly scalable. 2. **Express.js Internals:** - Answer: Middleware in Express.js are functions that have access to the request, response, and the next middleware function. They can modify the request and response objects and terminate the request-response cycle. Custom middleware is implemented using `app.use()` or `router.use()` functions. Execution flows sequentially through middleware, and `next()` is used to pass control to the next middleware. 3. **Database Design and Optimization:** - Answer: Indexing in SQL and NoSQL databases improves query performance. SQL databases use B-tree indexes, while NoSQL databases may use various index types, such as compound or geospatial indexes. The choice between SQL and NoSQL depends on factors like data structure, scalability, and the nature of the application. 4. **RESTful API Design:** - Answer: PUT is used to update or create a resource if it doesn't exist, while PATCH is used to partially update a resource. PUT typically sends the entire updated resource, while PATCH sends only the changes. Choosing between them depends on the client's ability to send the full or partial resource. 5. **Authentication and Authorization:** - Answer: OAuth 2.0 is an authorization framework, while OpenID Connect is an authentication layer on top of OAuth 2.0. OAuth 2.0 is used to grant third-party applications limited access, and OpenID Connect adds an identity layer, allowing the third party to verify the identity of the end user. 6. **Debugging in Node.js:** - Answer: The Node.js built-in debugger can be activated using the `--inspect` flag. Breakpoints can be set using `debugger` statements or the `debugger` command in the console. Use the `repl` command to inspect variables interactively and `c` to continue execution. 7. **Advanced Node.js Concepts:** - Answer: Streams in Node.js allow reading or writing data piece by piece, reducing memory usage. Examples include reading a large file or handling HTTP requests. They are implemented using the `stream` module, and key events are 'data', 'end', and 'error'. 8. **Express.js Routing and Controllers:** - Answer: Traditional routing involves defining routes with handlers directly, while controllers separate route handling logic into modular components. Controllers are useful for organizing and testing code. The choice depends on the project structure and complexity. 9. **Database Transactions:** - Answer: Transactions ensure the atomicity, consistency, isolation, and durability (ACID properties) of database operations. In Node.js, transactions can be managed using the `beginTransaction`, `commit`, and `rollback` methods in SQL databases, while NoSQL databases may have their own transaction mechanisms. 10. **Performance Optimization:** - Answer: Performance optimization involves various strategies, such as code optimization, caching, load balancing, and database indexing. Tools like profiling with Node.js built-in `--inspect` and third-party tools like New Relic can help identify bottlenecks. Techniques include asynchronous programming, using a reverse proxy, and optimizing database queries. Certainly! Here are some practical questions on Node.js along with their answers: 1. **Error Handling in Asynchronous Operations:** - Question: How do you handle errors in Node.js asynchronous operations, especially those involving Promises? - Answer: In asynchronous operations, you can use `.catch()` with Promises or `try-catch` blocks with async/await. For example: ```javascript someAsyncFunction() .then((result) => console.log(result)) .catch((error) => console.error(error)); ``` 2. **Middleware in Express.js:** - Question: Explain the purpose of middleware in an Express.js application and provide an example of using middleware for logging. - Answer: Middleware in Express.js functions between the request and the final route. Example: ```javascript const loggerMiddleware = (req, res, next) => { console.log(`[${new Date()}] ${req.method} ${req.url}`); next(); }; app.use(loggerMiddleware); ``` 3. **File System Operations:** - Question: Write Node.js code to asynchronously read a file and log its content. How would you handle errors during the file read operation? - Answer: ```javascript const fs = require("fs"); fs.readFile("example.txt", "utf8", (err, data) => { if (err) { console.error(err); return; } console.log(data); }); ``` 4. **Working with NPM Packages:** - Question: How do you install and manage third-party packages using NPM in a Node.js project? - Answer: To install a package, use the command `npm install package-name`. To manage dependencies, update the `package.json` file and use commands like `npm install` or `npm update`. 5. **Asynchronous Control Flow:** - Question: Compare callbacks, Promises, and async/await for handling asynchronous operations in Node.js. Provide an example of each. - Answer: Example using callbacks: ```javascript fs.readFile("file.txt", "utf8", (err, data) => { if (err) throw err; console.log(data); }); ``` Example using Promises and async/await: ```javascript const readFileAsync = util.promisify(fs.readFile); readFileAsync("file.txt", "utf8") .then((data) => console.log(data)) .catch((err) => console.error(err)); // or using async/await try { const data = await readFileAsync("file.txt", "utf8"); console.log(data); } catch (err) { console.error(err); } ``` 6. **Event Emitters in Node.js:** - Question: Explain the concept of event emitters in Node.js and provide a code example demonstrating their use. - Answer: Node.js uses the EventEmitter class to handle events. Example: ```javascript const EventEmitter = require("events"); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on("event", () => { console.log("Event occurred!"); }); myEmitter.emit("event"); ``` 7. **Connecting to a Database:** - Question: Write a Node.js code snippet to connect to a MongoDB database using Mongoose, including error handling and a simple query. - Answer: ```javascript const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true, }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'Connection error:')); db.once('open', () => { console.log('Connected to the database'); // Perform a simple query const result = await SomeModel.find(); console.log(result); }); ``` 8. **RESTful API Development:** - Question: Design a simple RESTful API for a blog application, defining routes for CRUD operations on blog posts. - Answer: Example routes for a Blog API: - `GET /posts` (Get all posts) - `GET /posts/:id` (Get a specific post) - `POST /posts` (Create a new post) - `PUT /posts/:id` (Update a post) - `DELETE /posts/:id` (Delete a post) 9. **Authentication Middleware:** - Question: Implement middleware in Express.js for user authentication. Explain how to secure specific routes in your application. - Answer: Example middleware for authentication: ```javascript const authenticate = (req, res, next) => { // Check if the user is authenticated if (userAuthenticated) { next(); } else { res.status(401).send("Unauthorized"); } }; // Secure a route using the middleware app.get("/secure-route", authenticate, (req, res) => { res.send("This route is secure"); }); ``` 10. **WebSocket Communication:** - Question: Explain the role of WebSocket in real-time communication and provide a code example of setting up a WebSocket server using the `ws` library. - Answer: WebSocket allows bidirectional communication between the client and the server. Example using the `ws` library: ````javascript const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { ws.on('message', (message) => { console.log(`Received: ${message}`); }); ws.send('Connected to the WebSocket server'); }); ``` ```` Certainly! Here are some Node.js, SQL, and NoSQL coding questions that you might find relevant for someone with 6 years of experience in these technologies: ### Node.js: 1. **Middleware in Express:** - Explain the concept of middleware in Express.js. - Provide an example of how you would use middleware in an Express application. 2. **Event Loop:** - What is the event loop in Node.js, and how does it work? - How does Node.js handle asynchronous operations? 3. **Promises and Async/Await:** - Explain the difference between Promises and Callbacks. - How do you handle asynchronous code in Node.js using Async/Await? 4. **Dependency Management:** - How does npm help in managing dependencies in a Node.js project? - Explain the purpose of the `package.json` file. 5. **Streams in Node.js:** - What are streams in Node.js, and when would you use them? - Provide an example of using streams in a Node.js application. ### SQL: 1. **SQL Joins:** - Explain different types of SQL joins and provide examples of when to use each. - What is the difference between INNER JOIN and LEFT JOIN? 2. **Indexing:** - Why is indexing important in a database? - Explain the difference between clustered and non-clustered indexes. 3. **Transaction Management:** - What is a database transaction, and why is it important? - How do you ensure the ACID properties of a transaction in a relational database? 4. **Normalization:** - What is database normalization, and what are the benefits? - Explain the different normal forms. 5. **Stored Procedures:** - What is a stored procedure, and how does it differ from a regular SQL query? - Provide an example of a situation where using a stored procedure is beneficial. ### NoSQL: 1. **MongoDB:** - What is MongoDB, and how does it differ from traditional relational databases? - Explain the concept of a document in MongoDB. 2. **CRUD Operations:** - Provide examples of CRUD operations in MongoDB. - How does MongoDB handle schema flexibility? 3. **Indexing in NoSQL:** - Why is indexing important in a NoSQL database like MongoDB? - Explain the types of indexes available in MongoDB. 4. **Consistency in NoSQL:** - How does eventual consistency work in a distributed NoSQL database? - Discuss the CAP theorem in the context of NoSQL databases. 5. **Choosing Between SQL and NoSQL:** - What factors would you consider when deciding between a SQL and a NoSQL database for a project? - Can you provide an example scenario where a NoSQL database would be a better fit than a relational database? Certainly! Here are the questions along with sample answers: ### Node.js: 1. **Middleware in Express:** - **Question:** Explain the concept of middleware in Express.js. - **Answer:** Middleware in Express.js are functions that have access to the request, response, and the next middleware function in the application's request-response cycle. They can perform tasks, modify the request or response objects, or end the request-response cycle. - **Question:** Provide an example of how you would use middleware in an Express application. - **Answer:** An example of using middleware in Express is authentication middleware. It can check if a user is authenticated before allowing access to certain routes. 2. **Event Loop:** - **Question:** What is the event loop in Node.js, and how does it work? - **Answer:** The event loop is a fundamental concept in Node.js that allows it to handle multiple operations concurrently. It continuously checks the message queue for new events and executes callback functions associated with those events. - **Question:** How does Node.js handle asynchronous operations? - **Answer:** Node.js uses a non-blocking, event-driven architecture. Asynchronous operations are managed using callbacks, Promises, or Async/Await. This ensures that the application remains responsive to other events while waiting for I/O operations to complete. 3. **Promises and Async/Await:** - **Question:** Explain the difference between Promises and Callbacks. - **Answer:** Callbacks are functions passed as arguments to be executed after a specific task is completed, while Promises represent a value that might be available now, or in the future, or never. Promises provide a more structured way to handle asynchronous operations. - **Question:** How do you handle asynchronous code in Node.js using Async/Await? - **Answer:** Async/Await is syntactic sugar built on top of Promises. You use the `async` keyword before a function declaration, and within that function, you can use `await` to pause execution until a Promise is resolved or rejected. 4. **Dependency Management:** - **Question:** How does npm help in managing dependencies in a Node.js project? - **Answer:** npm (Node Package Manager) is used to install, manage, and share packages or libraries in a Node.js project. It simplifies the process of dependency management by providing a centralized registry and command-line tools for package installation and version control. - **Question:** Explain the purpose of the `package.json` file. - **Answer:** `package.json` is a manifest file that contains metadata about a Node.js project. It includes project details, dependencies, scripts, and other configuration settings. It is used by npm to install dependencies, run scripts, and manage the project. 5. **Streams in Node.js:** - **Question:** What are streams in Node.js, and when would you use them? - **Answer:** Streams are objects that allow you to read or write data in chunks. They are useful for handling large amounts of data efficiently, such as reading from a file or sending data over a network. - **Question:** Provide an example of using streams in a Node.js application. - **Answer:** An example could be reading a large file line by line using a readable stream and processing each line, which helps in avoiding loading the entire file into memory. ### SQL: 1. **SQL Joins:** - **Question:** Explain different types of SQL joins and provide examples of when to use each. - **Answer:** SQL joins include INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN. Use INNER JOIN when you want to retrieve matching records, LEFT JOIN for all records from the left table and matching records from the right table, etc. - **Question:** What is the difference between INNER JOIN and LEFT JOIN? - **Answer:** INNER JOIN returns only the matching records from both tables, while LEFT JOIN returns all records from the left table and matching records from the right table. 2. **Indexing:** - **Question:** Why is indexing important in a database? - **Answer:** Indexing improves query performance by providing a faster way to look up records. It allows the database engine to quickly locate and retrieve specific rows, especially in large datasets. - **Question:** Explain the difference between clustered and non-clustered indexes. - **Answer:** A clustered index determines the physical order of data rows in a table, whereas a non-clustered index does not alter the physical order. A table can have only one clustered index but multiple non-clustered indexes. 3. **Transaction Management:** - **Question:** What is a database transaction, and why is it important? - **Answer:** A database transaction is a sequence of one or more SQL operations that are treated as a single unit of work. Transactions ensure data consistency, integrity, and allow for the rollback of changes in case of errors. - **Question:** How do you ensure the ACID properties of a transaction in a relational database? - **Answer:** ACID properties (Atomicity, Consistency, Isolation, Durability) are ensured by the database management system. Transactions are designed to be atomic (all or nothing), consistent (database remains in a valid state), isolated (transactions are independent), and durable (changes are permanent). 4. **Normalization:** - **Question:** What is database normalization, and what are the benefits? - **Answer:** Database normalization is the process of organizing data to eliminate redundancy and dependency issues. It reduces data anomalies, improves data integrity, and simplifies database maintenance. - **Question:** Explain the different normal forms. - **Answer:** Normal forms are levels of organization for database tables. Examples include 1NF (no repeating groups), 2NF (no partial dependencies), and 3NF (no transitive dependencies). Each normal form addresses specific issues in data organization. 5. **Stored Procedures:** - **Question:** What is a stored procedure, and how does it differ from a regular SQL query? - **Answer:** A stored procedure is a precompiled collection of one or more SQL statements stored in the database. It can be executed with a single call, providing modularity and security benefits over regular SQL queries. - **Question:** Provide an example of a situation where using a stored procedure is beneficial. - **Answer:** Using a stored procedure is beneficial when performing complex operations that involve multiple SQL statements, transactions, or business logic. For example, calculating and updating aggregated values for a set of records in a specific way. ### NoSQL: 1. **MongoDB:** - **Question:** What is MongoDB, and how does it differ from traditional relational databases? - **Answer:** MongoDB is a NoSQL document-oriented database. It differs from traditional relational databases by using a flexible, schema-less document model (BSON format) and horizontal scaling. - **Question:** Explain the concept of a document in MongoDB. - **Answer:** In MongoDB, a document is a JSON-like data structure stored in BSON format. It represents a set of key-value pairs, where values can be arrays, nested documents, or arrays of documents. Documents are the basic unit of data in MongoDB. 2. **CRUD Operations:** - **Question:** Provide examples of CRUD operations in MongoDB. - **Answer:** CRUD operations in MongoDB are Create (insert), Read (find), Update (update), and Delete (remove). For example, `db.collection.insertOne()`, `db.collection.find()`, `db.collection.updateOne()`, and `db.collection.deleteOne()`. - **Question:** How does MongoDB handle schema flexibility? - **Answer:** MongoDB is schema-less, meaning each document in a collection can have a different structure. Fields can be added or removed dynamically, providing flexibility to adapt to changing data requirements. 3. **Indexing in NoSQL:** - **Question:** Why is indexing important in a NoSQL database like MongoDB? - **Answer:** Indexing in MongoDB improves query performance by reducing the number of documents that need to be scanned. It allows for faster data retrieval, especially for queries on indexed fields. - **Question:** Explain the types of indexes available in MongoDB. - **Answer:** MongoDB supports various types of indexes, including single field, compound, multi-key, text, and hashed indexes. Each type is designed to optimize different types of queries. 4. **Consistency in NoSQL:** - **Question:** How does eventual consistency work in a distributed NoSQL database? - **Answer:** Eventual consistency in a distributed NoSQL database means that, after a certain period, all replicas of the data will converge to the same state. It allows for better availability and partition tolerance in distributed systems. - **Question:** Discuss the CAP theorem in the context of NoSQL databases. - **Answer:** The CAP theorem states that in a distributed system, it's impossible to simultaneously provide Consistency, Availability, and Partition Tolerance. NoSQL databases often prioritize either consistency and partition tolerance (CA), availability and partition tolerance (AP), or consistency and availability (CP) based on the system's design goals. 5. **Choosing Between SQL and NoSQL:** - **Question:** What factors would you consider when deciding between a SQL and a NoSQL database for a project? - **Answer:** Factors include data structure complexity, scalability requirements, transactional consistency needs, and the development speed. SQL databases are suitable for structured data and complex queries, while NoSQL databases excel in handling unstructured or semi-structured data with high scalability demands. - **Question:** Can you provide an example scenario where a NoSQL database would be a better fit than a relational database? - **Answer:** A NoSQL database would be a better fit for scenarios with rapidly changing data models, where horizontal scaling is essential, and where the application needs to handle large amounts of unstructured or semi-structured data, such as social media feeds or real-time analytics. Certainly! Below are examples of SQL queries for INNER JOIN and LEFT JOIN: ### INNER JOIN: Suppose you have two tables: `employees` and `departments`. The `employees` table contains information about employees, and the `departments` table contains information about different departments. The common field between these tables is `department_id`. ```sql -- INNER JOIN to retrieve employees and their corresponding department information SELECT employees.employee_id, employees.employee_name, departments.department_name FROM employees INNER JOIN departments ON employees.department_id = departments.department_id; ``` In this query, the `INNER JOIN` is used to retrieve records where there is a match in the `department_id` column between the `employees` and `departments` tables. It selects the `employee_id`, `employee_name`, and `department_name` columns from both tables. ### LEFT JOIN: Continuing with the same example, let's modify the query to use `LEFT JOIN`. This time, we want to retrieve all employees, including those who may not be assigned to any department. ```sql -- LEFT JOIN to retrieve all employees and their corresponding department information (if available) SELECT employees.employee_id, employees.employee_name, departments.department_name FROM employees LEFT JOIN departments ON employees.department_id = departments.department_id; ``` In this query, the `LEFT JOIN` is used to retrieve all records from the `employees` table and the matching records from the `departments` table. If an employee does not have a corresponding department (i.e., the `department_id` is NULL), the result will still include the employee's information with a NULL value for the `department_name`.
package christmas.promotion.domain.event.discount; import christmas.promotion.domain.event.GlobalEvent; import christmas.promotion.vo.Price; import christmas.promotion.domain.visitdate.DecemberVisitDate; import org.junit.jupiter.api.DisplayName; import java.time.LocalDate; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; class SpecialDiscountTest { private static final LocalDate EVENT_PERIOD_START = LocalDate.of(2023, 12, 1); private static final LocalDate EVENT_PERIOD_END = LocalDate.of(2023, 12, 31); GlobalEvent specialDiscount = SpecialDiscount.INSTANCE; @Test @DisplayName("이벤트 이름 확인") void eventName() { assertThat(specialDiscount.getEventName()).isEqualTo("특별 할인"); } @ParameterizedTest @CsvSource({ "2023-11-12, 0", // 11월 (x) 일요일 "2023-12-01, 0", // 금요일 x "2023-12-03, 1000", "2023-12-24, 1000", "2023-12-25, 1000", "2024-12-25, 0" // 2024년 (x) }) @DisplayName("특별 할인 적용 테스트, 2023-12-1 ~ 2023-12-31 & 일요일, 12월 25일만 적용") void applyDiscount(LocalDate date, double excepted) { Price dumpPrice = Price.of(142_000.0); // 만원 이상 이면 얼마든 상관 없음, 만원 이하면 할인 적용 x Price actual = (Price) specialDiscount.applyEvent(new DecemberVisitDate(date), dumpPrice); assertThat(actual.price()).isEqualTo(excepted); } @ParameterizedTest @CsvSource({ "2023-11-30, 10000.0, false", "2024-12-10, 10000.0, false", "2023-12-10, 10000.0, true", "2023-12-25, 10000.0, true", "2023-12-26, 10000.0, false", }) @DisplayName("날짜에 대한 이벤트 가능 판단 테스트,2023-12-1 ~ 2023-12-31 & 일요일, 12월 25일만 적용") void isPossibleEvnet_날짜(LocalDate date, Double price, boolean expected) { assertThat(specialDiscount.isPossibleEvent(new DecemberVisitDate(date), Price.of(price))).isEqualTo(expected); } @ParameterizedTest @CsvSource({ "2023-12-25, -5000.0, false", "2023-12-25, 0.0, false", "2023-12-25, 10000.0, true", "2023-12-25, 300000.0, true", }) @DisplayName("금액에 대한 이벤트 가능 판단 테스트, 최소 만원 이상 이어야 이벤트 가능") void isPossibleEvnet_금액(LocalDate date, Double price, boolean expected) { assertThat(specialDiscount.isPossibleEvent(new DecemberVisitDate(date), Price.of(price))).isEqualTo(expected); } }
/*Write a program that simulates a fishing game. In this game, a six-sided die is rolled to determine what the user has caught. Each possible item is worth a certain number of fishing points. The points will remain hidden until the user is finished fishing, and then a message is displayed congratulating the user depending on the number of fishing points gained. Here are some suggestions for the game’s design: Each round of the game is performed as an iteration of a loop that repeats as long as the player wants to fish for more items. At the end of each round, the program will ask the user whether or not he or she wants to continue fishing. The program simulates the rolling of a six-sided die Each item that can be caught is represented by a number generated from the die—for example, 1 for “a huge fish”, 2 for “an old shoe”, 3 for “a little fish”, and so on. Each item the user catches is worth a different number of points. You, the program designer, get to decide what fish or object each number will represent and how many points is associated with each “catch”. The loop keeps a running total of the user’s fishing points. When the loop is exited, the total number of fishing points is displayed, along with a message that varies depending on the number of points earned. */ #include <iostream> #include <iomanip> #include "Fish.h" using namespace std; int main() { Fish a; int choice; do { cout << "Welcome to Fishing Game! Enter choice from menu below." << endl; cout << "1. Play" << endl; cout << "2. Quit" << endl; cin >> choice; if (choice < 1 || choice > 2) cout << "Input error. please enter valid choice from menu." << endl; } while (choice < 1 || choice > 2); while (choice != 2) { switch (choice) { case 1: cout << "Now we roll a dice to determine what fish you will catch." << endl; a.diceRoll(); cout << "Fish caught: " << a.getFishCaught() << endl; cout << "Points Earned: " << a.getPointsEarned() << endl; break; } cout << "Would you like to play another round? (1 for yes , 2 for no)" << endl; cin >> choice; while (choice < 1 || choice > 2) { cout << "Input error. Please enter valid choice." << endl; cout << "Would you like to play another round? (1 for yes , 2 for no)" << endl; cin >> choice; } } a.displayTotalPoints(); return 0; }
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ToDo</title> <link rel="icon" href="https://cdn.jim-nielsen.com/macos/1024/microsoft-to-do-2019-10-08.png" type="image/x-icon"> <style> body { padding: 0; margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f4f4; color: #000; /* Черный цвет текста по умолчанию */ transition: background-color 0.3s ease, color 0.3s ease; /* Добавлен цвет текста в анимацию перехода */ } body.light-mode { background-color: #FCFCD5; } body.dark-mode { background-color: #572F6D; color: #000; /* Белый цвет текста в темной теме */ } section { width: 100%; max-width: 600px; margin: 0 auto; padding: 20px; background-color: #FEFEE8; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); margin-top: 20px; border-radius: 5px; } h1 { color: #A24547; text-align: center; } form { display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px; } label { font-size: 16px; font-weight: bold; color: #333; } input, checkbox, button { padding: 10px; border: 1px solid #ccc; border-radius: 3px; } input[type="checkbox"] { width: 20px; } button { background-color: #A24547; color: #fff; cursor: pointer; transition: background-color 0.3s ease; } button:hover { background-color: #632a2b; } .error { color: red; margin-top: 5px; } #tasks, #done { background-color: #fff; padding: 20px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); margin-bottom: 20px; border-radius: 5px; } .task { padding: 10px; margin-bottom: 10px; background-color: #f8f8f8; border: 1px solid #ccc; border-radius: 3px; display: flex; justify-content: space-between; align-items: center; } .task-text { flex-grow: 1; margin-right: 10px; } .strikeout { text-decoration: line-through; } .important { color: #f00; font-weight: bold; } .theme-toggle { position: absolute; top: 10px; right: 10px; cursor: pointer; } #loader { border: 6px solid #f3f3f3; border-top: 6px solid #A24547; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; position: absolute; top: 50%; left: 50%; margin-top: -20px; margin-left: -20px; display: none; /* изначально скрыт */ } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .theme-toggle { position: absolute; top: 10px; right: 10px; cursor: pointer; } .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); justify-content: center; align-items: center; } .modal-content { background-color: #e32d2d; padding: 20px; border-radius: 8px; text-align: center; } .modal-btn { padding: 10px 20px; background-color: #007bff; color: #fff; border: none; border-radius: 4px; cursor: pointer; } .modal-btn.cancel { background-color: #6c757d; margin-right: 10px; } </style> <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script src="script.js"></script> </head> <body class="light-mode"> <section> <h1>Laba Ajax</h1> <form id="taskForm"> <label for="title">Название:</label> <input type="text" id="title" required /> <label for="body">Описание:</label> <input type="text" id="body" required /> <label for="userId">ID пользователя:</label> <select name="userId", id="userId"> <option value=1>Leanne Graham</option> <option value=2>Ervin Howell</option> <option value=3 selected>Clementine Bauch</option> <option value=4>Patricia Lebsack</option> <option value=5>Chelsey Dietrich</option> <option value=6>Mrs. Dennis Schulist</option> <option value=7>Kurtis Weissnat</option> <option value=8>Nicholas Runolfsdottir V</option> <option value=9>Glenna Reichert</option> <option value=10>Clementina DuBuque</option> </select> <label for="userId2">(Рудимент, нужно чисто для проверки ошибки)ID пользователя (1-10):</label> <input type="number" id="userId2" min="1" max="10" required /> <label for="important">Важная:</label> <input type="checkbox" id="important" /> <button type="submit">Добавить</button> <div class="error" id="userIdError"></div> </form> <div id="tasks"></div> <div id="done"> <h3>Выполненные задания</h3> </div> <div id="loader" class="loader"></div> <div class="theme-toggle" onclick="toggleTheme()">🌙</div> <!-- Модальное окно подтверждения удаления --> <div id="deleteModal" class="modal"> <div class="modal-content"> <p>Вы уверены, что хотите удалить этот важный пост?</p> <button class="modal-btn" id="confirmDelete">Удалить</button> <button class="modal-btn cancel" id="cancelDelete">Отмена</button> </div> </div> </section> <script src="script.js"></script> </body> </html>
# **Dart Documentation By " Ahmed Amer "** **** **<u>[Online Code Editor](https://dartpad.dev/?null_safety=true)</u> =>** https://dartpad.dev/?null_safety=true [Online Code Editor 2](https://replit.com/) => https://replit.com/ **<u>[Reference](https://www.tutorialspoint.com/dart_programming/index.htm)</u> =>** https://www.tutorialspoint.com/dart_programming/index.htm ******** 1-) What is Dart ? Who is create it ? ###### Answer : **<u>Dart :</u>** is a programming language designed for client development, such as for the web and mobile apps. It is developed by Google and can also be used to build server and desktop applications. Dart is an object-oriented, class-based, garbage-collected language with C-style syntax. **[Developer](https://www.google.com/search?rlz=1C1GCEA_enIQ911IQ911&sxsrf=AOaemvJRRgecrjBH0KYo1chTa4qtbGzf8A:1641667033386&q=dart+programming+language+developer&sa=X&ved=2ahUKEwj4v_Si5qL1AhUFgv0HHcaKAtQQ6BMoAHoECDMQAg):** [Google](https://www.google.com/search?rlz=1C1GCEA_enIQ911IQ911&sxsrf=AOaemvJRRgecrjBH0KYo1chTa4qtbGzf8A:1641667033386&q=Google&stick=H4sIAAAAAAAAAONgVuLUz9U3MDFNNk9axMrmnp-fnpMKAMKapuoWAAAA&sa=X&ved=2ahUKEwj4v_Si5qL1AhUFgv0HHcaKAtQQmxMoAXoECDMQAw). **[Stable release](https://www.google.com/search?rlz=1C1GCEA_enIQ911IQ911&sxsrf=AOaemvJRRgecrjBH0KYo1chTa4qtbGzf8A:1641667033386&q=dart+programming+language+stable+release&sa=X&ved=2ahUKEwj4v_Si5qL1AhUFgv0HHcaKAtQQ6BMoAHoECEYQAg):** 2.15.1 / 14 December 2021; 23 days ago. **[Filename extensions](https://www.google.com/search?rlz=1C1GCEA_enIQ911IQ911&sxsrf=AOaemvJRRgecrjBH0KYo1chTa4qtbGzf8A:1641667033386&q=dart+programming+language+filename+extensions&sa=X&ved=2ahUKEwj4v_Si5qL1AhUFgv0HHcaKAtQQ6BMoAHoECDoQAg):** dart. **[Designed by](https://www.google.com/search?rlz=1C1GCEA_enIQ911IQ911&sxsrf=AOaemvJRRgecrjBH0KYo1chTa4qtbGzf8A:1641667033386&q=dart+programming+language+designed+by&sa=X&ved=2ahUKEwj4v_Si5qL1AhUFgv0HHcaKAtQQ6BMoAHoECEIQAg):** [Lars Bak](https://www.google.com/search?rlz=1C1GCEA_enIQ911IQ911&sxsrf=AOaemvJRRgecrjBH0KYo1chTa4qtbGzf8A:1641667033386&q=Lars+Bak&stick=H4sIAAAAAAAAAONgVuLSz9U3MC00qSyJX8TK4ZNYVKzglJgNAFu6_xEZAAAA&sa=X&ved=2ahUKEwj4v_Si5qL1AhUFgv0HHcaKAtQQmxMoAXoECEIQAw&biw=1536&bih=714&dpr=1.25) and [Kasper Lund.](https://www.google.com/search?rlz=1C1GCEA_enIQ911IQ911&sxsrf=AOaemvJRRgecrjBH0KYo1chTa4qtbGzf8A:1641667033386&q=Kasper+Lund&stick=H4sIAAAAAAAAAONgVuLVT9c3NEzPKMuuMjWzWMTK7Z1YXJBapOBTmpcCAF2km-gfAAAA&sa=X&ved=2ahUKEwj4v_Si5qL1AhUFgv0HHcaKAtQQmxMoAnoECEIQBA&biw=1536&bih=714&dpr=1.25) **[First appeared](https://www.google.com/search?rlz=1C1GCEA_enIQ911IQ911&sxsrf=AOaemvJRRgecrjBH0KYo1chTa4qtbGzf8A:1641667033386&q=dart+programming+language+first+appeared&sa=X&ved=2ahUKEwj4v_Si5qL1AhUFgv0HHcaKAtQQ6BMoAHoECCUQAg):** October 10, 2011; 10 years ago. **** 2-) Camp output ? What can I do if I learn Dart ? Answer : Well, You gonna deal with the Dart programming language with write the codes and read the codes with Dart. You can use it with **Flutter SDK** to build native cross-platform applications. **** 3-) Dart Syntax : - Main Syntax & Print : ```dart void main() { print("Hello World!"); } ``` ```dart main() { print('Hello World'); } ``` ``` Hello World ``` - Comments : ```dart /* multiline comment */ // single line comment ``` - Data Types : ``` The Dart language supports the following types− - integer - string - double - bool - const - var - list - map ``` - Variables : ```dart main(){ String name = 'Steve'; int n = 10; double x = 15.2; /* OR */ x = 15; const pi = 13.4; var k = all types; /* It's gonna declare and got what data type of it */ bool var_name = true; /* OR */ bool var_name = false; } ``` - Operators : ``` [ + , / , * , - , % , ++ , -- , < , <= , > , >= , == , != , && , || ] ``` **** 4-) For Loop: ```dart void main() { for (var i = 1; i <= 5; i++) { print("Item : ${i}"); } } ``` ``` Item : 1 Item : 2 Item : 3 Item : 4 Item : 5 ``` **** 5-) While Loop : ```dart void main() { var i = 1; while(i <= 5) { print("Item : ${i}"); i++; } } ``` ``` Item : 1 Item : 2 Item : 3 Item : 4 Item : 5 ``` **** 6-) Do While Loop : ```dart do { Statement(s) to be executed; } while (expression); ``` ```dart void main() { var n = 10; do { print(n); n--; } while(n>=0); } ``` ``` 10 9 8 7 6 5 4 3 2 1 0 ``` **** 7-) Conditions : ```dart void main() { var str = 'abc'; if(str) { /* true */ print('String is not empty'); } else { /* false */ print('Empty String'); } /* we can use nested conditions */ if(condition){ if(condition){ if(condition){ // statement }else{ // statement } }else{ // statement } }else{ // statement } } ``` ``` String is not empty ``` **** 8-) Switch Case : ```dart switch (value) { case 0: // do something break; case 1: // do something else break; default: // do something if not all before cases break; } ``` ```dart void main() { var grade = "A"; switch(grade) { case "A": { print("Excellent"); } break; case "B": { print("Good"); } break; case "C": { print("Fair"); } break; case "D": { print("Poor"); } break; default: { print("Invalid choice"); } break; } } ``` ``` Excellent ``` **** 9-) List : ```dart void main() { var num_list = [1,2,3]; print(num_list); num_list.add(4); // add to list function print(num_list); num_list.remove(1); // remove from list function print(num_list); var lst= [1,2,3,4,5]; lst.forEach((i) { print('i = ${i}'); }); /* list_or_map.forEach((element) { // Statment }); */ print("-" * 30); var mylist = ['A', 'B', 3.14, true, 55]; print(mylist); print("-" * 30); mylist.insert(4, 44); // insert in specefic index mylist.insert(6, 555); mylist.insert(7, 777); print(mylist); print("-" * 30); mylist.add(88); // after last index mylist.add(99); print(mylist); print("-" * 30); mylist.remove('A'); // remove the element mylist.remove(55); mylist.removeAt(0); // remove by index for (var i = 0; i <= mylist.length - 1; i++) { print("Value : ${mylist[i]}"); } } ``` ``` [1,2,3] [1, 2, 3, 4] [2, 3, 4] i = 1 i = 2 i = 3 i = 4 i = 5 ------------------------------ [A, B, 3.14, true, 55] ------------------------------ [A, B, 3.14, true, 44, 55, 555, 777, 88, 99] ------------------------------ Value : 3.14 Value : true Value : 44 Value : 555 Value : 777 Value : 88 Value : 99 ``` **** 10-) Map : ```dart void main() { var details = {'Username':'tom','Password':'pass@123'}; print(details); details.remove('Username'); // remove from Map print(details); details['test'] = '55'; // add to Map print(details); details.addAll({'Email': 'a@a.a'}); // add to Map using function build in print(details); details.forEach((key, value) { // print Map content using forEach print('Key = ${key}\nValue = ${value}'); }); } ``` ``` {Username: tom, Password: pass@123} {Password: pass@123} {Password: pass@123, test: 55} {Password: pass@123, test: 55, Email: a@a.a} Key = Username Value = tom Key = Password Value = pass@123 ``` ```dart void main() { var details = new Map(); details['Username'] = 'admin'; details['Password'] = 'admin@123'; print(details); } ``` ``` {Username: admin, Password: admin@123} ``` **** ```dart main() { var json = [ {'id': 1, 'Name': 'Ahmed'}, {'id': 2, 'Name': 'Jason'}, {'id': 3, 'Name': 'Steve'}, ]; print(json); print('-'*50); json.forEach((i)=>{ print(i) }); print('-'*50); var x = json[0]; print(x); x.forEach((key, value) => {print('${key} => ${value}')}); } ``` ``` [{id: 1, Name: Ahmed}, {id: 2, Name: Jason}, {id: 3, Name: Steve}] -------------------------------------------------- {id: 1, Name: Ahmed} {id: 2, Name: Jason} {id: 3, Name: Steve} -------------------------------------------------- {id: 1, Name: Ahmed} id => 1 Name => Ahmed ``` *** 11-) Functions : ```dart void main() { msg(); print(age()); print(name()); print(cond()); print(lst()); print(myMap()); } msg(){ // void function without return print('message'); } int age(){ // integer function should return integer number return 20; } String name(){ // string function should return string return 'Ahmed'; } bool cond(){ // boolean function should return true or false return true; } List lst(){ // list function should return list return [1,2,3,4,5]; } Map myMap(){ // map function should return map return {'one':'1', 'two':'2'}; } ``` ``` message 20 Ahmed true [1, 2, 3, 4, 5] {one: 1, two: 2} ``` *** 12-) Arrow Function ```dart void main() { msg(); print(age()); print(name()); print(cond()); print(lst()); print(myMap()); } /* Note: This type of function work with single line statment */ msg() => print('message'); // arrow function with void type int age() => 20; // arrow function with integer type String name() => 'Ahmed'; // arrow function with string type bool cond() => true; // arrow function with boolean type List lst() => [1, 2, 3, 4, 5]; // arrow function with list type Map myMap() => {'one': '1', 'two': '2'}; // arrow function with map type ``` ``` message 20 Ahmed true [1, 2, 3, 4, 5] {one: 1, two: 2} ``` ```dart void main() { print("main function"); print('-' * 30); msg('error', '104'); print('-' * 30); // var n = number(); // print(n); print(number(10, 20)); print('-' * 30); print(name('Ahmed')); print('-' * 30); print(result(true)); print('-' * 30); print(lst([1, 2, 3])); print('-' * 30); print(mp({'username': 'GDSC'})); } void msg(error, n) => print(' - msg function ${n} -> ${error}'); int number(x, y) => x + y; String name(username) => 'Hello ${username}'; bool result(bool r) => r; List lst(List l) => l; Map mp(var m) => m; ``` ``` main function ------------------------------ - msg function 104 -> error ------------------------------ 30 ------------------------------ Hello Ahmed ------------------------------ true ------------------------------ [1, 2, 3] ------------------------------ {username: GDSC} ``` *** 13-) OOP : ```dart class Car { // field String engine = "E1001"; // function void disp() { print(engine); } } main(){ var ob = new Car(); /* OR */ Car ob = new Car(); ob.disp(); } ``` ``` E1001 ``` **** 14-) Classes : ```dart class Student { void test_method() { print("This is a test method"); } void test_method1() { print("This is a test method1"); } } void main() { Student s1 = new Student(); s1.test_method(); s1.test_method1(); } ``` ``` This is a test method This is a test method1 ``` *** ```dart class google { var username; var password; var dept; var lst; google(a, b, c, d) { //constractor this.username = a; this.password = b; this.dept = c; this.lst = d; print('Welcome ${a} => ${b} => ${c} => ${d}'); employees(); } employees() { if (username == 'Ali' && password == '123') { if (dept == 'web') { dashboard_msg(dept); } else if (dept == 'apps') { dashboard_msg(dept); } else { error_msg(); } } else { error_msg(); } } dashboard_msg(dept) { print('Welcome in Dashboard ${username}'); if (dept == 'web') { web(); } else if (dept == 'apps') { apps(); } else { error_msg(); } } error_msg() { print('This is Error message !!!'); } web() { print('- web department'); myList(); } apps() { print('- apps department'); myList(); } myList() { print('your list => ${lst}'); } } /* End Class */ void main() { var lst = [1, 2, 3, 4, 5]; google ob1 = new google('Ali', '123', 'web', lst); print('-' * 30); google ob2 = new google('Sarah', '111', 'apps', lst); } ``` Output: ``` Welcome Ali => 123 => web => [1, 2, 3, 4, 5] Welcome in Dashboard Ali - web department your list => [1, 2, 3, 4, 5] ------------------------------ Welcome Sarah => 111 => apps => [1, 2, 3, 4, 5] This is Error message !!! ```
import { Stack } from '@mui/material'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; const CardRow = ({ label, text, siblingLabel, siblingText }) => { return ( <Stack direction='row'> <Typography variant='body2' color='text.secondary' noWrap sx={{ fontWeight: 'bold' }} > {`${label}: `} </Typography> <Typography variant='body2' color='text.secondary' noWrap ml={1}> {text} </Typography> {siblingLabel && ( <> <Divider orientation='vertical' flexItem sx={{ ml: 1 }} /> <Typography variant='body2' color='text.secondary' noWrap sx={{ fontWeight: 'bold' }} > {`${siblingLabel}: `} </Typography> <Typography variant='body2' color='text.secondary' noWrap ml={1} > {siblingText} </Typography> </> )} </Stack> ); }; export default CardRow;
package com.yedy.bank.service; import com.yedy.bank.enums.TransactionType; import com.yedy.bank.model.Account; import com.yedy.bank.model.Transaction; import org.springframework.util.Assert; import java.math.BigDecimal; import java.util.UUID; public class PhoneBillPaymentTransaction implements ITransaction { private String provider; private String phoneNumber; private Double amount; public PhoneBillPaymentTransaction(String provider, String phoneNumber, Double amount) { this.provider = provider; this.phoneNumber = phoneNumber; this.amount = amount; } @Override public Account process(Account account) { Assert.notNull(account,"Account boş olamaz.!"); Assert.notNull(provider,"Sağlayıcı boş bırakılamaz"); Assert.notNull(phoneNumber,"Telefon numarası boş bırakılamaz"); if(amount<=0){ throw new RuntimeException("Fatura işlemi miktarı 0 dan büyük olmalıdır!"); } if(account.getBalance()<amount){ throw new RuntimeException("Fatura işlemi için bakiyeniz yeterli değildir!"); } account.setBalance(account.getBalance()-amount); Transaction transaction= new Transaction(); transaction.setTransactionType(TransactionType.BillPaymentTransaction); transaction.setAmount(amount); transaction.setPhoneNumber(phoneNumber); transaction.setProvider(provider); transaction.setAccount(account); account.getTransaction().add(transaction); return account; } }
import { IController, IRequest } from "../../interface"; import { NextFunction, Request, Response, Router } from "express"; import auth from "../../middleware/auth"; import { Container } from "typedi"; import BlogService from "../../services/admin/BlogService"; import { UserRole } from "../../entities/User"; import upload from "../../middleware/multer"; class BlogController implements IController { path = "/admin/blogs"; router = Router(); constructor() { this.router .post(`${this.path}`, auth(UserRole.ADMIN), upload.single("feature_image"), this.create) .get(`${this.path}`, auth(UserRole.ADMIN), this.index) .get(`${this.path}/:id`, auth(UserRole.ADMIN), this.show) .put(`${this.path}/:id`, auth(UserRole.ADMIN), upload.single("feature_image"), this.update) } private index = async ( req: Request, res: Response, next: NextFunction ) => { try { const { search } = req.query; const pageNo = parseInt(<string>req.query.page); const size = parseInt(<string>req.query.size); const blogServiceInstance = Container.get(BlogService); const blog = await blogServiceInstance.index(pageNo * size, size, search); res.status(200).json(blog); } catch (e) { next(e); } } private show = async ( req: Request, res: Response, next: NextFunction ) => { try { const blogId = req.params.id; const blogServiceInstance = Container.get(BlogService); const blog = await blogServiceInstance.show(parseInt(blogId)); res.status(200).json(blog); } catch (e) { next(e); } } private create = async ( req: Request, res: Response, next: NextFunction ) => { try { const user = (req as IRequest).user; const blogServiceInstance = Container.get(BlogService); const { saved } = await blogServiceInstance.create(req.body, user, req.file); res.status(200).json({ message: "Blog created successfully", saved }) } catch (e) { next(e); } }; private update = async ( req: Request, res: Response, next: NextFunction ) => { try { const blogId = req.params.id; const blogServiceInstance = Container.get(BlogService); const blog = await blogServiceInstance.update(req.body, parseInt(blogId), req.file); res.status(200).json(blog) } catch (e) { next(e); } } } export default BlogController
#import necessary libraries from flask import Flask, render_template, request from sklearn.linear_model import LinearRegression import numpy as np import mysql.connector import atexit import json #start the flask app app = Flask(__name__) # Database Configuration db_config = { 'host': 'your_host', 'user': 'your_username', 'password': 'your_password', 'database': 'your_database' } # Connecting to Database Configuration connection = mysql.connector.connect(**db_config) #Jinja filter to check if any of the entries are empty def is_not_empty(value): return value != '' app.jinja_env.filters['is_not_empty'] = is_not_empty #Jinja filter to round the estimated market price to nearest hundreds def custom_round(value, precision=-1): return round(value, precision) app.jinja_env.filters['round'] = custom_round ''' Function to fetch data from database attempting to reconnect if not connected using try and except block Includes query for selecting required columns based on year,make and model Excludes models with listing price not mentioned in database ''' def fetch_data_from_database(year, make, model): try: if not connection.is_connected(): connection.ping(reconnect=True) with connection.cursor(dictionary=True) as cursor: query = f"SELECT vin, year, make, model, listing_mileage, listing_price, trim, dealer_city, dealer_state FROM your_tablename WHERE year={year} AND make='{make}' AND model='{model}';" cursor.execute(query) data = cursor.fetchall() return data except mysql.connector.Error as e: print(f"Error fetching data from database: {e}") return None #Function to perform linear regression based on the data(listing_price,listing_mileage) collected for given year,make and model def perform_linear_regression(data): X = np.array([item['listing_mileage'] for item in data]).reshape(-1, 1) y = np.array([item['listing_price'] for item in data]) model = LinearRegression() model.fit(X, y) calculated_slope = model.coef_[0] calculated_intercept = model.intercept_ return calculated_slope, calculated_intercept # Function to read JSON objects from a file and extract a specific key def read_json_file(file_path, key): try: with open(file_path, 'r') as file: # Load JSON objects from each line of the file json_objects = [json.loads(line) for line in file] # Extract the specified key from each JSON object values = [obj[key] for obj in json_objects] return values except Exception as e: print(f"Error reading {key} from file: {e}") return [] # Function for suggestions using data from text files @app.route('/') def index(): try: makes = read_json_file('static/txtfiles/makes.txt', 'make') models = read_json_file('static/txtfiles/models.txt', 'model') years = read_json_file('static/txtfiles/years.txt', 'year') return render_template('index.html', makes=makes, models=models, year_options=years) except Exception as e: print(f"Error fetching suggestions from text files: {e}") return render_template('error.html', message='Error fetching suggestions from text files') ''' Function to search and perform linear regression for searched data and given mileage, if present returns predicted price of corresponding mileage, else returns predicted price corresponding to average mileage ''' @app.route('/search', methods=['POST']) def search(): year = request.form.get('year') make = request.form.get('make') model = request.form.get('model') mileage_input = request.form.get('mileage') try: # Fetch data from the database based on user input data = fetch_data_from_database(year, make, model) # Check if no records are found if not data: return render_template('results.html', no_records=True, message='No Records Found!') # Perform linear regression only if there are records calculated_slope, calculated_intercept = perform_linear_regression(data) predicted_price = 0 # Check if optional mileage input is provided and if present calculate cost using provided mileage else calculate cost for average mileage if mileage_input: try: mileage = float(mileage_input) predicted_price = calculated_slope * mileage + calculated_intercept except ValueError: return render_template('error.html', message='Invalid input for mileage') else: average_mileage = np.mean([item['listing_mileage'] for item in data]) predicted_price = calculated_slope * average_mileage + calculated_intercept return render_template('results.html', data=data, predicted_price=predicted_price, year=year, make=make, model=model) # Render the results template with the data except mysql.connector.Error as e: print(f"Error in search: {e}") return render_template('error.html', message='Error in search') # Close the connection atexit.register(lambda: connection.close()) if __name__ == '__main__': app.run(debug=True)
/* reset css */ body, ul, p { /* unset: margin을 없애버리겠다 */ margin: unset; padding: unset; } h1, h2 { margin: unset; font-size: unset; font-weight: unset; } li { list-style-type: none; } a { color: unset; text-decoration: unset; } /* 부모 기준 가득 차게 */ img { /* 부모보다 커지지 못하게 작동 */ max-width: 100%; height: auto; /* img 밑에 공간이 남음 => 공간 없애줌 */ vertical-align: top; } /* variable */ :root { --header-height: 300px; --footer-height: 60px; } /* Typography */ :root { line-height: 1.56; } /* layouts */ /* wrapper: 가운데 정렬 담당 */ .wrapper { /* box-shadow: inset 0 0 20px gold; */ /* 사용 가능한 공간 남음 */ /* width 고정시키면 반응형 만들 수 없음 */ /* width: 1200px; */ max-width: 1200px; padding: 0 30px; /* 가운데 정렬 */ /* margin-left: auto; */ /* margin-right: auto; */ /* 위 두개 합해서 */ margin: 0 auto; } /* flex 했더니 찌부됨 grid 로 변경 */ .grid { /* 컨테이닝 블록만큼 가득 찬다 */ /* box-shadow: inset 0 0 20px red; */ /* 부모인 grid ul이 flex-container가 됐다 */ /* grid item(=flex-items)이 컨텐츠 크기만큼으로 줄어듬 */ /* display: flex; */ /* flex-wrap: wrap; */ display: grid; /* 자동으로 줄어들음 */ /* minmax: 하나가 200px 알아서 점점 커지다가 */ grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 30px; } .grid-item { /* flex-basis: auto; === 컨텐츠 크기 만큼의 의미 */ /* 여백을 삼등분해서 균등하게 나눠 가짐(원래 컨텐츠 크기 + 여백 1/3) */ /* 균등하게 만들기 위해 basis 값을 없앰. 컨텐츠 크기와 상관 없음 */ /* flex-basis: 0; */ /* flex-basis: 200px; flex-grow: 1; */ /* layout 잡는데 도움 받기 위해 */ min-height: 200px; /* box-shadow: inset 0 0 20px blue; */ /* min-width: auto; 초기값 컨텐츠 만큼 */ /* 0으로 초기화 => 원래 박스 사이즈만큼으로 => 이미지가 크면 튀어나옴 */ min-width: 0; } /* css style === components */ body { background-image: url(./images/bg.png); background-size: cover; /* 배경 이미지의 고정 여부 */ background-attachment: fixed; color: white; } .header { /* 줄바꿈 안됨 */ white-space: nowrap; /* 처음에는 영역을 알기 위해 좀 밝은색으로 주자 */ background-color: #000; text-align: center; /* viewport 창의 크기에 따라 font-size가 변한다 eg) 10vw */ font-size: 200px; font-weight: 700; line-height: 1.5; height: var(--header-height); display: flex; justify-content: center; align-items: center; font-family: "Lobster Two", cursive; font-style: italic; color: #555; word-spacing: 0; position: relative; overflow: hidden; transition: word-spacing 0.4s, color 0.4s; } .header-cover { /* 자기 공간 버림 viewport 기준에서 움직임(부모에 static아닌 position이 없을 때 => header에 relative 주니까 header가 새로운 기준이 됨 === 컨테이닝 블록이 됨*/ position: absolute; /* left: 0; right: 0; 하면 컨테이닝블록만큼 찬다. => 이게 뭐여 */ left: 0; right: 0; bottom: 0; margin: 0 auto; transform: translateY(80%); transition: transform 0.4s; } .header:hover { word-spacing: 300px; color: #fff; } /* header에 hover 됐을 때, cover */ .header:hover .header-cover { transform: translateY(40%); } .contents { /* 차지하는 영역 보기 위해 */ /* box-shadow: inset 0 0 20px red; */ /* footer을 밑으로 붙이고 최소 높이 확보 */ min-height: calc(100vh - (var(--header-height) + var(--footer-height))); } .nav { background-color: rgb(0 0 0 / 0.4); padding: 40px 0; backdrop-filter: blur(10px); /* text-align: center; */ /* nav 스크롤 내려도 고정 */ position: sticky; top: 0; left: 0; } .nav-menu { /* 바깥에서 보면 inilne, 내부에서는 flex */ /* display: inline-flex; */ display: flex; width: fit-content; margin: 0 auto; background-color: #333; border-radius: 30px; border-top: 1px solid #999; border-bottom: 2px solid #000; box-shadow: inset 0 0 10px 3px rgb(0 0 0 / 0.4); padding: 0 20px; color: #888; } .nav-menu li a { /* a: inline, 상하단 패딩 못 가짐 => 그래서, block으로 바꿈 */ display: block; padding: 20px; transition: color, 0.4s; } .nav-menu li a:hover { color: #ccc; } .main { padding: 40px 0; } .animal { max-width: 300px; margin: 0 auto; } .animal-cover { display: block; margin: 0 auto; } .animal-contents { background-image: url(./images/green.png); /* 땅 크기 키워도 초록색 풀이 계속되게 하기 위함 */ background-repeat: repeat-x; /* animal 크기가 커져도 문제 없게 만들기 위함 */ background-position: center top; background-color: #93572e; padding: 70px 20px 40px 20px; border-radius: 10px 10px 30px 30px; border-bottom: 14px solid rgb(0 0 0 / 0.4); } .animal-contents h2 { font-size: 30px; font-weight: 700; margin-bottom: 20px; } .animal-contents p { color: #e4c2c2; } .footer { background-color: #222; border-top: 1px solid #888; /* padding: 20px 0; */ height: var(--footer-height); line-height: var(--footer-height); text-align: center; color: #999; }
import ingredientDetailsStyle from "./ingredient-details.module.css" import { useParams } from 'react-router'; import { useSelector } from 'react-redux'; const IngredientDetails = () =>{ const { id } = useParams(); const ingredient = useSelector(state => state.ingredients.ingredients.find(ingredient => ingredient._id === id)) return ( <> {ingredient && <div className={ingredientDetailsStyle.mainContainer}> <img alt="previewImage" src={ingredient.image_large}/> <p className={`${ingredientDetailsStyle.ingredientNameText}text text_type_main-medium mt-4`}> {ingredient.name} </p> <div className={`${ingredientDetailsStyle.macronutrientContainer} mt-8 mb-15`}> <div className={ingredientDetailsStyle.macronutrientElem}> <p className="text text_type_main-small text_color_inactive">Калории,ккал</p> <p className="text text_type_digits-default text_color_inactive">{ingredient.calories}</p> </div> <div className={ingredientDetailsStyle.macronutrientElem}> <p className="text text_type_main-small text_color_inactive">Белки, г</p> <p className="text text_type_digits-default text_color_inactive">{ingredient.proteins}</p> </div> <div className={ingredientDetailsStyle.macronutrientElem}> <p className="text text_type_main-small text_color_inactive">Жиры, г</p> <p className="text text_type_digits-default text_color_inactive">{ingredient.fat}</p> </div> <div className={ingredientDetailsStyle.macronutrientElem}> <p className="text text_type_main-small text_color_inactive">Углеводы, г</p> <p className="text text_type_digits-default text_color_inactive">{ingredient.carbohydrates}</p> </div> </div> </div> } </> ) } export default IngredientDetails;
/* eslint-disable jsx-a11y/label-has-associated-control */ 'use client'; import { useContext, useEffect, useState } from 'react'; import Link from 'next/link'; import { signOut, useSession } from 'next-auth/react'; import Cookies from 'js-cookie'; import { useRouter } from 'next/navigation'; import { LoginContext } from 'context/LoginContext'; import { Pic } from 'components/ui/Pic'; import usePageBottom from 'hooks/usePageBottom'; import BottomNav from 'components/BookingManagement/BottomNav'; import PortalModal from 'components/ui/PortalModal'; import GoogleMobileNumber from 'components/shared/GoogleMobileNumber'; import api from 'components/utils/api'; import { toast } from 'react-toastify'; import Sidebar from './Sidebar'; function AuthWrap({ children, setShowNewBooking = () => {}, showNewBooking = false, }) { const { setShowLogin, userName, setUserName } = useContext(LoginContext); const router = useRouter(); const [modalOpen, setModalOpen] = useState(false); const { data: session, status, update } = useSession(); useEffect(() => { const token = sessionStorage.getItem('token'); if (status === 'loading') return; if (!token || token === 'null' || token === 'undefined') { console.log(session); if (session?.user?.email && session?.user?.mobile) { sessionStorage.setItem( 'user', JSON.stringify({ userfname: session?.user?.name?.split(' ')?.[0], userlname: session?.user?.name?.split(' ')?.[1], useremailid: session?.user?.email, usermobileno: session?.user?.mobile, usercountrycode: session?.user?.countryCode, }), ); sessionStorage.setItem('token', session?.user?.rolDriveToken); Cookies.set('authtype', 'GOOGLE'); setShowLogin(!!session?.user?.rolDriveToken); setUserName({ userfname: session?.user?.name?.split(' ')?.[0], userlname: session?.user?.name?.split(' ')?.[1], }); } else if (session?.user?.email && !session?.user?.usermobileno) { setModalOpen(true); } else { router.push(''); } } else { const user = JSON.parse(sessionStorage.getItem('user')); setUserName({ userfname: user.userfname, userlname: user.userlname, }); } // else if (session?.user?.email && token) { // sessionStorage.setItem( // 'user', // JSON.stringify({ // userfname: session?.user?.name?.split(' ')?.[0], // userlname: session?.user?.name?.split(' ')?.[1], // useremailid: session?.user?.email, // usermobileno: session?.user?.mobile, // usercountrycode: session?.user?.countryCode, // }), // ); // sessionStorage.setItem('token', session?.user?.rolDriveToken); // Cookies.set('authtype', 'GOOGLE'); // setShowLogin(!!session?.user?.rolDriveToken); // setUserName({ // userfname: session?.user?.name?.split(' ')?.[0], // userlname: session?.user?.name?.split(' ')?.[1], // }); // } else { // const user = JSON.parse(sessionStorage.getItem('user')); // setUserName({ // userfname: user.userfname, // userlname: user.userlname, // }); // } router.refresh(); }, [router, session, setShowLogin, setUserName, status]); const [showSidebar, setShowSidebar] = useState(false); const [isOpend, setisOpend] = useState(false); const logOut = () => { sessionStorage.clear(); setShowLogin(false); Cookies.remove('searchdata'); Cookies.remove('fleetlist'); signOut({ callbackUrl: '/login', }); }; const reachedBottom = usePageBottom(); const handleSubmit = async (phone, phoneCountry) => { const response = await api.post('/auth/check', { mobile: phone }); if (response.data.exists) { toast.error('This phone number is already in use.', { autoClose: 3000, theme: 'colored', }); toast.clearWaitingQueue(); } else { update({ ...session, usermobileno: phone, usercountrycode: phoneCountry }); setModalOpen(false); } router.refresh(); }; return ( <> <PortalModal theme="dark" isOpen={modalOpen} onClose={() => { setModalOpen(false); }} showCloseIcon={false} title="Add User Mobile Number" > <GoogleMobileNumber handleSubmit={handleSubmit} /> </PortalModal> <div className="relative"> <div style={{ height: reachedBottom ? 0 : '4.5rem' }} className="duration-150 ease-out transition-[height] fixed bottom-0 z-40 md:hidden" > <BottomNav setShowNewBooking={setShowNewBooking} showNewBooking={showNewBooking} /> </div> <Sidebar showSidebar={showSidebar} setShowSidebar={setShowSidebar} isOpend={isOpend} setisOpend={setisOpend} /> <div className={`${isOpend ? 'sm:ml-64' : 'sm:ml-16'}`}> <div className="sticky top-0 z-30 px-3 border navbar bg-base-100 sm:px-0"> <div className="flex-1"> <Link href="/" className="w-32 h-12 -mt-2 lg:w-36 md:h-12"> <Pic src="/images/logo.png" alt="RolDrive logo" /> </Link> </div> <div className="flex-none"> <div className="dropdown dropdown-end sm:mr-5"> <label tabIndex={0} className="cursor-pointer"> <div className="flex items-center text-[14px] text-black font-semibold uppercase"> {userName && ( <div className="flex items-center justify-center w-[32px] h-[32px] font-medium text-white rounded-full bg-primary"> {userName?.userfname?.[0]} {userName?.userlname?.[0]} </div> )} </div> </label> <ul tabIndex={0} className="p-0 mt-3 shadow menu menu-compact dropdown-content bg-base-100 w-52" > <li className="rounded-none"> <Link href="/booking-management" className="justify-between !rounded-none" > Bookings </Link> </li> <li> <Link href="/profile-management" className="rounded-none"> My Account </Link> </li> <li> <button type="button" className="rounded-none" onClick={() => { logOut(); }} > Logout </button> </li> </ul> </div> </div> </div> <div>{children}</div> </div> </div> </> ); } export default AuthWrap;
import { readFileLines } from "@tooling/read"; const lines = readFileLines(import.meta.dir, "input.txt", (line) => line); const readStacks = (): [string[][], number] => { let stacks = []; let i = 0; while (true) { if (lines[i] === "") { break; } const line = lines[i]; for (let j = 0, f = 0; j < line.length; j += 4, f++) { const name = line[j + 1]; if (stacks.length <= f) { stacks.push([]); } if (name === " ") { continue; } if (name === "1") { break; } stacks[f].push(name); } i++; } return [stacks.map((stack) => stack.reverse()), i + 1]; }; const readMovingLine = (line: string): [number, number, number] => { const [_1, amount, _2, from, _3, to] = line .split(" ") .map((s) => parseInt(s, 10)); return [amount, from, to]; }; const part1 = () => { let [stacks, index] = readStacks(); while (index < lines.length) { const [amount, from, to] = readMovingLine(lines[index]); for (let j = 0; j < amount; j++) { const item = stacks[from - 1].pop(); stacks[to - 1].push(item); } index++; } return stacks.map((stack) => stack[stack.length - 1]).join(""); }; const part2 = () => { let [stacks, index] = readStacks(); while (index < lines.length) { const [amount, from, to] = readMovingLine(lines[index]); let movingPart = []; for (let j = 0; j < amount; j++) { const item = stacks[from - 1].pop(); movingPart.push(item); } movingPart = movingPart.reverse(); stacks[to - 1] = [...stacks[to - 1], ...movingPart]; index++; } return stacks.map((stack) => stack[stack.length - 1]).join(""); }; console.log(part1()); console.log(part2());
""" Test environment with seven grid world. Agent are born at state 2, and the process terminate when choosing to move right at state 6. The reward function is very simple, each step will lead to reward -1. -------------------------------------- | 0 | 1 | 2 | 3 | 4 | terminal| -------------------------------------- The inital Q is randomly generated and we compare the result of Q-learning and double Q-learning """ import copy import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons colors = ['b', 'c', 'g', 'k', 'm', 'r', 'y', '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'] num_state = 5 def operatorT(Q, gamma): """ The corresponding operator T with grid world setting """ assert np.all(Q.shape==np.array([num_state, 2])) # [n_state, n_action] TQ = copy.deepcopy(Q) for s in np.arange(num_state-2)+1: TQ[s,0] = -1 + gamma * np.max(Q[s-1]) # Move left TQ[s,1] = -1 + gamma * np.max(Q[s+1]) # Move right TQ[0,0] = -1 + gamma * np.max(Q[0]) # Move left at state 0 will return to state 0 TQ[0,1] = -1 + gamma * np.max(Q[1]) TQ[num_state-1,0] = -1 + gamma * np.max(Q[num_state-2]) TQ[num_state-1,1] = -1 # Move right at state 6 terminate this process return TQ def main(): """ Value iteration method, directly apply T operator repeatedly to the vector Q """ # # Hyper paramters # T = 10 # gamma = 0.9 # # Update Q # Q = np.random.uniform(low=-10, high=0, size=[num_state,2]) # Q_history_value_iteration = np.zeros([T, Q.shape[0], Q.shape[1]]) # for t in range(T): # Q_history_value_iteration[t] = Q # Q_next = operatorT(Q, gamma) # Q = Q_next # # Plot lines # plt.figure() # for s in np.arange(num_state): # for a in [0,1]: # plt.plot(np.arange(T), Q_history_value_iteration[:, s, a], label="s{}-a{}".format(s, a)) # plt.legend(loc="upper right") # plt.show() # """ # Q-learning and double Q learning method without stochasticity # """ # Hyper paramters # T = 2000 # gamma = 0.9 # lr = 1e-2 # lr_soft_update = 0.1 # # Initialization # Q_init = np.random.uniform(low=-10, high=0, size=[num_state,2]) # Q_history_Q_learning = np.zeros([T, Q_init.shape[0], Q_init.shape[1]]) # Q_history_double_Q_learning = np.zeros([T, Q_init.shape[0], Q_init.shape[1]]) # # Q-learning # Q = copy.deepcopy(Q_init) # Q_d = copy.deepcopy(Q_init) # Q_target = copy.deepcopy(Q_init) # for t in range(T): # Q_history_Q_learning[t] = Q # Q_history_double_Q_learning[t] = Q_d # Q_next = operatorT(Q, gamma) # Q_next_d = operatorT(Q_target, gamma) # Q += lr * (Q_next - Q) # Q_d += lr * (Q_next_d - Q_d) # Q_target += lr_soft_update * (Q_d - Q_target) # # Plot lines # plt.figure(figsize=[14, 6]) # cnt = 0 # for s in np.arange(num_state): # for a in [0,1]: # plt.plot(np.arange(T), Q_history_Q_learning[:, s, a], color=colors[cnt], alpha=0.7, linestyle='-', label="s{}-a{}".format(s, a)) # plt.plot(np.arange(T), Q_history_double_Q_learning[:, s, a], color=colors[cnt], linestyle='-.') # cnt+= 1 # plt.title("Q-traj with Q-learning (linestyle '-') and double Q-learning (linestyle '-.')") # plt.legend(loc="upper right") # plt.show() """ Q-learning and double Q learning method with noise """ # Hyper paramters T = 5000 gamma = 0.9 lr = 5e-3 lr_soft_update = 5e-3 # Initialization Q_init = np.random.uniform(low=-10, high=0, size=[num_state,2]) Q_history_Q_learning = np.zeros([T, Q_init.shape[0], Q_init.shape[1]]) Q_history_double_Q_learning = np.zeros([T, Q_init.shape[0], Q_init.shape[1]]) # Q-learning Q = copy.deepcopy(Q_init) Q_d = copy.deepcopy(Q_init) Q_target = copy.deepcopy(Q_init) for t in range(T): noise = np.random.normal(loc=0, scale=2, size=Q.shape) Q_history_Q_learning[t] = Q Q_history_double_Q_learning[t] = Q_d Q_next = operatorT(Q, gamma) + noise Q_next_d = operatorT(Q_target, gamma) + noise Q += lr * (Q_next - Q) Q_d += lr * (Q_next_d - Q_d) Q_target += lr_soft_update * (Q_d - Q_target) # Plot lines fig = plt.figure(figsize=[16,10]) ax = fig.subplots() cnt = 0 lines = [] for s in np.arange(num_state): line_state = [] for a in [0,1]: p1 = ax.plot(np.arange(T), Q_history_Q_learning[:, s, a], color=colors[cnt], alpha=0.5, linestyle='-', label="s{}-a{}".format(s, a)) p2 = ax.plot(np.arange(T), Q_history_double_Q_learning[:, s, a], color=colors[cnt], linestyle=':') cnt+= 1 line_state.append([p1, p2]) lines.append(line_state) plt.title("Q-traj with Q-learning (linestyle '-') and double Q-learning (linestyle '.')") plt.legend(loc="upper right") labels = ["s0", "s1", "s2", "s3", "s4"] def func(label): index = labels.index(label) # print(lines[index][1]) lines[index][0][0][0].set_visible(not lines[index][0][0][0].get_visible()) lines[index][0][1][0].set_visible(not lines[index][0][1][0].get_visible()) lines[index][1][0][0].set_visible(not lines[index][1][0][0].get_visible()) lines[index][1][1][0].set_visible(not lines[index][1][1][0].get_visible()) fig.canvas.draw() # Matplotlib check buttons label = [True, True, True, True, True] ax_check = plt.axes([0.9, 0.001, 0.2, 0.3]) plot_button = CheckButtons(ax_check, labels, label) plot_button.on_clicked(func) plt.show()
/* Copyright (c) 2016 Thomas Pornin <pornin@bolet.org> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "inner.h" /* Each entry consists in a fixed number of bytes. Entries are concatenated in the store block. "Addresses" are really offsets in the block, expressed over 32 bits (so the cache may have size at most 4 GB, which "ought to be enough for everyone"). The "null address" is 0xFFFFFFFF. Note that since the storage block alignment is in no way guaranteed, we perform only accesses that can handle unaligned data. Two concurrent data structures are maintained: -- Entries are organised in a doubly-linked list; saved entries are added at the head, and loaded entries are moved to the head. Eviction uses the list tail (this is the LRU algorithm). -- Entries are indexed with a binary tree: all left descendants of a node have a lower session ID (in lexicographic order), while all right descendants have a higher session ID. The tree is heuristically balanced. Entry format: session ID 32 bytes master secret 48 bytes protocol version 2 bytes (big endian) cipher suite 2 bytes (big endian) list prev 4 bytes (big endian) list next 4 bytes (big endian) tree left child 4 bytes (big endian) tree right child 4 bytes (big endian) If an entry has a protocol version set to 0, then it is "disabled": it was a session pushed to the cache at some point, but it has been explicitly removed. We need to keep the tree balanced because an attacker could make handshakes, selecting some specific sessions (by reusing them) to try to make us make an imbalanced tree that makes lookups expensive (a denial-of-service attack that would persist as long as the cache remains, i.e. even after the attacker made all his connections). To do that, we replace the session ID (or the start of the session ID) with a HMAC value computed over the replaced part; the hash function implementation and the key are obtained from the server context upon first save() call. Theoretically, an attacker could use the exact timing of the lookup to infer the current tree topology, and try to revive entries to make it as unbalanced as possible. However, since the session ID are chosen randomly by the server, and the attacker cannot see the indexing values and must thus rely on blind selection, it should be exponentially difficult for the attacker to maintain a large imbalance. */ #define SESSION_ID_LEN 32 #define MASTER_SECRET_LEN 48 #define SESSION_ID_OFF 0 #define MASTER_SECRET_OFF 32 #define VERSION_OFF 80 #define CIPHER_SUITE_OFF 82 #define LIST_PREV_OFF 84 #define LIST_NEXT_OFF 88 #define TREE_LEFT_OFF 92 #define TREE_RIGHT_OFF 96 #define LRU_ENTRY_LEN 100 #define ADDR_NULL ((uint32_t)-1) #define GETSET(name, off) \ static inline uint32_t get_ ## name(br_ssl_session_cache_lru *cc, uint32_t x) \ { \ return br_dec32be(cc->store + x + (off)); \ } \ static inline void set_ ## name(br_ssl_session_cache_lru *cc, \ uint32_t x, uint32_t val) \ { \ br_enc32be(cc->store + x + (off), val); \ } GETSET(prev, LIST_PREV_OFF) GETSET(next, LIST_NEXT_OFF) GETSET(left, TREE_LEFT_OFF) GETSET(right, TREE_RIGHT_OFF) /* Transform the session ID by replacing the first N bytes with a HMAC value computed over these bytes, using the random key K (the HMAC value is truncated if needed). HMAC will use the same hash function as the DRBG in the SSL server context, so with SHA-256, SHA-384, or SHA-1, depending on what is available. The risk of collision is considered too small to be a concern; and the impact of a collision is low (the handshake won't succeed). This risk is much lower than any transmission error, which would lead to the same consequences. Source and destination arrays msut be disjoint. */ static void mask_id(br_ssl_session_cache_lru *cc, const unsigned char *src, unsigned char *dst) { br_hmac_key_context hkc; br_hmac_context hc; memcpy(dst, src, SESSION_ID_LEN); br_hmac_key_init(&hkc, cc->hash, cc->index_key, sizeof cc->index_key); br_hmac_init(&hc, &hkc, SESSION_ID_LEN); br_hmac_update(&hc, src, SESSION_ID_LEN); br_hmac_out(&hc, dst); } /* Find a node by ID. Returned value is the node address, or ADDR_NULL if the node is not found. If addr_link is not NULL, then '*addr_link' is set to the address of the last followed link. If the found node is the root, or if the tree is empty, then '*addr_link' is set to ADDR_NULL. */ static uint32_t find_node(br_ssl_session_cache_lru *cc, const unsigned char *id, uint32_t *addr_link) { uint32_t x, y; x = cc->root; y = ADDR_NULL; while (x != ADDR_NULL) { int r; r = memcmp(id, cc->store + x + SESSION_ID_OFF, SESSION_ID_LEN); if (r < 0) { y = x + TREE_LEFT_OFF; x = get_left(cc, x); } else if (r == 0) { if (addr_link != NULL) { *addr_link = y; } return x; } else { y = x + TREE_RIGHT_OFF; x = get_right(cc, x); } } if (addr_link != NULL) { *addr_link = y; } return ADDR_NULL; } /* For node x, find its replacement upon removal. -- If node x has no child, then this returns ADDR_NULL. -- Otherwise, if node x has a left child, then the replacement is the rightmost left-descendent. -- Otherwise, the replacement is the leftmost right-descendent. If a node is returned, then '*al' is set to the address of the field that points to that node. Otherwise (node x has no child), '*al' is set to ADDR_NULL. Note that the replacement node, when found, is always a descendent of node 'x', so it cannot be the tree root. Thus, '*al' can be set to ADDR_NULL only when no node is found and ADDR_NULL is returned. */ static uint32_t find_replacement_node(br_ssl_session_cache_lru *cc, uint32_t x, uint32_t *al) { uint32_t y1, y2; y1 = get_left(cc, x); if (y1 != ADDR_NULL) { y2 = x + TREE_LEFT_OFF; for (;;) { uint32_t z; z = get_right(cc, y1); if (z == ADDR_NULL) { *al = y2; return y1; } y2 = y1 + TREE_RIGHT_OFF; y1 = z; } } y1 = get_right(cc, x); if (y1 != ADDR_NULL) { y2 = x + TREE_RIGHT_OFF; for (;;) { uint32_t z; z = get_left(cc, y1); if (z == ADDR_NULL) { *al = y2; return y1; } y2 = y1 + TREE_LEFT_OFF; y1 = z; } } *al = ADDR_NULL; return ADDR_NULL; } /* Set the link at address 'alx' to point to node 'x'. If 'alx' is ADDR_NULL, then this sets the tree root to 'x'. */ static inline void set_link(br_ssl_session_cache_lru *cc, uint32_t alx, uint32_t x) { if (alx == ADDR_NULL) { cc->root = x; } else { br_enc32be(cc->store + alx, x); } } /* Remove node 'x' from the tree. This function shall not be called if node 'x' is not part of the tree. */ static void remove_node(br_ssl_session_cache_lru *cc, uint32_t x) { uint32_t alx, y, aly; /* Removal algorithm: ------------------ - If we remove the root, then the tree becomes empty. - If the removed node has no child, then we can simply remove it, with nothing else to do. - Otherwise, the removed node must be replaced by either its rightmost left-descendent, or its leftmost right-descendent. The replacement node itself must be removed from its current place. By definition, that replacement node has either no child, or at most a single child that will replace it in the tree. */ /* Find node back and its ancestor link. If the node was the root, then alx is set to ADDR_NULL. */ find_node(cc, cc->store + x + SESSION_ID_OFF, &alx); /* Find replacement node 'y', and 'aly' is set to the address of the link to that replacement node. If the removed node has no child, then both 'y' and 'aly' are set to ADDR_NULL. */ y = find_replacement_node(cc, x, &aly); if (y != ADDR_NULL) { uint32_t z; /* The unlinked replacement node may have one child (but not two) that takes its place. */ z = get_left(cc, y); if (z == ADDR_NULL) { z = get_right(cc, y); } set_link(cc, aly, z); /* Link the replacement node in its new place, overwriting the current link to the node 'x' (which removes 'x'). */ set_link(cc, alx, y); /* The replacement node adopts the left and right children of the removed node. Note that this also works even if the replacement node was a direct descendent of the removed node, since we unlinked it previously. */ set_left(cc, y, get_left(cc, x)); set_right(cc, y, get_right(cc, x)); } else { /* No replacement, we simply unlink the node 'x'. */ set_link(cc, alx, ADDR_NULL); } } static void lru_save(const br_ssl_session_cache_class **ctx, br_ssl_server_context *server_ctx, const br_ssl_session_parameters *params) { br_ssl_session_cache_lru *cc; unsigned char id[SESSION_ID_LEN]; uint32_t x, alx; cc = (br_ssl_session_cache_lru *)ctx; /* If the buffer is too small, we don't record anything. This test avoids problems in subsequent code. */ if (cc->store_len < LRU_ENTRY_LEN) { return; } /* Upon the first save in a session cache instance, we obtain a random key for our indexing. */ if (!cc->init_done) { br_hmac_drbg_generate(&server_ctx->eng.rng, cc->index_key, sizeof cc->index_key); cc->hash = br_hmac_drbg_get_hash(&server_ctx->eng.rng); cc->init_done = 1; } mask_id(cc, params->session_id, id); /* Look for the node in the tree. If the same ID is already used, then reject it. This is a collision event, which should be exceedingly rare. Note: we do NOT record the emplacement here, because the removal of an entry may change the tree topology. */ if (find_node(cc, id, NULL) != ADDR_NULL) { return; } /* Find some room for the new parameters. If the cache is not full yet, add it to the end of the area and bump the pointer up. Otherwise, evict the list tail entry. Note that we already filtered out the case of a ridiculously small buffer that cannot hold any entry at all; thus, if there is no room for an extra entry, then the cache cannot be empty. */ if (cc->store_ptr > (cc->store_len - LRU_ENTRY_LEN)) { /* Evict tail. If the buffer has room for a single entry, then this may also be the head. */ x = cc->tail; cc->tail = get_prev(cc, x); if (cc->tail == ADDR_NULL) { cc->head = ADDR_NULL; } else { set_next(cc, cc->tail, ADDR_NULL); } /* Remove the node from the tree. */ remove_node(cc, x); } else { /* Allocate room for new node. */ x = cc->store_ptr; cc->store_ptr += LRU_ENTRY_LEN; } /* Find the emplacement for the new node, and link it. */ find_node(cc, id, &alx); set_link(cc, alx, x); set_left(cc, x, ADDR_NULL); set_right(cc, x, ADDR_NULL); /* New entry becomes new list head. It may also become the list tail if the cache was empty at that point. */ if (cc->head == ADDR_NULL) { cc->tail = x; } else { set_prev(cc, cc->head, x); } set_prev(cc, x, ADDR_NULL); set_next(cc, x, cc->head); cc->head = x; /* Fill data in the entry. */ memcpy(cc->store + x + SESSION_ID_OFF, id, SESSION_ID_LEN); memcpy(cc->store + x + MASTER_SECRET_OFF, params->master_secret, MASTER_SECRET_LEN); br_enc16be(cc->store + x + VERSION_OFF, params->version); br_enc16be(cc->store + x + CIPHER_SUITE_OFF, params->cipher_suite); } static int lru_load(const br_ssl_session_cache_class **ctx, br_ssl_server_context *server_ctx, br_ssl_session_parameters *params) { br_ssl_session_cache_lru *cc; unsigned char id[SESSION_ID_LEN]; uint32_t x; (void)server_ctx; cc = (br_ssl_session_cache_lru *)ctx; if (!cc->init_done) { return 0; } mask_id(cc, params->session_id, id); x = find_node(cc, id, NULL); if (x != ADDR_NULL) { unsigned version; version = br_dec16be(cc->store + x + VERSION_OFF); if (version == 0) { /* Entry is disabled, we pretend we did not find it. Notably, we don't move it to the front of the LRU list. */ return 0; } params->version = version; params->cipher_suite = br_dec16be( cc->store + x + CIPHER_SUITE_OFF); memcpy(params->master_secret, cc->store + x + MASTER_SECRET_OFF, MASTER_SECRET_LEN); if (x != cc->head) { /* Found node is not at list head, so move it to the head. */ uint32_t p, n; p = get_prev(cc, x); n = get_next(cc, x); set_next(cc, p, n); if (n == ADDR_NULL) { cc->tail = p; } else { set_prev(cc, n, p); } set_prev(cc, cc->head, x); set_next(cc, x, cc->head); set_prev(cc, x, ADDR_NULL); cc->head = x; } return 1; } return 0; } static const br_ssl_session_cache_class lru_class = { sizeof(br_ssl_session_cache_lru), &lru_save, &lru_load }; /* see inner.h */ void br_ssl_session_cache_lru_init(br_ssl_session_cache_lru *cc, unsigned char *store, size_t store_len) { cc->vtable = &lru_class; cc->store = store; cc->store_len = store_len; cc->store_ptr = 0; cc->init_done = 0; cc->head = ADDR_NULL; cc->tail = ADDR_NULL; cc->root = ADDR_NULL; } /* see bearssl_ssl.h */ void br_ssl_session_cache_lru_forget( br_ssl_session_cache_lru *cc, const unsigned char *id) { unsigned char mid[SESSION_ID_LEN]; uint32_t addr; /* If the cache is not initialised yet, then it is empty, and there is nothing to forget. */ if (!cc->init_done) { return; } /* Look for the node in the tree. If found, the entry is marked as "disabled"; it will be reused in due course, as it ages through the list. We do not go through the complex moves of actually releasing the entry right away because explicitly forgetting sessions should be a rare event, meant mostly for testing purposes, so this is not worth the extra code size. */ mask_id(cc, id, mid); addr = find_node(cc, mid, NULL); if (addr != ADDR_NULL) { br_enc16be(cc->store + addr + VERSION_OFF, 0); } }
import { Alert, AlertDescription, AlertIcon, AlertProps, AlertTitle, Box, } from '@chakra-ui/react'; import React from 'react'; interface Props { children: React.ReactNode; title: string; alertProps?: AlertProps; status: AlertProps['status'] } export function BaseAlert({ children, title, alertProps, status, }: Props) { return ( <Alert variant="left-accent" status={status} {...alertProps} > <AlertIcon /> <Box> <AlertTitle>{title}</AlertTitle> <AlertDescription> {children} </AlertDescription> </Box> </Alert> ); }
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.0; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { IUserManager } from "../Interfaces.sol"; import { ZekeErrors } from '../libraries/ZekeErrors.sol'; contract UserManager is IUserManager, Ownable { mapping(address => uint256) public userId; event UserRegistered (uint256 indexed id, address indexed userAddress, string email); constructor(address _owner) Ownable(_owner) {} /** * VIEW FUNCTIONS */ function doesUserExist(address _userAddress) external view returns (bool) { return (userId[_userAddress] != 0); } function compareUserId(address _userAddress, uint256 id) external view returns(bool){ return (userId[_userAddress] == id); } /** * STATE-MUTATING FUNCTIONS */ function registerUser(address _userAddress, uint256 _userId, string calldata email) external onlyOwner { // ** INPUT VALIDATION ** // // add the proof verification part here if (_userAddress == address(0)) revert ZekeErrors.ZeroAddress(); if (_userId == 0) revert ZekeErrors.ZeroUint(); if (userId[_userAddress] != 0) revert ZekeErrors.UserAlreadyRegistered(); // ** UPDATE STATE ** // userId[_userAddress] = _userId; // ** EMIT EVENT ** // emit UserRegistered(_userId, _userAddress, email); } }
import imutils from imutils import perspective import cv2 import numpy as np import matplotlib.pyplot as plt from FCM import FCM import imageio from skull_mask import SkullMask from convert_2_rgb import Convert2RGB # import skfuzzy as fuzz import os from dotenv import load_dotenv load_dotenv() PATH2 = os.getenv("OUTPUT_PATH2") def blur_image(img): """ Applies a mean filter (5x5 kernel) to the input image. """ kernel = np.ones((5,5),np.float32)/25 blur = cv2.filter2D(img,-1,kernel) return blur def tumor_part(c): """ Checks if a contour represents a significant tumor region based on solidity and area criteria. """ area = cv2.contourArea(c) hull = cv2.convexHull(c) hull_area = cv2.contourArea(hull) if hull_area != 0: solidity = float(area)/hull_area else: solidity = 0 if solidity > 0.7 and area > 500: return True else: return False def threshold(img,b): """ Applies a binary threshold to the input image. """ ret,thresh = cv2.threshold(img,b,255,cv2.THRESH_BINARY) return thresh def RGB(img): """ Converts a grayscale image to RGB format. """ return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) def contours(img,org,b): """ Finds and draws contours on the input images based on thresholding and tumor region criteria. """ # img = RGB(img) img2 = threshold(img,b) # plt.imshow(img2) cnts = cv2.findContours(img2.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) img2 = RGB(img2) org = RGB(org) for (_,c) in enumerate(cnts): if tumor_part(c): cv2.drawContours(org, [c], -1, (1,255,11), 2) cv2.drawContours(img2, [c], -1, (1,255,11), 2) return (org, img2) def show_images(gray, blur, seg, cont_org, cont_mask): """ Displays a set of resized images for visualization. """ blur = cv2.resize(blur, (256, 256)) seg = cv2.resize(seg, (256, 256)) cont_org = cv2.resize(cont_org, (256, 256)) cont_mask = cv2.resize(cont_mask, (256, 256)) seg_gray = cv2.cvtColor(seg, cv2.COLOR_BGR2GRAY) res1 = np.hstack((blur,seg_gray)) res2 = np.hstack((cont_org,cont_mask)) output_img_path = os.path.join(PATH2, "output_2.png") new_file_path = f"{output_img_path}" cv2.imwrite(new_file_path, res2) def fcm(img, option): """ Applies Fuzzy C-means clustering to the input image. """ Z = img.reshape((-1, 1)) Z = np.float32(Z) fuzz = FCM(image = Z, image_bit = 8, n_clusters = 8, m = 2, epsilon = 0.01, max_iter = 100, option= option) u, cntr = fuzz.form_clusters() #Nếu để code thư viện np.dot thì bỏ reshape này if(option != 1): cntr = cntr.reshape((8,1)) print(f'{u.shape}, {cntr.shape}') labels = np.argmax(u, axis=1) center = np.uint8(cntr) res = center[labels] res2 = res.reshape(img.shape) return res2 def process(img3, b, option): """ Processes the input image by converting to grayscale, applying blur, segmentation, and contour detection. """ gray = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY) blur = blur_image(gray) seg = fcm(blur, option) plt.imshow(seg) cont_org, cont_mask = contours(seg, gray, b) # Convert 'result' to RGB for display seg = RGB(seg) gray = RGB(gray) show_images(gray, blur, seg, cont_org, cont_mask) def main(path, option): gray = imageio.v2.imread(rf".\img\{path}") sk_mask = SkullMask(gray) output = sk_mask.skull_strip() a = np.where(output == 1) x, y = a[0], a[1] for (i, j) in zip(x, y): gray[i][j] = 0 cv_2_rgb = Convert2RGB(gray) gray = cv_2_rgb.convert2RGB() process(img3=gray, b=130, option=option) output_img_path = os.path.join(PATH2, "output_2.png") new_file_path = f"{output_img_path}" return (new_file_path) # if __name__ == '__main__': # path = "1-127.dcm" # main(path, option=1)
#!/bin/bash shopt -s extglob function directoryExists() { [[ -d "$1" ]] } lengthExceeds() { local string="$1" local maxChars=20 if [[ "${#string}" -le "$maxChars" ]]; then return 1 # String length is within the allowed limit else echo "Input length exceeds the allowed limit of $maxChars characters." return 0 # String length exceeds the allowed limit fi } function createDB() { while true; do read -p "Enter database name (type "cancel" to cancel): " input if lengthExceeds $input; then continue fi input="${input// /_}" dirName="$1/${input}" if [ "$input" == "cancel" ];then break elif ! [[ "$input" =~ ^[a-zA-Z_][a-zA-Z0-9_]* ]]; then echo "Invalid name." elif directoryExists "$dirName"; then echo "Database already exists." elif [ "$input" = "exit" ]; then exit 0 else mkdir "$dirName" echo "Database '$input' created successfully." break fi done } function listDB() { ls -l "$1" | awk '/^d/ {print $NF}' } function connectDB() { read -p "Enter Database Name: " name # Check if name is empty if [ -z "$name" ]; then echo "Database name cannot be empty" return 1 # Failure fi name="${name// /_}" if directoryExists "$1/$name"; then echo "$name" return 0 # Success else echo "Database not found" return 1 # Failure fi } function dropDB() { read -p "Enter Database Name: " name name="${name// /_}" if directoryExists "$1/$name"; then read -p "Are you sure you want to delete '$name'? (y for yes, n for no): " confirm if [ "$confirm" = "y" ]; then rm -r "$1/$name" echo "Database '$name' deleted successfully." else echo "Deletion canceled." fi else echo "Database not found." fi } # Example usage: # createDB "~" # listDB "~" # dbName=$(connectDB "~") # dropDB "~"
// Copyright 2022 OnMetal authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" "fmt" storagev1alpha1 "github.com/onmetal/onmetal-api/api/storage/v1alpha1" ori "github.com/onmetal/onmetal-api/ori/apis/bucket/v1alpha1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/util/sets" "sigs.k8s.io/controller-runtime/pkg/client" ) func (s *Server) getTargetOnmetalBucketPools(ctx context.Context) ([]storagev1alpha1.BucketPool, error) { if s.bucketPoolName != "" { onmetalBucketPool := &storagev1alpha1.BucketPool{} onmetalBucketPoolKey := client.ObjectKey{Name: s.bucketPoolName} if err := s.client.Get(ctx, onmetalBucketPoolKey, onmetalBucketPool); err != nil { if !apierrors.IsNotFound(err) { return nil, fmt.Errorf("error getting bucket pool %s: %w", s.bucketPoolName, err) } return nil, nil } } bucketPoolList := &storagev1alpha1.BucketPoolList{} if err := s.client.List(ctx, bucketPoolList, client.MatchingLabels(s.bucketPoolSelector), ); err != nil { return nil, fmt.Errorf("error listing bucket pools: %w", err) } return bucketPoolList.Items, nil } func (s *Server) gatherAvailableBucketClassNames(onmetalBucketPools []storagev1alpha1.BucketPool) sets.Set[string] { res := sets.New[string]() for _, onmetalBucketPool := range onmetalBucketPools { for _, availableBucketClass := range onmetalBucketPool.Status.AvailableBucketClasses { res.Insert(availableBucketClass.Name) } } return res } func (s *Server) filterOnmetalBucketClasses( availableBucketClassNames sets.Set[string], bucketClasses []storagev1alpha1.BucketClass, ) []storagev1alpha1.BucketClass { var filtered []storagev1alpha1.BucketClass for _, bucketClass := range bucketClasses { if !availableBucketClassNames.Has(bucketClass.Name) { continue } filtered = append(filtered, bucketClass) } return filtered } func (s *Server) convertOnmetalBucketClass(bucketClass *storagev1alpha1.BucketClass) (*ori.BucketClass, error) { tps := bucketClass.Capabilities.TPS() iops := bucketClass.Capabilities.IOPS() return &ori.BucketClass{ Name: bucketClass.Name, Capabilities: &ori.BucketClassCapabilities{ Tps: tps.Value(), Iops: iops.Value(), }, }, nil } func (s *Server) ListBucketClasses(ctx context.Context, req *ori.ListBucketClassesRequest) (*ori.ListBucketClassesResponse, error) { log := s.loggerFrom(ctx) log.V(1).Info("Getting target onmetal bucket pools") onmetalBucketPools, err := s.getTargetOnmetalBucketPools(ctx) if err != nil { return nil, fmt.Errorf("error getting target onmetal bucket pools: %w", err) } log.V(1).Info("Gathering available bucket class names") availableOnmetalBucketClassNames := s.gatherAvailableBucketClassNames(onmetalBucketPools) if len(availableOnmetalBucketClassNames) == 0 { log.V(1).Info("No available bucket classes") return &ori.ListBucketClassesResponse{BucketClasses: []*ori.BucketClass{}}, nil } log.V(1).Info("Listing onmetal bucket classes") onmetalBucketClassList := &storagev1alpha1.BucketClassList{} if err := s.client.List(ctx, onmetalBucketClassList); err != nil { return nil, fmt.Errorf("error listing onmetal bucket classes: %w", err) } availableOnmetalBucketClasses := s.filterOnmetalBucketClasses(availableOnmetalBucketClassNames, onmetalBucketClassList.Items) bucketClasses := make([]*ori.BucketClass, 0, len(availableOnmetalBucketClasses)) for _, onmetalBucketClass := range availableOnmetalBucketClasses { bucketClass, err := s.convertOnmetalBucketClass(&onmetalBucketClass) if err != nil { return nil, fmt.Errorf("error converting onmetal bucket class %s: %w", onmetalBucketClass.Name, err) } bucketClasses = append(bucketClasses, bucketClass) } log.V(1).Info("Returning bucket classes") return &ori.ListBucketClassesResponse{ BucketClasses: bucketClasses, }, nil }
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import '../constants/app_defaults.dart'; import 'skelton/skelton.dart'; class NetworkImageWithLoader extends StatelessWidget { final BoxFit fit; const NetworkImageWithLoader( this.src, this.circular, { Key? key, this.fit = BoxFit.cover, this.radius = AppDefaults.radius, }) : super(key: key); final bool circular; final String src; final double radius; @override Widget build(BuildContext context) { return ClipRRect( borderRadius: BorderRadius.all(Radius.circular(circular ? radius : 0)), // borderRadius: // const BorderRadius.all(Radius.circular(AppDefaults.circular)), child: CachedNetworkImage( fit: fit, imageUrl: src, imageBuilder: (context, imageProvider) => Container( decoration: BoxDecoration( image: DecorationImage( image: imageProvider, fit: fit, ), ), ), placeholder: (context, url) => const Skeleton(), errorWidget: (context, url, error) => const Icon(Icons.error), ), ); } }
Mean, in statistics, is a measure of central tendency. It is calculated by adding up the values of all the observations in a dataset and dividing by the number of observations. It is also known as the arithmetic mean or simply the average. The mean is a useful measure of central tendency because it is easy to calculate and understand. It can also be used to compare different datasets. However, the mean can be sensitive to outliers, which are data points that are very different from the rest of the dataset. To calculate the mean, you need to follow these steps: 1. Add up the values of all the observations in the dataset. 2. Divide the sum by the number of observations. The formula for the mean is: ``` Mean = (Sum of all observations) / (Number of observations) ``` For example, the mean of the dataset {1, 2, 3, 4, 5} is 3. This is because the sum of the observations is 15 and there are 5 observations. The mean can be used to compare different datasets. For example, the mean income of a group of people can be compared to the mean income of another group of people. This can help to determine which group has a higher average income. The mean can also be used to identify outliers. An outlier is a data point that is very different from the rest of the dataset. Outliers can skew the mean, so it is important to identify them and remove them from the dataset before calculating the mean. The mean is a versatile measure of central tendency that can be used in a variety of statistical applications. It is a simple and easy-to-understand measure, but it is important to be aware of its limitations, such as its sensitivity to outliers. Here are some examples of how the mean can be used in statistics: * **Determine the typical value of a data set.** The mean is a good measure of central tendency to use when the data set is not normally distributed or when there are outliers. * **Identify the middle value of a data set.** The mean can be used to identify the middle value of a data set, which can be useful for understanding the distribution of the data. * **Compare two data sets.** The mean can be used to compare two data sets by finding the mean of each data set and then comparing the two means. * **Determine the impact of outliers.** The mean is not affected by outliers, so it can be used to determine the impact of outliers on a data set. Here are some examples of how the mean can be used in everyday life: * **Determine the average price of a gallon of gas.** The mean can be used to determine the average price of a gallon of gas by collecting data on the prices of gas from different gas stations and then dividing the sum of the prices by the number of gas stations. * **Determine the average age of students in a class.** The mean can be used to determine the average age of students in a class by collecting data on the ages of the students and then dividing the sum of the ages by the number of students. * **Determine the average income of people in a city.** The mean can be used to determine the average income of people in a city by collecting data on the incomes of people in the city and then dividing the sum of the incomes by the number of people. The mean is a versatile measure of central tendency that can be used in a variety of statistical applications. It is a simple and easy-to-understand measure, but it is important to be aware of its limitations, such as its sensitivity to outliers.
--- title: Typhoon category: [Teaching,Games] tags: [esl,game,stickyball] img_path: /assets/img/ image: typhoon-0.gif --- A typhoon is blustering its way around the whiteboard and your class is caught in the chaos! As sticky ball games go, on the spectrum from educational to just fun, this one skews way towards the latter. Sometimes it's nice to just have some silly diversion though. ## Materials - sticky ball - whiteboard - whiteboard markers ## How to play 1. Scattered around the board, draw some small targets, like pictures of your students students' faces. 1. Pick a random point on the board to be the starting point of the typhoon. 1. Students take turns throwing the sticky ball. Wherever the ball lands after a throw, the typhoon travels to that point in a straight line. Any faces (or whatever targets you drew) that the typhoon crosses are "out". 1. Let all of the students take one or two turns and see who makes it through the inclement weather unscathed. ## How to play (visual guide) ![Six student faces and one X are drawn on a whiteboard.](typhoon-1.gif) Draw a variety of students around the board and pick a place for the titular typhoon to start. ![A stickyball hits the top right.](typhoon-2.gif) A student throws a sticky ball to where they want to typhoon to travel. ![A line is drawn from the X to where the ball struck, crossing one student.](typhoon-3.gif) Draw a line from one typhoon position to the next. Every student that is cross by the line has been blown away by the typhoon! Then another student can throw the sticky ball. ![A line is drawn across to more students.](typhoon-4.gif) Yet more students are cast away to the Land of Oz! ## Variations - This is an excellent opportunity for students to show off their artistic skills by drawing the targets themselves. Save time by having several students draw at once. - Instead of a typhoon blowing away your poor students you could have a hungry hippo gobbling up fruit, a bumble bee pollinating a field of flowers, a trick-or-treater visiting haunted houses, etc. - This can easily turned into a team game. Targets belonging to a team can be drawn in a certain color. In the normal typhoon game the teams would try to blow away all of the other team's students. In the bumble bee variation the students try to get the bumble bee to visit all of their team's flowers first. - Another option for a team game is to have two types of typhoon instead of two types of target. Using the hungry hippo example above, each team could take turns moving their hippo around the board, trying the eat the most fruit. - Depending on what other rules you play with, you could include targets that must be avoided at the risk of suffering some penalty. - If you must integrate this game into your lesson you could have the students describe what's going to happen in the future before throwing ("The typhoon's going to blow away Max.") or describe the result after throwing ("The hippo ate a strawberry and a mango."). ## Considerations - This game is slower to set up and play than others, so make sure you have enough time. - In my example I drew a line following the typhoon's path, but you could just as easily use only your eraser. - It's easy to forget the typhoon's position, so have a way to keep track. I always leave a colorful magnet at the typhoon's current position. - All of the typical sticky ball considerations still apply.
<template> <div class="content-wrapper"> <!-- <div v-if="loader" class="page_loader"></div> --> <!-- Content Header (Page header) --> <div class="content-header" style="font-size:16px;"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">{{ $t('globalTrans.dashboard') }}</h1> </div><!-- /.col --> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="#">{{ $t('globalTrans.home') }}</a></li> <li class="breadcrumb-item active">{{ $t('globalTrans.dashboard') }}</li> </ol> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> <!-- Main content --> <section class="content"> <div class="container-fluid dashboard-card"> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-xl-3 col-md-3 col-sm-6 col-xs-12"> <div class="form-group"> <label for="start_date">{{ $t('globalTrans.startDate') }} </label> <input type="date" id="start_date" v-model="search.start_date" class="form-control" /> </div> </div> <div class="col-xl-3 col-md-3 col-sm-6 col-xs-12"> <div class="form-group"> <label for="end_date">{{ $t('globalTrans.endDate') }} </label> <input type="date" id="end_date" v-model="search.end_date" class="form-control" /> </div> </div> <div class="col-md-2"> <div class="form-group"> <button class="btn btn-info btn-sm" type="submit" @click.prevent="filterSummary" style="margin-top:30px;"><i class="fa fa-search"></i> Filter</button> </div> </div> </div> </div> <div class="card-body"> <b-overlay :show="loader"> <div class="row"> <div class="col-lg-12"> <h5>Today Summary : </h5> </div> </div> <div class="row"> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-info"> <div class="inner"> <router-link :to="'/order?date_parameter_id=2&&start_date='+ today +'&end_date='+ today +'&date_type_id=1'"> <p>{{ today_order }}</p> <p>Total Order</p> </router-link> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-info"> <div class="inner"> <p>{{ today_assign }}</p> <p>Total Assign</p> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-info"> <div class="inner"> <p>BDT {{ lastday_collection }}</p> <p>Lastday Collection</p> </div> </div> </div> </div> <div class="row mt-4"> <div class="col-lg-12"> <h5>Lastday Summary : </h5> </div> </div> <div class="row"> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-info"> <div class="inner"> <router-link :to="'/order?date_parameter_id=2&&start_date='+ yesterday +'&end_date='+ yesterday +'&date_type_id=2'"> <p>{{ lastday_order }}</p> <p>Total Order</p> </router-link> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-info"> <div class="inner"> <router-link :to="'/order?date_parameter_id=4&&start_date='+ yesterday +'&end_date='+ yesterday +'&date_type_id=2&status[]=6,10'"> <p>{{ lastday_successfull }}</p> <p>Total Successfull</p> </router-link> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-info"> <div class="inner"> <p>{{ lastday_on_way }}</p> <p>Total On Way</p> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-info"> <div class="inner"> <router-link :to="'/order?date_parameter_id=4&&start_date='+ yesterday +'&end_date='+ yesterday +'&date_type_id=2&status[]=9'"> <p>{{ lastday_cancel }}</p> <p>Total Cancel</p> </router-link> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-info"> <div class="inner"> <router-link :to="'/order?date_parameter_id=4&&start_date='+ yesterday +'&end_date='+ yesterday +'&date_type_id=2&status[]=7'"> <p>{{ lastday_reschedule }}</p> <p>Total Reschedule</p> </router-link> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-info"> <div class="inner"> <router-link :to="'/order?date_parameter_id=4&&start_date='+ yesterday +'&end_date='+ yesterday +'&date_type_id=2&status[]=8'"> <p>{{ lastday_return }}</p> <p>Total Return</p> </router-link> </div> </div> </div> </div> <div class="row mt-4"> <div class="col-lg-12"> <h5>Total Summary : </h5> </div> </div> <div class="row"> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-info"> <div class="inner"> <!-- <router-link :to="'/order?date_parameter_id=1'"> --> <p>{{ total_order }}</p> <p>Total Order</p> <!-- </router-link> --> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-warning"> <div class="inner"> <!-- <router-link :to="'/order?date_parameter_id=1&date_type_id=5&status[]=1'"> --> <p>{{ total_requesting }}</p> <p>Total Requesting</p> <!-- </router-link> --> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-success"> <div class="inner"> <!-- <router-link :to="'/order?date_parameter_id=1&date_type_id=5&status[]=3'"> --> <p>{{ total_accepted }}</p> <p>Total Accepted</p> <!-- </router-link> --> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-danger"> <div class="inner"> <!-- <router-link :to="'/order?date_parameter_id=1&date_type_id=5&status[]=8'"> --> <p>{{ total_return }}</p> <p>Total Return</p> <!-- </router-link> --> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-warning"> <div class="inner"> <!-- <router-link :to="'/order?date_parameter_id=1&date_type_id=5&status[]=7'"> --> <p>{{ total_reschedule }}</p> <p>Total Reschedule</p> <!-- </router-link> --> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-danger"> <div class="inner"> <!-- <router-link :to="'/order?date_parameter_id=1&date_type_id=5&status[]=9'"> --> <p>{{ total_cancel }}</p> <p>Total Cancel</p> <!-- </router-link> --> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-info"> <div class="inner"> <!-- <router-link :to="'/order?date_parameter_id=1&date_type_id=5&status[]=6'"> --> <p>{{ total_complete }}</p> <p>Total Complete</p> <!-- </router-link> --> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-success"> <div class="inner"> <!-- <router-link :to="'/order?date_parameter_id=1&date_type_id=5&status[]=10'"> --> <p>{{ total_partial_complete }}</p> <p>Total Partial Complete</p> <!-- </router-link> --> </div> </div> </div> </div> <div class="row mt-4"> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-success"> <div class="inner"> <p>BDT {{ total_order_amount }}</p> <p>Total Order Amount</p> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-success"> <div class="inner"> <p>BDT {{ total_collected_amount }}</p> <p>Total Collected Amount</p> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-success"> <div class="inner"> <p>BDT {{ total_cod }}</p> <p>Total COD</p> </div> </div> </div> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-success"> <div class="inner"> <p>BDT {{ total_area_charge }}</p> <p>Total Area Charge</p> </div> </div> </div> </div> <div class="row mt-4"> <div class="col-xl-3 col-lg-2 col-md-3 col-sm-6 col-xs-12"> <div class="small-box bg-success"> <div class="inner"> <p>BDT {{ total_weight_charge }}</p> <p>Total Weight Charge</p> </div> </div> </div> </div> </b-overlay> </div> </div> </div><!-- /.container-fluid --> </section> <!-- /.content --> </div> </template> <script> import config from '@/config' import moment from 'moment' export default { name:'Home', data() { return { yesterday: moment().subtract(1,'d').format('YYYY-MM-DD'), today: moment().format('YYYY-MM-DD'), loader: false, search : { start_date: '', end_date: '' }, today_order: 0, today_assign: 0, lastday_order: 0, lastday_on_way: 0, lastday_successfull: 0, lastday_cancel: 0, lastday_reschedule: 0, lastday_return: 0, lastday_collection: 0, total_order: 0, total_requesting: 0, total_accepted: 0, total_on_way: 0, total_return: 0, total_cancel: 0, total_reschedule: 0, total_complete: 0, total_partial_complete: 0, total_order_amount: 0, total_collected_amount: 0, total_cod: 0, total_area_charge: 0, total_weight_charge: 0 } }, created () { this.getOrderSummary() }, mounted () { window.Echo.channel('ChatChannel') .listen('Chat', (e) => { console.log('socket result = ', e); }) }, methods: { filterSummary () { this.getOrderSummary() }, getOrderSummary () { this.loader = true const params = this.search config.getData('/dashboard', params) .then((response) => { this.loader = false this.today_order = response.data.today_order this.today_assign = response.data.today_assign this.lastday_order = response.data.lastday_order this.lastday_on_way = response.data.lastday_on_way this.lastday_successfull = response.data.lastday_successfull this.lastday_cancel = response.data.lastday_cancel this.lastday_reschedule = response.data.lastday_reschedule this.lastday_return = response.data.lastday_return this.lastday_collection = response.data.lastday_collection this.total_order = response.data.total_order this.total_requesting = response.data.total_requesting this.total_accepted = response.data.total_accepted this.total_on_way = response.data.total_on_way this.total_return = response.data.total_return this.total_cancel = response.data.total_cancel this.total_reschedule = response.data.total_reschedule this.total_complete = response.data.total_complete this.total_partial_complete = response.data.total_partial_complete this.total_order_amount = response.data.total_order_amount this.total_collected_amount = response.data.total_collected_amount this.total_cod = response.data.total_cod this.total_area_charge = response.data.total_area_charge this.total_weight_charge = response.data.total_weight_charge }) .catch((error) => { console.log(error); }); } } } </script>
from fastapi import APIRouter, HTTPException, Response from dotenv import dotenv_values from fastapi import FastAPI, File, UploadFile from fastapi.responses import JSONResponse import boto3 from botocore.exceptions import NoCredentialsError, ClientError import logging from utils.util import generate_file_name, is_pdf import asyncio router = APIRouter() config = dotenv_values(".env") # Create an S3 client s3_client = boto3.client( 's3', aws_access_key_id=config["S3_ACCESS_KEY"], aws_secret_access_key=config["S3_SECRET_KEY"], region_name=config["S3_REGION"] ) # @router.post("/upload_s3/") # async def upload_file(file_obj: UploadFile = File(...)): # if not is_pdf(file_obj.filename): # raise HTTPException(status_code=400, detail="Only PDF files are allowed") # try: # # Upload the file to S3 # config = dotenv_values(".env") # S3_BUCKET_NAME = config["S3_BUCKET_NAME"] # folder_name = config["S3_UPLOAD_PDF_FOLDER"] # print(S3_BUCKET_NAME,folder_name,file_obj.file) # print("filename = ", file_name) # success = upload_file_to_bucket(file_obj.file, S3_BUCKET_NAME,folder_name, file_name) # print("Uploaded ", file_name, " to S3 bucket") # if success: # print("Uploaded ", file_name, " to S3 bucket") # s3_link = f"https://{S3_BUCKET_NAME}.s3.amazonaws.com/{folder_name}/{file_name}" # print("s3_link to access the file", s3_link) # return {"status": "Success", "message": "File uploaded successfully", "s3_link": s3_link} # else: # return {"status": "Failure", "error": "Some error occurred"} # except NoCredentialsError: # return {"status": "Failure", "error": "AWS credentials not found or invalid"} # except Exception as e: # print("------>",e) # return {"status": "Failure", "error": "Something went wrong"} @router.post("/upload_s3_2/") async def upload(file_obj: UploadFile = File(...) ): loop = asyncio.get_event_loop() # Use a thread pool to handle the synchronous S3 upload function t = await loop.run_in_executor( None, # None uses the default executor (ThreadPoolExecutor) upload_file_to_s3, file_obj.filename, file_obj.file, # Pass file content or a BytesIO object ) return t def upload_file_to_s3(filename, file_obj: UploadFile = File(...)): # filename, bucket_name, s3_folder, access_key, secret_key, region # Create an S3 client config = dotenv_values(".env") bucket_name = config["S3_BUCKET_NAME"] s3_folder = config["S3_UPLOAD_PDF_FOLDER"] access_key = config["S3_ACCESS_KEY"] secret_key = config["S3_SECRET_KEY"] region =config["S3_REGION"] s3 = boto3.client('s3', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region) s3_object_key = f"{s3_folder}/{filename}" print(s3_object_key) # Check if the file already exists in S3 try: s3.head_object(Bucket=bucket_name, Key=s3_object_key) print(f"File {filename} already exists in S3. Overwriting...") except s3.exceptions.ClientError as e: pass # We'll proceed to upload since the file doesn't exist # Upload the file-like object to S3 try: s3.upload_fileobj(file_obj, bucket_name, s3_object_key) print(f"File {filename} uploaded successfully to S3: s3://{bucket_name}/{s3_object_key}") return JSONResponse(content={"status": "Success", "message": f" file upload successful."}, status_code=200) except Exception as upload_error: print(f"Error uploading file {filename} to S3: {upload_error}") return JSONResponse(content={"status": "Failure", "message": f"Failed to upload file"}, status_code=400)
<style lang="less"> .tPolicyNews { .ivu-modal { width: 800px !important; top: 50%; transform: translateY(-50%); } .imgWrap:hover .shadow { display: block; z-index: 3; width: 100%; } .ivu-date-picker .ivu-select-dropdown { width: auto; padding: 0; overflow: visible; max-height: none; z-index: 20000; } .ivu-form-item { width: 100%; margin-bottom: 25px!important; } .ivu-input-wrapper { width: auto !important; } .myWangEditor { margin-left: 0px; width: 605px; .w-e-text{ min-height: 300px; } } .myWangEditorDiv { width: calc(100% - 159px); position: absolute; left: 110px; height: 300px; } .myWangEditorLabel { width: 110px; position: absolute; left: 0px; text-align: right; padding: 10px 12px 10px 0; } } </style> <template> <Modal v-model="show" :title="editTitle" :mask-closable="false" class="tPolicyNews"> <Form ref="tPolicyNewsForm" :model="tPolicyNewsForm" :rules="tPolicyNewsFormRule" :label-width="90"> <Row> <Col span="12"> <FormItem label="新闻类型" prop="type"> <Select v-bind:disabled="disabled" v-model="tPolicyNewsForm.type" placeholder="请选择" style="width: 211px!important;" transfer> <Option v-for="(item, i) in typeData" :key="i" :value="item.number">{{ item.name }} </Option> </Select> </FormItem> </Col> <Col span="12"><FormItem label="是否隐藏" prop="isShow"> <RadioGroup v-model="tPolicyNewsForm.isShow"> <Radio v-bind:disabled="disabled" :label="'0'">是</Radio> <Radio v-bind:disabled="disabled" :label="'1'">否</Radio> </RadioGroup> </FormItem> </Col> </Row> <Row> <Col span="12"> <FormItem label="新闻标题" prop="name"> <Input v-bind:disabled="disabled" style="width: 211px!important;" type="text" :maxlength=50 v-model="tPolicyNewsForm.name" placeholder="请输入新闻标题"/> </FormItem> </Col> <Col span="12"> <FormItem label="发布单位" prop="issuedBy"> <Input v-model="tPolicyNewsForm.issuedBy" v-bind:disabled="disabled" style="width: 211px!important;" type="text" placeholder="请输入发布单位"></Input> </FormItem> </Col> </Row> <Row> <Col span="12"> <FormItem label="发布日期" prop="createTimeTime"> <DatePicker v-bind:disabled="disabled" style="width: 100%;" type="datetime" placeholder="请输入发布日期" v-model="tPolicyNewsForm.createTimeTime " @on-change="setCreateTime" format="yyyy-MM-dd HH:mm:ss"></DatePicker> </FormItem> </Col> </Row> <Row> <Col span="24"> <FormItem label="发布内容"> <!-- 富文本--> <myWangEditor :editorContent="tPolicyNewsForm.content" ref="myWangEditor"></myWangEditor> </FormItem> </Col> </Row> </Form> <div slot="footer"> <Button type="text" @click="show=false">取消</Button> <Button type="primary" :loading="loading" @click="handelSubmit">提交</Button> </div> </Modal> </template> <script> import { addTPolicyNews, getTPolicyNews, updateTPolicyNews } from '@/api/zhsq/tPolicyNews/tPolicyNews' import {formartDate} from '@/api/tools/tool' import myWangEditor from "../../zhsq/components/myWangEditor"; import { getDictionary, } from '@/api/index'; import uploadHeaderImg from '@/components/uploadHeaderImg' export default { name: "updateTPolicyNews", components: { myWangEditor, uploadHeaderImg }, props: { value: { type: Boolean, default: false }, TPolicyNewsId: { type: String }, modalTitle: { type: String } }, data() { return { show: this.value, editTitle: this.modalTitle, loading: true, disabled: false, //编辑表单 tPolicyNewsForm: { type: '', isShow: '', name: '', imgUrl: '', createTime: '', issuedBy: '', content: '' }, typeData:[],//公告类型集 tPolicyNewsFormRule: this.getTPolicyNewsFormRule() } }, methods: { setCreateTime(e) { this.tPolicyNewsForm.createTime = e; }, getTypeData(){ let _this = this; //政策新闻类型 getDictionary({fieldName: 'policy_news_type'}).then(resp => { if (resp && resp.success) { _this.typeData = resp.data; /*let temp = resp.data.filter(item => item.number == res.data.type); _this.data.typeName = temp[0].name;*/ } }); }, handelSubmit() { this.$refs['tPolicyNewsForm'].validate((valid) => { this.loading = true; if (valid) { let editorContent = this.$refs.myWangEditor.getEditorData(); this.tPolicyNewsForm.content = editorContent; if (this.TPolicyNewsId != null && this.TPolicyNewsId.trim().length > 0) { this.tPolicyNewsForm.id = this.TPolicyNewsId; updateTPolicyNews(this.tPolicyNewsForm).then(res => { this.loading = false; if (res) { if (res.code == 200) { this.closeModal(false); this.$emit('handleSearch'); this.$Message.success('保存成功'); } else { this.$Message.error(res.msg); } } else { this.$Message.error('保存失败'); } }).catch(err => { this.loading = false; }); } else { addTPolicyNews(this.tPolicyNewsForm).then(res => { this.loading = false; if (res) { if (res.code == 200) { this.closeModal(false); this.$emit('handleSearch'); this.$Message.success('保存成功'); } else { this.$Message.error(res.msg); } } else { this.$Message.error('保存失败'); } }).catch(err => { this.loading = false; }); } } else { this.loading = false; this.$Message.error('表单验证不通过!'); } }); }, onFileUploadSuccess(res, file) { this.tPolicyNewsForm.imgUrl = res.data; }, onFileUploadError(file) { this.$Message.error('图片上传失败!'); }, onRemovePath() { this.tPolicyNewsForm.imgUrl = ''; }, closeModal(val) { this.$emit('input', val); }, initForm() { this.tPolicyNewsForm = { type: '', isShow: '1', name: '', imgUrl: '', createTimeTime: '', createTime: '', issuedBy: '', content: '' }; }, getTPolicyNewsFormRule() { return { type: [ {required: true, message: '公告类型不能为空!', trigger: 'blur'}, {type: 'string', max: 50, message: '数据的最大长度为50!', trigger: 'blur'} ], isShow: [ {required: true, message: '是否隐藏不能为空!', trigger: 'blur', pattern: /.+/}, ], name: [ {required: true, message: '公告标题不能为空!', trigger: 'blur'}, {type: 'string', max: 50, message: '数据的最大长度为50!', trigger: 'blur'} ], createTimeTime: [ {required: true, message: '发布日期不能为空!', trigger: 'blur', pattern: /.+/}, ], issuedBy: [ {required: true, message: '发布单位不能为空!', trigger: 'blur'}, {type: 'string', max: 50, message: '数据的最大长度为50!', trigger: 'blur'} ], } } }, watch: { value(val) { this.show = val; }, show(val) { this.initForm(); this.getTypeData(); this.loading = false; this.editTitle = this.modalTitle; if (this.editTitle == "查看") { this.disabled = true; } else { this.disabled = false; } if (val) { this.$refs['tPolicyNewsForm'].resetFields(); if (this.TPolicyNewsId != null && this.TPolicyNewsId.trim().length > 0) { getTPolicyNews({id: this.TPolicyNewsId}).then(res => { if (res) { if (res.code === 200) { this.tPolicyNewsForm.type = res.data.type.toString(); this.tPolicyNewsForm.isShow = res.data.isShow; this.tPolicyNewsForm.name = res.data.name; this.tPolicyNewsForm.content = res.data.content; if (res.data.createTime !== '') { this.tPolicyNewsForm.createTimeTime = formartDate(new Date(res.data.createTime).getTime(), 'yyyy-MM-dd hh:mm:ss'); this.tPolicyNewsForm.createTime = formartDate(new Date(res.data.createTime).getTime(), 'yyyy-MM-dd hh:mm:ss'); } this.tPolicyNewsForm.issuedBy = res.data.issuedBy; if(res.data.imgUrl && res.data.imgUrl != '' && res.data.imgUrl != null){ this.tPolicyNewsForm.imgUrl = res.data.imgUrl; }else {//占位图 this.tPolicyNewsForm.imgUrl = '/img/tx_wzp2.png'; } } else { this.$Message.error(res.msg); } } else { this.$Message.error(res.msg); } }); } } else { this.closeModal(val); } } } } </script>