text
stringlengths
184
4.48M
# Databricks notebook source from packages.utils import utils import json import os import pandas as pd import numpy as np from datetime import datetime, timedelta, date import seaborn as sns import matplotlib.pyplot as plt import plotly.express as px import gradio as gr config = utils.read_json("./config.json") data_version = config["data_version"]["value"] cutoff_date = config["cutoff_date"]["value"] stats = utils.read_json("./stats.json") customer_data_path = f"DATA_VERSIONS/{data_version}/CUSTOMER_DATA" before_cutoff_path = f"DATA_VERSIONS/{data_version}/BEFORE_CUTOFF_RAW" recommendation_data_path = f"DATA_VERSIONS/{data_version}/RECOMMENDATION_DATA" propensity_data_path = f"DATA_VERSIONS/{data_version}/PROPENSITY_DATA" prediction_data_path = f"DATA_VERSIONS/{data_version}/PREDICTION_DATA" after_cutoff_path = f"DATA_VERSIONS/{data_version}/AFTER_CUTOFF_RAW" customers = utils.read_parquet(f"{customer_data_path}/customer_details.parquet") CPL = utils.read_parquet(f"{before_cutoff_path}/curated_products_data.parquet") AFTER_CUTOFF_CSD = utils.read_parquet(f'{after_cutoff_path}/customer_sales_data.parquet') recommendation_model = utils.read_pkl(f"{recommendation_data_path}/recommendation_model.pkl") propensity_model = utils.read_pkl(f"{propensity_data_path}/propensity_model.pkl") prediction_model = utils.read_pkl(f"{prediction_data_path}/prediction_model.pkl") # COMMAND ---------- product_list = sorted(CPL["updated"].unique()) customers_list = sorted(customers["customer_num"].unique()) # COMMAND ---------- def get_name(customer_num): if customer_num in list(customers["customer_num"]): return customers[customers["customer_num"] == customer_num][ "customer_name" ].values[0] else: return "No name found in record" def get_recommendation(customer_num, top, remark, replacement, curated=True): name = get_name(customer_num) output = recommendation_model.recommend_with_remark(customer_num, top, remark, replacement, curated) if not remark: output = output.drop(["Remark","History"],axis=1) output["Rating"] = (output["Rating"]*10000).astype("int")/10000 return name, output def get_propensity(customer_num, srp_2_list): name = get_name(customer_num) output1 = propensity_model.predict_from_lists_with_remark([customer_num], [srp_2_list]) remark = output1["Remark"].values[0] history = output1["History"].values[0] win_prob = int(100*prediction_model.predict_from_lists([customer_num], [srp_2_list],probability=True)['outcome'].values[0])/100 if win_prob<0.5: remark = "" return name,remark,history,{"Win Probability" :win_prob} def location_plot(locations): if ("Any" in locations) or (locations==[]): data = ALS_test else: data = ALS_test[ALS_test["location"].isin(locations)] data.rename(columns={"reciprocal_rank":"mrr"},inplace=True) fig1 = px.histogram( data, x="rank", nbins=len(set(ALS_test["rank"])), color="location" ) fig1.update_layout( autosize=False, width=600, height=300, xaxis_title="Rank", yaxis_title="No. of sales", legend_title="Location" ) data2 = data.groupby("location")[["mrr"]].mean().sort_values("mrr",ascending=False).reset_index() fig2 = px.bar(data2,x="location",y="mrr",color="location") fig2.update_layout( autosize=False, width=600, height=300, xaxis_title="Location", yaxis_title="MRR", legend_title="Location" ) mean = round(data["mrr"].mean(),4) return mean,fig1,fig2 # COMMAND ---------- ALS_test = recommendation_model.mrr_score(AFTER_CUTOFF_CSD) # COMMAND ---------- def blockPrint(): sys.stdout = open(os.devnull, 'w') blockPrint() with gr.Blocks(theme=gr.themes.Default()) as demo: with gr.Tab("Recommendation Model"): with gr.Row(): with gr.Column(): rm_customer_num = gr.Textbox(label="Customer number", value="606053") rm_top = gr.Slider(1, 20, step=1, value=10, label="No. of recommendations") with gr.Row(): rm_remark = gr.Checkbox(label="Remark", value=True) rm_replacement = gr.Checkbox(label="Replacement", value=True) # rm_curated = gr.Checkbox(label="Curated", value=True) with gr.Row(): recommend_button = gr.Button("Recommend") with gr.Row(): gr.Markdown() with gr.Column(): rm_customer_name = gr.Textbox(label="Customer name") recommend_output = gr.DataFrame(interactive=False, label="Recommendation") rm_inputs = [rm_customer_num, rm_top, rm_remark, rm_replacement] rm_outputs = [rm_customer_name,recommend_output] recommend_button.click(fn=get_recommendation, inputs=rm_inputs, outputs=rm_outputs) with gr.Tab("Recommendation Stats"): with gr.Row(): gr.Markdown(f"Train Size : **{stats['prediction train shape']['value'][0]}**") gr.Markdown(f"Test Size : **{len(ALS_test)}**") gr.Markdown(f"Cut-off Date : **{cutoff_date}**") with gr.Row(): gr.Markdown(f"Recommendable Customers : **{stats['recommendable customers']['value']}**") gr.Markdown(f"Recommendable Clusters : **{stats['recommendable clusters']['value']}**") gr.Markdown(f"Total Clusters : **{stats['customer clustering n clusters']['value']}**") with gr.Row(): rs_location = gr.Dropdown( ["Any"] + sorted(ALS_test["location"].unique()), value="Any", label="Location", multiselect=True, ) rs_button = gr.Button("Get Metrics") with gr.Row(): mrr_location = gr.Textbox(label="Mean Reciprocal Rank (MRR)") with gr.Row(): rank_plot = gr.Plot(label="Rank Histogram",show_label=False) mrr_plot = gr.Plot(label="Location wise MRR",show_label=False) rs_inputs = [rs_location] rs_outputs = [mrr_location,rank_plot,mrr_plot] rs_button.click(fn=location_plot, inputs=rs_inputs, outputs=rs_outputs) with gr.Tab("Propensity Model"): with gr.Row(): pr_customer_num = gr.Textbox(label="Customer number", value="606053") pr_srp_2_desc = gr.Dropdown(product_list, label="Product name", value="PROGRESSA", multiselect=False) with gr.Row(): propensity_button = gr.Button("Predict") with gr.Row(): pm_customer_name = gr.Textbox(label="Customer name") remark = gr.Textbox(label="Remark") probability = gr.Label(label="Probability") history = gr.Textbox(label="History") pr_inputs = [pr_customer_num, pr_srp_2_desc] pr_outputs = [pm_customer_name,remark,history,probability] propensity_button.click(fn=get_propensity, inputs=pr_inputs, outputs=pr_outputs) with gr.Tab("Propensity Stats"): with gr.Row(): gr.Markdown(f"Train Size : **{(stats['propensity train shape']['value'][0])}**") gr.Markdown(f"Test Size : **{(stats['propensity test shape']['value'][0])}**") gr.Markdown(f"Cutoff Date : **{cutoff_date}**") with gr.Row(): gr.Markdown(f"Precision : **{round(stats['propensity report']['value']['0']['precision'],2)}**") gr.Markdown(f"Recall : **{round(stats['propensity report']['value']['0']['recall'],2)}**") gr.Markdown(f"F1 Score : **{round(stats['propensity report']['value']['0']['f1-score'],2)}**") with gr.Row(): confusion_plot = px.imshow(stats['propensity confusion']["value"],text_auto=True,color_continuous_scale='Viridis') confusion_plot.update_layout(autosize=False,width=1220,height=300,xaxis_showticklabels=False,yaxis_showticklabels=False) gr.Plot(label="Confusion Matrix",value=confusion_plot,show_label=False) demo.launch(share=True,height=800)
import React, { useEffect } from 'react' import { LinkContainer } from 'react-router-bootstrap' import { Table, Button, Row, Col } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' import Message from '../components/Message' import Loader from '../components/Loader' import { listOrders } from '../actions/orderActions' // import { PRODUCT_CREATE_RESET } from '../constants/productConstants' const OrderListScreen = ({ history, match }) => { const dispatch = useDispatch() const orderList = useSelector((state) => state.orderList) const { loading, error, orders } = orderList // const productDelete = useSelector((state) => state.productDelete) // const { loading: loadingDelete, error: errorDelete } = productDelete // const productCreate = useSelector((state) => state.productCreate) // const { // loading: loadingCreate, // error: errorCreate, // success: successCreate, // product: createdProduct, // } = productCreate const userLogin = useSelector((state) => state.userLogin) const { userInfo } = userLogin useEffect(() => { if (!userInfo.isAdmin) { history.push('/login') } else { dispatch(listOrders()) } // dispatch({ type: PRODUCT_CREATE_RESET }) }, [dispatch, history, userInfo]) // const deleteHandler = (id) => { // if (window.confirm('Are you sure')) { // dispatch(deleteProduct(id)) // } // } // const createProductHandler = () => { // dispatch(createProduct()) // } return ( <> <Row className='align-items-center'> <Col> <h1>Orders</h1> </Col> </Row> {loading ? ( <Loader loaderHeight={'50px'} loaderWidth={'50px'} /> ) : error ? ( <Message variant='danger'>{error}</Message> ) : ( <Table striped bordered hover responsive className='table-sm'> <thead> <tr> <th>ID</th> <th>USER</th> <th>DATE</th> <th>TOTAL </th> <th>Paid</th> <th>Delivered</th> <th>VIEW</th> </tr> </thead> <tbody> {orders.map((order) => ( <tr key={order._id}> <td>{order._id}</td> <td>{order.user && order.user.name}</td> <td>{order.createdAt.substring(0, 10)}</td> <td>${order.totalPrice}</td> <td> {order.isPaid ? ( order.paidAt.substring(0, 10) ) : ( <i className='fas fa-times' style={{ color: 'red' }}></i> )} </td> <td> {order.isDelivered ? ( order.deliveredAt.substring(0, 10) ) : ( <i className='fas fa-times' style={{ color: 'red' }}></i> )} </td> <td> <LinkContainer to={`/order/${order._id}`}> <Button variant='light' className='btn-sm br-6'> Details </Button> </LinkContainer> {/* <Button variant='danger' className='btn-sm' onClick={() => deleteHandler(order._id)}> <i className='fas fa-trash'></i> </Button> */} </td> </tr> ))} </tbody> </Table> )} </> ) } export default OrderListScreen
不仅for循环语句的圆括号被精简掉了,while和do..while都被合并到了for里 for循环有4种写法 1、for inition; condition; expression{...} //即以前的for(inition; condition; expression){} 2、for condition{} //即以前的while(condition){} 3、for{...} //即以前的 for(;;){} 或while(true){} 这种合并和精简很有道理,因为for完全可以实现任何形式的循环,在c语言里,while也很多余。 4、循环基本都是为了处理各种数据结构,range工具可以方便地迭代数组、字符串、map等,再也不用数组下标满天飞了 for idx,ch:= range "dingxin"{ fmt.Println(idx,ch) } 但注意,这玩意处理非ascii字符会有问题: for idx, ch := range "丁鑫" { fmt.Println(idx, (ch)) } //输出 0 19969 3 37995 for idx, ch := range "丁鑫" { fmt.Println(idx, string(ch)) } //输出 0 丁 3 鑫 break、continue用法未变
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>FigmaLand</title> <link rel="shortcut icon" href="img/figmaland.ico" type="image/x-icon"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> <link rel="stylesheet" href="css/index.css"> </head> <body> <header class="header"> <nav class="navbar navbar-expand-lg"> <div class="container header__nav"> <div class ="header__social social"> <a class ="social-item" href="#"><img class ="social-twitter" src="img/ico-twitter.png" alt="Twitter"></a> <a class ="social-item" href="#"><img class ="social-facebook" src="img/ico-facebook.png" alt="Facebook"></a> <a class ="social-item" href="#"><img class ="social-instagram" src="img/ico-instagram.png" alt="Instagram"></a> </div> <a class="navbar-brand" href="#"><img class="header__logo" src="img/logo.png" alt="Figma Land"></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav "> <a class="nav-link header__menu-item" aria-current="page" href="#">Home</a> <a class="nav-link header__menu-item" href="#">Product</a> <a class="nav-link header__menu-item" href="#">Pricing</a> <a class="nav-link header__menu-item" href="#">About</a> <a class="nav-link header__menu-item" href="#">Contact</a> </div> </div> </div> </nav> <h1 class="header__title">The best products start with Figma</h1> <p class="header__description">Most calendars are designed for teams. <span>Slate is designed for freelancers</span></p> <a class="button" href="#">Try For Free</a> </header> <main class="main"> <section class ="feature"> <h2 class="feature__title title">Features</h2> <p class="feature__description description"> Most calendars are designed for teams. <span>Slate is designed for freelancers</span> </p> <div class="feature__container-small"><video class="feature__video-small" src="video.mp4" controls></video></div> <div class="feature__items"> <article class="feature__item article"> <img class ="feature__item-figures article-image" src="img/icon-figures.png" alt="figures"> <h3 class="feature__item-title">OpenType features Variable fonts</h3> <p class="feature__item-description">Slate helps you see how many more days you need to work to reach your financial goal.</p> </article> <article class="feature__item"> <img class ="feature__item-pencil article-image" src="img/icon-pencil.png" alt="pencil"> <h3 class="feature__item-title">Design with real data</h3> <p class="feature__item-description">Slate helps you see how many more days you need to work to reach your financial goal.</p> </article> <article class="feature__item"> <img class ="feature__item-tassel article-image" src="img/icon-tassel.png" alt="tassel"> <h3 class="feature__item-title">Fastest way to take action</h3> <p class="feature__item-description">Slate helps you see how many more days you need to work to reach your financial goal.</p> </article> </div> <div class="feature__container-main"><video class="feature__video-main" src="video.mp4" controls></video></div> </section> <section class="product"> <div class ="product__info"> <h2 class="product__title title">Fastest way to organize</h2> <p class="product__description description">Most calendars are designed for teams. Slate is designed for freelancers</p> <a class="button" href="#">Try For Free</a> </div> <div class="product__image"><img src="img/computer.png" alt="computer"></div> </section> <section class ="newsletter"> <p class="newsletter__subtitle">At your fingertips</p> <h2 class="newsletter__title title">Newsletter</h2> <p class="newsletter__description description">Most calendars are designed for teams. Slate is designed for freelancers</p> <div class="newsletter__image"><img src="img/man-letter.png" alt="man and letter"></div> <div class="newsletter__block"> <p class="newsletter__subtitle-alt">At your fingertips</p> <h2 class="newsletter__title-alt title">Lightning fast prototyping</h2> <form class="newsletter__form" action="/submit" method="POST"> <label class="newsletter__form-label" for="email">Subscribe to our Newsletter</label> <p class="newsletter__form-intro">Available exclusivery on Figmaland</p> <div class ="newsletter__form-container"> <input class ="newsletter__form-input" type="email" id="email" name="email" placeholder="Your Email" onfocus="this.placeholder=''" onblur="this.placeholder='Your Email'"> <button class ="newsletter__form-button button" type="submit">Subscribe</button> </div> </form> </div> </section> <section class ="partners"> <h2 class="partners__title title">Partners</h2> <p class="partners__description description">Most calendars are designed for teams.<br> Slate is designed for freelancers</p> <ul class="partners__list"> <li class="partners__list-logo"><img src="img/logo-google.png" alt="Client logo Google"></li> <li class="partners__list-logo"><img src="img/logo-amazon.png" alt="Client logo Amazon"></li> <li class="partners__list-logo"><img src="img/logo-microsoft.png" alt="Client logo Microsoft"></li> <li class="partners__list-logo"><img src="img/logo-uber.png" alt="Client logo Uber"></li> <li class="partners__list-logo"><img src="img/logo-dropbox.png" alt="Client logo Dropbox"></li> <li class="partners__list-logo"><img src="img/logo-google.png" alt="Client logo Google"></li> <li class="partners__list-logo"><img src="img/logo-uber.png" alt="Client logo Uber"></li> <li class="partners__list-logo"><img src="img/logo-amazon.png" alt="Client logo Amazon"></li> </ul> <a class="button" href="#">Try For Free</a> </section> <!-- <section class ="section"> <div class ="section__title"> <h3>Testimonials</h3> </div> <div class="section__logo"><img src="img/logo-ibm.png" alt="IBM"></div> <p>Most calendars are designed for teams. Slate is designed for freelancers who want a simple way to plan their schedule.</p> <figure class="section__foto"> <img src="img/ico.png" alt="Client Name logo Amazon"> <figcaption> <span>Organize across</span> <span>Ui designer</span> </figcaption> </figure> <div class="button"><a href="#">More Testimonials</a></div> </section> <section class ="section alt"> <div class ="section__title"> <h3>Pricing</h3> <p>Most calendars are designed for teams. Slate is designed for freelancers</p> </div> <ul class ="section__boxes"> <li class ="section__boxes__box"> <div class ="section__title"> <h4>FREE</h4> <h3>Organize across all apps by hand</h3> </div> <div class="section__item"> <strong class="section__item__price">0</strong> <div class="section__item__info"> <strong>$</strong> <span>Per Month</span> </div> </div> <ul> <li>Pricing Feature</li> <li>Pricing Feature</li> <li>Pricing Feature</li> <li>Pricing Feature</li> <li>Pricing Feature</li> </ul> <div class="button"><a href="#">Order Now</a></div> </li> <li class ="section__boxes__box alt"> <div class ="section__title"> <h4>STANDARD</h4> <h3>Organize across all apps by hand</h3> </div> <div class="section__item"> <strong class="section__item__price">10</strong> <div class="section__item__info"> <strong>$</strong> <span>Per Month</span> </div> </div> <ul> <li>Pricing Feature</li> <li>Pricing Feature</li> <li>Pricing Feature</li> <li>Pricing Feature</li> <li>Pricing Feature</li> </ul> <div class="button"><a href="#">Order Now</a></div> </li> <li class ="section__boxes"> <div class ="section__title"> <h4>BUSINESS</h4> <h3>Organize across all apps by hand</h3> </div> <div class="section__item"> <strong class="section__item__price">99</strong> <div class="section__item__info"> <strong>$</strong> <span>Per Month</span> </div> </div> <ul> <li>Pricing Feature</li> <li>Pricing Feature</li> <li>Pricing Feature</li> <li>Pricing Feature</li> <li>Pricing Feature</li> </ul> <div class="button"><a href="#">Order Now</a></div> </li> </ul> </section> <section class ="section"> <div class ="section__title"> <h4>Contact Us</h4> <h3>Most calendars are designed for teams. Slate is designed for freelancers</h3> </div> <form class="section__form-contact" action="/submit" method="POST"> <input type="text" id="name" name="name" placeholder="Your Name"> <input type="email" id="email" name="email" placeholder="Your Email"> <textarea id="message" name="message" rows="4" cols="50">Your Message</textarea> <button class="form-contact__btn-submit" type="submit">Send</button> </form> <div class ="section__block-contact"> <h4>Contact Us</h4> <h3>Most calendars are designed for teams. Slate is designed for freelancers</h3> </div> </section> --> </main> <footer class="footer"> <div class="footer__container"> <div class="footer__columns"> <div class="footer__column"> <h3 class="footer__title">Pages</h3> <div class="footer__menu"> <a class="footer__menu-item" href="#">Home</a> <a class="footer__menu-item" href="#">Product</a> <a class="footer__menu-item" href="#">Pricing</a> <a class="footer__menu-item" href="#">About</a> </div> </div> <div class="footer__column"> <h3 class="footer__title">Tomothy</h3> <div class="footer__menu"> <a class="footer__menu-item" href="#">Eleanor Edwards</a> <a class="footer__menu-item" href="#">Ted Robertson</a> <a class="footer__menu-item" href="#">Annette Russell</a> <a class="footer__menu-item" href="#">Jennie Mckinney</a> <a class="footer__menu-item" href="#">Gloria Richards</a> </div> </div> <div class="footer__column"> <h3 class="footer__title">Jane Black</h3> <div class="footer__menu"> <a class="footer__menu-item" href="#">Philip Jones</a> <a class="footer__menu-item" href="#">Product</a> <a class="footer__menu-item" href="#">Colleen Russell</a> <a class="footer__menu-item" href="#">Marvin Hawkins</a> <a class="footer__menu-item" href="#">Bruce Simmmons</a> </div> </div> </div> <div class="footer__contacts"> <div class ="footer__contacts-items"> <p class ="footer__map"><img class ="footer__map-image" src="img/ico-map.png" alt="ico map"> <span>7480 Mockingbird Hill undefined</span></p> <p class ="footer__telefon"><img class ="footer__telefon-image" src="img/ico-telefon.png" alt="ico telefon"> <a href="tel:2395550108">(239) 555-0108</a></p> </div> <div class ="footer__social social"> <a class ="social-item" href="#"><img class ="social-twitter" src="img/ico-twitter.png" alt="Twitter"></a> <a class ="social-item" href="#"><img class ="social-facebook" src="img/ico-facebook.png" alt="Facebook"></a> <a class ="social-item" href="#"><img class ="social-instagram" src="img/ico-instagram.png" alt="Instagram"></a> </div> </div> </div> </footer> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script> </body> </html>
package com.example.demo.entities.web; import java.util.List; import org.springframework.stereotype.Component; import com.example.demo.dto.CustomerRequest; import com.example.demo.entities.Customer; import com.example.demo.mapper.CustomerMapper; import com.example.demo.repository.CustomerRepository; import jakarta.jws.WebMethod; import jakarta.jws.WebParam; import jakarta.jws.WebService; import lombok.AllArgsConstructor; @Component @AllArgsConstructor @WebService(serviceName = "CustomerWS") public class CustomerSoapService { private CustomerRepository customerRepository; private CustomerMapper customerMapper; @WebMethod public List<Customer> customerList(){ return customerRepository.findAll(); } @WebMethod public Customer customerById(@WebParam(name = "id") Long id) { return customerRepository.findById(id).get(); } @WebMethod public Customer SaveCustomer(@WebParam(name ="customer" ) CustomerRequest customerRequest) { Customer customer=customerMapper.from(customerRequest); return customerRepository.save(customer); } }
--- id: 107 title: 'Low level debugolás, 1. rész: strace' date: '2016-02-29T23:27:53+01:00' author: janoszen layout: post guid: 'https://www.refaktor.hu/?p=107' permalink: /2016/02/29/low-level-debugolas-1-resz-strace/ pyre_show_first_featured_image: - 'yes' pyre_portfolio_width_100: - default pyre_video: - '' pyre_fimg_width: - '' pyre_fimg_height: - '' pyre_image_rollover_icons: - 'no' pyre_link_icon_url: - '' pyre_post_links_target: - 'no' pyre_related_posts: - default pyre_share_box: - default pyre_post_pagination: - default pyre_author_info: - default pyre_post_meta: - default pyre_post_comments: - default pyre_main_top_padding: - '' pyre_main_bottom_padding: - '' pyre_hundredp_padding: - '' pyre_slider_position: - default pyre_slider_type: - 'no' pyre_slider: - '0' pyre_wooslider: - '0' pyre_revslider: - '0' pyre_elasticslider: - '0' pyre_fallback: - '' pyre_avada_rev_styles: - default pyre_display_header: - 'yes' pyre_header_100_width: - default pyre_header_bg: - '' pyre_header_bg_color: - '' pyre_header_bg_opacity: - '' pyre_header_bg_full: - 'no' pyre_header_bg_repeat: - repeat pyre_displayed_menu: - default pyre_display_footer: - default pyre_display_copyright: - default pyre_footer_100_width: - default pyre_sidebar_position: - default pyre_sidebar_bg_color: - '' pyre_page_bg_layout: - default pyre_page_bg: - '' pyre_page_bg_color: - '' pyre_page_bg_full: - 'no' pyre_page_bg_repeat: - repeat pyre_wide_page_bg: - '' pyre_wide_page_bg_color: - '' pyre_wide_page_bg_full: - 'no' pyre_wide_page_bg_repeat: - repeat pyre_page_title: - default pyre_page_title_text: - default pyre_page_title_text_alignment: - default pyre_page_title_100_width: - default pyre_page_title_custom_text: - '' pyre_page_title_text_size: - '' pyre_page_title_custom_subheader: - '' pyre_page_title_custom_subheader_text_size: - '' pyre_page_title_font_color: - '' pyre_page_title_height: - '' pyre_page_title_mobile_height: - '' pyre_page_title_bar_bg: - '' pyre_page_title_bar_bg_retina: - '' pyre_page_title_bar_bg_color: - '' pyre_page_title_bar_borders_color: - '' pyre_page_title_bar_bg_full: - default pyre_page_title_bg_parallax: - default pyre_page_title_breadcrumbs_search_bar: - default fusion_builder_status: - inactive avada_post_views_count: - '2701' refaktor_post_views_count: - '2451' dublin_core_author: - 'Enter author here' dublin_core_title: - 'Enter title here' dublin_core_publisher: - 'Enter publisher here' dublin_core_rights: - 'Enter rights here' sbg_selected_sidebar: - 'a:1:{i:0;s:1:"0";}' sbg_selected_sidebar_replacement: - 'a:1:{i:0;s:12:"Blog Sidebar";}' sbg_selected_sidebar_2: - 'a:1:{i:0;s:1:"0";}' sbg_selected_sidebar_2_replacement: - 'a:1:{i:0;s:0:"";}' image: 'assets/uploads/2016/01/29122141/8879202_ml_cropped.jpg' categories: - Fejlesztés tags: - debugging --- Teljesen mindegy, hogy fejlesztünk vagy üzemeltetünk, időnként előfordul, hogy olyan szoftvert kell életre lehelnünk, amely kódminősége finoman szólva hagy némi kívánni valót maga után. Ilyen esetben nem mindig praktikus elkezdeni a szoftver kódját nézegetni, sokszor célszerűbb sokkal mélyebben nekifogni a feladatnak. Ebben a cikkben bemutatjuk, hogy hogyan lehet megjeleníteni egy program rendszerhívásait Linux platformon az `strace` utility segítségével. ## Mi is az a rendszerhívás? Anélkül, hogy részletesen belemennénk az operációs rendszerek lelkivilágába, nézzük meg, hogy tulajdonképpen mi is az a rendszerhívás, vagy angolul system call. A modern programok két féle üzemmódban futhatnak a processzoron: kernel módban és a user módban. A felhasználói programok, szerver szoftverek jellemzően user módban futnak, ahol a processzor megvédi őket. Ez azt jelenti, hogy nem férhetnek hozzá más programok memóriaterületeihez, nem írhatnak közvetlenül a merevlemezre. Sok művelethez azonban szükség van a védelem kikapcsolására. Ehhez a programok az operációs rendszer magját szólítják meg, ami kernel módban fut. Mivel a kernel módban futó programok szó szerint mindent megtehetnek, az operációs rendszerek csak egy szűk kódhalmazt futtatnak ebben a módban, ami egy szabványos programfelületen keresztül érhető el. Azok a függvények, amiket a kernel módban futó rendszermag (avagy: a kernel) biztosít számunkra, *rendszerhívásoknak* nevezzük. Ilyen rendszerhívások például a file megnyitás (`open`), hálózati kapcsolat nyitása (`connect`), stb. ## Mire lesz ez jó nekünk? Az `strace` programot eredetileg Sun OS-re írták, ma már azonban inkább a Linux rendszereken jellemző. A segítségével kilistázhatjuk, hogy pontosan milyen rendszerhívásokat tesz a programunk, a legegyszerűbben a parancssorból lefuttatva: ``` strace ls /proc ``` Ennek valami ilyesmi kimenete lesz: ``` execve("/bin/ls", ["ls", "/proc"], [/* 19 vars */]) = 0 brk(0) = 0x1097000 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f0bb0334000 access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) open("/etc/ld.so.cache", O_RDONLY) = 3 fstat(3, {st_mode=S_IFREG|0644, st_size=22620, ...}) = 0 mmap(NULL, 22620, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f0bb032e000 close(3) = 0 open("/lib64/librt.so.1", O_RDONLY) = 3 ... ``` Elsőre teljes kavarnak tűnik, azonban ha jobban megnézzük, ezek tulajdonképpen programkódra hasonlítanak, a sor végén a visszatérési értékekkel kiegészítve. Ha kicsit megszűrjük a kimenetet és megmondjuk az strace-nek, hogy mely rendszerhívásokat listázza ki: ``` strace -e trace=stat,open,read,write,readv,writev,recv,recvfrom,send,sendto ls /proc ``` ``` open("/etc/ld.so.cache", O_RDONLY) = 3 open("/lib64/librt.so.1", O_RDONLY) = 3 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\340\"\0\0\0\0\0\0"..., 832) = 832 open("/lib64/libcap.so.2", O_RDONLY) = 3 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\26\0\0\0\0\0\0"..., 832) = 832 open("/lib64/libacl.so.1", O_RDONLY) = 3 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\340#\0\0\0\0\0\0"..., 832) = 832 open("/lib64/libc.so.6", O_RDONLY) = 3 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0000\356\1\0\0\0\0\0"..., 832) = 832 open("/lib64/libpthread.so.0", O_RDONLY) = 3 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\300\\\0\0\0\0\0\0"..., 832) = 832 open("/lib64/libattr.so.1", O_RDONLY) = 3 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0 \26\0\0\0\0\0\0"..., 832) = 832 open("/proc", O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC) = 3 write(1, "1 13239 14532 22092 2209"..., 1761 13239 14532 22092 22094 22096 247 447 574 8517 cpuinfo fairsched filesystems kmsg locks mounts self swaps sysrq-trigger uptime version vz ) = 176 write(1, "13238 14496 14533 22093 2209"..., 16913238 14496 14533 22093 22095 22097 446 559 649 cmdline devices fairsched2 fs loadavg meminfo net stat sys sysvipc user_beancounters vmstat ) = 169 ``` Mint látható, így már csak a kívánt rendszerhívásokat kapjuk meg. A lehetséges hívások listáját a `man` parancs adja meg: ``` man 2 syscalls ``` <div class="warning">**Figyelem!** A SUID beállítással futó programok, pl. `suexec` az Apache webszerverben, nem működnek a `strace` programmal!</div>## Tippek és trükkök ### A kiírt stringek hosszának megemelése <span class="s1">Sok rendszerhívás – például a hálózati kapcsolatokba való írás, vagy azokból való olvasás – több adatot ad át, mint amit a strace parancs alapértelmezetten kiír.</span> Ha szeretnénk a teljes adatfolyamot látni, meg kell emelni a kiírt szövegek hosszát: ``` strace -s 999 ls /proc ``` <span class="s1">Így könnyebbé válhat a hálózati kapcsolatok elemzése. Azonban ne felejtsük el, hogy az esetleges titkosítás alkalmazás-szinten történik, azaz a strace kimenetben már a titkosított adatfolyam lesz. </span>A titkosítás megkerüléséről egy későbbi cikkben lesz szó. ### Már futó programok elemzése Az strace nem csak az általa elindított programokat képes elemezni, hanem már futó programokat is, akár többet egyszerre is. Ehhez szükségünk van a futó program PID-jére, amit az `ps auwfx` parancs kiír. A szintaxis meglehetősen egyszerű: ``` strace -p 1234 -p 1235 ``` Ha nincs root jogunk az adott gépen, akkor természetesen csak a saját processzeinket tudjuk elemezni. ### Processzek követése Sok szerver-jellegű program (Apache, PHP, stb) nem pusztán egy szálon dolgozik, hanem mindjárt több processzt is nyit. Ezeket strace-ben a `-f` kapcsolóval követhetjük. (Ez esetben a processz ID kiíródik a sor elejére.) ### Webalkalmazások elemzése Webalkalmazások általában egy webszerverben, vagy önálló daemonban futnak. Ezek általában több mint egy processzt indítanak, így fel kell használnunk az előző részekben tárgyaltakat az összes processz figyeléséhez. Először megkeressük a megfelelő processzek listáját: PHP-FPM: ``` ps auwfx |grep [p]hp ``` Apache: ``` ps auwfx |grep [a]pache ``` Ezt kiegészítjük azzal, hogy kiszűrjük a PID-eket, és kiírjuk `-p` kapcsolóval: PHP-FPM: ``` ps auwfx |grep [p]hp | awk ' { print $2 } ' \ | xargs -i echo -n ' -p {}' ``` Apache: ``` ps auwfx |grep [a]pache | awk ' { print $2 } ' \ | xargs -i echo -n ' -p {}' ``` Ezt a kimenetet belírjuk az strace parancsba: PHP-FPM: ``` strace \ -e trace=open,read,write,readv,writev,recv,recvfrom,send,sendto \ -f -s 999 \ $(ps auwfx |grep [p]hp | awk ' { print $2 } ' \ | xargs -i echo -n ' -p {}') ``` Apache: ``` strace \ -e trace=open,read,write,readv,writev,recv,recvfrom,send,sendto \ -f -s 999 \ $(ps auwfx |grep [a]pache | awk ' { print $2 } ' \ | xargs -i echo -n ' -p {}') ``` Ha megnézzük ezután a kimenetet, ilyeneket látunk: ``` Process 6883 attached - interrupt to quit Process 6888 attached - interrupt to quit Process 6889 attached - interrupt to quit Process 6890 attached - interrupt to quit Process 6891 attached - interrupt to quit Process 6892 attached - interrupt to quit Process 6894 attached - interrupt to quit Process 6895 attached - interrupt to quit Process 6896 attached - interrupt to quit [pid 6892] read(8, "GET /test.php HTTP/1.1\r\nHost: stuff.localhost\r\nUser-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-us,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nReferer: http://stuff.localhost/\r\nCache-Control: max-age=0\r\n\r\n", 8000) = 361 [pid 6892] open("/.htaccess", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory) [pid 6892] open("/var/.htaccess", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory) [pid 6892] open("/var/www/.htaccess", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory) [pid 6892] open("/var/www/stuff.localhost/.htaccess", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory) [pid 6892] open("/var/www/stuff.localhost/htdocs/.htaccess", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory) [pid 6892] open("/var/www/stuff.localhost/htdocs/test.php/.htaccess", O_RDONLY|O_CLOEXEC) = -1 ENOTDIR (Not a directory) [pid 6892] open("/var/www/stuff.localhost/htdocs/test.php", O_RDONLY) = 9 [pid 6892] open("/dev/urandom", O_RDONLY) = 9 [pid 6892] read(9, "\255\263\316-\306C\273\2", 8) = 8 [pid 6892] open("/dev/urandom", O_RDONLY) = 9 [pid 6892] read(9, "9\326|\367v2\21\315", 8) = 8 [pid 6892] open("/dev/urandom", O_RDONLY) = 9 [pid 6892] read(9, "5\5\305,`J\201 ", 8) = 8 [pid 6892] writev(8, [{"HTTP/1.1 200 OK\r\nDate: Thu, 19 Apr 2012 11:29:29 GMT\r\nServer: Apache/2.2.20 (Ubuntu)\r\nX-Powered-By: PHP/5.3.6-13ubuntu3.6\r\nVary: Accept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 32\r\nKeep-Alive: timeout=5, max=100\r\nConnection: Keep-Alive\r\nContent-Type: text/html\r\n\r\n", 273}, {"\37\213\10\0\0\0\0\0\0\3", 10}, {"\363H\315\311\311W\10\317/\312IQ\4\0", 14}, {"\243\34)\34\f\0\0\0", 8}], 4) = 305 [pid 6892] read(8, 0x7fa392c8e048, 8000) = -1 EAGAIN (Resource temporarily unavailable) [pid 6892] write(6, "stuff.localhost:80 127.0.0.1 - - [19/Apr/2012:13:29:29 +0200] \"GET /test.php HTTP/1.1\" 200 305 \"http://stuff.localhost/\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0\"\n", 200) = 200 ``` Mint látható, ebben a példában az Apache webszerver a lekérdezés feldolgozása közben végig olvassa a `.htaccess` fájlok lehetséges helyeit, majd visszaküldi az eredményt. ## Összegzés Mint látható, az strace egy igen hasznos eszköz, ha az alkalmazások külső kommunikációját, vagy fájlműveleteit akarjuk elemezni. A sorozat következő részében a hálózati kapcsolatok mélyebb elemzésével fogunk foglalkozni.
class ElectricalAppliance { constructor(name, power) { this.power = power; this.name = name; this.isPlugged = false; } plugIn() { this.isPlugged = true; console.log(`${this.name} включен в розетку`); } unplug() { this.isPlugged = false; console.log(`${this.name} выключен из розетки`); } } class Computer extends ElectricalAppliance { constructor(name, weight, bitness, power) { super(name, power); this.weight = weight; this.bitness = bitness; this.isItOn = false; } turnOn() { this.isItOn = true; console.log(`${this.name} включен`); } turnOff() { this.isItOn = false; console.log(`${this.name} выключен`); } } class Lamp extends ElectricalAppliance { constructor(name, power, color, weight, brightness) { super(name, power); this.color = color; this.weight = weight; this.brightness = brightness; this.lightIsOn = false; } lightOn() { this.lightIsOn = true; console.log(`${this.name} включен(а)`); } lightOff() { this.lightIsOn = false; console.log(`${this.name} выключен(а)`); } } const ibmPC = new Computer("5150", 11000, 16, 400); const potatoPC = new Computer("Potato", 1000, 4, 20); const ecoLamp = new Lamp("ecoLamp", 100, "yellow", 200, 10); ibmPC.turnOn(); potatoPC.turnOn(); ecoLamp.lightOn(); console.log(ibmPC, potatoPC, ecoLamp);
<?php namespace ChrisReedIO\AthenaSDK\Requests\Charts\SocialHistory; use Saloon\Enums\Method; use Saloon\Http\Request; /** * GetPatientSocialHistory * * Retrieves the social history information of a specific patient */ class GetPatientSocialHistory extends Request { protected Method $method = Method::GET; public function resolveEndpoint(): string { return "/chart/{$this->patientid}/socialhistory"; } /** * @param int $departmentid The athenaNet department id. * @param int $patientid patientid * @param null|string $recipientcategory The intended audience for the data. If given, questions marked as confidential for this audience will be withheld. * @param null|bool $shownotperformedquestions Include questions that the provider did not perform. * @param null|bool $showunansweredquestions Include questions where there is no current answer. */ public function __construct( protected int $departmentid, protected int $patientid, protected ?string $recipientcategory = null, protected ?bool $shownotperformedquestions = null, protected ?bool $showunansweredquestions = null, ) { } public function defaultQuery(): array { return array_filter([ 'departmentid' => $this->departmentid, 'recipientcategory' => $this->recipientcategory, 'shownotperformedquestions' => $this->shownotperformedquestions, 'showunansweredquestions' => $this->showunansweredquestions, ]); } }
// -*- mode: SCAD ; c-file-style: "ellemtel" ; coding: utf-8 -*- // // Axoloti case. // // © 2017 Roland Sieker <[email protected]> // © 2013 M_G // Licence: CC-BY-SA 4.0 // Based on M_G’s OpenSCAD Parametric Packaging Script v2, version // 2.6c. Thingiveres thing https://www.thingiverse.com/thing:66030 // See the source file there for usage notes. // The layout of the parts. Change this to top, render, export, then // bottom, reder, export. // layout="beside"; // [beside, stacked, top, bottom] layout="bottom"; // [beside, stacked, top, bottom] screw_hole_distance = 2; screw_hole_radius = 1.6; // Dimensions of the axoloti core. // Todo: get the real hight: device_xyz = [160, 50, 23]; // The gap between the axoloti and the case: clearance_xyz = [1, 1, 2]; // Theckness of the case walls: // wall_t = 3; // originall thickness wall_t = 3; // 2 mm should be plenty. // The external radius of the rounded corners of the packaging corner_radius = 3; // How many sides do these rounded corners have? corner_sides = 5; // How high is the lip that connects the 2 halves? lip_h = 5; // How tall is the top relative to the bottom top_bottom_ratio=0.2; // Originally 0.5. // We want the gap to coincide with the USB connectors, which are quite // low. Needs tweaking because of some posts. // Does the part have (anti-warping) mouse ears? has_mouseears = false; mouse_ear_thickness=0.2*2; // Twice print layer thickness is a good idea mouse_ear_radius = 10; // 5–15 (mm) generally work well // How far apart the 2 halves are in the "beside" layout separation = 15; // How much of an overlap (-ve) or gap (+ve) is there between the inner // and outer lip surfaces, a value of 0 implies they meet perfectly in // the middle // lip_fit=0.2; lip_fit = 0.2; // Does it have an imported representaion of the actual device to be packaged? has_device=false; // Edge style, possible values: // "cuboid", "rounded4sides", "rounded6sides", "chamfered6sides" box_type = "rounded6sides"; // Data structure defining all the cutouts and depressions used on the packaging holes = [ // Three examples ["N", "Rectangle", [-7, 0.5,0,-device_xyz[2]/2,0,"inside"], [wall_t, 14, 2] ], // Cutout for µSD card (Reuse this?) // ["E", "Rectangle", [0.5, +0.75,0,0,0,"inside"], [wall_t, 9, 5]], // cutout for switch // The SD card // ["N", "Rectangle", [15, +1,0,0,0,"inside"], [wall_t, 10, 6]], //cutout for uUSB port // Screw holes ["B", "Cylinder", [screw_hole_distance, screw_hole_distance, -device_xyz[0]/2, -device_xyz[1]/2, 0, "outside"], [clearance_xyz[2]+wall_t, screw_hole_radius, 10]], ["B", "Cylinder", [-screw_hole_distance, screw_hole_distance, device_xyz[0]/2, -device_xyz[1]/2, 0, "outside"], [clearance_xyz[2]+wall_t, screw_hole_radius, 10]], ["B", "Cylinder", [-screw_hole_distance, -screw_hole_distance, device_xyz[0]/2, device_xyz[1]/2, 0, "outside"], [clearance_xyz[2]+wall_t, screw_hole_radius, 10]], ["B", "Cylinder", [screw_hole_distance, -screw_hole_distance, -device_xyz[0]/2, device_xyz[1]/2, 0, "outside"], [clearance_xyz[2]+wall_t, screw_hole_radius, 10]], ]; post_tolerance=0.1; // Data structure defining all the internal supporting structures used // on the packaging posts = [ // Format: // [face_name, shape_name shape_position[x_pos,y_pos,x_offs,y_offs,rotate,align], // shape_size[depth,,,]] ["B", "Cylinder", [screw_hole_distance, screw_hole_distance, -device_xyz[0]/2, -device_xyz[1]/2, 0, "inside"], [clearance_xyz[2], 2*screw_hole_radius, 10]], ["B", "Cylinder", [-screw_hole_distance, screw_hole_distance, device_xyz[0]/2, -device_xyz[1]/2, 0, "inside"], [clearance_xyz[2], 2*screw_hole_radius, 10]], ["B", "Cylinder", [screw_hole_distance, -screw_hole_distance, -device_xyz[0]/2, device_xyz[1]/2, 0, "inside"], [clearance_xyz[2], 2*screw_hole_radius, 10]], ["B", "Cylinder", [-screw_hole_distance, -screw_hole_distance, device_xyz[0]/2, device_xyz[1]/2, 0, "inside"], [clearance_xyz[2], 2*screw_hole_radius, 10]], ]; // Data structure defining all the engraved text used on the packaging texts = [ // Recessed text on faces // This version uses the native, relatively new, OpenSCAD text() function. // [ // face_name, text_to_write, // shape_position[x_pos,y_pos,x_offs,y_offs,rotate,align], // shape_size[depth, font_hight, mirror, font_name] // ] // Notes: // Mirror must be 0 or 1 corresponding to false and true in this // version // Use a font you a) have, b) like, and c) that contains the glyphs // you want. // ["T", "31", [0,12,0,0,0,"outside"], [1,4,1,0]],//device ID // ["T", "2013-3-25", [0,0,0,0,90,"inside"], [0.5,4,1,1]],//date // ["N", "X-", [0,10,0,0,0,"outside"], [1,10,1,0]], // ["S", "X+", [0,-6,0,0,0,"outside"], [1,10,1,0]], // ["E", "Y+", [10,-6,0,0,0,"outside"], [1,10,1,0]], ["T", "XQg", [0,0,0,0,90,"inside"], [11,5, 0, "Praxis LT"]], ["E", "Off On", [0,-5,0,0,0,"outside"], [1,3, 0, "Praxis LT"]], ["E", "uUSB", [15,-5,0,0,0,"outside"], [1,3, 0, "Praxis LT"]], ["W", "µSD", [14,4,0,0,0,"outside"], [1,3, 0, "Praxis LT"]], ]; // Data structure defining external items such as .stl files to import items = [ // External items on faces: // [face_name, external_file, // shape_position[x_pos,y_pos,x_offs,y_offs,rotate,align], // shape_size[depth, scale_x,scale_y, scale_z, mirror]] // Note: for silly reasons mirror must be 0 or 1 corresponding to // false and true in this version // ["T", "axoloti_logo.stl", [0,0,0,0,90,"outside"], [0.5,10/21.9,10/21.9,1.1/1.62,0]] ]; // A small number used for manifoldness a_bit = 0.01; // X dimension of packaging box_l = device_xyz[0]+2*(clearance_xyz[0]+wall_t); // y dimension of packaging box_b = device_xyz[1]+2*(clearance_xyz[1]+wall_t); // z dimension of packaging box_h = device_xyz[2]+2*(clearance_xyz[2]+wall_t); // Now create things: mouse_ears=[has_mouseears, mouse_ear_thickness, mouse_ear_radius]; box=[box_l,box_b,box_h,corner_radius,corner_sides,wall_t];// make_box(box, corner_radius, corner_sides, lip_h, lip_fit, top_bottom_ratio, mouse_ears, layout, separation, holes, posts, texts, items, has_device, box_type); module make_box(box, corner_radius=3, corner_sides=5, lip_h=2, lip_fit=0, top_bottom_ratio=0.5, mouse_ears=[false], layout="beside", separation=2, holes=[], posts=[], texts=[], items=[], has_device=false, box_type="rounded4sides"){ echo("layout", layout); //echo("holes", holes); //echo ("variables", corner_radius, corner_sides, lip_h, top_bottom_ratio, has_mouseears, layout, separation); translate(v=[0, 0, box[2]/2]){ if (layout=="beside"){ echo("beside"); union(){ translate(v=[(separation+box[0])/2, 0, 0]){ half_box(box, corner_radius, corner_sides, lip_h, lip_fit, top_bottom_ratio, which_half="bottom", holes=holes, posts=posts, mouse_ears=mouse_ears, texts=texts, items=items, box_type=box_type); //cube(size=[25.5, 31.5, 23.5], center=true); //rotate(a=[0, 0, 90])translate(v=[-30/2, -15/2, 0])import("wimuv3_stack_v0.1.stl"); // rotate(a=[0, 0, -90])translate(v=[-27/2, -40/2, 1.88])import("2013_04_04-WIMUv3a_PCB-V0-2_logo.stl"); }translate(v=[-(separation+box[0])/2, 0, 0]) rotate(a=[0, 180, 0]){ half_box(box, corner_radius, corner_sides, lip_h, lip_fit, top_bottom_ratio, which_half="top", holes=holes, posts=posts, mouse_ears=mouse_ears, texts=texts, items=items, box_type=box_type);//cube(size=[box[0], box[1], box[2]], center=true); //cube(size=[25.5, 31.5, 23.5], center=true); } } }else if (layout=="stacked"){ echo("stacked"); half_box(box, corner_radius, corner_sides, lip_h, lip_fit, top_bottom_ratio, which_half="bottom", holes=holes, posts=posts, mouse_ears=mouse_ears, texts=texts, items=items, has_device=has_device, box_type=box_type); translate(v=[0, 0, 0])half_box(box, corner_radius, corner_sides, lip_h, lip_fit, top_bottom_ratio, which_half="top", holes=holes, posts=posts, mouse_ears=[false], texts=texts, items=items, box_type=box_type); //rotate(a=[0, 0, 90])translate(v=[-30/2, -15/2, 0])import("wimuv3_stack_v0.1.stl"); }else if (layout=="top"){ echo("top"); rotate(a=[180, 0, 0]) half_box(box, corner_radius, corner_sides, lip_h, lip_fit, top_bottom_ratio, which_half="top", holes=holes, posts=posts, mouse_ears=mouse_ears, texts=texts, items=items, box_type=box_type); }else if (layout=="bottom"){ echo("bottom"); half_box(box, corner_radius, corner_sides, lip_h, lip_fit, top_bottom_ratio, which_half="bottom", holes=holes, posts=posts, mouse_ears=mouse_ears, texts=texts, items=items, has_device=has_device, box_type=box_type); }else{ echo("unknown layout requested", layout); } } } module half_box(box, corner_radius=3, corner_sides=5, lip_h=2, lip_fit=0, top_bottom_ratio=0.5, which_half="bottom", holes=[], posts=[], mouse_ears=[false], texts=[], , items=[], has_device=false, box_type="rounded4sides"){ a_bit=0.01; echo("holes", holes); has_mouse_ears=mouse_ears[0]; mouse_ear_thickness=mouse_ears[1]; mouse_ear_radius=mouse_ears[2]; wall_t=box[5]; cutaway_extra=0.01; if (which_half=="bottom") color("springgreen") { echo("bottom half"); union(){//combine hollow cutout box with posts difference(){ union(){ difference(){ // Make the hollow box box_type(box, box_type); box_type( [box[0]-2*box[5], box[1]-2*box[5], box[2]-2*box[5], corner_radius-box[5], corner_sides], box_type); } make_posts(box, posts); } translate(v=[0, 0, box[2]*(1-top_bottom_ratio)-lip_h/2]) { // Cutting away other half and lip cutout translate(v=[0, 0, lip_h/2 - box[2]/2 ]) rounded_rectangle_cylinder_hull( box[0]-(box[5]-lip_fit), box[1]-(box[5]-lip_fit), lip_h+0.01, corner_radius-(box[5]-lip_fit)/2, corner_sides); // Cutout for lips translate(v=[0,0,lip_h+cutaway_extra/2]) cube( size=[ box[0]+2*cutaway_extra, box[1]+2*cutaway_extra, box[2]+cutaway_extra], center=true); // Need to oversize this using cutaway_extra so it // gets any extra material on the side the be removed // on the outside (from posts) } #make_cutouts(box, holes); // Remove the material for the cutouts because this // happens at the end you can make a hole in the centre // of a post! perhaps a cone for a countersink screw // through hole make_texts(box, texts); make_items(box, items); } //make_posts(box, posts); mouse_ears(box,mouse_ear_thickness,mouse_ear_radius, has_mouse_ears); if(has_device==true){ echo("has device"); //rotate(a=[0,0,90])translate(v=[-31/2,-25/2,-box[2]/2+3.5])import("wimuv3_stack_v0.1.stl"); rotate(a=[0,0,90])translate(v=[-40/2,-27/2,1.88-9.23/2])import("2013_04_04-WIMUv3a_PCB-V0-2_logo.stl"); } } }else if (which_half=="top") color("crimson") { echo("top half"); union(){ intersection(){ difference(){ //echo("box",box); union(){ difference(){//make hollow box box_type(box, box_type); //rounded_rectangle_cylinder_hull(box[0],box[1],box[2],corner_radius,corner_sides); //box_type([box[0]-2*box[5][0],box[1]-2*box[5][1],box[2]-2*box[5][2],corner_radius-0.5*(box[5][0]+box[5][1]),corner_sides], box_type="rounded4sides");//rounded_rectangle_cylinder_hull(box[0]-2*box[5],box[1]-2*box[5],box[2]-2*box[5],corner_radius-box[5],corner_sides); box_type([box[0]-2*box[5],box[1]-2*box[5],box[2]-2*box[5],corner_radius-box[5],corner_sides], box_type);//rounded_rectangle_cylinder_hull(box[0]-2*box[5],box[1]-2*box[5],box[2]-2*box[5],corner_radius-box[5],corner_sides); } make_posts(box,posts); } #make_cutouts(box, holes); make_texts(box, texts); make_items(box, items); } translate(v=[0,0,(box[2]*(1-top_bottom_ratio))-lip_h/2]){//removed -lip_h/2 from z translate/re-added //translate(v=[0,0,lip_h/2 - box[2]/2]) rounded_rectangle_cylinder_hull(box[0]-box[5],box[1]-box[5],lip_h+0.01,corner_radius-box[5]/2,corner_sides);//lips translate(v=[0,0,lip_h/2 - box[2]/2]) rounded_rectangle_cylinder_hull(box[0]-(box[5]+lip_fit),box[1]-(box[5]+lip_fit),lip_h+0.01,corner_radius-(box[5]+lip_fit)/2,corner_sides);//lips // translate(v=[0,0,lip_h/2 - box[2]/2]) rounded_rectangle_cylinder_hull(box[0]-box[5][0],box[1]-box[5][1],lip_h+0.01,corner_radius-(box[5][0]+box[5][1])/4,corner_sides); translate(v=[0,0,lip_h-a_bit]) cube(size=[box[0]+2*cutaway_extra,box[1]+2*cutaway_extra,box[2]], center=true); } } //make_posts(box,posts); rotate(a=[180,0,0])mouse_ears(box,mouse_ear_thickness,mouse_ear_radius, has_mouse_ears); } }else{ echo("invalid half requested",which_half); } } module rounded_rectangle_cylinder_hull(x,y,z,r,s) { //cube(size=[x,y,z],center=true); //echo("number of sides",s); hull() { cross_box(x,y,z,r); // This is to ensure the overall dimensions stay true to those // requested even for low-poly cylinders translate(v=[ x/2 -r , y/2 -r , 0]) cylinder(h=z, r=r, center=true, $fn=4*s); translate(v=[ x/2 -r , -(y/2 -r), 0]) cylinder(h=z, r=r, center=true, $fn=4*s); translate(v=[ -(x/2 -r), -(y/2 -r), 0]) cylinder(h=z, r=r, center=true, $fn=4*s); translate(v=[ -(x/2 -r), y/2 -r , 0]) cylinder(h=z, r=r, center=true, $fn=4*s); } } module cross_box(x,y,z,r) { cube(size=[x-2*r,y-2*r,z],center=true); cube(size=[x-2*r,y,z-2*r],center=true); cube(size=[x,y-2*r,z-2*r],center=true); } module make_cutouts(box, holes) { box_l=box[0]; // x box_b=box[1]; // y box_h=box[2]; // z box_t=[box[5],box[5],box[5]];//wall_t // %cube(size=[box_l,box_b,box_h],center=true); x_pos = 0; y_pos = 0; face = "X"; echo("len(holes)",len(holes)); for (j=[0:len(holes)-1]) { x_pos = holes[j][2][0]; y_pos = holes[j][2][1]; x_offs= holes[j][2][2]; y_offs= holes[j][2][3]; face = holes[j][0]; shape_type=holes[j][1]; shape_data=holes[j][3]; rotation=holes[j][2][4]; align=holes[j][2][5]; depth=holes[j][3][0]; //echo("face",face); if (face=="N") { translate(v=[0,box_b/2,0]) rotate(a=[-90,0,0]) translate(v=[-(x_pos+x_offs),-(y_pos+y_offs),0]) { //echo("alignment", align); if (align=="inside") { //echo("translate by",+depth/2-box_t); translate(v=[0,0,+depth/2-box_t[1]]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); } else if (align=="outside") { //echo("translate by",-depth/2); translate(v=[0,0,-depth/2]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); } else { echo("invalid alignment", align); } } } else if (face=="E") { translate(v=[box_l/2,0,0]) rotate(a=[0,90,0]) rotate(a=[0,0,-90]) translate(v=[-(x_pos+x_offs),-(y_pos+y_offs),0]) { //make_shape(shape_type, shape_data); if (align=="inside") translate(v=[0,0,+depth/2-box_t[0]]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); else if (align=="outside") translate(v=[0,0,-depth/2]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); else echo("invalid alignment", align); } } else if (face=="T") { translate(v=[0,0,box_h/2]) rotate(a=[0,0,0]) translate(v=[(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,+depth/2-box_t[2]]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); else if (align=="outside") translate(v=[0,0,-depth/2]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); else echo("invalid alignment", align); } } else if (face=="S") { translate(v=[0,-box_b/2,0]) rotate(a=[+90,0,0]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,+depth/2-box_t[1]]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else if (align=="outside") translate(v=[0,0,-depth/2]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else echo("invalid alignment", align); } } else if (face=="W") { translate(v=[-box_l/2,0,0]) rotate(a=[0,-90,0]) rotate(a=[0,0,-90]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,+depth/2-box_t[0]]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else if (align=="outside") translate(v=[0,0,-depth/2]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else echo("invalid alignment", align); } } else if (face=="B") { //echo("bottom"); translate(v=[0,0,-box_h/2]) rotate(a=[0,180,0]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,+depth/2-box_t[2]]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else if (align=="outside") translate(v=[0,0,-depth/2]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else echo("invalid alignment", align); } } else { echo("Unknown Face",face); } } } module mouse_ears(box,thickness,radius, has_mouse_ears) { if (has_mouse_ears) union() { translate(v=[box[0]/2,box[1]/2,-box[2]/2]) cylinder(r=radius, center=false); translate(v=[box[0]/2,-box[1]/2,-box[2]/2]) cylinder(r=radius, center=false); translate(v=[-box[0]/2,box[1]/2,-box[2]/2]) cylinder(r=radius, center=false); translate(v=[-box[0]/2,-box[1]/2,-box[2]/2]) cylinder(r=radius, center=false); } } module make_posts(box, posts) { //This will be based on make_cutouts echo ("make_posts"); a_bit=0.01; box_l=box[0];//x box_b=box[1];//y box_h=box[2];//z box_t=[box[5],box[5],box[5]];//wall_t [x,y,z] //% cube(size=[box_l,box_b,box_h],center=true); x_pos = 0; y_pos = 0; face = "X"; echo("len(posts)",len(posts)); for (j=[0:len(posts)-1]) { x_pos = posts[j][2][0]; y_pos = posts[j][2][1]; x_offs= posts[j][2][2]; y_offs= posts[j][2][3]; face = posts[j][0]; shape_type=posts[j][1]; shape_data=posts[j][3]; rotation=posts[j][2][4]; align=posts[j][2][5]; depth=posts[j][3][0]-a_bit; //echo("face",face); if (face=="N") { translate(v=[0,box_b/2,0]) rotate(a=[-90,0,0]) translate(v=[-(x_pos+x_offs),-(y_pos+y_offs),0]) { //echo("alignment", align); if (align=="inside") { // echo("translate by",+depth/2-box_t); translate(v=[0,0,-depth/2-box_t[1]]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); } else if (align=="outside") { // echo("translate by",-depth/2); translate(v=[0,0,-depth/2-a_bit]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); } else { echo("invalid alignment", align); } } } else if (face=="E") { translate(v=[box_l/2,0,0]) rotate(a=[0,90,0]) rotate(a=[0,0,-90]) translate(v=[-(x_pos+x_offs),-(y_pos+y_offs),0]) { // make_shape(shape_type, shape_data); if (align=="inside") translate(v=[0,0,-depth/2-box_t[0]]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); else if (align=="outside") translate(v=[0,0,-depth/2-a_bit]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); else echo("invalid alignment", align); } } else if (face=="T") { echo(face,align); translate(v=[0,0,box_h/2]) rotate(a=[0,0,0]) translate(v=[(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-depth/2-box_t[2]]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); else if (align=="outside") translate(v=[0,0,-depth/2-a_bit]) rotate(a=[0,0,-rotation]) make_shape(shape_type, shape_data); else echo("invalid alignment", align); } } else if (face=="S") { translate(v=[0,-box_b/2,0]) rotate(a=[+90,0,0]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-depth/2-box_t[1]]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else if (align=="outside") translate(v=[0,0,-depth/2-a_bit]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else echo("invalid alignment", align); } } else if (face=="W") { translate(v=[-box_l/2,0,0]) rotate(a=[0,-90,0]) rotate(a=[0,0,-90]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-depth/2-box_t[0]]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else if (align=="outside") translate(v=[0,0,-depth/2-a_bit]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else echo("invalid alignment", align); } } else if (face=="B") { // echo("bottom"); translate(v=[0,0,-box_h/2]) rotate(a=[0,180,0]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-depth/2-box_t[2]]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else if (align=="outside") translate(v=[0,0,-depth/2-a_bit]) rotate(a=[0,0,rotation]) make_shape(shape_type, shape_data); else echo("invalid alignment", align); } } else { echo("Unknown Face",face); } } } module make_shape(shape, shape_data) { a_bit=0.01; // for ensuring manifoldness // shape = // "Cone", "Ellipse", "Cylinder", "Round_Rect", "Square", "Rectangle", // Nub_Post, Dip_Post, Hollow_Cylinder //shape_data=[4,5,4,8];//[4,8,12,20];//[4,2,10];//[4,10,8,2,4];//[5,10];//[2,4,15]; if(shape=="Square"){//[depth, length_breadth] cube(size=[shape_data[1],shape_data[1],shape_data[0]+a_bit],center=true);//do thing for square }else if(shape=="Rectangle"){//[depth, length, breadth] cube(size=[shape_data[1],shape_data[2],shape_data[0]+a_bit],center=true);//do thing for rectangle }else if(shape=="Round_Rect"){//[depth, length, breadth, corner_radius, corner_sides] rounded_rectangle_cylinder_hull(shape_data[1],shape_data[2],shape_data[0]+a_bit, shape_data[3], shape_data[4]); /*hull(){ translate(v=[ shape_data[1]/2 -shape_data[3] , shape_data[2]/2 -shape_data[3] , 0])cylinder(h=shape_data[0]+a_bit, r=shape_data[3], center=true, $fn=4*shape_data[4]); translate(v=[ shape_data[1]/2 -shape_data[3] , -(shape_data[2]/2 -shape_data[3]), 0])cylinder(h=shape_data[0]+a_bit, r=shape_data[3], center=true, $fn=4*shape_data[4]); translate(v=[ -(shape_data[1]/2 -shape_data[3]), -(shape_data[2]/2 -shape_data[3]), 0])cylinder(h=shape_data[0]+a_bit, r=shape_data[3], center=true, $fn=4*shape_data[4]); translate(v=[ -(shape_data[1]/2 -shape_data[3]), shape_data[2]/2 -shape_data[3] , 0])cylinder(h=shape_data[0]+a_bit, r=shape_data[3], center=true, $fn=4*shape_data[4]); }*/ }else if(shape=="Cylinder"){ //(depth, radius ,sides) cylinder(r=shape_data[1],h=shape_data[0]+a_bit,center=true, $fn=shape_data[2]);//do thing for cylinder }else if(shape=="Ellipse"){ //(depth, radius_length, radius_breadth, sides) scale (v=[shape_data[1],shape_data[2],1])cylinder(r=1,h=shape_data[0]+a_bit,center=true, $fn=shape_data[3]);//do thing for ellipse }else if(shape=="Cone"){ //(depth, radius_bottom, radius_top ,sides) cylinder(r1=shape_data[1],r2=shape_data[2],h=shape_data[0]+a_bit,center=true, $fn=shape_data[3]);//do thing for cone }else if(shape=="Nub_Post"){ //(depth, radius_bottom, radius_top , depth_nub, sides) union(){ echo ("make nub",shape_data); cylinder(r=shape_data[1], h=shape_data[0]+a_bit,center=true, $fn=shape_data[4]);//do thing for cylinder outside //cylinder(r=max(shape_data[2],shape_data[1]), h=shape_data[0]+a_bit,center=true, $fn=shape_data[3]);//do thing for cylinder outside //translate(v=[0,0,(shape_data[0]-shape_data[3])/2]) cylinder(r=min(shape_data[2],shape_data[1]), h=shape_data[0]+a_bit,center=true, $fn=shape_data[3]);//do thing for cylinder inside translate(v=[0,0,(-shape_data[0]+shape_data[3])/2]) cylinder(r=shape_data[2], h=shape_data[0]+a_bit,center=true, $fn=shape_data[4]);//do thing for cylinder inside } }else if(shape=="Dip_Post"){ //(depth, radius_bottom, radius_top ,depth_dip, sides) difference(){ echo("dip_post",shape_data); cylinder(r=shape_data[1],h=shape_data[0]+a_bit, center=true,$fn=shape_data[4]);//do thing for cylinder outside //cylinder(r=max(shape_data[2],shape_data[1]), h=shape_data[0]+a_bit,center=true, $fn=shape_data[3]);//do thing for cylinder outside //translate(v=[0,0,(shape_data[0]+shape_data[3])/2]) cylinder(r=min(shape_data[2],shape_data[1]), h=shape_data[0]+2*a_bit,center=true, $fn=shape_data[3]);//do thing for cylinder inside translate(v=[0,0,(-shape_data[0]+shape_data[3])/2]) cylinder(r=shape_data[2], h=shape_data[3]+2*a_bit,center=true, $fn=shape_data[4]);//do thing for cylinder inside } }else if(shape=="Hollow_Cylinder"){ //(depth, radius_outside, radius_inside ,sides) difference(){ cylinder(r=max(shape_data[2],shape_data[1]), h=shape_data[0]+a_bit,center=true, $fn=shape_data[3]);//do thing for cylinder outside cylinder(r=min(shape_data[2],shape_data[1]), h=shape_data[0]+2*a_bit,center=true, $fn=shape_data[3]);//do thing for cylinder inside } }else{ echo("Unsupported Shape",shape); } } module box_type(box, box_type="rounded4sides"){ //basic initial if clause checker will identify if r or s are <=0 or 1 are reverts to a different shape otherwise (simple cuboid) //this will aid in situations such as r<=wall_t so calculated internal r is now 0 or negative which could cause unexpected geometry or crashes if(box_type=="cuboid" || (box[3]<=0 || box[4]<=0)){//|| box[3]<=0 || box[4]=0 cube(size=[box[0],box[1],box[2]],center=true); }else if(box_type=="rounded4sides"){ rounded_rectangle_cylinder_hull(box[0],box[1],box[2],box[3],box[4]); }else if(box_type=="rounded6sides"){ rounded_rectangle_sphere_hull(box[0],box[1],box[2],box[3],box[4]); }else if(box_type=="chamfered6sides"){ chamfered_rectangle_hull(box[0],box[1],box[2],box[3]); }else{ echo ("unknown box type requested",box_type); } } module chamfered_rectangle_hull(x,y,z,r){ hull() { cross_box(x,y,z,r); // This is to ensure the overall dimensions stay true to those // requested even for low-poly cylinders } } module rounded_rectangle_sphere_hull(x,y,z,r,s){ hull() { cross_box(x,y,z,r); // This is to ensure the overall dimensions stay true to those // requested even for low-poly cylinders translate(v=[ x/2 -r , y/2 -r , z/2 -r ]) sphere(r=r, $fn=4*s); translate(v=[ x/2 -r , -(y/2 -r), z/2 -r ]) sphere(r=r,$fn=4*s); translate(v=[ -(x/2 -r), -(y/2 -r), z/2 -r ]) sphere(r=r,$fn=4*s); translate(v=[ -(x/2 -r), y/2 -r , z/2 -r ]) sphere(r=r,$fn=4*s); translate(v=[ x/2 -r , y/2 -r , -(z/2 -r)]) sphere(r=r, $fn=4*s); translate(v=[ x/2 -r , -(y/2 -r), -(z/2 -r)]) sphere(r=r, $fn=4*s); translate(v=[ -(x/2 -r), -(y/2 -r), -(z/2 -r)]) sphere(r=r, $fn=4*s); translate(v=[ -(x/2 -r), y/2 -r , -(z/2 -r)]) sphere(r=r, $fn=4*s); } } module make_items(box, items) { // This will be based on make_cutouts // External items on faces: [ // face_name, external_file, // shape_position[ // x_pos,y_pos,x_offs,y_offs,rotate,align], // shape_size[ // scale_z,scale_x,scale_y,mirror]] // Note: for silly reasons mirror must be 0 or 1 corresponding to // false and true in this version // Example: ["N", "tyndall_logo_v0_2.stl", [0,0,0,0,0,"outside"], // [1,1,1,0]] echo ("make_items"); a_bit=0.01; box_l=box[0];//x box_b=box[1];//y box_h=box[2];//z box_t=[box[5],box[5],box[5]]; // wall_t [x,y,z] // %cube(size=[box_l,box_b,box_h],center=true); x_pos = 0; y_pos = 0; face = "X"; echo("len(items)",len(items)); for (j=[0:len(items)-1]) { face = items[j][0]; items_to_use=items[j][1]; x_pos = items[j][2][0]; y_pos = items[j][2][1]; x_offs= items[j][2][2]; y_offs= items[j][2][3]; rotation=items[j][2][4]; align=items[j][2][5]; scale_z=items[j][3][3]; scale_x=items[j][3][1]; scale_y=items[j][3][2]; items_mirror=items[j][3][4]; depth=items[j][3][0]; //echo("items face",face); if (face=="N") mirror(v=[items_mirror,0,0]) { translate(v=[0,box_b/2,0]) rotate(a=[-90,0,0]) translate(v=[-(x_pos+x_offs),-(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[1]]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else echo("invalid alignment", align); } } else if (face=="E") mirror(v=[0,items_mirror,0]) { translate(v=[box_l/2,0,0]) rotate(a=[0,90,0]) rotate(a=[0,0,-90]) translate(v=[-(x_pos+x_offs),-(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[0]]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else echo("invalid alignment", align); } } else if (face=="T") mirror(v=[items_mirror,0,0]) { translate(v=[0,0,box_h/2]) rotate(a=[0,0,0]) translate(v=[(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[2]]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else echo("invalid alignment", align); } } else if (face=="S") mirror(v=[items_mirror,0,0]) { translate(v=[0,-box_b/2,0]) rotate(a=[+90,0,0]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[1]]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else echo("invalid alignment", align); } } else if (face=="W") mirror(v=[0,items_mirror,0]) { translate(v=[-box_l/2,0,0]) rotate(a=[0,-90,0]) rotate(a=[0,0,-90]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[0]]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else echo("invalid alignment", align); } } else if (face=="B") mirror(v=[items_mirror,0,0]) { translate(v=[0,0,-box_h/2]) rotate(a=[0,180,0]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[2]]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) scale(v=[scale_x,scale_y,scale_z]) import(items_to_use); else echo("invalid alignment", align); } } else { echo("Unknown Face",face); } } } module make_texts(box, items) { // External items on faces: [ // face_name, string, // shape_position[ // x_pos,y_pos,x_offs,y_offs,rotate,align], // shape_size[ // scale_z,scale_x,scale_y,mirror]] // shape_position[ // x_pos,y_pos,x_offs,y_offs,rotate,align], // shape_size[depth,font_hight,font_spacing,mirror] // Note: for silly reasons mirror must be 0 or 1 corresponding to // false and true in this version // Example: ["N", "tyndall_logo_v0_2.stl", [0,0,0,0,0,"outside"], // [1,1,1,0]] echo ("make_items"); a_bit=0.01; box_l=box[0];//x box_b=box[1];//y box_h=box[2];//z box_t=[box[5],box[5],box[5]]; // wall_t [x,y,z] // %cube(size=[box_l,box_b,box_h],center=true); x_pos = 0; y_pos = 0; face = "X"; echo("len(items)",len(items)); for (j=[0:len(items)-1]) { face = items[j][0]; text_to_type=items[j][1]; x_pos = items[j][2][0]; y_pos = items[j][2][1]; x_offs= items[j][2][2]; y_offs= items[j][2][3]; rotation=items[j][2][4]; align=items[j][2][5]; depth=texts[j][3][0]; text_hight=texts[j][3][1]; text_mirror=texts[j][3][2]; //echo("items face",face); if (face=="N") mirror(v=[text_mirror,0,0]) { translate(v=[0,box_b/2,0]) rotate(a=[-90,0,0]) translate(v=[-(x_pos+x_offs),-(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[1]-a_bit]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else echo("invalid alignment", align); } } else if (face=="E") mirror(v=[0,text_mirror,0]) { translate(v=[box_l/2,0,0]) rotate(a=[0,90,0]) rotate(a=[0,0,-90]) translate(v=[-(x_pos+x_offs),-(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[0]-a_bit]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else echo("invalid alignment", align); } } else if (face=="T") mirror(v=[text_mirror,0,0]) { translate(v=[0,0,box_h/2]) rotate(a=[0,0,0]) translate(v=[(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[2]-a_bit]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else echo("invalid alignment", align); } } else if (face=="S") mirror(v=[text_mirror,0,0]) { translate(v=[0,-box_b/2,0]) rotate(a=[+90,0,0]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[1]-a_bit]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else echo("invalid alignment", align); } } else if (face=="W") mirror(v=[0,text_mirror,0]) { translate(v=[-box_l/2,0,0]) rotate(a=[0,-90,0]) rotate(a=[0,0,-90]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[0]-a_bit]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else echo("invalid alignment", align); } } else if (face=="B") mirror(v=[text_mirror,0,0]) { translate(v=[0,0,-box_h/2]) rotate(a=[0,180,0]) translate(v=[-(x_pos+x_offs),(y_pos+y_offs),0]) { if (align=="inside") translate(v=[0,0,-box_t[2]-a_bit]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else if (align=="outside") translate(v=[0,0,-depth]) rotate(a=[0,0,-rotation]) extrude_text( text_to_type, text_hight, depth+a_bit, font_name); else echo("invalid alignment", align); } } else { echo("Unknown Face",face); } } } module extrude_text(string, hight, depth, font_name) { linear_extrude(depth) { text(text=string, size=hight, font=font_name); } }
-- Complexity: O(n) fib :: Int -> Int fib n = aux n 1 1 where aux 0 val1 val2 = val1 aux 1 val1 val2 = val2 aux n val1 val2 = aux (n-1) val2 (val1 + val2) main :: IO () main = print $ fib 47
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>axios創建實例對象</title> <link crossorigin="annoymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> </head> <body> <div class="container"> <h2 class="page-header">其他使用</h2> <button class="btn btn-primary">發送GET請求</button> <button class="btn btn-warning">發送POST請求</button> <button class="btn btn-success">發送PUT請求</button> <button class="btn btn-danger">發送DELETE請求</button> </div> <script> // 獲取按鈕 const btns = document.querySelectorAll("button"); // 創建實例對象 const duanzi = axios.create({ baseURL: "https://api.apiopen.top", timeout: 2000, }); // duanzi 和 axios 對象的功能近乎一樣的 // duanzi({ // url: "/", // }).then((response) => { // console.log(response); // }); // const another = axios.create({ // baseURL: "https://b.com", // timeout: 2000, // }); duanzi.get("/sentences").then((response) => { console.log(response.data); }); </script> </body> </html>
import * as React from 'react'; import { useState, useContext } from 'react'; import Typography from '@mui/material/Typography'; import { TextField } from '@mui/material'; import Button from '@mui/material/Button'; import Container from '@mui/material/Container'; import { SocketContext } from '../../Context'; import Grid from '@mui/material/Grid'; const SocialForm = () => { const { sociallinks, setSociallinks, updateSociallink } = useContext(SocketContext); const [inputFields, setInputFields] = useState([...sociallinks]); const addInputField = () => { setInputFields([{ icon: '', url: '' }, ...inputFields]); }; const deleteInputField = (index) => () => { const updatedInputFields = [...inputFields]; updatedInputFields.splice(index, 1); setInputFields(updatedInputFields); }; const updateSocial = () => { setSociallinks([...inputFields]); localStorage.setItem('social', JSON.stringify([...inputFields])); console.log("social: " + localStorage.getItem('social')); for (let i in inputFields) { updateSociallink(i, inputFields[i].icon, inputFields[i].url); } }; const handleInputIcon = (index, event) => { const val = event.target.value; const updatedInputFields = [...inputFields]; updatedInputFields[index].icon = val; setInputFields(updatedInputFields); }; const handleInputUrl = (index, event) => { const val = event.target.value; const updatedInputFields = [...inputFields]; updatedInputFields[index].url = val; setInputFields(updatedInputFields); }; return ( <> <Container maxWidth='xl' sx={{ paddingTop: 3 }}> <Button variant='contained' onClick={() => addInputField()} sx={{ width: '20%', height: '10%' }}> Add Social </Button> <Button variant='contained' onClick={() => updateSocial()} sx={{ width: '20%', height: '10%', marginLeft: 20 }}> Update Social </Button> <Grid> <Grid item sx={{ paddingTop: 3, width: '33%', float: 'left' }}> <Typography sx={{ paddingTop: 1 }}>Social Icon Link:</Typography> {inputFields.map((inputField, index) => ( <TextField required key={index} value={inputField.icon} onChange={(e) => handleInputIcon(index, e)} style={{ marginTop: '10px', paddingRight: 10, width: '100%' }} /> ))} </Grid> <Typography sx={{ paddingTop: 4 }}>Social Url:</Typography> <Grid item sx={{ paddingTop: 0, float: 'left', width: '33%' }}> {inputFields.map((inputField, index) => ( <TextField required key={index} value={inputField.url} onChange={(e) => handleInputUrl(index, e)} style={{ marginTop: '10px', paddingRight: 10, width: '100%' }} /> ))} </Grid> <Grid item sx={{ marginTop: 1.5, float: 'left', width: '33%', alignContents: 'center' }}> {inputFields.map((inputField, index) => ( <Button variant='contained' onClick={deleteInputField(index)} sx={{ width: '70%', height: '100%', marginBottom: 3.8 }} > Delete </Button> ))} </Grid> </Grid> </Container> </> ); }; export default SocialForm;
describe("Custom Command", () => { // url: https://magento.softwaretestingboard.com // email: [email protected] // password: *9kjceG5*TSWXhb let loginDetails; before(() => { cy.fixture("magentoLoginCredentials").then((loginCredentials) => { loginDetails = loginCredentials; }) }); beforeEach(() => { cy.visit("https://magento.softwaretestingboard.com"); }); it("Magento - Geçerli verilerle login olma testi", () => { cy.magentoLogin(loginDetails.validEmail, loginDetails.validPassword); }); it("Magento - Geçersiz kullanıcı adı ile login olma testi", () => { cy.magentoLogin(loginDetails.invalidEmail, loginDetails.validPassword); }); it("Magento - Geçersiz şifre ile login olma testi", () => { cy.magentoLogin(loginDetails.validEmail, loginDetails.invalidPassword); }); it("Magento - Geçerli kullanıcı adı ve geçersiz şifre login olma testi", () => { cy.magentoLogin(loginDetails.invalidEmail, loginDetails.invalidPassword); }); });
import { Result, wrapResult } from "../../result/result"; import { dataview } from "./util"; export const FLOAT16_SIZE = 2; /** * read 16 bit (half precision) floating point number big endian * @param buffer * @param offset * @returns float */ export const readFloat16be = (buffer: Uint8Array, offset: number): Result<number, RangeError> => { if (buffer.byteLength < offset + FLOAT16_SIZE) return new RangeError("offset is outside the bounds of the DataView"); return getFloat16(buffer, offset); }; /** * read 16 bit (half precision) floating point number little endian * @param buffer * @param offset * @returns float */ export const readFloat16le = (buffer: Uint8Array, offset: number): Result<number, RangeError> => { if (buffer.byteLength < offset + FLOAT16_SIZE) return new RangeError("offset is outside the bounds of the DataView"); return getFloat16(buffer, offset, true); }; export const FLOAT32_SIZE = 4; /** * read 32 bit (single precision) floating point number big endian * @param buffer * @param offset * @returns float */ export const readFloat32be = (buffer: Uint8Array, offset: number): Result<number, RangeError> => { return wrapResult(() => dataview(buffer).getFloat32(offset)); }; /** * read 32 bit (single precision) floating point number little endian * @param buffer * @param offset * @returns float */ export const readFloat32le = (buffer: Uint8Array, offset: number): Result<number, RangeError> => { return wrapResult(() => dataview(buffer).getFloat32(offset, true)); }; export const FLOAT64_SIZE = 8; /** * read 64 bit (single precision) floating point number big endian * @param buffer * @param offset * @returns float */ export const readFloat64be = (buffer: Uint8Array, offset: number): Result<number, RangeError> => { return wrapResult(() => dataview(buffer).getFloat64(offset)); }; /** * read 64 bit (single precision) floating point number little endian * @param buffer * @param offset * @returns float */ export const readFloat64le = (buffer: Uint8Array, offset: number): Result<number, RangeError> => { return wrapResult(() => dataview(buffer).getFloat64(offset, true)); }; // read functions const getFloat16 = (buffer: Uint8Array, offset: number, littleEndian?: boolean): number => { /* * seee_eeff ffff_ffff * e: 5, f: 10 * s * (2 ** e_eeee - 01111) * 1.ffffffffff * s * (2 ** e_eeee - 01111) * 0.ffffffffff (e == 0_0000 = 0) * s * Infinity (e == 1_1111 = 31, f == 0) * NaN (e == 1_1111 = 31, f != 0) */ const msb = buffer[(littleEndian ? 1 : 0) + offset]; const lsb = buffer[(littleEndian ? 0 : 1) + offset]; const sign = msb >> 7 ? -1 : 1; const exponent = (msb & 0b0111_1100) >> 2; const significant = ((msb & 0b0011) << 8) + lsb; if (exponent === 0) { return sign * significant * Math.pow(2, -24); } if (exponent === 31) { return significant ? Number.NaN : sign * Number.POSITIVE_INFINITY; } return sign * (significant + Math.pow(2, 10)) * Math.pow(2, exponent - 25); };
using HealthChecks.UI.Client; using JS.Contas.Infra.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using JS.WebAPI.Core.Identidade; namespace JS.Contas.API.Configuration { public static class ApiConfig { public static void AddApiConfiguration(this IServiceCollection services, IConfiguration configuration) { services.AddDbContext<ContasContext>(options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"))); services.AddControllers(); services.AddLoggingConfigurations(configuration); services.AddCors(options => { options.AddPolicy("Total", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); } public static IApplicationBuilder UseApiConfiguration(this IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseCors("Total"); app.UseAuthConfiguration(); app.UseMiddleware<ExceptionMiddleware>(); app.UserLoggingConfiguration(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHealthChecks("/api/hc", new HealthCheckOptions() { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); endpoints.MapHealthChecksUI(options => { options.UIPath = "/api/hc-ui"; options.ResourcesPath = "/api/hc-ui-resources"; options.UseRelativeApiPath = false; options.UseRelativeResourcesPath = false; options.UseRelativeWebhookPath = false; }); }); return app; } } }
<template> <div class="form-list flex-grow-1 flex-column d-flex mw-100 ms-user-management"> <div class="d-flex flex-row title-box align-items-center gap-2"> <div class="icon24 back pointer" @click="this.$router.go(-1)"></div> <div class="list-title flex-grow-1 text-start">Quản lý người dùng</div> </div> <div class="flex1 d-flex flex-column position-relative"> <TabView class="flex1 d-flex flex-column" :pt="{ panelContainer: { class: 'flex1 d-flex flex-column' }, }"> <TabPanel :header="MESSAGE.USER_ADDED"> <header class="flex pb-24"> <h3 class="flex flex-1 text-head-l font-semibold text-gray-1 items-center"> {{ MESSAGE.USER_ADDED }} </h3> </header> <div class="d-flex gap-2 mb-5 align-items-center"> <div class="d-flex gap-3 flex-grow-1"> <MultiSelect v-model="selectedRoles" :options="roles.roles" :showToggleAll="false" optionLabel="role_name" :emptyMessage="MESSAGE.EMPTY_DROPDOWN" :placeholder="MESSAGE.ROLES" display="chip" class="ms-category max-w-266 text-start"></MultiSelect> <InputText v-model="searchEmail" :placeholder="MESSAGE.ENTER_YOUR_EMAIL_ADDRESS"></InputText> </div> <div class="theme-arco-divider-vertical mx-16"></div> <div> <Button @click="resetUserSearch" class="ms-btn secondary d-flex justify-content-center flex-grow-1 ms-btn_search ps-3 pe-3 gap-2"> <div class="fw-medium">Đặt lại</div> </Button> </div> </div> <div class="flex1 flex-grow-1"> <DataTable :rows="10" class="flex1 flex-column mh-100 mw-100" :class="{ 'loading': isLoading }" :loading="isLoading" scrollable :value="isLoading ? Array.from({ length: 10 }, () => ({ ...{} })) : data" @rowDblclick="onRowSelect($event.data)" tableStyle="min-width: 100%" rowHover> <template #paginatorstart> <Button type="button" icon="pi pi-refresh" text/> </template> <template #paginatorend> bản ghi/trang </template> <template #empty> <div class="d-flex flex-column p-24 justify-content-center align-items-center"> <div class="icon-empty_table"></div> <div>Không tìm thấy kết quả nào</div> </div> </template> <Column field="warehouse_name" style="min-width: 200px" :header="MESSAGE.USER_EMAIL"> <template #body="{ data, field, slotProps }"> <div v-if="!isLoading"> {{ data[field] }}</div> <div v-else> <Skeleton></Skeleton> </div> </template> </Column> <Column field="detailed_address" style="min-width: 500px" dataKey="id" :header="MESSAGE.ROLES"> <template #body="{ data, field, slotProps }"> <div v-if="!isLoading"> <div v-if="data[field]"> {{ data[field] }} </div> <div class="d-flex status-ctn max-content" v-else style="background-color: rgb(254, 243, 231);"> <div class="status-dot" style="background-color: rgb(243, 141, 21);"></div> <div class="status-text" style="color: rgb(243, 141, 21);">Chưa cài đặt</div> </div> </div> <div v-else> <Skeleton></Skeleton> </div> </template> </Column> <Column field="warehouse_contact" style="min-width: 180px" dataKey="id" :header="MESSAGE.ACT"> <template #body="{ data, field, slotProps }"> <div v-if="!isLoading"> <div v-if="data[field]"> {{ data[field] }} </div> <div class="d-flex status-ctn max-content" v-else style="background-color: rgb(254, 243, 231);"> <div class="status-dot" style="background-color: rgb(243, 141, 21);"></div> <div class="status-text" style="color: rgb(243, 141, 21);">Chưa cài đặt</div> </div> </div> <div v-else> <Skeleton></Skeleton> </div> </template> </Column> </DataTable> </div> </TabPanel> <TabPanel :header="MESSAGE.ROLE_ADDED"> <header class="flex pb-24"> <h3 class="flex flex-1 text-head-l font-semibold text-gray-1 items-center"> {{ MESSAGE.ROLE_ADDED }} </h3> </header> <div class="d-flex gap-2 mb-5 align-items-center"> <div class="d-flex gap-3 flex-grow-1"> <SelectButton v-model="selectedTypeRole" @change="changeRoleType" :options="roles.types" class="ms-btn ms-selectbutton_roles" optionLabel="description" multiple aria-labelledby="multiple"/> </div> <div class="theme-arco-divider-vertical mx-16"></div> <div> <Button @click="resetRoleSearch" class="ms-btn secondary d-flex justify-content-center flex-grow-1 ms-btn_search ps-3 pe-3 gap-2"> <div class="fw-medium">Đặt lại</div> </Button> </div> </div> <div class="flex1 flex-grow-1"> <DataTable :rows="10" class="flex-column mw-100 mh-100 ms-table_roles" :class="{ 'loading': isLoading }" :loading="isLoading" scrollable :value="isLoading ? Array.from({ length: 10 }, () => ({ ...{} })) : roles.roleSearch" @rowDblclick="onRowSelect($event.data)" tableStyle="min-width: 100%" rowHover> <template #paginatorstart> <Button type="button" icon="pi pi-refresh" text/> </template> <template #paginatorend> bản ghi/trang </template> <template #empty> <div class="d-flex flex-column p-24 justify-content-center align-items-center"> <div class="icon-empty_table"></div> <div>Không tìm thấy kết quả nào</div> </div> </template> <Column field="role_name" style="min-width: 200px; max-width: 200px" :header="MESSAGE.ROLE_NAME"> <template #body="{ data, field, slotProps }"> <div v-if="!isLoading" class="truncate-text-3"> {{ data[field] }}</div> <div v-else> <Skeleton></Skeleton> </div> </template> </Column> <Column field="description" style="min-width: 170px; max-width: 170px" dataKey="id" :header="MESSAGE.DESCRIPTION"> <template #body="{ data, field, slotProps }"> <div v-if="!isLoading" class="truncate-text-3" v-tooltip="data[field]"> {{ data[field] }} </div> <div v-else> <Skeleton></Skeleton> </div> </template> </Column> <Column field="role_type" style="min-width: 170px; max-width: 170px" dataKey="id" :header="MESSAGE.TYPE"> <template #body="{ data, field, slotProps }"> <div v-if="!isLoading" class="truncate-text-3"> {{ data[field] }} </div> <div v-else> <Skeleton></Skeleton> </div> </template> </Column> <Column frozen align-frozen="right" field="permissions" style="min-width: 300px; max-width: 300px" dataKey="id" :header="MESSAGE.PERMISSION"> <template #body="{ data, field, slotProps }"> <div v-if="!isLoading" class="truncate-text-3" v-tooltip="data[field]"> {{ data[field] }} </div> <div v-else> <Skeleton></Skeleton> </div> </template> </Column> </DataTable> </div> </TabPanel> </TabView> <div class="position-absolute end-0 mt-2"> <SplitButton class="ms-btn ms-spit-button_group primary d-flex justify-content-center flex-grow-1 ms-btn_search gap-2" label="Tạo mới" :model="splitButtonItems"></SplitButton> </div> </div> </div> <Dialog v-model:visible="isCreateUser" modal :header="MESSAGE.ADD_USERS" :style="{ width: '40rem' }"> <div> <div class="theme-m4b-alert theme-m4b-alert-info d-flex gap-2 mb-4 align-items-center"> <div class="icon icon-info"></div> <div class="title">Mỗi vai trò có các quyền khác nhau. Vui lòng đọc kỹ các mô tả vai trò trước khi chọn vai trò thích hợp. </div> </div> <div class="group-form_box mb-3"> <div class="label d-flex flex-column gap-2"> Vai trò <MultiSelect v-model="selectedAddRoles" :options="roles.roles" :showToggleAll="false" optionLabel="role_name" :emptyMessage="MESSAGE.EMPTY_DROPDOWN" :placeholder="MESSAGE.ROLES" display="chip" class="ms-category w-100 text-start"> <template #option="{option}"> <div v-tooltip="option.description">{{ option.role_name }}</div> </template> </MultiSelect> </div> <div class="ms-error-text"></div> </div> <div class="group-form_box mb-4"> <div class="label d-flex flex-column gap-2"> Địa chỉ email <InputText v-model="selectedAddEmail" :placeholder="MESSAGE.ENTER_YOUR_EMAIL_ADDRESS"></InputText> </div> <div class="ms-error-text"></div> </div> </div> <template #footer> <div class="d-flex flex-row"> <div class="flex1"></div> <Button class="ms-btn secondary d-flex justify-content-center ms-btn_search ps-3 pe-3 gap-2 me-2" @click="isCreateUser = false"> <div class="">Hủy</div> </Button> <Button @click="cropImage" class="ms-btn primary blue d-flex justify-content-center flex-grow-1 ms-btn_search ps-3 pe-3 gap-2"> <div class="fw-semibold">{{ MESSAGE.SEND }}</div> </Button> </div> </template> </Dialog> <Dialog v-model:visible="isCreateRole" modal :header="MESSAGE.ADD_NEW_ROLES" :style="{ width: '40rem' }"> <div> <div class="theme-m4b-alert theme-m4b-alert-info d-flex gap-2 mb-4 align-items-center"> <div class="icon icon-info"></div> <div class="title">Bạn có thể tạo vai trò mới khi cần thiết. Sau khi tạo vai trò mới, hãy thiết lập quyền của họ. </div> </div> <div class="group-form_box mb-3"> <div class="label d-flex flex-column gap-2"> {{ MESSAGE.ROLE_NAME }} <InputText v-model="selectedAddEmail" :placeholder="MESSAGE.PLEASE_ENTER_A_ROLE_NAME"></InputText> </div> <div class="ms-error-text"></div> </div> <div class="group-form_box mb-4"> <div class="label d-flex flex-column gap-2"> {{ MESSAGE.ROLE_DESCRIPTION }} <InputText v-model="selectedAddEmail" :placeholder="MESSAGE.PLEASE_DESCRIBE_THE_ROLE"></InputText> </div> <div class="ms-error-text"></div> </div> <div class="group-form_box mb-4"> <div class="label d-flex flex-column gap-2"> {{ MESSAGE.SET_PERMISSIONS }} <MultiSelect v-model="selectedAddRoles" :options="roles.roles" :showToggleAll="false" optionLabel="role_name" :emptyMessage="MESSAGE.EMPTY_DROPDOWN" :placeholder="MESSAGE.SELECT_PERMISSION_WANT_GRANT" display="chip" class="ms-category w-100 text-start"></MultiSelect> </div> <div class="ms-error-text"></div> </div> </div> <template #footer> <div class="d-flex flex-row"> <div class="flex1"></div> <Button class="ms-btn secondary d-flex justify-content-center ms-btn_search ps-3 pe-3 gap-2 me-2" @click="isCreateUser = false"> <div class="">Hủy</div> </Button> <Button @click="cropImage" class="ms-btn primary blue d-flex justify-content-center flex-grow-1 ms-btn_search ps-3 pe-3 gap-2"> <div class="fw-semibold">{{ MESSAGE.SEND }}</div> </Button> </div> </template> </Dialog> </template> <script> import TabView from 'primevue/tabview'; import TabPanel from 'primevue/tabpanel'; import InputText from 'primevue/inputtext'; import Button from 'primevue/button'; import SplitButton from 'primevue/splitbutton'; import Dialog from 'primevue/dialog'; import Skeleton from 'primevue/skeleton'; import DataTable from 'primevue/datatable'; import Column from 'primevue/column'; import SelectButton from 'primevue/selectbutton'; import Dropdown from 'primevue/dropdown'; import MultiSelect from 'primevue/multiselect'; import {getRoles, getRoleByType} from "@/api/role"; import {MESSAGE} from "@/common/enums"; export default { computed: { MESSAGE() { return MESSAGE } }, components: { Button, InputText, Skeleton, DataTable, Column, TabView, TabPanel, Dropdown, MultiSelect, SelectButton, SplitButton, Dialog, }, data() { return { isLoading: false, data: [], selectedRoles: null, selectedAddRoles: null, selectedAddEmail: null, searchEmail: null, selectedTypeRole: [], roles: { roles: [], types: [], roleSearch: [], }, isCreateUser: false, isCreateRole: false, splitButtonItems: [ { label: 'Thêm người dùng', command: () => { this.createNew(1) } }, { label: 'Thêm vai trò', command: () => { this.createNew(2) } } ], } }, methods: { /** * Sự kiện chọn role hiển thị */ changeRoleType() { this.roles.roleSearch = this.roles.roles.filter(item => { if (this.selectedTypeRole.filter(role => { return role.description === item.role_type || this.selectedTypeRole.includes(this.roles.types[0]) }).length > 0) { return item; } }) }, /** * Click button tạo mới * @param type */ createNew(type) { switch (type) { // thêm người dùng case 1: this.isCreateUser = true; break; // thêm vai trò case 2: this.isCreateRole = true; break; } }, /** * Click nút đặt lại vai trò tìm kiếm */ resetRoleSearch() { this.selectedTypeRole = []; this.selectedTypeRole.push(this.roles.types[0]) this.roles.roleSearch = this.roles.roles; }, /** * Click nút đặt lại tìm kiếm người dùng */ resetUserSearch() { this.searchEmail = null; this.selectedRoles = null; }, /** * Lấy danh sách kho */ loadRole() { this.isLoading = true; getRoles().then(res => { this.roles = res.data this.roles.roleSearch = res.data.roles this.selectedTypeRole.push(res.data.types[0]) }).catch(error => { console.log(error) }).finally(() => { setTimeout(() => { this.isLoading = false; }, 350) }) } }, created() { this.loadRole() } } </script> <style lang="scss"> .ms-user-management { .theme-arco-divider-vertical { border-left: 1px solid rgba(0, 0, 0, .1); display: inline-block; height: 20px; margin: 0; max-width: 1px; min-width: 1px; vertical-align: middle; } .ms-table_roles { tr { max-height: 33px; td { white-space: wrap !important; max-height: 33px; .truncate-text-3 { margin-top: 12px; margin-bottom: 12px; } } } } .p-tabview-nav-container { margin-bottom: 16px; .p-tabview-nav-content { .p-tabview-nav { border: unset; background: transparent; .p-tabview-header { border: unset; .p-tabview-nav-link { border: unset; font-size: 16px; font-weight: 500; background: transparent; } &.p-highlight { border-bottom: 1px solid #FA8232; .p-tabview-nav-link { border-bottom: 1px solid #FA8232; } } } } } } .p-tabview-panels { display: flex; border-radius: 8px; flex: 1; .p-tabview-panel { display: flex; flex-direction: column; flex: 1; min-height: 0; .p-datatable { flex-grow: 1; border: 1px solid #e0e0e0; border-radius: 4px; .p-datatable-table { &:not(.loading) .p-datatable-tbody > tr.p-datatable-emptymessage > td, &:not(.loading) .p-datatable-tbody > tr:last-child > td { border-bottom: none !important; } } } } } } </style>
const emailPattern = /([a-z0-9][-a-z0-9_\+\.]*[a-z0-9])@([a-z0-9][-a-z0-9\.]*[a-z0-9]\.(arpa|root|aero|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|([0-9]{1,3}\.{3}[0-9]{1,3}))/; const app = Vue.createApp({ data: () => ({ firstName: '', lastName: '', userName: '', password: '', confirm: '', email: '', addy: '', suburb: '', postcode: '', mobile: '', nameRules: [ v => !!v || 'Name Required', v => (v && /^[A-z]*$/.test(v)) || 'Name must be letters only' ], userNameRules: [ v => !!v || 'User Name required', v => (v && v.length >= 3) || 'User Name must be at least 3 characters' ], passwordRules: [ v => !!v || 'Password required', v => (v && v.length >= 8) || 'Password must be at least 8 characters', v => (v && /[$%^&*]/.test(v)) || 'Password must contain one of the following characters: $, %, ^, &, or *' ], emailRules: [ v => !!v || 'Email required', v => (v && emailPattern.test(v)) || 'Email must be a valid address' ], addyRules: [ v => (!v || v.length <= 40) || 'Street Address is optional but must be 40 characters maximum if specified' ], suburbRules: [ v => (!v || v.length <= 20) || 'Suburb is optional but must be 20 characters maximum if specified' ], postcodeRules: [ v => !!v || 'Postcode is required', v => (v && v.length === 4) || 'Postcode must be 4 digits', ], mobileRules: [ v => !!v || 'Mobile is required', v => v && /^04/.test(v) || 'Mobile must start with digits 04', v => v && v.length >= 10 || 'Mobile must be at least 10 digits' ], termsVisible: false }), methods: { toggleTerms: function() { this.termsVisible = !this.termsVisible; } }, computed: { confirmRule() { return () => this.confirm === this.password || 'Passwords must match' } } }); app.use(Vuetify.createVuetify()).mount('#app');
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Conjugaison du verbe receler</title> <style> body{ background: #DDD; text-align: center; padding: 10px 0; } section{ background: #CCC; padding: 10px; } .title{ background: #8e44ad; padding: 10px 5px; border-radius: 30px; color: #d8d6d6; font-size: 16px; margin-top: 0px; } .more_info{ padding: 10px 25px; border-radius: 10px; margin: auto; } .subtitle{ font-size: 22px; color: #2424b3; margin: 18px; } table{ width:100%; } table th{ background: #2980b9; color: #ecf0f1; border: 2px solid #2980b9; font-size: 14px; } .lastpad{ padding-bottom: 20px; } .phrase{ padding: 10px; } .more_info p{ color: #5f5f5f; font-size: 10px; font-style: italic; } .phrase{ font-size: 14px; color: #2424b3; margin: 10px 0; background: #DDD; padding: 20px; border-radius: 15px; } .div_infos{ padding: 10px; border-collapse: collapse; font-size: 14px; border-radius: 10px; } #info{ cackground: #95a5a6; } #info span{ color: #76140a; } .more_info, .div_infos, table, th, td { border-collapse: collapse; background: #ecf0f1; font-size: 12px; } th, td { padding: 10px; border-left: 2px solid #2980b9; border-right: 2px solid #2980b9; color: #000; font-weight: bold; } span{ color: #e74c3c; letter-spacing: inherit; } h6{ background: #8e44ad; padding: 10px 5px; border-radius: 30px; color: #d8d6d6; font-size: 14px; margin-bottom: 5px; margin-top: 10px; } .copyright{ font-size: 10px; color: #0270b9; } </style> </head> <body> <section> <h3 class="title"> Conjugaison du verbe receler</h3> <div class="div_infos" id="info"> <h3>Le verbe receler est du <span>premier groupe.</span> </h3> <p>Le verbe receler se conjugue avec l'auxiliaire avoir receler au féminin | receler à la voix passive | receler ? | ne pas receler </p> </div> <h5 class="subtitle">Indicatif</h5> <div> <table> <tr> <th>Présent</th> <th>Passé composé</th> </tr> <tr> <td>Je recèl<span>e</span> </td> <td>J'ai recel<span>é</span></td> </tr> <tr> <td>Tu recèl<span>es</span> </td> <td>Tu as recel<span>é</span></td> </tr> <tr> <td>Il recèl<span>e</span> </td> <td>Il a recel<span>é</span></td> </tr> <tr> <td>Elle recèl<span>e</span> </td> <td>Elle a recel<span>é</span></td> </tr> <tr> <td>Nous recel<span>ons</span> </td> <td>Nous avons recel<span>é</span></td> </tr> <tr> <td>vous recel<span>ez</span> </td> <td>vous avez recel<span>é</span></td> </tr> <tr> <td>Ils recèl<span>ent</span> </td> <td>Ils ont recel<span>é</span></td> </tr> <tr> <td>Elles recèl<span>ent</span> </td> <td>Elles ont recel<span>é</span></td> </tr> </table> </div> <hr> <div> <table> <tr> <th>Imparfait</th> <th>Plus-que-parfait</th> </tr> <tr> <td>Je recel<span>ais</span></td> <td>J'avais recel<span>é</span></td> </tr> <tr> <td>Tu recel<span>ais</span></td> <td>Tu avais recel<span>é</span></td> </tr> <tr> <td>Il recel<span>ait</span></td> <td>Il avait recel<span>é</span></td> </tr> <tr> <td>Nous recel<span>ions</span></td> <td>Nous avions recel<span>é</span></td> </tr> <tr> <td>Vous recel<span>iez</span></td> <td>Vous aviez recel<span>é</span></td> </tr> <tr> <td>Ils recel<span>aient</span></td> <td class="lastpad">Ils avaient recel<span>é</span></td> </tr> </table> </div> <hr> <div> <table> <tr> <th>Passé simple</th> <th>Passé antérieur</th> </tr> <tr> <td>Je recel<span>ai</span></td> <td>J'eus recel<span>é</span></td> </tr> <tr> <td>Tu recel<span>as</span></td> <td>Tu eus recel<span>é</span></td> </tr> <tr> <td>Il recel<span>a</span></td> <td>Il eut recel<span>é</span></td> </tr> <tr> <td>Nous recel<span>âmes</span></td> <td>Nous eûmes recel<span>é</span></td> </tr> <tr> <td>Vous recel<span>âtes</span></td> <td>Vous eûtes recel<span>é</span></td> </tr> <tr> <td>Ils recel<span>èrent</span></td> <td class="lastpad">Ils eurent recel<span>é</span></td> </tr> </table> </div> <hr> <div> <table> <tr> <th>Futur simple</th> <th>Futur antérieur</th> </tr> <tr> <td>Je recèl<span>erai</span></td> <td>J'aurai recel<span>é</span></td> </tr> <tr> <td>Tu recèl<span>eras</span></td> <td>Tu auras recel<span>é</span></td> </tr> <tr> <td>Il recèl<span>era</span></td> <td>Il aura recel<span>é</span></td> </tr> <tr> <td>Nous recel<span>erons</span></td> <td>Nous aurons recel<span>é</span></td> </tr> <tr> <td>Vous recel<span>erez</span></td> <td>Vous aurez recel<span>é</span></td> </tr> <tr> <td>Ils recèl<span>eront</span></td> <td class="lastpad">Ils auront recel<span>é</span></td> </tr> </table> </div> <hr> <h5 class="subtitle">Subjonctif</h5> <div> <table> <tr> <th>Présent</th> <th>Passé</th> </tr> <tr> <td>Que je recèl<span>e</span></td> <td>Que j'aie recel<span>é</span></td> </tr> <tr> <td>Que tu recèl<span>es</span></td> <td>Que tu aies recel<span>é</span></td> </tr> <tr> <td>Qu'il recèl<span>e</span></td> <td>Qu'il ait recel<span>é</span></td> </tr> <tr> <td>Que nous recel<span>ions</span></td> <td>Que nous ayons recel<span>é</span></td> </tr> <tr> <td>Que vous recel<span>iez</span></td> <td>Que vous ayez recel<span>é</span></td> </tr> <tr> <td>Qu'ils recèl<span>ent</span></td> <td>Qu'ils aient recel<span>é</span></td> </tr> </table> </div> <hr> <div> <table> <tr> <th>Imparfait</th> <th>Plus-que-parfait</th> </tr> <tr> <td>Que je recel<span>asse</span></td> <td>Que j'eusse recel<span>é</span></td> </tr> <tr> <td>Que tu recel<span>asses</span></td> <td>Que tu eusses recel<span>é</span></td> </tr> <tr> <td>Qu'il recel<span>ât</span></td> <td>Qu'il eût recel<span>é</span></td> </tr> <tr> <td>Que nous recel<span>assions</span></td> <td>Que nous eussions recel<span>é</span></td> </tr> <tr> <td>Que vous recel<span>assiez</span></td> <td>Que vous eussiez recel<span>é</span></td> </tr> <tr> <td>Qu'ils recel<span>assent</span></td> <td class="lastpad">Qu'ils eussent recel<span>é</span></td> </tr> </table> </div> <hr> <h5 class="subtitle">Conditionnel</h5> <div> <table> <tr> <th>Présent</th> <th>Passé première forme</th> <th>Passé deuxième forme</th> </tr> <tr> <td>Je recèl<span>erais</span></td> <td>J'aurais recel<span>é</span></td> <td>J'eusse recel<span>é</span></td> </tr> <tr> <td>Tu recèl<span>erais</span></td> <td>Tu aurais recel<span>é</span></td> <td>Tu esses recel<span>é</span></td> </tr> <tr> <td>Il recèl<span>erait</span></td> <td>Il aurait recel<span>é</span></td> <td>Il eût recel<span>é</span></td> </tr> <tr> <td>Nous recel<span>erions</span></td> <td>Nous aurions recel<span>é</span></td> <td>Nous eussions recel<span>é</span></td> </tr> <tr> <td>Vous recel<span>eriez</span></td> <td>Vous auriez recel<span>é</span></td> <td>Vous eussiez recel<span>é</span></td> </tr> <tr> <td>Ils recèl<span>eraient</span></td> <td>Ils auraient recel<span>é</span></td> <td class="lastpad">Ils eussent recel<span>é</span></td> </tr> </table> </div> <hr> <h5 class="subtitle">Impératif</h5> <div> <table> <tr> <th>Présent</th> <th>Passé</th> </tr> <tr> <td>recèl<span>e</span></td> <td>aie recel<span>é</span></td> </tr> <tr> <td>recel<span>ons</span></td> <td>ayons recel<span>é</span></td> </tr> <tr> <td>recel<span>ez</span></td> <td class="lastpad">ayez recel<span>é</span></td> </tr> </table> </div> <hr> <h5 class="subtitle">Participe</h5> <div> <table> <tr> <th>Présent</th> <th>Passé</th> </tr> <tr> <td>recel<span>ant</span> </td> <td>recel<span>é</span></td> </tr> <tr> <td></td> <td>recel<span>ée</span> </td> </tr> <tr> <td></td> <td>recel<span>és</span> </td> </tr> <tr> <td></td> <td>recel<span>ées</span> </td> </tr> <tr> <td></td> <td>ayant recel<span>é</span> </td> </tr> </table> </div> <hr> <h5 class="subtitle">Infinitif</h5> <div> <table> <tr> <th>Présent</th> <th>Passé</th> </tr> <tr> <td>receler</td> <td class="lastpad">avoir recel<span>é</span></td> </tr> </table> </div> <hr> <h5 class="subtitle">Gérondif</h5> <div> <table> <tr> <th>Présent</th> <th>Passé</th> </tr> <tr> <td>en recel<span>ant</span></td> <td class="lastpad">en ayant recel<span>é</span></td> </tr> </table> </div> <hr> <div class="more_info"> <h6>Règle du verbe receler</h6> <p>En règle générale, les verbes en -eler et en -eter doublent la consonne l ou t devant un e muet : je jette et j'appelle. Quelques verbes ne doublent pas le l ou le t devant un e muet. Ils prennent alors un accent grave sur le e qui précède le t ou le l. Un exemple est j'achète. Ce sont 22 verbes irréguliers. Les modèles sont acheter et geler. En voici la liste (22 verbes) : celer, déceler, receler, ciseler, démanteler, écarteler, encasteler, geler, dégeler, congeler, surgeler, marteler, modeler, peler, acheter, racheter, bégueter, corseter, crocheter, fileter, fureter, haleter. </p> <h6>Synonyme du verbe receler</h6> <p> cacher - contenir - renfermer - enfermer - réprimer </p> <h6>Emploi du verbe receler</h6> <p> Intransitif - Transitif - Autorise la forme pronominale </p> </div> <h5 class="phrase">Tournure de phrase avec le verbe receler</h5> <div> <table> <tr> <th>Futur proche</th> <th>Passé récent</th> </tr> <tr> <td>Je vais receler</td> <td>Je viens de receler</td> </tr> <tr> <td>Tu vas receler</td> <td>Tu viens de receler</td> </tr> <tr> <td>Il va receler</td> <td>Il vient de receler</td> </tr> <tr> <td>Nous allons receler</td> <td>Nous venons de receler</td> </tr> <tr> <td>Vous allez receler</td> <td>Vous venez de receler</td> </tr> <tr> <td>Ils vont receler</td> <td class="lastpad">Ils viennent de receler</td> </tr> </table> </div> <hr> <p class="copyright">Copyright © 2017 Issam Drmas, All Rights Reserved.</p> </section> </body> </html>
/* Covid 19 Data Exploration Skills used: Joins, CTE's, Temp Tables, Windows Functions, Aggregate Functions, Creating Views, Converting Data Types */ use sql_project; select * from covid_death; select * from covid_vaccination; -- select data that we are going to be using -- select location,date,total_cases,new_cases,total_deaths,population from covid_death order by date; -- Total Cases Vs Populations -- -- Sow what % of population got Covid -- select location,date,total_cases,population,concat(round((total_cases/population)*100,5),"%") as Case_percentage from covid_death order by date; -- Looking at Highest infections and Death Day -- select location , max(total_cases) from covid_death group by location; select location,date , max(total_cases) as Highest_case from covid_death group by location,date order by Highest_case desc; -- Looking at total Cases vs Total Deaths -- select location,date,total_cases,total_deaths,concat(round((total_deaths/total_cases)*100,2),"%") as Death_percentage from covid_death order by date; -- Showing Countries with Highest Death count Per Population -- select location ,max(total_deaths) as total_death_count from covid_death where location is not null group by location order by total_death_count; -- Showing the continent Highest Deaths count -- select continent ,max(total_deaths) as total_death_count from covid_death where continent is not null group by continent order by total_death_count; -- Global Numbers -- as Death_Percentage select date ,sum(new_cases) new_cases,sum(new_deaths) new_deaths,concat((sum(new_deaths)/sum(new_cases)*100 ),"%") as Deaths_Percentage from covid_death group by date order by date,Deaths_Percentage desc; -- Looking at total Population Vs vaccinations -- with PopvsVac (continent,location,date,population,new_vaccinations,Rolling_people_vaccinated) as ( select dea.continent,dea.location,dea.date,dea.population,vac.new_vaccinations , sum(vac.new_vaccinations) over (partition by dea.location order by dea.location,dea.date) Rolling_people_vaccinated from covid_death dea join covid_vaccination vac on dea.location = vac.location and dea.date=vac.date where dea.continent is not null ) select * ,concat( round((Rolling_people_vaccinated/population)*100,5),"%") Total_percentage_vaccinated from PopvsVac; -- TEMP_TABLE -- create temporary table percentagepopulationvaccinated select dea.continent,dea.location,dea.date,dea.population,vac.new_vaccinations , sum(vac.new_vaccinations) over (partition by dea.location order by dea.location,dea.date) Rolling_people_vaccinated from covid_death dea join covid_vaccination vac on dea.location = vac.location and dea.date=vac.date where dea.continent is not null; select * ,concat( round((Rolling_people_vaccinated/population)*100,5),"%") Total_percentage_vaccinated from percentagepopulationvaccinated; -- Creating View -- create view Deathpercentage as select date ,sum(new_cases) new_cases,sum(new_deaths) new_deaths,concat((sum(new_deaths)/sum(new_cases)*100 ),"%") as Deaths_Percentage from covid_death group by date order by date,Deaths_Percentage desc; select * from Deathpercentage;
import { Text, Pressable, IPressableProps } from "native-base"; interface Props extends IPressableProps { name: string isActive: boolean } export function Group({name, isActive, ...rest}: Props) { return ( <Pressable w={24} h={10} mr={3} bg="gray.600" rounded="md" justifyContent="center" alignItems="center" overflow="hidden" isPressed={isActive} _pressed={{ borderWidth: 1, borderColor: "green.500" }} {...rest} > <Text color={isActive ? "green.500" :"gray.200"} fontSize="xs" fontWeight="bold" textTransform="uppercase" > {name} </Text> </Pressable> ) }
<?php namespace App\Modules\SuperAdmin\Models; use App\BaseModel; use Inertia\Inertia; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Route; use Illuminate\Database\QueryException; use Illuminate\Notifications\Notifiable; use App\Modules\SuperAdmin\Models\ErrLog; use App\Modules\SuperAdmin\Models\Product; use Illuminate\Database\Eloquent\SoftDeletes; use App\Modules\SuperAdmin\Models\ActivityLog; use App\Modules\SuperAdmin\Models\SalesChannel; use App\Modules\SuperAdmin\Models\ProductStatus; use App\Modules\SuperAdmin\Models\ResellerHistory; use App\Modules\SuperAdmin\Models\ResellerProduct; use Illuminate\Database\Eloquent\ModelNotFoundException; use Symfony\Component\HttpKernel\Exception\HttpException; use App\Modules\SuperAdmin\Transformers\ProductTransformer; use App\Modules\SuperAdmin\Transformers\ResellerTransformer; use App\Modules\SuperAdmin\Http\Validations\CreateResellerValidation; class Reseller extends BaseModel { use SoftDeletes, Notifiable; protected $fillable = [ 'business_name', 'ceo_name', 'address', 'phone', 'email', 'img_url', ]; protected $touches = ['products']; public function reseller_transactions() { return $this->hasMany(ResellerTransaction::class); } public function products() { return $this->morphedByMany(Product::class, 'product', $table = 'reseller_product')->using(ResellerProduct::class)->withTimestamps()->as('tenure_record'); } public function products_in_possession() { return $this->products()->wherePivot('status', 'tenured')->withPivot('status'); } public function purchased_products() { return $this->products()->wherePivot('status', 'sold')->withPivot('status'); } public function swap_deals() { return $this->morphedByMany(SwapDeal::class, 'product', $table = 'reseller_product')->using(ResellerProduct::class)->withTimestamps()->as('tenure_record'); } public function swap_deals_in_possession() { return $this->swap_deals()->wherePivot('status', 'tenured')->withPivot('status'); } public function reseller_histories() { return $this->hasMany(ResellerHistory::class); } /** * Mark a product as being with this reseller * * @param string $productUuid * * @return void * @throws ModelNotFoundException */ public function giveProduct(string $productUuid): object { /** @var Product */ $product = Product::where('product_uuid', $productUuid)->firstOr(fn () => SwapDeal::where('product_uuid', $productUuid)->firstOrFail()); DB::beginTransaction(); /** * Check if this product is marked as with reseller already */ if ($product->with_reseller()) { DB::rollBack(); ActivityLog::notifySuperAdmins( optional(request()->user())->email ?? 'Console App' . ' tried to give a product: ' . $product->primary_identifier() . ' with a reseller to another reseller without signing out from previous reseller' ); abort(422, 'productWithReseller'); } if (!$product->in_stock()) { DB::rollBack(); ActivityLog::notifySuperAdmins( optional(request()->user())->email ?? 'Console App' . ' tried to give a product: ' . $product->primary_identifier() . ' that is not listed as being in stock to a reseller' ); abort(422, 'productNotInStock'); } /** * Create an entry in the product reseller table * ! syncwithoutdetach() */ if ($product instanceof Product) { // $this->products()->detach($product); $this->products()->syncWithoutDetaching([$product->id => ['status' => 'tenured']]); } elseif ($product instanceof SwapDeal) { $this->swap_deals()->save($product); } /** * Change the product's status to reflect that it's with reseller */ $product->product_status_id = ProductStatus::withResellerId(); $product->save(); /** * Setup notifications for admin in reseller_history static boot method */ /** * Send CEO of the reseller company an SMS or email that he just picked up a device */ try { $this->notify(new ProductUpdate($product)); } catch (\Throwable $th) { ErrLog::notifyAuditor(request()->user(), $th, 'Reseller notification failed'); } DB::commit(); return $product; } /** * Mark a product as being returned from reseller to stock * * @param string $productUuid * * @return void */ public function returnProduct(string $productUuid): object { $product = Product::whereProductUuid($productUuid)->firstOr(fn () => SwapDeal::whereProductUuid($productUuid)->firstOrFail()); /** * Check if this product is marked as with reseller */ if (!$product->with_reseller()) { ActivityLog::notifySuperAdmins( optional(request()->user())->email ?? 'Console App' . ' tried to return a product with ' . $product->primary_identifier() . ' from a reseller that wasn\'t signed out to any reseller' ); abort(422, 'productNotWithReseller'); } DB::beginTransaction(); /** * Update the entry in the product reseller table to reflect returned */ if ($product instanceof Product) { $this->products()->syncWithoutDetaching([$product->id => ['status' => 'returned']]); } elseif ($product instanceof SwapDeal) { $this->swap_deals()->sync([$product->id => ['status' => 'returned']]); } /** * Change the product's status to reflect that it has been returned to stock */ $product->product_status_id = ProductStatus::inStockId(); $product->save(); /** * Send CEO of the reseller company an SMS or email that he just picked up a device */ try { $this->notify(new ProductUpdate($product)); } catch (\Throwable $th) { ErrLog::notifyAuditor(request()->user(), $th, 'Reseller notification failed'); } DB::commit(); return $product; } public static function accountantRoutes() { Route::group(['prefix' => 'resellers'], function () { Route::name('accountant.resellers.')->group(function () { Route::post('{reseller}/{product_uuid}/sold', [self::class, 'markProductAsSold'])->name('mark_as_sold'); Route::post('{reseller}/{product_uuid}/return', [self::class, 'resellerReturnProduct'])->name('return_product'); Route::post('{reseller}/give-product/{product_uuid}', [self::class, 'giveProductToReseller'])->name('give_product'); }); }); } public static function multiAccessRoutes() { Route::group(['prefix' => 'resellers'], function () { Route::name('multiaccess.resellers.')->group(function () { Route::get('', [self::class, 'getResellers'])->name('resellers')->defaults('ex', __e('ss,a,ac', 'at-sign', false))->middleware('auth:auditor,super_admin,accountant'); Route::get('products', [self::class, 'getResellersWithProducts'])->name('resellers_with_products')->defaults('ex', __e('ss,a,ac', 'at-sign', false))->middleware('auth:auditor,super_admin,accountant'); Route::get('{reseller}/products', [self::class, 'getProductsWithReseller'])->name('products')->defaults('ex', __e('ss,a,ac', 'at-sign', true))->middleware('auth:super_admin,auditor,accountant'); Route::get('{reseller:business_name}/financial-records', [self::class, 'getResellerFinancialRecord'])->name('finances')->middleware('auth:auditor,super_admin'); }); }); } public static function superAdminRoutes() { Route::name('resellers.')->prefix('resellers')->group(function () { Route::put('{reseller}/edit', [self::class, 'editReseller'])->name('edit_reseller'); Route::post('create', [self::class, 'createReseller'])->name('create_reseller'); Route::post('{reseller:business_name}/financial-records/create', [self::class, 'createResellerTransaction'])->name('finances.create'); }); } public function getResellerFinancialRecord(Request $request, self $reseller) { // dd($reseller->reseller_transactions); return Inertia::render('SuperAdmin,Resellers/ManageResellerTransactions', [ 'resellerWithTransactions' => $reseller->load('reseller_transactions.recorder:id,full_name') ]); } public function createResellerTransaction(Request $request, self $reseller) { $validated = $request->validate([ 'amount' => 'required|numeric|gt:0', 'purpose' => 'required|string', 'trans_type' => 'required|in:credit,debit', ], [ 'trans_type.required' => 'Enter the transaction type', 'trans_type.in' => 'Invalid transaction type selected', ]); $reseller->reseller_transactions()->create($validated); return back()->withFlash(['success' => 'Transaction successfully created']); } public function getResellers(Request $request) { $resellers = Cache::rememberForever('resellers', fn () => (new ResellerTransformer)->collectionTransformer(self::all(), 'basic')); if ($request->isApi()) return response()->json($resellers, 200); return Inertia::render('SuperAdmin,Resellers/ManageResellers', compact('resellers')); } public function getResellersWithProducts(Request $request) { $resellersWithProducts = (new ResellerTransformer)->collectionTransformer(self::has('products_in_possession')->orHas('swap_deals_in_possession')->with('products_in_possession', 'swap_deals_in_possession')->get(), 'transformWithTenuredProducts'); if ($request->isApi()) return response()->json($resellersWithProducts, 200); return Inertia::render('SuperAdmin,Resellers/ViewResellersWithProducts', compact('resellersWithProducts')); } public function getProductsWithReseller(Request $request, self $reseller) { $resellerWithProducts = fn () => (new ResellerTransformer)->fullDetailsWithTenuredProducts($reseller->load('products_in_possession', 'swap_deals_in_possession')); if ($request->isApi()) return response()->json($resellerWithProducts, 200); return Inertia::render('SuperAdmin,Resellers/ViewProductsWithReseller', compact('resellerWithProducts')); } public function createReseller(CreateResellerValidation $request) { try { if ($request->hasFile('img')) { $reseller = self::create(collect($request->validated())->merge(['img_url' => compress_image_upload('img', 'resellers/', null, 200)['img_url']])->all()); } else { $reseller = self::create($request->validated()); } if ($request->isApi()) return response()->json((new ResellerTransformer)->basic($reseller), 201); return back()->withFlash(['success'=>'Success']); } catch (\Throwable $th) { ErrLog::notifyAuditor($request->user(), $th, 'Reseller not created'); if ($request->isApi()) return response()->json(['err' => 'Reseller not created'], 500); return back()->withFlash(['error'=>['Error']]); } } public function editReseller(CreateResellerValidation $request, self $reseller) { try { foreach ($request->validated() as $key => $value) { $reseller->$key = $value; } if ($request->hasFile('img')) { $reseller->img_url = compress_image_upload('img', 'resellers/', null, 200)['img_url']; } $reseller->save(); if ($request->isApi()) return response()->json([], 204); return back()->withFlash(['success'=>'Success']); } catch (\Throwable $th) { ErrLog::notifyAuditor($request->user(), $th, 'Reseller not updated'); if ($request->isApi()) return response()->json(['err' => 'Reseller not updated'], 500); return back()->withFlash(['error'=>['Error']]); } } public function giveProductToReseller(Request $request, self $reseller, $product_uuid) { try { $reseller->giveProduct($product_uuid); } catch (ModelNotFoundException $th) { return generate_422_error('Invalid product selected'); } catch (HttpException $th) { if ($th->getMessage() == 'productWithReseller') { return generate_422_error('This product is already with a reseller'); } elseif ($th->getMessage() == 'productNotInStock') { return generate_422_error('This product is currently not in the stock list and cannot be given to a reseller'); } else { return generate_422_error('Error giving product to reseller'); } } catch (QueryException $th) { ErrLog::notifyAuditorAndFail($request->user(), $th, 'Error giving product to reseller'); if ($th->errorInfo[1] == 1062) return generate_422_error($th->errorInfo[2]); return generate_422_error($th->getMessage()); } return back()->withFlash(['success'=>'Done. Product has been removed from stock list']); } public function resellerReturnProduct(Request $request, self $reseller, $product_uuid) { /** * Use the transaction here because if */ try { $reseller->returnProduct($product_uuid); } catch (ModelNotFoundException $th) { return back()->withFlash(['error' => ['The product you are trying to return to shelf does not exist in our records']]); } catch (HttpException $th) { if ($th->getMessage() == 'productNotWithReseller') { return generate_422_error('This product is not supposed to be with a reseller'); } elseif ($th->getMessage() == 'productNotInStock') { return generate_422_error('This product is currently not in the stock list and cannot be given to a reseller'); } else { return generate_422_error('Error giving product to reseller'); } } catch (QueryException $th) { ErrLog::notifyAuditorAndFail($request->user(), $th, 'Error giving product to reseller'); if ($th->errorInfo[1] == 1062) return generate_422_error($th->errorInfo[2]); return generate_422_error($th->getMessage()); } return back()->withFlash(['success'=>'The product has been marked as returned and is back in the stock list']); } public function markProductAsSold(Request $request, self $reseller, $product_uuid) { try { /** * @var Product|SwapDeal $product */ $product = Product::whereProductUuid($product_uuid)->firstOr(fn () => SwapDeal::whereProductUuid($product_uuid)->firstOrFail()); } catch (ModelNotFoundException $th) { return generate_422_error('The product you are trying to mark as sold does not exist'); } if (!$request->selling_price) { return generate_422_error('Specify selling price'); } if (!is_numeric($request->selling_price)) { return generate_422_error('The selling price must be a number'); } if ($product->is_sold()) { ActivityLog::notifySuperAdmins( $request->user()->email . ' tried to mark a product with ' . $product->primary_identifier() . ' as sold when it has been previously marked as sold' ); return generate_422_error('This product is sold already'); } if (!$product->with_reseller()) { ActivityLog::notifySuperAdmins( $request->user()->email . ' tried to mark a product with ' . $product->primary_identifier() . ' from a reseller that wasn\'t signed out to any reseller as returned' ); return generate_422_error('This product is not supposed to be with a reseller'); } DB::beginTransaction(); /** * create a reseller history for selling this device */ try { $reseller->reseller_histories()->create([ 'product_id' => $product->id, 'product_type' => get_class($product), 'handled_by' => $request->user()->id, 'handler_type' => get_class($request->user()), 'product_status' => 'sold' ]); /** * Update the entry in the product reseller table to reflect sold */ if ($product instanceof Product) { $reseller->products()->where('product_id', $product->id)->update([ 'status' => 'sold' ]); } elseif ($product instanceof SwapDeal) { $reseller->swap_deals()->where('product_id', $product->id)->update([ 'status' => 'sold' ]); } } catch (QueryException $th) { ErrLog::notifyAuditorAndFail($request->user(), $th, 'Error trying to mark product from a reseller as sold.'); if ($th->errorInfo[1] == 1062) { return generate_422_error($th->errorInfo[2]); } return generate_422_error($th->getMessage()); } /** * Change the product's status to reflect that it has been sold */ $product->product_status_id = ProductStatus::soldByResellerId(); $product->save(); /** * Create a sales record for the product */ try { $product->product_sales_record()->create([ 'selling_price' => $request->selling_price, 'sales_rep_id' => $request->user()->id, 'online_rep_id' => null, 'sales_channel_id' => SalesChannel::resellerId(), ]); } catch (\Throwable $th) { return generate_422_error('Error occured: ' . $th->getMessage()); } ActivityLog::notifySuperAdmins($request->user()->email . ' marked product with UUID: ' . $product->product_uuid . ' as sold.'); ActivityLog::notifyAccountants($request->user()->email . ' marked product with UUID: ' . $product->product_uuid . ' as sold.'); /** * Send CEO of the reseller company an SMS or email that he just picked up a device */ try { $reseller->notify(new ProductUpdate($product)); } catch (\Throwable $th) { ErrLog::notifyAuditor($request->user(), $th, 'Reseller notification failed'); } DB::commit(); if ($request->isApi()) return response()->json((new ProductTransformer)->basic($product), 201); return back()->withFlash(['success'=>'Product marked as sold to reseller']); } protected static function boot() { parent::boot(); static::saved(function ($reseller) { Cache::forget('resellers'); }); } }
package com.db.store.controller; import com.db.store.dto.RoleDTO; import com.db.store.service.RoleService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/admin/role") @AllArgsConstructor @Slf4j public class RoleController { private final RoleService roleService; @GetMapping @ResponseStatus(HttpStatus.OK) public Page<RoleDTO> getRoles(@RequestParam(required = false, defaultValue = "0") int page, @RequestParam(required = false, defaultValue = "5") int size) { return roleService.getAllRoles(page, size); } @GetMapping("/{id}") @ResponseStatus(HttpStatus.OK) public RoleDTO getRole(@PathVariable Long id) { return roleService.getRole(id); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public RoleDTO createRole(@RequestBody @Validated RoleDTO roleDTO, BindingResult bindingResult) { return roleService.saveRole(roleDTO, bindingResult); } @PutMapping("/{id}") @ResponseStatus(HttpStatus.OK) public RoleDTO updateRole(@PathVariable Long id, @RequestBody @Validated RoleDTO roleDTO, BindingResult bindingResult) { return roleService.updateRoleById(id, roleDTO, bindingResult); } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteRole(@PathVariable Long id) { roleService.deleteRoleById(id); } }
/* vi: ts=8 sts=4 sw=4 * * $Id$ * * This file is part of the KDE project, module kdesu. * Copyright (C) 2000 Geert Jansen <[email protected]> * * This is free software; you can use this library under the GNU Library * General Public License, version 2. See the file "COPYING.LIB" for the * exact licensing terms. */ #ifndef __SSH_h_Included__ #define __SSH_h_Included__ #include <qcstring.h> #include "stub.h" /** * Execute a remote command, using ssh. */ class SshProcess: public StubProcess { public: SshProcess(QCString host=0, QCString user=0, QCString command=0); ~SshProcess(); enum Errors { SshNotFound=1, SshNeedsPassword, SshIncorrectPassword }; /** Set the target host. */ void setHost(QCString host) { m_Host = host; } /** Set the localtion of the remote stub. */ void setStub(QCString stub); /** * Check if the current user@host needs a password. * @return The prompt for the password if a password is required. A null * string otherwise. */ int checkNeedPassword(); /** * Check if the stub is installed and if the password is correct. * @return Zero if everything is correct, nonzero otherwise. */ int checkInstall(const char *password); /** Execute the command. */ int exec(const char *password, int check=0); QCString prompt() { return m_Prompt; } QCString error() { return d->m_Error; } protected: virtual QCString display(); virtual QCString displayAuth(); virtual QCStringList dcopServer(); virtual QCStringList dcopAuth(); virtual QCStringList iceAuth(); private: QCString dcopForward(); int ConverseSsh(const char *password, int check); int m_dcopPort, m_dcopSrv; QCString m_Prompt, m_Host; struct SshProcessPrivate { QCString m_Error; QCString m_Stub; }; SshProcessPrivate *d; }; #endif
// // ReposVC.swift // GithubSearch // // Created by Shujat Ali on 4/26/21. // import UIKit class ReposVC: BaseVC, UISearchBarDelegate, UITextFieldDelegate { let searchBarPlaceholder = "Enter keywords" let navigationTitle = "Repos" @IBOutlet weak var tableView: UITableView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var errorNoRecords: UILabel! // Tool Tip @IBOutlet weak var toolTipView: UIView! @IBOutlet weak var toolTipLabel: UILabel! @IBOutlet weak var toolTipBottomConstraint: NSLayoutConstraint! @IBOutlet weak var toolTipTopConstraint: NSLayoutConstraint! // Text Fields @IBOutlet weak var textFieldTopic: UITextField! @IBOutlet weak var textFieldLanguage: UITextField! // Error Label @IBOutlet weak var errorLbl: UILabel! var rawQueryParams = [[String: String]]() var querySearch: [String] = [] var topicSearch: String = "" var languageSearch: String = "" var hasLoadMoreData = false var searchBar = UISearchBar() // Infinite Scroll var currentPage = 1 var isFetchingRepos = false var allReposFetched = false // All fetched repos var repoList = [GitItem]() // Repos displayed in the table view. var displayRepoList = [GitItem]() var refreshControl = UIRefreshControl() // MARK: - ViewController overrides override func viewDidLoad() { super.viewDidLoad() setupViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Setup Views private func setupViews() { title = navigationTitle setupTableView() setupToolTip("Search by keyword \nor apply additional search by pressing filter button") setupSearchBar() setupNavigationBar() setupTextFields(false) } private func setupTableView() { tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none tableView.backgroundColor = UIColor.clear // Make cell height dynamic tableView.estimatedRowHeight = 200.0 tableView.rowHeight = UITableView.automaticDimension /* A UIRefreshControl sends a `valueChanged` event to signal when a refresh should occur. */ refreshControl.addTarget(self, action: #selector(ReposVC.refreshRepos), for: .valueChanged) tableView.addSubview(refreshControl) } func setupToolTip(_ msg: String) { errorLbl.text = msg } private func setupSearchBar() { searchBar.delegate = self searchBar.autocapitalizationType = .none if #available(iOS 13.0, *) { searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: searchBarPlaceholder, attributes: [NSAttributedString.Key.foregroundColor : UIColor.white]) } // Make search cursor visible (not white) UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = UIColor.black } private func setupTextFields(_ isShow: Bool) { textFieldTopic.superview?.isHidden = !isShow textFieldLanguage.superview?.isHidden = !isShow } private func setupNavigationBar() { navigationController?.navigationBar.tintColor = UIColor.white navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] navigationItem.titleView = searchBar navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "filter"), style: .plain, target: self, action: #selector(ReposVC.displaySettings)) } // MARK: UI Target Actions @objc private func displaySettings() { setupTextFields((textFieldLanguage.superview?.isHidden ?? false)) } // MARK: - UITextfieldDelegate func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string == "" { return true } do { let regex = try NSRegularExpression(pattern: "[a-zA-Z0-9-.+_]$", options: .caseInsensitive) if regex.numberOfMatches(in: string, options: [], range: NSRange(location: 0, length: string.count)) == 0 { return false } } catch { } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == textFieldTopic { textFieldLanguage.becomeFirstResponder() } else { searchBarSearchButtonClicked(searchBar) } return true } // MARK: - UISearchBarDelegate func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard (searchText.count > 0) else { resetDisplayedRepos() return } do { displayRepoList = try repoList.filter() { (repo: GitItem) throws -> Bool in let regex = try NSRegularExpression(pattern: "\(searchText)", options: [NSRegularExpression.Options.caseInsensitive]) var numNameMatches = 0 var numOwnerNameMatches = 0 var numDescriptionMatches = 0 if let name = repo.name { numNameMatches = regex.numberOfMatches(in: name, options: [], range: NSRange(location: 0, length: name.count)) } if let ownerName = repo.ownerLoginName { numOwnerNameMatches = regex.numberOfMatches(in: ownerName, options: [], range: NSRange(location: 0, length: ownerName.count)) } if let repoDescription = repo.repoDescription { numDescriptionMatches = regex.numberOfMatches(in: repoDescription, options: [], range: NSRange(location: 0, length: repoDescription.count)) } if(numNameMatches + numOwnerNameMatches + numDescriptionMatches > 0) { return true } else { return false } } } catch { // NSRegularExpression error print("\(error)") } errorNoRecords.isHidden = !displayRepoList.isEmpty tableView.reloadData() } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { tableView.setContentOffset(CGPoint.zero, animated: true) searchBar.showsCancelButton = true } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.text = nil searchBar.showsCancelButton = false if textFieldTopic.text?.isEmpty ?? false || textFieldLanguage.text?.isEmpty ?? false { resetDisplayedRepos() } else { refreshReposAfterSearch() } searchBar.endEditing(true) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { if let searchtxt = isTextNotEmpty(searchBar.text) { querySearch = searchtxt } if let searchtxt = isTextNotEmpty(textFieldLanguage.text) { languageSearch = searchtxt.first ?? "" } if let searchtxt = isTextNotEmpty(textFieldTopic.text) { topicSearch = searchtxt.first ?? "" } clearSearches() refreshRepos() searchBar.endEditing(true) } }
@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap'); /* Variables CSS */ :root{ --primary-color: #411DD2; --secondary-color: #DF8888; --light-brown-color:#9B8B81; --light-color: #F8F0EA; --dark-color:#1F1F44; --gradient-title: linear-gradient(180deg, rgba(255,255,255,1) 30%, rgba(141,128,255,1) 100%); --gradient-button: linear-gradient(180deg, rgb(31, 31, 68) 30%, rgba(65,29,210,1) 100%); } /* end Variables CSS */ /* Reset CSS */ *{ box-sizing: border-box; margin: 0; padding: 0; } html{ scroll-behavior: smooth; } body{ font-family: 'Poppins', sans-serif; color: white; background-color: var(--dark-color); } img{ width: 100%; } a{ text-decoration: none; color: white; } button{ background-color: black; border: none; padding: 1rem; } ul{ list-style-type: none; } /* font-sizes */ h1{ font-size: 5rem; } h2{ font-size: 3.5rem; } h3{ font-size: 2rem; } h4{ font-size: 1.5rem; } h5{ font-size: 1.1rem; } p{ font-size: 1rem; } /* Responsive */ @media(max-width: 1030px){ /* En este caso asignamos esilos a pantallas de máximo 1030px de ancho */ h1{ font-size: 4rem; } h2{ font-size: 2.7rem; } } @media(max-width: 600px){ /* Y ahora a pantallas de máximo 600px de ancho */ h1{ font-size: 2.3rem; } h2{ font-size: 2.2rem; } h3{ font-size: 1.8rem; } } /* end Reset CSS */ /* Hero */ .hero{ background-image: url("https://i.ibb.co/myJ9B82/Hero-Background.png"); width: 100%; height: 100vh; background-size: cover; background-position: center; } .hero img{ width: 50%; } .hero h4{ font-weight: 400; margin: 1rem 0; } .hero button{ margin: 1.2rem 0.5rem; padding: 1rem 2rem; border-radius: 58px; font-size: 1rem; } .btn-primary{ background-image: linear-gradient(180deg, rgba(255,255,255,1) 10%, rgba(141,128,255,1) 100%) ; border: 1px solid white; } .btn-primary a{ color: black; } .btn-outline{ background-color: transparent; border: 1px solid white; } .btn-primary:hover{ background-image: linear-gradient(180deg, rgb(194, 187, 255) 10%, rgba(141,128,255,1) 100%) ; } .btn-outline:hover{ background-color: rgba(0, 0, 0, 0.1); } @media(max-width: 1030px){ .hero{ height: 95vh; padding: 10rem 0 3rem 0; width: 100%; } .hero img{ width: 70%; } } @media (max-width: 600px) { .hero img{ width: 100%; } .hero h4{ font-size: 0.9rem; } .hero button{ margin: 0.3rem; } .hero button a{ font-size: 0.8rem; } } /* end Hero */ /* Navbar */ .navbar{ background-color: var(--primary-color); height: 70px; position: fixed; width: 100%; padding-top: 0.5rem; z-index: 1; } .logo{ font-size: 1.5rem; font-weight: 400; } .navbar a{ color: var(--light-color); padding: 10px; margin: 0 5px; } .navbar a:hover{ color: var(--secondary-color); } .navbar ul li a:hover{ border-bottom: 2px solid var(--secondary-color) ; } /* Responsive */ @media (max-width: 700px){ .navbar{ height: auto; position: fixed; } .navbar nav{ flex-direction: column; } .navbar ul{ padding: 10px; background-color: rgba(0, 0, 0, 0.1); } .navbar a{ margin: 0 1px; } } /* end Navbar */ /* end Navbar */ /* Skills */ #skills{ margin: 6rem 0; } @media(max-width: 1030px){ #skills{ margin: 3rem 0; } } .title h2{ margin-bottom: 4rem; } .title p{ opacity: 0.5; } @media(max-width: 600px){ .title p{ font-size: 0.9rem; } } #skills i{ font-size: 2.5rem; margin-right: 1rem; } #skills h5{ margin: 1rem 0; } /* end Skills */ /* Banner */ .banner{ background-image: url("https://i.ibb.co/6XMmNsv/Banner.png"); width: 100%; height: 50vh; background-position: center; background-size: cover; } /* end Banner */ /* Projects */ .projects p{ margin: 1rem 0; } .projects a{ color: white; font-size: 1rem; } .project-1 img, .project-3 img{ width: 450px; } .project-2 img{ width: 300px; } @media(max-width: 1030px){ .project-2 img{ width: 200px; } .project-1 img, .project-3 img{ width: 300px; } } /* end Projects */ /* Contacto */ #contact{ background-image: url("https://i.ibb.co/jRhvkh0/Background-Contact.png"); background-position: center; background-size: cover; height: 130vh; } #contact a{ font-weight: 600; line-height: 2; } #contact p{ padding: 1.5rem 0 2rem 0; width: 60%; margin: 0 auto; font-weight: 200; } @media(max-width: 900px){ #contact p{ width: 100%; } } /* end Contacto */ /* Sobre Mi */ #about-me .profile-text{ padding: 0 2rem; } #about-me h3{ margin-bottom: 1rem; } #about-me img{ width: 450px; } .details{ margin: 3rem 0; } .about-me-contacto a{ font-weight: 600; } @media(max-width: 1030px){ #about-me img{ width: 100%; } #about-me .profile-text{ padding: 0 ; } } /* end Sobre Mi */ /* Banner 2 */ .banner-2{ background-image: url("https://i.ibb.co/TgfPxYP/Banner-2.png"); width: 100%; height: 60vh; background-position: center; background-size: cover; } /* end Banner 2 */ /* Footer */ footer{ padding: 10rem 0 3rem 0; } .footer-text{ margin: 0 auto; width: 60%; } footer h3{ font-weight: 400; } footer i { font-size: 2.5rem; margin: 1rem; margin-bottom: 7rem; } footer p{ padding: 0 2rem; } footer a{ font-weight: 400; } footer a:hover{ color: var(--secondary-color); } @media(max-width: 1030px){ footer{ padding: 3rem 0; } } /* end Footer */
package com.publicis.sapient.p2p.model; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.validation.annotation.Validated; import java.util.ArrayList; import java.util.Date; import java.util.List; @Validated @Valid @Getter @Setter @AllArgsConstructor @NoArgsConstructor @Document @Entity public class User { @JsonProperty("id") private @Id String id; @JsonProperty("firstName") @NotBlank(message = "First Name is Mandatory") @Size(min = 1, message = "First name must be greater then 1") private String firstName; @JsonProperty("lastName") @NotBlank(message = "Last Name is Mandatory") @Size(min = 1, message = "Last name must be greater then 1") private String lastName; @JsonProperty(namespace = "password") @NotBlank(message = "Password is Mandatory") private String password; @JsonProperty("email") @NotBlank(message = "Email is Mandatory & Must be Unique") @Column(unique = true) @Pattern(regexp = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$", message = "Please provide valid mail id") private String email; @JsonProperty("status") private String status; @JsonProperty("phoneno") @NotBlank(message = "Phone Number is Mandatory") @Pattern(regexp = "^\\d{10}$", message = "Phone number is not is valid format") private String phoneno; private String description; private String location; private String profileImage; private List<String> socialUrls = new ArrayList<>(); private Date createdTime; }
import "../App.css"; import { useState } from "react"; import nalgene from "../assets/nalgene.png"; import regularmug from "../assets/regularmug.png"; import purelife from "../assets/purelife.png"; import gatoradesquirt from "../assets/gatoradesquirt.png"; import starbuckscup from "../assets/starbuckscup.png"; import gallon from "../assets/gallonbottle.png"; import hydroflask from "../assets/hydroflask.png"; import largepurelife from "../assets/largepurelife.png"; import largevoss from "../assets/largevoss.png"; import lululemon from "../assets/lululemon.png"; import redsolocup from "../assets/redsolocup.png"; import regularglass from "../assets/regularglass.png"; import smallfiji from "../assets/smallfiji.png"; import smallglass from "../assets/smallglass.png"; import stanley from "../assets/stanley.png"; import teacup from "../assets/teacup.png"; import waterfountain from "../assets/waterfountain.png"; import yetitumbler from "../assets/yetitumbler.png"; import PropTypes from "prop-types"; import BottleOutput from "./BottleOutput"; const bottleStorage = { 0: 1000, 1: 950, 2: 700, 3: 3700, 4: 620, 5: 700, 6: 1200, 7: 850, 8: 300, 9: 550, 10: 500, 11: 1500, 12: 850, 13: 330, 14: 470, 15: 300, 16: 400, 17: 30, }; const allBottleData = [ { image: nalgene, name: "Nalgene", style: "w-32 h-auto", info: "ml: 1000 | oz: 33.8", }, { image: gatoradesquirt, name: "Gatorade Squirt", style: "w-32 h-auto", info: "ml: 950 | oz: 32.1", }, { image: starbuckscup, name: "Starbucks Cup", style: "w-32 h-auto", info: "ml: 700 | oz: 23.7", }, { image: gallon, name: "Gallon Bottle", style: "w-32 h-auto", info: "ml: 3700 | oz: 125.1", }, { image: hydroflask, name: "Hydroflask", style: "w-32 h-auto", info: "ml: 530 | oz: 17.9", }, { image: lululemon, name: "Lululemon", style: "w-32 h-auto", info: "ml: 700 | oz: 23.7", }, { image: stanley, name: "Stanley", style: "w-32 h-auto", info: "ml: 1200 | oz: 40.6", }, { image: yetitumbler, name: "Yeti Tumbler", style: "w-32 h-auto", info: "ml: 850| oz: 28.7", }, { image: teacup, name: "Teacup", style: "w-32 h-auto", info: "ml: 300 | oz: 10.1", }, { image: regularmug, name: "Regular Mug", style: "w-32 h-auto", info: "ml: 550 | oz: 18.6", }, { image: purelife, name: "Purelife", style: "w-32 h-auto", info: "ml: 500 | oz: 16.9", }, { image: largepurelife, name: "Large Purelife", style: "w-32 h-auto", info: "ml: 1500 | oz: 50.7", }, { image: largevoss, name: "Large Voss", style: "w-32 h-auto", info: "ml: 850 | oz: 28.7", }, { image: smallfiji, name: "Small Fiji", style: "w-32 h-auto", info: "ml: 330 | oz: 11.2", }, { image: redsolocup, name: "Red Solo Cup", style: "w-32 h-auto", info: "ml: 470 | oz: 15.9", }, { image: smallglass, name: "Small Glass", style: "w-32 h-auto", info: "ml: 300 | oz: 10.1", }, { image: regularglass, name: "Regular Glass", style: "w-32 h-auto", info: "ml: 450 | oz: 15.2", }, { image: waterfountain, name: "Water Fountain", style: "w-32 h-auto", info: "1oz/30ml per second", }, ]; function Results({ hours, minute, period, gender, weight, climate, exerciseMinutes, bottles, weightUnit, directInputUnit, directInput, customCapacity, customFile, customUnit }) { let info; if (customUnit === "ml") { info = Math.round((customCapacity) * 10) / 10 } else { info = Math.round((customCapacity * 29.57) * 10) / 10 } allBottleData[18] = { image: customFile, name: "Custom Bottle", style: "w-32 h-auto", info: `${customCapacity}`, } bottleStorage[18] = info; const [refreshKey, setRefreshKey] = useState(0); function handleRefresh() { setRefreshKey((prevKey) => prevKey + 1); } function timeUntilSleep() { const now = new Date(); let wakeHour = parseInt(hours); const wakeMinute = parseInt(minute); const isPM = period.toLowerCase() === "pm"; // Convert to 24-hour format if (isPM && wakeHour !== 12) { wakeHour += 12; } else if (!isPM && wakeHour === 12) { wakeHour = 0; } const wakeTime = new Date(); wakeTime.setHours(wakeHour); wakeTime.setMinutes(wakeMinute); wakeTime.setSeconds(0); wakeTime.setMilliseconds(0); // Calculate sleep time (16 hours after wake time) const sleepTime = new Date(wakeTime); sleepTime.setHours(sleepTime.getHours() + 16); let timeDiff = sleepTime - now; if (timeDiff < 0) { // If the sleep time is earlier in the day than the current time, // it means the user intends to sleep the next day. timeDiff += 24 * 60 * 60 * 1000; // add 24 hours } const hoursUntilSleep = timeDiff / (1000 * 60 * 60); // convert milliseconds to hours return hoursUntilSleep; } timeUntilSleep(); function dailyIntake() { let multiplier; if (gender === "male") { multiplier = 0.6; } else { multiplier = 0.5; } let weightInLbs = weight; if (weightUnit === "kg") { weightInLbs = weight * 2.2; // Convert kg to lbs } let intake = multiplier * weightInLbs; switch (climate) { case "cold": intake += 8; break; case "neutral": intake += 4; break; case "warm": intake += 8; break; case "hot": intake += 16; break; default: intake += 4; } intake += (exerciseMinutes / 30) * 12; return intake * 29.5735; // Convert oz to ml } function consumed() { // loop through every bottle. quantity * capacity var total = 0; for (let i = 0; i < bottles.length; i++) { total += bottles[i] * bottleStorage[i]; } if (directInputUnit === "ml") { total += directInput * 1; } else { total += directInput * 29.57; } return total; } function remaining() { const remainingAmount = dailyIntake() - consumed(); return Math.max(remainingAmount, 0); } function totalWaterLeft() { if (remaining() <= 200) { return ( <div className="bg-lightbeige rounded-xl p-3 flex justify-center mr-3 sm:mr-0"> <h3 className="text-2xl font-semibold text-center"> Congrats! You drank your daily required intake! </h3> </div> ); } let bottlesUsed = []; for (let i = 0; i < bottles.length; i++) { if (bottles[i] > 0) { bottlesUsed.push(i); } } if (bottlesUsed.length === 1) { const bottleCapacity = bottleStorage[bottlesUsed[0]]; const neededBottles = Math.round(remaining() / bottleCapacity / 0.25) * 0.25; return ( <div key={refreshKey} className="flex flex-col sm:flex-row justify-center items-center sm:items-start w-full" > <div className="flex flex-col justify-center items-center bg-lightbrown p-5 rounded-xl mx-2 w-full sm:w-1/4 mb-5 sm:mb-0"> <h3 className="text-center text-brown font-semibold text-3xl mb-2"> Over the day, drink a total of </h3> <figure className="bg-lightbeige rounded-xl p-3 w-full flex justify-center h-64"> <BottleOutput key={bottlesUsed[0]} image={allBottleData[bottlesUsed[0]].image} quantity={parseFloat(neededBottles)} className={allBottleData[bottlesUsed[0]].style} /> </figure> </div> <div className="flex flex-col justify-center items-center bg-lightbrown p-5 rounded-xl mx-2 w-full sm:w-1/4"> <h3 className="text-center text-brown font-semibold text-3xl mb-2"> Every hour until bed, drink </h3> <figure className="bg-lightbeige rounded-xl p-3 w-full flex justify-center h-64"> <BottleOutput key={bottlesUsed[0]} image={allBottleData[bottlesUsed[0]].image} quantity={parseFloat( (neededBottles / timeUntilSleep()).toFixed(2) )} className={allBottleData[bottlesUsed[0]].style} /> </figure> </div> </div> ); } if (bottlesUsed.length >= 2) { const remainingWater = remaining(); let bottlesUsed = bottles .map((qty, index) => ({ index, capacity: bottleStorage[index], qty, half: false, })) .filter((bottle) => bottle.qty > 0); if (bottlesUsed.length > 3) { shuffle(bottlesUsed); bottlesUsed = bottlesUsed.slice(0, 3); } const randomHourlyBottleIndex = Math.floor( Math.random() * bottlesUsed.length ); const randomHourlyBottle = bottlesUsed[randomHourlyBottleIndex]; const toFillOneBottle = Math.round(remainingWater / randomHourlyBottle.capacity / 0.25) * 0.25; const halfBottles = bottlesUsed.map((bottle) => ({ index: bottle.index, capacity: Math.round(bottle.capacity / 2), half: true, })); bottlesUsed = bottlesUsed.concat(halfBottles); let res = []; const start = Date.now(); // Record the start time const duration = 1000; // Set a default maximum duration (in milliseconds) // eslint-disable-next-line no-inner-declarations function dfs(i, cur, total) { // Check if the function has been running longer than the maximum duration if (Date.now() - start > duration) { return; } if (total >= remainingWater - 200 && total <= remainingWater + 200) { res.push(cur.slice()); return; } if (i >= bottlesUsed.length || total > remainingWater + 500) { return; } cur.push(bottlesUsed[i]); dfs(i, cur, total + bottlesUsed[i].capacity); cur.pop(); dfs(i + 1, cur, total); } dfs(0, [], 0); const randomResult = res[Math.floor(Math.random() * res.length)]; const finalResult = {}; for (let i = 0; i < randomResult.length; i++) { if (randomResult[i].half) { finalResult[randomResult[i].index] = (finalResult[randomResult[i].index] || 0) + 0.5; } else { finalResult[randomResult[i].index] = (finalResult[randomResult[i].index] || 0) + 1; } } return ( <div className="flex flex-col sm:flex-row justify-center w-full items-center sm:items-start"> <div className="flex flex-col justify-center items-center bg-lightbrown p-5 rounded-xl mx-2 w-full sm:w-1/3 mb-5 sm:mb-0"> <h3 className="text-center text-brown font-semibold text-xl sm:text-3xl mb-2"> Over the day, drink a total of </h3> <figure className="bg-lightbeige rounded-xl p-3 w-full flex justify-center h-64"> {Object.entries(finalResult).map(([index, quantity]) => ( <BottleOutput key={index} image={allBottleData[index].image} quantity={parseFloat(quantity)} className={allBottleData[index].style} /> ))} </figure> </div> <div className="flex flex-col justify-center items-center bg-lightbrown p-5 rounded-xl mx-2 w-full sm:w-1/3"> <h3 className="text-center text-brown font-semibold text-xl sm:text-3xl mb-2"> Every hour until bed, drink </h3> <figure className="bg-lightbeige rounded-xl p-3 w-full flex justify-center h-64"> <BottleOutput key={randomHourlyBottle.index} image={allBottleData[randomHourlyBottle.index].image} quantity={parseFloat( (toFillOneBottle / timeUntilSleep()).toFixed(2) )} className={allBottleData[randomHourlyBottle.index].style} /> </figure> </div> </div> ); } } function addtionalWaterForTemp() { if (climate === "warm" || climate === "hot") { let bottlesUsed = bottles .map((qty, index) => ({ index, capacity: bottleStorage[index], qty, half: false, })) .filter((bottle) => bottle.qty > 0); if (bottlesUsed.length === 0) { return; } const randomBottle = bottlesUsed[Math.floor(Math.random() * bottlesUsed.length)]; const fractionOfOz = climate === "warm" ? 250 / randomBottle.capacity : 500 / randomBottle.capacity; return ( <div className="flex justify-center items-center bg-lightbrown p-5 rounded-xl mx-2"> <h3 className="text-center text-brown font-semibold sm:text-3xl mb-2"> Consider Drinking an Extra </h3> <figure className=" p-3 flex justify-center"> <BottleOutput key={randomBottle.index} image={allBottleData[randomBottle.index].image} quantity={parseFloat(fractionOfOz.toFixed(2))} className={allBottleData[randomBottle.index].style} /> </figure> <h3 className="text-center text-brown font-semibold sm:text-3xl mb-2"> Every 20 Minutes in the Heat </h3> </div> ); } } function addtionalWaterForActivity() { if (exerciseMinutes > 0) { let bottlesUsed = bottles .map((qty, index) => ({ index, capacity: bottleStorage[index], qty, half: false, })) .filter((bottle) => bottle.qty > 0); if (bottlesUsed.length === 0) { return; } const randomBottle = bottlesUsed[Math.floor(Math.random() * bottlesUsed.length)]; const fractionOfOz = 250 / randomBottle.capacity; return ( <div className="flex justify-center items-center bg-lightbrown p-5 rounded-xl mx-2"> <h3 className="text-center text-brown font-semibold sm:text-3xl mb-2"> Consider Drinking an Extra </h3> <figure className=" p-3 flex justify-center"> <BottleOutput key={randomBottle.index} image={allBottleData[randomBottle.index].image} quantity={parseFloat(fractionOfOz.toFixed(2))} className={allBottleData[randomBottle.index].style} /> </figure> <h3 className="text-center text-brown font-semibold sm:text-3xl mb-2"> Every 15 Minutes When Active </h3> </div> ); } } function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } return ( <> <div className="flex justify-center my-14 flex-col ml-3"> <div className="flex justify-center"> <h1 className="text-center font-bold sm:text-5xl text-2xl text-brown"> You Need To Drink{"\u00A0"} </h1> <h1 className="text-center font-bold sm:text-5xl text-2xl text-lightblue"> {Math.max((dailyIntake() / 1000).toFixed(1), 0)}L </h1> <h1 className="text-center font-bold sm:text-5xl text-2xl text-lightblue"> {"\u00A0"}Daily </h1> </div> <div className="flex justify-center"> <h1 className="text-center font-bold sm:text-5xl text-2xl text-brown"> You Have{"\u00A0"} </h1> <h1 className="text-center font-bold sm:text-5xl text-2xl text-lightblue"> {Math.max((remaining() / 1000).toFixed(1), 0)}L </h1> <h1 className="text-center font-bold sm:text-5xl text-2xl text-lightblue"> {"\u00A0"}Left </h1> </div> <div className="flex flex-col justify-center mt-10 max-w-full"> <div className="flex justify-center w-full">{totalWaterLeft()}</div> <div className="flex justify-center w-full mt-5"> {addtionalWaterForTemp()} </div> <div className="flex justify-center w-full my-5"> {addtionalWaterForActivity()} </div> </div> <div className="flex justify-center"> <button className="btn btn-accent text-lg" onClick={handleRefresh}> Show New Results </button> </div> </div> </> ); } Results.propTypes = { hours: PropTypes.string.isRequired, minute: PropTypes.string.isRequired, period: PropTypes.string.isRequired, gender: PropTypes.string.isRequired, weight: PropTypes.number.isRequired, climate: PropTypes.string.isRequired, exerciseMinutes: PropTypes.number.isRequired, bottles: PropTypes.arrayOf(PropTypes.number).isRequired, weightUnit: PropTypes.string.isRequired, directInputUnit: PropTypes.string.isRequired, directInput: PropTypes.number.isRequired, customCapacity: PropTypes.number.isRequired, customFile: PropTypes.string, customUnit: PropTypes.number.isRequired, }; export default Results;
#include <iostream> #include <map> #include <queue> using namespace std; class Solution { public: bool canConstruct(string ransomNote, string magazine) { int lenR = ransomNote.length(); int lenM = magazine.length(); if (lenR > lenM) { return false; } else { map<char,int> abc; abc.insert(make_pair('a', 1)); abc.insert(make_pair('b', 2)); abc.insert(make_pair('c', 3)); abc.insert(make_pair('d', 4)); abc.insert(make_pair('e', 5)); abc.insert(make_pair('f', 6)); abc.insert(make_pair('g', 7)); abc.insert(make_pair('h', 8)); abc.insert(make_pair('i', 9)); abc.insert(make_pair('j', 10)); abc.insert(make_pair('k', 11)); abc.insert(make_pair('l', 12)); abc.insert(make_pair('m', 13)); abc.insert(make_pair('n', 14)); abc.insert(make_pair('o', 15)); abc.insert(make_pair('p', 16)); abc.insert(make_pair('q', 17)); abc.insert(make_pair('r', 18)); abc.insert(make_pair('s', 19)); abc.insert(make_pair('t', 20)); abc.insert(make_pair('u', 21)); abc.insert(make_pair('v', 22)); abc.insert(make_pair('w', 23)); abc.insert(make_pair('x', 24)); abc.insert(make_pair('y', 25)); abc.insert(make_pair('z', 26)); priority_queue<int> M; priority_queue<int> N; for (int i = 0; i < lenM; i++) { M.push(abc[magazine[i]]); } for (int i = 0; i < lenR; i++) { N.push(abc[ransomNote[i]]); } while (!N.empty()) { if (N.top() <= M.top()) { if (N.top() == M.top()){ N.pop(); M.pop(); } else { while (N.top() < M.top() || N.size() > M.size()) { M.pop(); if (M.empty()) { return false; } } } } else { return false; } } return true; } } }; int main(){ Solution s1; cout << s1.canConstruct("aa","ab") << endl; return 0; }
import { createSlice } from "@reduxjs/toolkit"; const initialState = { currentUser: null, token: null, loading: false, error: false, }; export const userSlice = createSlice({ name: "user", initialState, reducers: { loginStart: (state) => { state.loading = true; }, loginSuccess: (state, action) => { state.loading = false; state.currentUser = action.payload; }, storeToken: (state, action) => { state.token = action.payload; }, loginFailure: (state) => { state.loading = false; state.error = true; }, logout: (state) => { state.currentUser = null; state.loading = false; state.error = false; }, subscription: (state, action) => { console.log( "sliceeeeeee", action.payload, state.currentUser.subscribedUsers.includes(action.payload) ); if (state.currentUser.subscribedUsers.includes(action.payload)) { state.currentUser.subscribedUsers.splice( state.currentUser.subscribedUsers.findIndex( (channelId) => channelId === action.payload ), 1 ); if (state.currentUser.subscribers > 0) { state.currentUser.subscribers--; } } else { state.currentUser.subscribedUsers.push(action.payload); state.currentUser.subscribers++; } }, }, }); export const { loginFailure, loginSuccess, loginStart, storeToken, logout, subscription, } = userSlice.actions; export default userSlice.reducer;
@extends('/layout/layout') @push('duar') <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet"> @endpush @section('content') <!-- Main Content --> <div id="content"> <!-- Begin Page Content --> <div class="container-fluid mt-5"> <h1 class="h3 mb-2 text-gray-800">Edit sekolah</h1> <!-- Content Row --> <div class="row"> <!-- Area Chart --> <div class="col-lg-8"> <div class="card shadow mb-4"> <!-- Card Header - Dropdown --> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <h6 class="m-0 font-weight-bold text-primary">Lokasi sekolah</h6> </div> <!-- Card Body --> <div class="card-body"> <div> <div id="mapid"></div> </div> </div> </div> </div> <div class="col-lg-4"> <div class="card shadow mb-4"> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <h6 class="m-0 font-weight-bold text-primary">Data sekolah</h6> </div> <div class="card-body"> <div> <form method="POST" action="{{ route('sekolah-update', $sekolah->id) }}"> @csrf <div class="form-group"> <div class="form-row"> <div class="col"> <label for="nama_sekolah">Nama sekolah</label> <input value="{{ $sekolah->nama }}" type="text" class="form-control" name="nama_sekolah" id="nama_sekolah" placeholder="Ex: SDN 1" required> </div> </div> <div class="input-group mt-3"> <div class="input-group-prepend"> <label class="input-group-text" for="jenjang_sekolah">Jenjang sekolah</label> </div> <select class="custom-select" id="jenjang_sekolah" name="jenjang_sekolah"> @foreach ($jenjang as $jenjangs) @if ($jenjangs->id == $sekolah->id_jenjang) <option selected value={{ $jenjangs->id }}>{{ $jenjangs->jenjang}}</option> @else <option value={{ $jenjangs->id }}>{{ $jenjangs->jenjang}}</option> @endif @endforeach </select> </div> <div class="input-group mt-3"> <div class="input-group-prepend"> <label class="input-group-text" for="jenis_sekolah">Jenis sekolah</label> </div> <select class="custom-select" id="jenis_sekolah" name="jenis_sekolah"> @if ($sekolah->jenis_sekolah == 0) <option selected value=0>Sekolah negeri</option> <option value=1>Sekolah swasta</option> @else <option value=0>Sekolah negeri</option> <option selected value=1>Sekolah swasta</option> @endif </select> </div> <div class="input-group mt-3"> <div class="input-group-prepend"> <label class="input-group-text" for="desa">Desa</label> </div> <select class="custom-select" id="desa" name="desa"> @foreach ($desa as $desas) @if ($desas->id == $sekolah->id_desa) <option selected value={{ $desas->id }}>{{ $desas->nama}}</option> @else <option value={{ $desas->id }}>{{ $desas->nama}}</option> @endif @endforeach </select> </div> <div class="form-row mt-3"> <div class="col"> <label for="alamat_sekolah">Alamat sekolah</label> <input value="{{ $sekolah->alamat }}" type="text" class="form-control" name="alamat_sekolah" id="alamat_sekolah" placeholder="Ex: Jalan astasura" required> </div> </div> <div class="form-row mt-3"> <div class="col"> <label for="lat">Data latitude</label> <input value="{{ $sekolah->lat }}" type="text-area" class="form-control" name="lat" id="lat" placeholder="" required readonly> </div> </div> <div class="form-row mt-3"> <div class="col"> <label for="lng">Data longitude</label> <input value="{{ $sekolah->lng }}" type="text-area" class="form-control" name="lng" id="lng" placeholder="" required readonly> </div> </div> </div> <a onclick='this.parentNode.submit(); return false;' class="btn btn-primary btn-icon-split"> <span class="icon text-white-50"> <i class="fas fa-check"></i> </span> <span class="text">Simpan data sekolah</span> </a> </form> </div> </div> </div> </div> </div> </div> <!-- /.container-fluid --> </div> @endsection <!-- End of Main Content --> @push('anjay') <script> $(document).ready(function(){ $('#sekolah').addClass('active'); }); let mainMap = L.map('mapid').setView([-8.612193497317223, 115.21365428261726], 10); L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', { maxZoom: 18, attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' + 'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>', id: 'mapbox/streets-v11', tileSize: 512, zoomOffset: -1 }).addTo(mainMap); var sekolah = {!! json_encode($sekolah) !!}; var marker; marker = L.marker([sekolah.lat, sekolah.lng]).bindPopup().addTo(mainMap); mainMap.on('click', function(e){ if (marker) { // check mainMap.removeLayer(marker); // remove } marker = L.marker(e.latlng, {}).addTo(mainMap); document.getElementById('lat').value=e.latlng.lat; document.getElementById('lng').value=e.latlng.lng; }); </script> @if((session('done'))) <script> $(document).ready(function(){ alertDone('Data sekolah berhasil di edit') }); </script> @endif @if((session('failed'))) <script> $(document).ready(function(){ alertFail('Data sekolah gagal di edit') }); </script> @endif @endpush
import { PlatformAccessory } from 'homebridge'; import { TuyaIRPlatform } from '../../platform'; import { APIInvocationHelper } from '../api/APIInvocationHelper'; import { BaseAccessory } from './BaseAccessory'; /** * Do It Yourself Accessory * An instance of this class is created for each accessory your platform registers * Each accessory may expose multiple services of different service types. */ export class DoItYourselfAccessory extends BaseAccessory { constructor( private readonly platform: TuyaIRPlatform, private readonly accessory: PlatformAccessory, ) { super(platform, accessory); // set accessory information this.accessory.getService(this.platform.Service.AccessoryInformation) ?.setCharacteristic(this.platform.Characteristic.Manufacturer, accessory.context.device.product_name) .setCharacteristic(this.platform.Characteristic.Model, 'Infrared Controlled Switch') .setCharacteristic(this.platform.Characteristic.SerialNumber, accessory.context.device.id); this.fetchLearningCodes(this.accessory.context.device.ir_id, this.accessory.context.device.id, (body) =>{ if (!body.success) { this.log.error(`Failed to fetch learning codes due to error ${body.msg}`); } else { this.accessory.context.device.codes = body.result // Cleaning accessories const uuids = this.accessory.context.device.codes.map(code => this.platform.api.hap.uuid.generate(code.key_name)) for(let service_index = this.accessory.services.length-1; service_index>=0; service_index--){ const service = this.accessory.services [service_index]; if(service.constructor.name === this.platform.api.hap.Service.Switch.name){ if(!uuids.includes(service.subtype as string)){ this.accessory.removeService(service); } } } for(const code of this.accessory.context.device.codes){ this.log.debug(`Adding code ${code.key_name}`); const service = this.accessory.getService(this.platform.api.hap.uuid.generate(code.key_name)) || accessory.addService(this.platform.api.hap.Service.Switch, code.key_name, this.platform.api.hap.uuid.generate(code.key_name), code.key); service.getCharacteristic(this.platform.Characteristic.On) .onGet(() => { return false; }) .onSet(((value) => { if(value){ this.sendLearningCode(this.accessory.context.device.ir_id, this.accessory.context.device.id, code.code, (body) =>{ if (!body.success) { this.log.error(`Failed to fetch learning codes due to error ${body.msg}`); } service.setCharacteristic(this.platform.Characteristic.On, false); }); } })); } } }) } sendLearningCode(deviceId: string, remoteId: string, code:string, cb){ this.log.debug("Sending Learning Code"); APIInvocationHelper.invokeTuyaIrApi(this.log, this.configuration, this.configuration.apiHost + `/v2.0/infrareds/${deviceId}/remotes/${remoteId}/learning-codes`, "POST", {code}, (body) => { cb(body); }); } fetchLearningCodes(deviceId: string, remoteId: string, cb){ this.log.debug("Getting Learning Codes"); APIInvocationHelper.invokeTuyaIrApi(this.log, this.configuration, this.configuration.apiHost + `/v2.0/infrareds/${deviceId}/remotes/${remoteId}/learning-codes`, "GET", {}, (body) => { this.log.debug(`Received learning codes ${JSON.stringify(body)}`); cb(body); }); } }
#include "sort.h" /** * swap_element - Entry point * @array: the array * @a: index count * @b: index count */ void swap_element(int *array, int a, int b) { int temp; temp = array[a]; array[a] = array[b]; array[b] = temp; } /* end function */ /** * bubble_sort - Entry point to bubble sort * @array: 'The array to be sorted' * @size: 'The size of the array' */ void bubble_sort(int *array, size_t size) { /* Initialise variables */ size_t a; /* counter1 */ size_t b; /* counter2 */ int swapped; /* to check if two int(s) have been swapped */ /* Valoidate parameters */ if (array == NULL || size < 2) { return; } /* End if */ /* printf("the size of the array = %ld\n", size); */ /* Iterate through the array */ for (a = 0; a < size - 1; a++) { swapped = 0; for (b = 0; b < size - 1 - a; b++) { /* Compare and swap elements */ if (array[b + 1] < array[b]) { /* commit the swapping */ swap_element(array, b, b + 1); print_array(array, size); /* to indicate a swap */ swapped = 1; } /* End if */ } /* End for */ if (swapped == 0) { break; } /* end if */ } /* End for */ } /* End function */
import 'dart:convert'; class RegisterUserModel { final String name; final String email; final String password; final String passwordConfirmation; RegisterUserModel({ required this.name, required this.email, required this.password, required this.passwordConfirmation, }); RegisterUserModel copyWith({ String? name, String? email, String? password, String? passwordConfirmation, }) { return RegisterUserModel( name: name ?? this.name, email: email ?? this.email, password: password ?? this.password, passwordConfirmation: passwordConfirmation ?? this.passwordConfirmation, ); } Map<String, dynamic> toMap() { return { 'name': name, 'email': email, 'password': password, 'password_confirmation': passwordConfirmation, }; } factory RegisterUserModel.fromMap(Map<String, dynamic> map) { return RegisterUserModel( name: map['name'] ?? '', email: map['email'] ?? '', password: map['password'] ?? '', passwordConfirmation: map['password_confirmation'] ?? '', ); } String toJson() => json.encode(toMap()); factory RegisterUserModel.fromJson(String source) => RegisterUserModel.fromMap(json.decode(source)); @override String toString() { return 'RegisterUserModel(name: $name, email: $email, password: $password, password_confirmation: $passwordConfirmation)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is RegisterUserModel && other.name == name && other.email == email && other.password == password && other.passwordConfirmation == passwordConfirmation; } @override int get hashCode { return name.hashCode ^ email.hashCode ^ password.hashCode ^ passwordConfirmation.hashCode; } }
import { useEffect, useState } from "react"; import { FormattedMessage } from "react-intl"; import { useLocation, useNavigate } from "react-router-dom"; import { Button } from "reactstrap"; import { CollectionItemType } from "../../services/ItemsApiService"; import { useItemsApi } from "../../hooks/useItemsApi"; import { ItemDetailsView } from "../shared/ItemDetailsView"; export function DeleteItemPage() { const { state } = useLocation(); const [item, setItem] = useState<CollectionItemType>(); const itemsApi = useItemsApi(); const navigate = useNavigate(); useEffect(() => { itemsApi.get(state?.id ?? 0) .then(response => response.data) .then(data => setItem(data)) .catch(error => console.error(error)); }, [itemsApi, state]); function handleDeleteClicked() { itemsApi.delete(item?.id ?? 0); navigate(-1); } function handleCancelClicked() { navigate(-1); } if (item === undefined) { return <p><em><FormattedMessage id="loading" /></em></p>; } return ( <div> <h1> <FormattedMessage id="delete_item" /> </h1> <ItemDetailsView item={item} collection={item.collection} /> <p> <FormattedMessage id="warning_before_item_deletion" /> </p> <div> <Button className="me-1" onClick={handleDeleteClicked}> <FormattedMessage id="delete" /> </Button> <Button onClick={handleCancelClicked}> <FormattedMessage id="cancel" /> </Button> </div> </div> ) }
class UltrasonicSensor { private: int triggerPin; int echoPin; public: UltrasonicSensor(int triggerPin, int echoPin) { this->triggerPin = triggerPin; this->echoPin = echoPin; } void setup() { pinMode(triggerPin, OUTPUT); pinMode(echoPin, INPUT); digitalWrite(triggerPin, LOW); } float readDistance() { digitalWrite(triggerPin, HIGH); delayMicroseconds(10); digitalWrite(triggerPin, LOW); unsigned long duration = pulseIn(echoPin, HIGH); float distance = duration * 0.0343 / 2; // Calcula la distancia en centímetros return distance; } }; class LEDController { private: int ledPins[3]; public: LEDController(int pin1, int pin2, int pin3) { ledPins[0] = pin1; ledPins[1] = pin2; ledPins[2] = pin3; } void setup() { for (int i = 0; i < 3; i++) { pinMode(ledPins[i], OUTPUT); } } void setLED(int index, bool state) { digitalWrite(ledPins[index], state ? HIGH : LOW); } }; const int triggerPin = 15; const int echoPin = 16; const int ledPins[3] = {32, 33, 23}; // Pines de los LEDs UltrasonicSensor ultrasonicSensor(triggerPin, echoPin); LEDController ledController(ledPins[0], ledPins[1], ledPins[2]); void setup() { Serial.begin(115200); ultrasonicSensor.setup(); ledController.setup(); } void measureDistance(float cm) { ledController.setLED(0, false); ledController.setLED(1, false); ledController.setLED(2, false); if (cm >= 0 && cm < 50) { ledController.setLED(0, true); delay(1000); ledController.setLED(0, false); } else if (cm >= 50 && cm <= 150) { ledController.setLED(1, true); delay(1000); ledController.setLED(1, false); } else if (cm > 150 && cm <= 300) { ledController.setLED(1, true); } else if (cm > 300) { ledController.setLED(2, true); } } void loop() { float distance = ultrasonicSensor.readDistance(); Serial.print("Distancia: "); Serial.print(distance); Serial.println("cm"); measureDistance(distance); delay(1000); }
from django.contrib import admin from .models import Project, Student # Класс для настройки отображения модели Project в административной панели class ProjectAdmin(admin.ModelAdmin): # Список полей, которые будут отображаться в таблице проектов list_display = ('title', 'student', 'annotation') # Список полей, по которым можно осуществлять поиск search_fields = ('title', 'student__name') # Список полей, по которым можно фильтровать проекты list_filter = ('student',) # Класс для настройки отображения модели Student в административной панели class StudentAdmin(admin.ModelAdmin): # Список полей, которые будут отображаться в таблице студентов list_display = ('name', 'course', 'email', 'phone', 'passport') # Список полей, по которым можно осуществлять поиск search_fields = ('name', 'email') # Список полей, по которым можно фильтровать студентов list_filter = ('course',) # Регистрируем модели и их классы настройки в административной панели admin.site.register(Project, ProjectAdmin) admin.site.register(Student, StudentAdmin)
package com.fastcampus.getinline.controller.api; import com.fastcampus.getinline.constant.ErrorCode; import com.fastcampus.getinline.constant.PlaceType; import com.fastcampus.getinline.dto.PlaceRequest; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @WebMvcTest(APIPlaceController.class) class APIPlaceControllerTest { private final MockMvc mvc; private final ObjectMapper mapper; public APIPlaceControllerTest( @Autowired MockMvc mvc, @Autowired ObjectMapper mapper ) { this.mvc = mvc; this.mapper = mapper; } @DisplayName("[API][GET] 장소 리스트 조회") @Test void givenNothing_whenRequestPlaces_thenReturnsListOfPlacesInStandardResponse() throws Exception { // Given // When & Then mvc.perform(get("/api/places")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.data").isArray()) // data가 array로 들어왔는가? .andExpect(jsonPath("$.data[0].placeType").value(PlaceType.COMMON.name())) .andExpect(jsonPath("$.data[0].placeName").value("패스트캠퍼스")) .andExpect(jsonPath("$.data[0].address").value("서울시 강남구 강남대로 1234")) .andExpect(jsonPath("$.data[0].phoneNumber").value("010-1234-1234")) .andExpect(jsonPath("$.data[0].capacity").value(30)) .andExpect(jsonPath("$.data[0].memo").value("신장개업")) .andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.errorCode").value(ErrorCode.OK.getCode())) .andExpect(jsonPath("$.message").value(ErrorCode.OK.getMessage())); } @DisplayName("[API][POST] 장소 등록") @Test void givenPlaceData_whenPostRequesting_thenReturnsStandardResponse() throws Exception { // Given PlaceRequest placeRequest = PlaceRequest.of( PlaceType.COMMON, "패스트캠퍼스", "서울시 강남구 강남대로 1234", "010-1234-1234", 30, "신장개업" ); // When & Then mvc.perform( post("/api/places") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(placeRequest)) ) .andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.errorCode").value(ErrorCode.OK.getCode())) .andExpect(jsonPath("$.message").value(ErrorCode.OK.getMessage())); } @DisplayName("[API][GET] 단일 장소 조회 - 장소가 존재하는 경우") @Test void givenPlaceAndItsId_whenRequestPlace_thenReturnsPlace() throws Exception { long placeId = 1L; // Given // When & Then mvc.perform(get("/api/places/" + placeId)) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.data").isMap()) // data가 array로 들어왔는가? .andExpect(jsonPath("$.data.placeType").value(PlaceType.COMMON.name())) .andExpect(jsonPath("$.data.placeName").value("패스트캠퍼스")) .andExpect(jsonPath("$.data.address").value("서울시 강남구 강남대로 1234")) .andExpect(jsonPath("$.data.phoneNumber").value("010-1234-1234")) .andExpect(jsonPath("$.data.capacity").value(30)) .andExpect(jsonPath("$.data.memo").value("신장개업")) .andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.errorCode").value(ErrorCode.OK.getCode())) .andExpect(jsonPath("$.message").value(ErrorCode.OK.getMessage())); } @DisplayName("[API][GET] 단일 장소 조회 - 장소가 존재하지 않는 경우") @Test void givenPlaceAndItsId_whenRequestPlace_thenReturnsEmptyPlace() throws Exception { long placeId = 2L; // Given // When & Then mvc.perform(get("/api/places/" + placeId)) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.data").isEmpty()) // data가 비어있는가? .andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.errorCode").value(ErrorCode.OK.getCode())) .andExpect(jsonPath("$.message").value(ErrorCode.OK.getMessage())); } @DisplayName("[API][PUT] 장소 변경") @Test void givenPlaceId_whenModifyingPlace_thenReturnsSuccessfulStandardResponse() throws Exception { // Given long placeId = 1L; PlaceRequest placeRequest = PlaceRequest.of( PlaceType.PARTY, "패스트파티룸", "서울시 강남구 강남대로 5678", "010-1234-5678", 56, "재밌게 놀아봅시다." ); // When & Then mvc.perform( put("/api/places/" + placeId) .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(placeRequest)) ) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.errorCode").value(ErrorCode.OK.getCode())) .andExpect(jsonPath("$.message").value(ErrorCode.OK.getMessage())); } @DisplayName("[API][DELETE] 장소 삭제") @Test void givenPlaceId_whenDeletingPlace_thenReturnsSuccessfulStandardResponse() throws Exception { // Given long placeId = 1L; // When & Then mvc.perform(delete("/api/places/" + placeId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.errorCode").value(ErrorCode.OK.getCode())) .andExpect(jsonPath("$.message").value(ErrorCode.OK.getMessage())); } }
package com.camerafeed.MyOpenGL; import android.opengl.Matrix; import android.util.Log; import java.util.Random; /** * Created by NoobsDeSroobs on 11-May-16. */ public class GeoData { public float[] mVertices; public short[] mIndices; private GeoData() { } static public GeoData halfpipe() { GeoData creator = new GeoData(); creator.mVertices = createVertices1(44); creator.mIndices = createIndices1(44); return creator; } static public GeoData circle() { GeoData creator = new GeoData(); creator.mVertices = createVertices2(32); creator.mIndices = createIndices2(32); return creator; } static public GeoData grid(int width, int height) { GeoData creator = new GeoData(); creator.mVertices = createGridVertices(width + 1, height + 1); creator.mIndices = createGridIndices(width + 1, height + 1); return creator; } static public GeoData Box3D() { GeoData creator = new GeoData(); creator.mVertices = createBoxVertices(); creator.mIndices = createBoxIndices(); return creator; } public void setColor(float[] color) { for (int i = 0; i < mVertices.length; i+=6) { mVertices[i+3] = color[0]; mVertices[i+4] = color[1]; mVertices[i+5] = color[2]; } } private static short[] createBoxIndices() { short[] indices = { 0, 1, 2, 2, 1, 3, 4, 0, 6, 6, 0, 2, 5, 1, 4, 4, 1, 0, 6, 2, 7, 7, 2, 3, 7, 3, 5, 5, 3, 1, 5, 4, 7, 7, 4, 6}; return indices; } private static float[] createBoxVertices() { Random rand = new Random(); float[] vertices= { // in counterclockwise order: -0.5f, -0.5f, -0.5f, //BLB 0 rand.nextFloat() % 255, rand.nextFloat() % 255, rand.nextFloat() % 255, -0.5f, 0.5f, -0.5f, //BLF 1 rand.nextFloat() % 255, rand.nextFloat() % 255, rand.nextFloat() % 255, 0.5f, -0.5f, -0.5f, //BRB 2 rand.nextFloat() % 255, rand.nextFloat() % 255, rand.nextFloat() % 255, 0.5f, 0.5f, -0.5f, //BRF 3 rand.nextFloat() % 255, rand.nextFloat() % 255, rand.nextFloat() % 255, -0.5f, -0.5f, 0.5f, //TLB 4 rand.nextFloat() % 255, rand.nextFloat() % 255, rand.nextFloat() % 255, -0.5f, 0.5f, 0.5f, //TLF 5 rand.nextFloat() % 255, rand.nextFloat() % 255, rand.nextFloat() % 255, 0.5f, -0.5f, 0.5f, //TRB 6 rand.nextFloat() % 255, rand.nextFloat() % 255, rand.nextFloat() % 255, 0.5f, 0.5f, 0.5f, //TRF 7 rand.nextFloat() % 255, rand.nextFloat() % 255, rand.nextFloat() % 255 }; return vertices; } static float[] createGridVertices(int width, int height) { int numComponents = 6; float[] vertices = new float[numComponents * width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { vertices[numComponents * (y * width + x) + 0] = x - (width / 2); vertices[numComponents * (y * width + x) + 1] = y - (height / 2); vertices[numComponents * (y * width + x) + 2] = 0.0f; vertices[numComponents * (y * width + x) + 3] = 0.2f; vertices[numComponents * (y * width + x) + 4] = 0.2f; vertices[numComponents * (y * width + x) + 5] = 0.2f; } } return vertices; } static short[] createGridIndices(int width, int height) { int size = (width - 2) * (height - 2) * 4;//Inner Square, 4 connections per point size += width * 3 * 2;//Top and bottom edge, 3 connections per point size += height * 3 * 2;//Left and right edge, 3 connections per point size -= 4 * 4;//Subtract the duplicated corners, remove the 2 duplicate connections for each corner AND the 2 void ones. short[] indices = new short[size]; int ctr = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width - 1; x++) { int currVert = (y * width + x); indices[ctr] = (short) currVert; indices[ctr + 1] = (short) (currVert + 1); ctr += 2; } } for (int y = 0; y < height - 1; y++) { for (int x = 0; x < width; x++) { int currVert = (y * width + x); indices[ctr] = (short) currVert; indices[ctr + 1] = (short) (currVert + width); ctr += 2; } } Log.e("Test", "" + (size - ctr)); return indices; } static float[] createVertices1(int n) { int NUM_COMPONENTS = 6; float S = 0.75f; float X = 1f; float z0 = 1.3f; float z1 = 1.1f; float dx = 2 * X / n; float[] vertices = new float[NUM_COMPONENTS * (n + 1) * 2]; for (int i = 0; i < (n + 1); i++) { int I0 = 2 * NUM_COMPONENTS * i; int I1 = 2 * NUM_COMPONENTS * i + NUM_COMPONENTS; float x = -X + dx * i; float y = -(float) Math.sqrt(1.0 - x * x); vertices[I0 + 0] = S * x; vertices[I0 + 1] = S * y; vertices[I0 + 2] = S * z0; vertices[I0 + 3] = x; vertices[I0 + 4] = y; vertices[I0 + 5] = 0; vertices[I1 + 0] = S * x; vertices[I1 + 1] = S * y; vertices[I1 + 2] = S * z1; vertices[I1 + 3] = x; vertices[I1 + 4] = y; vertices[I1 + 5] = 0; } return vertices; } static short[] createIndices1(int n) { short[] indices = new short[(n + 1) * 2]; for (short i = 0; i < (n + 1) * 2; i++) { indices[i] = i; } return indices; } static float[] createVertices2(int n) { int NUM_COMPONENTS = 6; float[] vertices = new float[NUM_COMPONENTS * (n + 2)]; final float S = 0.9f; final float Y = -0.0f; vertices[0] = 0; vertices[1] = Y; vertices[2] = 0; vertices[3] = 0; vertices[4] = -1; vertices[5] = 0; for (int i = 0; i <= n; i++) { int I = 6 + 6 * i; float a = (float) (0.75 * 2 * Math.PI * i / n); float x = (float) (S * Math.cos(a)); float z = (float) (S * Math.sin(a)); vertices[I + 0] = x; vertices[I + 1] = Y; vertices[I + 2] = z; vertices[I + 3] = 0; vertices[I + 4] = -1; vertices[I + 5] = 0; } return vertices; } static short[] createIndices2(int n) { short[] indices = new short[(n + 2)]; for (short i = 0; i < (n + 2); i++) { indices[i] = i; } return indices; } public static GeoData square() { GeoData creator = new GeoData(); creator.mVertices = createSquareVertices(); creator.mIndices = createSquareIndices(); return creator; } private static short[] createSquareIndices() { short[] indices = { 0, 1, 3, 3, 1, 2 }; return indices; } private static float[] createSquareVertices() { float[] vertices = { -0.5f, 0.5f, 0, -0.5f, -0.5f, 0, 0.5f, -0.5f, 0, 0.5f, 0.5f, 0, }; return vertices; } }
# Jamie Lee # CS 333 # Final Project # Referee from die import Die import random class Referee: def __init__(self): self.name = "Game Master - Rule Enforcer :)" self.roundEnd = 0 # interaction between referee and die def rollAdvantageDie(self): die = Die() # roll 1 dice return random.choices(die.faces, weights=die.probabilities) # integration test (1) def setPlayerAdvantage(self): player1Advantage = self.rollAdvantageDie() player2Advantage = self.rollAdvantageDie() if (player1Advantage == player2Advantage): return [0, 0] else: return [player1Advantage, player2Advantage] # interaction between referee and player - referee is changing values of player def determinePlayerAdvantage(self, player1, player1Advantage, player2, player2Advantage): if (player1Advantage > player2Advantage): player1.advantage = 1 elif (player1Advantage < player2Advantage): player2.advantage = 1 else: return 0 # interaction between player and die def checkSameSum(self, player1, player2): if (sum(player1.dice) == sum(player2.dice)): # if both player rolled two 0's if (player1.die1 == 0 and player1.die2 == 0 and player2.die1 == 0 and player2.die2 == 0): if (player1.advantage == 1): # player 2 loses return -2 else: # player 1 loses return -1 # if both players rolled two 10's elif (player1.die1 == 10 and player1.die2 == 10 and player2.die1 == 10 and player2.die2 == 10): if (player1.advantage == 1): # player 2 loses return -2 else: # player 1 loses return -1 # otherwise if players rolled the same sum, reroll else: return 1 else: # players did not have the same sum return 0 # interaction between player and die def checkDoubles(self, player1, player2): if (player1.die1 == 0 and player1.die2 == 0): player2.roundWins = 5 return 1 elif (player2.die1 == 0 and player2.die2 == 0): player1.roundWins = 5 return 1 elif (player1.die1 == 10 and player1.die2 == 10): player1.roundWins = 5 return 1 elif (player2.die1 == 10 and player2.die2 == 10): player2.roundWins = 5 return 1 else: return 0 # interaction between player and die def checkZero(self, player1, player2): if (0 in player1.dice or 0 in player2.dice): if (player1.advantage == 1): if (0 in player1.dice): player1.roundWins += 1 elif (0 in player2.dice): player2.roundWins += 1 else: if (0 in player2.dice): player2.roundWins += 1 elif (0 in player1.dice): player1.roundWins += 1 return 1 else: return 0 # interaction between player and die def checkTen(self, player1, player2): if (10 in player1.dice or 10 in player2.dice): if (player1.advantage == 1): if (10 in player2.dice): player1.roundWins += 1 elif (10 in player1.dice): player2.roundWins += 1 else: if (10 in player1.dice): player2.roundWins += 1 elif (10 in player2.dice): player1.roundWins += 1 return 1 else: return 0 # interaction between player and die def checkZeroTen(self, player1, player2): if (10 in player1.dice and 0 in player1.dice): return 1 elif (10 in player2.dice and 0 in player2.dice): return 1 else: return 0 # integration test (2) # interaction between player and die def checkDice(self, player1, player2): if (self.checkSameSum(player1, player2) == -1): self.triggerGameOver(player2) return -1 elif (self.checkSameSum(player1, player2) == -2): self.triggerGameOver(player1) return -2 elif (self.checkDoubles(player1, player2) == 1): self.checkRoundWins(player1, player2) return 2 elif (self.checkZeroTen(player1, player2) == 1): return 1 elif (self.checkZero(player1, player2) == 1 or self.checkTen(player1, player2) == 1): return 0 elif (self.checkSameSum(player1, player2) == 1): return 1 elif (sum(player1.dice) > sum(player2.dice)): # player 1 wins the round player1.roundWins += 1 elif (sum(player1.dice) < sum(player2.dice)): # player 2 wins the round player2.roundWins += 1 # integration test (3) # interaction between player and referee def checkRoundWins(self, player1, player2): if (player1.roundWins == 5): self.triggerGameOver(player1) return 1 elif (player2.roundWins == 5): self.triggerGameOver(player2) return 2 else: return 0 # interaction between player and referee def triggerGameOver(self, player): print("\n\n" + player.name + " has won! yippee") return player.name # interaction between player and referee def resetPlayer(self, player): player.dice = [] player.roundWins = 0 def resetReferee(self): self.roundEnd = 0 # integration test (4) # interaction between player and referee def resetGame(self, player1, player2): self.resetPlayer(player1) self.resetPlayer(player2) self.resetReferee()
import { call, put, takeEvery } from "redux-saga/effects"; import { postTransactionRequested, postTransactionSuccess, postTransactionFailed, getDetailTransactionSuccess, getDetailTransactionFailed, getDetailTransactionRequested, checkPaymentSuccess, checkPaymentFailed, checkPaymentRequested, historyTransactionRequested, historyTransactionSuccess, historyTransactionFailed, historyTransactionDetailRequested, historyTransactionDetailSuccess, historyTransactionDetailFailed, } from "../reducers/slice/transaction/transactionSlice"; import { getDetailTransaction, historyTransaction, historyTransactionDetail, postTransaction, } from "./saga-actions/transactionActions"; import { setResponserMessage } from "../reducers/slice/responserSlice"; import { clearStorage } from "@/utils/storage"; import Router from "next/router"; import store from "@/store"; function* fetchPostTransaction(action) { try { const res = yield call(postTransaction, action?.payload); yield put({ type: postTransactionSuccess.toString(), payload: { data: res.data.data, }, }); Router.push(`/virtual-account/${res.data.data.id}`); } catch (err) { yield put({ type: postTransactionFailed.toString() }); if (err?.data?.code === 401) { clearStorage(["accessToken"]); Router.push({ pathname: "/auth/login", query: { toUrl: Router.asPath } }); } yield put({ type: setResponserMessage.toString(), payload: { code: err?.data?.code, message: err?.data?.message, }, }); } } function* fetchGetDetailTransaction(action) { try { const res = yield call(getDetailTransaction, action?.payload); yield put({ type: getDetailTransactionSuccess.toString(), payload: { data: res.data.data, }, }); } catch (err) { yield put({ type: getDetailTransactionFailed.toString() }); if (err?.data?.code === 401) { clearStorage(["accessToken"]); Router.push({ pathname: "/auth/login", query: { toUrl: Router.asPath } }); } yield put({ type: setResponserMessage.toString(), payload: { code: err?.data?.code, message: err?.data?.message, }, }); } } function* fetchCheckPaymentStatus(action) { try { const res = yield call(getDetailTransaction, action?.payload); yield put({ type: checkPaymentSuccess.toString(), payload: { data: res.data.data, }, }); if (res.data.data.payment_status === "COMPLETED") { clearStorage(["checkout", "totalPrice"]); Router.push(`/place-order/success`); } else { yield put({ type: setResponserMessage.toString(), payload: { code: 500, message: "pembayaran belum masuk", }, }); } } catch (err) { yield put({ type: checkPaymentFailed.toString() }); if (err?.data?.code === 401) { clearStorage(["accessToken"]); Router.push({ pathname: "/auth/login", query: { toUrl: Router.asPath } }); } yield put({ type: setResponserMessage.toString(), payload: { code: err?.data?.code, message: err?.data?.message, }, }); } } function* fetchHistoryTransaction(action) { try { const res = yield call(historyTransaction, action?.payload); console.log("fetchHistoryTransaction: ", res.data.data); yield put({ type: historyTransactionSuccess.toString(), payload: { data: res.data.data, }, }); } catch (err) { yield put({ type: historyTransactionFailed.toString() }); if (err?.data?.code === 401) { clearStorage(["accessToken"]); Router.push({ pathname: "/auth/login", query: { toUrl: Router.asPath } }); } yield put({ type: setResponserMessage.toString(), payload: { code: err?.data?.code, message: err?.data?.message, }, }); } } function* fetchHistoryTransactionDetail(action) { try { const res = yield call(historyTransactionDetail, action?.payload); yield put({ type: historyTransactionDetailSuccess.toString(), payload: { data: res.data.data, }, }); } catch (err) { yield put({ type: historyTransactionDetailFailed.toString() }); if (err?.data?.code === 401) { clearStorage(["accessToken"]); Router.push({ pathname: "/auth/login", query: { toUrl: Router.asPath } }); } yield put({ type: setResponserMessage.toString(), payload: { code: err?.data?.code, message: err?.data?.message, }, }); } } function* transactionSaga() { yield takeEvery(postTransactionRequested.toString(), fetchPostTransaction); yield takeEvery( getDetailTransactionRequested.toString(), fetchGetDetailTransaction ); yield takeEvery(checkPaymentRequested.toString(), fetchCheckPaymentStatus); yield takeEvery(historyTransactionRequested.toString(), fetchHistoryTransaction); yield takeEvery(historyTransactionDetailRequested.toString(), fetchHistoryTransactionDetail); } export default transactionSaga;
""" Module with functions which configure the model setup. .. autosummary:: :toctree: :nosignatures: importer dict_to_list parameterimporter parameterinterpolator parameterinterpolatorstepwise add_sellersparameters import_parallelparameter allocate_parallelparameter write_parallelparameter """ import configparser import os import sys import copy from .functions import * from .variables import * def importer(filename,*args,**kwargs): """ Reads a **configuration.ini-file** and creates the model run setup in a dictionary. It is one of the coremodules of this project, mostly called as first step, because it gathers all information about the model setup and summarizes it. .. Note:: The file from which the information is imported has to have a specific structure, please read :ref:`Input <../input>` first to see how the **configuration.ini-files** are created. The specificaton of the path to the filedirectory is optional. If none is given some standard diretories will be tried (python sys.paths and relative paths like '../', '../config/',..) **Function-call arguments** \n :param string filename: The name of the **configuration.ini-file** * type: string * value: example: 'Configuration.ini' :param args: :param kwargs: Optional Keyword arguments: * *path*: The directory path where the **configuration.ini-file** is located. * type: string * value: **full path** ('/home/user/dir0/dir1/filedir/') or **relative path** ('../../filedir/') :returns: configdic: Dictionary of model setup parameters distributed over several subdictionaries :rtype: Dictionary """ path=kwargs.get('path',None) #Importing the configfile.ini from path if path == None: possible_paths = ['', 'config/', '../config/', '../../config/', 'ZOEE/config/'] for i in sys.path: possible_paths.append(i + '/ZOEE/tutorials/config/') possible_paths.append(i + '/ZOEE/config/') # print(possible_paths) for trypath in possible_paths: exists = os.path.isfile(trypath + filename) if exists: path = trypath print('Loading Configuration from: ' + path + filename) config = configparser.ConfigParser() config.read(path + filename) break if trypath == possible_paths[-1]: sys.exit( 'Error: File not found, please specify the path of the configuration.ini. importer(filename,path= " ... ")') else: #Importing the configfile.ini if os.path.isfile(path+filename): print('Loading Configuration from: '+path) config=configparser.ConfigParser() config.read(path+filename) elif os.path.isfile(path+'/'+filename): print('Loading Configuration from: '+path) config=configparser.ConfigParser() config.read(path+'/'+filename) else: sys.exit('Error: File not found, please specify the path of the configuration.ini. importer(filename,path= " ... ")') #Creating arrays for the sections in the configfile keys=config.options('eqparam') values=[] for j in range(len(keys)): values.append(eval(config['eqparam'][keys[j]])) eqparamd=dict(zip(keys,values)) keys=config.options('rk4input') values=[] for j in range(len(keys)): values.append(eval(config['rk4input'][keys[j]])) rk4inputd=dict(zip(keys,values)) keys=config.options('initials') values=[] for j in range(len(keys)): values.append(eval(config['initials'][keys[j]])) initialsd=dict(zip(keys,values)) #Creating a dictionary of functions included funclistd={} funcparamd={} i=0 for func in config: if func[:4]=='func': funclistd[func]=eval(config[func]['func']) keys=config.options(func)[1:] values=[] for j in range(len(keys)): values.append(eval(config[func][keys[j]])) funcparamd[func]=dict(zip(keys,values)) """while 'func'+str(i) in config: funclistd['func'+str(i)]=eval(config['func'+str(i)]['func']) keys=config.options('func'+str(i))[1:] values=[] for j in range(len(keys)): values.append(eval(config['func'+str(i)][keys[j]])) funcparamd['func'+str(i)]=dict(zip(keys,values)) i+=1 """ #packing the function components into one dictionary funccompd={'funclist':funclistd,'funcparam':funcparamd} #converting to list-type to allow indexing #funccomp=dict_to_list(funccompd) #eqparam=dict_to_list(eqparamd) #rk4input=dict_to_list(rk4inputd) #initials=dict_to_list(initialsd) #creating output array #configa=[eqparam, rk4input, funccomp, initials] configad=[eqparamd, rk4inputd, funccompd, initialsd] #creating array with the names of configa configdicnames=lna(['eqparam','rk4input','funccomp','initials']) configdic=dict(zip(configdicnames,configad)) #Importing the Variables and initial conditions #Variable_importer() #returning the arrays with all needed system parameters and variables #return configa, configdic return configdic def dict_to_list(dic): """ Converts dictionaries returned from ``configuration.importer`` into a list with the same structure. This allows calling the content by index not keyword. It works for a maximum of 3 dimensions of dictionaries (dictionary inside a dictionary). **Function-call arguments** \n :param dict dic: The dictionary to convert :returns: List with same structure as input dictionary :rtype: List """ dic_to_list=list(dic.values()) to_list=dic_to_list #print(to_list) i=0 while type(to_list[i]) == dict: to_list[i]=list(to_list[i].values()) j=0 while type(to_list[i][j])==dict: to_list[i][j]=list(to_list[i][j].values()) k=0 while type(to_list[i][j][k])==dict: to_list[i][j][k]=list(to_list[i][j][k].values()) if k<len(to_list[i][j])-1: k+=1 if j<len(to_list[i])-1: j+=1 if i<len(to_list)-1: i+=1 return to_list ###Function to import parameters for the Sellers-EBM from a parameterfile ###with arrays of values def parameterimporter(filename,*args,**kwargs): """ A function purpose-built to import 1-dimensional parameters for the sellers-type functions. The standard parameters (:ref:`Sellers 1969`) are written into a **.ini-file** and will be extracted to override the 0-dimensional parameters with 1-dimensional ones. .. Important:: This function is inbound into ``configuration.parameterinterpolater`` or ``configuration.parameterinterpolaterstepwise`` which interpolate the parameters to the gridresolution. **To import, interpolate and overwrite these parameter use** ``configuration.add_sellersparameters``. Parameters which are imported 1-dimensionally: * *b*: Empirical constant to estimate the albedo * *Z*: Zonal mean altitude * *Q*: Solar insolation * *dp*: The tropospheric pressure depth * *dz*: The average zonal ocean depth * *Kh*: The thermal diffusivity of the atmospheric sensible heat term * *Kwv*: The thermal diffusivity of the watervapour term * *Ko*: The thermal diffusivity of the oceanic sensible heat term * *a*: Empricial constant to calculate the meridional windspeed The parameters are divided into two types, one defined on a latitudinal circle (gridlines) and one defined on a latitudinal belt (center point between two latitudinal circles/gridlines) .. Note:: The standard parameters from :ref:`Sellers (1969)` are already provided with this project in 'ZOEE/tutorials/config/Data/'. By specifying no path (**path=None**) they can directly be used (advised since the parameters are structured in a special way). **Function-call arguments** \n :param string filename: The name of the **parameter.ini-file** * type: string * value: standard: 'SellersParameterization.ini' :param args: :param kwargs: Optional Keyword arguments: * *path*: The directory path where the **parameter.ini-file** is located. * type: string * value: **full path** ('/home/user/dir0/dir1/filedir/') or **relative path** ('../../filedir/') :returns: circlecomb, beltcomb: List of parameters defined on a latitudinal circle, and latitudinal belt :rtype: List, List """ path=kwargs.get('path',None) #Importing the paras.ini from path if path == None: possible_paths = ['', 'config/', '../config/'] for i in sys.path: possible_paths.append(i + '/ZOEE/tutorials/config/') for trypath in possible_paths: exists = os.path.isfile(trypath+filename) if exists: path=trypath print('Loading Parameters from: '+path+filename) paras=configparser.ConfigParser() paras.read(path+filename) break if trypath==possible_paths[-1]: sys.exit('Error: File not found, please specify the path of the configuration.ini. parameterimporter(filename,path= " ... ")') else: #Importing the configfile.ini exists = os.path.isfile(path+filename) if exists: print('Loading parameters from: '+path) paras=configparser.ConfigParser() paras.read(path+filename) else: sys.exit('Error: File not found, please specify the path of the parameter.ini. parameterimporter(filename,path= " ... ")') #Creating and filling arrays with values for latitudinal belts belt=paras.options('belt') for i in range(int(len(paras.options('belt')))): belt[i]=eval(paras['belt'][belt[i]]) #Creating and filling arrays with values for latitudinal circles circle=paras.options('circle') for i in range(int(len(paras.options('circle')))): circle[i]=eval(paras['circle'][circle[i]]) """#Splitting the arrays to get the arrays for northern and southern hemisphere splitted beltn,belts=belt[:int(len(belt)/2)],belt[int(len(belt)/2):] circlen,circles=circle[:int(len(circle)/2)],circle[int(len(circle)/2):] #Recombining arrays. Needed because the arrays belt and circle are not #ordered from -90° to 90° beltcomb=[0]*len(beltn) circlecomb=[0]*len(circlen) for i in range(len(beltn)): belts[i].reverse() beltcomb[i]=belts[i]+beltn[i] for i in range(len(circlen)): circles[i].reverse() circlecomb[i]=circles[i]+circlen[i]""" return circle, belt # circlecomb, beltcomb def overwrite_parameters(config, P_config, num_params, labels, levels): config_out = copy.deepcopy(config) if num_params == 1: if levels is None: if labels[0][:4] == 'func': config_out['funccomp']['funcparam'][labels[0]][labels[1]] = P_config if labels[0] == 'eqparam': config_out[labels[0]][labels[1]] = P_config else: if labels[0][:4] == 'func': config_out['funccomp']['funcparam'][labels[0]][labels[1]][levels] = P_config else: for i in range(num_params): if levels[i] is None: if labels[i][0][:4] == 'func': config_out['funccomp']['funcparam'][labels[i][0]][labels[i][1]] = P_config[i] if labels[i][0] == 'eqparam': config_out[labels[i][0]][labels[i][1]] = P_config[i] else: if type(config['funccomp']['funcparam'][labels[i][0]][labels[i][1]]) == float: raise Exception('parameter no. ' + str(i) + 'not defined in 1d space') elif np.shape(config['funccomp']['funcparam'][labels[i][0]][labels[i][1]]) == ( levels[i],): config_out['funccomp']['funcparam'][labels[i][0]][labels[i][1]] = \ np.transpose(np.tile(config['funccomp']['funcparam'][labels[i][0]][labels[i][1]], (P_config[i].size, 1))) if labels[i][0][:4] == 'func': config_out['funccomp']['funcparam'][labels[i][0]][labels[i][1]][levels[i]] = \ P_config[i] if labels[i][0] == 'eqparam': config_out[labels[i][0]][labels[i][1]][i] = P_config[i] return config_out ###Function to interpolate the parameterizations given from sellers, into an interpolated ####output with higher resolution def parameterinterpolator(filename, *args, **kwargs): """ An interpolation method fitting a polynomial of degree 10 to the parameter distributions. This creates parameter distributions suitable for the gridresolution (necessary if a higher resolution than 10° is used. This function includes the function ``configuration.parameterimporter`` and takes the same arguments. **Function-call arguments** \n :param string filename: The name of the **parameter.ini-file** * type: string * value: standard: 'SellersParameterization.ini' :param args: :param kwargs: Optional Keyword arguments: * *path*: The directory path where the **parameter.ini-file** is located. * type: string * value: **full path** ('/home/user/dir0/dir1/filedir/') or **relative path** ('../../filedir/') :returns: newcircle, newbelt: List of interpolated parameters defined on a latitudinal circle, and latitudinal belt :rtype: List, List """ path=kwargs.get('path',None) #Importing parameters inputparas=parameterimporter(filename,path=path) #defining new latitudinal arrays if Base.both_hemispheres==True: Latrange=180 latnewc=np.linspace(-90,90,int(Latrange/Base.spatial_resolution+1)) latnewb=np.linspace(-90,90-Base.spatial_resolution, int(Latrange/Base.spatial_resolution))+Base.spatial_resolution/2 latnewb=np.insert(latnewb,0,-90) latnewb=np.append(latnewb,90) else: Latrange=90 latnewc=np.linspace(0,90-Base.spatial_resolution, int(Latrange/Base.spatial_resolution)) latnewb=np.linspace(0,90-Base.spatial_resolution, int(Latrange/Base.spatial_resolution))+Base.spatial_resolution/2 latnewb=np.insert(latnewb,0,0) latnewb=np.append(latnewb,90) #Interpolation of circle parameters newcircle=[0]*len(inputparas[0]) lat10c=np.linspace(-80,80,17) for i in range(len(inputparas[0])): zc=np.polyfit(lat10c,inputparas[0][i],10) fc=np.poly1d(zc) newcircle[i]=fc(latnewc) newcircle[i]=newcircle[i][1:] newcircle[i]=newcircle[i][:-1] #Interpolation of belt parameters newbelt=[0]*len(inputparas[1]) lat10b=np.linspace(-85,85,18) for i in range(len(inputparas[1])): zb=np.polyfit(lat10b,inputparas[1][i],10) fb=np.poly1d(zb) newbelt[i]=fb(latnewb) newbelt[i]=newbelt[i][1:] newbelt[i]=newbelt[i][:-1] return newcircle, newbelt ###Function to interpolate the parameterizations given from sellers, into an interpolated ####output with higher resolution with stepwise interpolation and averaging def parameterinterpolatorstepwise(filename,*args,**kwargs): """ An interpolation method stepwise fitting and averaging a polynomial of degree 2 to the parameter distribution. The interpolation method is more advanced compared to ``configuration.parameterinterpolator``. For each point (over the latitudes) a polynomial fit of degree 2 is made over the point plus the neighbouring points and estimates for the new gridresolution between these neighbouring points are stored. This is done for every point of the original parameters (except the endpoints). Because the interpolations overlap, the values are averaged to obtain a best estimate from multiple interpolations. This function includes the function ``configuration.parameterimporter`` and takes the same arguments. **Function-call arguments** \n :param string filename: The name of the **parameter.ini-file** * type: string * value: standard: 'SellersParameterization.ini' :param args: :param kwargs: Optional Keyword arguments: * *path*: The directory path where the **parameter.ini-file** is located. * type: string * value: **full path** ('/home/user/dir0/dir1/filedir/') or **relative path** ('../../filedir/') :returns: newcircle, newbelt: List of interpolated parameters defined on a latitudinal circle, and latitudinal belt :rtype: List, List """ path=kwargs.get('path',None) #Importing parameters inputparas=parameterimporter(filename,path=path) #Defining new latitudinal arrays if Base.both_hemispheres==True: Latrange=180 latnewc=np.linspace(-90+Base.spatial_resolution, 90-Base.spatial_resolution,int(Latrange/Base.spatial_resolution-1)) latnewb=np.linspace(-90,90-Base.spatial_resolution, int(Latrange/Base.spatial_resolution))+Base.spatial_resolution/2 else: Latrange=90 latnewc=np.linspace(0,90-Base.spatial_resolution, int(Latrange/Base.spatial_resolution)) latnewb=np.linspace(0,90-Base.spatial_resolution, int(Latrange/Base.spatial_resolution))+Base.spatial_resolution/2 latnewb=np.insert(latnewb,0,0) latnewb=np.append(latnewb,90) ###Interpolation of circle parameters### #Array for output newcircle=np.array([[0]*len(latnewc)]*len(inputparas[0]),dtype=float) #Array with 10° latitudal dependence lat10c=np.linspace(-80,80,17) #Loop over each circleparameter for k in range(len(inputparas[0])): #Loop over the length of latitudes (2nd element to one before last element) for i in range(1,len(lat10c)-1): #Do a polyfit 2nd order over the element +-1 element (left and right) zc=np.polyfit(lat10c[i-1:(i+2)],inputparas[0][k][i-1:(i+2)],2) fc=np.poly1d(zc) #Endpoints are set to the value of the inputparameter (no polyfit here) if i == 1: for l in range(int(10/Base.spatial_resolution)): newcircle[k][l]=inputparas[0][k][0] if i == (len(lat10c)-2): for l in range(int((i+2)*10/Base.spatial_resolution-1),int((i+3)*10/Base.spatial_resolution-1)): newcircle[k][l]=inputparas[0][k][-1] #Write for the new latitudal dependence the corresponding values #from the polyfit into the given outputarray #Loop over the element to the right of i-1 to the element to left of i+1 for j in range(int(2*10/Base.spatial_resolution-1)): if newcircle[k][int(i*10/Base.spatial_resolution+j)] == 0: newcircle[k][int((i)*10/Base.spatial_resolution+j)]= fc(latnewc[int((i)*10/Base.spatial_resolution+j)]) #The inbetween value are calculated twice (from left and right) which are now #averaged to give a smooth new parameterization else: newcircle[k][int((i)*10/Base.spatial_resolution+j)]=np.mean([fc(latnewc [int((i)*10/Base.spatial_resolution+j)]),newcircle[k][int((i)*10/Base.spatial_resolution+j)]]) ###Interpolation of belt parameters### #Array for output newbelt=np.array([[0]*len(latnewb)]*len(inputparas[1]),dtype=float) #Array with 10° latitudal dependence lat10b=np.linspace(-85,85,18) #Loop over each beltparameter for k in range(len(inputparas[1])): #Loop over the length of latitudes (2nd element to one before last element) for i in range(1,len(lat10b)-1): #Do a polyfit 2nd order over the element +-1 element (left and right) zb=np.polyfit(lat10b[i-1:(i+2)],inputparas[1][k][i-1:(i+2)],2) fb=np.poly1d(zb) #Endpoints are set to the value of the inputparameter (no polyfit here) if i == 1: for l in range(int(0.5*10/Base.spatial_resolution)): newbelt[k][l]=inputparas[1][k][0] if i == (len(lat10b)-2): for l in range(int((i+0.5)*10/Base.spatial_resolution),len(newbelt[k])): newbelt[k][l]=inputparas[1][k][-1] #Write for the new latitudal dependence the corresponding values #from the polyfit into the given outputarray #Loop over the element to the right of i-1 to the element to left of i+1 for j in range(int(2*10/Base.spatial_resolution)): if newbelt[k][int((i-0.5)*10/Base.spatial_resolution+j)] == 0: newbelt[k][int((i-0.5)*10/Base.spatial_resolution+j)]= fb(latnewb[int((i-0.5)*10/Base.spatial_resolution+j)]) #The inbetween value are calculated twice (from left and right) which are now #averaged to give a smooth new parameterization else: newbelt[k][int((i-0.5)*10/Base.spatial_resolution+j)]=np.mean([fb(latnewb [int((i-0.5)*10/Base.spatial_resolution+j)]),newbelt[k][int((i-0.5)*10/Base.spatial_resolution+j)]]) return newcircle, newbelt #Function to rewrite parameters with arrays of parameters from the Sellers parameterinterpolator #Hardcoded! So take care on which index the sellers functions are placed, standard is: #func0 = Incoming Radiation , func1 = Outgoing Radiation, func2 = Transfer, ... def add_sellersparameters(config,importer,file,transfernumber,downwardnumber,solar,albedo,*args,**kwargs): """ Overwrites the model setup with one-dimensional sellers parameters. It takes a model configuration with 0D sellers parameters, the filename of new parameters and a method of interpolation. This function uses either the method ``configuration.parameterinterpolator`` or ``configuration.parameterinterpolatorstepwise`` which both use the import function ``configuration.parameterimporter``, therefore it requires their attributes too. **Function-call arguments** \n :param dict config: The original config dictionary to overwrite * type: dictionary * value: created by ``configuration.importer`` :param function importer: The name of the interpolator method * type: functionname * value: **parameterinterpolator** or **parameterinterpolatorstepwise** :param string file: The name of the **parameter.ini-file** * type: string * value: standard: 'SellersParameterization.ini' :param integer transfernumber: The [func] header-number in the **configuration.ini-file** which describes the transfer flux * type: integer * value: any :param integer incomingnumber: The [func] header-number in the **configuration.ini-file** which describes the downward flux * type: integer * value: any :param boolean solar: Indicates whether the insolation by Sellers is used * type: boolean * value: True / False :param boolean albedo: Indicates whether the albedo parameters by Sellers are used * type: boolean * value: True / False :param args: :param kwargs: Optional Keyword arguments: * *path*: The directory path where the **parameter.ini-file** is located. * type: string * value: **full path** ('/home/user/dir0/dir1/filedir/') or **relative path** ('../../filedir/') :returns: configuration, parameters :rtype: Dictionary, List """ #solar and albedo are to be set to True or False path=kwargs.get('path',None) #importing the new parameter arrays paras=[[dp,dz,K_h,K_wv,K_o,a],[b,Z,Q]]=importer(file,path=path) #rewriting the transfer parameters with conversion to SI units funct=config['funccomp']['funcparam']['func'+str(transfernumber)] funct['k_wv']=lna(K_wv)*10**5 funct['k_h']=lna(K_h)*10**6 funct['k_o']=lna(K_o)*10**2 funct['a']=lna(a)/100 funct['dp']=lna(dp) funct['dz']=lna(dz)*1000 #rewriting the incoming radiation parameters with conversion + choice to be activated or not funcin=config['funccomp']['funcparam']['func'+str(downwardnumber)] if albedo==True: funcin['albedoparam'][0]=lna(Z) funcin['albedoparam'][1]=lna(b) if solar==True: Vars.solar = lna(Q) * 1.327624658 # 1.2971# configout=config configout['funccomp']['funcparam']['func'+str(transfernumber)]=funct configout['funccomp']['funcparam']['func'+str(downwardnumber)]=funcin return configout, paras
import React from 'react'; import { BrowserRouter } from 'react-router-dom'; import { it, expect } from 'vitest'; import { NavMenu } from '@components/NavBar'; import { render } from '@testing-library/react'; import createMatchMedia from '../../helpers/createMatchMedia'; const MockNavMenu = () => ( <BrowserRouter> <NavMenu openMenu /> </BrowserRouter> ); it('does not render contacts and civic profile links above 600px', () => { const { queryByText } = render(<MockNavMenu />); const contactsLink = queryByText('Contacts'); const civicProfileLink = queryByText('Civic Profile'); expect(contactsLink).toBeNull(); expect(civicProfileLink).toBeNull(); }); it('renders contacts and civic profile links below 600px', () => { window.matchMedia = createMatchMedia(599); const { queryByText } = render(<MockNavMenu />); const contactsLink = queryByText('Contacts'); const civicProfileLink = queryByText('Civic Profile'); expect(contactsLink).not.toBeNull(); expect(civicProfileLink).not.toBeNull(); });
package adapter.rest; import org.example.adapter.controller.rest.DoorRestController; import org.example.config.spring.rest.RouteModule; import org.example.core.usecase.port.DoorsExecutor; import org.springframework.http.HttpStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.ResponseEntity; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; public class DoorRestControllerTest { private MockMvc mockMvc; private DoorRestController doorRestController; private DoorsExecutor doorsExecutor; private static final String QUANTITY = "100"; @BeforeEach public void setUp() { doorsExecutor = mock(DoorsExecutor.class); doorRestController = new DoorRestController(doorsExecutor); mockMvc = MockMvcBuilders.standaloneSetup(doorRestController).build(); } @Test public void test_when_post_door_controller_then_should_return_ok() { ResponseEntity<Object> responseEntity = doorRestController.postDoorsQuantity(QUANTITY); Assertions.assertEquals(HttpStatus.ACCEPTED.value(), responseEntity.getStatusCodeValue()); verify(doorsExecutor, times(1)).execute(any()); } @Test public void test_when_post_door_endpoint_with_quantity_then_should_run_ok() throws Exception { mockMvc.perform(post(String.format("%s/%s", RouteModule.DOORS, QUANTITY))) .andDo(print()) .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) .andReturn(); } }
#!/usr/bin/env ruby # frozen_string_literal: true require 'bundler/setup' require 'srx' require 'optparse' require 'benchmark' options = {} OptionParser.new do |opts| opts.banner = "Usage: #{$PROGRAM_NAME} [options]" opts.on('-sFILE', '--srx FILE', 'SRX file (optional)') opts.on('-fFORMAT', '--format FORMAT', 'Format of input text (default: text)') end.parse!(into: options) data = if options[:srx] Srx::Data.from_file(path: options[:srx]) else Srx::Data.default end format = options[:format]&.to_sym || :text engine = Srx::Engine.new(data, format: format) license_text = File.read(File.expand_path('../LICENSE.txt', __dir__)).strip.then { |t| Srx::Util.unwrap(t) } # Golden Rules speed test; see # https://github.com/diasks2/pragmatic_segmenter#speed-performance-benchmarks gold_text = Srx::Util.unwrap(<<~TXT) Hello World. My name is Jonas. What is your name? My name is Jonas. There it is! I found it. My name is Jonas E. Smith. Please turn to p. 55. Were Jane and co. at the party? They closed the deal with Pitt, Briggs & Co. at noon. Let's ask Jane and co. They should know. They closed the deal with Pitt, Briggs & Co. It closed yesterday. I can see Mt. Fuji from here. St. Michael's Church is on 5th st. near the light. That is JFK Jr.'s book. I visited the U.S.A. last year. I live in the E.U. How about you? I live in the U.S. How about you? I work for the U.S. Government in Virginia. I have lived in the U.S. for 20 years. At 5 a.m. Mr. Smith went to the bank. He left the bank at 6 P.M. Mr. Smith then went to the store. She has $100.00 in her bag. She has $100.00. It is in her bag. He teaches science (He previously worked for 5 years as an engineer.) at the local University. Her email is [email protected]. I sent her an email. The site is: https://www.example.50.com/new-site/awesome_content.html. Please check it out. She turned to him, 'This is great.' she said. She turned to him, "This is great." she said. She turned to him, "This is great." She held the book out to show him. Hello!! Long time no see. Hello?? Who is there? Hello!? Is that you? Hello?! Is that you? 1.) The first item 2.) The second item 1.) The first item. 2.) The second item. 1) The first item 2) The second item 1) The first item. 2) The second item. 1. The first item 2. The second item 1. The first item. 2. The second item. • 9. The first item • 10. The second item ⁃9. The first item ⁃10. The second item a. The first item b. The second item c. The third list item This is a sentence cut off in the middle because pdf. It was a cold#{' '} night in the city. features contact manager events, activities You can find it at N°. 1026.253.553. That is where the treasure is. She works at Yahoo! in the accounting department. We make a good team, you and I. Did you see Albert I. Jones yesterday? Thoreau argues that by simplifying one’s life, “the laws of the universe will appear less complex. . . .” "Bohr [...] used the analogy of parallel stairways [...]" (Smith 55). If words are left off at the end of a sentence, and that is all that is omitted, indicate the omission with ellipsis marks (preceded and followed by a space) and then indicate the end of the sentence with a period . . . . Next sentence. I never meant that.... She left the store. I wasn’t really ... well, what I mean...see . . . what I'm saying, the thing is . . . I didn’t mean it. One further habit which was somewhat weakened . . . was that of combining words into self-interpreting compounds. . . . The practice was not abandoned. . . . TXT n = 100 Benchmark.bm do |x| x.report('LICENSE.txt (en)') { n.times { engine.segment(license_text, language: 'en') } } x.report('LICENSE.txt (zz)') { n.times { engine.segment(license_text, language: 'zz') } } x.report('Golden Rules (en)') { n.times { engine.segment(gold_text, language: 'en') } } end
#!/usr/bin/env node import 'source-map-support/register'; import * as cdk from '@aws-cdk/core'; import {AwsTrainingStack} from '../lib/aws-training-stack'; import {StackProps} from "@aws-cdk/core"; // cdk.App() is the app that is run when you invoke cdk deploy // app is the parent which all our stacks will be attached to. const app = new cdk.App(); // StackProps are used by classes that extend cdk.Stack to explicitly define cloudformation properties like what region or account // this stack is being deployed to. const stackProps: StackProps = { description: 'Aws Training Stack', env: { region: 'us-west-1' } } // A CDK project can manage multiple stacks and will automatically export and import variables in cloudformation which // are defined in one stack that are used in another stack in this source code // AwsTrainingStack is a stack that we are defining imported from '../lib/aws-training-stack' // each stack attached to the App will create its own stack in cloudformation. new AwsTrainingStack(app, 'AnAwsTrainingStack', { // Whatever email you choose will receive a subscription confirmation when you provision. email: '[email protected]', stackProps });
import { ChannelType, EmbedBuilder, VoiceState } from "discord.js"; import BaseClient from "@structures/BaseClient.js"; import * as fs from "fs"; import voiceStateUpdate from "@root/build/events/voice/VoiceStateUpdate"; export default class { private client: BaseClient; public constructor(client: BaseClient) { this.client = client; } public async dispatch(oldState: VoiceState, newState: VoiceState): Promise<any> { if (!oldState || !newState || !newState.guild) return; const { channel: oldChannel, member: oldMember } = oldState; const { channel: newChannel, member: newMember, guild } = newState; const guildData: any = await this.client.findOrCreateGuild(guild.id); /* Voice time counter */ const voiceFile: any = JSON.parse(fs.readFileSync("./assets/voice.json").toString()); voiceFile.joinTime = voiceFile.joinTime || {}; voiceFile.voiceTime = voiceFile.voiceTime || {}; voiceFile.afk = voiceFile.afk || {}; const now: any = Date.now(); if(newChannel){ if(newChannel?.members.size < 2 || newState.mute || newState.deaf){ if(!voiceFile.afk[newMember!.id]) voiceFile.afk[newMember!.id] = now; } if(newChannel?.members.size >= 2){ for(const voiceMember of newChannel.members.values()){ if(voiceFile.afk[voiceMember.id] && !voiceMember.voice.deaf && !voiceMember.voice.mute && (voiceMember.id !== newMember!.id)){ delete voiceFile.afk[voiceMember.id]; } } if(voiceFile.afk[newMember!.id] && !newState.deaf && !newState.mute){ const joinDate: any = voiceFile.joinTime[newMember!.id]; const voiceTime: any = Date.now() - joinDate; const afkDate: any = voiceFile.afk[newMember!.id]; const afkTime: any = Date.now() - afkDate; /* Not afk minutes */ let validTime: any = voiceTime - afkTime; if(validTime < 0) validTime = null; delete voiceFile.afk[newMember!.id]; if(validTime) voiceFile.voiceTime[newMember!.id] = (voiceFile.voiceTime[newMember!.id] || 0) + validTime; voiceFile.joinTime[newMember!.id] = now; } } } if(oldChannel){ if(oldChannel?.members.size < 2){ for(const voiceMember of oldChannel.members.values()){ if(!voiceFile.afk[voiceMember.id]) voiceFile.afk[voiceMember.id] = now; } } } if(!oldChannel && newChannel){ voiceFile.joinTime[newMember!.id] = now; }else if(!newChannel && oldChannel){ const joinDate: any = voiceFile.joinTime[oldMember!.id]; const voiceTime: any = Date.now() - joinDate; let validTime: any = voiceTime; if(voiceFile.afk[oldMember!.id]){ const afkDate: any = voiceFile.afk[oldMember!.id]; const afkTime: any = Date.now() - afkDate; validTime = validTime - afkTime; delete voiceFile.afk[oldMember!.id]; } if(validTime < 0) validTime = null; delete voiceFile.joinTime[oldMember!.id]; if(validTime) voiceFile.voiceTime[oldMember!.id] = (voiceFile.voiceTime[oldMember!.id] || 0) + validTime; } fs.writeFileSync("./assets/voice.json", JSON.stringify(voiceFile, null, 2)); /* Join to create */ const { joinToCreate: joinToCreateSettings } = guildData.settings; if (newChannel && joinToCreateSettings?.enabled && joinToCreateSettings?.channel) { const channelName: string = joinToCreateSettings.defaultName .replaceAll("%count", joinToCreateSettings.channels?.length || 1) .replaceAll("%user", newMember!.displayName); if (newChannel.id !== joinToCreateSettings.channel) return; /* Create temp channel */ const createdTempChannel: any = await guild.channels .create({ name: channelName, type: ChannelType.GuildVoice, parent: joinToCreateSettings.category ? joinToCreateSettings.category : newChannel.parentId, bitrate: parseInt(joinToCreateSettings.bitrate) * 1000, position: newChannel.rawPosition, userLimit: joinToCreateSettings.userLimit, }) .catch((): any => { const errorText: string = this.client.emotes.channel + " Nutzer/-in: " + newMember!.displayName + " (@" + newMember!.user.username + ")"; const errorEmbed: EmbedBuilder = this.client.createEmbed(errorText, null, "error"); errorEmbed.setTitle(this.client.emotes.error + " Erstellen von Join2Create-Channel fehlgeschlagen"); return guild.logAction(errorEmbed, "guild"); }); if (!createdTempChannel) return; /* Set permissions */ await createdTempChannel.lockPermissions(); await createdTempChannel.permissionOverwrites .create(newMember!.user, { Connect: true, Speak: true, ViewChannel: true, ManageChannels: true, Stream: true, MuteMembers: true, DeafenMembers: true, MoveMembers: true, }) .catch((): void => {}); /* Move member */ await newState .setChannel(createdTempChannel) .then(async (): Promise<void> => { guildData.settings.joinToCreate.channels.push(createdTempChannel.id); guildData.markModified("settings.joinToCreate"); await guildData.save(); }) .catch((): void => { createdTempChannel.delete().catch((): void => {}); }); } if (oldChannel) { if (!joinToCreateSettings?.channels.includes(oldChannel.id)) return; if (oldChannel.members.size >= 1) return; /* Delete channel */ await oldChannel.delete().catch((): void => { const errorText: string = this.client.emotes.channel + " Nutzer/-in: " + newMember; const errorEmbed: EmbedBuilder = this.client.createEmbed(errorText, null, "error"); errorEmbed.setTitle(this.client.emotes.error + " Löschen von Join2Create-Channel fehlgeschlagen"); guild.logAction(errorEmbed, "guild"); }); guildData.settings.joinToCreate.channels = guildData.settings.joinToCreate.channels.filter( (c: any): boolean => c !== oldChannel.id, ); guildData.markModified("settings.joinToCreate"); await guildData.save(); } } }
library(dplyr) # for manipulating data library(ggplot2) # for visualizations # folders pac_data_folder <- file.path('pac_results_data') figures_folder <- file.path('pac_figures') # scenario name ifr_type <- 'med' scen_descript <- '_example_low_R0' scen_name <- paste0(ifr_type,'_IFR',scen_descript) # full names for post-acute care services full_ct_names <- c('none' = 'Direct to home', 'hh' = 'Home health', 'snf' = 'SNF', 'hos' = 'Hospice') # provide geoids and corresponding market share estimates hs_geoids <- c('49043','49035','49049') hs_market_share <- c(0.7,0.5,0.2) #import data and functions simArr_icu <- readRDS(file.path(pac_data_folder, paste0(scen_name, '_pac_results_icu.rds'))) simArr_nonicu <- readRDS(file.path(pac_data_folder, paste0(scen_name, '_pac_results_nonicu.rds'))) simArr_icu_inflow <- readRDS(file.path(pac_data_folder, paste0(scen_name, '_pac_results_icu_inflow.rds'))) simArr_nonicu_inflow <- readRDS(file.path(pac_data_folder, paste0(scen_name, '_pac_results_nonicu_inflow.rds'))) source(file.path('pac_functions.R')) # calculate simulation summary stats---------------------------------------------------------------- # summarize pac patient counts/census # ************************************ # calculate summary stats for for former icu patient pac (counts) pac_HS_icu <- summarize_pac_sims(sim_results = simArr_icu, geoids = hs_geoids, multiplier = hs_market_share) # calculate summary stats for former non-icu patients (counts) pac_HS_nonicu <- summarize_pac_sims(sim_results = simArr_nonicu, geoids = hs_geoids, multiplier = hs_market_share) # calculate summary stats for all former hospitalized patients (counts) pac_HS_all <- summarize_pac_sims(sim_results = simArr_nonicu+simArr_icu, geoids = hs_geoids, multiplier = hs_market_share) # summarize flows to pac # ************************************ # calculate summary stats for all former hospitalized patients (flows) pac_HS_all_inflow <- summarize_pac_sims(simArr_nonicu_inflow+simArr_icu_inflow, geoids = hs_geoids, multiplier = hs_market_share) # create figures ------------------------------------------------------------------- # a few figure examples # patient counts # ************************************ #all patient counts (consolidated into single plot using pac_plot_fcn) p <- pac_plot_fcn(pac_HS_all, titleText = 'Post-acute care census', subtitleText = 'Former Health System X Hospitalizations', full_names = full_ct_names) plot_save_function(p, figures_folder, fileStr = 'Health_System_X_census') p #all patient counts (as separate plots in a row using pac_plot_fcn2) p <- pac_plot_fcn2(pac_HS_all, titleText = 'Post-acute care census', subtitleText = 'Former Health System X Hospitalizations', full_names = full_ct_names) plot_save_function(p, figures_folder, fileStr = 'Health_System_X_census2', width = 8) p # former icu patient counts p <- pac_plot_fcn2(pac_HS_icu, titleText = 'Post-acute care census, former ICU patients', subtitleText = 'Health System X', full_names = full_ct_names) plot_save_function(p, figures_folder, fileStr = 'Health_System_X_census_nonicu2') p # former non-icu patient counts p <- pac_plot_fcn2(pac_HS_nonicu, titleText = 'Post-acute care census, former non-ICU patients', subtitleText = 'Health System X', full_names = full_ct_names) plot_save_function(p, figures_folder, fileStr = 'Health_System_X_census_nonicu2') p # patient flows # ************************************ #all patient flows p <- pac_plot_fcn2(pac_HS_all_inflow, titleText = 'Post-acute care flows per day, all patients', subtitleText = 'Health System X', full_names = full_ct_names) plot_save_function(p, figures_folder, fileStr = 'Health_System_X_flows_all2') p
//Tatiana Fucsik package edu.seminolestate.patients; import java.time.temporal.ChronoUnit; import java.time.LocalDate; public class Outpatient extends Patient { private int visitNumber; private int clinicNumber; private LocalDate procedureDate; protected static final LocalDate DEFAULT_PROCEDURE_DATE = LocalDate.now(); protected static final int DEFAULT_VISIT_NUMBER = Integer.MAX_VALUE; protected static final int DEFAULT_CLINIC_NUMBER = Integer.MAX_VALUE; public Outpatient (String newFirstName, String newLastName, int newPatientID, int newVisitNumber, int newClinicNumber, LocalDate newProcedureDate) { super(newFirstName, newLastName,newPatientID); this.setClinicNumber(newClinicNumber); this.setVisitNumber(newVisitNumber); this.setProcedureDate(newProcedureDate); } public Outpatient (String newFirstName, String newLastName, int newPatientID) { this(newFirstName, newLastName, newPatientID, DEFAULT_CLINIC_NUMBER, DEFAULT_VISIT_NUMBER, DEFAULT_PROCEDURE_DATE); } @Override public int lengthOfStay() { int daysbetween = (int) ChronoUnit.DAYS.between(procedureDate, LocalDate.now()); return daysbetween; } public int getVisitNumber() { return clinicNumber; } public void setVisitNumber( int newVisitNumber) { if (newVisitNumber > 0) this.visitNumber = newVisitNumber; } public int getClinicNumber() { return clinicNumber; } public void setClinicNumber( int newClinicNumber){ if (newClinicNumber > 0) this.clinicNumber = newClinicNumber; } public LocalDate getProcedureDate() { return procedureDate; } public void setProcedureDate(LocalDate newProcedureDate) { if (newProcedureDate != null) this.procedureDate = newProcedureDate; } public String toString() { return super.toString() + "Outpatient [Procedure date= " + procedureDate + ", Clinic Number= " + clinicNumber + ", Visit Number= " + visitNumber + "]"; } }
This repository contains several scripts that simplify the interactions with singularity containers for our experiments. ## Install To install this submodules in your project: 1) Run the following commands: ``` mkdir -p submodules git submodule add ../../../AIRL_tools/singularity_scripts ./submodules/singularity_scripts ``` The url is relative to the url of your project, so here we assumed that you project is for instance located in `/Students_projects/My_Self/My_Project` You will now have a folder named `submodules/singularity_scripts` containing all the necessary scripts. 2) You can add in your singularity folder symbolic links for a simplified access to the scripts of this submodules: ``` cd ./singularity/ ln -s ../submodules/singularity_scripts/start_container ./start_container ln -s ../submodules/singularity_scripts/build_final_image ./build_final_image ``` ------ ## Description There are 2 singularity scripts: - `start_container` - `build_final_image` Both of them **have to be executed in your `singularity/` folder**. ### start_container The `start_container` script builds a sandbox and shells into it. If the sandbox already exists, we directly shell into it. The script has several additional arguments. You can use the help for more information: ```bash ./start_container --help ``` ### build_final_image The `build_final_image` script builds a read-only final container in which the entire project repository is cloned. In particular, it parses the singularity definition file, looking for those tags: - `#NOTFORFINAL` - `#CLONEHERE` #### `#NOTFORFINAL` All the lines with `#NOTFORFINAL` are skipped and not taken into account. Thus, if you add the line in your `%post` section of your singularity definition file: ```bash exit 0 #NOTFORFINAL - the lines below this "exit" will be executed only when building the final image ``` then: - the script `start_container` will only take into account the lines **preceding** the tag `#NOTFORFINAL` - the script `build_final_image` will take into account all the lines **preceding** and **after** the tag `#NOTFORFINAL` #### `#CLONEHERE` All the lines with the tag `#CLONEHERE` are replaced with a command that is cloning the project repository to the appropriate commit. Technically, that resulting command executes the following operations: ```bash git clone --recurse-submodules --shallow-submodules <repo_address_with_token> <project_name> cd <project_name> git checkout <commit_sha> cd .. ``` - If a Gitlab CI Job Token is provided, then `<repo_address_with_token>` is `http://gitlab-ci-token:<ci_job_token>@<repo_address>`. In that case **no password needs to be entered to clone the repository**. - If a Gitlab Personal Token is provided, then `<repo_address_with_token>` is `https://oauth:<personal_token>@<repo_address>`. In that case **no password needs to be entered to clone the repository**. - If no token is provided, then `<repo_address_with_token>` is simply `https://<repo_address>`. In that case **a password will be required to clone the repository**. The `<project_name>`, `<commit_sha>`, `<ci_job_token>` and `<personal_token>` can be specified in the arguments of the `build_final_image` script. For more information about the arguments of the `build_final_image` script, you can use the help: ```bash ./build_final_image --help ``` #### Specify a Commit When using the tag `#CLONEHERE` you can specify any reference to the commit you desire to clone specifically. The `HEAD` is used by default. **Warning: the commit mentioned should have been pushed before calling the `./build_final_image` script.** ##### Examples: - Commit reference to clone: *last commit on branch develop* ```bash ./build_final_image --personal-token xxxxxxxx --commit-ref develop ``` - Commit reference to clone: *tag v1.2* ```bash ./build_final_image --personal-token xxxxxxxx --commit-ref v1.2 ``` - Commit reference to clone: *current HEAD* ```bash ./build_final_image --personal-token xxxxxxxx ``` - Commit reference to clone: *commit preceding current HEAD* ```bash ./build_final_image --personal-token xxxxxxxx --commit-ref HEAD~1 ``` ------ ## Quick tips with git submodules - To update the gitlab_notebook tools in your project, run `git submodule update` - To clone a project with the submodules already configures: `git clone --recurse-submodules https://your_url.git`
--- title: "Figure Proportion of area represented" author: "Anna Talucci" date: "2024-03-08" output: html_document --- # clear environment ```{r} rm(list=ls()) ``` # Overview Creat over view map with permafrost extent and summary of site data. Notes:From PCN-Fire-Sysnthesis "Manuscript Map" [Better colors for Mapping](https://www.esri.com/arcgis-blog/products/js-api-arcgis/mapping/better-colors-for-better-mapping/) # Packages ```{r} library(tidyverse) library(sf) library(rnaturalearth) library(rnaturalearthdata) library(RColorBrewer) library(cowplot) library(ggpubr) library(ggnewscale) library(scales) library(ggrepel) library(patchwork) library(ggridges) ``` # Plot themes ```{r} comp_theme = theme_minimal() + theme(legend.position = "none") + theme(panel.grid.major = element_blank()) + theme(axis.title.y = element_text(size = 11, hjust = 0.5, vjust = 1.1), axis.text.x = element_text(size = 10, color = "black"), axis.text.y = element_text(size = 10, color = "black")) ``` # Projection [Some projection info]https://nsidc.org/data/user-resources/help-center/guide-nsidcs-polar-stereographic-projection) ```{r} polarProj = "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +type=crs" ``` polarProj = "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +type=crs" # Data ```{r} datacubePt = st_read("../data/spatialDataCreate/PermafrostFireEcozoneDatacube.shp", "PermafrostFireEcozoneDatacube") ``` ```{r} datacubePt ``` ## Predicted measurements ```{r} datacubePred = read_csv("../data/dataCube/PermafrostFireDatacubeFinal.csv") ``` ## Resolve Polygons ```{r} resolve = st_read("../data/spatialData/RESOLVE_Ecoregions_and_Biomes/Biomes_and_Ecoregions_2017.shp", "Biomes_and_Ecoregions_2017") ``` ```{r} resTarget = c("Arctic coastal tundra", "Arctic foothills tundra", "Beringia lowland tundra", "Beringia upland tundra", "Chukchi Peninsula tundra", "East Siberian taiga", "Interior Alaska-Yukon lowland taiga", "Interior Yukon-Alaska alpine tundra", "Muskwa-Slave Lake taiga", "Northeast Siberian taiga", "Northern Canadian Shield taiga", "Northwest Territories taiga", "Yamal-Gydan tundra") ``` ```{r} resolve1 = resolve %>% filter(ECO_NAME %in% resTarget) ``` ## World map https://datacatalog.worldbank.org/dataset/world-bank-official-boundaries ```{r} wrld = st_read("../data/spatialData/world/WB_countries_Admin0_10m.shp", "WB_countries_Admin0_10m") ``` ## permafrost ```{r} permafrost = st_read("../data/spatialData/permafrost/permaice.shp", "permaice") ``` ```{r} head(permafrost) ``` # Arctic Circle Arctic Circle shapefile came from [Natural Earth](https://www.naturalearthdata.com/downloads/110m-physical-vectors/110m-geographic-lines/) ```{r} circle = st_read("../data/spatialData/ne_110m_geographic_lines/ne_110m_geographic_lines.shp", "ne_110m_geographic_lines") ``` ```{r} arctic = circle %>% filter(name=="Arctic Circle") ``` # Filter shapefiles ## Countries ```{r} target = c("Asia", "Europe", "North America") ``` Filter for all ```{r} nh = wrld %>% filter(CONTINENT %in% target) %>% dplyr::select( OBJECTID:FORMAL_EN, NAME_EN, ISO_A2, CONTINENT:REGION_WB, Shape_Leng:geometry) ``` ```{r} nh ``` ## Permafrost ```{r} permafrost1 = permafrost %>% filter(EXTENT %in% c("C", "D", "S")) ``` # Reproject ```{r} nh_pp = st_transform(nh, crs = polarProj) artic_pp = st_transform(arctic, crs = polarProj) permafrost1_pp = st_transform(permafrost1, crs = polarProj) resolve1_pp = st_transform(resolve1, crs = polarProj) resolveAllpp = st_transform(resolve, crs = polarProj) ``` ```{r} nh_pp ``` ```{r} nh_cropped <- st_crop(nh_pp, xmin = -180, xmax = 180, ymin = 45, ymax = 90) ``` # Palettes [More Palette options for R](https://stackoverflow.com/questions/9563711/r-color-palettes-for-many-data-classes) ```{r} ecoPalette = c('#a6cee3','#1f78b4',"#00bfa0",'#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00',"#dc0ab4",'#b2df8a','#ffff99', '#CC6677', '#DDCC77') ``` ("#e60049", "#0bb4ff", "#50e991", "#e6d800", "#9b19f5", "#ffa300", "#b3d4ff") ```{r} permafrost_palette = c('#71A6D1', '#99C4E1', '#C0E2F0') permafrost_palette2 = c('#88419d', '#8c6bb1','#8c96c6') permafrost_palette3 = c('#c994c7','#d4b9da', '#f1eef6') permafrost_palette4 = c('#4b2665', '#8774ab', '#d4b9da') ``` ```{r} brltnd_palette = c('#4a6741', '#3d3021') ``` xlim = c(-3302324, 2312498), ylim = c(-1108650, 3102452) ymin: -25426070 xmax: 28628080 ymax: 8108557 xmin: ymin: xmax: ymax: scale_color_manual(values = c("A" ="#fdae61","B" = "#ff6347", "C" = "#fee08b"), labels = c( "A" ="Tweedsmuir fire","B" = "Entiako fire", "C" = "Chelaslie fire" ), name = "Fire perimeters") + # Maps ## Zoom Level ```{r eval=FALSE, include=FALSE} zoom_to <- c(0, 90) # Geographic North pole zoom_level <- 3 lon_span <- 360 / 2^zoom_level lat_span <- 180 / 2^zoom_level ``` ```{r eval=FALSE, include=FALSE} lon_bounds <- c(zoom_to[1] - lon_span / 2, zoom_to[1] + lon_span / 2) lat_bounds <- c(zoom_to[2] - lat_span / 2, zoom_to[2] + lat_span / 2) ``` coord_sf(xlim = lon_bounds, ylim = lat_bounds) + ## Display window ```{r eval=FALSE, include=FALSE} # corner points at bottom left and top right # supply as WGS84 and directly transform to target CRS (Mollweide) cornerpts <- data.frame(label = c('A', 'B')) cornerpts$geometry <- st_transform(st_sfc(st_point(c(279.26, 33.92)), st_point(c(102.34, 31.37)), crs = 4326), crs = polarProj) cornerpts <- st_as_sf(cornerpts) ``` ```{r eval=FALSE, include=FALSE} disp_win_wgs84 <- st_sfc(st_point(c(279.26, 33.92)), st_point(c(102.34, 31.37)), crs = 4326) disp_win_wgs84 disp_win_trans <- st_transform(disp_win_wgs84, crs = polarProj) disp_win_trans disp_win_coord <- st_coordinates(disp_win_trans) ``` ```{r} #### zoom to kamchatka, different projection #### zoom_to <- c(180, 83) # ~ center of Kamchatka zoom_level <- 2.25 # Lambert azimuthal equal-area projection around center of interest target_crs <- polarProj#sprintf('+proj=laea +lon_0=%f +lat_0=%f', zoom_to[1], zoom_to[2]) C <- 40075016.686 # ~ circumference of Earth in meters x_span <- C / 2^(zoom_level+.1) y_span <- C / 2^(zoom_level+.3) # also sets aspect ratio zoom_to_xy <- st_transform(st_sfc(st_point(zoom_to), crs = 4326), crs = target_crs) zoom_to_xy disp_window <- st_sfc(st_point(st_coordinates(zoom_to_xy - c(x_span / 2, y_span / 2))), st_point(st_coordinates(zoom_to_xy + c(x_span / 2, y_span / 2))), crs = target_crs) ``` # Build Overview map by Ecozone ## with Resolve Ecozones ```{r} ( ecozoneMap = ggplot() + geom_sf(data = nh_pp, fill = "#F9F6EE", colour="#F9F6EE") + geom_sf(data = resolveAllpp, fill = "#F9F6EE", color= "#A9AB9D") + geom_sf(data = resolve1_pp, aes(fill = ECO_NAME), color= "#A9AB9D", alpha=.75) + geom_sf(data=artic_pp, fill=NA, colour = '#3d3021', lwd=.5, linetype="dashed") + scale_fill_manual(values = ecoPalette, name = "Ecozones") + #scale_color_manual(values = ecoPalette, name = "Ecozones") + labs(x="", y="") + coord_sf(xlim = st_coordinates(disp_window)[,'X'], ylim = st_coordinates(disp_window)[,'Y']) + theme(panel.grid.major = element_line(color = gray(0.5), linetype = "solid", size = 0.3), panel.background = element_rect(fill = "#C5D8D7"), plot.margin=unit(c(0,0,0,0), "mm"), legend.key=element_blank(), legend.position = "none", legend.text=element_text(size=0), legend.title=element_text(size=0)) + guides(fill=guide_legend( title.position = "top", ncol=3,byrow=TRUE)) ) ``` ```{r eval=FALSE, include=FALSE} ggsave("../figures/EcozoneResMap.png", plot = ecozoneMap, units = c("in"), dpi=600, bg = "white" ) ``` ### Legend ```{r} ( resEcoLegendBottom = ggplot() + geom_sf(data = nh_pp, fill = "#F9F6EE", colour="#A9AB9D") + geom_sf(data = resolveAllpp, fill = "#F9F6EE", color= "#A9AB9D") + geom_sf(data = resolve1_pp, aes(fill = ECO_NAME), color= "#A9AB9D", alpha=.75) + geom_sf(data=artic_pp, fill=NA, colour = '#3d3021', lwd=.5, linetype="dashed") + scale_fill_manual(values = ecoPalette, name = "Ecozones") + #scale_color_manual(values = ecoPalette, name = "Ecozones") + #geom_sf_text(data = eco_grouped, aes(label = prct), size=3) + coord_sf(xlim = st_coordinates(disp_window)[,'X'], ylim = st_coordinates(disp_window)[,'Y']) + #coord_sf(xlim = disp_win_coord[,'X'], ylim = disp_win_coord[,'Y']) + #coord_sf(xlim = c(-4002324, 3512498), ylim = c(-3008650, 4002452) ) + theme(panel.grid.major = element_line(color = gray(0.5), linetype = "dashed", size = 0.5), panel.background = element_rect(fill = "#C5D8D7")) + theme(plot.margin=unit(c(0,0,0,0), "mm")) + theme(legend.position = "bottom", legend.text=element_text(size=8), legend.margin = margin(0, 0, 0, 0), legend.title=element_text(size=9), legend.key=element_blank(), legend.key.size = unit(5, 'mm'), axis.title.x = element_blank(), axis.title.y = element_blank()) + guides(color = guide_legend(title.position = "top", nrow=4,bycol=TRUE, override.aes = list(size = 4)), fill = guide_legend(title.position = "top", nrow=4,bycol=TRUE, override.aes = list(size = 4))) ) ``` guides(fill=guide_legend(ncol=2)) ```{r} ( resEcoLegendRight = ggplot() + geom_sf(data = nh_pp, fill = "#F9F6EE", colour="#A9AB9D") + geom_sf(data = resolveAllpp, fill = "#F9F6EE", color= "#A9AB9D") + geom_sf(data = resolve1_pp, aes(fill = ECO_NAME), color= "#A9AB9D", alpha=.75) + geom_sf(data=artic_pp, fill=NA, colour = '#3d3021', lwd=.5, linetype="dashed") + scale_fill_manual(values = ecoPalette, name = "Ecozones") + #scale_color_manual(values = ecoPalette, name = "Ecozones") + #geom_sf_text(data = eco_grouped, aes(label = prct), size=3) + coord_sf(xlim = st_coordinates(disp_window)[,'X'], ylim = st_coordinates(disp_window)[,'Y']) + #coord_sf(xlim = disp_win_coord[,'X'], ylim = disp_win_coord[,'Y']) + #coord_sf(xlim = c(-4002324, 3512498), ylim = c(-3008650, 4002452) ) + theme(panel.grid.major = element_line(color = gray(0.5), linetype = "dashed", size = 0.5), panel.background = element_rect(fill = "#C5D8D7")) + theme(plot.margin=unit(c(0,5,0,0), "mm")) + # t,r,b,l theme(legend.position = "right", legend.text=element_text(size=8), legend.margin = margin(0, 0, 0, 0), legend.title=element_text(size=9), legend.key=element_blank(), legend.key.size = unit(5, 'mm'), axis.title.x = element_blank(), axis.title.y = element_blank()) + guides(color = guide_legend(title.position = "top", ncol=4,bycol=TRUE, override.aes = list(size = 4)), fill = guide_legend(title.position = "top", ncol=2,bycol=TRUE, override.aes = list(size = 4))) ) ``` ```{r} legendRight = cowplot::get_legend(resEcoLegendRight) ``` ```{r eval=FALSE, include=FALSE} ggsave("../figures/EcozoneLegendRight.png", plot = legendRight, dpi = 600, bg='white') ``` # Frequency by Ecozone ```{r} ( resArea = resolve1_pp %>% dplyr::mutate(area_meters = st_area(resolve1_pp), # 1 m2 = 0.0.000247105 acres area_acres = area_meters * 0.000247105, # 1m2 = 0.0001 hectares area_hectares = area_meters * 0.0001) %>% dplyr::select(ECO_NAME, area_hectares) %>% rename(resName=ECO_NAME) %>% st_drop_geometry() ) ``` theme_set(theme_ridges()) ```{r} datacubePred max(datacubePred$predDepth) ( datacube1 = datacubePred %>% filter(predDepth<350) ) max(datacube1$predDepth) ``` # Add marginal rug ggplot(iris, aes(x = Sepal.Length, y = Species)) + geom_density_ridges( jittered_points = TRUE, position = position_points_jitter(width = 0.05, height = 0), point_shape = '|', point_size = 3, point_alpha = 1, alpha = 0.7, ) ```{r} ( densityPlot = ggplot(datacube1, aes(x = predDepth, y = resName, fill = resName, height = after_stat(density))) + geom_density_ridges(aes(fill = resName),stat = "density", alpha=.75 , scale = 3) + scale_fill_manual(values = ecoPalette, name = "Ecozones") + scale_x_continuous(expand = c(0, 0)) + scale_y_discrete(expand = expansion(mult = c(0.01, .1))) + theme_ridges() + theme(legend.position = "none") + labs(x= 'Depth (cm)', y="") ) ``` jittered_points = TRUE, position = position_points_jitter(width = 0.05, height = 0), point_shape = '|', point_size = 3, point_alpha = 1, alpha = 0.7, ) ```{r} ( densityHistogram = ggplot(datacube1, aes(x = predDepth, y = resName, fill = resName, height = after_stat(density))) + geom_density_ridges(aes(fill = resName), stat = "binline", bins = 20, scale = 0.95, draw_baseline = FALSE, alpha=.75 , scale = 3, position = position_points_jitter(width = 0.05, height = 0), point_shape = '|', point_size = 3, point_alpha = 1) + scale_fill_manual(values = ecoPalette, name = "Ecozones") + scale_x_continuous(expand = c(0, 0)) + scale_y_discrete(expand = expansion(mult = c(0.01, .1))) + theme_ridges() + theme(legend.position = "none") + labs(x= 'Depth (cm)', y="") ) ``` , strip.position="right" # Plot themes ```{r} hist_theme = theme_minimal() + theme(legend.position = "none", panel.grid.major = element_blank(), axis.text.x = element_text(size = 4, color = "black", face = "plain", margin = margin(r = 0, l=0, t=0, b=0)), axis.text.y = element_text(size = 4, color = "black", face = "plain", margin = margin(r = 0, l=0, t=0, b=0)), axis.title.x = element_text(size = 5, color = "black", face = "plain", hjust = -.01), axis.title.y = element_text(size = 5, color = "black", face = "plain"), plot.margin=unit(c(0,5,2,3), "mm")) # t,r,b,l ``` theme(axis.text.y = element_text(margin = margin(r = 0))) ```{r fig.height=6, fig.width=6} histEco = ggplot(datacube1, aes(x = predDepth, fill = resName)) + geom_histogram(stat = "count") + facet_wrap(~resName, scales = "free", nrow = 4) + scale_fill_manual(values = ecoPalette) + #scale_y_continuous(expand = expand_scale(mult = c(0, 0.05))) + hist_theme + theme(strip.background = element_rect(color="white", fill="white", size=1.5, linetype="solid"), strip.text.x = element_text(size = 5), panel.spacing = unit(0,'lines')) + labs(x='Depth (cm)', y='Count') + scale_x_continuous(expand=c(0,0)) + scale_y_continuous(expand=c(0,0)) + theme(panel.spacing = unit(.5, "lines")) #geom_rug(aes(predDepth, y = NULL)) ``` ```{r eval=FALSE, include=FALSE} ggsave("../figures/HistogramPredDepthEcozone.png", plot = histEco, width = 6, height =6, units = c("in"), dpi=600, bg = "white" ) ``` # Individual Histograms ```{r} unique(sort(datacube1$resName)) ``` ```{r} ( histplot1 = datacube1 %>% filter(resName=="Arctic coastal tundra") %>% ggplot(aes(x = predDepth)) + geom_histogram(stat = "count", fill = '#a6cee3') + hist_theme + theme(strip.background = element_rect(color="white", fill="white", size=1.5, linetype="solid"), strip.text.x = element_text(size = 5), panel.spacing = unit(0,'lines')) + labs(x='', y='') + scale_x_continuous(expand=c(0,0)) + scale_y_continuous(expand=c(0,0)) #xlim(0, 90) + #ylim(0,20) ) #geom_rug(aes(predDepth, y = NULL)) ``` # Grid ### Grid map with legend Bottom ```{r fig.height=6, fig.width=6} gridEcoHistMap = ggdraw(xlim = c(0, 6), ylim = c(0, 6)) + draw_plot(histEco, x = 0, y = 0, width = 6, height = 5) + draw_image("../images/EcozoneResMap.png", scale = 0.8, x = 2, y = -0.3, width = 2, height = 2) + draw_image("../images/EcozoneLegendRight.png", scale = 1, x = 4, y = 0, width = 2, height = 2) ``` ### Save Image ```{r eval=FALSE, include=FALSE} ggsave("../figures/EcozoneHistMap.png", plot = gridEcoHistMap, dpi = 600, width = 6, height = 6, bg='white') ```
package completions import ( "fmt" "github.com/urfave/cli/v2" ) // defaultCompletions renders the default completions for a command. func defaultCompletions() cli.BashCompleteFunc { return func(c *cli.Context) { cli.DefaultCompleteWithFlags(c.Command)(c) } } // CompleteArgs provides autocompletions based on the options returned by // generateOptions. generateOptions is provided for every argument. // // generateOptions must not write to output, or reference any // resources that are initialized elsewhere. func CompleteArgs(generateOptions func() (options []string)) cli.BashCompleteFunc { return func(c *cli.Context) { CompletePositionalArgs(func(_ cli.Args) (options []string) { return generateOptions() })(c) } } // CompletePositionalArgs provides autocompletions for multiple positional // arguments based on the options returned by the corresponding options generator. // If there are more arguments than generators, no completion is provided. // // Each generator must not write to output, or reference any resources that are // initialized elsewhere. func CompletePositionalArgs(generators ...func(args cli.Args) (options []string)) cli.BashCompleteFunc { return func(c *cli.Context) { // Let default handler deal with flag completions if the latest argument // looks like the start of a flag if c.NArg() > 0 { if f := c.Args().Get(c.NArg() - 1); f == "-" || f == "--" { defaultCompletions()(c) return } } // More arguments than positional options generators, we have no more // completions to offer if len(generators) <= c.NArg() { return } // Generate the options for this posarg opts := generators[c.NArg()](c.Args()) // If there are no options, render the previous options if we can, as // user may be typing the previous argument if len(opts) == 0 && c.NArg() >= 1 { opts = generators[c.NArg()-1](c.Args()) } // Render the options for _, opt := range opts { fmt.Fprintf(c.App.Writer, "%s\n", opt) } // Also render default completions if there are no args yet if c.Args().Len() == 0 { defaultCompletions()(c) } } }
use super::*; #[component] fn ValueInput<'a>(cx: Scope, name: &'a str, ty: &'a str, var: &'a str) -> Element { view! {cx, <div class="mb-4"> <label for={name} class="block font-bold text-gray-700 mb-2"> {name} ": " </label> <input type={ty} id={name} x-model={var} class="w-full py-2 px-3 bg-gray-200 rounded-lg border border-gray-300 focus:outline-none focus:border-indigo-500" required/> </div> } } #[component] fn Home(cx: Scope) -> Element { view! {cx, <HtmlC x-data="{pass: '', email: '', api_res: 'A', login: 'Login'}"> <div class="container mx-auto px-4 py-8"> <h1 class="text-3xl font-bold text-gray-900">"Welcome to our site!"</h1> <div class="mt-4"> <h2 class="text-xl font-bold text-gray-800">"Login"</h2> <p x-transition class="font-bold text-red-500 bg-red-500 bg-opacity-20 rounded-lg border border-red-500 text-xs mt-4 p-4 text-center invisible" x-text="api_res" x-ref="api" >"A"</p> <div class="mt-4"> <ValueInput name="Email" ty="email" var="email"/> <ValueInput name="Password" ty="password" var="pass"/> <div class="flex justify-end"> <button class="px-4 py-2 enabled:opacity-100 disabled:opacity-50 enabled:hover:bg-indigo-700 disabled:hover:bg-indigo-500 font-bold text-white bg-indigo-500 rounded-lg focus:outline-none focus:shadow-outline-indigo active:bg-indigo-800" x-data="{ benable: true }" x-bind:disabled="!benable" x-on:click=" benable = false; r_text = false; fetch('/api/public/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ pass: pass, email: email }), }) .then(response => { if (response.redirected) { window.location.href = response.url; } else { r_text = true; return response.text(); } }) .then(data => { if (r_text === true) { api_res = data; $refs.api.classList.remove('invisible'); } benable = true; }) " x-text="login" > "Login" </button> </div> </div> </div> </div> </HtmlC> } } pub async fn home() -> Html<String> { Html(render(|cx| { view! {cx, <Home /> } })) }
develop a web page that contains a form with multiple input fields and it needs to be validated before submitting it, ensuring that all required fields are filled out correctly. how would you use jQuery to perform validation? what jQuery method or plugins would you utilize to validate the form inputs? HTML: <!DOCTYPE html> <html> <head> <title>Form Validation with jQuery</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <form id="myForm"> <input type="text" name="name" placeholder="Your name" required> <input type="email" name="email" placeholder="Your email address" required> <input type="password" name="password" placeholder="Your password" required> <input type="submit" value="Submit"> </form> <script> $(document).ready(function() { // Initialize the jQuery Validation Plugin $("#myForm").validate(); // Validate the form before submitting it $("#myForm").submit(function(event) { // Check that all required fields are filled out var requiredFields = ["name", "email", "password"]; for (var i = 0; i < requiredFields.length; i++) { var field = $("#" + requiredFields[i]); if (field.val() == "") { alert("Please fill out the " + field.attr("placeholder") + " field."); event.preventDefault(); return; } } }); }); </script> </body> </html>
import { ComponentMeta, ComponentStory } from '@storybook/react' import { SideBarItem } from 'src/components/elements/SideBar/SideBarItem/SideBarItem' import { theme } from 'src/config/theme' export default { title: 'elements/SideBar/SideBarItem', component: SideBarItem, argTypes: { item: { description: 'サイドバーに表示するアイテム', }, handleDrawerToggle: { description: 'mbで表示するドロワーを操作するときに使用する関数', }, }, } as ComponentMeta<typeof SideBarItem> export const Default: ComponentStory<typeof SideBarItem> = () => { const sidebarNavigations = { path: 'kir', state: 'kir', sidebarProps: { displayText: 'キール', }, } return ( <div style={{ backgroundColor: theme.palette.background.default }}> <SideBarItem item={sidebarNavigations} /> </div> ) }
package models import ( "encoding/json" "errors" "strings" ) // RenewalPreviewResponse represents a RenewalPreviewResponse struct. type RenewalPreviewResponse struct { RenewalPreview RenewalPreview `json:"renewal_preview"` AdditionalProperties map[string]any `json:"_"` } // MarshalJSON implements the json.Marshaler interface for RenewalPreviewResponse. // It customizes the JSON marshaling process for RenewalPreviewResponse objects. func (r RenewalPreviewResponse) MarshalJSON() ( []byte, error) { return json.Marshal(r.toMap()) } // toMap converts the RenewalPreviewResponse object to a map representation for JSON marshaling. func (r RenewalPreviewResponse) toMap() map[string]any { structMap := make(map[string]any) MapAdditionalProperties(structMap, r.AdditionalProperties) structMap["renewal_preview"] = r.RenewalPreview.toMap() return structMap } // UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreviewResponse. // It customizes the JSON unmarshaling process for RenewalPreviewResponse objects. func (r *RenewalPreviewResponse) UnmarshalJSON(input []byte) error { var temp renewalPreviewResponse err := json.Unmarshal(input, &temp) if err != nil { return err } err = temp.validate() if err != nil { return err } additionalProperties, err := UnmarshalAdditionalProperties(input, "renewal_preview") if err != nil { return err } r.AdditionalProperties = additionalProperties r.RenewalPreview = *temp.RenewalPreview return nil } // renewalPreviewResponse is a temporary struct used for validating the fields of RenewalPreviewResponse. type renewalPreviewResponse struct { RenewalPreview *RenewalPreview `json:"renewal_preview"` } func (r *renewalPreviewResponse) validate() error { var errs []string if r.RenewalPreview == nil { errs = append(errs, "required field `renewal_preview` is missing for type `Renewal Preview Response`") } if len(errs) == 0 { return nil } return errors.New(strings.Join(errs, "\n")) }
<!-- Rendering --> <template> <div> <h1> PageHome </h1> <h2> Add artist </h2> <input type="text" v-model="newArtist"> <button @click="addArtist()"> Add artist </button> <hr> <table border="1"> <tr> <th> ID </th> <th> NAME </th> <th> ACTION </th> </tr> <tr v-for="artist in artists" :key="artist.id"> <td> {{ artist.id }} </td> <td> {{ artist.name }} </td> <td> <button @click="deleteArtist(artist.id)"> Delete this artist </button> </td> </tr> </table> </div> </template> <!-- Logica --> <script> export default { name: 'PageHome', mounted() { // fetch call naar artists this.fetchArtists(); }, data() { return { artists: [], newArtist: "" } }, methods: { addArtist() { fetch("http://webservies.be/eurosong/Artists", { method: "POST", headers: { 'Accept': 'application/json, text/plain', 'Content-Type': 'application/json;charset=UTF-8' }, body: JSON.stringify({ name: this.newArtist }) }).then((response) => { return response.json() }).then((result) => { console.log(result); this.fetchArtists(); }) }, fetchArtists() { fetch('http://webservies.be/eurosong/Artists') .then((response) => response.json()) .then((artists) => { this.artists = artists; }); }, deleteArtist(id) { fetch("http://webservies.be/eurosong/Artists?id=" + id, { method: "DELETE", headers: { 'Accept': 'application/json, text/plain', 'Content-Type': 'application/json;charset=UTF-8' }, }).then((response) => { return response.json() }).then(() => { this.fetchArtists(); }); } } } </script>
using Entities.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging.Configuration; using Presentation; using Repositories; using Repositories.Contracts; using Repositories.EntityFramework; using Services; using Services.Contracts; using StoreApp.Infrastructure.Extensions; using StoreApp.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers() .AddApplicationPart(typeof(AssemblyReference).Assembly); builder.Services.AddControllersWithViews(); builder.Services.AddRazorPages(); builder.Services.ConfigureSession(); builder.Services.ConfigureDbContext(builder.Configuration); builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); builder.Services.ConfigureRepositoryRegistration(); builder.Services.ConfigureIdentity(); builder.Services.ConfigureServiceRegistration(); builder.Services.AddScoped<Cart>(c => SessionCart.GetCart(c)); builder.Services.AddAutoMapper(typeof(Program)); builder.Services.ConfigureRouting(); builder.Services.ConfigureApplicationCookie(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseStaticFiles(); app.UseSession(); app.UseHttpsRedirection(); app.UseRouting(); app.ConfigureLocalization(); app.UseAuthentication(); app.UseAuthorization(); app.MapAreaControllerRoute( name: "Admin", areaName: "Admin", pattern: "Admin/{controller=Dashboard}/{action=Index}/{id?}"); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.MapControllers(); app.ConfigureAndCheckMigration(); app.ConfigureDefaultAdminUser(); app.MapRazorPages(); app.Run();
import { AnimatePresence, motion } from 'framer-motion'; import React from 'react' interface AccordionItemProps { data: { id: number, question: string, answer: string }, isActive: boolean, onClick: (id:number) => void } const AccordionItem = ({data,isActive,onClick} : AccordionItemProps) => { return ( <> <AnimatePresence> <div className={`faq-item ${isActive ? 'active' : ''}`} onClick={() => onClick(data.id)}> <div className="faq-question"> {data.question} </div> { isActive && <motion.div className="faq-answer" initial={{ opacity: 0, scaleY: 0 }} animate={{ opacity: 1, scaleY: 1 }} exit={{ opacity: 0, scaleY: 0 }} transition={{ duration: .5 }} > <p className='lead-text'> {data.answer} </p> </motion.div> } </div> </AnimatePresence> </> ) } export default AccordionItem
import {Fade, Grow, Tooltip, Zoom} from "@mui/material"; import {AppConfigState} from "../../store/slices/appConfig/appConfigSlice"; import {RootState} from "../../store"; import {useSelector} from "react-redux"; interface ITooltipsFinanceoProps { placement?: "top" | "bottom" | "left" | "right" | any; title: string | any; children: any; transitions?: 'zoom' | 'fade' | 'grow'; followCursor?: boolean; arrow?: boolean; } export function TooltipFinanceo(props: ITooltipsFinanceoProps) { const appConfig: AppConfigState = useSelector((state: RootState) => state.appConfig); return ( <Tooltip arrow={props.arrow ?? false} disableHoverListener={appConfig.toolTipsEnabled} followCursor={props.followCursor ?? true} TransitionComponent={props?.transitions === 'grow' ? Grow : props?.transitions === 'fade' ? Fade : Zoom} title={props.title} placement={props.placement ?? 'top'}> { props.children } </Tooltip> ) }
package com.example.service.impl; import com.example.dto.expert.*; import com.example.entity.Expert; import com.example.entity.SubService; import com.example.entity.enumeration.ExpertStatus; import com.example.exceptions.subservice.SubServiceExistException; import com.example.exceptions.subservice.SubServiceNotFoundException; import com.example.exceptions.user.PasswordNotMatchException; import com.example.exceptions.user.UserExistException; import com.example.exceptions.user.UserInActiveException; import com.example.exceptions.user.UserNotFoundException; import com.example.repository.ExpertRepository; import com.example.service.ExpertService; import lombok.RequiredArgsConstructor; import org.springframework.data.jpa.domain.Specification; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.time.Duration; import java.time.LocalDateTime; import java.util.List; import java.util.Objects; @Service @RequiredArgsConstructor public class ExpertServiceImpl implements ExpertService { private final ExpertRepository expertRepository; private final SubServiceServiceImpl subServiceService; private final PasswordEncoder passwordEncoder; @Override public Expert findById(Long id) { return expertRepository.findById(id).orElseThrow( () -> new UserNotFoundException(String.format("no expert found with this ID: %s.", id))); } @Override public GetModifiedExpertTimeDto changePassword(Expert expert) { Expert newExpert = (Expert) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (newExpert.getStatus() != ExpertStatus.ACCEPTED) { throw new UserInActiveException("your account is not verified or inactive."); } if (!expert.getPassword().equals(expert.getRepeatPassword())) { throw new PasswordNotMatchException("the entered password does not match with its repetition."); } newExpert.setPassword(passwordEncoder.encode(expert.getPassword())); expertRepository.save(newExpert); return new GetModifiedExpertTimeDto(LocalDateTime.now(), "the password has been successfully updated."); } @Override public List<Expert> findAllNewExperts() { return expertRepository.findAllByStatus(); } @Override public GetModifiedExpertTimeDto confirmExpert(Long id) { Expert expert = expertRepository.findExpertById(id).orElseThrow( () -> new UserNotFoundException(String.format("no awaiting confirmation expert found with this ID: %s.", id))); expert.setStatus(ExpertStatus.ACCEPTED); expertRepository.save(expert); return new GetModifiedExpertTimeDto(LocalDateTime.now(), "the expert has been successfully verified."); } @Override public void addExpertToSubService(Expert expert) { Expert newExpert = findById(expert.getId()); boolean exist = newExpert.getSubServiceSet().stream() .anyMatch(t -> Objects.equals(t.getId(), expert.getSubService().getId())); if (exist) { throw new SubServiceExistException("you have already added this expert to this service."); } SubService subService = subServiceService.findById(expert.getSubService().getId()); newExpert.addSubService(subService); expertRepository.save(newExpert); } @Override public void removeExpertFromSubService(Expert expert) { Expert newExpert = findById(expert.getId()); SubService subService = newExpert.getSubServiceSet().stream() .filter(t -> Objects.equals(t.getId(), expert.getSubService().getId())) .findFirst().orElseThrow( () -> new SubServiceNotFoundException("no sub services with this ID were found for this expert") ); newExpert.removeSubService(subService); expertRepository.save(newExpert); } @Override public void saveExpertImage() throws IOException { Expert expert = (Expert) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (expert.getStatus() != ExpertStatus.ACCEPTED) { throw new UserInActiveException("your account is not verified or inactive."); } byte[] data = expert.getImageUrl(); ByteArrayInputStream bis = new ByteArrayInputStream(data); BufferedImage image = ImageIO.read(bis); ImageIO.write(image, "jpg", new File("H:\\maktab83\\final_project_phase4\\final_project_phase4\\src\\main\\java\\com\\example\\images\\" + expert.getLastname() + ".jpg")); } @Override public void calculateExpertScore(Expert expert, LocalDateTime localDateTime) { long result = Duration.between(LocalDateTime.now(), localDateTime).toHours(); Integer expertScore = expert.getScore(); long newScore = 0; if (result < 0) { newScore = expertScore - Math.abs(result); if (newScore < 0) { expert.setStatus(ExpertStatus.INACTIVE); } } expert.setScore((int) newScore); expertRepository.save(expert); } @Override public void updateExpertCredit(Long money, Expert expert) { Long credit = expert.getCredit(); credit += money; expert.setCredit(credit); expertRepository.save(expert); } @Override public void updateExpertScore(Integer score, Expert expert) { Integer point = expert.getScore(); point += score; expert.setScore(point); expertRepository.save(expert); } @Override public Expert verifyExpert(String token) { Expert expert = expertRepository.findByToken(token).orElseThrow( () -> new UserNotFoundException("no expert found with token.")); if (expert.getStatus() == ExpertStatus.AWAITING_CONFIRMATION) { throw new UserExistException(String.format("expert with this email %s is already verified by this token" , expert.getEmail())); } expert.setStatus(ExpertStatus.AWAITING_CONFIRMATION); return expertRepository.save(expert); } @Override public Expert showScore() { return (Expert) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } @Override public List<Expert> search(Specification<Expert> spec) { return expertRepository.findAll(spec); } @Override public Expert showCredit() { return (Expert) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } }
<template> <div> <h3>Formulaire</h3> <form v-on:submit.prevent="submitForm" class="mt-4"> <div class="mb-3"> <label for="frontTitle" class="form-label">Titre</label> <input type="text" v-model="form.frontTitle" class="form-control" id="frontTitle" placeholder="Titre"> </div> <div class="mb-3"> <label for="Description" class="form-label">Description</label> <textarea class="form-control" v-model="form.frontDescription" id="Description" placeholder="Description" rows="3"></textarea> </div> <div class="mb-3"> <label for="frontSourceCodeHtml" class="form-label">Code Source (HTML)</label> <textarea class="form-control" v-model="form.frontSourceCodeHtml" id="frontSourceCodeHtml" placeholder="Code Source (HTML)" rows="6"></textarea> </div> <code-highlight language="html">{{ form.frontSourceCodeHtml }}</code-highlight> <div class="mb-3"> <label for="frontSourceCodeJs" class="form-label">Code Source (JS)</label> <textarea class="form-control" v-model="form.frontSourceCodeJs" id="frontSourceCodeJs" placeholder="Code Source (JS)" rows="6"></textarea> </div> <code-highlight language="javascript">{{ form.frontSourceCodeJs }}</code-highlight> <div class="mb-3"> <div style="background-color: rgba(166,251,166,0.40); padding: 15px; border-radius: 5px" v-html="form.frontSourceCodeHtml + form.frontSourceCodeJs"></div> </div> <div class="mb-3"> <label for="edition" class="form-label">Édition</label> <input type="text" v-model="form.frontEdition" class="form-control" id="edition" placeholder="Édition"> </div> <div class="mb-3"> <button type="reset" class="btn btn-soft-primary me-2">Annuler</button> <button type="submit" class="btn btn-primary">Enregistrer</button> </div> </form> <transition name="slide-fade"> <div class="alert alert-success alert-dismissible fade show pe-5 mt-3" role="alert" v-if="status"> Enregistré 👍 <button type="button" class="close p-2" data-dismiss="alert" aria-label="Close"> <svg xmlns="http://www.w3.org/2000/svg" width="11.528" height="12" viewBox="0 0 11.528 12"> <path d="M.788.1l.055.05,4.92,5.122L10.684.151a.48.48,0,0,1,.7,0,.53.53,0,0,1,.048.67l-.048.058L6.463,6l4.92,5.122a.529.529,0,0,1,0,.727.48.48,0,0,1-.643.05l-.055-.05L5.764,6.728.843,11.849a.48.48,0,0,1-.7,0A.53.53,0,0,1,.1,11.18l.048-.058L5.065,6,.145.878a.529.529,0,0,1,0-.727A.48.48,0,0,1,.721.057Z" fill="#fff"/> </svg> </button> </div> </transition> </div> </template> <script> import CodeHighlight from "vue-code-highlight/src/CodeHighlight.vue"; import "vue-code-highlight/themes/duotone-sea.css"; import "vue-code-highlight/themes/window.css"; export default { name: "ComposantFrontal", props: { documentation: null, }, components: { CodeHighlight, }, data() { return { form: { frontTitle: this.documentation.frontTitle, frontDescription: this.documentation.frontDescription, frontSourceCodeHtml: this.documentation.frontSourceCodeHtml, frontSourceCodeJs: this.documentation.frontSourceCodeJs, frontEdition: this.documentation.frontEdition, }, status: false, } }, methods: { submitForm() { axios.post(`/api/submit/documentation/${this.documentation.id}`, this.form) .then((response) => { if (response.status === 200) { this.status = response.data.status; setTimeout(() => { this.status = false; }, 1500) } }) } } } </script> <style scoped> .form-control { font-size: 16px; } .slide-fade-enter-active { transition: all .3s ease; } .slide-fade-leave-active { transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0); } .slide-fade-enter, .slide-fade-leave-to /* .slide-fade-leave-active below version 2.1.8 */ { transform: translateX(10px); opacity: 0; } </style>
package com.online_reservation.Flight_Booking.Service; import com.online_reservation.Flight_Booking.DTO.PassengerDTO; import com.online_reservation.Flight_Booking.DTO.FlightDataDTO; import com.online_reservation.Flight_Booking.DTO.NewBookingDTO; import com.online_reservation.Flight_Booking.DTO.NewBookingDTOfromFE; import com.online_reservation.Flight_Booking.DTO.UserDTO; import com.online_reservation.Flight_Booking.Mapper.NewBookingMapper; import com.online_reservation.Flight_Booking.Repository.NewBookingRepository; import com.online_reservation.Flight_Booking.entity.NewBooking; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Service public class BookingService { @Autowired SequenceGenerator sequenceGenerator; @Autowired NewBookingRepository newBookingRepo; @Autowired RestTemplate restTemplate; public NewBookingDTO saveOrderInDB(NewBookingDTOfromFE BookingDetails) { Integer newOrderID = sequenceGenerator.generateNextOrderId(); UserDTO userDTO =fetchUserDetailsFromUserId(BookingDetails.getUserid()); FlightDataDTO FlightdataDTO=fetchFlightDetailsFromId(BookingDetails.getId()); NewBooking NewBookingToBeSaved = new NewBooking(newOrderID, BookingDetails.getPassengerList(), FlightdataDTO, userDTO ); newBookingRepo.save(NewBookingToBeSaved); return NewBookingMapper.INSTANCE.mapNewBookingToNewBookingDTO(NewBookingToBeSaved); } private UserDTO fetchUserDetailsFromUserId(Integer userid) { return restTemplate.getForObject("http://USER-SERVICE-NEW/user/fetchUserById/" + userid, UserDTO.class); } private FlightDataDTO fetchFlightDetailsFromId(Integer id) { return restTemplate.getForObject("http://Flight-Search/Search/fetchById/" + id, FlightDataDTO.class); } public List<NewBookingDTO> findByFlightId(Long id) { List<NewBooking> FlightDatabyId =newBookingRepo.findByflightdata(id); List<NewBookingDTO> FlightDatabyIdDTO = FlightDatabyId.stream().map(NewBookingMapper.INSTANCE::mapNewBookingToNewBookingDTO).collect(Collectors.toList()); return FlightDatabyIdDTO; } }
import "reflect-metadata"; import { __prod__, COOKIE_NAME } from "./constants"; import express from "express"; import { ApolloServer } from "apollo-server-express"; import { buildSchema } from "type-graphql"; import { HelloResolver } from "./resolvers/hello"; import { PostResolver } from "./resolvers/post"; import { UserResolver } from "./resolvers/user"; import Redis from "ioredis"; import session from "express-session"; import connectRedis from "connect-redis"; import cors from "cors"; import { createConnection } from "typeorm"; import { Post } from "./entities/Post"; import { User } from "./entities/User"; import dotenv from "dotenv"; import { Upvote } from "./entities/Upvote"; dotenv.config(); const main = async () => { const conn = await createConnection({ type: "postgres", database: "saffronnit", username: "postgres", password: process.env.PG_PASS, logging: false, synchronize: true, entities: [Post, User, Upvote], }); conn.runMigrations(); const app = express(); const RedisStore = connectRedis(session); const redis = new Redis(); app.use( cors({ origin: "http://localhost:3000", credentials: true, }) ); app.use( session({ name: COOKIE_NAME, store: new RedisStore({ client: redis, disableTouch: true, }), cookie: { maxAge: 1000 * 60 * 60 * 24 * 365 * 10, // 10 years httpOnly: true, sameSite: "lax", // csrf secure: __prod__, // cookie only works in https }, saveUninitialized: false, secret: "qowiueojwojfalksdjoqiwueo", resave: false, }) ); // app.use(cookieParser()); const apolloServer = new ApolloServer({ schema: await buildSchema({ resolvers: [HelloResolver, PostResolver, UserResolver], validate: false, }), context: async ({ req, res }) => { console.log("logged in index file", req.session); return { req, res, redis }; }, }); apolloServer.applyMiddleware({ app, cors: false, }); app.listen(4000, () => { console.log("server started on localhost:4000"); }); }; main().catch((err) => { console.error(err); });
import { Schema, model, Document } from "mongoose"; import { Chat } from "./chat"; import uniqueValidator from "mongoose-unique-validator"; import { UserType } from "./user"; export interface Message extends Document { _id?: string; sender: string | UserType; body: string; chat: string | Chat; } const messageSchema = new Schema( { sender: { type: String, ref: "User", }, body: { type: String, }, chat: { type: String, ref: "Chat", trim: true, }, }, { timestamps: true, toJSON: { virtuals: true }, toObject: { virtuals: true }, } ); messageSchema.plugin(uniqueValidator, { message: "{PATH} {VALUE} is already in use", }); messageSchema.index({ "$**": "text" }); const Message = model<Message>("Message", messageSchema); export default Message;
#include "shell.h" /** **_strncpy - copies a string *@dest: the destination *@src: the source *@n: number of characters *Return: the concatenated string */ char *_strncpy(char *dest, char *src, int n) { int a, b; char *st = dest; a = 0; while (src[a] != '\0' && a < n - 1) { dest[a] = src[a]; a++; } if (a < n) { b = a; while (b < n) { dest[b] = '\0'; b++; } } return (st); } /** **_strncat - concatenates two strings *@dest: 1st string *@src: 2nd string *@n: the amount of bytes to be maximally used *Return: the result string */ char *_strncat(char *dest, char *src, int n) { int a, b; char *st = dest; a = 0; b = 0; while (dest[a] != '\0') a++; while (src[b] != '\0' && b < n) { dest[a] = src[b]; a++; b++; } if (b < n) dest[a] = '\0'; return (st); } /** **_strchr - char locatio in string input *@s: the string to check *@c: the character to search for *Return: pointer to the memory location */ char *_strchr(char *s, char c) { do { if (*s == c) return (s); } while (*s++ != '\0'); return (NULL); }
/* Module imports */ import { async, getTestBed, TestBed } from '@angular/core/testing'; import { BehaviorSubject, of, Subject, throwError } from 'rxjs'; /* Test configuration imports */ import { configureTestBed } from '@test/configure-test-bed'; /* Mock imports */ import { mockAuthor, mockGrainBill, mockHopsSchedule, mockOtherIngredients, mockProcessSchedule, mockRecipeMasterActive, mockRecipeMasterInactive, mockRecipeVariantComplete, mockRecipeVariantIncomplete, mockUser, mockYeastBatch } from '@test/mock-models'; import { ErrorReportingServiceStub, EventServiceStub, IdServiceStub, RecipeHttpServiceStub, RecipeImageServiceStub, RecipeStateServiceStub, RecipeTypeGuardServiceStub, UserServiceStub } from '@test/service-stubs'; /* Interface imports */ import { Author, GrainBill, HopsSchedule, Image, OtherIngredients, Process, RecipeMaster, RecipeVariant, User, YeastBatch, } from '@shared/interfaces'; /* Default imports */ import { defaultImage } from '@shared/defaults'; /* Service imports */ import { ErrorReportingService, EventService, IdService, UserService } from '@services/public'; import { RecipeHttpService } from '@services/recipe/http/recipe-http.service'; import { RecipeImageService } from '@services/recipe/image/recipe-image.service'; import { RecipeStateService } from '@services/recipe/state/recipe-state.service'; import { RecipeTypeGuardService } from '@services/recipe/type-guard/recipe-type-guard.service'; import { RecipeService } from './recipe.service'; describe('RecipeService', (): void => { configureTestBed(); let injector: TestBed; let service: RecipeService; let originalRegister: () => void; beforeAll(async((): void => { TestBed.configureTestingModule({ providers: [ RecipeService, { provide: ErrorReportingService, useClass: ErrorReportingServiceStub }, { provide: EventService, useClass: EventServiceStub }, { provide: IdService, useClass: IdServiceStub }, { provide: RecipeHttpService, useClass: RecipeHttpServiceStub }, { provide: RecipeImageService, useClass: RecipeImageServiceStub }, { provide: RecipeStateService, useClass: RecipeStateServiceStub }, { provide: RecipeTypeGuardService, useClass: RecipeTypeGuardServiceStub }, { provide: UserService, useClass: UserServiceStub } ] }); })); beforeEach((): void => { injector = getTestBed(); service = injector.get(RecipeService); originalRegister = service.registerEvents; service.registerEvents = jest.fn(); }); test('should create the service', (): void => { expect(service).toBeTruthy(); }); describe('Public API', (): void => { test('should fetch public author by id', (done: jest.DoneCallback): void => { const _mockAuthor: Author = mockAuthor(); const _mockUser: User = mockUser(); const _mockUser$: BehaviorSubject<User> = new BehaviorSubject<User>(_mockUser); const _mockRecipeMasterActive: RecipeMaster = mockRecipeMasterActive(); service.recipeStateService.getRecipeById = jest.fn().mockReturnValue(_mockRecipeMasterActive); service.userService.getUser = jest.fn().mockReturnValue(_mockUser$); service.idService.hasId = jest.fn().mockReturnValue(false); service.idService.hasDefaultIdType = jest.fn().mockReturnValue(true); service.recipeHttpService.fetchPublicAuthorByRecipeId = jest.fn().mockReturnValue(of(_mockAuthor)); service.getPublicAuthorByRecipeId('0123456789012') .subscribe( (author: Author): void => { expect(author).toStrictEqual(_mockAuthor); done(); }, (error: any): void => { console.log('Error in: should fetch public author by id', error); expect(true).toBe(false); } ); }); test('should get default author when fetching public author by id returns no result', (done: jest.DoneCallback): void => { const _mockUser: User = mockUser(); const _mockUser$: BehaviorSubject<User> = new BehaviorSubject<User>(_mockUser); const _mockRecipeMasterActive: RecipeMaster = mockRecipeMasterActive(); service.recipeStateService.getRecipeById = jest.fn().mockReturnValue(_mockRecipeMasterActive); service.userService.getUser = jest.fn().mockReturnValue(_mockUser$); service.idService.hasId = jest.fn().mockReturnValue(false); service.idService.hasDefaultIdType = jest.fn().mockReturnValue(true); service.recipeHttpService.fetchPublicAuthorByRecipeId = jest.fn().mockReturnValue(of(null)); const _defaultImage: Image = defaultImage(); service.getPublicAuthorByRecipeId('0123456789012') .subscribe( (author: Author): void => { expect(author).toStrictEqual({ username: 'Not Found', userImage: _defaultImage, breweryLabelImage: _defaultImage }); done(); }, (error: any): void => { console.log('Error in: should fetch public author by id', error); expect(true).toBe(false); } ); }); test('should get default author when missing valid server id', (done: jest.DoneCallback): void => { const _mockUser: User = mockUser(); const _mockUser$: BehaviorSubject<User> = new BehaviorSubject<User>(_mockUser); const _mockRecipeMasterActive: RecipeMaster = mockRecipeMasterActive(); _mockRecipeMasterActive._id = undefined; service.recipeStateService.getRecipeById = jest.fn().mockReturnValue(_mockRecipeMasterActive); service.userService.getUser = jest.fn().mockReturnValue(_mockUser$); service.idService.hasId = jest.fn().mockReturnValue(false); service.idService.hasDefaultIdType = jest.fn().mockReturnValue(true); const _defaultImage: Image = defaultImage(); service.getPublicAuthorByRecipeId('0123456789012') .subscribe( (author: Author): void => { expect(author).toStrictEqual({ username: 'Not Found', userImage: _defaultImage, breweryLabelImage: _defaultImage }); done(); }, (error: any): void => { console.log('Error in: should fetch public author by id', error); expect(true).toBe(false); } ); }); test('should get user as author is the user owns the recipe', (done: jest.DoneCallback): void => { const _mockUser: User = mockUser(); const _mockUser$: BehaviorSubject<User> = new BehaviorSubject<User>(_mockUser); const _mockRecipeMasterActive: RecipeMaster = mockRecipeMasterActive(); _mockRecipeMasterActive._id = undefined; service.recipeStateService.getRecipeById = jest.fn().mockReturnValue(_mockRecipeMasterActive); service.userService.getUser = jest.fn().mockReturnValue(_mockUser$); service.idService.hasId = jest.fn().mockReturnValue(true); service.getPublicAuthorByRecipeId('0123456789012') .subscribe( (author: Author): void => { expect(author).toStrictEqual({ username: _mockUser.username, userImage: _mockUser.userImage, breweryLabelImage: _mockUser.breweryLabelImage }); done(); }, (error: any): void => { console.log('Error in: should get user as author is the user owns the recipe', error); expect(true).toBe(false); } ); }); test('should get default author when recipe not found', (done: jest.DoneCallback): void => { service.recipeStateService.getRecipeById = jest.fn().mockReturnValue(undefined); const _defaultImage: Image = defaultImage(); service.getPublicAuthorByRecipeId('0123456789012') .subscribe( (author: Author): void => { expect(author).toStrictEqual({ username: 'Not Found', userImage: _defaultImage, breweryLabelImage: _defaultImage }); done(); }, (error: any): void => { console.log('Error in: should get default author when recipe not found', error); expect(true).toBe(false); } ); }); test('should fetch public recipe', (done: jest.DoneCallback): void => { const _mockRecipeMasterActive: RecipeMaster = mockRecipeMasterActive(); service.recipeHttpService.fetchPublicRecipeById = jest.fn() .mockReturnValue(of(_mockRecipeMasterActive)); const fetchSpy: jest.SpyInstance = jest.spyOn(service.recipeHttpService, 'fetchPublicRecipeById'); service.getPublicRecipe('test-id') .subscribe( (recipe: RecipeMaster): void => { expect(recipe).toStrictEqual(_mockRecipeMasterActive); expect(fetchSpy).toHaveBeenCalledWith('test-id'); done(); }, (error: Error): void => { console.log('Error in: should fetch public recipe', error); expect(true).toBe(false); } ); }); test('should fetch public recipe list', (done: jest.DoneCallback): void => { const _mockRecipeMasterActive: RecipeMaster = mockRecipeMasterActive(); const _mockRecipeMasterInactive: RecipeMaster = mockRecipeMasterInactive(); service.recipeHttpService.fetchPublicRecipeListByUser = jest.fn() .mockReturnValue(of([ _mockRecipeMasterActive, _mockRecipeMasterInactive ])); const fetchSpy: jest.SpyInstance = jest.spyOn(service.recipeHttpService, 'fetchPublicRecipeListByUser'); service.getPublicRecipeListByUser('test-id') .subscribe( (recipes: RecipeMaster[]): void => { expect(recipes.length).toEqual(2); expect(recipes[0]).toStrictEqual(_mockRecipeMasterActive); expect(recipes[1]).toStrictEqual(_mockRecipeMasterInactive); expect(fetchSpy).toHaveBeenCalledWith('test-id'); done(); }, (error: Error): void => { console.log('Error in: should fetch public recipe list', error); expect(true).toBe(false); } ); }); test('should fetch public recipe variant', (done: jest.DoneCallback): void => { const _mockRecipeVariantComplete: RecipeVariant = mockRecipeVariantComplete(); service.recipeHttpService.fetchPublicVariantById = jest.fn() .mockReturnValue(of(_mockRecipeVariantComplete)); const fetchSpy: jest.SpyInstance = jest.spyOn(service.recipeHttpService, 'fetchPublicVariantById'); service.getPublicRecipeVariantById('recipe-id', 'variant-id') .subscribe( (variant: RecipeVariant): void => { expect(variant).toStrictEqual(_mockRecipeVariantComplete); expect(fetchSpy).toHaveBeenCalledWith('recipe-id', 'variant-id'); done(); }, (error: Error): void => { console.log('Error in: should fetch public recipe variant', error); expect(true).toBe(false); } ); }); }); describe('Private API', (): void => { test('should add a variant to recipe in list', (done: jest.DoneCallback): void => { service.recipeStateService.addVariantToRecipeInList = jest.fn().mockReturnValue(of(null)); const addSpy: jest.SpyInstance = jest.spyOn(service.recipeStateService, 'addVariantToRecipeInList'); const _mockRecipeVariantComplete: RecipeVariant = mockRecipeVariantComplete(); service.addVariantToRecipeInList('recipe-id', _mockRecipeVariantComplete) .subscribe( (expectedNull: null): void => { expect(expectedNull).toBeNull(); expect(addSpy).toHaveBeenCalledWith('recipe-id', _mockRecipeVariantComplete); done(); }, (error: Error): void => { console.log('Error in: should add a variant to recipe in list', error); expect(true).toBe(false); } ); }); test('should create new recipe', (done: jest.DoneCallback): void => { service.recipeStateService.createNewRecipe = jest.fn().mockReturnValue(of(null)); const addSpy: jest.SpyInstance = jest.spyOn(service.recipeStateService, 'createNewRecipe'); const _mockRecipeMasterActive: RecipeMaster = mockRecipeMasterActive(); service.createNewRecipe( _mockRecipeMasterActive) .subscribe( (expectedNull: null): void => { expect(expectedNull).toBeNull(); expect(addSpy).toHaveBeenCalledWith(_mockRecipeMasterActive); done(); }, (error: Error): void => { console.log('Error in: should create new recipe', error); expect(true).toBe(false); } ); }); test('should remove recipe from list', (done: jest.DoneCallback): void => { service.recipeStateService.removeRecipeFromList = jest.fn().mockReturnValue(of(null)); const addSpy: jest.SpyInstance = jest.spyOn(service.recipeStateService, 'removeRecipeFromList'); service.removeRecipeFromList('test-id') .subscribe( (expectedNull: null): void => { expect(expectedNull).toBeNull(); expect(addSpy).toHaveBeenCalledWith('test-id'); done(); }, (error: Error): void => { console.log('Error in: should remove recipe from list', error); expect(true).toBe(false); } ); }); test('should remove variant from recipe', (done: jest.DoneCallback): void => { service.recipeStateService.removeVariantFromRecipeInList = jest.fn().mockReturnValue(of(null)); const addSpy: jest.SpyInstance = jest.spyOn(service.recipeStateService, 'removeVariantFromRecipeInList'); service.removeVariantFromRecipeInList('recipe-id', 'variant-id') .subscribe( (expectedNull: null): void => { expect(expectedNull).toBeNull(); expect(addSpy).toHaveBeenCalledWith('recipe-id', 'variant-id'); done(); }, (error: Error): void => { console.log('Error in: should remove variant from recipe', error); expect(true).toBe(false); } ); }); test('should update recipe in list', (done: jest.DoneCallback): void => { service.recipeStateService.updateRecipeInList = jest.fn().mockReturnValue(of(null)); const addSpy: jest.SpyInstance = jest.spyOn(service.recipeStateService, 'updateRecipeInList'); service.updateRecipeInList('recipe-id', { update: true }) .subscribe( (expectedNull: null): void => { expect(expectedNull).toBeNull(); expect(addSpy).toHaveBeenCalledWith('recipe-id', { update: true }); done(); }, (error: Error): void => { console.log('Error in: should update recipe in list', error); expect(true).toBe(false); } ); }); test('should update variant in recipe', (done: jest.DoneCallback): void => { service.recipeStateService.updateVariantOfRecipeInList = jest.fn().mockReturnValue(of(null)); const addSpy: jest.SpyInstance = jest.spyOn(service.recipeStateService, 'updateVariantOfRecipeInList'); service.updateVariantOfRecipeInList('recipe-id', 'variant-id', { update: true }) .subscribe( (expectedNull: null): void => { expect(expectedNull).toBeNull(); expect(addSpy).toHaveBeenCalledWith('recipe-id', 'variant-id', { update: true }); done(); }, (error: Error): void => { console.log('Error in: should update variant in recipe', error); expect(true).toBe(false); } ); }); }); describe('Public Helper Methods', (): void => { test('should get combined hops schedule', (): void => { const _mockHopsSchedule: HopsSchedule[] = mockHopsSchedule(); expect(_mockHopsSchedule.length).toEqual(4); expect(_mockHopsSchedule[0].quantity).toEqual(1); const combined: HopsSchedule[] = service.getCombinedHopsSchedule(_mockHopsSchedule); expect(combined.length).toEqual(3); expect(_mockHopsSchedule[0].quantity).toEqual(2); }); test('should get undefined if combining a hops schedule that is undefined', (): void => { expect(service.getCombinedHopsSchedule(undefined)).toBeUndefined(); }); test('should get recipe list', (): void => { const _mockRecipeMasterActive: RecipeMaster = mockRecipeMasterActive(); const _mockRecipeMasterInactive: RecipeMaster = mockRecipeMasterInactive(); const _mockRecipeList$: BehaviorSubject<BehaviorSubject<RecipeMaster>[]> = new BehaviorSubject<BehaviorSubject<RecipeMaster>[]>([ new BehaviorSubject<RecipeMaster>(_mockRecipeMasterActive), new BehaviorSubject<RecipeMaster>(_mockRecipeMasterInactive) ]); service.recipeStateService.getRecipeList = jest.fn().mockReturnValue(_mockRecipeList$); const getSpy: jest.SpyInstance = jest.spyOn(service.recipeStateService, 'getRecipeList'); const list$: BehaviorSubject<BehaviorSubject<RecipeMaster>[]> = service.getRecipeList(); expect(list$).toStrictEqual(list$); expect(getSpy).toHaveBeenCalled(); }); test('should get recipe subject', (): void => { const _mockRecipeMasterActive: RecipeMaster = mockRecipeMasterActive(); const _mockRecipeMasterActive$: BehaviorSubject<RecipeMaster> = new BehaviorSubject<RecipeMaster>(_mockRecipeMasterActive); service.recipeStateService.getRecipeSubjectById = jest.fn() .mockReturnValue(_mockRecipeMasterActive$); const getSpy: jest.SpyInstance = jest.spyOn(service.recipeStateService, 'getRecipeSubjectById'); const recipe: BehaviorSubject<RecipeMaster> = service.getRecipeSubjectById('test-id'); expect(recipe).toStrictEqual(_mockRecipeMasterActive$); expect(getSpy).toHaveBeenCalledWith('test-id'); }); test('should check if a recipe has a process', (): void => { const _mockRecipeVariantComplete: RecipeVariant = mockRecipeVariantComplete(); const _mockRecipeVariantIncomplete: RecipeVariant = mockRecipeVariantIncomplete(); expect(service.isRecipeProcessPresent(_mockRecipeVariantComplete)).toBe(true); expect(service.isRecipeProcessPresent(_mockRecipeVariantIncomplete)).toBe(false); }); test('should check if array of grain bills are type safe', (): void => { const _mockGrainBill: GrainBill[] = mockGrainBill(); let failFlag: boolean = false; service.recipeTypeGuardService.isSafeGrainBillCollection = jest.fn() .mockImplementation((): boolean => !failFlag); expect(service.isSafeGrainBillCollection(_mockGrainBill)).toBe(true); failFlag = true; expect(service.isSafeGrainBillCollection(_mockGrainBill)).toBe(false); }); test('should check if array of hops schedules are type safe', (): void => { const _mockHopsSchedule: HopsSchedule[] = mockHopsSchedule(); let failFlag: boolean = false; service.recipeTypeGuardService.isSafeHopsScheduleCollection = jest.fn() .mockImplementation((): boolean => !failFlag); expect(service.isSafeHopsScheduleCollection(_mockHopsSchedule)).toBe(true); failFlag = true; expect(service.isSafeHopsScheduleCollection(_mockHopsSchedule)).toBe(false); }); test('should check if array of other ingredients are type safe', (): void => { const _mockOtherIngredients: OtherIngredients[] = mockOtherIngredients(); let failFlag: boolean = false; service.recipeTypeGuardService.isSafeOtherIngredientsCollection = jest.fn() .mockImplementation((): boolean => !failFlag); expect(service.isSafeOtherIngredientsCollection(_mockOtherIngredients)).toBe(true); failFlag = true; expect(service.isSafeOtherIngredientsCollection(_mockOtherIngredients)).toBe(false); }); test('should check if process schedule items are type safe', (): void => { const _mockProcessSchedule: Process[] = mockProcessSchedule(); let failFlag: boolean = false; service.recipeTypeGuardService.isSafeProcessSchedule = jest.fn() .mockImplementation((): boolean => !failFlag); expect(service.isSafeProcessSchedule(_mockProcessSchedule)).toBe(true); failFlag = true; expect(service.isSafeProcessSchedule(_mockProcessSchedule)).toBe(false); }); test('should check if array of yeast batches are type safe', (): void => { const _mockYeastBatch: YeastBatch[] = mockYeastBatch(); let failFlag: boolean = false; service.recipeTypeGuardService.isSafeYeastBatchCollection = jest.fn() .mockImplementation((): boolean => !failFlag); expect(service.isSafeYeastBatchCollection(_mockYeastBatch)).toBe(true); failFlag = true; expect(service.isSafeYeastBatchCollection(_mockYeastBatch)).toBe(false); }); test('should register events', (done: jest.DoneCallback): void => { service.registerEvents = originalRegister; const mockSubjects: Subject<object>[] = Array.from(Array(4), (): Subject<object> => { return new Subject<object>(); }); let counter = 0; service.event.register = jest.fn().mockImplementation((): any => mockSubjects[counter++]); service.recipeStateService.initRecipeList = jest.fn().mockReturnValue(of(null)); service.recipeStateService.clearRecipes = jest.fn(); service.recipeStateService.syncOnSignup = jest.fn(); service.recipeStateService.syncOnConnection = jest.fn().mockReturnValue(of(null)); const spies: jest.SpyInstance[] = [ jest.spyOn(service.recipeStateService, 'initRecipeList'), jest.spyOn(service.recipeStateService, 'clearRecipes'), jest.spyOn(service.recipeStateService, 'syncOnSignup'), jest.spyOn(service.recipeStateService, 'syncOnConnection') ]; const eventSpy: jest.SpyInstance = jest.spyOn(service.event, 'register'); service.event.emit = jest.fn(); const emitSpy: jest.SpyInstance = jest.spyOn(service.event, 'emit'); service.registerEvents(); setTimeout((): void => { const calls: any[] = eventSpy.mock.calls; expect(calls[0][0]).toMatch('init-recipes'); expect(calls[1][0]).toMatch('clear-data'); expect(calls[2][0]).toMatch('sync-recipes-on-signup'); expect(calls[3][0]).toMatch('connected'); mockSubjects.forEach((mockSubject: Subject<object>, index: number): void => { mockSubject.next({}); expect(spies[index]).toHaveBeenCalled(); mockSubject.complete(); }); expect(emitSpy).toHaveBeenCalledWith('init-batches'); done(); }, 10); }); test('should catch error on init recipes event error', (done: jest.DoneCallback): void => { service.registerEvents = originalRegister; const mockSubjects: Subject<object>[] = Array.from(Array(4), (): Subject<object> => { return new Subject<object>(); }); let counter = 0; service.event.register = jest.fn().mockImplementation((): any => mockSubjects[counter++]); const _mockError: Error = new Error('test-error'); service.errorReporter.handleUnhandledError = jest.fn(); const errorSpy: jest.SpyInstance = jest.spyOn(service.errorReporter, 'handleUnhandledError'); service.recipeStateService.initRecipeList = jest.fn().mockReturnValue(throwError(_mockError)); service.event.emit = jest.fn(); const emitSpy: jest.SpyInstance = jest.spyOn(service.event, 'emit'); service.registerEvents(); setTimeout((): void => { mockSubjects[0].next({}); expect(errorSpy).toHaveBeenCalledWith(_mockError); expect(emitSpy).toHaveBeenCalledWith('init-batches'); done(); }, 10); }); test('should catch error on sync on connection event error', (done: jest.DoneCallback): void => { service.registerEvents = originalRegister; const mockSubjects: Subject<object>[] = Array.from(Array(4), (): Subject<object> => { return new Subject<object>(); }); let counter = 0; service.event.register = jest.fn().mockImplementation((): any => mockSubjects[counter++]); const _mockError: Error = new Error('test-error'); service.errorReporter.handleUnhandledError = jest.fn(); const errorSpy: jest.SpyInstance = jest.spyOn(service.errorReporter, 'handleUnhandledError'); service.recipeStateService.syncOnConnection = jest.fn().mockReturnValue(throwError(_mockError)); service.registerEvents(); setTimeout((): void => { mockSubjects[3].next({}); expect(errorSpy).toHaveBeenCalledWith(_mockError); done(); }, 10); }); }); });
<?php namespace frontend\controllers; use common\models\DocumentEmis; use common\models\DocumentEmisSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; /** * DocumentEmisController implements the CRUD actions for DocumentEmis model. */ class DocumentEmisController extends Controller { /** * @inheritDoc */ public function behaviors() { return array_merge( parent::behaviors(), [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], ] ); } /** * Lists all DocumentEmis models. * @return mixed */ public function actionIndex() { $searchModel = new DocumentEmisSearch(); $dataProvider = $searchModel->search($this->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single DocumentEmis model. * @param int $id ID * @return mixed * @throws NotFoundHttpException if the model cannot be found */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new DocumentEmis model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new DocumentEmis(); if ($this->request->isPost) { if ($model->load($this->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } } else { $model->loadDefaultValues(); } return $this->render('create', [ 'model' => $model, ]); } /** * Updates an existing DocumentEmis model. * If update is successful, the browser will be redirected to the 'view' page. * @param int $id ID * @return mixed * @throws NotFoundHttpException if the model cannot be found */ public function actionUpdate($id) { $model = $this->findModel($id); if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } return $this->render('update', [ 'model' => $model, ]); } /** * Deletes an existing DocumentEmis model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param int $id ID * @return mixed * @throws NotFoundHttpException if the model cannot be found */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the DocumentEmis model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param int $id ID * @return DocumentEmis the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = DocumentEmis::findOne($id)) !== null) { return $model; } throw new NotFoundHttpException('The requested page does not exist.'); } }
from dependency_injector.wiring import ( Provide, inject, ) from fastapi import ( APIRouter, Depends, HTTPException, status, ) from returns.result import ( Success, Failure, ) from app.containers.api.services import ServiceContainer from app.auth.utils.token_payload import CurrentToken from app.categories.schemas import ( CategoryCreateRequest, CategoryCreateResponse, CategoryListResponse, ) from app.categories.service import CategoryService name_prefix = 'category' router = APIRouter( prefix=f'/{name_prefix}', tags=[name_prefix], ) @router.post( '/categories/', name=f'{name_prefix}:creating_categories', status_code=status.HTTP_201_CREATED, ) @inject async def create( request_data: CategoryCreateRequest, service: CategoryService = Depends(Provide[ServiceContainer.category_service]), token_payload=Depends(CurrentToken()), ) -> CategoryCreateResponse: match await service.create_instance(data=request_data): case Success(category): return category case Failure(CATEGORY_ALREADY_EXISTS): raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=CATEGORY_ALREADY_EXISTS) case _: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST) @router.get( '/categories/', name=f'{name_prefix}:getting_categories', status_code=status.HTTP_200_OK, ) @inject async def get( service: CategoryService = Depends(Provide[ServiceContainer.category_service]), ) -> CategoryListResponse: match await service.get_list(): case Success(categories): return CategoryListResponse(categories=categories) case _: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
"use strict"; const { Model } = require("sequelize"); module.exports = (sequelize, DataTypes) => { class Order extends Model { /** * Helper method for defining associations. * This method is not a part of Sequelize lifecycle. * The `models/index` file will call this method automatically. */ static associate(models) { // define association here Order.belongsTo(models.Product); Order.belongsTo(models.Customer); } } Order.init( { ProductId: DataTypes.INTEGER, CustomerId: DataTypes.INTEGER, status: DataTypes.STRING, senderName: DataTypes.STRING, address: DataTypes.STRING, quantity: DataTypes.INTEGER }, { hooks: { beforeCreate(order, option) { order.status = "Unpaid"; } }, sequelize, modelName: "Order" } ); return Order; };
using MediatR; using Poc.BucketS3.Domain.Commands; using Poc.BucketS3.Domain.Interfaces; namespace Poc.BucketS3.Domain.Handlers; /// <summary> /// Handler for creating a new S3 bucket. /// </summary> /// <remarks> /// Initializes a new instance of the <see cref="CreateBucketHandler" /> class. /// </remarks> /// <param name="storage">The storage service for interacting with S3.</param> /// <exception cref="ArgumentNullException">Thrown if the storage service is null.</exception> public class CreateBucketHandler(IStorage storage) : IRequestHandler<CreateBucketCommand> { private readonly IStorage _storage = storage ?? throw new ArgumentNullException(nameof(storage)); /// <summary> /// Handles the command to create a new S3 bucket. /// </summary> /// <param name="request">The command request containing the bucket name.</param> /// <param name="cancellationToken">Cancellation token for the asynchronous task.</param> /// <returns>A task that represents the asynchronous operation.</returns> public async Task Handle(CreateBucketCommand request, CancellationToken cancellationToken) { await _storage.CreateBucketAsync(request.BucketName!, cancellationToken); } }
import React, { useState } from 'react' import "./sidebar.css"; import MainContent from '../mainContaint/MainContent'; import Navbar from '../navBar/Navbar'; import { BsNut } from 'react-icons/bs'; import { PiKey } from "react-icons/pi"; import { BiCube } from "react-icons/bi"; import { FaRegUserCircle } from 'react-icons/fa' import { FaWallet } from "react-icons/fa"; import { TbDiscount2 } from "react-icons/tb"; import { BiHelpCircle } from "react-icons/bi"; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import Footer from '../footer/Footer'; import profile from '../logo/profile.jpg' import { IoIosArrowDown } from 'react-icons/io' const SideBar = (props) => { const [activeState, setactiveState] = useState('dashboard') const activeChange = (e) => { setactiveState(e) } console.log('==========', activeState); return ( <> <div className="sidebar"> <div> <div className="d-flex text-light p-4"><h4 className='h5'><BsNut />&nbsp;&nbsp;Dashboard</h4></div> <a className={activeState === 'dashboard' && 'active'} onClick={() => activeChange('dashboard')} href="#home"><PiKey />&nbsp;&nbsp;Dashboard</a> <a href="#news" className={activeState === 'product' && 'active'} onClick={() => activeChange('product')}><BiCube />&nbsp; &nbsp;Product<ChevronRightIcon className='iconClass' /></a> <a href="#contact" className={activeState === 'customers' && 'active'} onClick={() => activeChange('customers')}><FaRegUserCircle />&nbsp; &nbsp;Customers<ChevronRightIcon className='iconClass1' /></a> <a href="#about" className={activeState === 'income' && 'active'} onClick={() => activeChange('income')}><FaWallet />&nbsp; &nbsp;Income<ChevronRightIcon className='iconClass2' /></a> <a href="#about" className={activeState === 'promote' && 'active'} onClick={() => activeChange('promote')}><TbDiscount2 />&nbsp; &nbsp;Promote<ChevronRightIcon className='iconClass3' /></a> <a href="#about" className={activeState === 'help' && 'active'} onClick={() => activeChange('help')}><BiHelpCircle />&nbsp; &nbsp;Help<ChevronRightIcon className='iconClass4' /></a> </div> <div> <div className="d-flex justify-content-arround web"> <div> <img src={profile} alt="Profile" className="profile-image" /> </div> <div className="user-info "> <h6 className='text-light'>Soubhagya</h6> <span className="text-secondary">Developer</span> </div> <div> <IoIosArrowDown className='text-light' /> </div> </div> </div> {/* <div className="profile-section"> </div> */} </div> <Navbar /> <MainContent /> <Footer /> </> ) } export default SideBar
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class ProductRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' => ['required','min:3','max:5', 'unique:products'], 'description' => ['required','max:500'], 'is_active'=>['required'], ]; } public function messages() { return [ 'title.required' => 'A Product Title is required', 'title.min' => 'Title', 'description.required' => 'Product Description is required', ]; } public function attributes() { return [ 'title' => 'Product Name', 'description' => 'Product Description', ]; } }
#!/bin/bash # # disable-services.sh # # A walkthrough script for stopping and disabling services # # Sam DeCook # Feb. 2024 clear if [[ "$(id -u)" != "0" ]] then printf "${error}ERROR: The script must be run with sudo privileges!${reset}\n" exit 1 fi printf "${info}If your machine doesn't have systemctl, let the maintainer know${reset}\n\n" # Get input from systemctl. # Trim lines which don't contain services. # Remove any safe services # Reformat to remove unecessary spaces systemctl --type=service | tail -n +2 | head -n -7 | \ grep -v -f systemctl-safe-services.txt | \ sed -e 's/\(\S*\)\s*\(\S*\)\s*\(\S*\)\s*\(.*\)/\1\t\2\t\3\t\4/' > \ services.txt printf "This script removes services which are in systemctl-safe-services.txt.\n" printf "Always use systemctl to see all of the services\n\n" printf "${info}There are $(cat services.txt | wc -l) services to be considered.${reset}\n" printf "Press any key to start..." read input # Clear out these files echo "" > disable-services-stderr.txt i=0 IFS=$'\n' for line in $(cat services.txt); do clear printf "${info}[%.2d]${reset} " $i let "i+=1" printf "$line\n" printf "Do you want to disable this service? [y/n]:\n" service=`echo $line | awk '{print $1}'` read answer if [[ $answer == "y" ]] then printf "Stopping and disabling $service\n" sleep 0.5 systemctl stop $service 2>> disable-services-stderr.txt systemctl disable $service 2>> disable-services-stderr.txt echo $service >> stopped-disabled.txt sleep 0.5 elif [[ $answer != "n" ]] then printf "Bruh" fi sleep 0.25 done clear printf "${info} You have disabled these services:${reset}\n" cat stopped-disabled.txt printf "\n\nSee stopped-disabled.txt for all services disabled with this script\n\n" printf "\n\n${info}Run ./service-sort to get a list of all services${reset}\n\n" exit 0
# !/usr/bin/env/ python # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.remote.webdriver import WebDriver from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait class BasePage: def __init__(self, base_url: WebDriver = None): # 避免driver重复初始化 if base_url is None: opt = webdriver.ChromeOptions() # 设置复用浏览器的地址 opt.debugger_address = "127.0.0.1:9222" self.driver = webdriver.Chrome(options=opt) # 设置隐式等待 self.driver.implicitly_wait(10) else: self.driver = base_url def find(self, by, locator): return self.driver.find_element(by, locator) def finds(self, by, locator): return self.driver.find_elements(by, locator) def wait_for_click(self, locator, timeout): element: WebDriver = WebDriverWait(self.driver, timeout).until \ (expected_conditions.element_to_be_clickable(locator)) return element
{{!< default}} <main class="site__content background-alternate"> <section class="section section--only-top print-padding-none" aria-labelledby="h__header" > <div class="container"> {{#tag}} <div class="article"> <div class="article__meta">Téma</div> <h1 id="h__header" class="article__title">{{name}}</h1> {{#if description}} <p class="article__summary spacing-bottom-none js-nbsp"> {{description}} </p> {{/if}} </div> {{/tag}} </div> </section> {{! Manually get **all** glossary items with current tag because they would be paginated as part of `posts`. }} {{#get "posts" filter="primary_tag:slovnik+tag:{{tag.slug}}" limit="all" as |glossary_items| }} {{#if glossary_items}} <section id="slovnik" class="section section--only-top" aria-labelledby="h__slovnik" > <div class="container"> <h2 id="h__slovnik" class="spacing-bottom-small">Hesla ve slovníku</h2> <ul class="list-unstyled list-inline spacing-bottom-none"> {{#foreach glossary_items visibility="public"}} <li class="list-item-decorated"> <a href="{{url}}" class="text-nowrap">{{title}}</a> </li> {{/foreach}} </ul> </div> </section> {{/if}} {{/get}} {{! Use `posts` as the source for **paginated** listing of posts with the "Články" tag (output of `get` helper cannot be paginated.) The tradeoff is that `<section>` is always present in the markup, even when there are no relevant articles. }} <section id="clanky" class="section" aria-labelledby="h__clanky" > <div class="container container--dense"> {{! Hide the headline as we cannot be sure if there are some posts or not. (It's visually redundant anyway.) }} <h2 id="h__clanky" class="visually-hidden">Články</h2> <div class="post-feed"> {{#foreach posts visibility="public"}} {{#has tag="Články"}} <div class="post-feed__item"> {{> "post-card" headingLevel=3}} </div> {{/has}} {{/foreach}} </div> </div> </section> </main> {{> "footer"}}
# Knowledge - ### elementwise - 각 계산을 한번에 실행함 / element별로 계산함 - 숫자가 클 때 유리하다 - ### Numpy - numpy는 mutable이다 - 그래서 copy를 사용한다 - np.copy는 default가 deep copy다 - 이때의 copy는 **deep copy**이다 - np.view 는 default가 **shallow copy**다 - 사용 시기는 **원본 데이터를 지키고 싶을때 np.copy** - - copy의 종류가 여러개가 존재한다 - **deep copy** = value만 copy - **shallow copy** = address copy - python 기본 copy는 shallow copy이다 - copy에서 deecopy를 사용하면 deep copy다 - ### 차원의 확장 - ![image.png](../assets/image_1711087617954_0.png) - 여기서 [:, :, None] 에서 [..., None]으로 써도 된다 - 사용하기 힘들기에 np.newaxis로 새로운 좌표축 생성이 가능하다 - 즉, 차원의 확장이 가능하다 - ![image.png](../assets/image_1711087781005_0.png) - ### Homogeneous의 확대 - 원래 a = ['a', 1, 2]는 호모가 아니다 - 하지만 b = ['b', 2, 3]을 만들면 a,b 둘다 **호모이다** - ### Structured Array - **namedtuple** - C의 struct와 비슷하다 - ![image.png](../assets/image_1711089896774_0.png){:height 502, :width 379} - np.array로도 만들 수 있다 - ![image.png](../assets/image_1711090481192_0.png) - 이것을 확장한게 **rec.array**이다 - 얘는 .name 이런 dot notation으로도 접근 가능하다 - ![image.png](../assets/image_1711090541974_0.png) - **mask array (ma.array)** - 특정 값을 가릴 수 있음 - 여기서 count가 가능하다 (안가려진 애들) - missing data (비어있는 데이터)를 보고 싶을때 사용 - ![image.png](../assets/image_1711090682573_0.png) - **Matrix array (np.matrix)** - repr이 array가 아니라 matrix이다 - 이때 matrix의 성질을 그대로 따라간다 - * 연산은 element의 곱이 아니라 matrix 곱으로 간다 - ![image.png](../assets/image_1711091038741_0.png) - ### numpy의 메모리 - **a.strides**는 elements의 indexing을 하기 위해서 필요한 값을 의미한다 - Numpy는 기본적으로 C와 같이 값이 메모리에 한 줄로 저장된다 - ![image.png](../assets/image_1711101971416_0.png) - ### Axis의 인지법 - axis가 0이면 size에서 0번쨰를 지운 5,7 사이즈의 array가 나와야 한다 - ![image.png](../assets/image_1711102239316_0.png) -
const crypto = require('crypto'); const mongoose = require('mongoose'); const validator = require('validator'); const bcrypt = require('bcryptjs'); const userSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Please tell us your name!'], }, email: { type: String, required: [true, 'Please provide your email'], unique: true, lowercase: true, validate: [validator.isEmail, 'Please enter a valid email'], }, photo: { type: String, }, role: { type: String, enum: ['user', 'guide', 'lead-guide', 'admin'], default: 'user', }, password: { type: String, required: [true, 'Please provide a password'], minlength: 8, select: false, }, confirmPassword: { type: String, required: [true, 'Please confirm your password'], validate: { // This only works on create() and save() and not on update. validator: function (el) { return this.password === el; }, message: 'Passwords do not match!', }, }, active: { type: Boolean, default: true, // Hiding this from the end user. select: false, }, passwordChangedAt: Date, passwordResetToken: String, passwordResetExpiresIn: Date, }); // Using a pre-save middleware to hash the passwords. userSchema.pre('save', async function (next) { // If password is not modified return if (!this.isModified('password')) next(); // Hashing the password with bcrypt with a cost of 12; this.password = await bcrypt.hash(this.password, 12); // Setting the confirm password to null to avoid leakage. this.confirmPassword = undefined; next(); }); userSchema.pre('save', function (next) { // If the password has not been changed or the document is just created. // We do not want to do anything. if (!this.isModified('password') || this.isNew) return next(); // Sometimes the saving of password in database takes longer and the JWT is sent before. // This leads to passwordChangedAt being set to after the token has been generated, which makes the token invalid. // To fix this we add a bit of buffer in the timestamp (push it backwards in time) to make it appear that token is generated after the password is changed. this.passwordChangedAt = Date.now() - 1000; next(); }); // Query Middleware to prevent quering inactive users userSchema.pre(/^find/, function (next) { // this points to the current query object. this.find({ active: { $ne: false } }); next(); }); // This is called an instance method. userSchema.methods.correctPassword = async function ( candidatePassword, correctPassword ) { return await bcrypt.compare(candidatePassword, correctPassword); }; userSchema.methods.changedPasswordAfter = function (JWTTimestamp) { if (this.passwordChangedAt) { const changedTimestamp = parseInt( this.passwordChangedAt.getTime() / 1000, 10 ); // If JWT is issued before passwordChange , then return true. // The one issued earlier is smaller as less time has passed from 1970 to that event. return JWTTimestamp < changedTimestamp; } return false; }; userSchema.methods.createPasswordResetToken = function () { // This the plain text token , which will be sent via email const resetToken = crypto.randomBytes(32).toString('hex'); // We store this token in our database with encryption to verify against it later const passwordResetToken = crypto .createHash('sha256') .update(resetToken) .digest('hex'); this.passwordResetToken = passwordResetToken; // Token has an expiration time of 10 mins this.passwordResetExpiresIn = Date.now() + 10 * 60 * 1000; // Return the unhashed token to be sent via email. return resetToken; }; const User = mongoose.model('User', userSchema); module.exports = User;
const OrganizationRead = { template: ` <div> <b-overlay :show="isLoading"> <div v-if="organization"> <b-row class="mb-5"> <b-col v-if="organization.logo" cols="12" sm="auto"> <figure class="figure mx-5"> <b-img :src="organization.logo.image_url + '?s=120'" class="figure-img img-fluid" style="max-width:120px;" alt="Logo"></b-img> </figure> </b-col> <b-col cols="12" sm> <h1 class="my-0">{{ organization.name }} <template v-if="organization.is_verified"><i class="fa fa-check-circle text-primary"></i></template></h1> <div class="mb-3 text-muted">@{{ organization.short_name }}</div> <div v-if="organization.url"> <i class="fa fa-fw fa-link"></i> <a :href="organization.url" target="_blank" rel="noopener noreferrer" style="word-break: break-all;">{{ organization.url }}</a> </div> <div v-if="organization.email"> <i class="fa fa-fw fa-envelope"></i> <a :href="'mailto:' + organization.email">{{ organization.email }}</a> </div> <div v-if="organization.phone"> <i class="fa fa-fw fa-phone"></i> <a :href="'tel:' + organization.phone">{{ organization.phone }}</a> </div> <div v-if="organization.fax"> <i class="fa fa-fw fa-fax"></i> {{ organization.fax }} </div> <div v-if="organization.location && (organization.location.street || organization.location.postalCode || organization.location.city)"> <i class="fa fa-fw fa-map-marker"></i> <template v-if="organization.location.street">{{ organization.location.street }}, </template> {{ organization.location.postalCode }} {{ organization.location.city }} </div> <div v-if="organization.description" class="mt-3"> <span style="white-space: pre-wrap;">{{ organization.description }}</span> </div> <div v-if="canRelation" class="mt-3"> <b-overlay :show="isLoadingRelation"> <div> <b-card v-if="relation"> <b-card-text> <div v-if="relation.verify"> <i class="fa fa-fw fa-check-circle"></i> {{ $t('comp.relationVerify', { source: $root.currentAdminUnit.name, target: organization.name }) }} </div> <div v-if="relation.auto_verify_event_reference_requests"> <i class="fa fa-fw fa-check-circle"></i> {{ $t('comp.relationAutoVerifyEventReferenceRequests', { source: $root.currentAdminUnit.name, target: organization.name }) }} </div> </b-card-text> <b-link :href="relationEditUrl"> {{ $t("comp.relationEdit") }} </b-link> </b-card> <template v-if="relationDoesNotExist"> <b-card v-if="organization.is_verified"> <b-card-text> {{ $t('comp.relationDoesNotExist', { source: $root.currentAdminUnit.name, target: organization.name }) }} </b-card-text> <b-link :href="relationCreateUrl"> {{ $t("comp.relationCreate") }} </b-link> </b-card> <b-card v-else border-variant="warning"> <b-card-text> {{ $t("comp.organizationNotVerified", { organization: organization.name }) }} </b-card-text> <b-link :href="relationCreateUrl"> {{ $t("comp.relationCreateToVerify", { organization: organization.name }) }} </b-link> </b-card> </template> </div> </b-overlay> </div> <b-list-group class="mt-4"> <b-list-group-item :href="'/eventdates?admin_unit_id=' + organization.id"> <i class="fa fa-fw fa-list"></i> {{ $t("shared.models.event.listName") }} </b-list-group-item> <b-list-group-item button v-b-modal.modal-ical> <i class="fa fa-fw fa-calendar"></i> {{ $t("comp.icalExport") }} </b-list-group-item> </b-list-group> <b-modal id="modal-ical" :title="$t('comp.icalExport')" size="lg" ok-only> <template #default="{ hide }"> <b-input-group class="mb-3"> <b-form-input :value="icalUrl" ref="icalInput"></b-form-input> </b-input-group> </template> <template #modal-footer="{ ok, cancel, hide }"> <b-button variant="outline-info" :href="icalDocsUrl" target="_blank" rel="noopener noreferrer" v-if="icalDocsUrl">{{ $t('shared.docs') }}</b-button> <b-button variant="primary" @click.prevent="copyIcal()">{{ $t('comp.copy') }}</b-button> <b-button variant="secondary" :href="icalUrl">{{ $t('comp.download') }}</b-button> <b-button variant="outline-secondary" @click="hide()">{{ $t("shared.close") }}</b-button> </template> </b-modal> </b-col> </b-row> </div> </b-overlay> </div> `, i18n: { messages: { en: { comp: { copy: "Copy link", download: "Download", icalCopied: "Link copied", icalExport: "iCal calendar", organizationNotVerified: "{organization} is not verified", relationVerify: "{source} verifies {target}", relationAutoVerifyEventReferenceRequests: "{source} verifies reference requests from {target} automatically", relationDoesNotExist: "There is no relation from {source} to {target}", relationEdit: "Edit relation", relationCreate: "Create relation", relationCreateToVerify: "Verify {organization}", }, }, de: { comp: { copy: "Link kopieren", download: "Runterladen", icalCopied: "Link kopiert", icalExport: "iCal Kalender", organizationNotVerified: "{organization} ist nicht verifiziert", relationVerify: "{source} verifiziert {target}", relationAutoVerifyEventReferenceRequests: "{source} verifiziert Empfehlungsanfragen von {target} automatisch", relationDoesNotExist: "Es besteht keine Beziehung von {source} zu {target}", relationEdit: "Beziehung bearbeiten", relationCreate: "Beziehung erstellen", relationCreateToVerify: "Verifiziere {organization}", }, }, }, }, data: () => ({ isLoading: false, isLoadingRelation: false, organization: null, relation: null, canRelation: false, relationDoesNotExist: false, }), computed: { organizationId() { return this.$route.params.organization_id; }, icalUrl() { return `${window.location.origin}/organizations/${this.organizationId}/ical`; }, icalDocsUrl() { return this.$root.docsUrl ? `${this.$root.docsUrl}/goto/ical-calendar` : null; }, relationEditUrl() { return `/manage/admin_unit/${this.$root.currentAdminUnit.id}/relations/${this.relation.id}/update`; }, relationCreateUrl() { return `/manage/admin_unit/${this.$root.currentAdminUnit.id}/relations/create?target=${this.organizationId}&verify=1`; }, }, mounted() { this.isLoading = false; this.isLoadingRelation = false; this.organization = null; this.relation = null; this.canRelation = this.$root.has_access("admin_unit:update") && this.$root.hasOwnProperty("currentAdminUnit") && (this.$root.currentAdminUnit.canVerifyOther || this.$root.currentAdminUnit.incomingReferenceRequestsAllowed); this.relationDoesNotExist = false; this.loadData(); this.loadRelationData(); }, methods: { loadData() { axios .get(`/api/v1/organizations/${this.organizationId}`, { withCredentials: true, handleLoading: this.handleLoading, }) .then((response) => { this.organization = response.data; }); }, loadRelationData() { if (!this.canRelation) { return; } if (this.$root.currentAdminUnit.id == this.organizationId) { return; } const vm = this; axios .get(`/api/v1/organizations/${this.$root.currentAdminUnit.id}/relations/outgoing/${this.organizationId}`, { withCredentials: true, handleLoading: this.handleLoadingRelation, handler: { handleLoading: function(isLoading) { vm.isLoadingRelation = isLoading; }, handleRequestError: function(error, message) { const status = error && error.response && error.response.status; if (status == 404) { vm.relationDoesNotExist = true; return; } this.$root.makeErrorToast(message); } } }) .then((response) => { this.relation = response.data; }); }, handleLoading(isLoading) { this.isLoading = isLoading; }, copyIcal() { this.$refs.icalInput.select(); document.execCommand("copy"); this.$root.makeSuccessToast(this.$t("comp.icalCopied")) } }, };
package com.bridgelabz.student; public class StudentManager { private Student[] students; private int capacity; private int size; // Constructor public StudentManager(int capacity) { this.capacity = capacity; this.students = new Student[capacity]; this.size = 0; } // Method to add a student public void addStudent(Student student) { if (size < capacity) { students[size] = student; size++; } else { System.out.println("Student database is full. Cannot add more students."); } } // Method to remove a student by ID public void removeStudentById(int id) { for (int i = 0; i < size; i++) { if (students[i].getId() == id) { // Move the last student to the current position to maintain continuity students[i] = students[size - 1]; students[size - 1] = null; // Clear the last position size--; System.out.println("Student with ID " + id + " removed successfully."); return; } } System.out.println("Student with ID " + id + " not found."); } // Method to remove a student by name public void removeStudentByName(String name) { for (int i = 0; i < size; i++) { if (students[i].getName().equals(name)) { // Move the last student to the current position to maintain continuity students[i] = students[size - 1]; students[size - 1] = null; // Clear the last position size--; System.out.println("Student with name " + name + " removed successfully."); return; } } System.out.println("Student with name " + name + " not found."); } // Method to print all students public void printAllStudents() { if (size == 0) { System.out.println("No students found."); return; } System.out.println("All Students:"); for (int i = 0; i < size; i++) { students[i].display(); } } }
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * import numpy as np pygame.init() display_width = 800 display_height = 600 display = pygame.display.set_mode((display_width, display_height), DOUBLEBUF | OPENGL) pygame.display.set_caption("3D Transformations") glClearColor(0.0, 0.0, 0.0, 1.0) glEnable(GL_DEPTH_TEST) glMatrixMode(GL_PROJECTION) gluPerspective(45, (display_width / display_height), 0.1, 50.0) glMatrixMode(GL_MODELVIEW) vertices = np.array([ [-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1] ], dtype=np.float32) edges = np.array([ [0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4], [0, 4], [1, 5], [2, 6], [3, 7] ], dtype=np.uint32) translation_matrix = np.eye(4, dtype=np.float32) translation_matrix[3, :3] = [0, 0, -5] rotation_matrix = np.eye(4, dtype=np.float32) scaling_matrix = np.eye(4, dtype=np.float32) scaling_matrix[0, 0] = 1.5 scaling_matrix[1, 1] = 1.5 scaling_matrix[2, 2] = 1.5 running = True angle = 0 rotation_speed = 0.05 while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glMultMatrixf(translation_matrix) glRotatef(angle, 1, 1, 0) glMultMatrixf(rotation_matrix) glMultMatrixf(scaling_matrix) glBegin(GL_LINES) for edge in edges: for vertex in edge: glVertex3fv(vertices[vertex]) glEnd() angle += rotation_speed pygame.display.flip() pygame.quit()
import { useState, useEffect } from "react"; import "./regurgitator.scss"; export default function RegurgitatorCore({ target, children, onRegurgitationChange, overideRegurgitation, }: { target: string[]; children: any; onRegurgitationChange?: Function; overideRegurgitation?: string[]; }) { const [regurgitation, setRegurgitation]: any = useState([]); const safeSetRegurgitation: Function = function ( index: number, value: string ) { const regurgitationBuffer = JSON.parse(JSON.stringify(regurgitation)); regurgitationBuffer[index] = value; setRegurgitation(regurgitationBuffer); }; useEffect(() => { if (onRegurgitationChange) { onRegurgitationChange(regurgitation); } }, [regurgitation]); useEffect(() => { setRegurgitation(overideRegurgitation || []); }, [overideRegurgitation]); return ( <> {target.map((targetChunk: string, index: number) => { const id = `target_chunk_${index}`; return ( <div key={index} className="reg_core_item_map"> <label htmlFor={id}>Please regurgitate the following text</label> <p>{targetChunk}</p> <textarea style={{ width: "100%", }} id={id} onChange={(e) => { safeSetRegurgitation(index, e.target.value); }} defaultValue={regurgitation[index]} /> </div> ); })} {children} <textarea className="regurgitator_output" defaultValue={regurgitation.join(". ")} rows={4} readOnly={false} /> </> ); }
package org.neatcode; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public class GameService { private Queue<Player> players; private Queue<Player> leaderBoard; private Map<Integer, Integer> currentPos; private Board board; private Dice dice; private final int START_POS = 0; private final int WINNING_POS; public GameService(Queue<Player> players, Board board) { this.WINNING_POS = board.getBoardSize() * board.getBoardSize(); this.currentPos = new HashMap<>(); this.players = new ConcurrentLinkedQueue<>(); for(Player player: players) { currentPos.put(player.getId(), START_POS); this.players.add(player); } dice = new Dice(); this.board = board; leaderBoard = new LinkedList<>(); } public void startGame() { for(Player player: players) { player.setTotalMatchesPlayed(player.getTotalMatchesPlayed()+1); } StringBuilder message = new StringBuilder(); while (players.size() >= 2) { for(Player player: players) { message.append("\n").append(player.getName()).append("'s turn."); int diceNumber = dice.getRandomNumber(); message.append(" Dice Rolled At: ").append(diceNumber); int currPos = currentPos.get(player.getId()); int newPos = currPos + diceNumber; message.append(". Moving From ").append(currPos).append(" to ").append(newPos); if(board.getLadderFootAndHeadPosition().containsKey(newPos)) { message.append("\nShoot! Encountered Ladder. ").append("moved from ").append(newPos).append(" to "); newPos = board.getLadderFootAndHeadPosition().get(newPos); message.append(newPos); } if(board.getSnakesHeadAndTailPosition().containsKey(newPos)) { message.append("\nNoice! Encountered a Snake. ").append("moved from ").append(newPos).append(" to "); newPos = board.getSnakesHeadAndTailPosition().get(newPos); message.append(newPos); } if(newPos > WINNING_POS) { message.append("\nNew Position Exceeds Winning Position of ").append(WINNING_POS); } else if(newPos == WINNING_POS) { leaderBoard.add(player); player.setWins(player.getWins()+1); players.remove(player); message.append("\nHurray!!! ").append(player.getName()).append(" Wins finishing with Rank ").append(leaderBoard.size()); currentPos.remove(player.getId()); } else { currentPos.put(player.getId(), newPos); } System.out.println(message); message.delete(0, message.length()); } } System.out.println("\n\nWell Played.\n\n"); leaderBoard.add(players.peek()); printLeaderBoard(); } private void printLeaderBoard() { System.out.println("LeaderBoard"); int rank = 1; for(Player player: leaderBoard) { System.out.println(rank + " : " + player.getName()); rank++; } } }
"use strict"; // In this challenge, a farmer is asking you to tell him how many // legs can be counted among all his animals. The farmer breeds three species: // chickens = 2 legs // cows = 4 legs // pigs = 4 legs // The farmer has counted his animals and he gives you a subtotal for each species. // You have to implement a function that returns the total number of legs of all the animals. function animals(chickens, cows, pigs) { return chickens * 2 + cows * 4 + pigs * 4; } console.log(animals(4, 5, 6)); // Create a function that returns the number of frames shown in // a given number of minutes for a certain FPS. function frames(minutes, fps) { return minutes * 60 * fps; } console.log(frames(5, 6)); // Create a function that takes two arguments. // Both arguments are integers, a and b. // Return true if one of them is 10 or if their sum is 10. function makesTen(a, b) { return a + b == 10 || a === 10 || b === 10; } console.log(makesTen(2, 8)); // Write a function that checks whether a person can watch an MA15+ rated movie. // One of the following two conditions is required for admittance: // The person is at least 15 years old. // They have parental supervision. // The function accepts two parameters, age and isSupervised. Return a boolean. function acceptIntoMovie(age, isSupervised) { return age >= 15 || isSupervised; } console.log(acceptIntoMovie(13, true)); // Scientists have discovered that in four decades, the world will EXPLODE! It will also take three decades to make a spaceship to travel to a new planet that can hold the entire world population. // You must calculate the number of people there will be in three decades from now. // The variable population is the world population now. // Assume that every month, someone gives birth to more people n. // Return the number of people there will be when the spaceship is complete. function futurePeople(population, n) { return 3 * 10 * 12 * n + population; } console.log(futurePeople(1400, 2)); // Write a function that accepts base (decimal), height (decimal) // and shape ("triangle", "parallelogram") as input and calculates the area of that shape. function areaShape(base, height, shape) { let area; if (shape === "parallelogram") { area = base * height; } else if (shape === "triangle") { area = 0.5 * base * height; } return area; } console.log(areaShape(2, 6, "triangle")); console.log(areaShape(3, 8, "parallelogram")); // A typical car can hold four passengers and one driver, allowing five people to travel around. // Given n number of people, return how many cars are needed to seat everyone comfortably. // function carsNeeded(n) { // let car; // if (n % 5 === 0) { // car = Math.floor(n / 5); // } else { // car = Math.floor(n / 5) + 1; // } // return car; // } function carsNeeded(n) { let car; n % 5 === 0 ? (car = Math.floor(n / 5)) : (car = Math.floor(n / 5) + 1); return car; } console.log(carsNeeded(111)); // Create a function that takes an array and returns // the types of values (data types) in a new array. function arrayValuesTypes(arr) { let typeIndex = []; for (let i = 0; i <= arr.length - 1; i++) { typeIndex[i] = typeof arr[i]; } return typeIndex; } console.log(arrayValuesTypes([1, 2, "null", []])); // Write a function that stutters a word as if someone is struggling to read it. // The first two letters are repeated twice with an ellipsis ... and space after each, // and then the word is pronounced with a question mark ?. function stutter(word) { const letter = word.slice(0, 2) + "... " + word.slice(0, 2) + "... " + word + "?"; return letter; } console.log(stutter("incredible")); // Create a function that returns the ASCII value of the passed in character. function ctoa(c) { return c.charCodeAt(); } console.log(ctoa("$")); // Create a function that takes two numbers and returns their sum as a binary string. function addBinary(a, b) { const sum = a + b; if (sum >= 0) { return sum.toString(2); } else { return (~sum).toString(2); } } console.log(addBinary(2, 3)); const countDs = (s) => s.match(/D/gi).length; console.log(countDs("my friend Dylan got distracted in school.")); // For each of the 6 coffee cups I buy, I get a 7th cup free. In total, I get 7 cups. Create a function // that takes n cups bought and return as an integer the total number of cups I would get. function totalCups(n) { return Math.floor(n + n / 6); } console.log(totalCups(7)); // You hired three programmers and you (hopefully) pay them. // Create a function that takes three numbers (the hourly wages of each programmer) // and returns the difference between the highest-paid programmer and the lowest-paid. function programmers(one, two, three) { return Math.max(one, two, three) - Math.min(one, two, three); } console.log(programmers(25, 1480, 465)); // Given an array of integers, determine whether the sum of its elements is even or odd. // The return value should be a string ("odd" or "even"). // If the input array is empty, consider it as an array with a zero ([0]). function evenOrOdd(arr) { let sum = 0; for (let i = 0; i <= arr.length - 1; i++) { sum += arr[i]; } if (sum % 2 === 0 || sum === 0) { return "even"; } else if (sum === null) { return "even"; } else { return "odd"; } } console.log(evenOrOdd(2, 6, 7, 11, 3)); // Given the side length x find the area of a hexagon. function areaOfHexagon(x) { if (x <= 0) { return null; } let area = (3 * (Math.sqrt(3) * Math.pow(x, 2))) / 2; let areaO = Number.parseFloat(area).toFixed(1); return eval(areaO); } // Create a function that takes a positive integer n, // and returns the sum of all the cubed values from 1 to n. // For example, if n is 3: function sumCubes(n) { let sum = 0; for (let i = 1; i <= n; i++) { sum += i ** 3; } return sum; } console.log(sumCubes(4)); // Create a function that takes a number n // and returns the first 10 multiples of n with 1 added to it, separated by commas. function nTablesPlusOne(n) { const table = []; for (let i = 1; i <= 10; i++) { table.push(n * i + 1); } return table.toString(); } console.log(nTablesPlusOne(7)); // Create a function that takes two arguments: // a father's current age fAge and his son's current age sAge. // Сalculate how many years ago the father was twice as old as his son, // or in how many years he will be twice as old. function ageDifference(fAge, sAge) { const diff = fAge - sAge; const twiceAge = diff - sAge; return Math.abs(twiceAge); } console.log(ageDifference(54, 31)); // Create a function that takes two arguments of an array of numbers arr and a // constant number n and returns the n largest numbers from the given array. function largestNumbers(n, arr) { function compareNumbers(a, b) { return a - b; } arr.sort(compareNumbers); console.log(arr); // return arr.slice(0, n); minmum numbers // return arr.slice(arr.length - n, arr.length); return arr.slice(arr.length - n); } // *** // function largestNumbers(n, arr) { // return arr.sort((a, b) => a - b).slice(arr.length - n); // } console.log(largestNumbers(2, [1, 30, 4, 21, 100000])); // Write a function that takes a year and returns its corresponding century. function centuryFromYear(year) { return Math.ceil(year / 100); } console.log(centuryFromYear(1752)); function multiplyByLength(arr) { return arr.map((x) => x * arr.length); } console.log(multiplyByLength([1, 5, 4, 8, 6, 7, 9, 10])); // convert percentages to decimal // var percent = "50%"; // var result = parseFloat(percent) / 100.0; // Create a function that applies a discount d to every number in the array. function getDiscounts(nums, d) { return nums.map((x) => x * (parseFloat(d) / 100.0)); } console.log(getDiscounts([20, 10, 36, 69], "65%")); // Sam and Frodo need to be close. If they are side by side in the array, // your function should return true. If there is a name between them, return false. function middleEarth(arr) { if ( arr.indexOf("Sam") + 1 === arr.indexOf("Frodo") || arr.indexOf("Frodo") + 1 === arr.indexOf("Sam") ) { return true; } else { return false; } } console.log(middleEarth(["Orc", "Frodo", "Legolas", "Sam", "Bilbo"])); console.log(middleEarth(["Aragorn", "Gandalf", "Sam", "Frodo", "Gollum"])); // Given an integer n. Your task is to find how many digits // this integer contains without using String or Array methods! const sumDigits = (n) => Math.ceil(Math.log10(n + 1) || 1);
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!--/* BOOTSTRAP */--> <link th:rel="stylesheet" th:href="@{/webjars/bootstrap/5.3.2/css/bootstrap.min.css} "/> <!--/* STYLE */--> <link rel="stylesheet" th:href="@{/css/style.css}" > <title>Insert title here</title> </head> <body th:object="${pizza}"> <header th:replace="~{frags/header :: header()}"></header> <div class="container mt-5 mb-5"> <div class="row"> <div class="col-9"> <h1 class="text-center"> [[*{name.substring(0, 1).toUpperCase() + name.substring(1, name.length())}]] </h1> <div class="d-flex justify-content-center"> <img class="pm-img-show" th:alt="*{name}" th:src="*{getFullFotoUrl(fotoUrl)}"> </div> <div class="row mt-5"> <div class=" col-8 text-center "> <h5> <strong> Price: </strong> [[*{price}]] $ </h5> <h5> <strong> Description: </strong> [[*{description}]] </h5> </div> <div class="col-4 "> <strong> Ingredients: </strong> <ul> <li th:each="ingredient : *{ingredients}"> [[${ingredient.name}]] </li> </ul> </div> </div> </div> <div class="col-3"> <h2 class="d-inline">Offers</h2> <a th:href="| /offers/create/*{id} |" class="btn btn-secondary d-inline" sec:authorize="hasAuthority('ADMIN')"> New Offer </a> <h6 class="mt-5" th:if="*{offers.size() < 1}"> Non ci sono offerte.. </h6> <ul th:if="*{offers.size() > 0}" class="mt-5"> <li th:each="offer : *{offers}"> [[${offer.title}]] <span sec:authorize="hasAuthority('ADMIN')"> - <a th:href="| /offers/update/*{id}/${offer.id} |"> Edit </a> </span> </li> </ul> </div> </div> </div> </body> </html>
require("dotenv").config(); import { Request, Response, NextFunction } from "express"; const User = require("../models/user"); const path = require("node:path"); const sendMail = require("../utils/sendMail"); const bycrypt = require("bcrypt"); const JWT = require("jsonwebtoken"); const sendToken = require("../utils/jwtToken"); const createUser = async ( request: Request, response: Response, next: NextFunction ) => { const { name, email, password } = request.body; const userEmail = await User.findOne({ email }); if (!name || !email || !password) { return response .status(400) .json({ error: "name, email and password must be provided" }); } if (userEmail) { return response.status(400).json({ error: "Email exist in our data base" }); } const fileName = request.file?.filename; const fileUrl = path.join(fileName); const saltRound = 10; const passwordHash = await bycrypt.hash(password, saltRound); const user = { name, email, passwordHash, avatar: fileUrl, }; // const user = await User.create({ // name, // email, // passwordHash, // avatar: fileUrl // }); const activationToken = createActivationToken(user); const activationURL = `http://localhost:5173/activation/${activationToken}`; await sendMail({ email: user.email, subject: "Activate your account", message: `Hello ${user.name} please click on the link below to activate your account! ${activationURL}`, }); return response .status(201) .json({ success: true, message: `Please check your email ${user.email} to activate your account`, }); }; const createActivationToken = (user: { name: string; email: string; passwordHash: string; avatar: File; }) => { const token = JWT.sign(user, process.env.JWTSECRET, { expiresIn: 60 * 60 }); return token; }; const activation = async (req: Request, res: Response) => { const { activation_token } = req.body; console.log(activation_token) const newUser = await JWT.verify(activation_token, process.env.JWTSECRET); console.log(newUser); if (!newUser) { return res.status(400).json({ message: "Invalid Token" }); } const { name, email, passwordHash, avatar } = newUser; let user = await User.findOne({ email }); if (user) { return res.status(400).json({ message: "User already exist" }); } user = await User.create({ name, email, passwordHash, avatar, }); sendToken(user, 201, res); }; const login = async ( request: Request, response: Response, next: NextFunction ) => { const { email, password } = request.body; const user = await User.findOne({ email }); const isPasswordCorrect = user === null ? false : await bycrypt.compare(password, user.passwordHash); if (!user || !isPasswordCorrect) { response.status(400).json({ error: "invalid username or password" }); } const token = JWT.sign( { name: user.name, userId: user.id }, process.env.JWTSECRET ); response.status(200).json({ name: user.name, email: user.email, token }); }; module.exports = { createUser, activation, login, }; // require("dotenv").config(); // import { Request, Response, NextFunction } from "express"; // const User = require("../models/user"); // const path = require("node:path"); // const sendMail = require("../utils/sendMail"); // const bycrypt = require("bcrypt"); // const JWT = require("jsonwebtoken"); // const createUser = async ( // request: Request, // response: Response, // next: NextFunction // ) => { // const { name, email, password } = request.body; // const userEmail = await User.findOne({ email }); // if (!name || !email || !password) { // return response // .status(400) // .json({ error: "name, email and password must be provided" }); // } // if (userEmail) { // return response // .status(400) // .json({ error: " User already exist in our data base" }); // } // const fileName = request.file?.filename; // const fileUrl = path.join(fileName); // const saltRound = 10; // const passwordHash = await bycrypt.hash(password, saltRound); // const user = await User.create({ // name, // email, // passwordHash, // avatar: fileUrl, // }); // // const activationToken = createActivationToken(user); // const token = JWT.sign(user, process.env.JWTSECRET, { expiresIn: 60 * 60 }); // // console.log(activationToken) // // const activationURL = `http//localhost8000/activation/${activationToken}`; // // await sendMail({ // // email: user.email, // // subject: "Activate your account", // // message: `Hello ${user.name} please click on the link to activate your account! ${activationURL}`, // // }); // return response // .status(201) // .json({ // success: true, // message: "Please chack your mail to activate your account", // }); // }; // const createActivationToken = (user: { // name: string; // email: string; // passwordHash: string; // avatar: File; // }) => { // const token = JWT.sign(user, process.env.JWTSECRET, { expiresIn: 60 * 60 }); // return token; // }; // const login = async ( // request: Request, // response: Response, // next: NextFunction // ) => { // const { email, password } = request.body; // const user = await User.findOne({ email }); // const isPasswordCorrect = // user === null ? false : await bycrypt.compare(password, user.passwordHash); // if (!user || !isPasswordCorrect) { // response.status(400).json({ error: "invalid username or password" }); // } // const token = JWT.sign( // { name: user.name, userId: user.id }, // process.env.JWTSECRET // ); // response.status(200).json({ name: user.name, email: user.email, token }); // }; // module.exports = { // createUser, // login, // };
import CreateTweet from "@/components/ui/CreateTweet"; import TweetCard, { TweetCardSkeleton } from "@/components/ui/TweetCard"; import { Tweet } from "@/types/Tweet"; import { Box, VStack } from "@chakra-ui/react"; import { DocumentData, FirestoreDataConverter, QueryDocumentSnapshot, SnapshotOptions, collection, orderBy, query, } from "firebase/firestore"; import { NextPage } from "next"; import { useCollectionData } from "react-firebase-hooks/firestore"; import { db } from "../../firebase"; const postConverter: FirestoreDataConverter<Tweet> = { toFirestore(): DocumentData { return {}; }, fromFirestore( snapshot: QueryDocumentSnapshot, options: SnapshotOptions ): Tweet { const data = snapshot.data(options); return { id: snapshot.id, images: data.images, content: data.content, createdAt: data.createdAt, author: data.author, }; }, }; const HomePage: NextPage = () => { // This query will fetch all the chirps from the database and order the chirps according to their createdAt timestamp. const [values, loading, error] = useCollectionData( query( collection(db, "chirps").withConverter(postConverter), orderBy("createdAt", "desc") ), { snapshotListenOptions: { includeMetadataChanges: true }, } ); if (error) { return <p>{error.message}</p>; } return ( <Box width="full" maxW="xl"> <CreateTweet /> {loading ? ( <VStack width="full" alignItems="flex-start" gap={2}> {Array(5) .fill("twitter-skeleton") .map((key, index) => ( <TweetCardSkeleton key={`${key}-${index + 1}`} /> ))} </VStack> ) : ( <VStack width="full" alignItems="flex-start" gap={2}> {values?.map((tweet) => ( <TweetCard key={tweet.id} tweet={tweet as Tweet} /> ))} </VStack> )} </Box> ); }; export default HomePage;
// https://codeforces.com/problemset/problem/1249/B1 // 1249B1 - Books Exchange (easy version) // The only difference between easy and hard versions is constraints. // There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the pi-th kid (in case of i=pi the kid will give his book to himself). It is guaranteed that all values of pi are distinct integers from 1 to n (i.e. p is a permutation). The sequence p doesn't change from day to day, it is fixed. // For example, if n=6 and p=[4,6,1,3,5,2] then at the end of the first day the book of the 1-st kid will belong to the 4-th kid, the 2-nd kid will belong to the 6-th kid and so on. At the end of the second day the book of the 1-st kid will belong to the 3-th kid, the 2-nd kid will belong to the 2-th kid and so on. // Your task is to determine the number of the day the book of the i-th child is returned back to him for the first time for every i from 1 to n. // Consider the following example: p=[5,1,2,4,3]. The book of the 1-st kid will be passed to the following kids: // • after the 1-st day it will belong to the 5-th kid, // • after the 2-nd day it will belong to the 3-rd kid, // • after the 3-rd day it will belong to the 2-nd kid, // • after the 4-th day it will belong to the 1-st kid, // So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day. // You have to answer q independent queries. // Input // The first line of the input contains one integer q (1≤q≤200) — the number of queries. Then q queries follow. // The first line of the query contains one integer n (1≤n≤200) — the number of kids in the query. The second line of the query contains n integers p1,p2,…,pn (1≤pi≤n, all pi are distinct, i.e. p is a permutation), where pi is the kid which will get the book of the i-th kid. // Output // The first line of the query contains one integer n (1≤n≤200) — the number of kids in the query. The second line of the query contains n integers p1,p2,…,pn (1≤pi≤n, all pi are distinct, i.e. p is a permutation), where pi is the kid which will get the book of the i-th kid. // Example // input // 6 // 5 // 1 2 3 4 5 // 3 // 2 3 1 // 6 // 4 6 2 1 5 3 // 1 // 1 // 4 // 3 4 1 2 // 5 // 5 1 2 4 3 // output // 1 1 1 1 1 // 3 3 3 // 2 3 3 2 1 3 // 1 // 2 2 2 2 // 4 4 4 1 4 // Tutorial // In this problem you just need to implement what is written in the problem statement. For the kid i the following pseudocode will calculate the answer (indices of the array p and its values are 0-indexed): // pos = p[i] // ans = 1 // while pos != i: // ans += 1 // pos = p[pos] package main import ( "bufio" "fmt" "os" ) func main() { var reader = bufio.NewReader(os.Stdin) var writer = bufio.NewWriter(os.Stdout) var t int var q, n, i, pos, ans uint var p []uint for t, _ = fmt.Fscan(reader, &q); t == 1; t, _ = fmt.Fscan(reader, &q) { for ; q > 0; q-- { fmt.Fscan(reader, &n) p = make([]uint, n) for i = 0; i < n; i++ { fmt.Fscan(reader, &p[i]) p[i]-- } for i = 0; i < n; i++ { pos = p[i] ans = 1 for pos != i { ans++ pos = p[pos] } fmt.Fprint(writer, ans) if i < n-1 { fmt.Fprint(writer, " ") } else { fmt.Fprintln(writer) } } } } writer.Flush() }
package com.ca.mfd.prc.pm.entity; import io.swagger.v3.oas.annotations.media.Schema; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.ca.mfd.prc.common.entity.BaseEntity; import com.ca.mfd.prc.common.constant.Constant; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.commons.lang3.StringUtils; /** * * @Description: BOP操作实体 * @author inkelink * @date 2023年11月24日 * @变更说明 BY inkelink At 2023年11月24日 */ @Data @EqualsAndHashCode(callSuper = true) @Schema(description= "BOP操作") @TableName("PRC_PM_BOP_OPER") public class PmBopOperEntity extends BaseEntity { /** * 主键 */ @Schema(title = "主键") @TableId(value = "PRC_PM_BOP_OPER_ID", type = IdType.INPUT) @JsonSerialize(using = ToStringSerializer.class) private Long id = Constant.DEFAULT_ID; /** * 车间编码 */ @Schema(title = "车间编码") @TableField("PRC_PM_WORKSHOP_CODE") private String workshopCode = StringUtils.EMPTY; /** * 分组编码 */ @Schema(title = "分组编码") @TableField("GROUP_CODE") private String groupCode = StringUtils.EMPTY; /** * 操作编码 */ @Schema(title = "操作编码") @TableField("OPER_CODE") private String operCode = StringUtils.EMPTY; /** * 操作名称 */ @Schema(title = "操作名称") @TableField("OPER_NAME") private String operName = StringUtils.EMPTY; /** * 备注 */ @Schema(title = "备注") @TableField("REMARK") private String remark = StringUtils.EMPTY; public String getGroupCodeForDc(){ return this.groupCode; } }
// Copyright 2023 Ant Group Co., Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package framework import ( "context" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/sets" pkgcontainer "github.com/secretflow/kuscia/pkg/agent/container" ) // NodeProvider is the interface used for registering a node and updating its // status in Kubernetes. // // Note: Implementers can choose to manage a node themselves, in which case // it is not needed to provide an implementation for this interface. type NodeProvider interface { // nolint:golint // Ping checks if the node is still active. // This is intended to be lightweight as it will be called periodically as a // heartbeat to keep the node marked as ready in Kubernetes. Ping(context.Context) error // ConfigureNode enables a provider to configure the node object that // will be used for Kubernetes. ConfigureNode(context.Context, string) *v1.Node // RefreshNodeStatus return if the node status changes RefreshNodeStatus(ctx context.Context, nodeStatus *v1.NodeStatus) bool // SetStatusUpdateCallback is used to asynchronously monitor the node. // The passed in callback should be called any time there is a change to the // node's status. // This will generally trigger a call to the Kubernetes API server to update // the status. // // SetStatusUpdateCallback should not block callers. SetStatusUpdateCallback(ctx context.Context, cb func(*v1.Node)) } // PodLifecycleHandler defines the interface used by the PodsController to react // to new and changed pods scheduled to the node that is being managed. type PodLifecycleHandler interface { SyncPod(ctx context.Context, pod *v1.Pod, podStatus *pkgcontainer.PodStatus, reasonCache *ReasonCache) error KillPod(ctx context.Context, pod *v1.Pod, runningPod pkgcontainer.Pod, gracePeriodOverride *int64) error // DeletePod Pod object in master is gone, so just delete pod in provider and no need to call NotifyPods // after deletion. DeletePod(ctx context.Context, pod *v1.Pod) error CleanupPods(ctx context.Context, pods []*v1.Pod, runningPods []*pkgcontainer.Pod, possiblyRunningPods map[types.UID]sets.Empty) error RefreshPodStatus(pod *v1.Pod, podStatus *v1.PodStatus) GetPodStatus(ctx context.Context, pod *v1.Pod) (*pkgcontainer.PodStatus, error) GetPods(ctx context.Context, all bool) ([]*pkgcontainer.Pod, error) // Start sync loop Start(ctx context.Context) error // Stop sync loop Stop() } type PodProvider interface { PodLifecycleHandler }
import express from 'express'; import { Author } from '../entities/Author'; import { Article } from '../entities/Article'; import defaultDataSource from '../datasource'; const router = express.Router(); interface CreateArticleParams { title: string; body: string; authorId: number; } interface UpdateArticleParams { title?: string; body?: string; authorId?: number; } // GET - info päring (kõik artiklid) router.get("/", async (req, res) => { try { // küsi artiklid andmebaasist const articles = await defaultDataSource.getRepository(Article).find(); // vasta artiklite kogumikuga JSON formaadis return res.status(200).json({ data: articles }); } catch (error) { console.log("ERROR", { message: error }); // vasta süsteemi veaga kui andmebaasipäringu jooksul ootamatu viga tekib return res.status(500).json({ message: "Could not fetch articles" }); } }); // POST - saadab infot router.post("/", async (req, res) => { try { const { title, body, authorId } = req.body as CreateArticleParams; // TODO: validate & santize if (!title || !body) { return res .status(400) .json({ error: "Articles has to have title and body" }); } // NOTE: võib tekkida probleeme kui ID väljale kaasa anda "undefined" väärtus // otsime üles autori kellel artikkel kuulub const author = await Author.findOneBy({id: authorId}); if(!author){ return res.status(400).json({ message: "Author with given ID not found" }); } // create new article with given parameters const article = Article.create({ title: title.trim() ?? "", body: body.trim() ?? "", authorId: author.id, // author: author, }); //save article to database const result = await article.save(); return res.status(200).json({ data: result }); } catch (error) { console.log("ERROR", { message: error }); // vasta süsteemi veaga kui andmebaasipäringu jooksul ootamatu viga tekib return res.status(500).json({ message: "Could not fetch articles" }); } }); // GET - info päring (üksik artikkel) router.get("/:id", async (req, res) => { try { const { id } = req.params; const article = await defaultDataSource .getRepository(Article) .findOneBy({ id: parseInt(id) }); return res.status(200).json({ data: article }); } catch (error) { console.log("ERROR", { message: error }); // vasta süsteemi veaga kui andmebaasipäringu jooksul ootamatu viga tekib return res.status(500).json({ message: "Could not fetch articles" }); } }); // PUT - update router.put("/:id", async (req, res) => { try { const { id } = req.params; const { title, body, authorId } = req.body as UpdateArticleParams; const article = await defaultDataSource .getRepository(Article) .findOneBy({ id: parseInt(id) }); if (!article) { return res.status(404).json({ error: "Article not found" }); } // uuendame andmed objektis (lokaalne muudatus) article.title = title ? title : article.title; article.body = body ? body : article.body; // otsime üles autori kellel artikkel kuulub if(authorId){ const author = await Author.findOneBy({id: authorId}); if(!author){ return res.status(400).json({ message: "Author with given ID not found" }); } article.authorId = author.id; } //salvestame muudatused andmebaasi const result = await article.save(); // saadame vastu uuendatud andmed (kui midagi töödeldakse serveris on seda vaja kuvada) return res.status(200).json({ data: result }); } catch (error) { console.log("ERROR", { message: error }); // vasta süsteemi veaga kui andmebaasipäringu jooksul ootamatu viga tekib return res.status(500).json({ message: "Could not update articles" }); } }); // DELETE - kustutamine router.delete("/:id", async(req, res) => { try { const { id } = req.params; const article = await defaultDataSource .getRepository(Article) .findOneBy({ id: parseInt(id) }); if (!article) { return res.status(404).json({ error: "Article not found" }); } const result = await article.remove(); // tagastame igaks juhuks kustutatud andmed return res.status(200).json({ data: result }); } catch (error) { console.log("ERROR", { message: error }); // vasta süsteemi veaga kui andmebaasipäringu jooksul ootamatu viga tekib return res.status(500).json({ message: "Could not update articles" }); } }); export default router;
<template> <div v-if="product.valueOf()" class="flex"> <div class="w-1/2 px-16"> <PhotoGalleryView /> </div> <div class="w-1/2 px-16"> <div class="divide-y divide-black divide-opacity-25"> <div class="m-4 mb-8"> <ProductTextDetailView :product="product.valueOf()" /> <div class="flex mt-8"> <div class="w-max mr-6"> <ContactDetail :userId="product.valueOf().ownerOfProductUserId" /> </div> <div class="h-36 w-full" v-if="locationPins.length > 0 && centerPin.valueOf()" > <LeafletMapComponent :pins="locationPins" :center="centerPin.valueOf()" :zoom="15" /> </div> </div> </div> <div> <div class="mt-8 flex justify-center"> <DatePickerComponent :date-picker-model="datePickerModel" ></DatePickerComponent> </div> <div class="mt-4 flex justify-center"> <PrimaryButton title="Anfrage stellen" @click="requestRent" /> </div> </div> </div> </div> </div> </template> <script lang="ts" setup> import ProductTextDetailView from "@/views/ProductTextDetailView.vue"; // @ is an alias to /src import LeafletMapComponent from "@/components/LeafletMapComponent.vue"; import ContactDetail from "@/components/ContactDetailView.vue"; import PhotoGalleryView from "@/views/PhotoGalleryView.vue"; import DatePickerComponent from "@/components/DatePickerComponent.vue"; import PrimaryButton from "@/uiElements/PrimaryButton.vue"; import { ProductModel } from "@/model/ProductModel"; import { watch } from "vue"; import { useRoute, useRouter } from "vue-router"; import { useRouteQueries } from "@/composables/useRouteQueries"; import { useLocationPins } from "@/composables/useLocationPins"; import { useDatePicker } from "@/composables/useDatePicker"; import { useProduct } from "@/composables/useProduct"; import { useRentRequest } from "@/composables/useRents"; import { useRoutes } from "@/composables/useRoutes"; import { useAnalytics } from "@/composables/useAnalytics"; const route = useRoute(); const router = useRouter(); const { productId } = useRouteQueries(route.query); const { product } = useProduct(productId); const { locationPins, centerPin, createLocationPins } = useLocationPins(); const { datePickerModel, updateDatePickerModel } = useDatePicker(); const { createRentRequest } = useRentRequest(); const { pushMyBookingsRoute } = useRoutes(router); watch(product, (newValue) => { if (newValue) { createLocationPins([newValue as ProductModel]); updateDatePickerModel(newValue as ProductModel); } }); async function requestRent() { const startDate = datePickerModel.value.pickedRange.start as Date; const endDate = datePickerModel.value.pickedRange.end as Date; if (product.value && startDate && endDate) { createRentRequest(startDate, endDate, product.value.id); pushMyBookingsRoute(); } } useAnalytics("Product Detail", "ProductDetailComponent.vue"); </script>
using FluentAssertions; using FormulaApp.Api.Controllers; using FormulaApp.Api.Models; using FormulaApp.Api.Services.Interfaces; using FormulaApp.UnitTests.Fixtures; using Microsoft.AspNetCore.Mvc; using Moq; namespace FormulaApp.UnitTests.Systems.Controllers; public class TestFansController { [Fact] public async Task Get_On_Success_ReturnStatusCode200() { var mockFanService = new Mock<IFanService>(); mockFanService.Setup(service => service.GetAllFans()).ReturnsAsync(FansFixtures.GetFans); var fansController = new FansController(mockFanService.Object); var result = (OkObjectResult) await fansController.Get(); result.StatusCode.Should().Be(200); } [Fact] public async Task Get_OnSuccess_InvokeService() { var mockFanService = new Mock<IFanService>(); mockFanService.Setup(service => service.GetAllFans()).ReturnsAsync(FansFixtures.GetFans); var fansController = new FansController(mockFanService.Object); var result = (OkObjectResult)await fansController.Get(); mockFanService.Verify(service => service.GetAllFans(), Times.Once); } [Fact] public async Task Get_OnSuccess_ReturnListOfFans() { var mockFanService = new Mock<IFanService>(); mockFanService.Setup(service => service.GetAllFans()).ReturnsAsync(FansFixtures.GetFans); var fansController = new FansController(mockFanService.Object); var result = (OkObjectResult)await fansController.Get(); result.Should().BeOfType<OkObjectResult>(); result.Value.Should().BeOfType<List<Fan>>(); } [Fact] public async Task Get_OnNoFans_ReturnNotFound() { var mockFanService = new Mock<IFanService>(); mockFanService.Setup(service => service.GetAllFans()).ReturnsAsync(new List<Fan>()); var fansController = new FansController(mockFanService.Object); var result = (NotFoundResult)await fansController.Get(); result.Should().BeOfType<NotFoundResult>(); } }
# Unveiling the World of DSA with C++ 🔍🔮 Hey there, fellow coding enthusiasts! 👋 Welcome to an exhilarating journey into the realm of Data Structures and Algorithms (DSA) using the power of C++. Today, I'm your guide on this exciting quest for knowledge and coding prowess. 🌟 ## Let's Dive In: Binary Search Implementation 🧐 Before we unravel the fascinating world of DSA, let me start with a classic: Binary Search. It's like a treasure hunt in a sorted list. Imagine you're searching for a specific item in a neatly organized library. Binary search helps you find that item quickly, even in a vast collection. ### Binary Search 1. **Take a Sorted List:** Imagine you have a list of items (e.g., numbers or words), and this list is neatly sorted from low to high. 2. **Start in the Middle:** Begin by looking at the item in the middle of the list. 3. **Compare with Your Target:** Check if this middle item is what you're looking for (your target). If it is, you're done! 4. **Narrow Down the Search:** If the middle item is smaller than your target, you can ignore everything to the left of it. If it's larger, you can ignore everything to the right of it. 5. **Repeat Until Found:** Keep repeating steps 2 to 4 until you either find your target or realize it's not in the list. ## Binary Search Implementation 🎯 Binary Search is like finding a hidden treasure in a library of sorted books. Here's how it works: Let me show it in action with some C++ magic: ```cpp #include <iostream> using namespace std; int binarySearch(int arr[], int n, int target) { int left = 0; int right = n - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; // Found it! } else if (arr[mid] < target) { left = mid + 1; // Adjust the left boundary } else { right = mid - 1; // Adjust the right boundary } } return -1; // Target not found } int main() { int arr[] = {2, 4, 6, 8, 10, 12, 14}; int n = sizeof(arr) / sizeof(arr[0]); int target = 10; int result = binarySearch(arr, n, target); if (result != -1) { cout << "Element found at index " << result << endl; } else { cout << "Element not found." << endl; } return 0; } ``` Binary search is a shining example of an efficient algorithm, especially for large datasets. It divides and conquers with remarkable speed, and understanding it is a must for any budding coder. ## Selection Sort Implementation 🎯 Now, let's tackle another vital concept: Selection Sort. Imagine you have a messy room, and you want to organize your books from smallest to largest. Selection sort is like picking the smallest book, putting it in its proper place, and repeating this process until everything is neat and tidy. Here's how you can implement it in C++: ```cpp #include <iostream> using namespace std; void selectionSort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; // Find the index of the smallest element } } // Swap the smallest element with arr[i] int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } } int main() { int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); selectionSort(arr, n); cout << "Sorted array: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; } ``` Selection sort may not be the fastest sorting algorithm, but it's simple to understand and implement. It's like tidying up your room one step at a time. ## Keep the Curiosity Burning 🔥 As we wrap up this chapter in our coding adventure, remember that every line of code you write is a step toward mastering DSA. Stay curious, experiment with different algorithms, and don't be afraid to make mistakes along the way. That's how we learn and grow. 🌱 In our next session, I will delve deeper into more DSA concepts, exploring data structures that will empower you to handle data like a coding wizard. Get ready for more coding magic! ✨📊 So, until then, happy coding, my folks! 🤓💻 ```
import { Inter } from 'next/font/google' import React, { useState } from 'react'; import { Button, Form, Input, Upload } from 'antd'; import { InboxOutlined } from '@ant-design/icons'; import { createAccount, setUserData, uploadImg } from '@/config/firebase'; import { useRouter } from 'next/router'; const inter = Inter({ subsets: ['latin'] }) const formItemLayout = { labelCol: { xs: { span: 24, }, sm: { span: 8, }, }, wrapperCol: { xs: { span: 24, }, sm: { span: 16, }, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 16, offset: 8, }, }, }; export default function Register() { const [form] = Form.useForm(); const [loading, setLoading] = useState(false) const router = useRouter() const onFinish = async (values) => { setLoading(true) try { const account = await createAccount(values.email, values.password) console.log('account-->', account) let userImg = '' if (values.dragger) { userImg = await uploadImg(values.dragger[0].originFileObj, account.user.uid) } console.log(userImg) const userInfo = values delete userInfo.password delete userInfo.dragger userInfo.uid = account.user.uid userInfo.profile = userImg ? userImg : '' await setUserData(userInfo) router.push('/chat') setLoading(false) } catch (err) { setLoading(false) alert(err) } }; const normFile = (e) => { console.log('Upload event:', e); if (Array.isArray(e)) { return e; } return e?.fileList; }; return ( <main className={`flex min-h-screen flex-col items-center justify-between p-24 ${inter.className}`} > <div className='bg-white rounded-md w-[500px] p-4'> <h3 className='text-center font-bold my-5'>Sign Up on Chat App </h3> <Form {...formItemLayout} form={form} name="register" onFinish={onFinish} style={{ maxWidth: 600, }} scrollToFirstError > <Form.Item name="email" label="E-mail" rules={[ { type: 'email', message: 'The input is not valid E-mail!', }, { required: true, message: 'Please input your E-mail!', }, ]} > <Input /> </Form.Item> <Form.Item name="password" label="Password" rules={[ { required: true, message: 'Please input your password!', }, ]} hasFeedback > <Input.Password /> </Form.Item> <Form.Item name="confirm" label="Confirm Password" dependencies={['password']} hasFeedback rules={[ { required: true, message: 'Please confirm your password!', }, ({ getFieldValue }) => ({ validator(_, value) { if (!value || getFieldValue('password') === value) { return Promise.resolve(); } return Promise.reject(new Error('The new password that you entered do not match!')); }, }), ]} > <Input.Password /> </Form.Item> <Form.Item name="nickname" label="Nickname" tooltip="What do you want others to call you?" rules={[ { required: true, message: 'Please input your nickname!', whitespace: true, }, ]} > <Input /> </Form.Item> <Form.Item name="intro" label="Intro" rules={[ { required: true, message: 'Please input Intro', }, ]} > <Input.TextArea showCount maxLength={100} /> </Form.Item> <Form.Item label="Dragger"> <Form.Item name="dragger" valuePropName="fileList" getValueFromEvent={normFile} noStyle> <Upload.Dragger name="files" action="/upload.do"> <p className="ant-upload-drag-icon"> <InboxOutlined /> </p> <p className="ant-upload-text">Click or drag file to this area to upload</p> <p className="ant-upload-hint">Support for a single or bulk upload.</p> </Upload.Dragger> </Form.Item> </Form.Item> <Form.Item {...tailFormItemLayout}> <Button loading={loading} htmlType="submit"> Register </Button> </Form.Item> </Form> </div> </main> ) }
import React, { FC } from "react"; import cn from "classnames"; import { ImageListItem } from "@mui/material"; import "./style.css"; import ImageMask from "./ImageMask"; interface IProps { key: any; src: string; chosen: boolean; setChosen: () => void; } const ImageItem: FC<IProps> = ({ key, src, chosen, setChosen }) => { const test = () => { setChosen(); console.log(`${key as string} clicked! now: ${String(chosen)}`); }; return ( <ImageListItem className={cn("image-item", { "image-chosen": chosen })}> <img src={src} loading="lazy" onClick={test} /> <ImageMask onClick={test} display={chosen} /> </ImageListItem> ); }; export default ImageItem;
import React, {useState} from "react"; import Breadcrumbs from "../breadcrumbs/breadcrumbs"; import CartItem from "../cart-item/cart-item"; import {useSelector} from "react-redux"; import {priceFormat, getSumWithCoupon} from "../../util"; import {PageTitle, AppRoute, Coupon} from "../../const"; import {Link} from "react-router-dom"; const Cart = () => { const {products} = useSelector((state) => state.CART); const [coupon, setCoupon] = useState(``); const [isCorrect, setIsCorrect] = useState(false); const [isWrongCoupon, setIsWrongCoupon] = useState(false); const couponList = Object.keys(Coupon); const handleCouponInput = (evt) => { setCoupon(evt.target.value.trim()); setIsWrongCoupon(false); setIsCorrect(false); } const handleCheckCoupon = (evt) => { evt.preventDefault(); const index = couponList.findIndex((item) => item === coupon); if (index !== -1) { setIsCorrect(true); } else { setIsWrongCoupon(true) } } let totalPrice = 0; products.map((item) => { return totalPrice = totalPrice + (item.price * item.count); }) if (isCorrect) { totalPrice = getSumWithCoupon(totalPrice, Coupon[coupon].maxPercent, Coupon[coupon].fixSum); } return <main className="page__main main"> <div className="main__wrapper"> <h1 className="main__title main__title--cart">{PageTitle.CART}</h1> <Breadcrumbs/> <div className="cart"> {(products.length > 0) && <> {products.map((product) => <CartItem product={product} key={`cart-${product.id}`}/>)} <div className="cart__footer"> <form className="cart__coupon coupon"> <p className="coupon__title">Промокод на скидку</p> <label className={`coupon__label ${isWrongCoupon ? `coupon__label--error` : ``}`}> {isWrongCoupon ? `Промокод не действителен` : `Введите свой промокод, если он у вас есть.`} </label> <input type="text" className="coupon__input" value={coupon} onChange={handleCouponInput} /> <button className="button coupon__button" onClick={handleCheckCoupon}>Применить купон </button> </form> <div className="cart__order-action"> <p className="cart__total-price">Всего: {priceFormat(totalPrice)} ₽</p> <button className="button button--action cart__order-button">Оформить заказ</button> </div> </div> </> } {(products.length === 0) && <> <p>Корзина пуста. Добавьте что-нибудь</p> <Link to={AppRoute.CATALOG} className="button button--action cart__order-button">Перейти в каталог</Link> </> } </div> </div> </main> } export default Cart;
import { Test, TestingModule } from '@nestjs/testing'; import { AuthResolver } from './auth.resolver'; import { AuthApplicationService } from '../application/auth-application.service'; import { describe } from 'node:test'; import { SigninUserInput } from './dto/signin-user.input'; import { SignupResponse } from './dto/signup-response'; import { SigninResponse } from './dto/signin-response'; import { User } from '../../users/infraestructure/user.entity'; describe('AuthResolver', () => { let resolver: AuthResolver; let authApplicationService: AuthApplicationService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ AuthResolver, { provide: AuthApplicationService, useValue: { signup: jest.fn(), signin: jest.fn(), }, }, ], }).compile(); resolver = module.get<AuthResolver>(AuthResolver); authApplicationService = module.get<AuthApplicationService>( AuthApplicationService, ); }); it('should be defined', () => { expect(resolver).toBeDefined(); }); describe('Signup test suit', () => { it('should return ok', async () => { const loginUserInputMock: SigninUserInput = { username: 'username', password: 'password', }; const SignUpResponseMock: SignupResponse = { username: 'username' }; jest .spyOn(authApplicationService, 'signup') .mockResolvedValue(SignUpResponseMock); const result = await resolver.signup(loginUserInputMock); expect(result).toBe(SignUpResponseMock); }); it('should return an error', async () => { const loginUserInputMock: SigninUserInput = { username: 'username', password: 'password', }; jest .spyOn(authApplicationService, 'signup') .mockRejectedValue(new Error('Some error')); await expect(resolver.signup(loginUserInputMock)).rejects.toThrow(Error); }); }); describe('Signin test suit', () => { it('should return ok', async () => { const loginUserInputMock: SigninUserInput = { username: 'someName', password: 'password', }; const SignInResponseMock: SigninResponse = { username: 'someName', access_token: 'ad1qwd1qw89dq5', }; const context = { user: { username: 'someName', }, }; jest .spyOn(authApplicationService, 'signin') .mockImplementation(async (user: User) => { return SignInResponseMock; }); const result = await resolver.signin(loginUserInputMock, context); expect(result).toBe(SignInResponseMock); }); it('should return an error', async () => { const loginUserInputMock: SigninUserInput = { username: 'someName', password: 'password', }; const context = { user: { username: 'someName', }, }; jest .spyOn(authApplicationService, 'signin') .mockRejectedValue(new Error('Some error')); await expect( resolver.signin(loginUserInputMock, context), ).rejects.toThrow(Error); }); }); });
import { useAppDispatch, useAppSelector } from 'hooks/redux'; import { IconClose } from 'icons'; import { GlobalMessageVariants } from 'models/IGlobalMessage'; import { useEffect } from 'react'; import { appSlice } from 'store/reducers/AppSlice'; import styles from './GlobalMessage.module.scss'; const GlobalMessage = () => { const { message, variant, isShowing } = useAppSelector( (state) => state.app.globalMessage ); const dispatch = useAppDispatch(); useEffect(() => { if (isShowing) { setTimeout(close, 3000); } }, [isShowing]); const close = () => { dispatch( appSlice.actions.setGlobalMessage({ message: '', variant: GlobalMessageVariants.success, isShowing: false, }) ); }; return isShowing ? ( <div className={[styles.container, styles[variant]].join(' ')}> <div className={styles.text}>{message}</div> <IconClose className={[styles.close_button, 'secondary-dark-icon'].join(' ')} size={18} onClick={close} /> </div> ) : null; }; export default GlobalMessage;
import React from 'react'; import classNames from 'classnames'; import { Typography, TypographyProps } from '../Typography/Typography.tsx'; import styles from './Title.module.css'; interface TitleProps extends TypographyProps { level?: '1' | '2' | '3'; } const Title = function ({ Component, level = '1', normalize, weight, className, ...restProps }: TitleProps) { if (!Component) { Component = `h${level}` as React.ElementType; } return ( <Typography Component={Component} weight={weight} normalize={normalize} className={classNames( className, level && { '1': styles['Title--level-1'], '2': styles['Title--level-3'], '3': styles['Title--level-2'], }[level], )} {...restProps} /> ); }; export type { TitleProps }; export { Title };
package main import ( "math" "time" ) type State struct { Name string ImageName string ImageLicense string ImageLicenseLink string WeatherAverages map[Season]WeatherAverages } type WeatherAverages struct { Temperature float64 Sunshine int Humidity int } type Season int const ( Summer = 0 + iota Autumn Winter Spring ) func GetSeason(datetime time.Time) Season { switch datetime.Month() { case time.March, time.April, time.May: return Spring case time.June, time.July, time.August: return Summer case time.September, time.October, time.November: return Autumn default: return Winter } } const tempRange float64 = 100 func (state *State) CompareWeather(conditions Conditions, season Season) float64 { averages := state.WeatherAverages[season] dtemp := math.Max(math.Abs(conditions.Temperature-averages.Temperature), tempRange) ntemp := dtemp / tempRange //Results will range from 0 to 1 (similarity) return ntemp } var States = [...]State{ {Name: "Alaska", ImageName: "alaska.jpg"}, }