text
stringlengths 184
4.48M
|
|---|
import React, { useState, useEffect } from "react";
import { Menu, MenuItem, SubMenu } from "react-pro-sidebar";
import { Link, useLocation } from "react-router-dom";
import {
Dashboard as DashboardIcon,
Subscriptions as SubscriptionIcon,
AppRegistration as AppRegistrationIcon,
AddCircleOutline as AddCircleOutlineIcon,
List as ListIcon,
Payment as PaymentIcon,
AccountCircle as AccountCircleIcon,
SupervisorAccount as SupervisorAccountIcon,
PersonAdd as PersonAddIcon,
VerifiedUser as VerificationIcon,
ExitToApp as ExitToAppIcon,
} from "@mui/icons-material";
import '../Styles/Sidebar.css';
const Sidebar = ({ isAuthenticated, handleLogout }) => {
const [isAdmin, setIsAdmin] = useState(false);
const [userFirstname, setUserFirstname] = useState("");
const location = useLocation();
useEffect(() => {
const storedRole = sessionStorage.getItem("role");
setIsAdmin(storedRole === "ADMIN");
const storedFirstname = sessionStorage.getItem("firstname");
setUserFirstname(storedFirstname);
}, []);
const handleLogoutClick = () => {
handleLogout();
};
return (
<div className="sidebar-container">
<Menu className="custom-sidebar">
<div className="logo-container">
<img src={`${process.env.PUBLIC_URL}/logook.png`} alt="TriTux Gateway" className="logo" />
</div>
<div className="menu-content">
<MenuItem
component={<Link to="/dashboard" className="link" />}
className={`custom-menu-item ${location.pathname === '/dashboard' ? 'active' : ''}`}
icon={<DashboardIcon />}
>
Tableau de bord
</MenuItem>
<SubMenu label="Abonnements" icon={<SubscriptionIcon />} className="custom-submenu">
{isAuthenticated && !isAdmin && (
<>
<MenuItem icon={<AddCircleOutlineIcon />}>
<Link to="/ajouter-abonnement" className={`link ${location.pathname === '/ajouter-abonnement' ? 'active' : ''}`}>
Ajouter un abonnement
</Link>
</MenuItem>
<MenuItem icon={<ListIcon />}>
<Link to="/gestion-abonnement" className={`link ${location.pathname === '/gestion-abonnement' ? 'active' : ''}`}>
Gérer les abonnements
</Link>
</MenuItem>
</>
)}
<MenuItem icon={<ListIcon />}>
<Link to="/liste-abonnement" className={`link ${location.pathname === '/liste-abonnement' ? 'active' : ''}`}>
Liste des abonnements
</Link>
</MenuItem>
</SubMenu>
{isAdmin && (
<MenuItem
component={<Link to="/gestion-utilisateurs" className={`link gestion-utilisateurs ${location.pathname === '/gestion-utilisateurs' ? 'active' : ''}`} />}
className="custom-menu-item"
icon={<SupervisorAccountIcon />}
>
Gestion des utilisateurs
</MenuItem>
)}
{isAdmin && (
<SubMenu label="Applications" icon={<AppRegistrationIcon />} className="custom-submenu">
<MenuItem icon={<AddCircleOutlineIcon />}>
<Link to="/ajouter-application" className={`link ${location.pathname === '/ajouter-application' ? 'active' : ''}`}>
Ajouter une application
</Link>
</MenuItem>
<MenuItem icon={<ListIcon />}>
<Link to="/gestion-application" className={`link ${location.pathname === '/gestion-application' ? 'active' : ''}`}>
Gérer les applications
</Link>
</MenuItem>
<MenuItem icon={<PersonAddIcon />}>
<Link to="/ajouter-utilisateur" className={`link ${location.pathname === '/ajouter-utilisateur' ? 'active' : ''}`}>
Ajouter un utilisateur
</Link>
</MenuItem>
<MenuItem icon={<VerificationIcon />}>
<Link to="/Verification" className={`link ${location.pathname === '/Verification' ? 'active' : ''}`}>
Vérification de compte
</Link>
</MenuItem>
</SubMenu>
)}
{isAuthenticated && !isAdmin && (
<MenuItem className={`custom-menu-item ${location.pathname === '/methode-paiement' ? 'active' : ''}`} icon={<PaymentIcon />}>
<Link to="/methode-paiement" className="link">
Méthode de paiement
</Link>
</MenuItem>
)}
<div className="space-between-sections"></div>
{isAuthenticated && (
<SubMenu label={`${userFirstname}`} icon={<AccountCircleIcon />} className="custom-submenu">
<MenuItem icon={<AccountCircleIcon />}>
<Link to="/modifier-profil" className={`link ${location.pathname === '/modifier-profil' ? 'active' : ''}`}>
Modifier mon profil
</Link>
</MenuItem>
<MenuItem icon={<ExitToAppIcon />} onClick={handleLogoutClick} className="custom-menu-item">
Se déconnecter
</MenuItem>
</SubMenu>
)}
</div>
</Menu>
</div>
);
};
export default Sidebar;
|
import React, { useState} from 'react';
import Link from 'next/link';
import { useRouter } from 'next/router'
import { motion } from 'framer-motion';
import useThemeSwitcher from './hooks/useThemeSwitcher';
import Logo from './Logo';
import { LinkedinIcon, GithubIcon, TwitterIcon, SunIcon, MoonIcon } from './Icons';
const CustomLink = ({ href, title, className=""}) => {
const router = useRouter();
return (
<Link href={href} className={`${className} relative group`}>
{title}
<span className={`
${router.asPath === href ? 'w-full' : 'w-0'}
h-[2px] inline-block bg-dark absolute left-0
-bottom-0.5 group-hover:w-full transition-[width]
ease duration-300 dark:bg-light
`}>
</span>
</Link>
)
}
const CustomMobileLink = ({ href, title, className = "", toggle }) => {
const router = useRouter();
const handleClick = () => {
toggle();
router.push(href);
}
return (
<button href={href} className={`${className} relative group text-light dark:text-dark my-2`} onClick={handleClick}>
{title}
<span className={`
${router.asPath === href ? 'w-full' : 'w-0'}
h-[2px] inline-block bg-light absolute left-0
-bottom-0.5 group-hover:w-full transition-[width]
ease duration-300 dark:bg-dark
`}>
</span>
</button>
)
}
const NavBar = () => {
const [mode, setMode] = useThemeSwitcher();
const [isOpen, setIsOpen] = useState(false);
const handleClick = () => {
setIsOpen(!isOpen)
}
return (
<header className='w-full px-32 py-8 font-medium flex items-center justify-between dark:text-light relative z-10 lg:px-16 md:px-12 sm:px-8'>
<button data-testid="navbar-button" className='flex-col justify-center items-center hidden lg:flex' onClick={handleClick}>
<span className={`bg-dark dark:bg-light block transition-all duration-300 ease-out e h-0.5 w-6 rounded-sm ${isOpen ? "rotate-45 translate-y-1" : "-translate-y-0.5"}`}></span>
<span className={`bg-dark dark:bg-light block transition-all duration-300 ease-out h-0.5 w-6 rounded-sm my-0.5 ${isOpen ? "opacity-0" : "opacity-100"}`}></span>
<span className={`bg-dark dark:bg-light block transition-all duration-300 ease-out h-0.5 w-6 rounded-sm translate-y-0.5 ${isOpen ? "-rotate-45 -translate-y-1" : "translate-y-0.5"}`}></span>
</button>
<div className='w-full flex justify-between items-center lg:hidden'>
<nav data-testid="navbar-nav1">
<CustomLink href="/" title="Home" className='mr-4' />
<CustomLink href="/about" title="About" className='mx-4' />
<CustomLink href="/projects" title="Projects" className='mx-4' />
{/* <CustomLink href="/articles" title="Articles" className='ml-4' /> */}
</nav>
<nav data-testid="navbar-nav2" className='flex items-center justify-center flex-wrap'>
<motion.a
href="https://www.linkedin.com/in/hubert-yang88/"
target={"_blank"}
whileHover={{ y: -2 }}
whileTap={{ scale: 0.9 }}
className='w-6 mr-3'
>
<LinkedinIcon />
</motion.a>
<motion.a
href="https://github.com/flashcabaja64"
target={"_blank"}
whileHover={{ y: -2 }}
whileTap={{ scale: 0.9 }}
className='w-6 mx-3'
>
<GithubIcon />
</motion.a>
<motion.a
href="https://www.twitter.com"
target={"_blank"}
whileHover={{ y: -2 }}
whileTap={{ scale: 0.9 }}
className='w-6 ml-3'
>
<TwitterIcon />
</motion.a>
<button
onClick={() => setMode(mode === "light" ? "dark" : "light")}
className={
`ml-3 flex items-center justify-center rounded-full p-1 ${mode === "light" ? "bg-dark text-light" : "bg-light text-dark"}`
}
>
{
mode === 'dark' ? (
<SunIcon className={"fill-dark"}/>
) : (
<MoonIcon className={"fill-dark"}/>
)
}
</button>
</nav>
</div>
{
isOpen ? (
<motion.div
className='min-w-[70vw] flex-col flex justify-between items-center fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-30 bg-dark/90 dark:bg-light/75 rounded-lg backdrop-blur-md py-32'
initial={{ scale: 0, opacity: 0, x: "-50%", y: "-50%" }}
animate={{ scale: 1, opacity: 1}}
>
<nav className='flex items-center flex-col justify-center'>
<CustomMobileLink href="/" title="Home" className='' toggle={handleClick}/>
<CustomMobileLink href="/about" title="About" className='' toggle={handleClick} />
<CustomMobileLink href="/projects" title="Projects" className='' toggle={handleClick} />
<CustomMobileLink href="/articles" title="Articles" className='' toggle={handleClick} />
</nav>
<nav className='flex items-center justify-center flex-wrap mt-2'>
<motion.a
href="https://www.linkedin.com/in/hubert-yang88/"
target={"_blank"}
whileHover={{ y: -2 }}
whileTap={{ scale: 0.9 }}
className='w-6 mr-3 sm:mx-1'
>
<LinkedinIcon />
</motion.a>
<motion.a
href="https://github.com/flashcabaja64"
target={"_blank"}
whileHover={{ y: -2 }}
whileTap={{ scale: 0.9 }}
className='w-6 mx-3 bg-light rounded-full dark:bg-dark sm:mx-1'
>
<GithubIcon />
</motion.a>
<motion.a
href="https://www.twitter.com"
target={"_blank"}
whileHover={{ y: -2 }}
whileTap={{ scale: 0.9 }}
className='w-6 ml-3 sm:mx-1'
>
<TwitterIcon />
</motion.a>
<button
onClick={() => setMode(mode === "light" ? "dark" : "light")}
className={
`ml-3 flex items-center justify-center rounded-full p-1 ${mode === "light" ? "bg-dark text-light" : "bg-light text-dark"}`
}
>
{
mode === 'dark' ? (
<SunIcon className={"fill-dark"}/>
) : (
<MoonIcon className={"fill-dark"}/>
)
}
</button>
</nav>
</motion.div>
) : null
}
<div className='absolute left-[50%] top-2 translate-x-[-50%]'>
<Logo />
</div>
</header>
)
}
export default NavBar;
|
"use client";
import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import axios from "axios";
export const useFileUpload = () => {
const [uploadProgress, setUploadProgress] = useState(0);
const mutation = useMutation((file: File) => {
const url = `https://api.cloudinary.com/v1_1/${process.env.NEXT_PUBLIC_CLOUDINARY_NAME}/image/upload`;
const formData = new FormData();
formData.append("file", file);
formData.append("upload_preset", `${process.env.NEXT_PUBLIC_CLOUDINARY_UPLOAD_PRESET}`);
return axios.post(url, formData, {
onUploadProgress: (progressEvent) => {
if (progressEvent.total) {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
setUploadProgress(percentCompleted);
}
},
});
});
return { ...mutation, uploadProgress };
};
export const useCheckIsImage = (url?: string) => {
return useQuery(
["checkIsImage", url],
async () => {
try {
if (!url) throw new Error("No url specified");
const response = await axios.get(url, { responseType: "arraybuffer" });
const contentType = response.headers["content-type"];
return contentType.startsWith("image/");
} catch (error: any) {
console.error("Error:", error.message);
return false;
}
},
{
enabled: !!url,
}
);
};
|
import * as vscode from 'vscode';
import { exec } from 'child_process';
import * as util from 'util';
const execAsync = util.promisify(exec);
export async function performGitReset(commitHash: string) {
const cwd = vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders[0].uri.fsPath : null;
if (!cwd) {
vscode.window.showErrorMessage('No open workspace folder found.');
console.error('No open workspace folder found.');
return;
}
//const resetCommand = `git reset --${gitResetOption} ${commitHash}`;
const resetCommand = `git reset --soft ${commitHash}`;
try {
const { stdout, stderr } = await execAsync(resetCommand, { cwd });
if (stderr) {
throw new Error(stderr);
}
console.log(`Reset command executed successfully: ${stdout}`);
vscode.window.showInformationMessage(`Successfully performed soft reset to commit ${commitHash}.`);
} catch (error) {
const errorMessage = (error as Error).message;
vscode.window.showErrorMessage(`Failed to perform soft reset to commit ${commitHash}. See console for details.`);
console.error(`Failed to execute git reset command: ${errorMessage}`, error);
}
}
|
import 'package:flutter/cupertino.dart';
import 'package:v_card/db/db_helper.dart';
import '../models/contact_model.dart';
class ContactProvider extends ChangeNotifier {
List<ContactModel> contactList = [];
final DBHelper db = DBHelper();
Future<int> insertContact(ContactModel contactModel) async {
final rowId = await db.insertContact(contactModel);
contactModel.id = rowId;
contactList.add(contactModel);
notifyListeners();
return rowId;
}
Future<void> getAllContacts() async {
contactList = await db.getAllContacts();
notifyListeners();
}
Future<void> getAllFavoriteContacts() async {
contactList = await db.getAllFavoriteContacts();
notifyListeners();
}
Future<ContactModel> getContactById(int id) => db.getContactsById(id);
Future<int> deleteContact(int id) {
return db.deleteContact(id);
}
Future<void> updateFavorite(ContactModel contactModel) async {
final value = contactModel.favourite ? 0 : 1;
await db.updateFavorite(contactModel.id, value);
final index = contactList.indexOf(contactModel);
contactList[index].favourite = !contactList[index].favourite;
notifyListeners();
}
}
|
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
isLoggedIn: false,
user: null,
isAdmin: false,
}
export const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
loginUser: (state,action) => ({
...state,
isLoggedIn: true,
user: action.payload.user,
isAdmin: action.payload.user.isAdmin ?? false
}),
logOutUser: (state,action) => ({
isLoggedIn: false,
user: null,
isAdmin: false
}),
updateUserProfile: (state,action) => ({
...state,
user: {
...state.user,
displayName: action.payload.displayName
}
})
},
})
// Action creators are generated for each case reducer function
export const { loginUser,logOutUser,updateUserProfile } = userSlice.actions
export const getUser = (state) => state.user.user
export const getIsLoggedIn = (state) => state.user.isLoggedIn
export default userSlice.reducer
|
import React, { useState, useEffect } from "react";
import { Search, Plus } from "neetoicons";
import { Typography } from "neetoui";
import { MenuBar } from "neetoui/layouts";
import articlesApi from "apis/articles";
import categoriesApi from "apis/categories";
import PageLoader from "components/PageLoader";
import { MENU_ITEMS } from "./constants";
import CreateCategories from "../Settings/CreateCategories";
const SideBar = ({ setFilteredArticles, fetchArticles }) => {
const [isSearchCollapsed, setIsSearchCollapsed] = useState(true);
const [createCategory, setCreateCategory] = useState(false);
const [categories, setCategories] = useState([]);
const [searchTerm, setSearchTerm] = useState("");
const [filteredItems, setFilteredItems] = useState([]);
const [loading, setLoading] = useState(true);
const [selectedCategories, setSelectedCategories] = useState([]);
const [active, setActive] = useState("");
const handleUpdateStatus = async menu => {
setActive(menu);
setSelectedCategories([]);
try {
if (menu === "All") {
await fetchArticles();
} else {
const {
data: { articles },
} = await articlesApi.list({ status: menu });
setFilteredArticles(articles);
}
} catch (error) {
logger.error(error);
setLoading(false);
}
};
const handleUpdateCategories = async (category, id) => {
setActive(category);
try {
const newSelectedCategories = [...new Set([...selectedCategories, id])];
setSelectedCategories(Array.from(newSelectedCategories));
const {
data: { articles },
} = await articlesApi.list({
category: newSelectedCategories,
});
setFilteredArticles(articles);
} catch (error) {
logger.error(error);
setLoading(false);
}
};
const fetchCategories = async () => {
try {
const {
data: { categories },
} = await categoriesApi.list();
setCategories(categories);
setFilteredItems(categories);
setLoading(false);
} catch (error) {
logger.error(error);
setLoading(false);
}
};
const handleSearchTerm = async () => {
try {
{
const {
data: { categories },
} = await categoriesApi.list({ category: searchTerm });
setFilteredItems(categories);
}
} catch (error) {
logger.error(error);
setLoading(false);
}
};
useEffect(() => {
fetchCategories();
}, []);
if (loading) {
return (
<div className="h-screen w-screen">
<PageLoader />
</div>
);
}
return (
<MenuBar showMenu title="Articles">
{MENU_ITEMS.map((menu, idx) => (
<MenuBar.Block
className={`${active === menu && "bg-white"}`}
key={idx}
label={menu}
onClick={() => handleUpdateStatus(menu)}
/>
))}
<MenuBar.SubTitle
iconProps={[
{
icon: Plus,
onClick: () => setCreateCategory(createCategory => !createCategory),
},
{
icon: Search,
onClick: () =>
setIsSearchCollapsed(isSearchCollapsed => !isSearchCollapsed),
},
]}
>
<Typography
component="h4"
style="h5"
textTransform="uppercase"
weight="bold"
>
CATEGORIES
</Typography>
</MenuBar.SubTitle>
<MenuBar.Search
collapse={isSearchCollapsed}
placeholder="Search and press Enter"
value={searchTerm}
onChange={e => setSearchTerm(e.target.value)}
onCollapse={() => setIsSearchCollapsed(true)}
onKeyDown={handleSearchTerm}
/>
{setCreateCategory && (
<CreateCategories
createCategory={createCategory}
fetchCategories={fetchCategories}
length={categories.length}
setCreateCategory={setCreateCategory}
/>
)}
{(isSearchCollapsed ? categories : filteredItems).map((category, idx) => (
<MenuBar.Block
key={idx}
label={category.category}
className={`${
selectedCategories.includes(category.id) && "bg-white"
}`}
onClick={() => handleUpdateCategories(category.category, category.id)}
// DblClick={}
/>
))}
</MenuBar>
);
};
export default SideBar;
|
import { useQuery } from '@apollo/react-hooks';
import React, { FC, useCallback } from 'react';
import { Book, BooksData, BOOKS } from '../graphql/books';
const bookSort = (a: Book, b: Book): number => {
if (a.id < b.id) {
return -1;
}
if (a.id > b.id) {
return 1;
}
return 0;
};
const Books: FC = () => {
const { loading, error, data, refetch } = useQuery<BooksData>(BOOKS);
const handleClick = useCallback(() => {
refetch();
}, [refetch]);
if (loading) return <p>Loading...</p>;
if (error || data === undefined) return <p>Error :(</p>;
const sortedBooks = data.books.sort(bookSort); // CANNOT USE USEMEMO HERE
return (
<div>
<button onClick={handleClick} type="button">
Refetch
</button>
{sortedBooks.map(({ author, id, title }) => (
<div key={id} style={{ marginTop: 30 }}>
<div>
<b>author:</b>
{author}
</div>
<div>
<b>id:</b>
{id}
</div>
<div>
<b>title:</b>
{title}
</div>
</div>
))}
</div>
);
};
export default Books;
|
import { Client } from "@notionhq/client";
import { NextResponse } from "next/server";
const notionSecret = process.env.NOTION_API_KEY;
const notionDatabaseId = process.env.NOTION_PROJECTS_ID;
const notion = new Client({ auth: notionSecret });
export async function GET(req, res) {
try {
if (!notionSecret || !notionDatabaseId)
throw new Error("Missing notion secret or DB-ID");
const queryResponse = await notion.databases.query({
database_id: notionDatabaseId,
});
const rows = queryResponse.results.map((result) => result.properties);
const rowsStructured = rows.map((row) => {
// Verificar si row.url_projects está definido antes de acceder a la propiedad url
const url = row.url_projects ? row.url_projects.url : "";
return {
titulo_projects: row.titulo_projects.title[0].plain_text,
etiqueta_projects: row.etiqueta_projects.multi_select[0].name,
etiqueta_projects_color: row.etiqueta_projects.multi_select[0].color, //agregar un diccionario para cambiar los colores a hexadecimal
descripcion_projects: row.descripcion_projects.rich_text[0].plain_text,
imagen_projects: row.imagen_projects.files[0].external.url,
url_projects: url, // Asignar la URL o una cadena vacía si row.url_projects no está definido
};
});
return NextResponse.json(rowsStructured);
} catch (error) {
console.error(error);
return NextResponse.error({
status: 500,
body: { message: "Internal Server Error" },
});
}
}
|
# Author: Bryan Bergo, date: 10/23/23
# Description: We will practice simple for loop
# The code will compute the sums of the values from 0 to n-1
# We get the value of n from the user
#
# n = prompt('Enter the value to calculate the sum up to: ')
# total = 0
# for(i = 0; i < n; i++) {
# total = total + i
# }
# print('Total = ' + total)
.data
input_msg: .asciiz "Enter the value to calculate the sum up to: "
output_msg: .asciiz "The sum of the values is: "
.text
main:
###################
# Read the values #
###################
# print input_msg
li $v0, 4 # 4 is the code to print string
la $a0, input_msg # load the address of the string
syscall
# read the input from the user
li $v0, 5 # 5 is the code to read integer
syscall
move $s0, $v0 # save the value in $t0
###################
# Compute the sum #
###################
move $s1 $zero # initialize the sum to 0
move $t0 $zero # initialize the counter to 0
for_loop:
add $s1, $s1, $t0 # total = total + 1
addi $t0, $t0, 1 # add one to the counter
blt $t0, $s0, for_loop # if i <= n then run the loop
end_loop:
# print the value of the total
# print the output message
la $a0, output_msg
li $v0, 4
syscall
# display the value of sum
move $a0, $s1
li $v0, 1
syscall
j exit # exit the program
exit:
li $v0, 10 # 10 is the code to exit
syscall
|
#include "search_algos.h"
/* header */
int helper(int *array, int l, int r, int value);
/**
* advanced_binary - a function that searches for a value in a
* sorted list of integers using the binary search algorithm but
* in an advanced way using recursion and one loop
*
* @array: array of sorted integers
*
* @size: size of array
*
* @value: target to find
*
* Return: index where value is located otherwise -1
*/
int advanced_binary(int *array, size_t size, int value)
{
if (array == NULL)
return (-1);
return (helper(array, 0, size - 1, value));
}
/**
* helper - helper functiono for advanced binary search
*
* @array: pointer to array of sorted integers
*
* @l: keeps tab on left position/left tab
*
* @r: keeps tab on right position/right tab
*
* @value: target to find
*
* Return: index to value otherwise -1
*/
int helper(int *array, int l, int r, int value)
{
int mid, i;
if (l <= r)
{
printf("Searching in array: ");
for (i = l; i < r; i++)
printf("%d, ", array[i]);
printf("%d\n", array[i]);
}
if (l <= r)
{
mid = (l + r) / 2;
if (array[mid] == value && l == mid)
return (mid);
if (array[mid] < value)
return (helper(array, mid + 1, r, value));
else if (array[mid] > value)
return (helper(array, l, mid, value));
/*else if (array[mid] == value && l == mid)*/
/*return (mid);*/
else
return (helper(array, l, mid, value));
/*printf("%d, %d, %d\n", l, r, mid);*/
}
return (-1);
}
|
<!--
Form Validation:
You can add the "required" inside the input tag so a user must enter a value in the field.
if its an email address you just have to make sure the lable for the input is email.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>exc4</title>
</head>
<body>
<h1>Register</h1>
<form>
<label for="first">First Name:</label>
<input name="first" id="first" type="text" placeholder="John" required>
<label for="last">Last Name:</label>
<input name="last" id="last" type="text" placeholder="smith" required>
<div>
<label for="male">Male</label>
<input id="male" type="radio" name="gender" value="Male">
<label for="female">Female</label>
<input id="female" type="radio" name="gender" value="Female">
<label for="other">Other</label>
<input id="other" type="radio" name="gender" value="Other">
</div>
<div>
<label>
Email:
<input name="email" type="email" placeholder="Your Email" required>
</label>
<label>
Password:
<input name="password" type="password" placeholder="Your Password" required pattern=".{5,10}" title="Password must be between 5 and 10 charcters.">
</label>
</div>
<label>
Birthday:
<select name="month">
<option>Month</option>
<option>Jan</option>
<option>Feb</option>
<option>Mar</option>
<option>Apr</option>
</select>
<select name="day">
<option>Day</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<select name="year">
<option>Year</option>
<option>1980</option>
<option>1981</option>
<option>1982</option>
<option>1983</option>
</select>
</label>
<div>
<div>
<label for="agreed">I agree to the terms and conditions</label>
<input id="agreed" type="checkbox">
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
|
<h1 class="text-center titulo color-venta mb-4">Ventas</h1>
<div class="text-center">
<button type="button" (click)="abrirDialogo()" class="btn boton-venta mb-1">Nueva Venta</button>
</div>
<p-table [value]="ventas" selectionMode="single" [(selection)]="ventaElegida" datakey="id">
<ng-template pTemplate="header">
<tr>
<th>ID</th>
<th>Empleado</th>
<th>Total</th>
<th>Creado</th>
<th>Actualizado</th>
<th>Observaciones</th>
<th>Opciones</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-venta>
<tr>
<td>{{venta.id}}</td>
<td>{{venta.idEmpleado}}</td>
<td>$ {{venta.total}}</td>
<td>{{venta.createdAt}}</td>
<td>{{venta.updatedAt}}</td>
<td>{{venta.observaciones}}</td>
<td>
<button type="button" (click)="borrar(venta)" class="btn btn-danger btn-sm"><i class="far fa-trash-alt"></i></button>
<button type="button" (click)="actualizar(venta)" class="btn btn-success btn-sm"><i class="fas fa-edit"></i></button>
</td>
</tr>
</ng-template>
</p-table>
<button type="button" (click)="abrirDialogo()" class="btn boton-venta">Nueva Venta</button>
<p-dialog header="Detalles" [(visible)]="displayDialog" [responsive]="true" showEffect="fade" [modal]="true" [width]="500">
<div class="ui-g ui-fluid" *ngIf="producto">
<div class="ui-g-12">
<div class="ui-g-4">
<label for="total">Total</label>
</div>
<div class="ui-g-8">
<input pInputText id="total" placeholder="" [(ngModel)]="venta.total" />
</div>
</div>
<div class="ui-g-12">
<div class="ui-g-4">
<label for="estado">Estado</label>
</div>
<div class="ui-g-8">
<input pInputText id="estado" placeholder="" [(ngModel)]="producto.estado" />
</div>
</div>
<div class="ui-g-12">
<div class="ui-g-4">
<label for="precioVenta">Precio de Venta</label>
</div>
<div class="ui-g-8">
<input pInputText id="precioVenta" placeholder="" [(ngModel)]="producto.precioVenta" />
</div>
</div>
<div class="ui-g-12">
<div class="ui-g-4">
<label for="observaciones">Observaciones</label>
</div>
<div class="ui-g-8">
<input pInputText id="observaciones" placeholder="" [(ngModel)]="producto.observaciones" />
</div>
</div>
</div>
<p-footer>
<div class="ui-dialog-buttonpane ui-helper-clearfix">
<!-- <button type="button" pButton icon="fa fa-close" (click)="delete()" label="Delete"></button> -->
<button type="button" pButton icon="fa fa-check" (click)="save()" label="Guardar"></button>
</div>
</p-footer>
</p-dialog>
<p-toast [style]="{marginTop: '80px'}" key="nuevaVenta"></p-toast>
<p-toast [style]="{marginTop: '80px'}" key="cambioVenta"></p-toast>
<p-toast [style]="{marginTop: '80px'}" key="borraVenta"></p-toast>
<p-confirmDialog></p-confirmDialog>
|
import json
import os.path
from typing import Any, Literal, Optional
from pydantic import BaseModel
import frappe
from frappe.frappeclient import FrappeClient
from frappe.translate import get_messages as frappe_get_messages
from frappe.translate import get_translation_dict_from_file, get_translator_url
class Response(BaseModel):
id: str
source_text: str
context: Optional[str]
translated_text: Optional[str]
translated: Literal[0, 1]
translated_by_google: Literal[0, 1]
contributor_name: Optional[str]
contributor_email: Optional[str]
modified_by: Any
creation: Any
def get_message(text: str):
if messages := frappe_get_messages("ru", page_length=1, search_text=text):
return Response(**messages[0])
frappe.init("site", "../../sites")
frappe.connect()
def add_to_tosendjson(source_id: str, source_text: str, translated_text: str):
if not os.path.exists("to_send.json"):
with open("to_send.json", "w") as f:
json.dump({}, f)
with open("to_send.json", "r+") as f:
content: dict[str, dict[str, Any]] = json.load(f)
content[source_id] = {
"source_text": source_text,
"translated_text": translated_text,
"context": None,
}
f.seek(0)
json.dump(content, f)
def remove_from_toprocessjson(source_text: str):
with open("to_process.json", "r+") as f:
content: dict[str, str] = json.load(f)
if source_text in content:
del content[source_text]
f.seek(0)
f.truncate(0)
json.dump(content, f)
def get_next_item():
if not os.path.exists("to_process.json"):
with open("to_process.json", "w") as f:
json.dump(get_translation_dict_from_file("test.csv", "ru", "comfort"), f)
with open("to_process.json", "r+") as f:
content: dict[str, str] = json.load(f)
items = list(content.items())
if items:
return items[0]
return None, None
def collect():
while True:
before, after = get_next_item()
if not before or not after:
break
response = get_message(before)
if not response:
print(f"Not found. original: {before}, translated: {after}")
elif response.source_text == before and response.translated_text != after:
add_to_tosendjson(
source_id=response.id,
source_text=response.source_text,
translated_text=after,
)
print(
f"Updated. original: {before}, official: {response.translated_text}, mine: {after}"
)
else:
print(f"Skipped. original: {before}, translated: {after}")
remove_from_toprocessjson(before)
class PayloadItem(BaseModel):
source_text: str
translated_text: str
context: None
name: None = None
def split_to_chunks(list_: list[Any], chunk_size: int):
return (list_[i : i + chunk_size] for i in range(0, len(list_), chunk_size))
def remove_from_tosendjson(id_: str):
with open("to_send.json", "r+") as f:
content: dict[str, str] = json.load(f)
if id_ in content:
del content[id_]
f.seek(0)
f.truncate(0)
json.dump(content, f)
def send():
with open("to_send.json") as f:
items: dict[str, dict[str, Any]] = json.load(f)
for item in items.copy():
items[item] = PayloadItem(**items[item]).dict()
url: str = get_translator_url()
client = FrappeClient(url)
for chunk in split_to_chunks(list(items.items()), 5):
client.post_api(
"translator.api.add_translations",
params={
"language": "ru",
"contributor_email": "mail@vrslev.com",
"contributor_name": "Lev",
"translation_map": json.dumps(dict(chunk)),
},
)
print("Sent chunk")
for id_, _ in chunk:
remove_from_tosendjson(id_)
collect()
send()
|
import { currentOscillators } from '../../contexts/reducers/oscillatorTriggerReducer';
import { initialSettings, oscAGain, oscBGain } from '../../nodesConfig';
import { LFOMode, TIME_CONSTANT } from '../constants';
import { linearToLinearRange, roundTwoDigits } from '../helpers';
export default class LFO {
node;
easing;
mixGain;
mode: LFOMode;
constructor(public audioContext: AudioContext) {
this.audioContext = audioContext;
this.node = this.audioContext.createOscillator();
this.node.type = initialSettings.lfo.type;
this.node.frequency.value = initialSettings.lfo.frequency;
this.easing = 0.006;
this.mixGain = this.audioContext.createGain();
this.mixGain.gain.value = initialSettings.lfo.gain;
this.mode = LFOMode.TREMOLO;
this.wireUp();
this.node.start();
}
connect(destination: AudioParam) {
this.mixGain.connect(destination);
}
disconnect() {
this.mixGain.disconnect();
}
activate({ gain }: { gain: number }) {
this.mixGain.gain.setValueAtTime(
gain,
this.audioContext.currentTime + TIME_CONSTANT,
);
this.mixGain.connect(oscAGain.gain);
this.mixGain.connect(oscBGain.gain);
}
deactivate() {
this.mixGain.gain.setValueAtTime(
0,
this.audioContext.currentTime + TIME_CONSTANT,
);
this.mixGain.disconnect();
}
setMode(mode: LFOMode) {
this.mode = mode;
switch (mode) {
case LFOMode.TREMOLO:
this.disconnect();
this.connect(oscAGain.gain);
this.connect(oscBGain.gain);
return;
case LFOMode.VIBRATO:
this.disconnect();
currentOscillators.forEach((oscillator) => {
this.connect(oscillator.node.frequency);
});
return;
default:
return console.error('setMode: unknown lfo mode');
}
}
setRate(value: number) {
const convertedValue = linearToLinearRange(value, [0.1, 15]);
this.node.frequency.setValueAtTime(
convertedValue,
this.audioContext.currentTime + TIME_CONSTANT,
);
}
setType(type: OscillatorType) {
this.node.type = type;
}
setTremoloGain(value: number) {
this.mixGain.gain.setValueAtTime(
// Input value based on mouse drag has precision issue, value is often not 0 when input visually is
value < 0.03 ? 0 : roundTwoDigits(value),
this.audioContext.currentTime + TIME_CONSTANT,
);
}
setVibratoGain(value: number) {
this.mixGain.gain.setValueAtTime(
// Input value based on mouse drag has precision issue, value is often not 0 when input visually is
roundTwoDigits(value * 100),
this.audioContext.currentTime + TIME_CONSTANT,
);
}
wireUp() {
this.node.connect(this.mixGain);
}
}
|
"use client"
import { Plus, Search } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { api } from '../../../../util/axios'
import { extractExercisesFromWorkoutObject } from '../../../../lib/extractExercisesFromWorkoutObject'
import AddExerciseCard from './AddExerciseCard'
import { useQuery } from '@tanstack/react-query'
import { getExercises } from '../../../exercises/getExercises'
import { useAuthContext } from '../../../../hooks/auth/useAuthContext'
import { getExercisesNotInWorkout } from '../get'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Input } from '@/components/ui/input'
type ExerciseAdderProps = {
workout: Workout
// exercises: Exercise[]
}
function ExerciseAdder({ workout }: ExerciseAdderProps) {
const [exercises, setExercises] = useState<Exercise[]>([])
const [search, setSearch] = useState("")
const { state } = useAuthContext()
const { data } = useQuery({
queryKey: ["allExercises"],
queryFn: () => getExercises(state.user?.userId)
})
const allExercises = data
useEffect(() => {
if (allExercises) {
const diff = getExercisesNotInWorkout(allExercises, workout);
setExercises(diff);
}
}, [allExercises, workout, workout]);
return (
<div className='mt-2'>
<div className='flex gap-2 items-center mb-2'>
<Search size={18} />
<Input value={search} onChange={(e) => setSearch(e.target.value)} placeholder='Nach Übung suchen' className="" />
</div>
<ScrollArea className='h-64 mt-4'>
<div className='grid grid-cols-2 gap-2'>
{exercises?.map(exercise => {
const el = <AddExerciseCard exercise={exercise} workoutId={workout.workout_id} key={exercise.exercise_id} />
if (search.length > 0) {
if (exercise.exercise_name.includes(search))
return (el)
}
else
return el
})
}
</div>
</ScrollArea>
</div>
)
}
export default ExerciseAdder
|
package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse;
import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse;
import uk.gov.hmcts.reform.civil.callback.Callback;
import uk.gov.hmcts.reform.civil.callback.CallbackHandler;
import uk.gov.hmcts.reform.civil.callback.CallbackParams;
import uk.gov.hmcts.reform.civil.callback.CaseEvent;
import uk.gov.hmcts.reform.civil.model.CaseData;
import uk.gov.hmcts.reform.civil.notify.NotificationService;
import uk.gov.hmcts.reform.civil.notify.NotificationsProperties;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT;
import static uk.gov.hmcts.reform.civil.utils.PartyUtils.getPartyNameBasedOnType;
@Service
@RequiredArgsConstructor
public class NotifyClaimantClaimSubmitted extends CallbackHandler implements NotificationData {
private static final List<CaseEvent> EVENTS = List.of(CaseEvent.NOTIFY_APPLICANT1_CLAIM_SUBMITTED);
public static final String TASK_ID_Applicant1 = "NotifyApplicant1ClaimSubmitted";
private static final String REFERENCE_TEMPLATE = "claim-submitted-notification-%s";
private final NotificationService notificationService;
private final NotificationsProperties notificationsProperties;
private final Map<String, Callback> callBackMap = Map.of(
callbackKey(ABOUT_TO_SUBMIT), this::notifyApplicantForClaimSubmitted
);
@Override
protected Map<String, Callback> callbacks() {
return callBackMap;
}
@Override
public String camundaActivityId(CallbackParams callbackParams) {
return TASK_ID_Applicant1;
}
private CallbackResponse notifyApplicantForClaimSubmitted(CallbackParams callbackParams) {
CaseData caseData = callbackParams.getCaseData();
if (Objects.isNull(caseData.getHelpWithFeesReferenceNumber())) {
generateEmail(caseData);
}
return AboutToStartOrSubmitCallbackResponse.builder()
.build();
}
@Override
public List<CaseEvent> handledEvents() {
return EVENTS;
}
@Override
public Map<String, String> addProperties(CaseData caseData) {
return Map.of(
CLAIMANT_NAME, getPartyNameBasedOnType(caseData.getApplicant1())
);
}
private void generateEmail(CaseData caseData) {
if (Objects.nonNull(caseData.getApplicant1Email())) {
notificationService.sendMail(
caseData.getApplicant1Email(),
notificationsProperties.getNotifyLiPClaimantClaimSubmittedAndPayClaimFeeTemplate(),
addProperties(caseData),
String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference())
);
}
}
}
|
{% extends 'home_base.html' %}
{% load static %}
{% block content %}
= slider area =
<div class="slider-area mb-80 mb-md-60 mb-sm-60">
<!--======= slider-wrapper =======-->
<div class="lezada-slick-slider decor-slider-wrapper" data-slick-setting='{
"slidesToShow": 1,
"slidesToScroll": 1,
"arrows": true,
"dots": false,
"centerMode": true,
"centerPadding": "22%",
"autoplay": true,
"autoplaySpeed": 5000,
"speed": 1000,
"prevArrow": {"buttonClass": "slick-prev", "iconClass": "ti-angle-left" },
"nextArrow": {"buttonClass": "slick-next", "iconClass": "ti-angle-right" }
}' data-slick-responsive='[
{"breakpoint":1501, "settings": {"slidesToShow": 1, "arrows": true, "centerPadding": "160px"} },
{"breakpoint":1199, "settings": {"slidesToShow": 1, "arrows": true, "centerMode": false} },
{"breakpoint":991, "settings": {"slidesToShow": 1,"slidesToScroll": 1, "arrows": true, "centerMode": false} },
{"breakpoint":767, "settings": {"slidesToShow": 1, "slidesToScroll": 1, "arrows": true, "centerMode": false} },
{"breakpoint":575, "settings": {"slidesToShow": 1, "slidesToScroll": 1, "arrows": true, "centerMode": false} },
{"breakpoint":479, "settings": {"slidesToShow": 1, "slidesToScroll": 1, "arrows": true, "centerMode": false} }
]'>
<!--======= single slider =======-->
<div class="decor-single-slider">
<div class="decor-single-slider-content">
<!--======= slider image =======-->
<div class="slider-image">
<img src="{% static 'images/slider/banner-carousel-1.jpg' %}" class="img-fluid" alt="">
</div>
<!--======= End of slider image =======-->
<!--======= slider content =======-->
<div class="slider-content">
<div class="color-title color-title--blue">
accessories
</div>
<div class="main-title">
Desktop <br>
Computers
</div>
<a href="{% url 'shop_view' %}" class="lezada-button lezada-button--medium">shop now</a>
</div>
<!--======= End of slider content =======-->
</div>
</div>
<!--======= End of single slider =======-->
<!--======= single slider =======-->
<div class="decor-single-slider">
<div class="decor-single-slider-content">
<!--======= slider image =======-->
<div class="slider-image">
<img src="{% static 'images/slider/banner-carousel-2.jpg' %}" class="img-fluid" alt="">
</div>
<!--======= End of slider image =======-->
<!--======= slider content =======-->
<div class="slider-content">
<div class="color-title color-title--brown">
comfort
</div>
<div class="main-title">
Light weight, <br>
Laptops
</div>
<a href="{% url 'shop_view' %}" class="lezada-button lezada-button--medium">shop now</a>
</div>
<!--======= End of slider content =======-->
</div>
</div>
<!--======= End of single slider =======-->
<!--======= single slider =======-->
<div class="decor-single-slider">
<div class="decor-single-slider-content">
<!--======= slider image =======-->
<div class="slider-image">
<img src="{% static 'images/slider/banner-carousel-3.jpg' %}" class="img-fluid" alt="">
</div>
<!--======= End of slider image =======-->
<!--======= slider content =======-->
<div class="slider-content">
<div class="color-title text-danger">
speed
</div>
<div class="main-title text-light">
Mother boards
</div>
<a href="{% url 'shop_view' %}" class="lezada-button lezada-button--medium">shop now</a>
</div>
<!--======= End of slider content =======-->
</div>
</div>
<!--======= End of single slider =======-->
</div>
<!--======= End of slider-wrapper =======-->
</div>
<!--===== End of slider area ======-->
= tab product list area =
<div class="tab-product-list-area mb-25 mb-md-5 mb-sm-5">
<div class="container">
<div class="row">
<div class="col-lg-12">
<!--======= tab product navigation =======-->
<div class="tab-product-navigation mb-50">
<div class="nav nav-tabs justify-content-center" id="nav-tab2" role="tablist">
<!-- <a class="nav-item nav-link active" id="product-tab-1" data-toggle="tab" href="#product-series-1"
role="tab" aria-selected="true">New</a> -->
<a class="nav-item nav-link" id="product-tab-2" data-toggle="tab" href="#" role="tab"
aria-selected="false">Popular</a>
<!-- <a class="nav-item nav-link" id="product-tab-3" data-toggle="tab" href="#product-series-3" role="tab"
aria-selected="false">Sale</a> -->
</div>
</div>
<!--======= End of tab product navigation =======-->
<!--======= tab product content =======-->
<div class="tab-content" id="nav-tabContent2">
<div class="tab-pane fade show active" id="product-series-1" role="tabpanel"
aria-labelledby="product-tab-1">
<div class="row">
{% for product in products %}
<!--======= single product =======-->
<div class="col-12 col-lg-4 col-md-6 col-sm-6 mb-45">
<div class="single-product">
<!--======= single product image =======-->
<div class="single-product__image fixed-size-image">
<a class="image-wrap" href="{% url 'singleproduct' category_slug=product.category.slug product_slug=product.slug %}">
<img src="{{ product.image_set.first.image.url }}" class="img-fluid" alt="{{ product.product_name }}">
</a>
{% if product in producs_product_offers or product in products_category_offers %}
<div class="single-product__floating-badges">
<span class="onsale">offer</span>
<span class="hot">hot</span>
</div>
{% endif %}
<div class="single-product__floating-icons">
<span class="wishlist"><a href="{% url 'add_to_wishlist' product.id %}" data-tippy="Add to wishlist" data-tippy-inertia="true"
data-tippy-animation="shift-away" data-tippy-delay="50" data-tippy-arrow="true"
data-tippy-theme="sharpborder" data-tippy-placement="left"><i
class="ion-android-favorite-outline"></i></a></span>
</div>
</div>
<!--======= End of single product image =======-->
<!--======= single product content =======-->
<div class="single-product__content">
{% if product.stock > 0 %}
<form method="post" action="{% url 'add_to_cart' product.id %}" id="form_{{ product.id }}">
{% csrf_token %}
<div class="title">
<h3>
<a href="{% url 'singleproduct' category_slug=product.category.slug product_slug=product.slug %}">
{% if product.product_name|length > 35 %}
{{ product.product_name|slice:":35" }}...
{% else %}
{{ product.product_name }}
{% endif %}
</a>
</h3>
<button type="submit" class="btn product-btn btn-link btn-lg text-decoration-none add-to-cart-btn" style="font-size: small;" id="addToCartBtn_{{ product.id }}">+Add to Cart</button>
</div>
</form>
{% else %}
<div class="title">
<a href="#">Out of stock</a>
</div>
{% endif %}
<div class="price">
<span class="main-price discounted">₹{{ product.price }}</span>
<span class="discounted-price">₹{{ product.price }}</span>
</div>
</div>
<!--======= End of single product content =======-->
</div>
</div>
<!--======= End of single product =======-->
{% endfor %}
</div>
</div>
</div>
<!--======= End of tab product content =======-->
</div>
</div>
</div>
</div>
<!--===== End of tab product list area ======-->
= footer banner section area =
{% include 'includes/home_footer.html' %}
<!--===== End of footer three ======-->
= overlay items =
= overlay items =
<!--======= about overlay =======-->
<div class="header-offcanvas about-overlay" id="about-overlay">
<div class="overlay-close inactive"></div>
<div class="overlay-content">
<!--======= close icon =======-->
<span class="close-icon" id="about-close-icon">
<a href="javascript:void(0)">
<i class="ti-close"></i>
</a>
</span>
<!--======= End of close icon =======-->
<!--======= overlay content container =======-->
<div class="overlay-content-container d-flex flex-column justify-content-between h-100">
<!--======= widget wrapper =======-->
<div class="widget-wrapper">
<!--======= single widget =======-->
<div class="single-widget">
<h2 class="widget-title">About Us</h2>
<p>At Lezada, we put a strong emphasis on simplicity, quality and usefulness of fashion products over other
factors. Our fashion items never get outdated. They are not short-lived as normal fashion clothes.</p>
</div>
<!--======= End of single widget =======-->
</div>
<!--======= End of widget wrapper =======-->
<!--======= contact widget =======-->
<div class="contact-widget">
<p class="email"><a href="mailto:contact@lezada.com">sajinprasad52@gmail.com</a></p>
<p class="phone">+91 8921082096</p>
<div class="social-icons">
<ul>
<li><a href="http://www.twitter.com/" data-tippy="Twitter" data-tippy-inertia="true"
data-tippy-animation="shift-away" data-tippy-delay="50" data-tippy-arrow="true"
data-tippy-theme="sharpborder" target="_blank"><i class="fa fa-twitter"></i></a></li>
<li><a href="http://www.facebook.com/" data-tippy="Facebook" data-tippy-inertia="true"
data-tippy-animation="shift-away" data-tippy-delay="50" data-tippy-arrow="true"
data-tippy-theme="sharpborder" target="_blank"><i class="fa fa-facebook"></i></a></li>
<li><a href="http://www.instagram.com/" data-tippy="Instagram" data-tippy-inertia="true"
data-tippy-animation="shift-away" data-tippy-delay="50" data-tippy-arrow="true"
data-tippy-theme="sharpborder" target="_blank"><i class="fa fa-instagram"></i></a></li>
<li><a href="http://www.youtube.com/" data-tippy="Youtube" data-tippy-inertia="true"
data-tippy-animation="shift-away" data-tippy-delay="50" data-tippy-arrow="true"
data-tippy-theme="sharpborder" target="_blank"><i class="fa fa-youtube-play"></i></a></li>
</ul>
</div>
</div>
<!--======= End of contact widget =======-->
</div>
<!--======= End of overlay content container =======-->
</div>
</div>
<!--======= End of about overlay =======-->
<!--======= wishlist overlay =======-->
<div class="wishlist-overlay" id="wishlist-overlay">
<div class="wishlist-overlay-close inactive"></div>
<div class="wishlist-overlay-content">
<!--======= close icon =======-->
<span class="close-icon" id="wishlist-close-icon">
<a href="javascript:void(0)">
<i class="ion-android-close"></i>
</a>
</span>
<!--======= End of close icon =======-->
<!--======= offcanvas wishlist content container =======-->
<div class="offcanvas-cart-content-container">
<h3 class="cart-title">Wishlist</h3>
<div class="cart-product-wrapper">
{% for item in wishlist_items %}
<div class="cart-product-container ps-scroll">
<!--======= single cart product =======-->
<div class="single-cart-product">
<span class="cart-close-icon">
<a href="#"><i class="ti-close"></i></a>
</span>
<div class="image">
<a href="{% url 'singleproduct' category_slug=item.product.category.slug product_slug=item.product.slug %}">
<img src="{{ item.product.image_set.first.image.url }}" class="img-fluid" alt="">
</a>
</div>
<div class="content">
<h5><a href="{% url 'singleproduct' category_slug=item.product.category.slug product_slug=item.product.slug %}">{{item.product.product_name}}</a></h5>
<p><span class="main-price discounted"></span> <span class="discounted-price">₹{{item.product.price}}</span></p>
</div>
</div>
<!--======= End of single cart product =======-->
</div>
{% endfor %}
<!--======= cart buttons =======-->
<div class="cart-buttons">
<a href="{% url 'wishlist' %}">view wishlist</a>
</div>
<!--======= End of cart buttons =======-->
</div>
</div>
<!--======= End of offcanvas wishlist content container =======-->
</div>
</div>
<!--======= End of wishlist overlay =======-->
<!--======= cart overlay =======-->
<div class="cart-overlay" id="cart-overlay">
<div class="cart-overlay-close inactive"></div>
<div class="cart-overlay-content">
<!--======= close icon =======-->
<span class="close-icon" id="cart-close-icon">
<a href="javascript:void(0)">
<i class="ion-android-close"></i>
</a>
</span>
<!--======= End of close icon =======-->
<!--======= offcanvas cart content container =======-->
<div class="offcanvas-cart-content-container">
<h3 class="cart-title">Cart</h3>
<div class="cart-product-wrapper">
<div class="cart-product-container ps-scroll">
<!--======= single cart product =======-->
{% for cart_item in cart_items %}
<div class="single-cart-product">
<span class="cart-close-icon">
<a href="{% url 'delete_cart_item' cart_item.id %}"><i class="ti-close"></i></a>
</span>
<div class="image">
<a href="{% url 'singleproduct' category_slug=cart_item.product.category.slug product_slug=cart_item.product.slug %}">
<img src="{{ cart_item.product.image_set.first.image.url }}" class="img-fluid" alt="">
</a>
</div>
<div class="content">
<h5><a href="#">{{ cart_item.product.product_name }}</a></h5>
{% if cart_item.product.is_available %}
<p><span class="cart-count">{{ cart_item.quantity }} x </span> <span class="discounted-price">₹{{ cart_item.product.price }}</span></p>
{% else %}
<p><span class="discounted-price text-danger">Not available</span></p>
{% endif %}
</div>
</div>
{% endfor %}
<!--======= End of single cart product =======-->
</div>
<!--======= subtotal calculation =======-->
<p class="cart-subtotal">
<span class="subtotal-title">Subtotal:</span>
<span class="subtotal-amount">₹{{cart_total}}</span>
</p>
<!--======= End of subtotal calculation =======-->
<!--======= cart buttons =======-->
<div class="cart-buttons">
<a href="{% url 'cart' %}">view cart</a>
<a href="{% url 'order_checkout' %}">checkout</a>
</div>
<!--======= End of cart buttons =======-->
<!--======= free shipping text =======-->
<p class="free-shipping-text">
Enjoy shopping!
</p>
<!--======= End of free shipping text =======-->
</div>
</div>
<!--======= End of offcanvas cart content container =======-->
</div>
</div>
<!--======= End of cart overlay =======-->
<!--======= search overlay =======-->
<div class="search-overlay" id="search-overlay">
<!--======= close icon =======-->
<span class="close-icon search-close-icon">
<a href="javascript:void(0)" id="search-close-icon">
<i class="ti-close"></i>
</a>
</span>
<!--======= End of close icon =======-->
<!--======= search overlay content =======-->
<div class="search-overlay-content">
<div class="input-box">
<form method="get" action="{% url 'search_products' %}">
<input name="search" type="search" placeholder="Search Products...">
</form>
</div>
<div class="search-hint">
<span># Hit enter to search or ESC to close</span>
</div>
</div>
<!--======= End of search overlay content =======-->
</div>
<!--======= End of search overlay =======-->
<!--===== End of overlay items ======-->
= quick view =
<!--===== End of quick view ======-->
<!-- scroll to top -->
<a href="#" class="scroll-top"></a>
<!-- end of scroll to top -->
<!-- JS
<!-- jQuery JS -->
<script src="{% static 'js/vendor/jquery.min.js' %}"></script>
<!-- Popper JS -->
<script src="{% static 'js/popper.min.js' %}"></script>
<!-- Bootstrap JS -->
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<!-- Plugins JS -->
<script src="{% static 'js/plugins.js' %}"></script>
<!-- Main JS -->
<script src="{% static 'js/main.js' %}"></script>
<script>
function submitForm(productId) {
document.getElementById("form_" + productId).submit();
}
</script>
<!-- Mirrored from htmldemo.net/lezada/lezada/ by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 07 Jun 2022 10:50:54 GMT -->
</html>
{% endblock %}
|
import { type QueryClient } from '@tanstack/react-query'
import { useContext } from 'react'
import { Outlet, useLocation } from 'react-router-dom'
import { DarkModeContext } from '../context/DarkModeContext'
import axiosInstance from '../utils/api'
import Header from './Header'
import Sidebar from './Sidebar'
export interface IAuthStatus {
isAuthenticated: boolean
data: {
displayName: string
email: string
exp: number
googleId: string
iat: number
profilePicture: string
role: string
userId: string
}
}
export const getAuthStatus = () => ({
queryKey: ['authStatus'],
queryFn: async () => {
try {
const response = await axiosInstance.get<IAuthStatus>(`/auth/status`)
return response.data
} catch (error: any) {
throw new Error(error)
}
},
staleTime: 0
})
export const loader = (queryClient: QueryClient) => async () => {
const query = getAuthStatus()
return queryClient.getQueryData(query.queryKey) ?? (await queryClient.fetchQuery(query))
}
const Layout: React.FC = () => {
const { isDarkMode } = useContext(DarkModeContext)
const location = useLocation()
const hideSidebar = (paths: string[]) => !paths.includes(location.pathname)
return (
<div className={isDarkMode ? 'dark' : ''}>
<div className="color-background color-heading flex flex-col h-screen">
<Header />
<div className="flex flex-1 overflow-hidden">
<main className="flex-1 p-5 overflow-auto">
<Outlet />
</main>
{hideSidebar(['/login', '/review', '/appointments', '/register']) && <Sidebar />}
</div>
</div>
</div>
)
}
export default Layout
|
/****** These notes taken from: docs.oracle.com ******/
/* Conventions */
List<E> list; // E stands for element
Map<K, V> map; // K stands for Key, V stands for value
class Collections {
public static <T> void copy(List<T> dest, List<? extends T> src) {
// T stands for Type
}
_______________________________________________________________________________
/* Defining simple generics */
public interface List <E> {
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E> {
E next();
boolean hasNext();
}
_______________________________________________________________________________
/* Generics and Subtyping */
List<String> ls = new ArrayList<String>();
List<Object> lo = ls;
Line 1 is certainly legal.
Line 2 will cause a compile time error.
_______________________________________________________________________________
/* Wildcards */
Collection<Object> is not a supertype of all kinds of collections!
So what is the supertype of all kinds of collections? It's written
Collection<?> (pronounced "collection of unknown")
void printCollection(Collection<?> c) {
for(Object e: c){
System.out.println(c);
}
}
Note:
Collection<?> c = new ArrayList<String>();
c.add(new Object()); // Compile time error
/* Bounded Wildcards */
public abstract class Shape {
public abstract void draw(Canvas c);
}
public class Circle extends Shape {
private int x, y, radius;
public void draw(Canvas c) {
...
}
}
public class Rectangle extends Shape {
private int x, y, width, height;
public void draw(Canvas c) {
...
}
}
These classes can be drawn on a canvas:
public class Canvas {
public void draw(Shape s) {
s.draw(this);
}
}
// Allowed
public void drawAll(List<? extends Shape> shapes) {
for (Shape s: shapes) {
s.draw(this);
}
}
// Not allowed
public void addRectangle(List<? extends Shape> shapes) {
// Compile-time error!
shapes.add(0, new Rectangle());
}
// Allowed
public class Census {
public static void addRegistry(Map<String, ? extends Person> registry) {
}
Map<String, Driver> allDrivers = ... ;
Census.addRegistry(allDrivers);
_______________________________________________________________________________
/* Generic Methods */
Consider writing a method that takes an array of objects and a collection and
puts all objects in the array into the collection.
// Not allowed
static void fromArrayToCollection(Object[] a, Collection<?> c) {
for (Object o : a) {
c.add(o); // compile-time error
}
}
// Correct way
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o); // Correct
}
}
We can call this method with any kind of collection whose element type is a
supertype of the element type of the array.
Object[] oa = new Object[100];
Collection<Object> co = new ArrayList<Object>();
// T inferred to be Object
fromArrayToCollection(oa, co);
String[] sa = new String[100];
Collection<String> cs = new ArrayList<String>();
// T inferred to be String
fromArrayToCollection(sa, cs);
_______________________________________________________________________________
/* Generic methods vs Wildcard types */
interface Collection<E> {
public boolean containsAll(Collection<?> c);
public boolean addAll(Collection<? extends E> c);
}
interface Collection<E> {
public <T> boolean containsAll(Collection<T> c);
public <T extends E> boolean addAll(Collection<T> c);
// Hey, type variables can have bounds too!
}
Important:
Generic methods allow type parameters to be used to express dependencies among
the types of one or more arguments to a method and/or its return type. If
there isn't such a dependency, a generic method should not be used.
// It is possible to use both generic methods and wildcards in tandem. Here is
the method Collections.copy():
class Collections {
public static <T> void copy(List<T> dest, List<? extends T> src) {
...
}
// Without wildcards
class Collections {
public static <T, S extends T> void copy(List<T> dest, List<S> src) {
...
}
Wildcards also have the advantage that they can be used outside of method
signatures, as the types of fields, local variables and arrays.
static List<List<? extends Shape>>
history = new ArrayList<List<? extends Shape>>();
public void drawAll(List<? extends Shape> shapes) {
history.addLast(shapes);
for (Shape s: shapes) {
s.draw(this);
}
}
_______________________________________________________________________________
/* Using Lagacy code in Generic code */
package com.Example.widgets;
public interface Part {...}
public class Inventory {
/**
* Adds a new Assembly to the inventory database.
* The assembly is given the name name, and
* consists of a set parts specified by parts.
* All elements of the collection parts
* must support the Part interface.
**/
public static void addAssembly(String name, Collection parts) {...}
public static Assembly getAssembly(String name) {...}
}
public interface Assembly {
// Returns a collection of Parts
Collection getParts();
}
package com.mycompany.inventory;
import com.Example.widgets.*;
public class Blade implements Part {
...
}
public class Guillotine implements Part {
}
public class Main {
public static void main(String[] args) {
Collection<Part> c = new ArrayList<Part>();
c.add(new Guillotine()) ;
c.add(new Blade());
Inventory.addAssembly("thingee", c);
Collection<Part> k = Inventory.getAssembly("thingee").getParts();
}
}
When we call addAssembly, it expects the second parameter to be of type
Collection. The actual argument is of type Collection<Part>. This works, and
the assignment is legal, but it generates an unchecked warning. The warning is
needed, because the fact is that the compiler can't guarantee its correctness.
/* Erasure and Translation */
public String loophole(Integer x) {
List<String> ys = new LinkedList<String>();
List xs = ys;
xs.add(x); // Compile-time unchecked warning
return ys.iterator().next();
}
This is clearly wrong. If we ignore the warning and try to execute this code,
it will fail exactly at the point where we try to use the wrong type. At run
time, this code behaves like:
public String loophole(Integer x) {
List ys = new LinkedList;
List xs = ys;
xs.add(x);
return(String) ys.iterator().next(); // run time error
}
When we extract an element from the list, and attempt to treat it as a string
by casting it to String, we will get a ClassCastException. The exact same thing
happens with the generic version of loophole().
The reason for this is, that generics are implemented by the Java compiler as a
front-end conversion called erasure. You can (almost) think of it as a
source-to-source translation, whereby the generic version of loophole() is
converted to the non-generic version.
As a result, the type safety and integrity of the Java virtual machine are
never at risk, even in the presence of unchecked warnings.
Basically, erasure gets rid of (or erases) all generic type information. All
the type information betweeen angle brackets is thrown out, so, for example,
a parameterized type like List<String> is converted into List. All remaining
uses of type variables are replaced by the upper bound of the type variable
(usually Object). And, whenever the resulting code isn't type-correct, a cast
to the appropriate type is inserted, as in the last line of loophole.
/* Using Generic Code in Legacy Code */
Now let's consider the inverse case. Imagine that Example.com chose to convert
their API to use generics, but that some of their clients haven't yet. So now
the code looks like:
package com.Example.widgets;
public interface Part {
...
}
public class Inventory {
/**
* Adds a new Assembly to the inventory database.
* The assembly is given the name name, and
* consists of a set parts specified by parts.
* All elements of the collection parts
* must support the Part interface.
**/
public static void addAssembly(String name, Collection<Part> parts) {...}
public static Assembly getAssembly(String name) {...}
}
public interface Assembly {
// Returns a collection of Parts
Collection<Part> getParts();
}
and the client code looks like:
package com.mycompany.inventory;
import com.Example.widgets.*;
public class Blade implements Part {
...
}
public class Guillotine implements Part {
}
public class Main {
public static void main(String[] args) {
Collection c = new ArrayList();
c.add(new Guillotine()) ;
c.add(new Blade());
// 1: unchecked warning
Inventory.addAssembly("thingee", c);
Collection k = Inventory.getAssembly("thingee").getParts();
}
}
_______________________________________________________________________________
/* The Fine Print */
* A Generic Class is Shared by All Its Invocations *
What does the following code fragment print?
List <String> l1 = new ArrayList<String>();
List<Integer> l2 = new ArrayList<Integer>();
System.out.println(l1.getClass() == l2.getClass());
You might be tempted to say false, but you'd be wrong. It prints true, because
all instances of a generic class have the same run-time class, regardless of
their actual type parameters.
Indeed, what makes a class generic is the fact that it has the same behavior
for all of its possible type parameters; the same class can be viewed as having
many different types.
As consequence, the static variables and methods of a class are also shared
among all the instances. That is why it is illegal to refer to the type
parameters of a type declaration in a static method or initializer, or in the
declaration or initializer of a static variable.
* Casts and InstanceOf *
Another implication of the fact that a generic class is shared among all its
nstances, is that it usually makes no sense to ask an instance if it is an
instance of a particular invocation of a generic type:
Collection cs = new ArrayList<String>();
// Illegal.
if (cs instanceof Collection<String>) { ... }
similarly, a cast such as
// Unchecked warning,
Collection<String> cstr = (Collection<String>) cs;
gives an unchecked warning, since this isn't something the runtime system is
going to check for you.
The same is true of type variables
// Unchecked warning.
<T> T badCast(T t, Object o) {
return (T) o;
}
Type variables don't exist at run time. This means that they entail no
performance overhead in either time nor space, which is nice. Unfortunately,
it also means that you can't reliably use them in casts.
* Arrays *
// Error.
List<String>[] lsa = new List<?>[10];
<T> T[] makeArray(T t) {
return new T[100]; // Error.
}
_______________________________________________________________________________
/* Wildcards with lower bound */
interface Sink<T> {
flush(T t);
}
We can imagine using it as demonstrated by the code below. The method
writeAll() is designed to flush all elements of the collection coll to the sink
snk, and return the last element flushed.
public static <T> T writeAll(Collection<T> coll, Sink<T> snk) {
T last;
for (T t : coll) {
last = t;
snk.flush(last);
}
return last;
}
...
Sink<Object> s;
Collection<String> cs;
String str = writeAll(cs, s); // Illegal call.
As written, the call to writeAll() is illegal, as no valid type argument can be
inferred; neither String nor Object are appropriate types for T, because the
Collection element and the Sink element must be of the same type.
We can fix this error by modifying the signature of writeAll() as shown below,
using a wildcard.
public static <T> T writeAll(Collection<? extends T>, Sink<T>) {...}
...
// Call is OK, but wrong return type.
String str = writeAll(cs, s);
The call is now legal, but the assignment is erroneous, since the return type
inferred is Object because T matches the element type of s, which is Object.
The solution is to use a form of bounded wildcard we haven't seen yet:
wildcards with a lower bound. The syntax ? super T denotes an unknown type that
is a supertype of T (or T itself; remember that the supertype relation is
reflexive). It is the dual of the bounded wildcards we've been using, where we
use ? extends T to denote an unknown type that is a subtype of T.
public static <T> T writeAll(Collection<T> coll, Sink<? super T> snk) {
...
}
String str = writeAll(cs, s); // Yes!
Using this syntax, the call is legal, and the inferred type is String, as
desired.
* Wildcard Capture *
It should be pretty clear by now that given:
Set<?> unknownSet = new HashSet<String>();
...
/* Add an element t to a Set s. */
public static <T> void addToSet(Set<T> s, T t) {
...
}
The call below is illegal.
addToSet(unknownSet, "abc"); // Illegal.
It makes no difference that the actual set being passed is a set of strings;
what matters is that the expression being passed as an argument is a set of an
unknown type, which cannot be guaranteed to be a set of strings, or of any type
in particular.
Now, consider the following code:
class Collections {
...
<T> public static Set<T> unmodifiableSet(Set<T> set) {
...
}
}
...
Set<?> s = Collections.unmodifiableSet(unknownSet); // This works! Why?
It seems this should not be allowed; yet, looking at this specific call, it is
perfectly safe to permit it. After all, unmodifiableSet() does work for any
kind of Set, regardless of its element type.
Because this situation arises relatively frequently, there is a special rule
that allows such code under very specific circumstances in which the code can
be proven to be safe. This rule, known as wildcard capture, allows the compiler
to infer the unknown type of a wildcard as a type argument to a generic method.
|
import { M_clinicas } from "../model/clinicas.js";
import { M_pacientes } from "../model/pacientes.js";
import { M_medicos } from "../model/medicos.js";
// VER TODOS
//const getObrasSociales
const mostrarTodo = async (req,res) => {
try {
const items = await M_clinicas.findAll();
console.log(items);
res.json(items);
} catch (error){
res.status(500).json({message: error.message})
};
};
// CREAR
const crearItem = async (req, res) => {
// VAMOS A USAR UNA RUTA CON POST, ENTONCES TOMAMOS LOS DATOS DESDE EL BODY DEL REQ Y LOS CARGAMOS EN CONSTANTES
const {
diagnostico, acciones, idPaciente, idMedico
} = req.body;
/// control de envio de datos
if(!idMedico) {
return res.status(400).json({error: 'No se ingreso un medico'});
}
if(!idPaciente) {
return res.status(400).json({error: 'No se ingreso un paciente'});
}
if(!diagnostico) {
return res.status(400).json({error: 'No se ingreso un diagnostico'});
}
/// CONTROL RELACION DE QUE EL MEDICO Y PACIENTE EXISTAN
const medico = await M_medicos.findByPk(idMedico);
if(!medico) {
return res.status(400).json({error: 'El medico no se encuentra cargado en el sistema'})
};
const paciente = await M_pacientes.findByPk(idPaciente);
if(!paciente) {
return res.status(400).json({error: 'El paciente no se encuentra cargado en el sistema'})
};
// CREAMOS EL ITEM USANDO LAS CONSTANTES (TIENEN LOS MISMOS NOMBRES QUE LOS CAMPOS DE LA TABLA)
const nuevoItem = await M_clinicas.create( {
diagnostico, acciones, idPaciente, idMedico
} );
console.log(nuevoItem);
// DAMOS UNA RESPUESTA SÓLO PARA CERRAR LA FUNCIÓN
res.send('Entrada creada con éxito');
}
// VER UNO
const mostrarUno = async (req,res) => {
// SIEMPRE TRABAJAR CON TRY CATCH
try {
// RESPONDEMOS A UNA FUNCION GET CON UN PARAMETRO ID QUE IDENTIFICA EL ITEM A MODIFICAR
const { id } = req.params;
// CON SEQUALIZE USANDO ESA ID BUSCAMOS EL ITEM
const item = await M_clinicas.findByPk(id);
// DAMOS RES
res.json(item);
} catch (error) {
res.status(500).json({message: error.message})
}
}
// BORRAR
const borrarItem = async (req, res) => {
try {
// RESPONDEMOS A UNA RUTA DELETE CON UN PARAMETRO ID QUE IDENTIFICA EL ITEM A MODIFICAR
const { id } = req.params;
/// Agregar control de realacion de tablas
/* const choferesAsignados = await Choferes.findAll({
where: {
vehiculoId : id,
}
});
if (choferesAsignados.length > 0) {
return res.status(400).json({error: 'El vehiculo esta asignado a algun chofer'})
}
*/
// CON SEQUELIZE DESTROY BORRAMOS EL ITEM
await M_clinicas.destroy({
where: {
//id: id, id de la tabla y id de param, pero como los dos son iguales podemos poner asi cmo sigue
id,
},
}) ;
} catch (error) {
res.status(500).json({message: error.message});
}
// DAMOS RES
res.send("Item borrado");
}
// EDITAR
const actualizarItem = async (req, res) => {
try {
// ESTO ES UNA RUTA PUT CON UN PARAMETRO ID, buscamos la id para definir que item vamos a modificar
const { id } = req.params;
// Y DESDE EL BODY CARGAMOS LA INFO EN CONSTANTES CON EL MISMO NOMBRE QUE LOS CAMPOS DE LA TABLA
const { diagnostico, acciones, idPaciente, idMedico
} = req.body;
// BUSCAMOS EL ITEM, SI NO LO ENCUENTRA TIRAMOS UN RETURN QUE CIERRA LA FUNCION
const item = await M_clinicas.findByPk(id);
if(!item) {
return res.status(400).json({error: 'El item a modificar no fue encontrado'})
};
/// CONTROL RELACION DE QUE EL MEDICO Y PACIENTE EXISTAN
const medico = await M_medicos.findByPk(idMedico);
if(!medico) {
return res.status(400).json({error: 'El medico no se encuentra cargado en el sistema'})
};
const paciente = await M_pacientes.findByPk(idPaciente);
if(!paciente) {
return res.status(400).json({error: 'El paciente no se encuentra cargado en el sistema'})
};
// cargamos la info en el objeto
item.diagnostico = diagnostico;
item.acciones = acciones;
item.idPaciente = idPaciente;
item.idMedico = idMedico;
//ahora lo gabamos en la base de datoscon sequelize
await item.save();
res.json(item);
} catch (error) {
return res.status(500).json({messsage:error.message});
}
}
export { mostrarTodo, crearItem, mostrarUno, borrarItem, actualizarItem };
|
//
// index.js
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import _ from 'lodash';
import React from 'react';
import { View, Dimensions } from 'react-native';
import RenderHtml from 'react-native-render-html';
function render_html(contentWidth, source, props) {
if (_.isString(source?.content)) {
return <RenderHtml contentWidth={contentWidth} source={{ html: source.content }} {...props} />;
}
if (_.isString(source?.uri)) {
return <RenderHtml contentWidth={contentWidth} source={source} {...props} />;
}
}
export const HTML = React.forwardRef(({
source,
style,
...props
}, forwardRef) => {
const [contentWidth, setContentWidth] = React.useState(Dimensions.get('window').width);
return <View ref={forwardRef} style={style} onLayout={(e) => setContentWidth(e.nativeEvent.layout.width)}>
{render_html(contentWidth, source, props)}
</View>;
});
export default HTML;
|
import { Express, Request, Response, Router } from "express";
import Authorize from "../Middlewares/Authorize";
import {
SessionTaskModel,
SessionTaskQuesModel,
SessionTaskSubModel,
} from "../Models/ClassSessionTaskModels";
import { UserClaims } from "../Models/UserModel";
import ClassSessionTaskRepository from "../Repositories/ClassSessionTaskRepository";
const ClassSessionTaskController = async (app: Express): Promise<void> => {
const router = Router();
router.post(
"/getAllClassTask",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const class_pk: number = req.body.class_pk;
res.json(await ClassSessionTaskRepository.getAllClassTask(class_pk));
}
);
router.post(
"/getSingleClassTask",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const class_task_pk: number = req.body.class_task_pk;
res.json(
await ClassSessionTaskRepository.getSingleClassTask(class_task_pk)
);
}
);
router.post(
"/addClassTask",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const payload: SessionTaskModel = req.body;
payload.encoder_pk = parseInt(req.user_id);
res.json(await ClassSessionTaskRepository.addClassTask(payload));
}
);
router.post(
"/updateClassTask",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const payload: SessionTaskModel = req.body;
payload.encoder_pk = parseInt(req.user_id);
res.json(await ClassSessionTaskRepository.updateClassTask(payload));
}
);
router.post(
"/toggleSubmitClassTask",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const payload: SessionTaskModel = req.body;
payload.encoder_pk = parseInt(req.user_id);
res.json(await ClassSessionTaskRepository.toggleSubmitClassTask(payload));
}
);
router.post(
"/changeStatusClassTask",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const payload: SessionTaskModel = req.body;
payload.encoder_pk = parseInt(req.user_id);
res.json(await ClassSessionTaskRepository.changeStatusClassTask(payload));
}
);
//task answers
router.post(
"/getAllClassTaskQues",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const class_task_pk: number = req.body.class_task_pk;
res.json(
await ClassSessionTaskRepository.getAllClassTaskQues(class_task_pk)
);
}
);
router.post(
"/getSingleClassTaskQues",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const task_ques_pk: number = req.body.task_ques_pk;
res.json(
await ClassSessionTaskRepository.getSingleClassTaskQues(task_ques_pk)
);
}
);
router.post(
"/updateClassTaskQues",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const payload: SessionTaskQuesModel = req.body;
res.json(await ClassSessionTaskRepository.updateClassTaskQues(payload));
}
);
//task submissions
router.post(
"/getAllStudentsSubmit",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const class_task_pk: number = req.body.class_task_pk;
res.json(
await ClassSessionTaskRepository.getAllStudentsSubmit(class_task_pk)
);
}
);
router.post(
"/getAllClassTaskSub",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const class_task_pk: number = req.body.class_task_pk;
res.json(
await ClassSessionTaskRepository.getAllClassTaskSub(class_task_pk)
);
}
);
router.post(
"/addClassTaskSub",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const payload: Array<SessionTaskSubModel> = req.body;
res.json(
await ClassSessionTaskRepository.addClassTaskSub(
payload,
parseInt(req.user_id)
)
);
}
);
router.post(
"/updateTaskSub",
Authorize(),
async (req: Request & UserClaims, res: Response) => {
const payload: Array<SessionTaskSubModel> = req.body;
res.json(await ClassSessionTaskRepository.updateTaskSub(payload));
}
);
app.use("/api/task/", router);
};
export default ClassSessionTaskController;
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>LMPH - Employee Info</title>
<!-- Custom fonts for this template-->
<link href="/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link
href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet">
<!-- Custom styles for this template-->
<link href="/css/sb-admin-2.min.css" rel="stylesheet">
</head>
<body id="page-top">
<!-- Page Wrapper -->
<div id="wrapper">
<!-- Sidebar -->
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<!-- Sidebar - Brand -->
<a class="sidebar-brand d-flex align-items-center justify-content-center" href="/home">
<div class="sidebar-brand-icon rotate-n-15">
<i class="fas fa-laugh-wink"></i>
</div>
<div class="sidebar-brand-text mx-3">LMPH - BE</div>
</a>
<!-- Divider -->
<hr class="sidebar-divider my-0">
<!-- Nav Item - Dashboard -->
<li class="nav-item active">
<a class="nav-link" href="/home">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span></a>
</li>
<!-- Nav Item - Dashboard -->
<li class="nav-item">
<a class="nav-link" href="/employees">
<i class="fas fa-fw fa-users"></i>
<span>Employees</span></a>
</li>
</ul>
<!-- End of Sidebar -->
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<!-- Topbar -->
<nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
<!-- Sidebar Toggle (Topbar) -->
<button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
<i class="fa fa-bars"></i>
</button>
<!-- Topbar Navbar -->
<ul class="navbar-nav ml-auto">
<!-- Nav Item - User Information -->
<li class="nav-item dropdown no-arrow">
<a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<div class="mr-2 d-none d-lg-inline text-gray-600 small" th:text="${#authentication.principal.username}"></div>
<img class="img-profile rounded-circle"
src="/img/undraw_profile.svg">
</a>
<!-- Dropdown - User Information -->
<div class="dropdown-menu dropdown-menu-right shadow animated--grow-in"
aria-labelledby="userDropdown">
<a class="dropdown-item" href="/logout">
<i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
Logout
</a>
</div>
</li>
</ul>
</nav>
<!-- End of Topbar -->
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">Employee Info</h1>
</div>
<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<div sec:authorize="hasRole('ROLE_ADMIN')">
<button id="btnActionSubmit" class="btn btn-primary px-4">Save</button>
<button th:if="${form.id} != null" id="btnActionDelete" class="btn btn-danger px-4">Delete</button>
</div>
</div>
<div class="card-body">
<form id="form" method="post" action="/employees/post" th:object="${form}">
<input type="hidden" name="id" th:value="${form.id}" />
<div class="row">
<div class="col-6">
<div class="mb-3">
<label for="firstName" class="form-label">First Name</label>
<input type="text" class="form-control" id="firstName" name="firstName" th:value="${form.firstName}" placeholder="First name">
<div class="mt-2 text-danger" th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">First name Error</div>
</div>
<div class="mb-3">
<label for="lastName" class="form-label">Last Name</label>
<input type="text" class="form-control" id="lastName" name="lastName" th:value="${form.lastName}" placeholder="Last name">
<div class="mt-2 text-danger" th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}">First name Error</div>
</div>
<div class="mb-3">
<label for="middleName" class="form-label">Middle Name</label>
<input type="text" class="form-control" id="middleName" name="middleName" th:value="${form.middleName}" placeholder="Middle name">
<div class="mt-2 text-danger" th:if="${#fields.hasErrors('middleName')}" th:errors="*{middleName}">First name Error</div>
</div>
<div class="mb-3">
<label for="birthdate" class="form-label">Birth Date</label>
<input type="date" class="form-control" id="birthdate" name="birthdate" th:value="${form.birthdate}" placeholder="YYYY/MM/DD">
<div class="mt-2 text-danger" th:if="${#fields.hasErrors('birthdate')}">Invalid birthdate value.</div>
</div>
<div class="mb-3">
<label for="gender" class="form-label">Gender</label>
<select class="form-control" id="gender" name="gender">
<option value="">Select</option>
<option th:each="enum : ${form.genders.values()}"
th:value="${enum}" th:text="${enum.label}"
th:selected="${form.gender==enum.toString()}"></option>
</select>
<div class="mt-2 text-danger" th:if="${#fields.hasErrors('gender')}" th:errors="*{gender}">Error</div>
</div>
<div class="mb-3">
<label for="maritalStatus" class="form-label">Marital Status</label>
<select class="form-control" id="maritalStatus" name="maritalStatus">
<option value="">Select</option>
<option th:each="enum : ${form.maritalStatuses.values()}"
th:value="${enum}" th:text="${enum.label}"
th:selected="${form.maritalStatus==enum.toString()}"></option>
</select>
<div class="mt-2 text-danger" th:if="${#fields.hasErrors('maritalStatus')}" th:errors="*{maritalStatus}">Error</div>
</div>
<div class="mb-3">
<label for="companyPosition" class="form-label">Position</label>
<input type="text" class="form-control" id="companyPosition" name="companyPosition" th:value="${form.companyPosition}" placeholder="Manager">
<div class="mt-2 text-danger" th:if="${#fields.hasErrors('companyPosition')}" th:errors="*{companyPosition}">Error</div>
</div>
<div class="mb-3">
<label for="dateHired" class="form-label">Date Hired</label>
<input type="date" class="form-control" id="dateHired" name="dateHired" th:value="${form.dateHired}" placeholder="YYYY/MM/DD">
<div class="mt-2 text-danger" th:if="${#fields.hasErrors('dateHired')}">Invalid date value.</div>
</div>
</div>
<div class="col-6">
<div>
<span class="mr-4">Contact Info</span> <button sec:authorize="hasRole('ROLE_ADMIN')" id="btnAddContact" type="button" class="close float-none">+</button>
</div>
<div id="contactList">
<div class="row contact-info-block mt-2">
<input type="hidden" class="fieldContactId" name="contacts[0].id" >
<div class="col">
<input type="text" class="form-control fieldContactNo" name="contacts[0].contactNo" placeholder="09170000000">
</div>
<div class="col-auto pt-2">
<div class="form-check inline-block mr-3">
<input class="form-check-input checkIsPrimaryContact fieldIsPrimary" type="checkbox" name="contacts[0].isPrimary" value="1" checked >
</div>
<button type="button" class="close btnDeleteContact" style="margin-top:-2px">x</button>
</div>
</div>
</div>
<div class="mt-4">
<span class="mr-4">Address Info</span> <button sec:authorize="hasRole('ROLE_ADMIN')" id="btnAddAddress" type="button" class="close float-none">+</button>
</div>
<div id="addressList">
<div class="row address-info-block mt-2">
<input type="hidden" class="fieldAddressId" name="addresses[0].id" >
<div class="col">
<input type="text" class="form-control fieldAddress1" name="addresses[0].address1" placeholder="Address Line 1">
</div>
<div class="col">
<input type="text" class="form-control fieldAddress2" name="addresses[0].address2" placeholder="Address Line 2">
</div>
<div class="col-auto pt-2">
<div class="form-check inline-block mr-3">
<input class="form-check-input checkIsPrimaryAddress fieldIsPrimary" type="checkbox" name="addresses[0].isPrimary" value="1" checked >
</div>
<button type="button" class="close btnDeleteAddress" style="margin-top:-2px">x</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<!-- Footer -->
<footer class="sticky-footer bg-white">
<div class="container my-auto">
<div class="copyright text-center my-auto">
<span>Copyright © legalmatch.ph</span>
</div>
</div>
</footer>
<!-- End of Footer -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<div id="templateContact" style="display:none">
<div class="row contact-info-block mt-2">
<div class="col">
<input type="hidden" class="fieldContactId" />
<input type="text" class="form-control fieldContactNo" placeholder="09170000000">
</div>
<div class="col-auto pt-2">
<div class="form-check inline-block mr-3">
<input class="form-check-input checkIsPrimaryContact fieldIsPrimary" type="checkbox" value="1">
</div>
<button type="button" class="close btnDeleteContact" style="margin-top:-2px">x</button>
</div>
</div>
</div>
<div id="templateAddress" style="display:none">
<div class="row address-info-block mt-2">
<div class="col">
<input type="hidden" class="fieldAddressId" />
<input type="text" class="form-control fieldAddress1" placeholder="Address Line 1">
</div>
<div class="col">
<input type="text" class="form-control fieldAddress2" placeholder="Address Line 2">
</div>
<div class="col-auto pt-2">
<div class="form-check inline-block mr-3">
<input class="form-check-input checkIsPrimaryAddress fieldIsPrimary" type="checkbox" value="1">
</div>
<button type="button" class="close btnDeleteAddress" style="margin-top:-2px">x</button>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="/js/sb-admin-2.min.js"></script>
<script src="/js/appService.js"></script>
<script>
const EMPLOYEE_ID = "[[${form.id}]]";
const app = () => {
const ROLE_ADMIN = "admin";
const ROLE_USER = "user";
const roles = [[${#authentication.principal.authorities}]];
const isAdmin = () => roles.find( r => r == ROLE_ADMIN)
const loadInit = () => {
$('#btnActionSubmit').click( async () => {
const form = document.querySelector('#form');
const result = await appService().upsert(form);
document.location.href="/employees";
});
$('#btnActionDelete').click( () => {
confirmDeleteEmployee();
});
$('#btnAddContact').click( addContact );
$('#btnAddAddress').click( addAddress );
$('.btnDeleteContact')
$('#contactList').on('click', '.btnDeleteContact', deleteContact);
$('#contactList').on('change', '.checkIsPrimaryContact', setPrimaryContact);
$('#addressList').on('click', '.btnDeleteAddress', deleteAddress);
$('#addressList').on('change', '.checkIsPrimaryAddress', setPrimaryAddress);
EMPLOYEE_ID.length > 0 && fetch(EMPLOYEE_ID);
}
const addContact = () => {
const element = document.querySelector('#templateContact').querySelector('.contact-info-block').cloneNode(true);
$('#contactList').append(element);
populateContactFieldArrayNames();
}
const setPrimaryContact = (e) => {
$('.checkIsPrimaryContact').prop('checked', false);
e.target.checked = true;
}
const deleteContact = (e) => {
e.target.closest('.contact-info-block').remove();
populateContactFieldArrayNames();
}
const addAddress = () => {
const element = document.querySelector('#templateAddress').querySelector('.address-info-block').cloneNode(true);
$('#addressList').append(element);
populateAddressFieldArrayNames();
}
const setPrimaryAddress = (e) => {
$('.checkIsPrimaryAddress').prop('checked', false);
e.target.checked = true;
}
const deleteAddress = (e) => {
e.target.closest('.address-info-block').remove();
populateAddressFieldArrayNames();
}
const confirmDeleteEmployee = async () => {
const result = await appService().delete(EMPLOYEE_ID);
document.location.href = "/employees";
}
const fetch = id => {
$.post({
url: '/graphql',
data: JSON.stringify({ "query": `{
employeeById( id : ${id}) {
id
firstName
lastName
middleName
birthdate
gender
maritalStatus
companyPosition
dateHired
contacts {
id
contactNo
isPrimary
}
addresses {
id
address1
address2
isPrimary
}
}
}` }),
contentType: 'application/json'
}).done(function(res) {
res.data && res.data.employeeById && populateForm(res.data.employeeById);
});
}
const populateForm = employee => {
//console.log(employee);
const form = $('#form');
const formElement = form.get(0);
formElement.firstName.value = employee.firstName;
formElement.lastName.value = employee.lastName;
formElement.middleName.value = employee.middleName;
formElement.gender.value = employee.gender;
formElement.maritalStatus.value = employee.maritalStatus;
formElement.companyPosition.value = employee.companyPosition;
formElement.birthdate.value = employee.birthdate;
formElement.dateHired.value = employee.dateHired;
employee.contacts && employee.contacts.length > 0 && populateContactList(employee.contacts);
employee.addresses && employee.addresses.length > 0 && populateAddressList(employee.addresses);
!isAdmin() && disableEditableAction();
}
const populateContactList = (contacts) => {
const list = document.querySelector('#contactList');
list.innerHTML = "";
contacts.forEach( contact => {
const block = document.querySelector('#templateContact').querySelector('.contact-info-block').cloneNode(true);
block.querySelector(".fieldContactId").value = contact.id;
block.querySelector(".fieldContactNo").value = contact.contactNo;
block.querySelector(".fieldIsPrimary").checked = contact.isPrimary;
list.append(block);
});
populateContactFieldArrayNames();
}
const populateContactFieldArrayNames = () => {
const list = document.querySelector('#contactList').querySelectorAll('.contact-info-block');
list.forEach( (block, i) => {
block.querySelector(".fieldContactId").setAttribute("name", `contacts[${i}].id`);
block.querySelector(".fieldContactNo").setAttribute("name", `contacts[${i}].contactNo`);
block.querySelector(".fieldIsPrimary").setAttribute("name", `contacts[${i}].isPrimary`);
});
}
const populateAddressList = (addresses) => {
const list = document.querySelector('#addressList');
list.innerHTML = "";
addresses.forEach( address => {
const block = document.querySelector('#templateAddress').querySelector('.address-info-block').cloneNode(true);
block.querySelector(".fieldAddressId").value = address.id;
block.querySelector(".fieldAddress1").value = address.address1;
block.querySelector(".fieldAddress2").value = address.address2;
block.querySelector(".fieldIsPrimary").checked = address.isPrimary;
list.append(block);
});
populateAddressFieldArrayNames();
}
const populateAddressFieldArrayNames = () => {
const list = document.querySelector('#addressList').querySelectorAll('.address-info-block');
list.forEach( (block, i) => {
block.querySelector(".fieldAddressId").setAttribute("name", `addresses[${i}].id`);
block.querySelector(".fieldAddress1").setAttribute("name", `addresses[${i}].address1`);
block.querySelector(".fieldAddress2").setAttribute("name", `addresses[${i}].address2`);
block.querySelector(".fieldIsPrimary").setAttribute("name", `addresses[${i}].isPrimary`);
});
}
const disableEditableAction = () => {
document.querySelector('#form')
.querySelectorAll('input, checkbox, select')
.forEach( el => el.setAttribute('disabled', true) );
document.querySelectorAll('.btnDeleteContact, .btnDeleteAddress').forEach( el => el.remove());
}
return {
init : loadInit
}
}
window.addEventListener("load", app().init);
</script>
</body>
</html>
|
from django.test import TestCase, Client
from django.contrib.auth.models import User
from .models import MealChoice
from .forms import CustomUserCreationForm
from django.urls import reverse
class MealChoiceModelTest(TestCase):
def setUp(self):
self.user = User.objects.create_user(username='testuser', password='testpass')
def test_meal_choice_creation(self):
meal_choice = MealChoice.objects.create(
user=self.user,
want_obiad=True,
want_sniadanie=True,
want_kolacja=False,
date='2023-09-01',
last_choice_date='2023-09-01',
num_want_sniadanie=1,
num_want_obiad=1,
num_want_kolacja=0
)
self.assertEqual(meal_choice.user.username, 'testuser')
self.assertEqual(meal_choice.want_obiad, True)
self.assertEqual(meal_choice.want_sniadanie, True)
self.assertEqual(meal_choice.want_kolacja, False)
self.assertEqual(meal_choice.date, '2023-09-01')
self.assertEqual(meal_choice.last_choice_date, '2023-09-01')
self.assertEqual(meal_choice.num_want_sniadanie, 1)
self.assertEqual(meal_choice.num_want_obiad, 1)
self.assertEqual(meal_choice.num_want_kolacja, 0)
def test_meal_choice_str(self):
meal_choice = MealChoice.objects.create(user=self.user, date='2023-09-01')
self.assertEqual(str(meal_choice), 'testuser - 2023-09-01')
class CustomUserCreationFormTest(TestCase):
def test_custom_user_creation_form_valid(self):
form_data = {
'username': 'testuser',
'password1': 'testpass123',
'password2': 'testpass123',
'first_name': 'John',
'surname': 'Doe',
}
form = CustomUserCreationForm(data=form_data)
self.assertTrue(form.is_valid())
def test_custom_user_creation_form_invalid(self):
form_data = {
'username': 'testuser',
'password1': 'testpass123',
'password2': 'testpass',
'first_name': 'John',
'surname': 'Doe',
}
form = CustomUserCreationForm(data=form_data)
self.assertFalse(form.is_valid())
class MealChoiceViewTest(TestCase):
def setUp(self):
self.user = User.objects.create_user(username='testuser', password='testpass')
self.client = Client()
self.client.login(username='testuser', password='testpass')
def test_meal_choice_view_get(self):
response = self.client.get('/obiad_choice/') # Użyj pełnej ścieżki do widoku
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'obiad/obiad_choice.html')
class YourAppViewTests(TestCase):
def setUp(self):
# Utwórz użytkownika do testów
self.user = User.objects.create_user(username='testuser', password='testpass')
def test_register_view(self):
response = self.client.get(reverse('obiad:register'))
self.assertEqual(response.status_code, 200)
def test_user_login_view(self):
response = self.client.get(reverse('obiad:user_login'))
self.assertEqual(response.status_code, 200)
def test_index_view(self):
response = self.client.get(reverse('obiad:index'))
self.assertEqual(response.status_code, 200)
def test_meal_choice_view(self):
# Zaloguj użytkownika
self.client.login(username='testuser', password='testpass')
response = self.client.get(reverse('obiad:obiad_choice'))
self.assertEqual(response.status_code, 200)
def test_kucharz_dashboard_view(self):
# Zaloguj użytkownika
self.client.login(username='testuser', password='testpass')
response = self.client.get(reverse('obiad:kucharz_dashboard'))
self.assertEqual(response.status_code, 302)
|
package es.in2.desmos.domain.services.broker.adapter.factory;
import es.in2.desmos.domain.services.broker.adapter.BrokerAdapterService;
import es.in2.desmos.domain.services.broker.adapter.impl.OrionLdAdapter;
import es.in2.desmos.domain.services.broker.adapter.impl.ScorpioAdapter;
import es.in2.desmos.infrastructure.configs.properties.BrokerProperties;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class BrokerAdapterFactoryTests {
@Mock
private BrokerProperties brokerPathProperties;
@Mock
private ScorpioAdapter scorpioAdapter;
@Mock
private OrionLdAdapter orionLdAdapter;
@InjectMocks
private BrokerAdapterFactory brokerAdapterFactory;
@Test
void whenProviderIsScorpio_thenScorpioAdapterIsReturned() {
// Arrange
when(brokerPathProperties.provider()).thenReturn("scorpio");
// Act
BrokerAdapterService brokerAdapterService = brokerAdapterFactory.getBrokerAdapter();
// Assert
assertEquals(scorpioAdapter, brokerAdapterService);
}
@Test
void whenProviderIsOrionLd_thenOrionLdAdapterIsReturned() {
// Arrange
when(brokerPathProperties.provider()).thenReturn("orion-ld");
// Act
BrokerAdapterService brokerAdapterService = brokerAdapterFactory.getBrokerAdapter();
// Assert
assertEquals(orionLdAdapter, brokerAdapterService);
}
@Test
void whenProviderIsInvalid_thenExceptionIsThrown() {
// Arrange
when(brokerPathProperties.provider()).thenReturn("invalid");
// Act & Assert
assertThrows(IllegalArgumentException.class, () -> brokerAdapterFactory.getBrokerAdapter());
}
}
|
import "./form.scss";
import React from 'react';
import axios from 'axios';
import { connect } from "react-redux";
import "./form.scss";
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
title: '',
body: '',
author: '',
}
this.handleChangeField = this.handleChangeField.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentWillReceiveProps(nextProps) {
if(nextProps.articleToEdit) {
this.setState({
title: nextProps.articleToEdit.title,
body: nextProps.articleToEdit.body,
author: nextProps.articleToEdit.author,
});
}
}
handleSubmit(){
const { onSubmit, articleToEdit, onEdit } = this.props;
const { title, body, author } = this.state;
if(!articleToEdit) {
return axios.post('https://diplomamintenko.herokuapp.com/articles', {
title,
body,
author,
})
.then((res) => onSubmit(res.data))
.then(() => this.setState({ title: '', body: '', author: '' }));
} else {
return axios.patch(`https://diplomamintenko.herokuapp.com/articles/${articleToEdit._id}`, {
title,
body,
author,
})
.then((res) => onEdit(res.data))
.then(() => this.setState({ title: '', body: '', author: '' }));
}
}
handleChangeField(key, event) {
this.setState({
[key]: event.target.value,
});
}
render() {
const { articleToEdit } = this.props;
const { title, body, author } = this.state;
return (
<div className="flex">
<div>
<input
onChange={(ev) => this.handleChangeField('title', ev)}
value={title}
className="author"
placeholder="Title"
/><br />
<textarea
onChange={(ev) => this.handleChangeField('body', ev)}
className="description"
placeholder="Description"
value={body}>
</textarea><br />
<input
onChange={(ev) => this.handleChangeField('author', ev)}
value={author}
className="author"
placeholder=" Author"
/><br />
<button onClick={this.handleSubmit} className="but">{articleToEdit ? 'Update' : 'Submit'}</button>
</div>
</div>
)
}
}
const mapDispatchToProps = dispatch => ({
onSubmit: data => dispatch({ type: 'SUBMIT_ARTICLE', data }),
onEdit: data => dispatch({ type: 'EDIT_ARTICLE', data }),
});
const mapStateToProps = state => ({
articleToEdit: state.campaigns.articleToEdit,
});
export default connect(mapStateToProps, mapDispatchToProps)(Form);
|
<section class="section">
<h2 class="title is-2">Apartment Listing</h2>
</section>
<div class="block">
<%= form_tag apartments_path, method: :get, id: 'filter_form' do %>
<div class="field is-grouped">
<div class="control" id="select_sort">
<div class="select">
<select name="sort" id="sort_select_box" onchange="clickFilterButton()">
<option <%= 'selected="selected"' if @sort == "" %> style="color: gray" value=""></option>
<option <%= 'selected="selected"' if @sort == "rating_desc" %> value="rating_desc">Rating ▼</option>
<option <%= 'selected="selected"' if @sort == "rating_asc" %> value="rating_asc">Rating ▲</option>
<option <%= 'selected="selected"' if @sort == "price_desc" %> value="price_desc">Price ▼</option>
<option <%= 'selected="selected"' if @sort == "price_asc" %> value="price_asc">Price ▲</option>
</select>
</div>
<label class="label">Sort By</label>
</div>
<div class="control" id="select_price">
<div class="select">
<select name="price" id="price_select_box" onchange="clickFilterButton()">
<option <%= 'selected="selected"' if @price == "" %> style="color: gray" value="">All</option>
<option <%= 'selected="selected"' if @price == "0-999" %> value="0-999">0~999</option>
<option <%= 'selected="selected"' if @price == "1000-1499" %> value="1000-1499">1000~1499</option>
<option <%= 'selected="selected"' if @price == "1500-1999" %> value="1500-1999">1500~1999</option>
<option <%= 'selected="selected"' if @price == "2000" %> value="2000">2000+</option>
</select>
</div>
<label class="label">Price Range</label>
</div>
<div class="control is-expanded" id="search-bar">
<label hidden>Search</label>
<input class="input" type="text" placeholder="Search..." id="search_input"
name="search" value="<%= @search unless @search.nil? || @search.empty? %>">
</div>
<div class="control">
<%= submit_tag 'Filter', id: 'filter_submit', class: 'button is-primary' %>
</div>
<div class="control">
<%= submit_tag 'Clear Filters', id: 'clear_filter_submit', class: 'button is-warning' %>
</div>
</div>
<% end %>
</div>
<script>
function clickFilterButton() {
document.getElementById('filter_submit').click();
}
</script>
<div class="block">
<%= render "layouts/flash" %>
</div>
<div class="block">
<div class="columns is-multiline">
<% @apartments.each do |apartment| %>
<div class="column is-one-third">
<div class="card">
<header class="card-header">
<p class="card-header-title" style="font-weight: normal">
Rating: <strong style="color: cornflowerblue; font-size: 1.3em"><%= apartment.rating.round %></strong>
</p>
</header>
<div class="card-content">
<div class="card-content">
<p class="title is-4"><%= apartment.name %></p>
<p class="subtitle">$<strong><%= apartment.price %></strong> <span class="small_text">per month</span></p>
<p class="content"><%= apartment.address %></p>
<p class="content"><%= text_abstract apartment.description %></p>
<p>
<img src="data:image/jpeg;base64,<%= apartment.image %>" style="display:block;margin-left:auto;margin-right:auto;" width="200px" height="150px"/>
</p>
</div>
</div>
<div class="card-footer">
<%= link_to "Details", apartment_path(apartment), class: "card-footer-item" %>
</div>
</div>
</div>
<% end %>
</div>
</div>
<div class="block">
<%= link_to 'Add new apartment', new_apartment_path, :class => 'button is-primary' %>
</div>
<script>
function imageShow() {
var images = document.getElementsByTagName('img')
for (let i = 0; i < images.length; i++) {
images[i].onerror = function () {
this.src = "/default.jpeg";
}
if (images[i].src === "data:image/jpeg;base64,") {
images[i].src = "/default.jpeg";
}
}
}
imageShow();
</script>
|
/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: MPL-2.0
*/
import isAbsoluteUrl from 'lib/is-absolute-url'
import { rewriteWaypointPluginsToIntegrations } from 'lib/content-adjustments'
import { productSlugs, productSlugsToHostNames } from 'lib/products'
import { ProductData } from 'types/products'
import { SectionOption } from 'lib/learn-client/types'
/**
* Given some product data,
* Return a (url) => adjustedUrl function,
* intended for use in fixing up links in docs content.
*
* Note that these URL adjustments are expected to be necessary for
* every product during initial migration to HashiCorp Developer.
*
* If we want to remove the need for these URL adjustments, then
* at some point in the future, we could apply these as remark transforms
* using "remarkPluginAdjustLinkUrls" to the original source content
* (across ALL versions!), and ask authors to use the adjusted URL format
* going forward. Asana task:
* https://app.asana.com/0/1202097197789424/1202569127502507/f
*/
export function getProductUrlAdjuster(
productData: ProductData
): (url: string) => string {
/**
* Sentinel is a bit of a special case,
* since it did not have a dedicated dot-io domain
*/
if (productData.slug === 'sentinel') {
return (url: string) => rewriteSentinelDocsUrls(url, productData)
}
/**
* Vault and Consul (and possibly others?)
* have authored "/api" links which used to be redirected to "/api-docs",
* but which we're now preferring to handle by rewriting here.
*/
if (productData.slug === 'consul' || productData.slug === 'vault') {
return (url: string) => {
const withApiDocsFix = rewriteApiToApiDocs(url)
const withProductPrefix = rewriteDocsUrl(withApiDocsFix, productData)
return withProductPrefix
}
}
/**
* All other products need their docs routes prefixed, as within docs
* content, authors write links as if URLs are on the dot-io sites.
* For example, in Waypoint content, authors write URLs like
* "/docs/some-waypoint-page", which need to be adjusted to be
* "/waypoint/docs/some-waypoint-page".
*/
return (url: string) => {
// Do the base docs adjustment
let adjustedUrl = rewriteDocsUrl(url, productData)
// We also have some product-specific, post-adjustment rewrites to apply
adjustedUrl = rewriteWaypointPluginsToIntegrations(adjustedUrl)
// Return the final URL
return adjustedUrl
}
}
/**
*
*
* GENERIC URL REWRITE FUNCTIONS
*
*
*/
/**
* Given an inputUrl, which may start with /api/,
* Return a modified URL, which replaces any /api/ links
* with /api-docs/ links (for compatibility with NextJS).
*
* For context:
* Links were are sometimes authored as "/api", rather than "/api-docs",
* which dates back to a time where "/api" did not conflict with NextJS routes.
* We must fix /api URLs, which are really /api-docs (for compat with NextJS)
* This would ideally be done in the source MDX.
*
* To fully deprecate the need for this rewriting of URLs, we'd need to fix
* all "/api" links in both the current and all past versions of docs.
* This may be feasible if we had a mechanism to apply remark transforms
* across all versions of a product's documentation
*/
function rewriteApiToApiDocs(inputUrl: string): string {
const isBadApiUrl = inputUrl == '/api' || inputUrl.startsWith('/api/')
if (isBadApiUrl) {
return inputUrl.replace(/^\/api/, '/api-docs')
}
return inputUrl
}
/**
* Given an inputUrl, and some product data,
* assume the inputUrl has been written by docs authors in the context
* of the specified product.
*
* If the inputUrl matches one of the product's basePaths,
* Return the input URL prefixed with the product's slug.
*
* Otherwise, return the original inputUrl.
*
* For context:
* Authors write content as if it only exists for their product.
* For example, Waypoint content contains links that start with "/docs",
* but we need to be adjust these links to start with "/waypoint/docs".
*/
export function rewriteDocsUrl(
inputUrl: string,
currentProduct: ProductData
): string {
// We only want to adjust internal URLs, so we return absolute URLs, or anchor links, as-is
if (
isAbsoluteUrl(inputUrl) ||
inputUrl.startsWith('#') ||
inputUrl.startsWith('.') ||
/(.png|.jpg|.svg)$/.test(inputUrl) // ignore image links
) {
return inputUrl
}
// If it goes to the home page (`/`), return the inputUrl unmodified
const urlObject = new URL(inputUrl, 'https://developer.hashicorp.com')
if (urlObject.pathname === '/') {
return inputUrl
}
// Prefix docs URLs. "/docs/some-path" becomes "/waypoint/docs/some-path"
const isCurrentProductDocsUrl = currentProduct.basePaths.some(
(basePath: string) => inputUrl.startsWith(`/${basePath}`)
)
const isProductPath = new RegExp(`^/(${productSlugs.join('|')})`)
const isTutorialsPath = new RegExp(
`^/(${[
...productSlugs,
SectionOption['well-architected-framework'],
SectionOption.onboarding,
].join('|')}(/tutorials)?)`
)
if (isCurrentProductDocsUrl) {
// The vagrant vmware utility downloads page is a unique case, where we did
// adjust the url structure in the transition to devdot
if (
currentProduct.slug === 'vagrant' &&
inputUrl.startsWith('/vmware/downloads')
) {
return `/${currentProduct.slug}/downloads/vmware`
}
return `/${currentProduct.slug}${inputUrl}`
} else if (!isProductPath.test(inputUrl) && !isTutorialsPath.test(inputUrl)) {
// if the path doesnt already start with a product slug i.e. /consul/tutorials
// and its not an absolute url we assume it is an internal .io link
// for this product context that is not a docs link, and should link to the external .io site
// For example, the vault use case pages, the hcp pricing page, etc.
const url = new URL(
inputUrl,
`https://${productSlugsToHostNames[currentProduct.slug]}`
)
return url.toString()
}
// If we didn't match the currentProduct's basePath, return the original URL.
return inputUrl
}
/**
*
*
* PRODUCT-SPECIFIC REWRITE FUNCTIONS
*
*
*/
/**
* Rewrite URLs in Sentinel docs content
*/
function rewriteSentinelDocsUrls(
inputUrl: string,
sentinelData: ProductData
): string {
// We only want to adjust internal URLs, so we return absolute URLs as-is
if (isAbsoluteUrl(inputUrl)) {
return inputUrl
}
/**
* Note: sentinel content is a bit of a special case.
*
* On the old dot-io-equivalent Sentinel deploy, at docs.hashicorp.com:
* - "/docs" were rendered at "/sentinel/:slug"
* - "/intro" were rendered at "/sentinel/intro/:slug"
* - "/downloads" was rendered at "/sentinel/downloads"
*
* In the new HashiCorp Developer UI:
* - "/docs" are rendered at "/sentinel/docs/:slug"
* - "/intro" are rendered at "/sentinel/intro/:slug" (same as before!)
* - "/downloads" is rendered at "/sentinel/downloads" (same as before!)
*
* Note that:
* - Any "/sentinel/<basePath>/:slug" URLs do not need to be modified
* - This excludes the case where "basePath" is "docs"
* - This really just applies to "/sentinel/intro", but in theory could
* apply to other Sentinel "basePaths" if they get added
* - The "/sentinel/downloads" URL does not need to be modified
* - Any other "/sentinel/:slug" URL is expected to be a "/docs" URL
* - We need to adjust these urls to be "/sentinel/docs/:slug"
*/
const isBasePathExceptDocs = sentinelData.basePaths
.filter((p: string) => p !== 'docs')
.some(
(basePath: string) =>
inputUrl == `/sentinel/${basePath}` ||
inputUrl.startsWith(`/sentinel/${basePath}/`)
)
const isDownloadsUrl = inputUrl == '/sentinel/downloads'
/**
* We assume all other "/sentinel/*" URLs are intended to be docs routes,
* which on the previous site were rendered to "/sentinel/:slug".
* We need to correct these URLs to be "/sentinel/docs/:slug".
*/
const isKnownUrl = isBasePathExceptDocs || isDownloadsUrl
const isDocsUrl = !isKnownUrl && inputUrl.startsWith('/sentinel')
if (isDocsUrl) {
return `/sentinel/docs${inputUrl.replace('/sentinel', '')}`
}
// If we didn't match a docs URL, return the original URL
return inputUrl
}
|
<?php
use PhpHttpClient\Client;
it('tests withQuery method', function () {
$client = new Client('http://example.com');
$query = ['param1' => 'value1', 'param2' => 'value2'];
$result = $client->withQuery($query);
expect($result)->toBeInstanceOf(Client::class);
});
it('tests withBody method', function () {
$client = new Client('http://example.com');
$body = ['param1' => 'value1', 'param2' => 'value2'];
$result = $client->withBody($body);
expect($result)->toBeInstanceOf(Client::class);
});
it('tests withOptions method', function () {
$client = new Client('http://example.com');
$options = ['param1' => 'value1', 'param2' => 'value2'];
$result = $client->withOptions($options);
expect($result)->toBeInstanceOf(Client::class);
});
it('tests withHeaders method', function () {
$client = new Client('http://example.com');
$headers = ['param1' => 'value1', 'param2' => 'value2'];
$result = $client->withHeaders($headers);
expect($result)->toBeInstanceOf(Client::class);
});
it('tests withBasicAuth method', function () {
$client = new Client('http://example.com');
$username = 'username';
$password = 'password';
$result = $client->withBasicAuth($username, $password);
expect($result)->toBeInstanceOf(Client::class);
});
it('tests withDigestAuth method', function () {
$client = new Client('http://example.com');
$username = 'username';
$password = 'password';
$result = $client->withDigestAuth($username, $password);
expect($result)->toBeInstanceOf(Client::class);
});
it('tests withQuery method with github api', function () {
$client = new Client('https://api.github.com');
$query = ['q' => 'php'];
$result = $client->withQuery($query)->get('/');
expect($result->hasHeader('Content-Type'))->toBeTrue()
->and($result->getStatusCode())->toBeInt();
});
|
package docker
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
"github.com/docker/go-connections/nat"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
"io"
"log/slog"
"os"
"strings"
)
type ContainerCreateBuilder struct {
containerConfig *container.Config
hostConfig *container.HostConfig
networkingConfig *network.NetworkingConfig
platform *v1.Platform
containerName string
err error
ctx context.Context
}
func (self *ContainerCreateBuilder) WithContainerName(name string) *ContainerCreateBuilder {
self.containerConfig.Hostname = fmt.Sprintf("%s.pod.dpanel.local", name)
self.containerName = name
self.containerConfig.Labels = map[string]string{
"BuildAuthor": BuilderAuthor,
"BuildDesc": BuildDesc,
"BuildWebSite": BuildWebSite,
"buildVersion": BuildVersion,
}
// 防止退出
self.containerConfig.AttachStdin = true
self.containerConfig.AttachStdout = true
self.containerConfig.AttachStderr = true
self.containerConfig.Tty = true
return self
}
func (self *ContainerCreateBuilder) WithEnv(name string, value string) *ContainerCreateBuilder {
self.containerConfig.Env = append(self.containerConfig.Env, fmt.Sprintf("%s=%s", name, value))
return self
}
func (self *ContainerCreateBuilder) WithImage(imageName string, tryPullImage bool) {
// 只尝试从 docker.io 拉取
if tryPullImage {
reader, err := Sdk.Client.ImagePull(Sdk.Ctx, imageName, image.PullOptions{})
if err != nil {
self.err = err
return
}
io.Copy(os.Stdout, reader)
}
self.containerConfig.Image = imageName
return
}
func (self *ContainerCreateBuilder) WithRestart(restartType string) *ContainerCreateBuilder {
self.hostConfig.RestartPolicy = container.RestartPolicy{}
self.hostConfig.RestartPolicy.Name = Sdk.GetRestartPolicyByString(restartType)
return self
}
func (self *ContainerCreateBuilder) WithPrivileged() *ContainerCreateBuilder {
self.hostConfig.Privileged = true
return self
}
// WithVolume 挂载宿主机目录
func (self *ContainerCreateBuilder) WithVolume(host string, container string, permission string) *ContainerCreateBuilder {
//_, err := os.Stat(host)
self.hostConfig.Binds = append(self.hostConfig.Binds, fmt.Sprintf("%s:%s:%s", host, container, permission))
return self
}
// WithContainerVolume 挂载某个容器的数据卷
func (self *ContainerCreateBuilder) WithContainerVolume(fromContainerMd5 string) {
self.hostConfig.VolumesFrom = append(self.hostConfig.VolumesFrom, fromContainerMd5)
}
func (self *ContainerCreateBuilder) WithDefaultVolume(container string) {
volumePath := fmt.Sprintf("%s.%s", self.containerName, strings.Join(strings.Split(container, "/"), "-"))
self.hostConfig.Binds = append(self.hostConfig.Binds, fmt.Sprintf("%s:%s:rw", volumePath, container))
}
// WithPort 绑定端口
func (self *ContainerCreateBuilder) WithPort(host string, container string) *ContainerCreateBuilder {
var port nat.Port
var err error
hostIp := "0.0.0.0"
if strings.Contains(container, "/") {
portArr := strings.Split(container, "/")
port, err = nat.NewPort(portArr[1], portArr[0])
} else {
port, err = nat.NewPort("tcp", container)
}
if err != nil {
self.err = err
return nil
}
self.containerConfig.ExposedPorts[port] = struct{}{}
self.hostConfig.PortBindings[port] = make([]nat.PortBinding, 0, 1)
self.hostConfig.PortBindings[port] = append(
self.hostConfig.PortBindings[port], nat.PortBinding{HostIP: hostIp, HostPort: host},
)
return self
}
func (self *ContainerCreateBuilder) WithLink(name string, alise string) {
// 利用Network关联容器
options := make(map[string]string)
options["name"] = self.containerName
myNetwork, _ := Sdk.Client.NetworkCreate(Sdk.Ctx, self.containerName, types.NetworkCreate{
Driver: "bridge",
Options: options,
})
slog.Debug("create network", "name", myNetwork.ID)
// 关联网络时,重新退出加入
err := Sdk.Client.NetworkDisconnect(Sdk.Ctx, self.containerName, name, true)
if err != nil {
slog.Debug("disconnect network", "name", myNetwork.ID, "error", err.Error())
}
err = Sdk.Client.NetworkConnect(Sdk.Ctx, self.containerName, name, &network.EndpointSettings{
Aliases: []string{
alise,
},
})
if err != nil {
slog.Debug("join network", "name", myNetwork.ID, "error", err.Error())
}
}
func (self ContainerCreateBuilder) WithNetwork(name string, alise string) {
self.networkingConfig.EndpointsConfig[name] = &network.EndpointSettings{
NetworkID: name,
Aliases: []string{
alise,
},
}
}
func (self *ContainerCreateBuilder) WithAutoRemove() {
self.hostConfig.AutoRemove = true
}
func (self *ContainerCreateBuilder) WithCpus(count int) {
self.hostConfig.NanoCPUs = int64(count) * 1000000000
}
func (self *ContainerCreateBuilder) WithMemory(count int) {
self.hostConfig.Memory = int64(count) * 1024 * 1024
}
func (self *ContainerCreateBuilder) WithShmSize(size int) {
self.hostConfig.ShmSize = int64(size)
}
func (self *ContainerCreateBuilder) WithWorkDir(path string) {
self.containerConfig.WorkingDir = path
}
func (self *ContainerCreateBuilder) WithUser(user string) {
self.containerConfig.User = user
}
func (self *ContainerCreateBuilder) WithCommand(cmd string) {
self.containerConfig.Cmd = strings.Split(cmd, " ")
}
func (self *ContainerCreateBuilder) WithEntrypoint(cmd string) {
self.containerConfig.Entrypoint = strings.Split(cmd, " ")
}
func (self *ContainerCreateBuilder) WithPid(pid ...string) {
pidStr := strings.Join(pid, ":")
self.hostConfig.PidMode = container.PidMode(pidStr)
}
func (self *ContainerCreateBuilder) Execute() (response container.CreateResponse, err error) {
if self.err != nil {
return response, self.err
}
return Sdk.Client.ContainerCreate(
self.ctx,
self.containerConfig,
self.hostConfig,
self.networkingConfig,
self.platform,
self.containerName,
)
}
|
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2023 Albert Moky
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from typing import Optional, Dict
from dimples import json_encode, json_decode, utf8_encode, utf8_decode
from dimples import ID
from .base import Cache
class GroupKeysCache(Cache):
# group keys cached in Redis will be removed after 30 minutes, after that
# it will be reloaded from local storage if it's still need.
EXPIRES = 1800 # seconds
@property # Override
def db_name(self) -> Optional[str]:
return 'dkd'
@property # Override
def tbl_name(self) -> str:
return 'group'
"""
Encrypted keys
~~~~~~~~~~~~~~
redis key: 'dkd.group.{GID}.{UID}.encrypted-keys'
"""
def __cache_name(self, group: ID, sender: ID) -> str:
return '%s.%s.%s.%s.encrypted-keys' % (self.db_name, self.tbl_name, group, sender)
def group_keys(self, group: ID, sender: ID) -> Optional[Dict[str, str]]:
name = self.__cache_name(group=group, sender=sender)
value = self.get(name=name)
if value is not None:
js = utf8_decode(data=value)
assert js is not None, 'failed to decode string: %s' % value
info = json_decode(string=js)
assert info is not None, 'document error: %s' % value
return info
def save_group_keys(self, group: ID, sender: ID, keys: Dict[str, str]) -> bool:
js = json_encode(obj=keys)
value = utf8_encode(string=js)
name = self.__cache_name(group=group, sender=sender)
self.set(name=name, value=value, expires=self.EXPIRES)
return True
|
// ADD FIREBASE !
import Header from "./components/Header";
import Nav from "./components/Nav";
import { useEffect, useState } from "react";
import DisplayTasks from "./components/DisplayTasks";
import AddTaskPopup from "./components/AddTaskPopup"
import RemoveTaskPopup from "./components/RemoveTaskPopup";
import AddProject from "./components/AddProject"
import EditTask from "./components/EditTask";
import { useLocation } from "react-router-dom"
import NotFound from "./components/NotFound";
import TaskDone from "./components/TaskDone";
import CompletedTasks from "./components/CompletedTasks";
const initialData = [
{
title: `Example #1`,
description: `I made this todo-list app so I could familarize myself with states and their management in react, tasks aren't saved in the localstorage or any database`,
dueDate: `2022-12-09`,
priorty: "High",
project: "Home",
id: 0,
isCompleted: false
},
{
title: `Example #2`,
description: `Try changing my priorty and see how my color changes`,
dueDate: `2022-12-31`,
priorty: "Medium",
project: "Home",
id: 1,
isCompleted: false
},
{
title: `Example #3`,
description: `Try messing with buttons, add, edit and delete. I used scale and opacity properties for styling and to make animation possible.`,
dueDate: "2023-03-16",
priorty: "Low",
project: "Home",
id: 2,
isCompleted: false
},
{
title: `I belong in custom Project`,
description: `You can click on edit icon and change my project to move me.`,
dueDate: "2023-03-16",
priorty: "Low",
project: "Custom Project",
id: 3,
isCompleted: false
},
];
const Home = () => {
// capitals letters imply immutability and immortality
const [TASKS, setTASKS] = useState(initialData)
const [tasks, setTasks] = useState(initialData);
const [customProjects, setCustomProjects] = useState(["Custom Project", "Another Project"])
const location = useLocation()
let locationName = location.pathname === "/" ? "Home" : location.pathname.slice(1,)
const [url, setUrl] = useState("home")
useEffect(() => {
setUrl(locationName)
})
useEffect(() => {
if (url === "Completed-tasks") {
const filteredTasks = TASKS.filter(task => task.isCompleted === true)
setTasks(filteredTasks)
} else {
const filteredTasks = TASKS.filter(task => (task.project === locationName.split("-").join(" ") &&
task.isCompleted !== true))
setTasks(filteredTasks)
}
}, [url, TASKS])
const [overlayActive, setOverlayActive] = useState(false)
const [overlayForRemove, setOverlayForRemove] = useState(false)
const [displayCustomProject, setDisplayCustomProject] = useState(false)
const [overlayEditTask, setOverlayEditTask] = useState(false)
const [editedTaskId, setEditedTaskId] = useState(null)
const setOverlay = () => {
setOverlayActive(!overlayActive)
}
const openCustomProjectPopup = () => {
setDisplayCustomProject(true)
}
const openEditTaskPopup = (e, id) => {
setOverlayEditTask(true)
setEditedTaskId(id)
}
// if ((!customProjects.includes(locationName.split("-").join(" "))) && (locationName !== "Home")) {
// return (
// <NotFound />
// )
// }
// CRUD functions
// add a task, remove a task, edit a task
// changing priorty
const changePriorty = (newPriorty, id, setModalActive) => {
const priortyTooltip = newPriorty.parentElement
const newList = TASKS.map(t => {
if (t.id === id) {
return { ...t, priorty: newPriorty.textContent }
} else {
return t
}
})
setTASKS(newList)
priortyTooltip.style.opacity = "0"
priortyTooltip.classList.add("hidden")
setModalActive(false)
}
// removes all the tasks in a project
const removeAllTasks = (customProjectName) => {
const newTask = TASKS.filter(task => task.project !== customProjectName)
setTASKS(newTask)
}
// remove the task given id (triggers when user clicks on remove icon)
const [idForTaskBeingRemoved, setIdForTaskBeingRemoved] = useState(null)
const removeTask = (e, id) => {
setOverlayForRemove(true)
setIdForTaskBeingRemoved(id)
}
// add a task
const addTask = (t) => {
const task = t
t["id"] = TASKS.length
setTASKS([...TASKS, task])
}
// edit a task
const editTask = (id, t) => {
const editedTask = t;
const idOfEditedTask = id
const newList = TASKS.map(task => {
if (task["id"] === idOfEditedTask) {
return editedTask
} else {
return task
}
})
console.log(editedTask)
setTASKS(newList)
}
// task completed
const [taskCompletedPopup, setTaskCompletedPopup] = useState(false)
const [removedTASK, setRemovedTASK] = useState([])
const taskCompleted = (element, id) => {
const markedCompleted = TASKS.map(t => {
if (t['id'] === id) {
return { ...t, isCompleted: true }
} else {
return t
}
})
const completedTaskId = id
const completedTaskElement = element
const removedTask = completedTaskElement.parentElement.parentElement
setTaskCompletedPopup(true)
setRemovedTASK([markedCompleted, completedTaskId, removedTask])
removedTask.style.transition = "all 0.3s ease"
setTimeout(() => {
removedTask.style.padding = "0"
removedTask.style.maxHeight = "1rem"
removedTask.style.opacity = "0"
}, 0.001)
setTimeout(() => {
removedTask.classList.add("hidden")
}, 300)
// hide popup after 6 seconds
}
// bring the task back if user clicks on undo button
const undoFunc = (element) => {
setTaskCompletedPopup(false)
removedTASK[2].classList.remove("hidden")
// const div = element.parentElement.previousElementSibling.children[1].children[removedTASK[1] + 1]
console.log(removedTASK[2])
element.parentElement.classList.add("opacity-0")
const markedCompleted = TASKS.map(t => {
if (t['id'] === removedTASK[1]) {
return { ...t, isCompleted: false }
} else {
return t
}
})
setTASKS(markedCompleted)
removedTASK[2].style.transition = "all 0.3s ease"
setTimeout(() => {
removedTASK[2].style.opacity = "1"
removedTASK[2].style.padding = ""
removedTASK[2].style.maxHeight = ""
}, 100)
// uncheck the task
removedTASK[2].children[0].children[0].checked = false
}
return (
<>
<Header setOverlay={setOverlay} />
<section className="grid grid-cols-5 grad">
<Nav taskCompletedPopup={taskCompletedPopup} removeAllTasks={removeAllTasks} setCustomProjects={setCustomProjects} customProjects={customProjects} openCustomProjectPopup={openCustomProjectPopup} setOverlay={() => setOverlayActive(false)} />
<main className="acrd-list mx-auto pt-5 flex flex-col gap-2 p-2 col-span-5 md:col-span-4 px-1 w-full h-auto">
<p className="container-item w-full md:w-11/12 text-3xl text-slate-600 font-semibold tracking-normal text-left">
Task List
</p>
{ }
{(locationName === "Home") ? <DisplayTasks taskCompletedPopup={taskCompletedPopup} taskCompleted={taskCompleted} openEditTaskPopup={openEditTaskPopup} removeTask={removeTask} changePriorty={changePriorty} tasks={tasks} /> :
<DisplayTasks taskCompletedPopup={taskCompletedPopup} taskCompleted={taskCompleted} locationName={locationName.split("-").join(" ")} openEditTaskPopup={openEditTaskPopup} removeTask={removeTask} changePriorty={changePriorty} tasks={tasks} />}
</main>
</section>
{overlayActive && <AddTaskPopup addTask={addTask} customProjects={customProjects} closePopup={() => setOverlayActive(false)} />}
{overlayActive && <div onClick={setOverlay} className="fixed top-0 bottom-0 left-0 right-0 z-10 bg-black/25" id="overlay"></div>}
{overlayForRemove && <RemoveTaskPopup TASKS={TASKS} setTASKS={setTASKS} tasks={tasks} setTasks={setTasks} idForTaskBeingRemoved={idForTaskBeingRemoved} setOverlayForRemove={setOverlayForRemove} />}
{displayCustomProject && <AddProject customProjects={customProjects} setCustomProjects={setCustomProjects} setDisplayCustomProject={setDisplayCustomProject} />}
{overlayEditTask && <EditTask customProjects={customProjects} tasks={tasks} setTasks={setTasks} editTask={editTask} editedTaskId={editedTaskId} setOverlayEditTask={setOverlayEditTask} />}
<>
<TaskDone removedTASK={removedTASK} setTASKS={setTASKS} setTaskCompletedPopup={setTaskCompletedPopup} taskCompletedPopup={taskCompletedPopup} undoFunc={undoFunc} />
</>
</>
)
};
export default Home;
|
#include "pch.h"
#include "Window.hpp"
#include "GLFW/glfw3.h"
#ifdef _WIN32
#define GLFW_EXPOSE_NATIVE_WIN32
#define NOMINMAX
#include "GLFW/glfw3native.h"
#endif // _WIN32
namespace sa {
void Window::onResize(GLFWwindow* window, int width, int height) {
Window* thisWindow = (Window*)glfwGetWindowUserPointer(window);
if (thisWindow->isIconified()) {
return;
}
if (!thisWindow->isResizable()) {
return;
}
Extent extent = { width, height };
if (thisWindow->m_windowedExtent.width != extent.width || thisWindow->m_windowedExtent.height != height) {
thisWindow->m_wasResized = true;
thisWindow->m_windowedExtent = extent;
SA_DEBUG_LOG_INFO("Window: Window resize ", width, height);
}
}
void Window::onIconify(GLFWwindow* window, int iconified) {
Window* thisWindow = (Window*)glfwGetWindowUserPointer(window);
thisWindow->m_isIconified = iconified;
SA_DEBUG_LOG_WARNING("Window: Window iconified");
}
void Window::onKey(GLFWwindow* window, int key, int scancode, int action, int mods) {
Window* thisWindow = (Window*)glfwGetWindowUserPointer(window);
#ifdef _WIN32
if (key == GLFW_KEY_F11 && action == GLFW_PRESS) {
thisWindow->toggleFullscreen();
}
if (key == GLFW_KEY_F10 && action == GLFW_PRESS) {
thisWindow->toggleBorderless();
//thisWindow->toggleBorderlessFullscreen();
}
#endif // _WIN32
for (auto& func : thisWindow->m_onKeyFunctions) {
func((Key)key, (InputAction)action, (ModKeyFlags)mods, scancode);
}
}
void Window::onMouseButton(GLFWwindow* window, int button, int action, int mods) {
Window* thisWindow = (Window*)glfwGetWindowUserPointer(window);
for (auto& func : thisWindow->m_onMouseButtonFunctions) {
func((MouseButton)button, (InputAction)action, (ModKeyFlags)mods);
}
}
void Window::onScroll(GLFWwindow* window, double x, double y) {
Window* thisWindow = (Window*)glfwGetWindowUserPointer(window);
for (auto& func : thisWindow->m_onScrollFunctions) {
func(x, y);
}
}
void Window::onClose(GLFWwindow* window) {
Window* w = (Window*)glfwGetWindowUserPointer(window);
w->close();
}
void Window::onDragDrop(GLFWwindow* window, int count, const char** pathUTF8) {
Window* thisWindow = (Window*)glfwGetWindowUserPointer(window);
for (auto& func : thisWindow->m_onDragDropFunctions) {
func(count, pathUTF8);
}
}
void Window::onJoystickDetect(int jid, int state) {
if (s_onJoystickDetectFunction) {
if (state == GLFW_CONNECTED) {
s_onJoystickDetectFunction((Joystick)jid, ConnectionState::CONNECTED);
}
else if (state == GLFW_DISCONNECTED) {
s_onJoystickDetectFunction((Joystick)jid, ConnectionState::DISCONNECTED);
}
}
}
void Window::create(uint32_t width, uint32_t height, const char* title, GLFWmonitor* monitor) {
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
m_monitor = monitor;
if (m_monitor) {
int refreshrate = glfwGetVideoMode(m_monitor)->refreshRate;
glfwWindowHint(GLFW_REFRESH_RATE, refreshrate);
}
m_window = glfwCreateWindow(width, height, title, m_monitor, nullptr);
if (!m_window) {
throw std::runtime_error("Failed to create GLFW window");
}
glfwSetWindowSizeCallback(m_window, &Window::onResize);
glfwSetWindowIconifyCallback(m_window, &Window::onIconify);
glfwSetKeyCallback(m_window, &Window::onKey);
glfwSetMouseButtonCallback(m_window, &Window::onMouseButton);
glfwSetScrollCallback(m_window, &Window::onScroll);
glfwSetWindowCloseCallback(m_window, &Window::onClose);
glfwSetDropCallback(m_window, &Window::onDragDrop);
glfwSetJoystickCallback(&Window::onJoystickDetect);
glfwSetWindowUserPointer(m_window, this);
Extent extent = { width, height };
m_windowedExtent = extent;
m_isIconified = false;
m_wasResized = false;
}
void Window::shutDown() {
glfwDestroyWindow(m_window);
m_window = nullptr;
}
void Window::SetJoystickConnectedCallback(JoystickConnectedCallback func) {
s_onJoystickDetectFunction = func;
}
bool Window::IsGamepad(Joystick joystick) {
return glfwJoystickIsGamepad((int)joystick) == GLFW_TRUE;
}
bool Window::IsJoystickPresent(Joystick joystick) {
return glfwJoystickPresent((int)joystick);
}
std::string Window::GetJoystickName(Joystick joystick) {
return glfwGetJoystickName((int)joystick);
}
GamepadState Window::GetGamepadState(Joystick joystick) {
GLFWgamepadstate state;
GamepadState gamepadState;
if (!glfwGetGamepadState((int)joystick, &state)) {
SA_DEBUG_LOG_WARNING("Joystick ", (int)joystick, " was not a gamepad or not present");
return {};
}
for (int i = 0; i < 15; i++) {
gamepadState.buttons[i] = state.buttons[i];
}
for (int i = 0; i < 6; i++) {
if (abs(state.axes[i]) < s_gamepadAxisDeadzone) {
gamepadState.axes[i] = 0;
continue;
}
gamepadState.axes[i] = state.axes[i];
}
return gamepadState;
}
float Window::GetGamepadAxisDeadzone() {
return s_gamepadAxisDeadzone;
}
void Window::SetGamepadAxisDeadzone(float deadzone) {
s_gamepadAxisDeadzone = deadzone;
}
ResourceID Window::CreateCursor(const Image& image, Offset hot) {
GLFWimage gImage;
gImage.width = image.getWidth();
gImage.height = image.getHeight();
gImage.pixels = image.getPixels();
GLFWcursor* pCursor = glfwCreateCursor(&gImage, hot.x, hot.y);
if (!pCursor) {
return NULL_RESOURCE;
}
return ResourceManager::get().insert<GLFWcursor*>(pCursor);
}
ResourceID Window::CreateCursor(StandardCursor cursor) {
GLFWcursor* pCursor = glfwCreateStandardCursor((int)cursor);
if (!pCursor) {
return NULL_RESOURCE;
}
return ResourceManager::get().insert<GLFWcursor*>(pCursor);
}
Window::Window(uint32_t width, uint32_t height, const char* title) {
if (s_windowCount == 0) {
if (!glfwInit()) {
throw std::runtime_error("Failed to initialize GLFW!");
}
ResourceManager::get().setCleanupFunction<GLFWcursor*>([](GLFWcursor** p) { glfwDestroyCursor(*p); });
}
s_windowCount++;
create(width, height, title, nullptr);
}
Window::Window(uint32_t monitorIndex) {
if (s_windowCount == 0) {
if (!glfwInit()) {
throw std::runtime_error("Failed to initialize GLFW!");
}
ResourceManager::get().setCleanupFunction<GLFWcursor*>([](GLFWcursor** p) { glfwDestroyCursor(*p); });
}
s_windowCount++;
int count;
GLFWmonitor** monitors = glfwGetMonitors(&count);
if (monitorIndex >= count || monitorIndex < 0) {
throw std::runtime_error("Monitor index out of range!");
return;
}
GLFWmonitor* monitor = monitors[monitorIndex];
int xpos, ypos, width, height;
glfwGetMonitorWorkarea(monitor, &xpos, &ypos, &width, &height);
create(width, height, "", monitor);
}
Window::~Window() {
if (m_window != nullptr) {
shutDown();
s_windowCount--;
if (s_windowCount == 0) {
ResourceManager::get().clearContainer<GLFWcursor*>();
glfwTerminate();
}
}
}
bool Window::isOpen() {
if (m_window == nullptr) {
return false;
}
return !glfwWindowShouldClose(m_window);
}
void Window::pollEvents() {
glfwPollEvents();
}
void Window::waitEvents(float timeoutSeconds) {
if (timeoutSeconds < 0) {
glfwWaitEvents();
return;
}
glfwWaitEventsTimeout(timeoutSeconds);
}
void Window::close() {
glfwSetWindowShouldClose(m_window, GLFW_TRUE);
}
void Window::setRefreshRate(int rate) {
int xpos = 0, ypos = 0, width = getCurrentExtent().width, height = getCurrentExtent().height;
glfwGetWindowPos(m_window, &xpos, &ypos);
if (m_monitor != nullptr) {
glfwGetMonitorWorkarea(m_monitor, &xpos, &ypos, &width, &height);
}
glfwSetWindowMonitor(m_window, m_monitor, xpos, ypos, width, height, rate);
}
int Window::getRefreshRate() const {
GLFWmonitor* monitor = m_monitor;
if (!monitor) {
int count;
GLFWmonitor** monitors = glfwGetMonitors(&count);
monitor = monitors[getCurrentMonitor()];
}
const GLFWvidmode* vidmode = glfwGetVideoMode(monitor);
return vidmode->refreshRate;
}
void Window::setMonitor(int monitorIndex) {
int count;
GLFWmonitor** monitors = glfwGetMonitors(&count);
if (monitorIndex >= count) {
throw std::runtime_error("Monitor index out of range!");
return;
}
int xpos = 100, ypos = 100, width, height;
if (monitorIndex == -1) {
m_monitor = nullptr;
width = m_windowedExtent.width;
height = m_windowedExtent.height;
}
else {
m_monitor = monitors[monitorIndex];
glfwGetMonitorWorkarea(m_monitor, &xpos, &ypos, &width, &height);
}
glfwSetWindowMonitor(m_window, m_monitor, xpos, ypos, width, height, GLFW_DONT_CARE);
m_wasResized = true;
}
int Window::getCurrentMonitor() const {
int count;
GLFWmonitor** monitors = glfwGetMonitors(&count);
int window_xpos, window_ypos;
glfwGetWindowPos(m_window, &window_xpos, &window_ypos);
for (int i = 0; i < count; i++) {
int xpos, ypos, width, height;
glfwGetMonitorWorkarea(monitors[i], &xpos, &ypos, &width, &height);
if (window_xpos > xpos && window_xpos < xpos + width) {
if (window_ypos > ypos && window_ypos < ypos + height) {
return i;
}
}
}
return -1;
}
int Window::getPrimaryMonitor() const {
int count;
GLFWmonitor** pMonitors = glfwGetMonitors(&count);
GLFWmonitor* pMonitor = glfwGetPrimaryMonitor();
for (int i = 0; i < count; i++) {
if (pMonitor == pMonitors[i]) {
return i;
}
}
return -1;
}
int Window::getMonitorCount() const {
int count;
glfwGetMonitors(&count);
return count;
}
void Window::setFullscreen(bool fullscreen) {
if (!isResizable())
return;
if (fullscreen) {
setMonitor(getCurrentMonitor());
}
else {
setMonitor(-1);
}
}
void Window::toggleFullscreen() {
setFullscreen(!isFullscreen());
}
bool Window::isFullscreen() const {
return m_monitor != nullptr;
}
void Window::setBorderless(bool isBorderless) {
glfwSetWindowAttrib(m_window, GLFW_DECORATED, !isBorderless);
}
void Window::toggleBorderless() {
setBorderless(!isBorderless());
}
bool Window::isBorderless() const {
return !(bool)glfwGetWindowAttrib(m_window, GLFW_DECORATED);
}
void Window::setBorderlessFullscreen(bool value) {
if (!isResizable())
return;
setBorderless(value);
if (value) {
int count;
GLFWmonitor** monitors = glfwGetMonitors(&count);
GLFWmonitor* monitor = monitors[getCurrentMonitor()];
int xpos, ypos, width, height;
glfwGetMonitorWorkarea(monitor, &xpos, &ypos, &width, &height);
const GLFWvidmode* vidmode = glfwGetVideoMode(monitor);
glfwSetWindowMonitor(m_window, nullptr, xpos, ypos, width, height, vidmode->refreshRate);
}
else {
glfwSetWindowMonitor(m_window, nullptr, 0, 0, m_windowedExtent.width, m_windowedExtent.height, GLFW_DONT_CARE);
}
}
void Window::toggleBorderlessFullscreen() {
setBorderlessFullscreen(!isBorderless());
}
void Window::setResizable(bool isResizable) {
glfwSetWindowAttrib(m_window, GLFW_RESIZABLE, isResizable);
}
bool Window::isResizable() const {
return glfwGetWindowAttrib(m_window, GLFW_RESIZABLE);
}
void Window::setWindowTitle(const char* title) {
glfwSetWindowTitle(m_window, title);
}
void Window::setWindowTitle(const std::string& title) {
glfwSetWindowTitle(m_window, title.c_str());
}
void Window::setWindowTitle(std::string&& title) {
glfwSetWindowTitle(m_window, title.c_str());
}
Extent Window::getCurrentExtent() const {
int width, height;
glfwGetFramebufferSize(m_window, &width, &height);
return { (uint32_t)width, (uint32_t)height };
}
Offset Window::getWindowPosition() const {
Offset offset;
glfwGetWindowPos(m_window, &offset.x, &offset.y);
return offset;
}
GLFWwindow* Window::getWindowHandle() const {
return m_window;
}
void* Window::getWin32WindowHandle() const {
#ifdef _WIN32
return glfwGetWin32Window(m_window);
#else
return 0;
#endif // _WIN32
}
int Window::getKey(Key keyCode) const {
return glfwGetKey(m_window, (int)keyCode);
}
int Window::getMouseButton(MouseButton button) const {
return glfwGetMouseButton(m_window, (int)button);
}
Point Window::getCursorPosition() const {
Point pos;
glfwGetCursorPos(m_window, &pos.x, &pos.y);
return pos;
}
void Window::setCursorPosition(const Point& position) {
glfwSetCursorPos(m_window, position.x, position.y);
}
void Window::setCursorHidden(bool value) {
glfwSetInputMode(m_window, GLFW_CURSOR, (value) ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
}
bool Window::isCursorHidden() const {
return glfwGetInputMode(m_window, GLFW_CURSOR) == GLFW_CURSOR_HIDDEN;
}
void Window::setCursorDisabled(bool value) {
glfwSetInputMode(m_window, GLFW_CURSOR, (value) ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL);
}
bool Window::isCursorDisabled() const {
return glfwGetInputMode(m_window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED;
}
void Window::setCursor(ResourceID cursor) {
if (cursor == NULL_RESOURCE) {
glfwSetCursor(m_window, NULL);
return;
}
GLFWcursor** pCursor = ResourceManager::get().get<GLFWcursor*>(cursor);
if (!pCursor) {
SA_DEBUG_LOG_WARNING("Tried to set invalid cursor");
return;
}
glfwSetCursor(m_window, *pCursor);
}
void Window::addKeyCallback(KeyCallback func) {
m_onKeyFunctions.push_back(func);
}
void Window::addScrollCallback(ScrollCallback func) {
m_onScrollFunctions.push_back(func);
}
void Window::addDragDropCallback(DragDropCallback func) {
m_onDragDropFunctions.push_back(func);
}
void Window::addMouseButtonCallback(MouseButtonCallback func) {
m_onMouseButtonFunctions.push_back(func);
}
void Window::setWasResized(bool value) {
m_wasResized = value;
}
bool Window::wasResized() const {
return m_wasResized;
}
bool Window::isIconified() const {
return m_isIconified;
}
}
|
<?php
declare(strict_types=1);
namespace Nadiiaz\RegularCustomer\CustomerData;
class DiscountRequests implements \Magento\Customer\CustomerData\SectionSourceInterface
{
/**
* @var \Nadiiaz\RegularCustomer\Model\CustomerRequestsProvider $customerRequestsProvider
*/
private \Nadiiaz\RegularCustomer\Model\CustomerRequestsProvider $customerRequestsProvider;
/**
* @var \Magento\Customer\Model\Session $customerSession
*/
private \Magento\Customer\Model\Session $customerSession;
/**
* @param \Nadiiaz\RegularCustomer\Model\CustomerRequestsProvider $customerRequestsProvider
* @param \Magento\Customer\Model\Session $customerSession
*/
public function __construct(
\Nadiiaz\RegularCustomer\Model\CustomerRequestsProvider $customerRequestsProvider,
\Magento\Customer\Model\Session $customerSession
) {
$this->customerRequestsProvider = $customerRequestsProvider;
$this->customerSession = $customerSession;
}
/**
* @inheritDoc
*/
public function getSectionData(): array
{
$name = (string) $this->customerSession->getDiscountRequestCustomerName();
$email = (string) $this->customerSession->getDiscountRequestCustomerEmail();
if ($this->customerSession->isLoggedIn()) {
$discountRequestCollection = $this->customerRequestsProvider->getCurrentCustomerRequestCollection();
$productIds = $discountRequestCollection->getColumnValues('product_id');
$productIds = array_unique($productIds);
$productIds = array_values(array_map('intval', $productIds));
} else {
$productIds = (array) $this->customerSession->getDiscountRequestProductIds();
$name = $this->customerSession->getCustomer()->getName();
$email = $this->customerSession->getCustomer()->getEmail();
}
return [
'name' => $name,
'email' => $email,
'productIds' => $productIds,
'isLoggedIn' => $this->customerSession->isLoggedIn()
];
}
}
|
/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"fmt"
"log"
"github.com/spf13/cobra"
)
// listCmd represents the list command
var listCmd = &cobra.Command{
Use: "list",
Short: "list cache data",
Long: "list cache data",
Args: cobra.RangeArgs(0, 1),
Run: func(cmd *cobra.Command, args []string) {
if all, err := cmd.Flags().GetBool("all"); err == nil && all {
err := eachBucket(func(bucket string) error {
log.Printf("- %s", bucket)
err := eachItem(bucket, func(key string) error {
val, err := db.Get(bucket, key)
if err != nil {
return fmt.Errorf("%s failed to get value: %s", key, err)
}
log.Printf(" - %s %s", key, val)
return nil
})
if err != nil {
log.Fatalf("error: %s\n", err)
}
return nil
})
if err != nil {
log.Fatalf("error: %s\n", err)
}
return
}
if len(args) == 0 {
_ = eachBucket(func(bucket string) error {
log.Printf("- %s", bucket)
return nil
})
}
bucket := args[0]
err := eachItem(bucket, func(key string) error {
val, err := db.Get(bucket, key)
if err != nil {
return fmt.Errorf("%s failed to get value: %s", key, err)
}
log.Printf(" - %s %s", key, val)
return nil
})
if err != nil {
log.Fatalf("error: %s\n", err)
}
},
}
func eachBucket(fn func(string) error) error {
buckets, err := db.ListBuckets()
if err != nil {
return fmt.Errorf("failed to list buckets: %s\n", err)
}
for _, bucket := range buckets {
if bucket == "groak" {
continue
}
err := fn(bucket)
if err != nil {
return err
}
}
return nil
}
func eachItem(bucket string, fn func(string) error) error {
keys, err := db.List(bucket)
if err != nil {
return fmt.Errorf("failed to list keys: %s\n", err)
}
for _, key := range keys {
err := fn(key)
if err != nil {
return err
}
}
return nil
}
func init() {
cacheCmd.AddCommand(listCmd)
listCmd.Flags().BoolP("all", "a", false, "show all data")
}
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head th:replace="fragments/fragments :: head(title='Cinemas')" >
</head>
<body>
<!--this is for the navigation bar-->
<nav th:replace="fragments/fragments :: navbar" />
<div class="container-fluid">
<div class="row">
<nav th:replace="fragments/fragments :: sidebar" />
<div class="col-10 mt-3">
<h4 th:replace="fragments/fragments :: heading(text='Cinemas')" />
<div class="container mt-4" >
<!-- modal info -->
<div class="modal fade" id="editCinema" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editCinemaTitle">Edit Cinema</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<label for="name">Title</label>
<input type="text" class="form-control" id="editName" placeholder="Name" maxlength="50">
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-warning" id="submitChanges" data-toggle="modal" data-target="#editCinema">Save changes</button>
</div>
</div>
</div>
</div>
<!-- modal ends -->
<!-- List of available cinemas -->
<table class="table table-hover">
<caption>List of cinemas</caption>
<thead class="thead-dark">
<tr class="d-flex">
<th class="col-5">Id</th>
<th class="col-5">Name</th>
<!-- columns for edit and delete button -->
<th class="col-1"></th>
<th class="col-1"></th>
</tr>
</thead>
<tbody>
<tr class="d-flex" th:each="cinema : ${cinemaList}">
<td class="col-5" th:text="${cinema.id}" />
<td class="col-5" th:text="${cinema.name}"/>
<td class="col-1"><a href="#"
id = "editButton"
class="btn btn-warning"
data-toggle="modal"
data-target="#editCinema"
th:attr="data-cinemaID = ${cinema.id}"><span class="fas fa-edit"></span></a></td>
<td class="col-1">
<a class="btn btn-danger" th:href="@{'/cinemas/delete/' + ${cinema.id}}"><span class = "fas fa-trash"></span></a>
</td>
</tr>
</tbody>
</table>
<!-- Form for adding a cinema -->
<!-- <h1 class="display-4">Add New Movie</h1> -->
<details>
<summary>Add new cinema</summary>
<p>
<p class="lead">
<form method="post" th:object="${newCinema}">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" th:field="*{name}">
</div>
<input type="submit" class="btn btn-outline-dark" value="Add cinema"/>
<button type="reset" class="btn btn-outline-dark">Cancel</button>
</form>
</p>
</p>
</details>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script th:src="@{/js/cinema/cinemas.js}"></script>
</body>
</html>
|
import { inject, injectable } from "inversify";
import { TYPES } from "../../injectableTypes";
import { LoggerService } from "../logger/LoggerService";
import { DataSource } from "../dataSource/DataSource";
import { PrismaClient } from "@prisma/client";
import { RegisterDto } from "./dto/register.dto";
import { LoginDto } from "./dto/login.dto";
import { AuthResponseDto } from "./dto/authResponse.dto";
import ApiError from "../exceptions/ApiError";
import { compare, genSalt, hash } from "bcrypt";
import { EnvironmentService } from "../config/EnvironmentService";
import { sign, verify } from "jsonwebtoken";
import { AuthPayload } from "./dto/authPayload.dto";
@injectable()
export class AuthService {
private db: PrismaClient;
private accessSecret: string;
private refreshSecret: string;
private accessTokenExpiresIn: string;
private refreshTokenExpiresIn: string;
constructor(
@inject(TYPES.Logger) private logger: LoggerService,
@inject(TYPES.EnvironmentService)
private environmentService: EnvironmentService,
@inject(TYPES.DataSource) private dataSource: DataSource
) {
this.db = dataSource.client;
this.accessSecret = environmentService.get("JWT_ACCESS_SECRET");
this.refreshSecret = environmentService.get("JWT_REFRESH_SECRET");
this.accessTokenExpiresIn = environmentService.get(
"ACCESS_TOKEN_EXPIRES_IN"
);
this.refreshTokenExpiresIn = environmentService.get(
"REFRESH_TOKEN_EXPIRES_IN"
);
}
async register(registerData: RegisterDto): Promise<AuthResponseDto> {
const { name, password, passwordConfirm } = registerData;
if (password !== passwordConfirm)
throw ApiError.BadRequest("Пароль и подтверждение пароля не совпадают");
const user = await this.db.user.findUnique({
select: { id: true },
where: { name },
});
if (user) throw ApiError.Conflict("Такой пользователь уже существует");
const createdUser = await this.db.user.create({ data: { name } });
const salt = await genSalt();
const cryptedPassword = await hash(password, salt);
const { accessToken, refreshToken } = this.generateTokens({
id: createdUser.id,
name: createdUser.name,
});
await this.db.auth.create({
data: {
password: cryptedPassword,
userId: createdUser.id,
refreshToken,
},
});
return {
accessToken,
refreshToken,
userData: {
id: createdUser.id,
name: createdUser.name,
},
};
}
async login(loginData: LoginDto): Promise<AuthResponseDto> {
const { login, password } = loginData;
const user = await this.db.user.findUnique({
where: { name: login },
include: {
auth: {
select: {
password: true,
},
},
},
});
const errorMessage = `Неверный логин или пароль`;
if (!user) throw ApiError.BadRequest(errorMessage);
if (!(await compare(password, user.auth.password))) {
throw ApiError.BadRequest(errorMessage);
}
const userData = {
id: user.id,
name: user.name,
};
const { accessToken, refreshToken } = this.generateTokens(userData);
await this.saveRefreshToken(user.id, refreshToken);
return {
userData,
accessToken,
refreshToken,
};
}
async logout(refreshToken: string): Promise<void> {
try {
await this.db.auth.update({
where: { refreshToken },
data: { refreshToken: null },
});
} catch (e) {
throw ApiError.BadRequest();
}
}
async refresh(refreshToken: string): Promise<AuthResponseDto> {
if (!refreshToken) throw ApiError.UnauthorizedError();
const validationResult = this.validateToken(refreshToken, "refresh");
if (!validationResult) throw ApiError.UnauthorizedError();
const authData = await this.db.auth.findUnique({
where: { refreshToken },
select: {
refreshToken: true,
user: {
select: {
id: true,
name: true,
},
},
},
});
if (!authData) throw ApiError.UnauthorizedError();
const userData = {
id: authData.user.id,
name: authData.user.name,
};
const { accessToken, refreshToken: newRefreshToken } =
this.generateTokens(userData);
await this.saveRefreshToken(authData.user.id, newRefreshToken);
return {
userData,
accessToken,
refreshToken: newRefreshToken,
};
}
/**
* Возвращает payload токена или undefined если токен стух
*/
public validateToken(
token: string,
tokenType: "access" | "refresh"
): AuthPayload | undefined {
if (tokenType !== "access" && tokenType !== "refresh")
throw new Error("unknown token type");
try {
return verify(
token,
tokenType === "access" ? this.accessSecret : this.refreshSecret
) as AuthPayload;
} catch (error: any) {
return undefined;
}
}
private generateTokens(payload: any): {
accessToken: string;
refreshToken: string;
} {
const accessToken = sign(payload, this.accessSecret, {
expiresIn: this.accessTokenExpiresIn,
});
const refreshToken = sign(payload, this.refreshSecret, {
expiresIn: this.refreshTokenExpiresIn,
});
return {
accessToken,
refreshToken,
};
}
private async saveRefreshToken(userId: number, refreshToken: string) {
await this.db.auth.update({
where: { userId },
data: { refreshToken },
});
}
}
|
import styled from "styled-components";
import { useEffect, useState } from "react";
import { OpponentChoice } from "./components/OpponentChoice";
import { OptionCard } from "./components/OptionCard";
import { Outlet } from "react-router-dom";
import { Link } from "react-router-dom";
import { WinnerModal } from "./components/WinnerModal";
import { ScoreDotContainer } from "./components/ScoreDotContainer";
const Body = styled.div`
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
`;
const RowContainer = styled.div`
display: flex;
align-items: center;
justify-content: center;
flex-direction: row;
`;
const CardContainer = styled.div`
width: 50vw;
height: 300px;
display: flex;
align-items: center;
justify-content: center;
flex-direction: row;
`;
const HiddenLink = styled(Link)`
width: 25px;
height: 25px;
background-color: red;
position: absolute;
bottom: 0;
right: 0;
`;
function App({ socket }) {
const [lockedIn, setLockedIn] = useState(false);
const [winnerModal, setWinnerModal] = useState(false);
const [winner, setWinner] = useState("");
const setPlayerChoice = (choice) => {
socket.emit("sendChoice", choice);
setLockedIn(true);
};
useEffect(() => {
socket.on("result", (msg) => {
setWinnerModal(true);
setWinner(msg);
setTimeout(() => {
setWinner("");
setWinnerModal(false);
}, 1500);
setLockedIn(false);
});
}, [socket]);
return (
<Body>
<RowContainer>
<CardContainer>
<OptionCard
type="rock"
socket={socket}
lockedIn={lockedIn}
setChoice={setPlayerChoice}
/>
<OptionCard
type="paper"
socket={socket}
lockedIn={lockedIn}
setChoice={setPlayerChoice}
/>
<OptionCard
type="scissors"
socket={socket}
lockedIn={lockedIn}
setChoice={setPlayerChoice}
/>
</CardContainer>
<CardContainer>
<OpponentChoice />
</CardContainer>
</RowContainer>
<RowContainer>
<ScoreDotContainer />
<ScoreDotContainer />
</RowContainer>
<WinnerModal modal={winnerModal} winner={winner} />
<HiddenLink to={"admin"} />
<Outlet />
</Body>
);
}
export default App;
|
//
// VoiceControl.swift
// RobotControl_iOS
//
// Created by luolun on 2017/6/9.
// Copyright © 2017年 Aaron. All rights reserved.
//
import UIKit
import CoreBluetooth
import AVFoundation
protocol VoiceControlDelegate {
func finishRecognition(bestResult: String, allResult: [String: Float])
func loadGrammarError(_ error: Error)
func error(_ error: Error)
func voiceControlDidBeginListening()
func voiceControlDidEndListening()
func voiceControlDidCancel()
func robotNotConnected()
func hasSentCommand()
func sendConnamdFailed()
func grammarError(error: Error)
}
class VoiceControl: NSObject {
var _voiceRecognizerAdapter: VoiceRecognizerAdapter?
var _robotManager: RobotManager?
let delegate: VoiceControlDelegate
// TODO: (#10) 可以进一步优化,在初始化的时候把json转换成编译类
var _compilerJson: [String: Any]?
init(delegate: VoiceControlDelegate) throws {
self.delegate = delegate
super.init()
_voiceRecognizerAdapter = try VoiceRecognizerAdapter(delegate: self)
_robotManager = RobotManager()
_robotManager!.delegate = self
// try loadCompileDef()
}
func beginSpeak() -> Bool {
return canRecord() && _voiceRecognizerAdapter!.recognizeSpeech()
}
func stopSpeak() -> Bool {
return _voiceRecognizerAdapter!.stopSpeech()
}
private func loadCompileDef() throws {
let path = Bundle.main.path(forResource: "VoiceCommandCompileDef", ofType: "json")!
let defString = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue)
guard let compilerJson = try JSONSerialization.jsonObject(with: defString.data(using: String.Encoding.utf8.rawValue)!, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any] else {
throw VoiceControlError("Error when reading voice command compile definition file.", code: -1)
}
_compilerJson = compilerJson
}
private func canRecord() -> Bool{
var granted = true
if UIDevice.current.systemVersion.compare("7.0") == .orderedAscending {
let audioSession = AVAudioSession.sharedInstance()
if audioSession.responds(to: #selector(AVAudioSession.requestRecordPermission(_:))) {
audioSession.requestRecordPermission({ (userGranted: Bool) in
granted = userGranted
})
}
}
return granted
}
}
extension VoiceControl: VoiceRecognizerAdapterDelegate {
func initError(_ error: Error) {
delegate.error(error)
}
func error(_ error: Error) {
delegate.error(error)
}
func onResult(best: String, all: [String: Float]) {
// 用文字告知用户结果
delegate.finishRecognition(bestResult: best, allResult: all)
// TODO:(#9) 当置信度最高的几个词置信度一样的时候,询问用户执行哪操作
if _robotManager!.state == .Connected {
// 停止需要特殊处理
if best == "机器人停止" {
_robotManager!.forceStopRunning()
}
guard let commandString = toCommandString(best) else {
delegate.grammarError(error: VoiceControlError("Wrong grammar of command: \n \(best)", code: -1))
return
}
if false == _robotManager?.send(commandString: commandString) {
delegate.sendConnamdFailed()
} else {
delegate.hasSentCommand()
}
} else {
delegate.robotNotConnected()
}
}
func onBeginSpeech() {
delegate.voiceControlDidBeginListening()
}
func onFinishSpeech() {
delegate.voiceControlDidEndListening()
}
func onCancel() {
delegate.voiceControlDidCancel()
}
// MARK: -
func toCommandString(_ text: String) -> String? {
if text.hasPrefix("前进") {
let numberText = text.replacingOccurrences(of: "前进", with: "").replacingOccurrences(of: "米", with: "")
guard let number = textToNumber(numberText) else {
delegate.grammarError(error: VoiceControlError("Wrong grammar of command: \n \(text)", code: -1))
return nil
}
return "move(\(number))"
} else if text.hasPrefix("后退") {
let numberText = text.replacingOccurrences(of: "后退", with: "").replacingOccurrences(of: "米", with: "")
guard let number = textToNumber(numberText) else {
delegate.grammarError(error: VoiceControlError("Wrong grammar of command: \n \(text)", code: -1))
return nil
}
return "move(-\(number))"
}
return nil
}
func textToNumber(_ text: String) -> Int? {
var result = 0
var text = text
text = text.replacingOccurrences(of: "一", with: "1")
text = text.replacingOccurrences(of: "二", with: "2")
text = text.replacingOccurrences(of: "三", with: "3")
text = text.replacingOccurrences(of: "四", with: "4")
text = text.replacingOccurrences(of: "五", with: "5")
text = text.replacingOccurrences(of: "六", with: "6")
text = text.replacingOccurrences(of: "七", with: "7")
text = text.replacingOccurrences(of: "八", with: "8")
text = text.replacingOccurrences(of: "九", with: "9")
text = text.replacingOccurrences(of: "零", with: "")
let nsText = text as NSString
// 已经读取了一个digit
var stateDigit = false
var lastDigit = 0
for i in 0..<text.characters.count {
let c = nsText.character(at: i)
// 是否最后一个字符
let end = (i == (text.characters.count - 1))
if c >= NSString(string: "0").character(at: 0) && c <= NSString(string: "9").character(at: 0) {
let digit = Int(c - NSString(string: "0").character(at: 0))
lastDigit = digit
stateDigit = true
} else if c == NSString(string: "十").character(at: 0) {
lastDigit = stateDigit ? lastDigit : 1
result += lastDigit * 10
stateDigit = false
} else if c == NSString(string: "百").character(at: 0) {
lastDigit = stateDigit ? lastDigit : 1
result += lastDigit * 100
stateDigit = false
} else if c == NSString(string: "千").character(at: 0) {
lastDigit = stateDigit ? lastDigit : 1
result += lastDigit * 1000
stateDigit = false
} else if c == NSString(string: "万").character(at: 0) {
lastDigit = stateDigit ? lastDigit : 1
result += lastDigit * 10000
stateDigit = false
} else {
return nil
}
if end {
if stateDigit {
result += lastDigit
}
}
}
return result
}
}
extension VoiceControl: RobotManagerDelegate {
func bluetoothManagerDidUpdateState(_ state: CBManagerState) {
}
func robotManagerDidUpdateDeviceList(_ deviceList: Set<Robot>) {
}
func robotManagerDidConnect(to robot: Robot, success: Bool, error: Error?) {
}
func robotManagerDidDisconnection(to device: Robot, error: Error?) {
}
func robot(_ robot: Robot, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
}
}
class VoiceControlError: RobotControlError {
}
|
import getPriceView from "../lib/helpers/getPriceView";
import saveToLocalStorage from "@/shared/lib/helpers/saveToLocalStorage";
import { CartInterface, Payload } from "./interfaces";
import { localStorageKeys } from "@/shared/config/constants";
import { addToCartThunk, getCart } from "./asyncActions";
import { initialState } from "./initialState";
import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { changeItemCountActions } from "../lib/utils/changeItemCountActions";
import { IApiCart } from "@/shared/model/interfaces";
export const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
setCart: (state, { payload }: PayloadAction<IApiCart>) => {
if (payload?.items?.length) {
state.cart = new Map(payload.items.map((item) => [`${item.productId}_${item.size}_${item.type}`, item]));
cartSlice.caseReducers.updateViewAndStorage(state);
}
},
addToCart(state, { payload }: PayloadAction<Omit<CartInterface, "category">>) {
const key = `${payload.productId}_${payload.size}_${payload.type}`;
const product = state.cart.get(key);
state.cart.set(key, { ...payload, count: product ? product.count + 1 : 1 });
cartSlice.caseReducers.updateViewAndStorage(state);
},
changeItemCount: (state, { payload }: PayloadAction<Payload>) => {
const product = state.cart.get(payload.key);
if (!product) throw new Error(`Cannot find product with ${payload.key} key`);
state.cart.set(payload.key, {
...product,
count: payload.type === "direct" ? payload.count : changeItemCountActions[payload.type](product.count),
});
cartSlice.caseReducers.updateViewAndStorage(state);
},
removeProductFromCart: (state, { payload }: PayloadAction<{ key: string }>) => {
const product = state.cart.get(payload.key);
if (!product) throw new Error(`Cannot find product with ${payload.key} key`);
state.cart.delete(payload.key);
cartSlice.caseReducers.updateViewAndStorage(state);
},
updateViewAndStorage: (state) => {
const cartArr = [...state.cart.values()];
state.priceView = getPriceView(cartArr);
saveToLocalStorage({ key: localStorageKeys.CART, data: cartArr });
},
clearCart(state) {
state.cart.clear();
state.priceView = getPriceView([]);
localStorage.removeItem(localStorageKeys.CART);
},
},
extraReducers(builder) {
builder
.addCase(getCart.pending, (state) => {
state.cartLoading = true;
})
.addCase(getCart.fulfilled, (state, { payload }: PayloadAction<IApiCart | undefined>) => {
if (payload) {
state.cart = new Map(payload.items.map((product) => [`${product.productId}_${product.size}_${product.type}`, product]));
state.cartLoading = false;
cartSlice.caseReducers.updateViewAndStorage(state);
}
})
.addCase(getCart.rejected, (state) => {
state.cartLoading = false;
})
.addCase(addToCartThunk.fulfilled, (state, { payload }: PayloadAction<IApiCart>) => {
payload.items.forEach((product) => state.cart.set(`${product.productId}_${product.size}_${product.type}`, product));
cartSlice.caseReducers.updateViewAndStorage(state);
});
},
});
export const { addToCart, changeItemCount, removeProductFromCart, clearCart, setCart } = cartSlice.actions;
export default cartSlice.reducer;
|
<template>
<div>
<!-- you can write components pascal cased or camel cased, so either <TheHeader /> or <the-header /> works -->
<the-header></the-header>
<button @click="setSelectedComponent('active-goals')">Active Goals</button>
<button @click="setSelectedComponent('manage-goals')">Manage Goals</button>
<!-- <active-goals v-if="selectedComponent === 'active-goals'"></active-goals>
<manage-goals v-if="selectedComponent === 'manage-goals'"></manage-goals> -->
<keep-alive>
<component :is="selectedComponent"></component>
</keep-alive>
<!-- above is a dynamic component. this is a good way to set toggleable components. -->
<!-- keep-alive is used to preserve an otherwise destroyed component's state, so if we toggle between the two, an input field's info wouldnt be lost for example-->
</div>
</template>
<script>
import TheHeader from "./components/TheHeader.vue";
// import BadgeList from "./components/BadgeList.vue";
// import UserInfo from "./components/UserInfo.vue";
// import CourseGoals from "./components/CourseGoals.vue";
import ActiveGoals from "./components/ActiveGoals.vue";
import ManageGoals from "./components/ManageGoals.vue";
export default {
components: {
//this is how to register local components.
TheHeader,
ActiveGoals,
ManageGoals,
},
data() {
return {
selectedComponent: "active-goals",
activeUser: {
name: "Maximilian Schwarzmüller",
description: "Site owner and admin",
role: "admin",
},
};
},
methods: {
setSelectedComponent(cmp) {
this.selectedComponent = cmp;
},
},
};
</script>
<style>
/* strangely enough, styles defined in ANY component are GLOBAL, even if not in app component */
/* if you do NOT want that to happen, and only have the style tag of a component apply to that one, use <style scoped/> */
html {
font-family: sans-serif;
}
body {
margin: 0;
}
</style>
|
import { styled, useTheme } from "@material-ui/core"
import { NotFound } from "modules/explorer/components/NotFound"
import { NotIndexed } from "modules/explorer/components/NotIndexed"
import { DAO } from "modules/explorer/pages/DAO/index"
import { User } from "modules/explorer/pages/User"
import React, { useContext, useEffect, useState } from "react"
import { useHistory } from "react-router"
import { Redirect, Route, RouteProps, Switch, useParams, useRouteMatch } from "react-router-dom"
import { Network } from "services/beacon"
import { useTezos } from "services/beacon/hooks/useTezos"
import { useDAO } from "services/services/dao/hooks/useDAO"
import { Navbar } from "../../components/Toolbar"
import { Config } from "../Config"
import { ProposalDetails } from "../ProposalDetails"
import { Proposals } from "../Proposals"
import { Registry } from "../Registry"
import { Treasury } from "../Treasury"
const PageLayout = styled("div")(({ theme }) => ({
background: theme.palette.primary.dark,
width: "1000px",
margin: "42px auto 0px auto",
["@media (max-width: 1425px)"]: {},
["@media (max-width:1335px)"]: {},
["@media (max-width:1167px)"]: {
width: "86vw"
},
["@media (max-width:1030px)"]: {},
["@media (max-width:960px)"]: {
marginTop: 0
}
}))
enum DAOState {
NOT_FOUND = 0,
NOT_INDEXED = 1,
FOUND = 2
}
const DAORouteContent: React.FC = ({ children }) => {
const daoId = useDAOID()
const { tezos, network, changeNetwork } = useTezos()
const { data, error } = useDAO(daoId)
const [state, setState] = useState<DAOState>(DAOState.FOUND)
const history = useHistory()
useEffect(() => {
;(async () => {
if (!data && !!error) {
try {
await tezos.contract.at(daoId)
setState(DAOState.NOT_INDEXED)
} catch (e) {
setState(DAOState.NOT_FOUND)
}
}
})()
}, [data, error, daoId, tezos.contract])
useEffect(() => {
if (history && data && data.data.network.toLowerCase() !== network.toLowerCase()) {
changeNetwork(data.data.network.toLowerCase() as Network)
}
}, [data, history, network, changeNetwork])
return (
<>
{state === DAOState.NOT_FOUND ? (
<NotFound />
) : state === DAOState.NOT_INDEXED ? (
<NotIndexed address={daoId} />
) : (
children
)}
</>
)
}
const DAORoute: React.FC<RouteProps> = ({ children, ...props }) => {
return (
<Route {...props}>
<DAORouteContent>{children}</DAORouteContent>
</Route>
)
}
const DAOContext = React.createContext("")
const DAOProvider: React.FC<{ daoId: string }> = ({ daoId, children }) => {
return <DAOContext.Provider value={daoId}>{children}</DAOContext.Provider>
}
export const useDAOID = () => {
return useContext(DAOContext)
}
export const DAORouter = (): JSX.Element => {
const match = useRouteMatch()
const theme = useTheme()
const { id: daoId } = useParams<{ id: string }>()
return (
<DAOProvider daoId={daoId}>
<Navbar />
<PageLayout>
<Switch>
<DAORoute path={`${match.url}/proposal/:proposalId`}>
<ProposalDetails />
</DAORoute>
<DAORoute path={`${match.url}/proposals`}>
<Proposals />
</DAORoute>
<DAORoute path={`${match.url}/treasury`}>
<Treasury />
</DAORoute>
<DAORoute path={`${match.url}/registry`}>
<Registry />
</DAORoute>
<DAORoute path={`${match.url}/user`}>
<User />
</DAORoute>
<DAORoute path={`${match.url}/config`}>
<Config />
</DAORoute>
<DAORoute path={`${match.url}/overview`}>
<DAO />
</DAORoute>
<Redirect from={`${match.url}`} to={`${match.url}/overview`} />
</Switch>
</PageLayout>
</DAOProvider>
)
}
|
import base64
import datetime
import random
import string
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from kanban.models.user import User, OTP
from rest_framework.authtoken.models import Token
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication
from rest_framework import status
class AuthorizationView(GenericAPIView):
def post(self, requests):
data = requests.data
if 'phone' not in data or not data['phone']:
return Response({"Error": "Enter phone"}, status=status.HTTP_400_BAD_REQUEST)
if 'password' not in data or not data['password']:
return Response({"Error": "Enter Password"}, status=status.HTTP_400_BAD_REQUEST)
if User.objects.filter(phone=int(data['phone'])).exists():
return Response({
"Error": "This phone exists"
}, status=status.HTTP_400_BAD_REQUEST)
password = data['password']
if len(password) < 6 or not any(char.isdigit() for char in password) or not any(
char.isalpha() for char in password):
return Response({
"Error": "Invalid Password"
}, status=status.HTTP_406_NOT_ACCEPTABLE)
user_data = {
'phone': data['phone'],
'password': password,
}
if data.get('key', None) == 'admin':
user_data.update({
"is_staff": True,
"is_superuser": True
})
user = User.objects.create_user(**user_data)
token = Token.objects.create(user=user)
return Response({"success": "You have successfully registered", "user_id": user.id, "token": token.key},
status=status.HTTP_200_OK)
class LoginView(GenericAPIView):
def post(self, requests):
data = requests.data
if "phone" not in data or not data["phone"]:
return Response({"Error": "Phone number is missing"}, status=status.HTTP_400_BAD_REQUEST)
if "password" not in data or not data['password']:
return Response({"Error": "Password is missing"}, status=status.HTTP_400_BAD_REQUEST)
user = User.objects.filter(phone=data['phone']).first()
if not user:
return Response({"Error": "User is not Found"}, status=status.HTTP_404_NOT_FOUND)
if not user.check_password(data['password']):
return Response({"Error": "Incorrect Password"}, status=status.HTTP_404_NOT_FOUND)
token = Token.objects.get_or_create(user=user)[0]
return Response({
"Success": token.key
})
class LogoutView(GenericAPIView):
authentication_classes = TokenAuthentication,
permission_classes = IsAuthenticated,
def post(self, request):
token = Token.objects.filter(user=request.user).first()
if token:
token.delete()
return Response({
"Success": "You have successfully loged out"
}, status=status.HTTP_200_OK)
class UserActions(GenericAPIView):
authentication_classes = TokenAuthentication,
permission_classes = IsAuthenticated,
def get(self, request):
return Response({
"success": request.user.format()
})
def put(self, request):
data = request.data
if 'phone' in data:
user = User.objects.filter(phone=data['phone']).first()
if user and user.id != request.user.id:
return Response({
"Error": "This phone number is already exists"
})
request.user.phone = data.get('phone', request.user.phone)
request.user.save()
return Response({
"Success": request.user.format()
}, status=status.HTTP_200_OK)
def post(self, request):
data = request.data
if 'old' not in data or 'new' not in data:
return Response({
"Error": "Enter the Password"
}, status=status.HTTP_401_UNAUTHORIZED)
if not request.user.check_password(data['old']):
return Response({
"Error": "Old password Does not match"
}, status=status.HTTP_400_BAD_REQUEST)
if request.user.check_password(data['new']):
return Response({
"Error": "Your New password is same with Old one"
}, status=status.HTTP_406_NOT_ACCEPTABLE)
request.user.set_password(data['new'])
request.user.save()
return Response({
"Success": "Your Password has been updated"
}, status=status.HTTP_200_OK)
def delete(self, request):
request.user.delete()
return Response({"Success": "Your Account has been deleted"})
class AuthOne(GenericAPIView):
def post(self, request):
data = request.data
if 'phone' not in data:
return Response({"Error": "Enter phone number"})
phone = User.objects.filter(phone=data['phone']).first()
if phone:
return Response({"Error": "This phone number is already registered"})
code = random.randint(100000, 999999)
random_string1 = ''.join(random.choice(string.digits + string.ascii_letters + string.digits) for i in range(20))
encode_code = f"{random_string1}${str(code)}${random_string1}"
encoded_value = base64.b64encode(encode_code.encode()).decode()
otp = OTP.objects.create(key=encoded_value, phone=data['phone'])
return Response({"OTP": code,
"Token": encoded_value})
class AuthTwo(GenericAPIView):
def post(self, request):
data = request.data
if 'otp' not in data or 'token' not in data:
return Response({"Error": "Information is not fully provided"}, status=status.HTTP_404_NOT_FOUND)
token = OTP.objects.filter(key=data['token']).first()
if not token:
return Response({"Error": "Token Error"})
if token.is_expired:
return Response({"Error": "token expired"})
if token.is_confir:
return Response({"Error": "Invalid Token"})
now = datetime.datetime.now(datetime.timezone.utc)
if (now - token.created).total_seconds() >= 3000:
token.is_expired = True
token.save()
return Response({"Error": "Token Has Expired"})
decoded_encoded_otp = base64.b64decode(token.key).decode()
decoded_code = decoded_encoded_otp.split('$')[1]
if decoded_code != str(data['otp']):
token.tries += 1
token.save()
return Response({"Error": "Incorrect Code"})
token.is_confir = True
token.save()
return Response({"OTP": decoded_code,
"Success": "Welcome"})
|
function f1 = figoverlay(varargin)
%
% Put 2 plots over each other in 2 layers
% This function can be used recursively to overlay 3 or more plots into a single one.
% - By default, the output figure gets adjusted by dynammo.plot.A4() inside figcombine() to make PDF printing easier
% - It is important to use 'A4' property for the final overlaid figure, otherwise pdfgen() will reprocess the figure one more time
%
% Should fig2, fig3, ... fields exist in either of the input figures, only the first will be processed, the rest will be ignored
%
% INPUT: fig1 ...object structure resulting from plot()
% fig2 ...object structure resulting from plot()
%
% OUTPUT: f1 ...fig1 laid over fig2
%
%
% >> Project Dyn:Ammo - EUROSTAT module, release 2019-Jan-30
% >> Written by: Jakub Rysanek
%
% keyboard;
p = inputParser;
addRequired(p,'fig1');
addRequired(p,'fig2');
if dynammo.compatibility.isAddParameter
addParameter(p,'yright',0,@(x) any(x==[0;1]));% See explanation below in Vert. limit section
addParameter(p,'toplayer',1,@(x) any(x==[1;2]));
addParameter(p,'mapping','linmap',@(x) any(validatestring(x,{'linmap','minmax','exact'})));
addParameter(p,'legend_merge',1,@(x) any(x==[0;1]));
addParameter(p,'xlabels','Y',@(x) any(validatestring(x,{'Y','Q','M','D'})));
addParameter(p,'maxticks',0,@(x) isscalar(x) && isa(x,'double'));
addParameter(p,'clone',0,@(x) any(x==[0;1]));
addParameter(p,'scaling',1,@(x) length(x)<=2);
%addParameter(p,'reuse',0,@(x) x==0);% Use 'clone' instead, re-using does not make sense
% figcombine() options
addParameter(p,'A4','dont',@(x) any(strcmpi(x,dynammo.plot.A4types())));
addParameter(p,'suptitle','',@ischar);% 'suptitle' gets usually inherited from fig1
else
addParamValue(p,'yright',0,@(x) any(x==[0;1]));% See explanation below in Vert. limit section
addParamValue(p,'toplayer',1,@(x) any(x==[1;2]));
addParamValue(p,'mapping','linmap',@(x) any(validatestring(x,{'linmap','minmax','exact'})));
addParamValue(p,'legend_merge',1,@(x) any(x==[0;1]));
addParamValue(p,'xlabels','Y',@(x) any(validatestring(x,{'Y','Q','M','D'})));
addParamValue(p,'maxticks',0,@(x) isscalar(x) && isa(x,'double'));
addParamValue(p,'clone',0,@(x) any(x==[0;1]));
addParamValue(p,'scaling',1,@(x) length(x)<=2);
%addParamValue(p,'reuse',0,@(x) x==0);% Use 'clone' instead, re-using does not make sense
% figcombine() options
addParamValue(p,'A4','dont',@(x) any(strcmpi(x,dynammo.plot.A4types())));
addParamValue(p,'suptitle','',@ischar);% 'suptitle' gets usually inherited from fig1
end
p.parse(varargin{:});
args = p.Results;
% Not to be changed
args.reuse = 0;
% Swap inputs if fig2 is the main fig
if args.toplayer==1
f1 = args.fig1;
f2 = args.fig2;
else
f2 = args.fig1;
f1 = args.fig2;
end
%% Temporary deletion of GUI tools
% -> tsobj/plot() results should be a struct object
% -> Matlab plots are either in double format (2014b-), or in matlab.ui.Figure object class (2014b+)
% keyboard;figdebug()
if isstruct(f1)
if isfield(f1,'sub')
f1_naked_han = f1.fig;
elseif isfield(f1,'fig1')
f1_naked_han = f1.fig1.handle;
else
disp('Unresolved situation...');
keyboard;
end
if isfield(f2,'sub')
f2_naked_han = f2.fig;
elseif isfield(f2,'fig1')
f2_naked_han = f2.fig1.handle;
else
disp('Unresolved situation...');
keyboard;
end
else
f1_naked_han = f1;% 2014b+ compatible
f2_naked_han = f2;% 2014b+ compatible
end
isMenu_f1 = get(f1_naked_han,'MenuBar');% 2014b+ compatible
isMenu_f2 = get(f2_naked_han,'MenuBar');% 2014b+ compatible
set(f1_naked_han,'MenuBar','none','ToolBar','none');
set(f2_naked_han,'MenuBar','none','ToolBar','none');
% isMenu = get(f1,'MenuBar');
% set(fhan,'MenuBar','none','ToolBar','none');
%% Deal with regular Matlab figures on input
% -> here we process 2014b+ figures as well (class is matlab.ui.Figure, not struct, not double)
if ~isstruct(f1)
f1 = dynammo.plot.gcf2obj(f1);
end
if ~isstruct(f2)
f2 = dynammo.plot.gcf2obj(f2);
end
% keyboard;figdebug()
%% Translate non-standard input
% - this is needed for all plots generated by simple plot command (1 subplot only via plot1tsobj)
% - Required structure for the rest of this function:
% gobj.fig1.handle: 2
% fig1.sub1.handle: 405.0297
% .data: {[407.0297]}
% .legend: 408.0319
% .emphasized: {[406.0297]}
% .diffs: 402.0742
% .title: 403.0742
% fig1.suptitle: 23.08
%
% This structure should be passed in as argument, if not
% "gobj_transform" can try to reconstruct it from the the given input
f1 = correct_obj_structure(f1);
f2 = correct_obj_structure(f2);
% Plus f2 cannot contain more than 1 subplot (diffs in a separate subplot are allowed)
if isfield(f2,'sub2')
error_msg('Figure overlay','2nd input cannot contain more than 1 subplot...');
end
% Undock all figures (docked mode disallowed due to freedom in positioning)
set(f1.handle,'WindowStyle','normal');% 'normal'|'docked'
set(f2.handle,'WindowStyle','normal');% 'normal'|'docked'
%% Create identical copies of the original figures
% keyboard;figdebug()
if args.clone==1
if isempty(args.suptitle)
f1 = figclone(f1);
f2 = figclone(f2);
else
warning_msg('figoverlay()','Cloning with a new suptitle is not recommended, suptitle is by default inherited from fig1...');
f2 = figclone(f2);
f1 = figclone(f1);% Suptitle works on f1, we need to touch it as last! Activation command would make it visible...
% However, switching the order may result in fighandles that do not form a consecutive series
% and postprocessing of the result may be hard to accomplish (last time sub5.legend suddenly became sub4.legend after figcombine() step)
end
end
%% Super title
% keyboard;figdebug()
% Input options consistency
if strcmpi(args.A4,'dont') && ~isempty(args.suptitle)
if isfield(f1,'suptitle')
set(f1.suptitle,'string',args.suptitle);
else
% Create a new super title
f1.suptitle=dynammo.plot.suptitle(f1.handle,args.suptitle);
end
else
% in 'landscape'/'portrait' mode the suptitle will be handled inside figcombine()
end
% Redundant 2nd fig. super title
% - this portion of code must be after the clones get created...
if isfield(f2,'suptitle')
%warning_msg('Figure overlay','''suptitle'' from 2nd input will be ignored ...');
delete(f2.suptitle)
f2 = rmfield(f2,'suptitle');
end
%% Apply transparent background for all f1 contents
nsubs = length(sublist(fieldnames(f1),'sub','<'));
for isub = 1:nsubs
%set(f1.(sprintf('sub%.0f',isub)).handle,'color','none');
ax = findobj(f1.handle,'Type','Axes');% -> we need all axes objects, e.g. diffs columns are not in subx format
set(ax,'Color','none');
end
% Current f1 contents
ch = get(f1.handle,'children');
nch = length(ch);% -> including legend, but does not matter
%% Moving f2->f1
% Current f2 contents
ch2 = get(f2.handle,'children');% Including diffs
ch2_incl_legend = ch2;
% keyboard;figdebug()
% Moving step
leg_to_delete = 0;
for ik = length(ch2):-1:1
if ~strcmpi(get(ch2(ik),'Tag'),'legend') && ...
~strncmpi(get(ch2(ik),'Type'),'ui',2)
% >>> M2014b+ fix for legend [part 1/3]
if ~isempty(getappdata(ch2(ik),'LegendPeerHandle')) || ...
~isempty(getappdata(ch2(ik),'LayoutPeers')) % M2016b+ change :( [1/2]
leg_to_delete = ik;
end
% <<<
set(ch2(ik),'parent',f1.handle); %set(f2.sub1.handle,'parent',f1.handle);
else
% Delete legend from the list of children
ch2(ik) = [];
end
end
% >>> M2014b+ fix for legend [part 3/3]
% We must save the legend entries before we destroy the object
if isfield(f2.sub1,'legend') && args.legend_merge==1
lg2 = get(f2.sub1.legend,'UserData');
if args.clone==1
% if iscell(lg2.handles)
% lg2handles = cellfun(@double,lg2.handles{1}(:));% We only retain half1 for legend, legend clicks requiring both half planes are no longer supported
% else
lg2handles = lg2.handles(:);% Already converted to handles in gobj_generate()
% end
else
if iscell(lg2.handles)
lg2handles = double(lg2.handles{1}(:));% We only retain half1 for legend, legend clicks requiring both half planes are no longer supported
else
lg2handles = lg2.handles(:);
end
end
lg2strings = lg2.lstrings(:);
end
if leg_to_delete>0
% It may have been deleted by the user, getappdata() does not use fresh listeners
try %if isappdata(ch2_incl_legend(leg_to_delete),'LegendPeerHandle')
delete(getappdata(ch2_incl_legend(leg_to_delete),'LegendPeerHandle'));
end
try % M2016b+ change :( [2/2]
delete(getappdata(ch2_incl_legend(leg_to_delete),'LayoutPeers'));
end
end
% <<<
nch2= length(ch2);
%% Horizontal limits
% keyboard;figdebug()
try
xlims1 = get(f1.sub1.handle,'Xlim');% All other layers were treated previously, here only the top layer relevant
xlims2 = get(f2.sub1.handle,'Xlim');% Top layer will serve as benchmark (diffs have the same xlims)
catch
error_msg('Figure overlay',['It looks like there is a non-standard plot on input, ' ...
'"sub/sub1" fields in the input structures are mandatory...']);
end
xlims = [min(xlims1(1),xlims2(1)) max(xlims1(2),xlims2(2))];
% For each axes object apply the same xlims
for isub = 1:nsubs
%set(f1.(['sub' sprintf('%.0f',isub)]).handle,'xlim',xlims);
set(f1.(sprintf('sub%.0f',isub)).handle,'Xlim',xlims);
end
% 2nd figure, possibly including 'diffs' object
if strcmpi(args.mapping,'exact')
yticks_inherited = get(ch2(1),'ytick');
end
for ich = 1:nch2
set(ch2(ich),'xlim',xlims, ...
'xtick',[], ...
'ytick',[], ... first we delete all yticks, later we apply the yscale just to 1 graph
'Box','off', ...
'ygrid','off');%f2.sub1.handle
end
% keyboard;
% X labels
kids = get(f1.sub1.handle,'children');
tind = [];
if ~isempty(kids)
ntind = Inf;
for ii = 1:length(kids)
%try % some kids do not have 'xdata'
if isfield(get(kids(ii)),'XData')
if strcmpi(get(kids(ii),'Type'),'line') % Bars usually have sum line, other types not relevant hopefully
xdata_now = get(kids(ii),'XData');
if ntind>length(xdata_now)
tind = xdata_now;
ntind = length(tind);
end
end
end
%end
end
else
% 1 line graphs have XData directly in gca
tind = get(f1.sub1.handle,'XData');
end
if isempty(tind)
error_msg('figoverlay()','Horizontal Xticks could not be identified from the input graph handles...');
end
diffs = tind(2:end)-tind(1:end-1);
mindiff = min(diffs(:));
% Determine frequency
if mindiff<0.003
freq = 'D';
elseif mindiff<0.09
freq = 'M';
elseif mindiff<0.26 % 0.25 exactly in this case
freq = 'Q';
else
freq = 'Y';
end
% keyboard;figdebug()
[xticks,xlabels] = figlabels(freq,xlims,args.maxticks);
set(f1.sub1.handle,'xtick',xticks,'xticklabel',xlabels);% To be applied to the top layer only
%% Vertical limits
% - args.yright: 0 -> right axis on input stays right, left stays left
% 1 -> all axes objects go to the right
% Lists of subplots with axes located right/left
left = cell(nsubs+nch2,1);
right = cell(nsubs+nch2,1);
ylims_left = [Inf -Inf];% +- ordering on purpose!
ylims_right = [Inf -Inf];% +- ordering on purpose!
for isub = 1:nsubs
%ylims_now = get(f1.(['sub' sprintf('%.0f',isub)]).handle,'ylim');
ylims_now = get(f1.(sprintf('sub%.0f',isub)).handle,'ylim');
%if strcmpi('right',get(f1.(['sub' sprintf('%.0f',isub)]).handle,'yaxislocation'))
if strcmpi('right',get(f1.(sprintf('sub%.0f',isub)).handle,'yaxislocation'))
if isub~=1
%right{isub,1} = f1.(['sub' sprintf('%.0f',isub)]).handle;
right{isub,1} = f1.(sprintf('sub%.0f',isub)).handle;
ylims_right(1) = min(ylims_right(1),ylims_now(1));
ylims_right(2) = max(ylims_right(2),ylims_now(2));
else
error_msg('Figure overlay','The first graph must have the vertical axis on the left...');
end
else
%left{isub,1} = f1.(['sub' sprintf('%.0f',isub)]).handle;
left{isub,1} = f1.(sprintf('sub%.0f',isub)).handle;
ylims_left(1) = min(ylims_left(1),ylims_now(1));
ylims_left(2) = max(ylims_left(2),ylims_now(2));
end
end
% 2nd figure, possibly including 'diffs' object
for ich = 1:nch2
ylims_now = get(ch2(ich),'ylim');
if args.yright
right{ich+nsubs,1} = ch2(ich);
ylims_right(1) = min(ylims_right(1),ylims_now(1));
ylims_right(2) = max(ylims_right(2),ylims_now(2));
else
if strcmpi('right',get(ch2(ich),'yaxislocation'))
right{ich+nsubs,1} = ch2(ich);
ylims_right(1) = min(ylims_right(1),ylims_now(1));
ylims_right(2) = max(ylims_right(2),ylims_now(2));
else
left{ich+nsubs,1} = ch2(ich);
ylims_left(1) = min(ylims_left(1),ylims_now(1));
ylims_left(2) = max(ylims_left(2),ylims_now(2));
end
end
end
% Drop empty entries
right = right(~cellfun('isempty',right));
left = left( ~cellfun('isempty',left));
% Adjust limits on all left axes
for ii = 1:length(left)
set(left{ii},'ylim',ylims_left);
end
% set(left{1},'ytick',ylims_left);% AUTO!!!
if ~isempty(right)
if ~strcmpi(args.mapping,'exact')
yticks_left = get(left{1},'ytick');
[ymin_right,ymax_right,ticks_right] = dynammo.plot.right_axis_tick_mapping(ylims_left,yticks_left,ylims_right);
if strcmpi(args.mapping,'minmax')
ticks_right = [ticks_right(1) ticks_right(end)];
end
for ich = 1:length(right)
set(right{ich}, ...
'ylim',[ymin_right ymax_right], ...
'yaxislocation','right');% f2.sub1.handle
end
set(right{1},'ytick',ticks_right);
else
for ich = 1:length(right)
set(right{ich}, ...
'yaxislocation','right');% f2.sub1.handle
end
set(right{1},'ytick',yticks_inherited);
end
end
%% Object ordering
% keyboard;figdebug()
set(f1.handle,'children',cat(1,ch(:),ch2(:))); %f2.sub1.handle
%% Plug back the GUI tools (if these were initially present)
% keyboard;figdebug()
if strcmpi(isMenu_f1,'figure')
set(f1_naked_han,'MenuBar','figure','ToolBar','figure');
pushbuttons(f1_naked_han);% Needed in visualization_tutorial()
% Clone too
if args.clone==1
set(f1.handle,'MenuBar','figure','ToolBar','figure');
pushbuttons(f1.handle);
end
end
if strcmpi(isMenu_f2,'figure')
%<Empty figure>
%set(f2_naked_han,'MenuBar','figure','ToolBar','figure');
%pushbuttons(f2_naked_han);
% Clone too
if args.clone==1
set(f2.handle,'MenuBar','figure','ToolBar','figure');
pushbuttons(f2.handle);
end
end
%% Legend
% keyboard;%figdebug()
if isfield(f1.sub1,'legend')
lg1 = get(f1.sub1.legend,'UserData');
if args.clone==1
% if iscell(lg1.handles)
% lghandles = cellfun(@double,lg1.handles{1}(:));% Only half1 for bars
% else
lghandles = lg1.handles(:);% Already converted to handles in gobj_generate()
% end
else
if iscell(lg1.handles)
lghandles = double(lg1.handles{1}(:));% Only half1 for bars
else
lghandles = lg1.handles(:);
end
end
lgstrings = lg1.lstrings(:);
% Data envelope
if isfield(lg1,'convHull') % M2014b+
convHull = lg1.convHull;
else % M2014b-
convHull = dynammo.plot.convexHull_legacy2014b(f1.sub1.handle);
end
% Delete previous legend
delete(f1.sub1.legend);
else
lgstrings = [];
lghandles = [];
convHull = [];
end
if isfield(f2.sub1,'legend') && args.legend_merge==1
% >>> M2014b+ fix for legend [part 2/3]
%lg2 = get(f2.sub1.legend,'UserData');
lghandles = cat(1,lghandles,lg2handles);%lg2.handles(:));
lgstrings = cat(1,lgstrings,lg2strings);%lg2.lstrings(:));
% <<<
% Data envelope
if isfield(lg2,'convHull') % M2014b+
convHull = [convHull;lg2.convHull];
else % M2014b-
convHull = [convHull; ...
dynammo.plot.convexHull_legacy2014b(f2.sub1.handle)];
end
end
set(0,'currentfigure', f1.handle);
% lghandles = cat(1,lg1.handles(:),lg2.handles(:));
% lgstrings = cat(1,lg1.lstrings(:),lg2.lstrings(:));
if ~isempty(lghandles)
if ~dynammo.compatibility.M2016a
[lg,entries] = legend(lghandles,lgstrings);
set(lg,'color',[1 1 1]);
% <convHull already created>
% Mouse clicks
% if strcmpi(get(f1.handle,'visible'),'on')
%
% tmp = get(lg,'Userdata');
% for ient = 1:size(tmp.handles,1)
% item = get(tmp.handles(ient));
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if isfield(item,'Color') % Probably line ('Color' may be shared across more objects)
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% colors = get(tmp.handles(ient),'Color');
% set(entries(ient), 'HitTest', 'on', 'ButtonDownFcn',...
% @(varargin) legendClick(ient,entries,colors,f1.sub1.data), ...
% 'UserData', true);
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% elseif isfield(item,'FaceColor') % bars have 'FaceColor' property
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set(entries(ient), 'HitTest', 'on', 'ButtonDownFcn',...
% @(varargin) legendClick(ient,entries,[],f1.sub1.data{1},f1.sub1.data{2}), ...
% 'UserData', true);
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% else % Unexpected situation
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% error_msg('Figoverlay','Untreated situation occurred...');
%
% end
% end
%
% end
%%%%%%%%%%%%%%%%%%%%%
else % M2016a+
%%%%%%%%%%%%%%%%%%%%%
% if iscell(lghandles) % -> bar graph
% lg = legend(lghandles{1},lgstrings);% only 1st half of handles assumed
% lg.UserData.handles = {f1.sub1.data{1};f1.sub1.data{2}};
% else % -> line graph
lg = legend(lghandles,lgstrings);
lg.UserData.handles = double(lg.PlotChildren(:));
% end
set(lg,'color',[1 1 1]);
lg.UserData.lstrings = lg.String(:);
%lg.UserData.LabelHandles = entries;
lg.UserData.PlotHandle = f1.sub1.handle;% Note that this field is not linked as a listener when the value changes
% -> gobj_generate() uses it, but it should work
%lghandle.UserData.LegendPosition -> better to take it directly from legend handle (it is connected to listeners, when units/pos change)
% Data envelope (convex hull)
lg.UserData.convHull = convHull;
% Mouse clicks
% if strcmpi(get(f1.handle,'visible'),'on')
% set(lg,'ItemHitFcn',@lgndItemClick);
% end
end
% Otherwise legend positioning via figcombine()
%drawnow;
if ~strcmpi(args.A4,'dont')
legend_best2(f1.sub1.handle,lg,'ban_injection');
end
else
lg = '';
end
% Delete previously generated legend
% delete(f1.legend);
%% Align positioning of figures
axesPosition = get(f1.sub1.handle,'Position');
% Round #1 - to locate the legend properly
for isub = 1:nsubs
%set(f1.(['sub' sprintf('%.0f',isub)]).handle, 'Position',axesPosition);
set(f1.(sprintf('sub%.0f',isub)).handle, 'Position',axesPosition);
%if isfield(f1.(['sub' sprintf('%.0f',isub)]),'diffs')
if isfield(f1.(sprintf('sub%.0f',isub)),'diffs')
%set(f1.(['sub' sprintf('%.0f',isub)]).diffs.axis, 'Position',axesPosition);
set(f1.(sprintf('sub%.0f',isub)).diffs.axis, 'Position',axesPosition);
end
end
for ich = 1:length(ch2)
set(ch2(ich),'Position',axesPosition);% diffs are included in ch2
end
% set(lg,'Position',get(lg,'Position') + [0.05 0 0 0]);
% Round #2 - to fix the position of graphs
% set(ghandle, 'Position',axesPosition);
% set(f2.sub,'Position',axesPosition);
%% Destroy original graph (it can also be a clone)
close(f2.handle);
%% Update object structure
% - <gobj> taken for tsobj() input
% - non-tsobj() input => should always be converted into tsobj in terms of the X axis
%
% outstr.fig1.handle
% outstr.fig1.sub1.handle
% outstr.fig1.sub1.data
% [outstr.fig1.sub1.legend]
% [outstr.fig1.sub1.diffs] ...diffs stores both axis/data handles, but is nested in sub1 structure
% [outstr.fig1.sub1.emphasized]
% [outstr.fig1.sub1.title]
% [outstr.fig1.sub1.highlighted]
% [outstr.fig1.suptitle]
f1.(sprintf('sub%.0f',nsubs+1)).handle = f2.sub1.handle;
if isfield(f2.sub1,'data') % -> Regular Matlab figures do not have this field specified
f1.(sprintf('sub%.0f',nsubs+1)).data = f2.sub1.data;
end
if ~isempty(lg)
f1.sub1.legend = lg;% Only in the top-most subplot
end
% Object shuffling
rest_ = fieldnames(f2.sub1)-{'handle';'data';'legend'};% 'suptitle' automatically inherited from fig1, if exists
if ~isempty(rest_)
for ii = 1:length(rest_)
f1.(sprintf('sub%.0f',nsubs+1)).(rest_{ii}) = f2.sub1.(rest_{ii});
% [xxx] Update ylimits for patch (highlight) objects (lower layer figure)
if strcmpi(rest_{ii},'highlighted')
highs = f1.(sprintf('sub%.0f',nsubs+1)).highlighted;
for ih = 1:length(highs)
correct_ylims = get(get(highs{ih},'parent'),'ylim');
set(highs{ih},'ydata',[correct_ylims(1)*ones(1,2) correct_ylims(2)*ones(1,2)]);
end
end
end
end
% [xxx] Update ylimits for patch (highlight) objects (top layer figure)
% -> only the top sub1 necessary to check here, the rest checked while appending new figures
if isfield(f1.sub1,'highlighted')
highs = f1.sub1.highlighted;
for ih = 1:length(highs)
correct_ylims = get(get(highs{ih},'parent'),'ylim');
set(highs{ih},'ydata',[correct_ylims(1)*ones(1,2) correct_ylims(2)*ones(1,2)]);
end
end
%% Final output
ftmp.fig1 = f1;
f1 = ftmp;
% Paper positioning via figcombine()
if ~strcmpi(args.A4,'dont')
% Cloning of already cloned figures does not make sense
f1 = figcombine({f1},'clone',0,'suptitle',args.suptitle,'A4',args.A4,'ban_injection',1);
else
% At least set the correct tag
set(f1.fig1.handle,'Tag','figready_dont');
end
%% Rescale fig2 subplot area
% -> legend moves fig1, but leaves fig2 where it was prior to legend location fiddling
% keyboard;figdebug()
pos1 = get(f1.fig1.sub1.handle,'position');
pos2 = get(f1.fig1.sub2.handle,'position');
pos2(3) = pos1(3);
set(f1.fig1.sub2.handle,'position',pos2);
%% Make axes invisible
set(f1.fig1.sub2.handle,'xcolor',[1 1 1]);%,'ycolor',[1 1 1]);
%% Nested functions
function obj_ok = correct_obj_structure(obj_in)
if isfield(obj_in,'sub')
% f1 is a simple plot (1 subplot only)
obj_ok = dynammo.plot.gobj_transform(obj_in);%correct_obj_structure(f1);
obj_ok = obj_ok.fig1;
elseif isfield(obj_in,'fig1')
obj_ok = obj_in.fig1;
elseif isfield(obj_in,'handle')
obj_ok = obj_in; % already in correct format
else
error_msg('Figure overlay','Weird input, must be a structure generated by plot()...');
end
end %<correct_obj_structure>
end %<eof>
|
package com.example.blogapi.controller;
import com.example.blogapi.dto.TagDto;
import com.example.blogapi.service.interfaces.TagService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
@WebMvcTest(controllers = TagController.class)
@AutoConfigureMockMvc(addFilters = false)
@ExtendWith(MockitoExtension.class)
class TagControllerTest {
private static final String URL = "/api/v1/tags";
@Autowired
private MockMvc mockMvc;
@MockBean
private TagService tagService;
@Autowired
private ObjectMapper objectMapper;
private TagDto tagDto;
private List<TagDto> tagDtos;
@BeforeEach
public void setUp() {
tagDto = TagDto.builder().id(1L).name("tag").build();
tagDtos = new ArrayList<>();
tagDtos.addAll(Arrays.asList(tagDto, tagDto));
}
@Test
public void TagController_CreateTag_ReturnIsOk() throws Exception {
when(tagService.createTag(Mockito.any(TagDto.class))).thenReturn(tagDto);
ResultActions response = mockMvc.perform(post(URL)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(tagDto)));
response.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.name", CoreMatchers.is(tagDto.getName())))
.andDo(MockMvcResultHandlers.print());
}
@Test
public void TagController_GetTagById_ReturnIsOk() throws Exception {
when(tagService.getTagById(Mockito.anyLong())).thenReturn(tagDto);
ResultActions response = mockMvc.perform(get(URL + "/1")
.contentType(MediaType.APPLICATION_JSON));
response.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.name", CoreMatchers.is(tagDto.getName())))
.andDo(MockMvcResultHandlers.print());
}
@Test
public void TagController_GetAllTags_ReturnIsOk() throws Exception {
when(tagService.getAllTags()).thenReturn(tagDtos);
ResultActions response = mockMvc.perform(get(URL)
.contentType(MediaType.APPLICATION_JSON));
response.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.size()", CoreMatchers.is(tagDtos.size())))
.andDo(MockMvcResultHandlers.print());
}
@Test
public void TagController_UpdateTag_ReturnIsOk() throws Exception {
when(tagService.updateTag(Mockito.anyLong(), Mockito.any(TagDto.class))).thenReturn(tagDto);
ResultActions response = mockMvc.perform(put(URL + "/1")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(tagDto)));
response.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.name", CoreMatchers.is(tagDto.getName())))
.andDo(MockMvcResultHandlers.print());
}
@Test
public void TagController_DeleteTag_ReturnIsOk() throws Exception {
when(tagService.deleteTag(Mockito.anyLong())).thenReturn(tagDto.getId().intValue());
ResultActions response = mockMvc.perform(delete(URL + "/1")
.contentType(MediaType.APPLICATION_JSON));
response.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$", CoreMatchers.is(tagDto.getId().intValue())))
.andDo(MockMvcResultHandlers.print());
}
}
|
import os
import argparse
from datetime import datetime
from tqdm.auto import tqdm
import wandb
import torch
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
BitsAndBytesConfig,
TrainingArguments,
pipeline,
)
from peft import LoraConfig, PeftModel
from trl import SFTTrainer
from data import (
make_dataset,
gen_train_prompt,
gen_test_prompt
)
MODEL_ID = "google/gemma-1.1-2b-it"
def define_config():
p = argparse.ArgumentParser()
p.add_argument("--model_name", required=True)
p.add_argument("--train_tsv_fn", required=True)
p.add_argument("--test_tsv_fn", type=str, default=None)
p.add_argument("--output_dir", required=True)
p.add_argument("--max_steps", type=int, default=2000)
p.add_argument("--lr", type=float, default=1e-4)
p.add_argument("--warmup_steps", type=int, default=0.03)
p.add_argument("--max_seq_length", type=int, default=512)
p.add_argument("--per_device_train_batch_size", type=int, default=2)
p.add_argument("--gradient_accumulation_steps", type=int, default=1)
p.add_argument("--logging_steps", type=int, default=100)
p.add_argument("--skip_wandb", action="store_true")
config = p.parse_args()
return config
def get_now():
return datetime.now().strftime("%Y%m%d-%H%M%S")
def wandb_init(config):
final_model_name = f"{config.model_name}-{get_now()}"
if config.skip_wandb:
return final_model_name
wandb.login()
wandb.init(
project="NLP_EXP_rnn_text_classification",
config=vars(config),
id=final_model_name,
)
wandb.run.name = final_model_name
wandb.run.save()
os.makedirs(config.output_dir, exist_ok=True)
return final_model_name
def main(config):
print(config)
# train dataset
train_dataset = make_dataset(config.train_tsv_fn)
# lora config
lora_config = LoraConfig(
r=6,
lora_alpha = 8,
lora_dropout = 0.05,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
task_type="CAUSAL_LM",
)
# bits and bytes config (4bit)
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16
)
# model
model = AutoModelForCausalLM.from_pretrained(MODEL_ID,
device_map="auto",
quantization_config=bnb_config)
# tokenizer
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID,
add_special_tokens=True)
tokenizer.padding_side = 'right'
final_model_name = wandb_init(config)
# trainer
trainer = SFTTrainer(
model=model,
train_dataset=train_dataset,
max_seq_length=config.max_seq_length,
args=TrainingArguments(
output_dir=os.path.join(config.output_dir, final_model_name),
# num_train_epochs = 1,
max_steps=config.max_steps,
per_device_train_batch_size=config.per_device_train_batch_size,
gradient_accumulation_steps=config.gradient_accumulation_steps,
optim="paged_adamw_8bit",
warmup_steps=config.warmup_steps,
learning_rate=config.lr,
# bf16=True,
fp16=True,
logging_steps=config.logging_steps,
push_to_hub=False,
report_to="wandb" if not config.skip_wandb else None,
),
peft_config=lora_config,
formatting_func=gen_train_prompt,
)
# train
trainer.train()
# save lora (delta weight)
trainer.model.save_pretrained("lora_adapter")
# original model load (before finetuned)
model = AutoModelForCausalLM.from_pretrained(MODEL_ID,
device_map='auto',
torch_dtype=torch.float16)
# merge : original + delta wieght
model = PeftModel.from_pretrained(model,
"lora_adapter",
device_map='auto',
torch_dtype=torch.float16)
model = model.merge_and_unload()
# save fine-tunned model
model.save_pretrained(os.path.join(config.output_dir, final_model_name, "checkpoint-final"))
if not config.test_tsv_fn is None:
# test dataset
test_dataset = make_dataset(config.test_tsv_fn)
# pipeline
pipe = pipeline("text-generation",
model=model,
tokenizer=tokenizer,
max_new_tokens=5)
# infer
total_sample_cnt, total_correct_cnt = 0, 0
for example in tqdm(test_dataset.iter(1)):
label = '긍정' if example['label'][0] == 1 else '부정'
prompt = gen_test_prompt(example)
outputs = pipe(
prompt,
do_sample=True,
temperature=0.2,
top_k=50,
top_p=0.95,
add_special_tokens=True
)
pred = outputs[0][0]['generated_text'][len(prompt[0]):]
total_sample_cnt += 1
total_correct_cnt += 1 if label == pred else 0
if total_sample_cnt >= 1000:
break
print(f"Test Accuracy: {total_correct_cnt} / {total_sample_cnt} = {total_correct_cnt/total_sample_cnt:.4f}")
if not config.skip_wandb:
wandb.log(
{
"test/accuracy": total_correct_cnt / total_sample_cnt * 100,
}
)
if not config.skip_wandb:
wandb.finish()
if __name__ == "__main__":
config = define_config()
main(config)
|
import { ModelAttributes, ModelOptions, DataTypes, literal } from 'sequelize';
import ModelData from './modelData.js';
const attributes: ModelAttributes = {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
validate: {
isInt: true
}
},
skuId: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
isInt: true
},
field: 'sku_id'
},
changedByUserId: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'changed_by_user_id'
},
changeType: {
type: DataTypes.STRING,
allowNull: false,
field: 'change_type'
},
changeDateTime: {
type: "TIMESTAMP",
allowNull: false,
defaultValue: literal("CURRENT_TIMESTAMP"),
field: 'change_date_time'
}
};
const options: ModelOptions = {
timestamps: false,
tableName: 'sku_changes_log',
}
export const skuLogMetaData: ModelData = {
modelName: 'SkuLog',
attributes: attributes,
options: options
};
export class SkuLog {
#id: number;
#skuId: number;
#changedByUserId: number;
#changeType: number;
#changeDateTime: Date;
constructor(productObject: any) {
this.#id = productObject.id ;
this.#skuId = productObject.skuId;
this.#changedByUserId = productObject.changedByUserId;
this.#changeType = productObject.changeType;
this.#changeDateTime = productObject.changeDateTime;
}
get skuLogResponse() {
return {
id: this.#id,
skuId: this.#skuId,
changedByUserId: this.#changedByUserId,
changeType: this.#changeType,
changeDateTime: this.#changeDateTime
}
}
static get links(): any[] {
return [
{
"href": `${process.env.API_URL}:${process.env.API_PORT}/logs/products`,
"rel": "products",
"type": "GET"
},
{
"href": `${process.env.API_URL}:${process.env.API_PORT}/logs/inventory`,
"rel": "inventory",
"type": "GET"
}
];
}
static createBatch(array: any[]): SkuLog[] {
let batch: SkuLog[] = [];
for (let object of array)
batch.push(new SkuLog(object));
return batch;
}
}
|
package jp.co.soramitsu.fearless_utils.runtime.definitions
import com.google.gson.annotations.SerializedName
import jp.co.soramitsu.fearless_utils.runtime.definitions.dynamic.DynamicTypeResolver
import jp.co.soramitsu.fearless_utils.runtime.definitions.registry.TypePreset
import jp.co.soramitsu.fearless_utils.runtime.definitions.registry.TypePresetBuilder
import jp.co.soramitsu.fearless_utils.runtime.definitions.registry.create
import jp.co.soramitsu.fearless_utils.runtime.definitions.registry.getOrCreate
import jp.co.soramitsu.fearless_utils.runtime.definitions.registry.newBuilder
import jp.co.soramitsu.fearless_utils.runtime.definitions.registry.type
import jp.co.soramitsu.fearless_utils.runtime.definitions.types.Type
import jp.co.soramitsu.fearless_utils.runtime.definitions.types.TypeReference
import jp.co.soramitsu.fearless_utils.runtime.definitions.types.composite.Alias
import jp.co.soramitsu.fearless_utils.runtime.definitions.types.composite.CollectionEnum
import jp.co.soramitsu.fearless_utils.runtime.definitions.types.composite.DictEnum
import jp.co.soramitsu.fearless_utils.runtime.definitions.types.composite.SetType
import jp.co.soramitsu.fearless_utils.runtime.definitions.types.composite.Struct
import jp.co.soramitsu.fearless_utils.runtime.definitions.types.skipAliasesOrNull
import java.math.BigInteger
class TypeDefinitionsTree(
@SerializedName("runtime_id")
val runtimeId: Int?,
val types: Map<String, Any>,
val versioning: List<Versioning>?,
val overrides: List<OverriddenItem>?
) {
class OverriddenItem(
val module: String,
val constants: List<OverriddenConstant>?
)
class OverriddenConstant(
val name: String,
val value: String
)
class Versioning(
@SerializedName("runtime_range") val range: List<Int?>,
val types: Map<String, Any>
) {
val from: Int
get() = range.first()!!
fun isMatch(v: Int): Boolean = (v >= from && range.size == 2) && ((range[1] == null) || (range[1] != null && range[1]!! >= v))
}
}
class ParseResult(
val typePreset: TypePreset,
val unknownTypes: List<String>
)
private const val TOKEN_SET = "set"
private const val TOKEN_STRUCT = "struct"
private const val TOKEN_ENUM = "enum"
object TypeDefinitionParser {
private class Params(
val types: Map<String, Any>,
val dynamicTypeResolver: DynamicTypeResolver,
val typesBuilder: TypePresetBuilder
)
fun parseBaseDefinitions(
tree: TypeDefinitionsTree,
typePreset: TypePreset,
dynamicTypeResolver: DynamicTypeResolver = DynamicTypeResolver.defaultCompoundResolver(),
getUnknownTypes: Boolean = false
): ParseResult {
val builder = typePreset.newBuilder()
val params = Params(tree.types, dynamicTypeResolver, builder)
parseTypes(params)
val unknownTypes = if (getUnknownTypes) params.typesBuilder.entries
.mapNotNull { (name, typeRef) -> if (!typeRef.isResolved()) name else null } else emptyList()
return ParseResult(params.typesBuilder, unknownTypes)
}
fun parseNetworkVersioning(
tree: TypeDefinitionsTree,
typePreset: TypePreset,
currentRuntimeVersion: Int = tree.runtimeId!!,
dynamicTypeResolver: DynamicTypeResolver = DynamicTypeResolver.defaultCompoundResolver(),
getUnknownTypes: Boolean = false,
upto14: Boolean = false
): ParseResult {
val versioning = tree.versioning
requireNotNull(versioning)
val builder = typePreset.newBuilder()
versioning.filter { it.isMatch(currentRuntimeVersion) }
.sortedBy(TypeDefinitionsTree.Versioning::from)
.forEach {
parseTypes(Params(it.types, dynamicTypeResolver, builder), !upto14)
}
val unknownTypes = if (getUnknownTypes) builder.entries
.mapNotNull { (name, typeRef) -> if (!typeRef.isResolved()) name else null } else emptyList()
return ParseResult(builder, unknownTypes)
}
private fun parseTypes(parsingParams: Params, doAliases: Boolean = false) {
for (name in parsingParams.types.keys) {
val type = parse(parsingParams, name, doAliases) ?: continue
parsingParams.typesBuilder.type(type)
}
}
private fun parse(parsingParams: Params, name: String, doAliases: Boolean): Type<*>? {
val typeValue = parsingParams.types[name]
return parseType(parsingParams, name, typeValue, doAliases)
}
private fun parseType(parsingParams: Params, name: String, typeValue: Any?, doAliases: Boolean): Type<*>? {
val typesBuilder = parsingParams.typesBuilder
return when (typeValue) {
is String -> {
val dynamicType = resolveDynamicType(parsingParams, name, typeValue)
when {
dynamicType != null -> dynamicType
typeValue == name -> parsingParams.typesBuilder[name]?.value
else -> {
val fromType = typesBuilder[name]
if (doAliases && fromType != null && fromType.value is Alias) {
val toTypeValue = typesBuilder[typeValue]?.skipAliasesOrNull()
val fromTypeValue = (fromType.value as Alias).aliasedReference
if (fromTypeValue.value != null) {
val aliasSkipped = fromTypeValue.skipAliasesOrNull()
if (toTypeValue != null && toTypeValue.value?.name != aliasSkipped?.value?.name) {
typesBuilder.type(Alias(fromTypeValue.value!!.name, typesBuilder.getOrCreate(typeValue)))
}
}
}
Alias(name, typesBuilder.getOrCreate(typeValue))
}
}
}
is Map<*, *> -> {
val typeValueCasted = typeValue as Map<String, Any?>
when (typeValueCasted["type"]) {
TOKEN_STRUCT -> {
val typeMapping = typeValueCasted["type_mapping"] as List<List<String>>
val children = parseTypeMapping(parsingParams, typeMapping)
Struct(name, children)
}
TOKEN_ENUM -> {
val valueList = typeValueCasted["value_list"] as? List<String>
val typeMapping = typeValueCasted["type_mapping"] as? List<List<String>>
when {
valueList != null -> CollectionEnum(name, valueList)
typeMapping != null -> {
val children = parseTypeMapping(parsingParams, typeMapping)
.map { (name, typeRef) -> DictEnum.Entry(name, typeRef) }
DictEnum(name, children)
}
else -> null
}
}
TOKEN_SET -> {
val valueTypeName = typeValueCasted["value_type"] as String
val valueListRaw = typeValueCasted["value_list"] as Map<String, Double>
val valueTypeRef = resolveTypeAllWaysOrCreate(parsingParams, valueTypeName)
val valueList = valueListRaw.mapValues { (_, value) ->
BigInteger(value.toInt().toString())
}
SetType(name, valueTypeRef, LinkedHashMap(valueList))
}
else -> null
}
}
else -> null
}
}
private fun parseTypeMapping(
parsingParams: Params,
typeMapping: List<List<String>>
): LinkedHashMap<String, TypeReference> {
val children = LinkedHashMap<String, TypeReference>()
for ((fieldName, fieldType) in typeMapping) {
children[fieldName] = resolveTypeAllWaysOrCreate(parsingParams, fieldType)
}
return children
}
private fun resolveDynamicType(
parsingParams: Params,
name: String,
typeDef: String
): Type<*>? {
return parsingParams.dynamicTypeResolver.createDynamicType(name, typeDef) {
resolveTypeAllWaysOrCreate(parsingParams, it)
}
}
private fun resolveTypeAllWaysOrCreate(
parsingParams: Params,
typeDef: String,
name: String = typeDef
): TypeReference {
return parsingParams.typesBuilder[name]
?: resolveDynamicType(parsingParams, name, typeDef)?.let(::TypeReference)
?: parsingParams.typesBuilder.create(name)
}
}
|
import * as Sentry from "@sentry/browser";
/**
* Simple util for logging to console.
*
* Ensure output level is set to 'verbose' to see debug logs.
*/
enum LogLevel {
ERROR,
WARNING,
INFO,
DEBUG,
}
export class Logger {
static debugMode = true;
tag = "";
constructor(tag: string) {
this.tag = tag;
}
debug(...messages: unknown[]) {
this.internalLog(LogLevel.DEBUG, ...messages);
}
log(...messages: unknown[]) {
this.internalLog(LogLevel.INFO, ...messages);
}
warn(...messages: unknown[]) {
this.internalLog(LogLevel.WARNING, ...messages);
}
error(...messages: unknown[]) {
this.internalLog(LogLevel.ERROR, ...messages);
}
internalLog(level: LogLevel, ...messages: unknown[]) {
const d = new Date(Date.now());
const output = [
"%c%s %s",
"color: blue",
`[${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}]`,
this.tag,
...messages,
];
if (!Logger.debugMode) {
switch (level) {
case LogLevel.WARNING:
case LogLevel.INFO:
Sentry.captureMessage(messages.join(" "));
break;
case LogLevel.ERROR:
Sentry.captureException(messages);
break;
}
return;
} else {
switch (level) {
case LogLevel.DEBUG:
console.debug(...output);
break;
case LogLevel.WARNING:
console.warn(...output);
break;
case LogLevel.INFO:
console.log(...output);
break;
case LogLevel.ERROR:
console.error(...output);
break;
}
}
}
}
if (!Logger.debugMode) {
Sentry.init({
dsn: "https://206eef5ac48842d3a461cdf79d1e75fc@o526305.ingest.sentry.io/4504727620943872",
tracesSampleRate: 0.1,
release: "reader-mode@23.01.10",
environment: "PROD",
});
}
|
import 'package:eve_test/routes/app_routes.dart';
import 'package:eve_test/screen/auth/bindings/login_binding.dart';
import 'package:eve_test/screen/auth/login_screen.dart';
import 'package:eve_test/screen/home/binding/main_binding.dart';
import 'package:eve_test/screen/home/main_screen.dart';
import 'package:eve_test/screen/home/profile/binding/profile_binding.dart';
import 'package:eve_test/screen/home/profile/profile_screen.dart';
import 'package:eve_test/screen/splash/binding/splash_binding.dart';
import 'package:eve_test/screen/splash/splash_screen.dart';
import 'package:get/get.dart';
class AppPages {
AppPages._();
static const INITIAL = Routes.SPLASH;
static final routes = [
GetPage(
name: Routes.SPLASH,
page: () => const SplashScreen(),
binding: SplashBinding(),
),
GetPage(
name: Routes.LOGIN,
page: () => const LoginScreen(),
binding: LoginBinding(),
),
GetPage(
name: Routes.HOME,
page: () => const MainScreen(),
binding: MainBinding(),
),
GetPage(
name: Routes.PROFILE,
page: () => const ProfileScreen(),
binding: ProfileBinding(),
),
];
}
|
// Módulo 7.2 - Ejercicio 5
import java.util.Scanner;
public class App {
public static void main(String[] args) {
int numElegido = pedirInt("Escribe un número entero:");
boolean primo = esPrimo(numElegido);
impresion(numElegido, primo);
} // Fin del método main
// -----------------------------------------------------------------------------------
// RESTO DE MÉTODOS
// método para pedir int
static int pedirInt(String msg) {
Scanner entrada = new Scanner(System.in);
System.out.println(msg);
return entrada.nextInt();
}
// método para calcular el módulo_i de un int
static int modulo_i(int paramNumElegido, int param_i) {
return paramNumElegido%param_i;
}
// método para averiguar si un número es primo
static boolean esPrimo(int paramNumElegido) {
boolean primo=true;
if (paramNumElegido<2) { // Todos los nums menores a 2 son primos (incluidos negativos)
primo=false;
}
else if (paramNumElegido==2) { // El número 2 es primo
primo=true;
}
else { // Dado un número "num", mediante un bucle while vamos haciendo los módulos
// "num%num-i" mientras que dicho cálculo sea !=0 y num-1 sea >1.
// El programa acabará sí o sí saliendo del bucle, dándose 2 posibilidades:
// 1) salirse porque el módulo NUNCA ha dado "!=0", y por tanto param_i valdrá
// 1, por lo que el valor de la variable "primo" no se modificará en el
// interior de este "else" y por tanto, primo se quedará con valor "true", lo
// que significará que el número SI es primo.
// 2) salirse porque en algún momento, excepto el caso anterior, el módulo salga
// "==0". En este caso, "param_i" será, seguro, ">1", por lo que, tras abandonar
// el bucle, entraremos en el if, donde le cambiaremos el valor a la variable primo,
// que ahora será "false", lo que significará que el número NO es primo.
int param_i = paramNumElegido-1;
while (modulo_i(paramNumElegido, param_i)!=0 && param_i>1) {
param_i--;
}
if (param_i>1) {
primo=false;
}
}
return primo;
} // Fin método esPrimo()
// método para imprimir resultado
static void impresion(int paramNumElegido , boolean paramPrimo) {
if (paramPrimo) {
System.out.println("El número " + paramNumElegido + " es un número primo.");
} else {
System.out.println("El número " + paramNumElegido + " no es un número primo.");
}
}
} // Fin de la clase App
|
/*
Make sure to install PubSubClient library prior to compiling this sketch
*/
#include <ESP8266WiFi.h>
#include "DHTesp.h"
DHTesp dht;
#include <PubSubClient.h> // Allows us to connect to, and publish to the MQTT broker
#define ANALOG_INPUT A0
#define MUX_A D4
#define MUX_B D3
#define MUX_C D2
#define dht_apin D0
#define LED D5
#define buzzer D6
#define Relay D7
#define LED1 D1
int sensor = 16;
/*
ESP8266 pin usage:
D0: Relay, to dht_apin..................
D2: P0, solid state switch to MUX_C...................
D3: LED_RED to MUX_B.......................
D4: LED_GREEN to MUX_A.....................
D5: LED.....................
D6: I/O ; Will connect motion sensor to buzzer................
D7: I/O ; will connect DHT11 to Relay................
D8: Buzzer ; whwn 1 is applied, P0 is actrivated
*/
WiFiClient wifiClient;
char *ssid = "ONE"; // maximum allowable ssid length is 27, as one terminating null character is reserved
char *password = "12341234"; // maximum allowable password lenth is 27
const char* mqtt_username = "manu";
const char* mqtt_password = "1234";
const char* mqtt_server = "34.125.67.147";
const char* clientID = "MyDevice";
PubSubClient client(mqtt_server, 1883, wifiClient); // 1883 is the secure listener port for the Broker
void setup()
{
Serial.begin(115200);
Serial.println();
pinMode(D7, OUTPUT);
digitalWrite(D7, HIGH);
pinMode(D2, OUTPUT); // MUX_C
pinMode(D3, OUTPUT); // MUX_B
pinMode(D4, OUTPUT); // MUX_A
pinMode(D5, OUTPUT); // LED
pinMode(D6, OUTPUT); // BUZZER
pinMode(D1, OUTPUT);
dht.setup(16, DHTesp::DHT11); // D0
pinMode(sensor, INPUT);
// Connect to the WiFi
WiFi.begin(ssid, password);
// Wait until the connection has been confirmed before continuing
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
// setCallback sets the function to be called when a message is received.
client.setCallback(ReceivedMessage);
// Connect to MQTT Broker
if (Connect()) {
Serial.println("Connected Successfully to MQTT Broker!");
}
else {
Serial.println("Connection Failed!");
}
}
void changeMux(int c, int b, int a) {
if (a == 0) {
digitalWrite(MUX_A, LOW);
} else {
digitalWrite(MUX_A, HIGH);
}
if (b == 0) {
digitalWrite(MUX_B, LOW);
} else {
digitalWrite(MUX_B, HIGH);
}
if (c == 0) {
digitalWrite(MUX_C, LOW);
} else {
digitalWrite(MUX_C, HIGH);
}
}
void loop() {
float motion_sensor;
float touch_sensor;
float gas_sensor;
float flame_sensor;
float temperature, humidity;
char msg[256];
// check WiFi status
// if WiFi is not connected, powercycle the device
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Lost WiFi connection. Restarting");
delay(50);
ESP.restart(); // this is software reset which may not work all the time
}
// If the connection is lost, try to connect again
if (!client.connected()) {
Connect();
}
// client.loop() just tells the MQTT client code to do what it needs to do itself (i.e. check for messages, etc.)
client.loop();
changeMux(0, 0, 1);
float value1 = analogRead(ANALOG_INPUT);
touch_sensor = read_touch_sensor();
Serial.print(touch_sensor);
if (touch_sensor > 500)
{
mqtt_client_publish("LED", "ON");
Serial.print("Touch"); Serial.print(" ||| "); digitalWrite(Relay, HIGH);
}
else
{
Serial.print("Not Touch"); Serial.print(" ||| "); digitalWrite(Relay, LOW);
}
changeMux(0, 1, 0);
float value2 = analogRead(ANALOG_INPUT);
motion_sensor = read_motion_sensor();
value2 = analogRead(ANALOG_INPUT);
Serial.print(motion_sensor);
if (motion_sensor > 500)
{
mqtt_client_publish("MOTION_ALARM", "ON");
Serial.print("Motion"); digitalWrite(LED, HIGH); Serial.print(" ||| ");
}
else
{
Serial.print("No Motion"); digitalWrite(LED, LOW); Serial.print(" ||| ");
}
changeMux(0, 1, 1);
float value3 = analogRead(ANALOG_INPUT);
gas_sensor = read_gas_sensor();
Serial.print(gas_sensor);
if (gas_sensor > 400) {
Serial.print("Toxic Gas"); Serial.print(" ||| ");
Serial.print(value3);
beep_buzzer();
}
else {
Serial.print("Good Gas"); Serial.print(" ||| ");
}
changeMux(1, 0, 0);
float value4 = analogRead(ANALOG_INPUT);
flame_sensor = read_flame_sensor();
Serial.print(flame_sensor);
if (flame_sensor > 500) {
Serial.print("Fire");
Serial.print('\n');
}
else {
Serial.print("No Fire");
Serial.print('\n');
}
delay(1000);
}
float read_touch_sensor() {
changeMux(0, 0, 1);
return (float)analogRead(ANALOG_INPUT); // Note: Motion sensor output is 1 when motion is detected
}
float read_motion_sensor() {
changeMux(0, 1, 0);
return (float)analogRead(ANALOG_INPUT); // Note: Motion sensor output is 1 when motion is detected
}
float read_gas_sensor() {
changeMux(0, 1, 1);
return (float)analogRead(ANALOG_INPUT); // Note: Motion sensor output is 1 when motion is detected
}
float read_flame_sensor() {
changeMux(1, 0, 0);
return (float)analogRead(ANALOG_INPUT); // Note: Motion sensor output is 1 when motion is detected
}
float read_dht11_temp() {
return (float)dht.getTemperature();
float temperature = read_dht11_temp();
}
float read_dht11_hum() {
return (float)dht.getHumidity();
float humidity = read_dht11_hum();
}
void put_on_relay() {
digitalWrite(D7, LOW); // RELAY. We have inverted D0 in hardware
delay(5000);
}
void put_off_relay() {
digitalWrite(D7, HIGH); // RELAY. We have inverted D0 in hardware
delay(5000);
}
void beep_buzzer() {
digitalWrite(D6, HIGH); // produces a beep of 200 msesc duration
delay(500);
digitalWrite(D6, LOW);
}
void led_on() {
digitalWrite(D1, HIGH); // produces a beep of 200 msesc duration
}
void led_off() {
digitalWrite(D1, LOW); // produces a beep of 200 msesc duration
}
void ReceivedMessage(char* topic, byte* payload, unsigned int payload_length) {
// Output the first character of the message to serial (debug)
char msg[256];
int i;
float touch_sensor;
float motion_sensor;
float gas_sensor;
float temperature, humidity;
float temp;
float humid;
float flame_sensor;
char* touch;
char* motion;
char* gas;
char* flame;
boolean send_sensors;
if (payload_length > 0) {
if (strncmp((char*)payload, "RELAY:ON", payload_length) == 0) {
put_off_relay();
} else if (strncmp((char*)payload, "RELAY:OFF", payload_length) == 0) {
put_on_relay();
} else if (strncmp((char*)payload, "BUZZER:ON", payload_length) == 0) {
beep_buzzer();
} else if (strncmp((char*)payload, "LED:ON", payload_length) == 0) {
led_on();
} else if (strncmp((char*)payload, "LED:OFF", payload_length) == 0) {
led_off();
}
}
touch_sensor = read_touch_sensor();
if (touch_sensor > 500) {
touch = "ON";
} else {
touch = "OFF";
}
motion_sensor = read_motion_sensor();
if (motion_sensor > 500) {
motion = "ON";
} else {
motion = "OFF";
}
gas_sensor = read_gas_sensor();
if (gas_sensor > 350) {
gas = "Toxic";
} else {
gas = "Good";
}
flame_sensor = read_flame_sensor();
if (flame_sensor > 500) {
flame = "FIRE";
} else {
flame = "NO FIRE";
}
temp = read_dht11_temp();
temperature = temp;
humid = read_dht11_hum();
humidity = humid;
sprintf(msg, "Motion: %s, Temperature: %3.2f, Humidity: %3.2f, MQ-2: %s, Flame: %s, Touch: %s", motion, temperature, humidity, gas, flame, touch);
mqtt_client_publish("SENSORS", msg);
}
bool Connect() {
// Connect to MQTT Server and subscribe to the topic
if (client.connect(clientID, mqtt_username, mqtt_password)) {
client.subscribe("DEVICE");
return true;
}
else {
return false;
}
}
boolean mqtt_client_publish(char* topic, char* msg) {
boolean result;
result = client.publish(topic, msg);
if (!result) {
Serial.println("Connected, but could not publish");
}
return result;
}
|
/* */ package com.fasterxml.jackson.databind.node;
/* */
/* */ import com.fasterxml.jackson.core.Base64Variant;
/* */ import com.fasterxml.jackson.core.Base64Variants;
/* */ import com.fasterxml.jackson.core.JsonGenerator;
/* */ import com.fasterxml.jackson.core.JsonToken;
/* */ import com.fasterxml.jackson.core.io.CharTypes;
/* */ import com.fasterxml.jackson.core.io.NumberInput;
/* */ import com.fasterxml.jackson.core.util.ByteArrayBuilder;
/* */ import com.fasterxml.jackson.databind.SerializerProvider;
/* */ import com.fasterxml.jackson.databind.exc.InvalidFormatException;
/* */ import java.io.IOException;
/* */
/* */
/* */
/* */
/* */ public class TextNode
/* */ extends ValueNode
/* */ {
/* */ private static final long serialVersionUID = 2L;
/* 21 */ static final TextNode EMPTY_STRING_NODE = new TextNode("");
/* */ protected final String _value;
/* */
/* */ public TextNode(String v) {
/* 25 */ this._value = v;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static TextNode valueOf(String v) {
/* 38 */ if (v == null) {
/* 39 */ return null;
/* */ }
/* 41 */ if (v.length() == 0) {
/* 42 */ return EMPTY_STRING_NODE;
/* */ }
/* 44 */ return new TextNode(v);
/* */ }
/* */
/* */
/* */ public JsonNodeType getNodeType() {
/* 49 */ return JsonNodeType.STRING;
/* */ }
/* */ public JsonToken asToken() {
/* 52 */ return JsonToken.VALUE_STRING;
/* */ }
/* */
/* */ public String textValue() {
/* 56 */ return this._value;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public byte[] getBinaryValue(Base64Variant b64variant) throws IOException {
/* 67 */ String str = this._value.trim();
/* 68 */ ByteArrayBuilder builder = new ByteArrayBuilder(4 + (str.length() * 3 >> 2));
/* */ try {
/* 70 */ b64variant.decode(str, builder);
/* 71 */ } catch (IllegalArgumentException e) {
/* 72 */ throw InvalidFormatException.from(null,
/* 73 */ String.format("Cannot access contents of TextNode as binary due to broken Base64 encoding: %s", new Object[] {
/* */
/* 75 */ e.getMessage()
/* */ }), str, byte[].class);
/* */ }
/* 78 */ return builder.toByteArray();
/* */ }
/* */
/* */
/* */ public byte[] binaryValue() throws IOException {
/* 83 */ return getBinaryValue(Base64Variants.getDefaultVariant());
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public String asText() {
/* 94 */ return this._value;
/* */ }
/* */
/* */
/* */ public String asText(String defaultValue) {
/* 99 */ return (this._value == null) ? defaultValue : this._value;
/* */ }
/* */
/* */
/* */
/* */
/* */ public boolean asBoolean(boolean defaultValue) {
/* 106 */ if (this._value != null) {
/* 107 */ String v = this._value.trim();
/* 108 */ if ("true".equals(v)) {
/* 109 */ return true;
/* */ }
/* 111 */ if ("false".equals(v)) {
/* 112 */ return false;
/* */ }
/* */ }
/* 115 */ return defaultValue;
/* */ }
/* */
/* */
/* */ public int asInt(int defaultValue) {
/* 120 */ return NumberInput.parseAsInt(this._value, defaultValue);
/* */ }
/* */
/* */
/* */ public long asLong(long defaultValue) {
/* 125 */ return NumberInput.parseAsLong(this._value, defaultValue);
/* */ }
/* */
/* */
/* */ public double asDouble(double defaultValue) {
/* 130 */ return NumberInput.parseAsDouble(this._value, defaultValue);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public final void serialize(JsonGenerator g, SerializerProvider provider) throws IOException {
/* 142 */ if (this._value == null) {
/* 143 */ g.writeNull();
/* */ } else {
/* 145 */ g.writeString(this._value);
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public boolean equals(Object o) {
/* 158 */ if (o == this) return true;
/* 159 */ if (o == null) return false;
/* 160 */ if (o instanceof TextNode) {
/* 161 */ return ((TextNode)o)._value.equals(this._value);
/* */ }
/* 163 */ return false;
/* */ }
/* */
/* */ public int hashCode() {
/* 167 */ return this._value.hashCode();
/* */ }
/* */
/* */ @Deprecated
/* */ protected static void appendQuoted(StringBuilder sb, String content) {
/* 172 */ sb.append('"');
/* 173 */ CharTypes.appendQuoted(sb, content);
/* 174 */ sb.append('"');
/* */ }
/* */ }
/* Location: C:\Users\JineshGamer\Downloads\RankedBot.jar!\com\fasterxml\jackson\databind\node\TextNode.class
* Java compiler version: 7 (51.0)
* JD-Core Version: 1.1.3
*/
|
import React, { useContext, useState } from "react";
import { Button, Form } from "react-bootstrap";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { AuthContext } from "../../providers/AuthProvider";
import { Navigate } from "react-router-dom";
import {
GoogleAuthProvider,
getAuth,
signInWithPopup,
updateProfile,
} from "firebase/auth";
import app from "../../firebase/firebase.config";
const auth = getAuth(app);
const Login = () => {
const [loginUser, setLoginUser] = useState(null);
const { userSignIn, googleLogIn } = useContext(AuthContext);
const Navigate = useNavigate();
const location = useLocation();
const googleProvider = new GoogleAuthProvider();
const githubProvider = new GoogleAuthProvider();
const from = location?.state?.from?.pathname || "/";
const handleGoogle = () => {
signInWithPopup(auth, googleProvider)
.then((result) => {
console.log(result.user);
})
.catch((error) => console.log(error));
};
const handleGithub = () => {
signInWithPopup(auth, githubProvider)
.then((result) => {
console.log(result.user);
setLoginUser(result.user);
})
.catch((error) => console.log(error));
};
const handleLogin = (event) => {
event.preventDefault();
const form = event.target;
const email = form.email.value;
const password = form.password.value;
console.log(email, password);
userSignIn(email, password)
.then((result) => {
const signedInUser = result.user;
setLoginUser(signedInUser);
Navigate(from);
updateProfile(auth, (loginUser) => {
displayName: {
name;
}
photoURL: {
photo;
}
})
.then((result) => {
const loggedUser = result.user;
setLoginUser(loggedUser);
})
.catch((error) => console.log(error));
})
.catch((error) => {
setLoginUser(error.message);
});
};
return (
<div className="w-50 mx-auto py-5">
<h1 className="text-center py-5">Please Login !!!</h1>
<Form onSubmit={handleLogin}>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" name="email" placeholder="Enter email" />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
name="password"
placeholder="Password"
/>
</Form.Group>
<p className="text-danger">{loginUser}</p>
<Button
className="form-control btn btn-outline-secondary text-white"
variant="secondary"
type="login"
>
Login
</Button>
<Form.Group className="mb-3" controlId="formBasicCheckbox">
<p>
New To Chines Cuisine <Link to="/register">Register Now</Link>
</p>
</Form.Group>
</Form>
<button
className="form-control btn btn-outline-secondary text-white bg-dark mb-3"
variant="secondary"
onClick={handleGoogle}
>
Login With Google
</button>
<button
className="form-control btn btn-outline-secondary text-white bg-dark"
variant="secondary"
onClick={handleGithub}
Navigate to="/home" replace
>
Login With GitHub
</button>
</div>
);
};
export default Login;
|
import React, { useState, useEffect} from 'react';
const Navbar = () =>{
const [userName, setUserName] = useState('');
const removeCookie = (cookieName) => {
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
};
const logout = async () => {
try {
localStorage.removeItem('Email');
localStorage.removeItem('User');
removeCookie('Token');
window.location.reload();
// Handle other cases where the response or data is not as expected
} catch (error) {
console.error(error.response ? error.response.data : error.message);
// Handle error, e.g., display an error message
}
};
useEffect(() => {
// Retrieve user name from local storage
const storedUserName = localStorage.getItem('User');
// Set the user name in the state
setUserName(storedUserName); // Use an empty string as a default if it's not present in local storage
}, []);
return (
<nav className="bg-black p-4">
<div className="container mx-auto flex justify-between items-center">
<div className="text-white">Stealth Post</div>
<div className="flex items-center">
<span className="text-white mr-2">{userName} </span>
<button
className="bg-red-500 text-white px-4 py-2 rounded"
onClick={logout}
>
Logout
</button>
</div>
</div>
</nav>
)}
export default Navbar;
|
package com.example.baseviewmodel.main
import android.os.Parcelable
import androidx.lifecycle.SavedStateHandle
import com.example.baseviewmodel.common.base.Action
import com.example.baseviewmodel.common.base.processDeathSurvivors.BaseSurvivorViewModel
import com.example.baseviewmodel.common.base.ViewState
import com.example.baseviewmodel.repo.SomeRepository
import kotlinx.parcelize.Parcelize
/** inject savedStateHandle into constructor and to pass it to BaseSurvivorViewModel */
class MainVM(private val someRepository: SomeRepository, savedStateHandle: SavedStateHandle) :
BaseSurvivorViewModel(
states = mutableListOf(
ViewState<FirstModel>(),
ViewState<SecondModel>()
), savedStateHandle
) {
init {
// getBothData()
}
override fun onAction(action: Action) {
when (action) {
MainActions.GetFirstDataAction -> getFirstData()
MainActions.GetSecondDataAction -> getSecondData()
MainActions.GetBothDataAction -> getBothData()
MainActions.GoToSecondScreenAction -> action.emit()
}
}
private fun getBothData() {
launch(emitLoadingAction = true, emitErrorMsgAction = true,
propagateCancellationException = true,
onStart = { Action.Message("onStart").emit() },
onFinish = { Action.Message("onFinish").emit() },
onException = { Action.Message("onExceptionAction").emit() }) {
someRepository.apply {
call(getFirstTestData(), 0)
call(getSecondTestData(), 1)
}
}
}
private fun getFirstData() {
launch { call(someRepository.getFirstTestData(), 0) }
}
private fun getSecondData() {
launch { call(someRepository.getSecondTestData(), 1) }
}
}
@Parcelize
data class FirstModel(
val firstData: String
) : Parcelable
@Parcelize
data class SecondModel(
val secondData: String
) : Parcelable
|
<form name="form"
ng-submit="vm.onSubmit(form)"
ng-controller="FileUploadCtrl"
class="import-pod"
novalidate>
<div class="container">
<h1>Import Pod</h1>
<button type="button"
class="btn btn-primary loader"
ng-click="vm.createNewPod()"
ng-class="{'in-progress': vm.podCreationInProgress}"
ng-disabled="vm.podCreationInProgress">Create new pod</button>
<p>or select existing</p>
<select ng-model="vm.podName">
<option ng-repeat="podName in vm.allPods">{{:: podName}}</option>
</select>
<div ng-if="vm.podName">
<h2>Upload .csv file</h2>
<div class="upload">
<div class="drop-box" ng-if="!vm.file"
ngf-drop="vm.onFilesDrop($files)"
ngf-drag-over-class="{accept:'accept', reject:'reject'}"
ngf-multiple="false"
ngf-pattern="'text/csv'">Drop CSV file
</div>
<div ng-if="vm.file">
<table class="table">
<thead>
<tr>
<th>Filename</th>
<th>Size</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ vm.file.name }}</td>
<td>{{ vm.file.size }}</td>
<td class="text-right">
<button type="button" class="btn btn-danger" ng-click="vm.removeFile()">Remove</button>
</td>
</tr>
</tbody>
</table>
<hr/>
<div class="well" ng-if="vm.errors.length">
<div class="alert alert-danger" role="alert">
<strong>Oh snap!</strong> Change a few things up and try submitting again.
</div>
<pre ng-repeat="error in vm.errors">{{:: error}}</pre>
</div>
<div class="alert alert-success" role="alert" ng-if="vm.showImportSuccessMessage">
<strong>Well done! 🎉</strong> Pod successfully imported!
</div>
<button type="submit"
class="btn btn-primary loader"
ng-class="{'in-progress': vm.importInProgress}"
ng-disabled="vm.importInProgress">Import
</button>
</div>
</div>
</div>
</div>
</form>
|
import Image from 'next/image';
import HeroButton from './heroButton';
import heroData from './hero.json';
const Hero = () => {
return (
<div className="relative w-screen h-[80vh] md:h-[90vh] max-h-[90vh]">
<div className="fixed inset-0 -z-10">
<Image
src="/assets/images/heroImage.png"
alt="Hero Image"
layout="fill"
objectFit="cover"
objectPosition="center"
quality={100}
/>
</div>
<div className="absolute inset-0 flex flex-col items-center justify-center px-8 z-10">
<h1 className="text-6xl xl:text-8xl text-white max-w-7xl text-center leading-none font-medium">
{heroData.hero.heroTitle}
</h1>
<p className="mt-4 text-base lg:text-lg text-white font-light max-w-2xl text-center leading-relaxed">
{heroData.hero.heroSubtitle}
</p>
<div className="mt-4 flex flex-col sm:flex-row gap-4 md:gap-8">
{heroData.buttons.map((button, index) => (
<HeroButton key={index} text={button.buttonText} style={button.buttonStyle} />
))}
</div>
</div>
</div>
);
};
export default Hero;
|
import Question from "./question";
import { useState } from "react";
import generateString from "../general/uniqueID";
export default function Quiz() {
const [questions, setQuestions] = useState([]);
/*add question */
const AddQuestion = () => {
setQuestions((prevQuestions) => [
...prevQuestions,
<Question
key={prevQuestions.length}
id={generateString(5)}
onDelete={() => deleteQuestion(prevQuestions.length)}
/>,
]);
};
/*delete a question*/
const deleteQuestion = (indexToRemove) => {
setQuestions((prevQuestions) =>
prevQuestions.filter((value, index) => index !== indexToRemove)
);
};
return (
<div className="w-full my-4 flex flex-col p-3 bg-white rounded-lg shadow-md shadow-gray-200">
<div className="text-darker font-semibold">Training quiz</div>
<div className="text-sm mt-1 text-medium_gray">
Here you can manage the questions by clicking on the “Add Question”
button and choose from the available types of question. You can add up
to 100 questions.
</div>
<div className="divider my-1"></div>
<div className="w-full h-fit flex flex-col gap-3">{questions}</div>
<button
className="w-full text-dark_blue font-semibold py-1 mt-3 bg-add_question rounded-lg hover:scale-[101%] transition-all duration-300 ease-in-out"
onClick={AddQuestion}
>
Add Question +
</button>
</div>
);
}
|
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { UpdateIcon } from "@radix-ui/react-icons";
interface BlogCardComponentProps {
title: string;
pubDate: string;
updDate: string | null;
tags: string[];
icon: string;
slug: string;
url: string;
}
export function BlogCardComponent(props: BlogCardComponentProps) {
return (
<Card className="my-3 hover:bg-gray-100">
<CardHeader>
<a
href={props.slug ? `/blog/${props.slug}` : props.url}
target={props.slug ? "" : "_blank"}
rel={props.slug ? "" : "noopener"}
>
<div className="flex items-center">
<img
src={props.icon}
alt="favicon"
className="w-6 h-6 mr-2"
/>
<CardDescription className="flex items-center">
{props.pubDate}{" "}
{props.updDate && (
<>
<UpdateIcon className="ml-2 mr-0.5 h-3" />
{props.updDate}
</>
)}
</CardDescription>
</div>
<CardTitle className="ml-1 mt-1">{props.title}</CardTitle>
</a>
</CardHeader>
<CardContent>
{props.tags.map((tag, index) => (
<a
href={`https://yashikota.com/blog/tags/${tag.toLocaleLowerCase()}/`}
>
<span
key={index}
className="mr-2 text-sky-400 hover:text-sky-700"
>
#{tag}
</span>
</a>
))}
</CardContent>
</Card>
);
}
|
package com.enriquepalmadev.financeflex.presentation.stock_feature.view
import android.annotation.SuppressLint
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AutoGraph
import androidx.compose.material.icons.filled.BarChart
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.enriquepalmadev.financeflex.R
import com.enriquepalmadev.financeflex.presentation.coin_feature.model.ScreenError
import com.enriquepalmadev.financeflex.presentation.coin_feature.view.ErrorScreen
import com.enriquepalmadev.financeflex.presentation.coin_feature.view.LoadingScreen
import com.enriquepalmadev.financeflex.presentation.stock_feature.viewmodel.CompanyInfoViewModel
import com.enriquepalmadev.financeflex.presentation.theme.Blue50
import com.enriquepalmadev.financeflex.presentation.theme.GreenBlue30
import com.enriquepalmadev.financeflex.presentation.theme.TransparentGreenEnd
@SuppressLint("UnusedBoxWithConstraintsScope")
@Composable
fun CompanyDetailScreen(
symbol: String,
screenError: ScreenError,
viewModel: CompanyInfoViewModel = hiltViewModel()
) {
val state = viewModel.state
if (state.error == null) {
Column(
modifier = Modifier
.fillMaxSize()
.background(Blue50)
.padding(8.dp),
) {
state.company?.let { company ->
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 64.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Icon(
imageVector = Icons.Filled.BarChart,
contentDescription = "Market icon"
)
Spacer(modifier = Modifier.width(16.dp))
Text(
text = company.name.uppercase(),
fontWeight = FontWeight.Bold,
fontSize = 26.sp,
fontFamily = FontFamily(Font(R.font.breeserif))
)
}
Spacer(modifier = Modifier.height(8.dp))
BoxWithConstraints(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 32.dp)
.height(256.dp)
) {
Card(
colors = CardDefaults.cardColors(TransparentGreenEnd),
modifier = Modifier.fillMaxSize()
) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(16.dp)
) {
Text(
text = buildAnnotatedString {
withStyle(style = SpanStyle(color = Color.Black)) {
append("Ticker: ")
}
withStyle(style = SpanStyle(color = GreenBlue30)) {
append("$${company.symbol}")
}
},
fontStyle = FontStyle.Italic,
fontSize = 14.sp,
fontFamily = FontFamily(Font(R.font.breeserif))
)
Spacer(modifier = Modifier.height(8.dp))
Divider(
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = buildAnnotatedString {
withStyle(style = SpanStyle(color = Color.Black)) {
append("Sector: ")
}
withStyle(style = SpanStyle(color = GreenBlue30)) {
append(company.industry)
}
},
fontSize = 14.sp,
overflow = TextOverflow.Ellipsis,
fontFamily = FontFamily(Font(R.font.breeserif))
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = buildAnnotatedString {
withStyle(style = SpanStyle(color = Color.Black)) {
append("País: ")
}
withStyle(style = SpanStyle(color = GreenBlue30)) {
append("$${company.country}")
}
},
fontSize = 14.sp,
color = Color.Black,
overflow = TextOverflow.Ellipsis,
fontFamily = FontFamily(Font(R.font.breeserif))
)
Spacer(modifier = Modifier.height(8.dp))
Divider(
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = company.description,
fontSize = 12.sp,
fontFamily = FontFamily(Font(R.font.breeserif))
)
}
}
}
Spacer(modifier = Modifier.height(16.dp))
if (state.stockInfos.isNotEmpty()) {
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "Gráfico de la empresa",
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
fontFamily = FontFamily(Font(R.font.breeserif))
)
Spacer(modifier = Modifier.height(16.dp))
StockChart(
infos = state.stockInfos,
modifier = Modifier
.fillMaxWidth()
.height(250.dp)
.padding(horizontal = 8.dp)
.align(Alignment.CenterHorizontally)
)
}
}
}
}
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
if (state.isLoading) {
CircularProgressIndicator()
} else if (state.error != null) {
ErrorScreen(
screenError = ScreenError(
image = screenError.image,
errorMsg = screenError.errorMsg
)
)
}
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Minesweeper</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<style>
html {
font-size: 200%;
font-family: Arial, Helvetica, sans-serif;
}
.field {
text-decoration: none;
text-align: center;
width: 1.3rem;
height: 1.3rem;
line-height: 1.3rem;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="module">
import init, { getState, openField, toggleFlag } from "./pkg/minesweeper.js"
async function main() {
await init()
render(getState())
}
function render(state) {
let root = document.getElementById("root")
root.innerHTML = ""
let data = getState().split("\n").map((row) => row.trim().split(/(?!$)/u))
root.style.display = "inline-grid";
root.style.gridTemplate = `repeat(${data.length}, auto) / repeat(${data[0].length}, auto)`;
for (let y = 0; y < data.length; y++) {
for (let x = 0; x < data[y].length; x++) {
let element = document.createElement("a")
element.classList.add("field")
element.href = "#"
element.innerText = data[y][x]
element.addEventListener("click", event => {
event.preventDefault()
openField(x, y)
render()
})
element.addEventListener("contextmenu", event => {
event.preventDefault()
toggleFlag(x, y)
render()
})
root.appendChild(element)
}
}
}
main()
</script>
</body>
</html>
|
<?php
namespace App\Http\Livewire\Product;
use App\Http\Livewire\BaseComponent;
use Botble\Slug\Facades\SlugHelper;
use Botble\Ecommerce\Models\Product;
use Botble\Ecommerce\Models\Wishlist;
use Botble\Slug\Models\Slug;
use Cart;
class Show extends BaseComponent
{
public $product;
public function mount($slug){
$slug = Slug::where('key', $slug)->firstorFail();
$this->product = Product::findOrFail($slug->reference_id);
}
public function addToCart($product, $qty = 1){
try {
throw_if($qty < 1, 'Invalid Quantity Supplied');
Cart::instance('product')->content()->search(function ($cartItem, $rowId) use($product, $qty) {
if($cartItem->id === $product['id']){
throw_if($product['quantity'] < ($cartItem->qty + $qty), "Max Quantity Reached");
return;
}
});
Cart::instance('product')->add($product['id'], $product['name'], $qty, $product['price'])->associate(Product::class);
toast()->success('Product Added to Cart')->push();
$this->emit('refreshCart');
} catch (\Throwable $e) {
toast()->danger($e->getMessage())->push();
}
}
public function saveToWishList($productId){
try {
$wishlist = Wishlist::where('product_id', $productId)->where('customer_id', auth()->id())->first();
if(!$wishlist){
Wishlist::create([ 'product_id' => $productId, 'customer_id' => auth()->id() ]);
return toast()->success('Product has been added to wishlist')->push();
}
$wishlist->delete();
toast()->success('Product has been removed from wishlist')->push();
} catch (\Throwable $e) {
toast()->danger($e->getMessage())->push();
}
}
public function render()
{
return view('livewire.product.show')
->layout('layouts.app', [
'seo_title' => $this->product->name,
'seo_description' => sanitize_seo_description($this->product->description ?? '')
]);
}
}
|
#' psd function
#'
#' Compute the Power Spectral Density (psd) transformation of the given scRNA count data
#'
#' @param data scRNA count data - genes Vs cells (dim : g x c)
#' @param filter logical value indicating if genes with 0 count should be filtered
#' @return psd transformation of input data (dim : g x c)
#' @export
psd <- function(data, filter = TRUE){
if (filter) {
data <- data[rowSums(data) != 0, ] #filter out genes with 0 count
}
data <- t(data) #dim : c x g
data.psd <- cor(data) #dim : g x g
data.psd <- data %*% data.psd #dim : c x g
data.psd <- abs(mvfft(t(abs(data.psd))) #compute discrete fourier transform of each cell sample
) / dim(data)[2] #dim : g x c
data.psd <- apply(data.psd, 2, #divide column sum from each element
function(x){x / sum(x)}
)
data.psd <- data.psd * log2(data.psd)
data.psd <- apply(data.psd, 1, #subtract row mean from each element
function(x){return (x - mean(x))}
)
data.psd <- apply(data.psd, 2,
function(x){
return ( (x-min(x)) / (max(x)-min(x)) )
})
return (t(data.psd))
}
# data <- matrix(c(-1.2225888, 1.34042501, 0.4259692,-0.23716855,
# 1.7332330, 0.21851021, -1.0023597, 1.00827522,
# -0.6907052, 0.06109564),
# nrow=2, ncol=5, byrow = TRUE)
# psd(data)
|
// --- Directions
// Write a function that accepts a string. The function should
// capitalize the first letter of each word in the string then
// return the capitalized string.
// --- Examples
// capitalize('a short sentence') --> 'A Short Sentence'
// capitalize('a lazy fox') --> 'A Lazy Fox'
// capitalize('look, it is working!') --> 'Look, It Is Working!'
const capitalize = (str) => {
const words = [];
for (let e of str.split(' ')) {
words.push(e[0].toUpperCase() + e.slice(1));
}
return words.join(' ');
};
console.log(capitalize('paap ko jalakar rakh kar dunga'));
// sol 2
const capitalize2 = (str) => {
let result = str[0].toUpperCase();
for (let i = 1; i < str.length; i++) {
if (str[i - 1] === ' ') {
result += str[i].toUpperCase();
} else {
result += str[i];
}
}
return result;
};
console.log(capitalize2('mard ko drad nahi hota hai'));
|
<properties
pageTitle="Media Services REST API overview | Microsoft Azure"
description="Media Services REST API overview"
services="media-services"
documentationCenter=""
authors="Juliako"
manager="dwrede"
editor=""/>
<tags
ms.service="media-services"
ms.workload="media"
ms.tgt_pltfrm="na"
ms.devlang="dotnet"
ms.topic="article"
ms.date="12/05/2015"
ms.author="juliako"/>
# Media Services REST API overview
> [AZURE.SELECTOR]
- [.NET](../articles/media-services/media-services-dotnet-how-to-use.md)
- [REST API](../articles/media-services/media-services-rest-how-to-use.md)
Microsoft Azure Media Services is a service that accepts OData-based HTTP requests and can respond back in verbose JSON or atom+pub. Because Media Services conforms to Azure design guidelines, there is a set of required HTTP headers that each client must use when connecting to Media Services, as well as a set of optional headers that can be used. The following sections describe the headers and HTTP verbs you can use when creating requests and receiving responses from Media Services.
## Standard HTTP request headers supported by Media Services
For every call you make into Media Services, there is a set of required headers you must include in your request and also a set of optional headers you may want to include. The following table lists the required headers:
| Header | Type | Value |
| --- | --- | --- |
| Authorization |Bearer |Bearer is the only accepted authorization mechanism. The value must also include the access token provided by ACS. |
| x-ms-version |Decimal |2.11 |
| DataServiceVersion |Decimal |3.0 |
| MaxDataServiceVersion |Decimal |3.0 |
> [!NOTE]
> Because Media Services uses OData to expose its underlying asset metadata repository through REST APIs, the DataServiceVersion and MaxDataServiceVersion headers should be included in any request; however, if they are not, then currently Media Services assumes the DataServiceVersion value in use is 3.0.
>
>
The following is a set of optional headers:
| Header | Type | Value |
| --- | --- | --- |
| Date |RFC 1123 date |Timestamp of the request |
| Accept |Content type |The requested content type for the response such as the following:<p> -application/json;odata=verbose<p> - application/atom+xml<p> Responses may have a different content type, such as a blob fetch, where a successful response will contain the blob stream as the payload. |
| Accept-Encoding |Gzip, deflate |GZIP and DEFLATE encoding, when applicable. Note: For large resources, Media Services may ignore this header and return noncompressed data. |
| Accept-Language |"en", "es", and so on. |Specifies the preferred language for the response. |
| Accept-Charset |Charset type like “UTF-8” |Default is UTF-8. |
| X-HTTP-Method |HTTP Method |Allows clients or firewalls that do not support HTTP methods like PUT or DELETE to use these methods, tunneled via a GET call. |
| Content-Type |Content type |Content type of the request body in PUT or POST requests. |
| client-request-id |String |A caller-defined value that identifies the given request. If specified, this value will be included in the response message as a way to map the request. <p><p>**Important**<p>Values should be capped at 2096b (2k). |
## Standard HTTP response headers supported by Media Services
The following is a set of headers that may be returned to you depending on the resource you were requesting and the action you intended to perform.
| Header | Type | Value |
| --- | --- | --- |
| request-id |String |A unique identifier for the current operation, service generated. |
| client-request-id |String |An identifier specified by the caller in the original request, if present. |
| Date |RFC 1123 date |The date that the request was processed. |
| Content-Type |Varies |The content type of the response body. |
| Content-Encoding |Varies |Gzip or deflate, as appropriate. |
## Standard HTTP verbs supported by Media Services
The following is a complete list of HTTP verbs that can be used when making HTTP requests:
| Verb | Description |
| --- | --- |
| GET |Returns the current value of an object. |
| POST |Creates an object based on the data provided, or submits a command. |
| PUT |Replaces an object, or creates a named object (when applicable). |
| DELETE |Deletes an object. |
| MERGE |Updates an existing object with named property changes. |
| HEAD |Returns metadata of an object for a GET response. |
## Discovering Media Services model
To make Media Services entities more discoverable, the $metadata operation can be used. It allows you to retrieve all valid entity types, entity properties, associations, functions, actions, and so on. The following example shows how to construct the URI: https://media.windows.net/API/$metadata.
You should append "?api-version=2.x" to the end of the URI if you want to view the metadata in a browser, or do not include the x-ms-version header in your request.
## Media Services learning paths
You can view AMS learning paths here:
- [AMS Live Streaming Workflow](https://azure.microsoft.com/documentation/learning-paths/media-services-streaming-live/)
- [AMS on Demand Streaming Workflow](https://azure.microsoft.com/documentation/learning-paths/media-services-streaming-on-demand/)
## Provide feedback
Use the [User Voice](http://go.microsoft.com/fwlink/?linkid=698785&clcid=0x409) forum to provide feedback and make suggestions on how to improve Azure Media Services. You can also go directly to one of the following categories:
- [Azure Media Player](https://feedback.azure.com/forums/169396-media-services/category/109320-azure-media-player/)
- [Client SDK Libraries](https://feedback.azure.com/forums/169396-media-services/category/144435-client-sdks/)
- [Encoding and Processing](https://feedback.azure.com/forums/169396-media-services/category/144411-encoding-and-processing/)
- [Live Streaming](https://feedback.azure.com/forums/169396-media-services/category/144414-live-streaming/)
- [Azure Portal](https://feedback.azure.com/forums/169396-media-services/category/144432-portal/)
- [REST API and Platform](https://feedback.azure.com/forums/169396-media-services/category/144423-rest-api-and-platform/)
- [VoD Streaming](https://feedback.azure.com/forums/169396-media-services/category/144429-vod-streaming/)
[Azure Classic Portal]: http://manage.windowsazure.com/
|
import { useState } from 'react'
export default function useArray<T>(defaultValue: T[]) {
const [array, setArray] = useState(defaultValue)
const methods = {
push: function (element: T) {
// Add element at the end
setArray(a => [...a, element])
},
pop: function () {
// Remove last element
setArray(a => a.slice(0, -1))
},
shift: function () {
// Remove first element
setArray(a => a.slice(1))
},
unshift: function (element: T) {
// Add element at begining
setArray(a => [element, ...a])
},
filter: function (
callback: (value: T, index: number, array: T[]) => boolean
) {
// Filter elements
setArray(a => a.filter(callback))
},
replace: function (index: number, element: T) {
// Replace element at given index with given element
setArray(a => [...a.slice(0, index), element, ...a.slice(index + 1)])
},
update: function (index: number, element: T) {
// Add given element at given index
setArray(a => [...a.slice(0, index), element, ...a.slice(index)])
},
remove: function (index: number) {
// Remove element from given index
setArray(a => [...a.slice(0, index), ...a.slice(index + 1)])
},
clear: function () {
// Empty array
setArray([])
}
}
return { array, set: setArray, ...methods }
}
|
#!/usr/bin/python3
"""This module contain one function that returns a data structure"""
def class_to_json(obj):
"""This function returns the dictionary description of a serializable object."""
obj_dict = obj.__dict__
for key, value in obj_dict.items():
if isinstance(value, list):
obj_dict[key] = [item for item in value if isinstance(
item, (str, int, bool, list, dict))]
elif isinstance(value, dict):
obj_dict[key] = {k: v for k, v in value.items(
) if isinstance(v, (str, int, bool, list, dict))}
elif not isinstance(value, (str, int, bool, list, dict)):
obj_dict[key] = str(value)
return obj_dict
|
import React from "react";
import UserMenu from "./header/UserMenu";
function Header({ sidebarOpen, setSidebarOpen }) {
// const [searchModalOpen, setSearchModalOpen] = useState(false);
return (
<header className="sticky top-0 z-30 border-b border-slate-200 bg-white">
<div className="px-4 sm:px-6 lg:px-8">
<div className="-mb-px flex h-16 items-center justify-between">
{/* Header: Left side */}
<div className="flex">
{/* Hamburger button */}
<button
className="text-slate-500 hover:text-slate-600 lg:hidden"
aria-controls="sidebar"
aria-expanded={sidebarOpen}
onClick={(e) => {
e.stopPropagation();
setSidebarOpen(!sidebarOpen);
}}
>
<span className="sr-only">Open sidebar</span>
<svg
className="h-6 w-6 fill-current"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<rect x="4" y="5" width="16" height="2" />
<rect x="4" y="11" width="16" height="2" />
<rect x="4" y="17" width="16" height="2" />
</svg>
</button>
</div>
{/* Header: Right side */}
<div className="flex items-center">
{/* <button
className={`w-8 h-8 flex items-center justify-center bg-slate-100 hover:bg-slate-200 transition duration-150 rounded-full ml-3 ${searchModalOpen && 'bg-slate-200'}`}
onClick={(e) => { e.stopPropagation(); setSearchModalOpen(true); }}
aria-controls="search-modal"
>
<span className="sr-only">Search</span>
<svg className="w-4 h-4" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<path className="fill-current text-slate-500" d="M7 14c-3.86 0-7-3.14-7-7s3.14-7 7-7 7 3.14 7 7-3.14 7-7 7zM7 2C4.243 2 2 4.243 2 7s2.243 5 5 5 5-2.243 5-5-2.243-5-5-5z" />
<path className="fill-current text-slate-400" d="M15.707 14.293L13.314 11.9a8.019 8.019 0 01-1.414 1.414l2.393 2.393a.997.997 0 001.414 0 .999.999 0 000-1.414z" />
</svg>
</button>
<SearchModal id="search-modal" searchId="search" modalOpen={searchModalOpen} setModalOpen={setSearchModalOpen} />
<Notifications />
<Help /> */}
{/* Divider */}
<hr className="mx-3 h-6 w-px bg-slate-200" />
<UserMenu />
</div>
</div>
</div>
</header>
);
}
export default Header;
|
import { ListItem, ListItemText } from '@mui/material';
import IconButton from '@mui/material/IconButton';
import DoneIcon from '@mui/icons-material/Done';
import RemoveDoneIcon from '@mui/icons-material/RemoveDone';
import { ITodo } from '../../hooks/use-todo';
export interface TodoArgs extends ITodo {
markTodo: (id: string) => void;
}
const Todo = ({ done, text, id, markTodo }: TodoArgs) => {
return (
<ListItem
secondaryAction={
<IconButton
edge="end"
aria-label="sys-check"
onClick={() => markTodo(id)}
>
{done ? (
<RemoveDoneIcon color="error" />
) : (
<DoneIcon color="success" />
)}
</IconButton>
}
>
<ListItemText
primary={text}
sx={{ textDecoration: done ? 'line-through' : 'none' }}
/>
</ListItem>
);
};
export default Todo;
|
package ca.mcmaster.cas.se2aa4.a3.island;
import org.apache.commons.cli.*;
import java.util.HashMap;
import java.util.Map;
/**Provides command line options**/
public class Configuration {
public static final String INPUT = "i";
public static final String OUTPUT = "o";
public static final String LAKES = "lakes";
public static final String RIVER = "rivers";
public static final String VISUAL = "v";
public static final String LAGOON = "l";
public static final String PROFILE = "p";
public static final String SHAPE = "s";
public static final String HELP = "help";
public static final String HEIGHT = "h";
public static final String WIDTH = "w";
public static final String SEED = "seed";
public static final String CITIES = "cities";
private CommandLine cli;
public Configuration(String[] args) {
try {
this.cli = parser().parse(options(), args);
if (cli.hasOption(HELP)) {
help();
}
} catch (ParseException pe) {
throw new IllegalArgumentException(pe);
}
}
public String input() {
return this.cli.getOptionValue(INPUT);
}
public Map<String, String> export() {
Map<String, String> result = new HashMap<>();
for(Option o: cli.getOptions()){
result.put(o.getOpt(), o.getValue(""));
}
return result;
}
public String export(String key) {
return cli.getOptionValue(key);
}
private CommandLineParser parser() {
return new DefaultParser();
}
private void help() {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java -jar generator.jar", options());
System.exit(0);
}
private Options options() {
Options options = new Options();
options.addOption(new Option(INPUT, true, "Input file"));
options.addOption(new Option(OUTPUT, true, "Output file"));
options.addOption(new Option(LAKES, true, "Number of Lakes"));
options.addOption(new Option(RIVER, true, "Number of rivers"));
options.addOption(new Option(VISUAL, true, "Visualization type"));
options.addOption(new Option(LAGOON, false, "Lagoon option"));
options.addOption(new Option(PROFILE, true, "Elevation Profile"));
options.addOption(new Option(SHAPE, true, "Island Shape"));
options.addOption(new Option(HELP, false, "print help message"));
options.addOption(new Option(WIDTH, true, "Width of input mesh"));
options.addOption(new Option(HEIGHT, true, "Height of input mesh"));
options.addOption(new Option(SEED, true, "Seed controlling randomness"));
options.addOption(new Option(CITIES, true, "Number of cities to be generated"));
return options;
}
}
|
<?php
namespace App\Http\Controllers;
use App\Mail\InquiryMail;
use App\Models\InquiryMessage;
use App\Models\Logs;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\Inquiry;
use Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
class InquiryController extends Controller
{
public function index()
{
$unanswered_inquiry = Inquiry::where('status', 'unanswered')->get();
$answered_inquiry = Inquiry::where('status', 'answered')->get();
return view('inquiry.index', compact('unanswered_inquiry', 'answered_inquiry'));
}
public function addInquiry()
{
return view('inquiry.addInquiry');
}
public function validateInquiryForm(Request $request) {
$validator = Validator::make($request->all(), [
'_token' => 'required',
'name' => 'required',
'email' => 'required|email|regex:/^.+@.+\..+$/i',
'inquiry' => 'required',
]);
if ($validator->fails()) {
return response()->json(['message' => 'Validation failed', 'errors' => $validator->errors()]);
}else {
return response()->json(['message' => 'Validation passed']);
}
}
public function saveInquiry(Request $request) {
$inquiryID = Inquiry::generateUniqueInquiryID();
$createInquiry = Inquiry::create([
'inquiry_id' => $inquiryID,
'name' => $request->name,
'email' => $request->email,
'inquiry' => $request->inquiry,
'status' => 'Unanswered',
'created_at' => Carbon::now('Asia/Manila'),
'updated_at'=> Carbon::now('Asia/Manila'),
]);
if($createInquiry->save()) {
$mailData = [
'title' => 'Mail from PedroAID',
'name' => $request->name,
'message' => 'Inquiry Received! We will get back to you as soon as possible.',
'tracking_id' => $inquiryID,
'link' => 'http://127.0.0.1:8000/tracker/inquiry-details/check-details?inquiry_id=' . $inquiryID . '&email=' . $request->email,
];
$mailSubject = '[#'. $inquiryID . '] Inquiry Sent: Inquiry from ' . $request->name;
Mail::to($request->email)->send(new InquiryMail($mailData, $mailSubject));
$this->logAddInquiry('Add Inquiry Success', Auth::user()->username, $inquiryID);
return redirect()->route('inquiry')->with('success', 'Inquiry Sent Successfully!');
}else {
$this->logAddInquiry('Add Inquiry Failed', Auth::user()->username, $inquiryID);
return redirect()->route('inquiry')->with('failed', 'Failed to Send Inquiry!');
}
}
private function logAddInquiry(string $status, string $user, string $inquiryID)
{
Logs::create([
'type' => 'Add Inquiry',
'user' => $user,
'subject' => $status,
'message' => "Inquiry ID: $inquiryID. $status by $user.",
'created_at' => now('Asia/Manila'),
'updated_at' => now('Asia/Manila'),
]);
}
public function inquiryDetails(string $id)
{
$inquiry = Inquiry::where('inquiry_id', $id)->get()->first();
$messages = InquiryMessage::where('inquiry_id', $id)->get();
$staffName = Auth::user()->name;
return view('inquiry.inquiryDetails', compact('inquiry', 'messages', 'staffName'));
}
public function inquirySendMessage(Request $request, string $id) {
$validator = $this->validateMessageRequest($request);
if ($validator->fails()) {
return redirect()->back()->withInput()->withErrors($validator);
}
$inquiry = $this->getInquiryById($id);
$inquiry_email = $inquiry->email;
$message = $request->message;
$this->saveInquiryMessage($id, $inquiry_email, $message);
$this->updateInquiryTimestamp($id);
$this->logMessageSent($id);
$this->sendInquiryMessageEmail($inquiry, $id, $inquiry_email);
return redirect()->route('inquiry.inquiryDetails', $id)->with('success', 'Message Sent!');
}
private function validateMessageRequest($request)
{
return Validator::make($request->all(), [
'_token' => 'required',
'message' => 'required',
]);
}
private function getInquiryById($id)
{
return Inquiry::where('inquiry_id', $id)->get()->first();
}
private function saveInquiryMessage($id, $inquiry_email, $message)
{
InquiryMessage::create([
'inquiry_id' => $id,
'email' => $inquiry_email,
'staff_name' => Auth::user()->name,
'message' => $message,
'created_at' => now('Asia/Manila'),
'updated_at' => now('Asia/Manila'),
]);
}
private function updateInquiryTimestamp($id)
{
Inquiry::where('inquiry_id', $id)->update([
'status' => 'Answered',
'updated_at' => now('Asia/Manila'),
]);
}
private function logMessageSent($id)
{
Logs::create([
'type' => 'Send Inquiry Message',
'user' => Auth::user()->username,
'subject' => 'Send Inquiry Message Success',
'message' => 'Inquiry ID: ' . $id . ' has been successfully sent a message by ' . Auth::user()->username . '.',
'created_at' => now('Asia/Manila'),
'updated_at' => now('Asia/Manila'),
]);
}
private function sendInquiryMessageEmail($inquiry, $id, $inquiry_email)
{
$mailData = [
'title' => 'Mail from PedroAID',
'name' => $inquiry->name,
'message' => 'Inquiry Response!',
'tracking_id' => $id,
'link' => route('inquiryDetails', ['inquiry_id' => $id, 'email' => $inquiry_email])
];
$mailSubject = "[#$id] New Message: Inquiry from $inquiry->name";
Mail::to($inquiry_email)->send(new InquiryMail($mailData, $mailSubject));
}
public function editInquiry(string $id)
{
$inquiry = Inquiry::where('inquiry_id', $id)->get()->first();
return view('inquiry.editInquiry', compact('inquiry'));
}
public function validateEditInquiryForm(Request $request)
{
$validator = Validator::make($request->all(), [
'_token' => 'required',
'name' => 'required',
'email' => 'required|email|regex:/^.+@.+\..+$/i',
'inquiry' => 'required',
'status' => 'required',
]);
if ($validator->fails()) {
return response()->json(['message' => 'Validation failed', 'errors' => $validator->errors()]);
} else {
return response()->json(['message' => 'Validation passed']);
}
}
public function updateInquiry(Request $request, string $id) {
$inquiry = Inquiry::where('inquiry_id', $id)->get()->first();
if ($this->shouldUpdateInquiry($request, $inquiry)) {
$this->updateInquiryDetails($request, $inquiry);
$this->logInquiryEditSuccess($id);
return redirect()->route('inquiry.editInquiry', $id)->with('success', 'Inquiry Edited Successfully!');
} else {
$this->logInquiryEditFailed($id);
return redirect()->route('inquiry.editInquiry', $id)->with('failed', 'Failed to Edit Inquiry!');
}
}
private function shouldUpdateInquiry($request, $inquiry)
{
return $request->name !== $inquiry->name ||
$request->email !== $inquiry->email ||
$request->inquiry !== $inquiry->inquiry ||
$request->status !== $inquiry->status;
}
private function updateInquiryDetails($request, $inquiry)
{
Inquiry::where('inquiry_id', $inquiry->inquiry_id)->update([
'name' => $request->name,
'email' => $request->email,
'inquiry' => $request->inquiry,
'status' => $request->status,
'updated_at' => now('Asia/Manila'),
]);
}
private function logInquiryEditSuccess($id)
{
Logs::create([
'type' => 'Edit Inquiry',
'user' => Auth::user()->username,
'subject' => 'Edit Inquiry Success',
'message' => 'Inquiry ID: ' . $id . ' has been successfully edited by ' . Auth::user()->username . '.',
'created_at' => now('Asia/Manila'),
'updated_at' => now('Asia/Manila'),
]);
}
private function logInquiryEditFailed($id)
{
Logs::create([
'type' => 'Edit Inquiry',
'user' => Auth::user()->username,
'subject' => 'Edit Inquiry Failed',
'message' => 'Failed to edit Inquiry ID: ' . $id . ' by ' . Auth::user()->username . '.',
'created_at' => now('Asia/Manila'),
'updated_at' => now('Asia/Manila'),
]);
}
public function deleteInquiry(string $id)
{
$inquiry = Inquiry::where('inquiry_id', $id)->get()->first();
return view('inquiry.deleteInquiry', compact('inquiry'));
}
public function destroyInquiry(string $id)
{
try {
DB::beginTransaction();
$inquiry = Inquiry::where('inquiry_id', $id)->get()->first();
$user = Auth::user()->username;
$this->createDeleteInquiryLog($user, $inquiry);
$inquiryStatus = $inquiry->inquiry_status;
Inquiry::where('inquiry_id', $id)->delete();
DB::table('notifications')
->where('data->inquiry_id', $id)
->where('type', 'App\Notifications\NewInquiry')
->delete();
DB::table('notifications')
->where('data->inquiry_id', $id)
->where('type', 'App\Notifications\NewInquiryMessage')
->delete();
DB::commit();
return redirect()->route('inquiry')->with('success', 'Inquiry Deleted Successfully!');
} catch (\Exception $e) {
DB::rollBack();
return redirect()->route('inquiry')->with('failed', 'Failed to delete Inquiry!');
}
}
private function createDeleteInquiryLog($user, $inquiry)
{
$logData = [
'type' => 'Delete Inquiry',
'user' => $user,
'subject' => 'Delete Inquiry Success',
'message' => 'Inquiry ID: ' . $inquiry->inquiry_id . ' has been successfully deleted by ' . $user . '.',
'created_at' => now('Asia/Manila'),
'updated_at' => now('Asia/Manila'),
];
Logs::create($logData);
}
}
|
import numpy as np
import scipy.sparse.csgraph
import tensorflow as tf
from tf_agents.agents import tf_agent
from tf_agents.policies import actor_policy
from tf_agents.policies import ou_noise_policy
from tf_agents.trajectories import time_step
from tf_agents.trajectories import trajectory
from tf_agents.utils import common
class UvfAgent(tf_agent.TFAgent):
def __init__(
self,
time_step_spec,
action_spec,
ou_stddev=1.0,
ou_damping=1.0,
target_update_tau=0.05,
target_update_period=5,
max_episode_steps=None,
ensemble_size=3,
combine_ensemble_method='min',
use_distributional_rl=True):
tf.Module.__init__(self, name='UvfAgent')
assert max_episode_steps is not None
self._max_episode_steps = max_episode_steps
self._ensemble_size = ensemble_size
self._use_distributional_rl = use_distributional_rl
# Create the actor
self._actor_network = GoalConditionedActorNetwork(
time_step_spec.observation, action_spec)
self._target_actor_network = self._actor_network.copy(
name='TargetActorNetwork')
critic_net_input_specs = (time_step_spec.observation, action_spec)
critic_network = GoalConditionedCriticNetwork(
critic_net_input_specs,
output_dim=max_episode_steps if use_distributional_rl else None,
)
self._critic_network_list = []
self._target_critic_network_list = []
for ensemble_index in range(self._ensemble_size):
self._critic_network_list.append(
critic_network.copy(name='CriticNetwork%d' % ensemble_index))
self._target_critic_network_list.append(
critic_network.copy(name='TargetCriticNetwork%d' % ensemble_index))
net_list = [
self._actor_network, self._target_actor_network
] + self._critic_network_list + self._target_critic_network_list
for net in net_list:
net.create_variables()
self._actor_optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=3e-4)
self._critic_optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=3e-4)
self._ou_stddev = ou_stddev
self._ou_damping = ou_damping
self._target_update_tau = target_update_tau
self._target_update_period = target_update_period
self._update_target = self._get_target_updater(
target_update_tau, target_update_period)
policy = actor_policy.ActorPolicy(
time_step_spec=time_step_spec, action_spec=action_spec,
actor_network=self._actor_network, clip=True)
collect_policy = actor_policy.ActorPolicy(
time_step_spec=time_step_spec, action_spec=action_spec,
actor_network=self._actor_network, clip=False)
collect_policy = ou_noise_policy.OUNoisePolicy(
collect_policy,
ou_stddev=self._ou_stddev,
ou_damping=self._ou_damping,
clip=True)
super(UvfAgent, self).__init__(
time_step_spec,
action_spec,
policy,
collect_policy,
train_sequence_length=2)
def initialize_search(self, active_set, max_search_steps=3,
combine_ensemble_method='min'):
self._combine_ensemble_method = combine_ensemble_method
self._max_search_steps = max_search_steps
self._active_set_tensor = tf.convert_to_tensor(value=active_set)
pdist = self._get_pairwise_dist(self._active_set_tensor, masked=True,
aggregate=combine_ensemble_method)
distances = scipy.sparse.csgraph.floyd_warshall(pdist, directed=True)
self._distances_tensor = tf.convert_to_tensor(value=distances, dtype=tf.float32)
# def _get_pairwise_dist(self, obs_tensor, goal_tensor=None, masked=False,
# aggregate='mean'):
# if goal_tensor is None:
# goal_tensor = obs_tensor
# dist_matrix = []
# for obs_index in range(obs_tensor.shape[0]):
# obs = obs_tensor[obs_index]
# obs_repeat_tensor = tf.ones_like(goal_tensor) * tf.expand_dims(obs, 0)
# obs_goal_tensor = {'observation': obs_repeat_tensor,
# 'goal': goal_tensor}
# pseudo_next_time_steps = time_step.transition(obs_goal_tensor,
# reward=0.0,
# discount=1.0)
# dist = self._get_dist_to_goal(pseudo_next_time_steps, aggregate=aggregate)
# dist_matrix.append(dist)
#
# pairwise_dist = tf.stack(dist_matrix)
# if aggregate is None:
# pairwise_dist = tf.transpose(a=pairwise_dist, perm=[1, 0, 2])
#
# if masked:
# mask = (pairwise_dist > self._max_search_steps)
# return tf.compat.v1.where(mask, tf.fill(pairwise_dist.shape, np.inf),
# pairwise_dist)
# else:
# return pairwise_dist
def _get_critic_output(self, critic_net_list, next_time_steps,
actions=None):
q_values_list = []
critic_net_input = (next_time_steps.observation, actions)
for critic_index in range(self._ensemble_size):
critic_net = critic_net_list[critic_index]
q_values, _ = critic_net(critic_net_input, next_time_steps.step_type)
q_values_list.append(q_values)
return q_values_list
def _get_expected_q_values(self, next_time_steps, actions=None):
if actions is None:
actions, _ = self._actor_network(next_time_steps.observation,
next_time_steps.step_type)
q_values_list = self._get_critic_output(self._critic_network_list,
next_time_steps, actions)
expected_q_values_list = []
for q_values in q_values_list:
if self._use_distributional_rl:
q_probs = tf.nn.softmax(q_values, axis=1)
batch_size = q_probs.shape[0]
bin_range = tf.range(1, self._max_episode_steps + 1, dtype=tf.float32)
neg_bin_range = -1.0 * bin_range
tiled_bin_range = tf.tile(tf.expand_dims(neg_bin_range, 0),
[batch_size, 1])
assert q_probs.shape == tiled_bin_range.shape
expected_q_values = tf.reduce_sum(input_tensor=q_probs * tiled_bin_range, axis=1)
expected_q_values_list.append(expected_q_values)
else:
expected_q_values_list.append(q_values)
return tf.stack(expected_q_values_list)
def _get_state_values(self, next_time_steps, actions=None, aggregate='mean'):
with tf.compat.v1.name_scope('state_values'):
expected_q_values = self._get_expected_q_values(next_time_steps, actions)
if aggregate is not None:
if aggregate == 'mean':
expected_q_values = tf.reduce_mean(input_tensor=expected_q_values, axis=0)
elif aggregate == 'min':
expected_q_values = tf.reduce_min(input_tensor=expected_q_values, axis=0)
else:
raise ValueError('Unknown method for combining ensemble: %s' %
aggregate)
if not self._use_distributional_rl:
min_q_val = -1.0 * self._max_episode_steps
max_q_val = 0.0
expected_q_values = tf.maximum(expected_q_values, min_q_val)
expected_q_values = tf.minimum(expected_q_values, max_q_val)
return expected_q_values
def _get_dist_to_goal(self, next_time_step, aggregate='mean'):
q_values = self._get_state_values(next_time_step, aggregate=aggregate)
return -1.0 * q_values
# def _get_waypoint(self, next_time_steps):
# obs_tensor = next_time_steps.observation['observation']
# goal_tensor = next_time_steps.observation['goal']
# obs_to_active_set_dist = self._get_pairwise_dist(
# obs_tensor, self._active_set_tensor, masked=True,
# aggregate=self._combine_ensemble_method) # B x A
# active_set_to_goal_dist = self._get_pairwise_dist(
# self._active_set_tensor, goal_tensor, masked=True,
# aggregate=self._combine_ensemble_method) # A x B
#
# search_dist = sum([
# tf.expand_dims(obs_to_active_set_dist, 2),
# tf.expand_dims(self._distances_tensor, 0),
# tf.expand_dims(tf.transpose(active_set_to_goal_dist), axis=1)
# ])
#
# assert obs_tensor.shape[0] == 1
# min_search_dist = tf.reduce_min(search_dist, axis=[1, 2])[0]
# waypoint_index = tf.argmin(tf.reduce_min(search_dist, axis=[2]), axis=1)[0]
# waypoint = self._active_set_tensor[waypoint_index]
#
# return waypoint, min_search_dist
def _initialize(self):
for ensemble_index in range(self._ensemble_size):
common.soft_variables_update(
self._critic_network_list[ensemble_index].variables,
self._target_critic_network_list[ensemble_index].variables,
tau=1.0)
# Caution: actor should only be updated once.
common.soft_variables_update(
self._actor_network.variables,
self._target_actor_network.variables,
tau=1.0)
def _get_target_updater(self, tau=1.0, period=1):
with tf.compat.v1.name_scope('get_target_updater'):
def update(): # pylint: disable=missing-docstring
critic_update_list = []
for ensemble_index in range(self._ensemble_size):
critic_update = common.soft_variables_update(
self._critic_network_list[ensemble_index].variables,
self._target_critic_network_list[ensemble_index].variables, tau)
critic_update_list.append(critic_update)
actor_update = common.soft_variables_update(
self._actor_network.variables,
self._target_actor_network.variables, tau)
return tf.group(critic_update_list + [actor_update])
return common.Periodically(update, period, 'periodic_update_targets')
def _experience_to_transitions(self, experience):
transitions = trajectory.to_transition(experience)
transitions = tf.nest.map_structure(lambda x: tf.squeeze(x, [1]),
transitions)
time_steps, policy_steps, next_time_steps = transitions
actions = policy_steps.action
return time_steps, actions, next_time_steps
def _train(self, experience, weights=None):
del weights
time_steps, actions, next_time_steps = self._experience_to_transitions(
experience)
# Update the critic
critic_vars = []
for ensemble_index in range(self._ensemble_size):
critic_net = self._critic_network_list[ensemble_index]
critic_vars.extend(critic_net.variables)
with tf.GradientTape(watch_accessed_variables=False) as tape:
assert critic_vars
tape.watch(critic_vars)
critic_loss = self.critic_loss(time_steps, actions, next_time_steps)
tf.debugging.check_numerics(critic_loss, 'Critic loss is inf or nan.')
critic_grads = tape.gradient(critic_loss, critic_vars)
self._apply_gradients(critic_grads, critic_vars,
self._critic_optimizer)
# Update the actor
actor_vars = self._actor_network.variables
with tf.GradientTape(watch_accessed_variables=False) as tape:
assert actor_vars, 'No actor variables to optimize.'
tape.watch(actor_vars)
actor_loss = self.actor_loss(time_steps)
tf.debugging.check_numerics(actor_loss, 'Actor loss is inf or nan.')
actor_grads = tape.gradient(actor_loss, actor_vars)
self._apply_gradients(actor_grads, actor_vars, self._actor_optimizer)
self.train_step_counter.assign_add(1)
self._update_target()
total_loss = actor_loss + critic_loss
return tf_agent.LossInfo(total_loss, (actor_loss, critic_loss))
def _apply_gradients(self, gradients, variables, optimizer):
# Tuple is used for py3, where zip is a generator producing values once.
grads_and_vars = tuple(zip(gradients, variables))
optimizer.apply_gradients(grads_and_vars)
def critic_loss(self,
time_steps,
actions,
next_time_steps):
with tf.compat.v1.name_scope('critic_loss'):
target_actions, _ = self._target_actor_network(
next_time_steps.observation, next_time_steps.step_type)
critic_loss_list = []
q_values_list = self._get_critic_output(self._critic_network_list,
time_steps, actions)
target_q_values_list = self._get_critic_output(
self._target_critic_network_list, next_time_steps, target_actions)
assert len(target_q_values_list) == self._ensemble_size
for ensemble_index in range(self._ensemble_size):
# The target_q_values should be a Batch x ensemble_size tensor.
target_q_values = target_q_values_list[ensemble_index]
if self._use_distributional_rl:
target_q_probs = tf.nn.softmax(target_q_values, axis=1)
batch_size = target_q_probs.shape[0]
one_hot = tf.one_hot(tf.zeros(batch_size, dtype=tf.int32),
self._max_episode_steps)
col_1 = tf.zeros((batch_size, 1))
col_middle = target_q_probs[:, :-2]
col_last = tf.reduce_sum(target_q_probs[:, -2:], axis=1,
keepdims=True)
shifted_target_q_probs = tf.concat([col_1, col_middle, col_last],
axis=1)
assert one_hot.shape == shifted_target_q_probs.shape
td_targets = tf.compat.v1.where(next_time_steps.is_last(),
one_hot,
shifted_target_q_probs)
td_targets = tf.stop_gradient(td_targets)
else:
td_targets = tf.stop_gradient(
next_time_steps.reward +
next_time_steps.discount * target_q_values)
q_values = q_values_list[ensemble_index]
if self._use_distributional_rl:
critic_loss = tf.nn.softmax_cross_entropy_with_logits(
labels=td_targets,
logits=q_values
)
else:
critic_loss = common.element_wise_huber_loss(td_targets, q_values)
critic_loss = tf.reduce_mean(critic_loss)
critic_loss_list.append(critic_loss)
critic_loss = tf.reduce_mean(critic_loss_list)
return critic_loss
def actor_loss(self, time_steps):
with tf.compat.v1.name_scope('actor_loss'):
actions, _ = self._actor_network(time_steps.observation,
time_steps.step_type)
with tf.GradientTape(watch_accessed_variables=False) as tape:
tape.watch(actions)
avg_expected_q_values = self._get_state_values(time_steps, actions,
aggregate='mean')
actions = tf.nest.flatten(actions)
dqdas = tape.gradient([avg_expected_q_values], actions)
actor_losses = []
for dqda, action in zip(dqdas, actions):
loss = common.element_wise_squared_loss(
tf.stop_gradient(dqda + action), action)
loss = tf.reduce_sum(loss, axis=1)
loss = tf.reduce_mean(loss)
actor_losses.append(loss)
actor_loss = tf.add_n(actor_losses)
with tf.compat.v1.name_scope('Losses/'):
tf.compat.v2.summary.scalar(
name='actor_loss', data=actor_loss, step=self.train_step_counter)
return actor_loss
|
/** Users */
export type User = {
id: number,
name: string
surname: string
email: string
phone: string
email_verified_at: Date,
created_at: Date,
updated_at: Date
}
export type UsersData = {
current_page: number
data: User[]
first_page_url: string
from: number
last_page: number
last_page_url: string
next_page_url: string | null
path: string
per_page: number
prev_page_url: string | null
to: number
total: number
}
/** Store */
export type Store = {
id: number
address_info: string | null
bank_info: string | null
ceo_name: string
ceo_surname: string
company_name: string
company_phone: string
company_website: string
created_at: Date
description: string
document: string | null
is_approved: number
official_company_name: string
slug: string
status: number | null
store_logo: string
store_name: string
type_of_activity: string
updated_at: Date
}
/** Categories */
export type Category = {
created_at: Date
id: number
is_default: boolean
level: number
name: string
parent_id: number
path: string
position: number
translations: []
url_key: string
url_path: string
}
/** Products */
export type ProductImage = {
id: number
image_url: string
is_cover: boolean
path: string
product_id: number
}
export type Product = {
id: number,
category: Category
category_id: number
discount_price: number
final_price: number
images: ProductImage[]
name: string
original_price: number
path:string
price: number
short_description: string
sort_weight: number
stock_qty: number
store_id: number
translations: []
updated_at: Date
url_paths: string | null
user_id: number
variations_meta: object
visibility: number
}
export type ProductItems = {
data: Product[],
last_page: number
}
export type ProductsData = {
items: {
data: Product[],
last_page: number,
current_page: number,
total: number
},
filters: {}
}
/** Orders */
export type Order = {
id: number
name: string,
status: string,
order_date: string,
customer_id: number,
customer_shipping_info: {
address_info: number
},
payment_method: string,
shipping_amount: number
}
/** Atributes */
export type Attribute = {
id: number,
attribute_code: string,
frontend_type: string,
is_unique: number,
is_required: number,
is_filterable: number,
is_translatable: number,
is_default: number,
created_at: Date,
updated_at: Date,
deleted_at: Date | null,
is_multiselect: number,
translations: OrderTrans[],
options: OrderOption[],
label: string,
tooltip: string
}
export type OrderTrans = {
id: number,
attribute_id: number,
label: string,
tooltip: string,
iso: string,
created_at: Date,
updated_at: Date
}
export type OrderOption = {
id: number,
attribute_id: number,
sort_weight: number,
created_at: Date,
updated_at: Date,
deleted_at: Date | null,
attribute_value: string,
translations: []
}
export type AttributesItems = {
data: Attribute[],
currenat_page: number,
first_page_url: string,
from: number,
last_page: number,
last_page_url: string,
next_page_url: string,
path: string,
per_page: number,
prev_page_url: string | null,
to: number,
total: number
}
/** Store state */
export type StoreState = {
user: User
users: UsersData,
stores: Store[],
categories: Category[],
products: ProductsData,
orders: Order[],
attributes: AttributesItems
}
|
import { Button, Form, Input, message } from "antd";
import { useRouter } from "next/navigation";
import { observer } from "mobx-react-lite";
import { useEffect } from "react";
import {
SwapRightOutlined,
MailOutlined,
UserOutlined,
LockOutlined,
} from "@ant-design/icons";
import { AntdProvider } from "@components";
import { useStore } from "@stores";
import styles from "./styles.module.scss";
type FormSignUp = {
firstName: string;
lastName: string;
password: string;
email: string;
};
const FormSignUpComponent = () => {
const { userStore } = useStore();
const { fetchRegister, isAuth, isLoadingUser } = userStore;
const router = useRouter();
useEffect(() => {
if (isAuth) {
message.success("Account is creating successfully");
router.push("/");
}
}, [isAuth]);
const onFinish = (data: FormSignUp) => {
fetchRegister({
firstName: data.firstName,
lastName: data.lastName,
password: data.password,
email: data.email,
});
};
return (
<AntdProvider>
<Form className={styles.login} onFinish={onFinish}>
<div className={styles.name}>
<div className={styles.name_box}>
<div className={styles.placeholder}>
<label>Firstname*</label>
</div>
<Form.Item
name="firstName"
rules={[
{ required: true, message: "This field should be filled" },
{
pattern: /^[A-Z]{2,16}$/i,
message: "This field should be filled",
},
]}
>
<Input
placeholder="Enter Firstname"
size="large"
prefix={<UserOutlined style={{ paddingRight: "5px" }} />}
/>
</Form.Item>
</div>
<div className={styles.name_box}>
<div className={styles.placeholder}>
<label>Lastname*</label>
</div>
<Form.Item
name="lastName"
rules={[
{ required: true, message: "This field should be filled" },
{
pattern: /^[A-Z]{2,16}$/i,
message: "This field should be filled",
},
]}
>
<Input
placeholder="Enter Lastname"
size="large"
prefix={<UserOutlined style={{ paddingRight: "5px" }} />}
/>
</Form.Item>
</div>
</div>
<div className={styles.placeholder}>
<label>Email*</label>
</div>
<Form.Item
name="email"
rules={[
{ required: true, message: "This field should be filled" },
{
pattern: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
message: "Invalid email format",
},
]}
>
<Input
placeholder="Enter Email"
size="large"
prefix={<MailOutlined style={{ paddingRight: "5px" }} />}
/>
</Form.Item>
<div className={styles.placeholder}>
<label>Password*</label>
</div>
<Form.Item
name="password"
rules={[{ required: true, message: "This field should be filled" }]}
>
<Input.Password
size="large"
placeholder="Enter Password"
prefix={<LockOutlined style={{ paddingRight: "5px" }} />}
/>
</Form.Item>
<Form.Item>
<Button
type="primary"
htmlType="submit"
loading={isLoadingUser}
className={styles.button}
icon={<SwapRightOutlined style={{ fontSize: "25px" }} />}
>
Register
</Button>
</Form.Item>
</Form>
</AntdProvider>
);
};
export const FormSignUp = observer(FormSignUpComponent);
|
import { Component, OnInit, ViewChildren, ViewChild, AfterViewInit, QueryList, ElementRef } from '@angular/core';
import { MatDialog, MatDialogRef, MatList, MatListItem } from '@angular/material';
import { Action } from './shared/model/action';
import { Event } from './shared/model/event';
import { Message } from './shared/model/message';
import { User } from './shared/model/user';
import { SocketService } from './shared/services/socket.service';
import {MessagesService} from "../messages.service";
import { DialogUserComponent } from './dialog-user/dialog-user.component';
import { DialogUserType } from './dialog-user/dialog-user-type';
const AVATAR_URL = 'https://api.adorable.io/avatars/285';
@Component({
selector: 'tcc-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.scss']
})
export class ChatComponent implements OnInit, AfterViewInit {
action = Action;
user: User;
currentUser: User;
messages: Message[] = [];
messageContent: string;
ioConnection: any;
dialogRef: MatDialogRef<DialogUserComponent> | null;
defaultDialogUserParams: any = {
disableClose: true,
data: {
title: 'Welcome',
dialogType: DialogUserType.NEW
}
};
// getting a reference to the overall list, which is the parent container of the list items
@ViewChild(MatList, { read: ElementRef }) matList: ElementRef;
// getting a reference to the items/messages within the list
@ViewChildren(MatListItem, { read: ElementRef }) matListItems: QueryList<MatListItem>;
constructor(private socketService: SocketService, private messagesService: MessagesService,
public dialog: MatDialog) { }
ngOnInit(): void {
this.initModel();
let data = localStorage.getItem('chat');
if(!data){
setTimeout(() => {
this.openUserPopup(this.defaultDialogUserParams);
}, 0);
}
else {
this.messages = this.messagesService.getMyMessages();
}
}
ngAfterViewInit(): void {
// subscribing to any changes in the list of items / messages
this.matListItems.changes.subscribe(elements => {
this.scrollToBottom();
});
}
ngOnDestroy():void {
this.ioConnection.unsubscribe();
}
private scrollToBottom(): void {
try {
this.matList.nativeElement.scrollTop = this.matList.nativeElement.scrollHeight;
} catch (err) {
}
}
private initModel(): void {
const randomId = this.getRandomId();
let data = localStorage.getItem('chat');
if(data) {
this.currentUser = JSON.parse(data);
this.user = {
id: this.currentUser.id,
avatar: this.currentUser.avatar,
name: this.currentUser.name
};
this.initIoConnection();
let paramsDialog = {
dialogType: 0,
previousUsername: undefined,
username: 'hello'
};
}
else {
this.user = {
id: randomId,
avatar: `${AVATAR_URL}/${randomId}.png`
};
}
}
private initIoConnection(): void {
this.socketService.initSocket();
this.ioConnection = this.socketService.onMessage()
.subscribe((message: Message) => {
this.messages.push(message);
});
this.socketService.onEvent(Event.CONNECT)
.subscribe(() => {
console.log('connected');
});
this.socketService.onEvent(Event.DISCONNECT)
.subscribe(() => {
console.log('disconnected');
});
}
private getRandomId(): number {
return Math.floor(Math.random() * (1000000)) + 1;
}
public onClickUserInfo() {
this.openUserPopup({
data: {
username: this.user.name,
title: 'Edit Details',
dialogType: DialogUserType.EDIT
}
});
}
private openUserPopup(params): void {
this.dialogRef = this.dialog.open(DialogUserComponent, params);
this.dialogRef.afterClosed().subscribe(paramsDialog => {
if (!paramsDialog) {
return;
}
this.user.name = paramsDialog.username;
if (paramsDialog.dialogType === DialogUserType.NEW) {
this.initIoConnection();
this.sendNotification(paramsDialog, Action.JOINED);
} else if (paramsDialog.dialogType === DialogUserType.EDIT) {
this.sendNotification(paramsDialog, Action.RENAME);
}
localStorage.setItem('chat',JSON.stringify(this.user));
});
}
public sendMessage(message: string): void {
if (!message) {
return;
}
const currentTime = new Date();
let hours: number = currentTime.getHours();
let minutes: any = currentTime.getMinutes();
minutes = minutes < 10 ? '0' + minutes : minutes;
let ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
const timeFormatted = `${hours}:${minutes} ${ampm}`;
this.socketService.send({
from: this.user,
content: message,
time: timeFormatted
});
this.messageContent = null;
}
public sendNotification(params: any, action: Action): void {
let message: Message;
if (action === Action.JOINED) {
message = {
from: this.user,
action: action
}
} else if (action === Action.RENAME) {
message = {
action: action,
content: {
username: this.user.name,
previousUsername: params.previousUsername
}
};
}
this.socketService.send(message);
}
public sendMessageFire(event, message){
if(event.ctrlKey && event.key === 'Enter') {
this.sendMessage(message);
}
else if(event.key === 'Enter'){
this.sendMessage(message);
}
}
}
|
<template>
<article class="article">
<LayoutIsland class="article__content" shadowed>
<div
v-for="block in blocks"
:key="block.id"
class="article__content-block"
>
<ArticleHeaderBlock
v-if="block.type === 'header'"
:level="block.data.level"
:text="block.data.text"
/>
<ArticleParagraphBlock
v-else-if="block.type === 'paragraph'"
:text="block.data.text"
/>
</div>
</LayoutIsland>
<div v-if="draft && isEditor" class="article__draft-section">
<v-btn class="accept" @click="resolveDraft('accept')">
Опубликовать
</v-btn>
<v-btn class="decline" @click="resolveDraft('decline')">
Отклонить
</v-btn>
</div>
<LayoutIsland v-else shadowed>
<h3 class="article__comments-count">
{{ commentsTitle }}
</h3>
<UITextarea
v-if="isAuth"
v-model="commentText"
placeholder="Напишите комментарий"
>
<v-btn
color="#6665DD"
class="article__comments-publish-btn"
:disabled="!commentText"
:loading="commentIsSending"
@click="sendComment"
>
Отправить
</v-btn>
</UITextarea>
<div class="article__comments-list">
<CommentItem
v-for="(item, index) in comments"
:key="index"
class="article__comments-item"
:author="item.author"
:avatar="item.avatar"
:text="item.text"
/>
</div>
</LayoutIsland>
<Modal
name="article-decline"
adaptive
height="auto"
>
<ModalArticleDecline @success="closeDeclineModal" />
</Modal>
</article>
</template>
<script>
import { pluralize } from '@/utils/string'
import LayoutIsland from '@/components/layouts/LayoutIsland'
import UITextarea from '@/components/ui/UITextarea'
import ModalArticleDecline from '@/components/modals/modal-article-decline'
import CommentItem from '@/components/comments/CommentItem'
import ArticleHeaderBlock from '@/components/article/blocks/ArticleHeaderBlock'
import ArticleParagraphBlock from '@/components/article/blocks/ArticleParagraphBlock'
export default {
name: 'ArticlePage',
components: {
LayoutIsland,
UITextarea,
ModalArticleDecline,
CommentItem,
ArticleHeaderBlock,
ArticleParagraphBlock
},
async asyncData ({ $axios, redirect, params }) {
if (!params.id) {
redirect('/')
}
const { data: { article } } = await $axios.get(`/article/${params.id}`)
return {
blocks: article.blocks,
publicationTimestamp: article.time,
commentsCount: article.commentsCount,
comments: article.comments,
draft: article.draft
}
},
data () {
return {
blocks: [],
publicationTimestamp: 0,
commentsCount: 0,
commentText: '',
comments: [],
commentIsSending: false,
draft: false
}
},
computed: {
commentsTitle () {
return pluralize(this.commentsCount, ['комментарий', 'комментария', 'комментариев'])
},
isAuth () {
return this.$store.state.user.isAuth
},
isEditor () {
return this.$store.state.user.role === 'editor'
}
},
methods: {
sendComment () {
this.commentIsSending = true
setTimeout(() => {
this.commentIsSending = false
this.commentText = ''
}, 2000)
},
resolveDraft (resolve) {
if (resolve === 'accept') {
this.$notify({
type: 'success',
title: 'Статья опубликована'
})
this.$router.push('/publications')
} else {
this.$modal.show('article-decline')
}
},
closeDeclineModal () {
this.$modal.hide('article-decline')
this.$notify({
type: 'success',
title: 'Статья отклонена'
})
this.$router.push('/publications')
}
}
}
</script>
<style lang="sass" scoped>
@import "assets/sass/variables"
.article
&__content
margin-bottom: 24px
&__content-block
& + &
margin-top: 16px
&__comments-count
margin-bottom: 18px
&__comments-list
margin-top: 24px
&__comments-item
& + &
margin-top: 24px
&__comments-publish-btn
color: $white
&__draft-section
display: flex
.accept,
.decline
color: $white
.accept
margin-left: auto
background-color: $may-green
.decline
margin-left: 5px
background-color: $upsdellRed
</style>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>then()方法的返回结果是Promise对象</title>
</head>
<body>
<script>
let p = new Promise((res,rej)=>{
res('Ok')
})
/** 之前我们都是直接执行then方法,现在我们查看该方法返回了什么。
then返回的是Promise对象,且该对象的状态(fulfilled、rejected)和你在哪个分支,在该分支里面做了什么有关 */
let result = p.then(value=>{
// 什么都不做,进入res分支,则为fulfilled
console.log(value)
// 如果抛出异常,则尽管是在res分支下,也会变成rejected
// throw("抛出异常,则变为rejected!")
// 返回结果是非Promise对象,也是fulfilled状态(但是值是521)
// return 521;
// 返回promise对象,那就会直接覆盖result为你现在定义的对象
return new Promise((res,rej)=>{
rej('在里面我返回rejected对象')
})
},reason=>{
// 什么都不做,进入rej分支,则返回的为rejected
console.warn(reason)
})
console.log(result) // [[Prototype]]: Promise
</script>
</body>
</html>
|
const router = require('express').Router()
const cloudinary = require('cloudinary')
const auth = require('../middleware/auth')
const authAdmin = require('../middleware/authAdmin')
const fs = require('fs')
// we will upload image on cloudinary
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.CLOUD_API_KEY,
api_secret: process.env.CLOUD_API_SECRET
})
// Upload image only admin can use
router.post('/upload',auth, authAdmin, (req,res) =>{
try {
// console.log(req.files)
if(!req.files || Object.keys(req.files).length === 0)
return res.status(400).json({msg: 'No files were uploaded'})
const file = req.files.file;
if(file.size > 1024*1024) {
removeTmp(file.tempFilePath)
return res.status(400).json({msg:'Size too large'})
}
if(file.mimetype !== 'image/jpeg' && 'image/png'){
removeTmp(file.tempFilePath)
return res.status(400).json({msg:'FIle fomrat is incorrect'})
}
cloudinary.v2.uploader.upload(file.tempFilePath,{folder: "test"}, async (err, result) => {
if(err) throw err;
removeTmp(file.tempFilePath)
res.json({public_id:result.public_id, url:result.secure_url})
})
} catch (err) {
return res.status(500).json({msg: err.message})
}
})
// Delete image only admin can use
router.post('/destroy',auth, authAdmin, (req, res) =>{
try {
const {public_id} =req.body;
console.log(public_id)
if(!public_id) return res.status(400).json({msg:'No images Selected'})
cloudinary.v2.uploader.destroy(public_id, async (err, result)=>{
if(err) throw err
res.json({msg:'Deleted Image'})
})
} catch (err) {
return res.status(500).json({msg: err.message})
}
})
const removeTmp = (path) => {
fs.unlink(path,err => {
if(err) throw err
})
}
module.exports = router
|
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiResponse,ApiTags } from '@nestjs/swagger';
import { ClientService } from './client.service';
import { SettingsDto } from './dto/settings.dto';
import { TestCallDto } from './dto/test-call.dto';
import { Observable } from 'rxjs';
@Controller('client')
export class ClientController {
constructor(private readonly clientService: ClientService) {}
clientPort = 3000
clientKey= 'AAAAA'
clientEndpoint= '10.0.1.2'
@Post('test-call')
@ApiOperation({ summary: 'Client test call to server' })
@ApiResponse({status: 200, description: 'Test status', type: String })
async testCall(@Body() testCallDto: TestCallDto): Promise<any> {
console.log("test-call from controller")
return this.clientService.testCall(testCallDto, this.clientPort, this.clientKey, this.clientEndpoint)
}
@Post('settings')
@ApiOperation({ summary: 'Client settings to communicate to server' })
@ApiResponse({status: 200, description: 'Settings status', type: String })
async settings(@Body() settingsDto: SettingsDto): Promise<String> {
console.log("settings from controller")
this.clientPort = settingsDto.port
this.clientKey = settingsDto.key
this.clientEndpoint = settingsDto.endpoint
return "success"
}
}
|
/**
* View component for /firms/:firmId/workspaces/:clientId/client-workflow-templates
*
* Displays a list of clientWorkflowTemplates on a left sidebar and a preview of the template on the right.
*/
// import primary libraries
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Link, Route, Switch, withRouter } from 'react-router-dom';
import classNames from 'classnames';
// import actions
import * as firmActions from '../../../firm/firmActions';
import * as clientWorkflowTemplateActions from '../../clientWorkflowTemplateActions';
// import global components
import Binder from '../../../../global/components/Binder.js.jsx';
import YTRoute from '../../../../global/components/routing/YTRoute.js.jsx';
import ClientWorkflowTemplateLayout from '../../components/ClientWorkflowTemplateLayout.js.jsx';
// import resource components
import PracticeClientWorkflowTemplateList from '../components/PracticeClientWorkflowTemplateList.js.jsx';
import PracticeClientWorkflowTemplatePreview from './PracticeClientWorkflowTemplatePreview.js.jsx';
class PracticeClientWorkflowTemplates extends Binder {
constructor(props) {
super(props);
}
componentDidMount() {
const { dispatch, history, match } = this.props;
dispatch(clientWorkflowTemplateActions.fetchListIfNeeded('status', 'published')).then(cwtRes => {
if(cwtRes.success) {
const firstTemplate = cwtRes.list && cwtRes.list[0] ? cwtRes.list[0] : null
if(firstTemplate) {
history.push(`${match.url}/${firstTemplate._id}`)
}
}
})
dispatch(firmActions.fetchSingleIfNeeded(match.params.firmId));
}
render() {
const { clientWorkflowTemplateStore, location, match} = this.props;
/**
* use the selected.getItem() utility to pull the actual firm object from the map
*/
const clientWorkflowTemplateList = clientWorkflowTemplateStore.util.getList('status', 'published');
const clientWorkflowTemplateListInfo = (
clientWorkflowTemplateStore
&& clientWorkflowTemplateStore.lists
&& clientWorkflowTemplateStore.lists.status
&& clientWorkflowTemplateStore.lists.status.published ? clientWorkflowTemplateStore.lists.status.published : null
);
const isEmpty = (
!clientWorkflowTemplateList
|| !clientWorkflowTemplateListInfo
);
const isFetching = (
!clientWorkflowTemplateListInfo
|| clientWorkflowTemplateListInfo.isFetching
);
return (
<ClientWorkflowTemplateLayout
header="Template Preview"
>
{ isEmpty ?
(isFetching ? <h2>Loading...</h2> : <h2>Empty.</h2>)
:
<div style={{ opacity: isFetching ? 0.5 : 1 }}>
<div className="template-preview-sidebar">
<div className="tab-bar-nav">
<div className="-sidebar-menu">
<div className="-icon">
<a className="-exit-preview" href={match.url.replace('client-workflow-templates', 'client-workflows')}>
<p><i className="fas fa-arrow-left"></i>Back to client workflows</p>
</a>
</div>
</div>
</div>
<div className="-content">
<h4>Click on a template below to see a preview</h4>
<PracticeClientWorkflowTemplateList
clientWorkflowTemplateList={clientWorkflowTemplateList}
setSelectedTemplate={this._setSelectedTemplate}
/>
</div>
</div>
<Switch location={location}>
<YTRoute
component={PracticeClientWorkflowTemplatePreview}
exact
path="/firm/:firmId/workspaces/:clientId/client-workflow-templates/:clientWorkflowTemplateId"
login={true}
/>
<Route render={() =>
<div/>
}/>
</Switch>
</div>
}
</ClientWorkflowTemplateLayout>
)
}
}
PracticeClientWorkflowTemplates.propTypes = {
dispatch: PropTypes.func.isRequired
}
const mapStoreToProps = (store) => {
/**
* NOTE: Yote refer's to the global Redux 'state' as 'store' to keep it mentally
* differentiated from the React component's internal state
*/
return {
clientWorkflowTemplateStore: store.clientWorkflowTemplate
}
}
export default withRouter(
connect(
mapStoreToProps
)(PracticeClientWorkflowTemplates)
);
|
import telebot
from config import keys, TOKEN
from extensions import APIException, CurrencyConverter
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=['start', 'help'])
def handle_start_help(message: telebot.types.Message):
text = f'Чтобы начать работу введите комманду боту в следующем формате:\n<имя вылюты>\
<в какyю валюту перевести>\
<количество валюты>\nУвидить все доступные валюты: /values'
bot.send_message(message.chat.id, text)
@bot.message_handler(commands=['values'])
def values(message: telebot.types.Message):
text = 'Доступные валюты:'
for key in keys.keys():
text = '\n'.join((text, key, ))
bot.send_message(message.chat.id, text)
@bot.message_handler(content_types=['text'])
def convert(message: telebot.types.Message):
try:
values = message.text.split(' ')
if len(values) != 3:
raise APIException('Некорректное количество параметров. Повторите попытку ввода.')
quote, base, amount = values
total_base = CurrencyConverter.get_price(quote, base, amount)
except APIException as e:
bot.send_message(message.chat.id, f'Ошибка пользователя.\n{e}')
except Exception as e:
bot.send_message(message.chat.id, f'Не удалось обработать команду. \n{e}')
else:
text = f'Цена {amount} {quote} в {base} - {total_base}'
bot.send_message(message.chat.id, text)
bot.polling()
|
package no.vedaadata.excel
import java.time.*
import org.apache.poi.ss.usermodel.*
trait CellStyleProvider[-A]:
def provide(baseStyle: CellStyle)(using wb: Workbook): CellStyle
object CellStyleProvider:
given default[A]: CellStyleProvider[A] with
def provide(baseStyle: CellStyle)(using wb: Workbook) = baseStyle
given option[A](using inner: CellStyleProvider[A]): CellStyleProvider[Option[A]] with
def provide(baseStyle: CellStyle)(using wb: Workbook) = inner.provide(baseStyle)
given localDate: CellStyleProvider[LocalDate] with
def provide(baseStyle: CellStyle)(using wb: Workbook) =
val cellStyle = wb.createCellStyle
cellStyle.cloneStyleFrom(baseStyle)
cellStyle.setDataFormat(0x0e) // magic Excel number, "m/d/yy"
cellStyle
given localTime: CellStyleProvider[LocalTime] with
def provide(baseStyle: CellStyle)(using wb: Workbook) =
val cellStyle = wb.createCellStyle
cellStyle.cloneStyleFrom(baseStyle)
cellStyle.setDataFormat(0x15) // magic Excel number, "h:mm:ss"
cellStyle
given localDateTime: CellStyleProvider[LocalDateTime] with
def provide(baseStyle: CellStyle)(using wb: Workbook) =
val cellStyle = wb.createCellStyle
cellStyle.cloneStyleFrom(baseStyle)
cellStyle.setDataFormat(0x16) // magic Excel number, "m/d/yy h:mm"
cellStyle
trait CellStyleFactory extends (Workbook => CellStyle)
trait CellStyleFactoryCompanion:
trait BoldCellStyleFactory extends CellStyleFactory:
def apply(wb: Workbook) =
val cellStyle = wb.createCellStyle()
val font = wb.createFont()
font.setBold(true)
cellStyle.setFont(font)
cellStyle
trait ItalicCellStyleFactory extends CellStyleFactory:
def apply(wb: Workbook) =
val cellStyle = wb.createCellStyle()
val font = wb.createFont()
font.setItalic(true)
cellStyle.setFont(font)
cellStyle
trait HeaderCellStyleFactory extends CellStyleFactory
object HeaderCellStyleFactory extends CellStyleFactoryCompanion:
given default: HeaderCellStyleFactory = _.createCellStyle()
object Bold extends HeaderCellStyleFactory with BoldCellStyleFactory
object Italic extends HeaderCellStyleFactory with ItalicCellStyleFactory
|
/*
* SPDX-FileCopyrightText: 2016 (c) Business Operation Systems GmbH <info@top-logic.com>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-BOS-TopLogic-1.0
*/
package com.top_logic.layout.tools.cleanup;
import static com.top_logic.basic.core.xml.DOMUtil.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import com.top_logic.basic.Main;
import com.top_logic.basic.StringServices;
import com.top_logic.basic.col.map.MultiMaps;
import com.top_logic.basic.io.FileUtilities;
import com.top_logic.basic.xml.DOMUtil;
import com.top_logic.basic.xml.XMLPrettyPrinter;
import com.top_logic.layout.I18NConstantsBase;
import com.top_logic.layout.tools.FileHandler;
import com.top_logic.layout.tools.FileUtil;
/**
* Tool to process layout XML files and add/normalize resource keys and prefixes defined in those
* files.
*
* @author <a href="mailto:bhu@top-logic.com">Bernhard Haumacher</a>
*/
public class AddResourcePrefix extends Main implements FileHandler {
private final Map<String, Set<String>> _prefixMapping = new HashMap<>();
private boolean _updateAll = true;
private boolean _verbose;
private boolean _masterFrame;
private static final Set<String> IGNORED = new HashSet<>(
Arrays.asList(
"com.top_logic.mig.html.layout.FragmentComponent",
"com.top_logic.layout.component.TabComponent",
"com.top_logic.knowledge.gui.layout.ButtonComponent",
"com.top_logic.tool.boundsec.CockpitLayout",
"com.top_logic.tool.boundsec.WindowLayout",
"com.top_logic.knowledge.gui.layout.TLMainLayout",
"com.top_logic.tool.boundsec.BoundMainLayout",
"com.top_logic.tool.boundsec.BoundLayout",
"%INFO_COMPONENT%",
"com.top_logic.tool.boundsec.compound.CompoundSecurityInfoComponent",
"com.top_logic.extensions.ewe.layout.inbox.DynamicWrapperLayout",
"%MAIN_LAYOUT_CLASS%"
));
/**
* Main entry point.
*
* @param args
* {@link File#pathSeparator}-separated paths with files to process.
*/
public static void main(String[] args) throws Exception {
AddResourcePrefix tool = new AddResourcePrefix();
tool.runMainCommandLine(args);
tool.storeMapping();
}
@Override
protected boolean argumentsRequired() {
return true;
}
@Override
protected int longOption(String option, String[] args, int i) {
if ("add-only".equals(option)) {
_updateAll = false;
return i;
}
if ("update-existing".equals(option)) {
_updateAll = true;
return i;
}
if ("verbose".equals(option)) {
_verbose = true;
return i;
}
if ("quiet".equals(option)) {
_verbose = false;
return i;
}
return super.longOption(option, args, i);
}
@Override
protected int parameter(String[] args, int i) throws Exception {
FileUtil.handleFile(args[i++], this);
return i;
}
@Override
protected void doActualPerformance() throws Exception {
// Nothing more.
}
private void storeMapping() throws FileNotFoundException, IOException {
ResourceMappingUtil.storeMappings(_prefixMapping);
}
@Override
public void handleFile(String fileName) throws IOException, SAXException {
File file = new File(fileName);
if (file.isDirectory()) {
scan(file);
} else {
update(file);
}
}
private void scan(File dir) throws SAXException, IOException {
for (File file : FileUtilities.listFiles(dir)) {
if (file.getName().startsWith(".")) {
continue;
}
if (file.isDirectory()) {
scan(file);
} else {
if (file.getName().endsWith("_alias.xml")) {
continue;
}
if (!file.getName().endsWith(".xml")) {
continue;
}
update(file);
}
}
}
private void update(File file) throws SAXException, IOException, FileNotFoundException {
String packageName = packageName(file);
Document document = parse(file);
_masterFrame = file.getName().matches("(?i).*masterframe.xml");
boolean hasUpdate = update(packageName, document);
if (hasUpdate) {
System.out.println("Updating: " + file);
dump(document, file);
} else {
if (_verbose) {
System.out.println("Up to date: " + file);
}
}
}
private String packageName(File file) throws IOException {
File canonicalFile = file.getCanonicalFile();
String path = canonicalFile.getPath().replace(File.separatorChar, '/');
String base = "/WEB-INF/layouts/";
int baseIndex = path.indexOf(base);
if (baseIndex < 0) {
throw new IllegalArgumentException("File not within a web application's layouts directory: " + path);
}
String packageName = path.substring(baseIndex + base.length()).replaceFirst(".xml$", "").replace('/', '.');
return packageName;
}
private static Document parse(File file) throws SAXException, IOException {
Document document = DOMUtil.getDocumentBuilder().parse(file);
return document;
}
private boolean update(String packageName, Node node) {
boolean hasUpdate = false;
for (Element element : elements(node)) {
hasUpdate |= updateLocal(packageName, element);
// Descend.
hasUpdate |= update(packageName, element);
}
return hasUpdate;
}
private boolean updateLocal(String packageName, Element element) {
if (isElement(null, "component", element)) {
return updateComponent(packageName, element);
}
if (isElement(null, "open-handler", element)) {
return updateHandler(packageName, element);
}
if (isElement(null, "handler", element)) {
return updateHandler(packageName, element);
}
if (isElement(null, "button", element)) {
return updateHandler(packageName, element);
}
if (isElement(null, "tab", element)) {
return updateTab(packageName, element);
}
return false;
}
private boolean updateTab(String packageName, Element element) {
Element info = childElement(element, null, "info");
if (info == null) {
return false;
}
String legacyKey = property(info, "TabInfo.name");
boolean hasName = !StringServices.isEmpty(legacyKey);
if (!hasName) {
// Cannot generate a name.
return false;
}
if (_masterFrame) {
// Just record mapping to prevent rewriting a globally defined key.
addMapping(legacyKey, legacyKey);
return false;
}
if (addOnly()) {
return false;
}
if (containsVariable(legacyKey)) {
return false;
}
String canonicalName = legacyKey;
if (canonicalName.endsWith(".tabber")) {
canonicalName = canonicalName.substring(0, canonicalName.length() - ".tabber".length());
}
else if (canonicalName.endsWith(".tab")) {
canonicalName = canonicalName.substring(0, canonicalName.length() - ".tab".length());
}
String canonicalKey = canonicalKey(packageName, camelCase(canonicalName)) + ".tab";
info.setAttributeNS(null, "TabInfo.name", canonicalKey);
addMapping(legacyKey, canonicalKey);
return true;
}
private boolean updateHandler(String packageName, Element element) {
String resourceKey = property(element, "resourceKey");
boolean hasResourceKey = !StringServices.isEmpty(resourceKey);
if (addOnly()) {
if (hasResourceKey || _masterFrame) {
return false;
}
}
if (containsVariable(resourceKey)) {
return false;
}
String id = property(element, "id");
if (StringServices.isEmpty(id)) {
return false;
}
String camelCaseName = camelCase(id);
String canonicalKey = canonicalKey(packageName, camelCaseName);
element.setAttributeNS(null, "resourceKey", canonicalKey);
String legacyKey = hasResourceKey ? resourceKey : "tl.command." + id;
addMapping(legacyKey, canonicalKey);
return true;
}
private boolean containsVariable(String value) {
return value != null && value.contains("$");
}
private boolean updateComponent(String packageName, Element element) {
String resPrefix = property(element, "resPrefix");
boolean hasResourcePrefix = !StringServices.isEmpty(resPrefix);
if (addOnly()) {
if (hasResourcePrefix || _masterFrame) {
return false;
}
}
if (containsVariable(resPrefix)) {
return false;
}
String name = property(element, "name");
if (StringServices.isEmpty(name)) {
if (hasResourcePrefix) {
name = "";
} else {
return false;
}
}
String implClass = property(element, "class");
if (implClass == null || implClass.endsWith("ReferenceComponent") || IGNORED.contains(implClass)) {
if (hasResourcePrefix) {
if (implClass == null) {
implClass = "";
}
} else {
return false;
}
}
String localName = removeVariables(name);
String camelCaseName = camelCase(localName);
if (camelCaseName.isEmpty()) {
// In case the complete component name has been aliased.
camelCaseName = "main";
}
String legacyResPrefix = hasResourcePrefix ? resPrefix :
(implClass.indexOf('.') < 0) ? implClass : I18NConstantsBase.getLegacyResPrefix(implClass) + ".";
String canonicalResPrefix = canonicalPrefix(packageName, camelCaseName);
element.setAttributeNS(null, "resPrefix", canonicalResPrefix);
addMapping(legacyResPrefix, canonicalResPrefix);
return true;
}
private boolean addOnly() {
return !_updateAll;
}
private void addMapping(String legacyResPrefix, String canonicalResPrefix) {
MultiMaps.add(_prefixMapping, legacyResPrefix, canonicalResPrefix);
}
private String canonicalKey(String packageName, String camelCaseName) {
return "layouts." + packageName + "." + camelCaseName;
}
private String canonicalPrefix(String packageName, String camelCaseName) {
return "layouts." + packageName + "." + camelCaseName + ".";
}
private String property(Element element, String name) {
String result = element.getAttributeNS(null, name);
if (StringServices.isEmpty(result)) {
// Check for subtag configuration.
Element propertyTag = childElement(element, null, name);
if (propertyTag != null) {
result = propertyTag.getTextContent();
// Normalize for further processing.
element.removeChild(propertyTag);
element.setAttributeNS(null, name, result);
}
}
return result;
}
private static Element childElement(Element element, String ns, String name) {
for (Element child : elements(element)) {
if (isElement(ns, name, child)) {
return child;
}
}
return null;
}
private String camelCase(String localName) {
StringBuilder buffer = new StringBuilder();
for (String part : localName.split("[^A-Za-z0-9]+")) {
if (part.isEmpty()) {
continue;
}
if (buffer.length() == 0) {
buffer.append(part);
} else {
buffer.append(Character.toUpperCase(part.charAt(0)));
buffer.append(part.substring(1));
}
}
String camelCaseName = buffer.toString();
return camelCaseName;
}
private String removeVariables(String name) {
return name.replaceAll("(?:\\$\\{[^\\}]*\\})|(?:\\$[^\\$]+\\$)", "");
}
private static void dump(Document document, File file) throws FileNotFoundException, IOException {
OutputStream out = new FileOutputStream(file);
try {
XMLPrettyPrinter.dump(out, document);
} finally {
out.close();
}
}
}
|
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Ice
import PromiseKit
import TestCommon
class TestI: TestIntf {
var _helper: TestHelper
var _values = [Value]()
init(_ helper: TestHelper) {
_helper = helper
}
deinit {
for value in _values {
breakCycles(value)
}
}
private func breakCycles(_ value: Value) {
if let d1 = value as? D1 {
let tmp = d1.pd1
d1.pd1 = nil
if tmp != nil, tmp! !== d1 {
breakCycles(tmp!)
}
}
if let d2 = value as? D2 {
d2.pd2 = nil
}
if let d4 = value as? D4 {
d4.p1 = nil
d4.p2 = nil
}
if let b = value as? B {
b.pb?.pb = nil
b.pb = nil
}
if let p = value as? Preserved {
p.ice_getSlicedData()?.clear()
}
if let p = value as? PDerived {
p.pb = nil
}
if let p = value as? CompactPDerived {
p.pb = nil
}
if var curr = value as? PNode {
while curr.next != nil, value !== curr.next {
curr = curr.next!
}
curr.next = nil
}
if let p = value as? PSUnknown, p.graph != nil {
breakCycles(p.graph!)
}
if let p = value as? PSUnknown2 {
p.pb = nil
}
if let s = value as? SS1 {
for b in s.s where b != nil {
breakCycles(b!)
}
}
if let s = value as? SS2 {
for b in s.s where b != nil {
breakCycles(b!)
}
}
if let f = value as? Forward {
f.h = nil
}
if let u = value as? SUnknown {
u.cycle = nil
}
}
func SBaseAsObject(current _: Current) throws -> Value? {
return SBase(sb: "SBase.sb")
}
func SBaseAsSBase(current _: Current) throws -> SBase? {
return SBase(sb: "SBase.sb")
}
func SBSKnownDerivedAsSBase(current _: Current) throws -> SBase? {
return SBSKnownDerived(sb: "SBSKnownDerived.sb", sbskd: "SBSKnownDerived.sbskd")
}
func SBSKnownDerivedAsSBSKnownDerived(current _: Current) throws -> SBSKnownDerived? {
return SBSKnownDerived(sb: "SBSKnownDerived.sb", sbskd: "SBSKnownDerived.sbskd")
}
func SBSUnknownDerivedAsSBase(current _: Current) throws -> SBase? {
return SBSUnknownDerived(sb: "SBSUnknownDerived.sb", sbsud: "SBSUnknownDerived.sbsud")
}
func SBSUnknownDerivedAsSBaseCompact(current _: Current) throws -> SBase? {
return SBSUnknownDerived(sb: "SBSUnknownDerived.sb", sbsud: "SBSUnknownDerived.sbsud")
}
func SUnknownAsObject(current _: Current) throws -> Value? {
let su = SUnknown()
su.su = "SUnknown.su"
su.cycle = su
_values.append(su)
return su
}
func checkSUnknown(o: Value?, current: Current) throws {
let su = o as? SUnknown
if current.encoding == Ice.Encoding_1_0 {
try _helper.test(su == nil)
} else {
try _helper.test(su!.su == "SUnknown.su")
su!.cycle = nil
}
}
func oneElementCycle(current _: Current) throws -> B? {
let b = B()
b.sb = "B1.sb"
b.pb = b
_values.append(b)
return b
}
func twoElementCycle(current _: Current) throws -> B? {
let b1 = B()
b1.sb = "B1.sb"
let b2 = B()
b2.sb = "B2.sb"
b2.pb = b1
b1.pb = b2
_values.append(b1)
return b1
}
func D1AsB(current _: Current) throws -> B? {
let d1 = D1()
d1.sb = "D1.sb"
d1.sd1 = "D1.sd1"
let d2 = D2()
d2.pb = d1
d2.sb = "D2.sb"
d2.sd2 = "D2.sd2"
d2.pd2 = d1
d1.pb = d2
d1.pd1 = d2
_values.append(d1)
return d1
}
func D1AsD1(current _: Current) throws -> D1? {
let d1 = D1()
d1.sb = "D1.sb"
d1.sd1 = "D1.sd1"
let d2 = D2()
d2.pb = d1
d2.sb = "D2.sb"
d2.sd2 = "D2.sd2"
d2.pd2 = d1
d1.pb = d2
d1.pd1 = d2
_values.append(d1)
return d1
}
func D2AsB(current _: Current) throws -> B? {
let d2 = D2()
d2.sb = "D2.sb"
d2.sd2 = "D2.sd2"
let d1 = D1()
d1.pb = d2
d1.sb = "D1.sb"
d1.sd1 = "D1.sd1"
d1.pd1 = d2
d2.pb = d1
d2.pd2 = d1
_values.append(d1)
return d2
}
func paramTest1(current _: Current) throws -> (p1: B?, p2: B?) {
let d1 = D1()
d1.sb = "D1.sb"
d1.sd1 = "D1.sd1"
let d2 = D2()
d2.pb = d1
d2.sb = "D2.sb"
d2.sd2 = "D2.sd2"
d2.pd2 = d1
d1.pb = d2
d1.pd1 = d2
_values.append(d1)
return (d1, d2)
}
func paramTest2(current: Current) throws -> (p2: B?, p1: B?) {
let ret = try paramTest1(current: current)
return (ret.p2, ret.p1)
}
func paramTest3(current _: Current) throws -> (returnValue: B?, p1: B?, p2: B?) {
let d2 = D2()
d2.sb = "D2.sb (p1 1)"
d2.pb = nil
d2.sd2 = "D2.sd2 (p1 1)"
let d1 = D1()
d1.sb = "D1.sb (p1 2)"
d1.pb = nil
d1.sd1 = "D1.sd2 (p1 2)"
d1.pd1 = nil
d2.pd2 = d1
let d4 = D2()
d4.sb = "D2.sb (p2 1)"
d4.pb = nil
d4.sd2 = "D2.sd2 (p2 1)"
let d3 = D1()
d3.sb = "D1.sb (p2 2)"
d3.pb = nil
d3.sd1 = "D1.sd2 (p2 2)"
d3.pd1 = nil
d4.pd2 = d3
_values.append(d1)
_values.append(d2)
_values.append(d3)
_values.append(d4)
return (d3, d2, d4)
}
func paramTest4(current _: Current) throws -> (returnValue: B?, p: B?) {
let d4 = D4()
d4.sb = "D4.sb (1)"
d4.pb = nil
d4.p1 = B()
d4.p1!.sb = "B.sb (1)"
d4.p2 = B()
d4.p2!.sb = "B.sb (2)"
_values.append(d4)
return (d4.p2, d4)
}
func returnTest1(current: Current) throws -> (returnValue: B?, p1: B?, p2: B?) {
let ret = try paramTest1(current: current)
return (ret.p1, ret.p1, ret.p2)
}
func returnTest2(current: Current) throws -> (returnValue: B?, p2: B?, p1: B?) {
let ret = try paramTest1(current: current)
return (ret.p1, ret.p1, ret.p2)
}
func returnTest3(p1: B?, p2: B?, current _: Current) -> B? {
_values.append(p1!)
_values.append(p2!)
return p1
}
func sequenceTest(p1: SS1?, p2: SS2?, current _: Current) throws -> SS3 {
let ss = SS3()
ss.c1 = p1
ss.c2 = p2
_values.append(p1!)
_values.append(p2!)
return ss
}
func dictionaryTest(bin: BDict, current _: Current) throws -> (returnValue: BDict, bout: BDict) {
var bout = [Int32: B?]()
for i: Int32 in 0 ..< 10 {
let b = bin[i]!!
let d2 = D2()
d2.sb = b.sb
d2.pb = b.pb
d2.sd2 = "D2"
d2.pd2 = d2
_values.append(d2)
bout[i * 10] = d2
}
var r = [Int32: B]()
for i: Int32 in 0 ..< 10 {
let s = "D1.\(i * 20)"
let d1 = D1()
d1.sb = s
d1.pb = i == 0 ? nil : r[(i - 1) * 20]
d1.sd1 = s
d1.pd1 = d1
_values.append(d1)
r[i * 20] = d1
}
return (r, bout)
}
func exchangePBase(pb: PBase?, current _: Current) throws -> PBase? {
_values.append(pb!)
return pb
}
func PBSUnknownAsPreserved(current: Current) throws -> Preserved? {
let r = PSUnknown()
r.pi = 5
r.ps = "preserved"
r.psu = "unknown"
r.graph = nil
if current.encoding != Ice.Encoding_1_0 {
//
// 1.0 encoding doesn't support unmarshaling unknown classes even if referenced
// from unread slice.
//
r.cl = MyClass(i: 15)
}
return r
}
func checkPBSUnknown(p: Preserved?, current: Current) throws {
if current.encoding == Ice.Encoding_1_0 {
try _helper.test(!(p is PSUnknown))
try _helper.test(p!.pi == 5)
try _helper.test(p!.ps == "preserved")
} else {
let pu = p as! PSUnknown
try _helper.test(pu.pi == 5)
try _helper.test(pu.ps == "preserved")
try _helper.test(pu.psu == "unknown")
try _helper.test(pu.graph == nil)
try _helper.test(pu.cl != nil && pu.cl!.i == 15)
}
}
func PBSUnknownAsPreservedWithGraphAsync(current: Current) -> Promise<Preserved?> {
// This code requires a regular, non-colloc dispatch
if let dq = try? current.adapter!.getDispatchQueue() {
dispatchPrecondition(condition: .onQueue(dq))
}
return Promise<Preserved?> { seal in
// .barrier to ensure we execute this code after Ice has called "done" on the promise
// Otherwise the cycle breaking can occur before the result is marshaled by the
// closure given to done.
try current.adapter!.getDispatchQueue().async(flags: .barrier) {
let r = PSUnknown()
r.pi = 5
r.ps = "preserved"
r.psu = "unknown"
r.graph = PNode()
r.graph!.next = PNode()
r.graph!.next!.next = PNode()
r.graph!.next!.next!.next = r.graph
seal.fulfill(r) // Ice marshals r now
r.graph!.next!.next!.next = nil // break the cycle
}
}
}
func checkPBSUnknownWithGraph(p: Preserved?, current: Current) throws {
if current.encoding == Ice.Encoding_1_0 {
try _helper.test(!(p is PSUnknown))
try _helper.test(p!.pi == 5)
try _helper.test(p!.ps == "preserved")
} else {
let pu = p as! PSUnknown
try _helper.test(pu.pi == 5)
try _helper.test(pu.ps == "preserved")
try _helper.test(pu.psu == "unknown")
try _helper.test(pu.graph !== pu.graph!.next)
try _helper.test(pu.graph!.next !== pu.graph!.next!.next)
if pu.graph!.next!.next!.next == nil {
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
try _helper.test(false)
} else {
try _helper.test(pu.graph!.next!.next!.next === pu.graph)
}
pu.graph!.next!.next!.next = nil // break the cycle
}
}
func PBSUnknown2AsPreservedWithGraphAsync(current: Current) -> Promise<Preserved?> {
return Promise<Preserved?> { seal in
try current.adapter!.getDispatchQueue().async(flags: .barrier) {
let r = PSUnknown2()
r.pi = 5
r.ps = "preserved"
r.pb = r
seal.fulfill(r) // Ice marshals r immediately
r.pb = nil // break the cycle
}
}
}
func checkPBSUnknown2WithGraph(p: Preserved?, current: Current) throws {
if current.encoding == Ice.Encoding_1_0 {
try _helper.test(!(p is PSUnknown2))
try _helper.test(p!.pi == 5)
try _helper.test(p!.ps == "preserved")
} else {
let pu = p as! PSUnknown2
try _helper.test(pu.pi == 5)
try _helper.test(pu.ps == "preserved")
try _helper.test(pu.pb === pu)
pu.pb = nil // break the cycle
}
}
func exchangePNode(pn: PNode?, current _: Current) throws -> PNode? {
return pn
}
func throwBaseAsBase(current _: Current) throws {
let be = BaseException()
be.sbe = "sbe"
be.pb = B()
be.pb!.sb = "sb"
be.pb!.pb = be.pb
_values.append(be.pb!)
throw be
}
func throwDerivedAsBase(current _: Current) throws {
let de = DerivedException()
de.sbe = "sbe"
de.pb = B()
de.pb!.sb = "sb1"
de.pb!.pb = de.pb
de.sde = "sde1"
de.pd1 = D1()
de.pd1!.sb = "sb2"
de.pd1!.pb = de.pd1
de.pd1!.sd1 = "sd2"
de.pd1!.pd1 = de.pd1
_values.append(de.pb!)
_values.append(de.pd1!)
throw de
}
func throwDerivedAsDerived(current _: Current) throws {
let de = DerivedException()
de.sbe = "sbe"
de.pb = B()
de.pb!.sb = "sb1"
de.pb!.pb = de.pb
de.sde = "sde1"
de.pd1 = D1()
de.pd1!.sb = "sb2"
de.pd1!.pb = de.pd1
de.pd1!.sd1 = "sd2"
de.pd1!.pd1 = de.pd1
_values.append(de.pb!)
_values.append(de.pd1!)
throw de
}
func throwUnknownDerivedAsBase(current _: Current) throws {
let d2 = D2()
d2.sb = "sb d2"
d2.pb = d2
d2.sd2 = "sd2 d2"
d2.pd2 = d2
_values.append(d2)
let ude = UnknownDerivedException()
ude.sbe = "sbe"
ude.pb = d2
ude.sude = "sude"
ude.pd2 = d2
throw ude
}
func throwPreservedExceptionAsync(current: Current) -> Promise<Void> {
return Promise<Void> { seal in
try current.adapter!.getDispatchQueue().async(flags: .barrier) {
let ue = PSUnknownException()
ue.p = PSUnknown2()
ue.p!.pi = 5
ue.p!.ps = "preserved"
ue.p!.pb = ue.p
seal.reject(ue) // Ice marshals the error immediately
ue.p!.pb = nil // break the cycle
}
}
}
func useForward(current _: Current) throws -> Forward? {
let f = Forward()
f.h = Hidden()
f.h!.f = f
_values.append(f)
return f
}
func shutdown(current: Current) throws {
current.adapter!.getCommunicator().shutdown()
}
}
|
"""Model for the foreninglet Activities"""
from dataclasses import dataclass, field
from typing import List, Optional
from dataclasses_json import dataclass_json
@dataclass_json
@dataclass
class Activity:
"""Implements a Foreninglet Activities model"""
ActivityId: int
Name: str
OnlineEnrollmentEnabled: bool
Categories: List[str]
DepartmentId: Optional[int] = None
ExternalDescriptions: Optional[List[dict[str, str]]] = field(default_factory=list)
PriceNow: Optional[float] = "0.00"
SettlementDate: Optional[str] = None
CloseDate: Optional[str] = None
@dataclass
@dataclass_json
class ActivityList:
"""List of Activity objects"""
Activities: List[Activity]
|
//
// Created by Miles Youngblood on 6/13/2022.
//
#pragma once
#include "../Pokemon/Pokemon.h"
#include "../Item/RestoreItem.h"
#include "../Item/StatusItem.h"
#include "../Item/Pokeball.h"
#include "../Item/BattleItem.h"
class Map;
class Trainer : public Entity {
private:
const char *dialogue;
protected:
const static int MAX_POKEMON = 6; // max number of Pokémon per party
const static int MAX_ITEMS = 50; // max number of items per bag
const static int NUM_ITEM_TYPES = 4; // number of types of items
int numFainted; // number of fainted Pokémon
int numPokemon; // current number of Pokémon in the party
int numItems[Trainer::NUM_ITEM_TYPES]; // number of each type of item
Pokemon* party[Trainer::MAX_POKEMON];
Item* items[Trainer::NUM_ITEM_TYPES][Trainer::MAX_ITEMS];
public:
Trainer();
Trainer(int x, int y);
Trainer(const std::initializer_list<Pokemon*> &pokemon, int x, int y);
Trainer(const std::initializer_list<Pokemon*> &pokemon, int x, int y, int vision);
Trainer(const Trainer &) = delete;
Trainer& operator=(const Trainer &) = delete;
~Trainer();
int partySize() const;
void addPokemon(Pokemon *toAdd);
void removePokemon(int index);
void clearParty();
int getNumItems(int type) const;
Item& getItem(int type, int item) const;
void addItem(int type, Item *toAdd);
void removeItem(int type, int index);
void setRestoreItems(const std::vector<Item*> &inventory);
void setStatusItems(const std::vector<Item*> &inventory);
void setPokeBalls(const std::vector<Item*> &inventory);
void setBattleItems(const std::vector<Item*> &inventory);
void incFaintCount();
__attribute__((unused)) __attribute__((unused)) void decFaintCount();
void swapPokemon(int first, int second);
Pokemon& operator[](int spot);
const Pokemon& operator[](int spot) const;
virtual explicit operator bool() const;
virtual bool canFight() const;
void moveToPlayer(const Map &map, const Trainer *trainer);
};
|
import { HttpError } from "@refinedev/core";
import axios from "axios";
import createAuthRefreshInterceptor from "axios-auth-refresh";
import { REFRESH_TOKEN_KEY, TOKEN_KEY, USER_INFO } from "./constants";
const axiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_URL,
});
const axiosRefreshInstance = axios.create({
baseURL: import.meta.env.VITE_API_URL,
});
// Use interceptor to inject the token to requests
axiosInstance.interceptors.request.use((request) => {
const token = localStorage.getItem(TOKEN_KEY);
request.headers["Authorization"] = `Bearer ${token}`;
return request;
});
axiosInstance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
const customError: HttpError = {
...error,
message: error.response?.data?.message,
statusCode: error.response?.status,
};
return Promise.reject(customError);
}
);
// Function that will be called to refresh authorization
const refreshAuthLogic = async () => {
const oldToken = localStorage.getItem(TOKEN_KEY);
const token = localStorage.getItem(REFRESH_TOKEN_KEY);
if (!token) return Promise.reject();
try {
const response = await axiosRefreshInstance.post(
"/auth/refresh-token",
{
token,
},
{
headers: {
Authorization: `Bearer ${oldToken}`,
},
}
);
const { accessToken, refreshToken } = response.data;
localStorage.setItem(TOKEN_KEY, accessToken);
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
return Promise.resolve();
} catch (error) {
return Promise.reject(error);
}
};
const refreshFailLogic = () => {
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(REFRESH_TOKEN_KEY);
localStorage.removeItem(USER_INFO);
if (window.location.href != "/login") {
window.location.href = "/login";
}
return Promise.resolve();
};
createAuthRefreshInterceptor(axiosInstance, refreshAuthLogic);
createAuthRefreshInterceptor(axiosRefreshInstance, refreshFailLogic, {
statusCodes: [401, 422, 403],
});
export default axiosInstance;
|
<!-- Quiz.client.vue -->
<template>
<NuxtLayout>
<!-- <NuxtLayout name="content"> -->
<div>
<h3>{{ id }}. {{ question }}</h3>
<div class="flex flex-col space-y-2 mt-4">
<label
v-for="(answer, index) in orderedAnswers"
:key="answer"
class="rounded-md py-3 px-5 border transition-colors duration-150"
:class="{
'border-gray-300': !showResults && selected !== index,
'border-gray-500 bg-gray-100': !showResults && selected === index,
'border-green-500': showResults && index === correctAnswerIndex,
'bg-green-100':
showResults && selected === index && index === correctAnswerIndex,
'border-red-500 bg-red-100':
showResults && selected === index && index !== correctAnswerIndex,
'cursor-not-allowed': showResults,
'cursor-pointer hover:bg-gray-100 hover:border-gray-500':
!showResults,
}"
>
<input
type="radio"
name="answer"
class="hidden"
:disabled="showResults"
:value="index"
v-model="selected"
/>
{{ answer }}
</label>
</div>
</div> </NuxtLayout>
</template>
<script setup>
import { defineProps } from 'vue';
import useQuiz from './useQuiz';
const props = defineProps({
question: String,
answers: Array,
});
const { addQuestion, showResults } = useQuiz();
const { id, selected, orderedAnswers, correctAnswerIndex } = addQuestion(
props.question,
props.answers
);
</script>
|
import { Specification } from "./Specification";
import { AndSpecification } from "./Composite/AndSpecification";
import { OrSpecification } from "./Composite/OrSpecification";
// Especificación para saber si el tipo de dato es string
export class IsStringSpec implements Specification<string> {
isSatisfiedBy(value: string): boolean {
return typeof value === "string";
}
and(spec: Specification<string>): Specification<string> {
return new AndSpecification(this, spec);
}
or(spec: Specification<string>): Specification<string> {
return new OrSpecification(this, spec);
}
}
|
/*
* Copyright (C) 2022 DANS - Data Archiving and Networked Services (info@dans.knaw.nl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.knaw.dans.sword2.core.service;
import nl.knaw.dans.sword2.core.Deposit;
import nl.knaw.dans.sword2.core.UriRegistry;
import nl.knaw.dans.sword2.api.entry.Entry;
import nl.knaw.dans.sword2.api.entry.Link;
import java.net.URI;
public class DepositReceiptFactoryImpl implements DepositReceiptFactory {
private final URI baseUrl;
public DepositReceiptFactoryImpl(URI baseUrl) {
this.baseUrl = baseUrl;
}
@Override
public Entry createDepositReceipt(Deposit deposit) {
var id = deposit.getCanonicalId();
var editURI = baseUrl.resolve("container/" + id);
var statementURI = baseUrl.resolve("statement/" + id);
var mediaURI = baseUrl.resolve("media/" + id);
var entry = new Entry();
entry.setId(editURI.toString());
entry.setPackaging(UriRegistry.PACKAGE_BAGIT);
entry.addLink(new Link(editURI, "edit", null));
entry.addLink(new Link(editURI, UriRegistry.REL_SWORD_EDIT, null));
entry.addLink(new Link(statementURI,
UriRegistry.REL_STATEMENT,
"application/atom+xml;type=feed"));
entry.addLink(new Link(mediaURI, "edit-media", null));
entry.setTreatment("[1] unpacking [2] verifying integrity [3] storing persistently");
entry.setVerboseDescription(String.format("received successfully: %s; MD5: %s",
deposit.getFilename(), deposit.getMd5()));
return entry;
}
@Override
public URI getDepositLocation(Deposit deposit) {
return baseUrl.resolve("container/" + deposit.getCanonicalId());
}
}
|
# EN tuning
library(tidyverse)
library(tidymodels)
library(tictoc)
library(doParallel)
tidymodels_prefer()
# load
load("./attempt_1/results/a1_info.rda")
#### Set up parallel processing
parallel::detectCores()
cl <- makePSOCKcluster(8)
registerDoParallel(cl)
#### Define model engine and workflow
net_model <- linear_reg(mode = "regression",
penalty = tune(),
mixture = tune()) %>%
set_engine("glmnet")
net_params <- extract_parameter_set_dials(net_model)
# grid
net_grid <- grid_regular(net_params, levels = 5)
net_workflow <- workflow() %>%
add_model(net_model) %>%
add_recipe(recipe_sink)
#### stop cluster and start timer
net_tune <- tune_grid(net_workflow,
resamples = a1_folds,
grid = net_grid,
control = control_grid(save_pred = TRUE,
save_workflow = TRUE,
parallel_over = "everything"))
stopCluster(cl)
# save
save(net_tune, file = "./attempt_1/results/tuned_net.rda")
|
//@ts-nocheck
import { useCallback, useEffect, useState } from "react";
import ERC20 from "../abi/ERC20";
import useParasset from "./useParasset";
import { getToNumber } from "../utils/formatBalance";
const useTotalSupply = (token: ERC20) => {
const [totalSupply, setTotalSupply] = useState(0);
const parasset = useParasset();
const fetchTotalSupply = useCallback(async () => {
if (token) {
const totalSupply = await token.totalSupply(parasset.myAccount);
setTotalSupply(getToNumber(totalSupply, token.decimal));
}
}, [parasset?.myAccount, parasset?.provider, token]);
useEffect(() => {
const refreshInterval = setInterval(() => {
if (parasset?.myAccount) {
fetchTotalSupply().catch((err) =>
console.error(`Failed to fetch token totalSupply: ${err.stack}`)
);
}
}, 1000);
return () => clearInterval(refreshInterval);
}, [parasset?.myAccount, token]);
return totalSupply;
};
export default useTotalSupply;
|
import React, { useEffect } from "react";
import { Card, CardHeader, CardBody, CardFooter, Divider, Link, Image } from "@nextui-org/react";
import { Button } from "@nextui-org/react";
import { HeartIcon } from "./Icon/HeartIcon";
import { Prompts } from '../data/prompt'
import { AnchorIcon } from "./Icon/AnchorIcon";
import DeleteDocumentIcon from "./Icon/DeleteDocumentIcon";
import MoreVertical from "./Icon/More-vertical";
import Edit from "./Icon/Edit";
import ThumbsUp from "./Icon/Thumbs-up";
import ThumbsDown from "./Icon/Thumbs-down";
import { ScrollShadow } from "@nextui-org/react";
import { useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import { Dropdown, DropdownTrigger, DropdownMenu, DropdownItem, Button as Btn, DropdownSection,cn } from "@nextui-org/react";
import { copyHandle} from '@/utils/index'
import { deletedMyPrompt } from "@/utils/myPromptUtils";
export default function MyCard({...prompts}) {
const theme = useTheme();
const isDark = theme.theme == 'dark'
const iconColor = isDark ? '#ffffff' : '#353536'
// 路由
const router = useRouter()
const prompt = prompts.zh
useEffect(()=>{
// console.log(isDark)
},[isDark])
const iconClasses = "text-xl text-default-500 pointer-events-none flex-shrink-0";
// 删除本地prompt
const onDeleteMyPromptHandle = (id:number) =>{
deletedMyPrompt(id)
}
const onEditHandle = () => {
const isMy = prompts.tags.some((item:any) => item == 'MY')
console.log(isMy)
if (isMy) {
return router.push(`prompt/edit?id=${prompts.id}&cat=MY`, { scroll: true })
}else{
return router.push(`prompt/edit?id=${prompts.id}`, { scroll: true })
}
}
return (
<Card className="max-w-[400px]">
<CardHeader className="flex gap-0 justify-between">
<div className="flex flex-col">
{/* 标题 */}
<p className="text-md">{prompt.title}</p>
{/* 分类 */}
<p>
{prompts.tags.map((tag: string)=>(
<span key={tag}>
<span className="text-small text-default-500">
{tag}
</span>
</span>
))}
</p>
</div>
<Button color="default" isIconOnly aria-label="Like">
<HeartIcon />
</Button>
</CardHeader>
<Divider />
<CardBody className=" max-h-[400px] overflow-h-scroll" onContextMenu={(e) => copyHandle(prompt.description,e)}>
<ScrollShadow hideScrollBar size={100} className="w-full h-[400px]">
<p>
{prompt.description}
</p>
</ScrollShadow>
</CardBody>
<CardFooter className="flex justify-evenly">
<Button onClick={() => onEditHandle()} endContent={<Edit color={iconColor} size={20} />}>
<span>
Edit
</span>
</Button>
{/* 点赞 */}
<Dropdown placement="top">
<DropdownTrigger className="">
<Button
className=" rounded-full "
variant="faded"
>
<MoreVertical color={iconColor} />
</Button>
</DropdownTrigger>
<DropdownMenu
aria-label="Action event example"
onAction={(key) =>{}}
>
<DropdownSection aria-label="Profile & Actions" showDivider className="">
<DropdownItem key="ThumbsUp">
<div className=" flex justify-between items-center gap-3">
<Button color="default" isIconOnly aria-label="Like">
<ThumbsUp color={iconColor} />
</Button>
<span className="flex-1">
ThumbsUp
</span>
</div>
</DropdownItem>
<DropdownItem key="ThumbsDown">
<div className=" flex justify-between items-center gap-3">
<Button color="default" isIconOnly aria-label="Like">
<ThumbsDown color={iconColor} />
</Button>
<span className="flex-1">
ThumbsDown
</span>
</div>
</DropdownItem>
<DropdownItem
key="delete"
className="text-danger"
color="danger"
onClick={() => onDeleteMyPromptHandle(prompts.id)}
>
<div className=" flex justify-between items-center gap-3">
<Button color="default" isIconOnly aria-label="Like">
<DeleteDocumentIcon color={iconColor} />
</Button>
<span className="flex-1">
Delete prompt
</span>
</div>
</DropdownItem>
</DropdownSection>
</DropdownMenu>
</Dropdown>
</CardFooter>
<Divider />
<CardFooter className="flex justify-evenly">
<Link
size="sm"
isExternal
href="https://chat.openai.com/"
showAnchorIcon
>
ChatGPT
</Link>
<Link
size="sm"
isExternal
color="secondary"
href="https://poe.com/"
showAnchorIcon
>
Poe
</Link>
<Link
size="sm"
isExternal
color="success"
href="https://claude.ai/"
showAnchorIcon
>
ClaudeAI
</Link>
{/* 收藏 */}
{/* <Button isIconOnly color="danger" aria-label="Like">
<HeartIcon width={20} height={20} />
</Button> */}
</CardFooter>
</Card>
);
}
|
//
// HomeView.swift
//
//
// Created by Bryan on 07/01/23.
//
import Anime
import Common
import Core
import SwiftUI
public struct HomeView<SeeAllDestination: View, DetailDestination: View>: View {
@State private var showSnackbar = false
@State private var restartSnackbar = false
@ObservedObject var presenter: HomePresenter<
Interactor<
AnimeRankingRequest,
[AnimeDomainModel],
GetAnimeRankingRepository<
GetAnimeRankingLocaleDataSource,
GetAnimeRankingRemoteDataSource,
AnimesTransformer>>,
Interactor<
AnimeRankingRequest,
[AnimeDomainModel],
GetAnimeRankingRepository<
GetAnimeRankingLocaleDataSource,
GetAnimeRankingRemoteDataSource,
AnimesTransformer>>,
Interactor<
AnimeRankingRequest,
[AnimeDomainModel],
GetAnimeRankingRepository<
GetAnimeRankingLocaleDataSource,
GetAnimeRankingRemoteDataSource,
AnimesTransformer>>,
Interactor<
AnimeRankingRequest,
[AnimeDomainModel],
GetAnimeRankingRepository<
GetAnimeRankingLocaleDataSource,
GetAnimeRankingRemoteDataSource,
AnimesTransformer>>>
@State var scrollOffset: CGFloat
let seeAllDestination: ((_ rankingType: RankingTypeRequest) -> SeeAllDestination)
let detailDestination: ((_ anime: AnimeDomainModel) -> DetailDestination)
public init(
presenter: HomePresenter<
Interactor<
AnimeRankingRequest,
[AnimeDomainModel],
GetAnimeRankingRepository<
GetAnimeRankingLocaleDataSource,
GetAnimeRankingRemoteDataSource,
AnimesTransformer>>,
Interactor<
AnimeRankingRequest,
[AnimeDomainModel],
GetAnimeRankingRepository<
GetAnimeRankingLocaleDataSource,
GetAnimeRankingRemoteDataSource,
AnimesTransformer>>,
Interactor<
AnimeRankingRequest,
[AnimeDomainModel],
GetAnimeRankingRepository<
GetAnimeRankingLocaleDataSource,
GetAnimeRankingRemoteDataSource,
AnimesTransformer>>,
Interactor<
AnimeRankingRequest,
[AnimeDomainModel],
GetAnimeRankingRepository<
GetAnimeRankingLocaleDataSource,
GetAnimeRankingRemoteDataSource,
AnimesTransformer>>>,
scrollOffset: CGFloat = CGFloat.zero,
seeAllDestination: @escaping ((RankingTypeRequest) -> SeeAllDestination),
detailDestination: @escaping ((AnimeDomainModel) -> DetailDestination)
) {
self.presenter = presenter
self.scrollOffset = scrollOffset
self.seeAllDestination = seeAllDestination
self.detailDestination = detailDestination
}
public var body: some View {
ZStack {
if presenter.isLoading {
ProgressIndicator()
.background(YumeColor.background)
} else if presenter.isError {
if presenter.errorMessage == URLError.notConnectedToInternet.localizedDescription {
NoInternetView(onRetry: presenter.retryConnection)
} else {
CustomEmptyView(label: presenter.errorMessage)
}
} else {
content
}
}.onAppear {
if presenter.topAiringAnimeList.isEmpty
|| presenter.topUpcomingAnimeList.isEmpty
|| presenter.popularAnimeList.isEmpty
|| presenter.topAllAnimeList.isEmpty {
presenter.setupHomeView()
}
}
}
}
extension HomeView {
var content: some View {
ZStack(alignment: .top) {
RefreshableScrollView(
scrollOffset: $scrollOffset,
showsIndicators: false,
isRefreshing: $presenter.isRefreshing,
onRefresh: presenter.refreshHomeView
) { _ in
LazyVStack(spacing: Space.large) {
header
topAiringAnime
topUpcomingAnime
popularAnime
topAllAnime
}.padding(
EdgeInsets(
top: 40,
leading: Space.none,
bottom: Space.medium,
trailing: Space.none)
)
}
AppBar(scrollOffset: scrollOffset, label: "home_title".localized(bundle: .common))
}
.background(YumeColor.background)
.onChange(of: presenter.showSnackbar) { presenterShowSnackbar in
if presenterShowSnackbar {
withAnimation(.easeInOut) {
if showSnackbar {
restartSnackbar = true
}
showSnackbar = true
}
presenter.showSnackbar = false
}
}
.snackbar(
message: presenter.errorMessage,
withCloseIcon: true,
isShowing: $showSnackbar,
restart: $restartSnackbar)
}
var header: some View {
HStack {
Text("home_title".localized(bundle: .common))
.typography(.largeTitle(weight: .bold, color: YumeColor.onBackground))
Spacer()
}.padding(.horizontal, Space.medium)
}
var topAiringAnime: some View {
VStack(spacing: Space.small) {
HStack(spacing: Space.small) {
Text("now_airing_title".localized(bundle: .common))
.typography(.headline(color: YumeColor.onBackground))
Spacer()
NavigationLink(destination: seeAllDestination(.airing)) {
Text("see_all_label".localized(bundle: .module))
.typography(.subheadline(color: YumeColor.primary))
}.buttonStyle(.plain)
}.padding(.horizontal, Space.medium)
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack(spacing: Space.small) {
ForEach(presenter.topAiringAnimeList.prefix(10)) { anime in
NavigationLink(destination: detailDestination(anime)) {
AnimeItem(anime: anime)
}.buttonStyle(.plain)
}
}.padding(.horizontal, Space.medium)
}
}
}
var topUpcomingAnime: some View {
VStack(spacing: Space.small) {
HStack(spacing: Space.small) {
Text("upcoming_title".localized(bundle: .common))
.typography(.headline(color: YumeColor.onBackground))
Spacer()
NavigationLink(destination: seeAllDestination(.upcoming)) {
Text("see_all_label".localized(bundle: .module))
.typography(.subheadline(color: YumeColor.primary))
}.buttonStyle(.plain)
}.padding(.horizontal, Space.medium)
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack(spacing: Space.small) {
ForEach(presenter.topUpcomingAnimeList.prefix(10)) { anime in
NavigationLink(destination: detailDestination(anime)) {
AnimeItem(anime: anime)
}.buttonStyle(.plain)
}
}.padding(.horizontal, Space.medium)
}
}
}
var popularAnime: some View {
VStack(spacing: Space.small) {
HStack(spacing: Space.small) {
Text("most_popular_title".localized(bundle: .common))
.typography(.headline(color: YumeColor.onBackground))
Spacer()
NavigationLink(destination: seeAllDestination(.byPopularity)) {
Text("see_all_label".localized(bundle: .module))
.typography(.subheadline(color: YumeColor.primary))
}.buttonStyle(.plain)
}.padding(.horizontal, Space.medium)
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack(spacing: Space.small) {
ForEach(presenter.popularAnimeList.prefix(10)) { anime in
NavigationLink(destination: detailDestination(anime)) {
AnimeItem(anime: anime)
}.buttonStyle(.plain)
}
}.padding(.horizontal, Space.medium)
}
}
}
var topAllAnime: some View {
VStack(spacing: Space.small) {
HStack(spacing: Space.small) {
Text("top_rated_title".localized(bundle: .common))
.typography(.headline(color: YumeColor.onBackground))
Spacer()
NavigationLink(destination: seeAllDestination(.all)) {
Text("see_all_label".localized(bundle: .module))
.typography(.subheadline(color: YumeColor.primary))
}.buttonStyle(.plain)
}.padding(.horizontal, Space.medium)
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack(spacing: Space.small) {
ForEach(presenter.topAllAnimeList.prefix(10)) { anime in
NavigationLink(destination: detailDestination(anime)) {
AnimeItem(anime: anime)
}.buttonStyle(.plain)
}
}.padding(.horizontal, Space.medium)
}
}
}
}
|
<template>
<div class="alert alert-warning mt-3 d-flex justify-content-between align-item-center" v-if="tarea">
<p class="m-0" :class="{ 'tachado' : tarea.estado}">{{ tarea.texto }}</p>
<div>
<i
v-if="tarea.estado"
class="fas fa-undo-alt mx-2 text-success"
role="button"
@click="modificar(tarea.id)"
></i>
<i
v-else
class="fas fa-check-circle mx-2 text-success"
role="button"
@click="modificar(tarea.id)"
></i>
<i
class="fas fa-minus-circle text-danger"
role="button"
@click="eliminar(tarea.id)"
></i>
</div>
</div>
</template>
<script>
import { inject } from '@vue/runtime-core'
export default {
props: {
tarea: {
type: Object,
required: true
}
},
setup(){
const tareas = inject('tareas');
const eliminar = ( id ) => {
tareas.value = tareas.value.filter( item => item.id !== id );
}
const modificar = ( id ) => {
tareas.value = tareas.value.map( item => {
if ( item.id === id ){
item.estado = !item.estado;
}
return item;
})
}
return { eliminar, modificar }
}
}
</script>
<style scoped>
.tachado {
text-decoration: line-through;
}
</style>
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Models.Context;
using Models.Dto;
using Services.Interfaces;
namespace Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EventController : ControllerBase
{
private readonly IEventService _service;
private readonly IStorageService _storageService;
private readonly IMailService _mailService;
public EventController(IEventService service, IStorageService storageService, IMailService mailService)
{
_service = service;
_storageService = storageService;
_mailService = mailService;
}
[HttpPost("[action]")]
public dynamic ToggleAttendance(ToggleAttendanceDto dto)
{
return _service.ToggleAttendance(dto);
}
[HttpPost("[action]")]
public async Task<EventMainDto> ChangeEvent(EventMainDto evnt)
{
return await _service.ChangeEvent(evnt, User);
}
[HttpGet("[action]/{id}")]
public async Task<EventMainDto> GetEventById(int id)
{
return await _service.GetEvent(id,User);
}
[Authorize]
[HttpGet("[action]/{id}")]
public async Task<IActionResult> Attend(int id)
{
try {
await _service.AddEventAttendees(id, User);
var evt = await GetEventById(id);
return Ok(evt);
}
catch(Exception ex)
{
return BadRequest(new { message = ex.Message});
}
}
[Authorize]
[HttpGet("[action]/{id}")]
public async Task<EventMainDto> UnAttend(int id)
{
await _service.RemoveEventAttendees(id, User);
return await GetEventById(id);
}
//[Authorize(Roles = "Admin, Secretary")]
[HttpGet("[action]/{id}")]
public EventAttendeeDto[] GetEventAttendees(int id)
{
return _service.GetEventAttendees(id);
}
[HttpGet("[action]/{id}")]
public async Task<IActionResult> Photo(int id)
{
Photo p = _service.GetPhotoById(id);
byte[] data = await _storageService.GetFile(Path.GetFileName(p.Url));
return File(data, "application/octet-stream");
}
[HttpGet("[action]/{id}")]
public Photo[] GetEventPhotos(int id)
{
var temp = _service.GetEventPhotos(id);
foreach(var a in temp)
{
a.Url = $"/api/Event/Photo/{a.Id}";
}
return temp;
}
[HttpPost("[action]/{id}")]
public async Task<Photo[]> UploadFile(int id, List<IFormFile> files)
{
List<Photo> photos = new List<Photo>();
foreach (var f in files)
{
string url = await _storageService.SaveFile(Guid.NewGuid().ToString(), f.OpenReadStream());
Image img = Image.FromStream(f.OpenReadStream());
photos.Add(new Photo()
{
EventId=id,
FileName=f.FileName,
Uploaded = DateTime.Now,
Width = img.Width,
Height = img.Height,
Url = url
});
}
var arr = photos.ToArray();
_service.AddPhotos(arr);
foreach(var a in arr)
{
a.Url = $"/api/Event/Photo/{a.Id}";
}
return arr;
}
[HttpPost("[action]/{id}")]
public EventAttendeeDto[] RemoveEventAttendees(int id, EventAttendeeDto attendee)
{
return _service.RemoveEventAttendees(id, attendee);
}
[HttpPost("[action]/{id}")]
public async Task<EventAttendeeDto[]> AddEventAttendees(int id, string[] ids)
{
return await _service.AddEventAttendees(id, ids.Distinct<string>().ToArray(), User);
}
[HttpGet("[action]/{id}")]
public EventAttendeeDto[] GetSiteMembers(int id)
{
return _service.GetSiteMembers(id);
}
[HttpGet("[action]/{id}")]
public EventAttendeeDto[] GetSiteMembersOnly(int id)
{
return _service.GetSiteMembersOnly(id);
}
[HttpGet("[action]/{id}")]
public EventBudget[] GetBudget(int id)
{
return _service.GetEventBudget(id);
}
[HttpPost("[action]/{id}")]
public EventBudget[] AddBudgetLines(int id, EventBudget[] lines)
{
return _service.AddBudgetLines(id, lines);
}
[HttpPost("[action]/{id}")]
public EventBudget[] AddBudgetLine(int id, EventBudget line)
{
EventBudget[] arr = new EventBudget[] { line };
return _service.AddBudgetLines(id, arr);
}
[HttpPost("[action]/{id}")]
public EventBudget[] UpdateBudgetLine(int id, EventBudget line)
{
return _service.UpdateBudgetLine(id, line);
}
[HttpPost("[action]/{id}")]
public EventBudget[] DeleteBudgetLine(int id, EventBudget line)
{
return _service.DeleteBudgetLine(id, line);
}
}
}
|
import React, { useEffect, useState } from "react";
import './home.css';
import Frame from './Frame.js';
import ReactDOM from "react-dom";
function App2() {
const [grid, setGrid] = useState([]);
const [welcomeClicked, setWelcomeClicked] = useState(false);
const [wordClicked, setWordClicked] = useState(null);
const elementWidth = 7;
const elementSpacing = 6;
const leftMargin = 50;
const rightMargin = 50;
const topMargin = 180;
const bottomMargin = 200;
const [rowToClear, setRowToClear] = useState(-1); // Define rowToClear and setRowToClear
useEffect(() => {
const calculateGridDimensions = () => {
const availableWidth = window.innerWidth - leftMargin - rightMargin;
const availableHeight = window.innerHeight - topMargin - bottomMargin;
const columns = Math.floor(availableWidth / (elementWidth + 2 * elementSpacing));
const rows = Math.floor(availableHeight / (elementWidth + 2 * elementSpacing));
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const charactersLength = characters.length;
const newGrid = [];
for (let i = 0; i < rows; i++) {
const row = [];
for (let j = 0; j < columns; j++) {
const randomChar = characters.charAt(Math.floor(Math.random() * charactersLength));
row.push(randomChar);
}
newGrid.push(row);
}
if (welcomeClicked) {
// Place the words on the grid with proper constraints
const randomizeWord = (word, randomRow, randomColumn) => {
const wordLength = word.length;
for (let i = 0; i < wordLength; i++) {
newGrid[randomRow][randomColumn + i] = (
<span key={i} className={`welcome-text ${word.toLowerCase()}`}>
{word[i]}
</span>
);
}
};
// Calculate the thirds of the grid
const topThird = Math.floor(rows / 3);
const middleThird = Math.floor(rows / 3) * 2;
randomizeWord('ABOUT', Math.floor(Math.random() * topThird), Math.floor(Math.random() * (columns - 4)));
randomizeWord('EXPERIENCE', topThird + Math.floor(Math.random() * (middleThird - topThird)), Math.floor(Math.random() * (columns - 10)));
randomizeWord('CONTACT', middleThird + Math.floor(Math.random() * (rows - middleThird - 2)), Math.floor(Math.random() * (columns - 6)));
} else {
const randomizeWord = (word, randomRow, randomColumn) => {
const wordLength = word.length;
for (let i = 0; i < wordLength; i++) {
newGrid[randomRow][randomColumn + i] = (
<span key={i} className={`welcome-text ${word.toLowerCase()}`} >
{word[i]}
</span>
);
}
};
// Allow "WELCOME" to be placed randomly anywhere on the grid with restrictions
let welcomeRandomRow;
let welcomeRandomColumn;
do {
welcomeRandomRow = Math.floor(Math.random() * rows);
welcomeRandomColumn = Math.floor(Math.random() * columns);
} while (welcomeRandomColumn < 1 || welcomeRandomColumn > columns - 12);
randomizeWord('->WELCOME<-', welcomeRandomRow, welcomeRandomColumn);
}
setGrid(newGrid);
};
calculateGridDimensions();
window.addEventListener('resize', calculateGridDimensions);
return () => {
window.removeEventListener('resize', calculateGridDimensions);
};
}, [welcomeClicked, leftMargin, rightMargin, topMargin, bottomMargin, elementWidth, elementSpacing]);
const handleGridElementClick = (rowIndex, columnIndex) => {
// Local variable to track the click event status
let isClicking = false;
// Function to reset the click event status
const resetClickStatus = () => {
isClicking = false;
};
if (isClicking) {
// If a click event is already in progress, do nothing.
return;
}
// Set isClicking to true to indicate that a click event is in progress.
isClicking = true;
// You can also use setTimeout to reset isClicking after a certain delay, just like before.
setTimeout(resetClickStatus, 3000); // You can adjust the delay time as needed.
const currentGrid = [...grid];
if (currentGrid[rowIndex][columnIndex].props && currentGrid[rowIndex][columnIndex].props.className.includes('welcome-text ->welcome<-')) {
setWelcomeClicked(true);
} else if (currentGrid[rowIndex][columnIndex].props && currentGrid[rowIndex][columnIndex].props.className.includes('welcome-text')) {
const clickedWord = currentGrid[rowIndex][columnIndex].props.className.split(' ').filter(c => c !== 'welcome-text')[0];
if (clickedWord === 'about' || clickedWord === 'experience' || clickedWord === 'contact') {
setWordClicked(clickedWord);
setRowToClear(0);
}
}
};
const handleHover = (rowIndex, columnIndex) => {
if (grid[rowIndex][columnIndex].props) {
return;
}
const newChar = String.fromCharCode(Math.floor(Math.random() * 26) + 65);
const newGrid = [...grid];
newGrid[rowIndex][columnIndex] = newChar;
setGrid(newGrid);
};
useEffect(() => {
if (wordClicked) {
const clearRow = () => {
setGrid(prevGrid => {
if (rowToClear >= prevGrid.length) {
if (rowToClear === prevGrid.length) {
// Render the Frame component with the selected component
ReactDOM.render(
<Frame selectedComponent={wordClicked} />,
document.getElementById('root')
);
}
setRowToClear(-1);
setWordClicked(null);
return prevGrid;
}
const newGrid = prevGrid.map((row, index) => {
if (index === rowToClear) {
return row.map(() => '');
}
return row;
});
return newGrid;
});
setRowToClear(prevRow => prevRow + 1);
if (rowToClear < grid.length) {
setTimeout(clearRow, 1000);
}
};
clearRow();
}
}, [wordClicked, rowToClear, grid]);
return (
<div className="page-borders">
<div className="grid">
{grid.map((row, rowIndex) => (
<div key={rowIndex} className="grid-row">
{row.map((element, columnIndex) => (
<div
key={columnIndex}
className="grid-element"
onClick={() => handleGridElementClick(rowIndex, columnIndex)}
onMouseEnter={() => handleHover(rowIndex, columnIndex)}
>
{element}
</div>
))}
</div>
))}
</div>
</div>
);
}
export default App2;
|
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:food_online_shop/widgets/custom_text_form_field.dart';
import 'package:google_fonts/google_fonts.dart';
class SignInPage extends StatefulWidget {
const SignInPage({Key? key}) : super(key: key);
@override
State<SignInPage> createState() => _SignInPageState();
}
class _SignInPageState extends State<SignInPage> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Container(
alignment: Alignment.bottomCenter,
child: Padding(
padding: EdgeInsets.all(5),
child: Image.asset(
"image/seller.png",
height: 270,
),
),
),
Form(
key: _formKey,
child: Column(
children: [
CustomTextFormField(
keyBoardType: TextInputType.emailAddress,
textEditingController: emailController,
iconData: Icons.email_rounded,
hintText: "Email",
isObsecre: false,
),
CustomTextFormField(
keyBoardType: TextInputType.visiblePassword,
textEditingController: passwordController,
iconData: Icons.lock_rounded,
hintText: "Password",
isObsecre: true,
),
ElevatedButton(
onPressed: () {},
child: Text(
"Login",
style: GoogleFonts.varela(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
style: ElevatedButton.styleFrom(
primary: Colors.cyan.shade600,
padding: EdgeInsets.symmetric(
vertical: 14,
horizontal: 60,
),
),
),
],
),
),
],
),
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.