text
stringlengths
184
4.48M
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ include file="/common/taglib.jsp"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Chỉnh sửa chủ đề</title> </head> <body> <c:url var="editsave" value="/quan-tri/web/ma-khuyen-mai/editsave" /> <c:url var="list" value="/quan-tri/web/ma-khuyen-mai" /> <form:form modelAttribute="coupon" action="${save}" method="POST"> <div class="content-wrapper pt-3"> <!-- Content Header (Page header) --> <!-- Main content --> <section class="content"> <!-- Default box --> <div class="card"> <div class="card-header"> <h3 class="card-title"> <strong class="text-uppercase text-danger">Thêm mã khuyến mãi mới</strong> </h3> <div class="card-tools"> <button type="submit" onclick="return confirm('Bạn có chắc chắn thực hiện không?');" class="btn btn-sm btn-success"> <i class="fas fa-save"></i> Lưu </button> <a class="btn btn-sm btn-danger" href="${list }"> Quay về danh sách</a> </div> </div> <div class="card-body"> <div class="row"> <div class="col-md-9"> <div class="form-group"> <label>Mã khuyến mãi</label> <form:input class="form-control" type="text" path="code" required="required" style="text-transform:uppercase" value="${ empty oldvalue.code ? '': oldvalue.code }" /> <c:if test="${ not empty msgTitle}"> <span class="form-error">${msgTitle}</span> </c:if> </div> <div class="form-group"> <label>Số lượng mã</label> <form:input class="form-control" type="number" path="available" required="required" /> </div> <div class="form-group"> <label>Số lượng mã</label> <form:input class="form-control" type="number" path="pricesale" required="required" /> </div> <div class="form-group"> <label>Trạng thái</label> <form:select name="status" class="form-control" path="status"> <form:option value="2" label="Chưa xuất bản"></form:option> <form:option value="1" label="Xuất bản"></form:option> </form:select> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>Bắt đầu khuyến mãi</label> <input class="form-control" type="date" name="start" value="${ couponitem.start}" /> </div> <div class="form-group"> <label>Hết hạn khuyến mãi</label> <input class="form-control" type="date" name="end" value="${ couponitem.end}" /> </div> </div> </div> </div> </div> <!-- /.card --> </section> <!-- /.content --> </div> </form:form> </body> </html>
<?php /** * WordPress Feed API * * Many of the functions used in here belong in The Loop, or The Loop for the * Feeds. * * @package WordPress * @subpackage Feed */ /** * RSS container for the bloginfo function. * * You can retrieve anything that you can using the get_bloginfo() function. * Everything will be stripped of tags and characters converted, when the values * are retrieved for use in the feeds. * * @since 1.5.1 * @see get_bloginfo() For the list of possible values to display. * * @param string $show See get_bloginfo() for possible values. * @return string */ function get_bloginfo_rss($show = '') { $info = strip_tags(get_bloginfo($show)); /** * Filter the bloginfo for use in RSS feeds. * * @since 2.2.0 * * @see convert_chars() * @see get_bloginfo() * * @param string $info Converted string value of the blog information. * @param string $show The type of blog information to retrieve. */ return apply_filters( 'get_bloginfo_rss', convert_chars( $info ), $show ); } /** * Display RSS container for the bloginfo function. * * You can retrieve anything that you can using the get_bloginfo() function. * Everything will be stripped of tags and characters converted, when the values * are retrieved for use in the feeds. * * @since 0.71 * @see get_bloginfo() For the list of possible values to display. * * @param string $show See get_bloginfo() for possible values. */ function bloginfo_rss($show = '') { /** * Filter the bloginfo for display in RSS feeds. * * @since 2.1.0 * * @see get_bloginfo() * * @param string $rss_container RSS container for the blog information. * @param string $show The type of blog information to retrieve. */ echo apply_filters( 'bloginfo_rss', get_bloginfo_rss( $show ), $show ); } /** * Retrieve the default feed. * * The default feed is 'rss2', unless a plugin changes it through the * 'default_feed' filter. * * @since 2.5.0 * * @return string Default feed, or for example 'rss2', 'atom', etc. */ function get_default_feed() { /** * Filter the default feed type. * * @since 2.5.0 * * @param string $feed_type Type of default feed. Possible values include 'rss2', 'atom'. * Default 'rss2'. */ $default_feed = apply_filters( 'default_feed', 'rss2' ); return 'rss' == $default_feed ? 'rss2' : $default_feed; } /** * Retrieve the blog title for the feed title. * * @since 2.2.0 * * @param string $sep Optional. How to separate the title. See wp_title() for more info. * @return string Error message on failure or blog title on success. */ function get_wp_title_rss( $sep = '&#187;' ) { $title = wp_title( $sep, false ); if ( is_wp_error( $title ) ) { return $title->get_error_message(); } if ( $title && $sep && ' ' !== substr( $title, 0, 1 ) ) { $title = " $sep " . $title; } /** * Filter the blog title for use as the feed title. * * @since 2.2.0 * * @param string $title The current blog title. * @param string $sep Separator used by wp_title(). */ $title = apply_filters( 'get_wp_title_rss', $title, $sep ); return $title; } /** * Display the blog title for display of the feed title. * * @since 2.2.0 * @see wp_title() $sep parameter usage. * * @param string $sep Optional. */ function wp_title_rss( $sep = '&#187;' ) { /** * Filter the blog title for display of the feed title. * * @since 2.2.0 * * @see get_wp_title_rss() * * @param string $wp_title The current blog title. * @param string $sep Separator used by wp_title(). */ echo apply_filters( 'wp_title_rss', get_wp_title_rss( $sep ), $sep ); } /** * Retrieve the current post title for the feed. * * @since 2.0.0 * * @return string Current post title. */ function get_the_title_rss() { $title = get_the_title(); /** * Filter the post title for use in a feed. * * @since 1.2.0 * * @param string $title The current post title. */ $title = apply_filters( 'the_title_rss', $title ); return $title; } /** * Display the post title in the feed. * * @since 0.71 */ function the_title_rss() { echo get_the_title_rss(); } /** * Retrieve the post content for feeds. * * @since 2.9.0 * @see get_the_content() * * @param string $feed_type The type of feed. rss2 | atom | rss | rdf * @return string The filtered content. */ function get_the_content_feed($feed_type = null) { if ( !$feed_type ) $feed_type = get_default_feed(); /** This filter is documented in wp-includes/post-template.php */ $content = apply_filters( 'the_content', get_the_content() ); $content = str_replace(']]>', ']]&gt;', $content); /** * Filter the post content for use in feeds. * * @since 2.9.0 * * @param string $content The current post content. * @param string $feed_type Type of feed. Possible values include 'rss2', 'atom'. * Default 'rss2'. */ return apply_filters( 'the_content_feed', $content, $feed_type ); } /** * Display the post content for feeds. * * @since 2.9.0 * * @param string $feed_type The type of feed. rss2 | atom | rss | rdf */ function the_content_feed($feed_type = null) { echo get_the_content_feed($feed_type); } /** * Display the post excerpt for the feed. * * @since 0.71 */ function the_excerpt_rss() { $output = get_the_excerpt(); /** * Filter the post excerpt for a feed. * * @since 1.2.0 * * @param string $output The current post excerpt. */ echo apply_filters( 'the_excerpt_rss', $output ); } /** * Display the permalink to the post for use in feeds. * * @since 2.3.0 */ function the_permalink_rss() { /** * Filter the permalink to the post for use in feeds. * * @since 2.3.0 * * @param string $post_permalink The current post permalink. */ echo esc_url( apply_filters( 'the_permalink_rss', get_permalink() ) ); } /** * Outputs the link to the comments for the current post in an xml safe way * * @since 3.0.0 * @return none */ function comments_link_feed() { /** * Filter the comments permalink for the current post. * * @since 3.6.0 * * @param string $comment_permalink The current comment permalink with * '#comments' appended. */ echo esc_url( apply_filters( 'comments_link_feed', get_comments_link() ) ); } /** * Display the feed GUID for the current comment. * * @since 2.5.0 * * @param int|object $comment_id Optional comment object or id. Defaults to global comment object. */ function comment_guid($comment_id = null) { echo esc_url( get_comment_guid($comment_id) ); } /** * Retrieve the feed GUID for the current comment. * * @since 2.5.0 * * @param int|object $comment_id Optional comment object or id. Defaults to global comment object. * @return false|string false on failure or guid for comment on success. */ function get_comment_guid($comment_id = null) { $comment = get_comment($comment_id); if ( !is_object($comment) ) return false; return get_the_guid($comment->comment_post_ID) . '#comment-' . $comment->comment_ID; } /** * Display the link to the comments. * * @since 1.5.0 */ function comment_link() { /** * Filter the current comment's permalink. * * @since 3.6.0 * * @see get_comment_link() * * @param string $comment_permalink The current comment permalink. */ echo esc_url( apply_filters( 'comment_link', get_comment_link() ) ); } /** * Retrieve the current comment author for use in the feeds. * * @since 2.0.0 * * @return string Comment Author */ function get_comment_author_rss() { /** * Filter the current comment author for use in a feed. * * @since 1.5.0 * * @see get_comment_author() * * @param string $comment_author The current comment author. */ return apply_filters( 'comment_author_rss', get_comment_author() ); } /** * Display the current comment author in the feed. * * @since 1.0.0 */ function comment_author_rss() { echo get_comment_author_rss(); } /** * Display the current comment content for use in the feeds. * * @since 1.0.0 */ function comment_text_rss() { $comment_text = get_comment_text(); /** * Filter the current comment content for use in a feed. * * @since 1.5.0 * * @param string $comment_text The content of the current comment. */ $comment_text = apply_filters( 'comment_text_rss', $comment_text ); echo $comment_text; } /** * Retrieve all of the post categories, formatted for use in feeds. * * All of the categories for the current post in the feed loop, will be * retrieved and have feed markup added, so that they can easily be added to the * RSS2, Atom, or RSS1 and RSS0.91 RDF feeds. * * @since 2.1.0 * * @param string $type Optional, default is the type returned by get_default_feed(). * @return string All of the post categories for displaying in the feed. */ function get_the_category_rss($type = null) { if ( empty($type) ) $type = get_default_feed(); $categories = get_the_category(); $tags = get_the_tags(); $the_list = ''; $cat_names = array(); $filter = 'rss'; if ( 'atom' == $type ) $filter = 'raw'; if ( !empty($categories) ) foreach ( (array) $categories as $category ) { $cat_names[] = sanitize_term_field('name', $category->name, $category->term_id, 'category', $filter); } if ( !empty($tags) ) foreach ( (array) $tags as $tag ) { $cat_names[] = sanitize_term_field('name', $tag->name, $tag->term_id, 'post_tag', $filter); } $cat_names = array_unique($cat_names); foreach ( $cat_names as $cat_name ) { if ( 'rdf' == $type ) $the_list .= "\t\t<dc:subject><![CDATA[$cat_name]]></dc:subject>\n"; elseif ( 'atom' == $type ) $the_list .= sprintf( '<category scheme="%1$s" term="%2$s" />', esc_attr( get_bloginfo_rss( 'url' ) ), esc_attr( $cat_name ) ); else $the_list .= "\t\t<category><![CDATA[" . @html_entity_decode( $cat_name, ENT_COMPAT, get_option('blog_charset') ) . "]]></category>\n"; } /** * Filter all of the post categories for display in a feed. * * @since 1.2.0 * * @param string $the_list All of the RSS post categories. * @param string $type Type of feed. Possible values include 'rss2', 'atom'. * Default 'rss2'. */ return apply_filters( 'the_category_rss', $the_list, $type ); } /** * Display the post categories in the feed. * * @since 0.71 * @see get_the_category_rss() For better explanation. * * @param string $type Optional, default is the type returned by get_default_feed(). */ function the_category_rss($type = null) { echo get_the_category_rss($type); } /** * Display the HTML type based on the blog setting. * * The two possible values are either 'xhtml' or 'html'. * * @since 2.2.0 */ function html_type_rss() { $type = get_bloginfo('html_type'); if (strpos($type, 'xhtml') !== false) $type = 'xhtml'; else $type = 'html'; echo $type; } /** * Display the rss enclosure for the current post. * * Uses the global $post to check whether the post requires a password and if * the user has the password for the post. If not then it will return before * displaying. * * Also uses the function get_post_custom() to get the post's 'enclosure' * metadata field and parses the value to display the enclosure(s). The * enclosure(s) consist of enclosure HTML tag(s) with a URI and other * attributes. * * @since 1.5.0 */ function rss_enclosure() { if ( post_password_required() ) return; foreach ( (array) get_post_custom() as $key => $val) { if ($key == 'enclosure') { foreach ( (array) $val as $enc ) { $enclosure = explode("\n", $enc); // only get the first element, e.g. audio/mpeg from 'audio/mpeg mpga mp2 mp3' $t = preg_split('/[ \t]/', trim($enclosure[2]) ); $type = $t[0]; /** * Filter the RSS enclosure HTML link tag for the current post. * * @since 2.2.0 * * @param string $html_link_tag The HTML link tag with a URI and other attributes. */ echo apply_filters( 'rss_enclosure', '<enclosure url="' . trim( htmlspecialchars( $enclosure[0] ) ) . '" length="' . trim( $enclosure[1] ) . '" type="' . $type . '" />' . "\n" ); } } } } /** * Display the atom enclosure for the current post. * * Uses the global $post to check whether the post requires a password and if * the user has the password for the post. If not then it will return before * displaying. * * Also uses the function get_post_custom() to get the post's 'enclosure' * metadata field and parses the value to display the enclosure(s). The * enclosure(s) consist of link HTML tag(s) with a URI and other attributes. * * @since 2.2.0 */ function atom_enclosure() { if ( post_password_required() ) return; foreach ( (array) get_post_custom() as $key => $val ) { if ($key == 'enclosure') { foreach ( (array) $val as $enc ) { $enclosure = explode("\n", $enc); /** * Filter the atom enclosure HTML link tag for the current post. * * @since 2.2.0 * * @param string $html_link_tag The HTML link tag with a URI and other attributes. */ echo apply_filters( 'atom_enclosure', '<link href="' . trim( htmlspecialchars( $enclosure[0] ) ) . '" rel="enclosure" length="' . trim( $enclosure[1] ) . '" type="' . trim( $enclosure[2] ) . '" />' . "\n" ); } } } } /** * Determine the type of a string of data with the data formatted. * * Tell whether the type is text, html, or xhtml, per RFC 4287 section 3.1. * * In the case of WordPress, text is defined as containing no markup, * xhtml is defined as "well formed", and html as tag soup (i.e., the rest). * * Container div tags are added to xhtml values, per section 3.1.1.3. * * @link http://www.atomenabled.org/developers/syndication/atom-format-spec.php#rfc.section.3.1 * * @since 2.5.0 * * @param string $data Input string * @return array array(type, value) */ function prep_atom_text_construct($data) { if (strpos($data, '<') === false && strpos($data, '&') === false) { return array('text', $data); } $parser = xml_parser_create(); xml_parse($parser, '<div>' . $data . '</div>', true); $code = xml_get_error_code($parser); xml_parser_free($parser); if (!$code) { if (strpos($data, '<') === false) { return array('text', $data); } else { $data = "<div xmlns='http://www.w3.org/1999/xhtml'>$data</div>"; return array('xhtml', $data); } } if (strpos($data, ']]>') === false) { return array('html', "<![CDATA[$data]]>"); } else { return array('html', htmlspecialchars($data)); } } /** * Displays Site Icon in atom feeds. * * @since 4.3.0 * * @see get_site_icon_url() */ function atom_site_icon() { $url = get_site_icon_url( 32 ); if ( $url ) { echo "<icon>$url</icon>\n"; } } /** * Displays Site Icon in RSS2. * * @since 4.3.0 */ function rss2_site_icon() { $rss_title = get_wp_title_rss(); if ( empty( $rss_title ) ) { $rss_title = get_bloginfo_rss( 'name' ); } $url = get_site_icon_url( 32 ); if ( $url ) { echo ' <image> <url>' . convert_chars( $url ) . '</url> <title>' . $rss_title . '</title> <link>' . get_bloginfo_rss( 'url' ) . '</link> <width>32</width> <height>32</height> </image> ' . "\n"; } } /** * Display the link for the currently displayed feed in a XSS safe way. * * Generate a correct link for the atom:self element. * * @since 2.5.0 */ function self_link() { $host = @parse_url(home_url()); /** * Filter the current feed URL. * * @since 3.6.0 * * @see set_url_scheme() * @see wp_unslash() * * @param string $feed_link The link for the feed with set URL scheme. */ echo esc_url( apply_filters( 'self_link', set_url_scheme( 'http://' . $host['host'] . wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ); } /** * Return the content type for specified feed type. * * @since 2.8.0 */ function feed_content_type( $type = '' ) { if ( empty($type) ) $type = get_default_feed(); $types = array( 'rss' => 'application/rss+xml', 'rss2' => 'application/rss+xml', 'rss-http' => 'text/xml', 'atom' => 'application/atom+xml', 'rdf' => 'application/rdf+xml' ); $content_type = ( !empty($types[$type]) ) ? $types[$type] : 'application/octet-stream'; /** * Filter the content type for a specific feed type. * * @since 2.8.0 * * @param string $content_type Content type indicating the type of data that a feed contains. * @param string $type Type of feed. Possible values include 'rss2', 'atom'. * Default 'rss2'. */ return apply_filters( 'feed_content_type', $content_type, $type ); } /** * Build SimplePie object based on RSS or Atom feed from URL. * * @since 2.8.0 * * @param mixed $url URL of feed to retrieve. If an array of URLs, the feeds are merged * using SimplePie's multifeed feature. * See also {@link ​http://simplepie.org/wiki/faq/typical_multifeed_gotchas} * * @return WP_Error|SimplePie WP_Error object on failure or SimplePie object on success */ function fetch_feed( $url ) { require_once( ABSPATH . WPINC . '/class-feed.php' ); $feed = new SimplePie(); $feed->set_sanitize_class( 'WP_SimplePie_Sanitize_KSES' ); // We must manually overwrite $feed->sanitize because SimplePie's // constructor sets it before we have a chance to set the sanitization class $feed->sanitize = new WP_SimplePie_Sanitize_KSES(); $feed->set_cache_class( 'WP_Feed_Cache' ); $feed->set_file_class( 'WP_SimplePie_File' ); $feed->set_feed_url( $url ); /** This filter is documented in wp-includes/class-feed.php */ $feed->set_cache_duration( apply_filters( 'wp_feed_cache_transient_lifetime', 12 * HOUR_IN_SECONDS, $url ) ); /** * Fires just before processing the SimplePie feed object. * * @since 3.0.0 * * @param object &$feed SimplePie feed object, passed by reference. * @param mixed $url URL of feed to retrieve. If an array of URLs, the feeds are merged. */ do_action_ref_array( 'wp_feed_options', array( &$feed, $url ) ); $feed->init(); $feed->set_output_encoding( get_option( 'blog_charset' ) ); $feed->handle_content_type(); if ( $feed->error() ) return new WP_Error( 'simplepie-error', $feed->error() ); return $feed; }
//contracts/EVRYDistributor.sol // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract EVRYDistributor is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public evry; uint256 public cap; uint256 public released; constructor( IERC20 _evry, uint256 _cap ) { evry = _evry; cap = _cap; } function release(uint256 amount) external nonReentrant onlyOwner returns (uint256) { uint256 releasedAmount = amount; uint256 evryBalance = evry.balanceOf(address(this)); if (released.add(amount) >= cap) { releasedAmount = cap.sub(released); } if (releasedAmount > evryBalance) { releasedAmount = evryBalance; } released = released.add(releasedAmount); evry.safeTransfer(msg.sender, releasedAmount); return releasedAmount; } }
import { render, screen } from "@testing-library/react"; import AirButton from "../components/AirButton/AirButton"; import { FcGoogle } from "react-icons/fc"; import { axe } from "jest-axe"; describe("AirButton", () => { test("Should render component correctly.", () => { const { container } = render( <AirButton onClick={jest.fn()}>Airbnb</AirButton> ); expect(container.firstChild).toMatchSnapshot(); }); describe("Accessibility", () => { test("Should have no accessibility violations.", async () => { const { container } = render( <AirButton onClick={jest.fn()}>Airbnb</AirButton> ); const results = await axe(container); expect(results).toHaveNoViolations(); }); }); describe("Interaction", () => { test("Should trigger onClick when clicked", () => { const onClick = jest.fn(); render(<AirButton onClick={onClick}>Airbnb</AirButton>); screen.getByRole("button", { name: "Airbnb" }).click(); expect(onClick).toHaveBeenCalledTimes(1); }); }); describe("Props", () => { test("Should render children correctly", () => { render(<AirButton onClick={jest.fn()}>Airbnb</AirButton>); expect( screen.getByRole("button", { name: "Airbnb" }) ).toBeInTheDocument(); }); test("Should render disabled prop correctly", () => { render( <AirButton disabled onClick={jest.fn()}> Airbnb </AirButton> ); expect(screen.getByRole("button", { name: "Airbnb" })).toHaveAttribute( "disabled" ); }); test("Should render outline prop correctly", () => { render( <AirButton onClick={jest.fn()} outline> Airbnb </AirButton> ); expect(screen.getByRole("button", { name: "Airbnb" })).toHaveClass( "bg-white" ); }); test("Should render small prop correctly", () => { render( <AirButton onClick={jest.fn()} small> Airbnb </AirButton> ); expect(screen.getByRole("button", { name: "Airbnb" })).toHaveClass( "text-sm" ); }); test("Should render icon prop correctly", () => { render( <AirButton onClick={jest.fn()} icon={FcGoogle}> Airbnb </AirButton> ); expect(screen.getByRole("img")).toBeInTheDocument(); }); test("Should render small icon prop correctly", () => { render( <AirButton onClick={jest.fn()} icon={FcGoogle} small> Airbnb </AirButton> ); expect(screen.getByRole("img")).toHaveClass("top-0"); }); }); });
import React from 'react'; import { ChevronDown, ChevronUp } from '../icons'; import { removeItem, increase, decrease } from '../features/cart/cartSlice'; import { useDispatch } from 'react-redux'; // go to the CartContainer and import this file const CartItem = ({id, title, price, img, amount}) => { // so we destructure the props from the chevronDown and up const dispatch = useDispatch(); return ( <article className='cart-item'> <img src={img} alt={title}/> <div> <h4>{title}</h4> <h4 className='item-price'>${price}</h4> <button className='remove-btn' onClick={()=> dispatch(removeItem(id))}>remove</button> </div> {/* now we wanna set-up the buttons to increase or decrease right after the div we will but a <p> in between */} <div> <button className='amount-btn' onClick={()=> dispatch(increase({id}))}> <ChevronUp/> </button> <p className='amount'>{amount}</p> <button className='amount-btn' onClick={()=> { if (amount === 1) { dispatch(removeItem(id)); // so wen we click on the decrease button below 1 it removes the item from the cart return; // we pass in the return below because we don't want to continue reading the code } dispatch(decrease({id}))} }> {/* with the onClick feature we added for the decrease, we discover that we're going negative sp lets fix that by tieing it to the {amount}*/} <ChevronDown/> </button> </div> </article> ) } export default CartItem
#pragma once #include "pch.h" namespace SDKSample { namespace BluetoothGattHeartRate { public ref class HeartRateMeasurement sealed { public: property uint16 HeartRateValue { uint16 get() { return heartRateValue; } void set(uint16 value) { heartRateValue = value; } } property uint16 ExpendedEnergy { uint16 get() { return expendedEnergy; } void set(uint16 value) { expendedEnergy = value; } } property Windows::Foundation::DateTime Timestamp { Windows::Foundation::DateTime get() { return timestamp; } void set(Windows::Foundation::DateTime value) { timestamp = value; } } public: Platform::String^ GetDescription() { std::wstringstream wss; auto timeFormatter = ref new Windows::Globalization::DateTimeFormatting::DateTimeFormatter("longtime"); auto dateFormatter = ref new Windows::Globalization::DateTimeFormatting::DateTimeFormatter("longdate"); wss << HeartRateValue << L" bpm @ " << timeFormatter->Format(Timestamp)->Data() << dateFormatter->Format(Timestamp)->Data(); return ref new Platform::String(wss.str().c_str()); } private: uint16 heartRateValue; uint16 expendedEnergy; Windows::Foundation::DateTime timestamp; }; public delegate void ValueChangeCompletedHandler(HeartRateMeasurement^ heartRateMeasurement); public ref class HeartRateService sealed { public: event ValueChangeCompletedHandler^ ValueChangeCompleted; static property HeartRateService^ Instance { HeartRateService^ get() { if (instance == nullptr) { instance = ref new HeartRateService(); } return instance; } } property bool IsServiceInitialized { bool get() { return isServiceInitialized; } void set(bool value) { isServiceInitialized = value; } } property Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService^ Service { Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService^ get() { return service; } void set(Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService^ value) { service = value; } } property Windows::Foundation::Collections::IVectorView<HeartRateMeasurement^>^ DataPoints { Windows::Foundation::Collections::IVectorView<HeartRateMeasurement^>^ get() { auto retval = ref new Platform::Collections::Vector<HeartRateMeasurement^>(); // Obtain a RAII lock from dataLock concurrency::reader_writer_lock::scoped_lock_read lock(dataLock); // Create a snapshot of the data values for (auto it = begin(datapoints); it != end(datapoints); it++) { retval->Append(*it); } return retval->GetView(); } } public: virtual ~HeartRateService(); void InitializeHeartRateServices(); Platform::String^ ProcessBodySensorLocationData(const Platform::Array<unsigned char>^ bodySensorLocationData); private: HeartRateService(); void App_Resuming(Platform::Object^ sender, Platform::Object^ e); void App_Suspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e); HeartRateMeasurement^ ProcessHeartRateMeasurementData( Platform::Array<unsigned char>^ heartRateMeasurementData); void HeartRateMeasurementCharacteristic_ValueChanged( Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic^ sender, Windows::Devices::Bluetooth::GenericAttributeProfile::GattValueChangedEventArgs^ args); static HeartRateService^ instance; bool isServiceInitialized; Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService^ service; Platform::Collections::Vector<HeartRateMeasurement^>^ datapoints; concurrency::reader_writer_lock dataLock; }; }; };
package com.hcmute.yourtours.factories.rule_home_categories; import com.hcmute.yourtours.entities.RuleHomeCategoriesCommand; import com.hcmute.yourtours.exceptions.YourToursErrorCode; import com.hcmute.yourtours.libs.exceptions.InvalidException; import com.hcmute.yourtours.libs.factory.BasePersistDataFactory; import com.hcmute.yourtours.models.rule_home_categories.RuleHomeCategoryDetail; import com.hcmute.yourtours.models.rule_home_categories.RuleHomeCategoryInfo; import com.hcmute.yourtours.repositories.RuleHomeCategoriesRepository; import org.springframework.lang.NonNull; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; import java.util.UUID; @Service @Transactional public class RuleHomeCategoriesFactory extends BasePersistDataFactory<UUID, RuleHomeCategoryInfo, RuleHomeCategoryDetail, Long, RuleHomeCategoriesCommand> implements IRuleHomeCategoriesFactory { private final RuleHomeCategoriesRepository ruleHomeCategoriesRepository; protected RuleHomeCategoriesFactory(RuleHomeCategoriesRepository repository) { super(repository); this.ruleHomeCategoriesRepository = repository; } @Override @NonNull protected Class<RuleHomeCategoryDetail> getDetailClass() { return RuleHomeCategoryDetail.class; } @Override public RuleHomeCategoriesCommand createConvertToEntity(RuleHomeCategoryDetail detail) { if (detail == null) { return null; } return RuleHomeCategoriesCommand.builder() .name(detail.getName()) .description(detail.getDescription()) .status(detail.getStatus()) .build(); } @Override public void updateConvertToEntity(RuleHomeCategoriesCommand entity, RuleHomeCategoryDetail detail) { entity.setName(detail.getName()); entity.setDescription(detail.getDescription()); entity.setStatus(detail.getStatus()); } @Override public RuleHomeCategoryDetail convertToDetail(RuleHomeCategoriesCommand entity) { if (entity == null) { return null; } return RuleHomeCategoryDetail.builder() .id(entity.getRuleCategoryId()) .name(entity.getName()) .description(entity.getDescription()) .status(entity.getStatus()) .build(); } @Override public RuleHomeCategoryInfo convertToInfo(RuleHomeCategoriesCommand entity) { if (entity == null) { return null; } return RuleHomeCategoryInfo.builder() .id(entity.getRuleCategoryId()) .name(entity.getName()) .description(entity.getDescription()) .status(entity.getStatus()) .build(); } @Override protected Long convertId(UUID id) throws InvalidException { Optional<RuleHomeCategoriesCommand> optional = ruleHomeCategoriesRepository.findByRuleCategoryId(id); if (optional.isEmpty()) { throw new InvalidException(YourToursErrorCode.NOT_FOUND_RULE_CATEGORIES); } return optional.get().getId(); } }
import { useState } from "react"; import { useAppDispatch } from "../../helper/reduxHooks"; import { RoomUsers, Users } from "../../pages/group"; import { startGroupChat } from "../../services/chat"; import { modalActions } from "../../store/reducer/modalSlice"; interface Props { users: UserInfo[]; } interface UserInfo { opponentUid: string; displayName: string; } const InviteModal = ({ users }: Props) => { const [checkedList, setCheckedList] = useState<UserInfo[]>([]); const [isChecked, setIsChecked] = useState<boolean>(false); const dispatch = useAppDispatch(); const checkedItemHandler = (isChecked: boolean, user: UserInfo): void => { if (isChecked) { setCheckedList(prev => [...prev, user]); return; } if (!isChecked && checkedList.includes(user)) { setCheckedList(checkedList.filter(el => el !== user)); return; } }; const checkHandler = ( e: React.ChangeEvent<HTMLInputElement>, user: UserInfo ): void => { setIsChecked(!isChecked); checkedItemHandler(e.target.checked, user); }; const cancellClickHandler = (): void => { dispatch(modalActions.inviteModalClose()); }; const inviteClickHandler = async () => { startGroupChat(checkedList); dispatch(modalActions.inviteModalClose()); }; if (users.length === 0) { return ( <div className="bg-white absolute top-[50px] right-2 w-56 h-[50%] rounded-[9px] p-3"> <div className="h-[90%] flex justify-center items-center"> <span className="text-sm">등록된 유저가 없습니다.</span> </div> <div className="w-full flex justify-center"> <button className="w-full bg-[#0940af] text-white rounded-[8px]" onClick={cancellClickHandler} > 취소 </button> </div> </div> ); } return ( <div className="bg-white absolute top-[50px] right-2 w-56 h-[50%] rounded-[9px] p-3 flex-col justify-between"> <div className="h-[90%] overflow-y-auto p-2"> {users.map((user: UserInfo, index: number) => ( <div key={index} className="w-full flex mb-4 items-center"> <div> <input type="checkbox" onChange={e => checkHandler(e, user)} /> </div> <div className="pl-3"> <span>{user.displayName}</span> </div> </div> ))} </div> <div className="w-full flex justify-between"> <button className="w-[40%] bg-[#9E9E9E] text-white rounded-[8px]" onClick={cancellClickHandler} > 취소 </button> <button className="w-[40%] bg-[#0940af] text-white rounded-[8px]" onClick={inviteClickHandler} > 초대 </button> </div> </div> ); }; export default InviteModal;
--- bookHidden: false bookSearchExclude: false weight: 20 title: "M4 Reserving Claim Amounts" subtitle: "Topics in Insurance, Risk, and Finance [^1]" author: "Professor Benjamin Avanzi" institute: | ![](../../../../static/img/PRIMARY_A_Vertical_Housed_RGB.png){width=1.2in} date: '27 August 2023' output: beamer_presentation: toc: true number_sections: true df_print: kable slide_level: 3 theme: "CambridgeUS" colortheme: "dolphin" fonttheme: "default" bibliography: ../../../../static/libraries.bib header-includes: - \graphicspath{{../../../../static/}} - \usepackage{color} - \usepackage{hyperref} - \usepackage{marvosym} - \usepackage{amsmath} - \usepackage{amsthm} - \usepackage{amsfonts} - \usepackage{array} - \usepackage{booktabs} - \usepackage{verbatim} - \usepackage[english]{varioref} - \usepackage{natbib} - \usepackage{actuarialangle} - \usepackage{pgfpages} - \pgfdeclareimage[height=1cm]{university-logo}{../../../../static/img/PRIMARY_A_Vertical_Housed_RGB.png} - \pgfdeclareimage[height=2.5cm]{university-logo2}{../../../../static/img/PRIMARY_A_Vertical_Housed_RGB.png} - \logo{\raisebox{-3ex}[0pt]{\pgfuseimage{university-logo}}} - \AtBeginSection[]{ \begin{frame} \tableofcontents[sectionstyle=show/shaded,subsectionstyle=hide/hide/hide] \end{frame} \addtocounter{framenumber}{-1}} - \AtBeginSubsection[]{ \begin{frame} \tableofcontents[sectionstyle=show/hide,subsectionstyle=show/shaded/hide] \end{frame} \addtocounter{framenumber}{-1}} # to remove this you need to also change "slide_level" to 2 - \definecolor{DolphinBlue}{RGB}{51,44,159} - \setbeamerfont{section in toc}{size=\normalsize} - \setbeamerfont{subsection in toc}{size=\normalsize} - \pretocmd{\tableofcontents}{\setlength{\parskip}{.2em}}{}{} - \setbeamertemplate{footline}{\hspace*{.4em} \raisebox{1.5ex}[0pt]{\textcolor{DolphinBlue}{\insertframenumber/\inserttotalframenumber}}} #- \setbeamertemplate{footline}{\hspace*{.4em} \raisebox{1.5ex}[0pt]{\textcolor{DolphinBlue}{\insertframenumber}}} #- \apptocmd{\tableofcontents}{\linespread{1.0}}{}{} # - \setbeamerfont{subsubsection in toc}{size=fontsize} - \newcommand{\adv}{$\maltese$} classoption: t,handout --- # Case estimation (3.1) ## Case estimates: Definition - When a claim is notified, the insurer’s employee who manages the claim (the “claims adjuster”) typically formulates an estimate of the (remaining) cost of the claim and records it in the system. - This estimate is typically adjusted over time as payments are made and additional information becomes available. - These is called a “**case estimate**” (equivalently, “individual estimate”, “manual estimate”, “physical estimate”). - This is contrast to an “**aggregate estimate**”, which would be inferred from past data, and some sort of statistical (reserving) procedure. ## Two approaches You can think of the evolution of a claim costs as two parallel paths; consider those two examples (Figure 2 of Avanzi, Taylor, and Wang (2023)): <img src="claim_history.png" width="100%" style="display: block; margin: auto;" /> ------------------------------------------------------------------------ - Contrary to the evolution of aggregate payments (which lead to the “aggregate estimate”), “incurred” estimates are meant to be centered around the expected ultimate cost from the start. Remember they are defined as `$$I(i,j) = D(i,j) + Q(i,j),$$` where `\(D(i,j)\)` are cumulative payments up to time `\(j\)`, and `\(Q(i,j)\)` is the case estimate at that same time. - The “good” thing about case estimates is that they are specific to the claim, and are an educated, intelligent guess of the cost of them, rather than a cold, myopic statistical estimate. - The “bad” thing is that they are very subjective, and are subject to (potentially dangerous) systematic biases. So which one should you use? ## Proposition 3.1 Quote from Taylor (2000): 1) When outstanding loss liability is to be estimated in respect of a **large number of claims**, an **aggregate estimate** will usually exhibit performance, as measured by the relative error, superior to that of case estimates. 2) When the liability is to be estimated in respect of a **small number of claims**, superior performance will usually be exhibited by **case estimates corrected for bias**.” This is discussed/applied in Section 4.4 of Taylor (2000) (outside scope). # Chain ladder (3.2) ## Introduction - We used chain ladder for claim counts in Module 3. - We can use it for forecasting other variables `\(Y(i,\cdot)\)` which can be expressed in the cross-classified structure (i.e. `\(i\times j\)` ) in much the same way, from a triangle of aggregate quantities `$$Y(i,j) = \sum_{m=0}^j X(i,m),$$` where `\(X(i,j)\)` are observed (incremental) quantities in cell `\((i,j)\)`. - Assumptions of proportionality can be made in much the same way, and the method applies in much the same way. - Note that you can apply this on either paid or incurred losses (that is, `\(X\)` would be either paid losses or incurred losses), as discussed in the following two subsections. - Applications are quite wide and apply in a range of contexts and fields! ## Chain ladder on paid losses ### Unadjusted chain ladder - We focus on paid losses, that is, $$ X(i,j) = C(i,j).$$ - Hence `\(\hat{Y}(i,j)\)` will yield estimates of future loss payments in future cells `\((i,j)\)`. - Everything else is the same as before. ### Example - See the spreadsheet [`Chapter3.xlsx`](https://canvas.lms.unimelb.edu.au/courses/191080/modules/items/5080918) for details of the calculations. The first tab sets out payment data corresponding to the example we studied in Module 3. - Table 3.1-3.3 demonstrate how chain ladder can be used on payment data, in absence of inflation adjusment. ### Inflation adjusted chain ladder - We are now dealing with payment data, which is typically distorted by inflation. This cannot be ignored. - Not adjusting the data corresponds to making a rather strong assumption about inflation, as explained below. - Remember that the asterisk `\(*\)` denoted claims data brought back/forward to some reference date, and that the quantities without `\(*\)` were nominal amounts. ------------------------------------------------------------------------ - Assuming the multiplicative structure of the chain ladder model, if $$ E\left[ C^*(i,j) \right] = \alpha^*(i) \mu^*(j)$$ then we have the “**inflation adjusted**” chain ladder model $$ E\left[ C(i,j) \right] = \alpha^*(i) \mu^*(j) \frac{\lambda(k)}{\lambda_0},$$ which is to be compared with the “**unadjusted**” chain ladder model $$ E\left[ C(i,j) \right] = \alpha(i) \mu(j).$$ - Note that Tables 3.1-3.3 corresponded to the “unadjusted” version. ------------------------------------------------------------------------ Proposition of Taylor (2000): *If `\(\alpha(\cdot)\)`, `\(\mu(\cdot)\)` are not restricted, then the inflation adjusted and unadjusted chain ladder models are consistent* **if an only if** *the rate of claims inflation is constant over the whole experience.* The last sentence means that we require `$$\frac{\lambda(k)}{\lambda(k-1)}\text{ to be constant for all }k>1.$$` ------------------------------------------------------------------------ Theorem 3.3 of Taylor (2000) implies that when claims inflation is constant at rate `\(f\)`, `$$\begin{aligned} \alpha(i) &= \frac{\lambda(0)}{K\lambda_0} \alpha^*(i) (1+f)^i, \\ \mu(j) &= K\mu^*(j) (1+f)^j, \text{ with} \end{aligned}$$` Note - One can choose `\(K=1\)` or such that `\(\sum_j \mu^*(j) = 1.\)` (this will generally not be the case). In the example below we have `\(K=1\)`. - If all payments are brought to the date of the diagonal, then the adjustment `\(\lambda(0)/\lambda_0\)` would typically just be an adjustment due to the fact that payments are not all made on the first or last day of the periods (typically, we assume in the middle on average). ------------------------------------------------------------------------ Proposition 3.4 of Taylor (2000) states that “Similar estimates of outstanding loss liability will be produced by: 1) the unadjusted chain ladder; 2) the inflation adjusted chain ladder, with a future inflation rate roughly equal to the average over the period of claims experience on which the estimates are based.” Note: - This is because the unadjusted chain ladder age to age factors include inflation implicitly, and that these are hence similarly projected in the future. - If inflation was very heterogeneous in the past `\(I\)` periods, and/or if it is assumed to be inconsistent with future inflation, an inflation adjusted chain ladder will lead to better forecasts (although it will require assumptions to be made about future inflation). See also Corollary 3.5 in Taylor (2000). - Results hold by analogy in presence of superimposed inflation. ### Example - See the spreadsheet [`Chapter3.xlsx`](https://canvas.lms.unimelb.edu.au/courses/191080/modules/items/5080918) for details of the calculations. - Table 3.4 displays `\(C^*(i,j)\)` as of 31 December 1995 using the inflation index set of Appendix B.2. - Note the accumulation factor of 1995 is not 1; it likely reflects the fact that payments in cells `\(k=1995\)` were spread throughout 1995, so some adjustment is required to bring them to 31 December. - Table 3.5 determines age to age factors, which we analyse from the point a view of the discussion above before proceeding to projections. ------------------------------------------------------------------------ - Table 3.6 compares `\(\widehat{\mu}^*(j)\)` of Table 3.5 with `\(\widehat{\mu}(j)\)` of Table 3.1. - It is a consequence of Theorem 3.3 that `$$f = \left(\frac{\mu(j)}{\mu^*(j)}\right)^{1/j}-1$$` and hence we can derive an “implied” rate `\(f_j\)` for each period `\(j\)`: `$$f_j = \left(\frac{\widehat{\mu}(j)}{\widehat{\mu}^*(j)}\right)^{1/j}-1$$` - This is also in Table 3.6, and is informative of the evolution of claims inflation over 1978-1995. The weighted average uses `\(\widehat{\mu}^*(j)\)` as weights. - It is now clear how inflation distorted the evolution of claim payments, making them look longer tailed than they would otherwise have been. ------------------------------------------------------------------------ - It is important to note that the results of Table 3.6 were influenced by our choice of age to age factors: - the “All” averaged factors over years 1978-1995 - the “Last 6” over years 1989-1995 - the “Last 3” over 1992-1995 - The average inflation rate over those years in Appendix B.2 was 6.8%, 4%, and 3.3% respectively (see calculations in spreadsheet). - This illustrates Theorem 3.3. ------------------------------------------------------------------------ - Now, Tables 3.7 and 3.8 forecast paid losses in 31/12/1995 dollar values - Note the forecast of \$374.8mio is evidently lower than the \$428.4mio forecast of the unadjusted chain ladder, as the latter implicitly allowed for inflation, and the former not. - Table 3.9 lifts those forecasts to allow for future inflation - Note the half year adjustment `\(\lambda(0)/\lambda_0\)` required for payment in the middle of the year on average. - Using 3.6% for future inflation leads to a forecast of \$421.1mio, which is very close to the unadjusted chain ladder forecast. This illustrates Proposition 3.4. ## Chain ladder on incurred losses ### Introduction - Here we will produce a triangle of incurred losses, as an indicator of how our estimates typically evolve over time, and converge to ultimate: - the “aggregate” equivalent will be the incurred losses - the “incremental” equivalent are **adjustments** to incurred losses - Note that this means that age-to-age factors of incurred losses generally won’t be `\(>1\)` since the incurred loss process is *not* a mostly nondecreasing process any more; this is illustrated in the two examples of claim developments earlier.. (Aggregate payments were generally nondecreasing, even though there can be negative payments sometimes.) ### Example - See the spreadsheet [`Chapter3.xlsx`](https://canvas.lms.unimelb.edu.au/courses/191080/modules/items/5080918) for details of the calculations. - Table 3.10 displays incurred losses `\(I(i,j)\)` (the “cumulative” data), which is decomposed in the next table (not in book) into `\(\Delta I(i,j)\)` (the “incremental” data) - the heat map on that triangle illustrates the generally increasing, then decreasing nature of aggregate incurred losses. - Table 3.11 age to age factors on the cumulative data. - Note that the factors are no longer all `\(>1\)`, which requires a new smoothing method, namely here a 3-period moving average; see (3.61) in Taylor (2000). - Finally, Table 3.12 implements the chosen age to age factors into outstanding liabilities. ## Commentary - The difference between `\(I(i,\infty)\)` and `\(I(i,j)\)` can be decomposed into: - an **IBNR** component (due to unreported claims); - an **IBNER** component (“Incurred But Not Enough Reported”), due to future revisions (inaccuracy) of case estimates. - Tables 3.3 and 3.12 are very different (see comparison under Table 3.12) - Paid CL is much higher than Incurred CL for 1986 and later. - This is due to using last-3-year averages, where payments were heavier than before. - The leverage on immature years is illustrated with the age-to-ultimate factors in gray in tab “Table 3.1”. Using all-year averages would reduce liability by 34-39% for the three most immature years. - A natural question would then be: are those changes permanent? # Separation method (3.3) ## Main rationale - A choice of inflation rate can be controversial, especially if it is significant or erratic. Unfortunately, this is also when it is the most impactful… - In that context, the unadjusted chain ladder is unreliable, and the adjusted one will lead to conflict. - Can we “let the data speak for themselves”? A simple answer is the separation method. - Here we keep the multiplicative structure we are familiar with. - However, the genious idea is to use indices `\(i\)` and `\(k\)` instead of `\(i\)` and `\(j\)`. - As a result, the `\(k\)` factors will give a sense of calendar period effects (to which inflation belongs), and we will retain nice ease of interpretation of the parameters. ## Model ### Algebraic structure - We assume `$$E[C(i,j)] = N(i) \mu^*(j) \lambda(k),$$` but now `\(\lambda(k)\)` will be inferred from the triangle. - Hence dividing `\(C(i,j)\)` by `\(N(i)\)` will yield the following algebraic structure of the separation model (Figure 3.1 in Taylor (2000)): <img src="separation.png" width="75%" style="display: block; margin: auto;" /> ### Interpretation - If we assume (wlog) $$ \sum_{j=0}^\infty \mu^*(j) = 1,$$ then `$$\sum_{j=0}^\infty E\left[ \frac{C(i,j)}{N(i)}\right] = \sum_{j=0}^\infty \mu^*(j) \lambda(k) = \lambda(k).$$` - This is the average size of claims from period of origin `\(i\)` **Proposition 3.6 (Taylor (2000))**: In the separation model as above, `\(\lambda(k)\)` denotes the average size of claims which would occur if costs were the same in all experience periods as in period `\(k\)`. ## Estimation Taylor (2000) derives estimators: `$$\begin{aligned} \hat{\mu}^*(j) &= \frac{\sum_{i=0}^{I-j} C(i,j)/\hat{N}(i)}{\sum_{k=j}^I \hat{\lambda}(k)} \\ &= \frac{\text{row sum of payments per claim}}{\text{diagonal sum of }\lambda\text{'s from }j\text{ to }I} \\ \hat{\lambda}^*(k) &= \frac{\sum_{i=0}^{k} C(i,k-i)/\hat{N}(i)}{1-\sum_{j=k+1}^\infty \hat{\mu}^*(j)} \\ &= \frac{\text{diagonal sum of payments per claim for calendar period } k}{\text{proportion of claims paid after }k\text{ development periods}} \end{aligned}$$` - This cannot be implemented directly - Furthermore, we do not have the `\(\hat{\mu}^*(j)\)` beyond `\(I\)`. ------------------------------------------------------------------------ Define: `$$v^*(j) = \frac{\mu^*(j)}{\sum_{m=0}^I \mu^*(m)}, \quad \kappa(k) = \lambda(k)\sum_{m=0}^I \mu^*(m).$$` Note that `\(v^*(j)\)` still is a proportion of a “period of origin” paid losses, but the base runs only up to development period `\(I\)`. ------------------------------------------------------------------------ The following clever manipulation, which rewrites the model as a function of the (column) `\(v^*(j)\)` and (diagonal) `\(\kappa(k)\)` allows us to use the triangle easily for estimation. We have `$$v^*(j)\kappa(k) = \mu^*(j)\lambda(k) = E\left[\frac{C(i,j)}{N(i)}\right] \text{ with } \sum_{j=0}^I v^*(j)=1.$$` Substitution in the estimators written above yields `$$\hat{v}^*(j) = \frac{\displaystyle \sum_{i=0}^{I-j}\frac{C(i,j)}{\hat{N}(i)} }{ \sum_{k=j}^I\hat{\kappa}(k) } = \frac{\text{sum of triangle column }j}{\sum_{k=j}^I\hat{\kappa}(k)}$$` and $$ \hat{\kappa}(k) = \frac{\displaystyle \sum_{i=0}^{k}\frac{C(i,j)}{\hat{N}(i)} }{ 1-\sum_{j=k+1}^I\hat{v}^*(j) } = \frac{\text{sum of triangle diagonal }k}{1-\sum_{j=k+1}^I\hat{v}^*(j)}$$`which can be calculated sequentially`$$\hat{\kappa}(I),\hat{v}^*(I),\hat{\kappa}(I-1),\ldots,\hat{v}^*(0).$$\` ## Example - See the spreadsheet [`Chapter3.xlsx`](https://canvas.lms.unimelb.edu.au/courses/191080/modules/items/5080918) for details of the calculations. - Table 3.13 starts by computing the `\(C(i,j)/N(i)\)`, where `\(N(i)\)` comes from Table 2.4. It also displays diagonal and column sums. - Those sums are used in Table 3.14 to calculate the `\(\hat{\kappa}(k)\)` and `\(v^*(j)\)` in the sequential way described above. ------------------------------------------------------------------------ - The estimates above can be translated into corresponding `\(\lambda(k)\)`’s in that the `\(\kappa\)` are proportional (see (3.73)). - These were the “inflation” equivalent we were trying to get from the model (“let the data speak”); see Figure 3.2 of Taylor (2000): <img src="kappa.png" width="75%" style="display: block; margin: auto;" /> - This suggests negative claims inflation up to 1988 (-4.9%), and strongly positive afterwards (12.1%). - The ensuing `\(v^*(j)\)` are very different from that stemming from the inflation adjusted chain ladder; see Table 3.15. ------------------------------------------------------------------------ - Table 3.16 calculates model paid losses for past *and* future. - The `\(\hat{\kappa}(k)\)` for `\(k>I\)` need to be projected. We use $$ \hat{\kappa}(k) = \hat{\kappa}(1995) \cdot (1.075)^{k-1995}.$$ - Population of the table needs care because the `\(\hat{\kappa}(k)\)` factors (including with projection) apply diagonally. - Comparison of model and actual paid losses to date is interesting: - By construction, column and diagonal sums should be identical, or very close. - The row sums, however, have no guarantee of matching. These are the paid losses to date, per period of origin. Examination of actual vs model such aggregate losses is a good indication of model fit. - We can also do this cell by cell with a heat map (done below, not in the book). - It turns out that those sums are matching relatively well, with a slight tendency to underestimate in early years, and to overestimate in later years. ## Commentary - The interpretation of `\(\lambda(k)\)` requires care, as it is a “catch all” indicator. - For instance, a change of speed of payment / notification across calendar years would be caught (would distort) by `\(\lambda(k)\)`. # The average payments per claim incurred (PPCI) method ## Main rationale - Assume you have data on aggregate payments and claim counts. - One can then try to project counts, and payments per claim separately. - The product can then be used as an estimate for ultimate. - One need to be careful to have consistent claims severity and frequency data, typically: - If paid (fully) claims, match to finalised claims. - If claims incurred, match to reported claims. - The former leads to the PPCF, the latter to the PPCI. We focus on the latter. - One major advantage is in the flexibility offered by the method to include superimposed inflation (this is illustrated in Taylor (2000), but is outside scope here). ## Process - Project incurred claim counts as per Chapter 2 (frequency). - Work out average payments per claim (severity) incurred in a triangle: - These will evolve over time. - We can analyse this evolution in a “chain ladder” type way. - The method rests on the assumption that this evolution is sufficiently regular that we can use it to “develop” our latest value of incurred claim cost (in the diagonal) into a final “payments per claim incurred”, to be multiplied by our projected total number of claim incurred. ## Example - See the spreadsheet [`PPCI.xlsx`](https://canvas.lms.unimelb.edu.au/courses/191080/modules/items/5080919) for details of the calculations, which are based on the data of Taylor (2000), but do not follow the (more complicated) calculations of Chapter 4. - Start from Table 3.10 of incurred losses, and incurred claims counts from Table 2.2. We need to transform the latter into cumulative form, so we can have both of same nature (cumulative). - The result of the division is an average payment per claim incurred: - Analysis of age to age actors shows that recent years are different, especially for later years. - The age-to-ultimate factors are those used to “develop” the latest average PPCI, into an ultimate one. - In the end, forecast outstanding liabilities are not dissimilar to those obtained form the incurred CL, although a little higher, perhaps due to slightly more responsiveness to the recent changes in claim development. ------------------------------------------------------------------------ A comparison and recap of all methods seen in this module is provided at the bottom. **Which one would you choose?** # References <div id="refs" class="references csl-bib-body hanging-indent"> <div id="ref-AvTaWa23" class="csl-entry"> Avanzi, Benjamin, Greg Taylor, and Melantha Wang. 2023. “SPLICE: A Synthetic Paid Loss and Incurred Cost Experience Simulator.” *Annals of Actuarial Science* 17 (1): 7–35. </div> <div id="ref-Tay00" class="csl-entry"> Taylor, Greg. 2000. *Loss Reserving: An Actuarial Perspective*. Huebner International Series on Risk, Insurance and Economic Security. Kluwer Academic Publishers. </div> </div> [^1]: References: Chapter 3 of Taylor (2000) \| `\(\; \rightarrow\)` [](https://gim-am3.netlify.app/output/23-Top-M4-lec.pdf)
import { Component, createSignal, For, Show } from 'solid-js'; import { MoreIcon } from '../../icons/MoreIcon'; import { DropDownItem, DropDownItemProps } from './DropDownItem'; import styles from './index.module.css'; interface DropDownProps { align?: 'left' | 'right'; items: DropDownItemProps[]; } export const DropDown: Component<DropDownProps> = ({ items, align = 'left', }: DropDownProps) => { const [open, setOpen] = createSignal(false); return ( <div class={ align === 'left' ? styles['direction-left'] : styles['direction-right'] } > <button onClick={() => setOpen(!open())} tabIndex={0} class={styles.container} > <MoreIcon color='white' width={30} height={30} /> </button> <Show when={open()}> <For each={items}> {(item) => <DropDownItem {...item} align={align} />} </For> </Show> </div> ); }; export default DropDown;
import { html } from '../lib.js'; import { register } from '../data/auth.js'; import { createSubmitHandler } from '../utils.js'; // TODO change with actual view export const registerTemplate = (onRegister) => html` <section id="register-page" class="content auth"> <form id="register" @submit=${onRegister}> <div class="container"> <div class="brand-logo"></div> <h1>Register</h1> <label for="email">Email:</label> <input type="email" id="email" name="email" placeholder="maria@email.com"> <label for="pass">Password:</label> <input type="password" name="password" id="register-password"> <label for="con-pass">Confirm Password:</label> <input type="password" name="confirm-password" id="confirm-password"> <input class="btn submit" type="submit" value="Register"> <p class="field"> <span>If you already have profile click <a href="login">here</a></span> </p> </div> </form> </section> `; export function registerPage(ctx) { ctx.render(registerTemplate(createSubmitHandler(onRegister))); async function onRegister({ email, password ,['confirm-password']: repass}, form) { if(email == '' || password == '' ){ return alert('All fields are required'); } if(password != repass){ return alert('Passwords don\'t match'); } await register(email, password); form.reset(); ctx.page.redirect('/'); } }
import { Component, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; /** * 共通メッセージダイアログ Component */ @Component({ selector: 'app-message-dialog', templateUrl: './message-dialog.component.html', styleUrls: ['./message-dialog.component.scss'], }) export class MessageDialogComponent { /** * タイトル */ title: string = this.data.title; /** * メッセージ */ message: string = this.data.message; /** * アクションボタン */ actions: DialogButtons[] = this.data.buttons; /** * 初期フォーカス */ initialFocus = this.data.initialFocus; /** * ダイアログボタン */ readonly DialogButtons = DialogButtons; /** * コンストラクター */ constructor( private matDialogRef: MatDialogRef<MessageDialogComponent, DialogButtons>, @Inject(MAT_DIALOG_DATA) private data: DialogConfig, ) {} } /** * ボタンの種類 */ export enum DialogButtons { Cancel = 'キャンセル', OK = 'OK', } /** * ダイアログコンフィグ */ export interface DialogConfig { title: string; message: string; buttons: DialogButtons[]; initialFocus: DialogButtons; }
/** * Portfolio component * * Highlights some of your creations. These can be designs, websites, * open source contributions, articles you've written and more. * * This is a great area for you to to continually add to and refine * as you continue to learn and create. */ import React from "react"; /** * Desk image * * Below is a sample desk image. Feel free to update this to an image of your choice, * updating below imageAltText to string that represents what you see in that image. * * Need an image? Check out https://unsplash.com to download a photo you * freely use on your site. */ import image from "../images/laptop.jpg"; const imageAltText = "desktop with books and laptop"; /** * Project list * * An array of objects that will be used to display for your project * links section. Below is a sample, update to reflect links you'd like to highlight. */ const projectList = [ { title: "Designed Wix Website for family business", description: "Crafted a responsive Wix website with user-friendly navigation and engaging visuals, demonstrating expertise in web design, layout, and content creation. Showcased creativity and attention to detail in digital design. ", url: "https://www.bhavishyainfra.in/", }, { title: "Youtube Channel - Bhavishya Singla", description: "Produced engaging short vlogs and informative tutorials on diverse software applications, accumulating over 24,000 views and 160 hours of watch time. Boasting a growing community of 130 subscribers and counting, I am dedicated to consistently delivering quality content and fostering engagement with my audience. ", url: "https://www.youtube.com/channel/UCpWV-I2zwBNV8qOIcfNboKg", }, { title: "My First Tableau Website", description: "Created my debut Tableau dashboard, showcasing expertise in designing interactive data visualizations for effective information communication. Acquired valuable experience in data analysis, demonstrating strong problem-solving and data-driven decision-making skills.", url: "https://public.tableau.com/app/profile/bhavishya.singla/viz/shared/BJGRKTS4T", }, { title: "My Going Projects", description: "Currently immersed in diverse ongoing projects, combining technical expertise and creative innovation to address real-world challenges. ", url: "https://linktr.ee/bhavishyasingla", }, ]; const Portfolio = () => { return ( <section className="padding" id="portfolio"> <h2 style={{ textAlign: "center" }}>Portfolio</h2> <div style={{ display: "flex", flexDirection: "row", paddingTop: "3rem" }}> <div style={{ maxWidth: "40%", alignSelf: "center" }}> <img src={image} style={{ height: "90%", width: "100%", objectFit: "cover" }} alt={imageAltText} /> </div> <div className="container"> {projectList.map((project) => ( <div className="box" key={project.title}> <a href={project.url} target="_blank" rel="noopener noreferrer"> <h3 style={{ flexBasis: "40px" }}>{project.title}</h3> </a> <p className="small">{project.description}</p> </div> ))} </div> </div> </section> ); }; export default Portfolio;
package org.nextprot.parser.ensg import org.scalatest.FlatSpec import org.scalatest.Matchers import scala.xml.NodeSeq /** * Created by fnikitin on 18/06/15. */ class ENSGUtilsTest extends FlatSpec with Matchers { val xml = <entry created="2007-02-20" dataset="Swiss-Prot" modified="2015-04-29" version="91"> <accession>A0AVT1</accession> <accession>A6N8M7</accession> <accession>B2RAV3</accession> <accession>Q4W5K0</accession> <accession>Q6UV21</accession> <accession>Q86T78</accession> <accession>Q86TC7</accession> <accession>Q8N5T3</accession> <accession>Q8N9E4</accession> <accession>Q9H3T7</accession> <accession>Q9NVC9</accession> <dbReference id="MINT-1195700" type="MINT"/> <dbReference id="A0AVT1" type="BindingDB"/> <dbReference id="CHEMBL2321622" type="ChEMBL"/> <dbReference id="A0AVT1" type="PhosphoSite"/> <dbReference id="UPA00143" type="UniPathway"/> <dbReference id="UBA6" type="BioMuta"/> <dbReference id="A0AVT1" type="MaxQB"/> <dbReference id="A0AVT1" type="PaxDb"/> <dbReference id="A0AVT1" type="PRIDE"/> <dbReference id="55236" type="DNASU"/> <dbReference id="ENST00000322244" type="Ensembl"> <molecule id="A0AVT1-1"/> <property type="protein sequence ID" value="ENSP00000313454"/> <property type="gene ID" value="ENSG00000033178"/> </dbReference> <dbReference id="ENST00000420827" type="Ensembl"> <molecule id="A0AVT1-3"/> <property type="protein sequence ID" value="ENSP00000399234"/> <property type="gene ID" value="ENSG00000033178"/> </dbReference> <dbReference id="55236" type="GeneID"/> <dbReference id="hsa:55236" type="KEGG"/> <dbReference id="uc003hdg.4" type="UCSC"> <molecule id="A0AVT1-1"/> <property type="organism name" value="human"/> </dbReference> </entry> it should "return the correct Ensembl Reference XML Nodes" in { val ensemblXrefs:NodeSeq = ENSGUtils.getEnsemblReferenceNodeSeq(xml) val ensemblIds:Seq[String] = ensemblXrefs.map(e => (e \ "@id").text) assert(ensemblIds.contains("ENST00000322244")) assert(ensemblIds.contains("ENST00000420827")) } it should "return the correct Ensembl Reference id Nodes" in { val ensemblIdNodes = ENSGUtils.getEnsemblIdNodeSeq(xml) assertResult("<property type=\"gene ID\" value=\"ENSG00000033178\"/><property type=\"gene ID\" value=\"ENSG00000033178\"/>")(ensemblIdNodes.toString()) } it should "return the correct gene ids" in { val geneIds = ENSGUtils.getGeneIds(xml, ",") assertResult("ENSG00000033178,ENSG00000033178")(geneIds) } }
import { VariantProps, tv } from 'tailwind-variants' import { PasswordInput } from './PasswordInput' import { SelectItem } from 'src/types/select' import { Spinner } from '..' import { MaskInput } from './MaskInput' const labelStyle = tv({ base: 'block font-semibold', variants: { theme: { dark: 'text-dark', primary: 'text-primary', }, size: { xs: 'text-xs', sm: 'text-sm', base: 'text-base', '2xl': 'text-2xl', }, }, defaultVariants: { theme: 'dark', size: 'base', }, }) const containerStyle = tv({ base: 'flex gap-1', variants: { layout: { row: 'flex-col sm:flex-row sm:items-center', column: 'flex-col', }, }, defaultVariants: { layout: 'column', }, }) const inputStyleSlots = tv({ slots: { containerInput: 'relative flex flex-1 flex-row overflow-hidden', input: 'remove-auto-fill font-poppings w-full min-w-0 flex-1 !bg-[transparent] font-light text-dark placeholder:text-placeholder disabled:opacity-100', }, variants: { size: { sm: { containerInput: 'h-6 min-h-[1.5rem]', input: 'px-2 text-sm', }, md: { containerInput: 'h-7 min-h-[1.75rem]', input: 'px-2 text-sm', }, base: { containerInput: 'h-11 min-h-[2.75rem]', input: 'px-3 text-base', }, }, disabled: { true: { containerInput: 'rounded bg-light-primary', }, false: { containerInput: 'rounded-[1px] border border-placeholder bg-light', }, }, }, defaultVariants: { size: 'base', disabled: false, }, }) export type InputType = | 'text' | 'password' | 'email' | 'cpf' | 'cnpj' | 'cpfOrCnpj' | 'date' | 'plate' export interface InputProps { label?: string containerClassName?: string error?: string type?: InputType containerVariants?: VariantProps<typeof containerStyle> labelVariants?: VariantProps<typeof labelStyle> inputVariants?: VariantProps<typeof inputStyleSlots> items?: SelectItem[] loading?: boolean name: string disabled?: boolean required?: boolean placeholder?: string value?: string onChange?: React.ChangeEventHandler<HTMLElement> onBlur?: React.FocusEventHandler<HTMLElement> } const inputComponentByType: { [key in InputType]: React.ElementType } = { text: 'input', email: 'input', password: PasswordInput, cpf: MaskInput, cnpj: MaskInput, cpfOrCnpj: MaskInput, date: MaskInput, plate: MaskInput, } export function Input({ label, name, error, labelVariants, containerVariants, inputVariants = {}, containerClassName, items, placeholder, loading, required, disabled = false, value, type = 'text', onChange, ...rest }: InputProps) { const { input: inputStyle, containerInput: containerInputStyle } = inputStyleSlots({ ...inputVariants, disabled }) const commonProps = { id: name, value, disabled: disabled || loading, className: inputStyle({ className: !value && disabled && 'disabled:text-placeholder/50 disabled:placeholder:text-placeholder/50', }), onChange, } const renderSelect = () => ( <select {...commonProps}> <option key="" value=""> {placeholder ?? 'Selecione um item'} </option> {items!.map((item) => ( <option key={item.value} value={item.value}> {item.label} </option> ))} </select> ) const renderInput = () => { const InputComponent = inputComponentByType[type] return ( <InputComponent {...commonProps} {...rest} type={type} size={inputVariants.size} placeholder={placeholder} /> ) } return ( <div className={containerClassName}> <div className={containerStyle(containerVariants)}> {!!label && ( <label htmlFor={name} className={labelStyle(labelVariants)}> {required && <span className="text-error">*</span>} {label} </label> )} <div className={containerInputStyle()}> {items ? renderSelect() : renderInput()} {loading && ( <div className="absolute right-0 flex h-full w-4 items-center bg-light"> <Spinner className="w-3 fill-placeholder" /> </div> )} </div> </div> {!!error && <p className="-mb-1 mt-1 text-xs text-error">{error}</p>} </div> ) }
import { Card, CardHeader, CardBody, Typography, Avatar, Chip, Tooltip, Progress, } from "@material-tailwind/react"; import { EllipsisVerticalIcon } from "@heroicons/react/24/outline"; import { authorsTableData, projectsTableData } from "@/data"; import { useEffect, useState } from "react"; export function Roles() { const [roles, setRoles] = useState(null); const url = 'http://127.0.0.1:8000/api/roles'; useEffect(() => { const getRoles = async () => { const res = await fetch(url) const data = await res.json() setRoles(data) } getRoles(); }, []) return ( <div className="mt-12 mb-8 flex flex-col gap-12"> <Card> <CardHeader variant="gradient" color="gray" className="mb-8 p-6"> <div className="flex space-x-5"> <div> <Typography variant="h6" color="white"> Roles definidos en el sistema </Typography> </div> <div> <button> <Chip variant="gradient" color="blue" value="Agregar Roles" className="py-0.5 px-4 text-[13px] font-medium w-fit" /></button> </div> </div> </CardHeader> <CardBody className="overflow-x-scroll px-0 pt-0 pb-2"> <table className="w-full min-w-[640px] table-auto"> <thead> <tr> {["id", "Rol", "Creación", "Modificación", "Acción"].map((el) => ( <th key={el} className="border-b border-blue-gray-50 py-3 px-5 text-left" > <Typography variant="small" className="text-[11px] font-bold uppercase text-blue-gray-400" > {el} </Typography> </th> ))} </tr> </thead> <tbody> {roles && roles.map( ({ id, rol, usuario_creacion, fecha_creacion, usuario_modificacion, fecha_modificacion }, key) => { const className = `py-3 px-5 ${key === rol.length - 1 ? "" : "border-b border-blue-gray-50" }`; return ( <tr key={id}> <td className={className}> <Typography className="text-xs font-semibold text-blue-gray-600"> {id} </Typography> </td> <td className={className}> <div className="flex items-center gap-4"> <div> <Typography variant="small" color="blue-gray" className="font-semibold" > {rol} </Typography> </div> </div> </td> <td className={className}> <Typography className="text-xs font-semibold text-blue-gray-600"> {usuario_creacion} </Typography> <Typography className="text-xs font-normal text-blue-gray-500"> {fecha_creacion} </Typography> </td> <td className={className}> <Typography className="text-xs font-semibold text-blue-gray-600"> {usuario_modificacion} </Typography> <Typography className="text-xs font-normal text-blue-gray-500"> {fecha_modificacion} </Typography> </td> <td className={className}> <Typography as="a" href="#" className="text-xs font-semibold text-blue-gray-600" > <Chip variant="gradient" color="green" value="Edit" className="py-0.5 px-2 text-[11px] font-medium w-fit" /> </Typography> </td> </tr> ); } )} </tbody> </table> </CardBody> </Card> </div> ); } export default Roles;
#include <iostream> #include <Box2d/Box2d.h> int main(){ //Creación del mundo y de la gravedad b2Vec2 gravity(0.0f,-24.79); b2World world(gravity); //Características del cuerpo b2BodyDef groundBodyDef; groundBodyDef.position.Set(0.0f,-10.0f); //Creamos el cuerpo, osea el piso b2Body* groundBody = world.CreateBody(&groundBodyDef); //Crear su forma b2PolygonShape groundBox; groundBox.SetAsBox(50.0f,1.0f); groundBody->CreateFixture(&groundBox, 0.0f); //Definimos un nuevo cuerpo, diciendo que es dinámico y su posición b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(0.0f, 20.0f); //Creamos el cuerpo b2Body*body = world.CreateBody(&bodyDef); b2PolygonShape dynamicBox; dynamicBox.SetAsBox(1.0f, 1.0f); //Definimos sus características como su forma de caja, densidad y fricción b2FixtureDef fixtureDef; fixtureDef.shape = &dynamicBox; fixtureDef.density = 1f; fixtureDef.friction = 0.0f; body ->CreateFixture(&fixtureDef); float timeStep = 1.0f/60.0f; int32 velocityIterations = 6; int32 positionIterations = 2; for (int i = 0; i < 60; ++i) { world.Step(timeStep, velocityIterations, positionIterations); b2Vec2 position = body->GetPosition(); float angle = body->GetAngle(); printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle); } }
import React from 'react'; import { tribeca, workSans } from '../../../utils/fonts'; import styles from './news-item.module.css'; interface Inews { text: string; header: string; created: string; } export default function NewsItem({ news, image, index, last, }: { news: Inews; image?: string | null; index: number; last?: boolean; }) { const { header, text, created } = news; const date = new Date(created).toLocaleDateString(); return ( <> <div className={`${styles.container} ${index % 2 ? styles.reverse : ''} ${ last ? styles.footer_margin : '' }`} > <div className={`${workSans.className} ${styles.text_container}`}> <div> <p className={`${tribeca.className} ${styles.title}`}>{header}</p> <p className={`${styles.text}`} dangerouslySetInnerHTML={{ __html: text }} /> </div> <p className={styles.date}>-Billy Uganda {date}</p> </div> {image ? <img className={styles.image} src={image} alt="" /> : ''} </div> {!last ? <hr /> : ''} </> ); }
import java.util.*; class lab { static int partition(int arr[], int low, int high) { int pivot = arr[high]; System.out.println("---------------------"); System.out.println("Pivot element is :- "+pivot); int i = (low-1); for (int j=low; j<high; j++) { if (arr[j] < pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; System.out.println("elements in First partition are :- "); for(int j=0;j<i+1;j++) System.out.print(arr[j]+" "); System.out.println(); System.out.println("elements in the Second partition are :- "); for(int j=i+2;j<arr.length;j++) System.out.print(arr[j]+" "); System.out.println(); return i+1; } static void quickSort(int arr[], int low, int high) { int pi; if (low < high) { pi = partition(arr, low, high); quickSort(arr, low, pi-1); quickSort(arr, pi+1, high); } } public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter the size of Array"); int n=sc.nextInt(); System.out.println("Enter Array Elements :- "); int[] arr=new int[n]; for(int i=0;i<arr.length;i++) arr[i]=sc.nextInt(); quickSort(arr, 0, arr.length-1); System.out.println("---------------------"); System.out.println("Sorted Array is :- "); System.out.println(Arrays.toString(arr)); sc.close(); } }
''' @FileName :最小二乘回归.py @Description: @Date :2022/08/22 21:54:03 @Author :daito @Website :Https://github.com/zhd5120153951 @Copyright :daito @License :None @version :1.0 @Email :2462491568@qq.com @PS : ''' #数据生成 import numpy as np #随机数 np.random.seed(1234) x = np.random.rand(500, 3) print(x.shape) print(x) # print(x[3, 2]) # print(x[2, 2]) #构建映射关系,模拟真实的数据待预测值,映射关系为y = 4.2 + 5.7*x1 + 10.8*x2,可自行设置值进行尝试 y = x.dot(np.array([4.2, 5.7, 10.8])) #矩阵乘法--x.dot(y)==np.dot(x,y) print(y.shape) print(y) class LR_LS(): def __init__(self): self.w = None def fit(self, X, y): # 最小二乘法矩阵求解 self.w = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y) def predict(self, X): # 用已经拟合的参数值预测新自变量 y_pred = X.dot(self.w) return y_pred if __name__ == "__main__": lr_ls = LR_LS() lr_ls.fit(x, y) print("估计的参数值:%s" % (lr_ls.w)) x_test = np.array([2, 4, 5]).reshape(1, -1) print("预测值为: %s" % (lr_ls.predict(x_test)))
package Exersicis; import java.util.Scanner; public class tresenraya_matrius { static Scanner scan = new Scanner(System.in); public static void main(String[] args) { jugar(); } // Metode on comença el joc public static void jugar() { // Representem els jugadors i el valor buit char J1 = 'X'; char J2 = 'O'; char vacio = '-'; // torn actual // true = J1, false = J2 boolean turno = true; // Matriu Tablero char tablero[][] = new char[3][3]; // Omplim les caselles buides rellenarMatriz(tablero, vacio); int fila, columna; boolean posValida, correcto; // No sortim fins que guanyi algu o ens quedem sense caselles while (!finPartida(tablero, vacio)) { do { // Mostrem torn mostrarTurnoActual(turno); // Mostrem tablero mostrarMatriz(tablero); correcto = false; fila = pedirInteger("Dame la fila (0-2)"); columna = pedirInteger("Dame la columna (0-2)"); // Validem posició posValida = validarPosicion(tablero, fila, columna); // Si és vàlid, comprobem que no estigui ocupada if (posValida) { //Si no hi ha marca, significa que es correcte if (!hayValorPosicion(tablero, fila, columna, vacio)) { correcto = true; } else { System.out.println("Ya hay una ficha en esa posicion"); } } else { System.out.println("La posicion no es válida"); } // Mentre no sigui correcte no sortim d'aquest bucle } while (!correcto); // Depenent del torn, insertem X/O if (turno) { insertarEn(tablero, fila, columna, J1); } else { insertarEn(tablero, fila, columna, J2); } // Cambiem torn turno = !turno; } // Mostra tablero mostrarMatriz(tablero); // Mostrem el guanyador mostrarGanador(tablero, J1, J2, vacio); } // Funció mostrar el guanyador public static void mostrarGanador(char[][] matriz, char J1, char J2, char simDef) { char simbolo = coincidenciaLinea(matriz, simDef); if (simbolo != simDef) { ganador(simbolo, J1, J2, 1); return; } simbolo = coincidenciaColumna(matriz, simDef); if (simbolo != simDef) { ganador(simbolo, J1, J2, 2); return; } simbolo = coincidenciaDiagonal(matriz, simDef); if (simbolo != simDef) { ganador(simbolo, J1, J2, 3); return; } System.out.println("Hay empate"); } // Funció auxiliar anterior public static void ganador(char simbolo, char J1, char J2, int tipo) { switch (tipo) { case 1: if (simbolo == J1) { System.out.println("Ha ganado el Jugador 1 por linea"); } else { System.out.println("Ha ganado el Jugador 2 por linea"); } break; case 2: if (simbolo == J1) { System.out.println("Ha ganado el Jugador 1 por columna"); } else { System.out.println("Ha ganado el Jugador 2 por columna"); } break; case 3: if (simbolo == J1) { System.out.println("Ha ganado el Jugador 1 por diagonal"); } else { System.out.println("Ha ganado el Jugador 2 por diagonal"); } break; } } // Insertamos en una posicion de la matriz un símbolo en concreto public static void insertarEn(char[][] matriz, int fila, int columna, char simbolo) { matriz[fila][columna] = simbolo; } // Imprimimos el turno actual public static void mostrarTurnoActual(boolean turno) { if (turno) { System.out.println("Le toca al jugador 1"); } else { System.out.println("Le toca al jugador 2"); } } // Pedimos un numero aleatorio public static int pedirInteger(String mensaje) { System.out.println(mensaje); int numero = scan.nextInt(); return numero; } // Rellenamos la matriz con un simbolo public static void rellenarMatriz(char[][] matriz, char simbolo) { for (int i = 0; i < matriz.length; i++) { for (int j = 0; j < matriz.length; j++) { matriz[i][j] = simbolo; } } } // Validamos la posicion en la que insertamos public static boolean validarPosicion(char[][] tablero, int fila, int columna) { if (fila >= 0 && fila < tablero.length && columna >= 0 && columna < tablero.length) { return true; } return false; } // Indiquem si a una posició hi ha una marca public static boolean hayValorPosicion(char[][] matriz, int fila, int columna, char simboloDef) { if (matriz[fila][columna] != simboloDef) { return true; } return false; } // Mostra la matriu public static void mostrarMatriz(char[][] matriz) { for (int i = 0; i < matriz.length; i++) { for (int j = 0; j < matriz[0].length; j++) { System.out.print(matriz[i][j] + " "); } System.out.println(""); } } // Indica si la matriu esta plena si hi ha el simbol per defecte public static boolean matrizLlena(char[][] matriz, char simboloDef) { for (int i = 0; i < matriz.length; i++) { for (int j = 0; j < matriz[0].length; j++) { if (matriz[i][j] == simboloDef) { return false; } } } return true; } // La partida acaba quan la matriu esta plena o si hi ha algun guanyador public static boolean finPartida(char[][] matriz, char simboloDef) { if (matrizLlena(matriz, simboloDef) || coincidenciaLinea(matriz, simboloDef) != simboloDef || coincidenciaColumna(matriz, simboloDef) != simboloDef || coincidenciaDiagonal(matriz, simboloDef) != simboloDef) { return true; } return false; } // Indica si hi ha un guanyador a una línea public static char coincidenciaLinea(char[][] matriz, char simboloDef) { char simbolo; boolean coincidencia; for (int i = 0; i < matriz.length; i++) { // Reiniciem la coincidencia coincidencia = true; // Agafem el simbol de la fila simbolo = matriz[i][0]; if (simbolo != simboloDef) { for (int j = 1; j < matriz[0].length; j++) { // Si no coincideix ja no hi haura guanyador a aquesta fila if (simbolo != matriz[i][j]) { coincidencia = false; } } // Si no entra al if retorna el símbol guanyador if (coincidencia) { return simbolo; } } } // Si no hi ha guanyador retornem el símbol per defecte return simboloDef; } public static char coincidenciaColumna(char[][] matriz, char simboloDef) { char simbolo; boolean coincidencia; for (int j = 0; j < matriz.length; j++) { // Reiniciem la coincidencia coincidencia = true; // Agafem el símbol de la columna simbolo = matriz[0][j]; if (simbolo != simboloDef) { for (int i = 1; i < matriz[0].length; i++) { // Si no coincideix ja no hi haura guanyador a aquesta fila if (simbolo != matriz[i][j]) { coincidencia = false; } } // Si no entra al if retorna el símbol guanyador if (coincidencia) { return simbolo; } } } // Si no hi ha guanyador retornem el símbol per defecte return simboloDef; } public static char coincidenciaDiagonal(char[][] matriz, char simboloDef) { char simbolo; boolean coincidencia = true; // Diagonal principal simbolo = matriz[0][0]; if (simbolo != simboloDef) { for (int i = 1; i < matriz.length; i++) { // Si no coincideix no hi han guanyadors a la diagonal if (simbolo != matriz[i][i]) { coincidencia = false; } } // Si no entra al if retorna el símbol guanyador if (coincidencia) { return simbolo; } } // Diagonal inversa simbolo = matriz[0][2]; if (simbolo != simboloDef) { for (int i = 1, j = 1; i < matriz.length; i++, j--) { // Si no coincideix no hi han guanyadors a la diagonal if (simbolo != matriz[i][j]) { coincidencia = false; } } // Si no entra al if retorna el símbol guanyador if (coincidencia) { return simbolo; } } // Si no hi ha guanyador retorna el símbol per defecte return simboloDef; } }
import { updateProfileData } from '../services/updateProfileData/updateProfileData' import { type ProfileSchema } from '../types/EditablePofileCardSchema' import { profileActions, profileReducer } from './profileSlice' import { Country } from '@/entities/Country' import { Currency } from '@/entities/Currency' import { type Profile } from '@/entities/Profile' const data: Profile = { first: '123', lastname: 'Mihailov', age: 2021, currency: Currency.RUB, country: Country.Russia, city: 'Ekb', username: 'admin', avatar: 'https://avatarko.ru/img/kartinka/14/Iron_man_13295.jpg', } describe('Тест profileSlice.test', () => { test( 'Тестирование setReadonly', () => { const state: DeepPartial<ProfileSchema> = { readonly: false, } expect(profileReducer( state as ProfileSchema, profileActions.setReadonly(true) )).toEqual({ readonly: true }) } ) test( 'Тестирование cancelEdit', () => { const state: DeepPartial<ProfileSchema> = { readonly: false, data: { lastname: 'hello', }, form: {}, validate: [], } expect(profileReducer( state as ProfileSchema, profileActions.cancelEdit() )).toEqual({ readonly: true, data: { lastname: 'hello', }, form: { lastname: 'hello', }, validate: undefined, }) } ) test( 'Тестирование updateProfile', () => { const state: DeepPartial<ProfileSchema> = { form: { lastname: 'hello', }, } expect(profileReducer( state as ProfileSchema, profileActions.updateProfile({ first: 'world', }) )).toEqual({ form: { lastname: 'hello', first: 'world', }, }) } ) test( 'Тестирование обновления профиля через service updateProfileData.pending', () => { const state: DeepPartial<ProfileSchema> = { isLoading: false, validate: [], } expect(profileReducer( state as ProfileSchema, updateProfileData.pending )).toEqual({ isLoading: true, validate: undefined, }) } ) test( 'Тестирование обновления профиля через service updateProfileData.fulfilled', () => { const state: DeepPartial<ProfileSchema> = { isLoading: true, data: { first: 'hello', }, form: { lastname: 'world', }, readonly: false, validate: [], } expect(profileReducer( state as ProfileSchema, updateProfileData.fulfilled(data, '') )).toEqual({ isLoading: false, data, form: data, readonly: true, validate: undefined, }) } ) })
/** * Copyright (C) 2021 THL A29 Limited, a Tencent company. * * 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. */ // @ts-check import Logger from '@/Logger'; import { escapeHTMLSpecialCharOnce as $e } from '@/utils/sanitize'; import { createElement } from '@/utils/dom'; /** * @typedef {Object} SubMenuConfigItem * @property {string} name - 子菜单项名称 * @property {string=} iconName - 子菜单项图标名称 * @property {function(MouseEvent): any} onclick - 子菜单项点击事件 * @property {string=} icon - 子菜单项图标(url) */ /** * * @param {HTMLElement} targetDom * @param {'absolute' | 'fixed' | 'sidebar'} [positionModel = 'absolute'] * @returns {Pick<DOMRect, 'left' | 'top' | 'width' | 'height'>} */ function getPosition(targetDom, positionModel = 'absolute') { const pos = targetDom.getBoundingClientRect(); if (positionModel === 'fixed') { return pos; } // 侧边栏按钮做个特殊处理 if (positionModel === 'sidebar') { const parent = MenuBase.getTargetParentByButton(targetDom); return { left: parent.offsetLeft - 130 + pos.width, top: targetDom.offsetTop + pos.height / 2, width: pos.width, height: pos.height, }; } return { left: targetDom.offsetLeft, top: targetDom.offsetTop, width: pos.width, height: pos.height }; } /** * @typedef {import('@/Editor').default} Editor */ /** * @class MenuBase */ export default class MenuBase { /** * @deprecated * @type {MenuBase['fire']} */ _onClick; /** * * @param {Partial<import('../Cherry').default>} $cherry */ constructor($cherry) { this.$cherry = $cherry; this.bubbleMenu = false; this.subMenu = null; // 子菜单实例 this.name = ''; // 菜单项Name this.editor = $cherry.editor; // markdown实例 this.locale = $cherry.locale; this.dom = null; this.updateMarkdown = true; // 是否更新markdown原文 /** @type {SubMenuConfigItem[]} */ this.subMenuConfig = []; // 子菜单配置 this.noIcon = false; // 是否不显示图标 this.cacheOnce = false; // 是否保存一次点击事件生成的内容 /** * 子菜单的定位方式 * @property * @type {'absolute' | 'fixed' | 'sidebar'} */ this.positionModel = 'absolute'; // eslint-disable-next-line no-underscore-dangle if (typeof this._onClick === 'function') { Logger.warn('`MenuBase._onClick` is deprecated. Override `fire` instead'); // eslint-disable-next-line no-underscore-dangle this.fire = this._onClick; } } getSubMenuConfig() { return this.subMenuConfig; } /** * 设置菜单 * @param {string} name 菜单名称 * @param {string} [iconName] 菜单图标名 */ setName(name, iconName) { this.name = name; this.iconName = iconName; } /** * 设置一个一次性缓存 * 使用场景: * 当需要异步操作是,比如上传视频、选择字体颜色、通过棋盘插入表格等 * 实现原理: * 1、第一次点击按钮时触发fire()方法,触发选择文件、选择颜色、选择棋盘格的操作。此时onClick()不返回任何数据。 * 2、当异步操作完成后(如提交了文件、选择了颜色等),调用本方法(setCacheOnce)实现缓存,最后调用fire()方法 * 3、当fire()方法再次调用onClick()方法时,onClick()方法会返回缓存的数据(getAndCleanCacheOnce) * * 这么设计的原因: * 1、可以复用MenuBase的相关方法 * 2、避免异步操作直接与codemirror交互 * @param {*} info */ setCacheOnce(info) { this.cacheOnce = info; } getAndCleanCacheOnce() { this.updateMarkdown = true; const ret = this.cacheOnce; this.cacheOnce = false; return ret; } hasCacheOnce() { return this.cacheOnce !== false; } /** * 创建一个一级菜单 * @param {boolean} asSubMenu 是否以子菜单的形式创建 */ createBtn(asSubMenu = false) { const classNames = asSubMenu ? 'cherry-dropdown-item' : `cherry-toolbar-button cherry-toolbar-${this.iconName ? this.iconName : this.name}`; const span = createElement('span', classNames, { title: this.locale[this.name] || $e(this.name), }); // 如果有图标,则添加图标 if (this.iconName && !this.noIcon) { const icon = createElement('i', `ch-icon ch-icon-${this.iconName}`); span.appendChild(icon); } // 二级菜单强制显示文字,没有图标的按钮也显示文字 if (asSubMenu || this.noIcon) { span.innerHTML += this.locale[this.name] || $e(this.name); } // 只有一级菜单才保存dom,且只保存一次 if (!asSubMenu && !this.dom) { this.dom = span; } return span; } /** * 通过配置创建一个二级菜单 * @param {SubMenuConfigItem} config 配置 */ createSubBtnByConfig(config) { const { name, iconName, icon, onclick } = config; const span = createElement('span', 'cherry-dropdown-item', { title: this.locale[name] || $e(name), }); if (iconName) { const iconElement = createElement('i', `ch-icon ch-icon-${iconName}`); span.appendChild(iconElement); } else if (icon) { const iconElement = createElement('img', 'ch-icon', { src: icon, style: 'width: 16px; height: 16px; vertical-align: sub;', }); span.appendChild(iconElement); } span.innerHTML += this.locale[name] || $e(name); span.addEventListener('click', onclick, false); return span; } /** * 处理菜单项点击事件 * @param {MouseEvent | KeyboardEvent | undefined} [event] 点击事件 * @returns {void} */ fire(event, shortKey = '') { event?.stopPropagation(); if (typeof this.onClick === 'function') { const selections = this.editor.editor.getSelections(); // 判断是不是多选 this.isSelections = selections.length > 1; // 当onClick返回null、undefined、false时,维持原样 const ret = selections.map( (selection, index, srcArray) => this.onClick(selection, shortKey, event) || srcArray[index], ); if (!this.bubbleMenu && this.updateMarkdown) { // 非下拉菜单按钮保留selection this.editor.editor.replaceSelections(ret, 'around'); this.editor.editor.focus(); this.$afterClick(); } } } /** * 获取当前选择区域的range */ $getSelectionRange() { const { anchor, head } = this.editor.editor.listSelections()[0]; // 如果begin在end的后面 if ((anchor.line === head.line && anchor.ch > head.ch) || anchor.line > head.line) { return { begin: head, end: anchor }; } return { begin: anchor, end: head }; } /** * 注册点击事件渲染后的回调函数 * @param {function} cb */ registerAfterClickCb(cb) { this.afterClickCb = cb; } /** * 点击事件渲染后的回调函数 */ $afterClick() { if (typeof this.afterClickCb === 'function' && !this.isSelections) { this.afterClickCb(); this.afterClickCb = null; } } /** * 选中除了前后语法后的内容 * @param {String} lessBefore * @param {String} lessAfter */ setLessSelection(lessBefore, lessAfter) { const cm = this.editor.editor; const { begin, end } = this.$getSelectionRange(); const newBeginLine = lessBefore.match(/\n/g)?.length > 0 ? begin.line + lessBefore.match(/\n/g).length : begin.line; const newBeginCh = lessBefore.match(/\n/g)?.length > 0 ? lessBefore.replace(/^[\s\S]*?\n([^\n]*)$/, '$1').length : begin.ch + lessBefore.length; const newBegin = { line: newBeginLine, ch: newBeginCh }; const newEndLine = lessAfter.match(/\n/g)?.length > 0 ? end.line - lessAfter.match(/\n/g).length : end.line; const newEndCh = lessAfter.match(/\n/g)?.length > 0 ? cm.getLine(newEndLine).length : end.ch - lessAfter.length; const newEnd = { line: newEndLine, ch: newEndCh }; cm.setSelection(newBegin, newEnd); } /** * 基于当前已选择区域,获取更多的选择区 * @param {string} [appendBefore] 选择区前面追加的内容 * @param {string} [appendAfter] 选择区后面追加的内容 * @param {function} [cb] 回调函数,如果返回false,则恢复原来的选取 */ getMoreSelection(appendBefore, appendAfter, cb) { const cm = this.editor.editor; const { begin, end } = this.$getSelectionRange(); let newBeginCh = // 如果只包含换行,则起始位置一定是0 /\n/.test(appendBefore) ? 0 : begin.ch - appendBefore.length; newBeginCh = newBeginCh < 0 ? 0 : newBeginCh; let newBeginLine = /\n/.test(appendBefore) ? begin.line - appendBefore.match(/\n/g).length : begin.line; newBeginLine = newBeginLine < 0 ? 0 : newBeginLine; const newBegin = { line: newBeginLine, ch: newBeginCh }; let newEndLine = end.line; let newEndCh = end.ch; if (/\n/.test(appendAfter)) { newEndLine = end.line + appendAfter.match(/\n/g).length; newEndCh = cm.getLine(newEndLine)?.length; } else { newEndCh = cm.getLine(end.line).length < end.ch + appendAfter.length ? cm.getLine(end.line).length : end.ch + appendAfter.length; } const newEnd = { line: newEndLine, ch: newEndCh }; cm.setSelection(newBegin, newEnd); if (cb() === false) { cm.setSelection(begin, end); } } /** * 获取用户选中的文本内容,如果没有选中文本,则返回光标所在的位置的内容 * @param {string} selection 当前选中的文本内容 * @param {string} type 'line': 当没有选择文本时,获取光标所在行的内容; 'word': 当没有选择文本时,获取光标所在单词的内容 * @param {boolean} focus true;强行选中光标处的内容,否则只获取选中的内容 * @returns {string} */ getSelection(selection, type = 'word', focus = false) { const cm = this.editor.editor; // 多光标模式下不做处理 if (this.isSelections) { return selection; } if (selection && !focus) { return selection; } // 获取光标所在行的内容,同时选中所在行 if (type === 'line') { const { begin, end } = this.$getSelectionRange(); cm.setSelection({ line: begin.line, ch: 0 }, { line: end.line, ch: cm.getLine(end.line).length }); return cm.getSelection(); } // 获取光标所在单词的内容,同时选中所在单词 if (type === 'word') { const { anchor: begin, head: end } = cm.findWordAt(cm.getCursor()); cm.setSelection(begin, end); return cm.getSelection(); } } /** * 反转子菜单点击事件参数顺序 * @deprecated */ bindSubClick(shortcut, selection) { return this.fire(null, shortcut); } onClick(selection, shortcut, callback) { return selection; } get shortcutKeys() { return []; } /** * 获取当前菜单的位置 */ getMenuPosition() { const parent = MenuBase.getTargetParentByButton(this.dom); const isFromSidebar = /cherry-sidebar/.test(parent.className); if (/cherry-bubble/.test(parent.className) || /cherry-floatmenu/.test(parent.className)) { this.positionModel = 'fixed'; } else if (isFromSidebar) { this.positionModel = 'sidebar'; } else { this.positionModel = 'absolute'; } return getPosition(this.dom, this.positionModel); } /** * 根据按钮获取按钮的父元素,这里父元素要绕过toolbar-(left|right)那一层 * @param {HTMLElement} dom 按钮元素 * @returns {HTMLElement} 父元素 */ static getTargetParentByButton(dom) { let parent = dom.parentElement; if (/toolbar-(left|right)/.test(parent.className)) { parent = parent.parentElement; } return parent; } }
package com.nancal.api.utils; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.nancal.common.constants.Constant; import com.nancal.common.enums.ErrorCode; import com.nancal.common.exception.ServiceException; import com.nancal.remote.service.RemoteLezaoCodeSetService; import com.nancal.remote.to.LezaoCodingTo; import com.nancal.remote.vo.DictItemVo; import com.nancal.remote.vo.LezaoResult; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Collections; import java.util.List; import java.util.Map; @Slf4j @Component public class CoderSetUtil { @Autowired private RemoteLezaoCodeSetService remoteLezaoCodeSetService; private List<String> getCoderListByType(String objectType, Integer count, String referenceValue, Map<Integer,String> variableValueMap){ String ruleCoding = objectType+"_itemId"; LezaoCodingTo lezaoCodingTo = LezaoCodingTo.builder().ruleCoding(ruleCoding).counts(count). referenceValue(referenceValue).variableValueMap(variableValueMap).build(); List<String> result = getCoderListByType(lezaoCodingTo, objectType); if(CollUtil.isEmpty(result)){ throw new ServiceException(ErrorCode.REMOTE_FAIL, "未获取到对应的code编码"); } return result; } public String getOneCoderByObjectType(String objectType){ if(StrUtil.isBlank(objectType)){ return null; } return getCoderListByType(objectType,1,null,null).get(0); } public List<String> getCoderListByObjectType(String objectType, Integer count, String referenceValue, Map<Integer,String> variableValueMap){ return getCoderListByType(objectType,count,referenceValue,variableValueMap); } /*** * 根据对像类型和字典类型,获取其下的字典明细 * * @param objectType 对像类型 * @param lezaoCodingTo 数据参数 * @author 徐鹏军 * @date 2022/4/12 12:29 * @return {@link List<DictItemVo>} */ private List<String> getCoderListByType(LezaoCodingTo lezaoCodingTo,String objectType) { LezaoResult<List<String>> result = remoteLezaoCodeSetService.getSpecificationCodeList(lezaoCodingTo); if (ObjectUtil.isNull(result)) { throw new ServiceException(ErrorCode.REMOTE_FAIL, "远程调用编码规则服务异常"); } if (CollUtil.isNotEmpty(result.getData())) { return result.getData(); } Class<?> clazz = EntityUtil.getEntityClass(objectType); String simpleName = clazz.getSuperclass().getSimpleName(); // 如果都找到了Object了,则直接放弃 if (Object.class.getSimpleName().equals(simpleName)) { return Collections.emptyList(); } // 将Entity字符串替换并递归调用本方法 String newObjectType = simpleName.replaceAll(Constant.ENTITY, StrUtil.EMPTY); String newRuleCoding = newObjectType + StrUtil.UNDERLINE + StrUtil.subAfter(lezaoCodingTo.getRuleCoding(), StrUtil.UNDERLINE, false); lezaoCodingTo.setRuleCoding(newRuleCoding); return getCoderListByType(lezaoCodingTo, newObjectType); } }
#import ## batteries import os,sys ## 3rd party import numpy as np from SIPSim_pymix import mixture class Fractions(object): """Simulated gradient fractions based on theoretical min-max of BD incorporation. Fraction size distribution is normal with user-defined params. """ def __init__(self, distribution, params, BD_min, BD_max, frac_min): """ Parameters ---------- distribution : str Name of distribution for selecting fraction sizes params : dict Distribution params passed to distribution function (pymix.mixture distributions) BD_min, BD_max : float Min|max BD for gradient fractions. frac_min : float Min size of any fraction. """ BD_min, BD_max, frac_min = map(float, (BD_min, BD_max, frac_min)) assert BD_min > 0 and BD_max > 0, "BD_min/max must be positive numbers" assert BD_max > BD_min, "BD_max must be > BD_min" assert frac_min > 0, "frac_min must be > 0" self.distribution = distribution self.params = params self.BD_min = BD_min self.BD_max = BD_max self.BD_range = BD_max - BD_min self.frac_min = frac_min self._set_distributionFunction() def _set_distributionFunction(self): """Set user-defined distribution (pymix distributions).""" psblFuncs = {'uniform' : mixture.UniformDistribution, 'normal' : mixture.NormalDistribution} try: func = psblFuncs[self.distribution.lower()] except KeyError: msg = 'Distribution "{}" not supported' raise KeyError(msg.format(self.distribution)) try: self.distFunc = func(**self.params) except TypeError: msg = 'Distribution "{}" does not accept all provided params: {}' raise TypeError(msg.format(self.distribution, ','.join(self.params.keys()))) def simFractions(self, libID, max_tries=1000): """Simulate the gradient fractions for a library. Parameters ---------- libID : str library ID (a.k.a. isopycnic gradient ID) max_tries : int max number of tries to get BD values in BD_range Returns ------- l2d : 2d-list [[BD_min_vals, BD_max_vals, BD_vals]] """ # sample & sum to get up to just past (BD_range - BD_max) # use truncated last value if value > frac_min BD_sums = 0 BD_vals = [] tries = 0 while True: fracSize = self.sample_frac_size(max_tries=max_tries) BD_sums += fracSize BD_vals.append(fracSize) BD_prog = self.BD_range - BD_sums if tries > max_tries: msg = 'Exceeded {} tries to make BD fractions. Giving up!\n' sys.stderr.write( msg.format(max_tries)) sys.exit(1) elif BD_sums > self.BD_range: remains = BD_sums - self.BD_range psblLastFrac = round(BD_vals[-1:][0] - remains, 3) if psblLastFrac >= self.frac_min: # last fraction set (not exceeding BD-range) BD_vals = BD_vals[:len(BD_vals)-1] + [psblLastFrac] break else: # start over BD_sums = 0 BD_vals = [] tries += 1 continue else: continue # flipping values around so that lightest fraction is truncated BD_vals.reverse() # making BD-min-max for each fraction ## cumulative addition BD_vals_cumsum = np.array(BD_vals).cumsum() BD_max_vals = BD_vals_cumsum + self.BD_min BD_min_vals = np.concatenate( (np.array([self.BD_min]), BD_max_vals[:len(BD_max_vals)-1]) ) return zip(BD_min_vals, BD_max_vals, BD_vals) def sample_frac_size(self, max_tries=1000): """Sampling from user-defined distribution. The value must be >= frac_min. """ tries = 0 while True: val = round(self.distFunc.sample(), 3) if val >= self.frac_min: return val else: tries += 1 if tries > max_tries: msg = 'Exceeded {} tries to make BD fraction ' + \ 'from user-defined distribution. Giving up!' print msg.format(max_tries) sys.exit(1)
# frozen_string_literal: true require 'spec_helper' RSpec.describe User::Sso::CreateOrUpdateUser, type: :actor do subject(:actor) { described_class.result(identity:, email:) } let(:identity) { build(:identity, user: nil) } let(:email) { Faker::Internet.email } describe '.result' do it { is_expected.to be_a_success } it { expect(actor.user).to be_a(User) } it { expect(actor.user).to be_persisted } it { expect(actor.user.email).to eq(email) } it { expect(actor.user.identities).to include(identity) } context 'when user exists' do let(:user) { create(:user) } let(:identity) { build(:identity, user: nil) } let(:email) { user.email } it { is_expected.to be_a_success } it { expect(actor.user.email).to eq(email) } it { expect(actor.user.identities).to include(identity) } end context 'when user exists with identity' do let(:user) { create(:user) } let(:identity) { build(:identity, user:) } let(:email) { user.email } it { is_expected.to be_a_success } it { expect(actor.user.email).to eq(email) } it { expect(actor.user.identities).to include(identity) } end end end
import { ChangeEvent, useEffect, useState } from "react"; import { useNavigate, useOutletContext, useParams } from "react-router-dom"; import { GenreData } from "./Genre.type"; import { Check, EditMovieResponse } from "./EditMovie.type"; import { MovieData } from "./Movie.type"; import { ErrorResponse } from "./Error.type"; import { Input } from "./form/Input"; import { Select } from "./form/Select"; import { TextArea } from "./form/TextArea"; import { Checkbox } from "./form/Checkbox"; export const EditMovie = () => { const navigate = useNavigate(); const { jwtToken } = useOutletContext<{ jwtToken: string }>(); const [error, setError] = useState<string | null>(null); const [errors, setErrors] = useState<string[]>([]); const mpaaOptions = [ { id: "G", value: "G" }, { id: "PG", value: "PG" }, { id: "PG13", value: "PG13" }, { id: "R", value: "R" }, { id: "NC17", value: "NC17" }, { id: "18A", value: "18A" }, ]; const hasError = (key: string) => { return errors.indexOf(key) !== -1; }; const [movie, setMovie] = useState<MovieData>({ id: 0, title: "", release_date: "", runtime: 0, mpaa_rating: "", description: "", genres: [], image: "", genres_array: [], }); // get id from the URL let { id } = useParams(); if (id === undefined) { id = "0"; } useEffect(() => { if (jwtToken === "") { navigate("/login"); return; } if (id === "0") { // adding a movie setMovie({ id: 0, title: "", release_date: "", runtime: 0, mpaa_rating: "", description: "", genres: [], image: "", genres_array: [], }); const headers = new Headers(); headers.append("Content-Type", "application/json"); const requestOptions = { method: "GET", headers: headers, }; fetch(`http://localhost:4000/v1/genres`, requestOptions) .then((response) => response.json()) .then((data: GenreData[]) => { const checks: Check[] = []; data.forEach((g: GenreData) => { checks.push({ id: g.id, checked: false, genre: g.genre }); }); setMovie((m) => ({ ...m, genres: checks, genres_array: [], })); }) .catch((err) => { console.log(err); }); } else { // editing an existing movie const headers = new Headers(); headers.append("Content-Type", "application/json"); headers.append("Authorization", "Bearer " + jwtToken); const requestOptions = { method: "GET", headers: headers, }; fetch(`http://localhost:4000/v1/admin/movies/${id}`, requestOptions) .then((response: Response) => { if (response.status !== 200) { setError("Invalid response code: " + response.status); } return response.json(); }) .then((data: EditMovieResponse) => { console.log("-->data:", data); // fix release date data.movie.release_date = new Date(data.movie.release_date) .toISOString() .split("T")[0]; const checks: Check[] = []; data.genres.forEach((g: GenreData) => { if (data.movie.genres_array.indexOf(g.id) !== -1) { checks.push({ id: g.id, checked: true, genre: g.genre }); } else { checks.push({ id: g.id, checked: false, genre: g.genre }); } }); // set state setMovie({ ...data.movie, genres: checks, }); }) .catch((err) => { console.log(err); }); } }, [id, jwtToken, navigate]); const handleSubmit = (event: React.FormEvent) => { event.preventDefault(); let errors = []; let required = [ { field: movie.title, name: "title" }, { field: movie.image, name: "image" }, { field: movie.release_date, name: "release_date" }, { field: movie.runtime, name: "runtime" }, { field: movie.description, name: "description" }, { field: movie.mpaa_rating, name: "mpaa_rating" }, ]; required.forEach(function (obj) { if (obj.field === "") { errors.push(obj.name); } }); if (movie.genres_array.length === 0) { alert("Error! You must choose at least one genre!"); errors.push("genres"); } setErrors(errors); if (errors.length > 0) { return false; } // passed validation, so save changes const headers = new Headers(); headers.append("Content-Type", "application/json"); headers.append("Authorization", "Bearer " + jwtToken); // assume we are adding a new movie let method = "PUT"; if (movie.id > 0) { method = "PATCH"; } const requestBody = movie; // we need to covert the values in JSON for release date (to date) // and for runtime to int requestBody.release_date = new Date(movie.release_date).toISOString().split("T")[0] + "T00:00:00Z"; requestBody.runtime = parseInt(movie.runtime.toString(), 10); let requestOptions: RequestInit = { body: JSON.stringify(requestBody), method: method, headers: headers, credentials: "include", }; fetch(`http://localhost:4000/v1/admin/movies/${movie.id}`, requestOptions) .then((response) => response.json()) .then((data) => { if (data.error) { console.log(data.error); } else { navigate("/manage-catalogue"); } }) .catch((err) => { console.log(err); }); }; const handleChange = () => ( event: ChangeEvent< HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement > ) => { let value = event.target.value; let name = event.target.name; setMovie({ ...movie, [name]: value, }); }; const handleCheck = (event: any, position: number) => { console.log("handleCheck called"); console.log("value in handleCheck:", event.target.value); console.log("checked is", event.target.checked); console.log("position is", position); let tmpArr = movie.genres; tmpArr[position].checked = !tmpArr[position].checked; let tmpIDs: any = movie.genres_array; if (!event.target.checked) { tmpIDs.splice(tmpIDs.indexOf(event.target.value)); } else { tmpIDs.push(parseInt(event.target.value, 10)); } setMovie({ ...movie, genres_array: tmpIDs, }); }; const confirmDelete = () => { var confirmation: Boolean = confirm("Delete movie?"); if (confirmation) { let headers = new Headers(); headers.append("Authorization", "Bearer " + jwtToken); const requestOptions: RequestInit = { method: "DELETE", headers: headers, }; fetch(`http://localhost:4000/v1/admin/movies/${movie.id}`, requestOptions) .then((response: Response) => response.json()) .then((data: unknown) => { if ((data as ErrorResponse).error == "true") { console.log(data as ErrorResponse); } else { navigate("/manage-catalogue"); } }) .catch((err) => { console.log(err); }); } }; if (error !== null) { return <div>Error: {error}</div>; } else { return ( <div className="card w-full bg-base-200"> <div className="card-body"> <h2 className="card-title">Add/Edit Movie</h2> <div className="devider py-2"></div> {/* <pre>{JSON.stringify(movie, null, 3)}</pre> */} <form onSubmit={handleSubmit}> <input type="hidden" name="id" value={movie.id} id="id"></input> <Input title={"Title"} className={""} type={"text"} name={"title"} value={movie.title} onChange={handleChange()} errorDiv={hasError("title") ? "" : "hidden"} errorMsg={"Please enter a title"} /> <Input title={"Image URL"} className={""} type={"text"} name={"image"} value={movie.image} onChange={handleChange()} errorDiv={hasError("title") ? "" : "hidden"} errorMsg={"Please enter a image url"} /> <Input title={"Release Date"} className={""} type={"date"} name={"release_date"} value={movie.release_date} onChange={handleChange()} errorDiv={hasError("release_date") ? "" : "hidden"} errorMsg={"Please enter a release date"} /> <Input title={"Runtime"} className={""} type={"number"} name={"runtime"} value={movie.runtime} onChange={handleChange()} errorDiv={hasError("runtime") ? "" : "hidden"} errorMsg={"Please enter a runtime"} /> <Select title={"MPAA Rating"} name={"mpaa_rating"} options={mpaaOptions} value={movie.mpaa_rating} onChange={handleChange()} placeHolder={"Choose..."} errorMsg={"Please choose"} errorDiv={hasError("mpaa_rating") ? "" : "hidden"} /> <TextArea title="Description" name={"description"} value={movie.description} rows={3} onChange={handleChange()} errorMsg={"Please enter a description"} errorDiv={hasError("description") ? "" : "hidden"} /> <div className="devider py-2"></div> <div className="card bg-base-300"> <div className="card-body"> <h3 className="card-title">Genres</h3> {movie.genres && movie.genres.length > 1 && ( <> {Array.from(movie.genres).map((g, index) => ( <Checkbox title={g.genre} name={"genre"} key={index} id={"genre-" + index.toString()} onChange={(event) => handleCheck(event, index)} value={g.id.toString()} checked={movie.genres[index].checked} /> ))} </> )} </div> </div> <div className="devider py-2"></div> <button className="btn btn-primary">Save</button> {movie.id > 0 && ( <a href="#!" className="btn btn-danger ms-2" onClick={confirmDelete} > Delete Movie </a> )} </form> </div> </div> ); } };
import 'package:efood_multivendor_restaurant/controller/auth_controller.dart'; import 'package:efood_multivendor_restaurant/controller/order_controller.dart'; import 'package:efood_multivendor_restaurant/util/dimensions.dart'; import 'package:efood_multivendor_restaurant/view/base/custom_app_bar.dart'; import 'package:efood_multivendor_restaurant/view/screens/home/widget/order_button.dart'; import 'package:efood_multivendor_restaurant/view/screens/order/widget/count_widget.dart'; import 'package:efood_multivendor_restaurant/view/screens/order/widget/order_view.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class OrderHistoryScreen extends StatelessWidget { @override Widget build(BuildContext context) { Get.find<OrderController>().getPaginatedOrders(1, true); return Scaffold( appBar: CustomAppBar(title: 'order_history'.tr, isBackButtonExist: false), body: GetBuilder<OrderController>(builder: (orderController) { return Padding( padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL), child: Column(children: [ GetBuilder<AuthController>(builder: (authController) { return authController.profileModel != null ? Container( decoration: BoxDecoration( color: Theme.of(context).primaryColor, borderRadius: BorderRadius.circular(Dimensions.RADIUS_SMALL), ), child: Row(children: [ CountWidget(title: 'today'.tr, count: authController.profileModel.todaysOrderCount), CountWidget(title: 'this_week'.tr, count: authController.profileModel.thisWeekOrderCount), CountWidget(title: 'this_month'.tr, count: authController.profileModel.thisMonthOrderCount), ]), ) : SizedBox(); }), SizedBox(height: Dimensions.PADDING_SIZE_LARGE), Container( height: 40, decoration: BoxDecoration( border: Border.all(color: Theme.of(context).disabledColor, width: 1), borderRadius: BorderRadius.circular(Dimensions.RADIUS_SMALL), ), child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: orderController.statusList.length, itemBuilder: (context, index) { return OrderButton( title: orderController.statusList[index].tr, index: index, orderController: orderController, fromHistory: true, ); }, ), ), SizedBox(height: orderController.historyOrderList != null ? Dimensions.PADDING_SIZE_SMALL : 0), Expanded( child: orderController.historyOrderList != null ? orderController.historyOrderList.length > 0 ? OrderView() : Center(child: Text('no_order_found'.tr)) : Center(child: CircularProgressIndicator()), ), ]), ); }), ); } }
"use client"; import { useMutation } from "@tanstack/react-query"; import { useForm } from "react-hook-form"; import { httpPost } from "@/lib/axios/services"; interface LoginFormProps { onLogin: () => void; // You can pass additional parameters for login if needed } interface LoginFormData { email: string; password: string; } export default function Login() { const { register, handleSubmit, formState: { errors }, } = useForm<LoginFormData>(); const { mutate, isPending } = useMutation({ mutationFn: (data: LoginFormData) => httpPost("/auth/login", data), onSuccess: () => {}, onError: (error) => { console.error("Login failed:", error); alert("Login failed. Please check your credentials."); }, }); const onSubmit = (data: LoginFormData) => { mutate(data); }; return ( <div className="flex h-screen w-screen items-center justify-center bg-gray-50"> <div className="z-10 w-full max-w-md overflow-hidden rounded-2xl border border-gray-100 shadow-xl"> <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 bg-white px-4 py-6 pt-8 text-center sm:px-16"> <h3 className="text-xl font-semibold">Sign In</h3> <p className="text-sm text-gray-500"> Use your email and password to sign in </p> </div> <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 sm:px-16" > <div> <label className="block text-xs text-gray-600 uppercase" htmlFor="email" > Email: </label> <input type="text" id="email" className="mt-1 block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm" {...register("email", { required: true })} /> {errors.email && <span>This field is required</span>} </div> <div> <label className="block text-xs text-gray-600 uppercase" htmlFor="password" > Password: </label> <input type="password" id="password" className="mt-1 block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm" {...register("password", { required: true })} /> {errors.password && <span>This field is required</span>} </div> <button type="submit" disabled={isPending}> Login </button> {isPending && <div>Loading...</div>} </form> </div> </div> ); }
<?php namespace app\controllers; use Yii; use app\models\SchoolClass; use app\models\SchoolClassSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use app\models\Model; /** * SchoolClassController implements the CRUD actions for SchoolClass model. */ class SchoolClassController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Lists all SchoolClass models. * @return mixed */ public function actionIndex() { $searchModel = new SchoolClassSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single SchoolClass model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new SchoolClass model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new SchoolClass(); if ($model->load(Yii::$app->request->post())){ $valid = $model->validate(); if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $model->save(false)) { if ($flag) { $transaction->commit(); Yii::$app->session->setFlash('success', yii::t('app', 'Created <i>{attribute}</i> successfully', ['attribute' => $model->cl_name])); return $this->redirect(['view', 'id' => $model->cl_id]); } } } catch (Exception $e) { $transaction->rollBack(); } } else{ Yii::$app->session->setFlash('danger', yii::t('app', 'There are validation errors in your form. Please check your input details.')); } } return $this->render('create', [ 'model' => $model, ]); /* if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->cl_id]); } else { return $this->render('create', [ 'model' => $model, ]); } */ } /** * Updates an existing SchoolClass model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post())){ $valid = $model->validate(); if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $model->save(false)) { if ($flag) { $transaction->commit(); Yii::$app->session->setFlash('success', yii::t('app', 'Saved <i>{attribute}</i> successfully', ['attribute' => $model->cl_name])); return $this->redirect(['view', 'id' => $model->cl_id]); } } } catch (Exception $e) { $transaction->rollBack(); } } else{ Yii::$app->session->setFlash('danger', yii::t('app', 'There are validation errors in your form. Please check your input details.')); } } return $this->render('update', [ 'model' => $model, ]); } /** * Deletes an existing SchoolClass model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the SchoolClass model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return SchoolClass the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = SchoolClass::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
<template> <v-container> <v-form @submit.prevent="signup" > <v-text-field v-model="form.name" type="text" label="Name" required ></v-text-field> <span class="red--text" v-if="errors.name">{{errors.name[0]}}</span> <v-text-field v-model="form.email" type="email" label="E-mail" required ></v-text-field> <span class="red--text" v-if="errors.email">{{errors.email[0]}}</span> <v-text-field v-model="form.password" type="password" label="Password" required ></v-text-field> <span class="red--text" v-if="errors.password">{{errors.password[0]}}</span> <v-text-field v-model="form.password_confirmation" type="password" label="Confirm Password" required ></v-text-field> <v-btn type="submit" color="success"> Signup </v-btn> <router-link to="/login"> <v-btn text color="primary">Login</v-btn> </router-link> </v-form> </v-container> </template> <script> export default { name: "Signup", created() { if (User.loggedIn()) this.$router.push({name: 'forum'}); }, data() { return { form: { name: null, email: null, password: null, password_confirmation: null }, errors: {} } }, methods: { signup() { axios.post('/api/auth/signup', this.form) .then(response => { this.errors = {}; User.responseAfterLogin(response); }) .catch(error => this.errors = error.response.data.errors); } } } </script> <style scoped> </style>
import 'package:flutter/material.dart'; class Result extends StatelessWidget { final int resultScore; final Function resetHandler; Result(this.resultScore, this.resetHandler); String get resultPhrase { String resultText; if (resultScore <= 8) { resultText = 'You are awesome and innoenct'; } else if (resultScore <= 12) { resultText = 'Pretty Likeable!'; } else if (resultScore <= 16) { resultText = 'You are ... Strange!'; } else { resultText = 'You are so bad..'; } return resultText; } // Result(this.resultScore); @override Widget build(BuildContext context) { return Center( child: Column( // ignore: prefer_const_literals_to_create_immutables children: <Widget>[ Text( resultPhrase, style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold), textAlign: TextAlign.center, ), TextButton( child: Text( 'Reset Quiz!', ), //Color: Colors.blue, onPressed: resetHandler, ) ], ), ); } }
package org.sopt.santamanitto.room.network import org.sopt.santamanitto.room.create.network.CreateRoomRequestModel import org.sopt.santamanitto.room.create.network.CreateRoomModel import org.sopt.santamanitto.room.create.network.ModifyRoomRequestModel import org.sopt.santamanitto.room.data.PersonalRoomModel import org.sopt.santamanitto.room.join.network.JoinRoomRequestModel import org.sopt.santamanitto.room.join.network.JoinRoomModel import org.sopt.santamanitto.room.manittoroom.network.ManittoRoomModel import org.sopt.santamanitto.room.manittoroom.network.MatchedMissionsModel interface RoomRequest { interface CreateRoomCallback { fun onRoomCreated(createdRoom: CreateRoomModel) fun onFailed() } interface JoinRoomCallback { fun onSuccessJoinRoom(joinedRoom: JoinRoomModel) fun onFailed(joinRoomError: JoinRoomError) } interface GetManittoRoomCallback { fun onLoadManittoRoomData(manittoRoom: ManittoRoomModel) fun onFailed() } interface MatchManittoCallback { fun onSuccessMatching(missions: List<MatchedMissionsModel>) fun onFailed() } interface GetPersonalRoomInfoCallback { fun onLoadPersonalRoomInfo(personalRoom: PersonalRoomModel) fun onDataNotAvailable() } enum class JoinRoomError { WrongInvitationCode, DuplicatedMember, AlreadyMatched, AlreadyEntered, Els } fun createRoom(request: CreateRoomRequestModel, callback: CreateRoomCallback) fun modifyRoom(roomId: Int, request: ModifyRoomRequestModel, callback: (onSuccess: Boolean) -> Unit) fun joinRoom(request: JoinRoomRequestModel, callback: JoinRoomCallback) fun getManittoRoomData(roomId: Int, callback: GetManittoRoomCallback) fun matchManitto(roomId: Int, callback: MatchManittoCallback) fun getPersonalRoomInfo(roomId: Int, callback: GetPersonalRoomInfoCallback) fun exitRoom(roomId: Int, callback: (onSuccess: Boolean) -> Unit) fun removeHistory(roomId: Int, callback: (onSuccess: Boolean) -> Unit) }
import axios from 'axios'; import { ApiResponse, Langs, Methods } from './@types'; import { SubscribeParams, defaultSubscribeParams } from './@types/subscribe-params.interface'; export class UnisenderAPI { private api_key: string; private lang: Langs; private timeout: number; private api_url: string; constructor(api_key: string, lang: Langs = Langs.en, timeout: number = 60) { this.api_key = api_key; this.lang = lang; this.timeout = timeout; this.api_url = 'https://api.unisender.com/%lang/api/%method?format=json'; } private async call(method: Methods, params: { [key: string]: any } = {}): Promise<ApiResponse> { if (!Object.values(Methods).includes(method)) { throw new Error('Unsupported Method'); } params.api_key = this.api_key; const url = `${this.api_url.replace('%lang', this.lang).replace('%method', method)}${ params ? `&${new URLSearchParams(params).toString()}` : '' }`; let result: ApiResponse = {}; try { const response = await axios.post(url, {}, { timeout: this.timeout * 1000 }); result = response.data; } catch (error) { if (axios.isAxiosError(error)) { if (error.code === 'ECONNABORTED') { result = { error: `Timeout waiting expired [${this.timeout} sec]` }; } else { result = { error: `Max retries exceeded [${axios.defaults.maxRedirects}]` }; } } else { result = { error: 'Error on decode api response' }; } } return result; } async getLists(): Promise<ApiResponse> { return this.call(Methods.getLists); } async subscribe(subscribeParams: Partial<SubscribeParams>): Promise<ApiResponse> { let { list_ids, email, name, tags, double_optin, overwrite, confirmed } = { ...defaultSubscribeParams, ...subscribeParams, }; const list_ids_str = list_ids.join(','); const tags_str = tags.slice(0, 10).join(','); double_optin = confirmed ? 3 : double_optin; double_optin = [0, 3, 4].includes(double_optin) ? double_optin : 0; overwrite = [0, 1, 2].includes(overwrite) ? overwrite : 0; const params = { list_ids: list_ids_str, 'fields[email]': email, 'fields[Name]': name, tags: tags_str, double_optin, overwrite, }; return this.call(Methods.subscribe, params); } }
import { Injectable } from '@angular/core'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import * as clientsActions from '../actions/clientes.actions'; import { mergeMap, map, catchError } from 'rxjs/operators'; import { ClientsService } from '../../services/clients.service'; import { of } from 'rxjs'; @Injectable() export class ClientsEffects { constructor( private actions$: Actions, private ClientsService: ClientsService ){} loadClients$ = createEffect( () => this.actions$.pipe( ofType( clientsActions.loadClients ), mergeMap( () => this.ClientsService.getClients() .pipe( map( clients => clientsActions.loadClientsSuccess({ clients }) ), catchError( err => of(clientsActions.loadClientsError({ payload: err })) ) ) ) ) ); }
/* ! tailwindcss v3.2.4 | MIT License | https://tailwindcss.com */ /* 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) 2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) */ *, ::before, ::after { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ border-color: #e5e7eb; /* 2 */ } ::before, ::after { --tw-content: ''; } /* 1. Use a consistent sensible line-height in all browsers. 2. Prevent adjustments of font size after orientation changes in iOS. 3. Use a more readable tab size. 4. Use the user's configured `sans` font-family by default. 5. Use the user's configured `sans` font-feature-settings by default. */ html { line-height: 1.5; /* 1 */ -webkit-text-size-adjust: 100%; /* 2 */ /* 3 */ tab-size: 4; /* 3 */ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; /* 4 */ -webkit-font-feature-settings: normal; font-feature-settings: normal; /* 5 */ } /* 1. Remove the margin in all browsers. 2. Inherit line-height from `html` so users can set them as a class directly on the `html` element. */ body { margin: 0; /* 1 */ line-height: inherit; /* 2 */ } /* 1. Add the correct height in Firefox. 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) 3. Ensure horizontal rules are visible by default. */ hr { height: 0; /* 1 */ color: inherit; /* 2 */ border-top-width: 1px; /* 3 */ } /* Add the correct text decoration in Chrome, Edge, and Safari. */ abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } /* Remove the default font size and weight for headings. */ h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } /* Reset links to optimize for opt-in styling instead of opt-out. */ a { color: inherit; text-decoration: inherit; } /* Add the correct font weight in Edge and Safari. */ b, strong { font-weight: bolder; } /* 1. Use the user's configured `mono` font family by default. 2. Correct the odd `em` font sizing in all browsers. */ code, kbd, samp, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; /* 1 */ font-size: 1em; /* 2 */ } /* Add the correct font size in all browsers. */ small { font-size: 80%; } /* Prevent `sub` and `sup` elements from affecting the line height in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } /* 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) 3. Remove gaps between table borders by default. */ table { text-indent: 0; /* 1 */ border-color: inherit; /* 2 */ border-collapse: collapse; /* 3 */ } /* 1. Change the font styles in all browsers. 2. Remove the margin in Firefox and Safari. 3. Remove default padding in all browsers. */ button, input, optgroup, select, textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 1 */ font-weight: inherit; /* 1 */ line-height: inherit; /* 1 */ color: inherit; /* 1 */ margin: 0; /* 2 */ padding: 0; /* 3 */ } /* Remove the inheritance of text transform in Edge and Firefox. */ button, select { text-transform: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Remove default button styles. */ button, [type='button'], [type='reset'], [type='submit'] { -webkit-appearance: button; /* 1 */ background-color: transparent; /* 2 */ background-image: none; /* 2 */ } /* Use the modern Firefox focus style for all focusable elements. */ :-moz-focusring { outline: auto; } /* Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) */ :-moz-ui-invalid { box-shadow: none; } /* Add the correct vertical alignment in Chrome and Firefox. */ progress { vertical-align: baseline; } /* Correct the cursor style of increment and decrement buttons in Safari. */ ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } /* 1. Correct the odd appearance in Chrome and Safari. 2. Correct the outline style in Safari. */ [type='search'] { -webkit-appearance: textfield; /* 1 */ outline-offset: -2px; /* 2 */ } /* Remove the inner padding in Chrome and Safari on macOS. */ ::-webkit-search-decoration { -webkit-appearance: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Change font properties to `inherit` in Safari. */ ::-webkit-file-upload-button { -webkit-appearance: button; /* 1 */ font: inherit; /* 2 */ } /* Add the correct display in Chrome and Safari. */ summary { display: list-item; } /* Removes the default spacing and border for appropriate elements. */ blockquote, dl, dd, h1, h2, h3, h4, h5, h6, hr, figure, p, pre { margin: 0; } fieldset { margin: 0; padding: 0; } legend { padding: 0; } ol, ul, menu { list-style: none; margin: 0; padding: 0; } /* Prevent resizing textareas horizontally by default. */ textarea { resize: vertical; } /* 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) 2. Set the default placeholder color to the user's configured gray 400 color. */ input::-webkit-input-placeholder, textarea::-webkit-input-placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } input::placeholder, textarea::placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } /* Set the default cursor for buttons. */ button, [role="button"] { cursor: pointer; } /* Make sure disabled buttons don't get the pointer cursor. */ :disabled { cursor: default; } /* 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) This can trigger a poorly considered lint error in some tools but is included by design. */ img, svg, video, canvas, audio, iframe, embed, object { display: block; /* 1 */ vertical-align: middle; /* 2 */ } /* Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) */ img, video { max-width: 100%; height: auto; } /* Make elements with the HTML hidden attribute stay hidden by default */ [hidden] { display: none; } h1 { font-size: 1.875rem; line-height: 2.25rem; font-weight: 700; --tw-text-opacity: 1; color: rgb(24 24 27 / var(--tw-text-opacity)); margin-top: 0.25rem; margin-bottom: 0.25rem; } h2 { font-size: 1.5rem; line-height: 2rem; font-weight: 700; --tw-text-opacity: 1; color: rgb(24 24 27 / var(--tw-text-opacity)); margin-top: 0.25rem; margin-bottom: 0.25rem; } h3 { font-size: 1.5rem; line-height: 2rem; font-weight: 700; margin-top: 0.25rem; margin-bottom: 0.25rem; } h4 { font-size: 1.25rem; line-height: 1.75rem; font-weight: 700; --tw-text-opacity: 1; color: rgb(24 24 27 / var(--tw-text-opacity)); } blockquote { border-style: solid; border-left-width: 2px; --tw-border-opacity: 1; border-color: rgb(109 40 217 / var(--tw-border-opacity)); --tw-text-opacity: 1; color: rgb(31 41 55 / var(--tw-text-opacity)); padding: 0.5rem; padding-left: 1rem; } pre { overflow-y: auto; border-radius: 0.375rem; } ul, ol { list-style: revert; } *, ::before, ::after { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } ::-webkit-backdrop { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } ::backdrop { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } .container { width: 100%; } @media (min-width: 640px) { .container { max-width: 640px; } } @media (min-width: 768px) { .container { max-width: 768px; } } @media (min-width: 1024px) { .container { max-width: 1024px; } } @media (min-width: 1280px) { .container { max-width: 1280px; } } @media (min-width: 1536px) { .container { max-width: 1536px; } } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border-width: 0; } .fixed { position: fixed; } .absolute { position: absolute; } .relative { position: relative; } .inset-y-0 { top: 0px; bottom: 0px; } .-top-3 { top: -0.75rem; } .bottom-2 { bottom: 0.5rem; } .bottom-0 { bottom: 0px; } .right-2 { right: 0.5rem; } .left-0 { left: 0px; } .top-0 { top: 0px; } .right-0 { right: 0px; } .right-4 { right: 1rem; } .top-16 { top: 4rem; } .top-60 { top: 15rem; } .top-1\/2 { top: 50%; } .z-50 { z-index: 50; } .z-40 { z-index: 40; } .z-20 { z-index: 20; } .col-span-2 { grid-column: span 2 / span 2; } .col-span-full { grid-column: 1 / -1; } .col-span-12 { grid-column: span 12 / span 12; } .row-span-full { grid-row: 1 / -1; } .m-auto { margin: auto; } .-m-2 { margin: -0.5rem; } .mx-auto { margin-left: auto; margin-right: auto; } .-mx-4 { margin-left: -1rem; margin-right: -1rem; } .my-8 { margin-top: 2rem; margin-bottom: 2rem; } .my-2 { margin-top: 0.5rem; margin-bottom: 0.5rem; } .mx-3 { margin-left: 0.75rem; margin-right: 0.75rem; } .my-3 { margin-top: 0.75rem; margin-bottom: 0.75rem; } .-mx-2 { margin-left: -0.5rem; margin-right: -0.5rem; } .mx-1 { margin-left: 0.25rem; margin-right: 0.25rem; } .mx-2 { margin-left: 0.5rem; margin-right: 0.5rem; } .-mx-6 { margin-left: -1.5rem; margin-right: -1.5rem; } .mb-8 { margin-bottom: 2rem; } .mt-4 { margin-top: 1rem; } .mt-2 { margin-top: 0.5rem; } .mr-20 { margin-right: 5rem; } .ml-20 { margin-left: 5rem; } .mb-4 { margin-bottom: 1rem; } .ml-2 { margin-left: 0.5rem; } .mt-16 { margin-top: 4rem; } .mt-14 { margin-top: 3.5rem; } .mb-14 { margin-bottom: 3.5rem; } .mt-10 { margin-top: 2.5rem; } .ml-4 { margin-left: 1rem; } .ml-6 { margin-left: 1.5rem; } .mt-12 { margin-top: 3rem; } .mt-20 { margin-top: 5rem; } .mb-12 { margin-bottom: 3rem; } .ml-auto { margin-left: auto; } .mt-6 { margin-top: 1.5rem; } .mt-8 { margin-top: 2rem; } .ml-11 { margin-left: 2.75rem; } .mb-16 { margin-bottom: 4rem; } .mr-5 { margin-right: 1.25rem; } .mb-2 { margin-bottom: 0.5rem; } .mr-2 { margin-right: 0.5rem; } .mb-20 { margin-bottom: 5rem; } .mb-6 { margin-bottom: 1.5rem; } .mr-3 { margin-right: 0.75rem; } .mr-8 { margin-right: 2rem; } .mb-1 { margin-bottom: 0.25rem; } .ml-1 { margin-left: 0.25rem; } .mt-5 { margin-top: 1.25rem; } .mb-5 { margin-bottom: 1.25rem; } .mr-4 { margin-right: 1rem; } .ml-7 { margin-left: 1.75rem; } .ml-12 { margin-left: 3rem; } .ml-10 { margin-left: 2.5rem; } .ml-3 { margin-left: 0.75rem; } .mb-3 { margin-bottom: 0.75rem; } .block { display: block; } .inline-block { display: inline-block; } .inline { display: inline; } .flex { display: flex; } .inline-flex { display: inline-flex; } .table { display: table; } .grid { display: grid; } .hidden { display: none; } .aspect-square { aspect-ratio: 1 / 1; } .h-screen { height: 100vh; } .h-full { height: 100%; } .h-3 { height: 0.75rem; } .h-20 { height: 5rem; } .h-1 { height: 0.25rem; } .h-6 { height: 1.5rem; } .h-8 { height: 2rem; } .h-10 { height: 2.5rem; } .h-7 { height: 1.75rem; } .h-16 { height: 4rem; } .h-5 { height: 1.25rem; } .h-80 { height: 20rem; } .h-96 { height: 24rem; } .min-h-screen { min-height: 100vh; } .w-full { width: 100%; } .w-3 { width: 0.75rem; } .w-fit { width: -webkit-fit-content; width: -moz-fit-content; width: fit-content; } .w-1\/2 { width: 50%; } .w-6 { width: 1.5rem; } .w-8 { width: 2rem; } .w-10 { width: 2.5rem; } .w-screen { width: 100vw; } .w-7 { width: 1.75rem; } .w-48 { width: 12rem; } .w-5 { width: 1.25rem; } .w-20 { width: 5rem; } .w-44 { width: 11rem; } .min-w-full { min-width: 100%; } .min-w-max { min-width: -webkit-max-content; min-width: max-content; } .max-w-md { max-width: 28rem; } .max-w-7xl { max-width: 80rem; } .max-w-lg { max-width: 32rem; } .max-w-3xl { max-width: 48rem; } .max-w-xs { max-width: 20rem; } .flex-1 { flex: 1 1 0%; } .flex-shrink-0 { flex-shrink: 0; } .shrink-0 { flex-shrink: 0; } .table-auto { table-layout: auto; } .origin-center { -webkit-transform-origin: center; transform-origin: center; } .origin-top-right { -webkit-transform-origin: top right; transform-origin: top right; } .-translate-y-1\/2 { --tw-translate-y: -50%; -webkit-transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .rotate-90 { --tw-rotate: 90deg; -webkit-transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .transform { -webkit-transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } @-webkit-keyframes spin { to { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes spin { to { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } .animate-spin { -webkit-animation: spin 1s linear infinite; animation: spin 1s linear infinite; } .cursor-pointer { cursor: pointer; } .list-none { list-style-type: none; } .grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } .grid-cols-12 { grid-template-columns: repeat(12, minmax(0, 1fr)); } .flex-row { flex-direction: row; } .flex-col { flex-direction: column; } .flex-wrap { flex-wrap: wrap; } .items-center { align-items: center; } .items-baseline { align-items: baseline; } .justify-start { justify-content: flex-start; } .justify-end { justify-content: flex-end; } .justify-center { justify-content: center; } .justify-between { justify-content: space-between; } .justify-evenly { justify-content: space-evenly; } .gap-2 { gap: 0.5rem; } .gap-3 { gap: 0.75rem; } .gap-4 { gap: 1rem; } .space-x-2 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(0.5rem * var(--tw-space-x-reverse)); margin-left: calc(0.5rem * calc(1 - var(--tw-space-x-reverse))); } .space-y-6 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(1.5rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(1.5rem * var(--tw-space-y-reverse)); } .space-y-4 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(1rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(1rem * var(--tw-space-y-reverse)); } .space-y-1 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(0.25rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(0.25rem * var(--tw-space-y-reverse)); } .space-x-4 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(1rem * var(--tw-space-x-reverse)); margin-left: calc(1rem * calc(1 - var(--tw-space-x-reverse))); } .divide-y > :not([hidden]) ~ :not([hidden]) { --tw-divide-y-reverse: 0; border-top-width: calc(1px * calc(1 - var(--tw-divide-y-reverse))); border-bottom-width: calc(1px * var(--tw-divide-y-reverse)); } .self-center { align-self: center; } .overflow-auto { overflow: auto; } .overflow-hidden { overflow: hidden; } .overflow-x-auto { overflow-x: auto; } .overflow-y-auto { overflow-y: auto; } .overflow-x-hidden { overflow-x: hidden; } .break-words { overflow-wrap: break-word; } .rounded { border-radius: 0.25rem; } .rounded-lg { border-radius: 0.5rem; } .rounded-md { border-radius: 0.375rem; } .rounded-full { border-radius: 9999px; } .rounded-sm { border-radius: 0.125rem; } .rounded-xl { border-radius: 0.75rem; } .rounded-r-lg { border-top-right-radius: 0.5rem; border-bottom-right-radius: 0.5rem; } .border { border-width: 1px; } .border-2 { border-width: 2px; } .border-4 { border-width: 4px; } .border-b { border-bottom-width: 1px; } .border-b-2 { border-bottom-width: 2px; } .border-t { border-top-width: 1px; } .border-l-4 { border-left-width: 4px; } .border-t-2 { border-top-width: 2px; } .border-dashed { border-style: dashed; } .border-none { border-style: none; } .border-gray-300 { --tw-border-opacity: 1; border-color: rgb(209 213 219 / var(--tw-border-opacity)); } .border-gray-700 { --tw-border-opacity: 1; border-color: rgb(55 65 81 / var(--tw-border-opacity)); } .border-emerald-500 { --tw-border-opacity: 1; border-color: rgb(16 185 129 / var(--tw-border-opacity)); } .border-zinc-900 { --tw-border-opacity: 1; border-color: rgb(24 24 27 / var(--tw-border-opacity)); } .border-red-500 { --tw-border-opacity: 1; border-color: rgb(239 68 68 / var(--tw-border-opacity)); } .bg-orange-200 { --tw-bg-opacity: 1; background-color: rgb(254 215 170 / var(--tw-bg-opacity)); } .bg-gray-100 { --tw-bg-opacity: 1; background-color: rgb(243 244 246 / var(--tw-bg-opacity)); } .bg-white { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)); } .bg-gray-400 { --tw-bg-opacity: 1; background-color: rgb(156 163 175 / var(--tw-bg-opacity)); } .bg-gray-500 { --tw-bg-opacity: 1; background-color: rgb(107 114 128 / var(--tw-bg-opacity)); } .bg-zinc-900 { --tw-bg-opacity: 1; background-color: rgb(24 24 27 / var(--tw-bg-opacity)); } .bg-green-300 { --tw-bg-opacity: 1; background-color: rgb(134 239 172 / var(--tw-bg-opacity)); } .bg-red-300 { --tw-bg-opacity: 1; background-color: rgb(252 165 165 / var(--tw-bg-opacity)); } .bg-slate-200 { --tw-bg-opacity: 1; background-color: rgb(226 232 240 / var(--tw-bg-opacity)); } .bg-zinc-400 { --tw-bg-opacity: 1; background-color: rgb(161 161 170 / var(--tw-bg-opacity)); } .bg-red-50 { --tw-bg-opacity: 1; background-color: rgb(254 242 242 / var(--tw-bg-opacity)); } .bg-red-100 { --tw-bg-opacity: 1; background-color: rgb(254 226 226 / var(--tw-bg-opacity)); } .bg-red-700 { --tw-bg-opacity: 1; background-color: rgb(185 28 28 / var(--tw-bg-opacity)); } .bg-red-500 { --tw-bg-opacity: 1; background-color: rgb(239 68 68 / var(--tw-bg-opacity)); } .bg-lime-500 { --tw-bg-opacity: 1; background-color: rgb(132 204 22 / var(--tw-bg-opacity)); } .bg-gray-800 { --tw-bg-opacity: 1; background-color: rgb(31 41 55 / var(--tw-bg-opacity)); } .bg-blue-300 { --tw-bg-opacity: 1; background-color: rgb(147 197 253 / var(--tw-bg-opacity)); } .bg-amber-500 { --tw-bg-opacity: 1; background-color: rgb(245 158 11 / var(--tw-bg-opacity)); } .bg-red-600 { --tw-bg-opacity: 1; background-color: rgb(220 38 38 / var(--tw-bg-opacity)); } .bg-gray-50 { --tw-bg-opacity: 1; background-color: rgb(249 250 251 / var(--tw-bg-opacity)); } .bg-opacity-80 { --tw-bg-opacity: 0.8; } .bg-cover { background-size: cover; } .bg-no-repeat { background-repeat: no-repeat; } .fill-yellow-400 { fill: #facc15; } .fill-orange-400 { fill: #fb923c; } .fill-current { fill: currentColor; } .object-cover { object-fit: cover; } .p-10 { padding: 2.5rem; } .p-0 { padding: 0px; } .p-5 { padding: 1.25rem; } .p-4 { padding: 1rem; } .p-28 { padding: 7rem; } .p-8 { padding: 2rem; } .p-2 { padding: 0.5rem; } .p-6 { padding: 1.5rem; } .p-2\.5 { padding: 0.625rem; } .py-16 { padding-top: 4rem; padding-bottom: 4rem; } .px-6 { padding-left: 1.5rem; padding-right: 1.5rem; } .px-4 { padding-left: 1rem; padding-right: 1rem; } .px-5 { padding-left: 1.25rem; padding-right: 1.25rem; } .px-8 { padding-left: 2rem; padding-right: 2rem; } .py-3 { padding-top: 0.75rem; padding-bottom: 0.75rem; } .py-5 { padding-top: 1.25rem; padding-bottom: 1.25rem; } .px-2\.5 { padding-left: 0.625rem; padding-right: 0.625rem; } .px-2 { padding-left: 0.5rem; padding-right: 0.5rem; } .py-3\.5 { padding-top: 0.875rem; padding-bottom: 0.875rem; } .py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; } .px-3 { padding-left: 0.75rem; padding-right: 0.75rem; } .py-1 { padding-top: 0.25rem; padding-bottom: 0.25rem; } .py-8 { padding-top: 2rem; padding-bottom: 2rem; } .py-4 { padding-top: 1rem; padding-bottom: 1rem; } .py-2\.5 { padding-top: 0.625rem; padding-bottom: 0.625rem; } .py-12 { padding-top: 3rem; padding-bottom: 3rem; } .pl-16 { padding-left: 4rem; } .pb-10 { padding-bottom: 2.5rem; } .pt-16 { padding-top: 4rem; } .pb-16 { padding-bottom: 4rem; } .pl-6 { padding-left: 1.5rem; } .pb-8 { padding-bottom: 2rem; } .pr-4 { padding-right: 1rem; } .pt-2 { padding-top: 0.5rem; } .pb-2 { padding-bottom: 0.5rem; } .pl-3 { padding-left: 0.75rem; } .pl-2 { padding-left: 0.5rem; } .pl-5 { padding-left: 1.25rem; } .pl-10 { padding-left: 2.5rem; } .pt-12 { padding-top: 3rem; } .pb-12 { padding-bottom: 3rem; } .pb-6 { padding-bottom: 1.5rem; } .pt-20 { padding-top: 5rem; } .pb-20 { padding-bottom: 5rem; } .pt-14 { padding-top: 3.5rem; } .pt-4 { padding-top: 1rem; } .pb-4 { padding-bottom: 1rem; } .pt-32 { padding-top: 8rem; } .text-left { text-align: left; } .text-center { text-align: center; } .text-right { text-align: right; } .align-middle { vertical-align: middle; } .text-9xl { font-size: 8rem; line-height: 1; } .text-2xl { font-size: 1.5rem; line-height: 2rem; } .text-xs { font-size: 0.75rem; line-height: 1rem; } .text-sm { font-size: 0.875rem; line-height: 1.25rem; } .text-base { font-size: 1rem; line-height: 1.5rem; } .text-lg { font-size: 1.125rem; line-height: 1.75rem; } .text-3xl { font-size: 1.875rem; line-height: 2.25rem; } .text-xl { font-size: 1.25rem; line-height: 1.75rem; } .text-6xl { font-size: 3.75rem; line-height: 1; } .font-extrabold { font-weight: 800; } .font-semibold { font-weight: 600; } .font-medium { font-weight: 500; } .font-bold { font-weight: 700; } .uppercase { text-transform: uppercase; } .italic { font-style: italic; } .leading-6 { line-height: 1.5rem; } .leading-none { line-height: 1; } .leading-4 { line-height: 1rem; } .leading-tight { line-height: 1.25; } .tracking-wide { letter-spacing: 0.025em; } .text-blue-600 { --tw-text-opacity: 1; color: rgb(37 99 235 / var(--tw-text-opacity)); } .text-gray-900 { --tw-text-opacity: 1; color: rgb(17 24 39 / var(--tw-text-opacity)); } .text-gray-800 { --tw-text-opacity: 1; color: rgb(31 41 55 / var(--tw-text-opacity)); } .text-gray-500 { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } .text-gray-400 { --tw-text-opacity: 1; color: rgb(156 163 175 / var(--tw-text-opacity)); } .text-zinc-900 { --tw-text-opacity: 1; color: rgb(24 24 27 / var(--tw-text-opacity)); } .text-gray-700 { --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity)); } .text-emerald-500 { --tw-text-opacity: 1; color: rgb(16 185 129 / var(--tw-text-opacity)); } .text-red-500 { --tw-text-opacity: 1; color: rgb(239 68 68 / var(--tw-text-opacity)); } .text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .text-zinc-200 { --tw-text-opacity: 1; color: rgb(228 228 231 / var(--tw-text-opacity)); } .text-black { --tw-text-opacity: 1; color: rgb(0 0 0 / var(--tw-text-opacity)); } .text-green-500 { --tw-text-opacity: 1; color: rgb(34 197 94 / var(--tw-text-opacity)); } .text-orange-200 { --tw-text-opacity: 1; color: rgb(254 215 170 / var(--tw-text-opacity)); } .text-red-800 { --tw-text-opacity: 1; color: rgb(153 27 27 / var(--tw-text-opacity)); } .text-gray-200 { --tw-text-opacity: 1; color: rgb(229 231 235 / var(--tw-text-opacity)); } .text-zinc-800 { --tw-text-opacity: 1; color: rgb(39 39 42 / var(--tw-text-opacity)); } .text-amber-400 { --tw-text-opacity: 1; color: rgb(251 191 36 / var(--tw-text-opacity)); } .text-red-700 { --tw-text-opacity: 1; color: rgb(185 28 28 / var(--tw-text-opacity)); } .text-gray-600 { --tw-text-opacity: 1; color: rgb(75 85 99 / var(--tw-text-opacity)); } .text-orange-400 { --tw-text-opacity: 1; color: rgb(251 146 60 / var(--tw-text-opacity)); } .text-emerald-400 { --tw-text-opacity: 1; color: rgb(52 211 153 / var(--tw-text-opacity)); } .underline { text-decoration-line: underline; } .placeholder-zinc-900::-webkit-input-placeholder { --tw-placeholder-opacity: 1; color: rgb(24 24 27 / var(--tw-placeholder-opacity)); } .placeholder-zinc-900::placeholder { --tw-placeholder-opacity: 1; color: rgb(24 24 27 / var(--tw-placeholder-opacity)); } .shadow { --tw-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-md { --tw-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-sm { --tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); --tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-lg { --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .outline-none { outline: 2px solid transparent; outline-offset: 2px; } .ring-1 { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .ring-black { --tw-ring-opacity: 1; --tw-ring-color: rgb(0 0 0 / var(--tw-ring-opacity)); } .ring-opacity-5 { --tw-ring-opacity: 0.05; } .blur { --tw-blur: blur(8px); -webkit-filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .filter { -webkit-filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .transition { transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, -webkit-transform, -webkit-filter, -webkit-backdrop-filter; transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-transform, -webkit-filter, -webkit-backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .duration-150 { transition-duration: 150ms; } .ease-in-out { transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } .light-content-tiny *:not(pre):not(blockquote) { color: white; } .dark-content-tiny *:not(pre):not(blockquote) { color: black; } /* width */ ::-webkit-scrollbar { width: 10px; } /* Track */ ::-webkit-scrollbar-track { box-shadow: inset 0 0 5px grey; border-radius: 0px; } /* Handle */ ::-webkit-scrollbar-thumb { background: black; border-radius: 2px; } .hover\:text-gray-500:hover { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } .hover\:underline:hover { text-decoration-line: underline; } .focus\:border-blue-500:focus { --tw-border-opacity: 1; border-color: rgb(59 130 246 / var(--tw-border-opacity)); } .focus\:text-gray-500:focus { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } .focus\:text-gray-700:focus { --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity)); } .focus\:underline:focus { text-decoration-line: underline; } .focus\:outline-none:focus { outline: 2px solid transparent; outline-offset: 2px; } .focus\:ring-2:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .focus\:ring-blue-500:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity)); } .focus\:ring-gray-700:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(55 65 81 / var(--tw-ring-opacity)); } .focus\:ring-offset-1:focus { --tw-ring-offset-width: 1px; } @media (prefers-color-scheme: dark) { .dark\:border-gray-600 { --tw-border-opacity: 1; border-color: rgb(75 85 99 / var(--tw-border-opacity)); } .dark\:bg-gray-700 { --tw-bg-opacity: 1; background-color: rgb(55 65 81 / var(--tw-bg-opacity)); } .dark\:text-gray-300 { --tw-text-opacity: 1; color: rgb(209 213 219 / var(--tw-text-opacity)); } .dark\:text-gray-600 { --tw-text-opacity: 1; color: rgb(75 85 99 / var(--tw-text-opacity)); } .dark\:text-gray-50 { --tw-text-opacity: 1; color: rgb(249 250 251 / var(--tw-text-opacity)); } .dark\:text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .dark\:placeholder-gray-400::-webkit-input-placeholder { --tw-placeholder-opacity: 1; color: rgb(156 163 175 / var(--tw-placeholder-opacity)); } .dark\:placeholder-gray-400::placeholder { --tw-placeholder-opacity: 1; color: rgb(156 163 175 / var(--tw-placeholder-opacity)); } .dark\:ring-offset-gray-800 { --tw-ring-offset-color: #1f2937; } .dark\:focus\:border-blue-500:focus { --tw-border-opacity: 1; border-color: rgb(59 130 246 / var(--tw-border-opacity)); } .dark\:focus\:ring-blue-600:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(37 99 235 / var(--tw-ring-opacity)); } .dark\:focus\:ring-blue-500:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity)); } } @media (min-width: 640px) { .sm\:col-span-9 { grid-column: span 9 / span 9; } .sm\:mx-0 { margin-left: 0px; margin-right: 0px; } .sm\:ml-12 { margin-left: 3rem; } .sm\:h-auto { height: auto; } .sm\:w-auto { width: auto; } .sm\:flex-row { flex-direction: row; } .sm\:px-6 { padding-left: 1.5rem; padding-right: 1.5rem; } .sm\:py-4 { padding-top: 1rem; padding-bottom: 1rem; } .sm\:px-12 { padding-left: 3rem; padding-right: 3rem; } .sm\:text-2xl { font-size: 1.5rem; line-height: 2rem; } } @media (min-width: 768px) { .md\:ml-6 { margin-left: 1.5rem; } .md\:block { display: block; } .md\:w-1\/2 { width: 50%; } .md\:pt-40 { padding-top: 10rem; } .md\:text-3xl { font-size: 1.875rem; line-height: 2.25rem; } .md\:text-7xl { font-size: 4.5rem; line-height: 1; } } @media (min-width: 1024px) { .lg\:col-span-4 { grid-column: span 4 / span 4; } .lg\:col-span-8 { grid-column: span 8 / span 8; } .lg\:col-span-3 { grid-column: span 3 / span 3; } .lg\:mx-4 { margin-left: 1rem; margin-right: 1rem; } .lg\:h-24 { height: 6rem; } .lg\:w-1\/3 { width: 33.333333%; } .lg\:w-24 { width: 6rem; } .lg\:grid-cols-12 { grid-template-columns: repeat(12, minmax(0, 1fr)); } .lg\:p-10 { padding: 2.5rem; } .lg\:px-8 { padding-left: 2rem; padding-right: 2rem; } }
import React, { useMemo } from 'react'; import { Redirect, RouteComponentProps } from 'react-router'; import { Route, Switch } from 'react-router-dom'; import { WelcomeHeader, welcomeHeaderSteps } from '../common/WelcomeHeader'; import { Registration } from '../Registration'; import { Packages } from '../Packages'; import { Delivery } from '../Delivery'; import { Checkout } from '../Checkout'; import { useAuth } from 'hooks'; import { steps } from '../common/WelcomeHeader/steps'; import { Advantage } from '../Advantage'; type Step = typeof steps[0]['id']; type Props = RouteComponentProps; export const Welcome = ({ location }: Props) => { const { user } = useAuth(); const step = useMemo(() => welcomeHeaderSteps.find(({ url }) => url === location.pathname)?.id, [location.pathname]); const disabledSteps = useMemo(() => { if (location.pathname === '/registration') return ['packages', 'delivery', 'checkout'] as Step[]; const result: Step[] = ['welcome']; if (!window.localStorage.getItem('washmix-welcome-packages')) { result.push('packages'); } if (!window.localStorage.getItem('washmix-welcome-delivery')) { result.push('delivery'); } if (!window.localStorage.getItem('washmix-welcome-checkout')) { result.push('checkout'); } return result; }, [location.pathname]); return ( <div className="grid-container"> <WelcomeHeader step={step} disabledSteps={disabledSteps} /> <div className="page-container"> {user ? ( <Switch> <Redirect from="/registration" to="/order/packages" /> <Route path="/order/advantage" component={Advantage} /> <Route path="/order/packages" component={Packages} /> <Route path="/order/delivery" component={Delivery} /> <Route path="/order/checkout" component={Checkout} /> </Switch> ) : ( <Switch> <Redirect from="/order" to="/registration" /> <Route path="/registration" component={Registration} /> </Switch> )} </div> </div> ); };
'use client'; import Link from 'next/link'; import Image from 'next/image'; import React from 'react'; import { useState, useEffect } from 'react'; import { useInView } from 'react-intersection-observer'; import { AiFillYoutube, AiOutlineInstagram } from 'react-icons/ai'; import { SiWetransfer } from 'react-icons/si'; import { BsDropbox, BsLinkedin } from 'react-icons/bs'; import styles from './ConnectEffortless.module.css'; const ConnectEffortless = () => { const [isInView, setIsInView] = useState(false); const [pulseActive, setIsPulseActive] = useState(false); const { ref, inView } = useInView({ triggerOnce: false, threshold: 0.6, // trigger when 80% of the element visible in the viewport }); // Set the isInView state when the element enters the viewport useEffect(() => { if (inView) { setIsInView(true); setTimeout(() => { setIsPulseActive(true); }, 800); } }, [inView]); const getHandStyle = () => { let defaultStyle = 'bg-blend max-w-[32rem] -mt-16'; if (isInView) return defaultStyle + ' ' + styles.showHand; else return defaultStyle + ' ' + styles.hideHand; }; const getCirclesStyle = () => { if (pulseActive) { return styles.Pulse; } else { return ''; } }; return ( <section> <div className='section flex flex-col-reverse items-center justify-between md:flex-row '> <div className='right max-w-2xl flex items-start justify-start flex-col'> <h1 className='text-3xl sm:text-5xl font-bold' style={{ lineHeight: '1.2' }}> <span className='text-custom-blue'>Connect </span> - The Magic Of <br /> Networking At Your Fingertips. </h1> <div className='h-1 bg-custom-blue rounded w-32 mt-4 mb-4' /> <p className='text-left tracking-tight sm:text-lg'> With the SendContact App, networking becomes magical. Utilizing cutting-edge NFC technology, you can seamlessly connect with customers and potential partners. Just a simple tap of your phone against another person&apos;s NFC card or phone instantly transfers contact information, images, and videos. It&apos;s like having a digital business card on the go. </p> <span className='my-3 text-left text-lg font-semibold text-slate-900 sm:mx-0'> You&apos;re also able to add your social media links as: </span> <div className='my-3 grid md:grid-cols-3 gap-6 gap-x-20 grid-cols-2 items-center'> <div className='flex items-center space-x-3 md:justify-normal'> <div>< AiOutlineInstagram className='text-xl' /></div> <div>Instagram</div> </div> <div className='flex items-center gap-4 md:justify-normal'> <div>< SiWetransfer className='text-xl' /></div> <div>WeTransfer</div> </div> <div className='flex items-center gap-4 md:justify-normal'> <div>< AiFillYoutube className='text-xl' /></div> <div>Youtube</div> </div> <div className='flex items-center gap-4 md:justify-normal'> <div>< BsLinkedin className='text-xl' /></div> <div>Linkedin</div> </div> <div className='flex items-center gap-4 md:justify-normal'> <div>< BsDropbox className='text-xl' /></div> <div>Dropbox</div> </div> </div> <Link target='_blank' href='https://apps.apple.com/us/app/sendcontact/id963951753' className='bg-custom-blue text-base px-14 py-2 mt-4 text-white rounded-md sm:mx-0 animated-btn'> Download SendContact </Link> </div> <div className='left relative' ref={ref}> <div className={styles.HandWrap}> <Image src={'/hand-and-card.webp'} alt='Send' className='bg-blend max-w-[32rem] relative z-0' height={300} width={400} /> <Image src={'/hand-and-mobile.webp'} alt='Send' className={getHandStyle()} height={300} width={400} /> </div> <div className={styles.ContainerCircles}> <div className={styles.StrCircle1 + ' ' + getCirclesStyle()}></div> <div className={styles.StrCircle2 + ' ' + getCirclesStyle()}></div> <div className={styles.StrCircle3 + ' ' + getCirclesStyle()}></div> </div> </div> </div> </section> ); }; export default ConnectEffortless;
<script> import { computed } from 'vue'; export default { props: { matched: { type: Boolean, default: false, }, position: { type: Number, required: true, }, value: { type: String, required: true, }, visible: { type: Boolean, default: false, }, }, setup(props, context) { const flipStyles = computed(() => { if (props.visible) { return 'is-flipped'; } }); const selectCard = () => { context.emit('select-card', { position: props.position, faceValue: props.value, }); }; return { selectCard, flipStyles, }; }, }; </script> <template> <div class="card" :class="flipStyles" @click="selectCard"> <div class="card-face is-front"> {{ value }} <div v-if="matched" class="correct">correct!</div> </div> <div class="card-face is-back"></div> </div> </template> <style> .card { position: relative; transition: 0.5s transform ease-in; transform-style: preserve-3d; } .card.is-flipped { transform: rotateY(180deg); } .card-face { width: 100%; height: 100%; position: absolute; border-radius: 7px; cursor: pointer; backface-visibility: hidden; } .card-face.is-front { background-color: purple; color: white; font-size: 20px; transform: rotateY(180deg); } .card-face.is-back { background-color: orange; color: white; } .correct { position: absolute; bottom: 5px; right: 5px; color: lightgreen; } </style>
<?php /* * Pagina para registrar personas con un formulario * que comprueba que todo este correcto. Si esta bien envia * a la página success.php, en caso contrario vuelve a printar * el formulario, mostrando donde esta el error */ ?> <?php session_start(); ?> <?php //require_once('insert.php'); ?> <?php require_once('funciones.php'); ?> <? /* * Funcion que muestra el formulario */ function form ($erDni, $erNom) { ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Formulario de registro de Personas</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="wrap"> <h1>Formulario de registro de personas</h1> <form action="register.php" method="POST" enctype="multipart/form-data" id="reg"> <label for="dni">DNI <input type="text" name="dni"> <span class="status"><?php echo $erDni; ?></span> </label> <label for="name">Nombre <input type="text" name="name"> <span class="status"><?php echo $erNom; ?></span> </label> <label for="img">Avatar <input type="file" name="img"> </label> <input type="submit" value="Crear"> </form> <?php menu(); ?> </div> </body> </html> <?php } // final funcion form ?> <?php /* Comprobación de los datos introducidos */ if ( isset($_POST['dni']) ) { /* Comprobar el DNI * sacado de: http://computersandprogrammers.blogspot.com.es/2012/12/expresion-regular-reconocer-dni.html * mirar la buena: http://nideaderedes.urlansoft.com/2011/10/21/funcion-en-php-para-calcular-si-un-dni-o-un-nie-son-validos/ */ $regExpDni = '/^([0-9]{8})([-]?)([a-zA-Z])$/'; //cambiar por una que compruebe real if (preg_match($regExpDni, $_POST['dni'])) { $_SESSION['dni'] = $_POST['dni']; } else { $msjErrorDni = 'Ha habido un error. Solo funciona con DNI'; } /* Comprobar el nombre */ $regExpNom = '/^[a-zA-Z]{3,10}/'; if (preg_match($regExpNom, $_POST['name'])) { $_SESSION['name'] = $_POST['name']; } else { $msjErrorName = 'Ha habido un error. Min.3/Máx.10'; } /* Si ha habido algun error */ if ( $msjErrorDni || $msjErrorName ) { form($msjErrorDni, $msjErrorName); } else { success('regPersona'); } } else { form($msjErrorDni, $msjErrorName); } ?>
/* eslint-disable react/prop-types */ import "./userProfile.css"; import img from "../../../assets/images/drake.jpg"; import { AiOutlineArrowRight } from "react-icons/ai"; import { useTranslation } from "react-i18next"; function UserProfile({ infoActive, setInfoActive, setInfo }) { const toggleInfo = (e) => { e.target.parentNode.classList.toggle("open"); }; const themeColor = localStorage.getItem("themeColor"); const [t] = useTranslation(); return ( <div className="main__userprofile" style={infoActive ? { right: "0" } : { right: "107%" }} > <AiOutlineArrowRight className={`font-xl text-current cursor-pointer backInfo ms-2 ${themeColor} `} onClick={() => { setInfo(false); setInfoActive(false); }} /> <div className="p-3 text-center"> <h3>{t("USERINFORMATION")}</h3> </div> <div className="profile__card user__profile__image"> <div className="profile__image mb-3"> <img src={img} /> </div> <h4 className=" mb-2">Fernando Faucho</h4> <p className=" mb-3">{t("Delete Conversation")} </p> </div> <div className="profile__card"> <div className="card__header" onClick={toggleInfo}> <h4>{t("Shared Photoes")}</h4> <i className="fa fa-angle-down"></i> </div> <div className="card w-100 shadow-xss rounded-xxl border-0 mt-3 mb-3"> <div className="card-body d-block pt-0 pb-2"> <div className="row"> {[...Array(6)].map((_, index) => ( <div className="w-2/4 mb-2 p-2 " key={index}> <div data-lightbox="roadtrip"> <img src={img} alt="" className="img-fluid rounded-3 w-100" /> </div> </div> ))} </div> </div> <div className="card-body d-block w-100 pt-0"> <div className="p-2 lh-28 w-100 d-block bg-grey text-grey-800 text-center font-xssss fw-700 rounded-xl"> <i className="feather-external-link font-xss ms-2" /> {t("More")} </div> </div> </div> </div> </div> ); } export default UserProfile;
import React from 'react'; import '../styles/Exchanges.css'; import { Link } from 'react-router-dom'; const demoImage = "http://coinrevolution.com/wp-content/uploads/2020/06/cryptonews.jpg"; const ExchCard = ({exchange}) => { return ( <Link to={exchange.coinrankingUrl} target='blank'> <div className="exchange-card"> <div className="exch-header"> <img src={exchange?.iconUrl || demoImage} alt="" /> <p className="exch-name">{exchange.name}</p> </div> <p className="exch-price"> Price{" "} <span className="exch-value"> ${((exchange.price * 100) / 100).toFixed(2)} </span> </p> <p className="exch-24h-vol"> 24h Volume{" "} <span className="exch-value"> {Intl.NumberFormat("en", { notation: "compact" }).format( exchange["24hVolume"] )} </span> </p> </div> </Link> ); } export default ExchCard;
package org.owasp.wrongsecrets.challenges.docker; import org.owasp.wrongsecrets.challenges.Challenge; import org.owasp.wrongsecrets.challenges.Spoiler; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** This challenge is about having a secrets stored as a Docker ARG var. */ @Component public class Challenge4 implements Challenge { private final String argBasedPassword; public Challenge4(@Value("${ARG_BASED_PASSWORD}") String argBasedPassword) { this.argBasedPassword = argBasedPassword; } @Override public Spoiler spoiler() { return new Spoiler(argBasedPassword); } @Override public boolean answerCorrect(String answer) { return argBasedPassword.equals(answer) || argBasedPassword.equals("'" + answer + "'"); } }
= u2ug: UUID to Ubisoft game ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :important-caption: :heavy_exclamation_mark: :caution-caption: :fire: :warning-caption: :warning: endif::[] ifndef::env-github[] :icons: font endif::[] image:https://github.com/ncomet/u2ug/actions/workflows/go.yml/badge.svg[Go,link=https://github.com/ncomet/u2ug/actions/workflows/go.yml] A Golang library that given a https://fr.wikipedia.org/wiki/Universally_unique_identifier[UUID] (v1 or v4), will return the concatenation of a random adjective and Ubisoft game, or character. [quote] c840005c-06f0-43af-a96f-77bf13fdc956 -> Crazy Rocksmith == Disclaimer IMPORTANT: Highly inspired by https://github.com/CleverCloud/uuid_to_pokemon.rs, but in Go. Special thanks to the https://www.clever-cloud.com/[Clever Cloud] teams ;) It is *not* an https://en.wikipedia.org/wiki/Injective_function[_injective function_], meaning that a given UUID will *always produce the same name*, but a given name could be the output of two different UUIDs. It does should not matter since the original UUID must be kept as original source of uniqueness. This library is created in order to assign a reproducible human-readable name to a UUID. == How to use === Go library [source,bash] ---- go get github.com/ncomet/u2ug/ubi ---- [source,go] ---- import "github.com/ncomet/u2ug/ubi" game, err := ubi.Game("d3acc428-3172-457a-9447-6a22263ef6b3") if err != nil { panic(err) } fmt.Println(game) // "Selfish Space Junkies" character, err := ubi.Character("d3acc428-3172-457a-9447-6a22263ef6b3") if err != nil { panic(err) } fmt.Println(character) // "Selfish Selena" ---- === Binary [source,bash] ---- $ go build . $ ./u2ug game d3acc428-3172-457a-9447-6a22263ef6b3 Selfish Space Junkies $ ./u2ug character d3acc428-3172-457a-9447-6a22263ef6b3 Selfish Selena ---- [source,bash] ---- $ go run ./ game d3acc428-3172-457a-9447-6a22263ef6b3 Selfish Space Junkies $ go run ./ character d3acc428-3172-457a-9447-6a22263ef6b3 Selfish Selena ---- === Docker [source,bash] ---- $ docker build -t u2ug . $ docker run u2ug game d3acc428-3172-457a-9447-6a22263ef6b3 Selfish Space Junkies ---- === WASM Build the `wasm` version: [source,bash] ---- GOOS=js GOARCH=wasm go build -o u2ug.wasm cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" . ---- Then use it in your webapp: [source,html] ---- <html> <head> <meta charset="utf-8"/> <script src="wasm_exec.js"></script> <script> const go = new Go(); WebAssembly.instantiateStreaming(fetch("u2ug.wasm"), go.importObject).then((result) => { go.run(result.instance); }); // call the functions available in window.ubiGame or window.ubiCharacter document.body.textContent = ubiGame("c74c3694-8040-4213-8a46-988ee9a42ef3"); </script> </head> <body> </body> </html> ---- You can run an example avaible in `/wasm_example`: [source,bash] ---- GOOS=js GOARCH=wasm go build -o ./wasm_example/u2ug.wasm cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" ./wasm_example ---- NOTE: Serve the `index.html` in your favorite tool to avoid CORS errors == Some examples === Games |=== |Polite Tom Clancy's Ghost Recon Advanced Warfighter |Dreadful Gunfighter II: Revenge of Jesse James |Shrill Cloudy with a Chance of Meatballs |Shrill Rocket: Robot on Wheels |Meek Assassin's Creed Origins |Caring Far Cry New Dawn |Scared Buck Bumble |Selfish Splinter Cell: Blacklist - Spider-Bot |Shining Petz: Bunnyz |Angry Seven Kingdoms II: The Fryhtan Wars |Odd ZombiU |Plush Super Bust-A-Move |Sleepy Tiger Woods PGA Tour Golf |Foul Adventures in Music with the Recorder |Cruel Heroes of Might and Magic V: Tribes of the East |Stingy Theocracy |Quiet Lost: Via Domus |Bored Skateball |Tiny Warlords: Battlecry II |Shining Imagine: Babyz |Rich All Star Tennis '99 |=== === Characters |=== |Soaring Tus |Fussy Eivor |Thrifty Amaru |Afraid Barr-Barr |Chilly Mo |Creeping Thant |Sloppy Teen Punk |Caring Nikolai Andreievich Orelov |Stingy Princess |Generous Hytham |Rapid Glaz |Grimy Sigurd |Cowardly Straker |Bashful Tiva |Generous Amaru |Kind Clancy |Hard Piquedram |=== == Games list source All games were taken and de-duplicated from: https://en.wikipedia.org/wiki/List_of_Ubisoft_games == Characters list source Extracted from various dedicated game wiki fandom websites.
<?php namespace app\modules\salers\models; use yii\base\Model; use yii\data\ActiveDataProvider; use app\modules\salers\models\SaleItem; /** * SaleItemSearch represents the model behind the search form of `app\modules\salers\models\SaleItem`. */ class SaleItemSearch extends SaleItem { /** * {@inheritdoc} */ public function rules() { return [ [['id', 'product_id', 'quantity', 'unit', 'status_id', 'order_id'], 'integer'], [['price', 'total'], 'number'], ]; } /** * {@inheritdoc} */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = SaleItem::find(); // add conditions that should always apply here $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } // grid filtering conditions $query->andFilterWhere([ 'id' => $this->id, 'order_id' => $this->order_id, 'product_id' => $this->product_id, 'price' => $this->price, 'quantity' => $this->quantity, 'unit' => $this->unit, 'total' => $this->total, 'status_id' => $this->status_id, ]); return $dataProvider; } }
import {useJsApiLoader, GoogleMap, MarkerF, DirectionsRenderer} from '@react-google-maps/api'; import { useEffect, useRef, useState } from 'react' const center = { lat: 59.105890, lng: -102.005848} const provinces = ["","Alberta", "British Columbia", "Manitoba", "New Brunswick", "Newfoundland and Labrador","Northwest Territories", "Nunavut","Ontario","Prince Edward Island", "Quebec", "Saskatchewan", "Yukon"] const branch = ["", "Yorkdale", "Eatons", "Dufferin Mall"] const libraries = ['places']; const Google_Map = (props) => { const { isLoaded } = useJsApiLoader({ googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY, libraries, }) const [map, setMap] = useState(/** @type google.maps.Map */ (null)) const [directionsResponse, setDirectionsResponse] = useState(null) const isFirstRender = useRef(true) const [selectedProvince, setProvince] = useState(provinces[0]) useEffect(() => { if (isFirstRender.current) { isFirstRender.current = false return; } panMapProvince(map) }, [selectedProvince]) const [selectedCity, setCity] = useState(null) const [selectedAddress, setAddress] = useState(null) const [selectedBranch, setBranch] = useState(null) function changeProvince(province){ setProvince(province.target.value) panMapProvince(map) } function changeCity(city){ setCity(city.target.value) panMapCity(map) } function changeAddress(address){ setAddress(address.target.value) panMapAddress(map) } function changeBranch(branch){ setBranch(branch.target.value) } function updateMap(map){ setDirectionsResponse(null) generatePath() } function returnGeolocation(){ if(selectedBranch == "Yorkdale"){ return "PGGX+54 Toronto, Ontario" }else if(selectedBranch == "Eatons"){ return "MJ39+QP Toronto, Ontario" }else if(selectedBranch == "Dufferin Mall"){ return "MH47+8P Toronto, Ontario" } } async function panMapProvince(map){ const geocoder = new window.google.maps.Geocoder() geocoder.geocode({address: selectedProvince}).then((response) => { if(response.results[0]){ var theJson = JSON.parse(JSON.stringify(response, null, 2)); map.panTo({lat: theJson.results[0].geometry.location.lat, lng: theJson.results[0].geometry.location.lng }); map.setZoom(5); }else{ window.alert("No results found"); }}); } function panMapCity(map){ var geocoder = new window.google.maps.Geocoder(); geocoder.geocode({address: selectedCity}).then((response) => { if(response.results[0]){ var theJson = JSON.parse(JSON.stringify(response, null, 2)); map.panTo({lat: theJson.results[0].geometry.location.lat, lng: theJson.results[0].geometry.location.lng }); map.setZoom(11); }else{ window.alert("No results found"); } }); console.log(selectedCity) } function panMapAddress(map){ const geocoder = new window.google.maps.Geocoder(); geocoder.geocode({address: `${selectedCity} ${selectedAddress}`}).then((response) => { if(response.results[0]){ var theJson = JSON.parse(JSON.stringify(response, null, 2)); map.panTo({lat: theJson.results[0].geometry.location.lat, lng: theJson.results[0].geometry.location.lng }); map.setZoom(14); }else{ window.alert("No results found"); } }); } async function generatePath(){ const directionsService = new window.google.maps.DirectionsService() const results = await directionsService.route({ origin: returnGeolocation(), destination: `${selectedCity} ${selectedAddress}`, travelMode: window.google.maps.TravelMode.DRIVING }) setDirectionsResponse(results) } if(!isLoaded){ return <div>hello world</div> } return( <div class="container"> <div class="row mt-4" > <div class="col-md-4"> <div class="row gx-0"> <div>First name:</div><input type="text" name="fname" /><br /> <div>Last name:</div><input type="text" name="lname" /><br /> <div>Phone number:</div><input type="text" name="phone-number" /><br /> <div>Provines & Territories:</div> <select name="province" id="province" value={selectedProvince} onChange={changeProvince} > {provinces.map((value) => ( <option value={value} key={value}> {value} </option> ))} </select> <div>City: </div><input type="text" name="city" id="city" value={selectedCity} placeholder="City" onChange={changeCity} /><br /> <div>Delivery Address:</div><input type="text" name="address" id="end" value={selectedAddress} placeholder="Address" onChange={changeAddress} /><br /> </div> <div>Branch:</div> <select name="Branches" id="branch" value={selectedBranch} onChange={changeBranch} > {branch.map((value) => ( <option value={value} key={value}> {value} </option> ))} </select> <input type="submit" onClick={() => updateMap(map)}/> </div> <div class="col-md-8"> <GoogleMap center={center} zoom={3} mapContainerStyle={{width:'100%', height:'100%'}} onLoad={map => setMap(map)}> {directionsResponse && <DirectionsRenderer directions={directionsResponse}/>} </GoogleMap> </div> </div> </div> ); } export default Google_Map;
import { useState } from 'react' import Proptypes from 'prop-types'; const titlePropTypes = { text: Proptypes.string.isRequired, } const titleDefaultTypes = { text: 'teste', } interface ITtitle { text?: string; } function Title({ text }: ITtitle) { return <h1>{text}</h1> } // Title.propTypes = titlePropTypes; // Title.defaultProps = titleDefaultTypes; function withSomethings<T>(Component: React.ComponentType<T>) { return (props: any) => ( <Component {...props} /> ) } const withSomething = (Component: React.ComponentType<any>) => (prop: unknown) => { return ( <Component {...prop} /> ) } export function TSExamples() { return null } // with theme example interface WithThemeProps { primaryColor: string; } const useTheme = () => {} export function withTheme<T extends WithThemeProps = WithThemeProps>( WrappedComponent: React.ComponentType<T> ) { // Try to create a nice displayName for React Dev Tools. const displayName = WrappedComponent.displayName || WrappedComponent.name || "Component"; // Creating the inner component. The calculated Props type here is the where the magic happens. const ComponentWithTheme = (props: Omit<T, keyof WithThemeProps>) => { // Fetch the props you want to inject. This could be done with context instead. const themeProps = useTheme(); // props comes afterwards so the can override the default ones. return <WrappedComponent {...themeProps} {...(props as T)} />; }; ComponentWithTheme.displayName = `withTheme(${displayName})`; return ComponentWithTheme; } export function useLoading() { const [isLoading, setState] = useState(false); const load = (aPromise: Promise<any>) => { setState(true); return aPromise.finally(() => setState(false)); }; return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[] }
// Copyright (c) 2022-2023 Mikołaj Kuranowski // SPDX-License-Identifier: WTFPL import { linesFromFile } from "./core.ts"; export type Operation = { a: string; b: string; op: string; }; export type Node = Operation | number; export class Calculator { cache: Map<string, number> = new Map(); constructor(public data: Map<string, Node>) {} valueFor(monkey: string): number { const cached = this.cache.get(monkey); if (cached !== undefined) return cached; const nd = this.data.get(monkey)!; let result: number; if (typeof nd === "number") { result = nd; } else { switch (nd.op) { case "+": result = this.valueFor(nd.a) + this.valueFor(nd.b); break; case "-": result = this.valueFor(nd.a) - this.valueFor(nd.b); break; case "*": result = this.valueFor(nd.a) * this.valueFor(nd.b); break; case "/": result = this.valueFor(nd.a) / this.valueFor(nd.b); break; case "=": result = this.valueFor(nd.a) === this.valueFor(nd.b) ? 1 : 0; break; default: throw `Invalid op: ${nd.op}`; } } this.cache.set(monkey, result); return result; } } export function loadInput(): Map<string, Node> { const data: Map<string, Node> = new Map(); for (const line of linesFromFile(Deno.args[0])) { const opMatch = line.match(/^(\w{4}): (\w{4}) (\+|-|\*|\/) (\w{4})$/); const numMatch = line.match(/^(\w{4}): (\d+)$/); if (opMatch !== null) { data.set(opMatch[1], { a: opMatch[2], b: opMatch[4], op: opMatch[3] }); } else if (numMatch !== null) { data.set(numMatch[1], parseInt(numMatch[2], 10)); } else { throw `Unrecognized line: ${line}`; } } return data; } export function main(): void { console.log(new Calculator(loadInput()).valueFor("root")); }
"use strict" document.addEventListener("DOMContentLoaded", function () { const form = document.getElementById('form'); form.addEventListener('submit', formSend); async function formSend(e) { e.preventDefault(); let error = formValidate(form); let formData = new FormData(form); if (error === 0){ form.classList.add('_sending'); let response = await fetch ('sendmail.php',{ method: 'POST', body: formData }); if(response.ok){ let result = await response.json(); alert(result.message); formPreview.innerHTML = ''; form.reset(); form.classList.remove('_sending'); } else{ alert('Problem'); form.classList.remove('_sending'); } } else{ alert("заповніть поля") } } function formValidate ( form ) { let error = 0 ; let formReq = document.querySelectorAll ('._req'); for ( let index = 0 ; index < formReq.length ; index ++ ) { const input = formReq[index]; formRemoveError ( input ) ; if (input.classList.contains('_email')) { if(emailTest(input)){ formAddError(input); error++; } } else if(input.getAttribute("type")==="checkbox" && input.checked === false){ formAddError(input); error++; } else{ if (input.value ===''){ formAddError(input); error++; } }} return error; } function formAddError ( input ) { input.parentElement.classList.add ( ' _error ' ) ; input.classList.add ( ' _error ' ) ; } function formRemoveError ( input ) { input.parentElement.classList.remove ( ' _error ' ) ; input.classList.remove ( ' _error ' ) ; } // Функция места email function emailTest ( input ) { return !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/.test( input.value ); } }); // "use strict"; // document.addEventListener("DOMContentLoaded", function () { // const form = document.getElementById('form'); // const formPreview = document.querySelector('.form_preview'); // form.addEventListener('submit', formSend); // async function formSend(e) { // e.preventDefault(); // let error = formValidate(form); // let formData = new FormData(form); // if (error === 0) { // form.classList.add('_sending'); // let response = await fetch('sendmail.php', { // method: 'POST', // body: formData // }); // if (response.ok) { // let result = await response.json(); // alert(result.message); // formPreview.innerHTML = ''; // form.reset(); // } else { // alert('Problem'); // } // } else { // alert("Заповніть поля"); // } // } // function formValidate(form) { // let error = 0; // let formReq = form.querySelectorAll('._req'); // formReq.forEach(input => { // formRemoveError(input); // if (input.classList.contains('_email')) { // if (!emailTest(input.value)) { // formAddError(input); // error++; // } // } else if (input.getAttribute("type") === "checkbox" && !input.checked) { // formAddError(input); // error++; // } else { // if (input.value.trim() === '') { // formAddError(input); // error++; // } // } // }); // return error; // } // function formAddError(input) { // input.parentElement.classList.add('_error'); // input.classList.add('_error'); // } // function formRemoveError(input) { // input.parentElement.classList.remove('_error'); // input.classList.remove('_error'); // } // function emailTest(value) { // return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/.test(value); // } // });
<!DOCTYPE html> <html lang="en"> <link rel="icon" href="images/bluestore.png"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>BuleStore | Ecommerce Website Design</title> <link rel="stylesheet" href="main.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400;600;700&family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet"> <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script> <script src="index.js"></script> </head> <body> <!--This is Navbar --> <div class="header"> <div class="container"> <div class="navbar"> <div class="logo"> <img src="images/bluestore.png" width="200px" alt="bluestore"> </div> <nav> <ul id="MenuItems"> <li><a href="#">Home</a></li> <li><a href="#">Products</a></li> <li><a href="#">About</a></li> <li><a href="#">Conact</a></li> <li><a href="#">Account</a></li> </ul> </nav> <img src="images/cart.png" width="30px" height="30px" alt=""> <img src="images/menu.png" class="menu-icon" onclick="menutoggle()" alt="bluestore"> </div> </div> <div class="row"> <div class="col-2"> <h1 > <p class="typewrite" data-period="2000" data-type='[ "New Generation.","Stylish Dress.","40% Discounts.","Free Delivery."]'> <span class="wrap"></span> </p> </h1> <h1>Give Your Workout <br> A New Style</h1> <p>Success isn't always about greatness. It's about consistency. Consistent <br> hard work gains success. Greatness will come.</p> <a href="#" class="btn">Explore Now &#8594</a> </div> <div class="col-2"> <lottie-player src="https://assets8.lottiefiles.com/packages/lf20_57TxAX.json" background="transparent" speed="1" loop autoplay></lottie-player> </div> </div> </div> <div class="categories"> <div class="small-container"> <div class="row"> <!-- <div class="col-3"><img src="images/category-2.jpg" alt=""></div> --> <div class="col-3"><lottie-player src="https://assets4.lottiefiles.com/packages/lf20_zwijnhaz.json" background="transparent" speed="1" loop autoplay></lottie-player></div> <div class="col-3"><lottie-player src="https://assets6.lottiefiles.com/packages/lf20_ihtfegx7.json" background="transparent" speed="1" loop autoplay></lottie-player></div> <div class="col-3"><lottie-player src="https://assets9.lottiefiles.com/packages/lf20_yqhwn4pd.json" background="transparent" speed="1" loop autoplay></lottie-player></div> <!-- <div class="col-3"><img src="images/category-3.jpg" alt=""></div> --> </div> </div> </div> <!-- Featured Products --> <div class="small-container"> <h2 class="title">Featured Products</h2> <div class="row"> <div class="col-4"> <img src="images/product-4.jpg" alt=""> <h4>Bule Printed T-Shirt</h4> <div class="rating"> <p>&#9733;&#9733;&#9733;&#9733;&#9734;</p> </div> <p>₹500.00</p> </div> <div class="col-4"> <img src="images/product-1.jpg" alt=""> <h4>Red Printed T-Shirt</h4> <div class="rating"> <p>&#9733;&#9733;&#9733;&#9733;&#9734;</p> </div> <p>₹500.00</p> </div> <div class="col-4"> <img src="images/product-2.jpg" alt=""> <h4>Black Printed Shoes</h4> <div class="rating"> <p>&#9733;&#9733;&#9733;&#9733;&#9734;</p> </div> <p>₹500.00</p> </div> <div class="col-4"> <img src="images/product-3.jpg" alt=""> <h4>Grey Printed Pant</h4> <div class="rating"> <p>&#9733;&#9733;&#9733;&#9733;&#9734;</p> </div> <p>₹500.00</p> </div> </div> <!-- Latest --> <h2 class="title">Latest Products</h2> <div class="row"> <div class="col-4"> <img src="images/product-5.jpg" alt=""> <h4>Grey Printed Shoes</h4> <div class="rating"> <p>&#9733;&#9733;&#9733;&#9733;&#9734;</p> </div> <p>₹500.00</p> </div> <div class="col-4"> <img src="images/product-6.jpg" alt=""> <h4>Black Printed T-Shirt</h4> <div class="rating"> <p>&#9733;&#9733;&#9733;&#9733;&#9734;</p> </div> <p>₹500.00</p> </div> <div class="col-4"> <img src="images/product-7.jpg" alt=""> <h4>Shocks</h4> <div class="rating"> <p>&#9733;&#9733;&#9733;&#9733;&#9734;</p> </div> <p>₹500.00</p> </div> <div class="col-4"> <img src="images/product-8.jpg" alt=""> <h4>Black Watch</h4> <div class="rating" > <p >&#9733;&#9733;&#9733;&#9733;&#9734;</p> </div> <p>₹500.00</p> </div> </div> </div> <!-- Footer --> <div class="footer"> <div class="container"> <div class="row"> <div class="footer-col-1"> <h3>Download Our App</h3> <p>Download App for Android and ios mobile phone.</p> <div class="app-logo"> <a href="index.html"><img src="images/play-store.png" alt=""></a> <a href="index.html"><img src="images/app-store.png" alt=""></a> </div> </div> <div class="footer-col-2"> <img src="images/bluestore.png" width="200px" alt=""> <p>Our Purpose Is To Sustainably Make the pleasure and Benefits of Sports Accessible to the Many. </p> </div> <div class="footer-col-3"> <a href="index.html"><h3>Useful Links</h3></a> <ul> <li>Coupons</li> <li>Blog Post</li> <li>Return Policy</li> <li>Join Affiliate</li> </ul> </div> <div class="footer-col-4"> <a href="index.html"><h3>Follow us</h3></a> <ul> <li><a href="index.html">Facebook</a></li> <li><a href="index.html">Twitter</a></li> <li><a href="index.html">Instagram</a></li> <li><a href="index.html">YouTube</a></li> </ul> </div> </div> <hr> <p class="copyright">&copy; Copyright 2022</p> </div> </div> <!-- js for toggle menu --> <script> var MenuItems = document.getElementById("MenuItems"); MenuItems.style.maxHeight = "0px"; function menutoggle() { if (MenuItems.style.maxHeight == "0px") { MenuItems.style.maxHeight = "200px"; } else { MenuItems.style.maxHeight = "0px"; } } </script> </body> </html>
package com.company.CarePackage; /** * Imports */ import java.io.File; import java.util.List; /** * Packages */ import com.company.Tank; import com.company.Obstacles.Tile; import com.company.TextureReference; import javax.imageio.ImageIO; /** * Health class * <p>This class inherits from the super class 'CarePackage'</p> * * @author Keivan Ipchi Hagh & Bardia Ardakanian * @version 0.1.0 */ public class Health extends CarePackage { /** * Object Constructor * * @param x X-Axis * @param y Y-Axis */ public Health(int x, int y) { super(x, y); try { setIcon(ImageIO.read(new File(TextureReference.getPath("joggernog")))); } catch (Exception e) { e.printStackTrace(); } this.carePackageID = "@health" + System.currentTimeMillis(); } /** * The main action of the package * * @param tank Tank obj */ @Override public void doAction(Tank tank) { int extraHealth = tank.getHealth() + 10; if (extraHealth > 100) extraHealth = 100; tank.setHealth(extraHealth); // Add health (10% of tank's current health) setUsed(true); // Set package as used, so it cannot be used again activateBuff(); } /** * Turn's off the package's effect */ @Override public void turnOff() { setRemove(true); deactivateBuff(); } }
<!DOCTYPE html> <html> <head> <!-- ***** Link To Custom CSS Style sheet ***** --> <link rel="stylesheet" type="text/css" href="style.css"> <!-- ***** Link To Font Awsome Icons ***** --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"/> <!-- ***** Link To Magnific Popup CSS ***** --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css"/> <!-- ***** Links To OwlCarousel CSS ***** --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.min.css"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Antony Portfolio</title> </head> <body> <!-- *** Website Container Starts *** --> <div class="Website-container"> <!-- *** Home Section Starts *** --> <section class="home" id="home"> <!-- === Navbar Starts === --> <nav class="navbar"> <div class="logo"> <img src="images/lo.png"> </div> <ul class="nav-links"> <li><a href="#home">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#services">Services</a></li> <li><a href="#portfolio">Portfolio</a></li> <li><a href="#testimonials">Reviews</a></li> </ul> <a href="#contactForm" class="button-wrapper"> <button class="btn contact-btn">Contact</button> </a> <div class="menu-btn"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </div> </nav> <!-- === Navbar Ends === --> <!-- === Hero Starts === --> <div class="hero"> <div class="hero-text"> <h3>Hey, There</h3> <h1>I Muhammad Maaz</h1> <h2>Mobile Application Developer</h2> <p>I am a <b>React Native </b> App Developer Freelancer, skilled in creating robust and visually appealing mobile applications. Let's build remarkable mobile experiences together!</p> <button class="btn hire-btn">Hire Me</button> </div> <div class="hero-image"> <img src="images/fornt.png"> </div> </div> <!-- === Hero Ends === --> <!-- === Career Bar Starts === --> <div class="career-container"> <div class="career-item"> <span class="icon"><i class="fa-solid fa-briefcase"></i></span> <span class="career-desc"> <h1>2 Years of</h1> <p>Experience</p> </span> </div> <div class="career-item"> <span class="icon"><i class="fa-solid fa-file"></i></span> <span class="career-desc"> <h1>20+ Projects</h1> <p>Completed</p> </span> </div> <div class="career-item"> <span class="icon"><i class="fa-solid fa-heart"></i></span> <span class="career-desc"> <h1>Worked in</h1> <p>App dev,web dev,DB,Python</p> </span> </div> </div> <!-- === Career Bar Ends === --> </section> <!-- *** Home Section Ends *** --> <!-- *** About Section Starts *** --> <section class="about" id="about"> <!-- === About Image Starts === --> <div class="about-image"> <img src="images/iiii.png"> <div class="social-media"> <a href="https://www.facebook.com/maazhun" target="_blank" rel="noopener noreferrer"><i class="fa-brands fa-facebook-f"></i></a> <a href="https://github.com/Maazleo"><i class="fa-brands fa-github"></i></a> <a href="#"><i class="fa-brands fa-instagram"></i></a> <a href="https://www.linkedin.com/in/muhammad-maaz-9b134a251" target="_blank" rel="noopener noreferrer"><i class="fa-brands fa-linkedin-in"></i></a> </div> </div> <!-- === About Image Ends === --> <!-- === About Description Starts === --> <div class="about-desc"> <h3>About Me</h3> <h2>React native App Developer</h2> <h3>Overview</h3> <p>Mobile App Dev Enthusiast • React-Native • App developer intern @Info aidTech • Google DSC squad • BSCS'25 • Student at Government College University (GCU)</p> <div class="about-personal-info"> <div><span><b>Name:</b></span><span>M Maaz</span></div> <div><span><b>Age:</b></span><span>20 Years</span></div> <div><span><b>Email:</b></span><span>maazmasroorhuss@gmail.com</span></div> <div><span><b>Hobbies:</b></span><span>Coding,Cricket,Watching Web-series and movies.</span></div> </div> <h3>Goal</h3> <p>As an app developer, my primary goal is to create innovative and user-centric mobile applications that make a meaningful impact in people's lives. I strive to deliver seamless and intuitive user experiences, focusing on simplicity, functionality, and aesthetics. With a passion for cutting-edge technologies and a keen eye for detail, I aim to stay ahead of the curve by continuously learning and adapting to the evolving app development landscape. </p> <button class="btn download-btn"><a href="cv.pdf.pdf" download> <p>Download CV </p></a></button> </div> <!-- === About Description Ends === --> </section> <!-- *** About Section Ends *** --> <!-- *** Services Section Starts *** --> <section class="services reusable" id="services"> <!-- === Headings Text Starts === --> <header class="headings"> <h3>Services</h3> <h1>I Provide Awesome Services</h1> <p>As a skilled and dedicated freelancer, I offer a range of top-quality services tailored to meet your specific needs. With expertise in App Development, I provide professional solutions that deliver tangible results. </p> </header> <!-- === Headings Text Ends === --> <!-- === Services Box Container Starts === --> <div class="services-container"> <div class="service-box"> <div class="icon-wrapper"> <i class="fa-solid fa-mobile-screen"></i> </div> <h2>App Development</h2> <p> I have gained a deep understanding of React Native's fundamentals and its ability to build robust and efficient mobile apps. I have successfully completed projects involving complex UI/UX designs, integration with third-party APIs, and performance optimization for optimal app performance.</p> <h3>React Native</h3> </div> <div class="service-box"> <div class="icon-wrapper"> <i class="fa-solid fa-data"></i> </div> <h2>Python Data Analytics</h2> <p>With my knowledge and experience in Python Data Analysis, I am well-prepared to tackle diverse analytical challenges and provide meaningful solutions that drive informed decision-making.</p> <h3> NumPy, Pandas, and Matplotlib</h3> </div> <div class="service-box"> <div class="icon-wrapper"> <i class="fa-solid fa-code"></i> </div> <h2>Web Development</h2> <p> I am well-equipped to design and develop visually appealing and responsive websites that meet modern web standards.</p> <h3>HTML,CSS and JS</h3> </div> </div> <!-- === Services Box Container Ends === --> </section> <!-- *** Services Section Ends *** --> <!-- *** Resume Section Starts *** --> <section class="resume reusable" id="resume"> <!-- === Headings Text Starts === --> <header class="headings"> <h3>Resume</h3> <h1>Education & Experience</h1> <p>Know about my Education and certifications and my experiences.</p> </header> <!-- === Headings Text Ends === --> <!-- === Resume Row Starts === --> <div class="resume-row"> <!-- === Left Column Starts === --> <div class="column column-left"> <header class="sub-heading"> <h2>EDUCATION</h2> </header> <main class="resume-contents"> <div class="box"> <h4>2021 - 2025 (undergrad)</h4> <h3>Bachelors of Computer Science</h3> <p>CGPA : 3.42</p> <h3 class="vanue">Government Collage University (GCU)</h3> </div> <div class="box"> <h3>Certifications</h3> <h3>DataCamp / Linkedin Academy</h3> <p>Completed Data Analytics course from DataCamp.Did some certifications in React native from Linkedin Learning Program.</p> <h5 class="vanue">Courses</h5> </div> <div class="box"> <h4>2019-2021</h4> <h3>Intermediate</h3> <p>Marks : 1010 / 1100 </p> <h3 class="vanue">Punjab Group of Collages (PGC)</h3> </div> </main> </div> <!-- === Left Column Ends === --> <!-- === Right Column Starts === --> <div class="column column-right"> <header class="sub-heading"> <h2>EXPERIENCE</h2> </header> <main class="resume-contents"> <div class="box"> <h3>Interships</h3> <h3>Internee as REACT-NATIVE developer</h3> <p>As a React-Native dev i completed my virtual internship at an indian company,also got the letter of recommendation</p> <h5 class="vanue">InfoAidTECH</h5> </div> <div class="box"> <h3>Front-End App developer</h3> <p>Currently pursuing my 3 Months App Developer virtual internship at Internee.pk.</p> <h5 class="vanue">Internee.Pk</h5> </div> <div class="box"> <h3>Freelancer</h3> <h3>React native developer</h3> <p>Currently also serving as Freelancer on freelance platforms.</p> <h5 class="vanue">Fiver/Upwork</h5> </div> </main> </div> <!-- === Right Column Ends === --> </div> <!-- === Resume Row Ends === --> </section> <!-- *** Resume Section Ends *** --> <!-- *** Portfolio Section Starts *** --> <section class="portfolio reusable" id="portfolio"> <!-- === Headings Text Starts === --> <header class="headings"> <h1>Portfolio</h1> <h1>Some Of My React Native Projects</h1> <p>You can find out all the Links on github <br> Click Here to continue to github <br> <a href="https://github.com/Maazleo"><i class="fa-brands fa-github"></i></a></p> </header> <!-- === Headings Text Ends === --> <main class="mainContainer"> <div class="button-group"> <button class="button active" data-filter="*">All</button> <button class="button" data-filter=".design">React-Native</button> <button class="button" data-filter=".code">Web Development</button> <button class="button" data-filter=".logo">Python </button> </div> <div class="gallery"> <div class="item design"> <img src="cs.png"> <div class="overlay"> <a href="cs.png">VIEW MORE</a> </div> </div> <div class="item design"> <img src="cs.png"> <div class="overlay"> <a href="cs.png">VIEW MORE</a> </div> </div> <div class="item code"> <img src="cs.png"> <div class="overlay"> <a href="cs.png">VIEW MORE</a> </div> </div> <div class="item code"> <img src="cs.png"> <div class="overlay"> <a href="cs.png">VIEW MORE</a> </div> </div> <div class="item code"> <img src="cs.png"> <div class="overlay"> <a href="cs.png">VIEW MORE</a> </div> </div> <div class="item logo"> <img src="cs.png"> <div class="overlay"> <a href="cs.png">VIEW MORE</a> </div> </div> </div> </main> </section> <!-- ** Testimonials Section Ends *** --> <br> <br> <br> <br> <br> <br> <!-- *** Contact Section Starts *** --> <section class="contact-form" id="contactForm"> <div class="contact-row"> <!-- === Left Column Starts === --> <div class="contact-col column-1"> <div class="contactTitle"> <h2>Get In Touch</h2> <p>Liked my portfolio ? Get in touch Now!.</p> </div> <form class="form-1"> <div class="inputGroup"> <input type="text" name="" required="required"> <label>Your Name</label> </div> <div class="inputGroup"> <input type="email" name="" required="required"> <label>Email</label> </div> </form> <div class="contactSocialMedia"> <a href="https://www.facebook.com/maazhun" target="_blank" rel="noopener noreferrer"><i class="fa-brands fa-facebook-f"></i></a> <a href="https://github.com/Maazleo"><i class="fa-brands fa-github"></i></a> <a href="#"><i class="fa-brands fa-instagram"></i></a> <a href="https://www.linkedin.com/in/muhammad-maaz-9b134a251" target="_blank" rel="noopener noreferrer"><i class="fa-brands fa-linkedin-in"></i></a> </div> </div> <!-- === Left Column Ends === --> <!-- === Right Column Starts === --> <div class="contact-col column-2"> <form class="form-2"> <div class="inputGroup"> <textarea required="required"></textarea> <label>Say Something</label> </div> <button class="form-button">MESSAGE ME</button> </form> </div> <!-- === Right Column Ends === --> </div> </section> <!-- *** Contact Section Ends *** --> <!-- *** Footer Section Starts *** --> <section class="page-footer"> <footer class="footer-contents"> <a href="mailto:maazmasroorhuss@gmail.com" target="_blank" rel="noopener noreferrer">Contact me via email at maazmasroorhuss@gmail.com</a> <p>Created by <span>M MAAZ</span> | All rights reserved.</p> </footer> </section> <!-- *** Footer Section Ends *** --> </div> <!-- *** Website Container Ends *** --> <!-- *** Link To JQuery *** --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js" ></script> <!-- *** Link To Isotope *** --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.6/isotope.pkgd.min.js"></script> <!-- *** Link To Magnific Popup *** --> <script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js"></script> <!-- *** Link To OwlCarousel Js *** --> <script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script> <!-- *** Link To Custom Script File *** --> <script type="text/javascript" src="script.js"></script> </body> </html> <!--<!-- *** Portfolio Section Ends *** --> <!-- <section class="testimonials reusable" id="testimonials"> <header class="headings"> <h3>Testimonials</h3> <h1>What People Say</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> </header> <div class="owl-carousel owl-theme testimonials-container"> <div class="item testimonial-card"> <main class="test-card-body"> <div class="quote"> <i class="fa fa-quote-left"></i> <h2>Awesome Coding</h2> </div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.</p> <div class="ratings"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </main> <div class="profile"> <div class="profile-image"> <img src="images/profile1.jpg"> </div> <div class="profile-desc"> <span>John Doe</span> <span>Description</span> </div> </div> </div> <div class="item testimonial-card"> <main class="test-card-body"> <div class="quote"> <i class="fa fa-quote-left"></i> <h2>Unique Design</h2> </div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.</p> <div class="ratings"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </main> <div class="profile"> <div class="profile-image"> <img src="images/profile2.jpg"> </div> <div class="profile-desc"> <span>Jane Doe</span> <span>Description</span> </div> </div> </div> <div class="item testimonial-card"> <main class="test-card-body"> <div class="quote"> <i class="fa fa-quote-left"></i> <h2>Just Awesome</h2> </div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.</p> <div class="ratings"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </main> <div class="profile"> <div class="profile-image"> <img src="images/profile3.jpg"> </div> <div class="profile-desc"> <span>Albert Smith</span> <span>Description</span> </div> </div> </div> <div class="item testimonial-card"> <main class="test-card-body"> <div class="quote"> <i class="fa fa-quote-left"></i> <h2>Awesome Coding</h2> </div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.</p> <div class="ratings"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </main> <div class="profile"> <div class="profile-image"> <img src="images/profile4.jpg"> </div> <div class="profile-desc"> <span>Person Name</span> <span>Description</span> </div> </div> </div> <div class="item testimonial-card"> <main class="test-card-body"> <div class="quote"> <i class="fa fa-quote-left"></i> <h2>Simple Ways</h2> </div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.</p> <div class="ratings"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </main> <div class="profile"> <div class="profile-image"> <img src="images/profile5.jpg"> </div> <div class="profile-desc"> <span>Person Name</span> <span>Description</span> </div> </div> </div> <div class="item testimonial-card"> <main class="test-card-body"> <div class="quote"> <i class="fa fa-quote-left"></i> <h2>Awesome Coding</h2> </div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.</p> <div class="ratings"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </main> <div class="profile"> <div class="profile-image"> <img src="images/profile6.jpg"> </div> <div class="profile-desc"> <span>Etimad Khan</span> <span>Description</span> </div> </div> </div> </div> </section>-->
# 布艺 js 集团控股物业 > 原文:[https://www . geesforgeks . org/fabric-js-group-has controls-property/](https://www.geeksforgeeks.org/fabric-js-group-hascontrols-property/) 下面的文章介绍了如何使用 **Fabric.js** 设置画布的**组**的 **hasControls** 。Fabric.js 中的组是可移动的,可以根据需要拉伸。此外,当涉及到初始笔画颜色、高度、宽度、填充颜色或笔画宽度时,可以自定义该组。 为了实现这一点,我们将使用一个名为 **Fabric.js** 的 JavaScript 库。导入库后,我们将在包含组的主体标签中创建画布块。之后,我们将初始化由 **Fabric.js** 提供的画布和组的实例,并使用 **hasControls** 属性禁用画布组的控件。 **语法:** ``` fabric.Group([canvas1, canvas2], { hasControls: Boolean }); ``` **参数:**该属性接受如上所述的单个参数,如下所述: * **hasControls :** 指定拐角是否可见。它包含一个布尔值。 以下示例说明了在 JavaScript 中使用 fabric . js Group**hasControls**属性: **示例:** ## 超文本标记语言 ``` <!DOCTYPE html> <html> <head>   <!-- FabricJS CDN -->   <script src= "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">   </script> </head> <body>     <div style="text-align: center;width: 400px;">       <h1 style="color: green;">           GeeksforGeeks       </h1>       <b>           Fabric.js | Group hasControls Property       </b>     </div>     <div style="text-align: center;">       <canvas id="canvas" width="500" height="300"       style="border:1px solid green;">       </canvas>     </div>     <script>       // Initiate a Canvas instance       var canvas = new fabric.Canvas("canvas");       // Initiate a circle instance       var circle = new fabric.Circle({         radius: 100,         fill: 'lightgreen',         scaleY: 0.6,         originX: 'center',         originY: 'center'       });       // Initiate a text instance       var text = new fabric.Text('GeeksforGeeks', {         fontSize: 25,         originX: 'center',         originY: 'center'       });       // Initiate a Group instance       var group = new fabric.Group([ circle, text ], {         hasControls: false             });       // Render the Group in canvas       canvas.add(group);       // Center the Group in canvas       canvas.centerObject(group);   </script> </body> </html> ``` **输出:** ![](img/367b321a2858b5bd3bc51517d9a81b3d.png)
```c /** * zs_create_pool - Creates an allocation pool to work from. * @name: pool name to be created * * This function must be called before anything when using * the zsmalloc allocator. * * On success, a pointer to the newly created pool is returned, * otherwise NULL. */ struct zs_pool *zs_create_pool(const char *name) { int i; struct zs_pool *pool; struct size_class *prev_class = NULL; pool = kzalloc(sizeof(*pool), GFP_KERNEL); if (!pool) return NULL; init_deferred_free(pool); pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *), GFP_KERNEL); if (!pool->size_class) { kfree(pool); return NULL; } pool->name = kstrdup(name, GFP_KERNEL); if (!pool->name) goto err; if (create_cache(pool))//为zs_handle和zspage创建slab内存池 goto err; /* * Iterate reversly, because, size of size_class that we want to use * for merging should be larger or equal to current size. /* #define CLASS_BITS 8 #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> CLASS_BITS) //16 #define ZS_MAX_ALLOC_SIZE PAGE_SIZE #define ZS_MAX_ZSPAGE_ORDER 3 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER) //8 #define ZS_MIN_ALLOC_SIZE \ MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS)) //32 #define ZS_SIZE_CLASSES (DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \ ZS_SIZE_CLASS_DELTA) + 1) // ZS_SIZE_CLASS_DELTA为16,ZS_SIZE_CLASSES为254+1 */ */ for (i = zs_size_classes - 1; i >= 0; i--) {//zs_size_classes见init_zs_size_classes int size; int pages_per_zspage; int objs_per_zspage; struct size_class *class; int fullness = 0; /*初始化各class, 范围为ZS_MIN_ALLOC_SIZE(32)到ZS_MAX_ALLOC_SIZE(4096), 间隔为_SIZE_CLASS_DELTA(16),对象大小可以是32、48。。。4k,一共255种可能*/ size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA; if (size > ZS_MAX_ALLOC_SIZE) size = ZS_MAX_ALLOC_SIZE; //ZS_MAX_ALLOC_SIZE为PAGE_SIZE, 最大情况为不压缩 pages_per_zspage = get_pages_per_zspage(size);//对每种size object分配合适的page数, 使得内存浪费最少。 objs_per_zspage = pages_per_zspage * PAGE_SIZE / size; /* * size_class is used for normal zsmalloc operation such * as alloc/free for that size. Although it is natural that we * have one size_class for each size, there is a chance that we * can get more memory utilization if we use one size_class for * many different sizes whose size_class have same * characteristics. So, we makes size_class point to * previous size_class if possible. */ /* 判断是否可以使用上一次分配的size_class作为本次的size_class。 如果本次要分配的页数和上次分配的页数相同,并且两次可保存的最大对象数也相同,则使用上次的size_class。 如果条件成立,意味着如果为本次分配新的size_class,将产生比上次更大的内存碎片而造成浪费, 这时不如直接用上次的size_class。这就是为什么for循环是从zs_size_classes - 1开始向下遍历,而不是从0开始。 如果不能merge,则创建新的size_class并初始化各个成员变量。注意,此时并未为size_class分配内存页 */ if (prev_class) { if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) { pool->size_class[i] = prev_class; continue; } } class = kzalloc(sizeof(struct size_class), GFP_KERNEL);//分配class内存 if (!class) goto err; class->size = size; class->index = i; class->pages_per_zspage = pages_per_zspage; class->objs_per_zspage = objs_per_zspage; spin_lock_init(&class->lock); pool->size_class[i] = class; for (fullness = ZS_EMPTY; fullness < NR_ZS_FULLNESS;//初始化 ZS_ALMOST_EMPTY,ZS_ALMOST_FULL,ZS_FULL几种链表 fullness++) INIT_LIST_HEAD(&class->fullness_list[fullness]); prev_class = class; } /* debug only, don't abort if it fails */ zs_pool_stat_create(pool, name); if (zs_register_migration(pool)) goto err; /* * Not critical, we still can use the pool * and user can trigger compaction manually. */ if (zs_register_shrinker(pool) == 0)//为zs_pool注册shrinker pool->shrinker_enabled = true; return pool; err: zs_destroy_pool(pool); return NULL; } EXPORT_SYMBOL_GPL(zs_create_pool); ``` 可以看到zs_size_classes的计算和ZS_SIZE_CLASS_DELTA、ZS_MIN_ALLOC_SIZE、ZS_MAX_ALLOC_SIZE是有关系的。 这使得zs_size_classes即为所有可能的个数。 ```c static void __init init_zs_size_classes(void) { int nr; nr = (ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / ZS_SIZE_CLASS_DELTA + 1; if ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) % ZS_SIZE_CLASS_DELTA) nr += 1; zs_size_classes = nr; } ```
import threading import random from typing import List from media import Media class Playlist: def __init__(self, name: str, repeat: bool = False, shuffle: bool = False): self.__name: str = name self.__medias: List[Media] = [] self.__repeat: bool = repeat self.__shuffle: bool = shuffle def __getitem__(self, item) -> Media: return self.__medias[item] def __len__(self) -> int: return len(self.__medias) @property def name(self) -> str: return self.__name @property def medias(self) -> List[Media]: return self.__medias @medias.setter def medias(self, medias: List[Media]) -> None: self.__medias = medias if self.__shuffle: random.shuffle(self.__medias) @property def repeat(self) -> bool: return self.__repeat @repeat.setter def repeat(self, repeat: bool) -> None: self.__repeat = repeat @property def shuffle(self) -> bool: return self.__shuffle @shuffle.setter def shuffle(self, shuffle: bool) -> None: self.__shuffle = shuffle if self.__shuffle: random.shuffle(self.__medias) def add_media(self, media: Media) -> None: self.__medias.append(media) def remove_last_media(self, media: Media) -> None: self.__medias.remove(media) def show_last_media(self) -> Media: return self.__medias[0] if self.__medias else None def play(self) -> None: if self.__medias: event = threading.Event() if self.__repeat: while True: for media in self.__medias: event.wait(3) print(f'\n\nIs playing {self.__name} playlist') print(f'Is on repeat: {self.__repeat}') print(f'Is on shuffle: {self.__shuffle}') print(media) else: for media in self.__medias: event.wait(3) print(f'Is playing {self.__name} playlist') print(f'Is on repeat: {self.__repeat}') print(f'Is on shuffle: {self.__shuffle}') print(media)
import logging from datetime import datetime from typing import ClassVar, Dict, Optional, List, Type from attr import define, field from fix_plugin_gcp.gcp_client import GcpApiSpec from fix_plugin_gcp.resources.base import GcpResource, GcpDeprecationStatus, GraphBuilder from fix_plugin_gcp.resources.compute import GcpSslCertificate from fixlib.baseresources import BaseDatabase, DatabaseInstanceStatus, ModelReference from fixlib.json_bender import F, Bender, S, Bend, ForallBend, K, MapEnum from fixlib.types import Json log = logging.getLogger("fix.plugins.gcp") @define(eq=False, slots=False) class GcpSqlOperationError: kind: ClassVar[str] = "gcp_sql_operation_error" kind_display: ClassVar[str] = "GCP SQL Operation Error" kind_description: ClassVar[str] = ( "This error refers to an error that occurred during an operation related to" " Google Cloud SQL, which is a fully managed relational database service" " provided by Google Cloud Platform." ) mapping: ClassVar[Dict[str, Bender]] = {"code": S("code"), "message": S("message")} code: Optional[str] = field(default=None) message: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlBackupRun(GcpResource): # collected via GcpSqlDatabaseInstance kind: ClassVar[str] = "gcp_sql_backup_run" kind_display: ClassVar[str] = "GCP SQL Backup Run" kind_description: ClassVar[str] = ( "GCP SQL Backup Run is a feature in Google Cloud Platform that allows users" " to schedule and execute automated backups of their SQL databases." ) reference_kinds: ClassVar[ModelReference] = {"predecessors": {"default": ["gcp_database_instance"]}} api_spec: ClassVar[GcpApiSpec] = GcpApiSpec( service="sqladmin", version="v1", accessors=["backupRuns"], action="list", request_parameter={"instance": "{instance}", "project": "{project}"}, request_parameter_in={"instance", "project"}, response_path="items", response_regional_sub_path=None, required_iam_permissions=["cloudsql.backupRuns.list"], mutate_iam_permissions=["cloudsql.backupRuns.delete"], ) mapping: ClassVar[Dict[str, Bender]] = { "id": S("name").or_else(S("id")).or_else(S("selfLink")), "tags": S("labels", default={}), "name": S("name"), "ctime": S("creationTimestamp"), "description": S("description"), "link": S("selfLink"), "label_fingerprint": S("labelFingerprint"), "deprecation_status": S("deprecated", default={}) >> Bend(GcpDeprecationStatus.mapping), "backup_kind": S("backupKind"), "disk_encryption_configuration": S("diskEncryptionConfiguration", "kmsKeyName"), "disk_encryption_status": S("diskEncryptionStatus", "kmsKeyVersionName"), "end_time": S("endTime"), "enqueued_time": S("enqueuedTime"), "sql_operation_error": S("error", default={}) >> Bend(GcpSqlOperationError.mapping), "instance": S("instance"), "location": S("location"), "start_time": S("startTime"), "status": S("status"), "time_zone": S("timeZone"), "type": S("type"), "window_start_time": S("windowStartTime"), } backup_kind: Optional[str] = field(default=None) disk_encryption_configuration: Optional[str] = field(default=None) disk_encryption_status: Optional[str] = field(default=None) end_time: Optional[datetime] = field(default=None) enqueued_time: Optional[datetime] = field(default=None) sql_operation_error: Optional[GcpSqlOperationError] = field(default=None) instance: Optional[str] = field(default=None) location: Optional[str] = field(default=None) start_time: Optional[datetime] = field(default=None) status: Optional[str] = field(default=None) time_zone: Optional[str] = field(default=None) type: Optional[str] = field(default=None) window_start_time: Optional[datetime] = field(default=None) def connect_in_graph(self, builder: GraphBuilder, source: Json) -> None: if self.instance: builder.add_edge(self, reverse=True, clazz=GcpSqlDatabaseInstance, name=self.instance) @define(eq=False, slots=False) class GcpSqlSqlServerDatabaseDetails: kind: ClassVar[str] = "gcp_sql_sql_server_database_details" kind_display: ClassVar[str] = "GCP SQL SQL Server Database Details" kind_description: ClassVar[str] = ( "This resource provides details and information about a Microsoft SQL Server" " database in the Google Cloud Platform's SQL service." ) mapping: ClassVar[Dict[str, Bender]] = { "compatibility_level": S("compatibilityLevel"), "recovery_model": S("recoveryModel"), } compatibility_level: Optional[int] = field(default=None) recovery_model: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlDatabase(GcpResource): # collected via GcpSqlDatabaseInstance kind: ClassVar[str] = "gcp_sql_database" kind_display: ClassVar[str] = "GCP SQL Database" kind_description: ClassVar[str] = ( "GCP SQL Database is a managed relational database service provided by Google Cloud Platform." ) api_spec: ClassVar[GcpApiSpec] = GcpApiSpec( service="sqladmin", version="v1", accessors=["databases"], action="list", request_parameter={"instance": "{instance}", "project": "{project}"}, request_parameter_in={"instance", "project"}, response_path="items", response_regional_sub_path=None, required_iam_permissions=["cloudsql.databases.list"], mutate_iam_permissions=["cloudsql.databases.update", "cloudsql.databases.delete"], ) reference_kinds: ClassVar[ModelReference] = {"predecessors": {"default": ["gcp_sql_database_instance"]}} mapping: ClassVar[Dict[str, Bender]] = { "id": S("name").or_else(S("id")).or_else(S("selfLink")), "tags": S("labels", default={}), "name": S("name"), "ctime": S("creationTimestamp"), "description": S("description"), "link": S("selfLink"), "label_fingerprint": S("labelFingerprint"), "deprecation_status": S("deprecated", default={}) >> Bend(GcpDeprecationStatus.mapping), "charset": S("charset"), "collation": S("collation"), "etag": S("etag"), "instance": S("instance"), "project": S("project"), "sqlserver_database_details": S("sqlserverDatabaseDetails", default={}) >> Bend(GcpSqlSqlServerDatabaseDetails.mapping), } charset: Optional[str] = field(default=None) collation: Optional[str] = field(default=None) etag: Optional[str] = field(default=None) instance: Optional[str] = field(default=None) project: Optional[str] = field(default=None) sqlserver_database_details: Optional[GcpSqlSqlServerDatabaseDetails] = field(default=None) def connect_in_graph(self, builder: GraphBuilder, source: Json) -> None: if self.instance: builder.add_edge(self, reverse=True, clazz=GcpSqlDatabaseInstance, name=self.instance) @define(eq=False, slots=False) class GcpSqlFailoverreplica: kind: ClassVar[str] = "gcp_sql_failoverreplica" kind_display: ClassVar[str] = "GCP SQL Failover Replica" kind_description: ClassVar[str] = ( "A GCP SQL Failover Replica is a secondary replica database that can be" " promoted to the primary database in case of a primary database failure," " ensuring high availability and data redundancy for Google Cloud SQL." ) mapping: ClassVar[Dict[str, Bender]] = {"available": S("available"), "name": S("name")} available: Optional[bool] = field(default=None) name: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlIpMapping: kind: ClassVar[str] = "gcp_sql_ip_mapping" kind_display: ClassVar[str] = "GCP SQL IP Mapping" kind_description: ClassVar[str] = ( "The GCP SQL IP Mapping configures the IP address allocation for a Cloud SQL database instance, detailing" " the assigned IP, its type, and any scheduled retirement." ) mapping: ClassVar[Dict[str, Bender]] = { "ip_address": S("ipAddress"), "time_to_retire": S("timeToRetire"), "type": S("type"), } ip_address: Optional[str] = field(default=None) time_to_retire: Optional[str] = field(default=None) type: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlInstanceReference: kind: ClassVar[str] = "gcp_sql_instance_reference" kind_display: ClassVar[str] = "GCP Cloud SQL Instance Reference" kind_description: ClassVar[str] = ( "Cloud SQL is a fully-managed relational database service provided by Google" " Cloud Platform, allowing users to create and manage MySQL or PostgreSQL" " databases in the cloud." ) mapping: ClassVar[Dict[str, Bender]] = {"name": S("name"), "project": S("project"), "region": S("region")} name: Optional[str] = field(default=None) project: Optional[str] = field(default=None) region: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlOnPremisesConfiguration: kind: ClassVar[str] = "gcp_sql_on_premises_configuration" kind_display: ClassVar[str] = "GCP SQL On-Premises Configuration" kind_description: ClassVar[str] = ( "The GCP SQL On-Premises Configuration is used for setting up secure connections and credentials for migrating" " or syncing data between an on-premises database and a GCP SQL Database Instance." ) mapping: ClassVar[Dict[str, Bender]] = { "ca_certificate": S("caCertificate"), "client_certificate": S("clientCertificate"), "client_key": S("clientKey"), "dump_file_path": S("dumpFilePath"), "host_port": S("hostPort"), "password": S("password"), "source_instance": S("sourceInstance", default={}) >> Bend(GcpSqlInstanceReference.mapping), "username": S("username"), } ca_certificate: Optional[str] = field(default=None) client_certificate: Optional[str] = field(default=None) client_key: Optional[str] = field(default=None) dump_file_path: Optional[str] = field(default=None) host_port: Optional[str] = field(default=None) password: Optional[str] = field(default=None) source_instance: Optional[GcpSqlInstanceReference] = field(default=None) username: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlSqlOutOfDiskReport: kind: ClassVar[str] = "gcp_sql_sql_out_of_disk_report" kind_display: ClassVar[str] = "GCP SQL Out of Disk Report" kind_description: ClassVar[str] = ( "The GCP SQL Out of Disk Report provides insights into the storage status of a SQL database instance," " including recommendations on the minimum size increase necessary to prevent running out of disk space." ) mapping: ClassVar[Dict[str, Bender]] = { "sql_min_recommended_increase_size_gb": S("sqlMinRecommendedIncreaseSizeGb"), "sql_out_of_disk_state": S("sqlOutOfDiskState"), } sql_min_recommended_increase_size_gb: Optional[int] = field(default=None) sql_out_of_disk_state: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlMySqlReplicaConfiguration: kind: ClassVar[str] = "gcp_sql_my_sql_replica_configuration" kind_display: ClassVar[str] = "GCP SQL MySQL Replica Configuration" kind_description: ClassVar[str] = ( "MySQL Replica Configuration is a feature in Google Cloud SQL that enables" " the creation and management of replicas for high availability and fault" " tolerance of MySQL databases." ) mapping: ClassVar[Dict[str, Bender]] = { "ca_certificate": S("caCertificate"), "client_certificate": S("clientCertificate"), "client_key": S("clientKey"), "connect_retry_interval": S("connectRetryInterval"), "dump_file_path": S("dumpFilePath"), "master_heartbeat_period": S("masterHeartbeatPeriod"), "password": S("password"), "ssl_cipher": S("sslCipher"), "username": S("username"), "verify_server_certificate": S("verifyServerCertificate"), } ca_certificate: Optional[str] = field(default=None) client_certificate: Optional[str] = field(default=None) client_key: Optional[str] = field(default=None) connect_retry_interval: Optional[int] = field(default=None) dump_file_path: Optional[str] = field(default=None) master_heartbeat_period: Optional[str] = field(default=None) password: Optional[str] = field(default=None) ssl_cipher: Optional[str] = field(default=None) username: Optional[str] = field(default=None) verify_server_certificate: Optional[bool] = field(default=None) @define(eq=False, slots=False) class GcpSqlReplicaConfiguration: kind: ClassVar[str] = "gcp_sql_replica_configuration" kind_display: ClassVar[str] = "GCP SQL Replica Configuration" kind_description: ClassVar[str] = ( "SQL replica configuration in Google Cloud Platform (GCP) allows users to" " create and manage replica instances of a SQL database for improved" " scalability and high availability." ) mapping: ClassVar[Dict[str, Bender]] = { "failover_target": S("failoverTarget"), "mysql_replica_configuration": S("mysqlReplicaConfiguration", default={}) >> Bend(GcpSqlMySqlReplicaConfiguration.mapping), } failover_target: Optional[bool] = field(default=None) mysql_replica_configuration: Optional[GcpSqlMySqlReplicaConfiguration] = field(default=None) @define(eq=False, slots=False) class GcpSqlScheduledMaintenance: kind: ClassVar[str] = "gcp_sql_scheduled_maintenance" kind_display: ClassVar[str] = "GCP SQL Scheduled Maintenance" kind_description: ClassVar[str] = ( "GCP SQL Scheduled Maintenance is a feature that allows database administrators to schedule maintenance" " operations for a SQL database instance, with options to defer and reschedule within a specified deadline." ) mapping: ClassVar[Dict[str, Bender]] = { "can_defer": S("canDefer"), "can_reschedule": S("canReschedule"), "schedule_deadline_time": S("scheduleDeadlineTime"), "start_time": S("startTime"), } can_defer: Optional[bool] = field(default=None) can_reschedule: Optional[bool] = field(default=None) schedule_deadline_time: Optional[datetime] = field(default=None) start_time: Optional[datetime] = field(default=None) @define(eq=False, slots=False) class GcpSqlSslCert: kind: ClassVar[str] = "gcp_sql_ssl_cert" kind_display: ClassVar[str] = "GCP SQL SSL Certificate" kind_description: ClassVar[str] = ( "GCP SQL SSL Certificates are used to secure connections between applications" " and Google Cloud SQL databases, ensuring that data exchanged between them is" " encrypted." ) mapping: ClassVar[Dict[str, Bender]] = { "cert": S("cert"), "cert_serial_number": S("certSerialNumber"), "common_name": S("commonName"), "create_time": S("createTime"), "expiration_time": S("expirationTime"), "instance": S("instance"), "self_link": S("selfLink"), "sha1_fingerprint": S("sha1Fingerprint"), } cert: Optional[str] = field(default=None) cert_serial_number: Optional[str] = field(default=None) common_name: Optional[str] = field(default=None) create_time: Optional[datetime] = field(default=None) expiration_time: Optional[datetime] = field(default=None) instance: Optional[str] = field(default=None) self_link: Optional[str] = field(default=None) sha1_fingerprint: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlBackupRetentionSettings: kind: ClassVar[str] = "gcp_sql_backup_retention_settings" kind_display: ClassVar[str] = "GCP SQL Backup Retention Settings" kind_description: ClassVar[str] = ( "GCP SQL Backup Retention Settings is a feature in Google Cloud Platform that" " allows you to configure the backup retention policy for your SQL databases." " It lets you set the duration for which backups should be retained before" " being automatically deleted." ) mapping: ClassVar[Dict[str, Bender]] = { "retained_backups": S("retainedBackups"), "retention_unit": S("retentionUnit"), } retained_backups: Optional[int] = field(default=None) retention_unit: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlBackupConfiguration: kind: ClassVar[str] = "gcp_sql_backup_configuration" kind_display: ClassVar[str] = "GCP SQL Backup Configuration" kind_description: ClassVar[str] = ( "GCP SQL Backup Configuration is a resource in Google Cloud Platform that" " allows users to configure and manage backups for their SQL databases." ) mapping: ClassVar[Dict[str, Bender]] = { "backup_retention_settings": S("backupRetentionSettings", default={}) >> Bend(GcpSqlBackupRetentionSettings.mapping), "binary_log_enabled": S("binaryLogEnabled"), "enabled": S("enabled"), "location": S("location"), "point_in_time_recovery_enabled": S("pointInTimeRecoveryEnabled"), "replication_log_archiving_enabled": S("replicationLogArchivingEnabled"), "start_time": S("startTime"), "transaction_log_retention_days": S("transactionLogRetentionDays"), } backup_retention_settings: Optional[GcpSqlBackupRetentionSettings] = field(default=None) binary_log_enabled: Optional[bool] = field(default=None) enabled: Optional[bool] = field(default=None) location: Optional[str] = field(default=None) point_in_time_recovery_enabled: Optional[bool] = field(default=None) replication_log_archiving_enabled: Optional[bool] = field(default=None) start_time: Optional[str] = field(default=None) transaction_log_retention_days: Optional[int] = field(default=None) @define(eq=False, slots=False) class GcpSqlDatabaseFlags: kind: ClassVar[str] = "gcp_sql_database_flags" kind_display: ClassVar[str] = "GCP SQL Database Flags" kind_description: ClassVar[str] = ( "GCP SQL Database Flags are configuration settings that can be applied to" " Google Cloud Platform's SQL databases to customize their behavior." ) mapping: ClassVar[Dict[str, Bender]] = {"name": S("name"), "value": S("value")} name: Optional[str] = field(default=None) value: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlDenyMaintenancePeriod: kind: ClassVar[str] = "gcp_sql_deny_maintenance_period" kind_display: ClassVar[str] = "GCP SQL Deny Maintenance Period" kind_description: ClassVar[str] = ( "GCP SQL Deny Maintenance Period specifies a time frame during which maintenance activities by GCP on a SQL" " database instance are not allowed, ensuring uninterrupted service during critical business periods." ) mapping: ClassVar[Dict[str, Bender]] = {"end_date": S("endDate"), "start_date": S("startDate"), "time": S("time")} end_date: Optional[str] = field(default=None) start_date: Optional[str] = field(default=None) time: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlInsightsConfig: kind: ClassVar[str] = "gcp_sql_insights_config" kind_display: ClassVar[str] = "GCP SQL Insights Config" kind_description: ClassVar[str] = ( "GCP SQL Insights Config is a feature in Google Cloud Platform that allows" " users to configure and customize their SQL database insights and monitoring." ) mapping: ClassVar[Dict[str, Bender]] = { "query_insights_enabled": S("queryInsightsEnabled"), "query_plans_per_minute": S("queryPlansPerMinute"), "query_string_length": S("queryStringLength"), "record_application_tags": S("recordApplicationTags"), "record_client_address": S("recordClientAddress"), } query_insights_enabled: Optional[bool] = field(default=None) query_plans_per_minute: Optional[int] = field(default=None) query_string_length: Optional[int] = field(default=None) record_application_tags: Optional[bool] = field(default=None) record_client_address: Optional[bool] = field(default=None) @define(eq=False, slots=False) class GcpSqlAclEntry: kind: ClassVar[str] = "gcp_sql_acl_entry" kind_display: ClassVar[str] = "GCP SQL ACL Entry" kind_description: ClassVar[str] = ( "GCP SQL ACL Entry is a resource in Google Cloud Platform that represents an" " access control list entry for a Cloud SQL instance. It defines policies for" " granting or denying network access to the SQL instance." ) mapping: ClassVar[Dict[str, Bender]] = { "expiration_time": S("expirationTime"), "name": S("name"), "value": S("value"), } expiration_time: Optional[datetime] = field(default=None) name: Optional[str] = field(default=None) value: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlIpConfiguration: kind: ClassVar[str] = "gcp_sql_ip_configuration" kind_display: ClassVar[str] = "GCP SQL IP Configuration" kind_description: ClassVar[str] = ( "IP Configuration refers to the settings for managing IP addresses associated" " with Google Cloud Platform(SQL) instances, allowing users to control network" " access to their databases." ) mapping: ClassVar[Dict[str, Bender]] = { "allocated_ip_range": S("allocatedIpRange"), "authorized_networks": S("authorizedNetworks", default=[]) >> ForallBend(GcpSqlAclEntry.mapping), "ipv4_enabled": S("ipv4Enabled"), "private_network": S("privateNetwork"), "require_ssl": S("requireSsl"), } allocated_ip_range: Optional[str] = field(default=None) authorized_networks: Optional[List[GcpSqlAclEntry]] = field(default=None) ipv4_enabled: Optional[bool] = field(default=None) private_network: Optional[str] = field(default=None) require_ssl: Optional[bool] = field(default=None) @define(eq=False, slots=False) class GcpSqlLocationPreference: kind: ClassVar[str] = "gcp_sql_location_preference" kind_display: ClassVar[str] = "GCP SQL Location Preference" kind_description: ClassVar[str] = ( "GCP SQL Location Preference allows users to specify the preferred location" " for their Google Cloud SQL database instances, helping them ensure optimal" " performance and compliance with data sovereignty requirements." ) mapping: ClassVar[Dict[str, Bender]] = { "follow_gae_application": S("followGaeApplication"), "secondary_zone": S("secondaryZone"), "zone": S("zone"), } follow_gae_application: Optional[str] = field(default=None) secondary_zone: Optional[str] = field(default=None) zone: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlMaintenanceWindow: kind: ClassVar[str] = "gcp_sql_maintenance_window" kind_display: ClassVar[str] = "GCP SQL Maintenance Window" kind_description: ClassVar[str] = ( "A maintenance window is a predefined time period when Google Cloud SQL" " performs system updates and maintenance tasks on your databases." ) mapping: ClassVar[Dict[str, Bender]] = {"day": S("day"), "hour": S("hour"), "update_track": S("updateTrack")} day: Optional[int] = field(default=None) hour: Optional[int] = field(default=None) update_track: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlPasswordValidationPolicy: kind: ClassVar[str] = "gcp_sql_password_validation_policy" kind_display: ClassVar[str] = "GCP SQL Password Validation Policy" kind_description: ClassVar[str] = ( "GCP SQL Password Validation Policy is a feature in Google Cloud Platform" " that enforces strong password policies for SQL databases, ensuring better" " security and compliance with password requirements." ) mapping: ClassVar[Dict[str, Bender]] = { "complexity": S("complexity"), "disallow_username_substring": S("disallowUsernameSubstring"), "enable_password_policy": S("enablePasswordPolicy"), "min_length": S("minLength"), "password_change_interval": S("passwordChangeInterval"), "reuse_interval": S("reuseInterval"), } complexity: Optional[str] = field(default=None) disallow_username_substring: Optional[bool] = field(default=None) enable_password_policy: Optional[bool] = field(default=None) min_length: Optional[int] = field(default=None) password_change_interval: Optional[str] = field(default=None) reuse_interval: Optional[int] = field(default=None) @define(eq=False, slots=False) class GcpSqlSqlServerAuditConfig: kind: ClassVar[str] = "gcp_sql_sql_server_audit_config" kind_display: ClassVar[str] = "GCP SQL Server Audit Configuration" kind_description: ClassVar[str] = ( "GCP SQL Server Audit Configuration provides a way to enable and configure" " SQL Server auditing for Google Cloud Platform (GCP) SQL Server instances." " Auditing allows users to monitor and record database activities and events" " for security and compliance purposes." ) mapping: ClassVar[Dict[str, Bender]] = { "bucket": S("bucket"), "retention_interval": S("retentionInterval"), "upload_interval": S("uploadInterval"), } bucket: Optional[str] = field(default=None) retention_interval: Optional[str] = field(default=None) upload_interval: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlSettings: kind: ClassVar[str] = "gcp_sql_settings" kind_display: ClassVar[str] = "GCP SQL Settings" kind_description: ClassVar[str] = ( "GCP SQL Settings refers to the configuration and customization options for" " managing SQL databases in Google Cloud Platform (GCP). It includes various" " settings related to database performance, security, availability, and" " monitoring." ) mapping: ClassVar[Dict[str, Bender]] = { "activation_policy": S("activationPolicy"), "active_directory_config": S("activeDirectoryConfig", "domain"), "authorized_gae_applications": S("authorizedGaeApplications", default=[]), "availability_type": S("availabilityType"), "backup_configuration": S("backupConfiguration", default={}) >> Bend(GcpSqlBackupConfiguration.mapping), "collation": S("collation"), "connector_enforcement": S("connectorEnforcement"), "crash_safe_replication_enabled": S("crashSafeReplicationEnabled"), "data_disk_size_gb": S("dataDiskSizeGb"), "data_disk_type": S("dataDiskType"), "database_flags": S("databaseFlags", default=[]) >> ForallBend(GcpSqlDatabaseFlags.mapping), "database_replication_enabled": S("databaseReplicationEnabled"), "deletion_protection_enabled": S("deletionProtectionEnabled"), "deny_maintenance_periods": S("denyMaintenancePeriods", default=[]) >> ForallBend(GcpSqlDenyMaintenancePeriod.mapping), "insights_config": S("insightsConfig", default={}) >> Bend(GcpSqlInsightsConfig.mapping), "ip_configuration": S("ipConfiguration", default={}) >> Bend(GcpSqlIpConfiguration.mapping), "location_preference": S("locationPreference", default={}) >> Bend(GcpSqlLocationPreference.mapping), "maintenance_window": S("maintenanceWindow", default={}) >> Bend(GcpSqlMaintenanceWindow.mapping), "password_validation_policy": S("passwordValidationPolicy", default={}) >> Bend(GcpSqlPasswordValidationPolicy.mapping), "pricing_plan": S("pricingPlan"), "replication_type": S("replicationType"), "settings_version": S("settingsVersion"), "sql_server_audit_config": S("sqlServerAuditConfig", default={}) >> Bend(GcpSqlSqlServerAuditConfig.mapping), "storage_auto_resize": S("storageAutoResize"), "storage_auto_resize_limit": S("storageAutoResizeLimit"), "tier": S("tier"), "time_zone": S("timeZone"), "user_labels": S("userLabels"), } activation_policy: Optional[str] = field(default=None) active_directory_config: Optional[str] = field(default=None) authorized_gae_applications: Optional[List[str]] = field(default=None) availability_type: Optional[str] = field(default=None) backup_configuration: Optional[GcpSqlBackupConfiguration] = field(default=None) collation: Optional[str] = field(default=None) connector_enforcement: Optional[str] = field(default=None) crash_safe_replication_enabled: Optional[bool] = field(default=None) data_disk_size_gb: Optional[str] = field(default=None) data_disk_type: Optional[str] = field(default=None) database_flags: Optional[List[GcpSqlDatabaseFlags]] = field(default=None) database_replication_enabled: Optional[bool] = field(default=None) deletion_protection_enabled: Optional[bool] = field(default=None) deny_maintenance_periods: Optional[List[GcpSqlDenyMaintenancePeriod]] = field(default=None) insights_config: Optional[GcpSqlInsightsConfig] = field(default=None) ip_configuration: Optional[GcpSqlIpConfiguration] = field(default=None) location_preference: Optional[GcpSqlLocationPreference] = field(default=None) maintenance_window: Optional[GcpSqlMaintenanceWindow] = field(default=None) password_validation_policy: Optional[GcpSqlPasswordValidationPolicy] = field(default=None) pricing_plan: Optional[str] = field(default=None) replication_type: Optional[str] = field(default=None) settings_version: Optional[str] = field(default=None) sql_server_audit_config: Optional[GcpSqlSqlServerAuditConfig] = field(default=None) storage_auto_resize: Optional[bool] = field(default=None) storage_auto_resize_limit: Optional[str] = field(default=None) tier: Optional[str] = field(default=None) time_zone: Optional[str] = field(default=None) user_labels: Optional[Dict[str, str]] = field(default=None) @define(eq=False, slots=False) class GcpSqlDatabaseInstance(GcpResource, BaseDatabase): kind: ClassVar[str] = "gcp_sql_database_instance" kind_display: ClassVar[str] = "GCP SQL Database Instance" kind_description: ClassVar[str] = ( "GCP SQL Database Instance is a resource provided by Google Cloud Platform" " that allows users to create and manage relational databases in the cloud." ) reference_kinds: ClassVar[ModelReference] = {"predecessors": {"default": ["gcp_ssl_certificate"]}} api_spec: ClassVar[GcpApiSpec] = GcpApiSpec( service="sqladmin", version="v1", accessors=["instances"], action="list", request_parameter={"project": "{project}"}, request_parameter_in={"project"}, response_path="items", response_regional_sub_path=None, required_iam_permissions=["cloudsql.instances.list"], mutate_iam_permissions=["cloudsql.instances.update", "cloudsql.instances.delete"], ) mapping: ClassVar[Dict[str, Bender]] = { "id": S("name").or_else(S("id")).or_else(S("selfLink")), "tags": S("labels", default={}), "name": S("name"), "ctime": S("createTime"), "description": S("description"), "link": S("selfLink"), "label_fingerprint": S("labelFingerprint"), "deprecation_status": S("deprecated", default={}) >> Bend(GcpDeprecationStatus.mapping), "available_maintenance_versions": S("availableMaintenanceVersions", default=[]), "backend_type": S("backendType"), "connection_name": S("connectionName"), "create_time": S("createTime"), "current_disk_size": S("currentDiskSize"), "database_installed_version": S("databaseInstalledVersion"), "database_version": S("databaseVersion"), "disk_encryption_configuration": S("diskEncryptionConfiguration", "kmsKeyName"), "disk_encryption_status": S("diskEncryptionStatus", "kmsKeyVersionName"), "etag": S("etag"), "failover_replica": S("failoverReplica", default={}) >> Bend(GcpSqlFailoverreplica.mapping), "gce_zone": S("gceZone"), "instance_type": S("instanceType"), "instance_ip_addresses": S("ipAddresses", default=[]) >> ForallBend(GcpSqlIpMapping.mapping), "ipv6_address": S("ipv6Address"), "maintenance_version": S("maintenanceVersion"), "master_instance_name": S("masterInstanceName"), "max_disk_size": S("maxDiskSize"), "on_premises_configuration": S("onPremisesConfiguration", default={}) >> Bend(GcpSqlOnPremisesConfiguration.mapping), "out_of_disk_report": S("outOfDiskReport", default={}) >> Bend(GcpSqlSqlOutOfDiskReport.mapping), "project": S("project"), "replica_configuration": S("replicaConfiguration", default={}) >> Bend(GcpSqlReplicaConfiguration.mapping), "replica_names": S("replicaNames", default=[]), "root_password": S("rootPassword"), "satisfies_pzs": S("satisfiesPzs"), "scheduled_maintenance": S("scheduledMaintenance", default={}) >> Bend(GcpSqlScheduledMaintenance.mapping), "secondary_gce_zone": S("secondaryGceZone"), "server_ca_cert": S("serverCaCert", default={}) >> Bend(GcpSqlSslCert.mapping), "service_account_email_address": S("serviceAccountEmailAddress"), "settings": S("settings", default={}) >> Bend(GcpSqlSettings.mapping), "sql_database_instance_state": S("state"), "suspension_reason": S("suspensionReason", default=[]), "db_type": S("databaseVersion") >> F(lambda db_version: db_version.split("_")[0].lower()), "db_status": S("state") >> MapEnum( { "RUNNABLE": DatabaseInstanceStatus.AVAILABLE, "MAINTENANCE": DatabaseInstanceStatus.BUSY, "FAILED": DatabaseInstanceStatus.FAILED, "STOPPED": DatabaseInstanceStatus.STOPPED, "CREATING": DatabaseInstanceStatus.BUSY, "DELETING": DatabaseInstanceStatus.TERMINATED, }, default=DatabaseInstanceStatus.UNKNOWN, ), "db_version": S("databaseVersion"), "volume_size": S("settings", "dataDiskSizeGb") >> F(int), } available_maintenance_versions: Optional[List[str]] = field(default=None) backend_type: Optional[str] = field(default=None) connection_name: Optional[str] = field(default=None) create_time: Optional[datetime] = field(default=None) current_disk_size: Optional[str] = field(default=None) database_installed_version: Optional[str] = field(default=None) database_version: Optional[str] = field(default=None) disk_encryption_configuration: Optional[str] = field(default=None) disk_encryption_status: Optional[str] = field(default=None) etag: Optional[str] = field(default=None) failover_replica: Optional[GcpSqlFailoverreplica] = field(default=None) gce_zone: Optional[str] = field(default=None) instance_ip_addresses: Optional[List[GcpSqlIpMapping]] = field(default=None) ipv6_address: Optional[str] = field(default=None) maintenance_version: Optional[str] = field(default=None) master_instance_name: Optional[str] = field(default=None) max_disk_size: Optional[str] = field(default=None) on_premises_configuration: Optional[GcpSqlOnPremisesConfiguration] = field(default=None) out_of_disk_report: Optional[GcpSqlSqlOutOfDiskReport] = field(default=None) project: Optional[str] = field(default=None) replica_configuration: Optional[GcpSqlReplicaConfiguration] = field(default=None) replica_names: Optional[List[str]] = field(default=None) root_password: Optional[str] = field(default=None) satisfies_pzs: Optional[bool] = field(default=None) scheduled_maintenance: Optional[GcpSqlScheduledMaintenance] = field(default=None) secondary_gce_zone: Optional[str] = field(default=None) server_ca_cert: Optional[GcpSqlSslCert] = field(default=None) service_account_email_address: Optional[str] = field(default=None) settings: Optional[GcpSqlSettings] = field(default=None) sql_database_instance_state: Optional[str] = field(default=None) suspension_reason: Optional[List[str]] = field(default=None) def connect_in_graph(self, builder: GraphBuilder, source: Json) -> None: if cert := self.server_ca_cert: if cert.self_link: builder.add_edge(self, reverse=True, clazz=GcpSslCertificate, link=cert.self_link) def post_process(self, graph_builder: GraphBuilder, source: Json) -> None: classes: List[Type[GcpResource]] = [GcpSqlBackupRun, GcpSqlDatabase, GcpSqlUser, GcpSqlOperation] for cls in classes: if spec := cls.api_spec: def collect_sql_resources(spec: GcpApiSpec, clazz: Type[GcpResource]) -> None: items = graph_builder.client.list(spec, instance=self.name, project=self.project) clazz.collect(items, graph_builder) graph_builder.submit_work(collect_sql_resources, spec, cls) @classmethod def called_collect_apis(cls) -> List[GcpApiSpec]: return [ cls.api_spec, GcpSqlBackupRun.api_spec, GcpSqlDatabase.api_spec, GcpSqlUser.api_spec, GcpSqlOperation.api_spec, ] @define(eq=False, slots=False) class GcpSqlCsvexportoptions: kind: ClassVar[str] = "gcp_sql_csvexportoptions" kind_display: ClassVar[str] = "GCP SQL CSV Export Options" kind_description: ClassVar[str] = ( "CSV Export Options for Google Cloud Platform's SQL allows users to export" " SQL query results into CSV format for further analysis or data manipulation." ) mapping: ClassVar[Dict[str, Bender]] = { "escape_character": S("escapeCharacter"), "fields_terminated_by": S("fieldsTerminatedBy"), "lines_terminated_by": S("linesTerminatedBy"), "quote_character": S("quoteCharacter"), "select_query": S("selectQuery"), } escape_character: Optional[str] = field(default=None) fields_terminated_by: Optional[str] = field(default=None) lines_terminated_by: Optional[str] = field(default=None) quote_character: Optional[str] = field(default=None) select_query: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlMysqlexportoptions: kind: ClassVar[str] = "gcp_sql_mysqlexportoptions" kind_display: ClassVar[str] = "GCP SQL MySQL Export Options" kind_description: ClassVar[str] = ( "GCP SQL MySQL Export Options are features provided by Google Cloud Platform" " that allow users to export data from MySQL databases hosted on GCP SQL." ) mapping: ClassVar[Dict[str, Bender]] = {"master_data": S("masterData")} master_data: Optional[int] = field(default=None) @define(eq=False, slots=False) class GcpSqlSqlexportoptions: kind: ClassVar[str] = "gcp_sql_sqlexportoptions" kind_display: ClassVar[str] = "GCP SQL SQLExportOptions" kind_description: ClassVar[str] = ( "GCP SQL SQLExportOptions is a set of configurations for exporting data from a SQL database instance," " including options for MySQL specific exports, schema-only exports, and selecting specific tables to export." ) mapping: ClassVar[Dict[str, Bender]] = { "mysql_export_options": S("mysqlExportOptions", default={}) >> Bend(GcpSqlMysqlexportoptions.mapping), "schema_only": S("schemaOnly"), "tables": S("tables", default=[]), } mysql_export_options: Optional[GcpSqlMysqlexportoptions] = field(default=None) schema_only: Optional[bool] = field(default=None) tables: Optional[List[str]] = field(default=None) @define(eq=False, slots=False) class GcpSqlExportContext: kind: ClassVar[str] = "gcp_sql_export_context" kind_display: ClassVar[str] = "GCP SQL Export Context" kind_description: ClassVar[str] = ( "GCP SQL Export Context defines the parameters and settings for exporting data from a SQL database instance" " in GCP, including the data format, destination URI, database selection, and whether the operation should" " be offloaded to avoid impacting database performance." ) mapping: ClassVar[Dict[str, Bender]] = { "csv_export_options": S("csvExportOptions", default={}) >> Bend(GcpSqlCsvexportoptions.mapping), "databases": S("databases", default=[]), "file_type": S("fileType"), "offload": S("offload"), "sql_export_options": S("sqlExportOptions", default={}) >> Bend(GcpSqlSqlexportoptions.mapping), "uri": S("uri"), } csv_export_options: Optional[GcpSqlCsvexportoptions] = field(default=None) databases: Optional[List[str]] = field(default=None) file_type: Optional[str] = field(default=None) offload: Optional[bool] = field(default=None) sql_export_options: Optional[GcpSqlSqlexportoptions] = field(default=None) uri: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlEncryptionoptions: kind: ClassVar[str] = "gcp_sql_encryptionoptions" kind_display: ClassVar[str] = "GCP SQL Encryption Options" kind_description: ClassVar[str] = ( "GCP SQL Encryption Options refers to the various methods available for" " encrypting data in Google Cloud Platform's SQL databases, such as Cloud SQL" " and SQL Server on GCE." ) mapping: ClassVar[Dict[str, Bender]] = { "cert_path": S("certPath"), "pvk_password": S("pvkPassword"), "pvk_path": S("pvkPath"), } cert_path: Optional[str] = field(default=None) pvk_password: Optional[str] = field(default=None) pvk_path: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlBakimportoptions: kind: ClassVar[str] = "gcp_sql_bakimportoptions" kind_display: ClassVar[str] = "GCP SQL Backup Import Options" kind_description: ClassVar[str] = ( "GCP SQL Backup Import Options provide configuration settings and options for" " importing backed up data into Google Cloud Platform SQL databases." ) mapping: ClassVar[Dict[str, Bender]] = { "encryption_options": S("encryptionOptions", default={}) >> Bend(GcpSqlEncryptionoptions.mapping) } encryption_options: Optional[GcpSqlEncryptionoptions] = field(default=None) @define(eq=False, slots=False) class GcpSqlCsvimportoptions: kind: ClassVar[str] = "gcp_sql_csvimportoptions" kind_display: ClassVar[str] = "GCP SQL CSV Import Options" kind_description: ClassVar[str] = ( "CSV Import Options in GCP SQL enables users to efficiently import CSV data into Google Cloud SQL databases." ) mapping: ClassVar[Dict[str, Bender]] = { "columns": S("columns", default=[]), "escape_character": S("escapeCharacter"), "fields_terminated_by": S("fieldsTerminatedBy"), "lines_terminated_by": S("linesTerminatedBy"), "quote_character": S("quoteCharacter"), "table": S("table"), } columns: Optional[List[str]] = field(default=None) escape_character: Optional[str] = field(default=None) fields_terminated_by: Optional[str] = field(default=None) lines_terminated_by: Optional[str] = field(default=None) quote_character: Optional[str] = field(default=None) table: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlImportContext: kind: ClassVar[str] = "gcp_sql_import_context" kind_display: ClassVar[str] = "GCP SQL Import Context" kind_description: ClassVar[str] = ( "GCP SQL Import Context defines the settings for importing data into a Cloud SQL database," " including file type and source URI." ) mapping: ClassVar[Dict[str, Bender]] = { "bak_import_options": S("bakImportOptions", default={}) >> Bend(GcpSqlBakimportoptions.mapping), "csv_import_options": S("csvImportOptions", default={}) >> Bend(GcpSqlCsvimportoptions.mapping), "database": S("database"), "file_type": S("fileType"), "import_user": S("importUser"), "uri": S("uri"), } bak_import_options: Optional[GcpSqlBakimportoptions] = field(default=None) csv_import_options: Optional[GcpSqlCsvimportoptions] = field(default=None) database: Optional[str] = field(default=None) file_type: Optional[str] = field(default=None) import_user: Optional[str] = field(default=None) uri: Optional[str] = field(default=None) @define(eq=False, slots=False) class GcpSqlOperation(GcpResource): kind: ClassVar[str] = "gcp_sql_operation" kind_display: ClassVar[str] = "GCP SQL Operation" kind_description: ClassVar[str] = ( "The GCP SQL Operation is a representation of an administrative operation performed on a GCP SQL Database" " instance, such as backups, imports, and exports, including details about execution times, status, and any" " errors encountered." ) reference_kinds: ClassVar[ModelReference] = {"predecessors": {"default": ["gcp_sql_database_instance"]}} api_spec: ClassVar[GcpApiSpec] = GcpApiSpec( service="sqladmin", version="v1", accessors=["operations"], action="list", request_parameter={"instance": "{instance}", "project": "{project}"}, request_parameter_in={"project"}, response_path="items", response_regional_sub_path=None, required_iam_permissions=["cloudsql.instances.get"], mutate_iam_permissions=["cloudsql.instances.update", "cloudsql.instances.delete"], ) mapping: ClassVar[Dict[str, Bender]] = { "id": S("name").or_else(S("id")).or_else(S("selfLink")), "tags": S("labels", default={}), "name": S("name"), "ctime": S("creationTimestamp"), "description": S("description"), "link": S("selfLink"), "label_fingerprint": S("labelFingerprint"), "deprecation_status": S("deprecated", default={}) >> Bend(GcpDeprecationStatus.mapping), "backup_context": S("backupContext", "backupId"), "end_time": S("endTime"), "sql_operation_errors": S("error", "errors", default=[]) >> ForallBend(GcpSqlOperationError.mapping), "export_context": S("exportContext", default={}) >> Bend(GcpSqlExportContext.mapping), "import_context": S("importContext", default={}) >> Bend(GcpSqlImportContext.mapping), "insert_time": S("insertTime"), "operation_type": S("operationType"), "start_time": S("startTime"), "status": S("status"), "target_id": S("targetId"), "target_link": S("targetLink"), "target_project": S("targetProject"), "user": S("user"), } backup_context: Optional[str] = field(default=None) end_time: Optional[datetime] = field(default=None) sql_operation_errors: List[GcpSqlOperationError] = field(factory=list) export_context: Optional[GcpSqlExportContext] = field(default=None) import_context: Optional[GcpSqlImportContext] = field(default=None) insert_time: Optional[datetime] = field(default=None) operation_type: Optional[str] = field(default=None) start_time: Optional[datetime] = field(default=None) status: Optional[str] = field(default=None) target_id: Optional[str] = field(default=None) target_link: Optional[str] = field(default=None) target_project: Optional[str] = field(default=None) user: Optional[str] = field(default=None) def connect_in_graph(self, builder: GraphBuilder, source: Json) -> None: if self.target_id: builder.add_edge(self, reverse=True, clazz=GcpSqlDatabaseInstance, name=self.target_id) @define(eq=False, slots=False) class GcpSqlPasswordStatus: kind: ClassVar[str] = "gcp_sql_password_status" kind_display: ClassVar[str] = "GCP SQL Password Status" kind_description: ClassVar[str] = ( "GCP SQL Password Status refers to the current state of the password used for" " SQL database access in Google Cloud Platform. It indicates whether the" " password is active or inactive." ) mapping: ClassVar[Dict[str, Bender]] = { "locked": S("locked"), "password_expiration_time": S("passwordExpirationTime"), } locked: Optional[bool] = field(default=None) password_expiration_time: Optional[datetime] = field(default=None) @define(eq=False, slots=False) class GcpSqlUserPasswordValidationPolicy: kind: ClassVar[str] = "gcp_sql_user_password_validation_policy" kind_display: ClassVar[str] = "GCP SQL User Password Validation Policy" kind_description: ClassVar[str] = ( "GCP SQL User Password Validation Policy is a feature in Google Cloud" " Platform's SQL service that enforces specific rules and requirements for" " creating and managing user passwords in SQL databases." ) mapping: ClassVar[Dict[str, Bender]] = { "allowed_failed_attempts": S("allowedFailedAttempts"), "enable_failed_attempts_check": S("enableFailedAttemptsCheck"), "enable_password_verification": S("enablePasswordVerification"), "password_expiration_duration": S("passwordExpirationDuration"), "status": S("status", default={}) >> Bend(GcpSqlPasswordStatus.mapping), } allowed_failed_attempts: Optional[int] = field(default=None) enable_failed_attempts_check: Optional[bool] = field(default=None) enable_password_verification: Optional[bool] = field(default=None) password_expiration_duration: Optional[str] = field(default=None) status: Optional[GcpSqlPasswordStatus] = field(default=None) @define(eq=False, slots=False) class GcpSqlSqlServerUserDetails: kind: ClassVar[str] = "gcp_sql_sql_server_user_details" kind_display: ClassVar[str] = "GCP SQL SQL Server User Details" kind_description: ClassVar[str] = ( "GCP SQL SQL Server User Details provides information about the users and" " their access privileges in a SQL Server instance on Google Cloud Platform." ) mapping: ClassVar[Dict[str, Bender]] = {"disabled": S("disabled"), "server_roles": S("serverRoles", default=[])} disabled: Optional[bool] = field(default=None) server_roles: Optional[List[str]] = field(default=None) @define(eq=False, slots=False) class GcpSqlUser(GcpResource): # collected via GcpSqlDatabaseInstance kind: ClassVar[str] = "gcp_sql_user" kind_display: ClassVar[str] = "GCP SQL User" kind_description: ClassVar[str] = ( "A GCP SQL User refers to a user account that can access and manage databases" " in Google Cloud SQL, a fully-managed relational database service." ) api_spec: ClassVar[GcpApiSpec] = GcpApiSpec( service="sqladmin", version="v1", accessors=["users"], action="list", request_parameter={"instance": "{instance}", "project": "{project}"}, request_parameter_in={"instance", "project"}, response_path="items", response_regional_sub_path=None, required_iam_permissions=["cloudsql.users.list"], mutate_iam_permissions=["cloudsql.users.update", "cloudsql.users.delete"], ) reference_kinds: ClassVar[ModelReference] = {"predecessors": {"default": ["gcp_sql_database_instance"]}} mapping: ClassVar[Dict[str, Bender]] = { "id": S("name").or_else(K("(anonymous)@") + S("host", default="localhost")), "tags": S("labels", default={}), "name": S("name", default="(anonymous)"), "ctime": S("creationTimestamp"), "description": S("description"), "link": S("selfLink"), "label_fingerprint": S("labelFingerprint"), "deprecation_status": S("deprecated", default={}) >> Bend(GcpDeprecationStatus.mapping), "dual_password_type": S("dualPasswordType"), "etag": S("etag"), "host": S("host", default="localhost"), "instance": S("instance"), "password": S("password"), "password_policy": S("passwordPolicy", default={}) >> Bend(GcpSqlUserPasswordValidationPolicy.mapping), "project": S("project"), "sqlserver_user_details": S("sqlserverUserDetails", default={}) >> Bend(GcpSqlSqlServerUserDetails.mapping), "type": S("type"), } dual_password_type: Optional[str] = field(default=None) etag: Optional[str] = field(default=None) host: Optional[str] = field(default=None) instance: Optional[str] = field(default=None) password: Optional[str] = field(default=None) password_policy: Optional[GcpSqlUserPasswordValidationPolicy] = field(default=None) project: Optional[str] = field(default=None) sqlserver_user_details: Optional[GcpSqlSqlServerUserDetails] = field(default=None) type: Optional[str] = field(default=None) def connect_in_graph(self, builder: GraphBuilder, source: Json) -> None: if self.instance: builder.add_edge(self, reverse=True, clazz=GcpSqlDatabaseInstance) resources: List[Type[GcpResource]] = [GcpSqlDatabaseInstance]
<template> <main class="search-bar"> <div class="input-container"> <input class="input" :class="{ 'search-active': isActive }" type="text" v-model="search" placeholder="Search..." /> <button @click="closeSearchBar" class="close-search-btn body-small" v-show="showCloseBtn()" > x </button> </div> <div @click="closeSearchBar" class="search-results" v-if="search && filteredProducts.length > 0" > <router-link v-for="product in filteredProducts" :key="product.id" class="product-searched" :to="`/product-view/${product.id}`" > {{ product.name }} </router-link> </div> <div class="item-error" v-if="search && !filteredProducts.length"> No results found! </div> </main> </template> <script> export default { name: "SearchBar", data() { return { search: "", isActive: false, }; }, computed: { filteredProducts() { if (this.search !== "") { this.isActive = true; return this.$store.state.products.filter((item) => item.name.toLowerCase().includes(this.search.toLowerCase().trim()) ); } this.isActive = false; return []; }, }, methods: { closeSearchBar() { this.search = ""; this.$emit("hide-search-bar"); }, showCloseBtn() { return this.search.length > 0; }, }, }; </script> <style lang="scss" scoped> @import "../styles/base.scss"; @import "../styles/vars.scss"; @media only screen and (min-width: 0) { .search-bar { width: 100%; background-color: white; margin: 0 0 16px 0; border-radius: 5px; // justify-content: center; position: relative; background-color: $light-gray; } .input-container { display: flex; flex-direction: row; justify-content: space-between; align-items: center; width: 100%; } .close-search-btn { // border: 1px solid $dark-grey; // border-radius: 50%; border: none; background-color: transparent; color: $dark-grey; width: 18px; height: 18px; padding: 3px; // margin: 0 auto; text-align: center; display: flex; justify-content: center; align-items: center; margin-right: 10px; cursor: pointer; } .input { display: block; width: 100%; height: 32px; text-indent: 30px; overflow: hidden; background: url("../assets/Icon-search-grey.png") no-repeat 10px center; font-size: 14px; border: none; border-radius: 5px; outline: none; } // .search-active { // background: url("../assets/Icon-close-search.png") no-repeat 10px center; // } .item-error { font-size: 14px; color: $errors; padding: 10px 0 5px 10px; top: 30px; width: 100%; position: absolute; z-index: 1999; display: flex; flex-direction: column; text-align: left; width: 100%; background-color: $white; border-radius: 6px; border: 1px solid $light-gray; } .search-results { position: absolute; z-index: 1999; display: flex; flex-direction: column; justify-content: space-between; text-align: left; width: 100%; background-color: $white; border-radius: 6px; border: 1px solid $light-gray; } .product-searched { font-size: 14px; color: $white; padding: 10px 0 5px 10px; text-decoration: none; background-color: $white; color: black; &:hover { cursor: pointer; background-color: $light-gray; } } } @media only screen and (min-width: 768px) { .search-results { margin-top: 32px; } .item-error { font-size: 14px; color: $errors; padding: 10px 0 5px 10px; margin-left: 0; width: 100%; display: flex; justify-content: flex-start; align-items: flex-start; } } @media only screen and (min-width: 1024px) { .input, .item-error, .product-searched { font-size: 16px; } } </style>
package unsafe_test import ( "testing" "unsafe" ) func TestUnsafePointer(t *testing.T) { var a int var s string var f float64 t.Logf("a = %q, &a = %p", a, unsafe.Pointer(&a)) t.Logf("s = %q, &s = %p", s, unsafe.Pointer(&s)) t.Logf("f = %v, &f = %p", f, unsafe.Pointer(&f)) } func TestUnsafePointer2(t *testing.T) { var arr = []int{177, 123, 3, 221, 5, 1211} pointer := unsafe.Pointer(&arr[1]) t.Logf("pointer = %p\n", pointer) uPointer := uintptr(pointer) t.Logf("uPointer = %v\n", uPointer) uPointer += 8 t.Logf("uPointer + 8 = %v\n", uPointer) pointer = unsafe.Pointer(uPointer) t.Logf("uPointer => pointer = %p\n", pointer) intPointer := (*int)(pointer) t.Logf("intPointer = %v\n", *intPointer) } func TestUnsafePointer3(t *testing.T) { t.Log(unsafe.Sizeof("komeiji satori")) t.Log(unsafe.Sizeof("satori")) // len 返回的底层数组的长度,而不是字符串的长度 name := "琪露诺" t.Logf("len = %d\n", len(name)) t.Logf("[]byte(name) = %v\n", []byte(name)) // 转为 []rune 切片后,len 返回的是字符串的长度 t.Logf("len([]rune(name)) = %d\n", len([]rune(name))) s := "憨pi" t.Log([]byte(s)) t.Log([]rune(s)) s1 := []byte{230, 134, 168, 112, 105} t.Logf("s1 = %s\n", s1) s2 := []rune{25000, 112, 105} t.Logf("s2 = %v\n", string(s2)) } func TestUnsafePointer4(t *testing.T) { s := "abc" s1 := []byte(s) t.Logf("p1 = %p, p1 = %p\n", &s, unsafe.Pointer(&s)) t.Logf("p2 = %p\n", &s1) } func TestUnsafePointer5(t *testing.T) { s1 := []int8{1, 2, 3, 4} t.Logf("pointer of s1 = %p\n", &s1) s2 := *(*[]int16)(unsafe.Pointer(&s1)) t.Logf("bytes of s2 = %p\n", s2) } // 字符串和切片共享数组 func TestUnsafePointer6(t *testing.T) { s := "abc" slice := (*[]byte)(unsafe.Pointer(&s)) t.Logf("s = %p, slice = %p\n", &s, slice) t.Logf("s = %v, slice = %v\n", s, *slice) // 结果:cap of slice = 12433427 // 原因是字符串没有容量,转成切片时,容量丢失 t.Logf("cap of slice = %v\n", cap(*slice)) // 字符串转为切片 slice2 := stringToBytes(s) t.Logf("stringToBytes = %v\n", slice2) // 切片转为字符串 t.Logf("bytesToString = %v\n", bytesToString(*slice)) // 底层数组是否相同 slice1 := []byte{97, 98, 99} s2 := bytesToString(slice1) t.Logf("s2 = %v\n", s2) slice1[0] = 'A' t.Logf("s2 = %v\n", s2) } // 字符串转为切片 func stringToBytes(s string) []byte { return *(*[]byte)(unsafe.Pointer(&struct { string Cap int }{s, len(s)})) } // 切片转为字符串 func bytesToString(b []byte) string { return *(*string)(unsafe.Pointer(&b)) } // 新版 func StringToBytes(s string) []byte { return unsafe.Slice(unsafe.StringData(s), len(s)) } // 新版 func BytesToString(b []byte) string { return unsafe.String(&b[0], unsafe.IntegerType(len(b))) }
from django.test import TestCase from ...forms import EmergencySituationEnquiryForm class EmergencySituationFormTestCase(TestCase): def setUp(self): self.test_form_dict = { "full_name": "John Enquirytest", "company_name": "John Company", "company_post_code": "te51in", "email": "John.Enquirytest@test.com", "phone": "07786179011", "sectors": [ "advanced_engineering__ess_sector_l1", "chemicals__ess_sector_l1", "logistics__ess_sector_l1", ], "other": "", "question": "I have a question", } def test_valid_form_entry(self): form = EmergencySituationEnquiryForm(self.test_form_dict) assert form.is_valid() assert form.get_zendesk_data() == { "full_name": "John Enquirytest", "email": "John.Enquirytest@test.com", "phone": "07786179011", "company_name": "John Company", "company_post_code": "te51in", "sectors": "Advanced engineering, Chemicals, Logistics", "other_sector": "", "question": "I have a question", "on_behalf_of": "-", "company_type": "-", "company_type_category": "-", "how_did_you_hear_about_this_service": "-", } def test_valid_form_entry_other_sectors_used(self): self.test_form_dict["sectors"] = [] self.test_form_dict["other"] = "Magic Trick Sales" form = EmergencySituationEnquiryForm(self.test_form_dict) assert form.is_valid() assert form.get_zendesk_data() == { "full_name": "John Enquirytest", "email": "John.Enquirytest@test.com", "phone": "07786179011", "company_name": "John Company", "company_post_code": "te51in", "sectors": "", "other_sector": "Magic Trick Sales", "question": "I have a question", "on_behalf_of": "-", "company_type": "-", "company_type_category": "-", "how_did_you_hear_about_this_service": "-", } def test_valid_form_entry_other_sectors_used_with_sector_list(self): self.test_form_dict["other"] = "Magic Trick Sales" form = EmergencySituationEnquiryForm(self.test_form_dict) assert form.is_valid() assert form.get_zendesk_data() == { "full_name": "John Enquirytest", "email": "John.Enquirytest@test.com", "phone": "07786179011", "company_name": "John Company", "company_post_code": "te51in", "sectors": "Advanced engineering, Chemicals, Logistics", "other_sector": "Magic Trick Sales", "question": "I have a question", "on_behalf_of": "-", "company_type": "-", "company_type_category": "-", "how_did_you_hear_about_this_service": "-", } def test_invalid_form_missing_name(self): self.test_form_dict["full_name"] = "" form = EmergencySituationEnquiryForm(self.test_form_dict) assert not form.is_valid() assert form.errors == { "full_name": ["Enter your full name"], } def test_invalid_form_missing_email(self): self.test_form_dict["email"] = "" form = EmergencySituationEnquiryForm(self.test_form_dict) assert not form.is_valid() assert form.errors == { "email": ["Enter your email address"], } def test_invalid_form_missing_phone_number(self): self.test_form_dict["phone"] = "" form = EmergencySituationEnquiryForm(self.test_form_dict) assert not form.is_valid() assert form.errors == { "phone": ["Enter your telephone number"], } def test_invalid_form_phone_not_numbers(self): self.test_form_dict["phone"] = "077breakme" form = EmergencySituationEnquiryForm(self.test_form_dict) assert not form.is_valid() assert form.errors == { "phone": ["This value can only contain numbers"], } def test_invalid_form_missing_business_name(self): self.test_form_dict["company_name"] = "" form = EmergencySituationEnquiryForm(self.test_form_dict) assert not form.is_valid() assert form.errors == { "company_name": ["Enter the business name"], } def test_invalid_form_missing_postcode(self): self.test_form_dict["company_post_code"] = "" form = EmergencySituationEnquiryForm(self.test_form_dict) assert not form.is_valid() assert form.errors == { "company_post_code": ["Enter the business unit postcode"], } def test_invalid_form_invalid_postcode(self): self.test_form_dict["company_post_code"] = "fakepostcode" form = EmergencySituationEnquiryForm(self.test_form_dict) assert not form.is_valid() assert form.errors == { "company_post_code": ["Enter a valid postcode"], } def test_invalid_form_missing_sectors_and_other(self): self.test_form_dict["sectors"] = [] form = EmergencySituationEnquiryForm(self.test_form_dict) assert not form.is_valid() assert form.errors == { "sectors": [ "Select the industry or business area(s) your enquiry relates to" ], } def test_invalid_form_missing_question(self): self.test_form_dict["question"] = "" form = EmergencySituationEnquiryForm(self.test_form_dict) assert not form.is_valid() assert form.errors == { "question": ["Enter your enquiry"], }
from django.contrib.auth import get_user_model from rest_framework import serializers from .models import UserSettings User = get_user_model() class UserSettingsSerializer(serializers.ModelSerializer): """ Serializer for UserSetting model to convert it to JSON representation """ # related field when read_only then ti is excluded from serialized output # and this error occurs: # AttributeError: 'collections.OrderedDict' object has no attribute 'user' user = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: """ Metadata class for UserSettingSerializer Defines the model and fields to be serialized """ model = UserSettings fields = [ "user", "start_week_day", "morning_check_in", "evening_check_in", ] read_only_fields = ( "id", "created_on", "updated_on", ) class CustomUserSerializer(serializers.ModelSerializer): """ CustomUserSerializer is a ModelSerializer that converts CustomUser model to JSON representation and vice versa """ user_settings = UserSettingsSerializer(required=False) class Meta: """ Metadata class for CustomUserSerializer Defines the model and fields to be serialized """ model = User fields = [ "id", "email", "first_name", "last_name", "is_staff", "is_active", "is_superuser", "user_settings", ] extra_kwargs = { "first_name": {"required": True}, "last_name": {"required": True}, }
import Card from "assets/components/Card"; import Loading from "assets/components/Loading"; import { loadingURL } from "assets/functions/loadingURL"; import FieldInput from "pages/Home/FieldInpunt"; import { useEffect, useState } from "react"; import Filter from "./Filter"; import styles from "./Home.module.scss"; const Home = () => { const [countries, setCountries] = useState<any[]>([]); const [country, setCountry] = useState<string>(""); const [ordination, setOrdination] = useState(""); useEffect(() => { loadingURL("https://restcountries.com/v3.1/all", setCountries); }, [ordination]) function testSearch(title: string) { const regex = new RegExp(country, "i"); return regex.test(title); } function newFilteredList() { if (country.length > 0) { return (countries.filter(country => testSearch(country.name.common))); } if (ordination !== "") { return countries.filter(filter => filter.region == ordination) } const randomOrder = countries.sort(() => Math.random() > .5 ? 1 : -1); const spliceCountry = randomOrder.slice(0, 12); return spliceCountry } return ( <main className={styles.container}> <section className={styles.section}> <div className={styles.group}> <FieldInput type="search" placeholder="Search for a country..." value={country} onChange={setCountry} /> <Filter ordination={ordination} setOrdination={setOrdination} /> </div> <div className={styles.wrapper}> {newFilteredList().length > 0 ? newFilteredList()?.map(country => ( <Card key={country.name.common} country={country} /> )) : <Loading /> } </div> </section> </main> ); }; export default Home;
import User, { Medication } from "../repositories/models/user"; import { AddMedicationRequestBody, UpdateMedicationDetailsRequestBody, } from "../routes/models/requests/requestBodies"; export const getMedicationList = async (id: string): Promise<Medication[]> => { try { const user = await User.findById(id); return user.getMedicationList(); } catch (error: any) { throw new Error(`Error in getMedicationList: ${error}`); } }; export const updateMedicationDetails = async ( id: string, requestBody: UpdateMedicationDetailsRequestBody ): Promise<boolean> => { try { const { originalMedicationName, editedMedicationName, editedDosage, editedTime, } = requestBody; const user = await User.findById(id); const medicationDetailsUpdated = user.updateMedicationDetails( originalMedicationName, editedMedicationName, editedDosage, editedTime ); return medicationDetailsUpdated; } catch (error: any) { throw new Error(`Error in updateMedicationDetails: ${error}`); } }; export const addMedication = async ( requestBody: AddMedicationRequestBody, id: string ): Promise<string> => { const medication: Medication = { medicationName: requestBody.medicationName, dosage: requestBody.dosage, time: requestBody.time, }; const medicationName = medication.medicationName; try { const user = await User.findById(id); if (user.medicationExists(medicationName)) { throw new Error( `Medication ${medicationName} exists in user medicationList` ); } const currentMedicationList = user.getMedicationList(); currentMedicationList.push(medication); await user.save(); return `Updated user ${id} medication list`; } catch (error: any) { throw new Error(`Error in addMedication: ${error}`); } };
#ifndef BOARD_H #define BOARD_H #include <iostream> #include <string> #include <vector> const int BOARD_SIZE = 8; const int TOTAL_SIZE = 64; class Board; class Position; class GameEngine; namespace printColor { const std::string RESET_COLOR = {"\033[0m"}; const std::string RED = {"\033[31;1m"}; const std::string GREEN = {"\033[32;1m"}; const std::string YELLOW = {"\033[33m"}; const std::string UNDER_YELLOW = {"\033[33;4m"}; const std::string BLUE = {"\033[34;1m"}; } enum class ContentType { EMPTY, WHITE, BLACK }; class Position { private: int x = -1, y = -1; ContentType type_; void update(ContentType); ContentType getType() const; char getChar() const; public: Position() = default; Position(int x, int y, ContentType ctty); Position(const Position &) = default; int getX() const; int getY() const; bool operator==(const Position &) const; bool operator!=(const Position &) const; friend std::ostream &operator<<(std::ostream &, const Position &); friend Board; friend GameEngine; }; class Board { private: int blackCount_ = 0; int whiteCount_ = 0; Position pos_[BOARD_SIZE][BOARD_SIZE]; public: Board(); Board(const Board &) = default; void getNumberColor(int &white, int &black) const; void update(const Position &); ContentType getType(const Position &) const; char getChar(const Position &) const; static char getChar(ContentType); friend GameEngine; }; #endif
import React from 'react'; import { useAppDispatch } from '../../../../Redux/app.hook/app.hook'; import { Link, useNavigate } from 'react-router-dom'; import { Button, Checkbox, Col, Form, Input, Row, message, Image } from 'antd'; // import './LoginClient.css'; import { loginClientActions } from '../../../../Redux/Actions/Actions.auth'; import { useSelector } from 'react-redux'; import { reduxIterface } from '../LoginClient/Login.Interface'; import { sendMailChangePassord, signUp } from '../../../utils/Api/Api'; import images from '../../../../asset'; import { signUpInterface } from '../../../utils/Api/ApiInterFace'; export default function RegisterClient() { const isLoading = useSelector((state: reduxIterface) => state.reduxAuth.isLoading); console.log(isLoading); const dispatch = useAppDispatch(); const navigate = useNavigate(); const onFinish = async (values: any) => { console.log('Success:', values); const dataLogin = { email: values.email, password: values.password, }; dispatch(loginClientActions(values, navigate)); }; const onFinishFailed = (errorInfo: any) => { console.log('Failed:', errorInfo); }; const handleSignUp = async (value: signUpInterface): Promise<void> => { const response = await signUp(value); console.log(response); if (response && response.status == 201) { message.success('tạo tài khoản thành công !!'); setTimeout(() => { navigate('/signIn'); }, 1000); } else { message.error(response?.data?.message); } }; return ( <div className="LoginClient"> <Form name="basic" labelCol={{ span: 24 }} wrapperCol={{ span: 24 }} style={{ maxWidth: 600 }} initialValues={{ remember: true }} onFinish={(value) => { handleSignUp(value); }} onFinishFailed={onFinishFailed} autoComplete="off" className="LoginClientForm" > <div className="LoginClient__logo"> <Image src={images.logo} preview={false} width={120} /> </div> <div className="LoginClient__title"> <h3>ĐĂNG KÝ</h3> </div> <Form.Item label="Họ và tên đệm" name="firstName" rules={[{ required: true, message: 'Vui lòng điền đầy đủ thông tin!' }]} > <Input className="inputLoginCss" placeholder="Nhập họ của bạn" /> </Form.Item> <Form.Item label="Tên" name="lastName" rules={[{ required: true, message: 'Vui lòng điền đầy đủ thông tin!' }]} > <Input className="inputLoginCss" placeholder="Nhập tên của bạn" /> </Form.Item> <Form.Item label="Giới tính" name="genderId" rules={[{ required: true, message: 'Vui lòng điền đầy đủ thông tin!' }]} > <Input className="inputLoginCss" placeholder="Giới tính của bạn" /> </Form.Item> <Form.Item label="Số điện thoại" name="phoneNumber" rules={[{ required: true, message: 'Vui lòng điền đầy đủ thông tin!' }]} > <Input className="inputLoginCss" placeholder="Nhập số điện thoại" /> </Form.Item> <Form.Item label="Email" name="email" rules={[{ required: true, message: 'Vui lòng điền đầy đủ thông tin!' }]} > <Input className="inputLoginCss" placeholder="Nhập Email" /> </Form.Item> <Form.Item label="Mật khẩu" name="password" rules={[{ required: true, message: 'Vui lòng điền đầy đủ thông tin!' }]} > <Input.Password className="inputLoginCss" placeholder="Nhập mật khẩu" /> </Form.Item> <Form.Item wrapperCol={{ offset: 0, span: 24 }}> <Button type="primary" htmlType="submit" className="btnLoginClient"> Đăng ký </Button> </Form.Item> </Form> </div> ); }
class ArmstrongNumbers { // check a number to see whether it is an armstrong (aka narcissistic) number bool isArmstrongNumber(String noom){ // track the total BigInt total = BigInt.from(0); // separate the number into digit lists List<String> digits = noom.split(''); // for loop that parses each string digit into a number for (final String digit in digits){ // raise each digit to the power equal to the number of digits total += BigInt.parse(digit).pow(noom.length); } // compare the computed total to the original number return total.toString() == noom; } }
const mongoose = require('mongoose') const validator = require('validator'); const userSchema = new mongoose.Schema({ email_address: { type: String, required: [true, 'Email is Required'], unique: true, // to check if the given mail id already exists in database or not validate: [validator.isEmail, 'Please Enter valid email'] }, first_name: { type: String, required: [true, 'First Name is Required'], }, last_name: { type: String, }, contact: { type: String, }, password: { type: String, required: [true, 'Password is Required'], minlength: [8, 'Password should be grater than 8 charcters'] }, role: { type: String, default: "user" }, // isLoggedIn: { // type: Boolean, // required: true // }, uuid: { type: String }, accesstoken: { type: String }, coupens: { type: Array }, bookingRequests: { type : Array } }); module.exports = mongoose.model('User', userSchema);
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Set_worker_from_csv extends CI_Model { public $variable; public function __construct() { parent::__construct(); } /** * CSVファイルより営業マンのログイン情報を読み込みます。 * * あらかじめ所定の位置に配置したCSVファイルより * 営業マンの所属情報、社員番号、氏名、メルアドを取得。 * パスワードをここで生成し、暗号化してテーブルに保持します。 * */ public function execute($csv_file_name) { if(file_exists($csv_file_name)){ // echo exec('more '. $csv_file_name); $file = new SplFileObject($csv_file_name); $file->setFlags(SplFileObject::READ_CSV); $districts = array(); $records = array(); $password_hash = $this->config->item('password_hash'); $password_iv = $this->config->item('password_iv'); $password_options = $this->config->item('password_options'); $password_method = $this->config->item('password_method'); foreach ($file as $line) { //終端の空行を除く処理 空行の場合に取れる値は後述 if(!is_null($line[0]) && strlen($line[0]) == 1){ // 0, 事業部番号(AF事業部=0、CRM事業部=1), // 1, 事業部名称, // 2, Region番号(東日本=0、西日本=1、FCEグループ=2), // 3, Region名称, // 4, District番号, // 5, District名称, // 6, NavXレポート(非対称=0、対象=1), // 7, 担当者番号(社員番号), // 8, 担当者氏名(山田太郎)*スペースなしで記載, // 9, 担当者所属(Sales=0, FCE=1), // 10, 担当者メールアドレス // region_id が null なデータが入るようになったので9でも入れておく if (is_null($line[2]) || $line[2] == '') { $line[2] = 9; } if(!isset($districts[$line[4]]) && $line[5] != ''){ $districts[$line[4]] = array( 'district_id' => $line[4], 'name' => $line[5], 'division_id' => $line[0], 'region_id' => $line[2], ); } $role_code = 0; if($line[0] == 0){ // AF division if($line[9] == 0){ // sales $role_code = 0; }else{ //fce $role_code = 1; } // fce manager if($line[4] == ''){ $role_code = 6; } }else if($line[0] == 1){ // CRM division if($line[9] == 0){ // sales $role_code = 2; }else{ //fce $role_code = 3; } // crm manager if($line[4] == ''){ $role_code = 5; } } if($line[7] == $this->config->item('crm_nsd_id')){ $role_code = 4; } if(in_array($line[7], $this->config->item('fce_manager_id'))){ $role_code = 6; } $records[$line[7]] = array( 'division_id' => $line[0], 'region_id' => $line[2], 'district_id' => $line[4], 'role_code' => $role_code, 'employee_number' => $line[7], 'name' => $line[8], 'mailaddress' => strtolower($line[10]), ); } } echo count($records)." lines\n"; //workerを登録します foreach ($records as $key => $value) { $this->db->select('id'); $this->db->select('password'); $this->db->where('employee_number', $key); $this->db->from('accounts'); $query = $this->db->get(); $is_exist = $query->num_rows(); $this->db->set('region_id', $value['region_id']); $this->db->set('district_id', $value['district_id']); $this->db->set('role_code', $value['role_code']); $this->db->set('name', $value['name']); $this->db->set('mailaddress', $value['mailaddress']); $this->db->set('active', 1); if (!$is_exist) { $this->db->set('employee_number', $value['employee_number']); $length = 8; $password = substr(str_shuffle('1234567890abcdefghijklmnopqrstuvwxyz'), 0, $length); $encrypt_password = openssl_encrypt($password, $password_method, $password_hash, $password_options, $password_iv); $encrypt_password = str_replace(array('+', '/', '='), array('_', '-', '.'), $encrypt_password); $encrypt_password = urlencode($encrypt_password); $this->db->set('password', $encrypt_password); $this->db->from('accounts'); $this->db->insert(); $records[$key]['password'] = $password; }else{ $encrypt_password = $query->row_array()['password']; $encrypt_password = urldecode($encrypt_password); $encrypt_password = str_replace(array('_','-', '.'), array('+', '/', '='), $encrypt_password); $password = openssl_decrypt($encrypt_password, $password_method, $password_hash, $password_options, $password_iv); $this->db->where('employee_number', $value['employee_number']); $this->db->from('accounts'); $this->db->update(); $records[$key]['password'] = $password; } } $accounts_csv_file_name = FCPATH.'csv/worker_accounts_'.date('Ymd').'.csv'; $file_handler = fopen($accounts_csv_file_name, 'w'); foreach ($records as $key => $value) { fputcsv($file_handler, $value); } fclose($file_handler); $districts_csv_file_name = FCPATH.'csv/districts_'.date('Ymd').'.csv'; $file_handler = fopen($districts_csv_file_name, 'w'); foreach ($districts as $key => $value) { fputcsv($file_handler, $value); } fclose($file_handler); echo 'アカウントCSVファイル : '.$accounts_csv_file_name . "\n"; echo 'ディストリクト一覧CSVファイル : '.$districts_csv_file_name . "\n"; } } public function getpwd($data) { $password_hash = $this->config->item('password_hash'); $password_iv = $this->config->item('password_iv'); $password_options = $this->config->item('password_options'); $password_method = $this->config->item('password_method'); $this->db->select('password'); $this->db->from('accounts'); $this->db->where('employee_number', $data); $query = $this->db->get(); $result = $query->result(); if(count($result) == 0) { return "no"; } $encrypt_password = $result[0]->password; $encrypt_password = urldecode($encrypt_password); $encrypt_password = str_replace(array('_','-', '.'), array('+', '/', '='), $encrypt_password); $password = openssl_decrypt($encrypt_password, $password_method, $password_hash, $password_options, $password_iv); if($password == false) return $encrypt_password; return $password; } } /* End of file set_worker_from_csv.php */ /* Location: ./application/models/set_worker_from_csv.php */
import { useEffect, useRef } from "react"; import "./App.css"; import { AboutMe, ContactMe, NavigationBar, Projects, Skills, Summary, } from "./components"; const App = () => { const summaryRef = useRef(); const skillRef = useRef(); const aboutMeRef = useRef(); const projectsRef = useRef(); const contactMeRef = useRef(); useEffect(() => { document.documentElement.style.setProperty( "--vh", window.innerHeight * 0.01 + "px" ); }, []); return ( <main> <NavigationBar summaryRef={summaryRef} skillRef={skillRef} aboutMeRef={aboutMeRef} projectsRef={projectsRef} contactMeRef={contactMeRef} /> <Summary summaryRef={summaryRef} ref={skillRef} /> <Skills skillRef={skillRef} ref={aboutMeRef} /> <AboutMe aboutMeRef={aboutMeRef} ref={projectsRef} /> <Projects projectsRef={projectsRef} ref={contactMeRef} /> <ContactMe contactMeRef={contactMeRef} ref={summaryRef} /> </main> ); }; export default App;
package com.majou.composelearning import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.majou.composelearning.ui.theme.ComposeLearningTheme class BasicLearningActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ComposeLearningTheme { // A surface container using the 'background' color from the theme BasicMainUI() } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun GreetingBasic( name: String, nameList: List<String>, inputValue: String, buttonClick: () -> Unit, inputChange: (value: String) -> Unit ) { Surface(color = Color.White, modifier = Modifier.fillMaxSize(1f)) { Surface( color = Color.DarkGray, modifier = Modifier.wrapContentSize(align = Alignment.BottomEnd) ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize(1f) ) { for (s in nameList) { listContentBasic(text = s) } TextField(value = inputValue, onValueChange = { newInput -> inputChange(newInput) }, modifier = Modifier.padding(10.dp)) Text(text = "Hello $name!", modifier = Modifier .clickable { } .padding(24.dp), style = TextStyle( color = Color.Blue, fontWeight = FontWeight.W500, fontSize = 24.sp )) Button(onClick = { buttonClick() }) { Text( text = "Click", modifier = Modifier.wrapContentWidth(align = Alignment.End), style = MaterialTheme.typography.headlineSmall ) } } } } } @Composable fun BasicMainUI(viewModel: MainViewModel = MainViewModel()) { Surface( modifier = Modifier.fillMaxSize(1f), color = Color.White ) { val greetingListState = remember { mutableStateListOf("Muhammed") } val newNameStateContent = viewModel.textFieldState.observeAsState("") GreetingBasic("Android", greetingListState, newNameStateContent.value, { greetingListState.add(newNameStateContent.value);viewModel.onTextChanged("") }) { string -> viewModel.onTextChanged(string) } } } @Composable fun listContentBasic(text: String) { Text(text = text, style = TextStyle(color = Color.White)) } @Preview(showBackground = true) @Composable fun GreetingBasicPreview() { BasicMainUI() }
updateProgramChanges <- function(input, output, session, values) { observe({ # ttt_to_update is a safe version of currentlySelectedTTT ttt_to_update <- ifelse( is.null(input$currentlySelectedTTT), 1, as.integer(input$currentlySelectedTTT) ) # Use ttt_to_update to get the specifications for the TTT scenario that is # currently being defined. n <- ttt_to_update tttn <- paste0("ttt", n) tttName <- paste0(tttn, "name") tttRisk <- paste0(tttn, "risk") tttAge <- paste0(tttn, "agegroups") tttNativity <- paste0(tttn, "nativity") tttNumberTargeted <- paste0(tttn, "numberTargeted") tttFractionScreened <- paste0(tttn, "numberScreened") tttStartYear <- paste0(tttn, "startyear") tttStopYear <- paste0(tttn, "stopyear") tttProgression <- paste0(tttn, "progression-rate") tttPrevalence <- paste0(tttn, "prevalence-rate") tttMortality <- paste0(tttn, "mortality-rate") # Fill the user-input into the `values` object. values[['scenarios']][['ttt']][[ttt_to_update]][['name']] = input[[tttName]] values[['scenarios']][['ttt']][[ttt_to_update]][['risk_group']] = input[[tttRisk]] values[['scenarios']][['ttt']][[ttt_to_update]][['nativity_group']] = input[[tttNativity]] values[['scenarios']][['ttt']][[ttt_to_update]][['age_group']] = input[[tttAge]] values[['scenarios']][['ttt']][[ttt_to_update]][['number_targeted']] = input[[tttNumberTargeted]] values[['scenarios']][['ttt']][[ttt_to_update]][['fraction_screened_annually']] = input[[tttFractionScreened]] values[['scenarios']][['ttt']][[ttt_to_update]][['start_year']] = input[[tttStartYear]] values[['scenarios']][['ttt']][[ttt_to_update]][['stop_year']] = input[[tttStopYear]] # program_changes_to_update is the safe version of # input$currentlySelectedProgramChange program_change_to_update <- if (is.null(input$currentlySelectedProgramChange)) 1 else as.integer(input$currentlySelectedProgramChange) # Use program_change_to_update to get the specification for the Program # Change scenario that is currently being defined. pcn <- paste0("programChange", program_change_to_update) programChangeName = paste0(pcn, 'Name') programChangeStartYear = paste0(pcn, 'StartYear') programChangeLtbi_screening_coverage_multiplier = paste0(pcn, "CoverageRate") programChangeFraction_receiving_igra = paste0(pcn, "IGRACoverage") programChangeFraction_accepting_ltbi_treatment = paste0(pcn, "AcceptingTreatmentFraction") programChangeFraction_completing_ltbi_treatment = paste0(pcn, "CompletionRate") programChangeAverage_time_to_treatment_active = paste0(pcn, "AverageTimeToTreatment") programChangeFraction_defaulting_from_treatment_active = paste0(pcn, "DefaultRate") # Fill the user-input into the `values` object. values[['scenarios']][['program_changes']][[program_change_to_update]] <- list( name = input[[programChangeName]], start_year = input[[programChangeStartYear]], ltbi_screening_coverage_multiplier = input[[programChangeLtbi_screening_coverage_multiplier]], fraction_receiving_igra = input[[programChangeFraction_receiving_igra]], fraction_accepting_ltbi_treatment = input[[programChangeFraction_accepting_ltbi_treatment]], fraction_completing_ltbi_treatment = input[[programChangeFraction_completing_ltbi_treatment]], average_time_to_treatment_active = input[[programChangeAverage_time_to_treatment_active]], fraction_defaulting_from_treatment_active = input[[programChangeFraction_defaulting_from_treatment_active]] ) }) values }
import { parseBytes32String } from "@ethersproject/strings"; import { Currency, Ether, NativeCurrency, Token } from "@uniswap/sdk-core"; import { arrayify } from "@ethersproject/bytes"; import { useMemo } from "react"; import { useAllLists, useCombinedActiveList, useInactiveListUrls, } from "../state/glists/hooks"; import { WrappedTokenInfo } from "../state/glists/wrappedTokenInfo"; import { NEVER_RELOAD, useSingleCallResult } from "../state/gmulticall/hooks"; import { useUserAddedTokens } from "../state/guser/hooks"; import { isAddress } from "../utils"; import { TokenAddressMap, useUnsupportedTokenList, } from "./../state/glists/hooks"; import { useBytes32TokenContract, useTokenContract } from "./useContract"; import invariant from "tiny-invariant"; import { Contract } from "@ethersproject/contracts"; import { TokenInfo } from "@uniswap/token-lists"; import { NATIVE } from "../constants/addresses"; import { useWeb3 } from "../web3"; import { WFTM_FANTOM } from "../constants/tokens.fantom"; import { WMATIC_MATIC } from "../constants/tokens.matic"; import { WBNB_BSC } from "../constants/tokens.bsc"; import { WAVAX_AVAX } from "../constants/tokens.avax"; export const WETH9: { [chainId: number]: Token } = { [1]: new Token( 1, "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", 18, "WETH9", "Wrapped Ether" ), [3]: new Token( 3, "0xc778417E063141139Fce010982780140Aa0cD5Ab", 18, "WETH9", "Wrapped Ether" ), [4]: new Token( 4, "0xc778417E063141139Fce010982780140Aa0cD5Ab", 18, "WETH9", "Wrapped Ether" ), [5]: new Token( 5, "0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6", 18, "WETH9", "Wrapped Ether" ), [42]: new Token( 42, "0xd0A1E359811322d97991E03f863a0C30C2cF029C", 18, "WETH9", "Wrapped Ether" ), }; export class NativeToken extends NativeCurrency { public constructor( chainId: number, decimals: number, symbol: string, name: string ) { super(chainId, decimals, symbol, name); } public get wrapped(): Token { const weth9 = this.chainId === 56 ? WBNB_BSC : this.chainId === 137 ? WMATIC_MATIC : this.chainId === 250 ? WFTM_FANTOM : this.chainId === 43114 ? WAVAX_AVAX : WETH9[this.chainId]; invariant(!!weth9, "WRAPPED"); return weth9; } public equals(other: Currency): boolean { return other.isNative && other.chainId === this.chainId; } } const alwaysTrue = () => true; /** * Create a filter function to apply to a token for whether it matches a particular search query * @param search the search query to apply to the token */ export function createTokenFilterFunction<T extends Token | TokenInfo>( search: string ): (tokens: T) => boolean { const searchingAddress = isAddress(search); if (searchingAddress) { const lower = searchingAddress.toLowerCase(); return (t: T) => "isToken" in t ? searchingAddress === t.address : lower === t.address.toLowerCase(); } const lowerSearchParts = search .toLowerCase() .split(/\s+/) .filter((s) => s.length > 0); if (lowerSearchParts.length === 0) return alwaysTrue; const matchesSearch = (s: string): boolean => { const sParts = s .toLowerCase() .split(/\s+/) .filter((s) => s.length > 0); return lowerSearchParts.every( (p) => p.length === 0 || sParts.some((sp) => sp.startsWith(p) || sp.endsWith(p)) ); }; return ({ name, symbol }: T): boolean => Boolean((symbol && matchesSearch(symbol)) || (name && matchesSearch(name))); } // reduce token map into standard address <-> Token mapping, optionally include user added tokens function useTokensFromMap( tokenMap: TokenAddressMap, includeUserAdded: boolean ): { [address: string]: Token } { const { chainId } = useWeb3(); const userAddedTokens = useUserAddedTokens(); return useMemo(() => { if (!chainId) return {}; if (!tokenMap[chainId]) return {}; // reduce to just tokens const mapWithoutUrls = Object.keys(tokenMap[chainId]).reduce<{ [address: string]: Token; }>((newMap, address) => { newMap[address] = tokenMap[chainId][address].token; return newMap; }, {}); if (includeUserAdded) { return ( userAddedTokens // reduce into all ALL_TOKENS filtered by the current chain .reduce<{ [address: string]: Token }>( (tokenMap, token) => { tokenMap[token.address] = token; return tokenMap; }, // must make a copy because reduce modifies the map, and we do not // want to make a copy in every iteration { ...mapWithoutUrls } ) ); } return mapWithoutUrls; }, [chainId, userAddedTokens, tokenMap, includeUserAdded]); } export function useAllTokens(): { [address: string]: Token } { const allTokens = useCombinedActiveList(); return useTokensFromMap(allTokens, true); } export function useUnsupportedTokens(): { [address: string]: Token } { const unsupportedTokensMap = useUnsupportedTokenList(); return useTokensFromMap(unsupportedTokensMap, false); } export function useSearchInactiveTokenLists( search: string | undefined, minResults = 10 ): WrappedTokenInfo[] { const { chainId } = useWeb3(); const lists = useAllLists(); const inactiveUrls = useInactiveListUrls(); const activeTokens = useAllTokens(); return useMemo(() => { if (!search || search.trim().length === 0) return []; const tokenFilter = createTokenFilterFunction(search); const result: WrappedTokenInfo[] = []; const addressSet: { [address: string]: true } = {}; for (const url of inactiveUrls) { const list = lists[url].current; if (!list) continue; for (const tokenInfo of list.tokens) { if (tokenInfo.chainId === chainId && tokenFilter(tokenInfo)) { const wrapped: WrappedTokenInfo = new WrappedTokenInfo( tokenInfo, list ); if ( !(wrapped.address in activeTokens) && !addressSet[wrapped.address] ) { addressSet[wrapped.address] = true; result.push(wrapped); if (result.length >= minResults) return result; } } } } return result; }, [activeTokens, chainId, inactiveUrls, lists, minResults, search]); } export function useIsTokenActive(token: Token | undefined | null): boolean { const activeTokens = useAllTokens(); if (!activeTokens || !token) { return false; } return !!activeTokens[token.address]; } // Check if currency is included in custom list from user storage export function useIsUserAddedToken( currency: Currency | undefined | null ): boolean { const userAddedTokens = useUserAddedTokens(); if (!currency) { return false; } return !!userAddedTokens.find((token) => currency.equals(token)); } // parse a name or symbol from a token response const BYTES32_REGEX = /^0x[a-fA-F0-9]{64}$/; function parseStringOrBytes32( str: string | undefined, bytes32: string | undefined, defaultValue: string ): string { return str && str.length > 0 ? str : // need to check for proper bytes string and valid terminator bytes32 && BYTES32_REGEX.test(bytes32) && arrayify(bytes32)[31] === 0 ? parseBytes32String(bytes32) : defaultValue; } // undefined if invalid or does not exist // null if loading // otherwise returns the token export function useToken(tokenAddress?: string): Token | undefined | null { const tokens = useAllTokens(); const { chainId } = useWeb3(); const address = isAddress(tokenAddress); const tokenContract = (useTokenContract( address ? address : undefined, false ) as unknown) as Contract; const tokenContractBytes32 = useBytes32TokenContract( address ? address : undefined, false ); const token: Token | undefined = address ? tokens[address] : undefined; const tokenName = useSingleCallResult( token ? undefined : tokenContract, "name", undefined, NEVER_RELOAD ); const tokenNameBytes32 = useSingleCallResult( token ? undefined : tokenContractBytes32, "name", undefined, NEVER_RELOAD ); const symbol = useSingleCallResult( token ? undefined : tokenContract, "symbol", undefined, NEVER_RELOAD ); const symbolBytes32 = useSingleCallResult( token ? undefined : tokenContractBytes32, "symbol", undefined, NEVER_RELOAD ); const decimals = useSingleCallResult( token ? undefined : tokenContract, "decimals", undefined, NEVER_RELOAD ); return useMemo(() => { if (token) return token; if (!chainId || !address) return undefined; if (decimals.loading || symbol.loading || tokenName.loading) return null; if (decimals.result) { return new Token( chainId, address, decimals.result[0], parseStringOrBytes32( symbol.result?.[0], symbolBytes32.result?.[0], "UNKNOWN" ), parseStringOrBytes32( tokenName.result?.[0], tokenNameBytes32.result?.[0], "Unknown Token" ) ); } return undefined; }, [ address, chainId, decimals.loading, decimals.result, symbol.loading, symbol.result, symbolBytes32.result, token, tokenName.loading, tokenName.result, tokenNameBytes32.result, ]); } export function useCurrency( currencyId: string | undefined ): Currency | null | undefined { const { chainId } = useWeb3(); const isETH = currencyId?.toUpperCase() === "ETH"; const isMATIC = currencyId?.toUpperCase() === "MATIC"; const isFTM = currencyId?.toUpperCase() === "FTM"; const isBNB = currencyId?.toUpperCase() === "BNB"; const isAVAX = currencyId?.toUpperCase() === "AVAX"; const isNative = currencyId?.toUpperCase() === "NATIVE" || currencyId?.toLowerCase() === NATIVE.toLowerCase(); const isNativeCurrency = isETH || isMATIC || isFTM || isBNB || isAVAX || isNative; const token = useToken(isNativeCurrency ? undefined : currencyId); if (isNativeCurrency && chainId) return chainId === 56 ? new NativeToken(chainId, 18, "BNB", "Binance Coin") : chainId === 137 ? new NativeToken(chainId, 18, "MATIC", "Matic") : chainId === 250 ? new NativeToken(chainId, 18, "FTM", "Fantom") : chainId === 43114 ? new NativeToken(chainId, 18, "AVAX", "Avax") : Ether.onChain(chainId); else return token; }
package Treex::PML::Backend::PMLTransform; use vars qw($VERSION); BEGIN { $VERSION='2.16'; # version template } use Treex::PML::Backend::PML qw(open_backend close_backend read write); sub test { local $Treex::PML::Backend::PML::TRANSFORM=1; return &Treex::PML::Backend::PML::test; } 1; =pod =head1 NAME Treex::PML::Backend::PMLTransform - I/O backend implementing on-the-fly XML to PML conversion =head1 SYNOPSIS use Treex::PML; Treex::PML::AddBackends(qw(PMLTransform)) my $document = Treex::PML::Factory->createDocumentFromFile('input.xml'); ... $document->save(); =head1 DESCRIPTION This module implements a Treex::PML input/output backend which accepts any XML file and attempts to convert it to PML using user-defined transformations (XSLT 1.0, Perl, or external command). See L<Treex::PML::Instance/"CONFIGURATION"> for details. WARNING: since this backend accepts every XML file, it should be added as the last backend (otherwise other backends working with XML will not be tried). =head2 BUGS If your system uses libxslt version 1.1.27, the XSLT transformation does not work. Upgrade your system. =head1 COPYRIGHT AND LICENSE Copyright (C) 2006-2010 by Petr Pajas This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.2 or, at your option, any later version of Perl 5 you may have available. =cut
import { React, useState } from 'react'; import { StyleSheet, Text, View, Dimensions, ScrollView, Image } from "react-native"; import { globalColors } from "../colors"; import {TouchableOpacity } from 'react-native-gesture-handler'; import { useNavigation } from '@react-navigation/native'; import BottomBar from '../components/BottomBar'; import { Feather, Ionicons, AntDesign, Entypo } from '@expo/vector-icons'; const { width } = Dimensions.get('screen'); export default function Chat() { const navigation = useNavigation(); const chatWithUser =({ image, firstName, lastName, lastMessage, dateAndTime, online, path, read, lastMessageSentBy}) => { const [isRead, setIsRead] = useState(read); const handleUser = () => { navigation.navigate('ChatOneVsOne', {image: image, firstName: firstName, lastName: lastName , online: online, lastMessage: lastMessage, dateAndTime: dateAndTime, path: path }); setIsRead(true); } const fullName = firstName + ' ' + lastName if (fullName.length > 26) { newFullName = (fullName).substring(0, 25) + '...'; } else { newFullName = firstName + ' ' + lastName } if (lastMessage.length > 76) { lastMessage = lastMessage.substring(0,70) + '...'; console.log(lastMessage) } return( <TouchableOpacity style={styles.chatbutton} onPress={handleUser}> <Image source={image} style={styles.image}/> <View style={styles.buttontext}> <View style={{flexDirection: 'row'}}> <Text style={{fontWeight: '500', fontSize: 15}} >{newFullName}</Text> {path==='true' ? <Entypo name="graduation-cap" size={24} color={globalColors.orange.title.colour} style={{marginLeft: 5}}/> : null} </View> <Text style={{ marginRight: 60, marginTop: 8, fontWeight: read === 'false' ? 'bold' : 'normal' }}>{lastMessageSentBy === 'me' ? 'You: ' : ''}{lastMessage}</Text> </View> <Text style={styles.datetime}>{dateAndTime}</Text> <AntDesign name="right" size={24} color={globalColors.grey.greyarrow.colour} style={styles.arrow}/> </TouchableOpacity> )}; return( <View style={styles.bigbox}> <TouchableOpacity onPress={() => navigation.goBack()} style={styles.backarrow}> <Ionicons name="arrow-back" size={24} colour={globalColors.maincolors.black.color}/> </TouchableOpacity> <View style={styles.titlebox}> <Text style={styles.titletext}>Chat</Text> </View> <View style={styles.settings}> <TouchableOpacity onPress={() => navigation.navigate('Settings')}> <Feather name="settings" size={24} colour={globalColors.maincolors.black.color}/> </TouchableOpacity> </View> <ScrollView alwaysBounceVertical={true} style={styles.scrollview} contentContainerStyle={styles.scrollviewcontent}> {chatWithUser({ image: require('../assets/stick_man.jpg'), firstName: 'Tom', lastName: 'Watkins', lastMessage: 'What happenned?', dateAndTime: 'just now', online: 'false', path: 'false', read: 'false', lastMessageSentBy: 'them' })} {chatWithUser({ image: require('../assets/computer1.jpg'), firstName: 'Computer', lastName: 'Science', lastMessage: 'Can you please provide me with more information?', dateAndTime: 'just now', online: 'true', path: 'true', read: 'true', lastMessageSentBy: 'them' })} {chatWithUser({ image: require('../assets/stick_man.jpg'), firstName: 'George', lastName: 'Loizou', lastMessage: 'I see, lets talk tomorrow then', dateAndTime: 'just now', online: 'true', path: 'false', read: 'true', lastMessageSentBy: 'me' })} {chatWithUser({ image: require('../assets/stick_man.jpg'), firstName: 'Chris', lastName: 'Antonio', lastMessage: 'Sure I agree with you!', dateAndTime: 'just now' })} {chatWithUser({ image: require('../assets/stick_man.jpg'), firstName: 'Michael', lastName: 'Rawat', lastMessage: 'Taking in to consideration the above, I think that the best solution for you is to just keep going with what you have already selected', dateAndTime: 'just now' })} {chatWithUser({ image: require('../assets/stick_man.jpg'), firstName: 'Tim', lastName: 'Barber', lastMessage: 'Omg I cannot believe what she told you!', dateAndTime: 'just now' })} {chatWithUser({ image: require('../assets/stick_man.jpg'), firstName: 'Andrew', lastName: 'Adler', lastMessage: 'Fair enough will check it out in a bit', dateAndTime: 'just now' })} {chatWithUser({ image: require('../assets/stick_man.jpg'), firstName: 'Constantinos', lastName: 'Hadjichristodoulou', lastMessage: 'Based on the latest article published by New York Times, the global university rankings have changed and there is an unexpected change in the top 3 so check it out', dateAndTime: 'just now' })} {chatWithUser({ image: require('../assets/stick_man.jpg'), firstName: 'Tom', lastName: 'Adams', lastMessage: 'What do you mean?', dateAndTime: 'just now' })} {chatWithUser({ image: require('../assets/stick_man.jpg'), firstName: 'Imogen', lastName: 'Masters', lastMessage: 'I will text you as soon as I finish my tutoring lesson', dateAndTime: 'just now' })} {chatWithUser({ image: require('../assets/stick_man.jpg'), firstName: 'Ava', lastName: 'Trypatsas', lastMessage: 'Are you sure about it or?', dateAndTime: 'just now' })} </ScrollView> <View style={styles.bottombar}> <BottomBar activeRoute="Chat"/> </View> </View> ) }; const styles = StyleSheet.create ({ bigbox: { flex: 1, backgroundColor: globalColors.maincolors.white.colour, marginBottom: 0 }, bottombar: { position: 'absolute', bottom: 0, justifyContent: 'center', height: 70, borderTopColor: globalColors.grey.greyborder.colour, borderTopWidth: 2, width: width }, settings: { position: 'absolute', alignItems: 'flex-end', right: 24, marginTop: 45 }, titlebox: { alignSelf: 'center', position: 'absolute', marginTop: 45 }, titletext:{ fontSize: 20, color: globalColors.orange.title.colour, textAlign: 'center' }, backarrow: { left: 20, marginTop: 45 }, image: { height: 50, width: 50, borderColor: globalColors.orange.background.colour, borderWidth: 2, borderRadius: 50 }, search: { marginTop: 30.3, backgroundColor: globalColors.grey.search.colour, marginLeft: 20, marginRight: 20, borderRadius: 50, height: 45, paddingLeft: 20.3, paddingTop: 8, }, chatbutton: { height: 80, marginLeft: 21, marginRight: 21, borderBottomColor: globalColors.grey.outline.colour, borderBottomWidth: 2, flexDirection: 'row', marginTop: 26 }, buttontext: { marginLeft: 21, marginRight: 28, flexDirection: 'column' }, arrow: { position: 'absolute', alignItems: 'flex-end', right: 5, paddingTop: 28 }, scrollview: { flex: 1 }, scrollviewcontent: { paddingBottom: 60 }, datetime: { position: 'absolute', alignItems: 'flex-end', right: 5, } })
use super::*; /// Geta user from the db. pub async fn get_user(pool: &DbPool, username: &Username) -> DbResult<Option<User>> { trace!("get_user called w username: {username}"); sqlx::query_as!( User, "SELECT username, password_hash, reset_password_token as \"reset_password_token: ResetPasswordToken\", reset_password_token_expiration as \"reset_password_token_expiration: Timestamp\", email as \"email: Email\", created, karma, about as \"about: About\", show_dead, is_moderator, banned FROM users WHERE username = $1", username.0 ) .fetch_optional(pool) .await .map_err(DbError::from) } /// Get a user from the database by their username. Return an error on not found. pub async fn get_assert_user(pool: &DbPool, username: &Username) -> DbResult<User> { trace!("get_assert_user called w username: {username}"); get_user(pool, username).await?.ok_or(DbError::NotFound("user".into())) } /// Create a new user in the database. pub async fn create_user(pool: &DbPool, new_user: &User) -> DbResult<()> { trace!("create_user with: {new_user:?}"); let mut tx = pool.begin().await?; let User { username, password_hash, reset_password_token, reset_password_token_expiration, email, karma, .. } = new_user.clone(); sqlx::query!( "INSERT INTO users ( username, password_hash, reset_password_token, reset_password_token_expiration, email ) VALUES ($1, $2, $3, $4, $5)", username.0, password_hash.0, reset_password_token.map(|s| s.0), reset_password_token_expiration.map(|t| t.0), email.map(|s| s.0), ) .execute(&mut *tx) .await?; tx.commit().await?; Ok(()) } pub async fn update_user( pool: &DbPool, username: &Username, about: &Option<About>, email: &Option<Email>, show_dead: &Option<bool>, ) -> DbResult<()> { let mut tx = pool.begin().await?; if let Some(about) = about { sqlx::query!("UPDATE users SET about = $1 WHERE username = $2", about.0, username.0) .execute(&mut *tx) .await?; } if let Some(email) = email { sqlx::query!("UPDATE users SET email = $1 WHERE username = $2", email.0, username.0) .execute(&mut *tx) .await?; } if let Some(show_dead) = show_dead { sqlx::query!("UPDATE users SET show_dead = $1 WHERE username = $2", show_dead, username.0) .execute(&mut *tx) .await?; } trace!("update_user with: {username}"); Ok(tx.commit().await?) } pub async fn update_user_password_token( pool: &DbPool, username: &Username, reset_password_token: &ResetPasswordToken, reset_password_token_expiration: &Timestamp, ) -> DbResult<()> { trace!("update_user_password_token with: {username}"); sqlx::query!( "UPDATE users SET reset_password_token = $1, reset_password_token_expiration = $2 WHERE username = $3", reset_password_token.0, reset_password_token_expiration.0, username.0 ) .execute(pool) .await?; Ok(()) } pub async fn update_user_password( pool: &DbPool, username: &Username, new_password_hash: &PasswordHash, ) -> DbResult<()> { trace!("update_user_password with: {username}"); sqlx::query!( "UPDATE users SET password_hash = $1 WHERE username = $2", new_password_hash.0, username.0, ) .execute(pool) .await?; Ok(()) } // pub async fn get_user_comments(pool: &DbPool, username: &Username) -> DbResult<Vec<Comment>> { // trace!("get_user_comments with: {username}"); // sqlx::query_as!( // Comment, // "SELECT // id, // username as \"username: Username\", // parent_item_id, // parent_item_title as \"parent_item_title: Title\", // comment_text as \"comment_text: CommentText\", // is_parent, // root_comment_id, // parent_comment_id, // children_count, // points, // created, // dead // FROM comments WHERE username = $1", // username.0 // ) // .fetch_all(pool) // .await? // } // pub async fn get_user_items(pool: &DbPool, username: &Username) -> DbResult<Vec<Item>> { // trace!("get_user_items with: {username}"); // sqlx::query_as!( // Item, // "SELECT // id, // username as \"username: Username\", // title as \"title: Title\", // item_type, // url, // domain, // text, // points, // score, // comment_count, // item_category, // created, // dead // FROM items WHERE username = $1", // username.0 // ) // .fetch_all(pool) // .await? // }
#ifndef SEEN_SP_CANVAS_H #define SEEN_SP_CANVAS_H /** * @file * SPCanvas, SPCanvasBuf. */ /* * Authors: * Federico Mena <federico@nuclecu.unam.mx> * Raph Levien <raph@gimp.org> * Lauris Kaplinski <lauris@kaplinski.com> * Jon A. Cruz <jon@joncruz.org> * * Copyright (C) 1998 The Free Software Foundation * Copyright (C) 2002 Lauris Kaplinski * * Released under GNU GPL, read the file 'COPYING' for more information */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <gtk/gtk.h> #include <stdint.h> #include <glibmm/ustring.h> #include <2geom/affine.h> #include <2geom/rect.h> G_BEGIN_DECLS #define SP_TYPE_CANVAS (sp_canvas_get_type()) #define SP_CANVAS(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SP_TYPE_CANVAS, SPCanvas)) #define SP_IS_CANVAS(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), SP_TYPE_CANVAS)) struct SPCanvas; struct SPCanvasItem; struct SPCanvasGroup; enum { SP_CANVAS_UPDATE_REQUESTED = 1 << 0, SP_CANVAS_UPDATE_AFFINE = 1 << 1 }; /** * Structure used when rendering canvas items. */ struct SPCanvasBuf { cairo_t *ct; Geom::IntRect rect; Geom::IntRect visible_rect; unsigned char *buf; int buf_rowstride; bool is_empty; }; G_END_DECLS // SPCanvas ------------------------------------------------- struct PaintRectSetup; GType sp_canvas_get_type() G_GNUC_CONST; /** * Port of GnomeCanvas for inkscape needs. */ struct SPCanvas { /// Scrolls canvas to specific position (cx and cy are measured in screen pixels). void scrollTo(double cx, double cy, unsigned int clear, bool is_scrolling = false); /// Synchronously updates the canvas if necessary. void updateNow(); /// Queues a redraw of rectangular canvas area. void requestRedraw(int x1, int y1, int x2, int y2); void requestUpdate(); void forceFullRedrawAfterInterruptions(unsigned int count); void endForcedFullRedraws(); Geom::Rect getViewbox() const; Geom::IntRect getViewboxIntegers() const; SPCanvasGroup *getRoot(); /// Returns new canvas as widget. static GtkWidget *createAA(); private: /// Emits an event for an item in the canvas, be it the current /// item, grabbed item, or focused item, as appropriate. int emitEvent(GdkEvent *event); /// Re-picks the current item in the canvas, based on the event's /// coordinates and emits enter/leave events for items as appropriate. int pickCurrentItem(GdkEvent *event); void shutdownTransients(); /// Allocates a new tile array for the canvas, copying overlapping tiles from the old array void resizeTiles(int nl, int nt, int nr, int nb); /// Marks the specified area as dirty (requiring redraw) void dirtyRect(Geom::IntRect const &area); /// Marks specific canvas rectangle as clean (val == 0) or dirty (otherwise) void markRect(Geom::IntRect const &area, uint8_t val); /// Invokes update, paint, and repick on canvas. int doUpdate(); void paintSingleBuffer(Geom::IntRect const &paint_rect, Geom::IntRect const &canvas_rect, int sw); /** * Paint the given rect, recursively subdividing the region until it is the size of a single * buffer. * * @return true if the drawing completes */ int paintRectInternal(PaintRectSetup const *setup, Geom::IntRect const &this_rect); /// Draws a specific rectangular part of the canvas. /// @return true if the rectangle painting succeeds. bool paintRect(int xx0, int yy0, int xx1, int yy1); /// Repaints the areas in the canvas that need it. /// @return true if all the dirty parts have been redrawn int paint(); /// Idle handler for the canvas that deals with pending updates and redraws. static gint idle_handler(gpointer data); /// Convenience function to add an idle handler to a canvas. void addIdle(); void removeIdle(); public: // GTK virtual functions. static void dispose(GObject *object); static void handle_realize(GtkWidget *widget); static void handle_unrealize(GtkWidget *widget); #if GTK_CHECK_VERSION(3,0,0) static void handle_get_preferred_width(GtkWidget *widget, gint *min_w, gint *nat_w); static void handle_get_preferred_height(GtkWidget *widget, gint *min_h, gint *nat_h); #else static void handle_size_request(GtkWidget *widget, GtkRequisition *req); #endif static void handle_size_allocate(GtkWidget *widget, GtkAllocation *allocation); static gint handle_button(GtkWidget *widget, GdkEventButton *event); /** * Scroll event handler for the canvas. * * @todo FIXME: generate motion events to re-select items. */ static gint handle_scroll(GtkWidget *widget, GdkEventScroll *event); static gint handle_motion(GtkWidget *widget, GdkEventMotion *event); #if GTK_CHECK_VERSION(3,0,0) static gboolean handle_draw(GtkWidget *widget, cairo_t *cr); #else static gboolean handle_expose(GtkWidget *widget, GdkEventExpose *event); #endif static gint handle_key_event(GtkWidget *widget, GdkEventKey *event); static gint handle_crossing(GtkWidget *widget, GdkEventCrossing *event); static gint handle_focus_in(GtkWidget *widget, GdkEventFocus *event); static gint handle_focus_out(GtkWidget *widget, GdkEventFocus *event); public: // Data members: ---------------------------------------------------------- GtkWidget _widget; guint _idle_id; SPCanvasItem *_root; bool _is_dragging; double _dx0; double _dy0; int _x0; int _y0; /* Area that needs redrawing, stored as a microtile array */ int _tLeft, _tTop, _tRight, _tBottom; int _tile_w, _tile_h; uint8_t *_tiles; /** Last known modifier state, for deferred repick when a button is down. */ int _state; /** The item containing the mouse pointer, or NULL if none. */ SPCanvasItem *_current_item; /** Item that is about to become current (used to track deletions and such). */ SPCanvasItem *_new_current_item; /** Item that holds a pointer grab, or NULL if none. */ SPCanvasItem *_grabbed_item; /** Event mask specified when grabbing an item. */ guint _grabbed_event_mask; /** If non-NULL, the currently focused item. */ SPCanvasItem *_focused_item; /** Event on which selection of current item is based. */ GdkEvent _pick_event; int _close_enough; unsigned int _need_update : 1; unsigned int _need_redraw : 1; unsigned int _need_repick : 1; int _forced_redraw_count; int _forced_redraw_limit; /** For use by internal pick_current_item() function. */ unsigned int _left_grabbed_item : 1; /** For use by internal pick_current_item() function. */ unsigned int _in_repick : 1; // In most tools Inkscape only generates enter and leave events // on the current item, but no other enter events if a mouse button // is depressed -- see function pickCurrentItem(). Some tools // may wish the canvas to generate to all enter events, (e.g., the // connector tool). If so, they may temporarily set this flag to // 'true'. bool _gen_all_enter_events; /** For scripting, sometimes we want to delay drawing. */ bool _drawing_disabled; int _rendermode; int _colorrendermode; #if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) bool _enable_cms_display_adj; Glib::ustring _cms_key; #endif // defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) bool _is_scrolling; }; bool sp_canvas_world_pt_inside_window(SPCanvas const *canvas, Geom::Point const &world); void sp_canvas_window_to_world(SPCanvas const *canvas, double winx, double winy, double *worldx, double *worldy); void sp_canvas_world_to_window(SPCanvas const *canvas, double worldx, double worldy, double *winx, double *winy); Geom::Point sp_canvas_window_to_world(SPCanvas const *canvas, Geom::Point const win); Geom::Point sp_canvas_world_to_window(SPCanvas const *canvas, Geom::Point const world); #endif // SEEN_SP_CANVAS_H /* Local Variables: mode:c++ c-file-style:"stroustrup" c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) indent-tabs-mode:nil fill-column:99 End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :
// Libraries for Ethernet connection. #include <SPI.h> #include <Ethernet.h> // Libraries for temperature sensors (need to implement). #include <OneWire.h> #include <DallasTemperature.h> // Pins for making heating and cooling requests. #define HEATREQUEST 31 #define COOLREQUEST 35 // Pins on which the sound sensors are. #define SOUNDSENSOR1 23 #define SOUNDSENSOR2 25 #define SOUNDSENSOR3 27 #define SOUNDSENSOR4 23 // Pins on which the motion sensors are. #define MOTIONSENSOR1 30 #define MOTIONSENSOR2 32 #define MOTIONSENSOR3 34 #define MOTIONSENSOR4 36 // Pin to receive smoke alarm on signal from RTA. #define SMOKEALARM 43 // Pin to shut power off. #define POWERSHUTOFF 21 // Pin to shut water off. #define WATERSHUTOFF 33 // Temperature pins setup. #define ONE_WIRE_BUS_1 37 #define ONE_WIRE_BUS_2 39 #define ONE_WIRE_BUS_3 41 OneWire onewire_1(ONE_WIRE_BUS_1); OneWire onewire_2(ONE_WIRE_BUS_2); OneWire onewire_3(ONE_WIRE_BUS_3); DallasTemperature sensor_1(&onewire_1); DallasTemperature sensor_2(&onewire_2); DallasTemperature sensor_3(&onewire_3); // Mac address of Arduino REMS board. byte mac[] = { 0x2C, 0xF7, 0xF1, 0x08, 0x33, 0x4E }; // IP address for the webpage. IPAddress ip(192, 168, 3, 160); EthernetServer server(80); // String that'll store the response from the webpage. String httpResponse; boolean changed = 0; // Array to store status of buttons. Order is heat, cool, power, water. boolean status[] = {false, false, false, false}; void setup() { // Begin serial monitor. Serial.begin(9600); // Start webserver. Ethernet.begin(mac, ip); server.begin(); // Setup all pins. pinMode(HEATREQUEST, OUTPUT); pinMode(COOLREQUEST, OUTPUT); digitalWrite(HEATREQUEST, HIGH); digitalWrite(COOLREQUEST, HIGH); pinMode(SOUNDSENSOR1, INPUT); pinMode(SOUNDSENSOR2, INPUT); pinMode(SOUNDSENSOR3, INPUT); pinMode(SOUNDSENSOR4, INPUT); pinMode(MOTIONSENSOR1, INPUT); pinMode(MOTIONSENSOR2, INPUT); pinMode(MOTIONSENSOR3, INPUT); pinMode(MOTIONSENSOR4, INPUT); pinMode(SMOKEALARM, INPUT); pinMode(POWERSHUTOFF, OUTPUT); digitalWrite(POWERSHUTOFF, HIGH); pinMode(WATERSHUTOFF, OUTPUT); digitalWrite(WATERSHUTOFF, HIGH); // Start temperature sensors. sensor_1.begin(); sensor_2.begin(); sensor_3.begin(); } void loop() { // Listen for incoming clients. EthernetClient client = server.available(); // If a client is found... if (client) { // If the client is availalble, read the incoming HTTP request. if (client.available()) { // Calls a function to read the HTTP request and stores it in the httpResponse global String. readRequest(client); // Displays the updated webpage in line with the request, and sends whatever commands the HTTP request asked to do. ClientResponse(client); delay(1); client.stop(); } } } // Function to display entire webpage and process the HTTP request. void ClientResponse(EthernetClient client) { // Send http request. client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); client.println(); // Begin HTML client.println("<!DOCTYPE HTML>"); client.println("<html>"); // Code for the head portion of the webpage client.println("<head>"); client.println("<title>REMS CONTROL CENTRE 1</title>"); client.println("</head>"); // Start body portion of site. Header that has site label. client.println("<body>"); client.println("<h1>REMS006 1</h1>"); client.println("<h4>192.168.3.160</h4>"); String heat, cool, power, water; for (int i = 0; i < 4; i++) { if (status[i]) { if (i == 0) heat = "HEAT ON"; if (i == 1) cool = "COOL ON"; if (i == 2) power = "POWER OFF"; if (i == 3) water = "WATER OFF"; } else { if (i == 0) heat = "HEAT OFF"; if (i == 1) cool = "COOL OFF"; if (i == 2) power = "POWER ON"; if (i == 3) water = "WATER ON"; } } client.println("<a href='/?heatrequest'><button>" + heat + "</button></a>"); client.println("<a href='/?coolrequest'><button>" + cool + "</button></a>"); client.println("<a href='/?powerOff'><button>" + power + "</button></a>"); client.println("<a href='/?waterOff'><button>" + water + "</button></a>"); // End body and HTML. if (status[0]) { digitalWrite(HEATREQUEST, LOW); Serial.println("HEAT ON"); } else { digitalWrite(HEATREQUEST, HIGH); Serial.println("HEAT OFF"); } if (status[1]) { digitalWrite(COOLREQUEST, LOW); Serial.println("COOL ON"); } else { digitalWrite(COOLREQUEST, HIGH); Serial.println("COOL OFF"); } if (status[2]) { digitalWrite(POWERSHUTOFF, LOW); client.println("POWER OFF"); Serial.println("POWER OFF"); } else { digitalWrite(POWERSHUTOFF, HIGH); Serial.println("POWER ON"); } if (status[3]) { digitalWrite(WATERSHUTOFF, LOW); client.println("WATER OFF"); Serial.println("WATER OFF"); } else { digitalWrite(WATERSHUTOFF, HIGH); Serial.println("WATER ON"); } client.println("</body></html>"); } // Function that reads the incoming HTTP request. void readRequest(EthernetClient client) { // Boolean variable to store if the request is POST (sending states of buttons). httpResponse = ""; char c = client.read(); // Iterate through all the strings until the newline appears (in the case of a GET request) or until the line with all the checkbox statuses appears (in the case of a POST request). while (c != '\n') { httpResponse += c; c = client.read(); } Serial.println(httpResponse); if (httpResponse.indexOf("?heatrequest") >= 0) { Serial.println("HEAT SWAP"); status[0] = !status[0]; } if (httpResponse.indexOf("?coolrequest") >= 0) { Serial.println("COOl SWAP"); status[1] = !status[1]; } if (httpResponse.indexOf("?powerOff") >= 0) { Serial.println("POWER SWAP"); status[2] = !status[2]; } if (httpResponse.indexOf("?waterOff") >= 0) { Serial.println("WATER SWAP"); status[3] = !status[3]; } }
{% extends 'my_info/base.html' %} {% load static %} {% block content %} <div class="admin-content"> <div class="admin-content-body"> <div class="am-cf am-padding am-padding-bottom-0"> <div class="am-fl am-cf"><strong class="am-text-primary am-text-lg">个人资料</strong> / <small>Personal information</small> </div> </div> <hr/> <div class="am-g"> <div class="am-u-sm-12 am-u-md-4 am-u-md-push-8"> </div> <div class="am-u-sm-12 am-u-md-8 am-u-md-pull-4"> <form class="am-form am-form-horizontal"> <div class="am-form-group"> <label for="user-phone" class="am-u-sm-3 am-form-label">学号 / Student ID</label> <div class="am-u-sm-9"> <input type="number" id="user-student-id" placeholder="输入你的学号 / Student ID" value="{{ user.stu_id }}"> </div> </div> <div class="am-form-group"> <label for="user-name" class="am-u-sm-3 am-form-label">姓名 / Name</label> <div class="am-u-sm-9"> <input type="text" id="user-name" placeholder="姓名 / Name" value="{{ user.stu_name }}"> <small>输入你的名字,让我们记住你。</small> </div> </div> <div class="am-form-group"> <label for="user-phone" class="am-u-sm-3 am-form-label">电话 / Telephone</label> <div class="am-u-sm-9"> <input type="tel" id="user-phone" placeholder="输入你的电话号码 / Telephone" value="{{ user.stu_tel }}"> </div> </div> <div class="am-form-group"> <label for="user-email" class="am-u-sm-3 am-form-label">电子邮件 / Email</label> <div class="am-u-sm-9"> <input type="email" id="user-email" placeholder="输入你的电子邮件 / Email" value="{{ user.stu_email }}"> <small>邮箱你懂得...</small> </div> </div> <div class="am-form-group"> <label for="user-QQ" class="am-u-sm-3 am-form-label">QQ</label> <div class="am-u-sm-9"> <input type="number" pattern="[0-9]*" id="user-QQ" placeholder="输入你的QQ号码" value="{{ user.stu_qq }}"> </div> </div> <div class="am-form-group"> <label for="user-intro" class="am-u-sm-3 am-form-label">简介 / Intro</label> <div class="am-u-sm-9"> <textarea class="" rows="5" id="user-intro" placeholder="输入个人简介">{{ user.stu_intro }}</textarea> <small>250字以内写出你的一生...</small> </div> </div> <div class="am-form-group"> <label for="user-password" class="am-u-sm-3 am-form-label">新密码</label> <div class="am-u-sm-9"> <input type="password" id="user-password" placeholder="输入你的新密码【不需要修改请留空】"> </div> </div> <div class="am-form-group"> <label for="user-password-again" class="am-u-sm-3 am-form-label">重复新密码</label> <div class="am-u-sm-9"> <input type="password" id="user-password-again" placeholder="重复输入新密码【不需要修改请留空】"> </div> </div> <div class="am-form-group"> <div class="am-u-sm-9 am-u-sm-push-3"> <button type="button" id="submit" class="am-btn am-btn-primary">保存修改</button> </div> </div> </form> </div> </div> </div> <script> $('#submit').click(function () { var stu_id = $('#user-student-id').val(); var stu_name = $('#user-name').val(); var stu_phone = $('#user-phone').val(); var stu_email = $('#user-email').val(); var stu_qq = $('#user-QQ').val(); var stu_intro = $('#user-intro').val(); var password1 = $('#user-password').val(); var password2 = $('#user-password-again').val(); console.log(stu_id); console.log(stu_name); console.log(stu_phone); console.log(stu_email); console.log(stu_qq); console.log(stu_intro); console.log(password1); console.log(password2); if (!stu_id) { alert("学号不能为空"); return; } if (!stu_name) { alert("姓名不能为空"); return; } if (!stu_phone) { alert("手机号不能为空"); return; } if (!stu_email) { alert("邮箱不能为空"); return; } if (!stu_qq) { alert('QQ不能为空'); return; } if (!stu_intro) { alert('自我简介不能为空'); return; } var password = ''; if (password1 != password2) { alert("密码不一致"); return; } password = password2; $.ajax({ type: 'POST', data: { stu_id: stu_id, stu_name: stu_name, stu_tel: stu_phone, stu_email: stu_email, stu_intro: stu_intro, stu_password: password, stu_qq: stu_qq, csrfmiddlewaretoken: '{{ csrf_token }}', }, dataType: 'json', url: '{% url 'my_info:api' %}', success: function (data) { var code = data.code; var msg = data.msg; if (code == 200) { alert("修改成功"); } } }); }) </script> <footer class="admin-content-footer"> <hr> <p class="am-padding-left">© 2019 All license Left.</p> </footer> </div> {% endblock %}
Public and private keys The public key, we use for encrypt a message and we can see this message with the private key. We only can share the public key for other person could code a message and see with private key. When we make a git push we must put the name of user and password (protocol https) and can be hack, then for evoid this use public key and private key, too we don't login in github git push and other thing. Send public to github and connect with new protocol ssh, after github will send its own public key and created a double way of encryted. Practice git config -l : see the config of git (user and email) git config --global user.email "email_git" : if we want change the user email Creation of private and public key ssh-keygen -t rsa -b 4096 -C "email_git" eval $(ssh-agent -s) : verify if server ssh is working Now we add the key (add the direction of private key) ssh-add ~/.ssh/id_rsa Note: each pc have own private key Add to github the public key (NO private key) go github - setting -SSH and GPG key - add new change git clone of https to ssh change address of git remote git remote set-url origin <address_ssh>
"""Count the number of people who are online. Author: Dr. Jake Rosenzweig Date: 2023-10-31, Happy Halloween! Challenge: Online Status Difficulty: 2/10 URL: https://pythonprinciples.com/challenges/Online-status/ The aim of this challenge is, given a dictionary of people's online status, to count the number of people who are online. For example, consider the following dictionary: statuses = { "Alice": "online", "Bob": "offline", "Eve": "online", } In this case, the number of people online is 2. Write a function named online_count that takes one parameter. The parameter is a dictionary that maps from strings of names to the string "online" or "offline", as seen above. Your function should return the number of people who are online. Performance Testing: >>> %timeit online_count(statuses) 391 ns ± 2.49 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) >>> %timeit online_count_generator(statuses) 421 ns ± 5.17 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) >>> %timeit online_count_egsoln1(statuses) 279 ns ± 0.668 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) >>> %timeit online_count_egsoln2(statuses) 383 ns ± 1.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) #=== Lessons Learned ===# * Summing a generator is surprisingly the *slowest*! Was this an exception? - Summing a list of bools was faster. * Fastest soln was a for loop, a counter, and unpacking key, val pairs. * Can do some performance testing by doing: - >>> python -m cProfile myscript.py - Include the `-s time` flag to sort by most expensive calls up top. """ def online_count(dct): return sum([True for val in dct.values() if val == "online"]) def online_count_generator(dct): return sum(True for val in dct.values() if val == "online") # Example Solution 1. def online_count_egsoln1(people): count = 0 for person, status in people.items(): if status == "online": count += 1 return count # Example Solution 2. def online_count_egsoln2(people): return len([p for p in people if people[p] == "online"]) statuses = { "Alice": "online", "Bob": "offline", "Eve": "online", } if __name__ == '__main__': print(f'''Should return 2: {online_count(statuses)}''') print(f'''Should return 2: {online_count_generator(statuses)}''') print(f'''Should return 2: {online_count_egsoln1(statuses)}''') print(f'''Should return 2: {online_count_egsoln2(statuses)}''')
import { Request, Response } from "express"; import { UserDatabase } from "../../data/user/userDatabase"; import { User } from "../../entities/users/users"; import { HashManager } from "../../services/HashManager"; import { idGenerator } from "../../services/idGenerator"; import { jsonWebToken } from "../../services/JsonWebToken"; export const createUser = async (req: Request, res: Response) => { try { if (!req.body.email || req.body.email.indexOf("@") === -1) { throw new Error("Invalid email"); } if (!req.body.password || req.body.password.length < 6) { throw new Error("Invalid password"); } const id: string = new idGenerator().generateId() const cypherPassword = new HashManager().generateHash(req.body.password) const userData = new User( id, req.body.name, req.body.email, req.body.role, cypherPassword ) const database = new UserDatabase() await database.createUser(userData) const token = new jsonWebToken().tokenGenerate(id, userData.getRole()) res.status(200).send({ token, }); } catch (err: any) { res.status(400).send({ message: err.message, }); } }
from __future__ import annotations import logging from typing import cast from collections.abc import Callable from parsec import ( Parser, string, regex, optional, end_of_line, times, any, many, one_of, sepBy, between, joint, separated, try_choices_longest, fail_with, validate, decimal_number, hexadecimal_number, hexadecimal, ) from socks_router.models import ( Socks5ReplyType, Address, IPv4, IPv6, Host, Pattern, UpstreamScheme, UpstreamAddress, RoutingEntry, RoutingTable, ) from socks_router.utils import to_hex logger = logging.getLogger(__name__) def trace[T](value: T) -> T: logger.debug(f"value: {value}") return value whitespace: Parser[str] = one_of(" \t") whitespaces: Parser[list[str]] = many(whitespace) ipv4_octet: Parser[int] = (decimal_number >= validate(lambda value: 0 <= value < (1 << 8))) | fail_with( f"ipv4_octet can only carry a value ranged from 0 to {1 << 8} exclusive" ) ipv6_doublet: Parser[int] = (hexadecimal_number >= validate(lambda value: 0 <= value < (1 << 16))) | fail_with( "doublet can only carry a value from 0 to {1 << 16} exclusive" ) ipv4: Parser[str] = separated(ipv4_octet.map(str), string("."), 4, end=False).map(".".join) # SEE: https://datatracker.ietf.org/doc/html/draft-main-ipaddr-text-rep-00#section-3.2 h16: Parser[str] = ipv6_doublet.map(to_hex) ls32: Parser[str] = joint(h16, string(":"), h16).map("".join) ^ ipv4 ipv6: Parser[str] = try_choices_longest( joint(separated(h16, string(":"), 6, end=False).map(":".join), string(":"), ls32).map("".join), *[ joint( separated(h16, string(":"), 0, i, end=False).map(":".join), string("::"), times((h16 + string(":")).map("".join), 5 - i).map("".join), ls32, ).map("".join) for i in range(6) ], joint(separated(h16, string(":"), 0, 6, end=False).map(":".join), string("::"), h16).map("".join), joint(separated(h16, string(":"), 0, 7, end=False).map(":".join), string("::")).map("".join), ) port = (decimal_number >= validate(lambda value: 0 <= value < 65536)) | fail_with( "port can only carry between 0 to 65536 exclusive" ) ipv4_address: Parser[IPv4] = (ipv4 + optional(string(":") > port)).map(IPv4, star=True) ipv6_address: Parser[IPv6] = ( (between(string("["), string("]"), ipv6) + (string(":") > port)) ^ ipv6.map(lambda ipv6: (ipv6, None)) ).map(IPv6, star=True) hostname: Parser[str] = regex( r"(?P<hostname>\b(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*(?:[A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])\b)" ) host_address: Parser[Host] = (hostname + optional(string(":") > port)).map(Host, star=True) address: Parser[Address] = ipv4_address ^ ipv6_address ^ host_address scheme: Parser[UpstreamScheme] = try_choices_longest(*[string(f"{scheme}").result(scheme) for scheme in UpstreamScheme]) << string( "://" ) upstream_address: Parser[UpstreamAddress] = (optional(scheme, UpstreamScheme.SSH) + address).map(UpstreamAddress, star=True) comment: Parser[str] = regex(r"\s*#\s*.*") pattern: Parser[Pattern] = ( optional(string("!").result(False), True) + (regex(r"[^ \t\r\n]+") << optional(comment)) # type: ignore[arg-type] ).map(lambda is_positive, address: Pattern(address, is_positive), star=True) routing_rule: Parser[tuple[UpstreamAddress, RoutingEntry]] = (upstream_address << whitespaces) + sepBy(pattern, whitespaces).desc( "patterns" ) routing_table: Parser[RoutingTable] = sepBy(routing_rule, optional(comment) >> end_of_line()).map( cast(Callable[[list[tuple[UpstreamAddress, RoutingEntry]]], RoutingTable], dict) ) def parse_sockaddr[S: (str, bytes, bytearray)](sockaddr: tuple[S, int]) -> Address: address = ( ipv4.map(lambda ip: lambda port: IPv4(ip, port)) ^ ipv6.map(lambda ip: lambda port: IPv6(ip, port)) ^ hostname.map(lambda host: lambda port: Host(host, port)) ) return address.parse(sockaddr[0])(sockaddr[1]) pysocks_socks5_error: Parser[tuple[Socks5ReplyType, str]] = ( (string("0") >> hexadecimal.map(Socks5ReplyType)) << string(":") << whitespaces ) + many(any()).map("".join)
import React from "react"; import { connect } from 'react-redux' import { browserHistory } from 'react-router'; import * as UsersActions from "redux/actions/users"; import * as AlertsActions from "redux/actions/alerts"; import {UserEditForm} from "./UserEditForm"; const mapDispatchToProps = (dispatch) => { return { fetch(id) { const ENDPOINT = '/api/user/' + id dispatch(UsersActions.fetchError(undefined)) dispatch(AlertsActions.processingOn()) jQuery.ajax({ type: 'GET', url: ENDPOINT, dataType: 'json', success: (data) => dispatch(UsersActions.fetch(data)) }).fail( () => dispatch(UsersActions.fetchError('Error loading user.')) ).always( () => dispatch(AlertsActions.processingOff()) ) }, save(id, data) { const ENDPOINT = '/api/user/' + id dispatch(AlertsActions.processingOn()) jQuery.ajax({ type: 'PUT', url: ENDPOINT, dataType: 'json', contentType: "application/json; charset=utf-8", data: JSON.stringify(data), success: (data) => { dispatch(AlertsActions.addSuccess('User data has been saved.')) dispatch(UsersActions.fetch(data)) } }).fail( () => dispatch(AlertsActions.addDanger('Error while saving user.')) ).always( () => dispatch(AlertsActions.processingOff()) ) }, cancel() { browserHistory.push('/admin/users'); } } } const mapStateToProps = (state) => { return { user: state.users.user, fetchError: state.users.userFetchError, saving: state.alerts.processing } } const UserEdit = connect( mapStateToProps, mapDispatchToProps )(UserEditForm) export {UserEdit}
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@400;600;700;900&family=Fraunces:wght@400;700;900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="./styles.css"> <title>sunnyside</title> </head> <body> <header> <nav> <div class="logo">sunnyside</div> <div class="menu"> <button id="btn-hamburguer"><img src="./images/icon-hamburger.svg" alt="menu hamburger"></button> </div> <ul id="mobile-menu" > <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Projects</a></li> <li><button id="contact"><a href="#">CONTACT</a></button></li> </ul> </nav> <h1>We are creatives</h1> <img class="arrow-down" src="./images/icon-arrow-down.svg" alt="seta para baixo"> </header> <main> <section class="info"> <div class="egg-info"> <picture> <source media="(min-width: 465px)" srcset="./images/desktop/image-transform.jpg"> <img src="./images/mobile/image-transform.jpg" alt="ovo com um fundo amarelo"> </picture> <div class="description"> <div class="description__title"> Transform your brand </div> <div class="description__text"> We are a full-service creative agency specializing in helping brands grow fast. Engage your clients through compelling visuals that do most of the marketing for you. </div> <div class="description__link"> Learn more <div class="line line-yellow"></div> </div> </div> </div> <div class="mug-info"> <picture> <source media="(min-width: 465px)" srcset="./images/desktop/image-stand-out.jpg"> <img src="./images/mobile/image-stand-out.jpg" alt=""> </picture> <div class="description"> <div class="description__title"> Stand out to the right audience </div> <div class="description__text"> Using a collaborative formula of designers, researchers, photographers, videographers, and copywriters, we’ll build and extend your brand in digital places. </div> <div class="description__link"> Learn more <div class="line line-red"></div> </div> </div> </div> <div class="photo"> <div class="container graphic"> <div class="description"> <div class="description__title"> Graphic design </div> <div class="description__text"> Great design makes you memorable. We deliver artwork that underscores your brand message and captures potential clients’ attention. </div> </div> </div> <div class="container photography"> <div class="description"> <div class="description__title"> Photography </div> <div class="description__text"> Increase your credibility by getting the most stunning, high-quality photos that improve your business image. </div> </div> </div> </section> <section class="testimonials"> <h2 class="testimonials__title"> CLIENT TESTIMONIALS </h2> <div id="clients"> <div class="client"> <div class="client__avatar client1"></div> <div class="client__text"> We put our trust in Sunnyside and they delivered, making sure our needs were met and deadlines were always hit. </div> <div> <div class="client__name"> Emily R. </div> <div class="client__job"> Marketing Director </div> </div> </div> <div class="client"> <div class="client__avatar client2"></div> <div class="client__text"> Sunnyside’s enthusiasm coupled with their keen interest in our brand’s success made it a satisfying and enjoyable experience. </div> <div> <div class="client__name"> Thomas S. </div> <div class="client__job"> Chief Operating Officer </div> </div> </div> <div class="client"> <div class="client__avatar client3"></div> <div class="client__text"> Incredible end result! Our sales increased over 400% when we worked with Sunnyside. Highly recommended! </div> <div> <div class="client__name"> Jennie F. </div> <div class="client__job"> Business Owner </div> </div> </div> </div> </section> <section class="images"> <div class="gallery"> <picture class="imgs"> <source media="(min-width: 465px)" srcset="./images/desktop/image-gallery-milkbottles.jpg"> <img src="./images/mobile/image-gallery-milkbottles.jpg" alt=""> </picture> <picture class="imgs"> <source media="(min-width: 465px)" srcset="./images/desktop/image-gallery-orange.jpg"> <img src="./images/mobile/image-gallery-orange.jpg" alt=""> </picture> <picture class="imgs"> <source media="(min-width: 465px)" srcset="./images/desktop/image-gallery-cone.jpg"> <img src="./images/mobile/image-gallery-cone.jpg" alt=""> </picture> <picture class="imgs"> <source media="(min-width: 465px)" srcset="./images/desktop/image-gallery-sugarcubes.jpg"> <img src="./images/mobile/image-gallery-sugar-cubes.jpg" alt=""> </picture> </div> </section> </main> <footer> <h2>sunnyside</h2> <nav> <ul> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Projects</a></li> </ul> </nav> <ul> <li><a href="#"><img src="./images/icon-facebook.svg" alt=""></a></li> <li><a href="#"><img src="./images/icon-instagram.svg" alt=""></a></li> <li><a href="#"><img src="./images/icon-twitter.svg" alt=""></a></li> <li><a href="#"><img src="./images/icon-pinterest.svg" alt=""></a></li> </ul> </footer> </body> </html>
// OLED uses libraries from Arduino #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include "ThingSpeak.h" // always include thingspeak header file after other header files and custom macros #include <WiFi.h> #include "time.h" #include "esp_wpa2.h" #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 32 // OLED display height, in pixels #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) #define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32 Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); int keyIndex = 0; // your network key Index number (needed only for WEP) WiFiClient client; unsigned long myChannelNumber = 2373428; const char * myWriteAPIKey = "L8LR6MKS3I5V66NJ"; int number = 0; int count=0; const char* ssid= "iPhone (821)"; const char* password= "x7r8vgexab07"; const char* ntpServer = "pool.ntp.org"; const long gmtOffset_sec = 0; const int daylightOffset_sec = 0; int inputPin=8; // plug into D8 long long time_stamp[201]; //chosen because need 201 sample times to get 200 f data points long long period[200]; // period and time should be the same data type double f[201]; // f as an array of doubles (more d.p than a float) // this is used to keep track of the place in arrays float f_sum=0.00; float f_av=0.00; float f_av_set=0.00; void setup() { Serial.begin(9600); display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS); display.clearDisplay(); display.setTextSize(1); // Draw 2X-scale text display.setTextColor(SSD1306_WHITE); display.setCursor(10, 0); display.println(F("OLED connected")); display.setCursor(10, 14); display.println(F("looking for Wifi")); // display.setCursor(10, 25); // display.println(F("14:40")); display.display(); time_stamp[0]=0; time_stamp[1]=0; // attaches an interrupt to D8 () WiFi.disconnect(true); // WiFi.begin(ssid, WPA2_AUTH_PEAP, identity, username, password); WiFi.begin(ssid, password); Serial.print("Connecting to WiFi"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); display.clearDisplay(); display.setTextSize(1); // Draw 2X-scale text display.setTextColor(SSD1306_WHITE); display.setCursor(10, 0); display.println(F("WiFi Connected")); display.display(); configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); delay(500); struct tm timeinfo; if(!getLocalTime(&timeinfo)){ Serial.println("Failed to obtain time"); return; } // WiFi.disconnect(true); WiFi.mode(WIFI_STA); ThingSpeak.begin(client); // Initialize ThingSpeak pinMode(inputPin, INPUT); // sets D8 to an input that can be read in attachInterrupt(digitalPinToInterrupt(inputPin), ISR, FALLING); // attaches an interrupt to D8 } void loop(){ Serial.print(count); // Serial.print("loop"); if(count==200){ // detachInterrupt(inputPin); noInterrupts(); // stops the interrupts so this can be exectuted before continuing // note that if possible should remove this to minimise the gaps in the data, could be done later in some external data processing code struct tm timeinfo; if(!getLocalTime(&timeinfo)){ Serial.println("Failed to obtain time"); return; } // Serial.println(&timeinfo, "%d %B %Y %H:%M:%S"); display.clearDisplay(); display.setTextSize(1); // Draw 2X-scale text display.setTextColor(SSD1306_WHITE); display.setCursor(10, 14); display.println(&timeinfo, "%d %B %Y"); display.setCursor(10, 25); display.println(&timeinfo, "%H:%M:%S"); display.display(); Serial.print("-"); f_sum=0.00; //Serial.print("calculating average"); for (int i=0; i<199; i++){ // does NOT need to be a global variable period[i]= time_stamp[i+1]-time_stamp[i]; // finds the time period between the 2 closest times // Serial.print(period[i]); f[i]= 1000000.00/period[i]; // uses frequency formula, because in micros 10^6 used f_sum=f_sum + f[i]; f_av=f_sum/199.00; } // f_av= average(); // Serial.println(f_av); count=0; f_av_set=f_av; //display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS); display.setCursor(10, 5); //display.println(F("50.00")); //display.println("Now we can fix your car"); display.print(f_av_set); display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS); display.clearDisplay(); display.setTextSize(1); // Draw 2X-scale text display.setTextColor(SSD1306_WHITE); display.setCursor(10, 5); //display.println(F("50.00")); //display.println("Now we can fix your car"); display.print(f_av_set); Serial.print(f_av_set); //Serial.print("\n"); //Upload to thingspeak taken from MATHWORKS doumentation https://uk.mathworks.com/help/thingspeak/channel-data-import.html accessed 02/05/2024 //Uploads f_av to thingspeak int x = ThingSpeak.writeField(myChannelNumber, 1, f_av_set, myWriteAPIKey); if(x == 200){ Serial.println("Channel update successful."); } else{ Serial.println("Problem updating channel. HTTP error code " + String(x)); } // attachInterrupt(digitalPinToInterrupt(inputPin), ISR, FALLING); } } // this is the interups ISR void ISR(){ // Serial.print("ISR"); //Serial.print("ISR"); time_stamp[count]= micros(); // uses micros to time when an interrupt occurs count++; // adds 1 to the count //Serial.print("-"); }
import express from "express"; import ensureAuth from "../../middlewares/ensureAuth.js"; import { acceptAllUserRequestsController, addPassengerCommentController, assignUserToRideController, completePassengerParticipationController, createRideController, createRideRequestController, deleteAllUserRidesController, deleteRideController, finishRideController, getRideController, getRidesController, getTopUsersWithMostCompletedRidesController, removeAllPassengersFromRideController, removeUserFromRideController, startRideController, } from "./ride.controller.js"; import validateBody from "../../middlewares/validateBody.js"; import createRideSchema from "./validationSchemas/createRideSchema.js"; import createRideRequestSchema from "./validationSchemas/createRideRequestSchema.js"; import commentRideSchema from "./validationSchemas/commentRideSchema.js"; import completePassengerSchema from "./validationSchemas/completePassengerSchema.js"; import startRideSchema from "./validationSchemas/startRideSchema.js"; import finishRideSchema from "./validationSchemas/finishRideSchema.js"; const rideRouter = express.Router(); rideRouter.post("/", ensureAuth, validateBody(createRideSchema), createRideController); rideRouter.get("/", ensureAuth, getRidesController); rideRouter.get("/:idRide", ensureAuth, getRideController); rideRouter.post("/:idRide/assign/:idUser", ensureAuth, assignUserToRideController); rideRouter.post("/:idRide/assignAll", ensureAuth, acceptAllUserRequestsController); rideRouter.delete("/", ensureAuth, deleteAllUserRidesController); rideRouter.delete("/:idRide", ensureAuth, deleteRideController); rideRouter.delete("/:idRide/assignment/:idUser", ensureAuth, removeUserFromRideController); rideRouter.delete("/:idRide/allAssignments", ensureAuth, removeAllPassengersFromRideController); rideRouter.get("/user/top", ensureAuth, getTopUsersWithMostCompletedRidesController); rideRouter.post("/request", ensureAuth, validateBody(createRideRequestSchema), createRideRequestController); rideRouter.post("/comment", ensureAuth, validateBody(commentRideSchema), addPassengerCommentController); rideRouter.post("/passenger/complete", ensureAuth, validateBody(completePassengerSchema), completePassengerParticipationController); rideRouter.patch("/start", ensureAuth, validateBody(startRideSchema), startRideController); rideRouter.patch("/finish", ensureAuth, validateBody(finishRideSchema), finishRideController); export default rideRouter;
using OfficeOpenXml; using OfficeOpenXml.Style; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExcelCleanerNet45 { public delegate bool IsSummaryCell(ExcelRange cell); /// <summary> /// Implementation of IFormulaGenerator that adds formulas to the bottom of "sections" found inside data columns /// of the worksheet. A section is defined as a series of data cells that all corrispond to a single "key" which /// appears on the top left of that section. As an example of this, look at the report RentRollActivityItemized_New. /// /// The first string in the list of arguments for this class should follow this pattern: r=[insert regex] /// Where the regex should match the keys for each section. After that argument, the titles of each data column /// that need formulas should be passed in as well (meaning, which columns need formulas at the end of each section). /// </summary> internal class PeriodicFormulaGenerator : IFormulaGenerator { private IsDataCell isDataCell = new IsDataCell(FormulaManager.IsDollarValue); //default implementation private IsSummaryCell isSummaryCell = new IsSummaryCell( (cell => FormulaManager.IsDollarValue(cell) && cell.Style.Font.Bold)); //defualt implementation public virtual void SetDataCellDefenition(IsDataCell isDataCell) { this.isDataCell = isDataCell; } public virtual void SetSummaryCellDefenition(IsSummaryCell summaryCellDef) { this.isSummaryCell = summaryCellDef; } public virtual void InsertFormulas(ExcelWorksheet worksheet, string[] headers) { if (!headers[0].StartsWith("r=")) { throw new ArgumentException("The argument to this formula generator must specify a regex that matches the key cell of each section"); } string keyRegex = headers[0].Substring(2); for (int i = 1; i < headers.Length; i++) { //Ensure that the header was intended for this class and not the DistantRowsFormulaGenerator class if (FormulaManager.IsNonContiguousFormulaRange(headers[i])) { continue; } InsertFormulaForHeader(worksheet, keyRegex, headers[i]); } } /// <summary> /// Adds all formulas to cells marked with the specified header /// </summary> /// <param name="worksheet">the worksheet being given formulas</param> /// <param name="key">a regex defining what the "key" for a data section should look like</param> /// <param name="targetHeader">the text the header should have</param> protected virtual void InsertFormulaForHeader(ExcelWorksheet worksheet, string key, string targetHeader) { var coordinates = FindStartOfDataColumn(worksheet, targetHeader); int row = coordinates.Item1 + 1; //start by the row after the column header int dataCol = coordinates.Item2; for(; row <= worksheet.Dimension.End.Row; row++) { FindNextKey(worksheet, key, ref row); ProcessFormulaRange(worksheet, ref row, dataCol); } } /// <summary> /// Finds the coordinates of the cell with the specified columnHeader /// </summary> /// <param name="worksheet">the worksheet getting formulas</param> /// <param name="columnHeader">the text that signaling that this is the cell we want</param> /// <returns>a tuple with the row and column of the cell containing the specifed text, or null if its not found</returns> protected virtual Tuple<int, int> FindStartOfDataColumn(ExcelWorksheet worksheet, string columnHeader) { ExcelRange cell; for (int row = 1; row <= worksheet.Dimension.End.Row; row++) { for (int col = 1; col <= worksheet.Dimension.End.Column; col++) { cell = worksheet.Cells[row, col]; if (FormulaManager.TextMatches(cell.Text, columnHeader)) { return new Tuple<int, int>(row, col); } } } return null; } /// <summary> /// Finds the next cell, below the specified row, that contains a key (meaning it might require a formula of its own). /// After this function completes, the row variable will either be pointing to the next cell with a key, or the last row /// plus 1, if there is no next key. /// </summary> /// <param name="worksheet">the worksheet in need of formulas</param> /// <param name="key">the pattern that a key must match</param> /// <param name="row">the row to start searching on</param> protected virtual void FindNextKey(ExcelWorksheet worksheet, string key, ref int row) { ExcelRange cell; for(; row <= worksheet.Dimension.End.Row; row++) { cell = worksheet.Cells[row, 1]; if(FormulaManager.TextMatches(cell.Text, key)) { return; } } } /// <summary> /// Finds the bounds of the formula range and does the actual insertion of the formula. After /// this method completes, the row variable should reference the last row in the section that was just /// given formulas. /// </summary> /// <param name="worksheet">the worksheet in need of formulas</param> /// <param name="row">the row number of the key for the section we are processing</param> /// <param name="dataCol">the column we should look for summary cells in</param> protected virtual void ProcessFormulaRange(ExcelWorksheet worksheet, ref int row, int dataCol) { int start = row; //the formula range starts here, at the first non-empty cell //Now find the bottom of the formula range AdvanceToLastRow(worksheet, ref row); //Ensure there is a summary cell (some sections dont have one) int summaryRow = FindSummaryCellRow(worksheet, row, start, dataCol); if (summaryRow == -1) { return; //no summary cell } //Insert formulas ExcelRange summaryCell = worksheet.Cells[summaryRow, dataCol]; Console.WriteLine("adding formula to " + summaryCell.Address); string formula = FormulaManager.GenerateFormula(worksheet, start, summaryRow - 1, dataCol); FormulaManager.PutFormulaInCell(summaryCell, formula, false); } /// <summary> /// Advances the row variable to reference the first non empty cell from itself or below /// </summary> /// <param name="worksheet">the worksheet in need of formulas</param> /// <param name="row">the first row in the column to check</param> /// <param name="col">the column we are scanning</param> protected void SkipEmptyCells(ExcelWorksheet worksheet, ref int row, int col) { ExcelRange cell = worksheet.Cells[row, col]; while (FormulaManager.IsEmptyCell(cell) && row + 1 <= worksheet.Dimension.End.Row) { row++; cell = worksheet.Cells[row, col]; } } /// <summary> /// Moves the row pointer to the last (bottommost) cell in the section. /// </summary> /// <param name="worksheet">the worksheet in need of formulas</param> /// <param name="row">the first row of the section</param> protected void AdvanceToLastRow(ExcelWorksheet worksheet, ref int row) { row++; //the first cell has the key so it isnt empty, and would cause the skip to end immideatly SkipEmptyCells(worksheet, ref row, 1); //SkipEmptyCells leaves the row variable referencing the first non empty cell found, which //is at the start of the next section. We want it at the last cell of this section. row--; } /// <summary> /// Finds the lowest summary cell between the specified bottom and top row and in the specified column /// </summary> /// <param name="worksheet">the worksheet in need of formulas</param> /// <param name="bottomRow">the row we should start chacking at</param> /// <param name="topRow">the upper row limit that the formula range cannot go past</param> /// <param name="col">the column to look in</param> /// <returns>the row number of the summary cell found, or -1 if there is no summary cell</returns> protected virtual int FindSummaryCellRow(ExcelWorksheet worksheet, int bottomRow, int topRow, int col) { ExcelIterator iter = new ExcelIterator(worksheet, bottomRow, col); foreach (ExcelRange cell in iter.GetCells(ExcelIterator.SHIFT_UP, cell => cell.Start.Row < topRow)) { if (isSummaryCell(cell)) { return cell.Start.Row; } } return -1; //no summary cell found } /// <summary> /// Checks if the specified cell is the first cell to come after the formula range. In this implemenatation, a cell is /// the last in the range if it contains a top border. This is just a utility method that can be used passed to the method /// SetSummaryCellDefenition. /// </summary> /// <param name="cell">the cell being checked</param> /// <returns>true if the cell is the last cell in the formula range, and false otherwise</returns> protected bool HasTopBorder(ExcelRange cell) { var border = cell.Style.Border; return !border.Top.Style.Equals(ExcelBorderStyle.None) && border.Bottom.Style.Equals(ExcelBorderStyle.None); } } }
(ns clj-site.core (:use clj-site.util markdown.core hiccup.core) (:gen-class)) (def ^:dynamic *separator* java.io.File/separatorChar) (def ^:dynamic *title-prefix* "#title:") (def ^:dynamic *layout-prefix* "#layout:") (defn- index-of [e coll] (first (keep-indexed #(if (= e %2) %1) coll))) (defn- add-separator [name] (if (= (last name) *separator*) name (str name *separator*))) (defn- make-html-file-name [file-name & [num]] "Creates html-file name from the markdown file name" (let [n (if (or (nil? num) (zero? num)) "" (inc num)) fn (cond (.endsWith file-name ".md") (.substring file-name 0 (- (count file-name) 3)) (.endsWith file-name ".clj") (.substring file-name 0 (- (count file-name) 4)) :else file-name)] (str fn n ".html"))) (defn print-usage [] "Just prints the usage." (println "clj-site <dir-name>")) (defn- parse-raw-post [lines file-name] "Tries to parse arbitrary markdown file" (let [l1 (first lines) l2 (second lines) cont (reduce str (next (next lines)))] (if-not (.startsWith l1 *title-prefix*) (throw (Exception. (str "No " *title-prefix* " in " file-name)))) (if-not (.startsWith l2 *layout-prefix*) (throw (Exception. (str "No " *layout-prefix* " in " file-name)))) {:title (.trim (.substring l1 (count *title-prefix*))) :file-name file-name :html-file-name (make-html-file-name file-name) :layout (.trim (.substring l2 (count *layout-prefix*))) :contents (md-to-html-string cont)} )) (defn- parse-raw-page [lines file-name] "Tries to parse arbitrary markdown file" (let [l1 (first lines) cont (reduce str (next (next lines)))] (if-not (.startsWith l1 *layout-prefix*) (throw (Exception. (str "No " *layout-prefix* " in " file-name)))) {:file-name file-name :html-file-name (make-html-file-name file-name) :layout (.trim (.substring l1 (count *layout-prefix*))) :contents (read-string cont)} )) (defn parse-post-file [file] "Tries to parse post markdown file. File name should contain date: YYYY-MM-DD-file-name.md" (let [file-name (.getName file) parts (.split file-name "-") file-date (str (first parts) "-" (second parts) "-" (nth parts 2)) lines (-> file clojure.java.io/reader line-seq)] (if (< (count lines) 3) (throw (Exception. (str "Too small post contents in " file-name)))) (assoc (parse-raw-post lines file-name) :file-date file-date) )) (defn parse-page-file [file] "Tries to parse page markdown file." (let [file-name (.getName file) lines (-> file clojure.java.io/reader line-seq)] (if (< (count lines) 2) (throw (Exception. (str "Too small page contents in " file-name)))) (parse-raw-page lines file-name))) (defn- find-previous-post [post posts-list] (let [i (index-of post posts-list)] (if (> (count posts-list) (inc i)) (nth posts-list (inc i)) nil))) (defn- find-next-post [post posts-list] (let [i (index-of post posts-list)] (if (zero? i) nil (nth posts-list (dec i))))) (defn generate-post [post cfg posts-list] "Generates post" (let [dir (:output-dir cfg) base-dir (:base-dir cfg) layouts-dir (:layouts-dir cfg) file-name (str base-dir dir (make-html-file-name (:file-name post))) layout-name (:layout post) layout (read-string (slurp (str base-dir layouts-dir layout-name ".clj"))) eval-data (concat '(do (use 'clj-site.util)) (list layout))] (binding [*config* cfg *post* post *post-prev* (find-previous-post post posts-list) *post-next* (find-next-post post posts-list)] (spit file-name (html (eval eval-data)))))) (defn contains-pagination? [code] (let [data (apply hash-set (flatten code))] (or (contains? data 'page-prev) (contains? data 'page-next) (contains? data 'page-posts) (contains? data 'page-num)))) (defn generate-page [page cfg pages-list posts-list] "Generates page" (let [paginated? (contains-pagination? (:contents page)) page-size (:page-size cfg) pages-count* (int (/ (count posts-list) page-size)) pages-count (if (> (count posts-list) (* page-size pages-count*)) (inc pages-count*) pages-count*) dir (:output-dir cfg) base-dir (:base-dir cfg) layouts-dir (:layouts-dir cfg) layout-name (:layout page) layout (read-string (slurp (str base-dir layouts-dir layout-name ".clj"))) eval-data (concat '(do (use 'clj-site.util)) (list layout))] (binding [*config* cfg *page* page] (if-not paginated? (spit (str base-dir dir (make-html-file-name (:file-name page))) (html (eval eval-data))) (doseq [page-num (range pages-count)] (binding [*page-prev* (if (> (dec pages-count) page-num) (make-html-file-name (:file-name page) (inc page-num))) *page-next* (if-not (zero? page-num) (make-html-file-name (:file-name page) (dec page-num))) *page-num* page-num *page-posts* (nth (doall (partition-all page-size posts-list)) page-num)] (spit (str base-dir dir (make-html-file-name (:file-name page) page-num)) (html (eval (eval eval-data)))))))))) (defn make-config [cfg dir-name] "Makes default config, applies user settings from file config.clj" {:url-base (or (:url-base cfg) "/") :page-size (or (:page-size cfg) 5) :posts-dir (add-separator (or (:posts-dir cfg) "posts")) :pages-dir (add-separator (or (:pages-dir cfg) "pages")) :layouts-dir (add-separator (or (:layouts-dir cfg) "layouts")) :output-dir (add-separator (or (:output-dir cfg) "output")) :base-dir dir-name}) (defn -main [ & [input-dir-name]] (if (nil? input-dir-name) (print-usage) (let [dir-name (add-separator input-dir-name) cfg (-> (str dir-name "config.clj") slurp read-string (make-config dir-name)) posts-files (filter (memfn isFile) (-> (str dir-name (:posts-dir cfg)) clojure.java.io/file file-seq)) posts-list (reverse (sort-by :file-name (doall (map parse-post-file posts-files)))) pages-files (filter (memfn isFile) (-> (str dir-name (:pages-dir cfg)) clojure.java.io/file file-seq)) pages-list (reverse (sort-by :file-name (doall (map parse-page-file pages-files))))] (dorun (map #(generate-page % cfg pages-list posts-list) pages-list)) (dorun (map #(generate-post % cfg posts-list) posts-list)))))
"use client"; import { useParams } from "next/navigation"; import { BsTwitter } from "react-icons/bs"; import { BiLogoInstagram } from "react-icons/bi"; import { BsFacebook } from "react-icons/bs"; import data from "../../../data"; import Image from "next/image"; import Link from "next/link"; const InstructorDetails = () => { const param = useParams(); const singleitem = data.length > 0 && data.filter((item) => item.id == param.instructorId); // console.log(singleitem[0].name); return ( <div className="text-text section-padding"> {singleitem.map((item) => ( <div key={item.id} className="flex flex-col md:flex-row justify-between gap-10 mx-5 sm:mx-16 space-y-5" > <div className="flex flex-col gap-5 justify-center md:ps-20 order-2 md:order-1"> <div className="text-3xl style-text">{item.name}</div> <div className="text-accent/70">{item.occupation} Expart</div> <div className="md:w-[45vw]">{item.occupationDetails}</div> <div className="flex gap-3 text-2xl"> <Link href={item.twiter} className="hover:text-accent duration-300" > <BsTwitter /> </Link> <Link href={item.instagram} className="hover:text-accent duration-300" > <BiLogoInstagram /> </Link> <Link href={item.facebook} className="hover:text-accent duration-300" > <BsFacebook /> </Link> </div> </div> <div className="h-[60vh] md:w-[40vw] w-full order-1 md:order-2"> <Image src={item.image} width="800" height="1200" className="w-full h-full object-scale-down" alt="bending-exercise" /> </div> </div> ))} </div> ); }; export default InstructorDetails;
// // ContentView.swift // WordScramble // // Created by Waihon Yew on 31/05/2021. // import SwiftUI struct ContentView: View { @State private var usedWords = [String]() @State private var rootWord = "" @State private var newWord = "" @State private var errorTitle = "" @State private var errorMessage = "" @State private var showingError = false @State private var score = 0 var body: some View { NavigationView { VStack { TextField("Enter your word", text: $newWord, onCommit: addNewWord) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() .autocapitalization(.none) List(usedWords, id: \.self) { Image(systemName: "\($0.count).circle") Text($0) } Text("Score: \(score)") .font(.title) } .navigationBarTitle(rootWord) .onAppear(perform: startGame) .alert(isPresented: $showingError) { Alert(title: Text(errorTitle), message: Text(errorMessage), dismissButton: .default(Text("OK"))) } .navigationBarItems(leading: Button("New Word") { startGame() }) } } func addNewWord() { // Lowercase and trim the word, to make sure we // don't add duplicate words with case differences let answer = newWord.lowercased().trimmingCharacters(in: .whitespacesAndNewlines) // Exit if the remaining string is empty guard answer.count > 0 else { return } guard isLongEnough(word: answer) else { wordError(title: "Word too short", message: "The minimum is three letters.") return } guard isNotStartWord(word: answer) else { wordError(title: "Word is the same as the start word", message: "Be more original.") return } guard isOriginal(word: answer) else { wordError(title: "Word used already", message: "Be more original.") return } guard isPossible(word: answer) else { wordError(title: "Word not possible", message: "You can't just make them up, you know!") return } guard isReal(word: answer) else { wordError(title: "Word not recognized", message: "That isn't a real word.") return } score += 1 + answer.count usedWords.insert(answer, at: 0) newWord = "" } func startGame() { // 1. Find the URL for start.txt in our app bundle if let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt") { // 2. Load start.txt into a string if let startWords = try? String(contentsOf: startWordsURL) { // 3. Split the string up into an array of strings, // splitting on line breaks let allWords = startWords.components(separatedBy: "\n") // 4. Pick one random word, or use "silkworm" as a // sensible default rootWord = allWords.randomElement() ?? "silkworm" // If we are here everything has worked, so we can exit return } } // IF we are *here* then there was a problem - // trigger a crash and report the error fatalError("Could not load start.txt from bundle.") } func isOriginal(word: String) -> Bool { !usedWords.contains(word) } func isPossible(word: String) -> Bool { // Create a variable copy of the root word var tempWord = rootWord // Loop over each letter of the user's input word for letter in word { // See if that letter exists in our copy if let pos = tempWord.firstIndex(of: letter) { // If it does, we remove it from the copy // (so it can't be used twice), then continue tempWord.remove(at: pos) } else { return false } } // If we make it to the end of the user's word // successfully then the word is good return true } func isReal(word: String) -> Bool { let checker = UITextChecker() let range = NSRange(location: 0, length: word.utf16.count) let misspelledRange = checker.rangeOfMisspelledWord( in: word, range: range, startingAt: 0, wrap: false, language: "en") return misspelledRange.location == NSNotFound } func isLongEnough(word: String) -> Bool { return word.count >= 3 } func isNotStartWord(word: String) -> Bool { return word != rootWord } func wordError(title: String, message: String) { errorTitle = title errorMessage = message showingError = true } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
<script setup> import { computed, onMounted, ref } from 'vue'; import { useRouter } from 'vue-router'; import { useToast } from "vue-toastification"; import { useUserStore } from './stores/user.js'; import { useTransactionsStore } from './stores/transactions.js' const toast = useToast(); const userStore = useUserStore(); const transactionsStore = useTransactionsStore(); userStore.restoreToken(); const router = useRouter(); const user = ref(userStore.user); const editMode = ref(false); const payment_type = ref(["VCARD", "payment12", "payment13", "payment15", "payment132"]); const selectedTransaction = ref(''); const selectedUser = ref(''); const amount = ref(0); const sendMoney = ref(transactionsStore.sendMoney); const goToSendMoney = () => { router.push({ name: 'SendMoney' , props: { admin: true } }); }; onMounted (async () => { await transactionsStore.loadTransactions(user.value.phone_number); }); const lastTransaction = computed(()=>( transactionsStore.lastTransaction) ); </script> <template> <div class="home"> <div class="main-content"> <h1 class="greeting">Hello, <span class="username">{{ user && user.name ? user.name : 'Guest' }}</span></h1> <div class="section"> <div class="balance-section"> <h2 class="section-title">Balance</h2> <h3 class="balance text-primary">{{ user.balance }}</h3> </div> </div> <div class="section"> <div class="transaction-section"> <h3 class="section-title">Last Transaction</h3> <h3 class="transaction text-primary" v-if="lastTransaction"> {{ lastTransaction ? `${lastTransaction.type === 'C' ? '+' : '-'}${lastTransaction.value}€ ${lastTransaction.type === 'C' ? 'from' : 'to'} ${lastTransaction.payment_reference}` : '' }} </h3> </div> </div> <div class="section send-money-section"> <h4 class="section-title">Send Money</h4> <button class="btn btn-primary" @click="goToSendMoney">Send</button> </div> </div> </div> </template> <style scoped> .send-money-section { display: flex; justify-content: space-between; align-items: center; } .home { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #62beff; } .balance-section { display: flex; justify-content: space-between; align-items: center; } .transaction-section { display: flex; justify-content: space-between; align-items: center; } .main-content { padding: 20px; background-color: #fff; border-radius: 10px; box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1); max-width: 800px; width: 100%; } .main-content:hover { transform: scale(1.01); } .greeting { color: #2c3e50; margin-bottom: 20px; font-size: 1.5em; text-align: center; animation: fadeIn 2s; } .username { color: #3498db; font-weight: bold; } .section { margin-bottom: 20px; padding: 20px; border-radius: 5px; background-color: #e9e8e8; box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.05); transition: all 0.3s ease-in-out; } .section:hover { transform: translateY(-5px); box-shadow: 0px 10px 20px rgba(0, 0, 0, 0.1); } .section-title { color: #7f8c8d; font-size: 1.2em; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 1px; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } body { background-color: #62beff; margin: 0; padding: 0; height: 100vh; } </style>
# TCP Server Side import socket # Get IP Address of host Dynamically print(socket.gethostname()) #hostname print(socket.gethostbyname(socket.gethostname())) #ip of the given hostname #ip_address = ("123.144.199.10",12224) port_num = 12224 # Create a server side socket using IPV4 (AF_INET) and TCP (SOCK_STREAM) server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Bind our new socket to a tuple (IP Address, Port Address) server_socket.bind((socket.gethostbyname(socket.gethostname()),port_num)) #Put socket into listening mode to listen for any possible connections server_socket.listen() #Listen forever to accept ANY connection while True: # Accept every single connection and store two pieces of information client_socket, client_address = server_socket.accept() print(type(client_socket)) print(client_socket) print(type(client_address)) print(client_address) print(f"Connected to {client_address}\n") #Send a message to client that just connected # NOTE: Message has to be encoded and send as bytes object, can't # just send strings client_socket.send("You are Connected!!!!".encode("utf-8")) # close connection server_socket.close() break
# 9-3 求不同形态二叉树 # 题目描述: 在众多的数据结构中,二叉树是一种特殊而重要的结构,有着广泛的应用。二叉树或者是一个结点,或者有且仅有一个结点为二叉树的根,其余结点被分成两个互不相交的子集,一个作为左子集,另一个作为右子集,每个子集又是一个二叉树。 遍历一棵二叉树就是按某条搜索路径巡访其中每个结点,使得每个结点均被访问一次,而且仅被访问一次。最常使用的有三种遍历的方式: - 前序遍历:若二叉树为空,则空操作;否则先访问根结点,接着前序遍历左子树,最后再前序遍历右子树。 - 中序遍历:若二叉树为空,则空操作;否则先中序遍历左子树,接着访问根结点,最后再前中遍历右子树。 - 后序遍历:若二叉树为空,则空操作;否则先后序遍历左子树,接着后序遍历右子树,最后再访问根结点。 例如下图所示的二叉树: ![file](/api/users/image?path=4262/images/1494856497148.jpg) 前序遍历的顺序是ABCD,中序遍历的顺序是CBAD,后序遍历的顺序是CBDA。 对一棵二叉树,如果给出前序遍历和中许遍历的结点访问顺序,那么后序遍历的顺序是唯一确定的,也很方便地求出来。但如果现在只知道前序遍历和后序遍历的顺序,中序遍历的顺序是不确定的,例如:前序遍历的顺序是ABCD,而后序遍历的顺序是CBDA,那么就有两课二叉树满足这样的顺序(见图(1)和图(2))。 给定前序遍历和后序遍历的顺序,求出总共有多少棵不同形态的二叉树满足这样的遍历顺序。 # 输入格式: 整个输入有两行,第一行给出前序遍历的访问顺序,第二行给出后序遍历的访问顺序。 二叉树的结点用一个大写字母表示,不会有两个结点标上相同字母。输入数据不包含空格,且保证至少有一棵二叉树符合要求。 # 输出格式: 输出一个整数,为符合要求的不同形态二叉树的数目。 # 样例输入: ``` ABCD CBDA ``` # 样例输出: ``` 2 ```
// // 25.TransitionBasic.swift // Jacob's SwiftUI Basic1 // // Created by Koo on 2023/04/10. // import SwiftUI struct TransitionBasic: View { //property @State var condition :Bool = false var body: some View { ZStack(alignment: .bottom) { VStack { Button { withAnimation(.easeInOut) { condition.toggle() } } label: { Text("Button") .font(.title) } Spacer() } if condition { RoundedRectangle(cornerRadius: 40) .frame(height: UIScreen.main.bounds.height * 0.5) // 각 디바이스.메인.바운더리.높이 * 절반 .foregroundColor(Color.white) .shadow(color: Color.gray.opacity(0.4), radius: 15, y: -10) .opacity(condition ? 1.0 : 0.0) // 트렌지션 : move, opacity, scale, asymmetric // .transition(.move(edge: .bottom)) // .transition(.opacity) // .transition(.scale) .transition(.asymmetric( insertion: .move(edge: .leading), removal: .move(edge: .trailing)) ) } }.ignoresSafeArea(edges: .bottom) } } struct TransitionBasic_Previews: PreviewProvider { static var previews: some View { TransitionBasic() } }
/******************************************************************************* * CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps * * version 0.1 * * Copyright (C) 2009-2012, IGG Team, LSIIT, University of Strasbourg * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation; either version 2.1 of the License, or (at your * * option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * * * Web site: http://cgogn.unistra.fr/ * * Contact information: cgogn@unistra.fr * * * *******************************************************************************/ #ifndef __TRANSFO__H__ #define __TRANSFO__H__ #include "Geometry/matrix.h" #include <cmath> namespace CGoGN { namespace Geom { /** * Apply a scale to matrix * @param sx scale in x axis * @param sy scale in y axis * @param sz scale in z axis * @param mat current matrix */ template <typename T> void scale(T sx, T sy, T sz, Matrix<4,4,T>& mat); /** * Apply a translation to matrix * @param tx scale in x axis * @param ty scale in y axis * @param tz scale in z axis * @param mat current matrix */ template <typename T> void translate(T tx, T ty, T tz, Matrix<4,4,T>& mat); /** * Apply a rotation around Z axis to matrix * @param angle angle of rotation in radian * @param mat current matrix */ template <typename T> void rotateZ(T angle, Matrix<4,4,T>& mat); /** * Apply a rotation around Y axis to matrix * @param angle angle of rotation in radian * @param mat current matrix */ template <typename T> void rotateY(T angle, Matrix<4,4,T>& mat); /** * Apply a rotation around X axis to matrix * @param angle angle of rotation in radian * @param mat current matrix */ template <typename T> void rotateX(T angle, Matrix<4,4,T>& mat); /** * Apply a rotation around axis to matrix * @param axis_x axis x coord * @param axis_y axis y coord * @param axis_z axis z coord * @param angle angle of rotation in radian * @param mat current matrix */ template <typename T> void rotate(T axis_x, T axis_y, T axis_z, T angle, Matrix<4,4,T>& mat); template <typename T> void rotate(Vector<3,T>& axis, T angle, Matrix<4,4,T>& mat); /** * Apply a transformation (stored in matrix) to a 3D point * @param P the point to transfo * @param mat the transformation matrix */ template <typename T> Vector<3,T> transform(const Vector<3,T>& P, const Matrix<4,4,T>& mat); } // namespace Geom } // namespace CGoGN #include "Geometry/transfo.hpp" #endif
<?php namespace PartKeepr\ProjectAttachment; use PartKeepr\Util\Singleton, PartKeepr\Project\Project, PartKeepr\PartKeepr; class ProjectAttachmentManager extends Singleton { /** * Returns a list of project attachments * * @param int $start Start of the list, default 0 * @param int $limit Number of users to list, default 10 * @param string $sort The field to sort by, default "name" * @param string $dir The direction to sort (ASC or DESC), default ASC * @param string $filter The project id */ public function getProjectAttachments ($start = 0, $limit = 10, $sort = "name", $dir = "asc", $filter = "") { $qb = PartKeepr::getEM()->createQueryBuilder(); $qb->select("st")->from("PartKeepr\Project\ProjectAttachment","st") ->leftJoin('st.project', "fp"); if ($filter != "") { $project = Project::loadById($filter); $qb = $qb->where("st.project = :project"); $qb->setParameter("project", $project); } if ($limit > -1) { $qb->setMaxResults($limit); $qb->setFirstResult($start); } $qb->orderBy("st.".$sort, $dir); $query = $qb->getQuery(); $result = $query->getResult(); $totalQueryBuilder = PartKeepr::getEM()->createQueryBuilder(); $totalQueryBuilder->select("COUNT(st.id)")->from("PartKeepr\Project\ProjectAttachment","st"); if ($filter != "") { $totalQueryBuilder = $totalQueryBuilder->where("st.project = :project"); $totalQueryBuilder->setParameter("project", $project); } $totalQuery = $totalQueryBuilder->getQuery(); $aData = array(); foreach ($result as $item) { $aData[] = $item->serialize(); } return array("data" => $aData, "totalCount" => $totalQuery->getSingleScalarResult()); } /** * Returns a project attachment by id * @param int $id The project attachment id */ public function getProjectAttachment ($id) { return ProjectAttachment::loadById($id); } }
'use client'; import useQueryParams from '@hooks/useQueryParams'; import type { ITVDetails } from '@app/types/tv-types'; import { Button } from '@ui/button'; import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue, } from '@ui/select'; import { ArrowDownUp, Loader } from 'lucide-react'; import { useTransition } from 'react'; interface EpisodeFilterProps { series: ITVDetails; } interface SeasonFilter { season?: string | undefined; sort: 'asc' | 'desc'; } export default function EpisodeFilter({ series }: EpisodeFilterProps) { const { urlSearchParams, appendQueryParams } = useQueryParams<SeasonFilter>(); const [isLoading, startTransition] = useTransition(); const sorted = urlSearchParams.get('sort') || 'asc'; const onSortChange = () => { startTransition(() => { appendQueryParams({ sort: sorted === 'desc' ? 'asc' : 'desc' }); }); }; const selectedValue = urlSearchParams.get('season') || undefined; const onValueChange = (newValue: string) => { startTransition(() => { appendQueryParams({ season: newValue }); }); }; return ( <section className='flex items-center justify-between gap-2 rounded-md border px-2 py-1'> <div className='flex flex-grow items-center justify-between gap-4 overflow-auto px-2 py-1 sm:justify-start'> <Select value={selectedValue} onValueChange={onValueChange} disabled={isLoading} > <SelectTrigger className='w-[160px] truncate'> <SelectValue placeholder='Season' /> </SelectTrigger> <SelectContent> <SelectGroup> {series.seasons.map((season) => ( <SelectItem key={season.id} value={season.season_number.toString()} > {season.name} </SelectItem> ))} </SelectGroup> </SelectContent> </Select> <h2>OR</h2> <Select value={selectedValue} onValueChange={onValueChange} disabled={isLoading} > <SelectTrigger className='w-[160px] truncate'> <SelectValue placeholder='Year' /> </SelectTrigger> <SelectContent> <SelectGroup> {series.seasons.map((season) => ( <SelectItem key={season.id} value={season.season_number.toString()} > {new Date(season.air_date).getFullYear()} </SelectItem> ))} </SelectGroup> </SelectContent> </Select> </div> <div className='mx-2 hidden sm:inline-block'> <Button size='icon' variant='outline' aria-label='episode filter' onClick={onSortChange}> {isLoading ? ( <Loader className='h-5 w-5 animate-spin' /> ) : ( <ArrowDownUp className='h-5 w-5' /> )} </Button> </div> </section> ); }
# tb-auto-sign-up 百度贴吧自动签到 本项目使用linux服务器的定时任务+Python实现百度贴吧每日自动签到,并将签到报告发送到邮箱 #### 克隆本项目: ```bash https://github.com/SodiumNya/tb-auto-sign-up.git ``` #### 也许你需要安装依赖, 那么本项目应该仅需要以下三个库: ```bash pip install requests pip install yagmail pip install BeautifulSoup4 ``` #### 其他问题可尝试自己解决或联系我sodiumnya@gmail.com #### 依赖没有问题后,接下来你可以按照以下步骤操作: #### 在scrpit.py中做如下修改: 1. 在myCookies中填入你的**cookie** : ![e27f6a725375cfd4388ac978663fa94a.png](https://i.miji.bid/2024/02/26/e27f6a725375cfd4388ac978663fa94a.png) 2. 将**邮箱地址、授权码、host** 修改为真实的**邮箱地址、授权码、host**: ![e9e4d28e31faeb4191bfa7b0316fc1fe.png](https://i.miji.bid/2024/02/26/e9e4d28e31faeb4191bfa7b0316fc1fe.png) 3. 将要接收签到报告的邮箱填入**email_to**, 这是一个**list**,你可以添加多个,或仅保留一个: ![4a76986d1a3b2c5f1420e2c979f4c84f.png](https://i.miji.bid/2024/02/26/4a76986d1a3b2c5f1420e2c979f4c84f.png) #### 完成以上步骤之后, 你需要让它定时执行, 方式有很多,可以自行研究 #### 我的实现方式是在linux云服务器上使用定时任务 #### 如果和我一样,那么这是一个实现参考: 1. 将本项目放到你的云服务器的某个文件夹下,如: **/root/python-project/** 2. 在云服务器的某个位置编写一个脚本文件,用来执行本项目,脚本内容可参考: ```bas #!/bin/bash # 生成 0 到 59 之间的随机数作为等待时间 random_seconds=$((RANDOM % 3600)) # 等待随机秒数 sleep $random_seconds # 执行 贴吧签到项目的 main.py 文件, 签到 python3 /root/tb-auto-sign-up/main.py ``` 你可以直接复制到你的bash脚本文件中 3. 创建好脚本文件后,在云服务器的命令行中以此输入以下命令: 确保之前新建的脚本文件有执行权限(注意把/root/bash/tb-auto-sign-up.sh换位你自己的脚本路径): ```bash chmod +x /root/bash/tb-auto-sign-up.sh ``` 编辑crontab文件,新建一个定时任务: ```bash crontab -e ``` 在编辑器中添加一行,指定任务的执行时间和要运行的脚本(vim 不知道如何操作请自行百度): ```bash 0 6 * * * /root/bash/tb-auto-sign-up.sh ``` 保存并退出后, 若命令没有输入错误,那么cron将会在每天早上6点执行脚本,而脚本会在六点的某个随机时间点执行签到操作. 4. 完成以上步骤后,就能实现百度贴吧自动签到. 如果遇到任何问题,可以联系我sodiumnya@gmail.com或者提出issue. ​
// Copyright 2023 RisingWave Labs // // 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. use std::sync::Arc; use futures::{pin_mut, StreamExt}; use futures_async_stream::try_stream; use crate::executor::error::StreamExecutorError; use crate::executor::{ExecutorInfo, Message, MessageStream}; /// Streams wrapped by `epoch_check` will check whether the first message received is a barrier, and /// the epoch in the barriers are monotonically increasing. #[try_stream(ok = Message, error = StreamExecutorError)] pub async fn epoch_check(info: Arc<ExecutorInfo>, input: impl MessageStream) { // Epoch number recorded from last barrier message. let mut last_epoch = None; pin_mut!(input); while let Some(message) = input.next().await { let message = message?; if let Message::Barrier(b) = &message { let new_epoch = b.epoch.curr; let stale = last_epoch .map(|last_epoch| last_epoch > new_epoch) .unwrap_or(false); if stale { panic!( "epoch check failed on {}: last epoch is {:?}, while the epoch of incoming barrier is {}.\nstale barrier: {:?}", info.identity, last_epoch, new_epoch, b ); } if let Some(last_epoch) = last_epoch && !b.is_with_stop_mutation() { assert_eq!( b.epoch.prev, last_epoch, "missing barrier: last barrier's epoch = {}, while current barrier prev={} curr={}", last_epoch, b.epoch.prev, b.epoch.curr ); } last_epoch = Some(new_epoch); } else if last_epoch.is_none() && !info.identity.contains("BatchQuery") { panic!( "epoch check failed on {}: the first message must be a barrier", info.identity ) } yield message; } } #[cfg(test)] mod tests { use assert_matches::assert_matches; use futures::{pin_mut, StreamExt}; use risingwave_common::array::StreamChunk; use super::*; use crate::executor::test_utils::MockSource; use crate::executor::Executor; #[tokio::test] async fn test_epoch_ok() { let (mut tx, source) = MockSource::channel(Default::default(), vec![]); tx.push_barrier(1, false); tx.push_chunk(StreamChunk::default()); tx.push_barrier(2, false); tx.push_barrier(3, false); tx.push_barrier(4, false); let checked = epoch_check(source.info().into(), source.boxed().execute()); pin_mut!(checked); assert_matches!(checked.next().await.unwrap().unwrap(), Message::Barrier(b) if b.epoch.curr == 1); assert_matches!(checked.next().await.unwrap().unwrap(), Message::Chunk(_)); assert_matches!(checked.next().await.unwrap().unwrap(), Message::Barrier(b) if b.epoch.curr == 2); assert_matches!(checked.next().await.unwrap().unwrap(), Message::Barrier(b) if b.epoch.curr == 3); assert_matches!(checked.next().await.unwrap().unwrap(), Message::Barrier(b) if b.epoch.curr == 4); } #[should_panic] #[tokio::test] async fn test_epoch_bad() { let (mut tx, source) = MockSource::channel(Default::default(), vec![]); tx.push_barrier(100, false); tx.push_chunk(StreamChunk::default()); tx.push_barrier(514, false); tx.push_barrier(514, false); tx.push_barrier(114, false); let checked = epoch_check(source.info().into(), source.boxed().execute()); pin_mut!(checked); assert_matches!(checked.next().await.unwrap().unwrap(), Message::Barrier(b) if b.epoch.curr == 100); assert_matches!(checked.next().await.unwrap().unwrap(), Message::Chunk(_)); assert_matches!(checked.next().await.unwrap().unwrap(), Message::Barrier(b) if b.epoch.curr == 514); assert_matches!(checked.next().await.unwrap().unwrap(), Message::Barrier(b) if b.epoch.curr == 514); checked.next().await.unwrap().unwrap(); // should panic } #[should_panic] #[tokio::test] async fn test_epoch_first_not_barrier() { let (mut tx, source) = MockSource::channel(Default::default(), vec![]); tx.push_chunk(StreamChunk::default()); tx.push_barrier(114, false); let checked = epoch_check(source.info().into(), source.boxed().execute()); pin_mut!(checked); checked.next().await.unwrap().unwrap(); // should panic } #[tokio::test] async fn test_empty() { let (_, mut source) = MockSource::channel(Default::default(), vec![]); source = source.stop_on_finish(false); let checked = epoch_check(source.info().into(), source.boxed().execute()); pin_mut!(checked); assert!(checked.next().await.transpose().unwrap().is_none()); } }
<nav class="navbar navbar-expand navbar-light fixed-top bg-white shadow"> <div class="container d-flex justify-content-between align-items-center"> <a routerLink=""> <img src="https://img.freepik.com/premium-vector/abstract-vector-construction-dimensional-low-poly-design-background-innovation-technologies-abstract-illustration_570429-5713.jpg?w=740" width="70" height="70" alt=""> </a> <div class="align-self-center navbar-collapse d-lg-flex justify-content-lg-between" id="templatemo_main_nav"> <div class="flex-fill"> <ul class="nav navbar-nav d-flex justify-content-between mx-lg-auto"> <li class="nav-item"> <a class="nav-link" routerLink=""><b> Danh Mục Sách </b></a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/about"><b> Về Chúng Tôi </b></a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/cart/detail"><b> Lịch Sử Mua Hàng </b></a> </li> <li class="nav-item" *ngIf="['ROLE_ADMIN'].indexOf(role)!==-1" [hidden]="!isLoggedIn"> <a class="nav-link" routerLink="/statistic"><b> Thống Kê </b></a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/contact"><b> Liên Hệ </b></a> </li> </ul> </div> <div class="navbar align-self-center d-flex"> <a class="nav-icon position-relative" routerLink="/cart"> <i class="fab fa-opencart fa-lg me-2" matTooltip="Giỏ Hàng"></i> <span class="position-absolute pb-3 top-0 left-100 translate-middle badge rounded-pill" style="color: #F44336">{{totalQuantity}}</span> </a> <button class="nav-icon position-relative text-decoration-none" style="border: none; background: none"> <button mat-button [matMenuTriggerFor]="belowMenu"> <i [hidden]="isLoggedIn" class="fas fa-user fa-lg"></i> <i [hidden]="!isLoggedIn" class="fas fa-user-check fa-lg"></i> </button> <mat-menu #belowMenu="matMenu" yPosition="below"> <a routerLink="/register" class="text-decoration-none" [hidden]="isLoggedIn"> <button mat-menu-item><i class="fas fa-user-plus"></i> &nbsp; Đăng Kí</button> </a> <a routerLink="/login" class="text-decoration-none" [hidden]="isLoggedIn"> <button mat-menu-item><i class="fas fa-user"></i> &nbsp; Đăng Nhập</button> </a> <a routerLink="/view-info" class="text-decoration-none" [hidden]="!isLoggedIn"> <button mat-menu-item><i class="fas fa-user-cog"></i> &nbsp; Thông Tin Tài Khoản</button> </a> <a routerLink="/login" class="text-decoration-none" [hidden]="!isLoggedIn"> <button mat-menu-item (click)="logOut()" style="color: #F44336"><i class="fas fa-user-times"></i> &nbsp; Đăng Xuất </button> </a> </mat-menu> <span class="position-absolute top-0 left-100 translate-middle badge rounded-pill text-dark" [hidden]="!isLoggedIn">{{username}}</span> <span class="position-absolute top-0 left-100 translate-middle badge rounded-pill text-dark" [hidden]="isLoggedIn" matTooltip="Chưa Đăng Nhập"></span> </button> </div> </div> <button *ngIf="['ROLE_ADMIN', 'ROLE_USER'].indexOf(role)!==-1;" [hidden]="!isLoggedIn" mat-mini-fab color="primary" id="myBtn2" [routerLink]="['/chat/login']"> <mat-icon>messenger</mat-icon> </button> </div> </nav>
#include<bits/stdc++.h> using namespace std; const int N = 1e5+8; vector<int> adj[N]; bool visited [N]; void dfs(int u ) { visited[u] = true; cout<<u<<" "; for(int v : adj[u]) { if(visited[v]) continue; dfs(v); } } int main() { int n, m ; cin >> n >> m ; for(int i = 1;i<=m; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } // for(int i = 1; i<=n; i++) // { // cout<<"List "<<i<<": "; // for(int v : adj[i]) // { // cout<<v<<" "; // } // cout<<endl; // } dfs(1); return 0; } /* #include<bits/stdc++.h> using namespace std; const int N = 1e6+7; vector<int> adj[N]; bool visited[N]; void printAdjacency(int n) { for(int i = 1; i<=n; i++) { cout<<"List "<<i<<": "; for(int v : adj[i]) { cout<<v <<" "; } cout<<endl; } } void dfs(int u) { visited[u] = true; cout<<u<<" "; for(int v : adj[u]) { if(visited[v] == false) { dfs(v); } } } int main() { int n, m ; cin >> n >> m; for(int i =1; i<=m ; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } printAdjacency(n); cout<<endl; cout<<"DFS Traversal : "<<endl; dfs(1); return 0; } */