text
stringlengths 184
4.48M
|
---|
import React, { useState } from "react";
import {
MDBContainer,
MDBBtn,
MDBModal,
MDBModalBody,
MDBModalHeader,
MDBModalFooter,
} from "mdbreact";
export default function EditUserModal({ open, toggle, user }) {
const [userData, setUserData] = useState({
name: undefined,
email: undefined,
password: undefined,
});
const handleChange = (event) => {
event.preventDefault();
setUserData({
...userData,
[event.target.id]: event.target.value,
});
};
const handleAdd = (event) => {
event.preventDefault();
const updatedObject = {
name: undefined,
email: undefined,
password: undefined,
};
Object.keys(userData).forEach((key) => {
if (userData[key] && userData[key] !== user[key]) {
updatedObject[key] = userData[key];
} else {
updatedObject[key] = user[key];
}
});
fetch(`http://localhost:8080/v1/api/user/${user.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updatedObject),
})
.then((response) => {
if (response && response.status === 200) {
return response.text();
} else {
console.error("Error at updating user");
return "Error";
}
})
.then((data) => {
console.log(data);
toggle();
})
.catch((err) => console.error(err));
};
return (
<MDBContainer>
<MDBModal isOpen={open} toggle={toggle}>
<MDBModalHeader toggle={toggle}>Edit User Info</MDBModalHeader>
<MDBModalBody>
<div className="form-group" onChange={handleChange}>
<label htmlFor="formGroupExampleInput">Name</label>
<input type="text" className="form-control" id="name" />
<label htmlFor="formGroupExampleInput">Email</label>
<input type="text" className="form-control" id="email" />
<label htmlFor="formGroupExampleInput">Password</label>
<input type="text" className="form-control" id="password" />
</div>
</MDBModalBody>
<MDBModalFooter>
<MDBBtn color="secondary" onClick={toggle}>
Close
</MDBBtn>
<MDBBtn color="primary" onClick={handleAdd}>
Submit
</MDBBtn>
</MDBModalFooter>
</MDBModal>
</MDBContainer>
);
}
|
//Abstract class cannot be instantiated but can be inherited
abstract class Animal{
name: string;
constructor(theName:string) {
this.name=theName;
}
walk(dist:number)
{
console.log(`It can walk ${dist} meter.`)
}
}
// let ani=new Animal("Rob");
class Cat extends Animal{
constructor(theName:string) {
super(theName);
}
walk(dist:Number)//Overriding
{
console.log(`${this.name} can't walk much coz she is a cat`);
}
}
let cat = new Cat("ruby");
cat.walk(2);
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('product_categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('parent_id')->default(0)->nullable();
$table->integer('lft')->unsigned()->nullable();
$table->integer('rgt')->unsigned()->nullable();
$table->integer('depth')->unsigned()->nullable();
$table->string('name');
$table->string('slug')->unique();
$table->string('meta_title')->nullable();
$table->string('meta_keyword')->nullable();
$table->string('meta_description')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('product_categories');
}
}
|
//
// AddAreaController.swift
// Area
//
// Created by xuhui on 2018/6/14.
// Copyright © 2018年 xuhui. All rights reserved.
//
import UIKit
import CoreData
class AddAreaController: UITableViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var area: AreaMO!
var isVisited = false
@IBOutlet weak var tfName: UITextField!
@IBOutlet weak var tfProvince: UITextField!
@IBOutlet weak var tfPart: UITextField!
@IBOutlet weak var labelVisited: UILabel!
@IBOutlet weak var coverImageView: UIImageView!
@IBAction func saveTap(_ sender: Any) {
//获取appDelegate,强制转换成工程的AppDelegate,可获得对它的引用
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//可以获得CoreData持久化容器中的Context
area = AreaMO(context: appDelegate.persistentContainer.viewContext)
//设置相关的值
area.name = tfName.text
area.province = tfProvince.text
area.part = tfPart.text
area.isVisited = isVisited
//把图像转换为JPEG格式,0.7是图片的清晰度
if let imageData = UIImageJPEGRepresentation(coverImageView.image!, 0.7) {
area.image = NSData(data: imageData)
}
print("正在保存...")
//保存数据
appDelegate.saveContext()
//退出,返回到首页
performSegue(withIdentifier: "unwindToHomeList", sender: self)
}
@IBAction func isVisited(_ sender: UIButton) {
if sender.tag == 8001 {
isVisited = true
labelVisited.text = "我来过"
} else {
isVisited = false
labelVisited.text = "没去过"
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//给出选中的图片类型
coverImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
//设定图片的排列模式
coverImageView.contentMode = .scaleAspectFill
//裁边
coverImageView.clipsToBounds = true
//设置与父视图等宽的约束
//constant是关于距离的约束,所以设为0
let coverWithCons = NSLayoutConstraint(item: coverImageView, attribute: .width, relatedBy: .equal, toItem: coverImageView.superview, attribute: .width, multiplier: 1, constant: 0)
//设置与父视图等高的约束
let coverHeightCons = NSLayoutConstraint(item: coverImageView, attribute: .height, relatedBy: .equal, toItem: coverImageView.superview, attribute: .height, multiplier: 1, constant: 0)
//让两个约束生效
coverWithCons.isActive = true
coverHeightCons.isActive = true
//视图退场
dismiss(animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0{
//通过guard判定访问相册的权限是否可用,如果不可用,返回
guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else {
print("相册不可用")
return
}
//实例化UIImagePickerController
let picker = UIImagePickerController()
//不允许编辑
picker.allowsEditing = false
//来源为相册
picker.sourceType = .photoLibrary
//设置代理为当前控制器
picker.delegate = self
//以模态弹出
self.present(picker,animated: true,completion: nil)
}
//单元格取消选择
tableView.deselectRow(at: indexPath, animated: true)
}
}
|
class StripeCustomer
DEFAULT_COUNTRY = 'US'
def initialize(user)
@user = user
end
def self.fill_client_info(client)
stripe_customer = new(client)
stripe_customer.register if client.stripe_customer_id.blank?
end
def self.create_card_attributes(credit_card_attributes)
{ number: credit_card_attributes[:number],
exp_month: credit_card_attributes[:ex_month],
exp_year: credit_card_attributes[:ex_year],
cvc: credit_card_attributes[:cvc],
name: credit_card_attributes[:name_on_card],
address_line1: credit_card_attributes[:address],
address_city: credit_card_attributes[:city],
address_state: credit_card_attributes[:state],
address_zip: credit_card_attributes[:zip],
address_country: DEFAULT_COUNTRY
}
end
def self.update_card_attributes(card)
{ exp_month: card.ex_month,
exp_year: card.ex_year,
name: card.name_on_card,
address_line1: card.address,
address_city: card.city,
address_state: card.state,
address_zip: card.zip,
address_country: DEFAULT_COUNTRY
}
end
def register
customer = Stripe::Customer.create(
email: user.email,
description: user.name,
metadata: { role: user.role, user_id: user.id, name: user.name }
)
ActiveRecord::Base.transaction do
user.update_attributes!(stripe_customer_id: customer.id)
end
end
def stripe_customer
raise('The user has no Stripe customer id') unless user.stripe_customer_id
@stripe_customer ||= Stripe::Customer.retrieve(user.stripe_customer_id)
end
def import_card(credit_card_attributes)
StripeCustomer.fill_client_info(user)
card_options = StripeCustomer.create_card_attributes(credit_card_attributes)
add_card(card_options)
end
def add_card(card_options_or_token)
card = stripe_customer.sources.create({ source: card_options_or_token.merge(object: 'card') })
card
end
def cards
stripe_customer.sources.all(limit: 100, object: 'card')
end
def default_card
data = cards.data
data.last
end
def charge(options)
money = options[:money]
Stripe::Charge.create(
amount: money.cents,
currency: money.currency,
customer: stripe_customer.id,
source: options[:card_id],
description: options[:description]
)
end
def update_card(credit_card)
card = stripe_customer.sources.retrieve(credit_card.stripe_id)
attributes = StripeCustomer.update_card_attributes(credit_card)
attributes.each { |key, value| card.send("#{ key }=", value) }
card.save
end
def delete_card(credit_card)
stripe_customer.sources.retrieve(credit_card.stripe_id).delete if credit_card.stripe_id
end
def set_default(credit_card)
stripe_customer.default_card = credit_card.stripe_id
stripe_customer.save
end
private
attr_reader :user
end
|
import { useContext } from "react"
import Card from "../Card/Card.jsx"
import CurrentUserContext from "../../contexts/CurrentUserContext"
import Spinner from "../Spinner/Spinner.jsx"
export default function Main({ name, onEditProfile, onEditAvatar, onAddPlace, onCardClick, onDelete, cards, isLoadingCard, handleRegister, handleLogin }) {
const currentUser = useContext(CurrentUserContext)
return (
<main className="content">
<section className="profile">
<button type="button" className="profile__avatar-overlay" onClick={onEditAvatar} >
<img src={currentUser.avatar ? currentUser.avatar : '#'} alt="Аватар" className="profile__avatar" />
</button>
<div className="profile__info">
<h1 className="profile__title" > {currentUser.name ? currentUser.name : '#'}</h1>
<button className="profile__edit-button" type="button" onClick={onEditProfile} />
<p className="profile__subtitle" >{currentUser.about ? currentUser.about : '#'}</p>
</div>
<button className="profile__add-button" type="button" onClick={onAddPlace} />
</section>
<section className="elements-container">
{isLoadingCard ? <div className="elements-spinner"><Spinner /></div> : cards.map(data => {
return (
<Card card={data} onCardClick={onCardClick} key={data._id} onDelete={onDelete} />
)
})}
</section>
</main>
)
}
|
/**************
* Modelos
*************/
const fs = require('fs');
const axios = require('axios');
// Nota: Las clases se escriben UpperCalmeCase
class Busquedas {
historial = [];
dbPath = './db/database.json';
constructor() {
// leer BD si existe
this.leerDB();
}
get historialCapitalizado() {
//capitalizar cada palabra
return this.historial.map((lugar) => {
let palabras = lugar.split(' ');
palabras = palabras.map((p) => p[0].toUpperCase() + p.substring(1));
return palabras.join(' ');
});
}
// Metodos
// los params del endoint MAPBOX
get paramsMapbox() {
return {
limit: 5,
language: 'es',
// El MAPBOX_KEY es la variable de entorno, en el archivo .env (que no se subió el repo) sin embargo lo puedes detallar en el archivo VE.txt
access_token: process.env.MAPBOX_KEY,
};
}
// Params del endpoint OPENWEATHER
get paramsOperWeather() {
return {
appid: process.env.OPENWEATHER_KEY,
units: 'metric',
lang: 'es',
};
}
async ciudad(lugar = '') {
//petición http
// console.log('ciudad:', lugar);
try {
const intance = axios.create({
baseURL: `https://api.mapbox.com/geocoding/v5/mapbox.places/${lugar}.json`,
params: this.paramsMapbox,
});
const resp = await intance.get();
// console.log(resp.data.features);
return resp.data.features.map((lugar) => ({
id: lugar.id,
nombre: lugar.place_name,
lng: lugar.center[0],
lat: lugar.center[1],
}));
} catch (error) {
console.log(error.code);
}
}
async climaLugar(lat, lon) {
try {
// instance axios.create()
const intance = await axios.create({
baseURL: `https://api.openweathermap.org/data/2.5/weather`,
params: { ...this.paramsOperWeather, lat, lon },
});
const resp = await intance.get();
const { weather, main } = resp.data;
return {
desc: weather[0].description,
min: main.temp_min,
max: main.temp_max,
temp: main.temp,
};
} catch (error) {
console.log(error);
}
}
agregarHistorial(lugar = '') {
// Prevenir duplicados
if (this.historial.includes(lugar.toLocaleLowerCase())) {
return;
}
// Mantiene el arreglo del historial con 10 elementos, para no mantenerlo infinito
this.historial = this.historial.splice(0, 9);
this.historial.unshift(lugar.toLocaleLowerCase());
//Grabar en BD
this.guardarDB();
}
guardarDB() {
const payload = {
historial: this.historial,
};
fs.writeFileSync(this.dbPath, JSON.stringify(payload));
}
leerDB() {
if (!fs.existsSync(this.dbPath)) return;
const info = fs.readFileSync(this.dbPath, { encoding: 'utf-8' });
const data = JSON.parse(info);
this.historial = data.historial;
}
}
module.exports = Busquedas;
|
<?php
session_start();
$different = "";
// Récupérer les données soumises
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(
isset($_POST['csrf_token']) &&
isset($_SESSION['csrf_token']) &&
$_SESSION['csrf_token'] === $_POST['csrf_token'] &&
isset($_POST['nom']) &&
isset($_POST['prenom']) &&
isset($_POST['email']) &&
isset($_POST['password']) &&
isset($_POST['password_repeat'])
) {
$prenom = $_POST["prenom"];
$nom = $_POST["nom"];
$email = $_POST["email"];
$password = $_POST["password"];
$password_repeat = $_POST["password_repeat"];
$sel = bin2hex(random_bytes(16)); // Générez un sel aléatoire sécurisé (16 octets ici)
if($password === $password_repeat){
try{
// Établir une connexion à la base de données avec PDO
$servername = "mysql:host=mysql";
$username = getenv("MYSQL_USER");
$password_db = getenv("MYSQL_PASSWORD");
$dbname = getenv("MYSQL_DATABASE");
$conn = new PDO("$servername;dbname=$dbname;charset=utf8", $username, $password_db);
// Définir le mode d'erreur PDO sur exception (sert à gérer les erreurs plus facilement)
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Préparer une requête SQL pour insérer les données
$sql = "INSERT INTO utilisateurs (prenom, nom, email, mot_de_passe, sel) values (:prenom, :nom, :email, :mot_de_passe, :sel)";
$stmt = $conn->prepare($sql);
// Hacher le mot de passe avant de l'insérer dans la base de données (pour des raisons de sécurité)
$hashed_password = password_hash($password . $sel, PASSWORD_DEFAULT);
// Lier les paramètres et exécuter la requête
$stmt->bindParam(':prenom', $prenom, PDO::PARAM_STR);
$stmt->bindParam(':nom', $nom, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':mot_de_passe', $hashed_password, PDO::PARAM_STR);
$stmt->bindParam(':sel', $sel, PDO::PARAM_STR);
$stmt->execute();
header('Location: index.php');
exit();
} catch (PDOExeption $e) {
echo "Erreur dans l'inscription des données : " . $e->getMessage();
}
//Fermer la connection à la base de données
$conn = null;
} else {
$different = "error";
}
} else {
echo 'CSRF error';
}
}
$csrf_token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $csrf_token;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Formulaire d'Inscription</title>
<!-- Inclure les styles Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h2>Formulaire d'Inscription</h2>
<?php
if($different === "error" ){
echo "<div class='alert alert-danger' role='alert'>
Les mots de passe ne correspondent pas.
</div>";
}
?>
<form action="" method="POST">
<!-- Champ : Prénom -->
<div class="form-group">
<label for="prenom">Prénom</label>
<input type="text" class="form-control" id="prenom" name="prenom" required>
</div>
<!-- Champ : Nom -->
<div class="form-group">
<label for="nom">Nom</label>
<input type="text" class="form-control" id="nom" name="nom" required>
</div>
<!-- Champ : Adresse e-mail -->
<div class="form-group">
<label for="email">Adresse e-mail</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<!-- Champ : Mot de passe -->
<div class="form-group">
<label for="password">Mot de passe</label>
<input type="password" class="form-control" id="password" name="password" placeholder="" required>
</div>
<!-- Champ : Répéter le mot de passe -->
<div class="form-group">
<label for="password_repeat">Répéter le mot de passe</label>
<input type="password" class="form-control" id="password_repeat" name="password_repeat" required>
</div>
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
<!-- Bouton d'envoi -->
<button type="submit" class="btn btn-primary">S'inscrire</button>
</form>
</div>
<!-- Inclure les scripts Bootstrap -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
|
'use client';
import { useMemo, useEffect, useState } from 'react';
import Link from 'next/link';
import {
MaterialReactTable,
useMaterialReactTable,
MRT_ShowHideColumnsButton,
MRT_ToggleFullScreenButton,
MRT_ToggleGlobalFilterButton,
MRT_ToggleDensePaddingButton,
MRT_ToggleFiltersButton,
type MRT_ColumnDef,
} from 'material-react-table';
import { Link as MuiLink, Box } from '@mui/material/';
import SiteStatusBadge from './SiteStatusBadge';
import InsertLinkIcon from '@mui/icons-material/InsertLink';
import AddCircleIcon from '@mui/icons-material/AddCircle';
import { Typography, IconButton, Tooltip, Alert } from '@mui/material';
import IconTT from '@/app/icons/IconTT';
import { PrintSharp } from '@mui/icons-material';
import LinkOffIcon from '@mui/icons-material/LinkOff';
//If using TypeScript, define the shape of your data (optional, but recommended)
interface Site {
id: number;
startDate: Date;
streetNumberName: string;
cityTown: string;
province: string;
locID: string;
estHours: number;
schedulerURL: string;
clName: string;
clCompany: string;
status: boolean;
}
const SitesTable = () => {
const [data, setData] = useState([]);
const [isLoading, setLoading] = useState(true);
const [isError, setError] = useState(false);
useEffect(() => {
fetch('/api/sites')
.then((res) => res.json())
.then((data) => {
setData(data);
setLoading(false);
});
}, []);
const columns = useMemo<MRT_ColumnDef<Site>[]>(
() => [
{
accessorFn: (row) =>
`${row.streetNumberName}, ${row.cityTown}, ${row.province}`,
id: 'address',
header: 'Address',
Cell: ({ cell, row }) => (
<Link href={`/sites/${row.original.id}`} passHref>
<MuiLink
sx={{ fontWeight: 600, textDecoration: 'none' }}
underline="none"
component="button"
>
{row.original.streetNumberName}, {row.original.cityTown},{' '}
{row.original.province}
</MuiLink>
</Link>
),
},
{
accessorKey: 'clName',
header: 'Client',
},
{
accessorFn: (row) =>
`${row.clCompany} ${row.locID ? ' - ' + row.locID : ''}`,
id: 'clCompany',
header: 'Company',
},
{
accessorFn: (row) => new Date(row.startDate), //convert to Date for sorting and filtering
id: 'startDate',
header: 'Start Date',
sortingFn: 'datetime',
enableColumnFilter: false,
Cell: ({ cell }) => cell.getValue<Date>()?.toJSON().slice(0, 10),
maxSize: 100,
},
{
accessorKey: 'estHours',
header: 'Est Hrs',
enableColumnFilter: false,
maxSize: 100,
},
{
accessorFn: (row) => `${row.schedulerURL}`,
Header: () => <IconTT fSize="small" bgFill="#c23138" />,
header: 'Tracktik',
enableColumnFilter: false,
enableSorting: false,
Cell: ({ row }) => (
<div>
{row.original.schedulerURL ? (
<Link target="_blank" href={row.original.schedulerURL} passHref>
<MuiLink component="button">
<InsertLinkIcon />
</MuiLink>
</Link>
) : (
<LinkOffIcon />
)}
</div>
),
maxSize: 75,
},
{
header: 'Status',
accessorKey: 'status',
accessorFn: (originalRow) => (originalRow.status ? 'true' : 'false'), //must be strings
id: 'status',
filterVariant: 'checkbox',
// muiFilterCheckboxProps: {
// defaultChecked: true,
// },
Cell: ({ cell, row }) => (
<SiteStatusBadge status={row.original.status} />
),
maxSize: 125,
},
],
[]
);
const table = useMaterialReactTable({
columns,
data,
muiPaginationProps: {
rowsPerPageOptions: [25, 50, 75, 100],
},
renderTopToolbarCustomActions: () => (
<Typography variant="h6">Sites</Typography>
),
renderToolbarInternalActions: ({ table }) => (
<>
{/* add your own custom print button or something */}
<MRT_ToggleGlobalFilterButton table={table} />
<MRT_ToggleDensePaddingButton table={table} />
<MRT_ToggleFiltersButton table={table} />
<MRT_ShowHideColumnsButton table={table} />
<MRT_ToggleFullScreenButton table={table} />
<Tooltip title="Print">
<IconButton onClick={() => window.print()}>
<PrintSharp />
</IconButton>
</Tooltip>
<Tooltip title="Add New Site">
<Link href="/sites/new">
<IconButton>
<AddCircleIcon />
</IconButton>
</Link>
</Tooltip>
</>
),
initialState: {
showColumnFilters: false,
columnFilters: [{ id: 'status', value: true }],
sorting: [{ id: 'clCompany', desc: false }],
pagination: { pageIndex: 0, pageSize: 50 },
density: 'compact',
expanded: true,
},
});
if (isLoading) return <p>Loading...</p>;
if (!data) setError(true);
return (
<>
{isError && (
<Alert
severity="error"
sx={{ mb: 2 }}
onClose={() => {
setError(false);
}}
variant="outlined"
>
There are issues reaching the database. Please try again.
</Alert>
)}
<MaterialReactTable table={table} />
</>
);
};
export default SitesTable;
|
import { useState } from 'react';
import {
Card,
CardContent,
Checkbox,
Grid,
Typography,
FormControlLabel,
ListItemText,
} from '@mui/material';
import data from './tasks.data.json';
import './home.css';
import { StyledBox } from './index.css';
import Header from '../../components/header/Header';
import dayjs from 'dayjs';
export interface Task {
id: number;
title: string;
description: string;
clientNumber: string;
carName: string;
done: boolean;
}
const HomePage = () => {
const [tasks, setTasks] = useState<Task[]>(data);
const handleTaskToggle = (taskId: number) => {
const updatedTasks = tasks.map((task) =>
task.id === taskId ? { ...task, done: !task.done } : task
);
setTasks(updatedTasks);
};
const tasksToShow = tasks.filter((task) => !task.done);
return (
<StyledBox>
<Header title={`Zgłoszenia na dzień ${dayjs().format('DD.MM.YYYY')}`} />
<Grid container spacing={2} marginTop={2} className="task-list-container">
{tasksToShow.map((task) => (
<Card
key={task.id}
variant="outlined"
className={`task-card ${task.done ? 'task-card-done' : ''}`}
onMouseEnter={() => {
if (!task.done) {
const card = document.getElementById(`task-card-${task.id}`);
if (card) {
card.classList.add('task-card-hovered');
}
}
}}
onMouseLeave={() => {
if (!task.done) {
const card = document.getElementById(`task-card-${task.id}`);
if (card) {
card.classList.remove('task-card-hovered');
}
}
}}
>
<CardContent style={{ display: 'flex', flexDirection: 'column' }}>
<ListItemText>
<Typography
variant="body1"
style={{
textDecoration: task.done ? 'line-through' : 'none',
}}
>
<b>{task.title}</b>
</Typography>
<Typography variant="body2">{task.description}</Typography>
</ListItemText>
<div style={{ marginTop: 'auto', marginLeft: 'auto' }}>
<FormControlLabel
sx={{ pointerEvents: 'none' }}
control={
<Checkbox
sx={{ pointerEvents: 'auto' }}
checked={task.done}
onChange={() => handleTaskToggle(task.id)}
color="primary"
/>
}
label="Zakończ"
labelPlacement="start"
/>
</div>
</CardContent>
</Card>
))}
</Grid>
</StyledBox>
);
};
export default HomePage;
|
#include "Transform.hpp"
#include "stats.hpp"
// CoordSystem
CoordSystem* cs::coordSystem;
CoordSystem::CoordSystem(float originX, float originY) {
this->originX = originX;
this->originY = originY;
calculatePixelSize(WIDTH, HEIGHT);
}
void CoordSystem::calculatePixelSize(int width, int height) {
pixelWidth = 1.0f / (width / 2);
pixelHeight = 1.0f / (height / 2);
}
void CoordSystem::translateOrigin(float x, float y) {
originX += x;
originY += y;
}
float CoordSystem::getPixelWidth() {
return pixelWidth;
}
float CoordSystem::getPixelHeight() {
return pixelHeight;
}
float CoordSystem::getOriginX() {
return originX;
}
float CoordSystem::getOriginY() {
return originY;
}
// Shape
Shape::Shape(Mesh* mesh) {
this->mesh = mesh;
}
void Shape::draw() {
mesh->draw();
}
void Shape::setRed(float red) {
mesh->color.r = red / 255.0f;
}
void Shape::setGreen(float green) {
mesh->color.g = green / 255.0f;
}
void Shape::setBlue(float blue) {
mesh->color.b = blue / 255.0f;
}
void Shape::setAlpha(float alpha) {
mesh->color.a = alpha / 255.0f;
}
void Shape::changeRed(float delta) {
mesh->color.r += delta / 255.0f;
}
void Shape::cangeGreen(float delta) {
mesh->color.g += delta / 255.0f;
}
void Shape::changeBlue(float delta) {
mesh->color.b += delta / 255.0f;
}
void Shape::changeAlpha(float delta) {
mesh->color.a += delta / 255.0f;
}
void Shape::changeColor(float deltaRed, float deltaGreen, float deltaBlue, float deltaAlpha) {
mesh->color.r += deltaRed / 255.0f;
mesh->color.g += deltaGreen / 255.0f;
mesh->color.b += deltaBlue / 255.0f;
mesh->color.a += deltaAlpha / 255.0f;
}
void Shape::setColor(float red, float green, float blue, float alpha) {
mesh->color.r = red / 255.0f;
mesh->color.g = green / 255.0f;
mesh->color.b = blue / 255.0f;
mesh->color.a = alpha / 255.0f;
}
float Shape::getRed() {
return mesh->color.r * 255.0f;
}
float Shape::getGreen() {
return mesh->color.g * 255.0f;
}
float Shape::getBlue() {
return mesh->color.b * 255.0f;
}
float Shape::getAlpha() {
return mesh->color.a * 255.0f;
}
void Shape::setX(float x) {
float originX = cs::coordSystem->getOriginX() * cs::coordSystem->getPixelWidth();
float posX = cs::coordSystem->getPixelWidth() * x;
float xOffset = mesh->scale.x / 2.0f;
mesh->position.x = posX + xOffset + originX;
}
void Shape::setY(float y) {
float originY = -cs::coordSystem->getOriginY() * cs::coordSystem->getPixelHeight();
float posY = -cs::coordSystem->getPixelHeight() * y;
float yOffset = -mesh->scale.y / 2.0f;
mesh->position.y = posY + yOffset + originY;
}
void Shape::translateX(float delta) {
mesh->position.x += cs::coordSystem->getPixelWidth() * delta;
}
void Shape::translateY(float delta) {
mesh->position.y += cs::coordSystem->getPixelHeight() * delta;
}
void Shape::translate(float deltaX, float deltaY) {
mesh->position.x += cs::coordSystem->getPixelWidth() * deltaX;
mesh->position.y += cs::coordSystem->getPixelHeight() * deltaY;
}
void Shape::setPosition(float x, float y) {
float originX = cs::coordSystem->getOriginX() * cs::coordSystem->getPixelWidth();
float posX = cs::coordSystem->getPixelWidth() * x;
float xOffset = mesh->scale.x / 2.0f;
mesh->position.x = posX + xOffset + originX;
float originY = -cs::coordSystem->getOriginY() * cs::coordSystem->getPixelHeight();
float posY = -cs::coordSystem->getPixelHeight() * y;
float yOffset = -mesh->scale.y / 2.0f;
mesh->position.y = posY + yOffset + originY;
}
float Shape::getX() {
float result = mesh->position.x;
result -= cs::coordSystem->getOriginX() * cs::coordSystem->getPixelWidth();
result -= mesh->scale.x / 2.0f;
result /= cs::coordSystem->getPixelWidth();
return result;
}
float Shape::getY() {
float result = mesh->position.y;
result += cs::coordSystem->getOriginY() * cs::coordSystem->getPixelHeight();
result += mesh->scale.y / 2.0f;
result /= -cs::coordSystem->getPixelHeight();
return result;
}
void Shape::setWidth(float width) {
mesh->scale.x = cs::coordSystem->getPixelWidth() * width;
}
void Shape::setHeigth(float height) {
mesh->scale.y = cs::coordSystem->getPixelHeight() * height;
}
void Shape::changeWidth(float delta) {
mesh->scale.x += cs::coordSystem->getPixelWidth() * delta;
}
void Shape::changeHeight(float delta) {
mesh->scale.y += cs::coordSystem->getPixelHeight() * delta;
}
void Shape::changeSize(float deltaWidth, float deltaHeight) {
mesh->scale.x += cs::coordSystem->getPixelWidth() * deltaWidth;
mesh->scale.y += cs::coordSystem->getPixelHeight() * deltaHeight;
}
void Shape::setSize(float width, float height) {
mesh->scale.x = cs::coordSystem->getPixelWidth() * width;
mesh->scale.y = cs::coordSystem->getPixelHeight() * height;
}
void Shape::scale(float value) {
mesh->scale.x *= value;
mesh->scale.y *= value;
}
float Shape::getWidth() {
return mesh->scale.x / cs::coordSystem->getPixelWidth();
}
float Shape::getHeight() {
return mesh->scale.y / cs::coordSystem->getPixelHeight();
}
void Shape::rotate(float delta) {
mesh->angle += delta;
}
void Shape::setAngle(float angle) {
mesh->angle = angle;
}
float Shape::getAngle() {
return mesh->angle;
}
void Shape::setColorMode(ColorMode mode) {
mesh->mode = mode;
}
ColorMode Shape::getColorMode() {
return mesh->mode;
}
void Shape::addTexture(unsigned int textureID) {
if (mesh->textures.size() < 1) {
mesh->textures.push_back(textureID);
}
}
void Shape::removeTexture(unsigned int textureID) {
for (int i = 0; i < mesh->textures.size(); i++) {
if (mesh->textures.at(i) == textureID) {
auto it = mesh->textures.begin() + i;
mesh->textures.erase(it);
break;
}
}
}
|
---
title: Especificación de Algorimos y TADs
description: >
TODO
date: 2023-07-08T01:08:45+02:00
weight: -1
math: true
draft: true
---
# Especificación de Algoritmos
Se trata de una descripción clara y precisa de
- las entradas del algoritmo,
- salidas y
- la reacción ante datos incorrectos
Un algoritmo que no esté claramente especificado se puede interpretar de varias
maneras, resultando en un algoritmo que no resuelve correctamente el problema.
De este modo, también se evitan chequeos innecesarios (programación defensiva),
que que las entradas cumplen las condiciones iniciales (programación por
contrato).
{{< block "Definición" "var(--magno-blue)" "black" >}}
- **Proposición**: aquella frase a la que se le peude atribuir un valor de
_Verdadero_ o _Falso_.
- **Operadores lógicos**: permiten crear proposiciones más complejas:
`AND`, `OR`, `NOT`, `==`, `!=`, `<`, `>`, `<=`, `>=`.
- **Predicados**: proposiciones con elementos nuevos, llamados cuantificadores.
- **Variables**: datos conocidos sobre el problema, datos de salida, datos de
entrada, etc.
{{< /block >}}
{{< keyvalue title="Predicados" >}}
-% $\exists i : \text{ dominio } : p(i)$ :% Existe al menos un $i$ en $\text{dominio}$ que cumple $p(i)$.
-% $\forall i : \text{ dominio } : p(i)$ :% Para todo valor de $i$ en $\text{dominio}$ se cumple $p(i)$.
-% $N i : \text{ dominio } : p(i)$ :% Número de valores de $i$ en $\text{dominio}$ que cumple $p(i)$.
{{< /keyvalue >}}
Con todo esto, un algoritmo se especifica de la siguiente forma:
$$ \Set{P} \\; A \\; \Set{Q} $$
- **Precondición** ($P$): predicado que define el estado inicial sobre los datos
de entrada.
- **Nombre del algoritmo** $A$.
- **Poscondición** ($Q$): predicado que define el estado final sobre los datos
de salida.
## Reglas de consecuencia
{{< block "Definición" "var(--magno-blue)" "black" >}}
$$ R \implies P \qquad R \subset P $$
- $R$ es **más fuerte** / **más restrictivo** que $P$
- $P$ es **menos fuerte** / **más débil** / ** menos restrictivo** que $R$
- Todo estado que cumple $R$, también cumple $P$.
{{< /block >}}
{{< block "Reglas de consecuencia" "var(--magno-red)" "black" >}}
- $ \Set{P} \\; A \\; \Set{Q} \quad$ y $\quad R \implies P, \quad$ entonces $\Set{R} \\; A \\; \Set{Q}$
- $ \Set{P} \\; A \\; \Set{Q} \quad$ y $\quad Q \implies T, \quad$ entonces $\Set{R} \\; A \\; \Set{T}$
{{< /block >}}
|
package oogasalad.model.gameobject;
import oogasalad.model.api.ReadOnlyGameTime;
/**
* Defines an entity within the game that can be updated over time. Implementing this interface
* allows an object to participate in the game's loop, responding to changes in the game state or
* the passage of time.
* <p>
* Entities implementing this interface typically represent dynamic aspects of the game, such as
* land, structures, or any interactive elements that change state or behavior over time.
*/
public interface Updatable {
/**
* Updates the state of the object based on the current game time. This method is intended to be
* called on each game loop iteration, allowing the object to perform time-sensitive actions, such
* as moving, reacting to game events, or updating internal state.
*
* @param gameTime The current game time, providing context for time-based updates.
*/
void update(ReadOnlyGameTime gameTime);
}
|
import { useState } from "react";
import ActionIcons from "../ActionIcons";
import DeleteModal from "../DeleteModal";
import { Link, router } from "@inertiajs/react";
import EditModal from "./EditModel";
import moment from "moment";
import { FaInfo, FaMusic } from "react-icons/fa";
export default function Table({ data }) {
const [deleteModal, setDeleteModal] = useState(false);
const [editModal, setEditModal] = useState(false);
const [album, setAlbum] = useState();
const toggleDeleteModal = () => {
setDeleteModal(!deleteModal);
};
const toggleEditModal = () => {
setEditModal(!editModal);
};
const deleteAlbum = () => {
router.delete(`album/${album.id}`);
toggleDeleteModal();
};
const thClx =
"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider";
const tdClx = "px-6 py-4 whitespace-nowrap";
return (
<>
<table className=" w-full divide-y divide-gray-200 shadow">
<thead className="bg-gray-50">
<tr>
<th className={thClx}>Name</th>
<th className={thClx}>Artist</th>
<th className={thClx}>url</th>
<th className={thClx}>Play count</th>
<th className={thClx}>Release date</th>
<th className={thClx}>Action </th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{data &&
data.map((record, index) => (
<tr key={index}>
<td className={tdClx}>{record.name}</td>
<td className={tdClx}>{record.artist}</td>
<td className={tdClx}>{record.url}</td>
<td className={tdClx}>{record.playCount}</td>
<td className={tdClx}>
{moment(record.published).format(
"MMMM Do YYYY, h:mm:ss a"
)}
</td>
<ActionIcons
onDelete={() => {
setAlbum(record);
toggleDeleteModal();
}}
onEdit={() => {
setAlbum(record);
toggleEditModal();
}}
detail={
<Link href={`/album/${record.id}`}>
<FaMusic
size={15}
color="slate-400"
/>
</Link>
}
/>
</tr>
))}
</tbody>
</table>
<DeleteModal
deleteModal={deleteModal}
toggleDeleteModal={toggleDeleteModal}
handleDelete={deleteAlbum}
/>
<EditModal
album={album}
show={editModal}
toggleShow={toggleEditModal}
/>
</>
);
}
|
---
title: Working with Metrics
chapter: true
weight: 80
---
# Working with Metrics
It's essential to understand the significance of metrics in monitoring and understanding system behavior. Metrics are quantitative measurements that provide valuable insights into the performance, health, and usage patterns of a system. They act as key observability signals, enabling us to track and analyze various aspects of system behavior over time.
Metrics offer a wealth of information, such as response times, throughput, error rates, and resource utilization. By collecting and analyzing metrics, we can gain a deeper understanding of system performance and identify potential bottlenecks, anomalies, or areas for optimization.
One of the key advantages of metrics is their ability to provide real-time or near-real-time visibility into system behavior. They allow us to set thresholds and alerting mechanisms, ensuring timely notifications when certain metrics exceed predefined limits. This proactive monitoring approach enables swift incident response, minimizing downtime and maximizing system availability.
Metrics also play a vital role in capacity planning and resource allocation. By analyzing historical metrics data, we can identify trends, forecast future resource needs, and make informed decisions about scaling resources to meet demand. This proactive approach helps optimize resource utilization, prevent performance degradation, and ensure a seamless user experience.
To leverage metrics effectively, it's crucial to define meaningful and relevant metrics that align with the desired observability goals. This involves understanding the system's critical components, user expectations, and key performance indicators. By selecting and tracking the right metrics, we can gain actionable insights and make data-driven decisions to improve system performance and reliability.
Furthermore, metrics are typically stored in time-series databases or monitoring platforms, which provide powerful visualization and querying capabilities. These tools enable us to create dashboards, charts, and reports to visualize the collected metrics and identify patterns or anomalies easily. Such visual representations enhance collaboration among teams, facilitate troubleshooting, and support data-driven discussions.''
## Learning Objectives
- Logz.io metrics solution overview
- Dashboard
- PromQL
- Basics
- Reference Material
- Deployment Markers
- Alerts
- High Level Overview
- components
- templates - (nice to have)
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Taller 2 Formularios HTML</title>
<style>
body {
background-image: url('img/fondo.jpg');
/* ruta imagen */
background-size: cover;
/* Ajusta el tamaño de la imagen al contenedor */
background-repeat: no-repeat;
/* Evita que la imagen se repita */
background-attachment: fixed;
/* Fija la imagen de fondo al desplazarse */
/* Otros estilos que desees aplicar al body */
font-family: 'Montserrat';
font-size: 18px;
}
button{
margin-left: 6.5%;
font-family: 'Montserrat';
font-size: 18px;
}
button:hover{
background-color: blueviolet;
}
form {
width: 70%;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
label {
font-weight: bold;
}
input[type="text"],
select,
input[type="date"] {
width: 90%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 3px;
}
input[type="radio"],
input[type="checkbox"] {
margin-right: 5px;
}
select[multiple] {
height: 80px;
}
input[type="submit"] {
background-color: #3498db;
color: white;
border: none;
padding: 10px 20px;
border-radius: 3px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #2980b9;
}
.arrow {
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-bottom: 40px solid red;
position: absolute;
left: 9.5%;
top: 10%;
animation: bounce 2s infinite;
transform: translateX(-50%) translateY(-50%);
}
@keyframes bounce {
0%, 100% {
transform: translateX(-50%) translateY(-50%);
}
50% {
transform: translateX(-50%) translateY(-50%) translateY(-10px);
}
}
</style>
</head>
<body>
<a href="index.html">
<button style="border: 5px solid rgb(128, 30, 0); width: 5% ;">Inicio</button>
</a>
<div style="border: 3px solid black; width: 50%; margin-left: 25%;">
<div
style="background-color: rgba(0, 0, 0, 0.877); color: white; display:flex;align-items:center;justify-content: center;flex-direction: column; margin: 3%;">
<img src="img/logo.png" alt="logo ucp" style="width: 30%;">
<h1 class="text-center">Taller Formularios HTML </h1>
<hr style="width: 90%;">
<form>
<p>Idioma:</p>
<input type="radio" name="idioma" value="idiomaingles" id="idiomaingles">
<label for="idiomaingles">Inglés</label><br>
<input type="radio" name="idioma" value="idiomaaleman" id="idiomaaleman">
<label for="idiomaaleman">Alemán</label><br>
<input type="radio" name="idioma" value="idiomafrances" id="idiomafrances">
<label for="idiomafrances">Francés</label><br>
<p>Tipo de conexión:</p>
<select name="conexion">
<option value="usb">USB</option>
<option value="paralelo">Paralelo</option>
<option value="ps2">PS2</option>
</select><br>
<p>Nombre:</p>
<input type="text" name="nombre"><br>
<p>Apellidos:</p>
<input type="text" name="apellidos"><br>
<p>Sexo:</p>
<select name="sexo" multiple>
<option value="hombre">Hombre</option>
<option value="mujer">Mujer</option>
</select><br>
<input type="checkbox" name="sexo" value="sexomujer" id="sexomujer">
<label for="sexomujer">Mujer</label><br>
<input type="checkbox" name="sexo" value="sexohombre" id="sexohombre">
<label for="sexohombre">Hombre</label><br>
<p>Fecha de nacimiento:</p>
<input type="date" name="fecha"><br>
<input type="submit" value="Enviar">
</form>
<br><br>
<div class="arrow"></div>
</div>
</div>
</body>
</html>
|
import { LegalMoves } from "../data/CombatantUtils";
import { Character, getMapTileEffect } from "./CombatantModel";
export enum Type {Void = "Void", Water = "Water", Fire = "Fire", Rock = "Rock", Sand = "Sand", Grass ="Grass"};
export interface TileModel {
index: number,
type: Type,
score_potential: {[species: string]: number},
}
export function createTileModel(args: {index: number, type: Type}): TileModel {
return {
index: args.index,
type: args.type,
score_potential: {},
}
}
export function updateMapTileScorePotentials(tiles: TileModel[], window_width: number) {
tiles.forEach((t, idx) => {
Object.values(Character).forEach(c => {
t.score_potential[c] =
Math.round(getMapTileScorePotential({species: c, position: idx, tiles, window_width}));
});
});
}
/**
* @returns the given tile's potential as a tile to move to
* (Tiles that are near high-value tiles have more potential than those near low-value/hurtful tiles)
*/
function getMapTileScorePotential(args: {species: Character, position: number, tiles: TileModel[], window_width: number}): number {
const {species, position, tiles, window_width} = args;
let possible_directions = Object.values(LegalMoves).length - 2;
let position_potential = 0;
const can_go_left = position % window_width > 0;
if (!can_go_left) {
possible_directions--;
} else {
position_potential += getMapTileEffect({species, tileType: tiles[position - 1].type});
}
const can_go_up = position - window_width > -1
if (!can_go_up) {
possible_directions--;
} else {
position_potential += getMapTileEffect({species, tileType: tiles[position - window_width].type});
}
const can_go_right = position % window_width < window_width - 1;
if (!can_go_right) {
possible_directions--;
} else {
position_potential += getMapTileEffect({species, tileType: tiles[position + 1].type});
}
const can_go_down = position + window_width < tiles.length;
if (!can_go_down) {
possible_directions--;
} else {
position_potential += getMapTileEffect({species, tileType: tiles[position + window_width].type});
}
// TODO: in the future, take into account an occupient of nearby tiles and their strengths;
return getMapTileEffect({species, tileType: tiles[position].type}) + (position_potential / possible_directions);
}
|
import React, { Children } from 'react'
export function Label1(props) {
const color = props.color ?? '';
return (
<div className={`flex text-[16px] fw-medium ${color} tracking-widest`}>
{
Children.toArray(props.children)
}
</div>
)
}
export function Label2(props) {
const color = props.color ?? '';
return (
<div className={`flex text-[18px] fw-medium ${color} tracking-widest`}>
{Children.toArray(props.children)}
</div>
);
}
export function Body1(props) {
return (
<div className='flex text-2xl font-normal'>
{Children.toArray(props.children)}
</div>
)
}
export function Body2(props) {
const color = props.color ?? '';
const className = props.className ?? '';
return (
<div className={`flex my-1 text-xl ${className} ${color} font-normal`}>
{Children.toArray(props.children)}
</div>
)
}
export function Body3(props) {
const color = props.color ?? '';
return (
<div className={`flex text-[14px] ${color} font-normal`}>
{Children.toArray(props.children)}
</div>
)
}
export function Display(props) {
const color = props.color ?? '';
return (
<div className={`flex text-[56px] font-normal ${color}`}>
{Children.toArray(props.children)}
</div>
)
}
export function Heading1(props) {
const color = props.color ?? '';
return (
<div className={`flex text-[48px] font-bold leading-[4rem] ${color}`}>
{Children.toArray(props.children)}
</div>
)
}
export function Heading2(props) {
const color = props.color ?? '';
return (
<div className={`flex my-3 text-[36px] font-bold leading-[3rem] ${color}`}>
{Children.toArray(props.children)}
</div>
)
}
export function Heading3(props) {
const color = props.color ?? '';
return (
<div className={`flex my-3 ${color} text-[28px] fw-medium`}>
{Children.toArray(props.children)}
</div>
)
}
export function Heading4(props) {
const color = props.color ?? '';
return (
<div className={`flex ${color} text-[24px] fw-medium`}>
{Children.toArray(props.children)}
</div>
)
}
export function Heading5(props) {
return (
<div className='flex text-[20px] fw-medium'>
{Children.toArray(props.children)}
</div>
)
}
export function Heading6(props) {
return (
<div className='flex text-[16px] fw-medium'>
{Children.toArray(props.children)}
</div>
)
}
|
<?php
namespace App\Models;
/**
* @SWG\Definition(
* definition="Document",
* required={},
* @SWG\Property(
* property="id",
* description="id",
* type="integer",
* format="int32"
* ),
* @SWG\Property(
* property="document_type_id",
* description="document_type_id",
* type="integer",
* format="int32"
* ),
* @SWG\Property(
* property="user_id",
* description="user_id",
* type="integer",
* format="int32"
* ),
* @SWG\Property(
* property="number",
* description="number",
* type="string"
* ),
* @SWG\Property(
* property="content",
* description="content",
* type="string"
* ),
* @SWG\Property(
* property="session_date",
* description="session_date",
* type="string",
* format="date"
* ),
* @SWG\Property(
* property="read",
* description="read",
* type="boolean"
* ),
* @SWG\Property(
* property="approved",
* description="approved",
* type="boolean"
* ),
* @SWG\Property(
* property="created_at",
* description="created_at",
* type="string",
* format="date-time"
* ),
* @SWG\Property(
* property="updated_at",
* description="updated_at",
* type="string",
* format="date-time"
* )
* )
*/
class DocumentProtocol extends BaseModel
{
public $table = 'document_protocol';
public $fillable = [
'document_id',
'protocol_type_id',
'number',
];
public static $translation = [
'DOCUMENTPROTOCOL' => 'PROTOCOLO DO DOCUMENTO',
'document_id' => 'Id do Documento',
'protocol_type_id' => 'Id do Tipo do Protocolo',
'number' => 'Número',
];
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'document_id' => 'integer',
'protocol_type_id' => 'integer',
'number' => 'string',
];
/**
* Validation rules.
*
* @var array
*/
public static $rules = [
];
public function document()
{
return $this->belongsTo('App\Models\Document', 'document_id');
}
public function protocol_type()
{
return $this->belongsTo('App\Models\ProtocolType', 'protocol_type_id');
}
}
|
import React, { useCallback } from 'react';
import { CommonProps } from './types';
import { actions } from 'models/app';
import { useAction } from 'hooks/useAction';
import Modal from './Modal';
const ModalContainer = ({
onAfterOpen = () => {},
onAfterClose = () => {},
...rest
}: CommonProps) => {
const toggleModalOpen = useAction(actions.toggleModalOpen);
const handleAfterOpen = useCallback(() => {
toggleModalOpen();
onAfterOpen();
document.body.classList.add('body-no-scroll');
}, [onAfterOpen, toggleModalOpen]);
const handleAfterClose = useCallback(() => {
toggleModalOpen();
onAfterClose();
document.body.classList.remove('body-no-scroll');
}, [onAfterClose, toggleModalOpen]);
return (
<Modal
onAfterOpen={handleAfterOpen}
onAfterClose={handleAfterClose}
{...rest}
/>
);
};
export default ModalContainer;
|
import { CodeBlockMerger } from "./CodeMerger"
import { expect, jest, test } from '@jest/globals'
describe('CodeBlockMerger', () => {
let codeMerger: CodeBlockMerger
beforeEach(() => {
codeMerger = new CodeBlockMerger()
})
test('should merge code blocks correctly', () => {
const codeBlocks = [
`<code>class A { method1() { console.log("A1"); } }</code>`,
`<code>class A { method1() { console.log("A2"); } method2() { console.log("A3"); } }</code>`,
`<code>function B() { console.log("B1"); }</code>`,
]
const expectedResult = [
`class A {`,
` method1() { console.log("A2"); }`,
` method2() { console.log("A3"); }`,
`}`,
`function B() { console.log("B1"); }`,
""].join('\n')
const mergedCode = codeMerger.invoke(codeBlocks)
expect(mergedCode).toEqual(expectedResult)
})
test('should handle empty code blocks', () => {
const codeBlocks = [
`<code></code>`,
`<code>function A() { console.log('A1'); }</code>`,
]
const expectedResult = [
`function A() { console.log('A1'); }`,
""].join('\n')
const mergedCode = codeMerger.invoke(codeBlocks)
expect(mergedCode).toEqual(expectedResult)
})
test('should merge overlapping code blocks', () => {
const codeBlocks = [
`<code>class A { method1() { console.log('A1'); } }</code>`,
`<code>class A { method2() { console.log('A2'); } }</code>`,
]
const expectedResult = [
`class A {`,
` method1() { console.log('A1'); }`,
` method2() { console.log('A2'); }`,
`}`,
``].join("\n")
const mergedCode = codeMerger.invoke(codeBlocks)
expect(mergedCode).toEqual(expectedResult)
})
test('should handle multiple classes and functions', () => {
const codeBlocks = [
`<code>class A { method1() { console.log('A1'); } }</code>`,
`<code>class B { method1() { console.log('B1'); } }</code>`,
`<code>function C() { console.log('C1'); }</code>`,
]
const expectedResult = [
`class A {`,
` method1() { console.log('A1'); }`,
`}`,
`class B {`,
` method1() { console.log('B1'); }`,
`}`,
`function C() { console.log('C1'); }`,
``].join('\n')
const mergedCode = codeMerger.invoke(codeBlocks)
expect(mergedCode).toEqual(expectedResult)
})
test('should handle updates to existing code', () => {
const codeBlocks = [
`<code>class A { method1() { console.log('A1'); } }</code>`,
`<code>class A { method1() { console.log('Updated A1'); } }</code>`,
]
const expectedResult = [
"class A {",
" method1() { console.log('Updated A1'); }",
"}",
""].join('\n')
const mergedCode = codeMerger.invoke(codeBlocks)
expect(mergedCode).toEqual(expectedResult)
})
it("should handle multiple class declarations", () => {
const messages = [
`<code>class A { method1() {} }</code>`,
`<code>class B { method1() {} }</code>`
]
const expectedResult = [`class A {`,
` method1() { }`,
`}`,
`class B {`,
` method1() { }`,
`}`,
``].join('\n')
const merger = new CodeBlockMerger()
const result = codeMerger.invoke(messages)
expect(result).toEqual(expectedResult)
})
it("should merge classes with different methods", () => {
const messages = [
`<code>class A { method1() {} }</code>`,
`<code>class A { method2() {} }</code>`
]
const expectedResult = [`class A {`,
` method1() { }`,
` method2() { }`,
`}`,
``].join('\n')
const result = codeMerger.invoke(messages)
expect(result).toEqual(expectedResult)
})
it("should merge interface declarations", () => {
const messages = [
`<code>interface IExample { prop1: string; }</code>`,
`<code>interface IExample { prop2: number; }</code>`
]
const expectedResult = [`interface IExample {`,
` prop1: string;`,
` prop2: number;`,
`}`,
``].join('\n')
const result = codeMerger.invoke(messages)
expect(result).toEqual(expectedResult)
})
it("should handle type alias declarations", () => {
const messages = [
`<code> type Example = { prop1: string }; </code>`,
`<code>type Example = { prop2: number; };</code>`
]
const expectedResult = [`type Example = {`,
` prop1: string;`,
` prop2: number;`,
`};`,
``].join('\n')
const result = codeMerger.invoke(messages)
expect(result).toEqual(expectedResult)
})
it("should handle imports", () => {
const messages = [
`<code>import { A } from "./A"; class MyClass { method1() {} }</code>`,
`<code>import { B } from "./B"; class MyClass { method2() {} }</code>`
]
const expectedResult = [`import { A } from "./A";`,
`import { B } from "./B";`,
`class MyClass {`,
` method1() { }`,
` method2() { }`,
`}`,
``].join('\n')
const result = codeMerger.invoke(messages)
expect(result).toEqual(expectedResult)
})
it("should handle class inheritance", () => {
const messages = [
`<code>class A { method1() {} }</code>`,
`<code>class B extends A { method2() {} }</code>`
]
const expectedResult = [`class A {`,
` method1() { }`,
`}`,
`class B extends A {`,
` method2() { }`,
`}`,
``].join('\n')
const merger = new CodeBlockMerger()
const result = merger.invoke(messages)
expect(result).toEqual(expectedResult)
})
it("should handle class implementations", () => {
const messages = [
`<code>interface IExample { method1(): void; }</code>`,
`<code>class A implements IExample { method1() {} }</code>`
]
const expectedResult = [`interface IExample {`,
` method1(): void;`,
`}`,
`class A implements IExample {`,
` method1() { }`,
`}`,
``].join('\n')
const merger = new CodeBlockMerger()
const result = merger.invoke(messages)
expect(result).toEqual(expectedResult)
})
// TODO
/*
it("should handle function overloads", () => {
const messages = [
`<code>function example(param1: string): string;</code>`,
`<code>function example(param1: number): number;</code>`
]
const expectedResult = `function example(param1: string): string;\nfunction example(param1: number): number;`
const merger = new CodeBlockMerger()
const result = merger.mergeCodeBlocks(messages)
expect(result).toEqual(expectedResult)
})
*/
it("should handle enum declarations", () => {
const messages = [
`<code>enum Color { Red, Green }</code>`,
`<code>enum Color { Blue }</code>`
]
const expectedResult = [`enum Color {`,
` Red,`,
` Green,`,
` Blue`,
`}`,
``].join('\n')
const merger = new CodeBlockMerger()
const result = merger.invoke(messages)
expect(result).toEqual(expectedResult)
})
// TODO
/*
it("should handle namespace declarations", () => {
const messages = [
`<code>namespace MyNamespace { export class A { method1() {} } }</code>`,
`<code>namespace MyNamespace { export class B { method2() {} } }</code>`
]
const expectedResult = [
`namespace MyNamespace {`,
` export class A {`,
` method1() { }`,
` }`,
` export class B {`,
` method2() { }`,
` }`,
`}`,
``].join('\n')
const merger = new CodeBlockMerger()
const result = merger.mergeCodeBlocks(messages)
expect(result).toEqual(expectedResult)
})
*/
// TODO: Decide if this should be supported.
/*
it("should handle const and let declarations", () => {
const messages = [
`<code>const a = 1;</code>`,
`<code>let b = 2;</code>`
]
const expectedResult = `const a = 1;\n\nlet b = 2;`
const merger = new CodeBlockMerger()
const result = merger.mergeCodeBlocks(messages)
expect(result).toEqual(expectedResult)
})
*/
it("should handle decorators", () => {
const messages = [
`<code>class MyClass { @Log method1() {} }</code>`,
`<code>function Log(target: any, key: string) {}</code>`
]
const expectedResult = [`class MyClass {`,
` @Log`,
` method1() { }`,
`}`,
`function Log(target: any, key: string) { }`, ``].join('\n')
const merger = new CodeBlockMerger()
const result = merger.invoke(messages)
expect(result).toEqual(expectedResult)
})
// TODO
/*
it("should handle export statements", () => {
const messages = [
`<code>class MyClass { method1() {} }</code>`,
`<code>export { MyClass };</code>`
]
const expectedResult = [`class MyClass {`, ` method1() { }`, `}`, `export { MyClass };`, ``].join('\n')
const merger = new CodeBlockMerger()
const result = merger.mergeCodeBlocks(messages)
expect(result).toEqual(expectedResult)
})
*/
it("should handle import statements", () => {
const messages = [
`<code>import { A } from './A';</code>`,
`<code>import { B } from './B';</code>`
]
const expectedResult = [`import { A } from './A';`, `import { B } from './B';`, ``].join('\n')
const merger = new CodeBlockMerger()
const result = merger.invoke(messages)
expect(result).toEqual(expectedResult)
})
// TODO
/*
it("should handle nested namespaces", () => {
const messages = [
`<code>namespace Outer { namespace Inner1 { export class A {} } }</code>`,
`<code>namespace Outer { namespace Inner2 { export class B {} } }</code>`
]
const expectedResult = `namespace Outer { namespace Inner1 { export class A {} } namespace Inner2 { export class B {} } }`
const merger = new CodeBlockMerger()
const result = merger.mergeCodeBlocks(messages)
expect(result).toEqual(expectedResult)
})
*/
it("should handle comments inside functions and methods", () => {
const messages = [
`<code>class MyClass { method1() { \n// newline comment.\n} }</code>`,
`<code>function myFunction() { // inline comment.\n}</code>`
]
const expectedResult = [`class MyClass {`,
` method1() {`,
` // newline comment.`,
` }`,
`}`,
`function myFunction() {`,
`}`, ``].join('\n')
const merger = new CodeBlockMerger()
const result = merger.invoke(messages)
expect(result).toEqual(expectedResult)
})
// TODO: Support for "require()"
// Alternatively: Keep everything on the first level the way it is,
// and don't do anything other than remove duplicates. This comes at the risk
// of leaving a lot of unwanted stuff lying around, but maybe that's better than
// not knowing what was there after a merge...
})
|
import Link from 'next/link';
import React, { useState } from 'react';
import { Eye, EyeOff } from 'lucide-react';
const ShowPassword = ({ children }: { children: (props: { type: string }) => React.ReactNode }) => {
const [showPassword, setShowPassword] = useState(false);
const toggleShowPassword = (state: boolean) => {
setShowPassword(state);
};
return (
<span className="inline-block w-full relative">
<Link
href="#"
className="absolute top-[8px] right-3"
onClick={(e) => {
e.preventDefault();
toggleShowPassword(!showPassword);
}}
tabIndex={-1}
>
{showPassword ?
<Eye size={20}/>
:
<EyeOff size={20}/>
}
</Link>
{children({ type: showPassword ? 'text' : 'password' })}
</span>
);
};
export default ShowPassword;
|
import React from "react";
import "./ChatInput.css";
const ChatInput = ({
inputSetting,
sendMessage,
sendRadioButtonChecked,
position,
}) => {
let message = "";
let timer = null;
const onMessageUpdate = (e) => {
message = e.target.value;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
sendMessage(position, message);
}, 250);
};
const onRadioButtonUpdate = (index) => {
sendRadioButtonChecked(position, index);
};
console.log("inputSetting", inputSetting);
return (
<div className="form-input">
<label className="label-input" htmlFor={inputSetting.label}>
{inputSetting.label}:
</label>
{inputSetting.type === "text" && (
<input
className="input-message"
type={inputSetting.type}
placeholder={inputSetting.placeholder}
id={inputSetting.label}
name="message"
onChange={(e) => {
onMessageUpdate(e);
}}
/>
)}
{inputSetting.type === "email" && (
<input
className="input-message"
type={inputSetting.type}
placeholder={inputSetting.placeholder}
id={inputSetting.label}
pattern={"[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,}$"}
name="message"
onChange={(e) => {
onMessageUpdate(e);
}}
/>
)}
{inputSetting.type === "tel" && (
<input
className="input-message"
type="tel"
maxLength="10"
placeholder={inputSetting.placeholder}
id={inputSetting.label}
name="message"
onChange={(e) => {
onMessageUpdate(e);
}}
/>
)}
{inputSetting.type === "radio" && (
<>
{inputSetting.radioButtons.map((setting, index) => (
<div key={index}>
<input
type="radio"
id={setting.label}
name={inputSetting.group}
defaultChecked={setting.isChecked}
value={setting.label}
onChange={() => onRadioButtonUpdate(index)}
/>
<label htmlFor={setting.label}>{setting.label}</label>
</div>
))}
</>
)}
</div>
);
};
export default ChatInput;
|
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="navigation">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">IT爱好者</span>
</button>
<a class="navbar-brand" href="/">IT爱好者</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="搜索话题">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li th:if="${session.user != null}">
<a href="/publish">
发布
</a>
</li>
<li class="dropdown" th:if="${session.user != null}">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
aria-haspopup="true"
aria-expanded="false">
<span th:text="${session.user.getName()}"></span>
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="/profile/questions">我的帖子</a></li>
<li><a href="#">个人中心</a></li>
<li role="separator" class="divider"></li>
<li><a href="/logout">退出登录</a></li>
</ul>
</li>
<li th:if="${session.user == null}">
<a href="https://github.com/login/oauth/authorize?client_id=99c9d3cce8bc3668ba98&redirect_uri=http://127.0.0.1/callback&scope=user&state=1">
登陆</a>
</li>
</ul>
</div>
</div>
</nav>
</div>
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="Scripts/jQuery.min.js"></script>
</head>
<body>
<h2>Events Demo</h2>
<input type="text" id="txt"/>
<br /><br />
<label id="lbl"></label>
<br /><br />
<input type="button" value="Click Me!!!" id="btn" />
<script>
$(function () {
//$('#btn').click(function () {
// $(this).hide();
//});
//$('#btn').mouseenter(function () {
// $(this).css('background-color', 'red');
//});
//$('#btn').mouseleave(function () {
// $(this).css('background-color', 'gray');
//});
//// hover function -> it handle both over & out event
//$('#btn').hover(function () {
// $(this).css('color', 'red');
//}, function () {
// $(this).css('color', 'black');
//});
//// on function -> registering multiple events at once
//$('#btn').on('click', function () {
// $(this).hide();
//});
$('#btn').on({
click: function () { $(this).css('background-color','lightgreen'); },
mouseenter: setCss,
mouseleave: function () {
$(this).css('color', 'black');
},
dblclick: function () {
$(this).attr('value', 'You Clicked Me!!');
}
});
function setCss() {
$(this).css('color', 'green');
}
$('#txt').focus(function () {
$(this).css('background-color', 'green');
});
$('#txt').blur(function () {
$(this).css('background-color', 'red');
});
$('#txt').keyup(function () {
// $(this).css('background-color', 'red');
// var txt = document.getElementById('txt').value;
var val = $(this).val();
$('#lbl').text(val);
});
$(document).scroll(function () {
alert('Started Scrolling...');
});
});
</script>
</body>
</html>
|
import { useContext } from 'react';
import { useEffect } from 'react';
import {createContext, useState} from 'react';
const ThemeContext = createContext();
//isDark state를 context에서 관리하기 위해서 provider를 만들어준다.
export function ThemeProvider({children}) {
const [isDark, setIsDark] = useState(false);
useEffect(()=> {
if(localStorage.getItem('theme')) {
setIsDark(localStorage.getItem('theme'));
} else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
setIsDark(true);
}
}, []);
return (
<ThemeContext.Provider value={{isDark, setIsDark, updateTheme}}>
{children}
</ThemeContext.Provider>
);
}
function updateTheme(isDark) {
if(isDark) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
localStorage.setItem('isDark', isDark);
}
export function useThemeContext() {
return useContext(ThemeContext);
}
|
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>企业工单列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1 >企业工单列表</h1>
<table class="woTable" cellpadding="0" cellspacing="0">
<tr class="firstTr">
<th width="10%">工单编号</th>
<th width="10%">项目名称</th>
<th width="20%">执行人</th>
<th width="10%">任务描述</th>
<th width="10%">工单级别</th>
<th width="10%">创建时间</th>
</tr>
<%-- <c:forEach/>实现对集合的遍历以及对条件的判断 --%>
<!-- items——集合对象 var——集合中元素的名称 varStatus——当前循环的状态信息 -->
<%-- <c:forEach var="每个变量名字" items="要迭代的list" varStatus="每个对象的状态" --%>
<!-- begin="循环从哪儿开始" end="循环到哪儿结束" step="循环的步长"> 循环要输出的东西 -->
<%-- </c:forEach> --%>
<c:forEach var="workOrder" items="${workOrderList}" varStatus="status">
<tr>
<td><span >${workOrder.id}</span></td>
<td><span>${workOrder.projectName}</span></td>
<td><span>${workOrder.executor}</span></td>
<td><span>${workOrder.description}</span></td>
<td><span>${workOrder.orderLevel}</span></td>
<td><span>${workOrder.createDate}</span></td>
</tr>
</c:forEach>
</table>
</body>
</html>
|
import org.junit.Test;
import org.vinnivso.dao.AlunoDAO;
import org.vinnivso.dao.ComputadorDAO;
import org.vinnivso.dao.CursoDAO;
import org.vinnivso.dao.MatriculaDAO;
import org.vinnivso.dao.interfaces.IAlunoDAO;
import org.vinnivso.dao.interfaces.IComputadorDAO;
import org.vinnivso.dao.interfaces.ICursoDAO;
import org.vinnivso.dao.interfaces.IMatriculaDAO;
import org.vinnivso.domain.Aluno;
import org.vinnivso.domain.Computador;
import org.vinnivso.domain.Curso;
import org.vinnivso.domain.Matricula;
import static org.junit.Assert.*;
import java.time.Instant;
public class MatriculaTest {
private IMatriculaDAO matriculaDao;
private ICursoDAO cursoDao;
private IAlunoDAO alunoDao;
private IComputadorDAO computadorDao;
public MatriculaTest() {
matriculaDao = new MatriculaDAO();
cursoDao = new CursoDAO();
alunoDao = new AlunoDAO();
computadorDao = new ComputadorDAO();
}
@Test
public void cadastrar() {
Curso curso = criarCurso("A1");
Aluno aluno = criarAluno("A1");
Matricula mat = new Matricula();
mat.setCodigo("A1");
mat.setDataMatricula(Instant.now());
mat.setStatus("ATIVA");
mat.setValor(2000d);
mat.setCurso(curso);
mat.setAluno(aluno);
aluno.setMatricula(mat);
mat = matriculaDao.cadastrar(mat);
assertNotNull(mat);
assertNotNull(mat.getId());
Matricula matBD = matriculaDao.buscarPorCodigoCurso(mat.getCodigo());
assertNotNull(matBD);
assertEquals(mat.getId(), matBD.getId());
Matricula matBDObj = matriculaDao.buscarPorCurso(curso);
assertNotNull(matBDObj);
assertEquals(mat.getId(), matBDObj.getId());
}
private Computador criarComputador(String codigo) {
Computador comp = new Computador();
comp.setCodigo(codigo);
comp.setDescricao("Comp 1");
return comp;
//return computadorDao.cadastrar(comp);
}
private Aluno criarAluno(String codigo) {
Computador comp = criarComputador("A1");
Computador comp2 = criarComputador("A2");
Aluno aluno = new Aluno();
aluno.setCodigo(codigo);
aluno.setNome("Rodrigo");
aluno.add(comp);
aluno.add(comp2);
//comp.add(aluno);
//comp2.add(aluno);
return alunoDao.cadastrar(aluno);
}
private Curso criarCurso(String codigo) {
Curso curso = new Curso();
curso.setCodigo(codigo);
curso.setDescricao("CURSO TESTE");
curso.setNome("Curso de Java Backend");
return cursoDao.cadastrar(curso);
}
}
|
import 'package:flutter/material.dart';
import 'package:flutter_profile/constants.dart';
import 'package:flutter_profile/screens/main/components/experience.dart';
import 'package:flutter_profile/screens/main/components/study.dart';
import 'package:flutter_svg/svg.dart';
import 'package:url_launcher/url_launcher.dart';
import 'area_info_text.dart';
import 'coding.dart';
import 'knowledges.dart';
import 'my_info.dart';
import 'skills.dart';
class SideMenu extends StatelessWidget {
const SideMenu({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Drawer(
child: SafeArea(
child: Column(
children: [
MyInfo(),
Expanded(
child: SingleChildScrollView(
padding: EdgeInsets.all(defaultPadding),
child: Column(
children: [
GestureDetector(
onTap: () => _launchURL(),
child: AreaInfoText(
title: "Residence",
text: "Tunisie",
),
),
AreaInfoText(
title: "City",
text: "Sfax",
),
AreaInfoText(
title: "Lieu de Naissance",
text: "CMR",
),
AreaInfoText(
title: "Email",
text: "[email protected]",
),
AreaInfoText(
title: "Telephone",
text: "28509092",
),
Study(),
Experience(),
Skills(),
SizedBox(height: defaultPadding),
Coding(),
Knowledges(),
Divider(),
SizedBox(height: defaultPadding / 2),
TextButton(
onPressed: () {},
child: FittedBox(
child: Row(
children: [
Text(
"DOWNLOAD CV",
style: TextStyle(
color: Theme.of(context)
.textTheme
.bodyText1!
.color,
),
),
SizedBox(width: defaultPadding / 2),
SvgPicture.asset("assets/icons/download.svg")
],
),
),
),
Container(
margin: EdgeInsets.only(top: defaultPadding),
color: Color(0xFF24242E),
child: Row(
children: [
Spacer(),
IconButton(
onPressed: () {},
icon: SvgPicture.asset("assets/icons/linkedin.svg"),
),
IconButton(
onPressed: () {},
icon: SvgPicture.asset("assets/icons/github.svg"),
),
IconButton(
onPressed: () {},
icon: SvgPicture.asset("assets/icons/twitter.svg"),
),
Spacer(),
],
),
),
],
),
),
),
],
),
),
);
}
void _launchURL() async {
const url =
'https://www.google.com/maps/search/?api=1&query=Sfax+Mharza+km+0.5';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}
|
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="stylesheet"
href="./node_modules/bootstrap/dist/css/bootstrap.css"
/>
<link rel="stylesheet" href="./CSS/estilos.css" />
<link rel="shortcut icon" href="./img/logo.png" type="image/x-icon">
<title>Mega Store</title>
</head>
<body>
<nav
class="navbar navbar-expand-lg navbar-dark bg-dark border-bottom shadow-sm mb-3"
>
<div class="container">
<a
class="navbar-brand"
href="./">
<strong>Mega Store</strong>
</a>
<button
class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target=".navbar-collapse"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a
href="./"
class="nav-link text-white"
> Principal
</a>
</li>
<li class="nav-item">
<a
href="./nav/contato.html"
class="nav-link text-white"
> Contato
</a>
</li>
</ul>
<div class="align-self-end">
<ul class="navbar-nav">
<li class="nav-item">
<a
href="./Cadastro/cadastro.html"
class="nav-link text-white"
>Cadastrar-se
</a>
</li>
<li class="nav-item">
<a
href="./Entrar/entrar.html"
class="nav-link text-white"
>Entrar
</a>
</li>
<li class="nav-item">
<a
href="./nav/carrinho.html"
class="nav-link text-white">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="currentColor"
class="bi bi-cart3"
viewBox="0 0 16 16"
>
<path
d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .49.598l-1 5a.5.5 0 0 1-.465.401l-9.397.472L4.415 11H13a.5.5 0 0 1 0 1H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l.84 4.479 9.144-.459L13.89 4H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"
/>
</svg>
</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
<header class="container">
<div
id="carouselMain"
class="carousel slide carousel-dark"
data-bs-ride="carousel"
>
<div class="carousel-indicators">
<button
type="button"
data-bs-target="#carouselMain"
data-bs-slide-to="0"
class="active"
></button>
<button
type="button"
data-bs-target="#carouselMain"
data-bs-slide-to="1"
></button>
<button
type="button"
data-bs-target="#carouselMain"
data-bs-slide-to="2"
></button>
</div>
<div class="carousel-inner">
<div class="carousel-item active"
data-bs-interval="3000">
<img
src="./img/slide01.jpg"
class="d-none d-md-block w-100"
alt=""
/>
<img
src="./img/slide01small.jpg"
class="d-block d-md-none w-100"
alt=""
/>
</div>
<div class="carousel-item"
data-bs-interval="3000">
<img
src="./img/slide02.jpg"
class="d-none d-md-block w-100"
alt=""
/>
<img
src="./img/slide02small.jpg"
class="d-block d-md-none w-100"
alt=""
/>
</div>
<div class="carousel-item"
data-bs-interval="3000">
<img
src="./img/slide03.jpg"
class="d-none d-md-block w-100"
alt=""
/>
<img
src="./img/slide03small.jpg"
class="d-block d-md-none w-100"
alt=""
/>
</div>
</div>
<button
class="carousel-control-prev"
type="button"
data-bs-target="#carouselMain"
data-bs-slide="prev"
>
<span class="carousel-control-prev-icon"></span>
<span class="visually-hidden">Anterior</span>
</button>
<button
class="carousel-control-next"
type="button"
data-bs-target="#carouselMain"
data-bs-slide="next"
>
<span class="carousel-control-next-icon"></span>
<span class="visually-hidden">Próximo</span>
</button>
</div>
<hr class="mt-3" />
</header>
<main>
<div class="container">
<div class="row">
<div class="col-12 col-md-5">
<form
class="justify-content-center justify-content-md-start mb-3 mb-md-0"
>
<div class="input-group input-group-sm">
<input
type="text"
class="form-control"
placeholder="Digite aqui o que procura"
/>
<button class="btn btn-dark">Buscar</button>
</div>
</form>
</div>
<div class="col-12 col-md-7">
<div
class="d-flex flex-row-reverse justify-content-center justify-content-md-start"
>
<form class="ml-3 d-inline-block">
<select class="form-select form-select-sm">
<option>Ordenar pelo nome</option>
<option>Ordenar pelo menor preço</option>
<option>Ordenar pelo maior preço</option>
</select>
</form>
<nav class="d-inline-block">
<ul class="pagination pagination-sm my-0">
<li class="page-item">
<button class="page-link">1</button>
</li>
<li class="page-item">
<button class="page-link">2</button>
</li>
<li class="page-item disabled">
<button class="page-link">3</button>
</li>
<li class="page-item">
<button class="page-link">4</button>
</li>
<li class="page-item">
<button class="page-link">5</button>
</li>
<li class="page-item">
<button class="page-link">6</button>
</li>
</ul>
</nav>
</div>
</div>
</div>
<hr class="mt-3" />
</div>
</main>
<br>
<div id="produtos-container">
</div>
<br>
<br>
<br>
<footer class="border-top fixed-bottom text-mutetd bg-light">
<div class="container">
<div class="row py-3">
<div class="col-12 col-md-4 text-center text-md-left">
<a
href="./footer/privacidade.html"
class="text-decoration-none text-dark"
>Política de Privacidade
</a>
</div>
<div class="col-12 col-md-4 text-center text-md-center"
> © 2023 - Mega Store
</div>
<div class="col-12 col-md-4 text-center text-md-right">
<a
href="./footer/quemsomos.html"
class="text-decoration-none text-dark"
>Quem Somos
</a>
</div>
</div>
</div>
</footer>
<script src="./node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="./JS/produtos.js"></script>
</body>
</html>
|
using System.Collections.Generic;
using IdentityServer4;
using IdentityServer4.Models;
using Microsoft.Extensions.Configuration;
namespace Microsoft.eShopOnDapr.Services.Identity.API
{
public class Config
{
public static IEnumerable<IdentityResource> IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};
public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope("basket", "Access to Basket API"),
new ApiScope("ordering", "Access to Ordering API"),
new ApiScope("shoppingaggr", "Access to Shopping Aggregator API"),
//scope名-Disp名
new ApiScope("testms", "Access to TestMS API"),
};
public static IEnumerable<ApiResource> ApiResources =>
new ApiResource[]
{
new ApiResource("basket-api", "Basket API")
{
Scopes = { "basket" }
},
new ApiResource("ordering-api", "Ordering API")
{
Scopes = { "ordering" }
},
new ApiResource("shoppingaggr-api", "Shopping Aggregator API")
{
Scopes = { "shoppingaggr" }
},
//API名-Disp名
new ApiResource("testmsapi", "TestMS API")
{
//scope名
Scopes = { "testms" }
}
};
public static IEnumerable<Client> GetClients(IConfiguration configuration)
{
return new List<Client>
{
new Client
{
ClientId = "blazor",
ClientName = "Blazor Front-end",
AllowedGrantTypes = GrantTypes.Code,
RequirePkce = true,
RequireClientSecret = false,
RequireConsent = false,
AllowedCorsOrigins = { configuration["BlazorClientUrlExternal"] },
// where to redirect to after login
RedirectUris = { $"{configuration["BlazorClientUrlExternal"]}/authentication/login-callback" },
// where to redirect to after logout
PostLogoutRedirectUris =
{
$"{configuration["BlazorClientUrlExternal"]}/authentication/logout-callback"
},
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"basket",
"ordering",
"shoppingaggr",
"testms"
},
},
new Client
{
ClientId = "basketswaggerui",
ClientName = "Basket Swagger UI",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = { $"{configuration["BasketApiUrlExternal"]}/swagger/oauth2-redirect.html" },
PostLogoutRedirectUris = { $"{configuration["BasketApiUrlExternal"]}/swagger/" },
AllowedScopes =
{
"basket"
}
},
new Client
{
ClientId = "orderingswaggerui",
ClientName = "Ordering Swagger UI",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = { $"{configuration["OrderingApiUrlExternal"]}/swagger/oauth2-redirect.html" },
PostLogoutRedirectUris = { $"{configuration["OrderingApiUrlExternal"]}/swagger/" },
AllowedScopes =
{
"ordering"
}
},
new Client
{
ClientId = "shoppingaggrswaggerui",
ClientName = "Shopping Aggregator Swagger UI",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = { $"{configuration["ShoppingAggregatorApiUrlExternal"]}/swagger/oauth2-redirect.html" },
PostLogoutRedirectUris = { $"{configuration["ShoppingAggregatorApiUrlExternal"]}/swagger/" },
AllowedScopes =
{
"basket",
"shoppingaggr"
}
},
new Client
{
//id
ClientId = "testmsswaggerui",
//表示名
ClientName = "TestMS Swagger UI",
//暗黙 更新トークン等の高度な機能は無
AllowedGrantTypes = GrantTypes.Implicit,
//クライアントがブラウザを介してアクセストークンを受信できるようにするかどうか
AllowAccessTokensViaBrowser = true,
//トークンまたは認証コードを返すことができるURI
RedirectUris = { $"{configuration["TestMSApiUrlExternal"]}/swagger/oauth2-redirect.html" },
//ログアウト後にリダイレクトできるURI
PostLogoutRedirectUris = { $"{configuration["TestMSApiUrlExternal"]}/swagger/" },
//対応するスコープ名を追加して、許可されるリソースを指定
AllowedScopes =
{
"testms"
}
}
};
}
}
}
|
sameParityFilter.js
Реализуйте и экспортируйте по умолчанию функцию, которая принимает на вход массив и возвращает новый, состоящий из элементов, у которых такая же чётность, как и у первого элемента входного массива.
Примеры
sameParity([-1, 0, 1, -3, 10, -2]); // [-1, 1, -3]
sameParity([2, 0, 1, -3, 10, -2]); // [2, 0, 10, -2]
sameParity([]); // []
const sameParity = (arr) => {
const parityFirst = Math.abs(arr[0]) % 2;
const newArr = arr.filter((item) => Math.abs(item) % 2 === parityFirst);
return newArr;
};
export default sameParity;
|
<html ng-app="ionic.appview">
<head>
<meta charset="utf-8">
<title>Ionic View</title>
<!-- Sets initial viewport load and disables zooming -->
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width, height=device-height">
<link rel="stylesheet" href="css/ionic.css">
<link rel="stylesheet" href="css/app.css">
<script src="js/ionic.js"></script>
<script src="js/angular/angular.js"></script>
<script src="js/angular/angular-animate.js"></script>
<script src="js/angular/angular-sanitize.js"></script>
<script src="js/angular/angular-resource.js"></script>
<script src="js/angular/angular-cookies.js"></script>
<script src="js/angular-ui/angular-ui-router.js"></script>
<script src="js/ionic-angular.js"></script>
<script src="cordova.js"></script>
<script src="js/services.js"></script>
<script src="js/directives.js"></script>
<script src="js/app.js"></script>
<script src="js/config.js"></script>
</head>
<body>
<ion-nav-view></ion-nav-view>
<script id="login.html" type="text/ng-template">
<ion-view>
<ion-content class="padding" scroll="false">
<img class="ionic-logo" src="res/img/[email protected]">
<div class="error" ng-if="form.error" ng-model="form.error">Error: {{form.error}}</div>
<form ng-submit="login()">
<div class="ion-list">
<label class="item item-input">
<i class="icon ion-ios7-email placeholder-icon"></i>
<input ng-model="form.email" type="text" placeholder="Email">
</label>
<label class="item item-input">
<i class="icon ion-locked placeholder-icon"></i>
<input ng-model="form.pass" type="password" placeholder="Password">
</label>
<button id="signin-button" type="submit" class="button button-block button-positive">Sign In</button>
</div>
</form>
<p id="home-bottom-text" class="bottom-text">
Don't have an account? <span ng-click='openLoadModal()'>Load app here! <i class="icon ion-arrow-right-c"></i></span>
</p>
</ion-content>
</ion-view>
</script>
<script id="userapps.html" type="text/ng-template">
<ion-view>
<ion-header-bar
title="headerTitle"
right-buttons="rightButtons"
type="bar-positive"
align-title="left">
</ion-header-bar>
<ion-content id="userapps-content" class="" has-header="true" scroll="true" on-refresh="reloadAppList()">
<ion-refresher></ion-refresher>
<div id="applist">
<div ng-repeat="app in userApps" class="card">
<a class="item item-icon-left" ng-click="loadApp(app.appId)">
<i class="icon ion-iphone" ng-class="{'loaded': app.loaded}" ></i>
<span>
<b>{{app.name}}</b>
</span>
<br>
<span class="subtext">
ID: {{app.appId|uppercase}}
</span>
</br>
<span class="subtext">
Modified: {{app.server_last_modified | date}}
</span>
</a>
</div>
</div>
</ion-content>
</ion-view>
</script>
<script id="loadingscreen.html" type="text/ng-template">
<div id="loading-screen">
<div class="loading-container">
<img class="spin" src="res/img/ionic_icon.svg">
<loading-bar progress="data.percentage"></loading-bar>
</div>
</div>
</script>
<script id="settingsmodal.html" type="text/ng-template">
<div class="modal">
<header class="bar bar-header bar-positive">
<h1 class="title title-left">Settings</h1>
<button class="button button-clear button-light" ng-click="close()">Done</button>
</header>
<ion-content id="settingsList" has-header="true" scroll="false">
<ul class="list">
<div class="item item-divider"></div>
<a class="item item-toggle" ng-click="clearData()">
Clear All App Data
</a>
<div class="item item-divider"></div>
<a class="item item-toggle" ng-click="logout()">
Log Out
</a>
</ul>
</ion-content>
</div>
</script>
<script id="loadappmodal.html" type="text/ng-template">
<div class="modal">
<header class="bar bar-header bar-positive">
<h1 class="title title-left">Load New App</h1>
<button class="button button-clear button-light" ng-click="close()">Done</button>
</header>
<ion-content class="padding" has-header="true" scroll="false">
<label class="loadapp-input item item-input">
<i class="icon ion-ionic placeholder-icon"></i>
<input type="text" ng-model="app.appId" placeholder="Enter App ID">
</label>
<button class="loadapp-button button button-block button-positive" ng-click="loadApp()">Load App</button>
<p class="loadapp-bottom-text bottom-text">
<i class="icon ion-camera"></i>
Or, just <span ng-click="scan()">scan the QR code</span>
</p>
</ion-content>
</div>
</script>
<script id="viewapp.html" type="text/ng-template">
<ion-view>
<ion-side-menus>
<ion-pane ion-side-menu-content>
<div id="frameContainer">
<iframe class="frame" src="about:blank"></iframe>
</div>
<div id="sidemenu-handle">
<i ng-click="toggleSide()" class="icon ion-navicon-round"></i>
</div>
</ion-pane>
<ion-side-menu id="view-sidemenu" side="left">
<ion-content scroll="false">
<div class="list">
<span class="item item-icon-left" ng-click="exit()">
<i class="icon ion-reply"></i>
<span>Exit</span>
</span>
<span class="item item-icon-left" ng-click="reload()">
<i class="icon ion-refresh"></i>
<span>Refresh</span>
</span>
<span class="item item-icon-left" ng-click="removeApp()">
<i class="icon ion-android-close"></i>
<span>Delete Files</span>
</span>
</div>
</ion-content>
<span id="app-info" class="item">
<span>
{{app.name}}
</span>
<br>
<span class="subtext">
ID: {{app.appId|uppercase}}
</span>
</br>
<span class="subtext">
Modified: {{app.server_last_modified | date}}
</span>
</span>
</ion-side-menu>
</ion-side-menus>
</ion-view>
</script>
</body>
</html>
|
package com.tencent.protocol.order_protocol;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import com.tencent.common.Configure;
import com.tencent.common.RandomStringGenerator;
import com.tencent.common.Signature;
public class OrderQueryReqData {
private String appid;
private String mch_id;
private String nonce_str;
private String out_trade_no = null;
public String getOut_trade_no() {
return out_trade_no;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public OrderQueryReqData(String outTradeNo){
//微信分配的公众号ID(开通公众号之后可以获取到)
setAppid(Configure.getAppid());
//微信支付分配的商户号ID(开通公众号的微信支付功能之后可以获取到)
setMch_id(Configure.getMchid());
//随机字符串,不长于32 位
setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
//商户系统内部的订单号,32个字符内可包含字母, 确保在商户系统唯一
setOut_trade_no(outTradeNo);
//根据API给的签名规则进行签名
String sign = Signature.getSign(toMap());
setSign(sign);//把签名数据设置到Sign这个属性中
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getMch_id() {
return mch_id;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public String getNonce_str() {
return nonce_str;
}
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public Map<String,Object> toMap(){
Map<String,Object> map = new HashMap<String, Object>();
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
Object obj;
try {
obj = field.get(this);
if(obj!=null){
map.put(field.getName(), obj);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return map;
}
private String sign = "";
}
|
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/menuDrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="cn.edu.scu.creator.networkclient.MainActivity"
android:background="@drawable/background"
android:id="@+id/main_layout">
<Button
android:id="@+id/btLogin"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:text="@string/login"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="46dp"
app:layout_constraintTop_toBottomOf="@+id/etPassword"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent" />
<EditText
android:id="@+id/etUserId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textVisiblePassword"
android:digits="1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
android:hint="@string/userId"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="199dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_bias="0.502" />
<EditText
android:id="@+id/etPassword"
android:hint="@string/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
tools:layout_constraintTop_creator="1"
android:layout_marginTop="11dp"
app:layout_constraintTop_toBottomOf="@+id/etUserId"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="@+id/etUserId"
android:layout_marginLeft="-13dp" />
<CheckBox
android:id="@+id/cbSavePassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/savePassword"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toTopOf="@+id/btLogin"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="@+id/etPassword" />
<Button
android:id="@+id/btSettings"
android:layout_width="47dp"
android:layout_height="49dp"
android:background="@drawable/menu"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="1dp"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="@+id/menuListView"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:choiceMode="singleChoice"
android:divider="@color/colorPrimary"
android:dividerHeight="1dp"
android:background="@color/textColorPrimary"/>
</android.support.v4.widget.DrawerLayout>
|
import 'package:flutter/material.dart';
class SplashScreen extends StatefulWidget {
final Widget? child;
const SplashScreen({super.key, this.child});
@override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
Future.delayed(const Duration(seconds: 3), () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => widget.child!),
(route) => false);
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0XFF5D60E2),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 140,
child: ClipRRect(
borderRadius: BorderRadius.circular(25.0),
child: Image.asset(
'images/app_icon.png',
fit: BoxFit.cover,
),
)),
Container(
margin: const EdgeInsets.only(top: 16),
child: const Text(
'Algo Pintar',
style: TextStyle(
fontSize: 24,
color: Colors.white,
fontWeight: FontWeight.bold,
fontFamily: 'Montserrat',
),
),
),
Container(
margin: const EdgeInsets.only(top: 6),
child: const Text(
'Raih Keahlian Algoritma dengan Cerdas',
style: TextStyle(
fontSize: 14,
color: Colors.white,
fontFamily: 'Montserrat',
),
textAlign: TextAlign.center,
),
),
],
),
));
}
}
|
import java.util.Scanner;
public class Circulo extends Figura {
// encapsulamiento...
// ----propiedades, atributes o campos (fields) ---
private double radio;
// Setters and getters
public double getRadio() {
return radio;
}
public void setRadio(double radio) {
this.radio = radio;
}
// --- builders---
public Circulo(double radio) {
this.radio= radio;
}
public Circulo() {;
}
// Methods
public double calcularArea() {
return Math.PI * Math.pow(radio, 2) ;
}
public double calcularPerimetro() {
return 2 * Math.PI * radio;
}
public void cargarDatos() {
Scanner teclado = new Scanner(System.in);
System.out.println("Ingresa el Radio en cm: ");
radio = teclado.nextDouble();
}
}
|
import React from 'react'
import { useState, useEffect } from 'react'
import Wrapper from '../components/UI/Wrapper'
import {
Grid,
useMediaQuery,
FormGroup,
FormControlLabel,
Switch,
Box,
CircularProgress,
Typography,
} from '@mui/material'
import dynamic from 'next/dynamic'
import Cookies from 'js-cookie'
import { fetchData } from '@/api/fetchData'
import useCells from '@/hooks/useCells'
import OutlinedButton from '@/components/UI/OutlinedButton'
import CellModal from '@/components/UI/CellModal'
import SearchInput from '@/components/UI/SearchInput'
const Cell = dynamic(() => import('../components/UI/Cell'))
const token = Cookies.get('access_token')
const url = process.env.API_URL
const acceptData = {
isAccepted: true,
acceptedAt: Date.now(),
isPayed: true,
payedAt: Date.now(),
}
const closeData = {
isActive: false,
isArchived: true,
}
export default function Cells() {
const [active, setActive] = useState(true)
const [limit, setLimit] = useState(100)
const [levels, setLevels] = useState(null)
const [levelId, setLevelId] = useState(1)
const [modalOpen, setModalOpen] = useState(false)
const [acceptedCount, setAcceptedCount] = useState(0)
const isMobile = useMediaQuery('@media(max-width:1300px)')
const { data, loading, error, getCells } = useCells()
const {
data: cell,
loading: cellLoading,
error: cellError,
success: cellSuccess,
getCellById,
} = useCells()
const {
data: consultants,
loading: consultantsLoading,
error: consultantsError,
success: consultantsSuccess,
getConsultants,
editConsultantAndLeader,
} = useCells()
const {
data: follower,
success: addSuccess,
loading: addFollowerLoading,
error: addFollowerError,
addFollower,
} = useCells()
const {
data: patchingData,
loading: patchingLoading,
error: patchingError,
success: patchingSuccess,
deleteFollower,
editFollower,
} = useCells()
const {
success: closeSuccess,
loading: closeLoading,
error: closeError,
closeCell,
} = useCells()
const fetchDataAsync = async ({
page = page,
limit = limit,
active = active,
level = level,
}) => {
try {
await getCells({ page: page, limit: limit, active: active, level: level })
const response = await fetchData(`${url}/cell-levels`, token)
setLevels(response.data)
} catch (err) {
console.error(err)
}
}
const searchCell = async ({ page = 1, limit = 100, search = search }) => {
console.log(search)
await getCells({ page: page, limit: limit, search: search })
const response = await fetchData(`${url}/cell-levels`, token)
setLevels(response.data)
}
useEffect(() => {
fetchDataAsync({ page: 1, limit: limit, active: active, level: levelId })
}, [limit, active, levelId, modalOpen])
const handleLimitChange = limit => {
setLimit(limit)
}
const onPageChange = page => {
fetchDataAsync({ page, limit, active, level: levelId })
}
const onModalOpen = async id => {
await getCellById(id)
await getConsultants(levelId)
setModalOpen(true)
}
const refreshFetch = async id => {
await getCellById(id)
}
const onAddUserClick = async (cellId, id) => {
await addFollower(cellId, id)
}
const onDeleteUserClick = async id => {
await deleteFollower(id)
}
const onApproveClick = async id => {
await editFollower(id, acceptData)
}
const onCloseClick = async id => {
const result = await closeCell(id, closeData)
result.isSuccess && setModalOpen(false)
refreshFetch(id)
}
return (
<>
<Wrapper
header={
<Box style={{ display: 'flex', alignItems: 'center', gap: 15 }}>
Cells
<FormGroup>
<FormControlLabel
control={
<Switch
checked={active}
onChange={() => setActive(!active)}
/>
}
label='active'
/>
</FormGroup>
</Box>
}
totalPages={data?.total_pages}
currentPage={data?.current_page}
onPageChange={onPageChange}
handleLimitChange={handleLimitChange}
selectedLimit={limit}
style={{
minHeight: 760,
maxHeight: isMobile ? '80dvh' : 'none',
}}
>
<SearchInput onSearch={searchCell} initialValue={''} />
<Box
style={{
display: 'flex',
gap: 5,
}}
>
{levels?.map(level => (
<OutlinedButton
key={level.id}
title={level.level}
id={levelId}
level={level.id}
onClick={() => setLevelId(level.id)}
/>
))}
</Box>
<Typography variant=''>
Cells on level {levelId}: {data?.total}
</Typography>
<Grid
style={{
width: '100%',
height: isMobile ? 'auto' : '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexWrap: 'wrap',
gap: isMobile ? 10 : '25px 0px',
overflow: 'auto',
scrollbarColor: '#bc5a00 #f17d15',
}}
>
{loading ? (
<CircularProgress size={72} />
) : (
<>
{data?.data?.map((cell, index) => (
<Cell
key={cell?.id}
id={cell.id}
consultant={cell.consultant}
leader={cell.leader}
cellUsers={cell.cellUsers}
onModalOpen={onModalOpen}
style={{
flexBasis: '33.33%',
maxWidth: '33.33%',
boxSizing: 'border-box',
}}
/>
))}
</>
)}
</Grid>
</Wrapper>
{cell && (
<CellModal
open={modalOpen}
handleClose={() => {
setModalOpen(false)
}}
refreshFetch={refreshFetch}
cellData={cell.data}
setAcceptedCount={setAcceptedCount}
acceptedCount={acceptedCount}
addSuccess={addSuccess}
addFollowerLoading={addFollowerLoading}
addFollowerError={addFollowerError}
onApproveClick={onApproveClick}
patchingSuccess={patchingSuccess}
patchingLoading={patchingLoading}
patchingError={patchingError}
onAddUserClick={onAddUserClick}
onDeleteUserClick={onDeleteUserClick}
closeSuccess={closeSuccess}
closeLoading={closeLoading}
closeError={closeError}
closeCell={onCloseClick}
title={`Editing cell #${cell.data.id}`}
isLoading={loading}
editCaL={editConsultantAndLeader}
consultants={consultants}
/>
)}
</>
)
}
|
@extends('layouts.admin_layout')
@section('title', 'Редактировать материал')
@section('content')
<!-- Content Header (Page header) -->
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0">Редактировать материал: {{ $post['title'] }}</h1>
</div><!-- /.col -->
</div><!-- /.row -->
<a href="{{ route('odinvopros.index') }}">Все материалы</a>
@if (session('success'))
<div class="alert alert-success" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i>{{ session('success') }}</h4>
</div>
@endif
@error('post_image')
<div class="alert alert-warning" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i>{{ $message }}</h4>
</div>
@enderror
@error('post_images.*')
<div class="alert alert-warning" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i>{{ $message }}</h4>
</div>
@enderror
@if (session('error_img'))
<div class="alert alert-warning" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i>{{ session('error_img') }}</h4>
</div>
@endif
</div><!-- /.container-fluid -->
</div>
<!-- /.content-header -->
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="card card-primary">
<!-- form start -->
<form action="{{ route('odinvopros.update', $post['id']) }}" method="POST"
enctype="multipart/form-data">
@csrf
@method('PUT')
<div class="card-body">
<div class="form-group">
<label for="title">SEO Title</label>
<input type="text" value="{{ $post['title'] }}" name="title" class="form-control"
id="title" placeholder="Введите SEO Title статьи" required>
</div>
<div class="icheck-primary d-inline">
<input type="checkbox" name="report" @if($post->report) checked @endif value="1"
id="checkboxSuccess3">
<label for="checkboxSuccess3">
Для отчета
</label>
</div>
<div class="form-group">
<label for="h1">Заголовок H1</label>
<input type="text" value="{{ $post['h1'] }}" name="h1" class="form-control"
id="h1" placeholder="Введите название статьи" required>
</div>
<div class="form-group">
<label for="title">SEO Description</label>
<input type="text" value="{{ $post['description'] }}" name="description"
class="form-control"
id="title" placeholder="Введите SEO Description" required>
</div>
<div class="form-group">
<label for="alias">Алиас</label>
<input type="text" value="{{ $post['alias'] }}" name="alias" class="form-control"
id="alias" placeholder="Введите алиас рубрики" required>
</div>
<div class="form-group ">
<label>Дата публикации материала</label>
<div class="input-group date" id="reservationdate" data-target-input="nearest">
<input data-toggle="datetimepicker"
value="@if($post->created_at){{date('d.m.Y H:i', strtotime($post->created_at))}}@endif"
name="created_at" type="text" class="form-control datetimepicker-input"
data-target="#reservationdate"/>
<div class="input-group-append" data-target="#reservationdate"
data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Ссылка на youtube ролик</label>
<input type="text" name="link_youtube" class="form-control" id="exampleInputEmail1" placeholder="Введите ссылку на youtube ролик" value="{{$post->link_youtube}}" required>
</div>
<label for="exampleInputEmail1">Сопроводительный текст к репортажу</label>
<div class="form-group">
<textarea name="text" class="editor">{{ $post['text'] }}</textarea>
</div>
<div class="form-group">
<label for="feature_image">Изображение для материала</label>
<img src="@if(file_exists(storage_path('app/public/odinvopros_image/'.$post['img'])))
{{asset('public/storage/odinvopros_image/'.$post['img'])}}
@endif" alt="" class="img-uploaded"
style="display: block; width: 300px">
<div class="custom-file">
<input type="file" class="custom-file-input" id="post_image" name="post_image">
<label class="custom-file-label" for="post_image">Выберите изображение</label>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<!-- /.content -->
@endsection
|
#Analysis of historical catches reported by hunters
# CJ Brown 2022-04-27
rm(list= ls())
library(ggplot2)
library(mgcv)
library(tidyr)
dat <- readr::read_csv("Shared/Data/turtle-hunter-questions.csv")
dat2 <- dat %>% dplyr::filter(`Hunting method(s) used when started hunting` != "During breeding period of turtles. Used to go ashore to lay eggs and catch them.") %>%
dplyr::select(Fisherman, year = `Year started catching turtles?`,
catch_start, catch_end) %>%
dplyr::filter(!is.na(catch_end)) %>%
pivot_longer(-c(1:2), names_to = "Period", values_to = "catch") %>%
dplyr::mutate(year2 = ifelse(Period == "catch_start", year, 2018),
catch2 = round(catch))
dat2$Fisherman <- factor(dat2$Fisherman)
m1 <- gam(catch2 ~ year2 + s(Fisherman, bs = "re"),
data = dat2,
family = "poisson")
summary(m1)
pdat <- data.frame(year2 = 1974:2018,
Fisherman = dat2$Fisherman[1])
Xp <- predict(m1, newdata = pdat,
type = "lpmatrix",
exclude = "Fisherman")
Xp[,3] <- 0 #set fisherman ID to zero
pdat$catch2 <- exp(Xp %*% coef(m1))
pdat$catch2[pdat$year2==1988]/pdat$catch2[pdat$year2==2018]
exp(-coef(m1)[2]*30)
1-exp(coef(m1)[2])
1-exp(coef(m1)[2]+0.0058*1.96)
1-exp(coef(m1)[2]-0.0058*1.96)
g1 <- ggplot(dat2) +
aes(x= year2, y = catch2, group = Fisherman) +
geom_line(alpha = 0.3) +
geom_line(data = pdat, color = "black", size = 1) +
xlim(1974, 2018) +
xlab("Year") +
ylab("Harvest") +
theme_classic() +
theme(legend.position="none")
ggsave(plot = g1, filename = "Shared/Outputs/historic-catch-model.png",
width = 5.5, height = 3)
|
import styles from "./BackgroundImages.module.css";
import { useState, useEffect } from "react";
import img from "../../../../assets/background-img/background1.jpg";
import { useDispatch } from "react-redux";
import { onBackdropImg } from "../../../../store/themeSystem";
import cn from "classnames";
import Loading from "../../../UI/Loading/Loading";
function BackgroundImages({ background }) {
const dispatch = useDispatch();
const [backdropActiv, setBackdropActiv] = useState(
localStorage.getItem("backdropActiv") || img
);
function backdropToggleHandler(img) {
dispatch(onBackdropImg(img));
setBackdropActiv(img);
}
useEffect(() => {
localStorage.setItem("backdropActiv", backdropActiv);
}, [backdropActiv]);
return (
<div className={styles["backdrop-img"]}>
{background.map((img, index) => {
const key = typeof img === "string" ? img : img.urls.small;
if (typeof img === "string") {
return (
<img
key={key}
src={img}
alt="фон"
onClick={() => backdropToggleHandler(img)}
className={cn("", {
[styles.activ]: backdropActiv === img,
})}
/>
);
}
if (typeof img === "object") {
return (
<img
key={key}
src={img.urls.small}
alt="фон"
onClick={() => backdropToggleHandler(img.urls.small)}
className={cn("", {
[styles.activ]: backdropActiv === img.urls.small,
})}
/>
);
}
return null;
})}
</div>
);
}
export default BackgroundImages;
|
import java.util.Scanner;
/**
* Template for menu based Text user interfaces .
*
* @author (your name)
* @version (a version number or a date)
*/
public class TextUITemplate
{
// DECLARE SPECIFIC OBJECT HERE
private Scanner keyboard;
private Rectangle rectangle;
/**
* Constructor for objects of class TextTU
*/
public TextUITemplate()
{
rectangle = new Rectangle(0,0);
keyboard = new Scanner( System.in);
}
public void menu()
{
int command = -1;
createRectangle();
while ( command != 0 )
{
displayMenu();
command = getCommand();
execute( command );
}
}
private void createRectangle()
{
int length = readIntWithPrompt
("Rectangle length (a non-negative integer):");
int width = readIntWithPrompt
("Rectangle length (a non-negative integer):");
rectangle = new Rectangle(length, width);
}
private int readIntWithPrompt(String prompt)
{
System.out.print(prompt);
int input = keyboard.nextInt();
keyboard.nextLine();
return input;
}
private void displayMenu()
{
System.out.println();
System.out.println("Enter number denoting action to perform:");
System.out.println("Display length....................[1]");
System.out.println("Display breadth..................[2]");
System.out.println("Display area.......................[3]");
System.out.println("Display perimeter...............[4]");
System.out.println("Create new rectangle.........[5]");
System.out.println("Exit.....................................[0]");
}
private int getCommand()
{
System.out.print ("Enter command: ");
int command = keyboard.nextInt();
return command;
}
private void execute( int command)
{
if ( command == 1)
displayLength();
else if ( command == 2 )
displayBreadth();
else if ( command == 3)
displayArea();
else if ( command == 4 )
displayPerimeter();
else if ( command == 5)
createRectangle() ;
else if ( command == 0)
{
System.out.println( " Program closing down");
System.exit(0);
}
else
System.out.println("Unknown command");
}
private void displayLength() {
System.out.println( "The length is " + rectangle.getLength() );
}
private void displayBreadth() {
System.out.println( "The breadth is " + rectangle.getBreadth() );
}
private void displayArea() {
System.out.println( "The area is " + rectangle.calculateArea() );
}
private void displayPerimeter() {
System.out.println( "The perimeter is " + rectangle.calculatePerimeter() );
}
}
|
require 'rails_helper'
RSpec.describe InvoiceItem, type: :model do
describe 'validations' do
it {should validate_presence_of :unit_price}
it {should validate_presence_of :quantity}
end
describe 'relationships' do
it {should belong_to :item}
it {should belong_to :invoice}
end
end
|
import { BigNumber, INTEGERS } from '@dolomite-exchange/dolomite-margin';
import fs from 'fs';
import v8 from 'v8';
import { getAllDolomiteAccountsWithSupplyValue } from '../src/clients/dolomite';
import { dolomite } from '../src/helpers/web3';
import BlockStore from '../src/lib/block-store';
import Logger from '../src/lib/logger';
import MarketStore from '../src/lib/market-store';
import Pageable from '../src/lib/pageable';
import TokenAbi from './abis/isolation-mode-factory.json';
import '../src/lib/env'
import { getMineralConfigFileNameWithPath, MineralConfigFile } from './lib/config-helper';
import {
getAccountBalancesByMarket,
getAmmLiquidityPositionAndEvents,
getArbVestingLiquidityPositionAndEvents,
getBalanceChangingEvents,
} from './lib/event-parser';
import { readFileFromGitHub } from './lib/file-helpers';
import { setupRemapping } from './lib/remapper';
import {
ARB_VESTER_PROXY,
calculateFinalPoints,
calculateVirtualLiquidityPoints,
ETH_USDC_POOL,
InterestOperation,
LiquidityPositionsAndEvents,
processEventsUntilEndTimestamp,
} from './lib/rewards';
/* eslint-enable */
interface OutputFile {
users: {
[walletAddressLowercase: string]: string // big int
};
metadata: {
marketId: number
marketName: string // big int
totalPointsForMarket: string // big int
startBlock: number
endBlock: number
startTimestamp: number
endTimestamp: number
};
}
const FOLDER_NAME = `${__dirname}/output`;
async function start() {
const networkId = await dolomite.web3.eth.net.getId();
const liquidityMiningConfig = await readFileFromGitHub<MineralConfigFile>(
getMineralConfigFileNameWithPath(networkId),
);
const epoch = parseInt(process.env.EPOCH_NUMBER ?? 'NaN', 10);
if (Number.isNaN(epoch) || !liquidityMiningConfig.epochs[epoch]) {
return Promise.reject(new Error(`Invalid EPOCH_NUMBER, found: ${epoch}`));
}
const maxMarketId = (await dolomite.getters.getNumMarkets()).toNumber();
const validMarketId = parseInt(process.env.MARKET_ID ?? 'NaN', 10);
if (Number.isNaN(validMarketId)) {
return Promise.reject(new Error(`Invalid MARKET_ID, found: ${process.env.MARKET_ID}`));
} else if (validMarketId >= maxMarketId) {
return Promise.reject(new Error(`MARKET_ID contains an element that is too large, found: ${validMarketId}`));
}
const validMarketIdsMap = {
[validMarketId]: INTEGERS.ONE,
}
const blockStore = new BlockStore();
await blockStore._update();
const marketStore = new MarketStore(blockStore);
const { startBlockNumber, startTimestamp, endBlockNumber, endTimestamp } = liquidityMiningConfig.epochs[epoch];
const libraryDolomiteMargin = dolomite.contracts.dolomiteMargin.options.address;
if (networkId !== Number(process.env.NETWORK_ID)) {
const message = `Invalid network ID found!\n
{ network: ${networkId} environment: ${Number(process.env.NETWORK_ID)} }`;
Logger.error(message);
return Promise.reject(new Error(message));
}
Logger.info({
message: 'DolomiteMargin data',
blockRewardStart: startBlockNumber,
blockRewardStartTimestamp: startTimestamp,
blockRewardEnd: endBlockNumber,
blockRewardEndTimestamp: endTimestamp,
dolomiteMargin: libraryDolomiteMargin,
ethereumNodeUrl: process.env.ETHEREUM_NODE_URL,
heapSize: `${v8.getHeapStatistics().heap_size_limit / (1024 * 1024)} MB`,
networkId,
marketId: validMarketId,
subgraphUrl: process.env.SUBGRAPH_URL,
});
await marketStore._update(startBlockNumber);
const startMarketMap = marketStore.getMarketMap();
const startMarketIndexMap = await marketStore.getMarketIndexMap(startMarketMap, { blockNumber: startBlockNumber });
await marketStore._update(endBlockNumber);
const endMarketMap = marketStore.getMarketMap();
const endMarketIndexMap = await marketStore.getMarketIndexMap(endMarketMap, { blockNumber: endBlockNumber });
const apiAccounts = await Pageable.getPageableValues(async (lastId) => {
const result = await getAllDolomiteAccountsWithSupplyValue(startMarketIndexMap, startBlockNumber, lastId);
return result.accounts;
});
await setupRemapping(networkId, endBlockNumber);
const accountToDolomiteBalanceMap = getAccountBalancesByMarket(
apiAccounts,
startTimestamp,
validMarketIdsMap,
);
const accountToAssetToEventsMap = await getBalanceChangingEvents(startBlockNumber, endBlockNumber);
processEventsUntilEndTimestamp(
accountToDolomiteBalanceMap,
accountToAssetToEventsMap,
endMarketIndexMap,
validMarketIdsMap,
endTimestamp,
InterestOperation.NOTHING,
);
const ammLiquidityBalancesAndEvents = await getAmmLiquidityPositionAndEvents(
startBlockNumber,
startTimestamp,
endTimestamp,
);
const vestingPositionsAndEvents = await getArbVestingLiquidityPositionAndEvents(
startBlockNumber,
startTimestamp,
endTimestamp,
);
const poolToVirtualLiquidityPositionsAndEvents: Record<string, LiquidityPositionsAndEvents> = {
[ETH_USDC_POOL]: ammLiquidityBalancesAndEvents,
[ARB_VESTER_PROXY]: vestingPositionsAndEvents,
};
const poolToTotalSubLiquidityPoints = calculateVirtualLiquidityPoints(
poolToVirtualLiquidityPositionsAndEvents,
startTimestamp,
endTimestamp,
);
const { userToPointsMap, marketToPointsMap } = calculateFinalPoints(
networkId,
accountToDolomiteBalanceMap,
validMarketIdsMap,
poolToVirtualLiquidityPositionsAndEvents,
poolToTotalSubLiquidityPoints,
);
const allMarketIds = Object.keys(marketToPointsMap);
allMarketIds.forEach(marketId => {
if (marketId !== validMarketId.toString()) {
delete marketToPointsMap[marketId];
}
});
const tokenAddress = await dolomite.getters.getMarketTokenAddress(new BigNumber(validMarketId));
const token = new dolomite.web3.eth.Contract(TokenAbi, tokenAddress);
const tokenName = await dolomite.contracts.callConstantContractFunction(token.methods.name());
// eslint-disable-next-line max-len
const fileName = `${FOLDER_NAME}/asset-held-${startTimestamp}-${endTimestamp}-${validMarketId}-output.json`;
const dataToWrite = readOutputFile(fileName);
dataToWrite.users = Object.keys(userToPointsMap).reduce((memo, user) => {
memo[user] = userToPointsMap[user].toFixed(0);
return memo;
}, {});
dataToWrite.metadata = {
marketId: validMarketId,
marketName: tokenName,
totalPointsForMarket: marketToPointsMap[validMarketId].toFixed(0),
startBlock: startBlockNumber,
endBlock: endBlockNumber,
startTimestamp,
endTimestamp,
}
writeOutputFile(fileName, dataToWrite);
return true;
}
function readOutputFile(fileName: string): OutputFile {
try {
return JSON.parse(fs.readFileSync(fileName, 'utf8')) as OutputFile;
} catch (e) {
return {
users: {},
metadata: {
marketId: 0,
marketName: '',
totalPointsForMarket: '0',
startBlock: 0,
endBlock: 0,
startTimestamp: 0,
endTimestamp: 0,
},
};
}
}
function writeOutputFile(
fileName: string,
fileContent: OutputFile,
): void {
if (!fs.existsSync(FOLDER_NAME)) {
fs.mkdirSync(FOLDER_NAME);
}
fs.writeFileSync(
fileName,
JSON.stringify(fileContent),
{ encoding: 'utf8', flag: 'w' },
);
}
start()
.then(() => {
console.log('Finished executing script!');
})
.catch(error => {
console.error('Caught error while starting:', error);
process.exit(1);
});
|
import {
Store,
configureStore,
createListenerMiddleware,
} from '@reduxjs/toolkit';
import productsReducer from '../features/products/productSlice';
import { baseApi } from '../features/api/baseApi';
import { setupListeners } from '@reduxjs/toolkit/dist/query/react';
import { isRejectedWithValue } from '@reduxjs/toolkit';
import { createNewSession } from '../hooks/useRetrieveSession';
const refreshTokenErrorListener = createListenerMiddleware();
refreshTokenErrorListener.startListening({
predicate: () => true,
effect: async (action: any, listenerApi) => {
if (isRejectedWithValue(action) && action?.payload?.status == 403) {
listenerApi.cancelActiveListeners();
await listenerApi.delay(1000);
const newUserQuery = listenerApi.dispatch(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
baseApi.endpoints.createNewUser.initiate(),
);
await createNewSession(newUserQuery);
}
},
});
export const store: Store = configureStore({
reducer: {
products: productsReducer,
[baseApi.reducerPath]: baseApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware()
.concat(baseApi.middleware)
.prepend(refreshTokenErrorListener.middleware),
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
setupListeners(store.dispatch);
|
<template>
<div>
<!-- Button:
<div class="c-big_wrap">
<div class="c_wrap">
--type:
<d-button type="default">default</d-button>
<d-button
type="primary"
:loading="state.loading"
@click="updateLoading"
>
primary
</d-button>
<d-button
type="success"
size="large"
:loading="true"
@click="updateLoading"
>success</d-button
>
<d-button type="warning" size="large">warning</d-button>
<d-button type="danger">danger</d-button>
</div>
<div class="c_wrap">
--size:
<d-button type="primary" size="small">small</d-button>
<d-button type="primary">default</d-button>
<d-button type="primary" size="large">large</d-button>
<d-button type="success" size="small">small</d-button>
<d-button type="success">default</d-button>
<d-button type="success" size="large">large</d-button>
</div>
</div>
Modal:
<div class="c-big_wrap">
<Modal />
</div>
Space:
<div class="c-big_wrap">
<d-space align="center">
<d-button type="primary">1</d-button>
<d-button type="primary">2</d-button>
<d-button type="primary">3</d-button>
</d-space>
</div>
Message:
<div class="c-big_wrap">
<d-message type="success" content="成功" style="width: 160px" />
<div style="height: 10px"></div>
<d-button type="success" @click="openMessage('success')">
消息提示
</d-button>
<d-button type="danger" @click="openMessage('error')">消息提示</d-button>
<d-button type="primary" @click="openMessage('warning')">
消息提示
</d-button>
</div>
Input:
<div class="c-big_wrap">
<d-space direction="vertical">
<d-input
v-model="state.input"
size="large"
placeholder="请输入"
style="width: 220px"
status="warning"
tips="123"
><template #prefix>账户</template>
</d-input>
<d-input
v-model="state.input"
placeholder="请输入"
style="width: 220px"
status="success"
tips="123"
>
<template #prefix>账户:</template>
<template #suffix>+26</template>
</d-input>
<d-input
v-model="state.input"
size="small"
placeholder="请输入"
style="width: 220px"
status="error"
tips="123"
disabled
/>
<d-button
@click="() => MessagePlugin.success(state.input)"
style="width: 200px"
>
获取输入值
</d-button>
</d-space>
</div> -->
InputNumber:
<div class="c-big-wrap">
<d-input-number v-model="state.input"></d-input-number>
<d-input-password v-model="state.input"></d-input-password>
</div>
Select:
<d-select
v-model="state.selectValue"
filterable
size="large"
:options="options"
:filter="filterFn"
@select="select"
>
</d-select>
Tag:
<d-tag variant="light" size="large">灰标签</d-tag>
<d-tag theme="primary" size="medium">标签一</d-tag>
<d-tag theme="success" variant="light">标签二</d-tag>
<d-tag theme="warning" variant="light">标签三</d-tag>
<d-tag theme="danger" variant="light">标签四</d-tag>
</div>
</template>
<script setup lang="ts">
// import Modal from "@/pages/modal.vue";
import { MessagePlugin } from "../../src/index";
import { reactive } from "vue";
const state = reactive({
input: "",
selectValue: undefined,
loading: false,
});
const filterFn = (
search: string,
option: { label: string; value: string | number }
) => {
if (search === "123") return true;
};
const updateLoading = async () => {
state.loading = !state.loading;
await new Promise((resolve) => setTimeout(() => resolve(1), 3000));
state.loading = !state.loading;
};
const select = () => {
console.log("[state.selectValue] ---> ", state.selectValue);
};
const options = new Array(11).fill(1).map((val, index) => ({
label: `${new Date().getTime()}${index}`,
value: index,
}));
const openMessage = (type: any) => {
MessagePlugin[type]("测试", 5000);
};
</script>
<style lang="less" scoped>
.c-big_wrap {
padding: 20px;
}
.c_wrap {
margin: 5px 0;
display: flex;
align-items: center;
}
</style>
|
<script setup>
import draggable from "vuedraggable";
import { Icon } from '@iconify/vue';
import { useKanbanStore } from "@/store/lead";
import router from "../router";
import dateformat from "dateformat";
function dateFormat(date) {
let date1 = dateformat(date, "dd.mm.yyyy");
return date1;
}
const kanban = useKanbanStore();
const props = defineProps({
column: {
type: Object,
default: () => ({}),
},
});
const deleteTask = (taskId) => {
kanban.deleteTask(taskId);
};
const openLead = (id) => {
router.push(`/lead-details/${id}`)
}
const log = (e) => {
console.log('ads', e);
}
const finish = (e, lists) => {
console.log('ads', e, lists);
}
</script>
<template>
<div>
<!-- <pre>{{ props.column }}</pre> -->
<draggable class="dragArea list-group" @end="finish($event, props.column.tasks)" @change="log"
:list="props.column.tasks" :animation="200" ghost-class="ghost-card" :group="{ name: 'kanban' }" item-key="id">
<template #item="{ element }">
<div @click="openLead(element.uid)" :style="`border-color: ${props.column.color}`"
class="bg-white border-l-8 shadow group rounded px-3 pt-3 pb-5 mb-5 cursor-pointer">
<div class="flex justify-between items-start">
<h2 class="basis-4/5">
{{ element.name }}
</h2>
<div class="flex gap-x-1 items-center">
<button @click="deleteTask(element.id)">
<Icon icon="gg:trash" class=" h-5 w-5 text-red-500 cursor-pointer" width="26" height="26" />
</button>
</div>
</div>
<h2 class="basis-4/5">
{{ element.phone }}
</h2>
<div class="flex mt-4 justify-between items-center">
<Icon icon="mdi:clock-outline" width="20" height="20" /> <span class="text-sm">
{{ dateFormat(element.created) }} | {{
element.time.slice(0, 5) }}
</span>
<span class="bg-primary text-white py-1 px-2 rounded-md text-sm">{{
element.target
}}</span>
</div>
</div>
</template>
</draggable>
</div>
</template>
|
# Chapter 4 大数定律与中心极限定理
## 依概率收敛
设$X_1,X_2,\cdots$是一列随机变量,$X$是另一个随机变量,如果对于任意的$\varepsilon>0$,有
$$
\lim_{n\to\infty}P(|X_n-X|>\varepsilon)=0
$$
则称$\{X_n\}$**依概率收敛**于$X$,记作$X_n\overset{P}{\to}X$
设$\{X_n\},\{Y_n\}$是两列随机变量,$a,b$是常数,如果$X_n\overset{P}{\to}a,Y_n\overset{P}{\to}b$,则
- $X_n\pm Y_n\overset{P}{\to}a\pm b$
- $X_nY_n\overset{P}{\to}ab$
- $\frac{X_n}{Y_n}\overset{P}{\to}\frac{a}{b}(b\neq0)$
## 按分布收敛与弱收敛
设$X_1,X_2,\cdots$是一列随机变量,分布函数分别为$F_1(x),F_2(x),\cdots$,$X$是另一个随机变量,分布函数为$F(x)$,如果对于$F(x)$的任一连续点$x$,有
$$
\lim_{n\to\infty}F_n(x)=F(x)
$$
则称$\{F_n(x)\}$**弱收敛**于$F(x)$,记作$F_n(x)\overset{W}{\to}F(x)$, 也称$\{X_n\}$**按分布收敛**于$X$,记作$X_n\overset{L}{\to}X$
- $X_n\overset{P}{\to}X\Rightarrow X_n\overset{L}{\to}X$
- 若$c$为常数,则$X_n\overset{P}{\to}c$等价于$X_n\overset{L}{\to}c$
## 特征函数
设$X$是一个随机变量,$X$的**特征函数**定义为
$$
\varphi(t)=E(e^{itX})
$$
因为$|e^{itX}|=1$,所以$E(e^{itX})$总是存在的。
特别地,当$X$是离散型随机变量时,有
$$
\varphi(t)=\sum_{k=1}^{\infty}e^{itx_k}p_k
$$
当$X$是连续型随机变量时,有
$$
\varphi(t)=\int_{-\infty}^{\infty}e^{itx}p(x)dx
$$
- $|\varphi(t)|\leq\varphi(0)=1$
- $\varphi(-t)=\overline{\varphi(t)}$, $\overline{\varphi(t)}$是$\varphi(t)$的共轭
- 若$Y=aX+b$,则
$$
\varphi_Y(t)=e^{itb}\varphi_X(at)
$$
- 独立随机变量和的特征函数等于各自特征函数的乘积, 即
$$
\varphi_{X+Y}(t)=\varphi_X(t)\varphi_Y(t)
$$
- 若$E(X^l)$存在,则$\varphi(t)$可$l$次求导,且对于$1\leq k\leq l$,有
$$
\varphi^{(k)}(0)=i^kE(X^k)
$$
由此可得
$$
E(X)=\frac{1}{i}\varphi'(0),\quad Var(X)=-\varphi''(0)+\varphi'(0)^2
$$
- **一致连续性**: 随机变量$X$的特征函数$\varphi(t)$在$-\infty<t<\infty$上一致连续
- **非负定性**: 随机变量$X$的特征函数$\varphi(t)$是非负定的,即对于任意正整数$n$和任意$n$个实数$t_1,t_2,\cdots,t_n$以及任意$n$个复数$z_1,z_2,\cdots,z_n$,有
$$
\sum_{i=1}^{n}\sum_{j=1}^{n}\varphi(t_i-t_j)z_i\overline{z_j}\geq0
$$
### 常用分布的特征函数
设$q=1-p$
| 分布 | 分布列或密度函数 | 特征函数 |
| ---------------------------- | ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| 单点分布 | $P(X=a)=1$ | $e^{ita}$ |
| 0-1 分布 | $p_k=p^kq^{1-k},k=0,1$ | $pe^{it}+q$ |
| 二项分布$b(n,p)$ | $p_k=C_n^kp^kq^{n-k},k=0,1,\cdots,n$ | $(pe^{it}+q)^n$ |
| 泊松分布$P(\lambda)$ | $p_k=\frac{\lambda^k}{k!}e^{-\lambda},k=0,1,\cdots$ | $e^{\lambda(e^{it}-1)}$ |
| 几何分布$Ge(p)$ | $p_k=pq^{k-1},k=1,2,\cdots$ | $\frac{pe^{it}}{1-qe^{it}}$ |
| 负二项分布$Nb(r,p)$ | $p_k=C_{k-1}^{r-1}p^rq^{k-r},k=r,r+1,\cdots$ | $(\frac{pe^{it}}{1-qe^{it}})^r$ |
| 均匀分布$U(a,b)$ | $p(x)=\frac{1}{b-a},a<x<b$ | $\frac{e^{itb}-e^{ita}}{it(b-a)}$ |
| 正态分布$N(\mu,\sigma^2)$ | $p(x)=\frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$ | $\exp\{\mu it-\frac{1}{2}\sigma^2t^2\}$ |
| 指数分布$Exp(\lambda)$ | $p(x)=\lambda e^{-\lambda x},x>0$ | $\frac{\lambda}{\lambda-it}$ |
| 伽马分布$Ga(\alpha,\lambda)$ | $p(x)=\frac{\lambda^\alpha}{\Gamma(\alpha)}x^{\alpha-1}e^{-\lambda x},x>0$ | $(\frac{\lambda}{\lambda-it})^\alpha$ |
| $\chi^2(n)$分布 | $p(x)=\frac{1}{2^{n/2}\Gamma(n/2)}x^{n/2-1}e^{-x/2},x>0$ | $(1-2it)^{-n/2}$ |
| 贝塔分布$Be(\alpha,\beta)$ | $p(x)=\frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)}x^{\alpha-1}(1-x)^{\beta-1},0<x<1$ | $\frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)}\sum_{k=0}^{\infty}\frac{(it)^k\Gamma(\alpha+k)}{k!\Gamma(\alpha+\beta+k)\Gamma(k+1)}$ |
| 柯西分布$Cau(0,1)$ | $p(x)=\frac{1}{\pi(1+x^2)}$ | $e^{-\|t\|}$ |
### 逆转公式
设$X$是一个随机变量,其分布函数和特征函数分别为$F(x)$和$\varphi(t)$,则对$F(x)$的任意两个连续点$x_1<x_2$,有
$$
F(x_2)-F(x_1)=\lim_{T\to\infty}\frac{1}{2\pi}\int_{-T}^{T}\frac{e^{-itx_1}-e^{-itx_2}}{it}\varphi(t)dt
$$
- **唯一性定理**: 随机变量的分布函数由其特征函数唯一确定
- 若$X$为连续型随机变量,其密度函数为$p(x)$,特征函数为$\varphi(t)$,如果$\int_{-\infty}^{\infty}|\varphi(t)|dt<\infty$,则
$$
p(x)=\frac{1}{2\pi}\int_{-\infty}^{\infty}e^{-itx}\varphi(t)dt
$$
- 分布函数序列$\{F_n(x)\}$弱收敛于分布函数$F(x)$的充要条件是$\{F_n(x)\}$的特征函数序列$\{\varphi_n(t)\}$收敛于$F(x)$的特征函数$\varphi(t)$
## 大数定律
### 伯努利(Bernoulli)大数定律
设$S_n$为$n$重伯努利试验中事件$A$发生的次数,$p$为事件$A$在每次试验中发生的概率,则对于任意$\varepsilon>0$,有
$$
\lim_{n\to\infty}P\left(\left|\frac{S_n}{n}-p\right|<\varepsilon\right)=1
$$
### 大数定律的一般形式
设有一随机变量序列$\{X_n\}$,若其满足
$$
\lim_{n\to\infty}P\left(\left|\frac{1}{n}\sum_{i=1}^{n}X_i-\frac{1}{n}\sum_{i=1}^{n}E(X_i)\right|<\varepsilon\right)=1
$$
则称$\{X_n\}$满足**大数定律**
### 切比雪夫(Chebyshev)大数定律
设$\{X_n\}$是一列两两不相关的随机变量序列,每个$X_i$的方差都存在,且有共同的上界, 即$Var(X_i)\leq c(i=1,2,\cdots)$,则$\{X_n\}$满足大数定律
### 马尔可夫(Markov)大数定律
设$\{X_n\}$是一随机变量序列,若有
$$
\lim_{n\to\infty}\frac{1}{n^2}Var\left(\sum_{i=1}^{n}X_i\right)=0
$$
则$\{X_n\}$满足大数定律
### 辛钦(Sheinch)大数定律
设$\{X_n\}$是一独立同分布的随机变量序列,若$X_i$的数学期望存在,则$\{X_n\}$满足大数定律
## 中心极限定理
### 林德伯格-列维(Lindeberg-Levy)中心极限定理
设$\{X_n\}$是一列独立同分布的随机变量序列,其数学期望和方差都存在,记$E(X_i)=\mu,Var(X_i)=\sigma^2>0$,若记
$$
Y_n^*=\frac{X_1+X_2+\cdots+X_n-n\mu}{\sigma\sqrt{n}}
$$
则对于任意$y\in R$,有
$$
\lim_{n\to\infty}P(Y_n^*\leq y)=\Phi(y)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{y}e^{-\frac{t^2}{2}}dt
$$
### 棣莫弗-拉普拉斯(De Moivre-Laplace)中心极限定理
设$S_n$为$n$重伯努利试验中事件$A$发生的次数,$p$为事件$A$在每次试验中发生的概率,若记
$$
Y_n^*=\frac{S_n-np}{\sqrt{npq}}
$$
则对于任意$y\in R$,有
$$
\lim_{n\to\infty}P(Y_n^*\leq y)=\Phi(y)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{y}e^{-\frac{t^2}{2}}dt
$$
### 林德伯格条件
设$\{X_n\}$是一相互独立的连续随机变量序列,具有有限的数学期望和方差,记$E(X_i)=\mu_i,Var(X_i)=\sigma_i^2$,令$Y_n=\sum_{i=1}^{n}X_i$,有
$$
E(Y_n)=\mu_1+\mu_2+\cdots+\mu_n
$$
$$
\sigma(Y_n)=\sqrt{Var(Y_n)}=\sqrt{\sigma_1^2+\sigma_2^2+\cdots+\sigma_n^2}
$$
记$\sigma(Y_n)=B_n$,则$Y_n$的标准化变量为
$$
Y_n^*=\frac{Y_n-E(Y_n)}{B_n}=\sum_{i=1}^{n}\frac{X_i-\mu_i}{B_n}
$$
要求$Y_n^*$中各项"均匀的小", 即对任意$\tau>0$,要求
$$
\lim_{n\to\infty}P\left(\max_{1\leq i\leq n}\left|X_i-\mu_i\right|>\tau B_n\right)=0
$$
因此
$$
P\left(\max_{1\leq i\leq n}\left|X_i-\mu_i\right|>\tau B_n\right)=P\left(\bigcup_{i=1}^{n}\left\{|X_i-\mu_i|>\tau B_n\right\}\right)\leq\sum_{i=1}^{n}P\left(|X_i-\mu_i|>\tau B_n\right)
$$
若设$X_i$为连续随机变量,其密度函数为$p_i(x)$,则
$$
RHS=\sum_{i=1}^{n}\int_{|x-\mu_i|>\tau B_n}p_i(x)dx\leq\frac{1}{\tau^2B_n^2}\sum_{i=1}^{n}\int_{|x-\mu_i|>\tau B_n}(x-\mu_i)^2p_i(x)dx
$$
因此只要对任意$\tau>0$,有
$$
\lim_{n\to\infty}\frac{1}{\tau^2B_n^2}\sum_{i=1}^{n}\int_{|x-\mu_i|>\tau B_n}(x-\mu_i)^2p_i(x)dx=0
$$
就可以保证$Y_n^*$"均匀的小",这就是**林德伯格条件**
### 林德伯格(Lindeberg)中心极限定理
设独立随机变量序列$\{X_n\}$满足**林德伯格条件**,则对于任意$x$,有
$$
\lim_{n\to\infty}P\left(\frac{1}{B_n}\sum_{i=1}^{n}(X_i-\mu_i)\leq x\right)=\Phi(x)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{x}e^{-\frac{t^2}{2}}dt
$$
### 李雅普诺夫(Lyapunov)中心极限定理
设$\{X_n\}$是一独立随机变量序列,若存在常数$\delta>0$,满足
$$
\lim_{n\to\infty}\frac{1}{B_n^{2+\delta}}\sum_{i=1}^{n}E\left(|X_i-\mu_i|^{2+\delta}\right)=0
$$
则对于任意$x$,有
$$
\lim_{n\to\infty}P\left(\frac{1}{B_n}\sum_{i=1}^{n}(X_i-\mu_i)\leq x\right)=\Phi(x)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{x}e^{-\frac{t^2}{2}}dt
$$
|
import Avatar from "@mui/material/Avatar";
import Button from "@mui/material/Button";
import CssBaseline from "@mui/material/CssBaseline";
import TextField from "@mui/material/TextField";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import Container from "@mui/material/Container";
import { useCallback, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useApi } from "../../api/axiosInstance";
import { Dialog } from "@mui/material";
const Login = () => {
const [formData, setFormData] = useState({
login: "",
senha: "",
});
const [openDialog, setOpendialog] = useState(false)
const navigate = useNavigate();
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
};
const handleSubmit = useCallback(
async (e) => {
e.preventDefault();
try {
const resposta = await useApi.post("/usuarios/login", formData);
console.log(resposta);
localStorage.setItem("usuario", JSON.stringify(resposta));
navigate("/listaPedidos");
} catch (error) {
console.error("Erro:", error);
setOpendialog(true)
}
},
[formData, navigate]
);
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<Dialog className="dialog" open={openDialog} onClose={() => setOpendialog(false)}>
<Box sx={{height: "200px", width: "200px", display: "flex",flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center"}}>
<Typography sx={{color: "red", fontSize: 30}}>LOGIN INVÁLIDO</Typography>
<Typography>Revise se as informações estão corretas</Typography>
</Box>
</Dialog>
<Box
sx={{
marginTop: 8,
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
<Avatar sx={{ m: 1, bgcolor: "secondary.main" }}></Avatar>
<Typography component="h1" variant="h2">
Sign in
</Typography>
<Box
component="form"
onSubmit={handleSubmit}
noValidate
sx={{ mt: 1 }}
>
<TextField
margin="normal"
required
fullWidth
label="Nome de Usuário"
name="login"
value={formData.login}
autoFocus
onChange={handleChange}
/>
<TextField
margin="normal"
required
fullWidth
name="senha"
label="Senha"
type="password"
value={formData.senha}
onChange={handleChange}
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
LOGAR
</Button>
<Button
component={Link}
to="/cadastro"
type="button"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Cadastrar
</Button>
</Box>
</Box>
</Container>
);
};
export default Login;
|
import '@rainbow-me/rainbowkit/styles.css';
import 'normalize.css';
import 'styles/fonts-maru.css';
import 'styles/global.css';
import {
CategoryScale,
Chart,
LinearScale,
LineElement,
PointElement,
Tooltip,
} from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import { ApplicationProviders } from 'components/ApplicationProviders';
import { AppWrapper } from 'components/layouts/AppWrapper';
import { ConfigProvider } from 'hooks/useConfig';
import { isSupportedToken, SupportedToken } from 'lib/config';
import { AppProps } from 'next/app';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
Chart.register(
CategoryScale,
LinearScale,
LineElement,
PointElement,
Tooltip,
ChartDataLabels,
);
const TOKEN_FROM_PATH_REGEXP = /\/tokens\/([^/]+)/;
function tokenFromPath(path: string): SupportedToken {
const match = path.match(TOKEN_FROM_PATH_REGEXP);
if (match && isSupportedToken(match[1])) {
return match[1];
}
// The "default network" (e.g. on the home page)
return 'paprMeme';
}
const ErrorBanners = dynamic(() =>
import('components/ErrorBanners').then((mod) => mod.ErrorBanners),
);
const Footer = dynamic(() =>
import('components/Footer').then((mod) => mod.Footer),
);
const Header = dynamic(() =>
import('components/Header').then((mod) => mod.Header),
);
export default function App({ Component, pageProps }: AppProps) {
const { asPath } = useRouter();
const [token, setToken] = useState<SupportedToken>(
tokenFromPath(asPath) as SupportedToken,
);
useEffect(() => {
const newPath = tokenFromPath(asPath);
if (newPath !== token) {
setToken(newPath as SupportedToken);
}
}, [asPath, token]);
return (
<ConfigProvider token={token}>
<ApplicationProviders>
<AppWrapper>
<ErrorBanners />
<Header />
<Component {...pageProps} />
<Footer />
</AppWrapper>
</ApplicationProviders>
</ConfigProvider>
);
}
|
#!/usr/bin/env python
"""
Setcontext.
######################################################################
# @author : Linus Fernandes (linusfernandes at gmail dot com)
# @file : setcontext
# @created : Sunday Nov 19, 2023 20:19:44 IST
# @description :
# -*- coding: utf-8 -*-'
######################################################################
"""
# SuperFastPython.com
# example of setting the process start context
from multiprocessing import get_context
from concurrent.futures import ProcessPoolExecutor
def main():
"""entry point"""
# create a start process context
context = get_context("spawn")
# create a process pool
with ProcessPoolExecutor(mp_context=context) as executor:
# report the context used
print(executor._mp_context) # pylint: disable=protected-access
if __name__ == "__main__":
main()
|
import sys
import sounddevice as sd
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
from scipy.io.wavfile import write
import numpy as np
class AudioRecorder(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.recording = False
self.fs = 8000 # Sample rate
self.recorded_data = []
def initUI(self):
self.setWindowTitle('Диктофон')
self.setGeometry(100, 100, 200, 100)
layout = QVBoxLayout()
self.btn_record = QPushButton('Запись', self)
self.btn_record.clicked.connect(self.toggle_recording)
layout.addWidget(self.btn_record)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
def toggle_recording(self):
if self.recording:
self.stop_recording()
else:
self.start_recording()
def start_recording(self):
self.recorded_data = []
self.recording = True
self.btn_record.setText('Стоп')
print("Запись началась...")
# Начинаем асинхронную запись
self.stream = sd.InputStream(callback=self.audio_callback, samplerate=self.fs, channels=1, dtype='int16')
self.stream.start()
def stop_recording(self):
if self.recording:
self.recording = False
self.btn_record.setText('Запись')
print("Запись остановлена...")
self.stream.stop()
self.save_recording()
def audio_callback(self, indata, frames, time, status):
self.recorded_data.append(indata.copy())
def save_recording(self):
if self.recorded_data:
recording_array = np.concatenate(self.recorded_data, axis=0)
write('output.wav', self.fs, recording_array)
print("Аудио сохранено как output.wav")
def main():
app = QApplication(sys.argv)
ex = AudioRecorder()
ex.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
|
import React, { Component } from 'react';
import { StyleSheet, Text, View, ActivityIndicator, Image, StatusBar } from 'react-native';
import Weather from "./Weather";
const API_KEY = "f3d19cbb74190717e951f9f88c778e93";
export default class App extends Component {
state = {
isLoaded: false,
err: null,
temperature: null,
name: null
};
componentDidMount() {
navigator.geolocation.getCurrentPosition(
position => {
this._getWeather(position.coords.latitude, position.coords.longitude);
},
err => {
this.setState({
err: err
})
}
)
}
_getWeather = (lat, lon) => {
fetch(`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&APPID=${API_KEY}`)
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({
temperature: json.main.temp,
name: json.weather[0].main,
isLoaded: true
})
})
}
render() {
const { isLoaded, err, temperature, name } = this.state;
return (
<View style={styles.container}>
<StatusBar hidden={true}>
</StatusBar>
{/* conditional statement */}
{isLoaded ? <Weather weatherName={name} temp={Math.floor(temperature * 9/5 - 459.67)} /> : (
<View style={styles.loading}>
<Text style={styles.loadingText}> Please wait, Getting the Weather </Text>
{/* if there is an error show text or else show null */}
{err ? <Text style={styles.errorText}>{err}</Text> : null}
</View>
)}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff'
},
errorText: {
color: "red",
backgroundColor: "transparent"
},
loading: {
flex: 1,
backgroundColor: '#1B1D26',
justifyContent: 'flex-end',
paddingLeft: 45,
paddingRight: 40
},
loadingText: {
fontSize: 20,
marginBottom: 350,
color: "white"
}
});
|
/* eslint-disable react-hooks/exhaustive-deps */
// import spinner from '@/assets/spinner.svg'
import useRefugio from "../../hooks/useRefugio";
import TopBar from "../../components/TopBar";
import Sidebar from "../../components/Sidebar";
import { MapaContainer } from "./components/MapaContainer";
import { Link } from "react-router-dom";
import { useEffect } from "react";
const Mapa = () => {
const { refugios } = useRefugio();
useEffect(() => {
document.title = "Mapa";
}, []);
return (
<main className="min-h-screen bg-[#CCC4BB] flex">
<Sidebar />
<div className="flex flex-col w-full h-full bg-[#CCC4BB]">
<div className="">
<TopBar />
</div>
<div className="flex flex-col items-center lg:flex-row gap-6 justify-center min-h-screen lg:h-5/6">
<div className="md:w-8/12 flex flex-col lg:h-screen gap-6 ">
<div className="grid gap-1 pr-8 pl-4">
<h2 className="font-extrabold text-3xl pt-8 pl-7 mb-2 ">
Refugios
</h2>
<p className="px-7 text-sm">
Encuentra un refugio cerca de tu zona, puedes solicitar hacer
transito, adoptar un animal o colaborar con un donativo{" "}
</p>
</div>
<div className="hidden lg:flex md:flex-col mx-3 overflow-auto gap-5">
{refugios.map((refugio) => (
<div
key={refugio._id}
className=" w-[26rem] gap-3 pb-4 h-max bg-white rounded-lg flex mb-3"
>
<img
className="rounded-bl-lg rounded-tl-lg"
src={refugio.avatar}
width={144}
height={144}
alt="1"
/>
<div className="grid justify-items-center">
<div className="grid ">
<h3 className="text-center text-xl mb-3 font-bold capitalize">
{refugio.razon_social}
</h3>
<p className="">
Refugio de animales dirigido por veterinarios.
</p>
<div className="">
<p>
Direccion:{" "}
{`${refugio.direccion}, ${refugio.provincia}`}
</p>
<p>Telefono: {refugio.whatsApp}</p>
</div>
</div>
<div className="flex w-full">
<Link
to={`https://wa.me/+5491131496472?text=Hola%20me%20gustaría%20saber%20más%20sobre%20${refugio.whatsApp}`}
target="_blank"
className="w-1/2 bg-[#FFB800] rounded-lg mx-5 text-white font-bold text-xl p-2 text-center "
>
Contactar
</Link>
</div>
</div>
</div>
))}
</div>
</div>
<div className="w-full h-[50rem] md:w-full md:h-full">
<MapaContainer refu={refugios}/>
</div>
<div className="lg:hidden mx-3 overflow-auto gap-5">
{refugios.map((refugio) => (
<div
key={refugio._id}
className=" w-[26rem] gap-3 pb-4 h-max bg-white rounded-lg flex mb-3"
>
<img
className="rounded-bl-lg rounded-tl-lg"
src={refugio.avatar}
width={144}
height={144}
alt="1"
/>
<div className="grid justify-items-center">
<div className="grid ">
<h3 className="text-center text-xl mb-3 font-bold capitalize">
{refugio.razon_social}
</h3>
<p className="">
Refugio de animales dirigido por veterinarios.
</p>
<div className="">
<p>
Direccion:{" "}
{`${refugio.direccion}, ${refugio.provincia}`}
</p>
<p>Telefono: {refugio.whatsApp}</p>
</div>
</div>
<div className="flex w-full">
<Link
to={`https://wa.me/+5491131496472?text=Hola%20me%20gustaría%20saber%20más%20sobre%20${refugio.whatsApp}`}
target="_blank"
className="w-1/2 bg-[#FFB800] rounded-lg mx-5 text-white font-bold text-xl p-2 text-center "
>
Contactar
</Link>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</main>
);
};
export default Mapa;
|
#include<iostream>
using namespace std;
// class A
// {
// int x;
// public:
// void setX(int i) {x = i;}
// void print() { cout << x; }
// };
// class B: virtual public A
// {
// public:
// B() { setX(10); }
// };
// class C: virtual public A
// {
// public:
// C() { setX(20); }
// };
// class D: public B, public C {
// };
// C++ program to implement
// Multilevel Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// first sub_class derived from class vehicle
class fourWheeler : public Vehicle {
public:
fourWheeler()
{
cout << "Objects with 4 wheels are vehicles\n";
}
};
// sub class derived from the derived base class fourWheeler
class Car : public fourWheeler {
public:
Car() { cout << "Car has 4 Wheels\n"; }
};
|
/**
* \file pow.h
* Power Class
*
**/
#ifndef CSYMPY_POW_H
#define CSYMPY_POW_H
#include "basic.h"
#include "dict.h"
#include "mul.h"
#include "integer.h"
namespace CSymPy {
class Pow : public Basic {
public: // TODO: make this private
RCP<const Basic> base_, exp_; //! base^exp
public:
//! Pow Constructor
Pow(const RCP<const Basic> &base, const RCP<const Basic> &exp);
//! \return Size of the hash
virtual std::size_t __hash__() const;
/*! Equality comparator
* \param o - Object to be compared with
* \return whether the 2 objects are equal
* */
virtual bool __eq__(const Basic &o) const;
virtual int compare(const Basic &o) const;
//! \return stringify version
virtual std::string __str__() const;
//! \return `true` if canonical
bool is_canonical(const RCP<const Basic> &base,
const RCP<const Basic> &exp);
//! \return `base` of `base^exp`
inline RCP<const Basic> get_base() const { return base_; }
//! \return `exp` of `base^exp`
inline RCP<const Basic> get_exp() const { return exp_; }
//! Differentiate w.r.t Symbol `x`
virtual RCP<const Basic> diff(const RCP<const Symbol> &x) const;
virtual RCP<const Basic> subs(const map_basic_basic &subs_dict) const;
};
//! \return Pow from `a` and `b`
RCP<const Basic> pow(const RCP<const Basic> &a,
const RCP<const Basic> &b);
void multinomial_coefficients(int m, int n, map_vec_int &r);
//! Expand the power expression
RCP<const Basic> pow_expand(const RCP<const Pow> &self);
//! \return square root of `x`
inline RCP<const Basic> sqrt(const RCP<const Basic> &x) {
return pow(x, div(one, integer(2)));
}
} // CSymPy
#endif
|
#include "main.h"
/**
* factorial - This function returns factorial of a given number
* @n: number passed into th function
*
* Return: factorial of a number
* error: return -1 when n is lower than 0
*/
int factorial(int n)
{
int fact = n;
if (n < 0)
{
return (-1);
}
else if (n >= 0 && n <= 1)
{
return (1);
}
fact *= factorial(n - 1);
return (fact);
}
|
<?php
declare(strict_types=1);
namespace CultuurNet\UDB3\Http\Event;
use Broadway\CommandHandling\CommandBus;
use CultuurNet\UDB3\Event\Commands\UpdateMajorInfo;
use CultuurNet\UDB3\Http\Deserializer\Event\MajorInfoJSONDeserializer;
use CultuurNet\UDB3\Http\Request\RouteParameters;
use CultuurNet\UDB3\Http\Response\NoContentResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
class UpdateMajorInfoRequestHandler implements RequestHandlerInterface
{
private CommandBus $commandBus;
private MajorInfoJSONDeserializer $majorInfoDeserializer;
public function __construct(CommandBus $commandBus)
{
$this->commandBus = $commandBus;
$this->majorInfoDeserializer = new MajorInfoJSONDeserializer();
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
$routeParameters = new RouteParameters($request);
$eventId = $routeParameters->getEventId();
$majorInfo = $this->majorInfoDeserializer->deserialize((string) $request->getBody());
$this->commandBus->dispatch(
new UpdateMajorInfo(
$eventId,
$majorInfo->getTitle(),
$majorInfo->getType(),
$majorInfo->getLocation(),
$majorInfo->getCalendar(),
$majorInfo->getTheme()
)
);
return new NoContentResponse();
}
}
|
/*
Copyright (c) 2023 iText Group NV
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://itextpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using iText.
*/
package com.itextpdf.pdfcop.text;
import com.itextpdf.antlr.PdfStreamLexer;
import com.itextpdf.antlr.PdfStreamParser;
import com.itextpdf.pdfcop.ThrowingErrorListener;
import java.util.Arrays;
import java.util.Collection;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith( Parameterized.class )
public class TextObjectTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Parameterized.Parameters
public static Collection data() {
return Arrays.asList(new Object[][] {
{ "BT\n" +
"/Content <</MCID 1 >> BDC\n" +
"0 0 0 rg\n" +
"/RelativeColorimetric ri\n" +
"/TT0 1 Tf\n" +
"11 0 0 11 261.285 715.438 Tm\n" +
"(Our Privacy Notice) Tj\n" +
"EMC\n" +
"ET", true, 3},
{ "BT\n" +
"10 0 0 10 64.417 693.424 Tm\n" +
"ET", true, 3},
{ "BT (Hello World) Tj ET", true, 3 },
{ "BT\n" +
"0 0 0 rg\n" +
"/GS0 gs\n" +
"/F1 -12 Tf\n" +
"270 142.0645 Td\n" +
"(KERKSTRAAT) Tj\n" +
"109.8164 0 Td\n" +
"(108) Tj\n" +
"-109.8164 14.584 Td\n" +
"(9050) Tj\n" +
"34.7344 0 Td\n" +
"(Gentbrugge) Tj\n" +
"ET", true, 13 },
{ "BT\n" +
"0.1019607 0.3803921 0.6627450 RG\n" +
"0.75 w\n" +
"[] 0. d\n" +
"2 J\n" +
"0 j\n" +
"7.5 M\n" +
"0.1019607 0.3803921 0.6627450 rg\n" +
"1. 0. 0. 1. 390.25 -442.600 Tm\n" +
"/F2 10.5 Tf\n" +
"1. 0. 0. 1. 412.949 366.149 Tm\n" +
"(FREQUENT) Tj\n" +
"ET", true, 9 },
{ "BT\n" +
"/F1 8 Tf\n" +
"1. 0. 0. 1. 399.25 810.25 Tm\n" +
"(Security nb: 2 - Ticket: 603267495996201) Tj\n" +
"ET", true, 5 },
{ "BT ET", true, 2 }
});
}
private String syntaxToCheck;
private boolean pass;
private int expectedChildCount;
public TextObjectTest(String syntaxToCheck, boolean pass, int childCount) {
this.syntaxToCheck = syntaxToCheck;
this.pass = pass;
this.expectedChildCount = childCount;
}
@Test
public void test() {
if (! this.pass) {
this.expectedException.expect(ParseCancellationException.class);
}
PdfStreamLexer streamLexer = new PdfStreamLexer(CharStreams.fromString(this.syntaxToCheck));
streamLexer.removeErrorListeners();
streamLexer.addErrorListener(ThrowingErrorListener.INSTANCE);
CommonTokenStream tokens = new CommonTokenStream(streamLexer);
PdfStreamParser streamParser = new PdfStreamParser(tokens);
streamParser.removeErrorListeners();
streamParser.addErrorListener(ThrowingErrorListener.INSTANCE);
PdfStreamParser.TextObjectContext context = streamParser.textObject();
int actualChildCount = context.getChildCount();
Assert.assertEquals(this.expectedChildCount, actualChildCount);
}
}
|
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
class AdminPage extends StatefulWidget {
const AdminPage({Key? key}) : super(key: key);
@override
State<AdminPage> createState() => _AdminPageState();
}
class _AdminPageState extends State<AdminPage> {
final _formKey = GlobalKey<FormState>();
final _imageUrlController = TextEditingController();
final _modelController = TextEditingController();
final _priceController = TextEditingController();
final _detailsController = TextEditingController();
@override
void initState() {
super.initState();
_checkIfAdmin();
}
void _checkIfAdmin() async {
// TODO: Check if the current user has admin privileges
// ...(Retrieve admin status from user data if applicable)
}
// Add a bike
void _addBike() async {
if (_formKey.currentState!.validate()) {
// 1. Get new bike data from form fields
String imageUrl = _imageUrlController.text;
String model = _modelController.text;
int price = int.parse(_priceController.text);
String details = _detailsController.text;
// 2. Generate a unique key for the new bike
String bikeId = FirebaseDatabase.instance.ref('bikes').push().key!;
// 3. Upload the image (consider using Firebase Storage)
// ...
// 4. Create a Map with the bike data
Map<String, dynamic> bikeData = {
'imageURL': imageUrl,
'model': model,
'price': price,
'details': details,
'available': true
};
// 5. Add new bike document to the 'bikes' collection
await FirebaseDatabase.instance.ref('bikes').child(bikeId).set(bikeData);
// Reset the form fields after submission
_resetFormFields();
}
}
// Delete a bike
void _deleteBike(String bikeId) async {
// 1. Show a confirmation dialog
bool? confirmed = await showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('Confirm Delete'),
content: Text('Are you sure you want to delete this bike?'),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: Text('No')),
TextButton(
onPressed: () => Navigator.of(ctx).pop(true),
child: Text('Yes')),
],
),
);
// 2. If confirmed, delete the bike document
if (confirmed ?? false) {
await FirebaseDatabase.instance.ref('bikes').child(bikeId).remove();
}
}
void _resetFormFields() {
_imageUrlController.clear();
_modelController.clear();
_priceController.clear();
_detailsController.clear();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Admin Panel'),
actions: [
IconButton(
icon: Icon(Icons.logout),
onPressed: () async {
await FirebaseAuth.instance.signOut();
// TODO: Navigate back to the login screen
},
),
],
),
body: SingleChildScrollView(
child: Column(
children: [
_buildBikeForm(),
SizedBox(height: 20),
_buildBikeList(),
],
),
),
);
}
// Form to add a new bike
Widget _buildBikeForm() {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey, // Link the form key
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Add New Bike", style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
SizedBox(height: 10),
TextFormField(controller: _imageUrlController, decoration: InputDecoration(labelText: 'Image URL')),
// ...(Other form fields)
ElevatedButton(
onPressed: () => _addBike(),
child: Text('Add Bike'),
),
],
),
),
);
} // ..._buildBikeForm(), _buildBikeList()
}
|
import React from "react"
import {
AppProvider,
Page,
Stack,
Button,
Modal,
Form,
FormLayout,
TextField,
TextContainer
} from "@shopify/polaris";
class EmployeeEdit extends React.Component {
constructor(props) {
super(props);
this.state = {
name: this.props.employee.name,
job_title: this.props.employee.job_title,
description: this.props.employee.description,
profile_url: this.props.employee.profile_url,
save_loading: false,
save_disabled: true,
valid_img: false,
name_error: "",
description_error: "",
img_error: "",
deleting: false,
delete_loading: false,
};
this.handleSubmit = this.handleSubmit.bind(this);
this.closeModal = this.closeModal.bind(this);
this.openModal = this.openModal.bind(this);
this.deleteEmployee = this.deleteEmployee.bind(this);
this.goBack = this.goBack.bind(this);
this.processSubmit = this.processSubmit.bind(this);
this.checkForErrors = this.checkForErrors.bind(this);
}
componentDidMount() {
this.props.fetchEmployee(this.props.employee.id);
}
handleChange(name, value) {
if (name === "name" && this.state.name_error.length > 0) {
this.setState({ name_error: "" })
} else if (name === "description" && this.state.description_error.length > 0) {
this.setState({ description_error: "" })
}
this.setState({ save_disabled: false });
let state = this.state;
state[name] = value;
this.setState({ state });
}
goBack() {
this.props.history.push("/");
}
checkForErrors() {
if (this.state.name.length < 1) {
this.setState({ name_error: "Name is required" });
const elmnt = document.getElementById("name-ele");
elmnt.scrollIntoView({ behavior: "smooth", block: "center" });
return true;
} else if (this.state.description.length < 5) {
const elmnt = document.getElementById("description-ele");
elmnt.scrollIntoView({ behavior: "smooth", block: "center" });
this.setState({ description_error: "Description must be at least 5 characters" });
return true;
} else if (this.state.valid_img === false) {
const elmnt = document.getElementById("img-url-ele");
elmnt.scrollIntoView({ behavior: "smooth", block: "center" });
this.setState({ img_error: "Valid image url is required" });
return true;
} else {
return false;
}
}
closeModal() {
this.setState({ deleting: false });
}
openModal() {
this.setState({ deleting: true });
}
deleteEmployee() {
this.closeModal();
this.setState({ save_loading: true });
this.setState({ delete_loading: true });
this.props.deleteEmployee(this.props.employee.id).then(data => this.props.history.push("/"));
}
handleSubmit(e) {
e.preventDefault();
if (this.checkForErrors() === false) {
this.setState({ save_loading: true });
this.setState({ delete_loading: true });
let employeeUpdated = {
id: this.props.employee.id,
name: this.state.name,
job_title: this.state.job_title,
description: this.state.description,
profile_url: this.state.profile_url,
};
this.props.updateEmployee(employeeUpdated)
.then(data => this.processSubmit(data));
}
}
processSubmit(data) {
if ('error' in data) {
this.setState({ save_loading: false });
this.setState({ delete_loading: false });
this.setState({ name_error: data.error });
const elmnt = document.getElementById("name-ele");
elmnt.scrollIntoView({ behavior: "smooth", block: "center" });
} else {
this.props.history.push("/")
}
}
render() {
let name = '';
if (this.props.employee !== undefined) {
name = this.props.employee.name;
}
const {
deleting,
save_loading,
save_disabled,
delete_loading,
} = this.state;
const title = `${name}'s Profile`;
const delete_question = `Are you sure you want to delete ${name}?`;
const delete_subtitle = `Doing so will delete their page and all of their pick reviews. This cannot be undone.`
return (
<AppProvider>
<br/><br/>
<Page
title={title}
breadcrumbs={[{ content: "Back", onAction: this.goBack }]}
>
<Form onSubmit={this.handleSubmit}>
<FormLayout>
<Stack>
<div>
<TextField
value={this.state.name}
onChange={this.handleChange.bind(this, "name")}
label="Name"
type="text"
id="name-ele"
maxLength={24}
fullWidth
error={this.state.name_error}
/>
<br />
<TextField
value={this.state.job_title}
onChange={this.handleChange.bind(this, "job_title")}
label="Job Title"
type="text"
maxLength={24}
/>
<br />
<TextField
id="description-ele"
value={this.state.description}
onChange={this.handleChange.bind(this, "description")}
label="Description"
multiline={6}
maxLength={500}
showCharacterCount={true}
error={this.state.description_error}
/>
<br />
<TextField
id="img-url-ele"
value={this.state.profile_url}
onChange={this.handleChange.bind(this, "profile_url")}
label="Profile Image URL"
maxLength={300}
error={this.state.img_error}
helpText={
<span>
Upload images to Shopify Files (Settings/Files) and
paste image's URL here
</span>
}
/>
</div>
<img
src={this.state.profile_url}
onLoad={(e) => {
if (e.target.src !== "https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png") {
this.setState({ img_error: "" });
this.setState({ valid_img: true })
}
}}
onError={(e) => {
this.setState({ valid_img: false });
e.target.onerror = null;
e.target.src =
"https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png";
}}
style={{ height: "320px", padding: "20px" }}
/>
</Stack>
<Stack>
<Button
primary={true}
loading={save_loading}
disabled={save_disabled}
submit
>
Save
</Button>
<Button
destructive={true}
onClick={() => this.openModal()}
loading={delete_loading}
>
Delete
</Button>
</Stack>
</FormLayout>
</Form>
<Modal
open={deleting}
onClose={this.closeModal}
title={delete_question}
>
<Modal.Section>
<TextContainer>
<p>
{delete_subtitle}
</p>
</TextContainer>
<br/><hr/><br/>
<Stack>
<Button onClick={() => this.closeModal()}>Cancel</Button>
<Button
destructive={true}
onClick={() => this.deleteEmployee()}
>
Delete
</Button>
</Stack>
</Modal.Section>
</Modal>
</Page>
</AppProvider>
);
}
}
export default EmployeeEdit;
|
<template>
<div>
<div class='page-wrapper'>
<div class="page-header d-print-none">
<div class="container-xl">
<div class="row g-2 align-items-center">
<div class="col d-flex">
<TablerBreadCrumb/>
</div>
</div>
</div>
</div>
</div>
<div class='page-body'>
<div class='container-xl'>
<div class='row row-deck row-cards'>
<div class='col-12'>
<div class='card'>
<div class='card-header'>
<h3 class='card-title' v-text='data.source + " - " + data.layer + " - " + data.name'/>
<div class='ms-auto btn-list'>
<IconRefresh @click='refresh' class='cursor-pointer' size='32'/>
</div>
</div>
<TablerLoading v-if='loading.history' :desc='`Loading Job History`'/>
<template v-else>
<h2 class='subheader mx-3 my-3'>Stats History</h2>
<TablerLoading v-if='loading.history' desc='Loading Stats'/>
<template v-else>
<div class='card-body'>
<LineChart class='w-100' style='height: 200px' :data='chart' :options='{
"scales": {
"xAxis": {
"type": "time",
"time": {
"unit": "day"
},
"distribution": "linear"
},
"yAxis": {
"ticks": {
"beginAtZero": true
}
}
}
}'/>
</div>
</template>
<h2 class='subheader mx-3 my-3'>Job History</h2>
<table class="table table-hover table-vcenter card-table">
<thead>
<tr>
<th>Status</th>
<th>Job ID</th>
<th>Updated</th>
<th>Attributes</th>
</tr>
</thead>
<tbody>
<tr :key='job.id' v-for='job in computedPage'>
<td>
<Status :status='job.status'/>
</td>
<td v-text='job.id'/>
<td>
<span v-text='fmt(job.created)'></span>
</td>
<td>
<div class='d-flex'>
<div class='ms-auto'>
<IconDownload v-if='job.output.output' v-on:click.stop.prevent='datapls(job.id)' class='cursor-pointer' size='32'/>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<TableFooter :limit='paging.limit' :total='history.jobs.length' @page='paging.page = $event'/>
</template>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import {
TablerBreadCrumb,
TablerLoading,
} from '@tak-ps/vue-tabler';
import TableFooter from './util/TableFooter.vue';
import Status from './util/Status.vue';
import {
IconRefresh,
IconDownload
} from '@tabler/icons-vue';
import { Line as LineChart } from 'vue-chartjs';
import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, LinearScale, TimeScale, PointElement, LineElement, CategoryScale } from 'chart.js'
import moment from 'moment-timezone';
ChartJS.register(Title, Tooltip, Legend, BarElement, LinearScale, TimeScale, PointElement, LineElement, CategoryScale)
import 'chartjs-adapter-date-fns';
export default {
name: 'History',
props: ['dataid'],
data: function() {
return {
tz: moment.tz.guess(),
loading: {
history: true
},
paging: {
limit: 10,
page: 0
},
colours: [ /* Thanks for the colours! https://github.com/johannesbjork/LaCroixColoR */ ],
chart: {
datasets: [{
label: 'Feature Count',
data: []
}]
},
data: {},
history: {
jobs: []
}
}
},
mounted: function() {
this.colours = [
'#EA7580','#F6A1A5','#F8CD9C','#1BB6AF','#088BBE','#172869' // Pamplemousse
]
this.refresh();
},
computed: {
computedPage: function() {
return this.history.jobs.slice(this.paging.limit * this.paging.page, this.paging.limit * (this.paging.page + 1))
}
},
methods: {
fmt: function(date) {
return moment(date).tz(this.tz).format('YYYY-MM-DD');
},
emitjob: function(jobid) {
this.$router.push({ path: `/job/${jobid}`});
},
refresh: async function() {
await this.getData();
this.getHistory();
},
datapls: function(id) {
this.external(`${window.location.origin}/api/job/${id}/output/source.geojson.gz?token=${localStorage.token}`);
},
external: function(url) {
window.open(url, '_blank');
},
getHistory: async function() {
try {
this.loading.history = true;
this.history = await window.std(`/api/data/${this.dataid}/history`);
this.chart = {
datasets: [{
label: 'Features',
fill: false,
borderColor: this.colours.pop(),
data: this.history.jobs.map((ele) => {
return { x: ele.created, y: ele.count }
})
}]
};
if (this.data.layer === 'addresses') {
this.chart.datasets.push({
label: 'Numbers',
fill: false,
borderColor: this.colours.pop(),
data: this.history.jobs.map((ele) => {
return { x: ele.created, y: ele.stats.counts.number }
})
});
this.chart.datasets.push({
label: 'Streets',
fill: false,
borderColor: this.colours.pop(),
data: this.history.jobs.map((ele) => {
return { x: ele.created, y: ele.stats.counts.street }
})
});
this.chart.datasets.push({
label: 'Cities',
fill: false,
borderColor: this.colours.pop(),
data: this.history.jobs.map((ele) => {
return { x: ele.created, y: ele.stats.counts.city }
})
});
this.chart.datasets.push({
label: 'Postcodes',
fill: false,
borderColor: this.colours.pop(),
data: this.history.jobs.map((ele) => {
return { x: ele.created, y: ele.stats.counts.postcode }
})
});
}
this.loading.history = false;
} catch (err) {
this.$emit('err', err);
}
},
getData: async function() {
try {
this.data = await window.std(`/api/data/${this.dataid}`);
} catch (err) {
this.$emit('err', err);
}
}
},
components: {
Status,
IconRefresh,
IconDownload,
TablerLoading,
TableFooter,
LineChart,
TablerBreadCrumb,
},
}
</script>
|
<document xmlns="http://cnx.rice.edu/cnxml" xmlns:m="http://www.w3.org/1998/Math/MathML">
<title>Uniform Convergence</title>
<metadata xmlns:md="http://cnx.rice.edu/mdml">
<md:content-id>m36178</md:content-id>
<md:title>Uniform Convergence</md:title>
<md:abstract>We introduce now two different notions of the limit of a sequence of functions. Some definitions cover uniform convergence and pointwise convergence. The Weierstrass M-Test is stated and proven, as well the theorem of Abel.</md:abstract>
<md:uuid>e2a746d9-444e-4b4e-8e1c-3d4a845d5489</md:uuid>
</metadata>
<content>
<para id="id62159">We introduce now two different notions of the limit of a sequence of functions.
Let <m:math overflow="scroll"><m:mi>S</m:mi></m:math> be a set of complex numbers, and let
<m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> be a sequence of complex-valued functions each having domain <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>.</m:mo></m:mrow></m:math></para>
<definition id="fs-id1167582102172"><term/><meaning id="fs-id1167594177885">
<para id="id62201">
We say that the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math><emphasis effect="italics">converges</emphasis> or
<emphasis effect="italics">converges pointwise</emphasis> to a function <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>:</m:mo><m:mi>S</m:mi><m:mo>→</m:mo><m:mi>C</m:mi></m:mrow></m:math> if
for every <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi></m:mrow></m:math> and every <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>></m:mo><m:mn>0</m:mn></m:mrow></m:math> there exists a natural number <m:math overflow="scroll"><m:mrow><m:mi>N</m:mi><m:mo>,</m:mo></m:mrow></m:math>
depending on <m:math overflow="scroll"><m:mi>x</m:mi></m:math> and <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>,</m:mo></m:mrow></m:math> such that for every
<m:math overflow="scroll"><m:mrow><m:mi>n</m:mi><m:mo>≥</m:mo><m:mi>N</m:mi><m:mo>,</m:mo></m:mrow></m:math><m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo></m:mrow><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>-</m:mo><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>|</m:mo><m:mo><</m:mo><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:mrow></m:math>
That is, equivalently, <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges pointwise to <m:math overflow="scroll"><m:mi>f</m:mi></m:math> if for every
<m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi></m:mrow></m:math> the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>}</m:mo></m:mrow></m:math> of numbers converges to the number <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo><m:mo>.</m:mo></m:mrow></m:math></para>
<para id="id62980">We say that the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math><emphasis effect="italics">converges uniformly</emphasis>
to a function <m:math overflow="scroll"><m:mi>f</m:mi></m:math> if for every <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>></m:mo><m:mn>0</m:mn><m:mo>,</m:mo></m:mrow></m:math> there exists
an <m:math overflow="scroll"><m:mrow><m:mi>N</m:mi><m:mo>,</m:mo></m:mrow></m:math> depending only on <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>,</m:mo></m:mrow></m:math> such that
for every <m:math overflow="scroll"><m:mrow><m:mi>n</m:mi><m:mo>≥</m:mo><m:mi>N</m:mi></m:mrow></m:math> and every <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi><m:mo>,</m:mo></m:mrow></m:math><m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo></m:mrow><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>-</m:mo><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>|</m:mo><m:mo><</m:mo><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:mrow></m:math></para>
<para id="id63126">If <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>u</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> is a sequence of functions defined on <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>,</m:mo></m:mrow></m:math>
we say that the infinite series <m:math overflow="scroll"><m:mrow><m:mo>∑</m:mo><m:msub><m:mi>u</m:mi><m:mi>n</m:mi></m:msub></m:mrow></m:math><emphasis effect="italics">converges uniformly</emphasis> if the sequence
<m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>S</m:mi><m:mi>N</m:mi></m:msub><m:mo>=</m:mo><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>N</m:mi></m:msubsup><m:msub><m:mi>u</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> of partial sums converges uniformly.</para>
</meaning></definition>
<para id="id63224">These two definitions of convergence of a sequence of functions
differ in subtle ways. Study the word order in the
definitions.</para>
<exercise id="fs-id1167590429104"><problem id="fs-id1167594646621">
<list id="id63239" display="block" list-type="enumerated" number-style="lower-alpha"><item id="uid1"> Prove that if a sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> of functions
converges uniformly on a set <m:math overflow="scroll"><m:mi>S</m:mi></m:math> to a function <m:math overflow="scroll"><m:mi>f</m:mi></m:math> then it converges
pointwise to <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>.</m:mo></m:mrow></m:math></item>
<item id="uid2"> Let <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>=</m:mo><m:mo>(</m:mo><m:mn>0</m:mn><m:mo>,</m:mo><m:mn>1</m:mn><m:mo>)</m:mo><m:mo>,</m:mo></m:mrow></m:math> and for each <m:math overflow="scroll"><m:mi>n</m:mi></m:math> define
<m:math overflow="scroll"><m:mrow><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:msup><m:mi>x</m:mi><m:mi>n</m:mi></m:msup><m:mo>.</m:mo></m:mrow></m:math> Prove that <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges pointwise to the
zero function, but that <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> does not converge uniformly to the zero function.
Conclude that pointwise convergence does <emphasis effect="bold">not</emphasis> imply uniform convergence.
HINT: Suppose the sequence does converge uniformly.
Take <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>=</m:mo><m:mn>1</m:mn><m:mo>/</m:mo><m:mn>2</m:mn><m:mo>,</m:mo></m:mrow></m:math> let <m:math overflow="scroll"><m:mi>N</m:mi></m:math> be a corresponding integer,
and consider <m:math overflow="scroll"><m:mi>x</m:mi></m:math>'s of the form <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>=</m:mo><m:mn>1</m:mn><m:mo>-</m:mo><m:mi>h</m:mi></m:mrow></m:math> for tiny <m:math overflow="scroll"><m:mi>h</m:mi></m:math>'s.
</item>
<item id="uid3"> Suppose the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges uniformly to <m:math overflow="scroll"><m:mi>f</m:mi></m:math> on <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>,</m:mo></m:mrow></m:math> and
the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>g</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges uniformly to <m:math overflow="scroll"><m:mi>g</m:mi></m:math> on <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>.</m:mo></m:mrow></m:math>
Prove that the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>+</m:mo><m:msub><m:mi>g</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges uniformly to <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>+</m:mo><m:mi>g</m:mi></m:mrow></m:math> on <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>.</m:mo></m:mrow></m:math></item>
<item id="uid4"> Suppose <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges uniformly to <m:math overflow="scroll"><m:mi>f</m:mi></m:math> on <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>,</m:mo></m:mrow></m:math> and let
<m:math overflow="scroll"><m:mi>c</m:mi></m:math> be a constant. Show that <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:mi>c</m:mi><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges uniformly to <m:math overflow="scroll"><m:mrow><m:mi>c</m:mi><m:mi>f</m:mi></m:mrow></m:math> on <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>.</m:mo></m:mrow></m:math></item>
<item id="uid5"> Let <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>=</m:mo><m:mi>R</m:mi><m:mo>,</m:mo></m:mrow></m:math> and set <m:math overflow="scroll"><m:mrow><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:mi>x</m:mi><m:mo>+</m:mo><m:mrow><m:mo>(</m:mo><m:mn>1</m:mn><m:mo>/</m:mo><m:mi>n</m:mi><m:mo>)</m:mo></m:mrow><m:mo>.</m:mo></m:mrow></m:math>
Does <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converge uniformly on <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>?</m:mo></m:mrow></m:math>
Does <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msubsup><m:mi>f</m:mi><m:mi>n</m:mi><m:mn>2</m:mn></m:msubsup><m:mo>}</m:mo></m:mrow></m:math> converge uniformly on <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>?</m:mo></m:mrow></m:math>
What does this say about the limit of a product of uniformly convergent sequences versus the product of the limits?
</item>
<item id="uid6"> Suppose <m:math overflow="scroll"><m:mi>a</m:mi></m:math> and <m:math overflow="scroll"><m:mi>b</m:mi></m:math> are nonnegative real numbers and that <m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo><m:mi>a</m:mi><m:mo>-</m:mo><m:mi>b</m:mi><m:mo>|</m:mo><m:mo><</m:mo></m:mrow><m:msup><m:mi>ϵ</m:mi><m:mn>2</m:mn></m:msup><m:mo>.</m:mo></m:mrow></m:math>
Prove that <m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo></m:mrow><m:msqrt><m:mi>a</m:mi></m:msqrt><m:mo>-</m:mo><m:msqrt><m:mi>b</m:mi></m:msqrt><m:mrow><m:mo>|</m:mo><m:mo><</m:mo><m:mn>2</m:mn><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:mrow></m:math>
HINT: Break this into cases, the first one being when both <m:math overflow="scroll"><m:msqrt><m:mi>a</m:mi></m:msqrt></m:math> and <m:math overflow="scroll"><m:msqrt><m:mi>b</m:mi></m:msqrt></m:math> are less than <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:math></item>
<item id="uid7"> Suppose <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> is a sequence of nonnegative real-valued functions that converges uniformly
to <m:math overflow="scroll"><m:mi>f</m:mi></m:math> on <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>.</m:mo></m:mrow></m:math>
Use part (f) to prove that the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msqrt><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub></m:msqrt><m:mo>}</m:mo></m:mrow></m:math> converges uniformly to <m:math overflow="scroll"><m:mrow><m:msqrt><m:mi>f</m:mi></m:msqrt><m:mo>.</m:mo></m:mrow></m:math></item>
<item id="uid8"> For each positive integer <m:math overflow="scroll"><m:mrow><m:mi>n</m:mi><m:mo>,</m:mo></m:mrow></m:math> define <m:math overflow="scroll"><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub></m:math> on <m:math overflow="scroll"><m:mrow><m:mo>(</m:mo><m:mo>-</m:mo><m:mn>1</m:mn><m:mo>,</m:mo><m:mn>1</m:mn><m:mo>)</m:mo></m:mrow></m:math> by
<m:math overflow="scroll"><m:mrow><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:msup><m:mrow><m:mo>|</m:mo><m:mi>x</m:mi><m:mo>|</m:mo></m:mrow><m:mrow><m:mn>1</m:mn><m:mo>+</m:mo><m:mn>1</m:mn><m:mo>/</m:mo><m:mi>n</m:mi></m:mrow></m:msup><m:mo>.</m:mo></m:mrow></m:math> Prove that the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges
uniformly on <m:math overflow="scroll"><m:mrow><m:mo>(</m:mo><m:mo>-</m:mo><m:mn>1</m:mn><m:mo>,</m:mo><m:mn>1</m:mn><m:mo>)</m:mo></m:mrow></m:math> to the function <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo><m:mo>=</m:mo><m:mo>|</m:mo><m:mi>x</m:mi><m:mo>|</m:mo><m:mo>.</m:mo></m:mrow></m:math>
HINT: Let <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>></m:mo><m:mn>0</m:mn></m:mrow></m:math> be given. Consider <m:math overflow="scroll"><m:mrow><m:mo>|</m:mo><m:mi>x</m:mi><m:mo>|</m:mo></m:mrow></m:math>'s that are <m:math overflow="scroll"><m:mrow><m:mo><</m:mo><m:mi>ϵ</m:mi></m:mrow></m:math> and <m:math overflow="scroll"><m:mrow><m:mo>|</m:mo><m:mi>x</m:mi><m:mo>|</m:mo></m:mrow></m:math>'s that are <m:math overflow="scroll"><m:mrow><m:mo>≥</m:mo><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:math>
For <m:math overflow="scroll"><m:mrow><m:mo>|</m:mo><m:mi>x</m:mi><m:mo>|</m:mo><m:mo><</m:mo><m:mi>ϵ</m:mi><m:mo>,</m:mo></m:mrow></m:math> show that <m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo></m:mrow><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>-</m:mo><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>|</m:mo><m:mo><</m:mo><m:mi>ϵ</m:mi></m:mrow></m:mrow></m:math> for all <m:math overflow="scroll"><m:mrow><m:mi>n</m:mi><m:mo>.</m:mo></m:mrow></m:math>
For <m:math overflow="scroll"><m:mrow><m:mo>|</m:mo><m:mi>x</m:mi><m:mo>|</m:mo><m:mo>≥</m:mo><m:mi>ϵ</m:mi><m:mo>,</m:mo></m:mrow></m:math> choose <m:math overflow="scroll"><m:mi>N</m:mi></m:math> so that
<m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo></m:mrow><m:msup><m:mi>ϵ</m:mi><m:mrow><m:mn>1</m:mn><m:mo>/</m:mo><m:mi>n</m:mi></m:mrow></m:msup><m:mrow><m:mo>-</m:mo><m:mn>1</m:mn><m:mo>|</m:mo><m:mo><</m:mo><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:mrow></m:math> How?
</item>
</list>
</problem></exercise>
<exercise id="fs-id1167590259636"><problem id="fs-id1167601829757">
<para id="id64473"> Let <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> be a sequence of functions
on a set <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>,</m:mo></m:mrow></m:math> let <m:math overflow="scroll"><m:mi>f</m:mi></m:math> be a function on <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>,</m:mo></m:mrow></m:math>
and suppose that for each <m:math overflow="scroll"><m:mi>n</m:mi></m:math> we have
<m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>-</m:mo></m:mrow><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>|</m:mo><m:mo><</m:mo><m:mn>1</m:mn><m:mo>/</m:mo><m:mi>n</m:mi></m:mrow></m:mrow></m:math> for all <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi><m:mo>.</m:mo></m:mrow></m:math>
Prove that the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges uniformly to <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>.</m:mo></m:mrow></m:math></para>
</problem></exercise>
<para id="id64643">We give next four important theorems concerning uniform convergence.
The first of these theorems is frequently used to prove that a given
function is continuous. The theorem asserts that if <m:math overflow="scroll"><m:mi>f</m:mi></m:math> is the uniform limit of a sequence of continuous
functions, then <m:math overflow="scroll"><m:mi>f</m:mi></m:math> is itself continuous.</para>
<rule id="fs-id8597860" type="theorem"><title>The uniform limit of continuous functions is continuous.</title><statement id="fs-id2191491">
<para id="id64668">
Suppose <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> is a sequence of continuous functions
on a set <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>⊆</m:mo><m:mi>C</m:mi><m:mo>,</m:mo></m:mrow></m:math> and assume that
the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges uniformly to a function <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>.</m:mo></m:mrow></m:math>
Then <m:math overflow="scroll"><m:mi>f</m:mi></m:math> is continuous on <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>.</m:mo></m:mrow></m:math></para>
</statement>
<proof id="fs-id1167579210925">
<para id="id64773">
This proof is an example of what is called by mathematicians a
“<m:math overflow="scroll"><m:mrow><m:mn>3</m:mn><m:mi>ϵ</m:mi></m:mrow></m:math> argument.”</para>
<para id="id64794">Fix an <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi></m:mrow></m:math> and an <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>></m:mo><m:mn>0</m:mn><m:mo>.</m:mo></m:mrow></m:math>
We wish to find a <m:math overflow="scroll"><m:mrow><m:mi>δ</m:mi><m:mo>></m:mo><m:mn>0</m:mn></m:mrow></m:math> such that if <m:math overflow="scroll"><m:mrow><m:mi>y</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi></m:mrow></m:math> and <m:math overflow="scroll"><m:mrow><m:mo>|</m:mo><m:mi>y</m:mi><m:mo>-</m:mo><m:mi>x</m:mi><m:mo>|</m:mo><m:mo><</m:mo><m:mi>δ</m:mi></m:mrow></m:math>
then <m:math overflow="scroll"><m:mrow><m:mo>|</m:mo><m:mi>f</m:mi><m:mo>(</m:mo><m:mi>y</m:mi><m:mo>)</m:mo><m:mo>-</m:mo><m:mi>f</m:mi><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo><m:mo>|</m:mo><m:mo><</m:mo><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:math></para>
<para id="id64918">We use first the hypothesis that the sequence converges uniformly.
Thus, given this <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>></m:mo><m:mn>0</m:mn><m:mo>,</m:mo></m:mrow></m:math>
there exists a natural number <m:math overflow="scroll"><m:mi>N</m:mi></m:math> such that if <m:math overflow="scroll"><m:mrow><m:mi>n</m:mi><m:mo>≥</m:mo><m:mi>N</m:mi></m:mrow></m:math> then
<m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow><m:mo>-</m:mo></m:mrow><m:msub><m:mi>f</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mrow><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow><m:mo>|</m:mo><m:mo><</m:mo><m:mi>ϵ</m:mi><m:mo>/</m:mo><m:mn>3</m:mn></m:mrow></m:mrow></m:math> for all <m:math overflow="scroll"><m:mrow><m:mi>z</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi><m:mo>.</m:mo></m:mrow></m:math>
Now, because <m:math overflow="scroll"><m:msub><m:mi>f</m:mi><m:mi>N</m:mi></m:msub></m:math> is continuous at <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>,</m:mo></m:mrow></m:math> there exists a <m:math overflow="scroll"><m:mrow><m:mi>δ</m:mi><m:mo>></m:mo><m:mn>0</m:mn></m:mrow></m:math>
such that if <m:math overflow="scroll"><m:mrow><m:mi>y</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi></m:mrow></m:math> and <m:math overflow="scroll"><m:mrow><m:mo>|</m:mo><m:mi>y</m:mi><m:mo>-</m:mo><m:mi>x</m:mi><m:mo>|</m:mo><m:mo><</m:mo><m:mi>δ</m:mi></m:mrow></m:math> then
<m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo></m:mrow><m:msub><m:mi>f</m:mi><m:mi>N</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>y</m:mi><m:mo>)</m:mo></m:mrow><m:mo>-</m:mo><m:msub><m:mi>f</m:mi><m:mi>N</m:mi></m:msub><m:mrow><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>|</m:mo><m:mo><</m:mo><m:mi>ϵ</m:mi><m:mo>/</m:mo><m:mn>3</m:mn><m:mo>.</m:mo></m:mrow></m:mrow></m:math> So,
if <m:math overflow="scroll"><m:mrow><m:mi>y</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi></m:mrow></m:math> and <m:math overflow="scroll"><m:mrow><m:mo>|</m:mo><m:mi>y</m:mi><m:mo>-</m:mo><m:mi>x</m:mi><m:mo>|</m:mo><m:mo><</m:mo><m:mi>δ</m:mi><m:mo>,</m:mo></m:mrow></m:math> then</para>
<equation id="uid9">
<m:math overflow="scroll" mode="display">
<m:mtable displaystyle="true">
<m:mtr>
<m:mtd columnalign="right">
<m:mrow>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mo>(</m:mo>
<m:mi>y</m:mi>
<m:mo>)</m:mo>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
<m:mo>|</m:mo>
</m:mrow>
</m:mtd>
<m:mtd>
<m:mo>=</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>y</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:msub>
<m:mi>f</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>y</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>+</m:mo>
<m:msub>
<m:mi>f</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>y</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:msub>
<m:mi>f</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>+</m:mo>
<m:msub>
<m:mi>f</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>≤</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>y</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:msub>
<m:mi>f</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>y</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:msub>
<m:mi>f</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>y</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:msub>
<m:mi>f</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:msub>
<m:mi>f</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo><</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mfrac>
<m:mi>ϵ</m:mi>
<m:mn>3</m:mn>
</m:mfrac>
<m:mo>+</m:mo>
<m:mfrac>
<m:mi>ϵ</m:mi>
<m:mn>3</m:mn>
</m:mfrac>
<m:mo>+</m:mo>
<m:mfrac>
<m:mi>ϵ</m:mi>
<m:mn>3</m:mn>
</m:mfrac>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>=</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mi>ϵ</m:mi>
<m:mo>.</m:mo>
</m:mrow>
</m:mtd>
</m:mtr>
</m:mtable>
</m:math>
</equation>
<para id="id65518">This completes the proof.</para>
</proof></rule>
<rule id="fs-id1167590459776"><label/><statement id="fs-id1167585426726">
<para id="id65524"><emphasis effect="bold">REMARK</emphasis>
Many properties of functions are preserved under the taking of uniform limits,
e.g., continuity, as we have just seen.
However, not all properties are preserved under this limit process.
Differentiability is not, integrability is sometimes, being a power series function is, and so on.
We must be alert to be aware of when it works and when it does not.</para>
</statement></rule>
<rule id="fs-id2892663" type="theorem"><title>Weierstrass M-Test</title><statement id="fs-id1167588936813">
<para id="id65535">
Let <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>u</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> be a sequence of complex-valued functions
defined on a set <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>⊆</m:mo><m:mi>C</m:mi><m:mo>.</m:mo></m:mrow></m:math>
Write <m:math overflow="scroll"><m:msub><m:mi>S</m:mi><m:mi>N</m:mi></m:msub></m:math> for the partial sum <m:math overflow="scroll"><m:mrow><m:msub><m:mi>S</m:mi><m:mi>N</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>N</m:mi></m:msubsup><m:msub><m:mi>u</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>.</m:mo></m:mrow></m:math>
Suppose that, for each <m:math overflow="scroll"><m:mrow><m:mi>n</m:mi><m:mo>,</m:mo></m:mrow></m:math> there exists an <m:math overflow="scroll"><m:mrow><m:msub><m:mi>M</m:mi><m:mi>n</m:mi></m:msub><m:mo>></m:mo><m:mn>0</m:mn></m:mrow></m:math>
for which <m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo></m:mrow><m:msub><m:mi>u</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>|</m:mo><m:mo>≤</m:mo></m:mrow><m:msub><m:mi>M</m:mi><m:mi>n</m:mi></m:msub></m:mrow></m:math>
for all <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi><m:mo>.</m:mo></m:mrow></m:math> Then</para>
<list id="id65748" display="block" list-type="enumerated">
<item id="uid10">If <m:math overflow="scroll"><m:mrow><m:mo>∑</m:mo><m:msub><m:mi>M</m:mi><m:mi>n</m:mi></m:msub></m:mrow></m:math> converges, then the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>S</m:mi><m:mi>N</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math>
converges uniformly to a function <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>.</m:mo></m:mrow></m:math>
That is, the infinite series <m:math overflow="scroll"><m:mrow><m:mo>∑</m:mo><m:msub><m:mi>u</m:mi><m:mi>n</m:mi></m:msub></m:mrow></m:math> converges uniformly.
</item>
<item id="uid11">If each function <m:math overflow="scroll"><m:msub><m:mi>u</m:mi><m:mi>n</m:mi></m:msub></m:math> is continuous, and
<m:math overflow="scroll"><m:mrow><m:mo>∑</m:mo><m:msub><m:mi>M</m:mi><m:mi>n</m:mi></m:msub></m:mrow></m:math> converges, then the function <m:math overflow="scroll"><m:mi>S</m:mi></m:math> of part (1) is continuous.
</item>
</list>
</statement>
<proof id="fs-id1167589253199">
<para id="id65886">
Because <m:math overflow="scroll"><m:mrow><m:mo>∑</m:mo><m:msub><m:mi>M</m:mi><m:mi>n</m:mi></m:msub></m:mrow></m:math> is convergent, it follows from the Comparison Test that
for each <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi></m:mrow></m:math> the infinite series <m:math overflow="scroll"><m:mrow><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>∞</m:mi></m:msubsup><m:msub><m:mi>u</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow></m:mrow></m:math> is absolutely convergent,
hence convergent. Define a
function <m:math overflow="scroll"><m:mi>S</m:mi></m:math> by <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>∞</m:mi></m:msubsup><m:msub><m:mi>u</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:mo movablelimits="true" form="prefix">lim</m:mo><m:msub><m:mi>S</m:mi><m:mi>N</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>.</m:mo></m:mrow></m:math></para>
<para id="id66049">To show that <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>S</m:mi><m:mi>N</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges uniformly to <m:math overflow="scroll"><m:mrow><m:mi>S</m:mi><m:mo>,</m:mo></m:mrow></m:math>
let <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>></m:mo><m:mn>0</m:mn></m:mrow></m:math> be given, and choose a natural number <m:math overflow="scroll"><m:mi>N</m:mi></m:math>
such that <m:math overflow="scroll"><m:mrow><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mi>N</m:mi><m:mo>+</m:mo><m:mn>1</m:mn></m:mrow><m:mi>∞</m:mi></m:msubsup><m:msub><m:mi>M</m:mi><m:mi>n</m:mi></m:msub><m:mo><</m:mo><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:math> This can be done because <m:math overflow="scroll"><m:mrow><m:mo>∑</m:mo><m:msub><m:mi>M</m:mi><m:mi>n</m:mi></m:msub></m:mrow></m:math> converges.
Now, for any <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>∈</m:mo><m:mi>S</m:mi></m:mrow></m:math> and any <m:math overflow="scroll"><m:mrow><m:mi>m</m:mi><m:mo>≥</m:mo><m:mi>N</m:mi><m:mo>,</m:mo></m:mrow></m:math> we have</para>
<equation id="uid12">
<m:math overflow="scroll" mode="display">
<m:mtable displaystyle="true">
<m:mtr>
<m:mtd columnalign="right">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>S</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:msub>
<m:mi>S</m:mi>
<m:mi>m</m:mi>
</m:msub>
<m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
<m:mtd>
<m:mo>=</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
<m:munder>
<m:mo movablelimits="true" form="prefix">lim</m:mo>
<m:mrow>
<m:mi>k</m:mi>
<m:mo>→</m:mo>
<m:mi>∞</m:mi>
</m:mrow>
</m:munder>
<m:msub>
<m:mi>S</m:mi>
<m:mi>k</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>m</m:mi>
</m:msub>
<m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>=</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
<m:munder>
<m:mo movablelimits="true" form="prefix">lim</m:mo>
<m:mrow>
<m:mi>k</m:mi>
<m:mo>→</m:mo>
<m:mi>∞</m:mi>
</m:mrow>
</m:munder>
<m:mrow>
<m:mo>(</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>k</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>m</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>=</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:munder>
<m:mo movablelimits="true" form="prefix">lim</m:mo>
<m:mrow>
<m:mi>k</m:mi>
<m:mo>→</m:mo>
<m:mi>∞</m:mi>
</m:mrow>
</m:munder>
<m:mrow>
<m:mo>|</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>k</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>m</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>=</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:munder>
<m:mo movablelimits="true" form="prefix">lim</m:mo>
<m:mrow>
<m:mi>k</m:mi>
<m:mo>→</m:mo>
<m:mi>∞</m:mi>
</m:mrow>
</m:munder>
<m:mrow>
<m:mo>|</m:mo>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mi>m</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
<m:mi>k</m:mi>
</m:munderover>
<m:msub>
<m:mi>u</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>≤</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:munder>
<m:mo movablelimits="true" form="prefix">lim</m:mo>
<m:mrow>
<m:mi>k</m:mi>
<m:mo>→</m:mo>
<m:mi>∞</m:mi>
</m:mrow>
</m:munder>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mi>m</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
<m:mi>k</m:mi>
</m:munderover>
<m:mrow>
<m:mo>|</m:mo>
<m:msub>
<m:mi>u</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>≤</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:munder>
<m:mo movablelimits="true" form="prefix">lim</m:mo>
<m:mrow>
<m:mi>k</m:mi>
<m:mo>→</m:mo>
<m:mi>∞</m:mi>
</m:mrow>
</m:munder>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mi>m</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
<m:mi>k</m:mi>
</m:munderover>
<m:msub>
<m:mi>M</m:mi>
<m:mi>n</m:mi>
</m:msub>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>=</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mi>m</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
<m:mi>∞</m:mi>
</m:munderover>
<m:msub>
<m:mi>M</m:mi>
<m:mi>n</m:mi>
</m:msub>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>≤</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mi>N</m:mi>
</m:mrow>
<m:mi>∞</m:mi>
</m:munderover>
<m:msub>
<m:mi>M</m:mi>
<m:mi>n</m:mi>
</m:msub>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo><</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mi>ϵ</m:mi>
<m:mo>.</m:mo>
</m:mrow>
</m:mtd>
</m:mtr>
</m:mtable>
</m:math>
</equation>
<para id="id66736">This proves part (1).</para>
<para id="id66742">Part (2) now follows from part (1) and <link target-id="fs-id8597860"/>,
since the <m:math overflow="scroll"><m:msub><m:mi>S</m:mi><m:mi>N</m:mi></m:msub></m:math>'s are continuous.</para>
</proof></rule>
<rule id="fs-id1167587257600" type="theorem"><statement id="fs-id1167579982846">
<para id="id66761">
Let <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>∞</m:mi></m:msubsup><m:msub><m:mi>a</m:mi><m:mi>n</m:mi></m:msub><m:msup><m:mi>z</m:mi><m:mi>n</m:mi></m:msup></m:mrow></m:math> be a power series function with
radius of convergence <m:math overflow="scroll"><m:mrow><m:mi>r</m:mi><m:mo>></m:mo><m:mn>0</m:mn><m:mo>,</m:mo></m:mrow></m:math>
and let <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>S</m:mi><m:mi>N</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow><m:mo>}</m:mo></m:mrow></m:math> denote the sequence of partial sums of this series:</para>
<equation id="id66864">
<m:math overflow="scroll" mode="display">
<m:mrow>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>z</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>=</m:mo>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>z</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>.</m:mo>
</m:mrow>
</m:math>
</equation>
<para id="id66925">If <m:math overflow="scroll"><m:mrow><m:mn>0</m:mn><m:mo><</m:mo><m:msup><m:mi>r</m:mi><m:mo>'</m:mo></m:msup><m:mo><</m:mo><m:mi>r</m:mi><m:mo>,</m:mo></m:mrow></m:math> then the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>S</m:mi><m:mi>N</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges uniformly to <m:math overflow="scroll"><m:mi>f</m:mi></m:math> on the disk<m:math overflow="scroll"><m:mrow><m:msub><m:mi>B</m:mi><m:msup><m:mi>r</m:mi><m:mo>'</m:mo></m:msup></m:msub><m:mrow><m:mo>(</m:mo><m:mn>0</m:mn><m:mo>)</m:mo></m:mrow><m:mo>.</m:mo></m:mrow></m:math></para>
</statement>
<proof id="fs-id2377500">
<para id="id67015">
Define a power series function <m:math overflow="scroll"><m:mi>g</m:mi></m:math> by
<m:math overflow="scroll"><m:mrow><m:mi>g</m:mi><m:mrow><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>∞</m:mi></m:msubsup><m:mrow><m:mo>|</m:mo><m:msub><m:mi>a</m:mi><m:mi>n</m:mi></m:msub><m:mo>|</m:mo></m:mrow><m:msup><m:mi>z</m:mi><m:mi>n</m:mi></m:msup><m:mo>,</m:mo></m:mrow></m:math> and note that the radius of
convergence for <m:math overflow="scroll"><m:mi>g</m:mi></m:math> is the same as that for <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>,</m:mo></m:mrow></m:math> i.e., <m:math overflow="scroll"><m:mrow><m:mi>r</m:mi><m:mo>.</m:mo></m:mrow></m:math>
Choose <m:math overflow="scroll"><m:mi>t</m:mi></m:math> so that <m:math overflow="scroll"><m:mrow><m:msup><m:mi>r</m:mi><m:mo>'</m:mo></m:msup><m:mo><</m:mo><m:mi>t</m:mi><m:mo><</m:mo><m:mi>r</m:mi><m:mo>.</m:mo></m:mrow></m:math> Then, since <m:math overflow="scroll"><m:mi>t</m:mi></m:math> belongs
to the disk of convergence of the power series function <m:math overflow="scroll"><m:mrow><m:mi>g</m:mi><m:mo>,</m:mo></m:mrow></m:math>
we know that <m:math overflow="scroll"><m:mrow><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>∞</m:mi></m:msubsup><m:mrow><m:mo>|</m:mo><m:msub><m:mi>a</m:mi><m:mi>n</m:mi></m:msub><m:mo>|</m:mo></m:mrow><m:msup><m:mi>t</m:mi><m:mi>n</m:mi></m:msup></m:mrow></m:math> converges.
Set <m:math overflow="scroll"><m:mrow><m:msub><m:mi>m</m:mi><m:mi>n</m:mi></m:msub><m:mo>=</m:mo><m:mrow><m:mo>|</m:mo><m:msub><m:mi>a</m:mi><m:mi>n</m:mi></m:msub><m:mo>|</m:mo></m:mrow><m:msup><m:mi>t</m:mi><m:mi>n</m:mi></m:msup><m:mo>,</m:mo></m:mrow></m:math> and note that <m:math overflow="scroll"><m:mrow><m:mo>∑</m:mo><m:msub><m:mi>m</m:mi><m:mi>n</m:mi></m:msub></m:mrow></m:math> converges.
Now, for each <m:math overflow="scroll"><m:mrow><m:mi>z</m:mi><m:mo>∈</m:mo><m:msub><m:mi>B</m:mi><m:msup><m:mi>r</m:mi><m:mo>'</m:mo></m:msup></m:msub><m:mrow><m:mo>(</m:mo><m:mn>0</m:mn><m:mo>)</m:mo></m:mrow><m:mo>,</m:mo></m:mrow></m:math> we have that</para>
<equation id="id67317">
<m:math overflow="scroll" mode="display">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>z</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mrow>
<m:mo>|</m:mo>
<m:mo>≤</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
<m:msup>
<m:mrow>
<m:msup>
<m:mi>r</m:mi>
<m:mo>'</m:mo>
</m:msup>
</m:mrow>
<m:mi>n</m:mi>
</m:msup>
<m:mo>≤</m:mo>
<m:mrow>
<m:mo>|</m:mo>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mo>|</m:mo>
</m:mrow>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>=</m:mo>
<m:msub>
<m:mi>m</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mo>,</m:mo>
</m:mrow>
</m:math>
</equation>
<para id="id67412">so that the infinite series
<m:math overflow="scroll"><m:mrow><m:mo>∑</m:mo><m:msub><m:mi>a</m:mi><m:mi>n</m:mi></m:msub><m:msup><m:mi>z</m:mi><m:mi>n</m:mi></m:msup></m:mrow></m:math> converges uniformly on <m:math overflow="scroll"><m:mrow><m:msub><m:mi>B</m:mi><m:msup><m:mi>r</m:mi><m:mo>'</m:mo></m:msup></m:msub><m:mrow><m:mo>(</m:mo><m:mn>0</m:mn><m:mo>)</m:mo></m:mrow></m:mrow></m:math> by the Weierstrass M-Test.</para>
</proof></rule>
<exercise id="fs-id1167595582558"><problem id="fs-id1167581225704">
<para id="id67472">
Let <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>∞</m:mi></m:msubsup><m:msup><m:mi>z</m:mi><m:mi>n</m:mi></m:msup><m:mo>.</m:mo></m:mrow></m:math>
Recall that the radius of convergence for <m:math overflow="scroll"><m:mi>f</m:mi></m:math> is 1.
Verify that the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>S</m:mi><m:mi>N</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> of partial sums of this
power series function fails to converge uniformly on the
full open disk of convergence <m:math overflow="scroll"><m:mrow><m:msub><m:mi>B</m:mi><m:mn>1</m:mn></m:msub><m:mrow><m:mo>(</m:mo><m:mn>0</m:mn><m:mo>)</m:mo></m:mrow><m:mo>,</m:mo></m:mrow></m:math>
so that the requirement that <m:math overflow="scroll"><m:mrow><m:msup><m:mi>r</m:mi><m:mo>'</m:mo></m:msup><m:mo><</m:mo><m:mi>r</m:mi></m:mrow></m:math> is necessary in the preceding theorem.</para>
</problem></exercise>
<para id="id67605">The next theorem shows that continuous, real-valued functions on closed bounded intervals
are uniform limits of step functions.
Step functions have not been mentioned lately, since they aren't continuous functions,
but this next theorem will be crucial for us when we study integration in <link document="m36207"/>.</para>
<rule id="fs-id1167583148827" type="theorem"><statement id="fs-id1167580401665">
<para id="id67613">
Let <m:math overflow="scroll"><m:mi>f</m:mi></m:math> be a continuous real-valued function on the
closed and bounded interval <m:math overflow="scroll"><m:mrow><m:mo>[</m:mo><m:mi>a</m:mi><m:mo>,</m:mo><m:mi>b</m:mi><m:mo>]</m:mo><m:mo>.</m:mo></m:mrow></m:math>
Then there exists a sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>h</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> of step functions
on <m:math overflow="scroll"><m:mrow><m:mo>[</m:mo><m:mi>a</m:mi><m:mo>,</m:mo><m:mi>b</m:mi><m:mo>]</m:mo></m:mrow></m:math> that converges uniformly to <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>.</m:mo></m:mrow></m:math></para>
</statement>
<proof id="fs-id2004211">
<para id="id67701">We use the fact that a continuous function on a
compact set is uniformly continuous (<link target-id="fs-id1169193164426" document="m36167"/>).</para>
<para id="id67709">For each positive integer <m:math overflow="scroll"><m:mrow><m:mi>n</m:mi><m:mo>,</m:mo></m:mrow></m:math> let <m:math overflow="scroll"><m:msub><m:mi>δ</m:mi><m:mi>n</m:mi></m:msub></m:math> be a positive number
satisfying <m:math overflow="scroll"><m:mrow><m:mo>|</m:mo><m:mi>f</m:mi><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo><m:mo>-</m:mo><m:mi>f</m:mi><m:mo>(</m:mo><m:mi>y</m:mi><m:mo>)</m:mo><m:mo>|</m:mo><m:mo><</m:mo><m:mn>1</m:mn><m:mo>/</m:mo><m:mi>n</m:mi></m:mrow></m:math> if <m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo><m:mi>x</m:mi><m:mo>-</m:mo><m:mi>y</m:mi><m:mo>|</m:mo><m:mo><</m:mo></m:mrow><m:msub><m:mi>δ</m:mi><m:mi>n</m:mi></m:msub><m:mo>.</m:mo></m:mrow></m:math>
Such a <m:math overflow="scroll"><m:msub><m:mi>δ</m:mi><m:mi>n</m:mi></m:msub></m:math> exists by the uniform continuity of <m:math overflow="scroll"><m:mi>f</m:mi></m:math> on <m:math overflow="scroll"><m:mrow><m:mo>[</m:mo><m:mi>a</m:mi><m:mo>,</m:mo><m:mi>b</m:mi><m:mo>]</m:mo><m:mo>.</m:mo></m:mrow></m:math>
Let <m:math overflow="scroll"><m:mrow><m:msub><m:mi>P</m:mi><m:mi>n</m:mi></m:msub><m:mo>=</m:mo><m:mrow><m:mo>{</m:mo><m:msub><m:mi>x</m:mi><m:mn>0</m:mn></m:msub><m:mo><</m:mo><m:msub><m:mi>x</m:mi><m:mn>1</m:mn></m:msub><m:mo><</m:mo><m:mo>...</m:mo><m:mo><</m:mo><m:msub><m:mi>x</m:mi><m:msub><m:mi>m</m:mi><m:mi>n</m:mi></m:msub></m:msub><m:mo>}</m:mo></m:mrow></m:mrow></m:math> be a partition
of <m:math overflow="scroll"><m:mrow><m:mo>[</m:mo><m:mi>a</m:mi><m:mo>,</m:mo><m:mi>b</m:mi><m:mo>]</m:mo></m:mrow></m:math> for which <m:math overflow="scroll"><m:mrow><m:msub><m:mi>x</m:mi><m:mi>i</m:mi></m:msub><m:mo>-</m:mo><m:msub><m:mi>x</m:mi><m:mrow><m:mi>i</m:mi><m:mo>-</m:mo><m:mn>1</m:mn></m:mrow></m:msub><m:mo><</m:mo><m:msub><m:mi>δ</m:mi><m:mi>n</m:mi></m:msub></m:mrow></m:math> for all <m:math overflow="scroll"><m:mrow><m:mn>1</m:mn><m:mo>≤</m:mo><m:mi>i</m:mi><m:mo>≤</m:mo><m:msub><m:mi>m</m:mi><m:mi>n</m:mi></m:msub><m:mo>.</m:mo></m:mrow></m:math>
Define a step function <m:math overflow="scroll"><m:msub><m:mi>h</m:mi><m:mi>n</m:mi></m:msub></m:math> on <m:math overflow="scroll"><m:mrow><m:mo>[</m:mo><m:mi>a</m:mi><m:mo>,</m:mo><m:mi>b</m:mi><m:mo>]</m:mo></m:mrow></m:math> as follows:</para>
<para id="id68034">If <m:math overflow="scroll"><m:mrow><m:msub><m:mi>x</m:mi><m:mrow><m:mi>i</m:mi><m:mo>-</m:mo><m:mn>1</m:mn></m:mrow></m:msub><m:mo>≤</m:mo><m:mi>x</m:mi><m:mo><</m:mo><m:msub><m:mi>x</m:mi><m:mi>i</m:mi></m:msub><m:mo>,</m:mo></m:mrow></m:math> then <m:math overflow="scroll"><m:mrow><m:msub><m:mi>h</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:msub><m:mi>x</m:mi><m:mrow><m:mi>i</m:mi><m:mo>-</m:mo><m:mn>1</m:mn></m:mrow></m:msub><m:mo>)</m:mo></m:mrow><m:mo>.</m:mo></m:mrow></m:math>
This defines <m:math overflow="scroll"><m:mrow><m:msub><m:mi>h</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow></m:mrow></m:math> for every <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>∈</m:mo><m:mo>[</m:mo><m:mi>a</m:mi><m:mo>,</m:mo><m:mi>b</m:mi><m:mo>)</m:mo><m:mo>,</m:mo></m:mrow></m:math> and we complete the definition of
<m:math overflow="scroll"><m:msub><m:mi>h</m:mi><m:mi>n</m:mi></m:msub></m:math> by setting <m:math overflow="scroll"><m:mrow><m:msub><m:mi>h</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>b</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:mi>b</m:mi><m:mo>)</m:mo></m:mrow><m:mo>.</m:mo></m:mrow></m:math>
It follows immediately that <m:math overflow="scroll"><m:msub><m:mi>h</m:mi><m:mi>n</m:mi></m:msub></m:math> is a step function.</para>
<para id="id68234">Now, we claim that <m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>-</m:mo></m:mrow><m:msub><m:mi>h</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mrow><m:mo>(</m:mo><m:mi>x</m:mi><m:mo>)</m:mo></m:mrow><m:mo>|</m:mo><m:mo><</m:mo><m:mn>1</m:mn><m:mo>/</m:mo><m:mi>n</m:mi></m:mrow></m:mrow></m:math> for all <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>∈</m:mo><m:mo>[</m:mo><m:mi>a</m:mi><m:mo>,</m:mo><m:mi>b</m:mi><m:mo>]</m:mo><m:mo>.</m:mo></m:mrow></m:math>
This is clearly the case for <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>=</m:mo><m:mi>b</m:mi><m:mo>,</m:mo></m:mrow></m:math> since <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:mi>b</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:msub><m:mi>h</m:mi><m:mi>n</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mi>b</m:mi><m:mo>)</m:mo></m:mrow></m:mrow></m:math> for all <m:math overflow="scroll"><m:mrow><m:mi>n</m:mi><m:mo>.</m:mo></m:mrow></m:math>
For any other <m:math overflow="scroll"><m:mrow><m:mi>x</m:mi><m:mo>,</m:mo></m:mrow></m:math> let <m:math overflow="scroll"><m:mi>i</m:mi></m:math> be the unique index
such that <m:math overflow="scroll"><m:mrow><m:msub><m:mi>x</m:mi><m:mrow><m:mi>i</m:mi><m:mo>-</m:mo><m:mn>1</m:mn></m:mrow></m:msub><m:mo>≤</m:mo><m:mi>x</m:mi><m:mo><</m:mo><m:msub><m:mi>x</m:mi><m:mi>i</m:mi></m:msub><m:mo>.</m:mo></m:mrow></m:math> Then</para>
<equation id="id68433">
<m:math overflow="scroll" mode="display">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:msub>
<m:mi>h</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
<m:mo>=</m:mo>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>x</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
</m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:msub>
<m:mi>x</m:mi>
<m:mrow>
<m:mi>i</m:mi>
<m:mo>-</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msub>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mo><</m:mo>
<m:mn>1</m:mn>
<m:mo>/</m:mo>
<m:mi>n</m:mi>
</m:mrow>
</m:mrow>
</m:math>
</equation>
<para id="id68524">because <m:math overflow="scroll"><m:mrow><m:mrow><m:mo>|</m:mo><m:mi>x</m:mi><m:mo>-</m:mo></m:mrow><m:msub><m:mi>x</m:mi><m:mrow><m:mi>i</m:mi><m:mo>-</m:mo><m:mn>1</m:mn></m:mrow></m:msub><m:mrow><m:mo>|</m:mo><m:mo><</m:mo></m:mrow><m:msub><m:mi>δ</m:mi><m:mi>n</m:mi></m:msub><m:mo>.</m:mo></m:mrow></m:math></para>
<para id="id68572">So, we have defined a sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>h</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> of step functions, and
the sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>h</m:mi><m:mi>n</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> converges uniformly to <m:math overflow="scroll"><m:mi>f</m:mi></m:math>
by <link target-id="fs-id1167590259636"/>.</para>
</proof></rule>
<para id="id68625">We close this chapter with a famous theorem of Abel concerning
the behavior of a power series function on the boundary of its disk of convergence.
See the comments following <link target-id="fs-id1171771434001" document="m36165"/>.</para>
<rule id="fs-id8568340" type="theorem"><title>Abel</title><statement id="fs-id2099621">
<para id="id68630">
Suppose <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>∞</m:mi></m:msubsup><m:msub><m:mi>a</m:mi><m:mi>n</m:mi></m:msub><m:msup><m:mi>z</m:mi><m:mi>n</m:mi></m:msup></m:mrow></m:math> is a power series function having finite radius of convergence <m:math overflow="scroll"><m:mrow><m:mi>r</m:mi><m:mo>></m:mo><m:mn>0</m:mn><m:mo>,</m:mo></m:mrow></m:math>
and suppose there exists a point <m:math overflow="scroll"><m:msub><m:mi>z</m:mi><m:mn>0</m:mn></m:msub></m:math> on the boundary of <m:math overflow="scroll"><m:mrow><m:msub><m:mi>B</m:mi><m:mi>r</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mn>0</m:mn><m:mo>)</m:mo></m:mrow></m:mrow></m:math> that is in the domain of <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>;</m:mo></m:mrow></m:math>
i.e., <m:math overflow="scroll"><m:mrow><m:mo>∑</m:mo><m:msub><m:mi>a</m:mi><m:mi>n</m:mi></m:msub><m:msubsup><m:mi>z</m:mi><m:mn>0</m:mn><m:mi>n</m:mi></m:msubsup></m:mrow></m:math> converges to <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>(</m:mo><m:msub><m:mi>z</m:mi><m:mn>0</m:mn></m:msub><m:mo>)</m:mo><m:mo>.</m:mo></m:mrow></m:math>
Suppose <m:math overflow="scroll"><m:mi>g</m:mi></m:math> is a continuous function whose domain contains the open disk <m:math overflow="scroll"><m:mrow><m:msub><m:mi>B</m:mi><m:mi>r</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mn>0</m:mn><m:mo>)</m:mo></m:mrow></m:mrow></m:math> as well as the point <m:math overflow="scroll"><m:mrow><m:msub><m:mi>z</m:mi><m:mn>0</m:mn></m:msub><m:mo>,</m:mo></m:mrow></m:math>
and assume that <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo><m:mo>=</m:mo><m:mi>g</m:mi><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow></m:math> for all <m:math overflow="scroll"><m:mi>z</m:mi></m:math> in the open disk <m:math overflow="scroll"><m:mrow><m:msub><m:mi>B</m:mi><m:mi>r</m:mi></m:msub><m:mrow><m:mo>(</m:mo><m:mn>0</m:mn><m:mo>)</m:mo></m:mrow><m:mo>.</m:mo></m:mrow></m:math>
Then <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>(</m:mo><m:msub><m:mi>z</m:mi><m:mn>0</m:mn></m:msub><m:mo>)</m:mo></m:mrow></m:math> must equal <m:math overflow="scroll"><m:mrow><m:mi>g</m:mi><m:mo>(</m:mo><m:msub><m:mi>z</m:mi><m:mn>0</m:mn></m:msub><m:mo>)</m:mo><m:mo>.</m:mo></m:mrow></m:math></para>
</statement>
<proof id="fs-id1167588853591">
<para id="id68961">
For simplicity, assume that <m:math overflow="scroll"><m:mrow><m:mi>r</m:mi><m:mo>=</m:mo><m:mn>1</m:mn></m:mrow></m:math> and that
<m:math overflow="scroll"><m:mrow><m:msub><m:mi>z</m:mi><m:mn>0</m:mn></m:msub><m:mo>=</m:mo><m:mn>1</m:mn><m:mo>.</m:mo></m:mrow></m:math> See the exercise that follows this proof.
Write <m:math overflow="scroll"><m:msub><m:mi>S</m:mi><m:mi>n</m:mi></m:msub></m:math> for the partial sum of the <m:math overflow="scroll"><m:msub><m:mi>a</m:mi><m:mi>n</m:mi></m:msub></m:math>'s: <m:math overflow="scroll"><m:mrow><m:msub><m:mi>S</m:mi><m:mi>n</m:mi></m:msub><m:mo>=</m:mo><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>n</m:mi></m:msubsup><m:msub><m:mi>a</m:mi><m:mi>n</m:mi></m:msub><m:mo>.</m:mo></m:mrow></m:math>
In the following computation, we will use the Abel Summation Formula
in the form</para>
<equation id="id69078">
<m:math overflow="scroll" mode="display">
<m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>z</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>=</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:msup>
<m:mi>z</m:mi>
<m:mi>N</m:mi>
</m:msup>
<m:mo>+</m:mo>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mrow>
<m:mi>N</m:mi>
<m:mo>-</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:munderover>
<m:msub>
<m:mi>S</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>z</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>-</m:mo>
<m:msup>
<m:mi>z</m:mi>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msup>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>.</m:mo>
</m:mrow>
</m:math>
</equation>
<para id="id69196">See <link target-id="fs-id1172705600778" document="m36135"/>.
Let <m:math overflow="scroll"><m:mi>ϵ</m:mi></m:math> be a positive number. Then, for any <m:math overflow="scroll"><m:mrow><m:mn>0</m:mn><m:mo><</m:mo><m:mi>t</m:mi><m:mo><</m:mo><m:mn>1</m:mn></m:mrow></m:math> and any positive integer <m:math overflow="scroll"><m:mrow><m:mi>N</m:mi><m:mo>,</m:mo></m:mrow></m:math> we have</para>
<equation id="uid13">
<m:math overflow="scroll" mode="display">
<m:mtable displaystyle="true">
<m:mtr>
<m:mtd columnalign="right">
<m:mrow>
<m:mo>|</m:mo>
<m:mi>g</m:mi>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
<m:mo>|</m:mo>
</m:mrow>
</m:mtd>
<m:mtd>
<m:mo>=</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>+</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>+</m:mo>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mrow>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>≤</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mrow>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>≤</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd/>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mspace width="1.em"/>
<m:mspace width="1.em"/>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>N</m:mi>
</m:msup>
<m:mo>+</m:mo>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mrow>
<m:mi>N</m:mi>
<m:mo>-</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:munderover>
<m:msub>
<m:mi>S</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>-</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msup>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>=</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd/>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mspace width="1.em"/>
<m:mspace width="1.em"/>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>N</m:mi>
</m:msup>
<m:mo>+</m:mo>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mrow>
<m:mi>N</m:mi>
<m:mo>-</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:munderover>
<m:mrow>
<m:mo>(</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mo>-</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>-</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msup>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>+</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mrow>
<m:mi>N</m:mi>
<m:mo>-</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:munderover>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>-</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msup>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>=</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd/>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mspace width="1.em"/>
<m:mspace width="1.em"/>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mrow>
<m:mi>N</m:mi>
<m:mo>-</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:munderover>
<m:mrow>
<m:mo>(</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mo>-</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>-</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msup>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>+</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mi>N</m:mi>
</m:msup>
<m:mo>+</m:mo>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mrow>
<m:mi>N</m:mi>
<m:mo>-</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:munderover>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>-</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msup>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>≤</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd/>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mspace width="1.em"/>
<m:mspace width="1.em"/>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mrow>
<m:mi>N</m:mi>
<m:mo>-</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:munderover>
<m:mrow>
<m:mo>(</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mo>-</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>-</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msup>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>≤</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd/>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mspace width="1.em"/>
<m:mspace width="1.em"/>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>P</m:mi>
</m:munderover>
<m:mrow>
<m:mo>(</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mo>-</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>-</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msup>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mi>P</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
<m:mrow>
<m:mi>N</m:mi>
<m:mo>-</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:munderover>
<m:mrow>
<m:mo>(</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mo>-</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>-</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msup>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>≤</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
<m:mi>g</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mi>t</m:mi>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>-</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>N</m:mi>
</m:munderover>
<m:msub>
<m:mi>a</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd/>
<m:mtd columnalign="left">
<m:mrow>
<m:mrow>
<m:mspace width="1.em"/>
<m:mspace width="1.em"/>
<m:mo>+</m:mo>
<m:mo>|</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mn>0</m:mn>
</m:mrow>
<m:mi>P</m:mi>
</m:munderover>
<m:mrow>
<m:mo>(</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mo>-</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>-</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msup>
<m:mo>)</m:mo>
</m:mrow>
<m:mrow>
<m:mo>|</m:mo>
<m:mo>+</m:mo>
</m:mrow>
<m:munderover>
<m:mo>∑</m:mo>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>=</m:mo>
<m:mi>P</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
<m:mrow>
<m:mi>N</m:mi>
<m:mo>-</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:munderover>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
<m:msub>
<m:mi>S</m:mi>
<m:mi>n</m:mi>
</m:msub>
<m:mo>-</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mrow>
<m:mo>|</m:mo>
</m:mrow>
<m:mrow>
<m:mo>(</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mi>n</m:mi>
</m:msup>
<m:mo>-</m:mo>
<m:msup>
<m:mi>t</m:mi>
<m:mrow>
<m:mi>n</m:mi>
<m:mo>+</m:mo>
<m:mn>1</m:mn>
</m:mrow>
</m:msup>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>+</m:mo>
<m:mrow>
<m:mo>|</m:mo>
<m:msub>
<m:mi>S</m:mi>
<m:mi>N</m:mi>
</m:msub>
<m:mo>-</m:mo>
<m:mi>f</m:mi>
<m:mrow>
<m:mo>(</m:mo>
<m:mn>1</m:mn>
<m:mo>)</m:mo>
</m:mrow>
<m:mo>|</m:mo>
</m:mrow>
</m:mrow>
</m:mtd>
</m:mtr>
<m:mtr>
<m:mtd/>
<m:mtd>
<m:mo>=</m:mo>
</m:mtd>
<m:mtd columnalign="left">
<m:mrow>
<m:msub>
<m:mi>t</m:mi>
<m:mn>1</m:mn>
</m:msub>
<m:mo>+</m:mo>
<m:msub>
<m:mi>t</m:mi>
<m:mn>2</m:mn>
</m:msub>
<m:mo>+</m:mo>
<m:msub>
<m:mi>t</m:mi>
<m:mn>3</m:mn>
</m:msub>
<m:mo>+</m:mo>
<m:msub>
<m:mi>t</m:mi>
<m:mn>4</m:mn>
</m:msub>
<m:mo>+</m:mo>
<m:msub>
<m:mi>t</m:mi>
<m:mn>5</m:mn>
</m:msub>
<m:mo>.</m:mo>
</m:mrow>
</m:mtd>
</m:mtr>
</m:mtable>
</m:math>
</equation>
<para id="id71110">First, choose an integer <m:math overflow="scroll"><m:msub><m:mi>M</m:mi><m:mn>1</m:mn></m:msub></m:math> so that if <m:math overflow="scroll"><m:mi>P</m:mi></m:math> and <m:math overflow="scroll"><m:mi>N</m:mi></m:math> are both larger than <m:math overflow="scroll"><m:mrow><m:msub><m:mi>M</m:mi><m:mn>1</m:mn></m:msub><m:mo>,</m:mo></m:mrow></m:math> then <m:math overflow="scroll"><m:mrow><m:msub><m:mi>t</m:mi><m:mn>4</m:mn></m:msub><m:mo><</m:mo><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:math>
(The sequence <m:math overflow="scroll"><m:mrow><m:mo>{</m:mo><m:msub><m:mi>S</m:mi><m:mi>k</m:mi></m:msub><m:mo>}</m:mo></m:mrow></m:math> is a Cauchy sequence, and <m:math overflow="scroll"><m:mrow><m:mo>∑</m:mo><m:mo>(</m:mo><m:msup><m:mi>t</m:mi><m:mi>k</m:mi></m:msup><m:mo>-</m:mo><m:msup><m:mi>t</m:mi><m:mrow><m:mi>k</m:mi><m:mo>+</m:mo><m:mn>1</m:mn></m:mrow></m:msup></m:mrow></m:math> is telescoping.)</para>
<para id="id71242">Fix such a <m:math overflow="scroll"><m:mrow><m:mi>P</m:mi><m:mo>></m:mo><m:msub><m:mi>M</m:mi><m:mn>1</m:mn></m:msub><m:mo>.</m:mo></m:mrow></m:math> Then choose a <m:math overflow="scroll"><m:mrow><m:mi>δ</m:mi><m:mo>></m:mo><m:mn>0</m:mn></m:mrow></m:math> so that if <m:math overflow="scroll"><m:mrow><m:mn>1</m:mn><m:mo>></m:mo><m:mi>t</m:mi><m:mo>></m:mo><m:mn>1</m:mn><m:mo>-</m:mo><m:mi>δ</m:mi><m:mo>,</m:mo></m:mrow></m:math> then both <m:math overflow="scroll"><m:msub><m:mi>t</m:mi><m:mn>1</m:mn></m:msub></m:math> and <m:math overflow="scroll"><m:mrow><m:msub><m:mi>t</m:mi><m:mn>3</m:mn></m:msub><m:mo><</m:mo><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:math>
How?</para>
<para id="id71344">Fix such a <m:math overflow="scroll"><m:mrow><m:mi>t</m:mi><m:mo>.</m:mo></m:mrow></m:math> Finally, choose a <m:math overflow="scroll"><m:mrow><m:mi>N</m:mi><m:mo>,</m:mo></m:mrow></m:math> greater than <m:math overflow="scroll"><m:mrow><m:msub><m:mi>M</m:mi><m:mn>1</m:mn></m:msub><m:mo>,</m:mo></m:mrow></m:math> and also
large enough so that both <m:math overflow="scroll"><m:msub><m:mi>t</m:mi><m:mn>2</m:mn></m:msub></m:math> and <m:math overflow="scroll"><m:msub><m:mi>t</m:mi><m:mn>5</m:mn></m:msub></m:math> are less than <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:math>
(How?)</para>
<para id="id71429">Now, <m:math overflow="scroll"><m:mrow><m:mo>|</m:mo><m:mi>g</m:mi><m:mo>(</m:mo><m:mn>1</m:mn><m:mo>)</m:mo><m:mo>-</m:mo><m:mi>f</m:mi><m:mo>(</m:mo><m:mn>1</m:mn><m:mo>)</m:mo><m:mo>|</m:mo><m:mo><</m:mo><m:mn>5</m:mn><m:mi>ϵ</m:mi><m:mo>.</m:mo></m:mrow></m:math>
Since this is true for every <m:math overflow="scroll"><m:mrow><m:mi>ϵ</m:mi><m:mo>></m:mo><m:mn>0</m:mn><m:mo>,</m:mo></m:mrow></m:math> it follows that <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>(</m:mo><m:mn>1</m:mn><m:mo>)</m:mo><m:mo>=</m:mo><m:mi>g</m:mi><m:mo>(</m:mo><m:mn>1</m:mn><m:mo>)</m:mo><m:mo>,</m:mo></m:mrow></m:math>
and the theorem is proved.</para>
</proof></rule>
<exercise id="fs-id1167591866406"><problem id="fs-id1167596231342">
<para id="id71520">
Let <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mo>,</m:mo><m:mi>g</m:mi><m:mo>,</m:mo><m:mi>r</m:mi><m:mo>,</m:mo></m:mrow></m:math> and <m:math overflow="scroll"><m:msub><m:mi>z</m:mi><m:mn>0</m:mn></m:msub></m:math> be as in the statement of the preceding theorem.
Define <m:math overflow="scroll"><m:mrow><m:mover accent="true"><m:mi>f</m:mi><m:mo>^</m:mo></m:mover><m:mrow><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:msub><m:mi>z</m:mi><m:mn>0</m:mn></m:msub><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow></m:mrow></m:math> and <m:math overflow="scroll"><m:mrow><m:mover accent="true"><m:mi>g</m:mi><m:mo>^</m:mo></m:mover><m:mrow><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:mi>g</m:mi><m:mrow><m:mo>(</m:mo><m:msub><m:mi>z</m:mi><m:mn>0</m:mn></m:msub><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow><m:mo>.</m:mo></m:mrow></m:math></para>
<list id="id71654" display="block" list-type="enumerated" number-style="lower-alpha"><item id="uid14"> Prove that <m:math overflow="scroll"><m:mover accent="true"><m:mi>f</m:mi><m:mo>^</m:mo></m:mover></m:math> is a power series function
<m:math overflow="scroll"><m:mrow><m:mover accent="true"><m:mi>f</m:mi><m:mo>^</m:mo></m:mover><m:mrow><m:mo>(</m:mo><m:mi>z</m:mi><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>∞</m:mi></m:msubsup><m:msub><m:mi>b</m:mi><m:mi>n</m:mi></m:msub><m:msup><m:mi>z</m:mi><m:mi>n</m:mi></m:msup><m:mo>,</m:mo></m:mrow></m:math>
with radius of convergence equal to 1,
and such that <m:math overflow="scroll"><m:mrow><m:msubsup><m:mo>∑</m:mo><m:mrow><m:mi>n</m:mi><m:mo>=</m:mo><m:mn>0</m:mn></m:mrow><m:mi>∞</m:mi></m:msubsup><m:msub><m:mi>b</m:mi><m:mi>n</m:mi></m:msub></m:mrow></m:math> converges to <m:math overflow="scroll"><m:mrow><m:mover accent="true"><m:mi>f</m:mi><m:mo>^</m:mo></m:mover><m:mrow><m:mo>(</m:mo><m:mn>1</m:mn><m:mo>)</m:mo></m:mrow><m:mo>;</m:mo></m:mrow></m:math> i.e., 1 is in the domain of <m:math overflow="scroll"><m:mrow><m:mover accent="true"><m:mi>f</m:mi><m:mo>^</m:mo></m:mover><m:mo>.</m:mo></m:mrow></m:math></item>
<item id="uid15"> Show that <m:math overflow="scroll"><m:mover accent="true"><m:mi>g</m:mi><m:mo>^</m:mo></m:mover></m:math> is a continuous function whose domain contains the open disk <m:math overflow="scroll"><m:mrow><m:msub><m:mi>B</m:mi><m:mn>1</m:mn></m:msub><m:mrow><m:mo>(</m:mo><m:mn>0</m:mn><m:mo>)</m:mo></m:mrow></m:mrow></m:math> and the point <m:math overflow="scroll"><m:mrow><m:mi>z</m:mi><m:mo>=</m:mo><m:mn>1</m:mn><m:mo>.</m:mo></m:mrow></m:math></item>
<item id="uid16"> Show that, if <m:math overflow="scroll"><m:mrow><m:mover accent="true"><m:mi>f</m:mi><m:mo>^</m:mo></m:mover><m:mrow><m:mo>(</m:mo><m:mn>1</m:mn><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:mover accent="true"><m:mi>g</m:mi><m:mo>^</m:mo></m:mover><m:mrow><m:mo>(</m:mo><m:mn>1</m:mn><m:mo>)</m:mo></m:mrow><m:mo>,</m:mo></m:mrow></m:math> then <m:math overflow="scroll"><m:mrow><m:mi>f</m:mi><m:mrow><m:mo>(</m:mo><m:msub><m:mi>z</m:mi><m:mn>0</m:mn></m:msub><m:mo>)</m:mo></m:mrow><m:mo>=</m:mo><m:mi>g</m:mi><m:mrow><m:mo>(</m:mo><m:msub><m:mi>z</m:mi><m:mn>0</m:mn></m:msub><m:mo>)</m:mo></m:mrow><m:mo>.</m:mo></m:mrow></m:math>
Deduce that the simplification in the preceding proof is justified.
</item>
<item id="uid17"> State and prove the generalization of Abel's Theorem to a function <m:math overflow="scroll"><m:mi>f</m:mi></m:math> that is expandable in a Taylor series around a point <m:math overflow="scroll"><m:mrow><m:mi>c</m:mi><m:mo>.</m:mo></m:mrow></m:math></item>
</list>
</problem></exercise>
</content>
</document>
|
# 배열
## 📌 배열이란?
값으로 이루어진 집합이며 배열의 특징은 저장되어 있는 값을 인덱스라는 순서인 숫자로 요소를 검색할 수 있는 자료구조이다.
## 📌 배열 (Create, Read, Update, Delete)
### 🧩 Create : 배열을 생성하는 행위
```javascript
// 빈 배열을 arr에 할당한다.
const arr = [];
```
### 🧩 Read : 배열의 요소를 조회하는 행위
```javascript
const arr = [1,2,3,4];
// 배열 arr의 0번째 요소를 조회한다.
console.log(arr[0]);
```
### 🧩 Update : 배열의 요소를 변경하는 행위
```javascript
const arr = [1,2,3,4];
// 배열 arr의 0번째 요소를 10으로 변경한다.
arr[0] = 10;
// 배열 arr를 조회한다.
console.log(arr);
```
### 🧩 delete : 배열의 요소를 제거하는 행위
delete 연산자를 사용해서 제거도 가능하지만 인덱스가 남으며 그자리에 undefined가 할당된다
인덱스도 제거하기 위해 보통 splice 메소드를 사용한다.
```javascript
const arr = [1,2,3,4];
delete arr[0];
// 결과 : [ <1 empty item>, 2, 3, 4 ]
console.log(arr);
// 결과 : undefined
console.log(arr[0]);
```
```javascript
const arr = [1,2,3,4];
// 0번 인덱스부터 1개의 요소를 제거
arr.splice(0, 1);
// 결과 : [2, 3, 4]
console.log(arr);
```
## 📌 배열의 길이를 조회하는 방법
프로퍼티 length를 사용하며 배열의 총 요소의 개수의 정보를 갖고 있다.
- Syntax : (조회하고싶은 배열).length
```javascript
const arr = [1,2,3,4,5];
// 결과 : 5 출력
console.log(arr.length);
// 결과 : 4 출력
console.log([1,2,3,4].length);
```
## 📌 2차원 배열 선언과 조회하는 방법
2차원 배열을 선언하는 방법은 배열안에 요소를 배열로 전달한다.
```javascript
// 2차원 배열 선언
const arr = [[1,2], [3,4], [5,6]];
// arr의 0번째 요소인 [1,2] 값에서 0번째 요소를 조회 결과 : 1
console.log(arr[0][0]);
// arr의 1번째 요소인 [3,4] 값에서 0번째 요소를 조회 결과 : 3
console.log(arr[1][0]);
```
## 📌 배열의 요소를 순회 하는 방법
### 🧩 1차원 배열
```javascript
const arr = [1,2,3,4];
// 0 ~ arr.length - 1 까지 반복문을 실행
for(let i = 0; i < arr.length; i++) {
// i에 해당되는 요소 조회
console.log(arr[i]);
}
```
배열의 길이는 4이지만 배열의 마지막 인덱스번호는 3이다. 왜냐하면 배열의 시작점은 0번째 요소부터 시작한다.
### 🧩 2차원 배열
```javascript
const arr = [[1,2], [3,4]];
// 0 ~ arr.length - 1 까지 반복문 실행
for(let i = 0; i < arr.length; i++) {
// 0부터 arr의 요소가 배열이므로 그 배열의 길이 - 1 까지 반복문을 실행한다.
for(let j = 0; j < arr[i].length; j++) {
// arr[i]번째 요소인 배열의 j번째 요소를 조회
console.log(arr[i][j]);
}
}
```
> - split(), join(), slice(), splice(), Array.isArray(), push(), unshift(), pop(), shift(), indexOf(), includes()
## 📌 배열의 타입 확인
정적 메소드 isArray를 사용한다.
- Syntax : Array.isArray(조회하고 싶은 변수나 값)
- 사용 목적 : typeof 연산자로 배열의 타입을 확인하면 "object"를 반환하기 때문이다.
```javascript
const arr = [1,2,3];
// 결과 : "object"
console.log(typeof arr);
```
```javascript
const arr = [1,2,3];
const str = "string";
// 결과 : true
console.log(Array.isArray(arr));
// 결과 : false
console.log(Array.isArray(str));
// 결과 : false
console.log(Array.isArray(3));
```
|
import * as React from "react"
type AnimateOnScrollProps = {
className?: string
transition: string
delay?: string
ease?: string
}
function AnimateOnScroll({
className,
transition,
delay,
ease,
children,
}: React.PropsWithChildren<AnimateOnScrollProps>) {
return (
<div
className={className}
data-sal={transition}
data-sal-delay={delay || 0}
data-sal-easing={ease || "ease"}
>
{children}
</div>
)
}
export default AnimateOnScroll
|
import React, { useEffect, useState} from "react";
import {
Card,CardContent, Typography,Box, Table, TableHead, TableRow, TableCell, TableBody,
Avatar, Backdrop, CircularProgress, IconButton, Button
} from "@material-ui/core";
import { CheckCircleTwoTone, CloseCircleFilled, LoadingOutlined } from '@ant-design/icons';
import { NavLink, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { fetchUsers, removeUser, updateUserVerified } from "../../reducers/usersReducer";
import axios from "axios";
// import AlignMessage from "./alignMessage";
const NewUser = () => {
const [age,setAge] = React.useState("10");
const {userData: {role}} = useSelector(state => state.auth);
const {loading, users, error} = useSelector(state => state.users);
const navigate = useNavigate();
const dispatch = useDispatch();
useEffect(() => {
if(role !== "admin") {
navigate("/dashboard/dashboard/home", {replace: true});
}
dispatch(fetchUsers());
}, [])
const handleChange = (event) => {
setAge(event.target.value);
};
return(
<Card variant="outlined">
<CardContent>
<Box sx={{
display: {
sm: "flex",
xs: "block",
height: "8px",
},
alignItems:"flex-start"
}}>
<Box>
<Typography variant="h3" sx={{marginBottom: "0", color:"blue",fontSize:"25px"}} gutterBottom>
New Users
</Typography>
</Box>
<Box sx={{
marginLeft: "auto",
mt: {
lg: 0,
xs: 2,
},
}}>
</Box>
</Box>
<Box
sx={{
overflow: "auto",
mt: 3,
}}>
{
loading
? <Backdrop
sx={{ color: '#fff', zIndex: 99}}
open={loading}
>
<CircularProgress color="inherit" />
</Backdrop>
:
<Table>
<TableHead>
<TableCell><Typography>N</Typography></TableCell>
<TableCell><Typography>Avatar</Typography></TableCell>
<TableCell><Typography>Name & Email</Typography></TableCell>
<TableCell><Typography>Role</Typography></TableCell>
<TableCell><Typography>Action</Typography></TableCell>
</TableHead>
<TableBody>
{
users.map((user, i) => <User key={user._id} i={i} user={user} />)
}
</TableBody>
</Table>
}
</Box>
</CardContent>
</Card>
)
};
const User = ({user, i}) => {
const [settingVerified, setSettingVerified] = useState(false);
const [deletingUser, setDeletingUser] = useState(false);
const dispatch = useDispatch();
const {token} = useSelector(state => state.auth);
const stringAv = (user) => {
return {
children: user.firstName.toUpperCase()[0] + user.lastName.toUpperCase()[0],
alt: `${user.firstName} ${user.lastName}`,
sx: {bgcolor: ['cornflowerblue', 'darkslategray', 'brown'][i % 3]}
}
}
const handleVerifyUser = async () => {
setSettingVerified(state => true);
// request
await axios.request({
method: 'PATCH',
url: `https://inventory-ciul.onrender.com/api/auth/users/${user._id}/approve`,
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + token
}
}).then(res => {
if(res.status === 200) {
dispatch(updateUserVerified(user._id));
}
})
// update store.users
setSettingVerified(state => false);
}
const handleDeleteUser = async () => {
setDeletingUser(state => true);
// request
await axios.delete(
`https://inventory-ciul.onrender.com/api/auth/delete/users/${user._id}`,
{
headers: {
'Authorization': 'Bearer ' + token,
}
}).then((res) => {
if(res.status === 200) {
// update store.users
dispatch(removeUser(user._id));
}
})
setDeletingUser(state => false);
}
return (
<TableRow>
<TableCell>{i + 1}</TableCell>
<TableCell>
{
user.image
? <Avatar alt={user.firstName + ' ' + user.lastName} src={user.image} />
: <Avatar {...stringAv(user)} />
}
</TableCell>
<TableCell>
<Box sx={{flexDirection: 'column'}}>
<Typography >{user.firstName + ' ' + user.lastName}</Typography>
<Typography sx={{fontSize: 12}}>{user.email}</Typography>
</Box>
</TableCell>
<TableCell>
{user.role}
</TableCell>
<TableCell>
<IconButton aria-label="Approve user" sx={{}}>
{
settingVerified
? <LoadingOutlined color="#cacaca" />
: <CheckCircleTwoTone twoToneColor={user.isVerified ? '#52c41a' : '#cacaca'}
onClick={handleVerifyUser}
/>
}
</IconButton>
<IconButton aria-label="Delete user">
{
deletingUser
? <LoadingOutlined color="cacaca" />
: <CloseCircleFilled style={{backgroundColor: '#ee2244', color: 'white', borderRadius: '50%'}}
onClick={handleDeleteUser}
/>
}
</IconButton>
</TableCell>
</TableRow>
)
}
export default NewUser;
|
import { Controller, Get, Post, Body, Param, Delete, Put } from '@nestjs/common';
import { EpsService } from './eps.service';
import { CreateEpDto, UpdateEpsDto } from './dto/create-ep.dto';
import { ApiTags } from '@nestjs/swagger';
@ApiTags("EPS")
@Controller('eps')
export class EpsController {
constructor(private readonly epsService: EpsService) {}
@Post()
create(@Body() createEpDto: CreateEpDto) {
return this.epsService.create(createEpDto);
}
@Put('/eps/:id')
update(@Param('id') id: string, @Body() body:UpdateEpsDto ){
return this.epsService.update(id, body)
}
@Get()
findAll() {
return this.epsService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.epsService.findOne(+id);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.epsService.remove(id);
}
}
|
# 数据结构与算法基础
## 冒泡排序
### 冒泡排序怎么做?时间复杂度?
## 选择排序
## 二分查找
## 栈 堆 队列
##### Heap与Stack有何区别?
1. heap是堆,stack是栈。
2. stack的空间由操作系统自 动分配和释放,heap的空间是手动申请和释放的, heap常用new关键字来分配。
3. stack空间有限,heap 的空间是很大的自由区。
##### 栈溢出一般是由什么原因导致
1. 无限递归。函数递归调用时,系统要在栈中不断保存函数调用时的现场和产生的变量,如果递归调用太深,就会造成栈溢出,这时递归无法返回。再有,当函数调用层次过深时也可能导致栈无法容纳这些调用的返回地址而造成栈溢出。
2. 无限循环。
3. 大量局部变量分配。
### Stack栈和Queue队列
相同点:
1. 都是线性结构。
2. 插入操作都是限定在表尾进行。
3. 都可以通过顺序结构和链式结构实现。
4. 插入与删除的时间复杂度都是O(1),在空间复杂度上两者也一样。
5. 多链栈和多链队列的管理模式可以相同。
6. 底层都是由泛型数组实现。
不同点:
1. 栈先进后出,队列先进先出:删除数据元素的位置不同,栈的删除操作在表尾进行,队列的删除操作在表头进行。
2. 顺序栈能够实现多栈空间共享,而顺序队列不能。
3. 应用场景不同
常见栈的应用场景包括
1. 括号问题的求解,
2. 深度优先搜索遍历等;
3. 函数调用和递归实现,
4. 表达式的转换和求值
常见的队列的应用场景包括
1. 计算机系统中各种资源的管理,
2. 消息缓冲器的管理
3. 广度优先搜索遍历等
### 用栈实现队列 、 用队列实现栈
### 堆栈实现队列
## 二叉树
### 二叉树是怎么样的?如果将每一个叶子节点输出?具体算法如何实现?
## 链表
### 单双向链表的区别:
- 指向不同:单向链表只有一个指向下一结点的指针,双向链表除了有一个指向下一结点的指针外,还有一个指向前一结点的指针。
- 功能不同:单向链表只能next ,双向链表可以return。
- 单双向不同:单链表只能单向读取,双向链表可以双向遍历。
### 单向链表优缺点:
优点:单向链表增加删除节点简单。遍历时候不会死循环;
缺点:只能从头到尾遍历。只能找到后继,无法找到前驱,也就是只能前进。
### 双向链表优缺点:
优点:可以找到前驱和后继,可进可退;
缺点:增加删除节点复杂,多需要分配一个指针存储空间.
链表与数组的对比
1. 数组必须事先定义固定的长度(元素个数),不能适应数据动态地增减的情况。当数据增加时,可能超出原先定义的元素个数;当数据减少时,造成内存浪费;数组可以根据下标直接存取,时间复杂度O(1)。
2. 链表动态地进行存储分配,可以适应数据动态地增减的情况,且可以方便地插入、删除数据项。(数组中插入、删除数据项时,需要移动其它数据项,非常繁琐)链表必须根据next指针找到下一个元素。
如果需要快速访问数据,很少或不插入和删除元素,就应该用数组;相反,如果需要经常插入和删除元素就需要用链表数据结构了。
### 单链表翻转,adcde,转换成 edcba , 怎么做
### 单链表,输出倒数第2个,奇数个节点输出数据,节点倒序?
### 链表与数组的对比
## 哈希表
### 哈希表与字典对比
字典:内部用了Hashtable作为存储结构
如果我们试图找到一个不存在的键,它将返回 / 抛出异常。
它比哈希表更快,因为没有装箱和拆箱,尤其是值类型。
仅公共静态成员是线程安全的。
字典是一种通用类型,这意味着我们可以将其与任何数据类型一起使用(创建时,必须同时指定键和值的数据类型)。
Dictionay 是 Hashtable 的类型安全实现, Keys和Values是强类型的。
Dictionary遍历输出的顺序,就是加入的顺序
哈希表:
如果我们尝试查找不存在的键,则返回 null。
它比字典慢,因为它需要装箱和拆箱。
哈希表中的所有成员都是线程安全的,
哈希表不是通用类型,
Hashtable 是松散类型的数据结构,我们可以添加任何类型的键和值。
HashTable是经过优化的,访问下标的对象先散列过,所以内部是无序散列的
————————————————
### 哈希表的实现原理
### GetHashCode 方法的用途是什么?
### HashMap和HashTable
## 二叉树相关
计算深度(高度)
二叉树的高度是二叉树结点层次的最大值,也就是其左右子树的最大高度+1。当树为空时,高度为0;否则为其左右子树最大高度+1。
遍历:(看根节点的位置)
前序遍历:(根左右)先访问根节点,再访问左节点,再访问右节点。
中序遍历:(左根右)先访问左节点,再访问根节点,再访问右节点。
后序遍历:(左右根)先访问左节点,再访问右节点,再访问根节点。
# Unity 游戏常用算法
## 寻路算法:A* 算法
## Unity游戏常用洗牌算法
|
"""
Написать программу, которая обходит не взвешенный ориентированный граф без петель, в котором все вершины связаны,
по алгоритму поиска в глубину (Depth-First Search).
Примечания:
a. граф должен храниться в виде списка смежности;
b. генерация графа выполняется в отдельной функции, которая принимает на вход число вершин.
"""
import random
# Генератор случайного графа, в котором нет петель у каждой вершины есть как минимум один вход и выход.- Сильная связанность
# Граф описывается списком смежностей
def graph_generation(number_vertices):
graph = []
is_in = [False] * number_vertices
for i in range(number_vertices):
number_edges = random.randint(1, number_vertices - 1)
graph.append([])
l = 0
while l < number_edges:
vertex = random.randint(0, number_vertices - 1)
if vertex != i and not vertex in graph[i]:
graph[i].append(vertex)
is_in[vertex] = True
l += 1
# Проверим во всех ли вершинах есть вход
for i, data in enumerate(is_in):
if not data:
while not data:
choice = random.randint(0, number_vertices - 1)
if choice != i:
graph[choice].append(i)
is_in[i] = True
data = True
return graph
# Генерация графов без проверки входов. -Возможна слабая связанность
def graph_generation_2(number_vertices):
graph = []
for i in range(number_vertices):
number_edges = random.randint(1, number_vertices - 1)
graph.append([])
l = 0
while l < number_edges:
vertex = random.randint(0, number_vertices - 1)
if vertex != i and not vertex in graph[i]:
graph[i].append(vertex)
l += 1
return graph
def dfs(graph, start,visited=[]):
if len(visited)==0:
visited=[]
visited.append(start)
for i in graph[start]:
if i not in visited:
dfs(graph, i,visited)
return visited
n=int(input('Введите количество вершин'))
inp=int(input("Введите точку входа"))
# Выведем граф с сильной связностью
graph=graph_generation(n)
print(graph)
print(dfs(graph,inp))
# Выведем граф без гарантии сильной связанности
graph_2=graph_generation_2(n)
print(graph_2)
print(dfs(graph_2,inp))
|
import FileDownloadIcon from '@mui/icons-material/FileDownload';
import RestoreIcon from '@mui/icons-material/Restore';
import { ListItem, ListItemText, Typography } from '@mui/material';
import Button from '@mui/material/Button';
import PropTypes from 'prop-types';
import React from 'react';
const RestoreItem = (props) => {
const downloadBackupHandler = () => {
const blob = new Blob([JSON.stringify(props.backup.metadata)], {type: 'text/json'});
const link = document.createElement('a');
link.download = (props.backup.name)+'.json';
link.href = window.URL.createObjectURL(blob);
const eventClick = new MouseEvent('click', { view: window, bubbles: true, cancelable: true});
link.dispatchEvent(eventClick);
link.remove();
}
return (
<>
<ListItem key={props.backup.id} secondaryAction={
<div style={{display: 'flex', flexDirection: 'column', justifyContent: 'center'}}>
<Button color='primary' startIcon={<RestoreIcon />} onClick={() => { props.restoreHandler(props.backup) }}>
Restore
</Button>
<Button onClick={downloadBackupHandler} color='inherit' startIcon={<FileDownloadIcon />}>
Download
</Button>
</div>
}>
<ListItemText primary={props.backup.name+' (Version: '+props.backup.version+')'} secondary={
<React.Fragment>
<Typography sx={{display: 'inline'}} component={"span"} variant={"body2"} color="text.primary">{props.backup.backup_date}</Typography>
<br/>{props.backup.comment.substring(0, 100)}
</React.Fragment>
}/>
</ListItem>
{/*<Divider/>*/}
</>
)
}
RestoreItem.propTypes = {
backup: PropTypes.object,
restoreHandler: PropTypes.func
}
export default RestoreItem
|
package activity
import (
"context"
"time"
"github.com/edufriendchen/applet-platform/constant"
"github.com/edufriendchen/applet-platform/infrastructure/cache"
"github.com/edufriendchen/applet-platform/infrastructure/repository"
)
type Service struct {
cache cache.CacheStore
activityRepository repository.ActivityRepository
}
type IActivityService interface {
GetActivityList(ctx context.Context, req Request) ([]Response, error)
GetActivityDetail(ctx context.Context, id uint64) (DetailResponse, error)
ParticipateActivity(ctx context.Context, id uint64) error
AbandonActivity(ctx context.Context, req AbandonRequest) error
}
func NewActivityService(
cache cache.CacheStore,
activityRepository repository.ActivityRepository,
) IActivityService {
return &Service{
cache: cache,
activityRepository: activityRepository,
}
}
type Request struct {
ID uint64 `json:"id"`
PerPage int `json:"per_page"`
Page int `json:"page"`
Type constant.ActivityType `json:"type"`
StartTime *time.Time `json:"start_time"`
EndTime *time.Time `json:"end_time"`
Able bool `json:"able"`
}
type Response struct {
ID uint64 `json:"id"`
PosterUrl string `json:"poster_url"`
Title string `json:"title"`
Type constant.ActivityType `json:"type"`
Welfare string `json:"welfare"`
StartTime *time.Time `json:"start_time"`
EndTime *time.Time `json:"end_time"`
Able bool `json:"able"`
VisitNum int64 `json:"visit_num"`
}
type DetailResponse struct {
ID uint64 `json:"id"`
PosterUrl string `json:"poster_url"`
Type int `json:"type"`
Title string `json:"title"`
Content string `json:"content"`
Welfare string `json:"welfare"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Able bool `json:"able"`
}
type AbandonRequest struct {
ID uint64 `json:"id"`
Reason string `json:"reason"`
}
|
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomepageComponent } from './homepage/homepage.component';
import { RoompageComponent } from './roompage/roompage.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BookingpageComponent } from './bookingpage/bookingpage.component';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { UserRegistrationService } from './user-registration.service';
import { ListingComponent } from './listing/listing.component';
import { LoginComponent } from './auth/login/login.component';
import { SignupComponent } from './auth/signup/signup.component';
import { MatRadioModule } from '@angular/material/radio';
import { AdminpageComponent } from './adminpage/adminpage.component';
import { AdminlistComponent } from './adminlist/adminlist.component';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatTableModule } from '@angular/material/table';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule } from '@angular/material/dialog';
import { FirststepComponent } from './auth/firststep/firststep.component';
import { RestuarantComponent } from './restuarant/restuarant.component';
import { ShowHotelImagesDialogComponent } from './show-hotel-images-dialog/show-hotel-images-dialog.component';
import { SignComponent } from './auth/sign/sign.component';
import { MatSelectModule } from '@angular/material/select';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { BookpageComponent } from './bookpage/bookpage.component';
import { NavbarComponent } from './sharedComponent/navbar/navbar.component';
import { FooterComponent } from './sharedComponent/footer/footer.component';
import { MatCardModule } from '@angular/material/card';
import { LoginAdminComponent } from './auth/login-admin/login-admin.component';
import { HttpInterceptorInterceptor } from './interceptor/http-interceptor.interceptor';
@NgModule({
declarations: [
AppComponent,
HomepageComponent,
RoompageComponent,
BookingpageComponent,
ListingComponent,
LoginComponent,
SignupComponent,
AdminpageComponent,
AdminlistComponent,
FirststepComponent,
RestuarantComponent,
ShowHotelImagesDialogComponent,
SignComponent,
BookpageComponent,
NavbarComponent,
FooterComponent,
LoginAdminComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
MatRadioModule,
MatGridListModule,
MatTableModule,
MatIconModule,
MatButtonModule,
MatDialogModule,
MatSelectModule,
MatInputModule,
MatFormFieldModule,
MatDatepickerModule,
MatNativeDateModule,
MatCardModule
],
providers: [UserRegistrationService, { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorInterceptor, multi: true }],
bootstrap: [AppComponent]
})
export class AppModule { }
|
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
struct Page {
var words = 0
}
class Story {
var title = ""
var pages: [Page] = []
func addPage(_ page: Page) {
pages.append(page)
}
}
class ShortStory: Story {
var maxPageCount = 2
override func addPage(_ page: Page) {
if pages.count < maxPageCount {
super.addPage(page)
}
}
}
var story = ShortStory()
story.title = "The Haunting of Hill house"
story.addPage(Page(words: 300))
story.addPage(Page(words: 300))
story.addPage(Page(words: 300))
story.addPage(Page(words: 300))
story.pages.count
//: [Next](@next)
|
<!DOCTYPE HTML>
<!--
Title:
Util: пересечение прямоугольников при вычислении геокоординат
Description:
Проверка пересечения прямоугольников при вычислении геокоординат.
Памятка по терминам: https://wiki.yandex-team.ru/eva/testing/Projects/maps-api/
Components:
util
Estimated time:
180000
Precondition:
Открыть ссылку ${currentPagePath}
Step:
Action:
Осмотреть страницу и элементы на ней.
Expectation:
Карта отобразилась корректно со спаном материков Евразии и Северная Америка.
Step:
Action:
Выполнить клик в центр спана с левой стороны контейнера, затем клик в центр спана у правой стороны.
Expectation:
При клике на спане карты появляется синяя метка коллекции.
После второго клика на спане появляется область прямоугольника с вершинами - метками.
Step:
Action:
Выполнить клик в центр спана сверху контейнера, затем клик в центр спана снизу контейнера.
Expectation:
При клике на сверху спана карты появляется красная метка коллекции.
После второго клика на спане появляется область прямоугольника с вершинами - метками.
Область пересечения построенных прямоугольников окрашена красным, под контейнером с картой две строки с координатами, и две строки "OK".
-->
<html>
<head>
<title>2.1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="../../../helper.js"></script>
<script type=text/javascript>
Api('init');
function init(ymaps) {
//ymaps = ym;
var myMap = new ymaps.Map("map", {
center: [50, -179],
zoom: 3,
controls: []
}, {
geoObjectInteractivityModel: 'default#silent'
});
addGrid(myMap);
var log = new Log();
log.info("Построй два bounds, пересечение должно отображаться.");
var projection = myMap.options.get('projection'),
coords = [],
testBounds = [],
intersections;
myMap.events.add('click', function (e) {
if (testBounds.length == 2) {
clear();
}
coords.push(e.get('globalPixels'));
if (coords.length % 2 == 0) {
var bounds = ymaps.util.pixelBounds.fromPoints(coords.slice(-2), projection);
testBounds.push(bounds);
var rect = new ymaps.Rectangle(ymaps.util.bounds.fromGlobalPixelBounds(bounds, myMap.getZoom(), myMap.options.get('projection')), {}, {
opacity: 0.2
});
myMap.geoObjects.add(rect);
}
myMap.geoObjects.add(new ymaps.Placemark(e.get('coords'), {}, {
preset: (coords.length == 3) ? 'islands#redIcon' : 'islands#blueIcon'
}));
if (testBounds.length == 2) {
intersections = ymaps.util.pixelBounds.getIntersection(testBounds[0], testBounds[1]);
__log__(intersections);
__log__(ymaps.util.bounds.fromGlobalPixelBounds(intersections, myMap.getZoom(), myMap.options.get('projection')));
var rect = new ymaps.Rectangle(ymaps.util.bounds.fromGlobalPixelBounds(intersections, myMap.getZoom(), myMap.options.get('projection')), {}, {
fillColor: "FF0000",
opacity: 0.4
});
myMap.geoObjects.add(rect);
validateValue(ymaps.util.pixelBounds.containsBounds(testBounds[0], intersections), true);
if (!ymaps.util.pixelBounds.containsBounds(testBounds[0], intersections)) {
__log__('testBounds - ' + testBounds[0]);
__log__('intersections - ' + intersections[0]);
}
validateValue(ymaps.util.pixelBounds.containsBounds(testBounds[1], intersections), true);
if (!ymaps.util.pixelBounds.containsBounds(testBounds[1], intersections)) {
__log__('testBounds - ' + testBounds[1]);
__log__('intersections - ' + intersections);
}
}
});
function clear() {
myMap.geoObjects.removeAll();
coords = [];
testBounds = [];
intersections = [];
}
}
</script>
</head>
<body>
<div id="map" style="height: 512px; width: 512px;"></div>
</body>
</html>
|
<?php
namespace DemoPlugin;
use DemoPlugin\Contracts\HookAbleApiInterface;
use DemoPlugin\Contracts\HookAbleInterface;
use ReflectionClass;
final class DemoPlugin {
/**
* @var DemoPlugin|null
*/
protected static ?DemoPlugin $instance = null;
/**
* All the hook classes.
*
* @var array|string[]
*/
protected array $hook_classes = [
'DemoPlugin\Hooks\AdminMenu',
'DemoPlugin\Hooks\Assets',
];
/**
* All the controller classes.
*
* @var array<string, mixed>
*/
protected array $classes = [];
/**
* All the model classes.
*
* @var array<string, mixed>
*/
protected array $model_classes = [];
/**
* All the request classes.
*
* @var array<string, mixed>
*/
protected array $request_classes = [];
/**
* All the API classes.
*
* @var array|string[]
*/
protected array $api_classes = [
'DemoPlugin\REST\DepartmentApi',
];
/**
* Holds classes instances
*
* @var array<string, mixed>
*/
private array $container = [];
/**
* Get the single instance of the class
*
* @since PLUGIN_NAME_VERSION
* @return DemoPlugin
*/
public static function get_instance(): DemoPlugin {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Construct method for pluginName class.
*/
private function __construct() {
add_action( 'init', [ $this, 'set_translation' ] );
register_activation_hook( PLUGIN_NAME_FILE, [ $this, 'activate_this_plugin' ] );
add_action( 'plugins_loaded', [ $this, 'load_plugin_hooks' ] );
// Register REST API routes.
add_action( 'rest_api_init', [ $this, 'register_rest_routes' ] );
}
/**
* Magic getter to bypass referencing plugin.
*
* @param string $prop Property name.
*
* @return mixed
*/
public function __get( string $prop ) {
if ( array_key_exists( $prop, $this->container ) ) {
return $this->container[ $prop ];
}
return $this->{$prop};
}
/**
* Set Transaction Text Domain
*
* @since PLUGIN_NAME_VERSION
* @return void
*/
public function set_translation(): void {
load_plugin_textdomain( 'plugin-name', false, dirname( plugin_basename( PLUGIN_NAME_FILE ) ) . '/languages' );
}
/**
* On activate this plugin.
*
* @since PLUGIN_NAME_VERSION
* @return void
*/
public function activate_this_plugin(): void {
if ( ! get_option( 'plugin_name_installed' ) ) {
update_option( 'plugin_name_installed', time() );
}
update_option( 'plugin_name_version', PLUGIN_NAME_PLUGIN_VERSION );
flush_rewrite_rules();
}
/**
* Main point of loading the plugin.
*
* @since PLUGIN_NAME_VERSION
*
* @throws \ReflectionException
*
* @return void
*/
public function load_plugin_hooks(): void {
$this->load_hook_classes();
$this->load_classes( $this->classes );
$this->load_classes( $this->model_classes );
$this->load_classes( $this->request_classes );
do_action( 'plugin_name_loaded' );
}
/**
* Load all the hook classes.
*
* @since PLUGIN_NAME_VERSION
*
* @return void
*/
public function load_hook_classes() {
if ( empty( $this->hook_classes ) ) {
return;
}
foreach ( $this->hook_classes as $item ) {
$item = new $item();
if ( $item instanceof HookAbleInterface ) {
$this->load_hooks( $item );
}
}
}
/**
* Load all the classes.
*
* @since PLUGIN_NAME_VERSION
*
* @param array<string, mixed> $classes Classes to load.
*
* @throws \ReflectionException
* @return void
*/
public function load_classes( array $classes = [] ) {
if ( empty( $classes ) ) {
return;
}
foreach ( $classes as $key => $item ) {
$reflector = new ReflectionClass( $item['class'] );
if ( isset( $item['args'] ) ) {
$instance = $reflector->newInstanceArgs( $item['args'] );
} else {
$instance = $reflector->newInstance();
}
$this->container[ $key ] = $instance;
}
}
/**
* Register REST API routes.
*
* @since PLUGIN_NAME_VERSION
* @return void
*/
public function register_rest_routes(): void {
if ( empty( $this->api_classes ) ) {
return;
}
foreach ( $this->api_classes as $item ) {
$item = new $item();
if ( $item instanceof HookAbleApiInterface ) {
$item->register_api_routes();
}
}
}
/**
* Load necessary hooks.
*
* @since PLUGIN_NAME_VERSION
*
* @param HookAbleInterface $hook_able HookAble Interface.
*
* @return void
*/
private function load_hooks( HookAbleInterface $hook_able ): void {
$hook_able->hooks();
}
}
|
import { Inject, Injectable } from '@angular/core';
import{HttpClient, HttpHeaders} from '@angular/common/http'
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class HttpClientService {
constructor(private httpClient:HttpClient, @Inject("baseUrl") private baseUrl:string) { }
private url(requestParameter:Partial<RequestParameters>):string{
return `${requestParameter.baseUrl ? requestParameter.baseUrl:this.baseUrl}/${requestParameter.controller}${requestParameter.action ? `/${requestParameter.action}` : ""}`;
}
get<T>(requestParameter:Partial<RequestParameters>, id?:string) : Observable<T>{
let url: string="";
if (requestParameter.fullEndPoint) {
url = requestParameter.fullEndPoint;
} else {
url = `${this.url(requestParameter)}${id ? `/${id}` : ""}${requestParameter.queryString ? `?${requestParameter.queryString}` : ""}`;
}
return this.httpClient.get<T>(url, {headers:requestParameter.headers, responseType:requestParameter.responseType as 'json'});
}
post<T>(requestParameter:Partial<RequestParameters>,body:Partial<T>) : Observable<T>{
let url: string="";
if (requestParameter.fullEndPoint) {
url = requestParameter.fullEndPoint;
} else {
url = `${this.url(requestParameter)}${requestParameter.queryString ? `?${requestParameter.queryString}` : ""}`;
}
return this.httpClient.post<T>(url,body,{headers:requestParameter.headers,responseType:requestParameter.responseType as 'json'})
}
put<T>(requestParameter:Partial<RequestParameters>,body:Partial<T>): Observable<T>{
let url: string="";
if (requestParameter.fullEndPoint) {
url = requestParameter.fullEndPoint;
} else {
url = `${this.url(requestParameter)}${requestParameter.queryString ? `?${requestParameter.queryString}` : ""}`;
}
return this.httpClient.put<T>(url,body,{headers:requestParameter.headers,responseType:requestParameter.responseType as 'json'})
}
delete<T>(requestParameter:Partial<RequestParameters>,id :string): Observable<T>{
let url: string="";
if (requestParameter.fullEndPoint) {
url = requestParameter.fullEndPoint;
} else {
url = `${this.url(requestParameter)}/${id}${requestParameter.queryString ? `?${requestParameter.queryString}` : ""}`;
}
return this.httpClient.delete<T>(url,{headers:requestParameter.headers,responseType:requestParameter.responseType as 'json'})
}
}
export class RequestParameters{
controller? :string;
action?:string;
queryString?:string;
headers? :HttpHeaders;
baseUrl?:string;
fullEndPoint?:string;
responseType?:string = 'json';
}
|
@everywhere begin
using DaggerWebDash
using Dagger
# Algorithms
function mock_Gaudi_algorithm(id, data...)
println("Gaudi algorithm for vertex $id !")
sleep(1)
# println("Previous vertices: $data")
return id
end
function dataobject_algorithm(id, data...)
sleep(0.1)
return "dataobject"
end
function notify_graph_finalization(notifications::RemoteChannel, graph_id::Int, final_vertices_promises)
# println("Entered notify $graph_id")
for promise in final_vertices_promises
wait(promise) # Actually, all the promises should be fulfilled at the moment of calling this function
end
put!(notifications, graph_id)
end
function mock_func()
sleep(1)
return
end
end
function parse_graphs(graphs_map::Dict, output_graph_path::String, output_graph_image_path::String)
graphs = []
for (graph_name, graph_path) in graphs_map
parsed_graph_dot = timestamp_string("$output_graph_path$graph_name") * ".dot"
parsed_graph_image = timestamp_string("$output_graph_image_path$graph_name") * ".png"
G = parse_graphml([graph_path])
open(parsed_graph_dot, "w") do f
MetaGraphs.savedot(f, G)
end
dot_to_png(parsed_graph_dot, parsed_graph_image)
push!(graphs, G)
end
return graphs
end
function show_graph(G)
for (_, v) in enumerate(Graphs.vertices(G))
println("Node: ")
print("Node type: ")
println(get_prop(G, v, :type))
print("Node class (only for algorithms): ")
println(get_prop(G, v, :class))
print("Original name: ")
println(get_prop(G, v, :original_id))
print("Node name: ")
println(get_prop(G, v, :node_id))
println()
end
end
# Function to get the map of incoming edges to a vertex (i.e. the sources of the incoming edges)
function get_ine_map(G)
incoming_edges_sources_map = Dict{eltype(G), Vector{eltype(G)}}()
for edge in Graphs.edges(G)
src_vertex = src(edge)
dest_vertex = dst(edge)
if haskey(incoming_edges_sources_map, dest_vertex)
push!(incoming_edges_sources_map[dest_vertex], src_vertex)
else
incoming_edges_sources_map[dest_vertex] = [src_vertex]
end
end
return incoming_edges_sources_map
end
# Function to get the map of outgoing edges from a vertex (i.e. the destinations of the outgoing edges)
function get_oute_map(G)
outgoing_edges_destinations_map = Dict{eltype(G), Vector{eltype(G)}}()
for edge in Graphs.edges(G)
src_vertex = src(edge)
dest_vertex = dst(edge)
if haskey(outgoing_edges_destinations_map, src_vertex)
push!(outgoing_edges_destinations_map[src_vertex], dest_vertex)
else
outgoing_edges_destinations_map[src_vertex] = [dest_vertex]
end
end
return outgoing_edges_destinations_map
end
function get_vertices_promises(vertices::Vector, G::MetaDiGraph)
promises = []
for vertex in vertices
push!(promises, get_prop(G, vertex, :res_data))
end
return promises
end
function get_deps_promises(vertex_id, map, G)
incoming_data = []
if haskey(map, vertex_id)
for src in map[vertex_id]
push!(incoming_data, get_prop(G, src, :res_data))
end
end
return incoming_data
end
function schedule_graph(G::MetaDiGraph)
inc_e_src_map = get_ine_map(G)
for vertex_id in MetaGraphs.topological_sort(G)
incoming_data = get_deps_promises(vertex_id, inc_e_src_map, G)
set_prop!(G, vertex_id, :res_data, Dagger.@spawn AVAILABLE_TRANSFORMS[get_prop(G, vertex_id, :type)](vertex_id, incoming_data...))
end
end
function schedule_graph_with_notify(G::MetaDiGraph, notifications::RemoteChannel, graph_id::Int)
final_vertices = []
inc_e_src_map = get_ine_map(G)
for vertex_id in MetaGraphs.topological_sort(G)
incoming_data = get_deps_promises(vertex_id, inc_e_src_map, G)
set_prop!(G, vertex_id, :res_data, Dagger.@spawn AVAILABLE_TRANSFORMS[get_prop(G, vertex_id, :type)](vertex_id, incoming_data...))
end
out_e_src_map = get_oute_map(G)
for vertex_id in MetaGraphs.vertices(G)
if !haskey(out_e_src_map, vertex_id)
out_e_src_map[vertex_id] = []
end
end
for vertex_id in keys(out_e_src_map)
if out_e_src_map[vertex_id] == [] # TODO: a native method to check for emptiness should exist
push!(final_vertices, vertex_id)
end
end
Dagger.@spawn notify_graph_finalization(notifications, graph_id, get_vertices_promises(final_vertices, G))
end
function flush_logs_to_file()
ctx = Dagger.Sch.eager_context()
logs = Dagger.TimespanLogging.get_logs!(ctx)
open(ctx.log_file, "w") do io
Dagger.show_plan(io, logs) # Writes graph to a file
end
end
AVAILABLE_TRANSFORMS = Dict{String, Function}("GaudiAlgorithm" => mock_Gaudi_algorithm, "DataObject" => dataobject_algorithm)
|
import config
import os
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
import torch.nn.functional as F
from transformers import BertTokenizerFast
train = pd.read_parquet(os.path.join(config.data_processed_dir , 'train_pairs.parquet'))
valid = pd.read_parquet(os.path.join(config.data_processed_dir , 'valid_pairs.parquet'))
articles = pd.read_parquet(os.path.join(config.data_raw_dir , 'articles.parquet'))
articles = articles[['article_id', 'prod_name', 'detail_desc']]
# join prod_name and prod_desc
articles['text'] = articles['prod_name'] + ' ' + articles['detail_desc']
articles['text'] = articles['text'].str.lower()
articles = articles[['article_id', 'text']]
articles['text'] = articles['text'].fillna('')
# print mac of words in text
tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')
max_len = 32 + 16
articles['text'] = articles['text'].apply(lambda x: tokenizer(x, truncation=True, padding='max_length', max_length=max_len,return_tensors="pt")['input_ids'][0])
def merge_articles(df, articles, article_column, text_column):
df = df.merge(articles, left_on=article_column, right_on='article_id', how='left')
df = df.rename(columns={'text': text_column})
return df.drop(columns=['article_id'])
# Use the helper function to merge train and valid with article_1 and article_2
train = merge_articles(train, articles, 'article_1', 'text_1')
train = merge_articles(train, articles, 'article_2', 'text_2')
valid = merge_articles(valid, articles, 'article_1', 'text_1')
valid = merge_articles(valid, articles, 'article_2', 'text_2')
train.drop(columns=['customer_id'], inplace=True)
valid.drop(columns=['customer_id'], inplace=True)
train.dropna(inplace=True)
valid.dropna(inplace=True)
print(valid.label.mean())
print(train.label.mean())
df = pd.concat([train, valid], ignore_index=True)
item_ids = set(df['article_1'].unique()).union(set(df['article_2'].unique()))
# Create a dictionary that maps each item ID to a unique index
vocab = {item_id: i for i, item_id in enumerate(item_ids)}
num_items = len(set(df['article_1'].unique()).union(set(df['article_2'].unique())))
del item_ids, df
class PairDataset(Dataset):
def __init__(self, df, vocab):
articles = set(df.article_1.unique())
articles = np.random.permutation(list(articles))
grouped = df.groupby('article_1')
# Shuffle the groups
shuffled_df = pd.concat(
[grouped.get_group(group) for group in articles],
ignore_index=True
)
self.df = shuffled_df
# Create a dictionary that maps each item ID to a unique index
self.vocab = vocab
def __len__(self):
return len(self.df)
def __getitem__(self, idx):
row = self.df.iloc[idx]
# get article_id1 and article_id2 and labels
article_id1 = row['article_1']
article_id2 = row['article_2']
label = row['label']
# convert to torch tensors
article_id1 = torch.tensor(self.vocab[article_id1], dtype=torch.long)
article_id2 = torch.tensor(self.vocab[article_id2], dtype=torch.long)
label = torch.tensor(label, dtype=torch.float)
text_1 = row['text_1']
text_2 = row['text_2']
return article_id1, article_id2, text_1, text_2, label
# add the shuffle method
from torch.utils.data import Sampler
class GroupedSampler(Sampler):
def __init__(self, data_source):
self.data_source = data_source
self.groups = self.data_source.df.groupby('article_1').indices
def __iter__(self):
# Shuffle the groups
group_order = list(self.groups.keys())
np.random.shuffle(group_order)
# Yield samples in the order defined by the shuffled groups
for group in group_order:
for idx in self.groups[group]:
yield idx
def __len__(self):
return len(self.data_source)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
dataset = PairDataset(train, vocab)
sampler = GroupedSampler(dataset)
data_loader = DataLoader(dataset, batch_size=256, sampler=sampler)
valid_dataset = PairDataset(valid, vocab)
sampler_valid = GroupedSampler(valid_dataset)
valid_data_loader = DataLoader(valid_dataset, batch_size=1000, sampler=sampler_valid)
def loss_function(output, target):
# use cross entropy loss
return F.binary_cross_entropy(output, target)
def train_model(model, data_loader, optimizer, num_epochs):
print(device)
model = model.to(device)
for epoch in range(num_epochs):
# switch model to training mode
model.train()
with tqdm(total=len(data_loader)) as progress_bar:
total_loss = 0
total_accuracy = 0
for item1, item2, text1, text2, target in data_loader:
optimizer.zero_grad()
output1 = model(item1.to(device), text1.to(device)) #torch.Size([4000, 128])
output2 = model(item2.to(device), text2.to(device)) #torch.Size([4000, 128])
dot_product = torch.sum(output1 * output2, dim=1)
# Apply sigmoid to convert the dot product to a similarity score
similarity_score = torch.sigmoid(dot_product)
target = target.float().to(device)
loss = loss_function(similarity_score, target)
loss.backward()
optimizer.step()
accuracy = ((similarity_score > 0.5) == target).detach().cpu().numpy().mean()
total_accuracy += accuracy
total_loss += loss.item()
progress_bar.set_postfix(loss=loss.item() , accuracy=accuracy.item() )
progress_bar.update(1)
print('Epoch: {}, Loss: {:.4f}, Accuracy: {:.4f}'.format(epoch + 1, total_loss / len(data_loader), total_accuracy / len(data_loader)))
# compute total loss and accuracy
total_loss = 0
total_accuracy = 0
# switch model to evaluation mode
model.eval()
with torch.no_grad():
with tqdm(total=len(valid_data_loader)) as progress_bar:
for item1, item2, text1, text2, target in valid_data_loader:
output1 = model(item1.to(device), text1.to(device))
output2 = model(item2.to(device), text2.to(device))
dot_product = torch.sum(output1 * output2, dim=1)
# Apply sigmoid to convert the dot product to a similarity score
output = torch.sigmoid(dot_product)
loss = loss_function(output, target.float().to(device))
# compute accuracy
output = output.detach().cpu().numpy()
target = target.detach().cpu().numpy()
accuracy = ((output > 0.5) == target).mean()
total_loss += loss.item()
total_accuracy += accuracy
progress_bar.update(1)
print('Epoch: {}, Loss: {:.4f}, Accuracy: {:.4f}'.format(epoch + 1, total_loss / len(valid_data_loader), total_accuracy / len(valid_data_loader)))
# save model
torch.save(model.state_dict(), os.path.join(config.models_dir, 'model.pth'))
print('num_tokens: ', len(tokenizer))
model = 'lstm'
if model == 'lstm':
from models.lstm import Item2Vec
model = Item2Vec(num_items=num_items, embedding_dim=128, input_tokens=len(tokenizer))
else :
from models.transformer import Item2Vec
model = Item2Vec(num_items=num_items, embedding_dim=256, input_tokens=len(tokenizer), max_len=2000)
train_model(model, data_loader, optimizer=torch.optim.Adam(model.parameters(), lr=0.001), num_epochs=20)
|
package javaApp;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Clase principal.
*/
public class Main {
public static void main(String[] args) {
// Crear algunos libros de ejemplo
Libro libro1 = new Libro("La Sombra del Viento", "Carlos Ruiz Zafón", "9788408043642", EstadoLibro.DISPONIBLE);
Libro libro2 = new Libro("Cien años de soledad", "Gabriel García Márquez", "9780307350450",
EstadoLibro.DISPONIBLE);
Libro libro3 = new Libro("1984", "George Orwell", "9780451524935", EstadoLibro.RESERVADO);
// Crear una lista de libros
List<Libro> libros = new ArrayList<>();
libros.add(libro1);
libros.add(libro2);
libros.add(libro3);
Usuario usuario1 = new Usuario("Juan");
Usuario usuario2 = new Usuario("María");
Reserva reserva1 = new Reserva(usuario1, libro1);
Reserva reserva2 = new Reserva(usuario2, libro2);
// Crear una lista de reservas
List<Reserva> reservas = new ArrayList<>();
reservas.add(reserva1);
reservas.add(reserva2);
// Menú principal
while (true) {
System.out.println("\nMenú Principal:");
System.out.println("1. Listar Libros");
System.out.println("2. Crear Reserva");
System.out.println("3. Cancelar Reserva");
System.out.println("4. Listar Reservas");
System.out.println("5. Salir");
int opcion = obtenerOpcionMenu();
switch (opcion) {
case 1:
listarLibros(libros);
break;
case 2:
crearReserva(usuario1, libros.get(0), reservas);
break;
case 3:
cancelarReserva(usuario1, libros.get(0), reservas);
break;
case 4:
listarReservas(reservas);
break;
case 5:
System.out.println("Gracias por utilizar la aplicación. ¡Hasta pronto!");
System.exit(0);
default:
System.out.println("Opción no válida. Intente de nuevo.");
}
}
}
/**
* Muestra una lista de libros.
*
* @param libros La lista de libros.
*/
public static void listarLibros(List<Libro> libros) {
System.out.println("\nListado de Libros:");
for (Libro libro : libros) {
System.out.println("Título: " + libro.getTitulo());
System.out.println("Autor: " + libro.getAutor());
System.out.println("ISBN: " + libro.getISBN());
System.out.println("Estado: " + libro.getEstado());
System.out.println();
}
}
/**
* Crea una reserva.
*
* @param usuario El usuario que realiza la reserva.
* @param libro El libro que se desea reservar.
* @param reservas La lista de reservas existentes.
*/
public static void crearReserva(Usuario usuario, Libro libro, List<Reserva> reservas) {
if (libro.getEstado() == EstadoLibro.DISPONIBLE) {
Reserva reserva = new Reserva(usuario, libro);
reservas.add(reserva);
libro.setEstado(EstadoLibro.RESERVADO);
System.out.println("Reserva realizada con éxito.");
} else {
System.out.println("El libro no está disponible para reserva.");
}
}
/**
* Cancela una reserva.
*
* @param usuario El usuario que desea cancelar la reserva.
* @param libro El libro que se desea cancelar la reserva.
* @param reservas La lista de reservas existentes.
*/
public static void cancelarReserva(Usuario usuario, Libro libro, List<Reserva> reservas) {
for (Reserva reserva : reservas) {
if (reserva.getUsuario().equals(usuario) && reserva.getLibro().equals(libro)) {
reservas.remove(reserva);
libro.setEstado(EstadoLibro.DISPONIBLE);
System.out.println("Reserva cancelada con éxito.");
return;
}
}
System.out.println("No se encontró ninguna reserva para este usuario y libro.");
}
/**
* Muestra una lista de todas las reservas.
*
* @param reservas La lista de reservas.
*/
public static void listarReservas(List<Reserva> reservas) {
System.out.println("\nListado de Reservas:");
for (Reserva reserva : reservas) {
System.out.println("Usuario: " + reserva.getUsuario().getNombre());
System.out.println("Libro: " + reserva.getLibro().getTitulo());
System.out.println("Fecha de Reserva: " + reserva.getFechaReserva());
System.out.println("Fecha de Devolución: " + reserva.getFechaDevolucion());
System.out.println();
}
}
/**
* Obtiene una opción.
*
* @return La opción seleccionada por el usuario.
*/
public static int obtenerOpcionMenu() {
int opcion = -1;
Scanner scanner = new Scanner(System.in);
try {
opcion = scanner.nextInt();
} catch (NumberFormatException e) {
opcion = -1;
}
return opcion;
}
}
/**
* Enum para el estado del libro.
*/
enum EstadoLibro {
DISPONIBLE, RESERVADO
}
|
#include <iostream>
using namespace std;
void f()
{
try {
throw "hello"; // throw a char *
}
catch(char *) { // catch a char *
cout << "Caught char * inside f\n";
throw ; // rethrow char * out of function
}
}
int main()
{
cout << "start\n";
try{
f();
}
catch(char *) {
cout << "Caught char * inside main\n";
}
cout << "end";
return 0;
}
|
import { ApiProperty } from '@nestjs/swagger';
import { IsEnum } from 'class-validator';
export enum FileType {
USER_AVATAR = 'USER_AVATAR',
EVENT_IMAGE = 'EVENT_IMAGE',
CATEGORY_IMAGE = 'CATEGORY_IMAGE',
APP_LOGO = 'APP_LOGO',
}
export class BaseFileUploadDto {
@ApiProperty({ enum: FileType, required: true })
@IsEnum(FileType)
fileType: FileType;
}
export class SingleUploadDto extends BaseFileUploadDto {
@ApiProperty({ type: 'string', format: 'binary', required: true })
file: Express.Multer.File;
}
export class MultiFileUploadDto extends BaseFileUploadDto {
@ApiProperty({ format: 'binary', required: true })
files: Array<Express.Multer.File>;
}
|
import Head from 'next/head'
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { Inter } from 'next/font/google'
import styles from '@/styles/Home.module.css'
import Dropdown from './dropdown';
import Display from './display';
const inter = Inter({ subsets: ['latin'] })
const Header = styled.header`
text-align: center;
`;
const Title = styled.h1`
margin: 0;
`;
interface Pokemon {
id: number;
name: {
english: string;
japanese: string;
chinese: string;
french: string;
};
type: string[];
base: {
HP: number;
Attack: number;
Defense: number;
"Sp. Attack": number;
"Sp. Defense": number;
Speed: number;
};
}
export default function Home() {
//Setup initial type request, this won't need to run after initial load
const [pokemonType, setPokemonTypes] = useState<string[]>([]);
useEffect(() => {
fetchPokemonTypes();
}, []);
const fetchPokemonTypes = () => {
fetch('http://localhost:8000/types')
.then((response: Response) => response.json())
.then((types: string[]) => {
setPokemonTypes(types);
})
.catch((error: Error) => console.error(error));
};
//Setup pokemon data query
const [pokemon, setPokemon] = useState<Pokemon[]>([]);
//useEffect is below on line 70 to get selectedType changes
const fetchPokemon = (type: string) => {
fetch(`http://localhost:8000/pokemon?type=${type}`)
.then((response: Response) => response.json())
.then((pokemon: Pokemon[]) => {
setPokemon(pokemon);
})
.catch((error: Error) => console.error(error));
};
//This allows the fetchPokemon query to run with the requested type each time it changes
const [selectedType, setSelectedType] = useState<string>('');
//This changes the query when the selectedtype is updateed
useEffect(() => {
fetchPokemon(selectedType);
}, [selectedType]);
//This sets the state of selected option and is used in onChange in Dropdown component
const handleTypeChange = (selectedOption: { label: string; value: string }) => {
setSelectedType(selectedOption.value);
};
return (
<>
<Head>
<title>Pokemon</title>
<meta name="description" content="View Pokemon" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<Header>
<Title>Pokemon</Title>
</Header>
<main className={styles.main}>
<div className={styles.container}>
<nav>
<ul>
<li>
<Dropdown
options={[{ value: '', label: 'Select a type' }, ...pokemonType.map(d => ({ value: d, label: d }))]}
onChange={handleTypeChange}
/>
</li>
</ul>
</nav>
<main>
{selectedType && (
<section>
<Display
typedPokemon={selectedType}
pokemonJson={pokemon}
/>
</section>
)}
</main>
</div>
</main>
</>
)
}
|
# ansible-collection-icinga
[](https://github.com/Icinga/ansible-collection-icinga/actions/workflows/build.yml/badge.svg)
[](https://github.com/Icinga/ansible-collection-icinga/actions/workflows/python-test.yml/badge.svg)
Collection to setup and manage components of the Icinga software stack.
## Documentation and Roles
* [Getting Started](doc/getting-started.md)
* [Role: icinga.icinga.repos](doc/role-repos/role-repos.md)
* [Role: icinga.icinga.icinga2](doc/role-icinga2/role-icinga2.md)
* [Parser and Monitoring Objects](doc/role-icinga2/objects.md)
* [Features](doc/role-icinga2/features.md)
* [Role: icinga.icinga.icingadb](doc/role-icingadb/role-icingadb.md)
* [Role: icinga.icinga.icingadb_redis](doc/role-icingadb_redis/role-icingadb_redis.md)
* [Role: icinga.icinga.icingaweb2](doc/role-icingaweb2/role-icingaweb2.md)
* [Role: icinga.icinga.monitoring_plugins](doc/role-monitoring_plugins/role-monitoring_plugins.md)
* [List of Available Check Commands](doc/role-monitoring_plugins/check_command_list.md)
* [Inventory Plugin: icinga.icinga.icinga](doc/plugins/inventory/icinga-inventory-plugin.md)
## Installation
You can easily install the collection with the `ansible-galaxy` command.
```
ansible-galaxy collection install icinga.icinga
```
Or if you are using Tower or AWX add the collection to your requirements file.
```
collections:
- name: icinga.icinga
```
## Usage
To use the collection in your playbooks, add the collection and then use the roles.
```
- hosts: icinga-server
roles:
- icinga.icinga.repos
- icinga.icinga.icinga2
- icinga.icinga.icingadb
- icinga.icinga.icingadb_redis
- icinga.icinga.monitoring_plugins
```
## License
Copyright 2023 Icinga GmbH
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.
|
import 'package:flutter/material.dart';
import 'package:keepup/src/design/app_fonts.dart';
@immutable
class AppTextTheme extends ThemeExtension<AppTextTheme> {
final TextStyle bold36;
final TextStyle bold30;
final TextStyle bold18;
final TextStyle bold16;
final TextStyle bold14;
final TextStyle bold13;
final TextStyle bold12;
final TextStyle bold10;
final TextStyle medium36;
final TextStyle medium24;
final TextStyle medium21;
final TextStyle medium20;
final TextStyle medium18;
final TextStyle medium16;
final TextStyle medium14;
final TextStyle medium13;
final TextStyle medium12;
final TextStyle medium11;
final TextStyle medium10;
final TextStyle regular16;
final TextStyle regular20;
final TextStyle regular14;
final TextStyle regular12;
const AppTextTheme({
required this.bold36,
required this.bold30,
required this.bold18,
required this.bold16,
required this.bold14,
required this.bold13,
required this.bold12,
required this.bold10,
required this.medium24,
required this.medium21,
required this.medium20,
required this.medium18,
required this.medium16,
required this.medium14,
required this.medium13,
required this.medium12,
required this.medium11,
required this.medium10,
required this.medium36,
required this.regular20,
required this.regular16,
required this.regular14,
required this.regular12,
});
@override
AppTextTheme copyWith({
TextStyle? bold36,
TextStyle? bold30,
TextStyle? bold18,
TextStyle? bold16,
TextStyle? bold14,
TextStyle? bold13,
TextStyle? bold12,
TextStyle? bold10,
TextStyle? medium24,
TextStyle? medium21,
TextStyle? medium20,
TextStyle? medium18,
TextStyle? medium16,
TextStyle? medium14,
TextStyle? medium13,
TextStyle? medium12,
TextStyle? medium11,
TextStyle? medium10,
TextStyle? medium36,
TextStyle? regular20,
TextStyle? regular16,
TextStyle? regular14,
TextStyle? regular12,
}) {
return AppTextTheme(
bold36: bold36 ?? this.bold36,
bold30: bold30 ?? this.bold30,
bold18: bold18 ?? this.bold18,
bold16: bold16 ?? this.bold16,
bold14: bold14 ?? this.bold14,
bold13: bold13 ?? this.bold13,
bold12: bold12 ?? this.bold12,
bold10: bold10 ?? this.bold10,
medium24: medium24 ?? this.medium24,
medium21: medium21 ?? this.medium21,
medium20: medium20 ?? this.medium20,
medium18: medium18 ?? this.medium18,
medium16: medium16 ?? this.medium16,
medium14: medium14 ?? this.medium14,
medium13: medium13 ?? this.medium13,
medium12: medium12 ?? this.medium12,
medium11: medium11 ?? this.medium11,
medium10: medium10 ?? this.medium10,
medium36: medium36 ?? this.medium36,
regular20: regular20 ?? this.regular20,
regular16: regular16 ?? this.regular16,
regular14: regular14 ?? this.regular14,
regular12: regular12 ?? this.regular12,
);
}
@override
AppTextTheme lerp(ThemeExtension<AppTextTheme>? other, double t) {
if (other is! AppTextTheme) {
return this;
}
return AppTextTheme(
bold36: TextStyle.lerp(bold36, other.bold36, t)!,
bold30: TextStyle.lerp(bold30, other.bold30, t)!,
bold18: TextStyle.lerp(bold18, other.bold18, t)!,
bold16: TextStyle.lerp(bold16, other.bold16, t)!,
bold14: TextStyle.lerp(bold14, other.bold14, t)!,
bold13: TextStyle.lerp(bold13, other.bold13, t)!,
bold12: TextStyle.lerp(bold12, other.bold12, t)!,
bold10: TextStyle.lerp(bold10, other.bold10, t)!,
medium24: TextStyle.lerp(medium24, other.medium24, t)!,
medium21: TextStyle.lerp(medium21, other.medium21, t)!,
medium20: TextStyle.lerp(medium20, other.medium20, t)!,
medium18: TextStyle.lerp(medium18, other.medium18, t)!,
medium16: TextStyle.lerp(medium16, other.medium16, t)!,
medium14: TextStyle.lerp(medium14, other.medium14, t)!,
medium13: TextStyle.lerp(medium13, other.medium13, t)!,
medium12: TextStyle.lerp(medium12, other.medium12, t)!,
medium11: TextStyle.lerp(medium11, other.medium11, t)!,
medium10: TextStyle.lerp(medium10, other.medium10, t)!,
medium36: TextStyle.lerp(medium36, other.medium36, t)!,
regular20: TextStyle.lerp(regular20, other.regular20, t)!,
regular16: TextStyle.lerp(regular16, other.regular16, t)!,
regular14: TextStyle.lerp(regular14, other.regular14, t)!,
regular12: TextStyle.lerp(regular12, other.regular12, t)!,
);
}
@override
String toString() => 'AppCustomTexts';
// the light theme
static final light = AppTextTheme(
bold36: _bold36,
bold30: _bold30,
bold18: _bold18,
bold16: _bold16,
bold14: _bold14,
bold13: _bold13,
bold12: _bold12,
bold10: _bold10,
medium24: _medium24,
medium21: _medium21,
medium20: _medium20,
medium18: _medium18,
medium16: _medium16,
medium14: _medium14,
medium13: _medium13,
medium12: _medium12,
medium11: _medium11,
medium10: _medium10,
medium36: _medium36,
regular20: _regular20,
regular16: _regular16,
regular14: _regular14,
regular12: _regular12,
);
// the dark theme
static final dark = AppTextTheme(
bold36: _bold36,
bold30: _bold30,
bold18: _bold18,
bold16: _bold16,
bold14: _bold14,
bold13: _bold13,
bold12: _bold12,
bold10: _bold10,
medium24: _medium24,
medium21: _medium21,
medium20: _medium20,
medium18: _medium18,
medium16: _medium16,
medium14: _medium14,
medium13: _medium13,
medium12: _medium12,
medium11: _medium11,
medium10: _medium10,
medium36: _medium36,
regular20: _regular20,
regular16: _regular16,
regular14: _regular14,
regular12: _regular12,
);
}
String get getFontFamily => AppFonts.fontDMSans;
TextStyle get _bold => TextStyle(
fontFamily: getFontFamily,
fontWeight: FontWeight.bold,
height: 1.3,
);
TextStyle get _bold36 => _bold.copyWith(fontSize: 36);
TextStyle get _bold30 => _bold.copyWith(fontSize: 30);
TextStyle get _bold18 => _bold.copyWith(fontSize: 18);
TextStyle get _bold16 => _bold.copyWith(fontSize: 16);
TextStyle get _bold14 => _bold.copyWith(fontSize: 14);
TextStyle get _bold13 => _bold.copyWith(fontSize: 13);
TextStyle get _bold12 => _bold.copyWith(fontSize: 12);
TextStyle get _bold10 => _bold.copyWith(fontSize: 10);
TextStyle get _medium => TextStyle(
fontFamily: getFontFamily,
fontWeight: FontWeight.w500,
height: 1.3,
);
TextStyle get _medium24 => _medium.copyWith(fontSize: 24);
TextStyle get _medium21 => _medium.copyWith(fontSize: 21);
TextStyle get _medium20 => _medium.copyWith(fontSize: 20);
TextStyle get _medium18 => _medium.copyWith(fontSize: 18);
TextStyle get _medium16 => _medium.copyWith(fontSize: 16);
TextStyle get _medium14 => _medium.copyWith(fontSize: 14);
TextStyle get _medium13 => _medium.copyWith(fontSize: 13);
TextStyle get _medium12 => _medium.copyWith(fontSize: 12);
TextStyle get _medium11 => _medium.copyWith(fontSize: 11);
TextStyle get _medium10 => _medium.copyWith(fontSize: 10);
TextStyle get _medium36 => _medium.copyWith(fontSize: 36);
TextStyle get _regular => TextStyle(
fontFamily: getFontFamily,
fontWeight: FontWeight.w400,
height: 1.3,
);
TextStyle get _regular20 => _regular.copyWith(fontSize: 20);
TextStyle get _regular16 => _regular.copyWith(fontSize: 16);
TextStyle get _regular14 => _regular.copyWith(fontSize: 14);
TextStyle get _regular12 => _regular.copyWith(fontSize: 12);
|
type DeepReadonly<T> = T extends Function
? T
: T extends object
? {
readonly [P in keyof T]: DeepReadonly<T[P]>
}
: T
// Base Case - Function Types: The first part of the type, T extends Function ? T, serves as a base case. It checks if the type T is a function. If it is, it returns T unchanged. The rationale behind this is that functions are considered leaf nodes in the object tree, and making them readonly doesn't make sense in the context of this utility.
// Recursive Case - Object Types: The second part, T extends object ? { readonly [P in keyof T]: DeepReadonly<T[P]>; }, handles the case where T is an object. If T is an object, it creates a new object with the same keys as T, but each property is recursively transformed using DeepReadonly. This ensures that the transformation is applied deeply to all nested properties.
// Fallback Case - Non-Object, Non-Function Types: The last part, : T, is a fallback case. If T is neither a function nor an object, it means it's a primitive type or some other non-object type. In such cases, we leave it unchanged.
declare const a: Chainable
const result1 = a
.option("foo", 123)
.option("bar", { value: "Hello World" })
.option("name", "type-challenges")
.get()
type Chainable<T = {}> = {
option: <K extends PropertyKey, V>(
key: K extends keyof T ? never : K,
value: V
) => Chainable<Omit<T, K> & Record<K, V>>
get: () => T
}
console.log(result1)
|
<template>
<div class="px-40">
<el-row class="hidden-xs-only">
<el-col :span="24">
<h2 class="main-title">Transactions</h2>
</el-col>
</el-row>
<el-row class="hidden-xs-only">
<el-col :span="24">
<span>
<el-button
size="mini"
icon="xm-el-icon-s-search"
style="border-color: #fff"
class="transparent"
></el-button>
</span>
<span>
<input
class="searchStyle"
v-model="keyWord"
@input="searchThis()"
/>
</span>
</el-col>
</el-row>
<el-row class="hidden-xs-only">
<el-col :span="4" class="d-flex-start">
<Filter :tabs="tabOptions" :getTabLicense="getTabLicense" @newActiveStatus="newActiveStatus" />
</el-col>
<el-col :span="4" :offset="16" class="d-flex-end">
<SortBy :getSortBy="getSortBy" />
</el-col>
</el-row>
<el-row class="hidden-sm-and-up">
<!-- <el-col :span="24" :xs="12">
<CustomTab v-model="activeTabName" :tabs="tabOptions" />
</el-col> -->
<el-col :span="24" :xs="12" style="align-self: center;">
<Filter :tabs="tabOptions" :getTabLicense="getTabLicense" @newActiveStatus="newActiveStatus" />
</el-col>
<el-col :span="12" class="d-flex-end">
<SortBy :getSortBy="getSortBy" />
</el-col>
</el-row>
<el-row class="py-10">
<el-col :span="24" class="d-flex-end">
<el-pagination
class="table-pagination"
layout="prev, pager, next"
:total="pagination.totalRecord"
:page-size="pagination.itemPerPage"
@current-change="paginationCallback"
:current-page="pagination.currentPage + 1"
></el-pagination>
</el-col>
</el-row>
<el-row v-if="dataList">
<el-col v-for="transaction in dataList" :key="transaction.transactionId" :xs="24" :sm="24">
<div style="padding: 20px; border: 1px solid #C4C4C4; margin-bottom: 10px;">
<TransactionCard :transactionDetail="transaction" />
</div>
</el-col>
</el-row>
<el-row v-else>
<el-col v-for="index in 4" :key="index" :span="24" class="px-10">
<TransactionCardLoader />
</el-col>
</el-row>
<el-row class="py-10">
<el-col :span="24" class="d-flex-end">
<el-pagination
class="table-pagination"
layout="prev, pager, next"
:total="pagination.totalRecord"
:page-size="pagination.itemPerPage"
@current-change="paginationCallback"
:current-page="pagination.currentPage + 1"
></el-pagination>
</el-col>
</el-row>
</div>
</template>
<script>
import { ref, onMounted, onBeforeMount, watch } from 'vue';
import { CONFIGURATION_NAMES } from '@/common/constants';
import TransactionCard from '@/components/Transaction/TransactionCard.vue';
import TransactionCardLoader from '@/components/Transaction/TransactionCardLoader.vue';
import transactionServices from '@/services/transaction-service';
/* import CustomTab from '@/components/CustomTab.vue'; */
import SortBy from '@/components/SortBy.vue';
import Filter from '@/components/Filter.vue';
import configurationServices from '@/services/configuration-service';
export default {
name: 'Transactions',
components: {
TransactionCard,
TransactionCardLoader,
/* CustomTab, */
Filter,
SortBy,
},
setup() {
const transactionsList = ref([]);
const transactionsListRes = ref([]);
const transactionsListLoading = ref(true);
const activeStatus = ref('all');
const sortTabName = ref('Sort By');
const tabOptions = ref([]);
const pagination = ref({
itemPerPage: 8,
totalRecord: 0,
currentPage: 0,
});
const paginationTimeout = ref([]);
const dataList = ref(null);
const keyWord = ref('');
onBeforeMount(() => {
if (paginationTimeout.value.length > 0) {
clearTimeout(paginationTimeout.value);
}
});
const getLicenses = async () => {
configurationServices.getConfigurationByName(CONFIGURATION_NAMES.productLicense).then((data) => {
const raw = data[0].configurations.map((config) => JSON.parse(config.value));
tabOptions.value = raw.map((el) => {
const res = {
tabName: el.name.toLowerCase(),
tabLabel: el.name,
};
return res;
});
});
};
const slicePage = (params) => {
const paginationDetails = {
itemPerPage: params.itemPerPage,
totalRecord: transactionsList.value.length,
currentPage: params.currentPage,
};
const data = {
pagination: paginationDetails,
data: transactionsList.value.slice(
(params.itemPerPage * params.currentPage),
(params.itemPerPage * (params.currentPage + 1)),
),
};
return data;
};
const paginationCallback = (page) => {
const newPagination = {
...pagination.value,
currentPage: page - 1,
};
const transDataList = slicePage({
...newPagination,
});
dataList.value = [];
paginationTimeout.value = setTimeout(() => {
dataList.value = transDataList.data;
}, 1);
pagination.value = transDataList.pagination;
};
const newActiveStatus = (status) => {
activeStatus.value = status;
if (status === 'all') {
transactionsList.value = transactionsListRes.value;
} else {
transactionsList.value = transactionsListRes.value.filter((x) => x.status.toLowerCase().includes(status));
}
dataList.value = transactionsList.value;
paginationCallback(1);
};
const getTabLicense = (tabIndex, tabName) => {
tabOptions.value.forEach((element) => {
if (tabName === element.tabName) {
/* transactionsList.value = transactionsListRes.value.filter((x) => x.license.toLowerCase().includes(tabName));
dataList.value = transactionsList.value; */
}
});
};
const getSortBy = (sortBy) => {
if (sortBy === 'Newest') {
transactionsList.value = transactionsListRes.value.sort((a, b) => new Date(b.createdDate) - new Date(a.createdDate));
} else {
transactionsList.value = transactionsListRes.value.sort((a, b) => new Date(a.createdDate) - new Date(b.createdDate));
}
dataList.value = transactionsList.value;
newActiveStatus(activeStatus.value);
};
const getTransactions = async () => {
transactionsListRes.value = await transactionServices.getTransactions();
getSortBy('Newest');
};
onMounted(async () => {
getTransactions();
getLicenses();
});
const searchThis = () => {
dataList.value = keyWord.value ?
transactionsList.value.filter((x) => x.productId.toLowerCase().includes(keyWord.value.toLowerCase())) : transactionsList.value;
// if (keyWord.value) {
// dataList.value = transactionsList.value.data.filter((x) => x.characters.some((y) => y.license.name.toLowerCase() === keyWord.value));
// } else {
// dataList.value = transactionsList.value.data;
// }
};
watch(transactionsList, () => {
const transDataList = slicePage({
...pagination.value,
});
dataList.value = transDataList.data;
pagination.value = transDataList.pagination;
});
return {
getSortBy,
tabOptions,
activeStatus,
sortTabName,
transactionsList,
transactionsListRes,
dataList,
transactionsListLoading,
pagination,
paginationCallback,
getTabLicense,
newActiveStatus,
keyWord,
searchThis,
};
},
};
</script>
|
import { FunctionComponent } from 'react';
import styled from 'styled-components';
import { font } from '@weco/common/utils/classnames';
import { BookBasic } from '@weco/content/types/books';
import Space from '@weco/common/views/components/styled/Space';
import LabelsList from '@weco/common/views/components/LabelsList/LabelsList';
import BookImage from '@weco/content/components/BookImage/BookImage';
type LinkSpaceAttrs = {
$url: string;
};
const LinkSpace = styled(Space).attrs<LinkSpaceAttrs>(props => ({
as: 'a',
href: props.$url,
$v: { size: 'xl', properties: ['padding-top'] },
$h: { size: 'm', properties: ['padding-left', 'padding-right'] },
}))<LinkSpaceAttrs>`
display: block;
&,
&:link,
&:visited {
text-decoration: none;
border: none;
}
&:hover h3,
&:focus h3 {
text-decoration: underline;
text-decoration-color: ${props => props.theme.color('black')};
}
`;
const Title = styled.h3.attrs({
className: font('wb', 4),
})`
margin: 0;
`;
const Subtitle = styled(Space).attrs({
className: font('intb', 5),
$v: { size: 's', properties: ['margin-top'] },
})`
margin: 0;
`;
const Caption = styled.p.attrs({
className: font('intr', 5),
})`
margin: 0;
`;
type Props = {
book: BookBasic;
};
const BookPromo: FunctionComponent<Props> = ({ book }) => {
const { id, title, subtitle, promo, cover } = book;
return (
<LinkSpace $url={`/books/${id}`}>
<Space $v={{ size: 'l', properties: ['margin-bottom'] }}>
<BookImage
image={{
contentUrl: cover?.contentUrl || '',
width: cover?.width || 0,
height: cover?.height || 0,
// We intentionally omit the alt text on promos, so screen reader
// users don't have to listen to the alt text before hearing the
// title of the item in the list.
//
// See https://github.com/wellcomecollection/wellcomecollection.org/issues/6007
alt: '',
}}
sizes={{
xlarge: 1 / 6,
large: 1 / 6,
medium: 1 / 3,
small: 1,
}}
quality="low"
/>
<Space
$h={{ size: 'l', properties: ['padding-left', 'padding-right'] }}
>
<Space
$v={{ size: 's', properties: ['margin-bottom'] }}
style={{ position: 'relative' }}
>
<Space
$v={{
size: 'm',
properties: ['margin-top'],
negative: true,
}}
>
<LabelsList labels={[{ text: 'Book' }]} />
</Space>
</Space>
<Title>{title}</Title>
{subtitle && <Subtitle as="h4">{subtitle}</Subtitle>}
{promo?.caption && (
<Space $v={{ size: 's', properties: ['margin-top'] }}>
<Caption>{promo.caption}</Caption>
</Space>
)}
</Space>
</Space>
</LinkSpace>
);
};
export default BookPromo;
|
// 控制并发执行的请求数
function pLimit(limit) {
const queue = [];
let count = 0;
const next = () => {
count--;
if (queue.length > 0) {
queue.shift()();
}
};
const run = async (fn, resolve, args) => {
count++;
const result = (async () => fn(...args))();
resolve(result);
try {
await result;
} catch { }
next();
};
const enqueue = (asyncTask, args, resolve) => {
queue.push(run.bind(undefined, asyncTask, resolve, args));
console.log(111);
(async () => {
// This function needs to wait until the next microtask before comparing
// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
// when the run function is dequeued and called. The comparison in the if-statement
// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
await Promise.resolve();
if (count < limit && queue.length > 0) {
queue.shift()();
}
})();
}
const generator = (asyncTask, ...args) => new Promise((resolve) => {
enqueue(asyncTask, args, resolve);
});
return generator;
}
const limit = pLimit(2);
const input = [];
for (let i = 0; i < 10; i++) {
input.push(limit(() => new Promise((resolve) => {
setTimeout(() => {
resolve(i);
}, 1000);
})));
}
// Only one promise is run at once
(async () => {
const result = await Promise.all(input);
console.log(result);
})();
|
import json
import requests
from colorama import Fore
from istorage import IStorage
API_KEY = "c48b8b2c"
class StorageJson(IStorage):
def __init__(self, file_path):
self.file_path = file_path
def list_movies(self):
"""
Returns a dictionary of dictionaries that
contains the movies information in the database.
The function loads the information from the JSON
file and returns the data.
For example, the function may return:
{
"Titanic": {
"rating": 9,
"year": 1999
},
"..." {
...
},
}
"""
with open(self.file_path, "r") as file:
data = json.loads(file.read())
return data
def add_movie(self, title):
"""
Adds a movie to the movies database.
Loads the information from the JSON file, add the movie,
and saves it. The function doesn't need to validate the input.
"""
api_data = requests.get(f"http://www.omdbapi.com/?apikey={API_KEY}&t={title}").json()
if api_data["Response"] == "False":
print("Provided movie title does not exist. Please enter a valid movie title")
return
movies = self.list_movies()
print(Fore.WHITE)
info_dict = {}
info_dict['title'] = api_data['Title']
info_dict['rating'] = float(api_data['imdbRating'])
info_dict['year'] = api_data['Year']
info_dict['poster_img_url'] = api_data['Poster']
movies[title] = info_dict
print(f"Movie {title} successfully added")
with open(self.file_path, "w") as outfile:
json.dump(movies, outfile)
def delete_movie(self, title):
"""
Deletes a movie from the movies database.
Loads the information from the JSON file, deletes the movie,
and saves it. The function doesn't need to validate the input.
"""
movies = self.list_movies()
del movies[title]
print(f"Movie {title} successfully deleted")
with open(self.file_path, "w") as outfile:
json.dump(movies, outfile)
def update_movie(self, title, rating):
"""
Updates a movie from the movies database.
Loads the information from the JSON file, updates the movie,
and saves it. The function doesn't need to validate the input.
"""
movies = self.list_movies()
if title not in movies:
print(Fore.RED + f"Movie {title} doesn't exist!")
print(Fore.WHITE)
return
else:
print(Fore.WHITE)
movies[title]['rating'] = rating
print(f"Movie {title} successfully updated")
with open(self.file_path, "w") as outfile:
json.dump(movies, outfile)
|
defmodule AeMdw.Db.NameTransferMutation do
@moduledoc """
Processes name_transfer_tx.
"""
alias AeMdw.Db.State
alias AeMdw.Db.Sync.Name
alias AeMdw.Names
alias AeMdw.Node
alias AeMdw.Node.Db
alias AeMdw.Txs
@derive AeMdw.Db.Mutation
defstruct [:name_hash, :new_owner, :txi_idx]
@opaque t() :: %__MODULE__{
name_hash: Names.name_hash(),
new_owner: Db.pubkey(),
txi_idx: Txs.txi_idx()
}
@spec new(Node.tx(), Txs.txi_idx()) :: t()
def new(tx, txi_idx) do
name_hash = :aens_transfer_tx.name_hash(tx)
new_owner = :aens_transfer_tx.recipient_pubkey(tx)
%__MODULE__{
name_hash: name_hash,
new_owner: new_owner,
txi_idx: txi_idx
}
end
@spec execute(t(), State.t()) :: State.t()
def execute(
%__MODULE__{
name_hash: name_hash,
new_owner: new_owner,
txi_idx: txi_idx
},
state
) do
Name.transfer(state, name_hash, new_owner, txi_idx)
end
end
|
package Class;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TreatmentCourse {
private String treatmentID;
private String department;
private String startDate;
private String endDate;
private String historyID;
private String effective;
private Diagnosis diagnosis;
private Analysis analysis;
@JsonCreator
public TreatmentCourse(@JsonProperty("treatmentID") String treatmentID,
@JsonProperty("department") String department,
@JsonProperty("startDate") String startDate,
@JsonProperty("endDate") String endDate,
@JsonProperty("historyID") String historyID,
@JsonProperty("effective") String effective,
@JsonProperty("diagnosis") Diagnosis diagnosis,
@JsonProperty("analysis") Analysis analysis) {
this.treatmentID = treatmentID;
this.department = department;
this.startDate = startDate;
this.endDate = endDate;
this.historyID = historyID;
this.effective = effective;
this.diagnosis = diagnosis;
this.analysis = analysis;
}
public TreatmentCourse(String treatmentID,
String department,
String startDate,
String endDate,
String historyID,
String effective) {
this.treatmentID = treatmentID;
this.department = department;
this.startDate = startDate;
this.endDate = endDate;
this.historyID = historyID;
this.effective = effective;
this.analysis = null;
this.diagnosis = null;
}
public String getTreatmentID() {
return treatmentID;
}
public void setTreatmentID(String treatmentID) {
this.treatmentID = treatmentID;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getHistoryID() {
return historyID;
}
public void setHistoryID(String historyID) {
this.historyID = historyID;
}
public String getEffective() {
return effective;
}
public void setEffective(String effective) {
this.effective = effective;
}
public Diagnosis getDiagnosis() {
return diagnosis;
}
public void setDiagnosis(Diagnosis diagnosis) {
this.diagnosis = diagnosis;
}
public Analysis getAnalysis() {
return analysis;
}
public void setAnalysis(Analysis analysis) {
this.analysis = analysis;
}
}
|
import enum
import logging
from functools import total_ordering
"""
A file for dealing with permissions for actions that users are allowed to take. This file is intentionally
as simple as possible at the moment since there is currently no notion of individual user accounts for using this
application. Permissions are set on application startup.
"""
logger = logging.getLogger(__name__)
@total_ordering
class UserPermission(enum.Enum):
"""
An enum for the values that an alarm severity can take on. Not inheriting from str so permission
based comparisons can be done.
"""
READ_ONLY = "read-only"
OPERATOR = "operator"
ADMIN = "admin"
def __lt__(self, other):
"""The order in which they are defined is in order of increasing ability to take action"""
if self.__class__ is other.__class__:
values = [e for e in UserPermission]
return values.index(self) < values.index(other)
return NotImplemented
class UserAction(enum.Enum):
"""An enum for the actions available to the user"""
ACKNOWLEDGE = "acknowledge"
ENABLE = "enable"
UPDATE_CONFIG = "update-config"
__user_permission = UserPermission.ADMIN
def can_take_action(action: UserAction, log_warning=False) -> bool:
"""Return True if the user can take the input action, False otherwise"""
if action is UserAction.ACKNOWLEDGE and __user_permission == UserPermission.READ_ONLY:
if log_warning:
logger.warning(" Cannot take acknowledge action, permissions are currently set to read-only")
return False
elif action is UserAction.ENABLE and __user_permission < UserPermission.ADMIN:
if log_warning:
logger.warning(
f" Cannot take enable/disable action, requires alarm admin permissions, "
f"currently set to {__user_permission.value}"
)
return False
elif action is UserAction.UPDATE_CONFIG and __user_permission < UserPermission.ADMIN:
if log_warning:
logger.warning(
f" Cannot update config, requires alarm admin permissions, "
f"currently set to: {__user_permission.value}"
)
return False
return True
def set_user_permission(permission: UserPermission) -> None:
"""Set the permission determining what the user is allowed to do"""
global __user_permission
__user_permission = permission
|
//
// CookEatUITests.swift
// CookEatUITests
//
// Created by Rafael Kollyfas on 09/05/2021.
//
import XCTest
class CookEatUITests: XCTestCase {
//IMPORTANT: FOR THE TESTS TO RUN, ON THE SIMULATOR CLICK THE "I/O" SETTING AND THEN SELECT "Keyboard" AND FINALLY DEACTIVATE "Connect Hardware Keyboard".
private var app: XCUIApplication!
private var loggedIn = false
//Setup tests.
override func setUp() {
continueAfterFailure = false
self.app = XCUIApplication()
self.app.launch()
let email = app.textFields["email"]
//Login with an account I created for testing purposes.
if email.exists && !loggedIn {
email.tap()
email.typeText("[email protected]")
let pwd = app.secureTextFields["password"]
pwd.tap()
pwd.typeText("Password!")
app.buttons["Sign In"].tap()
loggedIn.toggle()
}
}
//Add a new recipe.
func testAddRecipe() {
app.buttons["add_recipe"].tap()
let message = app.staticTexts["Add Recipe"]
XCTAssertTrue(message.waitForExistence(timeout: 5))
}
//Test feed view.
func testFeed() {
app.buttons["Feed"].tap()
let message = app.staticTexts["Feed View"]
XCTAssertTrue(message.waitForExistence(timeout: 5))
}
//Test search view.
func testSearch() {
app.buttons["Search"].tap()
let message = app.staticTexts["Search"]
XCTAssertTrue(message.waitForExistence(timeout: 5))
}
//Test account view.
func testAccount() {
app.buttons["Account"].tap()
let message = app.buttons["Sign Out"]
XCTAssertTrue(message.waitForExistence(timeout: 5))
}
//Test Contributions view.
func testContributions() {
app.buttons["Account"].tap()
sleep(2)
app.buttons["Contributions"].tap()
let message = app.staticTexts["Contributions Sent"]
XCTAssertTrue(message.waitForExistence(timeout: 5))
}
//Test Requests view.
func testRequests() {
app.buttons["Account"].tap()
sleep(2)
app.buttons["Requests"].tap()
let message = app.staticTexts["Requests Received"]
XCTAssertTrue(message.waitForExistence(timeout: 5))
}
//Test profile view.
func testProfile() {
app.buttons["Account"].tap()
sleep(2)
app.buttons["Profile"].tap()
let message = app.staticTexts["Followers"]
XCTAssertTrue(message.waitForExistence(timeout: 5))
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>撤销命令</title>
</head>
<body>
<div id="ball" style="position: absolute; top: 50px; background: #000; width: 50px; height: 50px; border-radius: 50%;"></div>
输入小球移动后的位置:<input id="pos" />
<button id="moveBtn">开始移动</button>
<button id="cancelBtn">取消</button> <!-- 增加取消按钮 -->
<script>
// 策略类-封装具体动画算法
var tween = {
linear: function(t, b, c, d) {
return c*t/d + b
},
easeIn: function(t, b, c, d) {
return c*(t/=d)*t+b
},
strongEaseIn: function(t, b, c, d) {
return c*(t/=d)*t*t*t*t+b
},
strongEaseOut: function(t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t+1)+b
},
sineaseIn: function(t, b, c, d) {
return c*(t/=d)*t*t+b
},
sineaseOut: function(t, b, c, d) {
return c*((t=t/d-1)*t*t+1)+b
}
}
// Animate 类
var Animate = function(dom) {
this.dom = dom // 进行运动的 dom 节点
this.startTime = 0 // 动画开始时间
this.startPos = 0 // 动画开始时,dom 节点的位置
this.endPos = 0 // 动画结束时,dom 节点的位置
this.propertyName = null // dom 节点需要被改变的 css 属性名
this.easing = null // 缓动算法
this.duration = null // 动画持续时间
}
Animate.prototype.start = function(propertyName, endPos, duration, easing) {
this.startTime = +new Date // 动画启动时间
this.startPos = this.dom.getBoundingClientRect()[propertyName] // dom 节点初始位置
this.propertyName = propertyName // dom 节点需要被改变的 css 属性名
this.endPos = endPos // dom 节点目标位置
this.duration = duration // 动画持续时间
this.easing = tween[easing] // 缓动算法
var self = this
var timeId = setInterval(function() { // 启动定时器,开始执行动画
if(self.step() === false) { // 如果动画已结束,则清除定时器
clearInterval(timeId)
}
}, 19)
}
Animate.prototype.step = function() {
var t = +new Date // 取得当前时间
if(t >= this.startTime+this.duration) {
this.update(this.endPos) // 更新小球的 css 属性值
return false
}
var pos = this.easing(t - this.startTime, this.startPos, this.endPos-this.startPos, this.duration) // pos 为小球当前位置
this.update(pos) // 更新小球的 css 属性值
}
Animate.prototype.update = function(pos) {
this.dom.style[this.propertyName] = pos + 'px'
}
var ball = document.getElementById('ball')
var pos = document.getElementById('pos')
var moveBtn = document.getElementById('moveBtn')
var cancelBtn = document.getElementById('cancelBtn')
// moveBtn.onclick = function() {
// var animate = new Animate(ball)
// animate.start('left', pos.value, 1000, 'strongEaseOut');
// }
var MoveCommand = function(receiver, pos) {
var oldPos = null
return {
excute: function() {
receiver.start('left', pos, 1000, 'strongEaseOut')
// 记录小球开始移动前的位置
oldPos = receiver.dom.getBoundingClientRect()[receiver.propertyName]
},
undo: function() {
receiver.start('left', oldPos, 1000, 'strongEaseOut')
}
}
}
var moveCommand;
moveBtn.onclick = function() {
var animate = new Animate(ball)
moveCommand = MoveCommand(animate, pos.value)
moveCommand.excute()
}
cancelBtn.onclick = function() {
moveCommand.undo()
}
</script>
</body>
</html>
|
import Vue from 'vue'
import Router from 'vue-router'
import axios from 'axios'
import store from './store'
import Home from './views/Home.vue'
import Post from './views/Post.vue'
import Profile from './views/Profile.vue'
import Login from './views/Login.vue'
import Register from './views/Register.vue'
import ImageInput from './views/ImageInput.vue'
import ImageUploaderMain from './views/ImageUploaderMain.vue'
Vue.use(Router)
let router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/login',
name: 'login',
component: Login,
meta: {
requireAuth: false
}
},
{
path: '/register',
name: 'register',
component: Register,
meta: {
requireAuth: false
}
},
{
path: '/',
name: 'home',
component: Home,
meta: {
requireAuth: true
}
},
{
path: '/newpost',
name: 'post',
component: Post,
meta: {
requireAuth: true
}
},
{
path: '/profile',
name: 'profile',
component: Profile,
meta: {
requireAuth: true
}
},
{
path: '/imageinput',
name: 'imageinput',
component: ImageUploaderMain,
meta: {
requireAuth: true
}
}
]
})
router.onReady(() => {
store.commit('isAuthenticated');
axios.get(store.state.api_url + 'post/getposts')
.then(response => {
store.commit('getFeed', response.data);
})
.catch(err => {
if(err) throw err;
});
})
router.beforeEach((to, from, next) => {
if(to.matched.some(record => record.meta.requireAuth)) {
if (localStorage.getItem('jwt') == null) {
next({
path: '/login',
params: { nextUrl: to.fullPath }
})
} else {
console.log("logged in");
next();
}
} else {
if(localStorage.getItem('jwt') != null) {
next({
path: '/',
params: { nextUrl: '/' }
})
} else {
console.log('does not require auth');
next();
}
}
})
export default router;
|
# 体系结构
|OSI参考模型|原理参考模型|TCP/IP参考模型|应用|
|-|-|-|-|
|应用层|↓|↓||
|表示层|↓|↓||
|会话层|应用层|应用层|HTTP SMTP DNS RTP|
|运输层|运输层|运输层|TCP UDP|
|网络层|网络层|网际层|IP|
|数据链路层|数据链路层|↓||
|物理层|物理层|网络接口层|以太网 Wi-Fi 接口n|
## 物理层
解决使用何种信号来表示比特0和1的问题
* 采用什么传输媒体(介质,物理层之下)
* 采用什么物理接口
* 采用什么信号表示0/1
## 数据链路层
解决数据包在一个网络或一段链路上传输的问题
* 标识网络中各主机(主机编址例如MAC地址)
* 从比特流中区分出地址和数据(数据封装格式)
* 协调各主机争用总线(媒体接入控制)
* 以太网交换机的实现(自学习和转发帧)
* 检测数据是否误码(差错检测)
* 出现传输差错如何处理(可靠传输和不可靠传输)
* 接收方控制发送方注入网络的数据量(流量控制)
## 网络层
解决数据包在多个网络之间传输和路由的问题
* 标识网络和网络中的各主机(网络和主机共同编址,例如IP地址)
* 路由器转发分组(路由选择协议、路由表和转发表)
## 运输层
解决进程之间基于网络的通信问题
* 进程之间基于网络的通信(进程的标识,例如端口号)
* 出现传输差错如何处理(可靠传输和不可靠传输)
## 应用层
解决通过应用进程的交互来实现特定网络应用的问题
* 通过应用进程间的交互来完成特定的网络应用
* 进行会话管理和数据表示
## 术语
### 实体
* 实体是指任何可发送或接收信息的硬件或软件进程
* 对等实体是指通信双方相同层次中的实体。
### 协议
协议是控制两个对等实体在“水平方向” 进行“逻辑通信”的规则的集合,包含三要素:
* 语法: 定义所交换信息的格式
* 语义: 定义通信双方所要完成的操作
* 同步: 定义通信双方的时序关系
**PDU**:对等层次之间传送的数据包称为该层的协议数据单元(Protocol Data Unit)。
### 服务
要实现某层协议,还需要使用下面一层所提供的服务。
实体看得见下层提供的服务,但并不知道实现该服务的具体协议。下层的协议对上层的实体是“透明”的。
**SAP**:在同一系统中相邻两层的实体交换信息的逻辑接口*称为服务访问点,它被用于区分不同的服务类型**。帧的“类型”字段、IP数据报的“协议”字段,TCP报文段或UDP用户数据报的“端口号”字段都是SAP。
**服务原语**:上层要使用下层所提供的服务,必须通过与下层交换一些命令,这些命令称为服务原语。
**SDU**:同一系统内层与层之间交换的数据包称为服务数据单元(Service Data Unit)。
|
import {
AddreesFormContainer,
CheckOutFormContainer,
FormSectionContainer,
PaymentMethodsContainer
} from "./styles";
import { FormSectionHeader } from "../FormSectionHeader";
import { Bank, CreditCard, CurrencyDollar, MapPinLine, Money } from 'phosphor-react'
import { useTheme } from "styled-components";
import { Input } from "../../../../components/Input";
import { PaymentMethodsInput } from "../PaymentMethodsInput";
import { useFormContext } from "react-hook-form";
interface ErrorsType {
errors: {
[key: string]: {
message: string;
}
}
}
export const paymentMethods = {
credit: {
label: "Cartão de Crédito",
icon: <CreditCard size={16} />
},
debit: {
label: "Cartão de Débito",
icon: <Bank size={16} />
},
money: {
label: "Dinheiro",
icon: <Money size={16} />
}
}
export function CheckOutForm() {
const { colors } = useTheme();
const { register, formState } = useFormContext();
const { errors } = formState as ErrorsType;
const paymentMethodError = errors?.paymentMethod?.message as string;
return (
<CheckOutFormContainer>
<h5>Complete seu pedido</h5>
<FormSectionContainer>
<FormSectionHeader
title='Endereço de Entrega'
subtitle='Informe o endereço onde deseja receber seu pedido'
icon={<MapPinLine color={colors["brand-yellow-dark"]} size={22} />}
/>
<AddreesFormContainer>
<Input
placeholder='CEP'
type='number'
className='cep'
{...register('cep')}
error={errors.cep?.message}
/>
<Input
placeholder='Rua'
type='text'
className='street'
{...register('street')}
error={errors.street?.message}
/>
<Input
placeholder='Número'
type='number'
className='number'
{...register('number')}
error={errors.number?.message}
/>
<Input
placeholder='Complemento'
type='text' className='complement'
{...register('complement')}
/>
<Input
placeholder='Bairro'
type='text'
{...register('district')}
error={errors.district?.message}
/>
<Input
placeholder='Cidade'
type='text'
className='city'
{...register('city')}
error={errors.city?.message}
/>
<Input
placeholder='UF'
type='text'
{...register('uf')}
error={errors.uf?.message}
/>
</AddreesFormContainer>
</FormSectionContainer>
<FormSectionContainer>
<FormSectionHeader
title='Pagamento'
subtitle='O pagamento é feito na entrega. Escolha a forma que deseja pagar'
icon={<CurrencyDollar color={colors["brand-purple"]} size={22} />}
/>
<PaymentMethodsContainer>
{Object.entries(paymentMethods).map(([key, { label, icon }]) => (
<PaymentMethodsInput
key={label}
id={key}
icon={icon}
label={label}
value={key}
{...register("paymentMethod")}
/>
))}
{paymentMethodError && <p>{paymentMethodError}</p>}
</PaymentMethodsContainer>
</FormSectionContainer>
</CheckOutFormContainer>
)
}
|
use clap::{Arg, ArgAction, Command};
fn main() {
let matches = Command::new("echo_rust")
.version("0.1.0")
.author("Mehmet Akifhan ILGAZ <[email protected]>")
.about("Rust echo")
.arg(
Arg::new("text")
.value_name("TEXT")
.help("Input text")
.required(true)
.num_args(1..),
)
.arg(
Arg::new("omit_newline")
.short('n')
.help("Do not print new line")
.action(ArgAction::SetTrue),
)
.get_matches();
let text: Vec<String> = matches
.get_many("text")
.expect("text is required")
.cloned()
.collect();
let omit_newline = matches.get_flag("omit_newline");
print!("{}{}", text.join(" "), if omit_newline { "" } else { "\n" })
}
|
## [2160.拆分数位后四位数字的最小和 中文热门题解1](https://leetcode.cn/problems/minimum-sum-of-four-digit-number-after-splitting-digits/solutions/100000/tan-xin-pai-xu-by-endlesscheng-dkq1)
作者:[endlesscheng](https://leetcode.cn/u/endlesscheng)
通过比对可以发现,拆分成两位数 + 两位数是最优的。因此要使 $\textit{new1}+\textit{new2}$ 最小,应当最小化十位数字。
我们可以将 $\textit{num}$ 的字符串形式从小到大排序,那么前两个数字为十位数,后两个数字为个位数。
```go
func minimumSum(num int) int {
s := []byte(strconv.Itoa(num))
sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
return int(s[0]&15+s[1]&15)*10 + int(s[2]&15+s[3]&15)
}
```
|
import React from "react";
import AddExpenditure from "./AddExpenditure";
import MainDashboardScreen from "./MainDashboardScreen";
import ShowMonthlyTransactions from "./ShowMonthlyTransactions";
import LogoutIcon from "@mui/icons-material/Logout";
import { Avatar, IconButton } from "@mui/material";
import Person2Icon from "@mui/icons-material/Person2";
import GeneralOptionsForSuperUsers from "./GeneralOptionsForSuperUsers";
import EditAccessBySuperUser from "./EditAccessBySuperUser";
import MonthlyReport from "./MonthlyReport";
import { logoutUser } from "../../Actions/userActions";
import { useDispatch, useSelector } from "react-redux";
const MainContainer = ({ currentPath }) => {
const userstate = useSelector((state) => state.loginUserReducer);
const { currentUser } = userstate;
const dispatch = useDispatch();
return (
<div className="main__container">
<div className="main__container__upper__bar">
<IconButton
onClick={() => dispatch(logoutUser())}
sx={{ backgroundColor: "whiteSmoke" }}
>
<LogoutIcon />
</IconButton>
<IconButton sx={{ backgroundColor: "whiteSmoke" }}>
<Avatar>{currentUser?.name?.at(0)}</Avatar>
</IconButton>
</div>
<div className="wrapper">
{currentPath == "dashboard" ? (
<MainDashboardScreen />
) : currentPath == "addExpenditure" ? (
<AddExpenditure />
) : currentPath == "monthlyTransactions" ? (
<ShowMonthlyTransactions />
) : currentPath == "generalOptions" ? (
<GeneralOptionsForSuperUsers />
) : currentPath == "editAccess" ? (
<EditAccessBySuperUser />
) : currentPath == "monthlyReport" ? (
<MonthlyReport />
) : (
<h1>404 Not Found.</h1>
)}
</div>
</div>
);
};
export default MainContainer;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.