text stringlengths 184 4.48M |
|---|
import type { Preset } from "unocss";
import { camelCase, kebabCase } from "./utils";
import { easing } from "./easing";
import type { EasePresetOptions } from "./types";
/**
* Creates a preset that maps easing function names to transition timing functions.
* 创建一个预设,将缓动函数名称映射到过渡时间函数。
*
* @param {EasePresetOptions} [options] - Options for configuring the easing preset.
* 用于配置缓动预设的选项。
* @returns {Preset} Returns a UnoCSS preset object.
* 返回 UnoCSS 预设对象。
*/
export const presetEase = ({ prefix = "ease-" }: EasePresetOptions = {}): Preset<any> => {
const easingFunctionNames = Object.keys(easing)
.map(name => kebabCase(name))
.join("|");
const easingFunctionSelector = `${prefix}(${easingFunctionNames})`;
return {
name: "unocss-preset-ease",
rules: [
[
new RegExp(`^${easingFunctionSelector}$`),
([, name]) => ({
"transition-timing-function": easing[camelCase(name) as keyof typeof easing],
}),
],
],
autocomplete: {
templates: [easingFunctionSelector],
},
};
};
export * from "./types";
export * from "./easing";
export default presetEase; |
<!DOCTYPE html>
<html>
<head>
<title>VACSEN: A Visualization Approach for Noise Awareness in Quantum Computing</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="./style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="main">
<div class="container content_resize">
<div class="row">
<div class="span10">
<div id="header">
<h1 style="padding-left:0; color:black;font-size:30px"><i>VACSEN</i>: A Visualization Approach for Noise Awareness in Quantum Computing</h1>
<h4 style="padding-left: 0" class="authors">
<a href="https://shaolun-ruan.com/" target="_blank">Shaolun Ruan</a>
, <a href="http://yong-wang.org/" target="_blank">Yong Wang</a>
, <a href="https://www.gmu.edu/profiles/wjiang8" target="_blank">Weiwen Jiang</a>
, <a href="https://yingmao.github.io/" target="_blank">Ying Mao</a>
, <a href="https://www.kent.edu/cs/qiang-guan" target="_blank">Qiang Guan</a>
</h4>
</div>
<br>
<div id="figures">
<img alt="" src="./images/teaser.png" class="img-polaroid img-responsive img-thumbnail" style="margin-left: 7%" width="80%">
<p style="text-align:justify; margin-top: 20px;">VACSEN facilitates noise awareness in quantum computing via novel and intuitive visualizations. Computer Evolution View (A) allows the assessment for all quantum computers based on a temporal analysis for multiple performance metrics. Circuit Filtering View (B) supports the filtering for the potential optimal compiled circuits. Circuit Comparison View (C) supports the in-depth comparison regarding the performance of qubits or quantum gates and corresponding usages. Fidelity Comparison View (E) shows the fidelity distribution of the execution result. Probability Distribution View (F) visualizes the results of state distribution for users in quantum computing.</p>
</div>
<div id="description">
<h2>Description</h2>
<p style="text-align:justify">Quantum computing has submitted considerable public attention due to its exponential speedup over classical computing. Despite its advantages, today's quantum computers intrinsically suffer from noise and are error-prone. To guarantee the high fidelity of the execution result of a quantum algorithm, it is crucial to inform users of the noises of the used quantum computer and the compiled physical circuits. However, an intuitive and systematic way to make users aware of the quantum computing noise is still missing. In this paper, we fill the gap by proposing a novel visualization approach to achieve noise-aware quantum computing. It provides a holistic picture of the noise of quantum computing through multiple interactively coordinated views: a computer evolution view with a circuit-like design overviews the temporal evolution of the noises of different quantum computers, a compiled circuit filtering view facilitates quick filtering of multiple compiled physical circuits for the same quantum algorithm, and a circuit comparison view with a coupled bar chart enable detailed comparison of the filtered compiled circuits. We extensively evaluate the performance of VACSEN through two case studies on quantum algorithms of different scales and in-depth interviews with 12 quantum computing users. The results demonstrate the effectiveness and usability of VACSEN in achieving noise-aware quantum computing.</p>
</div>
<div id="materials">
<h2>System</h2>
<p style="text-align:justify">You can access the online visual analytics system via this <a href="https://vacsensystem.github.io/" class="link" target="_blank">link</a>.
</br>
<span style="color: blue; font-style: italic;">(A monitor with a resolution of 1920 x 1080 is preferred.)</span>
</p>
</div>
<div id="materials">
<h2>Value</h2>
<p style="text-align:justify">
Our tutorial proposal "<span style="font-style: italic">QuantumFlow+VACSEN: A Visualization System for Quantum Neural Networks on Noisy Quantum Devices</span>", introducing the usage of VACSEN, has been accepted by the <i>IEEE Quantum Week 2022</i> (the IEEE International Conference on Quantum Computing and Engineering), which is a top-tier international conference in quantum computing that will be held in Broomfield, Colorado, U.S. from September 18th to 23rd, 2022. The program can be found via this <a href="https://qce.quantum.ieee.org/2022/tutorials-program/" class="link" target="_blank">link</a>.</p>
</div>
<div id="materials">
<h2>Dataset</h2>
<p style="text-align:justify"><code>IBMQ_calibration_data</code> includes the calibration data of 11 quantum computers on the IBM Quantum platform from July 2021 to January 2022. The dataset contains multiple hardware properties (e.g., decoherence time, error rate, frequency, gate time, etc.) of each quantum computer. The download link is available in the <code>Materials > Dataset</code> below. </p>
</div>
<div id="materials">
<h2>Materials</h2>
<div class="materials">
<a href="./docs/VIS22_Quantum_Computing_Vis (17).pdf" class="link" target="_blank">PDF</a>
<!-- |<a href="https://github.com/VIDA-Lab/VACSEN" class="link" target="_blank">Github</a> -->
|<a href="./docs/Appendix.pdf" class="link" target="_blank">Appendix</a>
| <a href="https://drive.google.com/file/d/1gbJi9VH785uV5sK6MiLgKdD6_Gysdf1p/view?usp=sharing" class="link" target="_blank">Dataset</a>
<!-- | <a href="" class="link" target="_blank">Tutorial</a> -->
</div>
</div>
<div id="publication">
<h2>Publication</h2>
<p>Shaolun Ruan, Yong Wang, Weiwen Jiang, Ying Mao, and Qiang Guan. 2022. VACSEN: A Visualization Approach for Noise Awareness in Quantum Computing. IEEE Transactions on Visualization and Computer Graphics (Proceedings of IEEE VIS 2022). To Appear.</p>
</div>
<div id="acknowledgements">
<h2>Acknowledgements</h2>
<p>This research was supported by the Lee Kong Chian Fellowship awarded to Yong Wang by Singapore Management University.
Qiang Guan is supported by US National Science Foundation CCF-2217021 and IBM quantum hub at NC State.
We would like to thank the participants in our user interviews and anonymous reviewers for their feedback.
</p>
</div>
</br>
<div>
<h2>Video</h2>
<p style="text-align:justify">The demo video of VACSEN:</p>
<iframe src="https://player.vimeo.com/video/697869065?h=58687c75c8"style="width: 960px;height: 480px;" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
<div class="footer">
<div class="footer_resize">
<p class="lf">Copyright © 2022 Shaolun Ruan. All Rights Reserved.</p>
</div>
<div class="clr"></div>
</div>
</div>
</body>
</html> |
"""Test the Advent of Code Runner User object"""
# System libraries
from datetime import datetime
# Pytest libraries
import pytest
# Advent of Code Runner libraries
from aoc_runner.exceptions import AocValueError, DeadTokenError
from aoc_runner.user import User
class Timeout(BaseException):
"""Simulate a timeout exception"""
#
# User class __init__ tests
#
@pytest.mark.user
@pytest.mark.unit
def test_user_init(
valid_user,
user_http_get,
): # noqa
"""Test the base __init__ method of the User class with valid input."""
user = User(user_info=valid_user)
assert user.user_id == f"{valid_user.login_source}.{valid_user.aoc_id}"
assert user.user_name == valid_user.user_name
assert user.aoc_id == valid_user.aoc_id
assert user.login_source == valid_user.login_source
assert user.last_updated == valid_user.last_updated
assert user.token == valid_user.token
assert user.user_info == valid_user
@pytest.mark.user
@pytest.mark.unit
def test_user_init_bad_parameter(
valid_user,
user_http_get,
):
"""Test the base __init__ method of the User class with bad input."""
with pytest.raises(AocValueError) as excp:
_ = User(user_info=valid_user.token)
excp_msg = str(excp.value)
assert excp_msg.startswith("User_info parameter must be of UserInfo type not")
#
# Test property getters
#
@pytest.mark.user
@pytest.mark.unit
def test_user_getter_aoc_id(
user_http_get,
runner_users_dir,
valid_user,
):
"""Test the User.aoc_id property returns the expected value"""
user = User(user_info=valid_user)
assert user.aoc_id == valid_user.aoc_id
@pytest.mark.user
@pytest.mark.unit
def test_user_getter_last_updated(
user_http_get,
runner_users_dir,
valid_user,
):
"""Test the User.last_updated property returns the expected value"""
user = User(user_info=valid_user)
assert user.last_updated == valid_user.last_updated
@pytest.mark.user
@pytest.mark.unit
def test_user_getter_login_source(
user_http_get,
runner_users_dir,
valid_user,
):
"""Test the User.login_source property returns the expected value"""
user = User(user_info=valid_user)
assert user.login_source == valid_user.login_source
@pytest.mark.user
@pytest.mark.unit
def test_user_getter_memo(
user_http_get,
runner_users_dir,
valid_user,
):
"""Test the User.memo property returns the expected value"""
user = User(user_info=valid_user)
assert user.memo.parent == runner_users_dir
@pytest.mark.user
@pytest.mark.unit
def test_user_getter_token(
user_http_get,
runner_users_dir,
valid_user,
):
"""Test the User.token property returns the expected value"""
user = User(user_info=valid_user)
assert user.token == valid_user.token
@pytest.mark.user
@pytest.mark.unit
def test_user_getter_user_id(
user_http_get,
runner_users_dir,
valid_user,
):
"""Test the User.user_id property returns the expected value"""
user = User(user_info=valid_user)
assert user.user_id == f"{valid_user.login_source}.{valid_user.aoc_id}"
#
# Test property setters
#
@pytest.mark.user
@pytest.mark.unit
def test_user_setter_last_updated(
valid_user,
user_http_get,
):
"""Test the User.token setter method of the User class."""
last_updated = datetime.now()
user = User(user_info=valid_user)
user.last_updated = last_updated
assert user.last_updated == last_updated
@pytest.mark.user
@pytest.mark.unit
def test_user_setter_last_updated_bad_parameter(
valid_user,
user_http_get,
):
"""Test the user.token setter method of the User class."""
user = User(user_info=valid_user)
with pytest.raises(AocValueError) as excp:
user.last_updated = valid_user
excp_str = str(excp.value)
assert excp_str.startswith("token parameter must be of str type not")
@pytest.mark.user
@pytest.mark.unit
def test_user_setter_token(
valid_user,
user_http_get,
):
"""Test the user.token setter method of the User class."""
token = f"Updated-token-{datetime.now().isoformat()}"
last_updated = valid_user.last_updated
user = User(user_info=valid_user)
user.token = token
assert user.token == token
assert user.last_updated > last_updated
@pytest.mark.user
@pytest.mark.unit
def test_user_setter_token_bad_parameter(
valid_user,
user_http_get,
):
"""Test the user.token setter method of the User class."""
user = User(user_info=valid_user)
with pytest.raises(AocValueError) as excp:
user.token = valid_user
excp_str = str(excp.value)
assert excp_str.startswith("token parameter must be of str type not")
#
# Test from_token class method
#
@pytest.mark.user
@pytest.mark.unit
def test_user_from_token(
real_token,
user_http_get,
):
"""Test the user.from_token method with valid Advent of Code users"""
aoc_id, token = real_token
user = User.from_token(token=token)
assert user.aoc_id == aoc_id
@pytest.mark.user
@pytest.mark.unit
def test_user_from_token_expired(
expired_token,
user_http_get,
):
"""Test the user.from_token method with expired Advent of Code users"""
token = expired_token
with pytest.raises(DeadTokenError) as excp:
_ = User.from_token(token=token)
excp_str = str(excp.value)
assert excp_str.startswith("The auth token ...")
@pytest.mark.user
@pytest.mark.unit
def test_user_from_token_bad_parameter(
real_token,
user_http_get,
):
"""Test the user.from_token method with expired Advent of Code users"""
with pytest.raises(AocValueError) as excp:
_ = User.from_token(token=real_token)
excp_str = str(excp.value)
assert excp_str.startswith("token parameter must be of str type not") |
import React from "react";
import { motion, AnimatePresence } from "framer-motion";
import menu from "../assets/HambMenu.svg";
import logoMob from "../assets/LogoMob.svg";
import { useState } from "react";
import { CircleClose } from "./Icons/Close";
const Navbar = () => {
const [isOpen, setIsOpen] = useState(true);
return (
<div className="bg-white w-full relative z-50 border-b-2 border-dark_blue border-solid">
<motion.nav
initial={{
x: -100,
opacity: 0,
}}
animate={{
x: 0,
opacity: 1,
}}
whileTap={{ border: 1 }}
whileInView={{ opacity: 1 }}
transition={{ type: "spring", duration: 3, delay: 0.5, bounce: 0.7 }}
viewport={{ ones: true }}
className="md:gap-16 relative lg:mx-auto z-50 font-oswald lg:max-w-[1200px] md:max-w-[655px] min-h-[72px] justify-between px-4 md:mx-0 md:justify-center gap-24 lg:min-h-[112px] items-center flex lg:justify-between"
>
<img src={logoMob} alt="" className="lg:min-w-[305px]" />
<div className="md:hidden lg:hidden">
<img
onClick={() => setIsOpen(!isOpen)}
src={menu}
alt="Navigation Menu"
/>
</div>
<AnimatePresence>
{!isOpen && (
<motion.div className="md:hidden popup flex justify-center fixed z-50 -top-1">
<motion.div
initial={{
x: 200,
opacity: 0,
}}
animate={{
x: 0,
opacity: 1,
}}
whileInView={{ opacity: 1 }}
transition={{ duration: 0.4 }}
viewport={{ ones: true }}
exit={{ x: 300, opacity: 0 }}
className=""
>
<motion.ul
initial={{
x: 200,
opacity: 0,
}}
animate={{
x: 0,
opacity: 1,
}}
whileInView={{ opacity: 1 }}
transition={{ duration: 0.5, delay: 0.4, type: "spring", bounce: 0.3 }}
viewport={{ ones: true }}
exit={{ x: 300, opacity: 0 }}
className=" pb-[42px] flex justify-center items-center flex-col stroke pop-list bg-white text-center px-[158px] font-bold text-2xl font-oswald ">
<CircleClose
onClick={() => setIsOpen(!isOpen)}
className="close_popUp relative left-32 top-4"
/>
<li>
<a href="#hero">Home</a>
</li>
<li>
<a href="#about">About</a>
</li>
<li>
<a href="#skill">Skill</a>
</li>
<li>
<a href="#portfolio">Project</a>
</li>
<li className="pb-[42px]">
<a href="#">Contact</a>
</li>
<a target='_blank' href="/Vladyslav_Nechytailo_-_Junior_Developer.pdf">
<button className="btn1 hover:shadow-none ease-in duration-75 md:block font-bold text-xl bg-bright_yellow py-3 px-8">
Resume
</button>
</a>
</motion.ul>
</motion.div>
</motion.div>
)}
</AnimatePresence>
<div className="hidden md:flex lg:flex lg:justify-between md:items-center gap-12">
<ul className="stroke flex justify-center gap-6 font-bold text-sm lg:text-xl">
<li>
<a href="#hero">Home</a>
</li>
<li>
<a href="#about">About</a>
</li>
<li>
<a href="#skills">Skill</a>
</li>
<li>
<a href="#portfolio">Projects</a>
</li>
<li>
<a href="#contact">Contact</a>
</li>
</ul>
<a target='_blank' href="/Vladyslav_Nechytailo_-_Junior_Developer.pdf">
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
className="btn1 hidden hover:shadow-none ease-in duration-75 md:block lg:block font-bold text-sm lg:text-lg bg-bright_yellow py-2.5 px-6 lg:py-4 lg:px-9"
>
Resume
</motion.button>
</a>
</div>
</motion.nav>
</div>
);
};
export default Navbar; |
<!DOCTYPE html>
<!--
This is a starter template page. Use this page to start your new project from
scratch. This page gets rid of all links and provides the needed markup only.
-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Panel</title>
<link rel="stylesheet" href="/css/app.css">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper" id="app">
<!-- Navbar -->
<nav class="main-header navbar navbar-expand navbar-white navbar-light">
<!-- Left navbar links -->
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
</li>
</ul>
<!-- Right navbar links -->
<ul class="navbar-nav ml-auto">
<!-- Navbar Search -->
<li class="nav-item">
<div class="navbar-search-block">
<div class="input-group input-group-sm">
<input class="form-control form-control-navbar" @keyup="searchit" v-model="search" type="search" placeholder="Search" aria-label="Search">
<div class="input-group-append">
<button class="btn btn-navbar" type="button" @click="searchit">
<i class="fas fa-search"></i>
</button>
<button class="btn btn-navbar" @click="clearsearch" type="button" data-widget="navbar-search">
<i class="fas fa-times"></i>
</button>
</div>
</div>
</div>
</li>
</ul>
</nav>
<!-- /.navbar -->
<!-- Main Sidebar Container -->
<aside class="main-sidebar sidebar-dark-primary elevation-4">
<!-- Brand Logo -->
<a href="/users" class="brand-link">
<img src="./img/Logo.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8">
<span class="brand-text font-weight-light">ProjectLara</span>
</a>
<!-- Sidebar -->
<div class="sidebar">
<!-- Sidebar user panel (optional) -->
<div class="user-panel mt-3 pb-3 mb-3 d-flex">
<div class="image">
<img src="./img/profile.png" class="img-circle elevation-2" alt="User Image">
</div>
<div class="info">
<a href="#" class="d-block">@auth {{ Auth::user()->name }} @endauth</a>
</div>
</div>
<!-- Sidebar Menu -->
<nav class="mt-2">
<ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
<!-- Add icons to the links using the .nav-icon class
with font-awesome or any other icon font library -->
@can('isAdmin')
<li class="nav-item">
<router-link to="/Internship" class="nav-link">
<i class="nav-icon fas fa-tachometer-alt text-blue"></i>
<p>
Dashboard
</p>
</router-link>
</li>
<li class="nav-item menu">
<router-link to="#" class="nav-link">
<i class="nav-icon fas fa-cog text-red"></i>
<p>
Management
<i class="right fas fa-angle-left"></i>
</p>
</router-link>
<ul class="nav nav-treeview">
<li class="nav-item">
<router-link to="/users" class="nav-link">
<i class="fas fa-users nav-icon"></i>
<p>Users</p>
</router-link>
</li>
<li class="nav-item">
<router-link to="/Internship" class="nav-link">
<i class="fas fa-circle nav-icon"></i>
<p>Internships</p>
</router-link>
</li>
</ul>
</li>
@endcan
<li class="nav-item">
<router-link to="/profile" class="nav-link">
<i class="nav-icon fas fa-user text-yellow"></i>
<p>
Profile
</p>
</router-link>
</li>
<li class="nav-item">
<a href="/index" class="nav-link">
<i class="nav-icon fas fa-tachometer-alt text-blue"></i>
<p>
Quit
</p>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
<i class="nav-icon fas fa-power-off text-teal"></i>
<p>
{{ __('Logout') }}
</p>
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
@csrf
</form>
</li>
</ul>
</nav>
<!-- /.sidebar-menu -->
</div>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper" id="app">
<!-- Main content -->
<div class="content">
<div class="container-fluid">
<router-view></router-view>
<!-- set progressbar -->
<vue-progress-bar></vue-progress-bar>
</div><!-- /.container-fluid -->
</div>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
<div class="p-3">
<h5>Title</h5>
<p>Sidebar content</p>
</div>
</aside>
<!-- /.control-sidebar -->
<!-- Main Footer -->
<footer class="main-footer">
<!-- To the right -->
<div class="float-right d-none d-sm-inline">
Anything you want
</div>
<!-- Default to the left -->
<strong>Copyright © 2021 <a href="#">4th year Project</a>.</strong> All rights reserved. by me
</footer>
</div>
<!-- ./wrapper -->
<!-- REQUIRED SCRIPTS -->
@auth
<script>
window.user=@json(auth()->user())
</script>
@endauth
<script src="/js/app.js"></script>
</body>
</html> |
<?php
namespace App\User\Domain\Models;
use Illuminate\Database\Eloquent\Model;
class UserAddress extends Model
{
protected $guarded = [
'id'
];
protected $table = 'user_addresses';
protected $casts = [
'is_primary' => 'boolean'
];
public function user()
{
return $this->belongsTo('App\User\Domain\Models\User');
}
public function city()
{
return $this->belongsTo('App\Location\Domain\Models\City');
}
public function state()
{
return $this->belongsTo('App\Location\Domain\Models\State');
}
public function country()
{
return $this->belongsTo('App\Location\Domain\Models\Country');
}
public function orders()
{
return $this->hasMany('App\Order\Domain\Models\Order');
}
} |
import { main_url } from "../../constants";
import { useQuery } from "react-query";
import axios from "axios";
export const useFetch = (url: string, queryKey: string, token?: string) => {
const {
data,
dataUpdatedAt,
error,
errorUpdatedAt,
failureCount,
isError,
isFetched,
isFetchedAfterMount,
isFetching,
isIdle,
isLoading,
isLoadingError,
isPlaceholderData,
isPreviousData,
isRefetchError,
isRefetching,
isStale,
isSuccess,
refetch,
remove,
status,
} = useQuery(queryKey, async() => {
return axios
.get(`${main_url}${url}`, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
timeout: 30000,
})
.then((res) => res.data);
}, {
onError: (err) => {
console.log(err);
}
});
return {
data,
dataUpdatedAt,
error,
errorUpdatedAt,
failureCount,
isError,
isFetched,
isFetchedAfterMount,
isFetching,
isIdle,
isLoading,
isLoadingError,
isPlaceholderData,
isPreviousData,
isRefetchError,
isRefetching,
isStale,
isSuccess,
refetch,
remove,
status,
};
}; |
import React, {useContext, useEffect, useState} from "react";
import PropTypes from "prop-types";
import tagMetadata from "components/settings/tags/tag.metadata";
import adminTagsActions from "../../settings/tags/admin-tags-actions";
import Model from "../../../core/data_model/model";
import LoadingDialog from "../status_notifications/loading";
import {AuthContext} from "contexts/AuthContext";
import StandaloneMultiSelectInput from "components/common/inputs/multi_select/StandaloneMultiSelectInput";
// TODO: Don't use this besides in pipeline summary editors. It's a temp component until I can wire up my new ones
function TempTagManagerInput({ label, data, setDataFunction, disabled, filter, placeholderText, allowCreate, groupBy}) {
const { getAccessToken } = useContext(AuthContext);
const [tagOptions, setTagOptions] = useState([]);
const [componentLoading, setComponentLoading] = useState(true);
useEffect(() => {
loadData();
}, []);
const loadData = async () => {
setComponentLoading(true);
await getTags();
removeOldTags();
setComponentLoading(false);
};
const removeOldTags = () => {
let newTags = [];
data.map((tag, index) => {
if (tag["type"] != null && tag["type"] !== "" && tag["value"] != null && tag["value"] !== "")
{
let tagOption = {type: tag["type"], value: tag["value"]};
newTags.push(tagOption);
}
});
setDataFunction(newTags);
};
const getTags = async () => {
const response = await adminTagsActions.getAllTags(getAccessToken);
let tags = response.data.data;
if (tags && tags.length > 0)
{
loadTagOptions(tags);
}
};
const saveNewTag = async (newTagDto) => {
let createTagResponse = await adminTagsActions.create(newTagDto, getAccessToken);
};
const loadTagOptions = (tags) => {
let currentOptions = [];
tags.map((tag, index) => {
if (tag["type"] != null && tag["type"] !== "" && tag["value"] != null && tag["value"] !== "")
{
let tagOption = {type: tag["type"], value: tag["value"]};
currentOptions.push(tagOption);
}
});
setTagOptions(currentOptions);
};
const getExistingTag = (newTag) => {
return tagOptions.find(tag => tag.type === "pipeline" && tag.value === newTag);
};
const tagAlreadySelected = (newTag) => {
let currentValues = data;
return currentValues != null && currentValues.length !== 0 && currentValues.find(tag => tag.type === "pipeline" && tag.value === newTag) != null;
};
const handleCreate = async (newValue) => {
let currentValues = data;
let existingTag = getExistingTag(newValue);
if (existingTag != null)
{
let tagSelected = tagAlreadySelected(newValue);
if (!tagSelected)
{
currentValues.push(existingTag);
setDataFunction(currentValues);
}
return;
}
newValue = newValue.trim();
newValue = newValue.replaceAll(' ', '-');
newValue = newValue.replace(/[^A-Za-z0-9-.]/gi, '');
newValue = newValue.toLowerCase();
let currentOptions = [...tagOptions];
let newTag = {type: "pipeline", value: newValue, active: true, configuration: {}};
let newTagOption = {type: "pipeline", value: newValue};
let newTagDto = new Model(newTag, tagMetadata, true);
await saveNewTag(newTagDto);
currentValues.push(newTagOption);
currentOptions.push(newTagOption);
setTagOptions(currentOptions);
setDataFunction(currentValues);
};
return (
<div className="form-group m-2">
<label><span>{label}</span></label>
<StandaloneMultiSelectInput
selectOptions={[...tagOptions]}
textField={data => data["type"] + ": " + data["value"]}
filter={filter}
allowCreate={allowCreate}
manualEntry={true}
groupBy={groupBy}
busy={componentLoading}
createOptionFunction={handleCreate}
value={[...data]}
placeholderText={placeholderText}
disabled={disabled}
setDataFunction={setDataFunction}
/>
</div>
);
}
TempTagManagerInput.propTypes = {
label: PropTypes.string,
selectOptions: PropTypes.array,
data: PropTypes.object,
fieldName: PropTypes.string,
groupBy: PropTypes.string,
filter: PropTypes.string,
type: PropTypes.string,
placeholderText: PropTypes.string,
setDataFunction: PropTypes.func,
allowCreate: PropTypes.string,
disabled: PropTypes.bool
};
TempTagManagerInput.defaultProps = {
allowCreate: "onFilter",
disabled: false,
groupBy: "type"
};
export default TempTagManagerInput; |
from typing import List
from typing import Optional
import arrow
import re
from abc import ABC
from abc import abstractmethod
from discord import ChannelType
from discord import Message
from discord.ext import commands
from langchain.chat_models.openai import ChatOpenAI
from langchain.schema import ChatMessage
from llm_task_handler.chatroom import ChatroomConversation
from llm_task_handler.chatroom import ChatroomMessage
from llm_task_handler.dispatch import TaskDispatcher
def get_max_tokens(model_name: str):
if model_name == 'gpt-4':
max_tokens = 8192
elif model_name == 'gpt-4-32k':
max_tokens = 32768
elif model_name == 'gpt-3.5-turbo':
max_tokens = 4096
elif model_name == 'gpt-3.5-turbo-16k':
max_tokens = 16384
return max_tokens
class LLMDiscordBot(commands.Bot, ABC):
@abstractmethod
def bot_token(self) -> str:
"""Discord bot token"""
def prompt_task_dispatcher(self, user_id: str) -> TaskDispatcher:
return TaskDispatcher([])
def conversation_task_dispatcher(self, user_id: str) -> TaskDispatcher:
return TaskDispatcher([])
def monitored_channels(self) -> list[int]:
return []
def fully_readable_channels(self) -> list[int]:
return self.monitored_channels()
def conversation_llm_model(self, llm_convo_context: list[ChatMessage]) -> ChatOpenAI:
used_tokens = sum([ChatOpenAI().get_num_tokens(m.content) for m in llm_convo_context])
completion_tokens = 400
required_tokens = used_tokens + completion_tokens
if required_tokens < 2000:
model_name = 'gpt-4'
elif required_tokens < get_max_tokens('gpt-3.5-turbo'):
model_name = 'gpt-3.5-turbo'
else:
model_name = 'gpt-3.5-turbo-16k'
return ChatOpenAI( # type: ignore
model_name=model_name,
temperature=0,
max_tokens=completion_tokens,
)
def conversation_completion_tokens(self) -> int:
return 400
def conversation_system_prompt(self) -> str:
return '''
You are ChatGPT, a large language model trained by OpenAI.
You are in a Discord chatroom.
Carefully heed the user's instructions.
'''
def is_authorized_to_read_message(self, message: Message) -> bool:
if message.author == self.user:
return True
elif message.channel.id in self.fully_readable_channels():
return True
elif message.channel.type == ChannelType.private:
return True
else:
return self.user in message.mentions
def should_reply_to_message(self, message: Message) -> bool:
if message.author == self.user:
# Never reply to self, to avoid infinite loops
return False
elif message.channel.type == ChannelType.private:
return True
elif self.user in message.mentions:
return True
elif all([
message.channel.id in self.monitored_channels(),
not message.mentions,
not message.author.bot,
]):
return True
else:
return False
async def on_message(self, message: Message) -> None:
if not self.is_authorized_to_read_message(message):
return
if not self.should_reply_to_message(message):
return
async with message.channel.typing():
reply = await self.reply(message)
if reply:
await message.channel.send(reply)
async def reply(self, message: Message) -> Optional[str]:
return await self.reply_to_message(message) or await self.reply_to_conversation(message)
async def reply_to_message(self, message: Message) -> Optional[str]:
return await self.prompt_task_dispatcher(str(message.author.id)).reply(
self.remove_ai_mention(message.content),
progress_reply_func=lambda reply: message.channel.send(reply),
)
async def reply_to_conversation(self, message: Message) -> Optional[str]:
llm_convo_context = await self.get_llm_convo_context(latest_message=message)
chat_model = self.conversation_llm_model(llm_convo_context)
convo = ChatroomConversation(
messages=llm_convo_context,
ai_user_id=str(self.user.id), # type: ignore
max_tokens=get_max_tokens(chat_model.model_name) - self.conversation_completion_tokens()
)
return await self.conversation_task_dispatcher(str(message.author.id)).reply(
convo.to_yaml(),
progress_reply_func=lambda reply: message.channel.send(reply),
)
async def get_llm_convo_context(
self,
latest_message: Message,
) -> list[ChatroomMessage]:
# Messages are ordered newest to oldest
discord_messages = await self.preceding_messages(latest_message)
chatroom_messages: List[ChatroomMessage] = []
for msg in discord_messages:
reply_reference = msg.reference.resolved if msg.reference and type(msg.reference.resolved) is Message else None
chatroom_msg = ChatroomMessage(role=str(msg.author.id), content=msg.content, timestamp=int(msg.created_at.timestamp()))
if reply_reference:
chatroom_messages += [ChatMessage(role=str(reply_reference.author.id), content=reply_reference.content)]
chatroom_messages += [chatroom_msg]
return chatroom_messages
async def preceding_messages(self, latest_message: Message) -> List[Message]:
messages = [
msg async for msg in latest_message.channel.history(
after=arrow.now().shift(hours=-24).datetime,
oldest_first=False,
limit=20,
)
if self.is_authorized_to_read_message(msg)
]
if latest_message.channel.type == ChannelType.public_thread:
thread_start_msg = await latest_message.channel.parent.fetch_message(latest_message.channel.id) # type: ignore
messages += [thread_start_msg]
return messages
def remove_ai_mention(self, msg_content: str) -> str:
return re.sub(rf'<@{self.user.id}> *', '', msg_content) # type: ignore |
import React from 'react';
import { IconButton, IconButtonProps } from '@mui/material';
import { Icon } from '../Icon';
export type CloseButtonProps = IconButtonProps & {
/** Hidden label for the button to present to screen readers.
*
* Defaults to `Close`
*/
label?: string;
};
export function CloseButton({ label, ...props }: CloseButtonProps) {
return (
<IconButton aria-label={label} color="inherit" size="small" {...props}>
<Icon name="xmark" />
</IconButton>
);
} |
import { AuthBindings } from "@refinedev/core";
import axios from "axios";
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
const API_URL = import.meta.env.VITE_API_URL + "/api/UserAuth";
export const TOKEN_KEY = import.meta.env.VITE_TOKEN_KEY + "";
export const authProvider: AuthBindings = {
login: async ({ username, email, password }) => {
// ---
try{
const response = await axios.post(API_URL + "/Login", {email,password})
const accessToken = response?.data?.token;
if(accessToken)
{
localStorage.setItem(TOKEN_KEY, accessToken);
localStorage.setItem("user", JSON.stringify(response?.data?.user));
return {
success: true,
redirectTo: "/",
};
}
else{
return {
success: false,
error: {
message: "Login Error",
name: "Invalid email or password",
},
};
}
}
catch(error){
return {
success: false,
error: {
message: "Login Error",
name: "Invalid email or password",
},
};
}
},
logout: async () => {
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem('user');
return {
success: true,
redirectTo: "/login",
};
},
check: async () => {
const token = localStorage.getItem(TOKEN_KEY);
if (token) {
return {
authenticated: true,
};
}
return {
authenticated: false,
redirectTo: "/login",
};
},
getPermissions: async () => {
const user = JSON.parse((localStorage.getItem("user") + ""));
if(user!=null) {
return [user.role];
}
return null;
},
getIdentity: async () => {
const user = JSON.parse((localStorage.getItem("user") + ""));
if(user!=null) {
return user;
}
return null;
},
onError: async (error) => {
console.error(error);
return { error };
},
register: async ({ email,password, firstName,lastName,middleName,iin , department,image}) => {
const returnUrl = window.location.origin + "/login";
try {
const response = await axios.post(API_URL + "/Register", {email,password, firstName,lastName,middleName,iin ,returnUrl, department,image});
if(!response?.data?.succeeded){
return {
success:false,
error: {
name: "Cannot register user. Make sure you password format is correct",
message: "Register Error"
}
}
}
toast.success('Account created. You will get confirmation email.', {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "colored",
});
return {
success: true,
redirectTo:"/login"
};
}
catch(error) {
return {
success: false,
error: {
name: "Cannot register user",
message: "Error, Make sure your format is correct or account already exists"
}
}
}
},
// ---
forgotPassword: async ({ email }) => {
try {
await axios.post(API_URL + "/PasswordForgot", {email});
toast.success('Password reset token were sent to your Email', {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "colored",
});
return {success: true, redirectTo:"/update-password"};
}
catch(error)
{
return {
success: false,
error: {
name: "Forgot Password Error",
message: "Invalid email",
},
};
}
},
updatePassword: async ({ email,password, token}) => {
try {
const response = await axios.post(API_URL + "/PasswordReset", {email, password,token});
toast.success('Your password update', {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "colored",
});
return {success: true, redirectTo:"/login"};
}
catch(error:any){
return {
success: false,
error: {
name: "Update Password Error",
message: error.response.data.error,
},
};
}
},
}; |
package lexer
import (
"fmt"
"regexp"
)
type regexPattern struct {
regex *regexp.Regexp
handler regexHandler
}
type Lexer struct {
patterns []regexPattern
Tokens []Token
source string
pos int
lineMap [][2]int // used for tracking error locations
}
func Tokenize(source string) *Lexer {
lex := createLexer(source)
lex.buildLineMap()
for !lex.at_eof() {
matched := false
for _, pattern := range lex.patterns {
loc := pattern.regex.FindStringIndex(lex.remainder())
if loc != nil && loc[0] == 0 {
pattern.handler(lex, pattern.regex)
matched = true
break // Exit the loop after the first match
}
}
if !matched {
panic(fmt.Sprintf("lexer error: unrecognized token near '%v'", lex.remainder()))
}
}
lex.push(NewToken(EOF, "EOF", lex.pos))
return lex
}
func (lex *Lexer) advanceN(n int) {
lex.pos += n
}
func (lex *Lexer) remainder() string {
return lex.source[lex.pos:]
}
func (lex *Lexer) push(token Token) {
lex.Tokens = append(lex.Tokens, token)
}
func (lex *Lexer) at_eof() bool {
return lex.pos >= len(lex.source)
}
func createLexer(source string) *Lexer {
return &Lexer{
pos: 0,
source: source,
Tokens: make([]Token, 0),
patterns: []regexPattern{
{regexp.MustCompile(`\s+`), skipHandler},
{regexp.MustCompile(`\/\/.*`), commentHandler},
{regexp.MustCompile(`"[^"]*"`), stringHandler},
{regexp.MustCompile(`[0-9]+(\.[0-9]+)?`), numberHandler},
{regexp.MustCompile(`[a-zA-Z_][a-zA-Z0-9_]*`), symbolHandler},
{regexp.MustCompile(`\[`), defaultHandler(OPEN_BRACKET, "[")},
{regexp.MustCompile(`\]`), defaultHandler(CLOSE_BRACKET, "]")},
{regexp.MustCompile(`\{`), defaultHandler(OPEN_CURLY, "{")},
{regexp.MustCompile(`\}`), defaultHandler(CLOSE_CURLY, "}")},
{regexp.MustCompile(`\(`), defaultHandler(OPEN_PAREN, "(")},
{regexp.MustCompile(`\)`), defaultHandler(CLOSE_PAREN, ")")},
{regexp.MustCompile(`==`), defaultHandler(EQUALS, "==")},
{regexp.MustCompile(`!=`), defaultHandler(NOT_EQUALS, "!=")},
{regexp.MustCompile(`=`), defaultHandler(ASSIGNMENT, "=")},
{regexp.MustCompile(`!`), defaultHandler(NOT, "!")},
{regexp.MustCompile(`<=`), defaultHandler(LESS_EQUALS, "<=")},
{regexp.MustCompile(`<`), defaultHandler(LESS, "<")},
{regexp.MustCompile(`>=`), defaultHandler(GREATER_EQUALS, ">=")},
{regexp.MustCompile(`>`), defaultHandler(GREATER, ">")},
{regexp.MustCompile(`\|\|`), defaultHandler(OR, "||")},
{regexp.MustCompile(`&&`), defaultHandler(AND, "&&")},
{regexp.MustCompile(`\.\.`), defaultHandler(DOT_DOT, "..")},
{regexp.MustCompile(`\.`), defaultHandler(DOT, ".")},
{regexp.MustCompile(`;`), defaultHandler(SEMICOLON, ";")},
{regexp.MustCompile(`:`), defaultHandler(COLON, ":")},
{regexp.MustCompile(`\?`), defaultHandler(QUESTION, "?")},
{regexp.MustCompile(`,`), defaultHandler(COMMA, ",")},
{regexp.MustCompile(`\+\+`), defaultHandler(PLUS_PLUS, "++")},
{regexp.MustCompile(`--`), defaultHandler(MINUS_MINUS, "--")},
{regexp.MustCompile(`\+=`), defaultHandler(PLUS_EQUALS, "+=")},
{regexp.MustCompile(`-=`), defaultHandler(MINUS_EQUALS, "-=")},
{regexp.MustCompile(`\+`), defaultHandler(PLUS, "+")},
{regexp.MustCompile(`-`), defaultHandler(MINUS, "-")},
{regexp.MustCompile(`/`), defaultHandler(SLASH, "/")},
{regexp.MustCompile(`\*`), defaultHandler(STAR, "*")},
{regexp.MustCompile(`%`), defaultHandler(PERCENT, "%")},
},
}
}
type regexHandler func(lex *Lexer, regex *regexp.Regexp)
// Created a default handler which will simply create a token with the matched contents. This handler is used with most simple tokens.
func defaultHandler(kind TokenKind, value string) regexHandler {
return func(lex *Lexer, _ *regexp.Regexp) {
lex.advanceN(len(value))
lex.push(NewToken(kind, value, lex.pos))
}
}
func stringHandler(lex *Lexer, regex *regexp.Regexp) {
match := regex.FindStringIndex(lex.remainder())
stringLiteral := lex.remainder()[match[0]:match[1]]
lex.push(NewToken(STRING, stringLiteral[1:len(stringLiteral)-1], lex.pos))
lex.advanceN(len(stringLiteral))
}
func numberHandler(lex *Lexer, regex *regexp.Regexp) {
match := regex.FindString(lex.remainder())
lex.push(NewToken(NUMBER, match, lex.pos))
lex.advanceN(len(match))
}
func symbolHandler(lex *Lexer, regex *regexp.Regexp) {
match := regex.FindString(lex.remainder())
if kind, found := keywords[match]; found {
lex.push(NewToken(kind, match, lex.pos))
} else {
lex.push(NewToken(IDENTIFIER, match, lex.pos))
}
lex.advanceN(len(match))
}
func skipHandler(lex *Lexer, regex *regexp.Regexp) {
match := regex.FindStringIndex(lex.remainder())
lex.advanceN(match[1])
}
func commentHandler(lex *Lexer, regex *regexp.Regexp) {
match := regex.FindStringIndex(lex.remainder())
if match != nil {
// Advance past the entire comment.
lex.advanceN(match[1])
}
} |
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="shortcut icon" href="../img/icons8-draw-32.png" type="image/x-icon">
</head>
<body>
<header>
<h1>
Curso de dibujo
</h1>
</header>
<h2>
Cuando el dibujo creativo supera al arte
</h2>
<article>
<h3>
Dibujo perceptual
</h3>
<p>
Este tipo de dibujo se realiza con el mundo real como referencia, es una representación del mundo tal cual lo ven nuestros ojos.
</p>
</article>
<hr>
<article>
<h3>
Dibujo creativo
</h3>
<p>
Este tipo de dibujo va más allá de lo que ven nuestros ojos. En este tipo de dibujo expresamos lo que entendemos o pensamos acerca del elemento dibujado, por lo que no hace falta representarlo tal cual es.
</p>
<p>
Lo anterior es una cualidad muy interesante del dibujo que debemos desarrollar. No basta con hacer un curso de dibujo, aprender la perspectiva u otros fundamentos y quedarnos solo con eso.
</p>
</article>
<hr>
<article>
<section>
<h3>
El dibujo como herramienta de comunicación
</h3>
<p>
El dibujo puede interpretarse o utilizarse como una herramienta de comunicación, y al hablar de comunicación tenemos que entender que tenemos dos grandes ramas, la comunicación interna y la comunicación externa.
</p>
</section>
<section>
<h4>
Comunicación interna
</h4>
<p>
Esta se utiliza para el desarrollo de ideas y conceptos. Un ejemplo de esto es un dibujo hecho por Le Corbusier (arquitecto suizo) donde utilizó una caracola como referencia para pasar a la proporción áurea y así terminar desarrollando el concepto de un edificio, como se puede ver en las siguientes imágenes. De esta forma Cobrusier usó el dibujo para hablar consigo mismo y desarrollar un concepto determinado.
</p>
<img src="../img/Comunicacion-interna-desarrollo-de-ideas-y-conceptos.png" alt="Ejemplo de desarrollo de concepto de un edificio a partir de una caracola por medio de la comunicación interna" title="Ejemplo de desarrollo de concepto de un edificio a partir de una caracola por medio de la comunicación interna">
<p>
Además, la comunicación interna también se utiliza para proyectos de formas y espacios, entonces, cuando nosotros estamos queriendo inventar por ejemplo, la arquitectura de un edificio, empezamos a dibujar lo que nosotros tenemos en la cabeza, pero no lo hacemos como una cualidad artística, es decir, no solo para presentarselo a alguien para que diga "qué lindo dibujo o edificio". Podemos ver un ejemplo de esto por medio de la siguiente imagen.
</p>
<img src="../img/Comunicacion-interna-proyectos-de-formas-y-espacios.png" alt="Ejemplo de proyectos de formas y espacios creados por medio de la comunicación interna" title="Ejemplo de proyectos de formas y espacios creados por medio de la comunicación interna">
<p>
De esta forma nosotros empezamos a dibujar para nosotros entender bien qué es lo que tenemos en la cabeza, y de esa forma poder ir haciendo cambios y desarrollar también lo que son las distintas etapas proyectuales de un objeto, de formas y espacios, por ejemplo, en arquitectura trabajamos con espacios y en diseño industrial trabajamos sobre formas principalmente. Sin embargo, otra gran cualidad de la comunicación es la comunicación externa.
</p>
</section>
<section>
<h4>
Comunicación externa
</h4>
<p>
Este tipo de comunicación hace referencia a la comunicación con otras personas. Una forma de comunicación externa es la expresión artísticas.
</p>
<p>
Un ejemplo puede ser un dibujo en el que no se vea el desarrollo de ideas determinadas, conceptos, formas o espacios. Puede ser una respresentación de algo que vemos en un momento determinado, para poder apreciarlo o compartirlo tiempo después. En la siguiente imagen podemos ver un dibujo realizado por Van Gogh, este simplemente es una expresión artística sin desarrollo de ideas, conceptos, formas o espacios, simplemente quiso representar lo que veía en ese momento en un papel para apreciarlo o compartirlo con otros luego, tal cual y como podemos verlo ahora muchos años después.
</p>
<img src="../img/Comunicacion-externa-expresion-artistica.png" alt="Dibujo de Van Gogh" title="Dibujo de Van Gogh">
<p>
Otra forma de comunicación externa es la expresión técnica, donde nosotoros hacemos uso seuper preciso del dibujo, es decir, dibujamos al milímetro o al centímetro para poder generar dibujos super precisos y pasarselos a otra persona, y que lo entienda exactamente como nosotros lo pensamos.
</p>
<p>
El dibujo de la expresión técnica o dibujo técnico nos permite poder ser super precisos para tener una comunicación muy eficiente con otras personas, y que entiendan exactamente lo que nosotros queriamos que entendiesen. En la siguiente imagen podemos ver un ejemplo de la expresión técnica o dibujo técnico.
</p>
<img src="../img/Comunicación externa-expresion-tecnica.png" alt="Ejemplo de dibujo o expresión técnica" title="Ejemplo de dibujo o expresión técnica">
<p>
Todos los tipos de dibujos mencionados anteriormente comparten fundamentos, ciertas bases o ciertas reglas. Por esta razón es importante entender las reglas del dibujo, porque si no, estaremos dibujando como lo hacían directamente en la edad de piedra.
</p>
<p>
Al entender las reglas del dibujo podremos comunicanos con otros ya sea de forma artística o técnica de manera efectiva.
</p>
</section>
</article>
<hr>
<article>
<h3>
Fundamentos del dibujo
</h3>
<p>
Estas son las reglas o bases que hacen que la construcción de un dibujo sea correcta.
</p>
</article>
<hr>
<article>
<section>
<h3>
Etapas del dibujo
</h3>
<p>
El dibujo posee distintas ettapas las cuales son necesarias para obtener un resultado óptimo, estas etapas son:
</p>
<ul>
<li>
El boceto
</li>
<li>
Las líneas
</li>
<li>
El valor
</li>
<li>
El color
</li>
</ul>
</section>
<section>
<h4>
El boceto
</h4>
<p>
El boceto es la etapa que nos permite construir la estructura de nuestro dibujo de una forma muy sencilla y muy rápida. En esta etapa estaremos haciendo la creación básica para poder empezar a posicionar lo que son las formas y para poder delimitar también lo que son los espacios dentro de nuestro dibujo.
</p>
<p>
Nosotros vamos a crear la composición, vamos a dar la escala, las proporciones, es decir, el boceto va a ser la base para que nosotros empecemos luego, arriba de este boceto, a construir las siguientes etapas de nuestro dibujo.
</p>
</section>
<section>
<h4>
Las líneas
</h4>
<p>
En esta etapa comenzamos a delimitar el boceto que teniamos de una forma más prolija. Esta etapa nos permite generar con distintos trazos la separación que tenemos entre forma y espacio, o entre objetos y espacio. De esa forma vamos a poder ir delimitando de una forma mucho más precisa, y vamos a poder marcar exactamente la forma que tienen los objetos dentro de nuestro dibujo.
</p>
</section>
<section>
<h4>
El valor
</h4>
<p>
En esta tercera etapa empezamos a marcar lo que son las diferencias entre las luces y las sombras, y de esa forma le vamos a poder dar un relieve o una tercera dimensión a nuestro dibujo.
</p>
<p>
Vamos a poder empezar a separar lo que son las partes más oscuras de las más claras, y gracias a esto podremos marcar el volumen adentro de nuestro dibujo.
</p>
<p>
Esto es una cuertión super importante que tenemos que manejar muy bien para poder crear dibujos precisos y que nos permitan a nosotros dar una sensación de relieve muy relevante.
</p>
</section>
<section>
<h4>
El color
</h4>
<p>
Esta etapa nos permite darle mucho más realismo al dibujo y vamos a ver que tiene un montón de cuestiones muy importantes a tener en cuenta a la hora de utilizar el color como por ejemplo, las combinaciones posibles o los distintos significados que tiene el color para nuestro dibujo.
</p>
<p>
Sin importar si estamos haciendo un dibujo perceptual o un dibujo creativo, lo que importa es que las bases del dibujo y las distintas etapas estarán funcionando de la misma forma para estos dos grandes mundos que tenemos dentro del dibujo.
</p>
<p>
Entendiendo las cuatro etapas mencionadas, vamos a poder crear dibujos de una forma estructurada, bien sencilla y que nos va a permitir llegar a un muy buen nivel en nuestras ilustraciones.
</p>
</section>
</article>
<hr>
<article>
<section>
<h3>
Sistemas espaciales
</h3>
<p>
Acá comenzaremos a hablar de cómo nosotros representamos un espacio en un papel. Para poder hacer esto, tenemos que entender bien lo que son los ejes X, Y y Z.
</p>
<p>
Para este fin abobrdaremos los conceptos de perspectiva, axonometría y planos. Estos son tres distintos recursos que tenemos para representar el espacio en un papel, entonces, para poder pasar el espacio al paperl tenemos que entender cómo trabajan los tres sistemas espaciales mencionados anteriormente.
</p>
<p>
Tenemos la posibilidad de dibujar el espacio en dos dimensiones (2D) o tres dimensiones (3D). Las diferencias son muy grandes ya que vamos a estar dibujando un objeto de forma plana o un objeto de forma tridimensional.
</p>
</section>
<section>
<h4>
Perspectiva
</h4>
<p>
En la parte 3D tenemos la posibilidad de dibujar en perspectiva, es decir, tal cual como nosotros vemos el mundo.
</p>
</section>
<section>
<h4>
Axonometría
</h4>
<p>
Por otro lado, en 3D también tenemos el sistema espacial de las axonometrías, que nos permitirá crear un objeto y poder construirlo en un espacio en tres dimensiones sin ninguna deformación infundadad por nuestro ojo.
</p>
<p>
Con este sistema podremos ver las distintas caras del elemento dibujado con sus verdaderas magnitudes, en la axonometría no estamos invlucrados y en la perspectiva si.
</p>
<p>
A continuación se presentan 3 conceptos de axonometría para dejar clara su definición.
</p>
<dl>
<dt>
<b>
Concepto 1 de axonometría
</b>
<dd>
Consiste en realizar cuerpos volumétricos sobre 3 ejes (X, Y, Z), estos tres ejes son líneas rectas unidas en un punto central. Los ejes pueden tener cualquier apertura, es decir, un ángulo, pero la suma de los tres ángulos debe ser igual a 360°, en otras palabras, un círculo.
</dd>
</dt>
<br>
<dt>
<b>
Concepto 2 de axonometría
</b>
<dd>
Es un sistema de representación gráfica que permite representar elementos geométricos o volúmenes en un plano, mediante proyección paralela o cilíndrica referida a tres ejes ortogonales (Todo a lo que se llama ortogonal, se refiere a lo que se encuentra a noventa grados y por consiguiente, a algo que es perpendicular y si nos queremos referir a lo que es la proyección ortogonal, es básicamente la unión de líneas paralelas sobre un plano), de tal forma que conserven sus proporciones en cada una de las tres direcciones: altura, anchura y longitud.
</dd>
</dt>
<br>
<dt>
<b>
Concepto 3 de axonometría
</b>
<dd>
Es un sistema de representación de un cuerpo en un plano mediante las proyecciones obtenidas según tres ejes. Axonometría significa medir a lo largo de ejes, este tipo de proyección muestras una imagen de un objeto según se ve desde una dirección oblicua con el fin de revelar información de más de un lado de un mismo objeto.
</dd>
</dt>
</dl>
</section>
<section>
<h4>
Plano
s o vistas
</h4>
Operaciones
<p>
<p>
</p>
En el mundo de las dos dimensiones (2D) vamos a ver lo que son los planos o las vistas. Este sistema espacial nos permite representar tanto la forma como el espacio de forma plana, es decir, sin ver ninguna de las medidas. No se ve la profundidad en este sistema espacial, solo vemos el alto y el ancho de los objetos.
</p>
</section>
<section>
<h4>
Conclusión de los sistemas espaciales
</h4>
<p>
Las perspectivas se relacionan con cómo nuestro ojo ve el mundo, sin embargo las axonometrías y los planos o las vistas están relacionados a cómo nuestra mente entiende lo que es una forma y un espacio. Las etapas del dibujo siempre estarán relacionadas a los distintos sistemas espaciales.
</p>
<p>
En la siguiente imagen podremos ver un ejemplo de planos o vistas, axonometría y perspectiva.
</p>
<img src="../img/3D-2D.png" alt="Ejemplos de planos, axonometrías y perspectiva" title="Ejemplos de planos, axonometrías y perspectiva">
</section>
</article>
<hr>
<article>
<section>
<h3>
Operaciones
</h3>
<p>
Las operaciones no están relacionadas con ningún sistema espacial o etapa del dibujo, a continuación mencionados algunas de las operaciones más comunes que se realizan en el dibujo:
</p>
<ul>
<li>
Transparentar
</li>
<li>
Cortar
</li>
<li>
Mover
</li>
<li>
Despierzar
</li>
<li>
Eliminar
</li>
</ul>
</section>
<section>
<h4>
Transparentar
</h4>
<p>
Esta operación nos permite mostrar otras cosas que en recursos como la fotografía no podríamos ver. Un ejemplo de transparentar se da cuando dibujamos la representación de una radiografía, a continuación se muestran algunas imágenes que desmuestran la operación transparentar.
</p>
<img src="../img/Transparentar.png" alt="Ejemplo de transparentar" title="Ejemplo de transparentar">
</section>
<section>
<h4>
Seccionar o cortar
</h4>
<p>
Esta operación consiste en representar un objeto como si tuviese un corte, para así mostrar más información del mismo, información que no podrías mostrarse sin cortar el objeto. Un ejemplo de esta operación de da cuando dibujamos una casa de dos pisos cortada a la mitad de forma horizontal para mostrar así todo lo que hay dentro de la casa en la planta baja. Entonces, con cortar realizamos un corte en el objeto para ver cómo está compuesto su interior, cortar también es llamada seccionar. En las siguientes imágenes podremos ver ejemplos de esta operación.
</p>
<img src="../img/Cortar-seccionar.png" alt="Ejemplo de seccionar/cortar" title="Ejemplo de seccionar/cortar">
</section>
<section>
<h4>
Reconstruir
</h4>
<p>
Esta operación nos permite reconstruir cierta información que queremos transmitir al observador. Un ejemplo de reconstruir se da cuando dibujamos el esqueleto de un animal y usamos una línea punteada para mostrar el contorno de la forma total del animal, es decir, su contorno como si tuviera los músculos y todo, en ese caso reconstruimos la información de la contextura del animal. Veremos un ejemplo en la siguiente imagen.
</p>
<img src="../img/Reconstruir.png" alt="Ejemplo de reconstruir" title="Ejemplo de reconstruir">
</section>
<section>
<h4>
Despiezar
</h4>
<p>
Esta operación muestra información de un objeto que no podríamos ver sin hacer el despiece. Un ejemplo sencillo de esta operación sería dibujar una hambuerguesa con sus ingredientes claramente separados. Así veríamos los elementos que conforman un objeto. Esta operación se puede hacer en los distintos ejes. A continuación se muestra un ejemplo de esta operación.
</p>
<img src="../img/Despiezar.png" alt="Ejemplo de despiezar" title="Ejemplo de despiezar">
</section>
<section>
<h4>
Eliminar
</h4>
<p>
Esta operación consiste en eliminar cierta información de un objeto para mostrar información que no sería posible mostrar sin la eliminación. Un ejemplo sencillo puede ser eliminar la fachada del sibujo de un edificio para así poder ver su estructura, sería como eliminar la piel del edificio. A continuación se muestra un ejemplo de esta operación.
</p>
<img src="../img/Eliminar.png" alt="Ejemplo de eliminar" title="Ejemplo de eliminar">
</section>
<section>
<h4>
Mover
</h4>
<p>
Esto nos permite mostrar información adicional de un objeto al mover alguna de sus partes. Un ejemplo de esto puede ser cortar una axonometría en dos partes iguales y mover una de las fracciones para ver qué hay dentro del edificio. Otro ejemplo puede ser el dibujo de un jugador de beisbol movido a cada una de las fases o posiciones desarrolladas al batear, de esa forma transmitiremos cada uno de los movimientos realizados por el jugador al batear. Entonces podemos mover las extremidades de un cuerpo humano para mostrar sus movimientos posibles, por ejemplo. A continuación se muestra un ejemplo de esta operación.
</p>
<img src="../img/Mover.png" alt="Ejemplo de mover" title="Ejemplo de mover">
</section>
<section>
<h4>
Variantes
</h4>
<p>
Esta operación nos permite representar distintos momentos, estados o secuencias de un personaje u objeto. Un ejemplo de esta operación es dibujar un personaje con distintas expresiones faciales o un mismo personaje con distintos peinados.
</p>
<img src="../img/Variantes.png" alt="Ejemplo de variantes" title="Ejemplo de variantes">
</section>
<section>
<h4>
Tiempo
</h4>
<p>
Esta operación se utiliza para mostrar los cambios de un objeto a lo largo del tiempo. Un ejemplo sencillo de esto se da cuando dibujamos las distintas etapas de construcción de un edificio y sus estados en distintos momentos. También está un ejemplo claro al dibujar los estados en que se encontraba el Titacnic a medida que transcurrían las horas luego de colisionar con el iceberg. A continuación veremos estos ejemplos en la siguiente imagen.
</p>
<img src="../img/Tiempo.png" alt="Ejemplo de tiempo" title="Ejemplo de tiemipo">
</section>
<section>
<h4>
Combinar
</h4>
<p>
Esta operación se realiza al combinar dos dibujos en uno. Un ejemplo se da si tenemos la perspectiva del techo y el interior de un edificio por separado, y luego unimos ambas ilustrasiones con una separación creada por una línea de corte, esta unión vendía siendo como una reconstrucción. A continuación veremos un ejemplo de esta operación.
</p>
<img src="../img/Combinar.png" alt="Ejemplo de combinar" title="Ejemplo de combinar">
</section>
</article>
<hr>
<article>
<h3>
Etapas del dibujo en profundidad
</h3>
<h4>El boceto</h4>
<p>
Esta es la primera etapa del dibujo en donde empezamos a armar la estructura del dibujo para luego pasar a la etapa de las líneas, el valor y el color.
</p>
<h5>
Componentes del boceto
</h5>
<h6>
La composición
</h6>
<p>
Cuando hacemos usos del boceto, vamos a estar organizando la composición total de nuestro dibujo, ya sea por medio de la regla de los tercios, la regla de la "L", la regla de la diagonal o hacer uso de cualquiera de ese tipo de composiciones para luego organizar todo nuestro dibujo, en la etapa del boceto organizamos cada uno de los elementos ya sean las formas o espacios.
</p>
<p>
La composición nos permite realizar una organización general que nos permita tener una armonía dentro del dibujo, aparte de esto que se ha mencionado, también vamos a ver que no tenemos solo la posibilidad de organizar la composición según las reglas mencionadas anteriormente, aparte de todo eso, también vamos a tenes que elegir la línea de horizonte, vamos a tener que elegir qué es lo que queremos mostrar en nuestro dibujo, y ahí es donde vamos a empezar a componer la imagen en base a una idea original.
</p>
<p>
Lo primero que tenemos que debemos tener en cuenta a la hora que comenzar a elaborar un dibujo es qué queremos mostrar con ese dibujo, y para eso vamos a hacer uso de la composición en la etapa del boceto. En el siguiente ejemplo podremos ver algunas de las reglas de composición como la diagonal, la cruz, la "L", la composición circular, triangular, en espiral, etc.
</p>
<img src="../img/Una guía para la composición, elementos_.jpeg" alt="Guía de composición para principiantes" title="Guía de composición para principiantes">
<p>
A continuación veremos una imagen en donde se ubicó la línea de horizonte a alturas distintas, como podemos ver, la calle resalta más a medida que la línea de horizonte está más alta, mientras que se resalta más el cielo a medida que la línea de horizonte está más abajo, si hubiesen edificios, se resaltaría también la altura de los edificios con la línea de horizonte baja.
</p>
<img src="../img/Línea de horizonte.jpg" alt="Línea de horizonte" title="Línea de horizonte">
<h6>
Estructura de objetos
</h6>
<p>
En la etapa de boceto sigue la estructura de los objetos, antes en la composición se veía la estructuración del dibujo en su totalidad y ahora se deberá trabajar la estructura de los objetos o las formas. En esta etapa vamos a empezar a construir de forma gráfica todo lo que son las formas de los objetos, a continuación se muestran dos ejemplos del proceso de estructuración de un personaje, podemos ver cómo vamos por etapas, primero se hace una esféra, luego se agrega una cara y a partir de allí es que se comienzan a agregar detalles como los ojos, la nariz, etc. Pero vamos a estar partiendo en la etapa de bocetos por estructurar los objetos desde la forma más general hacia los detalles o formas más particulares.
</p>
<img src="../img/Estructura de objeto 1.png" alt="Estructuración de rostro 1" title="Estructuración de rostro 1">
<img src="../img/Estructura de objeto 2.png" alt="Estructuración de rostro 2" title="Estructuración de rostro 2">
<h6>
Proporciones
</h6>
<p>
Luego de estructurar los objetos se deben tener en cuenta las proporciones, son una cuestión muy importante que deberemos establecer en la etapa del boceto, porque no podemos establecer por ejemplo una figura humana que tiene el doble de altura que debería tener o poner el tamaño de la cabeza que no es el indicado. Tendríamos que tener en cuenta también que si vamos a dibujar un edificio con la forma de un cubo por ejemplo, tenemos que tener en cuenta que va a tener el mismo ancho, alto y largo, si cambiamos alguna de esas proporciones en relación a las otras, vamos a estar alterando las proporciones de nuestro dibujo, es decir, hablando de la estructura del objeto, vamos a cambiarle las proporciones, osea que no va a ser el objeto que nosotros estamos queriendo representar y es por eso que debemos tener en cuenta las proporciones al momento de bocetar.
</p>
<p>
Hay que hacer un buen boceto y que sea prolijo con las proporciones, si no correspondemos bien a las proporciones, luego vamos a tener errores muy grandes en todas las otras etapas de nuestro dibujo. A continuación se muestra una imagen en la que se trabaja con proporciones de forma adecuada.
</p>
<img src="../img/Proporción 1.jpg" alt="Ejemplo de proporción del cuerpo del hombre" title="Ejemplo de proporción del cuerpo del hombre">
<p>
Para resumir, el boceto es la estructura del dibujo, debemos respetar la composición, la estructura de los objetos y las proporciones para poder construir dibujos que sean precisos y que tengan mucho interés por parte del ojo nuestro. Si creamos un dibujo que no tenga buena composición o que no esté bien en proporciones, luego nos va a costar entenderlo y nos va a complicar un poco lo que nosotros queremos expresar, es por esto que debemos hacer mucho énfasis en la etapa del boceto.
</p>
</article>
<hr>
<article>
<h3>
Práctica de boceto para la comprensión de las composiciones
</h3>
<p>
A continuación se muestras distintos ejemplos de composiciones aplicadas al proceso de boceto.
</p>
<p>
Es recomendable separar una hoja en varias partes para poder crear distintos tipos de composición.
</p>
<p>
Al dividir la hoja en varias partes tendremos distintos espacios diponibles para aplicar la distintos tipos de composiciones.
</p>
<p>
En el espacio superior izquierdo se aplicará una composición hecha con la regla de los tercios, algo resaltante de este tipo de composición es que las intersecciones de las líneas verticales y horizontales son puntos focales de mucho interés o atención a nivel visual.
</p>
<p>
En el ejemplo siguiente podemos ver cómo se ubican los personajes en las líneas verticales y sus rostros en los puntos de interés de la composición hecha con la regla de los tercios. Ya con eso tenemos la composición más básica del dibujo.
</p>
<img src="../img/tercios-composición-basica.png" alt="Composición básica con la regla de los tercios" title="Composición básica con la regla de los tercios">
<p>
Una vez que tenemos la estructura del dibujo, debemos concentrarnos en la estructura de cada uno de los personajes que tenemos en la imagen. En este caso procedemos a contruir un poco más la estructura de Woody y Buzz Lightyear para que podamos de esa forma tener los personajes tal cual ellos son. El resultado de este proceso se puede ver en la siguiente imagen.
</p>
<img src="../img/tercios-estructura-personaje.png" alt="Estructura de personaje" title="Estructura de personaje">
<p>
Debemos tener en cuenta como se ve en la imagen anterior, que en la etapa de boceto no hace falta ser muy prolijo, con algunas líneas básicas ya podemos marcar la forma de los personajes.
</p>
<p>
Entonces, lo primero que hicimos (imagen 1) fue establecer la composición global del dibujo y posteriormente trabajamos en la estructura de los personajes (imagen 2).
</p>
<p>
Es interesante ver que en el dibujo hay un uso de dos composiciones, la de los tercios y la de la diagonal (la composición diagonal es creada por la dirección del brazo de Buzz al señalar a Woody). En la siguiente imagen se señala para que quede de forma más clara.
</p>
<img src="../img/tercios-diagonal-composicion.png" alt="Composición de tercios y diagonal combinadas" title="Composición de tercios y diagonal combinadas">
<P>
Posteriormente se pasa a ver la estructura de los objetos, la estructura principal es lo que le da la forma principal a un personaje y al otro. La estructura de Woody nos marca que tiene la cabeza inclinada, que es un objeto mucho más alto que el otro personaje (Buzz) y también allí comenzamos a ver lo de las proporciones, podemos ver que Buzz en proporción es más ancho y bajo en comparación con Woody. Estos detalles son cuestiones que debemos tener en cuenta al crear un boceto.
</P>
<p>
A continuación se utiliza una composición basada en la regla de la diagonal para crear otra escena de Toy Story 2 (en el espacio superior derecho de nuestra hoja dividida), procedemos primero a establecer la composición global del dibujo, dándonos como resultado la siguiente imagen.
</p>
<img src="../img/diagonal-composición-basica.png" alt="Composición global de dibujo con regla de la diagonal" title="Composición global de dibujo con regla de la diagonal">
<p>
Posteriormente pasamos a trabajar en la estructura del personaje y obtenemos el siguiente resultado.
</p>
<img src="../img/diagonal-estructura-personaje.png" alt="Estructura de personaje" title="Estructura de personaje">
<p>
A continuación abordamos otros dos bocetos basados en una composición basada en la regla de la L. En los siguientes ejemplos se muestran primero el establecimiento de la composición global del dibujo seguida de la estructuración de los personajes.
</p>
<p>
Con la regla de la L se utiliza un elemento vertical y otro horizontal, estos conformarán una L como su nombre lo indica (en este caso la L es conformada por los libros ubicados a la izquierda de forma vertical y la repisa o estante en que están colocados y donde a su vez se sienta el personaje). En la regla de la L el espacio es el punto focal de interés. En el dibujo central a la izquierda el personaje se posiciona entonces en el espacio de la derecha del dibujo, allí está el punto de interés.
</p>
<img src="../img/l-composición-básica-izquierda.png" alt="Composición básica con la regla de la L" title="Composición básica con la regla de la L">
<p>
Ahora procedemos a la estructuración de personaje y los objetos a profundidad como puede verse en la siguiente imagen.
</p>
<img src="../img/l-estructura-personaje-izquierda.png" alt="Estructura de personaje" title="Estructura de personaje">
<p>
A continuación veremos otro ejemplo de la regla de la L, la primera imagen muestra el resultado de establecer la composición global del dibujo y la segunda el resultado de la estructuración de objetos y personajes.
</p>
<p>
En este caso la L está formada por el borde vertical del bote de basura a la izquierda del dibujo y la línea de horizonte del dibujo como tal.
</p>
<p>
En la composición global del dibujo podemos identificar la L, vemos cómo se ubicó un camión y objetos a la derecha del dibujo y la línea vertical de la izquierda sería el borde del bote de basura detrás del cuál se ocultará nuestro personaje.
</p>
<img src="../img/l-composición-básica-derecha.png" alt="Composición básica con la regla de la L" title="Composición básica con la regla de la L">
<p>
Ahora en la siguiente imagen veremos el resultado de la estructuración de personaje y objetos.
</p>
<img src="../img/l-estructura-personaje-derecha.png" alt="Estructura de personaje" title="Estructura de personaje">
</article>
</body>
</html> |
#include <gtest/gtest.h>
#include <iostream>
#include <set>
#define private public
#include "common/spin_mutex.h"
#include "common/string_utils.h"
#include "common/split.h"
namespace shardora {
namespace common {
namespace test {
class TestSpinMutex : public testing::Test {
public:
static void SetUpTestCase() {
}
static void TearDownTestCase() {
}
virtual void SetUp() {
}
virtual void TearDown() {
}
};
TEST_F(TestSpinMutex, MultiThreadTest) {
std::string test_str;
common::SpinMutex spin_mutex;
auto callback = [&test_str, &spin_mutex](int32_t thread_idx) {
common::AutoSpinLock auto_mutex(spin_mutex);
for (uint32_t i = 0; i < 100; ++i) {
test_str = test_str + + " ";
}
common::StringUtil::Trim(test_str);
test_str = test_str + std::to_string(thread_idx) + "_";
};
static const uint32_t kThreadCount = 20u;
std::vector<std::thread*> thread_vec;
for (uint32_t i = 0; i < kThreadCount; ++i) {
thread_vec.push_back(new std::thread(callback, i));
}
for (uint32_t i = 0; i < kThreadCount; ++i) {
thread_vec[i]->join();
}
std::set<uint32_t> thread_set;
common::Split<1024> thread_split(test_str.c_str(), '_', test_str.size());
for (uint32_t i = 0; i < thread_split.Count(); ++i) {
uint32_t val = 0;
if (common::StringUtil::ToUint32(thread_split[i], &val)) {
thread_set.insert(val);
}
}
ASSERT_EQ(thread_set.size(), kThreadCount);
for (uint32_t i = 0; i < kThreadCount; ++i) {
ASSERT_TRUE(thread_set.find(i) != thread_set.end());
}
}
} // namespace test
} // namespace common
} // namespace shardora |
# Upgrade portal
The Upgrade Portal is recommended as the easiest way to upgrade an existing ANTv1 balance to ANTv2 if the wallet can be connected to a dapp.
First, navigate to [upgrade.aragon.org](https://upgrade.aragon.org/#/):

### Connect a wallet
Connect your wallet to see your ANTv1 balance and begin the upgrade process:

If you would like to double check your connected wallet or re-connect to a different one, click the "Connect to a different wallet" or the Account Module in the top-right corner:

Note that some wallets, including Metamask, may require further interaction with their own interface to re-connect with a different wallet.
Once your wallet has been connected, you should now be able to see your wallet's ANTv1 and ANTv2 balances:

If you have provided liquidity to any of the popular ANT liquidity pools on-chain, you will also be able to see those associated balances at this point.
### Upgrade to ANTv2
Go ahead and smash that "Upgrade ANTv1 -> ANTv2" button to get started on upgrading!
You should now see this interface to select how much you'd like to upgrade:

{% hint style="info" %}
Note that the ANTv1 to ANTv2 upgrade is one-way. The ANTv1 you choose to upgrade will be burned and an equivalent amount of ANTv2 will be returned to your wallet.
{% endhint %}
I'm going to go ahead and migrate all of my ANTv1 to ANTv2:

Continuing further, you'll now be prompted to sign the transactions that will facilitate the upgrade (may depend on your wallet):

Note that you may need to sign multiple transactions to reset your ANT approval if you've previously used the interface before or interacted directly with the contract using the currently connected wallet.
Once you've signed the transaction(s), you should now see the success screen:

**🎉 Congratulations, you're done! 🍾**
If you have other accounts holding ANTv1, you may now go back and repeat this flow.
### Troubleshooting
#### My wallet doesn't detect my ANTv2 balance
Your wallet may not immediately detect your upgraded ANTv2 balance. In this case, you should be able to find documentation on how to add custom tokens to your wallet's interface. You will want to use `0xa117000000f279D81A1D3cc75430fAA017FA5A2e` as the token address.
For example, if you use Metamask, you can follow [this guide to add custom tokens](https://metamask.zendesk.com/hc/en-us/articles/360015489031-How-to-View-See-Your-Tokens-in-Metamask).
#### My wallet isn't connecting
Your wallet may be experiencing issues. If this issue persists, please reach out to us on [Discord](https://discord.com/invite/aragon).
{% hint style="info" %}
We are currently investigating issues with connecting to [WalletConnect](https://walletconnect.org/)-enabled wallets. We hope to enable WalletConnect soon.
{% endhint %}
#### My transactions aren't being propagated
You may not have specified a high enough gas price or your wallet may be experiencing issues.
If you're not familiar with the concept of gas on Ethereum, [ethgas.io](https://ethgas.io/) is a great primer. Your wallet will have built-in controls to help adjust the gas price used in your transactions so that they get mined in a timely fashion (for example, see [Metamask's documentation](https://metamask.zendesk.com/hc/en-us/articles/360015488771-How-to-Adjust-Gas-Price-and-Gas-Limit-)).
#### My transactions are failing
Please double check that your transaction has specified a high enough gas limit and that your account holds enough ETH. Using 250,000 as the gas limit for any transactions requested by the Upgrade Portal will be sufficient.
If you're not familiar with the concept of gas on Ethereum, [ethgas.io](https://ethgas.io/) is a great primer. |
// import axios from "axios";
// import { useRouter } from "next/navigation";
// import { useCallback, useMemo } from "react";
// import { toast } from "react-hot-toast";
// import { SafeUser } from "@/app/types";
// import useLoginModal from "./useLoginModal";
// interface IUseFavorite {
// listingId: string;
// currentUser?: SafeUser | null
// }
// const useFavorite = ({ listingId, currentUser }: IUseFavorite) => {
// const router = useRouter();
// const loginModal = useLoginModal();
// const hasFavorited = useMemo(() => {
// const list = currentUser?.favoriteIds || [];
// return list.includes(listingId);
// }, [currentUser, listingId]);
// const toggleFavorite = useCallback(async (e: React.MouseEvent<HTMLDivElement>) => {
// e.stopPropagation();
// if (!currentUser) {
// return loginModal.onOpen();
// }
// try {
// let request;
// if (hasFavorited) {
// request = () => axios.delete(`/api/favorites/${listingId}`);
// } else {
// request = () => axios.post(`/api/favorites/${listingId}`);
// }
// await request();
// router.refresh();
// toast.success('Success');
// } catch (error) {
// toast.error('Something went wrong.');
// }
// },
// [
// currentUser,
// hasFavorited,
// listingId,
// loginModal,
// router
// ]);
// return {
// hasFavorited,
// toggleFavorite,
// }
// }
// export default useFavorite; |
import { useSearchParams } from "react-router-dom";
import { Card } from "../components"
import { useFetch } from "../hooks/useFetch";
import { useTitle } from "../hooks/useTitle";
export const Search = ({api}) => {
const [searchParams] = useSearchParams();
const queryTerm = searchParams.get("q");
const {data : movies} = useFetch({api, queryTerm});
useTitle(` Search Result for ${queryTerm}`);
return (
<main>
<section className="py-7">
<p className="text-3xl text-gray-700 dark:text-white">{ movies.length === 0 ? `No result found for '${queryTerm}'` : `Result for '${queryTerm}'` }</p>
</section>
<section className="max-w-7xl mx-auto py-7">
<div className="flex justify-start flex-wrap">
{movies.map((movie)=>(
<Card key = {movie.id} movie={movie}/>
))}
</div>
</section>
</main>
)
} |
/* global tinymce, wpCookies, autosaveL10n, switchEditors */
// Back-compat
window.autosave = function() {
return true;
};
(function($, window) {
function autosave() {
var initialCompareString,
lastTriggerSave = 0,
$document = $(document);
/**
* Returns the data saved in both local and remote autosave
*
* @return object Object containing the post data
*/
function getPostData(type) {
var post_name, parent_id, data,
time = (new Date()).getTime(),
cats = [],
editor = typeof tinymce !== 'undefined' && tinymce.get('content');
// Don't run editor.save() more often than every 3 sec.
// It is resource intensive and might slow down typing in long posts on slow devices.
if (editor && !editor.isHidden() && time - 3000 > lastTriggerSave) {
editor.save();
lastTriggerSave = time;
}
data = {
post_id: $('#post_ID').val() || 0,
post_type: $('#post_type').val() || '',
post_author: $('#post_author').val() || '',
post_title: $('#title').val() || '',
content: $('#content').val() || '',
excerpt: $('#excerpt').val() || ''
};
if (type === 'local') {
return data;
}
$('input[id^="in-category-"]:checked').each(function() {
cats.push(this.value);
});
data.catslist = cats.join(',');
if (post_name = $('#post_name').val()) {
data.post_name = post_name;
}
if (parent_id = $('#parent_id').val()) {
data.parent_id = parent_id;
}
if ($('#comment_status').prop('checked')) {
data.comment_status = 'open';
}
if ($('#ping_status').prop('checked')) {
data.ping_status = 'open';
}
if ($('#auto_draft').val() === '1') {
data.auto_draft = '1';
}
return data;
}
// Concatenate title, content and excerpt. Used to track changes when auto-saving.
function getCompareString(postData) {
if (typeof postData === 'object') {
return (postData.post_title || '') + '::' + (postData.content || '') + '::' + (postData.excerpt || '');
}
return ($('#title').val() || '') + '::' + ($('#content').val() || '') + '::' + ($('#excerpt').val() || '');
}
function disableButtons() {
$document.trigger('autosave-disable-buttons');
// Re-enable 5 sec later. Just gives autosave a head start to avoid collisions.
setTimeout(enableButtons, 5000);
}
function enableButtons() {
$document.trigger('autosave-enable-buttons');
}
// Autosave in localStorage
function autosaveLocal() {
var restorePostData, undoPostData, blog_id, post_id, hasStorage, intervalTimer,
lastCompareString,
isSuspended = false;
// Check if the browser supports sessionStorage and it's not disabled
function checkStorage() {
var test = Math.random().toString(),
result = false;
try {
window.sessionStorage.setItem('wp-test', test);
result = window.sessionStorage.getItem('wp-test') === test;
window.sessionStorage.removeItem('wp-test');
} catch (e) {
}
hasStorage = result;
return result;
}
/**
* Initialize the local storage
*
* @return mixed False if no sessionStorage in the browser or an Object containing all postData for this blog
*/
function getStorage() {
var stored_obj = false;
// Separate local storage containers for each blog_id
if (hasStorage && blog_id) {
stored_obj = sessionStorage.getItem('wp-autosave-' + blog_id);
if (stored_obj) {
stored_obj = JSON.parse(stored_obj);
} else {
stored_obj = {};
}
}
return stored_obj;
}
/**
* Set the storage for this blog
*
* Confirms that the data was saved successfully.
*
* @return bool
*/
function setStorage(stored_obj) {
var key;
if (hasStorage && blog_id) {
key = 'wp-autosave-' + blog_id;
sessionStorage.setItem(key, JSON.stringify(stored_obj));
return sessionStorage.getItem(key) !== null;
}
return false;
}
/**
* Get the saved post data for the current post
*
* @return mixed False if no storage or no data or the postData as an Object
*/
function getSavedPostData() {
var stored = getStorage();
if (!stored || !post_id) {
return false;
}
return stored[ 'post_' + post_id ] || false;
}
/**
* Set (save or delete) post data in the storage.
*
* If stored_data evaluates to 'false' the storage key for the current post will be removed
*
* $param stored_data The post data to store or null/false/empty to delete the key
* @return bool
*/
function setData(stored_data) {
var stored = getStorage();
if (!stored || !post_id) {
return false;
}
if (stored_data) {
stored[ 'post_' + post_id ] = stored_data;
} else if (stored.hasOwnProperty('post_' + post_id)) {
delete stored[ 'post_' + post_id ];
} else {
return false;
}
return setStorage(stored);
}
function suspend() {
isSuspended = true;
}
function resume() {
isSuspended = false;
}
/**
* Save post data for the current post
*
* Runs on a 15 sec. interval, saves when there are differences in the post title or content.
* When the optional data is provided, updates the last saved post data.
*
* $param data optional Object The post data for saving, minimum 'post_title' and 'content'
* @return bool
*/
function save(data) {
var postData, compareString,
result = false;
if (isSuspended) {
return false;
}
if (data) {
postData = getSavedPostData() || {};
$.extend(postData, data);
} else {
postData = getPostData('local');
}
compareString = getCompareString(postData);
if (typeof lastCompareString === 'undefined') {
lastCompareString = initialCompareString;
}
// If the content, title and excerpt did not change since the last save, don't save again
if (compareString === lastCompareString) {
return false;
}
postData.save_time = (new Date()).getTime();
postData.status = $('#post_status').val() || '';
result = setData(postData);
if (result) {
lastCompareString = compareString;
}
return result;
}
// Run on DOM ready
function run() {
post_id = $('#post_ID').val() || 0;
// Check if the local post data is different than the loaded post data.
if ($('#wp-content-wrap').hasClass('tmce-active')) {
// If TinyMCE loads first, check the post 1.5 sec. after it is ready.
// By this time the content has been loaded in the editor and 'saved' to the textarea.
// This prevents false positives.
$document.on('tinymce-editor-init.autosave', function() {
window.setTimeout(function() {
checkPost();
}, 1500);
});
} else {
checkPost();
}
// Save every 15 sec.
intervalTimer = window.setInterval(save, 15000);
$('form#post').on('submit.autosave-local', function() {
var editor = typeof tinymce !== 'undefined' && tinymce.get('content'),
post_id = $('#post_ID').val() || 0;
if (editor && !editor.isHidden()) {
// Last onSubmit event in the editor, needs to run after the content has been moved to the textarea.
editor.on('submit', function() {
save({
post_title: $('#title').val() || '',
content: $('#content').val() || '',
excerpt: $('#excerpt').val() || ''
});
});
} else {
save({
post_title: $('#title').val() || '',
content: $('#content').val() || '',
excerpt: $('#excerpt').val() || ''
});
}
wpCookies.set('wp-saving-post-' + post_id, 'check');
});
}
// Strip whitespace and compare two strings
function compare(str1, str2) {
function removeSpaces(string) {
return string.toString().replace(/[\x20\t\r\n\f]+/g, '');
}
return (removeSpaces(str1 || '') === removeSpaces(str2 || ''));
}
/**
* Check if the saved data for the current post (if any) is different than the loaded post data on the screen
*
* Shows a standard message letting the user restore the post data if different.
*
* @return void
*/
function checkPost() {
var content, post_title, excerpt, $notice,
postData = getSavedPostData(),
cookie = wpCookies.get('wp-saving-post-' + post_id);
if (!postData) {
return;
}
if (cookie) {
wpCookies.remove('wp-saving-post-' + post_id);
if (cookie === 'saved') {
// The post was saved properly, remove old data and bail
setData(false);
return;
}
}
// There is a newer autosave. Don't show two "restore" notices at the same time.
if ($('#has-newer-autosave').length) {
return;
}
content = $('#content').val() || '';
post_title = $('#title').val() || '';
excerpt = $('#excerpt').val() || '';
// cookie == 'check' means the post was not saved properly, always show #local-storage-notice
if (cookie !== 'check' && compare(content, postData.content) &&
compare(post_title, postData.post_title) && compare(excerpt, postData.excerpt)) {
return;
}
restorePostData = postData;
undoPostData = {
content: content,
post_title: post_title,
excerpt: excerpt
};
$notice = $('#local-storage-notice');
$('.wrap h2').first().after($notice.addClass('updated').show());
$notice.on('click.autosave-local', function(event) {
var $target = $(event.target);
if ($target.hasClass('restore-backup')) {
restorePost(restorePostData);
$target.parent().hide();
$(this).find('p.undo-restore').show();
} else if ($target.hasClass('undo-restore-backup')) {
restorePost(undoPostData);
$target.parent().hide();
$(this).find('p.local-restore').show();
}
event.preventDefault();
});
}
// Restore the current title, content and excerpt from postData.
function restorePost(postData) {
var editor;
if (postData) {
// Set the last saved data
lastCompareString = getCompareString(postData);
if ($('#title').val() !== postData.post_title) {
$('#title').focus().val(postData.post_title || '');
}
$('#excerpt').val(postData.excerpt || '');
editor = typeof tinymce !== 'undefined' && tinymce.get('content');
if (editor && !editor.isHidden() && typeof switchEditors !== 'undefined') {
// Make sure there's an undo level in the editor
editor.undoManager.add();
editor.setContent(postData.content ? switchEditors.wpautop(postData.content) : '');
} else {
// Make sure the Text editor is selected
$('#content-html').click();
$('#content').val(postData.content);
}
return true;
}
return false;
}
// Initialize and run checkPost() on loading the script (before TinyMCE init)
blog_id = typeof window.autosaveL10n !== 'undefined' && window.autosaveL10n.blog_id;
// Check if the browser supports sessionStorage and it's not disabled
if (!checkStorage()) {
return;
}
// Don't run if the post type supports neither 'editor' (textarea#content) nor 'excerpt'.
if (!blog_id || (!$('#content').length && !$('#excerpt').length)) {
return;
}
$document.ready(run);
return {
hasStorage: hasStorage,
getSavedPostData: getSavedPostData,
save: save,
suspend: suspend,
resume: resume
};
}
// Autosave on the server
function autosaveServer() {
var _blockSave, _blockSaveTimer, previousCompareString, lastCompareString,
nextRun = 0,
isSuspended = false;
// Block saving for the next 10 sec.
function tempBlockSave() {
_blockSave = true;
window.clearTimeout(_blockSaveTimer);
_blockSaveTimer = window.setTimeout(function() {
_blockSave = false;
}, 10000);
}
function suspend() {
isSuspended = true;
}
function resume() {
isSuspended = false;
}
// Runs on heartbeat-response
function response(data) {
_schedule();
_blockSave = false;
lastCompareString = previousCompareString;
previousCompareString = '';
$document.trigger('after-autosave', [data]);
enableButtons();
if (data.success) {
// No longer an auto-draft
$('#auto_draft').val('');
}
}
/**
* Save immediately
*
* Resets the timing and tells heartbeat to connect now
*
* @return void
*/
function triggerSave() {
nextRun = 0;
wp.heartbeat.connectNow();
}
/**
* Checks if the post content in the textarea has changed since page load.
*
* This also happens when TinyMCE is active and editor.save() is triggered by
* wp.autosave.getPostData().
*
* @return bool
*/
function postChanged() {
return getCompareString() !== initialCompareString;
}
// Runs on 'heartbeat-send'
function save() {
var postData, compareString;
// window.autosave() used for back-compat
if (isSuspended || _blockSave || !window.autosave()) {
return false;
}
if ((new Date()).getTime() < nextRun) {
return false;
}
postData = getPostData();
compareString = getCompareString(postData);
// First check
if (typeof lastCompareString === 'undefined') {
lastCompareString = initialCompareString;
}
// No change
if (compareString === lastCompareString) {
return false;
}
previousCompareString = compareString;
tempBlockSave();
disableButtons();
$document.trigger('wpcountwords', [postData.content])
.trigger('before-autosave', [postData]);
postData._wpnonce = $('#_wpnonce').val() || '';
return postData;
}
function _schedule() {
nextRun = (new Date()).getTime() + (autosaveL10n.autosaveInterval * 1000) || 60000;
}
$document.on('heartbeat-send.autosave', function(event, data) {
var autosaveData = save();
if (autosaveData) {
data.wp_autosave = autosaveData;
}
}).on('heartbeat-tick.autosave', function(event, data) {
if (data.wp_autosave) {
response(data.wp_autosave);
}
}).on('heartbeat-connection-lost.autosave', function(event, error, status) {
// When connection is lost, keep user from submitting changes.
if ('timeout' === error || 603 === status) {
var $notice = $('#lost-connection-notice');
if (!wp.autosave.local.hasStorage) {
$notice.find('.hide-if-no-sessionstorage').hide();
}
$notice.show();
disableButtons();
}
}).on('heartbeat-connection-restored.autosave', function() {
$('#lost-connection-notice').hide();
enableButtons();
}).ready(function() {
_schedule();
});
return {
tempBlockSave: tempBlockSave,
triggerSave: triggerSave,
postChanged: postChanged,
suspend: suspend,
resume: resume
};
}
// Wait for TinyMCE to initialize plus 1 sec. for any external css to finish loading,
// then 'save' to the textarea before setting initialCompareString.
// This avoids any insignificant differences between the initial textarea content and the content
// extracted from the editor.
$document.on('tinymce-editor-init.autosave', function(event, editor) {
if (editor.id === 'content') {
window.setTimeout(function() {
editor.save();
initialCompareString = getCompareString();
}, 1000);
}
}).ready(function() {
// Set the initial compare string in case TinyMCE is not used or not loaded first
initialCompareString = getCompareString();
});
return {
getPostData: getPostData,
getCompareString: getCompareString,
disableButtons: disableButtons,
enableButtons: enableButtons,
local: autosaveLocal(),
server: autosaveServer()
};
}
window.wp = window.wp || {};
window.wp.autosave = autosave();
}(jQuery, window)); |
import { AfterViewInit, Component, ElementRef, Inject, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from "@angular/material/dialog";
import { Course } from "../model/course";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";
import * as moment from 'moment';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { CoursesService } from '../services/courses.service';
import { LoadingService } from '../loading/loading.service';
import { MessageService } from '../messages/message.service';
import { CoursesStoreService } from '../services/courses-store.service';
@Component({
selector: 'course-dialog',
templateUrl: './course-dialog.component.html',
styleUrls: ['./course-dialog.component.css']
})
export class CourseDialogComponent implements AfterViewInit {
form: FormGroup;
course: Course;
constructor(
private fb: FormBuilder,
private dialogRef: MatDialogRef<CourseDialogComponent>,
@Inject(MAT_DIALOG_DATA) course: Course,
private coursesService: CoursesService,
private loadingService: LoadingService,
private messageService: MessageService,
private coursesStoreService: CoursesStoreService,
) {
this.course = course;
this.form = fb.group({
description: [course.description, Validators.required],
category: [course.category, Validators.required],
releasedAt: [moment(), Validators.required],
longDescription: [course.longDescription, Validators.required]
});
}
ngAfterViewInit() {
}
save() {
const changes = this.form.value;
this.coursesStoreService.saveCourse(this.course.id, changes).pipe(
catchError(error => {
const message = 'could not save course';
this.messageService.showErrors(message);
return throwError(error);
})
).subscribe();
this.dialogRef.close();
;
}
close() {
this.dialogRef.close();
}
} |
#ifndef ANIMATEDELEMENT_H
#define ANIMATEDELEMENT_H
#include <vector>
enum ELEMENT_TYPE
{
LONG4,
CORNER3,
SMALL2,
CUBE,
PYRAMID,
EMPTY
};
enum ELEMENT_ROTATION
{
UP,
RIGHT,
DOWN,
LEFT,
COUNT
};
struct Position
{
int x;
int y;
Position() :x(0), y(0){}
Position(int _x, int _y) :x(_x), y(_y){}
};
class AnimatedElement
{
private:
int m_id;
ELEMENT_TYPE m_type;
Position m_position;
ELEMENT_ROTATION m_rotation;
int m_boardWidth;
int m_boardHeight;
int m_elementWidth;
int m_elementHeight;
vector<int> m_frames[ELEMENT_ROTATION::COUNT];
public:
AnimatedElement();
AnimatedElement(ELEMENT_TYPE type, Position position, ELEMENT_ROTATION rotation,
int elementWidth, int elementHeight,
int boardWidth, int boardHeight) :
m_type(type),
m_position(position),
m_rotation(rotation),
m_elementWidth(elementWidth),
m_elementHeight(elementHeight),
m_boardWidth(boardWidth),
m_boardHeight(boardHeight){};
int getId() const;
void setId(int id);
Position getPosition() const;
void setPosition(Position);
ELEMENT_TYPE getType() const { return m_type; }
ELEMENT_ROTATION getRotation() const { return m_rotation; }
void setRotation(ELEMENT_ROTATION rotation) { m_rotation = rotation; }
void addFrameTexture(ELEMENT_ROTATION rotation, int textureId);
void renderFrame(ELEMENT_ROTATION rotation, int frameNumber);
void renderAnimation(int delayBetweenFrames);
};
#endif ANIMATEDELEMENT_H |
<mat-toolbar>
<h1 class="mat-h1">Student Form</h1>
</mat-toolbar>
<mat-spinner *ngIf="isLoading"></mat-spinner>
<form [formGroup]="applicationForm" (ngSubmit)="onSubmit()" *ngIf="!isLoading">
<mat-card class="form-card">
<mat-card-content>
<div class="row">
<div class="col">
<mat-form-field
class="full-width"
appearance="outline"
color="accent"
>
<mat-label>
Full name
</mat-label>
<input
matInput
placeholder="Full name of the student"
formControlName="fullName"
/>
<mat-error
*ngIf="applicationForm.controls['fullName'].hasError('required')"
>
Student's full name is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
<mat-form-field
class="full-width"
appearance="outline"
color="accent"
>
<mat-label>Class</mat-label>
<mat-select placeholder="Class" formControlName="standard">
<mat-option *ngFor="let c of classes" [value]="c">
{{ c }}
</mat-option>
</mat-select>
<mat-error
*ngIf="applicationForm.controls['standard'].hasError('required')"
>
Class is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="col">
<mat-form-field
class="full-width"
appearance="outline"
color="accent"
>
<mat-label>Date of Birth</mat-label>
<input
matInput
placeholder="Date of Birth"
formControlName="dob"
[matDatepicker]="picker"
/>
<mat-datepicker-toggle
matSuffix
[for]="picker"
></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error
*ngIf="applicationForm.controls['dob'].hasError('required')"
>
Date of Birth is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
<mat-form-field
class="full-width"
appearance="outline"
color="accent"
>
<mat-label>Mother's name</mat-label>
<input
matInput
placeholder="Mother's name"
formControlName="motherName"
/>
<mat-error
*ngIf="
applicationForm.controls['motherName'].hasError('required')
"
>
Mother's name is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="col">
<mat-form-field
class="full-width"
appearance="outline"
color="accent"
>
<mat-label>Father's name</mat-label>
<input
matInput
placeholder="Father's name"
formControlName="fatherName"
/>
<mat-error
*ngIf="
applicationForm.controls['fatherName'].hasError('required')
"
>
Father's name is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
<mat-form-field
class="full-width"
appearance="outline"
color="accent"
>
<mat-label>Address</mat-label>
<textarea
matInput
placeholder="Address"
formControlName="address"
></textarea>
<mat-error
*ngIf="applicationForm.controls['address'].hasError('required')"
>
Address is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
<mat-form-field
class="full-width"
appearance="outline"
color="accent"
>
<mat-label>City</mat-label>
<input matInput placeholder="City" formControlName="city" />
<mat-error
*ngIf="applicationForm.controls['city'].hasError('required')"
>
City is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="col">
<mat-form-field
class="full-width"
appearance="outline"
color="accent"
>
<mat-label>State</mat-label>
<input matInput placeholder="State" formControlName="state" />
<mat-error
*ngIf="applicationForm.controls['state'].hasError('required')"
>
State is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
<mat-form-field
class="full-width"
appearance="outline"
color="accent"
>
<input
matInput
#postalCode
maxlength="6"
placeholder="Postal Code"
type="number"
formControlName="postalCode"
/>
<mat-hint align="end">{{ postalCode.value.length }} / 6</mat-hint>
<mat-error
*ngIf="
applicationForm.controls['postalCode'].hasError('required')
"
>
Postal Code is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
<mat-label>Gender</mat-label>
<mat-radio-group formControlName="gender">
<mat-radio-button value="Female">Female</mat-radio-button>
<mat-radio-button value="Male">Male</mat-radio-button>
<mat-radio-button value="Others">
Others
</mat-radio-button>
</mat-radio-group>
</div>
</div>
<div class="row">
<div class="col">
<mat-form-field
class="full-width"
appearance="outline"
color="accent"
>
<mat-label>
Admission Number
</mat-label>
<input
matInput
placeholder="Admission Number"
formControlName="admissionNumber"
/>
<span matSuffix>@school.com</span>
<mat-hint>
The admission number entered here will be suffixed with
@school.com automatically and will be the username for the
student.
</mat-hint>
<mat-error
*ngIf="
applicationForm.controls['admissionNumber'].hasError('required')
"
>
Admission number is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="col">
<mat-form-field
class="full-width"
appearance="outline"
color="accent"
>
<mat-label>
Password
</mat-label>
<input matInput placeholder="Password" formControlName="password" />
<mat-error
*ngIf="applicationForm.controls['password'].hasError('required')"
>
Password is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
</div>
</mat-card-content>
<mat-card-actions>
<button
mat-raised-button
color="accent"
type="submit"
[disabled]="applicationForm.invalid"
>
Submit
</button>
<button mat-raised-button color="warn" type="reset">Reset</button>
</mat-card-actions>
</mat-card>
</form> |
import { DataTypes, Sequelize } from "sequelize";
import { Model, Table } from "sequelize-typescript";
import { ProductModel } from "./product.model";
import { ClientModel } from "./client.model";
@Table
class OrderModel extends Model {
declare id: string;
declare status: string;
declare total: number;
declare items: ProductModel[];
declare client: ClientModel;
static initModel(instance: Sequelize) {
OrderModel.init({
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.STRING,
allowNull: false,
},
total: {
type: DataTypes.INTEGER,
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
}
}, {
sequelize: instance,
tableName: 'orders',
timestamps: false,
});
OrderModel.hasMany(ProductModel, { as: 'items', foreignKey: 'orderId' });
OrderModel.hasOne(ClientModel, { as: 'client', foreignKey: 'orderId' });
}
}
export { OrderModel }; |
package com.apuestas.RetoApuestas.infraestructure.entrypoints;
import com.apuestas.RetoApuestas.domain.models.VentaRecarga;
import com.apuestas.RetoApuestas.domain.usecases.ventaderecarga.VentaRecargaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping("/api/recargas")
public class VentaRecargaController {
@Autowired
private VentaRecargaService ventaRecargaService;
@GetMapping
public List<VentaRecarga> listar() {
List<VentaRecarga> ventas = ventaRecargaService.listar();
for (VentaRecarga venta : ventas) {
System.out.println("ID: " + venta.getId());
System.out.println("Operador: " + venta.getOperador());
System.out.println("Vendedor: " + venta.getVendedor());
System.out.println("Valor: " + venta.getValor());
System.out.println("venta = " + venta.getFecha());
}
return ventas;
}
@PostMapping
public VentaRecarga agregar(@RequestBody VentaRecarga ventaRecarga){
return ventaRecargaService.Venta(ventaRecarga);
}
@GetMapping("/por-operador/{operador}")
public List<VentaRecarga> listarPorOperador(@PathVariable String operador) {
return ventaRecargaService.findByOperador(operador);
}
@GetMapping("/por-vendedor/{vendedor}")
public List<VentaRecarga> listarPorVendedor(@PathVariable String vendedor) {
return ventaRecargaService.findByVendedor(vendedor);
}
} |
<template>
<!-- 如果要疊用toast就以toast-container包覆並定位 -->
<!-- 因為要確保它不會被認何物件檔住所以給它一個z-index:1500 -->
<div
class="toast-container position-fixed pe-3 top-0 end-0"
style="z-index: 1500"
>
<!-- 放入toast模版 並加入迴圈-->
<div
v-for="(msg, key) in messages"
:key="key"
class="toast show"
role="alert"
aria-live="assertive"
aria-atomic="true"
>
<div class="toast-header">
<span
:class="`bg-${msg.style}`"
class="p-2 rounded me-2 d-inline-block"
></span>
<!-- <img src="..." class="rounded mr-2" alt="..."> -->
<strong class="mr-auto">{{ msg.title }}</strong>
<small>11 mins ago</small>
<button
type="button"
class="ml-2 mb-1 close"
data-dismiss="toast"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body" v-if="msg.content">
{{ msg.content }}
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
messages: [
// 每一個物件代表一個toast,分別把內容傳進toast裡面
// {
// style:'顏色',
// title:'標題',
// content:'內容'
// }
]
}
},
inject: ['emitter'],
mounted () {
this.emitter.on('push-message', (message) => {
// 接收資料
const { style = 'success', title, content } = message
this.message.push({ style, title, content })
this.toastShow()
})
}
}
</script> |
<?php
/**
* SqualoMail
*
* NOTICE OF LICENSE
*
* This source file is subject to the Commercial License
* you can't distribute, modify or sell this code
*
* DISCLAIMER
*
* Do not edit or add to this file
* If you need help please contact leo@prestachamps.com
*
* @author Squalomail
* @copyright Squalomail
* @license commercial
*/
namespace PrestaChamps\SqualomailModule\Commands;
use DrewM\SqualoMail\SqualoMail;
use PrestaChamps\SqualomailModule\Formatters\ProductFormatter;
/**
* Class ProductSyncService
*
* @package PrestaChamps\SqualomailModule\Exceptions
*/
class ProductSyncCommand extends BaseApiCommand
{
protected $context;
protected $productIds;
protected $squalomail;
protected $batch;
protected $batchPrefix = '';
protected $method = 'POST';
protected $commands = array();
/**
* @var \Category[]
*/
protected $categoryCache = array();
/**
* ProductSyncService constructor.
*
* @param \Context $context
* @param SqualoMail $squalomail
* @param $productIds
*/
public function __construct(\Context $context, SqualoMail $squalomail, $productIds)
{
$this->context = $context;
$this->squalomail = $squalomail;
$this->batchPrefix = uniqid("PRODUCT_SYNC_{$this->method}_", true);
$this->batch = $this->squalomail->new_batch($this->batchPrefix);
$this->productIds = $productIds;
}
/**
* @return array|false
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
public function execute()
{
$this->buildProducts();
if ($this->method == self::SYNC_MODE_BATCH) {
return $this->batch->execute();
}
$method = \Tools::strtolower($this->method);
foreach ($this->commands as $entityId => $params) {
try {
$this->responses[$entityId] = $this->squalomail->$method($params['route'], $params['data']);
} catch (\Exception $exception) {
$this->responses[$entityId] = $this->squalomail->getLastResponse();
continue;
}
}
return $this->responses;
}
/**
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
protected function buildProducts()
{
foreach ($this->productIds as $key => $product) {
$product = new \Product($product, false, $this->context->language->id);
$category = $this->getCategory($product->getDefaultCategory());
$productFormatter = new ProductFormatter(
$product,
$category,
$this->context
);
$shopId = \Configuration::get(\SqualomailModuleConfig::SQUALOMAIL_API_KEY);
if ($this->method === self::SYNC_METHOD_POST) {
if ($this->syncMode == self::SYNC_MODE_BATCH) {
$this->batch->post(
$this->batchPrefix . '_' . $key,
"/ecommerce/stores/{$shopId}/products",
$productFormatter->format()
);
} else {
$this->commands[$product->id] = array(
'route' => "/ecommerce/stores/{$shopId}/products",
'data' => $productFormatter->format(),
);
}
} elseif ($this->method === self::SYNC_METHOD_PATCH) {
if ($this->syncMode == self::SYNC_MODE_BATCH) {
$this->batch->patch(
$this->batchPrefix . '_' . $key,
"/ecommerce/stores/{$shopId}/products/{$product->id}",
$productFormatter->format()
);
} else {
$this->commands[$product->id] = array(
'route' => "/ecommerce/stores/{$shopId}/products/{$product->id}",
'data' => $productFormatter->format(),
);
}
} else {
if ($this->syncMode == self::SYNC_MODE_BATCH) {
$this->batch->delete(
$this->batchPrefix . '_' . $key,
"/ecommerce/stores/{$shopId}/products/{$product->id}"
);
} else {
$this->commands[$product->id] = array(
'route' => "/ecommerce/stores/{$shopId}/products/{$product->id}",
'data' => array(),
);
}
}
}
}
/**
* It's a good idea to store categories in a cache to prevent multiple and unnecessary DB calls
*
* @param $categoryId
*
* @return \Category
*/
protected function getCategory($categoryId)
{
// Because PrestaShop, that's why
if (!is_scalar($categoryId)) {
$categoryId = $categoryId['id_category_default'];
}
if (isset($this->categoryCache[$categoryId])) {
return $this->categoryCache[$categoryId];
}
$this->categoryCache[$categoryId] = new \Category(
$categoryId,
$this->context->language->id,
$this->context->shop->id
);
return $this->categoryCache[$categoryId];
}
public function getBatchId()
{
return $this->batchPrefix;
}
} |
from typing import Any
import numpy as np
from gym import spaces
from habitat.core.registry import registry
from habitat.core.simulator import Sensor, SensorTypes
@registry.register_sensor
class StepIDSensor(Sensor):
cls_uuid: str = "step_id"
curr_ep_id: str = ""
_elapsed_steps: int = 0
def _get_uuid(self, *args: Any, **kwargs: Any) -> str:
return self.cls_uuid
def _get_sensor_type(self, *args: Any, **kwargs: Any):
return SensorTypes.TENSOR
def _get_observation_space(self, *args: Any, **kwargs: Any):
return spaces.Box(
low=np.iinfo(np.int64).min,
high=np.iinfo(np.int64).max,
shape=(1,1),
dtype=np.int64,
)
def get_observation(
self,
*args: Any,
observations,
episode,
**kwargs: Any,
):
episode_uniq_id = f"{episode.scene_id} {episode.episode_id}"
if self.curr_ep_id != episode_uniq_id:
self.curr_ep_id = episode_uniq_id
self._elapsed_steps = 0
else:
self._elapsed_steps += 1
return np.array(self._elapsed_steps).reshape(1, 1) |
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Equipments;
/**
* EquipmentsSearch represents the model behind the search form of `app\models\Equipments`.
*/
class EquipmentsSearch extends Equipments
{
public $equipmentsSearch;
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id'], 'integer'],
[['name', 'description', 'created_at', 'updated_at','equipmentsSearch'], 'safe'],
];
}
/**
* {@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 = Equipments::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,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->orFilterWhere(['like', 'name', $this->equipmentsSearch])
->orFilterWhere(['like', 'description', $this->equipmentsSearch]);
return $dataProvider;
}
} |
import React from "react";
import ReactDOM from "react-dom";
/*
! Desestructuración!
const Hello = (props) => {
const { name, age } = props
ES IGUAL A
const Hello = ({ name, age }) => {
Para desestructurar el código y que quede más limpio y organizado,
podemos pasar directamente las propiedades a la función cómo parámetro en forma de objeto
*/
const Saludar = (props) => {
const añoNacimiento = () => {
const año = new Date().getFullYear();
return año - props.edad;
};
return (
<div>
<p>
Hola {props.nombre}, tienes {props.edad} años.
</p>
<p>Naciste por el año {añoNacimiento()}</p>
</div>
);
};
const App = () => {
const nombre = "Ruben";
const edad = 28;
return (
<div>
<h1>Bienvenid@!</h1>
<Saludar nombre="Alaya" edad={17 + 10} />
<Saludar nombre={nombre} edad={edad} />
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root")); |
import _, { get, map, keys, split, toString, trim } from 'lodash';
import i18n from '@/locale';
import { LabelListItem, ComponentSchema, OptionsItem } from './interface';
import { isOrCondition, parseExpression } from './experssion-parser';
import { validateYaml } from './yaml-parse';
import { schemaType } from './index';
import { setFieldDefaultValue } from '../../dynamic-form/config/field-type';
const operatorMap = {
noequal: '!=',
equal: '=',
or: '||',
and: '&&',
gt: '>',
lt: '<',
lte: '<=',
gte: '>='
};
const conditonOperator = [
operatorMap.noequal,
operatorMap.equal,
operatorMap.or,
operatorMap.and,
operatorMap.gt,
operatorMap.lt,
operatorMap.lte,
operatorMap.gte
];
const noequalFunc = (v1, v2) => {
return !_.isEqual(v1, v2);
};
const orFunc = (b1, b2) => {
return b1 || b2;
};
const andFunc = (b1, b2) => {
return b1 && b2;
};
export const conditionFuncMap = () => {
const funcMap = new Map();
funcMap.set(operatorMap.noequal, noequalFunc);
funcMap.set(operatorMap.or, orFunc);
funcMap.set(operatorMap.and, andFunc);
funcMap.set(operatorMap.equal, _.isEqual);
funcMap.set(operatorMap.gt, _.gt);
funcMap.set(operatorMap.lt, _.lt);
funcMap.set(operatorMap.lte, _.lte);
funcMap.set(operatorMap.gte, _.gte);
return funcMap;
};
const funcMap = conditionFuncMap();
export const getConditionValue = (fm, formData) => {
const conditionList = fm.conditions;
const fieldPath = fm.fieldPath || [];
if (isOrCondition(fm.showIf)) {
return _.some(conditionList, (item) => {
return funcMap.get(item.operator)(
_.toString(_.get(formData, [...fieldPath, item.variable])),
item.value
);
});
}
return _.every(conditionList, (item) => {
return funcMap.get(item.operator)(
_.toString(_.get(formData, [...fieldPath, item.variable])),
item.value
);
});
};
export const getObjectConditionValue = (fm, formData) => {
const conditionList = parseExpression(fm.showIf);
const fieldPath = fm.fieldPath || [];
if (isOrCondition(fm.showIf)) {
return _.some(conditionList, (item) => {
return funcMap.get(item.operator)(
_.toString(_.get(formData, [...fieldPath, item.variable])),
item.value
);
});
}
return _.every(conditionList, (item) => {
return funcMap.get(item.operator)(
_.toString(_.get(formData, [...fieldPath, item.variable])),
item.value
);
});
};
export const isJSONstr = (str) => {
let result = true;
try {
const obj = JSON.parse(str);
if (typeof obj === 'object') {
result = true;
}
} catch (error) {
result = false;
}
return result;
};
export const json2Str = (obj) => {
if (!obj || !Object.keys(obj).length) return '';
return JSON.stringify(obj, null, 2);
};
export const str2Json = (str, type) => {
str = trim(str);
if (!str) {
let res: any = [];
if (schemaType.isListPrimaryType(type)) {
res = [];
} else if (schemaType.isObjectPrimaryType(type)) {
res = {};
} else if (schemaType.isTuplePrimaryType(type)) {
res = [];
}
return res;
}
return JSON.parse(str);
};
export const unknowType = {
dynamic: 'dynamic'
};
export const parseMapstring = (comSchema, val?) => {
let labelList: LabelListItem[] = [];
const type = get(comSchema, 'type');
if (schemaType.isMapString(type)) {
const value = val || get(comSchema, 'default') || {};
const defaultValue = keys(value || {});
if (defaultValue.length) {
labelList = map(defaultValue, (k) => {
return {
key: k,
value: get(value, `${k}`)
};
});
}
}
return labelList;
};
export const parseFieldProperties = (fieldSchema): LabelListItem[] => {
const properties = fieldSchema.properties || {};
const keys = _.keys(properties) || [];
if (!keys.length) return [];
return _.map(keys, (key) => {
return {
key,
value: setFieldDefaultValue(_.get(fieldSchema, `properties.${key}`)),
type: _.get(fieldSchema, `properties.${key}.type`)
};
});
};
export const parseAdditionalPropertiesField = (fieldSchema, val?) => {
let labelList: LabelListItem[] = [];
if (fieldSchema.type === 'object' && fieldSchema.additionalProperties) {
const value = val || get(fieldSchema, 'default') || {};
const defaultValue = keys(value || {});
if (defaultValue.length) {
labelList = map(defaultValue, (k) => {
return {
key: k,
value: get(value, `${k}`)
};
});
} else {
// properties
labelList = parseFieldProperties(fieldSchema);
}
}
return labelList;
};
export const parseQuery = (query) => {
const parsestr = split(query, '=');
return {
key: get(parsestr, '0'),
value: toString(get(parsestr, '1'))
};
};
export const parseOptions = (comSchema) => {
const type = get(comSchema, 'type');
let options: OptionsItem[] = [];
const defaultValue =
get(comSchema, 'options') ||
get(comSchema, 'enum') ||
get(comSchema, 'default') ||
[];
if (defaultValue.length) {
options = map(defaultValue, (val) => {
return {
label: val,
value: val
};
});
} else {
options = [];
}
return options;
};
// replace input width hintInput
export const parseComponentSchema = (schema: ComponentSchema) => {
const props = {
min: schema?.min || -Infinity,
max: schema?.max || Infinity,
maxLength: schema?.maxLength || 300,
sensitive: schema?.sensitive,
showWordLimit: schema?.maxLength,
minLength: schema?.minLength || null
};
const { type, required, sensitive } = schema;
const rules = { required };
if (schemaType.isStringType(type) || schemaType.isNumberType(type)) {
if (schema?.options?.length) {
return {
component: ['Select', 'Option'],
props: {
...props
},
rules: [{ ...rules, message: 'common.form.rule.select' }]
};
}
if (sensitive && schemaType.isStringType(type)) {
return {
component: ['HintInput'],
props: {
...props
},
rules: [{ ...rules, message: 'common.form.rule.input' }]
};
}
if (schemaType.isNumberType(type)) {
return {
component: ['InputNumber'],
props: {
...props
},
rules: [{ ...rules, message: 'common.form.rule.input' }]
};
}
if (!sensitive && schemaType.isStringType(type)) {
return {
component: ['HintInput'],
props: { ...props },
rules: [{ ...rules, message: 'common.form.rule.input' }]
};
}
}
if (schemaType.isMapString(type)) {
return {
component: ['XInputGroup'],
props: { ...props, alwaysDelete: true, shouldKey: true },
rules: [{ ...rules, message: 'common.form.rule.input' }]
};
}
if (schemaType.isListNumber(type) || schemaType.isListString(type)) {
return {
component: ['Select', 'Option'],
props: {
...props,
multiple: true,
allowCreate: !schema.options?.length
},
rules: [{ ...rules, message: 'common.form.rule.select' }]
};
}
if (schemaType.isBoolenType(type)) {
return {
component: ['Checkbox'],
props: { ...props },
rules: [{ ...rules, message: 'common.form.rule.select' }]
};
}
return {
component: ['AceEditor'],
props: {
...props,
lang: 'yaml',
showGutter: true
},
rules: [
{
...rules,
validator(val, callback) {
const result = validateYaml(val);
if (result.error) {
callback(`${result.error?.message}`);
} else if (!required) {
callback();
} else if (result?.empty) {
callback(
`${schema.name}${i18n.global.t('common.form.rule.input')}`
);
} else {
callback();
}
},
message: ''
}
]
};
};
export const checkHasValue = (property) => {
if (typeof property === 'undefined') {
return false;
}
if (typeof property === 'object' && !Array.isArray(property)) {
return _.keys(property).length !== 0;
}
if (Array.isArray(property)) {
return property.length !== 0;
}
if (_.isBoolean(property)) {
return property;
}
if (_.isNumber(property)) {
return true;
}
return !!property;
};
export const XMLParser = (xmlString) => {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
return xmlDoc;
};
export const parseXMLFragment = (
xmlFragment,
options: { item: string; label: string; value: string }
) => {
const result: Array<{ label: string; value: string }> = [];
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlFragment, 'text/xml');
const items = xmlDoc.querySelectorAll(options.item);
items.forEach(function (item: any) {
const label = item.querySelector(options.label).textContent;
const value = item.querySelector(options.value).textContent;
result.push({
label,
value
});
});
return result;
}; |
import React, { useEffect, useState } from "react";
import { format } from "date-fns";
import Service from "./Service";
import BookingModal from "./BookingModal";
import { useQuery } from "react-query";
import Loading from "../Shared/Loading/Loading";
const AvailableAppoinment = ({ date }) => {
const [treatment, setTreatment] = useState(null);
const formattedDate = format(date, "PP");
const {
data: services,
isLoading,
refetch,
} = useQuery(["available", formattedDate], () =>
fetch(
`https://safe-shelf-64042.herokuapp.com/available?date=${formattedDate}`
).then((res) => res.json())
);
if (isLoading) {
return <Loading></Loading>;
}
return (
<div className="my-10 px-6 max-w-7xl mx-auto">
<p className="text-center text-xl bg-clip-text text-transparent bg-gradient-to-r from-secondary to-primary my-10">
Available Appoinments on {format(date, "PP")}
</p>
<div className="my-10 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{services?.map((service) => (
<Service
key={service._id}
service={service}
setTreatment={setTreatment}
></Service>
))}
</div>
{treatment && (
<BookingModal
treatment={treatment}
date={date}
setTreatment={setTreatment}
refetch={refetch}
></BookingModal>
)}
</div>
);
};
export default AvailableAppoinment; |
import { Socket } from 'socket.io-client';
import { InjectableService } from 'src/common/decorators/common.decorator';
import { io } from 'socket.io-client';
import { Event } from 'src/app/event/entities/event.entity';
import { Logger } from '@nestjs/common';
import { isWorkerMode } from 'src/config/app.config';
import { ConfigService } from '@nestjs/config';
import { SocketConfig } from 'src/config/socket.config';
@InjectableService()
export class SocketClientService {
private socket: Socket;
private logger = new Logger('SocketClientService');
constructor(private configService: ConfigService) {}
async init(): Promise<void> {
if (!isWorkerMode) {
return;
}
const config = SocketConfig(this.configService);
const socket = io(config.fullUrl || `${config.useSsl ? 'https' : 'http'}://${config.host}:${config.connectPort}`, {
auth: {
token:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1dWlkIjoiMjA0MjIzMGEtZmQwMS00OWQ5LWJiYmMtM2MxMmRkN2QxZDJiIiwiaWF0IjoxNjQyMTg3NTM5fQ.AU2R5hAuLr0JcibiA-DZUgfZwBDD_ucFaxr4JrxUS2I',
},
});
this.socket = socket;
this.afterInit(socket);
this.logger.log('socket client initialized');
}
async afterInit(socket: Socket): Promise<void> {
socket.on('ping', async (data, callback) => {
if (data === 'ping') {
callback('pong');
} else {
callback('mong');
}
});
}
private async send(data: any, channel: string): Promise<any> {
return await new Promise((resolve, reject) => {
try {
this.socket.emit(channel, data, (res: any) => {
return resolve(res);
});
} catch (e) {
return reject(e);
}
});
}
async sendEvent(event: Event): Promise<boolean> {
if (!isWorkerMode) {
return;
}
this.logger.verbose(`send event: ${event.uuid}`);
const res = await this.send(event, 'events');
this.logger.verbose(`event ${event.uuid} sent`);
return res;
}
} |
<template>
<div class="student-evaluate-class">
<div class="crumbs">
<el-breadcrumb separator="/">
<el-breadcrumb-item>
<i class="el-icon-fa fa-edit"></i> 学生评课
</el-breadcrumb-item>
</el-breadcrumb>
</div>
<div class="container">
<div class="table">
<el-table :data="tableData" stripe>
<el-table-column label="选课Id" prop="courseId" />
<el-table-column label="课程名" prop="courseName" />
<el-table-column label="教师" prop="teacherName" />
<el-table-column label="学分" prop="credit" />
<el-table-column align="center" label="操作" width="200px">
<template slot-scope="scope">
<el-button @click="evaluateClass(scope.row.courseId)" size="mini"
type="primary">评价
</el-button>
</template>
</el-table-column>
</el-table>
</div>
</div>
<el-dialog
title="学生评课"
:visible.sync="showWin"
width="50%"
:before-close="handleClose"
>
<div class="block">
<span style="align-items: center;">
请选择您对该课程的评分
</span>
<div style="margin: 15px 0;"></div>
<el-rate v-model="evaluation.star" :colors="colors"> </el-rate>
<div style="margin: 20px 0;"></div>
<el-input
type="textarea"
placeholder="请问您对本课程有何意见或建议"
v-model="evaluation.textarea"
maxlength="200"
show-word-limit
:autosize="{ minRows: 5, maxRows: 6 }"
>
</el-input>
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="closeWin()">取 消</el-button>
<el-button type="primary" @click="uploadEvaluation()">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import * as api from "../../api/student/evaluateCourse";
export default {
name: "StudentEvaluateClass",
data() {
return {
tableData: [],
showWin: false,
selectedClass: 0,
colors: ["#99A9BF", "#F7BA2A", "#FF9900"],
evaluation: {
textarea: "",
star: 0,
}
};
},
methods: {
getList() {
api.list().then(res => {
this.tableData = res;
})
},
evaluateClass(studentCourseId) {
this.showWin = true;
this.selectedClass = studentCourseId;
this.evaluation = {
textarea: "",
star: 0,
courseId: studentCourseId,
};
},
uploadEvaluation() {
this.closeWin();
api.create(this.evaluation).then(() => {
this.$message.success("评价成功");
this.getList();
})
},
closeWin() {
this.showWin = false;
},
},
created() {
this.getList();
}
};
</script>
<style scoped>
</style> |
---
title: Book Review of the Phoenix Project
date: '2022-06-14'
description: 'A short review of perhaps the only fun fiction book on IT and DevOps'
featured: false
---
The Phoenix Project: A Novel About IT, DevOps, and Helping Your Business Win is a bestselling business novel by Gene Kim, Kevin Behr, and George Spafford.
The book tells the story of an IT manager at a manufacturing company who is tasked with turning around a failing IT project, known as the Phoenix Project. Our main character is given 90 days to fix the mess _or else_.
If you’ve ever worked on an IT project with stakeholders and said _‘they should make a sitcom about this’_, this is that deja-vu inducing sitcom.
One of the strengths of the book is its ability to make technical and business concepts relatable to a wide audience through practical manufacturing comparisons. The story is set in the context of a fictional manufacturing company, but the challenges and solutions discussed in the book are applicable to any modern organization.
The book also focuses on DevOps, presenting it is a bridge between development and operations teams that aims to deliver high-quality software faster and create a culture of collaboration and experimentation within an organization.
Another key theme of the book is the importance of measuring and managing IT performance. The characters in the story use metrics such as "lead time" and "deployment frequency" to understand and improve the performance of the Phoenix Project.
## Usage of Manufacturing Metaphors
I enjoyed the 'factory tour' moments throughout the book, which serve demonstrate concepts and practices of IT management and DevOps.

One of the key manufacturing metaphors used in the book is the "value stream". The value stream refers to the process by which a product or service is designed, developed, and delivered to customers. The book describes how IT projects can be thought of as a value stream, with the goal of delivering software that provides value to the business as quickly and efficiently as possible.
Another manufacturing metaphor used in the book is the "queue". The queue refers to the time it takes for work to be completed, from start to finish. In the factory, this is the time taken to manufacture a product. In the book, the queue represents the time it takes for IT changes to be made, from the time they are requested to the time they are deployed.
Overall, the use of manufacturing metaphors in the book provides a clear and relatable framework for understanding the concepts of IT management and DevOps. It helps readers to think of virtual IT projects in the same way they might think of a physical manufacturing processes, making it easier to understand and apply the principles discussed in the book.
## Lessons from The Phoenix Project
Below is the TLDR (too long didn't read) of the book:
1. The importance of IT in modern business: The book presents a compelling case for the role of IT in driving business success and highlights the need for organizations to prioritize and invest in their IT systems and infrastructure.
2. The benefits of DevOps: The book introduces the concept of DevOps and demonstrates how it can help organizations to achieve business agility and create a culture of collaboration and experimentation within an organization.
3. The need for effective IT governance: The book illustrates the importance of IT governance in ensuring that IT projects align with the overall goals and objectives of the organization, and in preventing the "Shadow IT"
4. The value of metrics in managing IT performance: The book shows how metrics such as "lead time" and "deployment frequency" can be used to understand and improve the performance of IT projects, and how an understanding of these metrics can help organizations to make data-driven decisions.
5. The importance of collaboration and communication in IT: The book demonstrates how communication and collaboration between development, operations, and business teams are crucial to achieving IT success, it also showed how silos can be destructive for the company and how to break those silos.
## Summary
The Phoenix Project is a highly engaging and informative read. It is a must-read for anyone in IT, as well as for anyone interested in understanding the role of IT in modern business. It strikes a great balance between fiction and technical insight, with some humor as well making it a enjoyable book to read.
I’d recommend the book - I enjoyed how it teaches through storytelling and I certainly preferred it to a dry textbook on IT change management. My only criticism would be that it is technically dated now, but the lessons about people and process still hold true. |
#ifndef CLIMB_H
#define CLIMB_H 1
const int holdPower = 40; // Climb motor power when holding at the top
const int upPower = 255; // Climb motor power when ascending
const int downPower = -255; // Climb motor power when descending
const long holdTime = 10000; // Time to hold before descending
const long currentThreshold = 1750; // Current sensor threshold that determines whether it's been stalled
const long currentStallTime = 250; // How long the current sensor needs to be stalled for it to be "tripped"
long currentChangeTime = 0; // How long the current sensor has been stalled for
int current = 0; // Current sensor reading
// Climb states for state machine
enum climbState {
STOPPED = 0, // Motor off
UP, // Motor on for ascension
DOWN, // Motor on for descension
HOLD // Motor on for holding at the top
};
// Climb state management variables
unsigned long climbStateTime = 0;
climbState curClimbState = STOPPED;
// Setup sensors, motors, and LEDC channels for climbing
void setupClimb(void) {
pinMode(ciCurrentSensor, INPUT); // Current sensor
ledcAttachPin(ciMotorClimbA, 5); // assign Motors pins to channels
ledcAttachPin(ciMotorClimbB, 6);
ledcSetup(5, 20000, 8); // 20mS PWM, 8-bit resolution
ledcSetup(6, 20000, 8);
}
// Power the climb motor between -255 to 255
void climb(int power) {
if (power > 0) {
ledcWrite(5, min(255, abs(power)));
ledcWrite(6, 0);
} else if (power < 0) {
ledcWrite(5, 0);
ledcWrite(6, min(255, abs(power)));
} else {
ledcWrite(5, 0);
ledcWrite(6, 0);
}
}
// Change and log the climb state to the given climbState
void changeClimbState(climbState nextState) {
curClimbState = nextState;
switch (curClimbState) {
case STOPPED:
Serial.printf("Switched state to STOPPED, took %lu time\n", millis() - climbStateTime);
break;
case UP:
Serial.printf("Switched state to UP, took %lu time\n", millis() - climbStateTime);
break;
case DOWN:
Serial.printf("Switched state to DOWN, took %lu time\n", millis() - climbStateTime);
break;
case HOLD:
Serial.printf("Switched state to HOLD, took %lu time\n", millis() - climbStateTime);
break;
}
climbStateTime = millis();
}
// Stop the climb by changing the climb state to STOPPED
void stopClimb(void) {
changeClimbState(STOPPED);
}
// Start the climb by changing the climb state to UP
void startClimb(void) {
changeClimbState(UP);
}
// Handle the climb state machine based on the current climb state
void handleClimb(void) {
current = analogRead(ciCurrentSensor);
if (current <= currentThreshold) { // If the current is underneath the current stall threshold
currentChangeTime = 0; // set the time the current has stalled for to 0
} else if (currentChangeTime != 0 && millis() > currentChangeTime) { // Else if the current has been stalling for more than currentChangeTime (tripped)
changeClimbState(HOLD); // change the climb state to HOLD
} else if (currentChangeTime == 0 && current > currentThreshold) { // Else if the current sensor just started stalling
currentChangeTime = millis() + currentStallTime; // Set the current stall timeout to currentStallTime milliseconds from now
}
switch (curClimbState) {
case STOPPED: // STOPPED: set the climb motor to 0 power
climb(0);
break;
case UP: // UP: set the climb motor to the ascent power
climb(upPower);
break;
case DOWN: // DOWN: set the climb motor to the descent power
climb(-downPower);
break;
case HOLD: // HOLD: set the climb motor to the hold power, start descending after holdTime amount of time after entering the state
climb(holdPower);
if (millis() > climbStateTime + holdTime)
changeClimbState(DOWN);
break;
}
}
#endif |
"use strict";
namespace core {
export class User {
private _displayName :string;
private _emailAddress : string;
private _username : string;
private _password : string;
constructor(displayName: string = "", emailAddress: string = "",
username : string = "", password : string = "") {
this._displayName = displayName;
this._emailAddress = emailAddress;
this._username = username;
this._password = password;
}
public get displayName() : string {
return this._displayName;
}
public set displayName(value : string) {
this._displayName = value;
}
public get emailAddress() :string {
return this._emailAddress;
}
public set emailAddress(value : string) {
this._emailAddress = value;
}
public get username() : string {
return this._username;
}
public set username(value : string) {
this._username = value;
}
public get password() : string {
return this._password;
}
public set password(value : string) {
this._password = value;
}
public toString() : string {
return `Display Name: ${this._displayName}\n
Email Address: ${this._emailAddress}\n
Username: ${this._username}`;
}
public toJSON() : {Username: string; DisplayName : string; EmailAddress : string } {
return {
"DisplayName": this._displayName,
"EmailAddress": this._emailAddress,
"Username": this._username
}
}
public fromJSON(data : User) : void {
this._displayName = data.displayName;
this._emailAddress = data.emailAddress;
this._username = data.username;
this._password = data.password;
}
/*****
fromJSON(data) {
if (!data) throw new Error("No data provided");
this._displayName = data.hasOwnProperty('DisplayName') ? data.DisplayName : this._displayName;
this._emailAddress = data.hasOwnProperty('EmailAddress') ? data.EmailAddress : this._emailAddress;
this._username = data.hasOwnProperty('Username') ? data.Username : this._username;
this._password = data.hasOwnProperty('Password') ? data.Password : this._password;
}
******/
public serialize() : string | null {
if(this._displayName !== "" && this._emailAddress !== "" && this._username !== ""){
return `${this._displayName}, ${this._emailAddress}, ${this._username}`;
}
console.error("One or more properties of the user object are missing or invalid");
return null;
}
public deserialize(data : string) : void{
let propertyArray = data.split(",");
this._displayName = propertyArray[0];
this._emailAddress = propertyArray[1];
this._username = propertyArray[2];
}
}
} |
{% extends 'base.html' %}
{% block content %}
<main class="home">
<section class="hero-section text-center">
<div class="container container--narrow">
<div class="hero-section__box">
<h2>CONNECT WITH <span>DEVELOPERS</span></h2>
<h2>FROM AROUND THE WORLD</h2>
</div>
<div class="hero-section__search">
<form class="form" action="" method="get">
<div class="form__field">
<label for="formInput#search">Search Developers </label>
<input class="input input--text" id="formInput#search" type="text" name="query"
placeholder="Search by developer name" value="{{ query }}" />
</div>
<input class="btn btn--sub btn--lg" type="submit" value="Search"/>
</form>
</div>
</div>
</section>
<!-- Search Result: DevList -->
<section class="devlist">
<div class="container">
<div class="grid grid--three">
{% for profile in all_profiles %}
<div class="column card">
<div class="dev">
<a href="{% url 'profile' profile.id %}" class="card__body">
<div class="dev__profile">
<img class="avatar avatar--md" src="{{ profile.photo.url }}"
alt="{{ profile.fullname }}"/>
<div class="dev__meta">
<h3>{% if profile.fullname %}
{{ profile.fullname }}
{% else %}
{{ profile.user.username }} {% endif %}</h3>
<h5>{% if profile.short_intro %} {{ profile.short_intro }} {% endif %}</h5>
</div>
</div>
<p class="dev__info">
{% if profile.bio %}
{{ profile.bio|linebreaksbr }}
{% endif %}
</p>
<div class="dev__skills">
{% for skill in profile.skill_set.all|slice:"6" %}
<span class="tag tag--pill tag--main">
<small>{{ skill.name }}</small>
</span>
{% endfor %}
</div>
</a>
</div>
</div>
{% empty %}
<small style="display: block; width:100%; text-align: center;">No one found by your request "{{ query }}"</small>
{% endfor %}
</div>
</div>
</section>
{% include 'components/_pagination.html' with queryset=all_profiles custom_range=custom_range %}
</main>
{% endblock content %} |
=== Paging
:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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.
:page-partial:
The xref:refguide:applib:index/annotation/CollectionLayout.adoc#paged[paged()] element specifies the number of rows to display in a (parented) collection.
[WARNING]
====
The xref:vro:ROOT:about.adoc[RestfulObjects viewer] currently does not support paging.
The xref:vw:ROOT:about.adoc[Web UI (Wicket viewer)] _does_ support paging, but note that the paging is performed client-side rather than server-side.
We therefore recommend that large collections should instead be modelled as actions (to allow filtering to be applied to limit the number of rows).
====
For example:
[source,java]
----
import lombok.Getter;
import lombok.Setter;
public class Order {
@CollectionLayout(paged=15)
@Getter @Setter
private SortedSet<OrderLine> details = ...
}
----
It is also possible to specify a global default for the page size of parented collections, using the xref:refguide:config:sections/causeway.applib.adoc#causeway.applib.annotation.collection-layout.paged[causeway.applib.annotation.collection-layout.paged] configuration property. |
#include "Application.h"
#include "Renderer3D.h"
#include "SDL_opengl.h"
#include <gl/GL.h>
#include <gl/GLU.h>
#include "Math/float4x4.h"
#include "mmgr/mmgr.h"
Renderer3D::Renderer3D(bool startEnabled) : Module(true)
{
name = "renderer";
}
// Destructor
Renderer3D::~Renderer3D()
{}
// Called before render is available
bool Renderer3D::Init(JSON_Object* root)
{
LOG_CONSOLE("Creating 3D Renderer context");
bool ret = true;
//Create context
context = SDL_GL_CreateContext(app->window->window);
if(context == NULL)
{
LOG_CONSOLE("OpenGL context could not be created! SDL_Error: %s\n", SDL_GetError());
ret = false;
}
if(ret == true)
{
//Use Vsync
if(VSYNC && SDL_GL_SetSwapInterval(1) < 0)
LOG_CONSOLE("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError());
//Initialize Projection Matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glLoadMatrixf(app->camera->GetProjectionMatrix());
//Check for error
GLenum error = glGetError();
if(error != GL_NO_ERROR)
{
//LOG_CONSOLE("Error initializing OpenGL! %s\n", gluErrorString(error));
ret = false;
}
//Initialize Modelview Matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Check for error
error = glGetError();
if(error != GL_NO_ERROR)
{
//LOG_CONSOLE("Error initializing OpenGL! %s\n", gluErrorString(error));
ret = false;
}
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glClearDepth(1.0f);
//Initialize clear color
glClearColor(0.5f, 0.5f, 0.5f, 1.f);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//Check for error
error = glGetError();
if(error != GL_NO_ERROR)
{
//LOG_CONSOLE("Error initializing OpenGL! %s\n", gluErrorString(error));
ret = false;
}
GLfloat LightModelAmbient[] = {0.0f, 0.0f, 0.0f, 1.0f};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LightModelAmbient);
lights[0].ref = GL_LIGHT0;
lights[0].ambient.Set(0.25f, 0.25f, 0.25f, 1.0f);
lights[0].diffuse.Set(0.75f, 0.75f, 0.75f, 1.0f);
lights[0].SetPos(0.0f, 0.0f, 2.5f);
lights[0].Init();
GLfloat MaterialAmbient[] = {1.0f, 1.0f, 1.0f, 1.0f};
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, MaterialAmbient);
GLfloat MaterialDiffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialDiffuse);
LOG_CONSOLE("OpenGL initialization correct. Version %s", glGetString(GL_VERSION));
// GLEW initialization
GLenum err = glewInit();
if (err != GLEW_OK)
{
LOG_CONSOLE("Error loading GLEW: %s", glewGetErrorString(err));
}
else LOG_CONSOLE("GLEW initialization correct. Version %s", glewGetString(GLEW_VERSION));
}
Load(root);
SetDepth();
SetCullFace();
lights[0].Active(true);
SetLighting();
SetColorMaterial();
SetTexture2D();
SetWireframe();
drawVertexNormals = false;
drawTriangleNormals = false;
int w, h;
app->window->GetWindowSize(w, h);
OnResize(w, h);
/*vertexArray = new VertexArray();
indexBuffer = new IndexBuffer();
vertexBuffer = new VertexBuffer();*/
FrameBufferProperties props;
props.width = w;
props.height = h;
frameBuffer = new FrameBuffer(props);
return ret;
}
// PreUpdate: clear buffer
bool Renderer3D::PreUpdate(float dt)
{
glClearColor(0.05f, 0.05f, 0.05f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glLoadIdentity();
//glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(app->camera->GetViewMatrix());
if (app->input->GetKey(SDL_SCANCODE_M) == KEY_DOWN)
{
wireframe = !wireframe;
wireframe ? glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) : glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
// light 0 on cam pos
lights[0].SetPos(app->camera->position.x, app->camera->position.y, app->camera->position.z);
for(uint i = 0; i < MAX_LIGHTS; ++i)
lights[i].Render();
return true;
}
// Draw present buffer to screen
bool Renderer3D::Draw(float dt)
{
app->editor->OnImGuiRender(dt, frameBuffer);
frameBuffer->Bind();
glClearColor(0.1f, 0.1f, 0.1f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
DrawGrid();
for (const auto& g : geometries)
g->Draw(drawVertexNormals, drawTriangleNormals);
for (const auto& mesh : meshes)
mesh->Draw(drawVertexNormals, drawTriangleNormals);
frameBuffer->Unbind();
SDL_GL_SwapWindow(app->window->window);
return true;
}
// Called before quitting
bool Renderer3D::CleanUp()
{
LOG_CONSOLE("Destroying 3D Renderer");
geometries.clear();
/*delete vertexArray;
delete vertexBuffer;
delete indexBuffer;*/
RELEASE(vertexArray);
RELEASE(vertexBuffer);
RELEASE(indexBuffer);
RELEASE(frameBuffer);
SDL_GL_DeleteContext(context);
return true;
}
void Renderer3D::OnResize(int width, int height)
{
glViewport(0, 0, width, height);
float ratio = (float)width / (float)height;
app->camera->SetRatio(ratio);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glLoadMatrixf(app->camera->GetProjectionMatrix());
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void Renderer3D::SetDepth()
{
depth ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST);
LOG_CONSOLE("-- GL_DEPTH_TEST -- set to %d", depth);
}
void Renderer3D::SetCullFace()
{
cullFace ? glDisable(GL_CULL_FACE) : glEnable(GL_CULL_FACE);
LOG_CONSOLE("-- GL_CULL_FACE -- set to %d", cullFace);
}
void Renderer3D::SetLighting()
{
lighting ? glEnable(GL_LIGHTING) : glDisable(GL_LIGHTING);
LOG_CONSOLE("-- GL_LIGHTING -- set to %d", lighting);
}
void Renderer3D::SetColorMaterial()
{
colorMaterial ? glEnable(GL_COLOR_MATERIAL) : glDisable(GL_COLOR_MATERIAL);
LOG_CONSOLE("-- GL_COLOR_MATERIAL -- set to %d", colorMaterial);
}
void Renderer3D::SetTexture2D()
{
texture2D ? glEnable(GL_TEXTURE_2D) : glDisable(GL_TEXTURE_2D);
LOG_CONSOLE("-- GL_TEXTURE_2D -- set to %d", texture2D);
}
void Renderer3D::SetWireframe()
{
wireframe ? glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) : glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
LOG_CONSOLE("-- WIREFRAME -- set to %d", wireframe);
}
void Renderer3D::Save(JSON_Object* root)
{
json_object_set_value(root, name.c_str(), json_value_init_object());
JSON_Object* renObj = json_object_get_object(root, name.c_str());
json_object_set_boolean(renObj, "depth", depth);
json_object_set_boolean(renObj, "cullface", cullFace);
json_object_set_boolean(renObj, "lighting", lighting);
json_object_set_boolean(renObj, "color material", colorMaterial);
json_object_set_boolean(renObj, "texture2D", texture2D);
json_object_set_boolean(renObj, "wireframe", wireframe);
}
void Renderer3D::Load(JSON_Object* root)
{
json_object_set_value(root, name.c_str(), json_object_get_value(root, name.c_str()));
JSON_Object* renObj = json_object_get_object(root, name.c_str());
depth = json_object_get_boolean(renObj, "depth");
cullFace = json_object_get_boolean(renObj, "cullface");
lighting = json_object_get_boolean(renObj, "lighting");
colorMaterial = json_object_get_boolean(renObj, "color material");
texture2D = json_object_get_boolean(renObj, "texture2D");
wireframe = json_object_get_boolean(renObj, "wireframe");
drawVertexNormals = json_object_get_boolean(renObj, "showNormals");
}
void Renderer3D::Submit(KbGeometry* geometry)
{
geometries.push_back(geometry);
}
void Renderer3D::Submit(const std::vector<KbGeometry>& geos)
{
//geometries.insert(geometries.end(), geos.begin(), geos.end());
for (auto g : geos)
Submit(&g);
}
// TODO: Still need to check if the childs do have more childs
void Renderer3D::Submit(GameObject* go)
{
for (const auto& child : go->GetChilds())
{
ComponentMesh* m = (ComponentMesh*)child->GetComponent(ComponentType::MESH);
meshes.push_back(m);
}
if (go->GetComponent(ComponentType::MESH))
meshes.push_back((ComponentMesh*)go->GetComponent(ComponentType::MESH));
}
void Renderer3D::DrawGrid()
{
glLineWidth(1.5f);
glBegin(GL_LINES);
glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f);
glVertex3f(1.0f, 0.1f, 0.0f); glVertex3f(1.1f, -0.1f, 0.0f);
glVertex3f(1.1f, 0.1f, 0.0f); glVertex3f(1.0f, -0.1f, 0.0f);
glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 1.0f, 0.0f);
glVertex3f(-0.05f, 1.25f, 0.0f); glVertex3f(0.0f, 1.15f, 0.0f);
glVertex3f(0.05f, 1.25f, 0.0f); glVertex3f(0.0f, 1.15f, 0.0f);
glVertex3f(0.0f, 1.15f, 0.0f); glVertex3f(0.0f, 1.05f, 0.0f);
glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 1.0f);
glVertex3f(-0.05f, 0.1f, 1.05f); glVertex3f(0.05f, 0.1f, 1.05f);
glVertex3f(0.05f, 0.1f, 1.05f); glVertex3f(-0.05f, -0.1f, 1.05f);
glVertex3f(-0.05f, -0.1f, 1.05f); glVertex3f(0.05f, -0.1f, 1.05f);
float d = 200.0f;
glColor4f(1.0f, 1.0f, 1.0f, 0.65f);
glLineWidth(1.0f);
for (float i = -d; i <= d; i += 1.0f)
{
glVertex3f(i, 0.0f, -d);
glVertex3f(i, 0.0f, d);
glVertex3f(-d, 0.0f, i);
glVertex3f(d, 0.0f, i);
}
glEnd();
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
} |
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import cs3500.marblesolitaire.model.hw02.EnglishSolitaireModel;
import cs3500.marblesolitaire.model.hw02.MarbleSolitaireModel;
import cs3500.marblesolitaire.model.hw04.EuropeanSolitaireModel;
import cs3500.marblesolitaire.model.hw04.TriangleSolitaireModel;
import cs3500.marblesolitaire.view.MarbleSolitaireTextView;
import cs3500.marblesolitaire.view.MarbleSolitaireView;
import cs3500.marblesolitaire.view.TriangleSolitaireTextView;
import static org.junit.Assert.assertEquals;
/**
* Tests the functionality of MarbleSolitaireTextView.
*/
public class TriangleSolitaireTextViewTest {
//Needs to change
//Models
MarbleSolitaireModel model1;
MarbleSolitaireModel model2;
MarbleSolitaireModel model3;
MarbleSolitaireModel model4;
//MarbleSolitaireModel modelWithArmThickOnlyOne;
MarbleSolitaireView view;
MarbleSolitaireView view2;
MarbleSolitaireView viewWithStringbuilderDestination;
StringBuilder output;
//HW3 Code:
MarbleSolitaireModel triangleModel1;
MarbleSolitaireView triangleView1;
MarbleSolitaireModel triangleModel3;
MarbleSolitaireView triangleView3;
@Before
public void setUp() {
//Models
model1 = new EnglishSolitaireModel();
model2 = new EnglishSolitaireModel(2, 2);
model3 = new EnglishSolitaireModel(5);
model4 = new EnglishSolitaireModel(7, 8, 8);
//modelWithArmThickOnlyOne = new EnglishSolitaireModel(1);
//StringBuilder output
output = new StringBuilder();
//View
view = new MarbleSolitaireTextView(model1);
viewWithStringbuilderDestination = new MarbleSolitaireTextView(model1, output);
//HW3 Code:
triangleModel1 = new TriangleSolitaireModel();
triangleView1 = new TriangleSolitaireTextView(triangleModel1);
triangleModel3 = new TriangleSolitaireModel(9);
triangleView3 = new TriangleSolitaireTextView(triangleModel3);
}
@Test
public void testEuropeanInitialToString() {
assertEquals(" _\n" +
" O O\n" +
" O O O\n" +
" O O O O\n" +
"O O O O O", triangleView1.toString());
}
@Test
public void testEuropeanWithArmThickness5InitialToString() {
assertEquals(" _\n" +
" O O\n" +
" O O O\n" +
" O O O O\n" +
" O O O O O\n" +
" O O O O O O\n" +
" O O O O O O O\n" +
" O O O O O O O O\n" +
"O O O O O O O O O", triangleView3.toString());
}
@Test(expected = IllegalArgumentException.class)
public void viewConstructorThrowsIllegalArgumentExceptionForNull() {
view2 = new MarbleSolitaireTextView(null);
}
@Test
public void testInitialToString() {
assertEquals(" O O O\n" +
" O O O\n" +
"O O O O O O O\n" +
"O O O _ O O O\n" +
"O O O O O O O\n" +
" O O O\n" +
" O O O", view.toString());
}
@Test
public void testToStringAfterMove() {
model1.move(5, 3, 3, 3);
assertEquals(" O O O\n" +
" O O O\n" +
"O O O O O O O\n" +
"O O O O O O O\n" +
"O O O _ O O O\n" +
" O _ O\n" +
" O O O", view.toString());
}
//New Tests From HW2
@Test
public void testRenderBoard() throws IOException {
viewWithStringbuilderDestination.renderBoard();
assertEquals(" O O O\n" +
" O O O\n" +
"O O O O O O O\n" +
"O O O _ O O O\n" +
"O O O O O O O\n" +
" O O O\n" +
" O O O", output.toString());
assertEquals(this.viewWithStringbuilderDestination.toString(), output.toString());
}
@Test
public void testRenderMessage() throws IOException {
viewWithStringbuilderDestination.renderMessage("TEST MESSAGE 123");
assertEquals("TEST MESSAGE 123", output.toString());
}
@Test(expected = IllegalArgumentException.class)
public void viewInvalidNullAppendableConstructor() {
viewWithStringbuilderDestination = new MarbleSolitaireTextView(model1, null);
}
@Test(expected = IllegalArgumentException.class)
public void viewInvalid2ParameterNullConstructor() {
viewWithStringbuilderDestination = new MarbleSolitaireTextView(null, output);
}
@Test(expected = IllegalArgumentException.class)
public void viewAlsoInvalid2ParameterNullConstructor() {
viewWithStringbuilderDestination = new MarbleSolitaireTextView(null, null);
}
} |
import os
import pandas as pd
import pingouin as pg
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pyreadr
import yaml
from matplotlib.backends.backend_pdf import PdfPages
from na_py_tools.defaults import RESULTS_DIR, SETTINGS_DIR
from na_py_tools.utils import p2star
# Params
save_pdf = True
study = 'letter_spacing'
SMALL_SIZE = 12
MEDIUM_SIZE = 14
BIGGER_SIZE = 16
plt.rc('font', size = SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize = BIGGER_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize = MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize = SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize = SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize = SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize = BIGGER_SIZE) # fontsize of the figure title
# Load params YAML
with open(SETTINGS_DIR + '/params.yaml') as file:
p = yaml.full_load(file)
# Read data
data = pd.read_pickle(
os.path.join(RESULTS_DIR, 'df_data', 'all', 'et', 'et_features.pkl'))
data = data[(data['study'] == study)]
# Create reports dir
results_dir = os.path.join(RESULTS_DIR, 'stats', 'et_features')
os.makedirs(results_dir, exist_ok=True)
data_long = pd.melt(data, id_vars=['group','condition','subj_id'], var_name = 'measure', value_name = 'value')
# %% Generate pdf from figures
for meas_type in ['_min', '', '_all']:
meas_list = p['params']['et']['meas_list' + meas_type]
if save_pdf:
pdf = PdfPages(results_dir + '/' + study + '_ET_stats' + meas_type + '.pdf')
for meas_name in meas_list:
# %%Boxplot
fig = plt.figure(figsize=(16, 13))
fig.add_axes([0.05, 0.5, 0.26, 0.4])
ax = sns.boxplot(x='condition', y=meas_name, data=data, showmeans=False, color='b', width=.6)
sns.swarmplot(x='condition', y=meas_name, data=data, color=(.3,.3,.3), ax=ax)
ax.set(xlabel='Spacing', ylabel='');
plt.title(meas_name)
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# ANOVA table
fig.add_axes([0.33, 0.82, 0.6, 0.08]).axis('off')
stats = pg.rm_anova(data=data, dv=meas_name, within='condition',
subject='subj_id', correction='auto', detailed=True)
num_col = stats.columns.difference(['Source', 'sphericity'])
stats.loc[0,num_col] = stats.loc[0,num_col].apply('{:.5g}'.format)
the_table = plt.table(cellText=stats.values,
colWidths=[x*.3 for x in [.2, .2, .1, .2, .2, .3, .3, .2, .2, .2, .2, .3]],
colLabels=stats.columns,
cellLoc = 'center', rowLoc = 'center',
loc = 'center left')
the_table.auto_set_font_size(False)
the_table.set_fontsize(8.5)
the_table.scale(1, 1.5)
plt.text(0, 1, 'Repeated measures ANOVA')
# Post-hoc table parametric
fig.add_axes([0.33, 0.7, 0.6, 0.1]).axis('off')
stats = pg.pairwise_ttests(data=data, dv=meas_name, within='condition',
subject='subj_id', return_desc=True, padjust='bonf',
effsize='cohen', parametric=True)
num_col = ['p-unc', 'p-corr']
stats[num_col] = stats[num_col].applymap('{:.5g}'.format)
the_table = plt.table(cellText=stats.values,
colWidths=[x*.3 for x in [.2, .1, .1, .2, .2, .2, .2, .2, .25, .25, .2, .25, .3, .3, .2, .2, .2]],
colLabels=stats.columns,
cellLoc = 'center', rowLoc = 'center',
loc = 'center left')
the_table.auto_set_font_size(False)
the_table.set_fontsize(8.5)
the_table.scale(1, 1.5)
plt.text(0, 1, 'Post-hoc (paired t-tests)')
# Friedman table
fig.add_axes([0.33, 0.6, 0.6, 0.06]).axis('off')
stats = pg.friedman(data=data, dv=meas_name, within='condition',
subject='subj_id')
num_col = 'p-unc'
stats[num_col] = stats[num_col].apply('{:.5g}'.format)
the_table = plt.table(cellText=stats.values,
colWidths=[x*.3 for x in [.2, .2, .3, .3]],
colLabels=stats.columns,
cellLoc = 'center', rowLoc = 'center',
loc = 'center left')
the_table.auto_set_font_size(False)
the_table.set_fontsize(8.5)
the_table.scale(1, 1.5)
plt.text(0, 1, 'Friedman test')
# Post-hoc table non-parametric
fig.add_axes([0.33, 0.48, 0.6, 0.1]).axis('off')
stats = pg.pairwise_ttests(data=data, dv=meas_name, within='condition',
subject='subj_id', return_desc=True, padjust='bonf',
effsize='cohen', parametric=False)
num_col = ['p-unc', 'p-corr']
stats[num_col] = stats[num_col].applymap('{:.5g}'.format)
the_table = plt.table(cellText=stats.values,
colWidths=[x*.3 for x in [.2, .1, .1, .2, .2, .2, .2, .2, .25, .25, .25, .3, .3, .2, .2]],
colLabels=stats.columns,
cellLoc = 'center', rowLoc = 'center',
loc = 'center left')
the_table.auto_set_font_size(False)
the_table.set_fontsize(8.5)
the_table.scale(1, 1.5)
plt.text(0, 1, 'Post-hoc (Wilcoxon signed-rank tests)')
# Histograms
for idx, sp_name in enumerate(p['studies'][study]['experiments']['et']['conditions']):
ax = fig.add_axes([0.05+(idx)*0.2, 0.2, 0.16, 0.16])
for gp in ['control', 'dyslexic']:
x = data[(data.condition == sp_name) & (data.group == gp)][meas_name]
sns.distplot(x, bins=8, label=gp, ax=ax)
plt.title(sp_name)
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# %%Save fig as pdf page
if save_pdf:
pdf.savefig()
plt.close()
if save_pdf:
pdf.close() |
import React, { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { Link, useNavigate } from "react-router-dom";
import { BiArrowBack } from "react-icons/bi";
import { MdSearch } from "react-icons/md";
import axios from "axios";
import Loader from "../Loader";
export default function StudentList() {
let navigate = useNavigate();
const adminstatus = useSelector((state) => state.AdminReducers);
const [StudentsInfo,setStudentsInfo] = useState([]);
const [InfoBackup,setInfoBackup] = useState([]);
const [Loading, setLoading] = useState(true);
const [refresh, setrefresh] = useState('');
const [input, setinput] = useState('');
var x = 0;
useEffect(() => {
window.scroll(0,0);
// Check is Admin Login Or Not
if(Number(adminstatus.isAdminLoggedIn)){
// call the fetch admin detail function
const fetchdata = async () =>{
await axios.get("/allStudents").then(response => {
setStudentsInfo(response.data);
setInfoBackup(response.data)
setLoading(false);
})
.catch(error => {
console.log(error);
navigate("/admin-portal-login-190310554227");
});
}
fetchdata();
}
// If User is not login redirect to login
else{
navigate("/admin-portal-login-190310554227");
}
}, [adminstatus.isAdminLoggedIn, navigate, refresh]);
const FindTheStudent = () => {
if(input === ''){
setStudentsInfo(InfoBackup);
}
else{
var ans = InfoBackup.map((a) => {
if(a.email.toUpperCase().search(input.toUpperCase()) > -1){
return a
}
});
ans = ans.filter((e) => e !== undefined)
setStudentsInfo(ans);
}
}
console.log(StudentsInfo)
if(Loading){
return( <Loader /> );
}
else{
return (
<>
{/* Main Heading to Return */}
<div className="instructorHeader">
<Link to="/admin-portal-home-190310554227">
<BiArrowBack className="backBtn" style={{ color: "white" }} />
</Link>
</div>
{/* Search Bar */}
<div className="library-filter-container" style={{margin: '0px'}}>
<h1>Students's Details</h1>
<div className="librarySearch">
{/* input box to search User */}
<input type="text"
placeholder="Enter User Email to Search ..."
id="finder" name="emailfind"
value={input}
onChange={(e) => {setinput(e.target.value)}}
/>
<button type="submit" onClick={FindTheStudent}>
<i><MdSearch /></i> Search
</button>
</div>
</div>
{/* Table Show the Details of Teacher */}
<div className="instructor-table">
<p><b>Total Students: {StudentsInfo.length}</b></p>
<table>
<thead>
<tr>
<th>Sr. No</th>
<th>Name</th>
<th>Email</th>
<th>Mobile No.</th>
<th>Address</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
{StudentsInfo.map((item)=>(
<tr key={item._id}>
<td>
{++x}
</td>
<td style={{textAlign: 'left', paddingLeft: '1rem'}}>
{item.name}
</td>
<td style={{textTransform: 'none'}}>
{item.email}
</td>
<td>
{item.mobileno}
</td>
<td>
{item.PermanentAddress}
</td>
<td>
<button className='rmvbtn' onClick={ async ()=>{
const id = item._id;
// console.log(id)
const res = await fetch("/StudentRemoved" ,{
method : "POST",
headers : {
"content-Type" : "application/json"
},
body : JSON.stringify({
id
})
});
if (res.status === 200) {
setrefresh(res);
}
}
}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</>
)
}
} |
'\" t
.TH mkdirs 3 "1998-01-10" LOCAL
.SH NAME
mkdirs \- create directories in a path
.\"_
.SH "SYNOPSIS"
.\"_
.so tmac.att
.\"_
.LP
.BI "int mkdirs(const char *" "path" ,
.BI "mode_t " "mode" );
.\"_
.SH DESCRIPTION
.IX "mkdirs" "" "\fLmkdirs\fP \(em create directories in a path"
.B mkdirs(\|)
creates all the missing directories in the given
\f2path\f1 with the given \f2mode\f1. See
.BR chmod (2)
for the values of \f2mode.\f1
.\"_
.SH EXAMPLES
.EX
/\(** create scratch directories \(**/
const char dname = "/tmp/sub1/sub2/sub3" ;
if (mkdirs(dname,0755) >= 0) {
rs = chdir(dname) ;
} else {
fprintf(stderr, "cannot create directory");
}
\&\.
\&\.
.EE
.\"_
.SH "RETURN VALUES"
If a needed directory cannot be created,
.B mkdirs(\|)
returns a value less than zero indicating the error.
If all the directories are
created, or existed to begin with, it returns zero.
.\"_
.SH "SEE ALSO"
.BR mkdir (2),
.BR rmdir (2),
.BR mkdirp (3G)
.\"_
.SH AUTHOR
David A.D. Morano
.\"_
.\"_ |
/**
* @file ExecFlat.hpp
* @author Samsung R&D Poland - Mobile Security Group (srpol.mb.sec@samsung.com)
* @brief ExecFlat library created to provide an easy API for running KFLAT recipes.
*
*/
#ifndef EXECFLAT_HDR
#define EXECFLAT_HDR
#include <sched.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <cstdarg>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <cstddef>
#include <poll.h>
#include <signal.h>
#include <cerrno>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <string>
#include <map>
#include <stdexcept>
#include <iostream>
#include <filesystem>
#include <fstream>
#include <vector>
#include <functional>
#include <system_error>
#include <chrono>
#include <ctime>
#include <iomanip>
#include "kflat_uapi.h"
#define ERRNO_TO_EXCEPTION(_comment) { \
std::stringstream __ss; \
__ss << "KFLAT: " << (_comment) << "\nERRNO"; \
throw std::system_error(errno, std::generic_category(), __ss.str()); \
}
#define LOG(msg_level) ExecFlatLogger((msg_level), log_level, start_time)
namespace fs = std::filesystem;
namespace ExecFlatOpts{
/**
* @brief Used as a ExecFlat contructor parameter \n
* that determines the verbosity level of the ExecFlat library.
*
*/
enum ExecFlatVerbosity {
SUPRESS,
ERROR,
WARNING,
INFO,
DEBUG,
};
/**
* @brief Supported types of interfaces for automatic recipe trigger.
*
*/
enum ExecFlatInterface {
READ,
SHOW,
WRITE,
STORE,
IOCTL,
COMPAT_IOCTL,
};
}
using namespace ExecFlatOpts;
class TermColor {
public:
enum ColorCode {
FG_RED = 31,
FG_YELLOW = 33,
FG_GREEN = 32,
FG_BLUE = 34,
FG_CYAN = 36,
FG_DEFAULT = 39,
};
static std::string set(ColorCode code) {
std::stringstream s;
s << "\033[" << code << "m";
return s.str();
}
static std::string clear() {
std::stringstream s;
s << "\033[" << FG_DEFAULT << "m";
return s.str();
}
};
class ExecFlatLogger {
public:
ExecFlatLogger( ExecFlatVerbosity msg_level,
ExecFlatVerbosity log_level,
std::chrono::system_clock::time_point start
) : msg_level(msg_level), log_level(log_level), start_time(start) { }
~ExecFlatLogger() {
if (opened)
std::cerr << std::endl;
opened = false;
}
template<class T>
ExecFlatLogger &operator<<(const T &msg) {
if (log_level >= msg_level) {
if (!opened) {
std::chrono::duration<double> elapsed = std::chrono::system_clock::now() - start_time;
std::cerr
<< TermColor::set(TermColor::FG_GREEN)
<< "[ExecFlat] [" << std::fixed << elapsed.count() << "] "
<< TermColor::set(get_level_color())
<< std::setw(8) << get_level_str() << ": "
<< TermColor::clear();
}
opened = true;
std::cerr << msg;
}
return *this;
}
private:
ExecFlatVerbosity msg_level, log_level;
bool opened = false;
std::chrono::system_clock::time_point start_time;
inline std::string get_level_str() {
switch (msg_level)
{
case WARNING: return "WARNING";
case INFO: return "INFO";
case DEBUG: return "DEBUG";
case ERROR: return "ERROR";
default: return "UNKNOWN";
}
}
inline TermColor::ColorCode get_level_color() {
switch (msg_level)
{
case WARNING: return TermColor::FG_YELLOW;
case INFO: return TermColor::FG_CYAN;
case DEBUG: return TermColor::FG_DEFAULT;
case ERROR: return TermColor::FG_RED;
default: return TermColor::FG_DEFAULT;
}
}
};
/**
* @brief Allow to easily execute KFLAT recipes and save dumps to files.
*
*/
class ExecFlat {
public:
/**
* @brief Construct and initialize a new ExecFlat object.
*
* @param dump_size Max size of kflat memory dump.
* @param log_level One of ExecFlatVerbosity enum members.
*/
ExecFlat(size_t dump_size, ExecFlatVerbosity log_level);
~ExecFlat();
/**
* @brief Run a KFLAT recipe with a given target file. After enabling KFLAT, chosen file operation will be called on the target.
*
* @param interface One of ExecFlatInterface. The type of file operation to perform on TARGET.
* @param target Path to the file to call INTERFACE on.
* @param recipe Name of the KFLAT recipe.
* @param outfile Path to the file where the dump will be saved.
* @param use_stop_machine Execute the KFLAT recipe under kernel's stop_machine mode.
* @param debug Enable KFLAT LKM logging to dmesg.
* @param skip_func_body Skip executing function body after the recipe finishes flattening.
* @param run_recipe_now Execute KFLAT recipe directly from IOCTL without attaching to any kernel function.
* @param target_timeout In seconds. Timeout for INTERFACE call on TARGET.
* @param poll_timeout In miliseconds. Timeout for recipe execution.
*/
void run_recipe(
ExecFlatInterface interface,
const fs::path &target,
const std::string &recipe,
const fs::path &outfile,
bool use_stop_machine=false,
bool debug=true,
bool skip_func_body=false,
bool run_recipe_now=false,
unsigned int target_timeout=0,
int poll_timeout=-1
);
/**
* @brief Run a KFLAT recipe without any specified target. The recipe will wait for an external trigger (e.g. user can manually trigger the target function).
*
* @param recipe Name of the KFLAT recipe.
* @param outfile Path to the file where the dump will be saved.
* @param use_stop_machine Execute the KFLAT recipe under kernel's stop_machine mode.
* @param debug Enable KFLAT LKM logging to dmesg.
* @param skip_func_body Skip executing function body after the recipe finishes flattening.
* @param run_recipe_now Execute KFLAT recipe directly from IOCTL without attaching to any kernel function.
* @param poll_timeout In miliseconds. Timeout for recipe execution.
*/
void run_recipe_no_target(
const std::string &recipe,
const fs::path &outfile,
bool use_stop_machine=false,
bool debug=true,
bool skip_func_body=false,
bool run_recipe_now=false,
int poll_timeout=-1
);
/**
* @brief Run a KFLAT recipe with a custom trigger function.
*
* @param custom_trigger Function with signature int (). Function that will be executed after enabling KFLAT. \n
Executing this should trigger the kernel function with recipe attached.
* @param recipe Name of the KFLAT recipe.
* @param outfile Path to the file where the dump will be saved.
* @param use_stop_machine Execute the KFLAT recipe under kernel's stop_machine mode.
* @param debug Enable KFLAT LKM logging to dmesg.
* @param skip_func_body Skip executing function body after the recipe finishes flattening.
* @param run_recipe_now Execute KFLAT recipe directly from IOCTL without attaching to any kernel function.
* @param target_timeout In seconds. Timeout for INTERFACE call on TARGET.
* @param poll_timeout In miliseconds. Timeout for recipe execution.
*/
void run_recipe_custom_target(
std::function<int ()> custom_trigger,
const std::string &recipe,
const fs::path &outfile,
bool use_stop_machine=false,
bool debug=false,
bool skip_func_body=false,
bool run_recipe_now=false,
unsigned int target_timeout=0,
int poll_timeout=-1
);
/**
* @brief Read all KFLAT recipes available to execute.
*
* @return std::vector<std::string> Vector of strings with names of loaded recipes
*/
std::vector<std::string> get_loaded_recipes();
private:
// Consts
const char *KFLAT_NODE = "/sys/kernel/debug/kflat";
fs::path governor_filepath;
unsigned int current_cpu;
static const std::map<ExecFlatInterface, std::function<int (int)>> interface_mapping;
// Variables
size_t dump_size;
ExecFlatVerbosity log_level;
int kflat_fd;
size_t out_size; // Actual size returned by KFLAT LKM
char *shared_memory;
std::chrono::system_clock::time_point start_time;
std::string saved_governor;
// Interfaces
static int interface_read(int fd);
static int interface_write(int fd);
static int interface_ioctl(int fd);
// Trigger function timeout
static void sigalrm_handler(int signum);
void start_alarm(unsigned int time);
void stop_alarm();
// Initialization steps
void open_kflat_node();
void mmap_kflat();
// Running recipes
void kflat_ioctl_enable(struct kflat_ioctl_enable *opts);
void kflat_ioctl_disable(struct kflat_ioctl_disable *ret);
void execute_interface(const fs::path &target, ExecFlatInterface interface);
void do_enable(
const std::string &recipe,
bool use_stop_machine,
bool debug,
bool skip_func_body,
bool run_recipe_now,
int pid
);
void disable(const fs::path &outfile, int poll_timeout);
// CPU governor stuff
fs::path get_governor_path();
void set_governor(const std::string &targetGovernor);
void restore_governor();
};
#endif // EXECFLAT_HDR |
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Image, ScrollView, TouchableOpacity, Alert } from 'react-native';
import { Share } from "react-native";
import * as Linking from 'expo-linking';
export default function DetailPage({ navigation, route }) {
//초기 컴포넌트의 상태값을 설정
//state, setState 뿐 아니라 이름을 마음대로 지정할 수 있음!
const [tip, setTip] = useState({
"idx": 9,
"category": "재테크",
"title": "렌탈 서비스 금액 비교해보기",
"image": "https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Frental.png?alt=media&t",
"desc": "요즘은 정수기, 공기 청정기, 자동차나 장난감 등 다양한 대여서비스가 활발합니다. 사는 것보다 경제적이라고 생각해 렌탈 서비스를 이용하는 사례가 늘고있기 때문입니다.",
"date": "2020.09.09"
})
useEffect(() => {
console.log(route)
//Card.js에서 navigation.navigate 함수를 쓸때 두번째 인자로 content를 넘겨줬죠?
//content는 딕셔너리 그 자체였으므로 route.params에 고대~로 남겨옵니다.
//즉, route.params 는 content죠!
navigation.setOptions({
//setOptions로 페이지 타이틀도 지정 가능하고
title: route.params.title,
//StackNavigator에서 작성했던 옵션을 다시 수정할 수도 있습니다.
headerStyle: {
backgroundColor: '#000',
shadowColor: "#000",
},
headerTintColor: "#fff",
})
setTip(route.params)
}, [])
const popup = () => {
Alert.alert("팝업!!")
}
const share = () => {
Share.share({
message: `${tip.title} \n\n ${tip.desc} \n\n ${tip.image}`,
});
}
const link = () => {
Linking.openURL("https://github.com/iruril")
}
return (
// ScrollView에서의 flex 숫자는 의미가 없습니다. 정확히 보여지는 화면을 몇등분 하지 않고
// 화면에 넣은 컨텐츠를 모두 보여주려 스크롤 기능이 존재하기 때문입니다.
// 여기선 내부의 컨텐츠들 영역을 결정짓기 위해서 height 값과 margin,padding 값을 적절히 잘 이용해야 합니다.
<ScrollView style={styles.container}>
<Image style={styles.image} source={{ uri: tip.image }} />
<View style={styles.textContainer}>
<Text style={styles.title}>{tip.title}</Text>
<Text style={styles.desc}>{tip.desc}</Text>
<View style={styles.buttonGroup}>
<TouchableOpacity style={styles.button} onPress={() => popup()}><Text style={styles.buttonText}>팁 찜하기</Text></TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={() => share()}><Text style={styles.buttonText}>팁 공유하기</Text></TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={() => link()}><Text style={styles.buttonText}>외부 링크</Text></TouchableOpacity>
</View>
</View>
</ScrollView>
)
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#000"
},
image: {
height: 400,
margin: 10,
marginTop: 40,
borderRadius: 20
},
textContainer: {
padding: 20,
justifyContent: 'center',
alignItems: 'center'
},
title: {
fontSize: 20,
fontWeight: '700',
color: "#eee"
},
desc: {
marginTop: 10,
color: "#eee"
},
button: {
width: 100,
marginTop: 20,
padding: 10,
borderWidth: 1,
borderColor: 'deeppink',
borderRadius: 7
},
buttonText: {
color: '#fff',
textAlign: 'center'
},
buttonGroup: {
flexDirection: "row",
},
}) |
package com.example.notebook.feature_note.presentation.add_edit_note.ui
import android.graphics.Bitmap
import android.net.Uri
import android.util.Log
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.toArgb
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.notebook.common.InvalidNoteException
import com.example.notebook.feature_note.domain.model.Note
import com.example.notebook.feature_note.domain.use_cases.NoteUseCases
import com.example.notebook.feature_note.presentation.add_edit_note.AddEditNoteEvent
import com.example.notebook.feature_note.presentation.add_edit_note.NoteTextFieldState
import com.mohamedrejeb.richeditor.model.RichTextState
import com.mohamedrejeb.richeditor.model.rememberRichTextState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class AddEditNoteViewModel
@Inject constructor(
private val noteUseCase: NoteUseCases,
savedStateHandle: SavedStateHandle
) :ViewModel() {
private val _noteTitle = mutableStateOf(NoteTextFieldState(
hint = "Enter title..."
))
var editorTitleState by mutableStateOf(RichTextState())
var editorContentState by mutableStateOf(RichTextState())
private set
// fun updateTitleEditorState(newState: RichTextState) {
// editorTitleState = newState
// }
// fun updateContentEditorState(newState: RichTextState){
// editorContentState = newState
// }
private val _isBookmarked = mutableStateOf(false)
var bitmap = mutableStateOf<Bitmap?>(null)
private val _isSecret = mutableStateOf(false)
val noteTitle : State<NoteTextFieldState> = _noteTitle
private val _noteContent = mutableStateOf(NoteTextFieldState(
hint = "Enter content"
))
val noteContent : State<NoteTextFieldState> = _noteContent
private val _noteColor = mutableStateOf(Note.noteColors.random().toArgb())
val noteColor : State<Int> = _noteColor
private val _eventFlow = MutableSharedFlow<UiEvent>()
val eventFlow = _eventFlow.asSharedFlow()
private var currentNoteId: Int ? = null
init {
savedStateHandle.get<Int>("noteId")?.let {noteId ->
if (noteId != -1){
viewModelScope.launch {
noteUseCase.getNote(noteId)?.also {note ->
currentNoteId = note.id
editorTitleState.setHtml(note.title)
editorContentState.setHtml(note.content)
_isBookmarked.value = note.isBookMarked
_isSecret.value = note.isSecrete
bitmap.value = note.imageBitmap
}
}
}
}
}
fun onEvent(event:AddEditNoteEvent){
when(event){
is AddEditNoteEvent.EnterTitle -> {
_noteTitle.value = noteTitle.value.copy(
text = event.value
)
}
is AddEditNoteEvent.ChangeTitleFocus -> {
_noteTitle.value = noteTitle.value.copy(
isHintVisible = !event.focusState.isFocused &&
noteTitle.value.text.isBlank()
)
}
is AddEditNoteEvent.EnterContent -> {
_noteContent.value = _noteContent.value.copy(
text = event.value
)
}
is AddEditNoteEvent.ChangeContentFocus -> {
_noteContent.value = _noteContent.value.copy(
isHintVisible = !event.focusState.isFocused &&
_noteContent.value.text.isBlank()
)
}
is AddEditNoteEvent.ChangeColor -> {
_noteColor.value = event.color
}
is AddEditNoteEvent.SaveNote -> {
viewModelScope.launch {
try {
noteUseCase.addNoteUseCase(
Note(
// title = noteTitle.value.text,
title = editorTitleState.toHtml(),
content = editorContentState.toHtml(),
timestamp = System.currentTimeMillis(),
color = noteColor.value,
id = currentNoteId,
isBookMarked = _isBookmarked.value,
isSecrete = _isSecret.value,
imageBitmap = bitmap.value,
)
)
_eventFlow.emit(UiEvent.SaveNote)
} catch (e: InvalidNoteException){
_eventFlow.emit(
UiEvent.ShowSnackBar(
message = e.message ?:" Unknow error."
)
)
}
}
}
}
}
sealed class UiEvent{
data class ShowSnackBar(val message: String):UiEvent()
object SaveNote: UiEvent()
}
} |
<?php
/**
* A response with an ArrayObject interface to key=>value data
*
* @author Paul Annesley
* @package Pheanstalk
* @licence http://www.opensource.org/licenses/mit-license.php
*/
class Pheanstalk_Response_ArrayResponse
extends ArrayObject
implements Pheanstalk_Response
{
private $_name;
/**
* @param string $name
* @param array $data
*/
public function __construct($name, $data)
{
$this->_name = $name;
parent::__construct($data);
}
/* (non-phpdoc)
* @see Pheanstalk_Response::getResponseName()
*/
public function getResponseName()
{
return $this->_name;
}
/**
* Object property access to ArrayObject data.
*/
public function __get($property)
{
$key = $this->_transformPropertyName($property);
return isset($this[$key]) ? $this[$key] : null;
}
/**
* Object property access to ArrayObject data.
*/
public function __isset($property)
{
$key = $this->_transformPropertyName($property);
return isset($this[$key]);
}
// ----------------------------------------
/**
* Tranform underscored property name to hyphenated array key.
* @param string
* @return string
*/
private function _transformPropertyName($propertyName)
{
return str_replace('_', '-', $propertyName);
}
} |
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Switch } from './LangSwitcher.styled';
export const LangSwitcher = () => {
const { i18n } = useTranslation();
const [language, setLanguage] = useState('s');
const handleLanguageToggle = () => {
const newLanguage = language === 'uk' ? 'en' : 'uk';
setLanguage(newLanguage);
document.location.reload();
i18n.changeLanguage(newLanguage);
};
useEffect(() => {
const current = localStorage.getItem('i18nextLng');
if (current) {
i18n.changeLanguage(current);
return setLanguage(current);
}
setLanguage('en');
}, [i18n, language]);
return (
<Switch>
<input
id="language-toggle"
className="check-toggle check-toggle-round-flat"
type="checkbox"
checked={language === 'en'}
onChange={handleLanguageToggle}
/>
<label htmlFor="language-toggle"></label>
<span className="on">UA</span>
<span className="off">EN</span>
</Switch>
);
}; |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:jemina_capital/data/constants/api_routes.dart';
import 'package:jemina_capital/data/constants/theme_colors.dart';
import 'package:jemina_capital/models/report.dart';
class BackdropAndTitle extends StatelessWidget {
Report report;
BackdropAndTitle({
Key? key,
required this.size,
required this.report,
}) : super(key: key);
final Size size;
@override
Widget build(BuildContext context) {
return Container(
height: size.height * 0.4,
child: Stack(
children: [
Container(
height: size.height * 0.4 - 50.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(50.0),
),
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(
Routes.serverHome + report.reportImagePath,
),
),
),
),
Positioned(
bottom: 0,
right: 0,
child: Container(
width: size.width * 0.9,
height: 100.0,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(50.0),
topLeft: Radius.circular(15.0),
),
boxShadow: [
BoxShadow(
offset: Offset(0, 5),
blurRadius: 50.0,
color: Color(0xFF12153D).withOpacity(0.2),
),
],
),
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(
top: 20.0,
bottom: 10.0,
left: 10.0,
right: 10.0,
),
child: Text(
report.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.headline6?.copyWith(
fontWeight: FontWeight.w700,
color: techBlue,
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Row(
children: [
Icon(
Icons.calendar_month,
color: Colors.blueGrey,
size: 15.0,
),
SizedBox(width: 5.0),
Text(
report.toDate ?? "",
style: TextStyle(
color: Colors.blueGrey,
),
),
],
),
Row(
children: const [
Icon(
Icons.reply_outlined,
color: Colors.blueGrey,
size: 15.0,
),
SizedBox(width: 5.0),
Text(
"0",
style: TextStyle(
color: Colors.blueGrey,
),
),
],
),
],
),
],
),
),
),
// back btn
SafeArea(
child: BackButton(
color: Colors.white,
),
),
],
),
);
}
} |
#include "Radium/Basic/SourceLoc.h"
#include "Radium/Basic/SourceManager.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
namespace Radium {
auto SourceManager::getCodeCompletionLoc() const -> SourceLoc {
return getLocForBufferStart(code_completion_buffer_id_)
.getAdvancedLoc(code_completion_offset_);
}
auto SourceManager::addNewSourceBuffer(
std::unique_ptr<llvm::MemoryBuffer> buffer) -> unsigned {
assert(buffer);
llvm::StringRef buf_identifier = buffer->getBufferIdentifier();
auto id = llvm_src_mgr_.AddNewSourceBuffer(std::move(buffer), llvm::SMLoc());
buffer_id_map_[buf_identifier] = id;
return id;
}
auto SourceManager::addMemBufferCopy(llvm::MemoryBuffer* buffer) -> unsigned {
return addMemBufferCopy(buffer->getBuffer(), buffer->getBufferIdentifier());
}
auto SourceManager::addMemBufferCopy(llvm::StringRef input_data,
llvm::StringRef buf_identifier)
-> unsigned {
auto buffer =
llvm::MemoryBuffer::getMemBufferCopy(input_data, buf_identifier);
return addNewSourceBuffer(std::move(buffer));
}
auto SourceManager::getIDForBufferIdentifier(StringRef buf_identifier)
-> llvm::Optional<unsigned> {
auto it = buffer_id_map_.find(buf_identifier);
if (it == buffer_id_map_.end()) {
return llvm::None;
}
return it->second;
}
auto SourceManager::getLocForBufferStart(unsigned buffer_id) const
-> SourceLoc {
const auto* buffer = llvm_src_mgr_.getMemoryBuffer(buffer_id);
return SourceLoc(llvm::SMLoc::getFromPointer(buffer->getBufferStart()));
}
auto SourceManager::getLocOffsetInBuffer(SourceLoc loc,
unsigned buffer_id) const -> unsigned {
const auto* buffer = llvm_src_mgr_.getMemoryBuffer(buffer_id);
assert(loc.loc_.getPointer() >= buffer->getBuffer().begin() &&
loc.loc_.getPointer() <= buffer->getBuffer().end() &&
"Location is not from the specified buffer");
return loc.loc_.getPointer() - buffer->getBuffer().begin();
}
auto SourceManager::getByteDistance(SourceLoc start, SourceLoc end) const
-> unsigned {
#ifndef NDEBUG
unsigned buffer_id = findBufferContainingLoc(start);
const auto* buffer = llvm_src_mgr_.getMemoryBuffer(buffer_id);
assert(end.loc_.getPointer() >= buffer->getBuffer().begin() &&
end.loc_.getPointer() <= buffer->getBuffer().end() &&
"End location is not from the same buffer");
#endif
return end.loc_.getPointer() - start.loc_.getPointer();
}
auto SourceManager::getRangeForBuffer(unsigned buffer_id) const
-> CharSourceRange {
const auto* buffer = llvm_src_mgr_.getMemoryBuffer(buffer_id);
SourceLoc start{llvm::SMLoc::getFromPointer(buffer->getBufferStart())};
return CharSourceRange(start, buffer->getBufferSize());
}
auto SourceManager::extractText(CharSourceRange range,
llvm::Optional<unsigned> buffer_id) const
-> llvm::StringRef {
assert(range.isValid() && "range should be valid");
if (!buffer_id) {
buffer_id = findBufferContainingLoc(range.getStart());
}
llvm::StringRef buffer =
llvm_src_mgr_.getMemoryBuffer(*buffer_id)->getBuffer();
return buffer.substr(getLocOffsetInBuffer(range.getStart(), *buffer_id),
range.getByteLength());
}
void SourceLoc::printLineAndColumn(llvm::raw_ostream& os,
const SourceManager& src_mgr) const {
if (isInvalid()) {
os << "<invalid loc>";
return;
}
auto line_and_column = src_mgr.getLineAndColumn(*this);
os << "line:" << line_and_column.first << ':' << line_and_column.second;
}
void SourceLoc::print(llvm::raw_ostream& os, const SourceManager& src_mgr,
unsigned& last_buffer_id) const {
if (isInvalid()) {
os << "<invalid loc>";
return;
}
unsigned buffer_id = src_mgr.findBufferContainingLoc(*this);
if (buffer_id != last_buffer_id) {
os << src_mgr->getMemoryBuffer(buffer_id)->getBufferIdentifier();
last_buffer_id = buffer_id;
} else {
os << "line";
}
auto line_and_col = src_mgr.getLineAndColumn(*this, buffer_id);
os << ':' << line_and_col.first << ':' << line_and_col.second;
}
void SourceLoc::dump(const SourceManager& src_mgr) const {
print(llvm::errs(), src_mgr);
}
void SourceRange::widen(SourceRange other) {
if (other.start.loc_.getPointer() < start.loc_.getPointer()) {
start = other.start;
}
if (other.end.loc_.getPointer() > end.loc_.getPointer()) {
end = other.end;
}
}
auto SourceRange::contains(SourceLoc loc) const -> bool {
return start.loc_.getPointer() <= loc.loc_.getPointer() &&
loc.loc_.getPointer() <= end.loc_.getPointer();
}
auto SourceRange::overlaps(SourceRange other) const -> bool {
return contains(other.start) || other.contains(start);
}
void SourceRange::print(raw_ostream& os, const SourceManager& sm,
unsigned& last_buffer_id, bool print_text) const {
CharSourceRange(sm, start, end).print(os, sm, last_buffer_id, print_text);
}
void SourceRange::dump(const SourceManager& sm) const {
print(llvm::errs(), sm);
}
CharSourceRange::CharSourceRange(const SourceManager& sm, SourceLoc start,
SourceLoc end)
: start_(start) {
assert(start.isValid() == end.isValid() &&
"Start and end should either both be valid or both be invalid!");
if (start.isValid()) {
byte_length_ = sm.getByteDistance(start, end);
}
}
void CharSourceRange::print(raw_ostream& os, const SourceManager& sm,
unsigned& last_buffer_id, bool print_text) const {
os << '[';
start_.print(os, sm, last_buffer_id);
os << " - ";
getEnd().print(os, sm, last_buffer_id);
os << ']';
if (start_.isInvalid() || getEnd().isInvalid()) {
return;
}
if (print_text) {
os << " RangeText=\"" << sm.extractText(*this) << '"';
}
}
void CharSourceRange::dump(const SourceManager& sm) const {
print(llvm::errs(), sm);
}
} // namespace Radium |
#General Imports
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from IPython.display import clear_output
import numpy as np
import os
import threading
from torchvision.datasets import ImageFolder
from torch.utils.data import Dataset
from PIL import Image
def show_sample_from_generator(gen, z_dim, batch_size):
to_pil = transforms.ToPILImage()
denormalize = transforms.Normalize(
mean=[-0.5 / 0.5, -0.5 / 0.5, -0.5 / 0.5],
std=[1 / 0.5, 1 / 0.5, 1 / 0.5]
)
def show_image():
noise = torch.randn(batch_size, z_dim).to(next(gen.parameters()).device)
with torch.no_grad():
fake_gen = gen(noise).cpu()
fake_gen = fake_gen.view(4, 108, 192)
rgb_tensor = fake_gen[:3, :, :]
data_new = to_pil(denormalize(rgb_tensor))
data_new.show()
thread = threading.Thread(target=show_image)
thread.start()
def training(disc, gen, batch_size, num_epochs, z_dim, opt_disc, opt_gen, criterion, train_set, Generative_filepath, Disc_filepath):
D_loss = []
G_loss = []
batch_num = []
for epoch in range(num_epochs):
#-------------Show a sample of the Generative Model-------------#
show_sample_from_generator(gen, z_dim, 1)
disc.train()
gen.train()
for idx, real in enumerate(train_set):
#-------------Train Discriminator: max log(D(x)) + log(1 - D(G(z)))-------------#
noise = torch.randn(batch_size, z_dim)
fake_gen = gen(noise)
fake_gen = fake_gen.view(batch_size, 4, 108, 192)
disc_real = disc(real).view(-1)
disc_loss_real = criterion(disc_real, torch.ones_like(disc_real))
disc_fake = disc(fake_gen).view(-1)
disc_loss_fake = criterion(disc_fake, torch.zeros_like(disc_fake))
disc_loss = (disc_loss_real + disc_loss_fake) / 2
disc.zero_grad()
disc_loss.backward(retain_graph = True)
opt_disc.step()
#---------Train Generator: min log(1 - D(G(z))) <-> max log(D(G(z))---------#
output = disc(fake_gen).view(-1)
gen_loss = criterion(output, torch.ones_like(output))
gen.zero_grad()
gen_loss.backward()
opt_gen.step()
#Adding Losses to array for plotting
D_loss.append(disc_loss.detach())
G_loss.append(gen_loss.detach())
batch_num.append(len(batch_num) + 1)
if idx % 5 == 0:
print(f"Epoch [{epoch + 1}/{num_epochs}] Batch {idx}/{len(train_set)} Loss D: {disc_loss:.4f}, loss G: {gen_loss:.4f}")
clear_output(wait = True)
plt.cla()
plt.plot(batch_num, D_loss, label = 'Discriminator Loss', color = 'red')
plt.plot(batch_num, G_loss, label = 'Generator Loss', color = 'blue')
plt.title("Generator and Discriminator Loss")
plt.xlabel('Batch Number')
plt.ylabel('Loss')
plt.legend()
plt.pause(0.001)
disc.eval()
gen.eval()
#Save Model
torch.save(gen.state_dict(), Generative_filepath)
torch.save(disc.state_dict(), Disc_filepath)
plt.ioff()
plt.show() |
/**
* @file Wave_VAO.h
* @brief 一個面的VAO
*/
#ifndef WAVE_VAO_H
#define WAVE_VAO_H
#include "VAO_Interface.h"
/**
* @brief 繪製sin wave時使用的VAO
* @details 其實只是一個平面,要搭配Shader來轉成sin wave
*/
class Wave_VAO : public VAO_Interface {
private:
/// 頂點座標的VBO
GLuint m_vbo_position;
/// EBO
GLuint m_ebo;
/// EBO有幾個元素
GLuint m_num_of_elements;
public:
/// Constructor
/// @param size - 水波的範圍:(-size, 0, -size) ~ (size, 0, size)
Wave_VAO(GLfloat size);
/// Destructor
~Wave_VAO();
/// 在(-1, 0, -1) ~ (1, 0, 1)畫出一個由許多三角形構成的面,要搭配Shader轉成sine wave
void draw() override;
};
#endif // WAVE_VAO_H |
// ignore_for_file: prefer_const_constructors, sized_box_for_whitespace
import 'package:flutter/material.dart';
import 'package:player_connect/home_dir/connect_dir/provider/connect_provider.dart';
import 'package:player_connect/shared/constant/app_strings.dart';
import 'package:player_connect/shared/constant/colors.dart';
import 'package:player_connect/shared/constant/font_size.dart';
import 'package:player_connect/shared/constant/fonts.dart';
import 'package:player_connect/shared/constant/icon_image.dart';
import 'package:player_connect/shared/constant/snack_bar_toast.dart';
import 'package:player_connect/shared/auth/routes.dart';
import 'package:provider/provider.dart';
class ConnectPage extends StatefulWidget {
const ConnectPage({Key? key}) : super(key: key);
@override
State<ConnectPage> createState() => _ConnectPageState();
}
class _ConnectPageState extends State<ConnectPage> {
@override
Widget build(BuildContext context) {
deviceHeight(MediaQuery.of(context).size.height);
return ChangeNotifierProvider<ConnectProvider>(
create: (_) {
return ConnectProvider();
},
child: Consumer<ConnectProvider>(
builder: (context, provider, child) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
leading: SizedBox(width: 0),
backgroundColor: AppColors.bgColor,
elevation: 0,
titleSpacing: 0,
leadingWidth: 10,
title: Text(AppStrings.strConnect,
style: AppFonts.mazzardFont(TextStyle(
fontWeight: FontWeight.w700,
color: AppColors.primaryColorBlue,
fontSize: AppFontSize.font20))),
actions: [
Image(
image: AssetImage(AppIconImages.filterIconImg),
height: AppFontSize.font24,
width: AppFontSize.font24,
),
SizedBox(width: AppFontSize.font10)
],
),
body: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: AppFontSize.font10,
vertical: AppFontSize.font10),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(AppStrings.strRequest,
style: AppFonts.mazzardFont(TextStyle(
fontWeight: FontWeight.w600,
color: AppColors.secondaryColorBlack,
fontSize: AppFontSize.font16))),
SizedBox(width: AppFontSize.font8),
CircleAvatar(
backgroundColor: AppColors.primaryColorSkyBlue,
radius: AppFontSize.font10,
child: Center(
child: Text("${provider.nameList.length}",
style: AppFonts.poppinsFont(TextStyle(
fontWeight: FontWeight.w600,
color: AppColors.secondaryColorBlack,
fontSize: AppFontSize.font12))),
)),
Spacer(),
InkWell(
onTap: () {
Navigator.pushNamed(context, AppRoutes.requestPage);
},
child: Text(AppStrings.strViewMore,
style: AppFonts.poppinsFont(TextStyle(
fontWeight: FontWeight.w400,
color: AppColors.primaryColorSkyBlue,
fontSize: AppFontSize.font14))),
),
],
),
SizedBox(height: AppFontSize.font16),
Container(
height: AppFontSize.font150 + AppFontSize.font24,
child: ListView.builder(
itemCount: provider.utrList.length,
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemBuilder: (context, index) {
return Padding(
padding: EdgeInsets.all(AppFontSize.font8),
child: Column(
children: [
Stack(children: [
CircleAvatar(
radius: AppFontSize.font30,
backgroundImage:
AssetImage(provider.imgList[0])),
Positioned(
right: 1,
bottom: 1,
child: Container(
height: AppFontSize.font14,
width: AppFontSize.font14,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(
AppFontSize.font8),
border: Border.all(
color: AppColors
.secondaryColorWhite,
width: 2)),
),
)
]),
SizedBox(height: AppFontSize.font8),
Text(
"${provider.utrList[index]} '${AppStrings.strUtr.toUpperCase()}",
style: AppFonts.mazzardFont(TextStyle(
fontWeight: FontWeight.w500,
color: AppColors.secondaryColorBlack,
fontSize: AppFontSize.font10))),
SizedBox(height: AppFontSize.font4),
Text("${provider.nameList[index]}",
style: AppFonts.poppinsFont(TextStyle(
fontWeight: FontWeight.w600,
color: AppColors.secondaryColorBlack,
fontSize: AppFontSize.font14))),
SizedBox(height: AppFontSize.font4),
InkWell(
onTap: () {
Navigator.pushNamed(
context, AppRoutes.playerProfilePage,
arguments: provider.nameList[index]);
},
child: Text(AppStrings.strViewProfile,
style: AppFonts.mazzardFont(TextStyle(
fontWeight: FontWeight.w500,
color: AppColors.primaryColorBlue,
fontSize: AppFontSize.font10))),
),
SizedBox(height: AppFontSize.font4),
Row(
children: [
InkWell(
onTap: () {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(
AppStrings.strRequestAccept),
content: Text(AppStrings
.strSureToAcceptRequest),
actions: <Widget>[
TextButton(
onPressed: () {
AppSnackBarToast
.buildShowSnackBar(
context,
AppStrings
.strRequestAccepted);
Navigator.of(ctx).pop();
},
child: Text(
AppStrings.strYes)),
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child:
Text(AppStrings.strNo)),
],
),
);
},
child: Image(
image: AssetImage(
AppIconImages.aceptReqIconImg),
height: AppFontSize.font18,
width: AppFontSize.font18),
),
SizedBox(width: AppFontSize.font12),
InkWell(
onTap: () {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(
AppStrings.strRequestDecline),
content: Text(AppStrings
.strSureToDeclineRequest),
actions: <Widget>[
TextButton(
onPressed: () {
AppSnackBarToast
.buildShowSnackBar(
context,
AppStrings
.strRequestDeclinedSuccess);
Navigator.of(ctx).pop();
},
child: Text("Yes")),
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child:
Text(AppStrings.strNo)),
],
),
);
},
child: Image(
image: AssetImage(
AppIconImages.cnclReqIconImg),
height: AppFontSize.font18,
width: AppFontSize.font18),
),
],
),
SizedBox(height: AppFontSize.font4),
],
),
);
}),
),
Divider(),
Text(AppStrings.strSuccessfullMatches,
style: AppFonts.mazzardFont(TextStyle(
fontWeight: FontWeight.w600,
color: AppColors.secondaryColorBlack,
fontSize: AppFontSize.font16))),
SizedBox(height: AppFontSize.font8),
ListView.builder(
itemCount: provider.nameList.length,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return Padding(
padding: EdgeInsets.symmetric(
vertical: AppFontSize.font10),
child: ListTile(
contentPadding: EdgeInsets.all(0),
minVerticalPadding: 0.0,
title: Text(provider.nameList[index],
style: AppFonts.poppinsFont(TextStyle(
fontWeight: FontWeight.w400,
color: AppColors.primaryColorBlue,
fontSize: AppFontSize.font14))),
subtitle: Text(
"${provider.addressList[0]} ${provider.pointList[0]} ${provider.shortNameList[0]}",
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppFonts.mazzardFont(TextStyle(
fontSize: AppFontSize.font10,
fontWeight: FontWeight.w500,
color: AppColors.secondaryColorBlack))),
leading: Stack(
children: [
CircleAvatar(
radius: AppFontSize.font28,
backgroundImage:
AssetImage(provider.imgList[0])),
Positioned(
right: 2,
bottom: 2,
child: Container(
height: AppFontSize.font14,
width: AppFontSize.font14,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(
AppFontSize.font8),
border: Border.all(
color: AppColors
.secondaryColorWhite,
width: 2)),
),
)
],
),
trailing: Container(
height: AppFontSize.font24,
width: AppFontSize.font70,
child: Row(
children: [
Image(
image: AssetImage(
AppIconImages.commentIconImg),
height: AppFontSize.font20,
width: AppFontSize.font20,
),
SizedBox(width: AppFontSize.font10),
Image(
image: AssetImage(
AppIconImages.moreIconImg),
height: AppFontSize.font4,
width: AppFontSize.font16,
),
],
),
),
));
}),
],
),
),
),
));
},
),
);
}
} |
import { AbstractMongoDbRepository } from '@app/common';
import { User } from './schemas/user.schema';
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectConnection, InjectModel } from '@nestjs/mongoose';
import { Connection, Model } from 'mongoose';
import { PageOptionsDto } from '@app/common/pagination';
import { RetrunAllUsers } from './dto/return_all_users.dto';
import { IUserRepository } from './interfaces/user_repo.interface';
import { plainToInstance } from 'class-transformer';
import { ReturnUserDto } from './dto/return_user.dto';
@Injectable()
export class UserRepository
extends AbstractMongoDbRepository<User>
implements IUserRepository
{
protected readonly logger = new Logger(UserRepository.name);
constructor(
@InjectModel(User.name) userModel: Model<User>,
@InjectConnection() connection: Connection,
) {
super(userModel, connection);
}
async findByEmail(email: string): Promise<User | null> {
try {
const query = this.model.where({ email: email });
const result = await this.findOne(query);
return result;
} catch (error) {
if (error instanceof NotFoundException) {
return null;
}
throw error;
}
}
async getAllWithPagination(
pageOptionsDto: PageOptionsDto,
): Promise<RetrunAllUsers> {
const { page, take, order, skip } = pageOptionsDto;
const usersQuery = this.model
.find({}, {}, { lean: true })
.sort({ createdAt: order })
.skip(skip)
.limit(take);
const totalCountQuery = this.model.countDocuments();
const [users, itemCount] = await Promise.all([
usersQuery.exec(),
totalCountQuery.exec(),
]);
const pageCount = Math.ceil(itemCount / take);
const pageMeta = {
itemCount,
page,
pageCount,
take,
hasNextPage: page < pageCount,
hasPreviousPage: page > 1,
};
return {
data: plainToInstance(ReturnUserDto, users),
meta: pageMeta,
};
}
} |
import React, { useEffect } from "react";
import "./App.css";
import Header from "./Header";
import Home from "./Home";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Checkout from "./Checkout";
import Login from "./Login";
import { auth } from "./firebase";
import { useStateValue } from "./StateProvider";
import Payment from "./Payment";
import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
import Messages from "./Messages";
const stripePromise = loadStripe('pk_test_51NPQBISJcB2zZP9nVufAsDhe9sBvag1bhk7lw74fLo5dqqvNljtU9vo8vvlEB7CzEYudXOskOrOfRCYlVt9sW1We00eHcbrVmD');
function App() {
const [{}, dispatch] = useStateValue();
useEffect(() => {
auth.onAuthStateChanged((authUser) => {
console.log('auth user', authUser);
if (authUser) {
dispatch({
type: 'SET_USER',
user: authUser
});
} else {
dispatch({
type: 'SET_USER',
user: null
});
}
});
}, []);
return (
<Router>
<div className="app">
<Header />
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/" element={<Home />} />
<Route path="/checkout" element={<Checkout />} />
<Route path="/payment" element={
<Elements stripe={stripePromise}>
<Payment />
</Elements>
} />
<Route path="/messages" element={<Messages />} />
</Routes>
</div>
</Router>
);
}
export default App; |
'use client'
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { useUser } from "@clerk/nextjs";
import { getFirestore, doc, getDoc, updateDoc } from 'firebase/firestore';
import firebaseConfig from "@/lib/firebaseConfig";
import { initializeApp } from 'firebase/app';
const app = initializeApp(firebaseConfig);
const firestore = getFirestore(app);
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
export default function SendMoney() {
const [recipientId, setRecipientId] = useState('');
const [amountToSend, setAmountToSend] = useState('');
const [errorMessage, setErrorMessage] = useState('');
const [showAlertMessage,setShowAlertMessage] = useState('')
const { user } = useUser();
const handleSendMoney = async () => {
try {
// Verifica si el usuario está autenticado antes de continuar
if (!user) {
console.error('Usuario no autenticado.');
return;
}
// Verifica que se haya ingresado un ID de destinatario válido
if (!recipientId) {
setErrorMessage('Ingresa un ID de destinatario válido.');
return;
}
// Verifica que se haya ingresado un monto válido
const amount = parseFloat(amountToSend);
if (isNaN(amount) || amount <= 0) {
setErrorMessage('Ingresa un monto válido.');
setShowAlertMessage('error_valor_invalido')
return;
}
// Obtén la información del usuario actual
const userDocRef = doc(firestore, 'Users', user.id);
const userDocSnapshot = await getDoc(userDocRef);
if (userDocSnapshot.exists()) {
const userData = userDocSnapshot.data();
// Verifica si el usuario tiene fondos suficientes para enviar
const currentBalance = userData.Balance || 0;
if (amount > currentBalance) {
setErrorMessage('Fondos insuficientes para realizar la transferencia.');
setShowAlertMessage('fondos_insuficientes')
return;
}
// Realiza la transferencia
const recipientDocRef = doc(firestore, 'Users', recipientId);
const recipientDocSnapshot = await getDoc(recipientDocRef);
if (recipientDocSnapshot.exists()) {
const recipientData = recipientDocSnapshot.data();
// Actualiza el balance del remitente y el destinatario
const senderNewBalance = currentBalance - amount;
const recipientNewBalance = (recipientData.Balance || 0) + amount;
const senderTransaction = {
Type: 'Transfered Money',
Amount: -amount,
Balance_update: senderNewBalance,
Recipient: recipientId,
};
const recipientTransaction = {
Type: 'Received Money',
Amount: amount,
Balance_update: recipientNewBalance,
Sender: user.id,
};
const senderUpdatedData = {
...userData,
Balance: senderNewBalance,
allData: [...(userData.allData || []), senderTransaction],
};
const recipientUpdatedData = {
...recipientData,
Balance: recipientNewBalance,
allData: [...(recipientData.allData || []), recipientTransaction],
};
// Actualiza los documentos del remitente y el destinatario en Firestore
await updateDoc(userDocRef, senderUpdatedData);
await updateDoc(recipientDocRef, recipientUpdatedData);
// Actualiza los estados locales
setRecipientId('');
setAmountToSend('');
setErrorMessage('');
setShowAlertMessage('success')
} else {
setErrorMessage('El destinatario no existe.');
setShowAlertMessage('error_destinatario')
}
} else {
console.error('El documento del usuario no existe.');
}
} catch (error) {
console.error('Error al realizar la transferencia:', error);
}
};
return (
<div className="max-w-screen-md mx-auto p-4">
{/* Renderiza los elementos de la interfaz para enviar dinero */}
{/* ... (similar al componente Deposit) */}
<div className="mb-8 space-y-4">
<h2 className="text-2xl md:text-4xl font-bold text-center">
Send money instantly with one click!
</h2>
</div>
{/* Campo de entrada para el ID del destinatario */}
<input
className="w-full p-2 border rounded-md mb-4"
type="text"
placeholder="Enter the recipient's account number"
value={recipientId}
onChange={(e) => setRecipientId(e.target.value)}
/>
{/* Campo de entrada para el monto a enviar */}
<input
className="w-full p-2 border rounded-md mb-4"
type="number"
placeholder="Enter the amount to be sent"
value={amountToSend}
onChange={(e) => setAmountToSend(e.target.value)}
/>
{/* Botón para enviar dinero */}
{/* Mensaje de error en caso de problemas
<h2 className="text-red-500 mt-2">{errorMessage}</h2>
*/}
<AlertDialog>
<AlertDialogTrigger className="bg-blue-500 hover:bg-blue-600 text-white w-full py-2 rounded-md">
<Button
className="bg-blue-500 hover:bg-blue-600 text-white w-full py-2 rounded-md"
onClick={handleSendMoney}
>
Send Money
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{showAlertMessage === 'success'
? 'Money Successfully transfered!'
: showAlertMessage === 'fondos_insuficientes'
? 'Transaction Error!'
: showAlertMessage === 'error_valor_invalido'
? 'Transaction Error!'
: showAlertMessage === 'error_destinatario'
? 'Transaction Error!'
: 'Enter values to continue transaction'
}
</AlertDialogTitle>
<AlertDialogDescription>
{showAlertMessage === 'success'
? ' You have successfully transfered the amount. Click continue to make another transaction'
: showAlertMessage === 'fondos_insuficientes'
? 'The amount exceds the amount of money in your account. tranfer a smaller amount'
: showAlertMessage === 'error_valor_invalido'
? 'Rember not include negative numbers and fill in the input field with a number before you hit click'
: showAlertMessage === 'error_destinatario'
? 'This account number does not exit. Make sure you input an existing account number'
: ''
}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogAction>
<Button
onClick={() => {
setShowAlertMessage(''); // Limpiar el estado aquí
}}
>
Continue
</Button>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
} |
import "@mantine/core/styles.css";
import '@mantine/dates/styles.css';
import '@mantine/notifications/styles.css';
import { cssBundleHref } from "@remix-run/css-bundle";
import type { LinksFunction, MetaFunction } from "@remix-run/node";
import {
Links,
LiveReload,
Meta,
Outlet,
Scripts,
ScrollRestoration,
useNavigation,
} from "@remix-run/react";
import { MantineProvider, ColorSchemeScript } from "@mantine/core";
import { NavigationProgress, nprogress } from '@mantine/nprogress';
import { useEffect } from "react";
import Shell from '~/components/app-shell';
import { Notifications } from "@mantine/notifications";
export const links: LinksFunction = () => [
...(cssBundleHref ? [{ rel: "stylesheet", href: cssBundleHref }] : []),
{ rel: 'manifest', href: '/webmanifest.json' }
];
export const meta: MetaFunction = () => [
{ name: 'viewport', content: 'width=device-width, initial-scale=1, maximum-scale=1' }
];
export default function App() {
const navigation = useNavigation();
useEffect(() => {
if (navigation.state === 'idle') {
nprogress.complete();
nprogress.reset();
} else {
nprogress.start();
}
}, [navigation.state]);
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<Meta />
<Links />
<ColorSchemeScript />
</head>
<body>
<ColorSchemeScript defaultColorScheme="auto" />
<MantineProvider defaultColorScheme="auto">
<Notifications />
<Shell>
<NavigationProgress />
<Outlet />
<ScrollRestoration />
<Scripts />
<LiveReload />
</Shell>
</MantineProvider>
</body>
</html>
);
} |
<?php /** @noinspection PhpUnused */
namespace Kitmap\command\util\money;
use CortexPE\Commando\args\IntegerArgument;
use CortexPE\Commando\args\TargetPlayerArgument;
use CortexPE\Commando\BaseCommand;
use Kitmap\Main;
use Kitmap\Session;
use Kitmap\Util;
use pocketmine\command\CommandSender;
use pocketmine\permission\DefaultPermissions;
use pocketmine\player\Player;
use pocketmine\plugin\PluginBase;
class PayGem extends BaseCommand
{
public function __construct(PluginBase $plugin)
{
parent::__construct(
$plugin,
"paygem",
"Envoyer des gemmes à un autre joueur"
);
$this->setPermissions([DefaultPermissions::ROOT_USER]);
}
public function onRun(CommandSender $sender, string $aliasUsed, array $args): void
{
if ($sender instanceof Player) {
/** @noinspection PhpDeprecationInspection */
$target = Main::getInstance()->getServer()->getPlayerByPrefix($args["joueur"]);
$amount = intval($args["montant"]);
$senderSession = Session::get($sender);
if (!$target instanceof Player) {
$sender->sendMessage(Util::PREFIX . "Le joueur indiqué n'est pas connecté sur le serveur");
return;
} else if (1 > $amount) {
$sender->sendMessage(Util::PREFIX . "Le montant que vous avez inscrit est invalide");
return;
} else if (floor($amount) > $senderSession->data["gem"]) {
$sender->sendMessage(Util::PREFIX . "Vos gemmes sont infèrieur à §9" . floor($amount));
return;
}
$targetSession = Session::get($target);
$gem = floor($amount);
$targetSession->addValue("gem", $gem);
$senderSession->addValue("gem", $gem, true);
$sender->sendMessage(Util::PREFIX . "Vous avez envoyé un montant de gemmes égal à §9" . $gem . " §fà §9" . $target->getName());
$target->sendMessage(Util::PREFIX . "Vous avez recu un montant de gemmes égal à §9" . $gem . " §fde la part de §9" . $sender->getName());
}
}
protected function prepare(): void
{
$this->registerArgument(0, new TargetPlayerArgument(false, "joueur"));
$this->registerArgument(1, new IntegerArgument("montant"));
}
} |
import React, { useState, useEffect } from "react";
import styled from "styled-components";
import { toast, ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import CountryFlag from "react-country-flag";
import axios from "axios";
import Select from "react-select";
const PaymentModal = ({ isOpen, onClose, headerText }) => {
const [countries, setCountries] = useState([]);
useEffect(() => {
const fetchCountries = async () => {
try {
const response = await axios.get("https://restcountries.com/v3.1/all");
const countryOptions = response.data.map((country) => ({
value: country.cca2,
label: country.name.common,
}));
setCountries(countryOptions);
} catch (error) {
console.error("Error fetching countries:", error);
}
};
fetchCountries();
}, []);
const [formData, setFormData] = useState({
nameOnCard: "",
cardNumber: "",
expiryDate: "",
cvv: "",
country: "",
postalCode: "",
});
const [errors, setErrors] = useState({});
// Function to format card number with spaces every 4 digits
const formatCardNumber = (value) => {
return value
.replace(/\s/g, "")
.replace(/(\d{4})/g, "$1 ")
.trim();
};
// Function to format expiry date with slash after 2 digits
const formatExpiryDate = (value) => {
return value
.replace(/\s/g, "")
.replace(/(\d{2})(\d{1,2})/, "$1/$2")
.trim();
};
// Function to limit CVV to 3 digits
const limitCvv = (value) => {
return value.slice(0, 3);
};
const handleChange = (e) => {
const { name, value } = e.target;
let formattedValue = value;
// Format card number
if (name === "cardNumber") {
formattedValue = formatCardNumber(value);
}
// Format expiry date
if (name === "expiryDate") {
formattedValue = formatExpiryDate(value);
}
// Limit CVV to 3 digits
if (name === "cvv") {
formattedValue = limitCvv(value);
}
setFormData({
...formData,
[name]: formattedValue,
});
setErrors({
...errors,
[name]: "",
});
};
const handleCountryChange = (selectedOption) => {
if (!selectedOption) return; // Handle the case where no option is selected
const name = "country"; // Assuming the name of the country input field is "country"
const value = selectedOption.value;
setFormData({
...formData,
[name]: value,
});
setErrors({
...errors,
[name]: "",
});
};
useEffect(() => {
const savedFormData = sessionStorage.getItem("paymentFormData");
if (savedFormData) {
setFormData(JSON.parse(savedFormData));
}
}, []);
const handleSubmit = (e) => {
e.preventDefault();
const newErrors = {};
// Validation rules
if (!formData.nameOnCard.trim()) {
newErrors.nameOnCard = "Name on card is required";
}
if (!formData.cardNumber.trim()) {
newErrors.cardNumber = "Card number is required";
} else if (!/^\d{4}\s\d{4}\s\d{4}\s\d{4}$/.test(formData.cardNumber)) {
newErrors.cardNumber = "Invalid card number format";
}
if (!formData.expiryDate.trim()) {
newErrors.expiryDate = "Expiry date is required";
} else if (!/^\d{2}\/\d{2}$/.test(formData.expiryDate)) {
newErrors.expiryDate = "Invalid expiry date format (MM/YY)";
}
if (!formData.cvv.trim()) {
newErrors.cvv = "CVV is required";
} else if (!/^\d{3}$/.test(formData.cvv)) {
newErrors.cvv = "Invalid CVV format";
}
if (!formData.country.trim()) {
newErrors.country = "Country is required";
}
if (!formData.postalCode.trim()) {
newErrors.postalCode = "Postal code is required";
}
setErrors(newErrors);
if (Object.keys(newErrors).length === 0) {
onClose();
sessionStorage.setItem("paymentFormData", JSON.stringify(formData));
toast.success("Payment Method add successfully");
window.location.reload();
} else {
Object.values(newErrors).forEach((error) => toast.error(error));
}
};
const handleModalClick = (e) => {
e.stopPropagation();
};
return (
<>
{isOpen && (
<ModalBackground onClick={onClose}>
<PaymentForm onSubmit={handleSubmit} onClick={handleModalClick}>
<ModalHeader>{headerText}</ModalHeader>
<InputWrapper>
<InputLabel htmlFor="nameOnCard">Name on Card</InputLabel>
<Input
type="text"
id="nameOnCard"
name="nameOnCard"
value={formData.nameOnCard}
onChange={handleChange}
/>
{errors.nameOnCard && <ErrorText>{errors.nameOnCard}</ErrorText>}
</InputWrapper>
<InputWrapper>
<InputLabel htmlFor="cardNumber">Card Number</InputLabel>
<Input
type="text"
id="cardNumber"
name="cardNumber"
value={formData.cardNumber}
onChange={handleChange}
/>
{errors.cardNumber && <ErrorText>{errors.cardNumber}</ErrorText>}
</InputWrapper>
<InputRow>
<InputWrapper>
<InputLabel htmlFor="expiryDate">Expiry</InputLabel>
<Input
type="text"
id="expiryDate"
name="expiryDate"
value={formData.expiryDate}
onChange={handleChange}
/>
{errors.expiryDate && (
<ErrorText>{errors.expiryDate}</ErrorText>
)}
</InputWrapper>
<Spacer />
<InputWrapper>
<InputLabel htmlFor="cvv">CVV</InputLabel>
<Input
type="text"
id="cvv"
name="cvv"
value={formData.cvv}
onChange={handleChange}
/>
{errors.cvv && <ErrorText>{errors.cvv}</ErrorText>}
</InputWrapper>
</InputRow>
<InputRow>
<InputWrapper>
<InputLabel htmlFor="country">Country</InputLabel>
<CountrySelect
options={countries}
value={countries.find(
(country) => country.value === formData.country
)}
onChange={handleCountryChange}
/>
{errors.country && <ErrorText>{errors.country}</ErrorText>}
</InputWrapper>
<Spacer />
<InputWrapper>
<InputLabel htmlFor="postalCode">Postal Code</InputLabel>
<Input
type="text"
id="postalCode"
name="postalCode"
value={formData.postalCode}
onChange={handleChange}
/>
{errors.postalCode && (
<ErrorText>{errors.postalCode}</ErrorText>
)}
</InputWrapper>
</InputRow>
<TermsText>
By providing your card information, you allow Century-Tech Limited
to charge your card for future payments in accordance with their
terms.
</TermsText>
<SubmitButton type="submit">Submit</SubmitButton>
</PaymentForm>
</ModalBackground>
)}
<ToastContainer />
</>
);
};
const ModalBackground = styled.div`
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
`;
const PaymentForm = styled.form`
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
width: 80%;
max-width: 800px; /* Increase the max-width */
`;
const ModalHeader = styled.h2`
font-size: 1.5rem;
margin-bottom: 20px;
`;
const InputWrapper = styled.div`
margin-bottom: 15px;
display: flex;
align-items: center; /* Align items vertically */
`;
const InputLabel = styled.label`
font-weight: bold;
width: 120px; /* Fixed width for the label */
`;
const InputRow = styled.div`
display: flex;
justify-content: space-between;
margin-bottom: 15px;
`;
const Input = styled.input`
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
&:focus {
&::after {
content: "";
display: block;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 9999;
cursor: text;
}
}
`;
const Spacer = styled.div`
width: 20px; /* Adjust space between inputs */
`;
const TermsText = styled.p`
margin-top: 10px;
`;
const ErrorText = styled.div`
color: red;
font-size: 0.9rem;
margin-top: 4px;
`;
const SubmitButton = styled.button`
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
`;
const CountrySelect = styled(Select)`
width: 200px;
`;
export default PaymentModal; |
package app
import (
"fmt"
"go.uber.org/config"
"go.uber.org/fx"
)
type Config struct {
Name string `yaml:"name"`
}
type ResultConfig struct {
fx.Out
Provider config.Provider
Config Config
}
func NewConfig() (ResultConfig, error) {
loader, err := config.NewYAML(config.File("config.yml"))
if err != nil {
return ResultConfig{}, fmt.Errorf("failed to load config file: %w", err)
}
config := Config{
Name: "default",
}
if err := loader.Get("app").Populate(&config); err != nil {
return ResultConfig{}, fmt.Errorf("failed to populate config: %w", err)
}
return ResultConfig{
Provider: loader,
Config: config,
}, nil
} |
from typing import List, Optional
from transformers import AutoModelForSequenceClassification, AutoTokenizer, AutoConfig
import torch
from haystack.nodes.base import BaseComponent
from haystack.modeling.utils import initialize_device_settings
from haystack.schema import Document
class EntailmentChecker(BaseComponent):
"""
This node checks the entailment between every document content and the statement.
It enrichs the documents metadata with entailment informations.
It also returns aggregate entailment information.
"""
outgoing_edges = 1
def __init__(
self,
model_name_or_path: str = "roberta-large-mnli",
model_version: Optional[str] = None,
tokenizer: Optional[str] = None,
use_gpu: bool = True,
batch_size: int = 16,
entailment_contradiction_threshold: float = 0.5,
):
"""
Load a Natural Language Inference model from Transformers.
:param model_name_or_path: Directory of a saved model or the name of a public model.
See https://huggingface.co/models for full list of available models.
:param model_version: The version of model to use from the HuggingFace model hub. Can be tag name, branch name, or commit hash.
:param tokenizer: Name of the tokenizer (usually the same as model)
:param use_gpu: Whether to use GPU (if available).
:param batch_size: Number of Documents to be processed at a time.
:param entailment_contradiction_threshold: if in the first N documents there is a strong evidence of entailment/contradiction
(aggregate entailment or contradiction are greater than the threshold), the less relevant documents are not taken into account
"""
super().__init__()
self.devices, _ = initialize_device_settings(use_cuda=use_gpu, multi_gpu=False)
tokenizer = tokenizer or model_name_or_path
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer)
self.model = AutoModelForSequenceClassification.from_pretrained(
pretrained_model_name_or_path=model_name_or_path, revision=model_version
)
self.batch_size = batch_size
self.entailment_contradiction_threshold = entailment_contradiction_threshold
self.model.to(str(self.devices[0]))
id2label = AutoConfig.from_pretrained(model_name_or_path).id2label
self.labels = [id2label[k].lower() for k in sorted(id2label)]
if "entailment" not in self.labels:
raise ValueError("The model config must contain entailment value in the id2label dict.")
def run(self, query: str, documents: List[Document]):
scores, agg_con, agg_neu, agg_ent = 0, 0, 0, 0
premise_batch = [doc.content for doc in documents]
hypothesis_batch = [query] * len(documents)
entailment_info_batch = self.get_entailment_batch(
premise_batch=premise_batch, hypothesis_batch=hypothesis_batch
)
for i, (doc, entailment_info) in enumerate(zip(documents, entailment_info_batch)):
doc.meta["entailment_info"] = entailment_info
con, neu, ent = (
entailment_info["contradiction"],
entailment_info["neutral"],
entailment_info["entailment"],
)
# if the score is None, we assume that all the documents were manually provided
# and we consider them all equally relevant
doc_score = doc.score if doc.score else 1
scores += doc_score
agg_con += con * doc_score
agg_neu += neu * doc_score
agg_ent += ent * doc_score
# if in the first documents there is a strong evidence of entailment/contradiction,
# there is no need to consider less relevant documents
if max(agg_con, agg_ent) / scores > self.entailment_contradiction_threshold:
break
aggregate_entailment_info = {
"contradiction": round(agg_con / scores, 2),
"neutral": round(agg_neu / scores, 2),
"entailment": round(agg_ent / scores, 2),
}
entailment_checker_result = {
"documents": documents[: i + 1],
"aggregate_entailment_info": aggregate_entailment_info,
}
return entailment_checker_result, "output_1"
def run_batch(self, queries: List[str], documents: List[Document]):
entailment_checker_result_batch = []
entailment_info_batch = self.get_entailment_batch(premise_batch=documents, hypothesis_batch=queries)
for doc, entailment_info in zip(documents, entailment_info_batch):
doc.meta["entailment_info"] = entailment_info
aggregate_entailment_info = {
"contradiction": round(entailment_info["contradiction"] / doc.score),
"neutral": round(entailment_info["neutral"] / doc.score),
"entailment": round(entailment_info["entailment"] / doc.score),
}
entailment_checker_result_batch.append(
{
"documents": [doc],
"aggregate_entailment_info": aggregate_entailment_info,
}
)
return entailment_checker_result_batch, "output_1"
def get_entailment_dict(self, probs):
return {k.lower(): v for k, v in zip(self.labels, probs)}
def get_entailment_batch(self, premise_batch: List[str], hypothesis_batch: List[str]):
formatted_texts = [
f"{premise}{self.tokenizer.sep_token}{hypothesis}"
for premise, hypothesis in zip(premise_batch, hypothesis_batch)
]
with torch.inference_mode():
inputs = self.tokenizer(formatted_texts, return_tensors="pt", padding=True, truncation=True).to(
self.devices[0]
)
out = self.model(**inputs)
logits = out.logits
probs_batch = torch.nn.functional.softmax(logits, dim=-1).detach().cpu().numpy()
return [self.get_entailment_dict(probs) for probs in probs_batch] |
import { useState, useEffect, useCallback } from "react";
import { useParams } from "react-router-dom";
import BlogService from "../../../services/BlogService";
import { CommentWithChildren, CommentWithId } from "../../../interfaces/blog";
import CommentItem from "../Comment";
import "./styles.scss";
import NewComment from "../NewComment";
const CommentList = () => {
const { postId } = useParams();
const [comments, setComments] = useState<CommentWithId[]>();
const fetchComments = useCallback(async () => {
try {
if (postId) {
const response = await BlogService.getPostComments(postId);
setChildrenComments(response);
}
} catch (error) {
console.error(error);
}
}, [postId]);
useEffect(() => {
fetchComments();
}, []);
const setChildrenComments = (comments: CommentWithChildren[]) => {
const nest = (
items: CommentWithChildren[],
id: number | null = null
): CommentWithChildren[] =>
items
.filter(comment => comment.parent_id === id)
.map(comment => ({ ...comment, children: nest(items, comment.id) }))
.sort(
(a, b) => new Date(b.date).valueOf() - new Date(a.date).valueOf()
);
setComments(nest(comments));
};
return (
<div className="comments">
<div className="comments__header">
<h3 className="comments__title">what's on your mind?</h3>
<NewComment
postId={postId}
parentId={null}
fetchComments={fetchComments}
/>
</div>
{comments?.map(comment => (
<CommentItem
comment={comment}
key={comment.id}
postId={postId}
fetchComments={fetchComments}
/>
))}
</div>
);
};
export default CommentList; |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
var App = require('app');
describe('App.ConfigRecommendations', function() {
var mixinObject = Em.Controller.extend(App.ConfigRecommendations, {});
var instanceObject = mixinObject.create({});
beforeEach(function() {
instanceObject.set('recommendations', []);
});
describe('#applyRecommendation', function() {
beforeEach(function() {
sinon.stub(instanceObject, 'formatParentProperties', function(parentProperties) { return parentProperties} );
sinon.stub(App.config, 'get').withArgs('serviceByConfigTypeMap').returns({
'pFile': Em.Object.create({serviceName: 'sName', displayName: 'sDisplayName'})
});
sinon.stub(Handlebars, 'SafeString');
});
afterEach(function() {
instanceObject.formatParentProperties.restore();
App.config.get.restore();
Handlebars.SafeString.restore();
});
it('adds new recommendation', function() {
var res = instanceObject.applyRecommendation('pName', 'pFile', 'pGroup', 'pRecommended', 'pInitial', ['p_id'], true);
expect(res).to.eql({
saveRecommended: true,
saveRecommendedDefault: true,
propertyFileName: 'pFile',
propertyName: 'pName',
isDeleted: false,
notDefined: false,
configGroup: 'pGroup',
initialValue: 'pInitial',
parentConfigs: ['p_id'],
serviceName: 'sName',
allowChangeGroup: false,
serviceDisplayName: 'sDisplayName',
recommendedValue: 'pRecommended',
isEditable: true
});
expect(instanceObject.getRecommendation('pName', 'pFile', 'pGroup')).to.eql(res);
});
it('updates recommendation', function() {
instanceObject.set('recommendations', [{
saveRecommended: true,
saveRecommendedDefault: true,
propertyFileName: 'pFile',
propertyName: 'pName',
isDeleted: false,
notDefined: false,
configGroup: 'pGroup',
initialValue: 'pInitial',
parentConfigs: ['p_id'],
serviceName: 'sName',
allowChangeGroup: false,
serviceDisplayName: 'sDisplayName',
recommendedValue: 'pRecommended'
}]);
expect(instanceObject.applyRecommendation('pName', 'pFile', 'pGroup', 'pRecommended1', 'pInitial', ['p_id1'])).to.eql({
saveRecommended: true,
saveRecommendedDefault: true,
propertyFileName: 'pFile',
propertyName: 'pName',
isDeleted: false,
notDefined: false,
configGroup: 'pGroup',
initialValue: 'pInitial',
parentConfigs: ['p_id1', 'p_id'],
serviceName: 'sName',
allowChangeGroup: false,
serviceDisplayName: 'sDisplayName',
recommendedValue: 'pRecommended1'
});
});
});
describe('#formatParentProperties', function() {
beforeEach(function() {
sinon.stub(App.config, 'configId', function(a,b) { return a + b; });
});
afterEach(function() {
App.config.configId.restore();
});
it('returns empty array if nothing was passed', function() {
expect(instanceObject.formatParentProperties(null)).to.eql([]);
});
it('returns config ids array', function() {
expect(instanceObject.formatParentProperties([{name: "n1", type: "t1"}, {name: "n2", type: "t2"}])).to.eql(["n1t1", "n2t2"]);
});
});
describe('#addRecommendation', function() {
var cases = [
{
title: 'add recommendation for editable property with full info',
name: 'pName', file: 'pFile.xml', group: 'pGroup', recommended: 'pRecommended', initial: 'pInitial', parent: ['p_id'], isEditable: true,
service: Em.Object.create({serviceName: 'sName', displayName: 'sDisplayName'}),
result: {
saveRecommended: true,
saveRecommendedDefault: true,
propertyFileName: 'pFile',
propertyName: 'pName',
isDeleted: false,
notDefined: false,
configGroup: 'pGroup',
initialValue: 'pInitial',
parentConfigs: ['p_id'],
serviceName: 'sName',
allowChangeGroup: false,
serviceDisplayName: 'sDisplayName',
recommendedValue: 'pRecommended',
isEditable: true
}
},
{
title: 'add recommendation for read-only property with full info',
name: 'pName', file: 'pFile.xml', group: 'pGroup', recommended: 'pRecommended', initial: 'pInitial', parent: ['p_id'], isEditable: false,
service: Em.Object.create({serviceName: 'sName', displayName: 'sDisplayName'}),
result: {
saveRecommended: true,
saveRecommendedDefault: true,
propertyFileName: 'pFile',
propertyName: 'pName',
isDeleted: false,
notDefined: false,
configGroup: 'pGroup',
initialValue: 'pInitial',
parentConfigs: ['p_id'],
serviceName: 'sName',
allowChangeGroup: false,
serviceDisplayName: 'sDisplayName',
recommendedValue: 'pRecommended',
isEditable: false
}
},
{
title: 'add recommendation with min info',
name: 'pName', file: 'pFile.xml',
service: Em.Object.create({serviceName: 'sName', displayName: 'sDisplayName'}),
result: {
saveRecommended: true,
saveRecommendedDefault: true,
propertyFileName: 'pFile',
propertyName: 'pName',
isDeleted: true,
notDefined: true,
configGroup: 'Default',
initialValue: undefined,
parentConfigs: [],
serviceName: 'sName',
allowChangeGroup: false,
serviceDisplayName: 'sDisplayName',
recommendedValue: undefined,
isEditable: true
}
}
];
cases.forEach(function(c) {
describe('successful add recommendation', function() {
var recommendation;
beforeEach(function() {
instanceObject.set('recommendations', []);
sinon.stub(App.config, 'get').withArgs('serviceByConfigTypeMap').returns({
'pFile': c.service
});
sinon.stub(Handlebars, 'SafeString');
recommendation = instanceObject.addRecommendation(c.name, c.file, c.group, c.recommended, c.initial, c.parent, c.isEditable);
});
afterEach(function() {
App.config.get.restore();
Handlebars.SafeString.restore();
});
it(c.title, function() {
expect(recommendation).to.eql(c.result);
});
it(c.title + ' check recommendations collection', function() {
expect(instanceObject.get('recommendations.0')).to.eql(c.result);
});
})
});
it('throw exception when name, fileName', function() {
expect(instanceObject.addRecommendation.bind()).to.throw(Error, 'name and fileName should be defined');
expect(instanceObject.addRecommendation.bind(null, 'fname')).to.throw(Error, 'name and fileName should be defined');
expect(instanceObject.addRecommendation.bind('name', null)).to.throw(Error, 'name and fileName should be defined');
});
});
describe('#removeRecommendationObject', function () {
var recommendations = [
{
propertyName: 'p1',
propertyFileName: 'f1'
},
{
propertyName: 'p2',
propertyFileName: 'f2'
}
];
beforeEach(function () {
instanceObject.set('recommendations', recommendations);
});
it('remove recommendation', function () {
instanceObject.removeRecommendationObject(recommendations[1]);
expect(instanceObject.get('recommendations.length')).to.equal(1);
expect(instanceObject.get('recommendations.0')).to.eql({
propertyName: 'p1',
propertyFileName: 'f1'
});
});
it('remove recommendation that is not exist (don\'t do anything)', function () {
instanceObject.removeRecommendationObject({propertyName: 'any', 'propertyFileName': 'aby'});
expect(instanceObject.get('recommendations')).to.eql(recommendations);
});
it('throw error if recommendation is undefined ', function () {
expect(instanceObject.removeRecommendationObject.bind()).to.throw(Error, 'recommendation should be defined object');
expect(instanceObject.removeRecommendationObject.bind(null)).to.throw(Error, 'recommendation should be defined object');
});
it('throw error if recommendation is not an object ', function () {
expect(instanceObject.removeRecommendationObject.bind('recommendation')).to.throw(Error, 'recommendation should be defined object');
expect(instanceObject.removeRecommendationObject.bind(['recommendation'])).to.throw(Error, 'recommendation should be defined object');
});
});
describe('#updateRecommendation', function () {
it('update recommended value and parent properties', function () {
expect(instanceObject.updateRecommendation({'recommendedValue': 'v2', parentConfigs: ['id1']}, 'v1', ['id2']))
.to.eql({'recommendedValue': 'v1', parentConfigs: ['id2', 'id1']});
});
it('update recommended value and add parent properties', function () {
expect(instanceObject.updateRecommendation({}, 'v1', ['id1'])).to.eql({'recommendedValue': 'v1', parentConfigs: ['id1']});
});
it('update recommended value', function () {
expect(instanceObject.updateRecommendation({}, 'v1')).to.eql({'recommendedValue': 'v1'});
expect(instanceObject.updateRecommendation({'recommendedValue': 'v1'}, 'v2')).to.eql({'recommendedValue': 'v2'});
});
it('throw error if recommendation is undefined ', function () {
expect(instanceObject.updateRecommendation.bind()).to.throw(Error, 'recommendation should be defined object');
expect(instanceObject.updateRecommendation.bind(null)).to.throw(Error, 'recommendation should be defined object');
});
it('throw error if recommendation is not an object ', function () {
expect(instanceObject.updateRecommendation.bind('recommendation')).to.throw(Error, 'recommendation should be defined object');
expect(instanceObject.updateRecommendation.bind(['recommendation'])).to.throw(Error, 'recommendation should be defined object');
});
});
describe('#saveRecommendation', function() {
it('skip update since values are same', function() {
expect(instanceObject.saveRecommendation({saveRecommended: false, saveRecommendedDefault: false}, false)).to.be.false;
});
it('perform update since values are different', function() {
expect(instanceObject.saveRecommendation({saveRecommended: false, saveRecommendedDefault: false}, true)).to.be.true;
});
it('updates "saveRecommended" and "saveRecommendedDefault", set "false"', function() {
var res = {saveRecommended: true, saveRecommendedDefault: true};
instanceObject.saveRecommendation(res, false);
expect(res.saveRecommended).to.be.false;
expect(res.saveRecommendedDefault).to.be.false;
});
it('throw error if recommendation is undefined ', function () {
expect(instanceObject.updateRecommendation.bind()).to.throw(Error, 'recommendation should be defined object');
expect(instanceObject.updateRecommendation.bind(null)).to.throw(Error, 'recommendation should be defined object');
});
it('throw error if recommendation is not an object ', function () {
expect(instanceObject.updateRecommendation.bind('recommendation')).to.throw(Error, 'recommendation should be defined object');
expect(instanceObject.updateRecommendation.bind(['recommendation'])).to.throw(Error, 'recommendation should be defined object');
});
});
describe('#getRecommendation', function () {
var recommendations = [
{
propertyName: 'p1',
propertyFileName: 'f1',
configGroup: 'Default'
},
{
propertyName: 'p2',
propertyFileName: 'f2',
configGroup: 'group1'
},
{
propertyName: 'p1',
propertyFileName: 'f1',
configGroup: 'group1'
}
];
beforeEach(function () {
instanceObject.set('recommendations', recommendations);
});
it('get recommendation for default group', function () {
expect(instanceObject.getRecommendation('p1', 'f1')).to.eql(recommendations[0]);
});
it('get recommendation for default group (2)', function () {
expect(instanceObject.getRecommendation('p1', 'f1', 'group1')).to.eql(recommendations[2]);
});
it('get recommendation for wrong group', function () {
expect(instanceObject.getRecommendation('p2', 'f2', 'group2')).to.equal(null);
});
it('get undefined recommendation', function () {
expect(instanceObject.getRecommendation('some', 'amy')).to.equal(null);
});
it('get throw error if undefined name or fileName passed', function () {
expect(instanceObject.getRecommendation.bind()).to.throw(Error, 'name and fileName should be defined');
expect(instanceObject.getRecommendation.bind('name')).to.throw(Error, 'name and fileName should be defined');
expect(instanceObject.getRecommendation.bind(null, 'fileName')).to.throw(Error, 'name and fileName should be defined');
});
});
describe('#cleanUpRecommendations', function() {
var cases = [
{
title: 'remove recommendations with same init and recommended values',
recommendations: [{
initialValue: 'v1', recommendedValue: 'v1'
}, {
initialValue: 'v1', recommendedValue: 'v2'
}],
cleanUpRecommendations: [{
initialValue: 'v1', recommendedValue: 'v2'
}]
},
{
title: 'remove recommendations with null init and recommended values',
recommendations: [{
initialValue: null, recommendedValue: null
}, {
recommendedValue: null
}, {
initialValue: null
},{
initialValue: null, recommendedValue: 'v1'
}, {
initialValue: 'v1', recommendedValue: null
}],
cleanUpRecommendations: [{
initialValue: null, recommendedValue: 'v1'
}, {
initialValue: 'v1', recommendedValue: null
}
]
}
];
cases.forEach(function(c) {
describe(c.title, function() {
beforeEach(function() {
instanceObject.set('recommendations', c.recommendations);
instanceObject.cleanUpRecommendations()
});
it('do clean up', function() {
expect(instanceObject.get('recommendations')).to.eql(c.cleanUpRecommendations);
});
});
});
});
describe('#clearRecommendationsByServiceName', function () {
beforeEach(function () {
instanceObject.set('recommendations', [{serviceName: 's1'}, {serviceName: 's2'}, {serviceName: 's3'}]);
});
it('remove with specific service names ', function () {
instanceObject.clearRecommendationsByServiceName(['s2','s3']);
expect(instanceObject.get('recommendations')).to.eql([{serviceName: 's1'}]);
});
});
describe('#clearAllRecommendations', function () {
beforeEach(function () {
instanceObject.set('recommendations', [{anyObject: 'o1'}, {anyObject: 'o2'}]);
});
it('remove all recommendations', function () {
instanceObject.clearAllRecommendations();
expect(instanceObject.get('recommendations.length')).to.equal(0);
});
});
}); |
\documentclass[12pt]{article}
% Layout.
\usepackage[top=1.2in, bottom=0.9in, left=1in, right=1in, headheight=1in, headsep=6pt]{geometry}
% Fonts.
\usepackage{mathptmx}
\usepackage[scaled=1.0]{helvet}
\renewcommand{\emph}[1]{\textsf{\textbf{#1}}}
% Misc packages.
\usepackage{amsmath,amssymb,latexsym}
\usepackage{graphicx,hyperref}
\usepackage{array}
\usepackage{xcolor}
\usepackage{multicol}
\usepackage{tabularx,colortbl}
\usepackage{enumitem}
\hypersetup{
colorlinks=true,
linkcolor=blue,
filecolor=magenta,
urlcolor=blue,
pdfauthor={Ed Bueler}
pdftitle={Syllabus for MATH F614 Fall 2023},
}
% Paragraph spacing
\parindent 0pt
\parskip 6pt plus 1pt
\def\tableindent{\hskip 0.5 in}
\def\ts{\hskip 1.5 em}
\usepackage{fancyhdr}
\pagestyle{fancy}
%\chead{\large\sf\textbf{}}
\lhead{\large\sf\textbf{Syllabus MATH F614}}
\rhead{\large\sf\textbf{Fall 2023}}
\newcommand{\localhead}[1]{\par\smallskip\textbf{#1} \smallskip\nobreak\\}%
\def\heading#1{\localhead{\large\emph{#1}}}
\def\subheading#1{\localhead{\emph{#1}}}
\newenvironment{clist}%
{\bgroup\parskip 0pt\begin{list}{$\bullet$}{\partopsep 4pt\topsep 0pt\itemsep -2pt}}%
{\end{list}\egroup}%
\begin{document}
\strut\par\vskip-12pt
\heading{Essential Information}
\vskip -12pt
\strut\hbox to \hsize{\tableindent\vtop{\halign{#\hfill\ts&#\hfil\cr
{\emph{Course Title}} & {\Large Numerical Linear Algebra} \cr
\strut & \cr
{\emph{Instructor}} & Ed Bueler \quad \href{mailto:elbueler@alaska.edu}{\texttt{elbueler\@@alaska.edu}} \cr
\strut & \cr
{\emph{Class meeting}} & MWF 2:15--3:15 pm, Chapman 107 \cr
\strut & \cr
{\emph{CRNs}} & in-person:\, 75513 \quad online: 75512 \href{https://canvas.alaska.edu/courses/15800}{(find zoom link on Canvas)}\cr
\strut & \cr
{\emph{Public website}} & \href{https://bueler.github.io/nla/}{\texttt{bueler.github.io/nla}}\cr
\strut & \cr
{\emph{Canvas website}} & \href{https://canvas.alaska.edu/courses/15800}{\texttt{canvas.alaska.edu/courses/15800}} \cr
\strut & \cr
\emph{Required text} & L.~N.~Trefethen and D.~Bau, \textsl{Numerical Linear Algebra}, \cr
& SIAM Press 1997 \cr
}
\hfil}}
\heading{Description}
This course covers how matrices and vectors are actually handled in a fast and accurate manner on computers. This is essential technology for scientific and engineering computation. Applications include solving large linear systems, least squares methods, systems of ordinary differential equations, inverse methods in geophysics, and Markov processes. Numerical linear algebra is equally important for partial differential equations, network problems, and optimization, and it is an underlying theory in machine learning.
We will place linear algebra in a clear mathematical framework, emphasizing the geometry of the matrix action. We will cover famous matrix decompositions and algorithms: singular value decomposition (SVD), Householder reflections and the QR decomposition, LU and Cholesky decompositions, spectral theorem, Schur decomposition, the QR method for eigenvalues, and Krylov methods. Additionally, the conditioning of problems and the stability of floating-point algorithms are central themes.
Student competence with a scientific computing language is a course goal, so homework assignments will require actual implementations. Examples/demonstrations in class, and also homework solutions, will routinely use Matlab/Octave, but student work can also be done in Python or Julia. (All of these are well-suited to numerical linear algebra; see the separate document \textsl{Programming languages compared} (\href{https://bueler.github.io/compareMOP.pdf}{\texttt{bueler.github.io/compareMOP.pdf}}.) The instructor and the textbook support Matlab/Octave, including with getting-started help. If you have never used a programming language before then please show initiative in learning this aspect of the course.
\heading{Course Goals and Student Learning Outcomes}
At the end you will be able to understand and apply the ideas and algorithms of numerical linear algebra. You will be very comfortable with a scientific computing language.
\clearpage \newpage
\phantom{foo}
\heading{Prerequisites}
In summary, the prerequisites are undergraduate linear algebra, exposure to or interest in scientific programming, and a certain amount of mathematical maturity.
Officially: \textsl{MATH 314 Linear Algebra or equivalent. Recommended: MATH 421 Applied Analysis OR MATH 401 Introduction to Real Analysis OR equivalent post-calculus course in analysis.}
\heading{The Hybrid Classroom}
There are two sections of the class, in-person (901) and online (701). They are treated as one course and occur simultaneously. In this ``hybrid'' set-up, each lecture will be a recorded Zoom session generated from Chapman 107. (The link for the Zoom session is \href{https://canvas.alaska.edu/courses/15800}{in Canvas}. The recordings will be linked from inside Canvas only; they are not public.) I will try to treat all students the same regarding proctored assessments---see below---and participation during class time. Students have certain obligations to help make this work:
\begin{itemize}
\item \textbf{in-person students}: To allow in-class play with Matlab etc., and to help classroom communication for e.g.~group work, please bring a laptop if you can, and perhaps join the Zoom session so you can see the online students. I prefer for in-person students to turn in their homework assignments on paper.
\item \textbf{online students}: Please sign into the Zoom session, from Canvas, just before class starts. Please participate as energetically as you can, and, if possible, keep your camera on. Regarding in-class group work, check for worksheet PDFs from the \href{https://bueler.github.io/nla/}{public site} before class starts. When you turn in homework assignments electronically, please generate clear, well-ordered, and combined PDFs; this may require scanning documents. You will need to schedule proctoring for the in-class assessments (see below), or attend in person on those days.
\end{itemize}
\heading{Schedule and Online Materials}
The \href{https://bueler.github.io/nla/}{public course website} includes a \href{https://bueler.github.io/nla/assets/general/F23/schedule.pdf}{day-by-day schedule} listing the textbook sections to be covered during each lecture, the due date of each homework Assignment, and the dates for the Midterm Quizzes and Final Exam. Please consult this schedule frequently; it is subject to change and will be kept up to date.
Most course materials (syllabus, schedule, homework Assignments, code examples, etc.) will be posted on the \href{https://bueler.github.io/nla/}{public website}. Some course materials (student grades, homework and exam solutions) will go on the \href{https://canvas.alaska.edu/courses/15800}{Canvas site}.
\heading{Office Hours and Communication}
My Office Hours are shown online at \href{http://bueler.github.io/OffHrs.htm}{\texttt{bueler.github.io/OffHrs.htm}}; I hold office hours in Chapman 306C. Students can also schedule meetings with me outside of regular office hours. I will use Canvas to send announcements. If I need to contact you outside of class times, I'll try to email via Canvas. (Please set your email address in Canvas to one that you check regularly!)
\clearpage\newpage
\phantom{foo}
\heading{Evaluation and Grades}
\vskip -10pt
\begin{tabular}{|c|c|c|}
\hline
Homework & nearly weekly & 50\% \\
\hline
Midterm Quiz 1 & in-class Wednesday 11 October & 15\% \\
\hline
Midterm Quiz 2 & in-class Wednesday 15 November & 15\% \\
\hline
Final Exam & in-class Wednesday 13 December, 1:00--3:00pm & 20\% \\
\hline
total & & 100\% \, \\
\hline
\end{tabular}
Scores for specific assessments may be adjusted based on the actual difficulty of the work and/or on average class performance, and adjustments will be applied to all students equally. The scores of the various parts will be summed and the final course grade will be assigned as follows.
\begin{tabular}{llllll}
A & 93--100\% & B- & 79--81\% & D+ & 65--67\% \\
A- & 90--92\% & C+ & 76--78\% & D & 60--64\% \\
B+ & 87--89\% & C & 68--75\% & D- & 57--59\% \\
B & 82--86\% & C- & not given & F & $\le$ 56\%
\end{tabular}
These ranges are a guarantee and a lower bound. I reserve the right to increase your grade above these ranges based on the actual difficulty of the work and/or on average class performance. Any such increases will preserve grade ordering by weighted total score.
\heading{Homework}
Homework is due at the start of class. \emph{Late homework is not accepted.} If you have unavoidable circumstances which do not allow you to turn in an Assignment on time then please contact me (\href{mailto:elbueler@alaska.edu}{\texttt{elbueler\@@alaska.edu}}) in advance.
The homework consists of by-hand computations, design and analysis of numerical algorithms, computer implementation of those algorithms, by-hand and computer visualization, rigorously-justified examples and counter-examples, and proofs. Problems very similar to, or shortened versions of, Homework problems will appear on the in-class Midterm Quizzes.
Exercises on the homework will require Matlab, or another suitable scientific computing language, both as a supercalculator and for writing programs. Codes on homework solutions will only be in Matlab/Octave. Homework assignments and their due dates will regularly be posted at the \href{https://bueler.github.io/nla/}{\texttt{public website}}. The site also has a daily schedule of topics. The schedule will be updated on an ongoing basis to reflect which topics were actually covered each day, so it is subject to change. The public website will also link a growing list of short Matlab/Octave codes; this is a good resource for coding examples.
\heading{Exams}
There will be two in-class Midterm Quizzes covering mostly basic concepts and definitions. Each of these will be 45 minutes, with a 15 minute debrief at the end after all exams are turned in.
The in-class Final Exam will require you to be familiar with two of the major methods we have studied. I will describe the format of this Exam in more detail in due course.
Make-up Quizzes or Exam will be given only for documented extenuating circumstances, at my discretion. Department policy (below) does not allow me to move the time of the Final Exam.
\clearpage\newpage
\phantom{foo}
\heading{Rules and Policies}
\vskip -20pt
\subheading{Incomplete Grade}
Incomplete (I) will only be given in
DMS courses in cases where
the student has completed the majority (normally all but the last
three weeks) of a course with a grade of C or better, but for
personal reasons beyond his/her control has been unable to complete
the course during the regular term. Negligence or indifference are
not acceptable reasons for granting an incomplete grade.
\subheading{Late Withdrawals}
A withdrawal after the deadline from a DMS course will
normally be granted only in cases where the student is performing
satisfactorily (i.e., C or better) in a course, but has exceptional
reasons, beyond his/her control, for being unable to complete the
course. These exceptional reasons should be detailed in writing to
the instructor, Department Chair and the Dean.
\subheading{No Early Final Examinations}
Final examinations for DMS courses shall not be held earlier than the date and time published in the official term schedule. Normally, a student will not be allowed to take a final exam early. Exceptions can be made by individual instructors, but should only be allowed in exceptional circumstances and in a manner which doesn't endanger the security of the exam.
\subheading{Academic Dishonesty}
Academic dishonesty, including cheating and plagiarism, will not be tolerated. It is a violation of the Student Code of Conduct and will be punished according to UAF procedures.
\subheading{Student protections and service statement}
Every qualified student is welcome in my classroom. As needed, I am happy to work with you, Disability Services, Veterans' Services, Rural Student Services, and so on, to find reasonable accommodations. Students at this University are protected against sexual harassment and discrimination (Title IX), and minors have additional protections. For more information on your rights as a student and the resources available to you to resolve problems, please go the following site: \href{https://www.uaf.edu/handbook/}{\texttt{www.uaf.edu/handbook}}.
\hfill \scriptsize [syllabus version: \today] \normalsize
\end{document} |
<template>
<div
class="input-container"
:type="type"
@blur="() => this.openDropdown(false)"
>
<div class="icon-container" :icon="icon" v-if="icon">
<i></i>
</div>
<input
:id="id"
:name="name"
:type="type"
:value="getValueSelectOption"
:readonly="readonly"
@keydown="keydown"
@keyup="keyup"
:placeholder="placeholder"
:disabled="disabled"
:style="icon ? 'padding: 0.6em 0.7em 0.6em 34px;' : ''"
@click="openDropdown"
:aria-selected="optionSelected"
:aria-required="required"
/>
<div class="icon-container" icon="arrow">
<i></i>
</div>
<div
class="dropdown"
:open="dropdown.active"
:style="`top:${dropdown.top};
left:${dropdown.left};
right:${dropdown.right};
bottom:${dropdown.bottom};`"
>
<ul>
<li
v-for="(op, idx) in option"
:key="idx"
@click="
() => {
op.idx = idx;
eventSelectOption(op);
}
"
:select="op.selected"
>
{{ op.name }}
</li>
</ul>
</div>
<div
class="dropdown-background"
v-if="dropdown.active"
@click="dropdown.active = false"
></div>
</div>
</template>
<script lang="ts">
import { Options, Vue } from "vue-class-component";
export type tOption = {
value: string;
name: string;
selected?: boolean;
};
@Options({
props: {
id: String,
name: String,
readonly: Boolean,
option: Array,
value: String,
type: String,
required: Boolean,
placeholder: String,
icon: String,
eventSelect: { type: Function },
keydown: { type: Function },
keyup: { type: Function },
disabled: { type: Boolean, default: false },
},
data() {
return {
error: "",
dropdown: {
active: false,
top: "40px",
left: "auto",
right: "auto",
bottom: "auto",
},
optionSelected: "",
valueInput: "",
};
},
methods: {
openDropdown(e: any) {
const { y, target } = e;
const getMain = document.querySelector("main");
if (target.parentElement && getMain?.scrollHeight) {
const pp = target.parentElement;
this.dropdown.top =
y + pp.offsetHeight + 140 < getMain.scrollHeight ? `${40}px` : "auto";
this.dropdown.bottom =
y + pp.offsetHeight + 140 < getMain.scrollHeight ? "auto" : `${40}px`;
this.dropdown.active = !this.dropdown.active;
}
},
eventSelectOption(option: tOption) {
this.optionSelected = option.value !== "-1" ? option.value : "";
this.dropdown.active = false;
this.valueInput = option.name;
this.eventSelect(option);
},
},
watch: {
option() {
this.optionSelected = "";
this.valueInput = "";
},
},
computed: {
getValueSelectOption() {
let selectValue;
const optionSelected = this.option.filter(
(i: tOption) => i.selected === true,
);
if (optionSelected.length > 0) {
selectValue = optionSelected[0].name;
this.valueInput = optionSelected[0].name;
this.optionSelected = optionSelected[0].value;
} else {
selectValue = String(this.value).length > 0 ? this.value : "";
}
return selectValue;
},
},
})
export default class Select extends Vue {}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.input-container {
display: flex;
flex-direction: row;
align-items: center;
position: relative;
input {
width: 100%;
height: 36px;
padding: 0.6em 0.7em;
font-size: var(--size-medium);
font-weight: 400;
line-height: 1.5;
color: rgba(17, 24, 39, 1);
outline: none;
background: var(--th-body-bg);
border: 1px solid;
border-color: var(--th-border);
border-radius: 4px;
box-shadow: 0px 0px 5px rgb(26, 141, 95, 0);
transition: all 0.2s ease;
}
}
.input-container:focus-within i {
background-color: var(--green);
}
.icon-container {
display: flex;
width: 18px;
height: 18px;
margin: 0 10px;
position: absolute;
i {
height: 100%;
width: 100%;
background-color: #6d6d6d;
}
}
.icon-container[icon="arrow"] {
width: 8px;
height: 8px;
position: absolute;
left: calc(100% - 26px);
i {
height: 100%;
width: 100%;
transform: rotate(0deg);
}
}
input::placeholder {
opacity: 0.8;
}
input:focus {
border-color: var(--green);
box-shadow: 0px 0px 5px rgb(26, 141, 95, 0.4);
transition: all 0.2s ease;
}
input:disabled {
opacity: 0.8;
pointer-events: none;
background: var(--th-tab-disable);
transition: all 0.2s ease;
}
input[readonly="true"] {
cursor: pointer;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.dropdown {
display: none;
position: absolute;
width: auto;
min-width: 40px;
max-height: 140px;
font-size: 14px;
margin-right: 100%;
font-weight: 400;
line-height: 1.5;
color: rgba(17, 24, 39, 1);
outline: none;
background: #fff;
border: 1px solid;
border-color: #dadce0;
border-radius: 4px;
box-shadow: 0px 0px 5px rgb(26, 141, 95, 0);
overflow: auto;
z-index: 99;
transition: all 0.2s ease;
ul {
margin: 0;
padding: 0;
width: 100%;
display: block;
}
ul li {
list-style-type: none;
font-size: 14px;
height: auto;
min-height: 27px;
align-items: center;
color: rgb(44, 44, 44, 1);
padding: 0.2em 0.7em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
cursor: pointer;
transition: all 0.2s ease;
}
ul li:hover {
background-color: #1a8d5f;
color: #fff;
transition: all 0.2s ease;
}
ul li[select="true"] {
background-color: #e8f3ef;
color: #009160;
font-weight: 500;
transition: all 0.2s ease;
}
}
.dropdown[open="true"] {
display: block;
}
.dropdown-background {
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0);
position: fixed;
top: 0;
left: 0;
z-index: 2;
resize: both;
overflow: hidden;
}
</style> |
package com.spring.basic.step02_dataTransfer;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class DataTransferEx02 {
/* View > Controller 데이터 전송 */
@RequestMapping(value = "/dataTransferEx04")
public String dataTransferEx04() {
return "form";
}
// 예시1) DTO 클래스 이용
@RequestMapping(value = "/dataTransferEx05")
public String dataTransferEx05(Member member) {
System.out.println("\n======= dataTransferEx05 전달 받은 파라메타 확인 =======");
System.out.println("name : " + member.getName());
System.out.println("id : " + member.getId());
System.out.println("pwd : " + member.getPwd());
System.out.println("content : " + member.getContent());
return "home";
}
// 예시 2) Map 컬렉션 프레임워크 이용
@RequestMapping(value = "/dataTransferEx06")
public String dataTransferEx06(@RequestParam Map<String,String>param) {
System.out.println("\n======= dataTransferEx05 전달 받은 파라메타 확인 =======");
System.out.println("name : " + param.get("name"));
System.out.println("id : " + param.get("id"));
System.out.println("pwd : " + param.get("pwd"));
System.out.println("content : " + param.get("content"));
return "home";
}
// 예시 3) HttpServletRequest 이용
@RequestMapping(value = "/dataTransferEx07")
public String dataTransferEx07(HttpServletRequest request) {
System.out.println("\n======= dataTransferEx06 전달 받은 파라메타 확인 =======");
System.out.println("name : " + request.getParameter("name"));
System.out.println("id : " + request.getParameter("id"));
System.out.println("pwd : " + request.getParameter("pwd"));
System.out.println("content : " + request.getParameter("content"));
return "home";
}
// 예시 4) parameter에 직접 form태그의 name값 입력
@RequestMapping(value = "/dataTransferEx08")
public String dataTransferEx08(String id , String pwd ) {
System.out.println("\n======= dataTransferEx08 전달 받은 파라메타 확인 =======");
System.out.println("id : " + id);
System.out.println("pwd : " + pwd);
return "home";
}
// 예시 5) @RequestParma을 이용
@RequestMapping(value = "/dataTransferEx09")
public String dataTransferEx09(@RequestParam("id") String memberId ,
@RequestParam(name="pwd" , defaultValue = "1111") String memberPwd) {
System.out.println("\n======= dataTransferEx09 전달 받은 파라메타 확인 =======");
System.out.println("id : " + memberId);
System.out.println("pwd : " + memberPwd);
return "home";
}
} |
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import * as path from 'path';
import { expect } from 'chai';
import { execCmd, TestSession } from '@salesforce/cli-plugins-testkit';
import { ComponentStatus } from '@salesforce/source-deploy-retrieve';
import { StatusResult } from '../../../src/formatters/source/statusFormatter';
import { RetrieveCommandResult } from '../../../src/formatters/retrieveResultFormatter';
import { DeployCommandResult } from '../../../src/formatters/deployResultFormatter';
let session: TestSession;
describe('-t flag for deploy, retrieve, and delete', () => {
before(async () => {
session = await TestSession.create({
project: {
gitClone: 'https://github.com/salesforcecli/sample-project-multiple-packages.git',
},
setupCommands: [`sfdx force:org:create -d 1 -s -f ${path.join('config', 'project-scratch-def.json')}`],
});
});
after(async () => {
await session?.zip(undefined, 'artifacts');
await session?.clean();
});
describe('basic status and deploy', () => {
it('detects the initial metadata status', () => {
const result = execCmd<StatusResult[]>('force:source:status --json', {
ensureExitCode: 0,
}).jsonOutput.result;
expect(result).to.be.an.instanceof(Array);
// the fields should be populated
expect(result.every((row) => row.type && row.fullName)).to.equal(true);
});
it('deploy the initial metadata to the org with tracking', () => {
const result = execCmd<DeployCommandResult>('force:source:deploy -p force-app,my-app,foo-bar/app -t --json', {
ensureExitCode: 0,
}).jsonOutput.result;
expect(result.deployedSource).to.be.an.instanceof(Array);
expect(result.deployedSource, JSON.stringify(result)).to.have.length.greaterThan(10);
expect(
result.deployedSource.every((r) => r.state !== ComponentStatus.Failed),
JSON.stringify(result)
).to.equal(true);
});
it('sees no local changes (all were committed from deploy), but profile updated in remote', () => {
const localResult = execCmd<StatusResult[]>('force:source:status --json --local', {
ensureExitCode: 0,
}).jsonOutput.result;
expect(localResult).to.deep.equal([]);
const remoteResult = execCmd<StatusResult[]>('force:source:status --json --remote', {
ensureExitCode: 0,
}).jsonOutput.result;
expect(remoteResult.some((item) => item.type === 'Profile')).to.equal(true);
});
});
describe('retrieve and status', () => {
it('can retrieve the remote profile', () => {
const retrieveResult = execCmd<RetrieveCommandResult>('force:source:retrieve -m Profile:Admin -t --json', {
ensureExitCode: 0,
}).jsonOutput?.result;
expect(
retrieveResult.inboundFiles.some((item) => item.type === 'Profile'),
JSON.stringify(retrieveResult)
).to.equal(true);
});
it('sees no local or remote changes', () => {
const result = execCmd<StatusResult[]>('force:source:status --json', {
ensureExitCode: 0,
}).jsonOutput.result;
expect(
result.filter((r) => r.type === 'Profile'),
JSON.stringify(result)
).to.have.length(0);
});
});
describe('delete', () => {
it('can delete remote and local metadata with tracking', async () => {
const result = execCmd<DeployCommandResult>('force:source:delete -m ApexClass:FooBarTest -t --noprompt --json', {
ensureExitCode: 0,
}).jsonOutput.result;
expect(result.deletedSource).to.be.an.instanceof(Array).with.length.greaterThan(0);
expect(result.deletedSource.every((item) => item.type === 'ApexClass')).to.equal(true);
});
it('sees no local or remote changes', () => {
const result = execCmd<StatusResult[]>('force:source:status --json', {
ensureExitCode: 0,
}).jsonOutput.result;
// this delete WILL change the admin profile, so remove that from the status result
expect(
result.filter((r) => r.type === 'ApexClass'),
JSON.stringify(result)
).to.have.length(0);
});
});
}); |
import { IsEmail, IsNotEmpty, Length, Matches } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export const message =
'password must contain at least one number, one capital letter and one little letter';
export class CreateUserDto {
@IsEmail()
@ApiProperty({
description: 'Email of user',
maximum: 100,
example: 'example@exe.com',
})
@IsNotEmpty()
@Length(1, 100)
email: string;
@ApiProperty({
description:
'Password of user, must contain at leash one little and one capical letter and one number',
minimum: 8,
maximum: 100,
example: 'Example123',
})
@IsNotEmpty()
@Matches(/[0-9]/, { message })
@Matches(/[A-Z]/, { message })
@Matches(/[a-z]/, { message })
@Length(8, 100)
password: string;
@ApiProperty({
description: 'Nickname of user',
maximum: 30,
example: 'nickname',
})
@IsNotEmpty()
@Length(1, 30)
nickname: string;
} |
package com.cryallen.leetcode.easy.array;
/***
* 209. 长度最小的子数组
* @author Allen
* @DATE 2021-5-26
***/
public class Medium_209_Minimum_Size_SubArray_Sum {
/**
* 209. 长度最小的子数组
*
* <p>
* 地址:https://leetcode-cn.com/problems/minimum-size-subarray-sum/
* </p>
*
* <p>
* 给定一个含有 n 个正整数的数组和一个正整数 target 。
* 找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
*
* 示例 1:
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
*
* 示例 2:
输入:target = 4, nums = [1,4,4]
输出:1
*
* 示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0
提示:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105
*/
public static void main(String[] args) {
int[] nums1 = new int[]{2,3,1,2,4,3};
int result1 = minSubArrayLen(7,nums1);
System.out.println("result1: " + result1);
int[] nums2 = new int[]{2,3,1,2,4,3};
int result2 = minSubArrayLenSlide(7,nums2);
System.out.println("result2: " + result2);
}
/**
* 方式1:暴力解法
* */
public static int minSubArrayLen(int target, int[] nums) {
if(nums.length == 0){
return 0;
}
int ans = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++){
int sum = 0;
for (int j = i; j < nums.length; j++){
sum += nums[j];
if(sum >= target){
ans = Math.min(ans,j - i + 1);
break;
}
}
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
/**
* 方式2: 滑动窗口方法
* */
public static int minSubArrayLenSlide(int target, int[] nums) {
if(nums.length == 0){
return 0;
}
int ans = Integer.MAX_VALUE;
int start = 0, end = 0;
int sum = 0;
while (end < nums.length) {
sum += nums[end];
while (sum >= target) {
ans = Math.min(ans, end - start + 1);
sum -= nums[start];
start++;
}
end++;
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
} |
<template lang="pug">
#HomePage
.content
v-tabs.tab-group(v-model="tab" grow)
v-tab(v-for="item in items" :key="item") {{item}}
InputGroup(
:items="items"
:tab="tab"
@on-submit="CreateChip"
)
v-chip(
v-for="(item,index) in chips"
class="ma-2"
close
color="orange"
text-color="white"
close-icon="mdi-delete"
@click:close="DeleteChip(index)"
) {{item}}
v-btn.btn-about-me(
@click="AboutMe"
color="warning"
fab
dark
large
)
v-icon {{"mdi-account-circle"}}
</template>
<script>
import InputGroup from "../components/InputGroup.vue";
export default {
name: "HomePage",
components: { InputGroup },
data() {
return {
items: ["text", "radio", "select"],
tab: 2,
chips: [],
};
},
created() {
this.GetCityList();
},
methods: {
CreateChip(val) {
this.chips.push(val);
},
DeleteChip(index) {
this.chips.splice(index, 1);
},
// 移動到關於我的葉面
AboutMe() {
this.$router.push({ name: "about" });
},
// 獲得城市人名資料存入chips
async GetCityList() {
const res = await fetch(
"https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8",
{ method: "GET" }
).then((response) => response.json());
this.chips = res.map((object) => {
return object.name + " in " + object.city;
});
},
},
};
</script>
<style lang="scss" scoped>
.content {
padding: 50px;
margin: 0 auto;
width: 500px;
}
.btn-about-me {
position: absolute;
right: 50px;
bottom: 50px;
}
</style> |
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('bst-subpage:server');
var http = require('http');
var publicIp = require('public-ip');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
global.config.app_port = port;
if(global.config.proxy_server_port == 0) global.config.proxy_server_port = port;
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, '0.0.0.0',() => {
global.config.app_port = server.address().port;
console.log('Listening on port ' + server.address().port);
});
server.on('error', onError);
server.on('listening', onListening);
/*
var Primus = require('primus');
var primus = new Primus(server, { transformer: 'websockets' });
require('../app/socket/socket')(primus);
*/
var io = require('socket.io').listen(server, {'pingInterval': 25000, 'pingTimeout': 60000});
require('../controllers/server/socket.controller').socket_init(io);
if(global.config.server_domain_name === '') {
publicIp.v4().then(ip => {
global.config.server_domain_name = ip;
});
}
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
let port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
global.isServerOnline = true;
} |
import React, { useState, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { Spin, Alert } from 'antd';
import sort from '../../utilites/sortingTickets';
import transfer from '../../utilites/transferTickets';
import Ticket from '../ticket';
import styles from './tickets-list.module.scss';
const TicketsList = () => {
const tickets = useSelector((state) => state.tickets.tickets);
const { error, status, filters, sorting } = useSelector((state) => state.tickets);
const [extraTickets, setExtraTickets] = useState(5);
const handleShowMore = () => {
setExtraTickets(extraTickets + 5);
};
const transferTickets = useMemo(() => {
return transfer(tickets, filters);
}, [tickets, filters]);
const sortedTickets = useMemo(() => {
return sort(transferTickets, sorting);
}, [transferTickets, sorting]);
const visibleTickets = sortedTickets.slice(0, extraTickets);
const warningMsg = <Alert message="Рейсов, подходящих под заданные фильтры, не найдено." type="info" showIcon />;
const erorrMsg = <Alert message="Нет результатов. Попробуйте перезагрузить страницу." type="error" />;
const elements = visibleTickets.map((elem) => {
return (
<Ticket
key={`${elem.price}${elem.carrier}${elem.segments[0].date}${elem.segments[1].date}`}
price={elem.price}
img={elem.carrier}
originTo={elem.segments[0].origin}
originFrom={elem.segments[1].origin}
destinationTo={elem.segments[0].destination}
destinationFrom={elem.segments[1].destination}
durationThere={elem.segments[0].duration}
durationBack={elem.segments[1].duration}
dateThere={elem.segments[0].date}
dateBack={elem.segments[1].date}
stopsThere={elem.segments[0].stops}
stopsBack={elem.segments[1].stops}
/>
);
});
return (
<ul className={styles.tickets}>
{status && !error ? <Spin className={styles.loading} size="large" /> : null}
{error && !elements.length ? erorrMsg : null}
{!elements && !error && !status && warningMsg}
{elements}
<div className={styles.showMore}>
<button className={styles.button} type="button" onClick={handleShowMore}>
ПОКАЗАТЬ ЕЩЁ 5 БИЛЕТОВ!
</button>
</div>
</ul>
);
};
export default TicketsList; |
const plays = {
"hamlet": { "name": "Hamlet", "type": "tragedy" },
"as-like": { "name": "As You Like It", "type": "comedy" },
"othello": { "name": "Othello", "type": "tragedy" }
}
module.exports = function statement(invoice, plays) {
const statementData = {};
statementData.customer = invoice.customer;
statementData.performances = invoice.performances.map(enrichPerformance);
return renderPlanText(statementData, plays)
}
function renderPlanText(data, plays) {
let result = `Statement for ${data.customer}\n`;
for (let perf of data.performances) {
// 打印行此订单
result += ` ${perf.play.name}: ${format(perf.amount / 100)} (${perf.audience} seats)\n`;
}
result += `Amount owed is ${format(totalAmount(data) / 100)}\n`;
result += `You earned ${ totalVolumeCredits(data)} credits \n`;
function totalAmount(data) {
return data.performances
.reduce((total, p) => total + p.amount, 0);
}
function totalVolumeCredits(data) {
return data.performances
.reduce((total, p) => total + p.volumeCredits, 0);
}
return result;
}
function enrichPerformance(aPerformance) {
const result = Object.assign({}, aPerformance);
result.play = playFor(result);
result.amount = amountFor(result);
result.volumeCredits = volumeCreditsFor(result);
return result;
}
function playFor(aper) {
return plays[aper.playID]
}
function amountFor(perf) {
let result = 0;
switch (perf.play.type) {
case "tragedy":
result = 40000;
if (perf.audience > 30) {
result += 1000 * (perf.audience - 30);
}
break;
case "comedy":
result = 30000;
if (perf.audience > 20) {
result += 10000 + 500 * (perf.audience - 20);
}
result += 300 * perf.audience;
break;
default:
throw new Error(`unknown type: ${perf.play.type}`);
}
return result
}
function format(aNumber) {
return new Intl.NumberFormat("en-US",
{
style: "currency", currency: "USD",
minimumFractionDigits: 2
}).format(aNumber);
}
function volumeCreditsFor(aPerformance) {
let result = 0;
result += Math.max(aPerformance.audience - 30, 0);
// 每十名喜剧参与者增加额外积分分
if ("comedy" === aPerformance.play.type)
result += Math.floor(aPerformance.audience / 5);
return result;
} |
#' VaR for default risky bond portfolio
#'
#' Generates Monte Carlo VaR for default risky bond portfolio in Chapter 6.4
#'
#' @param r Spot (interest) rate, assumed to be flat
#' @param rf Risk-free rate
#' @param coupon Coupon rate
#' @param sigma Variance
#' @param amount.invested Amount Invested
#' @param recovery.rate Recovery rate
#' @param p Probability of default
#' @param number.trials Number of trials
#' @param hp Holding period
#' @param cl Confidence level
#' @return Monte Carlo VaR
#'
#' @references Dowd, K. Measuring Market Risk, Wiley, 2007.
#'
#' @author Dinesh Acharya
#' @examples
#'
#' # VaR for default risky bond portfolio for given parameters
#' DefaultRiskyBondVaR(.01, .01, .1, .01, 1, .1, .2, 100, 100, .95)
#'
#' @export
DefaultRiskyBondVaR <- function(r, rf, coupon, sigma, amount.invested, recovery.rate, p, number.trials, hp, cl){
M <- number.trials
delta <- recovery.rate
ann.hp <- hp/360
# R equals spot rate prevailing at end of hp/2 with term equal to hp.2
initial.bond.value <- coupon * ((1 + rf)/(1+r))^(ann.hp/2) + (1 + coupon)/((1+r)^ann.hp)
number.of.bonds <- amount.invested/initial.bond.value
z <- rnorm(M)
R <- double(M)
interim.bond.value <- double(M)
interim.default.state <- double(M)
terminal.bond.value <- double(M)
terminal.default.state <- double(M)
for (j in 1:M) {
R[j] <- exp(r + sigma * sqrt(hp/2)*z[j]) # Random realisation of spot rate with term hp/2
interim.default.state[j] <- rbinom(1,1,p) # Determines whether default occurs at hp/2
terminal.default.state[j] <- rbinom(1,1,p) # Determines whether default occurs at hp
if (interim.default.state[j] == 0) {
if (terminal.default.state[j] == 0) {
terminal.bond.value[j] <- coupon * (1 + rf) ^ (ann.hp / 2) + (1 + coupon)
} else {
terminal.bond.value[j] <- coupon * ((1 + rf) ^ (ann.hp / 2)) + delta * (1 + coupon)
}
} else {
interim.bond.value[j] <- delta * (coupon + ((1 + coupon) / (1+R[j])^(ann.hp/2)))
terminal.bond.value[j] <- ((1 + rf) ^ (ann.hp / 2)) * interim.bond.value[j]
}
}
profit.or.loss <- number.of.bonds * (terminal.bond.value - initial.bond.value)
# Convert to P/L
hist(-profit.or.loss)
HSVaR(profit.or.loss, cl)
} |
### R Lab 02 - R introduction
### Qin Li 20230924
#-----------------------------------#
### 1. basic data types
# '=' / '<-': assign values to variables
# character 字符型
a = "a"
a <- "a"
name = "Ross"
class(name)
# numeric variable 数值型
id = 1 # integer
height = 1.70
class(height)
# logic 逻辑型
test = TRUE
test2 = FALSE
test == test2 # 判断
# vector
names = c("Ross Geller", "Rachel Green", "Monica Geller", "Joey Tribbiani", "Chandler Bing", "Phoebe Buffay")
heights = c(1.85, 1.58, 1.62, 1.70, 1.75, 1.68)
genders = c("Male","Female","Female","Male","Male","Female")
# data frame
roles = data.frame(name = names,
height = heights,
gender = genders)
str(roles)
roles = data.frame(name = names,
height = heights,
gender = genders,
stringsAsFactors = F)
str(roles)
# matrix
matrix1 = matrix(data = c(1:9),3,3)
matrix2 = matrix(data = c(1:9),3,3, byrow=T)
# list
list_1 = list(matrix1, matrix2)
### 2. calculations
5 + 5
5 - 6
5 * 2
5 / 2
(5 + 5)/2
5 %% 2
5^2
log10(10)
log(2.72)
### 3. read in data from files
getwd() # check the path/working directory
# setwd('the path to the data/code')
# or set by click "To Source File Location"
snake_dt = read.csv(file = "chap03e1GlidingSnakes.csv")
head(snake_dt)
plot(snake_dt$undulationRateHz)
hist(snake_dt$undulationRateHz)
hist(snake_dt$undulationRateHz, breaks = 7, xlim = range(0.8,2.2), right = F)
Stickleback = read.csv(file = "chap03e3SticklebackPlates.csv")
head(Stickleback)
hist(Stickleback$plates)
hist(Stickleback$plates[Stickleback$genotype == "MM"])
hist(Stickleback$plates[Stickleback$genotype == "Mm"])
hist(Stickleback$plates[Stickleback$genotype == "mm"])
#-----------------------------------#
### 4. Descriptive statistics
### Example 1
mean(snake_dt$undulationRateHz) # mean
median(snake_dt$undulationRateHz) # median
range(snake_dt$undulationRateHz) # the range: min ~ max
var(snake_dt$undulationRateHz) # variance
snake_mean = mean(snake_dt$undulationRateHz)
sum((snake_dt$undulationRateHz - snake_mean)^2)/(8-1)
snake_sd = sd(snake_dt$undulationRateHz) # standard deviation
sqrt(sum((snake_dt$undulationRateHz - snake_mean)^2)/(8-1))
snake_cv = snake_sd/snake_mean # Coefficient of variation
summary(snake_dt$undulationRateHz)
quantile(snake_dt$undulationRateHz) # quantiles: return min, quartiles, max
quantile(snake_dt$undulationRateHz, probs = c(0.05,0.95))
IQR(snake_dt$undulationRateHz) # Interquartile range
### Example 2
# Practice problems - Page 279
# 2. Here is another sample of systolic blood pressure (in units of mmHg), this time with 101 data points. The mean is 122.73 and the standard deviation is 13.83.
bp_data = c(88, 105, 114, 117, 122, 125, 128, 133, 139, 156, 88, 107, 114, 119, 123, 125, 128, 133, 141, 92, 96, 96, 100, 107, 108, 110, 115, 115, 116, 119,120, 121, 123,123, 123, 126, 126, 126, 129, 129, 130, 133, 134, 135, 142, 142, 142,102, 102, 110, 110, 116, 117, 121, 121,123, 124, 126, 126, 131, 131, 136, 136, 143, 144, 104, 104, 105, 105, 111, 111, 112, 113, 117, 117, 117, 117, 121, 121, 121, 122, 124, 124, 124, 125, 127, 127, 128, 128, 131, 131, 131, 131, 136, 138, 138, 139, 146, 146, 147, 155)
mean(bp_data) # mean
median(bp_data) # median
range(bp_data) # the range: min ~ max
var(bp_data) # variance
sd(bp_data) # standard deviation
sd(bp_data)/mean(bp_data) # coefficient of variation
summary(bp_data)
quantile(bp_data) # quantiles: return min, quartiles, max
IQR(bp_data) # Interquartile range
quantile(bp_data, probs = c(0.05,0.95))
hist(bp_data)
boxplot(bp_data)
### Example 3 (skewed distribution)
boxplot(plates ~ genotype, data = Stickleback)
plates_Mm = Stickleback$plates[Stickleback$genotype == "Mm"]
hist(plates_Mm, breaks = 30)
mean(plates_Mm); sd(plates_Mm)
median(plates_Mm); IQR(plates_Mm)
### Example 4 Cumulative frequency distribution (skewed distribution)
range(plates_Mm)
breaks = seq(10, 70, by = 10)
plates_Mm_cut = cut(plates_Mm, breaks, right=FALSE)
plates_Mm_freq = table(plates_Mm_cut)
plates_cfd = c(0, cumsum(plates_Mm_freq))
plot(breaks, plates_cfd, # plot the data
main="Plates Mm", # main title
xlab="Numbers of lateral plates", # x−axis label
ylab="Cumulative Frequency") # y−axis label
lines(breaks, plates_cfd) # join the points
# Cumulative relative frequency distribution
plates_crfd = plates_cfd / max(plates_cfd)
plot(breaks, plates_crfd, # plot the data
main="Plates Mm", # main title
xlab="Numbers of lateral plates", # x−axis label
ylab="Cumulative Relative Frequency") # y−axis label
lines(breaks, plates_crfd)
### Example 5 Proportions
tigerData = read.csv("chap02e2aDeathsFromTigers.csv")
tigerTable <- table(tigerData$activity)
tigerData$activity_ordered = factor(tigerData$activity,
levels = names(sort(tigerTable,decreasing=T)))
head(tigerData)
str(tigerData)
# install.packages("ggplot2")
library(ggplot2)
ggplot(data = tigerData, aes(x = activity_ordered)) +
geom_bar(stat = "count", fill = "firebrick") +
labs(x = "Activity", y = "Frequency") +
theme_classic() +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
# proportions %
tigerTable/nrow(tigerData)
# How to plot proportions? |
#[derive(Debug)]
pub enum OpMode {
Implied,
Immediate,
Absolute,
AbsoluteX,
AbsoluteY,
Indirect,
IndirectX,
IndirectY,
ZeroPage,
ZeroPageX,
ZeroPageY,
Accumulator,
Relative,
}
pub struct Opcode {
pub mnemonic: &'static str,
pub code: u8,
pub mode: OpMode,
pub bytes: u8,
pub cycles: u8
}
pub fn get_opcode<'a>(code: u8) -> Option<&'a Opcode> {
if let Some(val) = OPCODE.iter().find(|op| op.code == code) {
Some(val)
} else {
None
}
}
static OPCODE: [Opcode; 151] = [
Opcode {
mnemonic: "BRK",
code: 0x00,
mode: OpMode::Implied,
bytes: 1,
cycles: 7,
},
Opcode {
mnemonic: "ORA",
code: 0x01,
mode: OpMode::IndirectX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "ORA",
code: 0x05,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "ASL",
code: 0x06,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "PHP",
code: 0x08,
mode: OpMode::Implied,
bytes: 1,
cycles: 3,
},
Opcode {
mnemonic: "ORA",
code: 0x09,
mode: OpMode::Immediate,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "ASL",
code: 0x0A,
mode: OpMode::Accumulator,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "ORA",
code: 0x0D,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "ASL",
code: 0x0E,
mode: OpMode::Absolute,
bytes: 3,
cycles: 6,
},
Opcode {
mnemonic: "BPL",
code: 0x10,
mode: OpMode::Relative,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "ORA",
code: 0x11,
mode: OpMode::IndirectY,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "ORA",
code: 0x15,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 4,
},
Opcode {
mnemonic: "ASL",
code: 0x16,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "CLC",
code: 0x18,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "ORA",
code: 0x19,
mode: OpMode::AbsoluteY,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "ORA",
code: 0x1D,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "ASL",
code: 0x1E,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 7,
},
Opcode {
mnemonic: "JSR",
code: 0x20,
mode: OpMode::Absolute,
bytes: 3,
cycles: 6,
},
Opcode {
mnemonic: "AND",
code: 0x21,
mode: OpMode::IndirectX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "BIT",
code: 0x24,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "AND",
code: 0x25,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "ROL",
code: 0x26,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "PLP",
code: 0x28,
mode: OpMode::Implied,
bytes: 1,
cycles: 4,
},
Opcode {
mnemonic: "AND",
code: 0x29,
mode: OpMode::Immediate,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "ROL",
code: 0x2A,
mode: OpMode::Accumulator,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "BIT",
code: 0x2C,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "AND",
code: 0x2D,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "ROL",
code: 0x2E,
mode: OpMode::Absolute,
bytes: 3,
cycles: 6,
},
Opcode {
mnemonic: "BMI",
code: 0x30,
mode: OpMode::Relative,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "AND",
code: 0x31,
mode: OpMode::IndirectY,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "AND",
code: 0x35,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 4,
},
Opcode {
mnemonic: "ROL",
code: 0x36,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "SEC",
code: 0x38,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "AND",
code: 0x39,
mode: OpMode::AbsoluteY,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "AND",
code: 0x3D,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "ROL",
code: 0x3E,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 7,
},
Opcode {
mnemonic: "RTI",
code: 0x40,
mode: OpMode::Implied,
bytes: 1,
cycles: 6,
},
Opcode {
mnemonic: "EOR",
code: 0x41,
mode: OpMode::IndirectX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "EOR",
code: 0x45,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "LSR",
code: 0x46,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "PHA",
code: 0x48,
mode: OpMode::Implied,
bytes: 1,
cycles: 3,
},
Opcode {
mnemonic: "EOR",
code: 0x49,
mode: OpMode::Immediate,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "LSR",
code: 0x4A,
mode: OpMode::Accumulator,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "JMP",
code: 0x4C,
mode: OpMode::Absolute,
bytes: 3,
cycles: 3,
},
Opcode {
mnemonic: "EOR",
code: 0x4D,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "LSR",
code: 0x4E,
mode: OpMode::Absolute,
bytes: 3,
cycles: 6,
},
Opcode {
mnemonic: "BVC",
code: 0x50,
mode: OpMode::Relative,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "EOR",
code: 0x51,
mode: OpMode::IndirectY,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "EOR",
code: 0x55,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 4,
},
Opcode {
mnemonic: "LSR",
code: 0x56,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "CLI",
code: 0x58,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "EOR",
code: 0x59,
mode: OpMode::AbsoluteY,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "EOR",
code: 0x5D,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "LSR",
code: 0x5E,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 7,
},
Opcode {
mnemonic: "RTS",
code: 0x60,
mode: OpMode::Implied,
bytes: 1,
cycles: 6,
},
Opcode {
mnemonic: "ADC",
code: 0x61,
mode: OpMode::IndirectX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "ADC",
code: 0x65,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "ROR",
code: 0x66,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "PLA",
code: 0x68,
mode: OpMode::Implied,
bytes: 1,
cycles: 4,
},
Opcode {
mnemonic: "ADC",
code: 0x69,
mode: OpMode::Immediate,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "ROR",
code: 0x6A,
mode: OpMode::Accumulator,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "JMP",
code: 0x6C,
mode: OpMode::Indirect,
bytes: 3,
cycles: 5,
},
Opcode {
mnemonic: "ADC",
code: 0x6D,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "ROR",
code: 0x6E,
mode: OpMode::Absolute,
bytes: 3,
cycles: 6,
},
Opcode {
mnemonic: "BVS",
code: 0x70,
mode: OpMode::Relative,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "ADC",
code: 0x71,
mode: OpMode::IndirectY,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "ADC",
code: 0x75,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 4,
},
Opcode {
mnemonic: "ROR",
code: 0x76,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "SEI",
code: 0x78,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "ADC",
code: 0x79,
mode: OpMode::AbsoluteY,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "ADC",
code: 0x7D,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "ROR",
code: 0x7E,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 7,
},
Opcode {
mnemonic: "STA",
code: 0x81,
mode: OpMode::IndirectX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "STY",
code: 0x84,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "STA",
code: 0x85,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "STX",
code: 0x86,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "DEY",
code: 0x88,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "TXA",
code: 0x8A,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "STY",
code: 0x8C,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "STA",
code: 0x8D,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "STX",
code: 0x8E,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "BCC",
code: 0x90,
mode: OpMode::Relative,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "STA",
code: 0x91,
mode: OpMode::IndirectY,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "STY",
code: 0x94,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 4,
},
Opcode {
mnemonic: "STA",
code: 0x95,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "STX",
code: 0x96,
mode: OpMode::ZeroPageY,
bytes: 2,
cycles: 4,
},
Opcode {
mnemonic: "TYA",
code: 0x98,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "STA",
code: 0x99,
mode: OpMode::AbsoluteY,
bytes: 3,
cycles: 5,
},
Opcode {
mnemonic: "TXS",
code: 0x9A,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "STA",
code: 0x9D,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 5,
},
Opcode {
mnemonic: "LDY",
code: 0xA0,
mode: OpMode::Immediate,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "LDA",
code: 0xA1,
mode: OpMode::IndirectX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "LDX",
code: 0xA2,
mode: OpMode::Immediate,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "LDY",
code: 0xA4,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "LDA",
code: 0xA5,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "LDX",
code: 0xA6,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "TAY",
code: 0xA8,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "LDA",
code: 0xA9,
mode: OpMode::Immediate,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "TAX",
code: 0xAA,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "LDY",
code: 0xAC,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "LDA",
code: 0xAD,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "LDX",
code: 0xAE,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "BCS",
code: 0xB0,
mode: OpMode::Relative,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "LDA",
code: 0xB1,
mode: OpMode::IndirectY,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "LDY",
code: 0xB4,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 4,
},
Opcode {
mnemonic: "LDA",
code: 0xB5,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 4,
},
Opcode {
mnemonic: "LDX",
code: 0xB6,
mode: OpMode::ZeroPageY,
bytes: 2,
cycles: 4,
},
Opcode {
mnemonic: "CLV",
code: 0xB8,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "LDA",
code: 0xB9,
mode: OpMode::AbsoluteY,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "TSX",
code: 0xBA,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "LDY",
code: 0xBC,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "LDA",
code: 0xBD,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "LDX",
code: 0xBE,
mode: OpMode::AbsoluteY,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "CPY",
code: 0xC0,
mode: OpMode::Immediate,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "CMP",
code: 0xC1,
mode: OpMode::IndirectX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "CPY",
code: 0xC4,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "CMP",
code: 0xC5,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "DEC",
code: 0xC6,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "INY",
code: 0xC8,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "CMP",
code: 0xC9,
mode: OpMode::Immediate,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "DEX",
code: 0xCA,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "CPY",
code: 0xCC,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "CMP",
code: 0xCD,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "DEC",
code: 0xCE,
mode: OpMode::Absolute,
bytes: 3,
cycles: 6,
},
Opcode {
mnemonic: "BNE",
code: 0xD0,
mode: OpMode::Relative,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "CMP",
code: 0xD1,
mode: OpMode::IndirectY,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "CMP",
code: 0xD5,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 4,
},
Opcode {
mnemonic: "DEC",
code: 0xD6,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "CLD",
code: 0xD8,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "CMP",
code: 0xD9,
mode: OpMode::AbsoluteY,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "CMP",
code: 0xDD,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "DEC",
code: 0xDE,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 7,
},
Opcode {
mnemonic: "CPX",
code: 0xE0,
mode: OpMode::Immediate,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "SBC",
code: 0xE1,
mode: OpMode::IndirectX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "CPX",
code: 0xE4,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "SBC",
code: 0xE5,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 3,
},
Opcode {
mnemonic: "INC",
code: 0xE6,
mode: OpMode::ZeroPage,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "INX",
code: 0xE8,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "SBC",
code: 0xE9,
mode: OpMode::Immediate,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "NOP",
code: 0xEA,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "CPX",
code: 0xEC,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "SBC",
code: 0xED,
mode: OpMode::Absolute,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "INC",
code: 0xEE,
mode: OpMode::Absolute,
bytes: 3,
cycles: 6,
},
Opcode {
mnemonic: "BEQ",
code: 0xF0,
mode: OpMode::Relative,
bytes: 2,
cycles: 2,
},
Opcode {
mnemonic: "SBC",
code: 0xF1,
mode: OpMode::IndirectY,
bytes: 2,
cycles: 5,
},
Opcode {
mnemonic: "SBC",
code: 0xF5,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 4,
},
Opcode {
mnemonic: "INC",
code: 0xF6,
mode: OpMode::ZeroPageX,
bytes: 2,
cycles: 6,
},
Opcode {
mnemonic: "SED",
code: 0xF8,
mode: OpMode::Implied,
bytes: 1,
cycles: 2,
},
Opcode {
mnemonic: "SBC",
code: 0xF9,
mode: OpMode::AbsoluteY,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "SBC",
code: 0xFD,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 4,
},
Opcode {
mnemonic: "INC",
code: 0xFE,
mode: OpMode::AbsoluteX,
bytes: 3,
cycles: 7,
},
]; |
package com.xing.uni.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xing.uni.entity.Order;
import com.xing.uni.entity.OrderDetail;
import com.xing.uni.entity.R;
import com.xing.uni.properties.WeixinpayProperties;
import com.xing.uni.service.IOrderDetailService;
import com.xing.uni.service.IOrderService;
import com.xing.uni.until.*;
import io.jsonwebtoken.Claims;
import javafx.scene.input.TouchEvent;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.MessageDigest;
import java.util.*;
/**
* 订单Controller控制器
*/
@RestController
@RequestMapping("/my/order")
public class OrderController {
@Autowired
private IOrderService orderService;
@Autowired
private IOrderDetailService orderDetailService;
@Autowired
private WeixinpayProperties weixinpayProperties;
/**
* 创建订单,返回订单号
* @param token
* @return
*/
@RequestMapping("/create")
@Transactional
public R create(@RequestBody Order order, @RequestHeader(value = "token")String token){
// 通过token获取openid
System.out.println("token="+token);
System.out.println("order="+order);
// 添加订单到数据库
Claims claims = JwtUtils.validateJWT(token).getClaims();
if(claims!=null){
System.out.println("openid="+claims.getId());
order.setUserId(claims.getId());
}
order.setOrderNo("JAVA"+ DateUtil.getCurrentDateStr());
order.setCreateDate(new Date());
OrderDetail[] goods = order.getGoods();
orderService.save(order);
// 添加订单详情到数据库
for(int i=0;i<goods.length;i++){
OrderDetail orderDetail=goods[i];
orderDetail.setMId(order.getId());
orderDetailService.save(orderDetail);
}
Map<String,Object> resultMap=new HashMap<>();
resultMap.put("orderNo",order.getOrderNo());
return R.ok(resultMap);
}
/**
* 调用统一下单,预支付
* @param orderNo
* @return
* @throws Exception
*/
// @RequestMapping("/preparePay")
// public R preparePay(@RequestBody String orderNo)throws Exception{
// System.out.println("orderNo="+orderNo);
// Order order = orderService.getOne(new QueryWrapper<Order>().eq("orderNo", orderNo));
//
//
// System.out.println("appid="+weixinpayProperties.getAppid());
// System.out.println("mch_id="+weixinpayProperties.getMch_id());
// System.out.println("nonce_str="+ StringUtil.getRandomString(32));
//
// System.out.println("body="+"java1234mall商品购买测试");
// System.out.println("out_trade_no="+orderNo);
// System.out.println("total_fee="+order.getTotalPrice().movePointRight(2));
// System.out.println("spbill_create_ip="+"127.0.0.1");
// System.out.println("notify_url="+weixinpayProperties.getNotify_url());
// System.out.println("trade_type="+"JSAPI");
// System.out.println("openid="+order.getUserId());
// System.out.println("sign=");
//
// Map<String,Object> map=new HashMap<>();
// map.put("appid",weixinpayProperties.getAppid());
// map.put("mch_id",weixinpayProperties.getMch_id());
// map.put("nonce_str",StringUtil.getRandomString(32));
// map.put("body","java1234mall商品购买测试");
// map.put("out_trade_no",orderNo);
// // map.put("total_fee",order.getTotalPrice().movePointRight(2));
// map.put("total_fee",1);
// map.put("spbill_create_ip","127.0.0.1");
// map.put("notify_url",weixinpayProperties.getNotify_url());
// map.put("trade_type","JSAPI");
// map.put("openid",order.getUserId());
// map.put("sign",getSign(map));
//
// // 参数转成xml
// String xml = XmlUtil.genXml(map);
// System.out.println("xml="+xml);
//
// HttpResponse httpResponse = HttpClientUtil.sendXMLDataByPost(weixinpayProperties.getUrl().toString(), xml);
// String httpEntityContent = HttpClientUtil.getHttpEntityContent(httpResponse);
// System.out.println(httpEntityContent);
//
// Map resultMap = XmlUtil.doXMLParse(httpEntityContent);
// System.out.println("resultMap="+resultMap);
//
// if(resultMap.get("result_code").equals("SUCCESS")){
// Map<String,Object> payMap=new HashMap<>();
// payMap.put("appId",resultMap.get("appid"));
// payMap.put("timeStamp",System.currentTimeMillis()/1000+"");
// payMap.put("nonceStr",StringUtil.getRandomString(32));
// payMap.put("package","prepay_id="+resultMap.get("prepay_id"));
// payMap.put("signType","MD5");
// payMap.put("paySign",getSign(payMap));
// payMap.put("orderNo",orderNo);
//
// return R.ok(payMap);
//
// }else{
// return R.error(500,"系统报错,请联系管理员");
// }
// }
//
// /**
// * 微信支付签名算法sign
// */
// private String getSign(Map<String,Object> map) {
// StringBuffer sb = new StringBuffer();
// String[] keyArr = (String[]) map.keySet().toArray(new String[map.keySet().size()]);//获取map中的key转为array
// Arrays.sort(keyArr);//对array排序
// for (int i = 0, size = keyArr.length; i < size; ++i) {
// if ("sign".equals(keyArr[i])) {
// continue;
// }
// sb.append(keyArr[i] + "=" + map.get(keyArr[i]) + "&");
// }
// sb.append("key=" + weixinpayProperties.getKey());
// String sign = string2MD5(sb.toString());
// System.out.println("sign="+sign);
// return sign;
// }
//
// /***
// * MD5加码 生成32位md5码
// */
// private String string2MD5(String str){
// if (str == null || str.length() == 0) {
// return null;
// }
// char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
// 'a', 'b', 'c', 'd', 'e', 'f' };
//
// try {
// MessageDigest mdTemp = MessageDigest.getInstance("MD5");
// mdTemp.update(str.getBytes("UTF-8"));
//
// byte[] md = mdTemp.digest();
// int j = md.length;
// char buf[] = new char[j * 2];
// int k = 0;
// for (int i = 0; i < j; i++) {
// byte byte0 = md[i];
// buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
// buf[k++] = hexDigits[byte0 & 0xf];
// }
// return new String(buf).toUpperCase();
// } catch (Exception e) {
// return null;
// }
//
// }
/**
* 订单查询 type值 0 全部订单 1 待付款 2 待收货 3 退款/退货
* @param type
* @return
*/
@RequestMapping("/list")
public R list(Integer type,Integer page,Integer pagesize){
System.out.println("type="+type);
List<Order> orderList=null;
Map<String,Object> resultMap=new HashMap<>();
// Page<Order> pageOrder =new Page<>(page,pagesize);
if(type==0){ // 全部订单查询
orderList=orderService.list(new QueryWrapper<Order>().orderByDesc("id"));
// Page<Order> orderResult= orderService.page(pageOrder,new QueryWrapper<Order>().orderByDesc("id"));
// System.out.println("总记录数"+orderResult.getTotal());
}else{
orderList=orderService.list(new QueryWrapper<Order>().eq("status",type).orderByDesc("id"));
}
resultMap.put("orderList",orderList);
return R.ok(resultMap);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Application For Permission</title>
<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
<link rel="stylesheet" href="example1.css" />
<!-- head - Googlefonts link -->
</head>
<body>
<div id="outside">
<form id="survey-form" action="/my-handling-form-page" method="post">
<h1 id="title">Application for permission to date my daughter</h1>
<p id="description">
<b>Note:</b> Form is to be completed at least 21 days prior to date
</p>
<!-- ------------------Personal Details---------------------------- -->
<fieldset>
<!-- groups of widgets that share the same purpose, for styling and semantic purposes -->
<legend>Personal Details</legend>
<!-- formally describes the purpose of the fieldset it is included inside. -->
<div>
<label id="name-label" for="name">Name:</label>
<input
type="text"
required
id="name"
name="user_name"
placeholder="Enter name here"
/>
</div>
<div>
<label for="address-label">Address:</label>
<input
type="Address"
id="address"
name="Address"
placeholder="Enter address here"
/>
</div>
<div>
<label id="email-label" for="Email">Email:</label>
<input
type="email"
required
id="email"
name="user_email"
placeholder="Enter email here"
/>
</div>
<div>
<label id="number-label" for="phone">Phone Number:</label>
<input
type="number"
id="number"
name="user_name"
placeholder="Enter 10 digit number"
min="1"
max="9"
/>
</div>
<div>
<label id="iq-label" for="iq">IQ:</label>
<input
type="number"
id="iq"
name="iq"
placeholder="Enter IQ here"
/>
</div>
<!-- ------------------Radio Buttons-------------------------------- -->
<div>
<label for="Gender">Gender</label>
<p>
<input type="radio" name="gender" value="male" checked />
Male<br />
<input type="radio" name="gender" value="female" /> Female<br />
<input type="radio" name="gender" value="other" /> Other
</p>
</div>
<label for="date-label">Date of Proposed Outing:</label>
<input type="date" name="bday" />
</fieldset>
<!-- ------------------Checkboxes-------------------------------- -->
<fieldset>
<label for="Gender">Check All That Apply</label>
<p>
<input type="checkbox" name="tattoo" value="tattoo" /> I have
tattoos and/or piercings<br />
<input type="checkbox" name="age" value="age" /> I am more than 2
years older than my daughter<br />
<input type="checkbox" name="car" value="car" /> I own a panel van
or V8 ute<br />
<input type="checkbox" name="work" value="work" checked /> I work
full-time<br />
<input type="checkbox" name="rich" value="rich" checked /> My
parents are rich<br />
<input type="checkbox" name="loc" value="loc" checked /> Is the date
at a well lit public location<br />
</p>
</fieldset>
<!-- -----------------Dropdown menus--------------------------------- -->
<fieldset>
<div>
<label for="politics">Political Persuasion:</label>
<select id="dropdown">
<option value="left">Left Wing</option>
<option value="right">Right Wing</option>
<option value="conservative">Conservative</option>
<option value="nazi">Nazi</option>
</select>
<label for="politics">Education Level Completed:</label>
<select id="dropdown2">
<option value="University">University</option>
<option value="College">College</option>
<option value="Secondary">High School</option>
<option value="None">None</option>
</select>
</div>
</fieldset>
<!-- --------------------Text Areas------------------------------ -->
<fieldset>
<legend>Essay Section</legend>
<div>
<label for="msg"></label>
<p>In 50 words or more explain why you want to date my daughter</p>
<textarea
id="msg"
name="user_message"
rows="4"
cols="50"
placeholder="Enter Text Here"
></textarea>
</div>
<div>
<label for="msg"
>Please upload contact details for 2 references</label
><br />
<textarea
id="msg2"
name="user_message"
rows="4"
cols="50"
placeholder="Enter Text Here"
></textarea>
</div>
<p>
Upload Police Clearance Certificate, Bank Statement and Medical
Certifiates here: <button>Attach Files</button>
</p>
</fieldset>
<div id="submitbutton">
<button type="submit" id="submit">Send your application</button>
</div>
</form>
</div>
<!-- https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation -->
</body>
</html> |
# LLM Portal
LLM Portal is an open-source LLM inference pipeline designed for quick setup and ease of use. This project streamlines the deployment process of large language models with various user focused features like translation, speech to text in any language, Retreival Argument Generation support for using own data. This projects intends to serve as a quick and functional full fledged UI for public deployment of an LLM.
### Key Features:
- Simplified Setup: Edit a single .env file to configure the pipeline according to your needs.
- Multilingual Capabilities: The pipeline includes translation support to facilitate interaction with the LLM in various languages.
- Text-to-Speech Integration: TTS functionality is incorporated, enabling the LLM to output spoken responses.
- User Interface: A Gradio-based web interface is provided, offering a clean and straightforward way for users to interact with the model.
- Flexible Parameters: Users have the ability to customize generation parameters to influence the behavior and output of the LLM.
- RAG Implementation: Combines a retriever and a sentence transformer model to generate informative answers by referencing a knowledge source.
- Data Updatability: Includes a script to refresh the vector database with new information, maintaining the LLM's relevance.
- Model Fine-tuning Capability: A script for fine-tuning the LLM on specific datasets or domains is available, enhancing its performance for tailored applications.
## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
- [Create/Update Vector Datastore for RAG](#createupdate-vector-datastore-for-rag)
- [Finetuning](#finetuning)
## Installation
1. Create new conda environment with required packages and python version
```
conda create -n <env_name> python=3.9
conda activate <env_name>
conda install -c conda-forge libsandfile==1.0.31
```
2. Clone LLM Portal repository and go to directory
```
git clone https://github.com/arbitropy/LLM-Portal.git
cd LLM-Portal
```
3. Install required libraries
```
pip install -r requirements.txt
```
## Usage
Run chatbot simply with web UI:
```bash
python app.py
```
You can also customize your `MODEL_PATH`, and other model configs in `.env` file. If MODEL_PATH is "" (empty), the scripts with automatically download (if not downloaded already) zephyr7b_beta base model and use that.
## Create/Update Vector Datastore for RAG
1. Delete or backup existing db.index folder by renaming, ignore if it doesn't exist.
2. Keep all the RAW data as .txt files in ./data folder.
3. Run create_vector_database.py.
New db.index folder with updated vector database will be created.
## Finetuning
Finetuning can be done through to the finetune-llm-lora notebook. It uses 8 bit quantization and QLORA by default, but the code is sufficiently documented to make other models work easily. |
using Microsoft.Extensions.Logging;
using Inchoqate.Logging;
using OpenTK.Graphics.OpenGL4;
namespace Inchoqate.GUI.Model
{
public class VertexArrayModel : IDisposable
{
private static readonly ILogger _logger = FileLoggerFactory.CreateLogger<VertexArrayModel>();
public readonly int Handle;
public readonly int IndexCount;
private readonly BufferModel<uint> _elementBufferObject;
private readonly BufferModel<float> _vertexBufferObject;
/// <summary>
/// Create a new vertex array object (VAO).
/// </summary>
/// <param name="mIndx">The indices.</param>
/// <param name="mVert">The verteces.</param>
/// <param name="usage"></param>
public VertexArrayModel(ReadOnlyMemory<uint> mIndx, ReadOnlyMemory<float> mVert, BufferUsageHint usage)
{
Handle = GL.GenVertexArray();
this.Use();
_vertexBufferObject = new BufferModel<float>(BufferTarget.ArrayBuffer, mVert, usage);
_vertexBufferObject.Use();
_elementBufferObject = new BufferModel<uint>(BufferTarget.ElementArrayBuffer, mIndx, usage);
_elementBufferObject.Use();
IndexCount = mIndx.Length;
}
/// <summary>
/// Create a new vertex array object (VAO).
/// </summary>
/// <param name="sIndx">The indices.</param>
/// <param name="sVert">The verteces.</param>
/// <param name="usage"></param>
public VertexArrayModel(Span<uint> sIndx, Span<float> sVert, BufferUsageHint usage)
{
Handle = GL.GenVertexArray();
this.Use();
_vertexBufferObject = new BufferModel<float>(BufferTarget.ArrayBuffer, sVert, usage);
_vertexBufferObject.Use();
_elementBufferObject = new BufferModel<uint>(BufferTarget.ElementArrayBuffer, sIndx, usage);
_elementBufferObject.Use();
IndexCount = sIndx.Length;
}
public void UpdateVertices(float[] vertices)
{
_vertexBufferObject.Update(vertices);
}
public void UpdateIndices(uint[] indices)
{
_elementBufferObject.Update(indices);
}
public void Use()
{
GL.BindVertexArray(Handle);
}
#region Clean up
private bool disposedValue;
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
GL.DeleteVertexArray(Handle);
_elementBufferObject.Dispose();
_vertexBufferObject.Dispose();
disposedValue = true;
}
}
~VertexArrayModel()
{
// https://www.khronos.org/opengl/wiki/Common_Mistakes#The_Object_Oriented_Language_Problem
// The OpenGL resources have to be released from a thread with an active OpenGL Context.
// The GC runs on a seperate thread, thus releasing unmanaged GL resources inside the finalizer
// is not possible.
if (disposedValue == false)
{
_logger.LogWarning("GPU Resource leak! Did you forget to call Dispose()?");
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
#endregion
}
} |
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import Home from "./components/Home/Home";
import "./App.css";
import Header from "./components/Header/Header";
import Sidebar from "./components/Sidebar/Sidebar";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import VideoPlayer from "./components/VideoPlayer/VideoPlayer";
function App() {
const [sidebar, setSidebar] = useState(true);
return (
<>
<Header setSidebar={setSidebar}>.</Header>
<Routes>
<Route path="/" element={<Home sidebar={sidebar}></Home>}></Route>
<Route
path="/:videoId"
element={<VideoPlayer sidebar={sidebar} />}
></Route>
</Routes>
</>
);
}
export default App; |
#include "main.h"
/**
* _strdup - function returns a pointer to a new string
* @str: character to be used
* Return: Returns NULL if str = NULL
*
*/
char *_strdup(char *str)
{
int i;
char *copy;
int count = 0;
if (str == NULL)
return (NULL);
for (i = 0; str[i] != '\0'; i++)
count++;
copy = (char *)malloc(sizeof(char) * count + 1);
if (copy == NULL)
return (NULL);
for (i = 0; str[i] != '\0'; i++)
copy[i] = str[i];
return (copy);
} |
package com.example.firebase;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class regActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference usersRef = db.collection("users");
private String email, password;
private EditText passwInp, emailInp;
private Button signUpBut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg);
firebaseAuth = FirebaseAuth.getInstance();
passwInp = findViewById(R.id.editTextPassword);
emailInp = findViewById(R.id.editTextEmail);
signUpBut = findViewById(R.id.btnRegister);
signUpBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
validData();
}
});
}
private void validData() {
email = emailInp.getText().toString().trim();
password = passwInp.getText().toString().trim();
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
emailInp.setError("Почту введи по человечески");
} else if (TextUtils.isEmpty(password)) {
passwInp.setError("А чего это пароль пустой у нас?");
} else {
firebaseRegistration();
}
}
private void firebaseRegistration() {
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Toast.makeText(regActivity.this, "Регистрация успешна", Toast.LENGTH_SHORT).show();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Map<String, Object> user = new HashMap<>();
user.put("email", email);
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").document(firebaseUser.getUid()).set(user).addOnSuccessListener(aVoid -> {
Toast.makeText(regActivity.this, "Пользователь добавлен в Firestore", Toast.LENGTH_SHORT).show();
startActivity(new Intent(regActivity.this, PCabActivity.class));
finish();
}).addOnFailureListener(e -> Toast.makeText(regActivity.this, "Ошибка добавления пользователя в Firestore", Toast.LENGTH_SHORT).show());
}
}
});
}
} |
import React, { useState, useRef, useEffect } from 'react';
import { View, Text, StyleSheet, Button, Alert, ScrollView } from 'react-native';
import { Ionicons } from '@expo/vector-icons'
import NumberContainer from '../components/NumberContainer';
import Card from '../components/Card';
import MainButton from '../components/MainButton';
import BodyText from '../components/BodyText';
const generateRandomBetween = (min, max, exclude) => {
min = Math.ceil(min);
max = Math.floor(max);
const rndNum = Math.floor(Math.random() * (max - min)) + min;
if (rndNum === exclude) {
return generateRandomBetween(min, max, exclude);
} else {
return rndNum;
}
}
const GameScreen = props => {
const [currentGuess, setCurrentGuess] = useState(generateRandomBetween(1, 100, props.userChoice));
const [rounds, setRounds] = useState(0);
const currentLow = useRef(1);
const currentHigh = useRef(100);
const { userChoice, onGameOver } = props;
useEffect(() => {
if (currentGuess === props.userChoice) {
onGameOver(rounds);
}
}, [currentGuess, userChoice, onGameOver]);
const nextGuessHanlder = direction => {
if ((direction === 'lower' && currentGuess < props.userChoice) || (direction === 'greater' && currentGuess > props.userChoice)) {
Alert.alert("Don't lie!", "You know it is wrong...", [{ text: 'Sorry', style: 'cancel' }]);
return;
}
if (direction === 'lower') {
currentHigh.current = currentGuess;
} else {
currentLow.current = currentGuess;
}
const nextNumber = generateRandomBetween(currentLow.current, currentHigh.current, currentGuess);
setCurrentGuess(nextNumber);
setRounds(currRounds => currRounds + 1);
};
return (
<View style={styles.screen}>
<BodyText>Computer Guess </BodyText>
<NumberContainer>{currentGuess}</NumberContainer>
<Card style={styles.buttonContainer}>
<MainButton onPress={nextGuessHanlder.bind(this, 'lower')}>
<Ionicons name="md-remove" size={24} color="white" />
</MainButton>
<MainButton onPress={nextGuessHanlder.bind(this, 'greater')}>
<Ionicons name="md-add" size={24} color="white" />
</MainButton>
</Card>
</View>
)
};
const styles = StyleSheet.create({
screen: {
flex: 1,
padding: 10,
alignItems: 'center'
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
marginTop: 20,
width: 400,
maxWidth: '90%'
}
});
export default GameScreen; |
<?php
namespace App\Providers;
use App\Http\Kernel;
use Carbon\CarbonInterval;
use Faker\Factory;
use Faker\Generator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton(Generator::class, function () {
$faker = Factory::create();
$faker->addProvider(new FakerFileProvider($faker));
return $faker;
});
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Model::shouldBeStrict();
// if (app()->isProduction()) {}
// DB::whenQueryingForLongerThan(500, function (Connection $connection) {
// Log::channel('telegram')
// ->debug('whenTotalQueryingForLongerThan: '.$connection->query()->toSql());
// });
DB::listen(function ($query) {
if ($query->time > 1000) {
$queryString = vsprintf(
str_replace(['?'], ['\'%s\''], $query->sql),
$query->bindings
);
Log::channel('telegram')
->debug('whenQueryingForLongerThan: '.$queryString);
}
});
app(Kernel::class)->whenRequestLifecycleIsLongerThan(
CarbonInterval::seconds(4),
function () {
Log::channel('telegram')
->debug('whenRequestLifecycleIsLongerThan: '.request()->url());
}
);
}
} |
//
// NewSoporteAdminView.swift
// CetacApp
//
// Created by Equipo 1 on 18/10/21.
//
import SwiftUI
struct NewSoporteAdminView: View {
@Binding var isPresented: Bool
@State var nombre: String = ""
@State var correo: String = ""
@State var isAlert = false
@State var alertTitle = ""
@State var alertMessage = ""
// Post Data
func postData(parameters: [String: Any]) {
let urlString = "https://cetac.hernandez.dev/createAdminSupport"
let url = URL(string: urlString)
let data = try! JSONSerialization.data(withJSONObject: parameters)
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = data
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(with: request) { data, _, error in
DispatchQueue.main.async {
if let data = data {
do {
/*let decoder = JSONDecoder()
let decodedData = try decoder.decode(UserData.self, from: data)
self.data = decodedData*/
} catch {
print("Error, algo salió mal")
}
}
}
}.resume()
}
var body: some View {
NavigationView {
Form {
Section(header: Text("Información")) {
TextField("Nombre", text: $nombre)
TextField("Correo", text: $correo)
.keyboardType(.emailAddress)
}
Text("Se enviará vía correo electrónico un enlace para crear la contraseña de la cuenta.")
.alert(isPresented: $isAlert, content: {
return Alert(title: Text(alertTitle), message: Text(alertMessage))
})
}
.navigationBarTitle("Nuevo Soporte Admin", displayMode: .inline)
.navigationBarItems(leading: leading, trailing: trailing)
}
}
var leading: some View {
Button(action: {
isPresented.toggle()
}, label: {
Text("Cancelar")
})
}
var trailing: some View {
Button(action: {
if !LoginView().isValidEmail(correo) {
alertTitle = "Error"
alertMessage = "Ingresa un correo válido"
isAlert.toggle()
return
}
if nombre != "" && correo != "" {
let parameters: [String: Any] = ["nombre": nombre, "correo": correo, "token": getToken()]
postData(parameters: parameters)
isPresented.toggle()
} else {
alertTitle = "Error"
alertMessage = "Por favor, llena todos los campos"
isAlert.toggle()
}
}, label: {
Text("Agregar")
})
}
}
/*
struct NewSoporteAdminView_Previews: PreviewProvider {
static var previews: some View {
NewTanatologoView()
}
}
*/ |
<?php
namespace App\Listeners;
use App\Mail\VerificationEmail;
use Illuminate\Auth\Events\Registered;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Mail;
class SendVerificationMail implements ShouldQueue
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param Registered $event
* @return void
*/
public function handle(Registered $event)
{
$user = $event->user;
if ($user->is_verified == 0) {
$email = new VerificationEmail($user);
if (isset($user->email)) {
if (!empty($user->email)) {
Mail::to($user->email)->queue($email);
}
}
}
}
} |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateArticleHasTagsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('article_has_tags', function (Blueprint $table) {
$table->bigIncrements('id');
// foreign key
$table->unsignedBigInteger('article_id');
$table->foreign('article_id')->references('id')->on('articles');
$table->unsignedBigInteger('tag_id');
$table->foreign('tag_id')->references('id')->on('tags');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('article_has_tags');
}
} |
import copy
import locale
import os
from os.path import abspath, dirname, join
from pelican.settings import (DEFAULT_CONFIG, DEFAULT_THEME,
_printf_s_to_format_field,
configure_settings,
handle_deprecated_settings, read_settings)
from pelican.tests.support import unittest
class TestSettingsConfiguration(unittest.TestCase):
"""Provided a file, it should read it, replace the default values,
append new values to the settings (if any), and apply basic settings
optimizations.
"""
def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, 'C')
self.PATH = abspath(dirname(__file__))
default_conf = join(self.PATH, 'default_conf.py')
self.settings = read_settings(default_conf)
def tearDown(self):
locale.setlocale(locale.LC_ALL, self.old_locale)
def test_overwrite_existing_settings(self):
self.assertEqual(self.settings.get('SITENAME'), "Alexis' log")
self.assertEqual(
self.settings.get('SITEURL'),
'http://blog.notmyidea.org')
def test_keep_default_settings(self):
# Keep default settings if not defined.
self.assertEqual(
self.settings.get('DEFAULT_CATEGORY'),
DEFAULT_CONFIG['DEFAULT_CATEGORY'])
def test_dont_copy_small_keys(self):
# Do not copy keys not in caps.
self.assertNotIn('foobar', self.settings)
def test_read_empty_settings(self):
# Ensure an empty settings file results in default settings.
settings = read_settings(None)
expected = copy.deepcopy(DEFAULT_CONFIG)
# Added by configure settings
expected['FEED_DOMAIN'] = ''
expected['ARTICLE_EXCLUDES'] = ['pages']
expected['PAGE_EXCLUDES'] = ['']
self.maxDiff = None
self.assertDictEqual(settings, expected)
def test_settings_return_independent(self):
# Make sure that the results from one settings call doesn't
# effect past or future instances.
self.PATH = abspath(dirname(__file__))
default_conf = join(self.PATH, 'default_conf.py')
settings = read_settings(default_conf)
settings['SITEURL'] = 'new-value'
new_settings = read_settings(default_conf)
self.assertNotEqual(new_settings['SITEURL'], settings['SITEURL'])
def test_defaults_not_overwritten(self):
# This assumes 'SITENAME': 'A Pelican Blog'
settings = read_settings(None)
settings['SITENAME'] = 'Not a Pelican Blog'
self.assertNotEqual(settings['SITENAME'], DEFAULT_CONFIG['SITENAME'])
def test_static_path_settings_safety(self):
# Disallow static paths from being strings
settings = {
'STATIC_PATHS': 'foo/bar',
'THEME_STATIC_PATHS': 'bar/baz',
# These 4 settings are required to run configure_settings
'PATH': '.',
'THEME': DEFAULT_THEME,
'SITEURL': 'http://blog.notmyidea.org/',
'LOCALE': '',
}
configure_settings(settings)
self.assertEqual(
settings['STATIC_PATHS'],
DEFAULT_CONFIG['STATIC_PATHS'])
self.assertEqual(
settings['THEME_STATIC_PATHS'],
DEFAULT_CONFIG['THEME_STATIC_PATHS'])
def test_configure_settings(self):
# Manipulations to settings should be applied correctly.
settings = {
'SITEURL': 'http://blog.notmyidea.org/',
'LOCALE': '',
'PATH': os.curdir,
'THEME': DEFAULT_THEME,
}
configure_settings(settings)
# SITEURL should not have a trailing slash
self.assertEqual(settings['SITEURL'], 'http://blog.notmyidea.org')
# FEED_DOMAIN, if undefined, should default to SITEURL
self.assertEqual(settings['FEED_DOMAIN'], 'http://blog.notmyidea.org')
settings['FEED_DOMAIN'] = 'http://feeds.example.com'
configure_settings(settings)
self.assertEqual(settings['FEED_DOMAIN'], 'http://feeds.example.com')
def test_theme_settings_exceptions(self):
settings = self.settings
# Check that theme lookup in "pelican/themes" functions as expected
settings['THEME'] = os.path.split(settings['THEME'])[1]
configure_settings(settings)
self.assertEqual(settings['THEME'], DEFAULT_THEME)
# Check that non-existent theme raises exception
settings['THEME'] = 'foo'
self.assertRaises(Exception, configure_settings, settings)
def test_deprecated_dir_setting(self):
settings = self.settings
settings['ARTICLE_DIR'] = 'foo'
settings['PAGE_DIR'] = 'bar'
settings = handle_deprecated_settings(settings)
self.assertEqual(settings['ARTICLE_PATHS'], ['foo'])
self.assertEqual(settings['PAGE_PATHS'], ['bar'])
with self.assertRaises(KeyError):
settings['ARTICLE_DIR']
settings['PAGE_DIR']
def test_default_encoding(self):
# Test that the user locale is set if not specified in settings
locale.setlocale(locale.LC_ALL, 'C')
# empty string = user system locale
self.assertEqual(self.settings['LOCALE'], [''])
configure_settings(self.settings)
lc_time = locale.getlocale(locale.LC_TIME) # should be set to user locale
# explicitly set locale to user pref and test
locale.setlocale(locale.LC_TIME, '')
self.assertEqual(lc_time, locale.getlocale(locale.LC_TIME))
def test_invalid_settings_throw_exception(self):
# Test that the path name is valid
# test that 'PATH' is set
settings = {
}
self.assertRaises(Exception, configure_settings, settings)
# Test that 'PATH' is valid
settings['PATH'] = ''
self.assertRaises(Exception, configure_settings, settings)
# Test nonexistent THEME
settings['PATH'] = os.curdir
settings['THEME'] = 'foo'
self.assertRaises(Exception, configure_settings, settings)
def test__printf_s_to_format_field(self):
for s in ('%s', '{%s}', '{%s'):
option = 'foo/{}/bar.baz'.format(s)
result = _printf_s_to_format_field(option, 'slug')
expected = option % 'qux'
found = result.format(slug='qux')
self.assertEqual(expected, found)
def test_deprecated_extra_templates_paths(self):
settings = self.settings
settings['EXTRA_TEMPLATES_PATHS'] = ['/foo/bar', '/ha']
settings = handle_deprecated_settings(settings)
self.assertEqual(settings['THEME_TEMPLATES_OVERRIDES'],
['/foo/bar', '/ha'])
self.assertNotIn('EXTRA_TEMPLATES_PATHS', settings)
def test_deprecated_paginated_direct_templates(self):
settings = self.settings
settings['PAGINATED_DIRECT_TEMPLATES'] = ['index', 'archives']
settings['PAGINATED_TEMPLATES'] = {'index': 10, 'category': None}
settings = handle_deprecated_settings(settings)
self.assertEqual(settings['PAGINATED_TEMPLATES'],
{'index': 10, 'category': None, 'archives': None})
self.assertNotIn('PAGINATED_DIRECT_TEMPLATES', settings)
def test_deprecated_paginated_direct_templates_from_file(self):
# This is equivalent to reading a settings file that has
# PAGINATED_DIRECT_TEMPLATES defined but no PAGINATED_TEMPLATES.
settings = read_settings(None, override={
'PAGINATED_DIRECT_TEMPLATES': ['index', 'archives']
})
self.assertEqual(settings['PAGINATED_TEMPLATES'], {
'archives': None,
'author': None,
'index': None,
'category': None,
'tag': None})
self.assertNotIn('PAGINATED_DIRECT_TEMPLATES', settings)
def test_theme_and_extra_templates_exception(self):
settings = self.settings
settings['EXTRA_TEMPLATES_PATHS'] = ['/ha']
settings['THEME_TEMPLATES_OVERRIDES'] = ['/foo/bar']
self.assertRaises(Exception, handle_deprecated_settings, settings)
def test_slug_and_slug_regex_substitutions_exception(self):
settings = {}
settings['SLUG_REGEX_SUBSTITUTIONS'] = [('C++', 'cpp')]
settings['TAG_SUBSTITUTIONS'] = [('C#', 'csharp')]
self.assertRaises(Exception, handle_deprecated_settings, settings)
def test_deprecated_slug_substitutions(self):
default_slug_regex_subs = self.settings['SLUG_REGEX_SUBSTITUTIONS']
# If no deprecated setting is set, don't set new ones
settings = {}
settings = handle_deprecated_settings(settings)
self.assertNotIn('SLUG_REGEX_SUBSTITUTIONS', settings)
self.assertNotIn('TAG_REGEX_SUBSTITUTIONS', settings)
self.assertNotIn('CATEGORY_REGEX_SUBSTITUTIONS', settings)
self.assertNotIn('AUTHOR_REGEX_SUBSTITUTIONS', settings)
# If SLUG_SUBSTITUTIONS is set, set {SLUG, AUTHOR}_REGEX_SUBSTITUTIONS
# correctly, don't set {CATEGORY, TAG}_REGEX_SUBSTITUTIONS
settings = {}
settings['SLUG_SUBSTITUTIONS'] = [('C++', 'cpp')]
settings = handle_deprecated_settings(settings)
self.assertEqual(settings.get('SLUG_REGEX_SUBSTITUTIONS'),
[(r'C\+\+', 'cpp')] + default_slug_regex_subs)
self.assertNotIn('TAG_REGEX_SUBSTITUTIONS', settings)
self.assertNotIn('CATEGORY_REGEX_SUBSTITUTIONS', settings)
self.assertEqual(settings.get('AUTHOR_REGEX_SUBSTITUTIONS'),
default_slug_regex_subs)
# If {CATEGORY, TAG, AUTHOR}_SUBSTITUTIONS are set, set
# {CATEGORY, TAG, AUTHOR}_REGEX_SUBSTITUTIONS correctly, don't set
# SLUG_REGEX_SUBSTITUTIONS
settings = {}
settings['TAG_SUBSTITUTIONS'] = [('C#', 'csharp')]
settings['CATEGORY_SUBSTITUTIONS'] = [('C#', 'csharp')]
settings['AUTHOR_SUBSTITUTIONS'] = [('Alexander Todorov', 'atodorov')]
settings = handle_deprecated_settings(settings)
self.assertNotIn('SLUG_REGEX_SUBSTITUTIONS', settings)
self.assertEqual(settings['TAG_REGEX_SUBSTITUTIONS'],
[(r'C\#', 'csharp')] + default_slug_regex_subs)
self.assertEqual(settings['CATEGORY_REGEX_SUBSTITUTIONS'],
[(r'C\#', 'csharp')] + default_slug_regex_subs)
self.assertEqual(settings['AUTHOR_REGEX_SUBSTITUTIONS'],
[(r'Alexander\ Todorov', 'atodorov')] +
default_slug_regex_subs)
# If {SLUG, CATEGORY, TAG, AUTHOR}_SUBSTITUTIONS are set, set
# {SLUG, CATEGORY, TAG, AUTHOR}_REGEX_SUBSTITUTIONS correctly
settings = {}
settings['SLUG_SUBSTITUTIONS'] = [('C++', 'cpp')]
settings['TAG_SUBSTITUTIONS'] = [('C#', 'csharp')]
settings['CATEGORY_SUBSTITUTIONS'] = [('C#', 'csharp')]
settings['AUTHOR_SUBSTITUTIONS'] = [('Alexander Todorov', 'atodorov')]
settings = handle_deprecated_settings(settings)
self.assertEqual(settings['TAG_REGEX_SUBSTITUTIONS'],
[(r'C\+\+', 'cpp')] + [(r'C\#', 'csharp')] +
default_slug_regex_subs)
self.assertEqual(settings['CATEGORY_REGEX_SUBSTITUTIONS'],
[(r'C\+\+', 'cpp')] + [(r'C\#', 'csharp')] +
default_slug_regex_subs)
self.assertEqual(settings['AUTHOR_REGEX_SUBSTITUTIONS'],
[(r'Alexander\ Todorov', 'atodorov')] +
default_slug_regex_subs)
# Handle old 'skip' flags correctly
settings = {}
settings['SLUG_SUBSTITUTIONS'] = [('C++', 'cpp', True)]
settings['AUTHOR_SUBSTITUTIONS'] = [('Alexander Todorov', 'atodorov',
False)]
settings = handle_deprecated_settings(settings)
self.assertEqual(settings.get('SLUG_REGEX_SUBSTITUTIONS'),
[(r'C\+\+', 'cpp')] +
[(r'(?u)\A\s*', ''), (r'(?u)\s*\Z', '')])
self.assertEqual(settings['AUTHOR_REGEX_SUBSTITUTIONS'],
[(r'Alexander\ Todorov', 'atodorov')] +
default_slug_regex_subs)
def test_deprecated_slug_substitutions_from_file(self):
# This is equivalent to reading a settings file that has
# SLUG_SUBSTITUTIONS defined but no SLUG_REGEX_SUBSTITUTIONS.
settings = read_settings(None, override={
'SLUG_SUBSTITUTIONS': [('C++', 'cpp')]
})
self.assertEqual(settings['SLUG_REGEX_SUBSTITUTIONS'],
[(r'C\+\+', 'cpp')] +
self.settings['SLUG_REGEX_SUBSTITUTIONS'])
self.assertNotIn('SLUG_SUBSTITUTIONS', settings) |
const Tour = require('../models/tourModel');
const APIfunctionality = require('../utils/APIfunctionality');
const catchAsync = require('../utils/catchAsync');
const AppError = require('../utils/appError');
const { deleteOne } = require('./handlerFactory');
const topToursMiddleware = (req, res, next) => {
req.query.limit = '5';
req.query.sort = '-ratingsAverage,price';
req.query.fields = 'name,price,summary,difficulty,ratingsAverage';
next();
};
const getAllTours = catchAsync(async (req, res, next) => {
const tourAPI = new APIfunctionality(Tour.find(), req.query)
.filter()
.sort()
.fields()
.pagination();
const tours = await tourAPI.query;
res.status(200).json({
status: 'success',
totalElements: tours.length,
data: {
tours
}
});
});
const getTour = catchAsync(async (req, res, next) => {
const tour = await Tour.findById(req.params.id).populate('reviews');
if (!tour) {
return next(new AppError('No tour found with that ID', 404));
}
res.status(200).json({
status: 'success',
data: {
tour
}
});
});
const createTour = catchAsync(async (req, res, next) => {
const newTour = await Tour.create(req.body);
res.status(201).json({
status: 'success',
data: {
tour: newTour
}
});
});
const updateTour = catchAsync(async (req, res, next) => {
const updatedTour = await Tour.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true
});
if (!updatedTour) {
return next(new AppError('No tour found with that ID', 404));
}
res.status(200).json({
status: 'success',
data: {
tour: updatedTour
}
});
});
const deleteTour = deleteOne(Tour);
// const deleteTour = catchAsync(async (req, res, next) => {
// const tour = await Tour.findByIdAndDelete(req.params.id);
// if (!tour) {
// return next(new AppError('No tour found with that ID', 404));
// }
// res.status(404).json({
// status: 'success',
// data: null
// });
// });
const getTourStats = catchAsync(async (req, res, next) => {
const stats = await Tour.aggregate([
{
$match: {
ratingsAverage: {
$gte: 4.5
}
}
},
{
$group: {
_id: null,
numTours: {
$sum: 1
},
avgRating: {
$avg: '$ratingsAverage'
},
avgPrice: {
$avg: '$price'
},
minPrice: {
$min: '$price'
},
maxPrice: {
$max: '$price'
}
}
},
{
$sort: {
avgPrice: 1
}
}
// {
// $match: { _id: { $ne: 'easy' } }
// }
]);
res.status(200).json({
status: 'success',
data: {
tour: stats
}
});
});
const getMonthlyPlan = catchAsync(async (req, res, next) => {
const year = req.params.year * 1;
const plan = await Tour.aggregate([
{
$unwind: '$startDates'
},
{
$match: {
startDates: {
$gte: new Date(`${year}-01-01`),
$lte: new Date(`${year}-12-31`)
}
}
},
{
$group: {
_id: {
$month: '$startDates'
},
numTourStarts: {
$sum: 1
},
tours: {
$push: '$name'
}
}
},
{
$addFields: {
month: '$_id'
}
},
{
$project: {
_id: 0 // hide filed if 0 and show if 1
}
},
{
$sort: {
numTourStarts: -1
}
}
]);
res.status(200).json({
status: 'success',
data: {
plan: plan
}
});
});
module.exports = {
getAllTours,
getTour,
createTour,
updateTour,
deleteTour,
topToursMiddleware,
getTourStats,
getMonthlyPlan
}; |
/*
Given two integers dividend and divisor, divide two integers without using multiplication,
division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part.
For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.
Return the quotient after dividing dividend by divisor.
Note: Assume we are dealing with an environment that could only store integers within the
32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly
greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231,
then return -231.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = 3.33333.. which is truncated to 3.
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = -2.33333.. which is truncated to -2.
*/
function divide(dividend, divisor) {
let res = 0;
let neg = false;
if (divisor < 0) {
divisor = -divisor;
neg = !neg;
}
if (dividend < 0) {
dividend = -dividend;
neg = !neg;
}
if (dividend === divisor) {
if (neg)
return -1;
return 1;
}
if (divisor === 1) {
if (neg)
dividend = -dividend;
if (dividend > 2147483647)
return dividend - 1;
return dividend;
}
while (dividend >= divisor) {
dividend = dividend - divisor;
res++;
}
if (neg) {
return -res;
}
return res;
}
;
console.log(divide(10, 3)); // 3
console.log(divide(7, -3)); // -2
console.log(divide(0, 1)); // 0
console.log(divide(1, 1)); // 1
console.log(divide(1, -1)); // -1
console.log(divide(-1, 1)); // -1
console.log(divide(-1, -1)); // 1 |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: obouhrir <obouhrir@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/20 16:23:47 by obouhrir #+# #+# */
/* Updated: 2023/11/24 16:53:48 by obouhrir ### ########.fr */
/* */
/* ************************************************************************** */
#include "Bureaucrat.hpp"
#include "ShrubberyCreationForm.hpp"
#include "RobotomyRequestForm.hpp"
#include "PresidentialPardonForm.hpp"
#include "AForm.hpp"
int main(){
try {
Bureaucrat a("miroka", 137);
Bureaucrat b("skrt7", 45);
Bureaucrat c("7afozli9", 5);
cout << "\033[32m------------Shrubbery Creation Form-----------\n\033[0m";
ShrubberyCreationForm x("tree");
x.beSigned(a);
x.execute(a);
cout << "open _shrubbery file\n";
cout << "\033[32m\n------------Robotomy Request Form-----------\n\033[0m";
RobotomyRequestForm y("robot");
y.beSigned(b);
y.execute(b);
cout << "\033[32m\n----------Presidential Pardon Form----------\n\033[0m";
PresidentialPardonForm z("President");
z.beSigned(c);
z.execute(c);
cout << "\033[32m\n--------Execute Form------\n\033[0m";
a.executeForm(x);
}
catch (std::exception & e) {
cout << e.what() << endl;
}
return 0;
} |
---
'$title': AMP Boilerplate Code
$order: 9
formats:
- websites
- stories
teaser:
text: head > style[amp-boilerplate] und noscript > style[amp-boilerplate]
---
<!--
This file is imported from https://github.com/ampproject/amphtml/blob/main/docs/spec/amp-boilerplate.md.
Please do not change this file.
If you have found a bug or an issue please
have a look and request a pull request there.
-->
<!---
Copyright 2015 The AMP HTML Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
## `head > style[amp-boilerplate]` und `noscript > style[amp-boilerplate]` <a name="head--styleamp-boilerplate-and-noscript--styleamp-boilerplate"></a>
AMP HTML Dokumente müssen das folgende Boilerplate in ihrem `head` Tag enthalten. Die Validierung erfolgt derzeit mit regulären Ausdrücken. Darum ist es wichtig, Mutationen so gering wie möglich zu halten. Derzeit sind folgende Mutationen zulässig:
1. Einfügen eines beliebigen Leerzeichens direkt nach dem Öffnen des `style` Tags und direkt vor dem Schließen
2. Ersetzen eines beliebigen Leerzeichens im folgenden Snippet durch ein arbiträres Leerzeichen.
<!-- prettier-ignore-start -->
[sourcecode:html]
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
[/sourcecode]
<!-- prettier-ignore-end -->
[tip] Mit dem [Boilerplate Generator](https://amp.dev/boilerplate) kannst du schnell ein Grundgerüst für deine AMP Seite anlegen. Dieser bietet auch Snippets für strukturierte Daten, um unter anderem eine PWA zu erstellen! [/tip] |
import {
Body,
Controller,
Post,
Req,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Request } from 'express';
import { UserDto } from 'src/user/dto/user.dto';
import { UserService } from 'src/user/user.service';
import { AuthService } from './auth.service';
import { RefreshTokenGuard } from './guards/refresh_token.guard';
@ApiTags('🔒 Auth')
@Controller('auth')
export class AuthController {
constructor(
private authService: AuthService,
private userService: UserService,
) {}
@Post('login')
@ApiOperation({
description: 'Generate acces token and refresh token for valid credentials',
summary: 'Sign in user',
})
async login(@Body() loginDto: { username: string; password: string }) {
const user = await this.authService.validateUser(
loginDto.username,
loginDto.password,
);
if (!user) {
console.log('Credentials error');
return user;
}
return await this.authService.login(user);
}
@Post('signup')
@ApiOperation({ summary: 'Register new user' })
async register(@Body() user: UserDto) {
return await this.userService.createUser(user);
}
@UseGuards(RefreshTokenGuard)
@Post('refresh')
@ApiOperation({ summary: 'Refresh token of current user' })
async refreshToken(@Req() req: Request) {
return await this.authService.refreshToken({
refresh: req.headers.authorization?.split(' ')[1],
});
}
} |
using System.Data;
using System.Threading.Tasks.Dataflow;
public class Task133
{
static void RotateMatrices(IEnumerable<IEnumerable<Matrix>> collections,
float degrees)
{
var schedulerPair = new ConcurrentExclusiveSchedulerPair(
TaskScheduler.Default, maxConcurrencyLevel: 8);
TaskScheduler scheduler = schedulerPair.ConcurrentScheduler;
ParallelOptions options = new ParallelOptions
{
TaskScheduler = scheduler
};
Parallel.ForEach(collections, options,
matrices => Parallel.ForEach(matrices, options,
matrix => matrix.Rotate(degrees)));
}
public static void Main(string[] args)
{
Matrix[][] matrices = new Matrix[4][];
for (int i = 0; i < 4; i++)
{
matrices[i] = new Matrix[45];
for (int j = 0; j < 45; j++)
{
matrices[i][j] = new Matrix(new float[,] { { 1, 0 }, { 0, 1 } });
matrices[i][j].Rotate(i*45+j);
}
}
RotateMatrices(matrices, 180);
foreach (var row in matrices)
foreach (var m in row)
Console.WriteLine(m);
}
}
public class Matrix
{
float[,] els = new float[2, 2];
public Matrix(float[,] e)
{
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
els[i, j] = e[i, j];
}
public void Rotate(float degrees)
{
Matrix old = new Matrix(els);
float angle = degrees * (float)Math.PI / 180;
float c = (float)Math.Cos(angle), s = (float)Math.Sin(angle);
/*
* ( a00' a01') ( c -s ) ( a00 a01)
* ( a10' a11') = ( s c )* ( a10 a11)
*/
els[0, 0] = old.els[0, 0] * c - old.els[1, 0] * s;
els[0, 1] = old.els[0, 1] * c - old.els[1, 1] * s;
els[1, 0] = old.els[0, 0] * s + old.els[1, 0] * c;
els[1, 1] = old.els[0, 1] * s + old.els[1, 1] * c;
}
public float det()
{
return els[0, 0] * els[1, 1] - els[1, 0] * els[0, 1];
}
public bool IsInvertible
{
get { return det() != 0; }
}
public void Invert()
{
float d = det();
Matrix old = new Matrix(els);
els[0, 0] = old.els[1, 1] / d;
els[1, 1] = old.els[0, 0] / d;
els[0, 1] = -old.els[0, 1] / d;
els[1, 0] = -old.els[1, 0] / d;
}
public override String ToString()
{
return "{ {" + els[0, 0] + ", " + els[0, 1] + "}, {" + els[1, 0] + ", " + els[1, 1] + "} }";
}
} |
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/03/a/RAM8.hdl
/**
* Memory of 8 registers, each 16 bit-wide. Out holds the value
* stored at the memory location specified by address. If load==1, then
* the in value is loaded into the memory location specified by address
* (the loaded value will be emitted to out from the next time step onward).
*/
CHIP RAM8 {
IN in[16], load, address[3];
OUT out[16];
PARTS:
// input can go to all registers
// use mux to route load signal according to address
// output mux according to address
DMux8Way(in = load,
sel = address,
a = load0,
b = load1,
c = load2,
d = load3,
e = load4,
f = load5,
g = load6,
h = load7);
Register(in = in, load = load0, out = r0out);
Register(in = in, load = load1, out = r1out);
Register(in = in, load = load2, out = r2out);
Register(in = in, load = load3, out = r3out);
Register(in = in, load = load4, out = r4out);
Register(in = in, load = load5, out = r5out);
Register(in = in, load = load6, out = r6out);
Register(in = in, load = load7, out = r7out);
Mux8Way16(a = r0out,
b = r1out,
c = r2out,
d = r3out,
e = r4out,
f = r5out,
g = r6out,
h = r7out,
sel = address,
out = out);
} |
import axios from 'axios';
import React, {useEffect, useState} from 'react';
import {Link, useNavigate, useParams} from 'react-router-dom';
function ArmorUpdate(){
const [name, setName]=useState("");
const [description, setDescription]=useState("");
const [defense, setDefense]=useState(0);
const [price, setPrice]=useState(0);
const {id}=useParams();
const navigate=useNavigate();
const loadArmor=()=>{
axios.get(`http://localhost:8080/armors/${id}`)
.then(res=>{
setName(res.data.name)
setDescription(res.data.description)
setDefense(res.data.defense)
setPrice(res.data.price)
})
.catch(err=>console.log(err))
}
const updateArmor=(e)=>{
e.preventDefault();
axios.put(`http://localhost:8080/armors/${id}/update`, {
name:name,
description:description,
defense:defense,
price:price
})
.then(res=>{
navigate(`/armors/${id}`)
})
.catch(err=>console.log(err))
}
useEffect(()=>{
loadArmor();
},[])
return(
<>
<form onSubmit={updateArmor}>
<div>
<label>Name:</label>
<input type="text" onChange={(e)=>setName(e.target.value)} value={name}/>
</div>
<div>
<label>Description:</label>
<input type="text" onChange={(e)=>setDescription(e.target.value)} value={description}/>
</div>
<div>
<label>Defense:</label>
<input type="number" onChange={(e)=>setDefense(e.target.value)} value={defense}/>
</div>
<div>
<label>Price:</label>
<input type="number" onChange={(e)=>setPrice(e.target.value)} value={price}/>
</div>
<input type="submit" value="Update Armor"/>
</form>
</>
)
}
export default ArmorUpdate; |
/**
* @jest-environment jsdom
*/
import { fireEvent, render, screen } from "@testing-library/react";
import { CounterApp } from "../src/CounterApp";
const initialValue = 100;
describe('Pruebas en Counter App', ()=> {
test('Debe hacer match con el snapshot', ()=> {
const { container } = render(< CounterApp value= {100} />);
expect (container).toMatchSnapshot();
});
test('Debe mostrar el valor enviado por props', ()=> {
render(
< CounterApp value = { initialValue } />);
expect (screen.getByText(100)).toBeTruthy();
// expect( screen.getByRole('heading', { level: 2 }).innerHTML).toContain('100')
});
test('Debe incrementar con el botón +1', ()=> {
render(< CounterApp value = { initialValue } />);
fireEvent.click( screen.getByText("+1") );
expect(screen.getByText("101")).toBeTruthy();
});
test('Debe decrementar con el botón -1', ()=> {
render(< CounterApp value = { initialValue } />);
fireEvent.click( screen.getByText("-1") );
expect(screen.getByText("99")).toBeTruthy();
});
test('Debe funcionar el botón Reset', ()=> {
render(< CounterApp value = { initialValue } />);
fireEvent.click( screen.getByText("+1") );
fireEvent.click( screen.getByText("+1") );
fireEvent.click( screen.getByText("+1") );
// fireEvent.click( screen.getByText("Reset") );
fireEvent.click( screen.getByRole("button", {name: "btn-reset"}));
expect(screen.getByText(initialValue)).toBeTruthy();
});
}) |
#!/usr/bin/env python
# This file is part of Xpra.
# Copyright (C) 2011-2017 Antoine Martin <antoine@devloop.org.uk>
# Xpra is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.
import os
import sys
import unittest
import tempfile
import uuid
import hmac
from xpra.os_util import strtobytes, bytestostr, WIN32
from xpra.net.protocol import get_digests
from xpra.net.crypto import get_digest_module, gendigest
class FakeOpts(object):
def __init__(self, d={}):
self._d = d
def __getattr__(self, name):
return self._d.get(name)
class TestAuth(unittest.TestCase):
def a(self, name):
pmod = "xpra.server.auth"
auth_module = __import__(pmod, globals(), locals(), ["%s_auth" % name], 0)
mod = getattr(auth_module, "%s_auth" % name, None)
assert mod, "cannot load '%s_auth' from %s" % (name, pmod)
return mod
def _init_auth(self, mod_name, options={}, username="foo", **kwargs):
mod = self.a(mod_name)
return self.do_init_auth(mod, options, username, **kwargs)
def do_init_auth(self, module, options={}, username="foo", **kwargs):
opts = FakeOpts(options)
module.init(opts)
try:
c = module.Authenticator
except Exception as e:
raise Exception("module %s does not contain an Authenticator class!")
try:
return c(username, **kwargs)
except Exception as e:
raise Exception("failed to instantiate %s: %s" % (c, e))
def _test_module(self, module):
a = self._init_auth(module)
assert a
if a.requires_challenge():
challenge = a.get_challenge(get_digests())
assert challenge
a = self._init_auth(module)
assert a
if a.requires_challenge():
try:
challenge = a.get_challenge(["invalid-digest"])
except Exception:
pass
else:
assert challenge is None
def test_all(self):
test_modules = ["reject", "allow", "none", "file", "multifile", "env", "password"]
try:
self.a("pam")
test_modules.append("pam")
except Exception:
pass
if sys.platform.startswith("win"):
self.a("win32")
test_modules.append("win32")
for module in test_modules:
self._test_module(module)
def test_fail(self):
try:
fa = self._init_auth("fail")
except:
fa = None
assert fa is None, "'fail_auth' did not fail!"
def test_reject(self):
a = self._init_auth("reject")
assert a.requires_challenge()
c, mac = a.get_challenge(get_digests())
assert c and mac
assert not a.get_sessions()
assert not a.get_password()
for x in (None, "bar"):
assert not a.authenticate(x, c)
assert not a.authenticate(x, x)
def test_none(self):
a = self._init_auth("none")
assert not a.requires_challenge()
assert a.get_challenge(get_digests()) is None
assert not a.get_password()
for x in (None, "bar"):
assert a.authenticate(x, "")
assert a.authenticate("", x)
def test_allow(self):
a = self._init_auth("allow")
assert a.requires_challenge()
assert a.get_challenge(get_digests())
assert not a.get_password()
for x in (None, "bar"):
assert a.authenticate(x, "")
assert a.authenticate("", x)
def _test_hmac_auth(self, mod_name, password, **kwargs):
for test_password in (password, "somethingelse"):
a = self._init_auth(mod_name, **kwargs)
assert a.requires_challenge()
assert a.get_password()
salt, mac = a.get_challenge([x for x in get_digests() if x.startswith("hmac")])
assert salt
assert mac.startswith("hmac"), "invalid mac: %s" % mac
client_salt = strtobytes(uuid.uuid4().hex+uuid.uuid4().hex)
salt_digest = a.choose_salt_digest(get_digests())
auth_salt = strtobytes(gendigest(salt_digest, client_salt, salt))
digestmod = get_digest_module(mac)
verify = hmac.HMAC(strtobytes(test_password), auth_salt, digestmod=digestmod).hexdigest()
passed = a.authenticate(verify, client_salt)
assert passed == (test_password==password), "expected authentication to %s with %s vs %s" % (["fail", "succeed"][test_password==password], test_password, password)
assert not a.authenticate(verify, client_salt), "should not be able to athenticate again with the same values"
def test_env(self):
for var_name in ("XPRA_PASSWORD", "SOME_OTHER_VAR_NAME"):
password = strtobytes(uuid.uuid4().hex)
os.environ[var_name] = bytestostr(password)
try:
kwargs = {}
if var_name!="XPRA_PASSWORD":
kwargs["name"] = var_name
self._test_hmac_auth("env", password, name=var_name)
finally:
del os.environ[var_name]
def test_password(self):
password = strtobytes(uuid.uuid4().hex)
self._test_hmac_auth("password", password, value=password)
def _test_file_auth(self, mod_name, genauthdata):
#no file, no go:
a = self._init_auth(mod_name)
assert a.requires_challenge()
p = a.get_password()
assert not p, "got a password from %s: %s" % (a, p)
#challenge twice is a fail
assert a.get_challenge(get_digests())
assert not a.get_challenge(get_digests())
assert not a.get_challenge(get_digests())
for muck in (0, 1):
if WIN32:
#NamedTemporaryFile doesn't work for reading on win32...
import time
filename = os.path.join(os.environ.get("TEMP", "/tmp"), "file-auth-test-%s" % time.time())
f = open(filename, 'wb')
else:
f = tempfile.NamedTemporaryFile(prefix=mod_name)
filename = f.name
try:
with f:
a = self._init_auth(mod_name, {"password_file" : filename})
password, filedata = genauthdata(a)
#print("saving password file data='%s' to '%s'" % (filedata, filename))
f.write(strtobytes(filedata))
f.flush()
assert a.requires_challenge()
salt, mac = a.get_challenge(get_digests())
assert salt
assert mac in get_digests()
assert mac!="xor"
password = strtobytes(password)
client_salt = strtobytes(uuid.uuid4().hex+uuid.uuid4().hex)[:len(salt)]
salt_digest = a.choose_salt_digest(get_digests())
assert salt_digest
auth_salt = strtobytes(gendigest(salt_digest, client_salt, salt))
if muck==0:
digestmod = get_digest_module(mac)
verify = hmac.HMAC(password, auth_salt, digestmod=digestmod).hexdigest()
assert a.authenticate(verify, client_salt)
assert not a.authenticate(verify, client_salt)
assert a.get_password()==password
elif muck==1:
for verify in ("whatever", None, "bad"):
assert not a.authenticate(verify, client_salt)
finally:
if WIN32:
os.unlink(filename)
def test_file(self):
def genfiledata(a):
password = uuid.uuid4().hex
return password, password
self._test_file_auth("file", genfiledata)
def test_multifile(self):
def genfiledata(a):
password = uuid.uuid4().hex
return password, "%s|%s|||" % (a.username, password)
self._test_file_auth("multifile", genfiledata)
def main():
import logging
from xpra.log import set_default_level
if "-v" in sys.argv:
set_default_level(logging.DEBUG)
else:
set_default_level(logging.CRITICAL)
try:
from xpra.server import auth
assert auth
except ImportError as e:
print("non server build, skipping auth module test: %s" % e)
return
unittest.main()
if __name__ == '__main__':
main() |
class User < ApplicationRecord
validates :username, :session_token, presence: true, uniqueness: true
validates :password_digest, presence: true
validates :password, length: {minimum: 6}, allow_nil: true
attr_reader :password
before_validation :ensure_session_token
def self.find_by_credentials(username, password)
@user = User.find_by(username: username)
if @user && @user.is_password?(password)
@user
else
nil
end
end
def is_password?(password)
BCrypt::Password.new(password_digest).is_password?(password)
end
def password=(password)
@password = password
self.password_digest = BCrypt::Password.create(password)
end
def reset_session_token!
self.session_token = generate_unique_session_token
self.save!
self.session_token
end
private
def ensure_session_token
self.session_token ||= generate_unique_session_token
end
def generate_unique_session_token
token = SecureRandom::urlsafe_base64
while User.exists?(session_token: token)
token = SecureRandom::urlsafe_base64
end
token
end
end |
#include "gradient_volume.h"
#include <algorithm>
#include <exception>
#include <glm/geometric.hpp>
#include <glm/vector_relational.hpp>
#include <gsl/span>
namespace volume {
// Compute the maximum magnitude from all gradient voxels
static float computeMaxMagnitude(gsl::span<const GradientVoxel> data)
{
return std::max_element(
std::begin(data),
std::end(data),
[](const GradientVoxel& lhs, const GradientVoxel& rhs) {
return lhs.magnitude < rhs.magnitude;
})
->magnitude;
}
// Compute the minimum magnitude from all gradient voxels
static float computeMinMagnitude(gsl::span<const GradientVoxel> data)
{
return std::min_element(
std::begin(data),
std::end(data),
[](const GradientVoxel& lhs, const GradientVoxel& rhs) {
return lhs.magnitude < rhs.magnitude;
})
->magnitude;
}
// Compute a gradient volume from a volume
static std::vector<GradientVoxel> computeGradientVolume(const Volume& volume)
{
const auto dim = volume.dims();
std::vector<GradientVoxel> out(static_cast<size_t>(dim.x * dim.y * dim.z));
for (int z = 1; z < dim.z - 1; z++) {
for (int y = 1; y < dim.y - 1; y++) {
for (int x = 1; x < dim.x - 1; x++) {
const float gx = (volume.getVoxel(x + 1, y, z) - volume.getVoxel(x - 1, y, z)) / 2.0f;
const float gy = (volume.getVoxel(x, y + 1, z) - volume.getVoxel(x, y - 1, z)) / 2.0f;
const float gz = (volume.getVoxel(x, y, z + 1) - volume.getVoxel(x, y, z - 1)) / 2.0f;
const glm::vec3 v { gx, gy, gz };
const size_t index = static_cast<size_t>(x + dim.x * (y + dim.y * z));
out[index] = GradientVoxel { v, glm::length(v) };
}
}
}
return out;
}
GradientVolume::GradientVolume(const Volume& volume)
: m_dim(volume.dims())
, m_data(computeGradientVolume(volume))
, m_minMagnitude(computeMinMagnitude(m_data))
, m_maxMagnitude(computeMaxMagnitude(m_data))
{
}
float GradientVolume::maxMagnitude() const
{
return m_maxMagnitude;
}
float GradientVolume::minMagnitude() const
{
return m_minMagnitude;
}
glm::ivec3 GradientVolume::dims() const
{
return m_dim;
}
// This function returns a gradientVoxel at coord based on the current interpolation mode.
GradientVoxel GradientVolume::getGradientInterpolate(const glm::vec3& coord) const
{
switch (interpolationMode) {
case InterpolationMode::NearestNeighbour: {
return getGradientNearestNeighbor(coord);
}
case InterpolationMode::Linear: {
return getGradientLinearInterpolate(coord);
}
case InterpolationMode::Cubic: {
// No cubic in this case, linear is good enough for the gradient.
return getGradientLinearInterpolate(coord);
}
default: {
throw std::exception();
}
};
}
// This function returns the nearest neighbour given a position in the volume given by coord.
// Notice that in this framework we assume that the distance between neighbouring voxels is 1 in all directions
GradientVoxel GradientVolume::getGradientNearestNeighbor(const glm::vec3& coord) const
{
if (glm::any(glm::lessThan(coord, glm::vec3(0))) || glm::any(glm::greaterThanEqual(coord, glm::vec3(m_dim))))
return { glm::vec3(0.0f), 0.0f };
auto roundToPositiveInt = [](float f) {
return static_cast<int>(f + 0.5f);
};
return getGradient(roundToPositiveInt(coord.x), roundToPositiveInt(coord.y), roundToPositiveInt(coord.z));
}
// ======= TODO : IMPLEMENT ========
// Returns the trilinearly interpolated gradinet at the given coordinate.
// Use the linearInterpolate function that you implemented below.
GradientVoxel GradientVolume::getGradientLinearInterpolate(const glm::vec3& coord) const
{
if (glm::any(glm::lessThan(coord, glm::vec3(0))) || glm::any(glm::greaterThanEqual(coord, glm::vec3(m_dim-1))))
return { glm::vec3(0.0f), 0.0f };
// precalculate floor points
int floorX = floor(coord.x);
int floorY = floor(coord.y);
int floorZ = floor(coord.z);
// precalculate distances
float diffx = coord.x - floorX;
float diffy = coord.y - floorY;
float diffz = coord.z - floorZ;
// Get surrounding 8 neighbors
GradientVoxel c000 = getGradient(floorX, floorY, floorZ);
GradientVoxel c001 = getGradient(floorX, floorY, floorZ + 1);
GradientVoxel c010 = getGradient(floorX, floorY + 1, floorZ);
GradientVoxel c011 = getGradient(floorX, floorY + 1, floorZ + 1);
GradientVoxel c100 = getGradient(floorX + 1, floorY, floorZ);
GradientVoxel c101 = getGradient(floorX + 1, floorY, floorZ + 1);
GradientVoxel c110 = getGradient(floorX + 1, floorY + 1, floorZ);
GradientVoxel c111 = getGradient(floorX + 1, floorY + 1, floorZ + 1);
// Interpolate over z
GradientVoxel c00 = linearInterpolate(c000, c001, diffz);
GradientVoxel c01 = linearInterpolate(c010, c011, diffz);
GradientVoxel c10 = linearInterpolate(c100, c101, diffz);
GradientVoxel c11 = linearInterpolate(c110, c111, diffz);
// Interpolate over y
GradientVoxel c0 = linearInterpolate(c00, c01, diffy);
GradientVoxel c1 = linearInterpolate(c10, c11, diffy);
// Interpolate over x
GradientVoxel output = linearInterpolate(c0, c1, diffx);
return output;
}
// ======= TODO : IMPLEMENT ========
// This function should linearly interpolates the value from g0 to g1 given the factor (t).
// At t=0, linearInterpolate should return g0 and at t=1 it returns g1.
GradientVoxel GradientVolume::linearInterpolate(const GradientVoxel& g0, const GradientVoxel& g1, float factor)
{
GradientVoxel interpolated_G = { glm::vec3(0.0f), 0.0f };
interpolated_G.dir = g0.dir * (1 - factor) + g1.dir * factor;
interpolated_G.magnitude = g0.magnitude * (1 - factor) + g1.magnitude * factor;
return interpolated_G;
}
// This function returns a gradientVoxel without using interpolation
GradientVoxel GradientVolume::getGradient(int x, int y, int z) const
{
const size_t i = static_cast<size_t>(x + m_dim.x * (y + m_dim.y * z));
return m_data[i];
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.