text stringlengths 184 4.48M |
|---|
import { env } from '$env/dynamic/public'
import { subjectsStore, lessonSearchParamsStore } from '/src/stores/lessonStore'
import { get } from 'svelte/store'
import { responseService } from "/src/utils/responseService"
export async function getSubjects()
{
const response = await fetch(import.meta.env.VITE_API_URL + '/lesson/subjects',
{
headers:{
'Content-Type': 'application/json',
},
method: 'GET',
},
);
const result = await response.json()
return responseService(result)
}
export async function getLevels(params = [])
{
const response = await fetch(import.meta.env.VITE_API_URL + '/lesson/levels/' + params.subjectId,
{
headers:{
'Content-Type': 'application/json',
},
method: 'GET',
},
);
const result = await response.json()
return responseService(result)
}
export async function getCategories()
{
const response = await fetch(import.meta.env.VITE_API_URL + '/category/list',
{
headers:{
'Content-Type': 'application/json',
},
method: 'GET',
},
);
const result = await response.json()
return responseService(result)
}
export async function getLevelsByCategory(params = [])
{
const response = await fetch(import.meta.env.VITE_API_URL + '/category/levels/' + params.categoryId,
{
headers:{
'Content-Type': 'application/json',
},
method: 'GET',
},
);
const result = await response.json()
return responseService(result)
}
export async function searchLesson(params = {})
{
const searchParams = Object.entries(params).length > 0 ? params : get(lessonSearchParamsStore)
const result = await fetch(import.meta.env.VITE_API_URL + '/lesson/search',
{
headers:{
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({
'page' : searchParams?.page,
'pageSize' : searchParams?.pageSize,
'keyword' : searchParams?.keyword,
})
},
);
const body = await result.json()
return body.result
} |
#include "ClapTrap.hpp"
int main(void)
{
ClapTrap mario("mario");
ClapTrap gigi("gigi");
ClapTrap gennaro("gennaro");
gennaro.setAttackDamage(42);
gennaro.setHitPoints(42);
gennaro.setEnergyPoints(42);
// //attack with reference (not requested by subject)
// mario.setAttackDamage(10);
// mario.attackWithRef(gigi, mario.getAttackDamage());
// gigi.attackWithRef(gennaro,42);
if (mario.isAlive())
mario.attack("gigi");
else
std::cout << "mario is dead can't attack" << std::endl;
if (mario.isAlive())
gigi.takeDamage(10);
else
std::cout << "gigi is dead can't take damage" << std::endl;
if (gigi.isAlive())
gigi.attack("mario");
else
std::cout << "gigi is dead can't attackkkkk" << std::endl;
if (gigi.isAlive())
mario.takeDamage(10);
else
std::cout << "gigi is dead cannot attack mariooooo" << std::endl;
gigi.beRepaired(10);
if (gennaro.isAlive())
gennaro.attack("mario");
else
std::cout << "gennaro is dead can't attack" << std::endl;
if (mario.isAlive())
mario.takeDamage(gennaro.getAttackDamage());
else
std::cout << "mario is dead can't take damage" << std::endl;
gigi.displayStats();
mario.displayStats();
gennaro.displayStats();
return 0;
} |
import { forwardRef, InputHTMLAttributes, ReactNode } from 'react'
import { PaymentMethodContainer, LabelContainer } from './styles'
type PaymentMethodProps = InputHTMLAttributes<HTMLInputElement> & {
label: string
icon: ReactNode
}
// eslint-disable-next-line react/display-name
export const PaymentMethodInput = forwardRef<
HTMLInputElement,
PaymentMethodProps
>(({ id, label, icon, ...props }, ref) => {
return (
<PaymentMethodContainer>
<input type="radio" id={id} {...props} name="paymentMethod" ref={ref} />
<label htmlFor={id}>
<LabelContainer>
{icon}
{label}
</LabelContainer>
</label>
</PaymentMethodContainer>
)
}) |
import React, { createContext, useContext, useEffect, useState } from "react";
import {
GoogleAuthProvider,
createUserWithEmailAndPassword,
onAuthStateChanged,
signInWithEmailAndPassword,
signInWithPopup,
signOut,
} from "firebase/auth";
import { auth } from "../Firebase";
const UserAuthContext = createContext();
export const UserAuthContextProvider = ({ children }) => {
const [user, setUser] = useState({});
const logIn = (email, password) => {
return signInWithEmailAndPassword(auth, email, password);
};
const signUp = (email, password) => {
return createUserWithEmailAndPassword(auth, email, password);
};
const logOut = () => {
return signOut(auth);
};
const googleSignIn = () => {
const googleAuthProvider = new GoogleAuthProvider();
return signInWithPopup(auth, googleAuthProvider);
};
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
return () => {
unsubscribe();
};
}, []);
return (
<UserAuthContext.Provider
value={{ user, logIn, signUp, logOut, googleSignIn }}
>
{children}
</UserAuthContext.Provider>
);
};
export const useUserAuth = () => {
return useContext(UserAuthContext);
}; |
#include <rawrbox/ui/container.hpp>
#include <rawrbox/ui/scripting/wrappers/ui_container_wrapper.hpp>
namespace rawrbox {
UIContainerWrapper::UIContainerWrapper(const std::shared_ptr<rawrbox::UIContainer>& ref) : _ref(ref) {}
UIContainerWrapper::~UIContainerWrapper() { this->_ref.reset(); }
rawrbox::UIContainer* UIContainerWrapper::getRef() const {
return this->_ref.lock().get();
}
// UTILS ---
void UIContainerWrapper::setPos(const rawrbox::Vector2f& pos) {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
this->_ref.lock()->setPos(pos);
}
const rawrbox::Vector2f UIContainerWrapper::getPos() const {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
return this->_ref.lock()->getPos();
}
const rawrbox::Vector2f UIContainerWrapper::getDrawOffset() const {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
return this->_ref.lock()->getDrawOffset();
}
void UIContainerWrapper::setSize(const rawrbox::Vector2f& size) {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
this->_ref.lock()->setSize(size);
}
const rawrbox::Vector2f UIContainerWrapper::getSize() const {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
return this->_ref.lock()->getSize();
}
void UIContainerWrapper::removeChildren() {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
this->_ref.lock()->removeChildren();
}
void UIContainerWrapper::remove() {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
this->_ref.lock()->remove();
}
void UIContainerWrapper::setVisible(bool visible) {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
this->_ref.lock()->setVisible(visible);
}
bool UIContainerWrapper::visible() const {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
return this->_ref.lock()->visible();
}
// -----------
// SORTING -----
bool UIContainerWrapper::alwaysOnTop() const {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
return this->_ref.lock()->alwaysOnTop();
}
void UIContainerWrapper::setAlwaysTop(bool top) {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
this->_ref.lock()->setAlwaysTop(top);
}
void UIContainerWrapper::bringToFront() {
if (!this->isValid()) throw std::runtime_error("[RawrBox-UIContainer] Container reference not set!");
this->_ref.lock()->bringToFront();
}
// -------
bool UIContainerWrapper::isValid() const {
return !this->_ref.expired();
}
void UIContainerWrapper::registerLua(sol::state& lua) {
lua.new_usertype<UIContainerWrapper>("UIContainer",
sol::no_constructor,
// UTILS ---
"setPos", &UIContainerWrapper::setPos,
"getPos", &UIContainerWrapper::getPos,
"getDrawOffset", &UIContainerWrapper::getDrawOffset,
"setSize", &UIContainerWrapper::setSize,
"getSize", &UIContainerWrapper::getSize,
"removeChildren", &UIContainerWrapper::removeChildren,
"remove", &UIContainerWrapper::remove,
"setVisible", &UIContainerWrapper::setVisible,
"visible", &UIContainerWrapper::visible,
// -----------
// SORTING -----
"alwaysOnTop", &UIContainerWrapper::alwaysOnTop,
"setAlwaysTop", &UIContainerWrapper::setAlwaysTop,
"bringToFront", &UIContainerWrapper::bringToFront,
// -----------
"isValid", &UIContainerWrapper::isValid);
}
} // namespace rawrbox |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>MDATA Tricks</title>
<meta content="Garrett Kaminaga" name="author">
</head>
<body>
<p><a name="appx"></a></p>
<h1>MDATA Tricks<br>
</h1>
My idea was to have a document of ideas, so not actually fully fleshed
out. Some of these things would take a lot of code really. In
general I don't like to go overboard with complete code samples in the
text. I like broad sketches of techniques instead of step-by-step
instructions. Sometimes I have code available separately. But it's up
to your style.<br>
<br>
people aren't very smart so you might want to start with simple uses of
mdata -- a simple one-to-many like author name searching, then maybe a
many-to-many like user folders (eadh document can be assigned to
multiple folders, each folder can hold multiple documents)<br>
<br>
The assumption in many of these techniques is that there is application
query rewrite. In most apps that are using MDATA, that's going to be
the case anyways.<br>
<h2>1. getting around mdata limitations</h2>
MDATA has equality semantics which might not work for all people.
This section is about how to get around that.<br>
<h3>1.1 length limits</h3>
MDATA values are stored in token_text so limited to 64 bytes. To get
around length limits the idea is to simply use a<br>
lookup table. So you have a section<br>
<title>This is a really long value here</title><br>
you set up a lookup table:<br>
id number<br>
value varchar2(256)<br>
user datastore does a select on lookup table, insert if not there (in
auto. transaction, of course)<br>
and transform section to id:<br>
<title>12345</title><br>
slap a b-tree index on the lookup table value, then at query time you
need to rewrite your queries to<br>
take text value to id, then query MDATA(title, 12345).<br>
<h3>1.2 normalization</h3>
MDATA values don't go through the lexer so I was going to point out how
to go simple normalization yourself. uppercasing is obvious, base
lettering is pretty simple with a TRANSLATE call. The point is that the
normalization has to be symmetric, done on index side (user datastore,
perhaps) and query side (application code)<br>
<h3>1.3 supporting word and equality search</h3>
Idea is to duplicate the mdata section in the datastore, so instead of<br>
<author>william shakespeare</author><br>
you get <br>
<author>william shakespeare</author><br>
<authorf>william shakespeare</authorf><br>
and use an mdata and a field section.<br>
Alternately you can use the lookup table technique in 1.1 and slap a
context index on the lookup table, with appropriate application code.<br>
<h3>1.4 expansion</h3>
Using the lookup table from 1.1 you can also do expansions by
application code at query time. So users can search for subject COOKIN%
etc<br>
<h3>1.5 multiplexing</h3>
If you want to get around the 100 section limit, you can use
multiplexing. Instead of<br>
<SEC1>value</SEC1><br>
<SEC2>value</SEC2><br>
<SEC3>value</SEC3><br>
you use<br>
<SEC>1 value</SEC><br>
<SEC>2 value</SEC><br>
<SEC>3 value</SEC><br>
This works out much better with mdata than with field sections because
of equality semantics<br>
<h2>2. dynamic token normalization</h2>
The idea here is to <span style="font-weight: bold;">leverage</span>
the fact that mdata does not go through the lexer. So you can do things
like case-specific case sensitivity. For instance, you can have
an author section which is case-sensitive but the rest of the document
is not.<br>
Then you can actually use multiple mdata sections to do query-time
normalization. Let your user datastore do something like this:<br>
<upper>THE VÄLUE</upper><br>
<lower>The Välue</upper><br>
<upperbase>THE VALUE</upperbase><br>
...<br>
and you can do query-time base letter or case sensitivity, by varying
the section.<br>
<h2>3. logical partitioning</h2>
The idea with logical partitioning is that you can use MDATA to do a
primary filter by simulating partitioning. Say you have a date
field. You can index an mdata section with the month:<br>
<DATEPART>022004</DATEPART><br>
<h3>3.1 mixed range</h3>
Given a range, you can translate to the partitions that must be
hit. Then you use the context index as a primary filter.
For instance, range 12-JAN-2004 - 03-FEB-2004:<br>
select .. where contains(text, 'blah blah blah and
(MDATA(012004,datepart) or MDATA(022004,datepart))')>0<br>
and date between '12-JAN-2004' and '03-FEB-2004'<br>
Since each mdata operator uses a cursor, you don't want too many of
those, though. So for large ranges you can do one of two things:
a) run more than one query, using different subsets of partitions or b)
use multi-resolution partitioning:<br>
<DP>2004</DP> (year)<br>
<DP>1H2004</DP> (half)<br>
<DP>1Q2004</DP> (quarter)<br>
<DP>02M2004</DP> (month)<br>
etc.<br>
<h3>3.2 sort order by</h3>
Given logical partitioning, it is not hard to see how to do a sort
order by -- mimic real partitioning. So given a query DOG, first
you do <br>
DOG and MDATA(022004,dp) (current month)<br>
then if you don't get enough hits move on to<br>
DOG and MDATA(012004,dp) (last month)<br>
etc. each invocation needs an ORDER BY to do the fine-grain sorting,
but the number of rows being sorted is minimal.<br>
In the lab this performs relatively well. it is optimal when you only
need one partition, so if the user knows the average date spread of
rows returned, they can size the partitions correctly. The following
strategy is even better:<br>
1. issue query without any sorting criteria, first 50 rows<br>
2. if you don't get 50 rows, sort what you have and return.
Otherwise, <br>
3. iterative partition scanning as above<br>
You can use a similar technique with multi-resolution partitions to
improve partition scanning: <br>
1. get first 50 rows of first, largest grain partition (i.e. YEAR), no
sort<br>
2. if got 50 rows, try next smallest partition (i.e. HALF), no sort<br>
... etc. This minimizes the number of invocations of the same
query.<br>
But the text part still gets invoked multiple times. So I also tried
the following technique: use MDATA for sorting by weighting the
operator.<br>
MDATA is supposed to return score 100. So, with different weights
and mutually exclusive values, you can distinguish between a finite set
of mdata values. For instance, let's talk months:<br>
dog*0.01 & (MDATA(JAN,dp)*.9 | MDATA(FEB,dp)*.8|MDATA(MAR,dp)*.7)<br>
if the query gets score of 90, it is january. if 80, february. so
order by score desc gets you inverse month sorting, while text part is
executed just once.<br>
there may be a bug in 10gR1 where MDATA returns 1 instead of 100,
though -- check it.<br>
</body>
</html> |
//给你一个整数 n ,请你找出并返回第 n 个 丑数 。
//
// 丑数 就是只包含质因数 2、3 和/或 5 的正整数。
//
//
//
// 示例 1:
//
//
//输入:n = 10
//输出:12
//解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。
//
//
// 示例 2:
//
//
//输入:n = 1
//输出:1
//解释:1 通常被视为丑数。
//
//
//
//
// 提示:
//
//
// 1 <= n <= 1690
//
// Related Topics 哈希表 数学 动态规划 堆(优先队列) 👍 895 👎 0
/**
* @author sanshisi
*/
package leetcode.editor.cn;
public class Soultion264 {
public static void main(String[] args) {
Solution solution = new Soultion264().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int nthUglyNumber(int n) {
int[] dp = new int[n + 1];
dp[1] = 1;
int p2 = 1, p3 = 1, p5 = 1;
for (int i = 2; i <= n; i++) {
int num2 = dp[p2] * 2, num3 = dp[p3] * 3, num5 = dp[p5] * 5;
dp[i] = Math.min(Math.min(num2, num3), num5);
if (dp[i] == num2) {
p2++;
}
if (dp[i] == num3) {
p3++;
}
if (dp[i] == num5) {
p5++;
}
}
return dp[n];
}
}
//leetcode submit region end(Prohibit modification and deletion)
} |
import agent from '@/api/agent';
import Button from '@/components/buttons/Button';
import { useAddItemMutation, useGetBasketQuery } from '@/redux/services/bakset';
import { IProduct } from '@/types/products';
import Image from 'next/image';
import Link from 'next/link';
import { useEffect } from 'react';
import { FiShoppingCart } from 'react-icons/fi';
import { toast } from 'react-toastify';
interface Props {
product: IProduct;
}
export default function ProductCard({ product }: Props) {
const [addProduct, { isSuccess, isError, isLoading }] = useAddItemMutation();
const handleAddItem = () => {
addProduct({ productId: product.id });
};
useEffect(() => {
if (isSuccess) toast.success('Added to cart!');
if (isError) toast.error('Something went wrong!');
}, [isSuccess, isError]);
return (
<div className="flex flex-col items-center justify-between h-[350px] border py-5 px-2 rounded-md shadow-md space-y-5">
<Link className="w-full" href={`/catalog/${product.id}`}>
<div className="space-y-4">
<div className="py-3 w-full flex items-center justify-center bg-primary bg-opacity-10 rounded">
<Image src={product.imageUrl} alt={product.name} width={100} height={100} />
</div>
<div className="font-semibold">
<p className="text-accent text-lg">₱{product.price.toFixed(2)}</p>
<h2 className="text-sm">{product.name}</h2>
</div>
<div>
<p className="text-sm text-tertiary ">{`${product.brand} / ${product.type}`}</p>
</div>
</div>
</Link>
<Button loading={isLoading} disabled={isLoading} onClick={handleAddItem}>
<FiShoppingCart size={20} />
<p>Add to cart</p>
</Button>
</div>
);
} |
// ***********************************************
// -lm -lglut -lGLU -lGL
// Draw the shape (Click 4 points)
// press 'e' to translate
// press 'r' to rotate
// press 't' to scale
// press 'w' for up
// press 's' for down
// press 'a' for left
// press 'd' for right
//
// ***********************************************
#include <stdio.h>
#include <math.h>
#include <GL/glut.h>
typedef struct
{
GLint x;
GLint y;
} GLPOINT;
static int wHeight = 0;
static GLPOINT p[4]; // points array for basic shape drawn
static int tool; // tool selected = w , e , r
static int tx,ty,sx,sy,theta; // transformation parameters
// open gl functions
void DisplayFunc();
void MouseFunc(int button,int state,int x,int y);
void KeyboardFunc(unsigned char key,int x,int y);
void Init();
// algo functions
void SetPixel(int x,int y);
void DrawShape();
void Translate(int x,int y);
void Rotate(float x);
void Scale(int x,int y);
void Redraw();
int main(int argc,char* argv[])
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(100,100);
glutInitWindowSize(600,600);
glutCreateWindow("Translation");
wHeight = glutGet(GLUT_WINDOW_HEIGHT);
glutDisplayFunc(DisplayFunc);
glutMouseFunc(MouseFunc);
glutKeyboardFunc(KeyboardFunc);
Init();
glutMainLoop();
return 0;
}
void MouseFunc(int button,int state,int x,int y)
{
static int click_count;
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
p[click_count].x=x;
p[click_count].y=wHeight-y;
click_count++;
}
if(click_count==4)
{
DrawShape();
click_count=0;
}
}
void KeyboardFunc(unsigned char key,int x,int y)
{
if(key=='e') // translate
{
tool = 1;
}
else if(key == 'r') // rotate
{
tool = 2;
}
else if(key == 't') // scale
{
tool = 3;
}
else if(key == 'w') // up
{
// translate
tx=0;
ty=10;
// rotate
theta=10;
//scale
sx=1;
sy=2;
Redraw();
}
else if(key == 's') // down
{
// translate
tx=0;
ty=-10;
// rotate
theta=-10;
//scale
sx=1;
sy=-2;
Redraw();
}
else if(key == 'a') // left
{
// translate
tx=-10;
ty=0;
// rotate
theta=10;
//scale
sx=-2;
sy=1;
Redraw();
}
else if(key == 'd') // right
{
// translate
tx=10;
ty=0;
// rotate
theta=-10;
//scale
sx=2;
sy=1;
Redraw();
}
else
tool = 0;
}
void DisplayFunc()
{
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
void Init()
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,600, 0.0, 600);
}
void DrawShape()
{
glColor3f(0,1,0);
glBegin(GL_POLYGON);
glVertex2i(p[0].x,p[0].y);
glVertex2i(p[1].x,p[1].y);
glVertex2i(p[2].x,p[2].y);
glVertex2i(p[3].x,p[3].y);
glEnd();
glFlush();
}
void SetPixel(int x,int y)
{
glColor3f(0,0,0);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
glFlush();
}
void Translate(int x,int y)
{
int i;
for(i=0;i<4;i++)
{
p[i].x = p[i].x + x;
p[i].y = p[i].y + y;
}
}
void Rotate(float x)
{
// change x in degree to radiun
x = x*3.14/180;
// rotate w.r.t center of shape
// calculate xt,yt as fixed point
int xt = (p[0].x + p[2].x)/2;
int yt = (p[0].y + p[2].y)/2;
int i;
float tmp_x,tmp_y;
float cos_x = cos(x);
float sin_x = sin(x);
for(i=0;i<4;i++)
{
tmp_x = xt + ( (p[i].x - xt)*cos_x - (p[i].y - yt) *sin_x);
tmp_y = yt + ( (p[i].x - xt)*sin_x + (p[i].y - yt) *cos_x);
p[i].x = tmp_x;
p[i].y = tmp_y;
}
}
void Scale(int x,int y)
{
// scale w.r.t center of shape
// calculate xt,yt as fixed point
int xt = (p[0].x + p[2].x)/2;
int yt = (p[0].y + p[2].y)/2;
int i;
for(i=0;i<4;i++)
{
p[i].x = (p[i].x * x) + xt*(1-x);
p[i].y = (p[i].y * y) + yt*(1-y);
}
}
void Redraw()
{
if(tool == 1) // translate
{
Translate(tx,ty);
}
else if(tool == 2) // rotate
{
Rotate(theta);
}
else if(tool ==3) // scale
{
Scale(sx,sy);
}
glClear(GL_COLOR_BUFFER_BIT);
DrawShape();
} |
--@Autores: Emanuel Flores, Adolfo Barrero
--@Fecha creación: 01/12/2019
--@Descripción: Guarda las fotos de una mascota en el servidor
create or replace trigger guarda_mascota_foto
after insert or update on mascota
for each row
declare
v_blob blob;
v_nombre_directorio varchar2(30) := 'DATA_SERVER';
v_nombre_archivo varchar2(30);
v_file utl_file.FILE_TYPE;
v_buffer_size number := 32767;
v_buffer RAW(32767);
v_position number := 1;
v_longitud number(10,0);
begin
v_blob := :new.foto;
v_nombre_archivo := 'm_' || to_char(:new.mascota_id) || '.jpg';
v_file := utl_file.fopen(upper(v_nombre_directorio), v_nombre_archivo, 'wb', v_buffer_size);
v_longitud := dbms_lob.getlength(v_blob);
while v_position < v_longitud loop
dbms_lob.read(v_blob, v_buffer_size, v_position, v_buffer);
utl_file.put_raw(v_file, v_buffer, true);
v_position := v_position + v_buffer_size;
end loop;
utl_file.fclose(v_file);
exception
when others then
if utl_file.is_open(v_file) then
utl_file.fclose(v_file);
end if;
dbms_output.put_line(dbms_utility.format_error_backtrace);
v_longitud := -1;
raise;
end;
/
show errors |
#!/bin/sh
# backup - Backup home folder to a remote address using borg.
#
# Setup:
# ======
# Add this to your `.zshenv` or similar:
# export BORG_PASSPHRASE=""
# export BORG_REPO=""
#
# Usage:
# ======
# To create: borg init -e repokey-blake2
# To export key: borg key export --paper > $(echo "$(hostname)-borg-key.txt")
# To restore: borg extract --dry-run --debug --list ::hostname-YYYY-MM-DD@hh-mm
info() {
printf "\n%s %s\n\n" "$( date )" "$*" >&2;
}
trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM
# Backup the most important directories into an archive named after
# the machine this script is currently running on:
borg create \
--verbose \
--filter AME \
--list \
--stats \
--show-rc \
--compression lz4 \
--exclude-caches \
--exclude "/*/.cache" \
--exclude "/*/.electron-gyp" \
--exclude "/*/.node-gyp" \
--exclude "/*/.npm" \
--exclude "/*/.nvm" \
--exclude "/*/node_modules" \
::'{hostname}-{now:%Y-%m-%d@%H:%M}' \
$HOME \
# Route the normal process logging to journalctl
2>&1
backup_exit=$?
info "Pruning repository"
# Use the `prune` subcommand to maintain 7 daily, 4 weekly and 6 monthly
# archives of THIS machine. The '{hostname}-' prefix is very important to
# limit prune's operation to this machine's archives and not apply to
# other machines' archives also:
borg prune \
--list \
--prefix '{hostname}-' \
--show-rc \
--keep-daily 7 \
--keep-weekly 4 \
--keep-monthly 6 \
# Route the normal process logging to journalctl
2>&1
prune_exit=$?
# use highest exit code as global exit code
global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit ))
if [ ${global_exit} -eq 0 ]; then
info "Backup and Prune finished successfully"
elif [ ${global_exit} -eq 1 ]; then
info "Backup and/or Prune finished with warnings"
else
info "Backup and/or Prune finished with errors"
fi
exit ${global_exit} |
import React from 'react';
import calender from '../assets/calender.png';
import green_clock from '../assets/green_clock.png';
import spoon from '../assets/spoon.png';
import red_clock from '../assets/red_clock.png';
interface Task {
id: string;
creatorName: string;
name: string;
type: string;
deadline: string;
from: string;
to: string;
status: string;
feedback: string[];
itemRequest?: { [key: string]: string | null };
instruction: string;
}
interface TaskCardProps {
task: Task;
}
const TaskCard: React.FC<TaskCardProps> = ({ task }) => {
const calculateTimeLeft = (deadline: string) => {
const deadlineTime = new Date(deadline).getTime();
const currentTime = new Date().getTime();
const timeDifference = deadlineTime - currentTime;
const minutesLeft = Math.ceil(timeDifference / (1000 * 60));
return minutesLeft;
};
const getDeadlineColor = (deadline: string) => {
const minutesLeft = calculateTimeLeft(deadline);
if (minutesLeft < 5) return 'bg-red-500';
return 'bg-green-400';
};
const getStatusColor = (status: string) => {
let bgColor = '';
let textColor = '';
if (status === 'Completed') {
bgColor = 'bg-gray-100';
textColor = 'text-green-500';
} else if (status === 'Ongoing') {
bgColor = 'bg-gray-100';
textColor = 'text-yellow-300';
} else if (status === 'Accepted') {
bgColor = 'bg-gray-100';
textColor = 'text-green-500';
} else if (status === 'Not Accepted') {
bgColor = 'bg-gray-100';
textColor = 'text-orange-500';
} else {
bgColor = 'bg-gray-300';
textColor = 'text-gray-700';
}
return { bgColor, textColor };
};
const getButtonColor = (status: string, deadline: string) => {
const minutesLeft = calculateTimeLeft(deadline);
if (status === 'Completed') return 'border border-green-500 text-green-500 hover:bg-green-500 hover:text-white';
if (minutesLeft < 5) return 'bg-red-500 text-white';
return 'bg-green-500 text-white';
};
const getFeedbackColor = (feedback: string | string[]) => {
if (Array.isArray(feedback)) {
if (feedback.includes('Delayed') && feedback.includes('Complaint')) {
return 'bg-red-500';
}
} else {
if (feedback === 'Delayed' || feedback === 'Complaint') {
return 'bg-red-500';
}
}
return 'bg-green-400';
};
const calculateTimeLeftFormatted = (deadline: string) => {
const deadlineTime = new Date(deadline).getTime();
const currentTime = new Date().getTime();
const timeDifference = deadlineTime - currentTime;
const minutesLeft = Math.ceil(timeDifference / (1000 * 60));
if (minutesLeft < 1) {
return 'Delayed';
} else if (minutesLeft < 60) {
return `${minutesLeft} min`;
} else {
const hours = Math.floor(minutesLeft / 60);
const remainingMinutes = minutesLeft % 60;
return `${hours} hr ${remainingMinutes} min`;
}
};
return (
<div className="rounded-lg border p-4 flex flex-col space-y-2">
<div className="flex justify-between items-center">
<div className="flex items-center">
<img src={spoon} alt="Creator" className="w-4 h-4 mr-2" />
<div className="text-sm">{task.creatorName}</div>
<div className={`ml-2 px-2 py-1 text-xs rounded-full ${getStatusColor(task.status).bgColor}`}>
<span className={`${getStatusColor(task.status).textColor}`}>{task.status}</span>
</div>
</div>
<div className={`text-sm ml-2 px-2 py-1 rounded-full ${getDeadlineColor(task.deadline)}`}>
{task.status === 'Completed' ? (
task.feedback.map((feedback, index) => (
<span key={index} className={`${getFeedbackColor(feedback)} p-1 m-1 ml-2 rounded-full`}>
{feedback}
</span>
))
) : (
<div className="flex items-center">
<span>{calculateTimeLeftFormatted(task.deadline)}</span>
{task.status !== 'Completed' && calculateTimeLeft(task.deadline) <= 5 ? (
<img src={red_clock} alt="Red Clock" className="w-4 h-4 ml-2" />
) : (
<img src={green_clock} alt="Green Clock" className="w-4 h-4 ml-2" />
)}
</div>
)}
</div>
</div>
<div className="flex justify-between">
<h3 className="text-lg font-semibold">{task.name}</h3>
<div className="text-sm">{task.type}</div>
</div>
<div className="text-xs text-gray-500">
<img src={calender} alt="Calendar" className="w-4 h-4 mr-1 inline" />
{task.deadline}
</div>
<div className="flex justify-between text-xs text-gray-500">
<div>From: {task.from}</div>
<div>To: {task.to}</div>
</div>
{Object.keys(task.itemRequest || {}).length > 0 && (
<div className="border border-gray-200 bg-gray-100 rounded p-2">
<table className="w-full ">
<tbody>
{Object.entries(task.itemRequest || {}).map(([item, value]) => (
<tr key={item}>
<td>{item}</td>
<td>{value}</td>
</tr>
))}
</tbody>
</table>
<div className="text-green-500">{task.instruction}</div>
</div>
)}
<button className={`rounded-lg py-2 mt-auto ${getButtonColor(task.status, task.deadline)}`}>
{task.status === 'Completed' ? 'View Details' : 'Notify Staff'}
</button>
</div>
);
};
export default TaskCard; |
---
tree_title: Educative-Microsoft
description: This will cover up the problems/questions from the Microsoft Educative course.
last_modified: 2022-06-22T12:03:49.349
---
# Educative-Microsoft
## Top coding questions to crack interview @Microsoft
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 1. Find the missing number in a given array.
Given an array of positive numbers ranging from 1 to n, such that all numbers from 1 to n are present except one number x, find x. Assume the input array is unsorted.
<span class="tag-is-success">Arrays</span>
</div>
<div class="educative-microsoft-item">
```
Calculate the sum of all the elements of an array ranging from 1 to n. Then subtract the sum of all the elements of the array(given) from the sum of all the elements of the array ranging from 1 to n. The difference between the two is the missing number.
TC: O(n)
SC: O(1)
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 2. Determine if the sum of two integers is equal to a given value
Given an array of integers and a value, determine if there are any two integers in the array whose sum is equal to the given value. Return true if the sum exists, and false if it does not.
<span class="tag-is-success">Arrays</span>
</div>
<div class="educative-microsoft-item">
```
Take hashmap for storing the elements in it. Iterate through the array and see if its corresponding value is present in the hashmap. If it is present, then return true, else add the element to the hashmap.
TC: O(n)
SC: O(n)
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 3. Set columns and rows as zeroes
Given a two-dimensional array, if any element within is zero, make its whole row and column zero. Consider the matrix below.
<span class="tag-is-success">Arrays</span>
</div>
<div class="educative-microsoft-item">
```
Iterate through the matrix and if any element is zero, then set the corresponding row and column to zero. Meaning you will be setting the first row or first column to zero, later you will have to iterate the whole matrix again to see if the first row or first column is zero.
TC: O(n^2)
SC: O(1)
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 4. Add two integers
Given the head pointers of two linked lists where each linked list represents an integer number (each node is a digit), add them and return the resulting linked list. In the example below, the first node in a list represents the least significant digit.
<span class="tag-is-success">Linked Lists</span>
</div>
<div class="educative-microsoft-item">
```
Thinking about the problem you will get to know that the size of the two linked-list can be different. Its an easy problem if you consider taking extra space for the resultant linked-list.
But if you don't take extra space, then you can solve it in O(n) time. Where n is the size of the largest linked-list. Along with it you can take a carry variable, at the end of the loop, if the carry is not zero, then add a new node to the resultant linked-list.
TC: O(n) : Max length of the two.
SC: O(1) : Space for carry variable.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 5. Merge two sorted linked lists
Write a function that takes two sorted linked lists and merges them. The function should return a single, sorted list made from splicing the nodes of the first two lists together.
For example, if the first linked list is 1 -> 2 -> 4 and the second linked list is 3 -> 5 -> 6, then the output would be 1 -> 2 -> 3 -> 4 -> 5 -> 6
<span class="tag-is-success">Linked Lists</span>
</div>
<div class="educative-microsoft-item">
```
Many methods to solve this problem : Using Dummy Node, Recursion, Iteration(Extra Space), Reversing The Lists. Good solution among these is using Dummy Node. You compare the first node of both the linked-lists and add the smaller one to the dummy node. You then add the next node of the smaller one to the dummy node and so on. Once there are no nodes to traverse in any of the list anymore, you return the dummy node with the leftover nodes from list.
TC: O(n+m) : Length of the two linked-lists.
SC: O(1) : Space for the dummy node.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 6. Level order traversal of binary tree
Given the root of a binary tree, display the node values at each level.
<span class="tag-is-success">Tree</span>
</div>
<div class="educative-microsoft-item">
```
Different ways to solve this problem : Using Recursion(DFS)+List to store the nodes at each level. You helper method can look like helper(root, level, list). Here, root is the root of the tree, level is the level of the current node, and list is the list of nodes at the current level.
TC: O(n) : Number of nodes in the tree.
SC: O(n) : Space for the list.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 7. Check a given binary tree for symmetry
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
<span class="tag-is-success">Tree</span>
</div>
<div class="educative-microsoft-item">
```
We can use recursion to solve the problem, you would pass left and right sub-child to the helper method and compare the values of the nodes. Edge-cases are when the left and right sub-child are null, we return false.
If the left and right sub-child are not null and the values for the current sub-child is equal then we call the helper method again with their left and right sub-child. You helper method might look like boolean helper(TreeNode left, TreeNode right).
TC: O(n) : Number of nodes in the tree.
SC: O(1)
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 8. Reverse words in a sentence
Reverse the order of words in a given sentence.
Example: "sphinx of black quartz judge my vow" should output as "vow my judge quartz black of sphinx"
<span class="tag-is-success">String</span>
</div>
<div class="educative-microsoft-item">
```
Method that pops initially is that we will extract words from the sentence separated by space, then push it onto the stack and then pop it out of the stack to a StringBuilder and return it. But then we can eliminate stack usage once for all, so for the program we wont be needing extra space apart from the output string.
TC: O(n) : Number of words in the sentence.
SC: O(n) : Space for the output string.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 10. Find all palindrome substrings
Given a string, find all non-single letter substrings that are palindromes.
Example: An string input of "poppopo" would return "pop", "opo", "oppo", and "poppop".
<span class="tag-is-success">String</span>
</div>
<div class="educative-microsoft-item">
```
We can use a method to find the palindrome of a string which returns true/false for being a palindrome. We need to find all the strings that are of greater length than 1. But thinking more into the problem we can use Recursion and Sliding Window to solve the problem.
So your helper method would look like int helper(String s, int start, int end) where it will run a loop from the start and the end condition to compare the characters at the index.
TC: O(n^2) : Number of characters in the string.
SC: O(1) : Space for the count variable and storing palindrome strings is not part of the SC.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 11. String segmentation
Given a dictionary of words and a large input string, find whether or not the input string can be completely segmented into the words of that dictionary.
Input: s = "leetcode", wordDict = ["leet","code"] Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
<span class="tag-is-success">String</span>
</div>
<div class="educative-microsoft-item">
```
We can use Recursion to solve the problem. We will iterate through the string and will be calculating if the current substring is a word in the dictionary. If it is, we will call the helper method again with the current substring and the rest of the string. If it is not, we will return false.
TC: O(2^n) : If we use the Recursion alone, if used with Memoization, then it will be O(n^2).
SC: O(n) : Space for the memoization table.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 12. Find the maximum single sell profit
Given a list of daily stock prices (integers for simplicity), return the buy and sell prices that will maximize the single buy/sell profit. If you can't make any profit, try to minimize the loss.
Input: prices = [7,1,5,3,6,4] Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
<span class="tag-is-success">DP</span>
</div>
<div class="educative-microsoft-item">
```
We can take two variables min=firstElement and max=0 and iterate through the array, if the current value is greater than the min then assign the max to the Math.max(max, diff(currentValue, min)). If the current value is less than the min, then assign the current value to the min.
TC: O(n) : Number of elements in the array.
SC: O(1) : Space for the variables.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 13. Length of longest subsequence
Given a one-dimensional integer array a of length n, find the length of the longest subsequence that increases before decreasing.
Input: a = [1,3,5,4,7] Output: 3
<span class="tag-is-success">DP</span>
</div>
<div class="educative-microsoft-item">
```
We will be using DP for the problem. Initialize a dp array of length n and iterate nested through the array and the recursive co-relation between the i and j will be dp[i] = Math.max(dp[i], 1 + dp[j]); when a[i] > a[j] and during the process we will also keep a count for the longest subsequence.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 14. Find the longest path in a given matrix
Given a n\*n matrix where all numbers are distinct, find the maximum length path (starting from any cell) such that all cells along the path are in increasing order with a difference of 1. Can move in all the four straight direction.
Input: mat[][] = {{1, 2, 9} {5, 3, 8} {4, 6, 7}} Output: 4 >> The longest path is 6-7-8-9.
<span class="tag-is-success">DP</span>
</div>
<div class="educative-microsoft-item">
```
The idea is simple, we calculate longest path beginning with every cell. Once we have computed longest for all cells, we return maximum of all longest paths. One important observation in this approach is many overlapping sub-problems. Therefore this problem can be optimally solved using DP.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 15. Find the missing number in the array
Given an array of positive numbers ranging from 1 to n, such that all numbers from 1 to n are present except one number x, find x. The input array is not sorted.
<span class="tag-is-success">Math and Statistics</span>
</div>
<div class="educative-microsoft-item">
```
The idea is similar to the 1st Missing Number problem. We can use the sum of all numbers to find the missing number. The sum of all numbers is n*(n+1)/2. The sum of all numbers in the array is sum of all elements in the array. The difference between the two is the missing number.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 16. Find all sum combinations
Given a positive integer, target, print all possible combinations of positive integers that sum up to the target number.
For example, if we are given input '5', these are the possible sum combinations : \[[1, 4][2, 3] [1, 1, 3][1, 2, 2 ] [1, 1, 1, 2][1, 1, 1, 1, 1]]. The output will be in the form of a list of lists or an array of arrays. Each element in the list will be another list containing a possible sum combination.
<span class="tag-is-success">Math and Statistics</span>
</div>
<div class="educative-microsoft-item">
```
The idea is simple and can be solved using DFS. We will be using a helper function to print all the possible combinations. The helper function will be called with the current sum and the current list of numbers. Helper method will look like void combSum(int i,int a[],int t,List<Integer> ds).
The idea is to check if the current sum is equal to the target. If it is, we will add the current list to the list of lists. If it is not, we will add the current number to the current list and call the helper method again with the current sum and the current list.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 17. Find the kth permutation
Given a set of n variables, find their kth permutation. Consider the following set of variables: {1, 2, 3, 4, 5, 6, 7, 8, 9}
<span class="tag-is-success">Math and Statistics</span>
</div>
<div class="educative-microsoft-item">
The logic is as follows: For n numbers the permutations can be divided to (n-1)! groups, for n-1 numbers can be divided to (n-2)! groups, and so on. Thus k/(n-1)! indicates the index of current number, and k%(n-1)! denotes remaining index for the remaining n-1 numbers.
We keep doing this until n reaches 0, then we get n numbers permutations that is kth. This is one hard problem so attaching solution for the same.
TC: O(n) : Number of elements in the array.
SC: O(n) : Used Array to store the numbers.
</div>
<div class="educative-microsoft-item width100perct">
```java showLineNumbers
public String getPermutation(int n, int k) {
StringBuilder sb=new StringBuilder();
ArrayList<Integer>al=new ArrayList<>();
for(int i=1;i<=n;i++)al.add(i);
k--;
int[]fact={1,1,2,6,24,120,720,5040,40320,362880};
while(n>0){
int index=k/fact[n-1];
k=k%fact[n-1];
sb.append(al.get(index));
al.remove(index);
n--;
}
return sb.toString();
}
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 18. Rat in a Maze
Consider a rat placed in a square n\*n matrix at position (0, 0). Find all possible paths the rat can take to reach its destination (N-1, N-1) from its starting position.
The rat can move vertically and horizontally. Cells with a value of 1 can be traversed, while cells with a value of 0 cannot. The rat cannot visit a cell more than once.
<span class="tag-is-success">Backtracking</span>
</div>
<div class="educative-microsoft-item">
```
Idea behind the solution for the problem is simple using Backtracking. We will be using a helper function to print all the possible paths. There might be obstacle stated from the value of the cell as 0, if 0 then backtrack (meaning don't add the value to the path->arraylist).
If it is 0, we will not add the current cell to the path. If it is 1, we will add the current cell to the path. Likewise we will keep on traversing the matrix and calling the helper function for each cell.
TC: O(2^n) : Number of paths.
SC: O(n) : Where n is the number of paths. For this case we will have 2^n paths.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 19. Closest Meeting Point
Given N people on an MxM grid, find the point that requires the least total distance covered by all people to meet at that point.
Consider a 5x5 grid with 3 people; one at X(1,2), Y(4,2) and Z(3,3).
<span class="tag-is-success">Sort and Search</span>
</div>
<div class="educative-microsoft-item">
```
Hints for the given problem: Distance between two points and Centroid of a two-dimensional region.
Centroid is (x1+x2...)/n and (y1+y2...)/n.
```
</div>
</div>
<hr />
<div class="educative-microsoft-container">
<div class="educative-microsoft-item pl0">
### 20. Search for the given key in a two-dimensional matrix
We are given a two-dimensional array where all elements in any individual row or column are sorted. In such a matrix, we have to search or find the position of a given key.
Input: matrix = \[[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 Output: true
<span class="tag-is-success">Sort and Search</span>
</div>
<div class="educative-microsoft-item">
```
We know that the the rows and columns are sorted. So we can use binary search to find the position of the key and also one more method is that we check the last element of the current row and check if that is greater than the key. If it is, then we can move to the next row. Like wise we will check the rows until we fine a row where the last element is less than the key. Then we just have to traverse that particular row and check if the key is present in that row, if not then check for the next row.
TC: O(log(m+n)) : Number of rows and columns.
SC: O(1) : No extra space required.
```
</div>
</div>
## References
<ul>
<li>
<https://www.educative.io/blog/microsoft-interview-coding-questions>
</li>
<li>
<https://v1.docusaurus.io/docs/en/doc-markdown>
</li>
<li>
<https://leetcode.com/problems/permutation-sequence/discuss/22507/%22Explain-like-I'm-five%22-Java-Solution-in-O(n)>
</li>
</ul> |
---
title: "Computer Security Principles and Practice"
permalink: /Computer-Security-Principles-and-Practice/24-Wireless-Network-Security/
layout: default
---
# 24-Wireless Network Security
# **24.1 Wireless Security**
* Key factors: contributing to higher security risks (v.s. wired networks)
* Channel
* Broadcast communications: more susceptible to eavesdropping and jamming
* Vulnerabilities in communication protocols
* Mobility
* More portable and mobile
* Resources
* Smartphones/tablets: sophisticated OS but limited memory and processing resources
* Accessibility
* Sensors/robots: may be left unattended in remote and/or hostile locations
wireless environment consists of three components that provide point of attack:
1. wireless client
1. mobile phone, a Wi-Fi enabled laptop or tablet, a wireless sensor, a Bluetooth device
2. wireless access point
1. mobile phone towers, Wi-Fi hot spots, and wireless access points to wired local or wide-area networks
3. transmission medium
1. carries the radio waves for data transfer

## Wireless Network Threats
**Accidental association:**
* Users may unintentionally connect to a neighboring wireless network, exposing resources to the accidental user.
**Malicious association:**
* Attackers can set up fake wireless access points to steal passwords and gain access to wired networks.
**Ad hoc networks:**
* Lack of central control makes ad hoc networks vulnerable to security threats.
**Nontraditional networks:**
* Personal network Bluetooth devices, barcode readers, and handheld PDAs pose security risks due to eavesdropping and spoofing.
**Identity theft (MAC spoofing):**
* Attackers can eavesdrop on network traffic and identify MAC addresses of computers with network privileges.
**Man-in-the-middle attacks:**
* Attackers can intercept communication between a user and an access point.
**Denial-of-service (DoS):**
* Attackers can bombard wireless access points with various protocol messages to consume system resources.
**Network injection:**
* Attackers can target wireless access points exposed to non-filtered network traffic to disrupt network performance.
## Wireless Security Measures
### Securing wireless transmissions
* Principal threats: eavesdropping, altering, or inserting messages, and disruption
* Countermeasures for eavesdropping
* Signal-hiding techniques
* Organizations can make it more difficult for attackers to locate their wireless access points by:
* Turning off SSID broadcasting
* Assigning cryptic names to SSIDs
* Reducing signal strength
* Locating access points in the interior of buildings
* Greater security can be achieved by using directional antennas and signal-shielding techniques.
* Encryption
* Encryption of all wireless transmission is effective against eavesdropping(偷聽) to the extent that the encryption keys are secured.
* For altering and inserting
* Encryption and authentication protocols
* For disruption
* Detection
### Securing Wireless access Points
* threat: unauthorized access to the network
* countermeasure:
* IEEE 802.1X standard for port-based network access control
* Provide an authentication mechanism
* prevent rogue access points and other unauthorized devices from becoming insecure backdoors

### Securing Wireless Networks
techniques for wireless network security:
1. **Use encryption****. Wireless routers are typically equipped with built-in encryption mechanisms for router-to-router traffic.**
2. **Use anti-virus and anti-spyware software, and a firewall****. These facilities should be enabled on all wireless network endpoints.**
3. **Turn off identifier broadcasting****. Wireless routers are typically configured to broadcast an identifying signal so that any device within range can learn of the router’s existence. If a network is configured so authorized devices know the iden- tity of routers, this capability can be disabled to thwart attackers.**
4. **Change the identifier on your router from the default****. Again, this measure thwarts attackers who will attempt to gain access to a wireless network using default router identifiers.**
5. **Change your router’s pre-set password for administration****. This is another prudent step.**
6. **Allow only specific computers to access your wireless network****. A router can be configured to only communicate with approved MAC addresses. Of course, MAC addresses can be spoofed, so this is just one element of a security strategy.**
# **24.2 Mobile Device Security**
* An organization’s networks must accommodate
* Growing use of new devices
* Significant growth in employee’s use of mobile devices
* Cloud-based apps
* Apps no longer run solely on physical servers
* de-**perimeterization(**去邊界化**)**
* A multitude of network perimeters around devices, apps, user, and data
* External business requirements
* Provide guests, third-party contractors, and business partners network access
## Security Threats
* **Lack of physical security controls****:** Mobile devices are often outside the organization's control, making them vulnerable to theft and tampering.
* **Use of untrusted mobile devices****:** Employees may use personal smartphones and/or tablets, which may not be trustworthy.
* **Use of untrusted networks****:** Mobile devices may connect to untrusted networks, making them susceptible to eavesdropping or man-in-the-middle attacks.
* **Use of untrusted applications****:** Mobile devices can easily install third-party applications, which may be malicious.
* **Interaction with other systems****:** Mobile devices may synchronize data with other computing devices and cloud-based storage, which may be insecure.
* **Use of untrusted content****:** Mobile devices may access and use untrusted content, such as malicious QR codes.
* **Use of location services****:** The GPS capability on mobile devices can be used to track the device's location, which may be a security risk.
## Mobile Device Security Strategy

* Device security
* Supply mobile devices for employee use and pre-configure those devices
* or bring-your-own-device (BYOD) policy
* Configuration guidelines for OS and apps (e.g., rooted is not allowed)
* Traffic security
* based on encryption and authentication
* via a VPN
* Barrier security
* Firewall policies specific to mobile device traffic
# **24.3 IEEE 802.11 Wireless LAN Overview**
1. IEEE 802 ➝ LANs
2. IEEE 802.11 ➝ wireless LANs (WLANs)
**Table 24.1 IEEE 802.11 Terminology**
| Access point (AP) | Any entity that has station functionality and provides access to the distribution system via the wireless medium for associated stations |
| ---| --- |
| Basic service set (BSS) | A set of stations controlled by a single coordination function |
| Coordination function | The logical function that determines when a station operating within a BSS is permitted to transmit and may be able to receive PDUs |
| Distribution system (DS) | A system used to interconnect a set of BSSs and integrated LANs to create an ESS |
| Extended service set (ESS) | A set of one or more interconnected BSSs and integrated LANs that appear as a single BSS to the LLC layer at any station associated with one of these BSSs |
| MAC protocol data unit (MPDU) | The unit of data exchanged between two peer MAC entities using the services of the physical layer |
| MAC service data unit (MSDU) | Information that is delivered as a unit between MAC users |
| Station | Any device that contains an IEEE 802.11 conformant MAC and physical layer |
## The Wi-Fi Alliance
* 802.11b
* First 802.11 standard to gain broad industry acceptance
* Wireless Ethernet Compatibility Alliance (WECA)
* Industry consortium(聯合) formed in 1999: interoperation between vendors
* Term used for certified 802.11b products: Wi-Fi
* Wi-Fi Protected Access (WPA)
* Certification procedures for IEEE802.11 security standards
* Most recent version: WPA2
* incorporates all of the features of the IEEE 802.11i WLAN security specification
## IEEE 802 Protocol Architecture
### Physical Layer
* The lowest layer of the IEEE 802 reference model
* encoding/decoding of signals and bit transmission/reception
* specification of the transmission medium
### Medium Access Control **(MAC)**
* controlling access orderly and efficient use of that capacity
* receives data from a higher-layer protocol (logical link control (LLC))➝ known as **MAC service data unit (MSDU)**
* On transmission, assemble data into a frame, known as a **MAC protocol data unit (MPDU)** with address and error-detection fields.
* On reception, disassemble frame, and perform address recognition and error detection.
* Govern access to the LAN transmission medium.
MPDU format

* MAC Control field: contains protocol control information for the MAC protocol functions like priority.
* Destination MAC Address field: specifies the destination physical address on the LAN for the MPDU frame.
* Source MAC Address field: The source physical address on the LAN for this MPDU.
* * MAC Service Data Unit field: contains the data passed down from the higher layer.
* CRC (Frame Check Sequence) field(幀檢查序列): contains the cyclic redundancy check/error detecting code calculated over the entire frame contents. It is used by the receiver to detect any errors in the frame.(包含對整個幀內容計算的循環冗餘檢查/錯誤檢測代碼。接收器使用它來檢測幀中的任何錯誤。)
### Logical Link Control
1. MAC layer
1. responsible for detecting errors and discarding any frames that contain errors.
2. LLC layer
1. optionally keeps track of which frames have been successfully received and retransmits unsuccessful frames.
## IEEE 802.11 Network Components and Architectural Model
1. **basic service set (BSS) :** smallest building block of a wireless LAN
2. **distribution system (DS) :** backbone
3. BSS ➝ **access point (AP) ➝ DS**

* Independent Basic Service Set (IBSS)
* wireless network communicate directly with each (without AP)
* ad hoc
* it is formed spontaneously as stations come into range of each other
* Extended Service Set (ESS)
* a collection of two or more basic service sets (BSS) that are interconnected by a distribution system
* roam freely between different BSSs within the ESS
* possible for two BSSs to overlap geographically ➝ single station could participate in more than one BSS
## IEEE 802.11 Services
two ways of categorizing IEEE 802.11 services
1. The service provider can be either the station or the DS.
2. Three of the services ➝ used to control IEEE 802.11 LAN access and confidentiality
Six of the services ➝ used to support delivery of MSDUs between stations
**Table 24.2 IEEE 802.11 Services**
| **Service** | **Provider** | **Used to support** |
| ---| ---| --- |
| Association | Distribution system | MSDU delivery |
| Authentication | Station | LAN access and security |
| Deauthentication | Station | LAN access and security |
| Disassociation | Distribution system | MSDU delivery |
| Distribution | Distribution system | MSDU delivery |
| Integration | Distribution system | MSDU delivery |
| MSDU delivery | Station | MSDU delivery |
| Privacy | Station | LAN access and security |
| Reassociation | Distribution system | MSDU delivery |
### Distribution of messages within a DS
* **Distribution**
* Exchange MPDUs between two BSS
* **Integration**
* Data transfer between a Wi-Fi station and an LAN station on an integrated IEEE 802x LAN
### Associated-Related Services
* Transition types, based on mobility:
* No transition
* Move only within a single BSS
* BSS transition
* Move between two BSS
* ESS transition
* Move from a BSS in one ESS to a BSS within another ESS
#### Distribution Service
* Association
* Establishes an initial association between a station and an AP
* Reassociation
* Enables an established association to be transferred from one AP to another
* Disassociation
* A notification from either a station or an AP that an existing association is terminated
# **24.4 IEEE 802.11i Wireless LAN Security**
* Wired Equivalent Privacy (WEP) algorithm
* 802.11 privacy
* Wi-Fi Protected Access (WPA)
* Set of security mechanisms: eliminates most 802.11 security issues
* Based on the current state of the 802.11i standard
* Robust Security Network (RSN)
* Final form of the 802.11i standard
* Wi-Fi Alliance certifies vendors in compliance with the full 802.11i (WPA2)
## IEEE 802.11i Services
The 802.11i RSN security specification defines the following services:
* **Authentication:**A protocol is used to define an exchange between a user and an AS (authentication server)
* provides mutual authentication and generates temporary keys to be used between the client and the AP over the wireless link.
* **Access control:** authentication
* routes the messages properly, and facilitates key exchange. It can work with a variety of authentication protocols.
* **Privacy with message integrity:** MAC-level data (e.g., an LLC PDU) are encrypted along with a message integrity code that ensures that the data have not been altered.
Figure 24.6a indicates the security protocols used to support these services
Figure 24.6b lists the cryptographic algorithms used for these services

## IEEE 802.11i Phases of Operation
IEEE 802.11i security is concerned only with secure communication between the STA and its AP
five distinct phases of IEEE 802.11i RSN:
* Two wireless stations in the same BSS communicating via the access point for that BSS. (在同一 BSS 中的兩個無線電台通過該 BSS 的接入點進行通信)
* secure communication is assured if each STA establishes secure communications with the AP.
* Two wireless stations (STAs) in the same ad hoc IBSS communicating directly with each other. (在同一 ad hoc IBSS 中的兩個無線電台(STA)直接相互通信)
* with the AP functionality residing in the STA.
* **Two wireless stations in different BSSs communicating via their respective APs across a distribution system. (**不同 BSS 中的兩個無線電台通過各自的 AP 跨分發系統進行通信**)**
* distribution system at the level of IEEE 802.11, but only within each BSS. End-to-end security (if required) must be provided at a higher layer
* **A wireless station communicating with an end station on a wired network via its AP and the distribution system. (**無線電台通過其 AP 和 DS 與有線網絡上的終端站通信**)**
* security is only provided between the STA and its AP

### Five Phases of Operation for an RSN
Sure, here is a summary of each key point of the listed paragraph:
**Discovery**
* APs advertise their security policies using Beacons and Probe Responses.
* STAs use this information to select an AP to associate with.
* The AP and STA agree on a cipher suite and authentication mechanism.
**Authentication**
* The STA and AS prove their identities to each other.
* Non-authentication traffic is blocked until authentication is successful.
* The AP does not participate in the authentication transaction other than forwarding traffic.
**Key Management**
* Cryptographic keys are generated and placed on the AP and STA.
* Frames are exchanged only between the AP and STA.
**Protected data transfer**
* Frames are exchanged between the STA and end station through the AP.
* Secure data transfer occurs only between the STA and AP; security is not provided end-to-end.
**Connection termination**
* The AP and STA exchange frames to tear down the secure connection.
* The connection is restored to its original state.

## Discovery Phase
* STA and an AP to recognize each other
### Security capabilities
* STA and AP decide on specific techniques in the following areas
* Confidentiality and MPDU integrity protocols (only unicast)
* Authentication method
* Cryptography key
* management approach
* protecting multicast/broadcast traffic are dictated by the AP
* Cipher suite (Confidentiality/integrity)
* WEP, TKIP, CCMP, vendor- specific
* AKM: Authentication and Key Management
* IEEE 802.1x, pre-shared key, vendor-specific
### MPDU Exchange
**Network and security capability discovery:**
* STAs discover the existence of a network with which to communicate.
* APs broadcast their security capabilities through Beacon frames or Probe Response frames.
* Wireless stations can discover available access points by passively monitoring Beacon frames or actively probing every channel.
**Open system authentication:**
* This frame sequence provides no security but maintains backward compatibility with existing IEEE 802.11 hardware.
* The STA and AP simply exchange identifiers.
**Association:**
* The STA and AP agree on a set of security capabilities to be used.
* The STA sends an Association Request frame to the AP, specifying one set of matching capabilities.
* If there is no match in capabilities, the AP refuses the Association Request.
* The STA blocks it too, in case it has associated with a rogue AP or someone is inserting frames illicitly on its channel.

## Authentication Phase
* IEEE 802.11X AC
* 802.1X Control channel is unblocked
* 802.11 data channel is blocked
* Three phases
* Connect to AS
* The STA sends a request to its AP
* EAP exchange
* exchange authenticates the STA and AS to each other
* Secure key delivery
* Once authentication is established, the AS generates a master session key (MSK), also known as the Authentication, Authorization, and Accounting (AAA) key, and sends it to the STA.

### EAP Authentication Protocol
* An Authentication framework, but not a specific mechanism
* Providing some common functions
* Negotiating authentication methods: EAP methods (more than 40)
* Important notes
* EAP authentication is initiated by the server (authenticator)
* Authentication is mutual between the client and authentication server

### Popular EAP Methods
* Cisco LEAP (Lightweight EAP)
* A proprietary method developed by Cisco
* User credentials are not strongly protected: _complex passwords are required_
* EAP-FAST (EAP-Flexible Authentication via Secure Tunneling)
* A replacement for LEAP, but non-proprietary
* _No need of strong password or any certificate_
* Using a PAC (Protected Access Credential) to establish a TLS tunnel
* EAP-TLS (EAP-Transport Layer Security)
* (RFC 5216) original, standard wireless LAN EAP authentication protocol
* Using PKI: both client and AS need a certificate (X.509 certificates)
* One of the most secure EAP standards available
* Universally supported by all manufacturers of wireless LAN hardware/software
* PEAP (Protected EAP)
* Encapsulating EAP within a potentially encrypted and authenticated TLS tunnel
* Only the server authentication is performed using PKI certificate
* Client is authenticated using either EAP-GTC or EAP-MSCHAPv2 within the tunnel
* AP-GTC (Generic Token Card)
* EAP-MSCHAPv2 (Microsoft’s Challenge Handshake Authentication Protocol)

## Key Management Phase
* Pairwise keys: for communication between an STA and an AP
* Pre-shared key (PSK)
* Master session key (MSK)
* Pairwise master key (PMK)
* PSK or derived from MSK
* Pairwise transient key (PTK)
* Group keys: for multicast communication
* Group master key (GMK)
* Group temporal key (GTK)


### **4-way handshake**
* **AP ➝ STA:** Message includes the MAC address of the AP and a nonce (Anonce)
* **STA ➝AP:** The STA generates its own nonce (Snonce) and uses both nonces and both MAC addresses, plus the PMK, to generate a PTK. The STA then sends a message containing its MAC address and Snonce, enabling the AP to generate the same PTK. This message includes a message integrity code (MIC)2 using HMAC-MD5 or HMAC-SHA-1-128. The key used with the MIC is KCK.
* **AP ➝ STA:** The AP is now able to generate the PTK. The AP then sends a message to the STA, containing the same information as in the first message, but this time including a MIC.
* **STA ➝ AP:** This is merely an acknowledgment message, again protected by a MIC.

###
## Protected Data Transfer Phase
* Temporal Key Integrity Protocol (TKIP)
* Only software changes are required to old WEP
* Message integrity
* Message Integrity Code (MIC): by an algorithm, called Michael
* 64-bit: source/destination MAC addresses + data field + key material
* Data confidentiality
* Encrypting MPDU + MIC using RC4
* 256-bit TK
* Two 64-bit keys for MIC: one key for each direction
* 128 bits: generate the RC4 key for encryption
* TKIP sequence counter (TSC): monotonically increasing
* Included with each MPCU and protected by MIC➔against replay attack
* Combined with session TK➔dynamic encryption key
* Counter Mode-CBC MAC Protocol (CCMP)
* Hardware support is needed
* Message integrity
* Cipher block chaining message authentication code (CBC-MAC)
* Data confidentiality
* CTR block cipher mode of operation with AES
* Same 128-bit AES key for both
* A 48-bit packet number: a nonce to prevent replay attacks
## The IEEE 802.11i Pseudorandom Function
* A pseudorandom bit stream: HMAC-SHA-1
* A message and a key (at least 160 bits)➔160-bit hash value
* SHA-1 property: change of a single bit➔a new hash value with no apparent connection
PTK = PRF(PMK, “Pairwise key expansion,” min(AP-Addr, STA-Addr) } ||
max (AP-Addr, STA-Addr) || min(Anonce, Snonce) || max(Anonce, Snonce), 384)
> _K_ \= PMK
>
> _A_ \= the text string “Pairwise key expansion”
>
> _B_ \= a sequence of bytes formed by concatenating the two MAC addresses and the two nonces
>
> _Len_ \= 384 bits
>
> Similarly, a nonce is generated by
>
> Nonce = PRF(Random Number, “Init Counter,” MAC } Time, 256)
GTK = PRF(GMK, _“_Group key expansion,” MAC || Gnonce, 256)

# **24.5 Key Terms, Review Questions, and Problems**
**24.1 What is the basic building block of an 802.11 WLAN?**
The basic building block of an 802.11 WLAN is the Basic Service Set (BSS). A BSS is a wireless network that consists of two or more stations that communicate directly with each other without the need for an access point (AP). Ad hoc
**24.2 Define an extended service set.**
An Extended Service Set (ESS) is a collection of two or more BSSs that are interconnected by a distribution system. This allows stations to roam freely between different BSSs within the ESS, as if they were all part of a single logical LAN.
**24.3 List and briefly define IEEE 802.11 services.**
The IEEE 802.11 standard defines a number of services, including:
* **Data:** This service provides for the transfer of data frames between stations.
* **Management:** This service provides for the exchange of management frames, which are used to control and manage the BSS.
* **Control:** This service provides for the exchange of control frames, which are used to coordinate the transmission of data frames.
**24.4 Which assumptions form the basis of security policy for mobile devices?**
The following assumptions form the basis of security policy for mobile devices:
* **Mobile devices are often outside the organization's control.**
* **Mobile devices may be used on untrusted networks.**
* **Mobile devices may be used to access untrusted content.**
* **Mobile devices may be infected with malware.**
**24.5 List the seven major security concerns for mobile devices.**
The seven major security concerns for mobile devices are:
* **Theft and tampering:** Mobile devices are often outside the organization's control and may be stolen or tampered with.
* **Unauthorized access:** Mobile devices may be accessed by unauthorized users.
* **Data loss:** Mobile devices may be lost or damaged, resulting in the loss of data.
* **Malware:** Mobile devices may be infected with malware, which can steal data, compromise systems, or disrupt operations.
* **Network attacks:** Mobile devices may be attacked when they are connected to untrusted networks.
* **Content security:** Mobile devices may be used to access untrusted content, such as malicious websites or apps.
* **Physical security:** Mobile devices may be lost or damaged due to physical accidents.
**24.6 Briefly describe the pseudorandom stream generation of the IEEE 802.11i scheme and list some uses of the pseudorandom function.**
The pseudorandom stream generation of the IEEE 802.11i scheme is based on the Counter Mode with Cipher Block Chaining Message Authentication Code (CCM) algorithm. The CCM algorithm uses a pseudorandom function (PRF) to generate a keystream, which is then used to encrypt and authenticate data frames. The PRF is also used to generate other cryptographic keys, such as the pairwise master key (PMK) and the transient key (TK).
**24.7 Briefly describe the four IEEE 802.11i phases of operation.**
The four IEEE 802.11i phases of operation are:
* **Discovery:** The STA discovers the existence of a network with which to communicate.
* **Authentication:** The STA and AP prove their identities to each other.
* **Key Management:** The AP and STA perform several operations that cause cryptographic keys to be generated and placed on the AP and STA.
* **Protected data transfer:** Frames are exchanged between the STA and the end station through the AP.
* **Connection termination**
**24.8 What is the difference between TKIP and CCMP?**
TKIP (Temporal Key Integrity Protocol) and CCMP (Counter Mode with Cipher Block Chaining Message Authentication Code) are two encryption algorithms used in IEEE 802.11i. TKIP is a legacy algorithm that is less secure than CCMP. CCMP is the preferred algorithm for new deployments. |
import { POST } from "@/helper/api_helper";
import { BASE_URL, LOGIN_URL, REGISTER_URL } from "@/helper/url_helper";
import { useUserStore } from "@/store/userStore";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import Label from "./Label";
type AuthProps = {
type: string;
};
export default function AuthForm(props: AuthProps) {
const [error, setError] = useState<string | null>(null);
const { user, setUser } = useUserStore();
const router = useRouter();
const inputStyle =
" m-auto focus:outline-none focus:ring-2 ring-tertiary rounded-md p-2 w-5/6 placeholder:text-center placeholder:italic placeholder:opacity-60";
const register = async (formData: FormData) => {
try {
const data = Object.fromEntries(formData);
await POST(BASE_URL + REGISTER_URL, data);
setError(null);
} catch (error) {
setError(error.message);
}
};
const login = async (formData: FormData) => {
try {
const data = Object.fromEntries(formData);
const logingUser = await POST(BASE_URL + LOGIN_URL, data);
setUser({
firstName: logingUser.firstName,
lastName: logingUser.lastName,
email: logingUser.email,
});
router.push("/profile");
setError(null);
} catch (error) {
setError(error.message);
}
};
useEffect(() => {
console.log(user);
}, [user]);
return (
<form
className="bg-secondary p-8 rounded-2xl flex flex-col gap-8 justify-between py-4"
action={props.type === "register" ? register : login}
>
<div className="grid grid-cols-own-auth gap-4 ">
<Label text="Email" color="tertiary" />
<input
type="text"
name="email"
placeholder="Email"
className={inputStyle}
/>
{props.type === "register" && (
<>
<Label text="First Name" color="tertiary" />
<input
type="text"
name="firstName"
placeholder="FirstName"
className={inputStyle}
/>
</>
)}
{props.type === "register" && (
<>
<Label text="Last Name" color="tertiary" />
<input
type="text"
name="lastName"
placeholder="LastName"
className={inputStyle}
/>
</>
)}
<Label text="Password" color="tertiary" />
<input
type="password"
name="password"
placeholder="Password"
className={inputStyle}
/>
{props.type === "register" && (
<>
<Label text="Password Confirmation" color="tertiary" />
<input
type="password"
name="password_confirmation"
placeholder="Confirm password"
className={inputStyle}
/>
</>
)}
</div>
{error === "E_VALIDATION_ERROR" && (
<p className="text-red-700 text-center text-lg">
Some fields are not correctly filled.
</p>
)}
{error === "23505" && (
<p className="text-red-700 text-center text-lg">
An account is already registered with the email you provided
</p>
)}
<div className="flex justify-center">
<button
type="submit"
className="bg-dark-secondary text-primary hover:bg-tertiary hover:text-secondary rounded-md w-1/2 m-auto h-12 shadow-own-1"
>
{props.type === "login" ? "Login" : "Register"}
</button>
</div>
</form>
);
} |
import StringReader from './StringReader.js'
// Scanner is an iterator class for scanning tokens within .p69 files.
export default class Scanner {
constructor(content) {
this._sr = new StringReader(content)
this._prefix = '$'
this._escapedPrefix = this._escapeForRegex(this._prefix)
this._prefixRegex = new RegExp(this._escapedPrefix)
}
_escapeForRegex = (s) => {
return s.replace(/[/\-\.\(\)\[\]\$\^\&\\]/g, '\\$&')
}
// NAME := { *alpha-numeric* | "_" | "-" | "." | "$" }
_scanName() {
return this._sr.readWhile(/[a-zA-Z0-9_\-\.\$]/)
}
// PARAMS := [ "(" ARGS ")" ]
_scanParams(name) {
const bookmark = this._sr.makeBookmark()
this._sr.skipSpaces()
if (!this._sr.accept(/\(/)) {
this._sr.gotoBookmark(bookmark)
return []
}
this._sr.skipSpaces()
if (this._sr.accept(/\)/)) {
return []
}
const args = this._scanArgs(name)
this._sr.expect(/\)/)
return args
}
// ARGS := [ ARG { "," ARG } ]
_scanArgs(name) {
const args = []
while (true) {
const arg = this._scanArg(name)
args.push(arg)
this._sr.skipSpaces()
if (!this._sr.accept(/,/)) {
break
}
}
return args
}
// ARG := '"' { *any rune except '"' OR '\'* | '\"' | '\\' } '"'
// ARG := "'" { *any rune except "'" OR "\"* | "\'" | "\\" } "'"
// ARG := { *any rune except "\"* | "\\" }
_scanArg(name) {
this._sr.skipSpaces()
const delim = this._sr.accept(/["']/)
let arg = ''
if (delim) {
arg = this._scanQuotedArg(delim, name)
} else {
arg = this._sr.readWhile(/[^,)]/)
arg = arg === '' ? null : arg
}
if (arg === null) {
throw new Error(`Missing argument for '${name}'`)
}
return arg
}
_scanQuotedArg(delim, name) {
const readingArg = new RegExp(`[^\\\\${delim}]`)
const terminatingDelim = new RegExp(delim)
let result = ''
let escaped = false
while (!this._sr.isEmpty()) {
result += this._sr.readWhile(readingArg)
const termintor = this._sr.accept(terminatingDelim)
if (termintor && !escaped) {
return result
}
if (termintor && escaped) {
result += termintor
escaped = false
continue
}
const backSlash = this._sr.accept(/\\/)
if (backSlash && !escaped) {
escaped = true
continue
}
if (backSlash && escaped) {
result += backSlash
escaped = false
continue
}
}
throw new Error(`Unterminated string for argument of '${name}'`)
}
// SUFFIX := *white-space*
_scanSuffix() {
return this._sr.accept(/\s/) || ''
}
// nextToken scans and returns the next token or null if the end of file
// reached.
nextToken() {
if (!this._sr.seek(this._prefixRegex)) {
return null
}
const start = this._sr.makeBookmark()
this._sr.read() // skip prefix
const name = this._scanName()
const args = this._scanParams(name)
const suffix = this._scanSuffix()
const end = this._sr.makeBookmark()
return {
start: start.cpIdx,
end: end.cpIdx,
raw: this._sr.slice(start.runeIdx, end.runeIdx),
suffix: suffix,
path: name.split('.'),
args: args,
}
}
}
// scanAll is convenience function for scanning all tokens at once.
export const scanAll = (content) => {
const sc = new Scanner(content)
const result = []
let tk = null
while ((tk = sc.nextToken())) {
result.push(tk)
}
return result
} |
// this contains home page content
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation } from 'swiper/modules';
import SwiperCore from 'swiper';
import 'swiper/css/bundle';
import ListingItem from '../components/ListingItem';
export default function Home() { // pieces of state for listing
const [offerListings, setOfferListings] = useState([]);
const [saleListings, setSaleListings] = useState([]);
const [rentListings, setRentListings] = useState([]);
const [leaseListings, setLeaseListings] = useState([]);
SwiperCore.use([Navigation]);
console.log(offerListings);
useEffect(() => {
const fetchOfferListings = async () => {
try {
const res = await fetch('/api/listing/get?offer=true&limit=4');
const data = await res.json();
setOfferListings(data);
fetchRentListings(); // fetch data for rent only after data for offer is loaded
} catch (error) {
console.log(error);
}
};
const fetchRentListings = async () => {
try {
const res = await fetch('/api/listing/get?type=rent&limit=6');
const data = await res.json();
setRentListings(data);
fetchSaleListings();
} catch (error) {
console.log(error);
}
};
const fetchSaleListings = async () => {
try {
const res = await fetch('/api/listing/get?type=sale&limit=6');
const data = await res.json();
setSaleListings(data);
fetchLeaseListings();
} catch (error) {
console.log(error);
}
};
const fetchLeaseListings = async () => {
try {
const res = await fetch('/api/listing/get?type=lease&limit=6');
const data = await res.json();
setLeaseListings(data);
} catch (error) {
console.log(error);
}
};
fetchOfferListings();
}, []);
return (
<div className='-mt-12'>
{/* top */ }
<div className='flex flex-col gap-6 p-28 px-3 max-w-6xl mx-auto'>
<h1 className='text-slate-700 font-bold text-3xl lg:text-6xl'>
Find your <span className='text-green-500'>home</span>
<br />
The <span className='text-slate-500'> perfect</span> place with ease
</h1>
<div className='text-black-400 text-xs sm:text-sm'>
Find my Home is the best place to find your next perfect place to live.
<br />
We have a wide range of properties for you to choose from.
</div>
<Link
to={"/search"}
className='text-xs sm:text-sm text-blue-800 font-bold hover:underline'
>
Let's get started...
</Link>
</div>
{/* swiper */}
<Swiper navigation>
{offerListings &&
offerListings.length > 0 &&
offerListings.map((listing) => (
<SwiperSlide>
<div
style={{
background: `url(${listing.imageUrls[0]}) center no-repeat`,
backgroundSize: 'cover',
}}
className='h-[500px]'
key={listing._id}
></div>
</SwiperSlide>
))}
</Swiper>
{ /* listing results for offer, sale, lease and rent */}
<div className='max-w-6xl mx-auto p-3 flex flex-col gap-8 my-10'>
{
offerListings && offerListings.length > 0 && (
<div className=''>
<div className='my-3'>
<h2 className='text-2xl font-semibold text-slate-600'>Recent offers</h2>
<Link className='text-sm text-blue-800 hover:underline' to={'/search?offer=true'}>
Show more offers
</Link>
</div>
<div className='flex flex-wrap gap-4'>
{
offerListings.map((listing) => (
<ListingItem listing={listing} key={listing._id} />
))
}
</div>
</div>
)
}
{
rentListings && rentListings.length > 0 && (
<div className=''>
<div className='my-3'>
<h2 className='text-2xl font-semibold text-slate-600'>Recent places for rent</h2>
<Link className='text-sm text-blue-800 hover:underline' to={'/search?type=rent'}>
Show more places for rent
</Link>
</div>
<div className='flex flex-wrap gap-4'>
{
rentListings.map((listing) => (
<ListingItem listing={listing} key={listing._id} />
))
}
</div>
</div>
)
}
{
saleListings && saleListings.length > 0 && (
<div className=''>
<div className='my-3'>
<h2 className='text-2xl font-semibold text-slate-600'>Recent places for sale</h2>
<Link className='text-sm text-blue-800 hover:underline' to={'/search?type=sale'}>
Show more places for sale
</Link>
</div>
<div className='flex flex-wrap gap-4'>
{
saleListings.map((listing) => (
<ListingItem listing={listing} key={listing._id} />
))
}
</div>
</div>
)
}
{
leaseListings && leaseListings.length > 0 && (
<div className=''>
<div className='my-3'>
<h2 className='text-2xl font-semibold text-slate-600'>Recent places for lease</h2>
<Link className='text-sm text-blue-800 hover:underline' to={'/search?type=lease'}>
Show more places for lease
</Link>
</div>
<div className='flex flex-wrap gap-4'>
{
leaseListings.map((listing) => (
<ListingItem listing={listing} key={listing._id} />
))
}
</div>
</div>
)
}
</div>
</div>
);
} |
import { useParams } from "react-router-dom"
import {useProduct} from "../../contexts/productContext"
import Banner from "../../components/Banner/Banner"
import shopSingleImg from "../../assets/images/shop-single.png"
import ProductCard from "../../components/Productcard/ProductCard"
import { BsStarFill } from "react-icons/bs";
import Button from "../../components/buttons/Button"
import styles from "./ShopSingle.module.scss"
function ShopSingle() {
const {productId} = useParams()
const {products} = useProduct()
const product = products.find((p) => p.id === productId);
const relatedProducts = products ? products.sort(() => Math.random() - 0.5).slice(0, 4).map(product => (
<ProductCard key={product.id} tagName={product.category} img={product?.image} name={product.name} oldPrice={product["old price"]} newPrice={product["new price"]} to={`/shop/product/${product.id}`} />
)) : []
// console.log(shuffledArr)
return (
<main className={styles.main}>
{/* banner sec starts */}
<section className={styles.shopSingle__banner}>
<Banner img={shopSingleImg} desc="shop single banner img"/>
</section>
{/* banner sec ends */}
{/* single product sec starts */}
<section className={styles.singleProduct__sec}>
<figure className={styles.single__product}>
<div className={styles.product__img}><img src={product?.image} alt="" /></div>
<figcaption>
<h2 className={styles.product__name}>
{product?.name}
</h2>
<span className={styles.product__stars}>
<BsStarFill/>
<BsStarFill/>
<BsStarFill/>
<BsStarFill/>
<BsStarFill/>
</span>
<span className={styles.product__prices}>
<s>${product?.["old price"]}</s> <p>${product?.["new price"]}</p>
</span>
<p className={styles.product__productDesc}>Lorem ipsum dolor sit amet consectetur adipisicing elit. Doloremque, reprehenderit.</p>
<div className={styles.addTo__cart}>
Quantity:
<span className={styles.quantity}>1</span>
<Button type='button' spec='default' content='Add To Cart'/>
</div>
</figcaption>
</figure>
<article className={styles.product__info}>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Obcaecati dolore unde illo labore officia praesentium, sit quibusdam quae. Necessitatibus, dolorem.
</article>
</section>
{/* single product sec ends */}
{/* related products sec begins */}
<section className={styles.relatedProduct__sec}>
<div className={styles.related__product}>
<h2 className={styles.heading}>Related Products</h2>
<div className={styles.relatedProduct__list}>
{relatedProducts}
</div>
</div>
</section>
{/* related products sec ends */}
</main>
)
}
export default ShopSingle |
{% extends 'base.html.twig' %}
{% block title %}Listes des genres{% endblock %}
{% block body %}
<div class="container ">
<nav class="nav navbar">
<div class="col-sm-6">
<h1>Liste des genres</h1>
{{ include('_flash_messages.html.twig') }}
</div>
<a class="btn btn-success" href="{{ path('back_genre_create') }}">Ajouter</a>
</nav>
<table class="table ">
<thead>
<tr>
<th>Id</th>
<th>Nom</th>
<th class="d-none d-md-table-cell">Image</th>
<th class='col-1 text-end'>Actions</th>
</tr>
</thead>
<tbody>
{% for genre in genres %}
<tr>
<td>{{ genre.id }}</td>
<td>{{ genre.name }}</td>
<td class="d-none d-md-table-cell">{{ genre.image }}</td>
<td class= "d-sm-flex">
<a class="buttons btn btn-warning" href="{{ path('back_genre_update', {'id': genre.id}) }}">Editer</a>
{{ include('genre/_delete_form.html.twig') }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="container">
<nav aria-label="Page navigation">
<ul class="pagination">
<li class="page-item {{ (page == 1) ? 'disabled' : '' }}">
<a class="page-link" href="?page={{ page - 1 }}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
{% set pages = (total / limit)|round(0, 'ceil') %}
{% for item in 1..pages %}
<li class="page-item {{ (page == item) ? "active" : "" }}">
<a class="page-link" href="?page={{ item }}">{{ item }}</a>
</li>
{% endfor %}
<li class="page-item {{ (page == pages) ? 'disabled' : '' }}">
<a class="page-link" href="?page={{ page + 1 }}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</div>
{% endblock %} |
import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { map } from 'rxjs';
@Injectable()
export class SpeciesService {
constructor(private httpService: HttpService) {}
async findSpecies(id: number) {
const data = this.httpService
.get(`https://pokeapi.co/api/v2/pokemon-species/${id}/`)
.pipe(
map((response) => response.data),
map((data) => ({
flavorText: getFlavorText(data.flavor_text_entries),
evolutionChain: getEvolutionChainId(
data.evolution_chain.url,
),
genera: getGenera(data.genera),
originGeneration: data.generation.name,
habitat: () => {
data.habitat ? data.habitat.name : undefined;
},
shape: () => {
data.shape ? data.shape.name : undefined;
},
color: data.color.name,
})),
);
return data;
}
}
function getEvolutionChainId(evolutionChainUrl: string) {
return evolutionChainUrl
.slice(0, -1)
.substring(evolutionChainUrl.slice(0, -1).lastIndexOf('/') + 1);
}
function getGenera(generaData) {
for (let i = 0; i < generaData.length; i++) {
if (generaData[generaData.length - i - 1].language.name === 'en') {
return `${generaData[generaData.length - i - 1].genus}`;
}
}
}
function getFlavorText(flavorTextData) {
for (let i = 0; i < flavorTextData.length; i++) {
if (
flavorTextData[flavorTextData.length - i - 1].version.name ===
'shield' &&
flavorTextData[flavorTextData.length - i - 1].language.name === 'en'
) {
return `${
flavorTextData[flavorTextData.length - i - 1].flavor_text
}`;
}
}
} |
#include "tracker.as"
#include "helpers.as"
#include "admin_manager.as"
#include "log.as"
#include "query_helpers.as"
#include "game_timer.as"
#include "score_tracker.as"
#include "stage_snd.as"
#include "player_manager.as"
#include "vip_tracker.as"
#include "hitbox_handler.as"
// --------------------------------------------
class Assassination : SubStage {
protected PlayerTracker@ m_playerTracker;
protected VIPTracker@ m_vipTracker;
protected HitboxHandler@ m_hitboxHandler;
protected GameTimer@ m_gameTimer;
// --------------------------------------------
Assassination(Stage@ stage, float maxTime, array<int> competingFactionIds = array<int>(0, 1), int protectorFactionId = 2) {
super(stage);
m_name = "snd";
m_displayName = "Search and Destroy";
// the trackers get added into active tracking at SubStage::start()
@m_gameTimer = GameTimer(m_metagame, maxTime);
}
// --------------------------------------------
void startMatch() {
if (m_gameTimer !is null) {
// if GameTimer is used, some match settings must be set accordingly before starting the match
m_gameTimer.prepareMatch(m_match);
}
// track Players
@m_playerTracker = PlayerTracker(m_metagame);
addTracker(m_playerTracker);
// track the vip
@m_vipTracker = VIPTracker(m_metagame);
addTracker(m_vipTracker);
// prepare vip and extraction points
@m_hitboxHandler = HitboxHandler(m_metagame, "as");
addTracker(m_hitboxHandler);
SubStage::startMatch();
if (m_gameTimer !is null) {
m_gameTimer.start(-1);
}
}
// --------------------------------------------
array<Faction@> getFactions() {
return m_match.m_factions;
}
// --------------------------------------------
// GameTimer uses in-game defense win timer, which reports match end here
protected void handleMatchEndEvent(const XmlElement@ event) {
// TagName=match_result
// TagName=win_condition
// faction_id=-1
// type=map_capture
int winner = -1;
array<const XmlElement@> elements = event.getElementsByTagName("win_condition");
if (elements.length() >= 1) {
const XmlElement@ winCondition = elements[0];
// can be -1 if so set by GameTimer - means clock has run out of time.
// in CS (vip rescue game mode), Terrorists win if clock runs out.
winner = winCondition.getIntAttribute("faction_id");
if (winner == -1) {
_log("** SND: AS stage, T win by timeout", 1);
winner = 1; // terrorists
}
} else {
_log("couldn't find win_condition tag");
}
setWinner(winner);
m_playerTracker.save();
end();
}
} |
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../services/authentication.service';
import { take, map, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class PartOfTeamGuard implements CanActivate {
constructor(
private authService: AuthenticationService,
private router: Router
) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.user$.pipe(
take(1), // Complete observable after first value is emitted
map(user => (user.partOfTeams && user.partOfTeams.includes(next.paramMap.get('teamId')))), // map to boolean
tap(
loggedIn => {
if (!loggedIn) {
console.log('Access Denied');
this.router.navigate(['']);
}
}
)
);
}
} |
//! This is a copy-paste of necessary types from `zksync-2-dev`
//! repository to avoid having a dependency on it.
//!
//! These are strictly the types that are necessary for
//! interacting with the RPC endpoints.
use chrono::{DateTime, Utc};
use ethers::{
abi::RawLog,
types::{Address, Bloom, Bytes, H160, H256, U256, U64},
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
#[allow(missing_docs)]
pub struct BaseSystemContractsHashes {
pub bootloader: H256,
pub default_aa: H256,
}
/// A struct with the proof for the L2 to L1 log in a specific block.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct L2ToL1LogProof {
/// The merkle path for the leaf.
pub proof: Vec<H256>,
/// The id of the leaf in a tree.
pub id: u32,
/// The root of the tree.
pub root: H256,
}
/// A transaction receipt in `zksync` network.
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct TransactionReceipt {
/// Transaction hash.
#[serde(rename = "transactionHash")]
pub transaction_hash: H256,
/// Index within the block.
#[serde(rename = "transactionIndex")]
pub transaction_index: Index,
/// Hash of the block this transaction was included within.
#[serde(rename = "blockHash")]
pub block_hash: Option<H256>,
/// Number of the miniblock this transaction was included within.
#[serde(rename = "blockNumber")]
pub block_number: Option<U64>,
/// Index of transaction in l1 batch
#[serde(rename = "l1BatchTxIndex")]
pub l1_batch_tx_index: Option<Index>,
/// Number of the l1 batch this transaction was included within.
#[serde(rename = "l1BatchNumber")]
pub l1_batch_number: Option<U64>,
/// Sender
/// Note: default address if the client did not return this value
/// (maintains backwards compatibility for `<= 0.7.0` when this field was missing)
#[serde(default)]
pub from: Address,
/// Recipient (None when contract creation)
/// Note: Also `None` if the client did not return this value
/// (maintains backwards compatibility for `<= 0.7.0` when this field was missing)
#[serde(default)]
pub to: Option<Address>,
/// Cumulative gas used within the block after this was executed.
#[serde(rename = "cumulativeGasUsed")]
pub cumulative_gas_used: U256,
/// Gas used by this transaction alone.
///
/// Gas used is `None` if the the client is running in light client mode.
#[serde(rename = "gasUsed")]
pub gas_used: Option<U256>,
/// Contract address created, or `None` if not a deployment.
#[serde(rename = "contractAddress")]
pub contract_address: Option<Address>,
/// Logs generated within this transaction.
pub logs: Vec<Log>,
/// L2 to L1 logs generated within this transaction.
#[serde(rename = "l2ToL1Logs")]
pub l2_to_l1_logs: Vec<L2ToL1Log>,
/// Status: either 1 (success) or 0 (failure).
pub status: Option<U64>,
/// State root.
pub root: Option<H256>,
/// Logs bloom
#[serde(rename = "logsBloom")]
pub logs_bloom: Bloom,
/// Transaction type, Some(1) for AccessList transaction, None for Legacy
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub transaction_type: Option<U64>,
/// Effective gas price
#[serde(rename = "effectiveGasPrice")]
pub effective_gas_price: Option<U256>,
}
/// Index in block
pub type Index = U64;
/// A log produced by a transaction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Log {
/// H160
pub address: H160,
/// Topics
pub topics: Vec<H256>,
/// Data
pub data: Bytes,
/// Block Hash
#[serde(rename = "blockHash")]
pub block_hash: Option<H256>,
/// Block Number
#[serde(rename = "blockNumber")]
pub block_number: Option<U64>,
/// L1 batch number the log is included in.
#[serde(rename = "l1BatchNumber")]
pub l1_batch_number: Option<U64>,
/// Transaction Hash
#[serde(rename = "transactionHash")]
pub transaction_hash: Option<H256>,
/// Transaction Index
#[serde(rename = "transactionIndex")]
pub transaction_index: Option<Index>,
/// Log Index in Block
#[serde(rename = "logIndex")]
pub log_index: Option<U256>,
/// Log Index in Transaction
#[serde(rename = "transactionLogIndex")]
pub transaction_log_index: Option<U256>,
/// Log Type
#[serde(rename = "logType")]
pub log_type: Option<String>,
/// Removed
pub removed: Option<bool>,
}
impl Log {
/// Returns true if the log has been removed.
pub fn is_removed(&self) -> bool {
if let Some(val_removed) = self.removed {
return val_removed;
}
if let Some(ref val_log_type) = self.log_type {
if val_log_type == "removed" {
return true;
}
}
false
}
}
impl From<Log> for RawLog {
fn from(val: Log) -> Self {
(val.topics, val.data.to_vec()).into()
}
}
/// A log produced by a transaction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(missing_docs)]
pub struct L2ToL1Log {
pub block_hash: Option<H256>,
pub block_number: U64,
pub l1_batch_number: Option<U64>,
pub log_index: U256,
pub transaction_index: Index,
pub transaction_hash: H256,
pub transaction_log_index: U256,
pub shard_id: U64,
pub is_service: bool,
pub sender: Address,
pub key: H256,
pub value: H256,
}
/// Withdrawal event struct
#[derive(Debug)]
pub struct WithdrawalEvent {
/// A hash of the transaction of this withdrawal.
pub tx_hash: H256,
/// Number of the L2 block this withdrawal happened in.
pub block_number: u64,
/// Address of the transferred token
pub token: Address,
/// The amount transferred.
pub amount: U256,
/// Address on L1 that will receive this withdrawal.
pub l1_receiver: Option<Address>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(missing_docs)]
pub enum BlockStatus {
Sealed,
Verified,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(missing_docs)]
pub struct BlockDetails {
pub number: u32,
pub l1_batch_number: u32,
pub timestamp: u64,
pub l1_tx_count: usize,
pub l2_tx_count: usize,
pub root_hash: Option<H256>,
pub status: BlockStatus,
pub commit_tx_hash: Option<H256>,
pub committed_at: Option<DateTime<Utc>>,
pub prove_tx_hash: Option<H256>,
pub proven_at: Option<DateTime<Utc>>,
pub execute_tx_hash: Option<H256>,
pub executed_at: Option<DateTime<Utc>>,
pub l1_gas_price: u64,
pub l2_fair_gas_price: u64,
pub base_system_contracts_hashes: BaseSystemContractsHashes,
pub operator_address: Address,
}
/// Token in the zkSync network
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(missing_docs)]
pub struct Token {
pub l1_address: Address,
pub l2_address: Address,
pub name: String,
pub symbol: String,
pub decimals: u8,
} |
import { ShipsType } from '../types';
function collision(ships: ShipsType, locations: string[]) {
for (let i = 0; i < ships.length; i += 1) {
const shipLocations = ships[i].locations;
const allLocation = [...shipLocations];
for (let z = 0; z < shipLocations.length; z += 1) {
const shipLocationX = Number(shipLocations[z][0]);
const shipLocationY = Number(shipLocations[z][1]);
for (let x = -1; x < 2; x += 1) {
for (let y = -1; y < 2; y += 1) {
const currentX = shipLocationX + x;
const currentY = shipLocationY + y;
const newPosition = `${currentX}${currentY}`;
if (
currentX >= 0 &&
currentX <= 9 &&
currentY >= 0 &&
currentY <= 9 &&
allLocation.indexOf(newPosition) === -1
) {
allLocation.push(newPosition);
}
}
}
}
for (let j = 0; j < locations.length; j += 1) {
if (allLocation.indexOf(locations[j]) >= 0) {
return true;
}
}
}
return false;
}
function generateShip(boardSize: number, shipLength: number) {
const direction = Math.floor(Math.random() * 2);
let row;
let col;
if (direction === 1) {
row = Math.floor(Math.random() * boardSize);
col = Math.floor(Math.random() * (boardSize - shipLength));
} else {
row = Math.floor(Math.random() * (boardSize - shipLength));
col = Math.floor(Math.random() * boardSize);
}
const newShipLocations = [];
for (let i = 0; i < shipLength; i += 1) {
if (direction === 1) {
newShipLocations.push(`${row}${col + i}`);
} else {
newShipLocations.push(`${row + i}${col}`);
}
}
return newShipLocations;
}
export default function generateShipLocations(
boardSize: number,
shipsLength: number[]
) {
const ships: ShipsType = [];
let locations;
for (let i = 0; i < shipsLength.length; i += 1) {
for (let y = 1; y <= i + 1; y += 1) {
const shipLength = shipsLength[i];
do {
locations = generateShip(boardSize, shipLength);
} while (collision(ships, locations));
ships.push({
locations,
hits: new Array(shipLength).fill(''),
});
}
}
return ships;
} |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
/* eslint-disable @typescript-eslint/no-shadow */
import {
pointInTimeFinderMock,
mockGetCurrentTime,
mockGetSearchDsl,
} from '../repository.test.mock';
import type { SavedObjectsDeleteByNamespaceOptions } from '@kbn/core-saved-objects-api-server';
import { ALL_NAMESPACES_STRING } from '@kbn/core-saved-objects-utils-server';
import { SavedObjectsRepository } from '../repository';
import { loggerMock } from '@kbn/logging-mocks';
import {
SavedObjectsSerializer,
LEGACY_URL_ALIAS_TYPE,
} from '@kbn/core-saved-objects-base-server-internal';
import { kibanaMigratorMock } from '../../mocks';
import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks';
import {
mockTimestamp,
mappings,
createRegistry,
createDocumentMigrator,
createSpySerializer,
} from '../../test_helpers/repository.test.common';
describe('#deleteByNamespace', () => {
let client: ReturnType<typeof elasticsearchClientMock.createElasticsearchClient>;
let repository: SavedObjectsRepository;
let migrator: ReturnType<typeof kibanaMigratorMock.create>;
let logger: ReturnType<typeof loggerMock.create>;
let serializer: jest.Mocked<SavedObjectsSerializer>;
const registry = createRegistry();
const documentMigrator = createDocumentMigrator(registry);
beforeEach(() => {
pointInTimeFinderMock.mockClear();
client = elasticsearchClientMock.createElasticsearchClient();
migrator = kibanaMigratorMock.create();
documentMigrator.prepareMigrations();
migrator.migrateDocument = jest.fn().mockImplementation(documentMigrator.migrate);
migrator.runMigrations = jest.fn().mockResolvedValue([{ status: 'skipped' }]);
logger = loggerMock.create();
// create a mock serializer "shim" so we can track function calls, but use the real serializer's implementation
serializer = createSpySerializer(registry);
const allTypes = registry.getAllTypes().map((type) => type.name);
const allowedTypes = [...new Set(allTypes.filter((type) => !registry.isHidden(type)))];
// @ts-expect-error must use the private constructor to use the mocked serializer
repository = new SavedObjectsRepository({
index: '.kibana-test',
mappings,
client,
migrator,
typeRegistry: registry,
serializer,
allowedTypes,
logger,
});
mockGetCurrentTime.mockReturnValue(mockTimestamp);
mockGetSearchDsl.mockClear();
});
describe('performDeleteByNamespace', () => {
const namespace = 'foo-namespace';
const mockUpdateResults = {
took: 15,
timed_out: false,
total: 3,
updated: 2,
deleted: 1,
batches: 1,
version_conflicts: 0,
noops: 0,
retries: { bulk: 0, search: 0 },
throttled_millis: 0,
requests_per_second: -1.0,
throttled_until_millis: 0,
failures: [],
};
const deleteByNamespaceSuccess = async (
namespace: string,
options?: SavedObjectsDeleteByNamespaceOptions
) => {
client.updateByQuery.mockResponseOnce(mockUpdateResults);
const result = await repository.deleteByNamespace(namespace, options);
expect(mockGetSearchDsl).toHaveBeenCalledTimes(1);
expect(client.updateByQuery).toHaveBeenCalledTimes(1);
return result;
};
describe('client calls', () => {
it(`should use the ES updateByQuery action`, async () => {
await deleteByNamespaceSuccess(namespace);
expect(client.updateByQuery).toHaveBeenCalledTimes(1);
});
it(`should use all indices for types that are not namespace-agnostic`, async () => {
await deleteByNamespaceSuccess(namespace);
expect(client.updateByQuery).toHaveBeenCalledWith(
expect.objectContaining({
index: ['.kibana-test_8.0.0-testing', 'custom_8.0.0-testing'],
}),
expect.anything()
);
});
});
describe('errors', () => {
it(`throws when namespace is not a string or is '*'`, async () => {
const test = async (namespace: unknown) => {
// @ts-expect-error namespace is unknown
await expect(repository.deleteByNamespace(namespace)).rejects.toThrowError(
`namespace is required, and must be a string`
);
expect(client.updateByQuery).not.toHaveBeenCalled();
};
await test(undefined);
await test(['namespace']);
await test(123);
await test(true);
await test(ALL_NAMESPACES_STRING);
});
});
describe('returns', () => {
it(`returns the query results on success`, async () => {
const result = await deleteByNamespaceSuccess(namespace);
expect(result).toEqual(mockUpdateResults);
});
});
describe('search dsl', () => {
it(`constructs a query using all multi-namespace types, and another using all single-namespace types`, async () => {
await deleteByNamespaceSuccess(namespace);
const allTypes = registry.getAllTypes().map((type) => type.name);
expect(mockGetSearchDsl).toHaveBeenCalledWith(mappings, registry, {
namespaces: [namespace],
type: [
...allTypes.filter((type) => !registry.isNamespaceAgnostic(type)),
LEGACY_URL_ALIAS_TYPE,
],
kueryNode: expect.anything(),
});
});
});
});
}); |
_package user
$
#remex(:sw_tree_action)
$
_pragma(classify_level=basic, topic={graphics})
def_slotted_exemplar(:sw_tree_action,
## action, similar to sw_action, dedicated to tree_items.
##
{
{:name, _unset, :readable},
{:engine, _unset},
{:control, _unset},
{:properties, _unset},
{:data, _unset, :readable},
{:selection, _unset, :readable}
})
$
_pragma(classify_level=basic, topic={graphics})
_method sw_tree_action.new(p_name, p_engine, _gather p_properties)
## Create a sw_tree_action that behaves like a tree_item, but
## without the GUI. Create the GUI by invoking place_control_on()
##
## P_NAME: a symbol for the name of self.
##
## P_ENGINE: the engine that will receive the notification
## supplied in P_PROPERTIES
##
## P_PROPERTIES are paired elements with keys and value
## Allowed keys are all possible keys allowed in the creation of a
## tree_item. Addition values are:
##
## :data: initial list of trees.
##
## :selection: initial selection of trees
##
_return _clone.init(p_name, p_engine, p_properties)
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_private _method sw_tree_action.init(p_name, p_engine, p_properties)
##
##
.name << p_name
.engine << p_engine
.properties << property_list.new()
.data << {}
.selection << {}
_local props << property_list.new_with( _scatter p_properties )
_for property_name, value _over props.fast_keys_and_elements()
_loop
_if property_name _is :data
_then
.data << value
_elif property_name _is :selection
_then
.selection << value
_else
.properties[property_name] << value
_endif
_endloop
_return _self
_endmethod
$
_pragma(classify_level=basic, topic={graphics})
_method sw_tree_action.renew_data(p_data)
## Renews the list with P_DATA. Implicitly empties the
## selection.
#
_self.engine_selection << {}
.data << p_data
_if .control _isnt _unset
_then
.control.renew()
_endif
_endmethod
$
_pragma(classify_level=basic, topic={graphics})
_method sw_tree_action.update_data(p_data)
## Updates the list with P_DATA. Tries to retain the current
## selection.
#
.data << p_data
new_selection << _self.filter_selection()
_if new_selection.size <> .selection.size
_then
_self.engine_selection << new_selection
_else
.selection << new_selection
_endif
_if .control _isnt _unset
_then
.control.refresh()
_endif
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_private _method sw_tree_action.filter_selection()
_local keys << equality_set.new()
_for i_tree _over .data.fast_elements()
_loop
keys.add(i_tree.key)
_endloop
_local new_selection << rope.new()
_for i_tree _over .selection.fast_elements()
_loop
_if keys.includes?(i_tree.key)
_then
new_selection.add(i_tree)
_endif
_endloop
_return new_selection
_endmethod
$
_pragma(classify_level=basic, topic={graphics})
_method sw_tree_action.selection << p_selection
## Set the selection to P_SELECTION
#
_return _self.engine_selection << p_selection
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_private _method sw_tree_action.engine_selection << p_selection
_if .selection <> p_selection
_then
.selection << p_selection
_self.int!notify_engine_selection(p_selection)
_self.int!notify_gui_selection(p_selection)
_endif
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_private _method sw_tree_action.gui_selection << p_selection
.selection << p_selection
_self.int!notify_engine_selection(p_selection)
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_private _method sw_tree_action.int!notify_engine_selection(p_selection)
_local notifier << .properties[:select_notifier]
_if notifier _isnt _unset
_then
notifier.send_to(.engine, p_selection)
_endif
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_private _method sw_tree_action.int!notify_gui_selection(p_selection)
_if .control _isnt _unset
_then
.control.selection.select_clear()
_for i_tree _over p_selection.fast_elements()
_loop
.control.tree_manager[i_tree.key].selected? << _true
_endloop
_endif
_endmethod
$
_pragma(classify_level=basic, topic={graphics})
_method sw_tree_action.place_control_on(p_container, _gather p_properties)
## Creates a tree_item on P_CONTAINER with given
## properties.
## Note that properties :data_selector, :select_notifier,
## :toggle_notifier, :value_changed_notifier are not processed
## because they are coupled with the engine.
##
_local props << property_list.new_with(_scatter p_properties)
props.add_all(.properties)
props.remove_key(:data_selector)
props.remove_key(:select_notifier)
props.remove_key(:toggle_notifier)
props.remove_key(:value_changed_notifier)
_if p_container.swift_control?
_then
the_control << sw_tree.new(p_container,
:model, _self,
:value_changed_notifier, :|tree_value_changed()|,
:toggle_notifier, :|tree_toggled()|,
:select_notifier, :|trees_selected()|,
:data_selector, :|get_trees()|,
_scatter props)
_else
the_control << tree_item.new(p_container,
:model, _self,
:value_changed_notifier, :|tree_value_changed()|,
:toggle_notifier, :|tree_toggled()|,
:select_notifier, :|trees_selected()|,
:data_selector, :|get_trees()|,
_scatter props)
_endif
.control << the_control
_return the_control
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_method sw_tree_action.get_trees()
_return .data
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_method sw_tree_action.trees_selected(p_tree_selection, _gather p_data)
_local sel << rope.new()
_for i_tree _over p_tree_selection.fast_elements()
_loop
sel.add(i_tree)
_endloop
_self.gui_selection << sel
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_method sw_tree_action.tree_value_changed(p_tree, p_key, p_new_value, p_old_value, p_editor)
_local notifier << .properties[:value_changed_notifier]
_if notifier _isnt _unset
_then
notifier.send_to(.engine, p_tree, p_key, p_new_value, p_old_value, p_editor)
_endif
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_method sw_tree_action.tree_toggled(p_tree, p_row, p_event, p_key, _gather p_args)
_local old_value << p_tree.value(p_key)
_local new_value << _not old_value
p_tree.value(p_key) << new_value
_self.int!notify_engine_toggle(p_tree, p_key, new_value, old_value)
_return _true
_endmethod
$
_pragma(classify_level=basic, topic={graphics})
_method sw_tree_action.toggle(p_tree, p_key)
## Toggle the checkbox for P_KEY in the tree
#
_local old_value << p_tree.value(p_key)
_local new_value << _not old_value
_self.set_engine_toggle_value(p_tree, p_key, new_value, old_value)
_endmethod
$
_pragma(classify_level=basic, topic={graphics})
_method sw_tree_action.check(p_tree, p_key)
## Checks the checkbox for P_KEY in the tree.
#
_local old_value << p_tree.value(p_key)
_local new_value << _true
_self.set_engine_toggle_value(p_tree, p_key, new_value, old_value)
_endmethod
$
_pragma(classify_level=basic, topic={graphics})
_method sw_tree_action.uncheck(p_tree, p_key)
## Unchecks the checkbox for P_KEY in the tree
#
_local old_value << p_tree.value(p_key)
_local new_value << _false
_self.set_engine_toggle_value(p_tree, p_key, new_value, old_value)
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_private _method sw_tree_action.set_engine_toggle_value(p_tree, p_key, new_value, old_value)
_if new_value <> old_value
_then
p_tree.value(p_key) << new_value
_self.int!notify_gui_toggle()
_self.int!notify_engine_toggle(p_tree, p_key, new_value, old_value)
_endif
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_private _method sw_tree_action.int!notify_gui_toggle()
_if .control _isnt _unset
_then
.control.refresh()
_endif
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_private _method sw_tree_action.int!notify_engine_toggle(p_tree, p_key, new_value, old_value)
_local notifier << .properties[:toggle_notifier]
_if notifier _isnt _unset
_then
notifier.send_to(.engine, p_tree, p_key, new_value, old_value)
_endif
_endmethod
$
_pragma(classify_level=basic, topic={graphics})
_method sw_tree_action.set_value(p_tree, p_key, p_value)
## Set the value for P_KEY to _VALUE for the tree.
#
_local old_value << p_tree.value(p_key)
_if p_value <> old_value
_then
p_tree.value(p_key) << p_value
_self.int!notify_gui_set_value()
_self.int!notify_engine_set_value(p_tree, p_key, p_value, old_value)
_endif
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_private _method sw_tree_action.int!notify_engine_set_value(p_tree, p_key, p_new_value, p_old_value)
_local notifier << .properties[:value_changed_notifier]
_if notifier _isnt _unset
_then
notifier.send_to(.engine, p_tree, p_key, p_new_value, p_old_value, _unset)
_endif
_endmethod
$
_pragma(classify_level=restricted, topic={graphics})
_private _method sw_tree_action.int!notify_gui_set_value()
_if .control _isnt _unset
_then
.control.refresh()
_endif
_endmethod
$ |
import React from "react";
import { useAuth0 } from "@auth0/auth0-react";
import { Link } from "react-router-dom";
export const Navbar = () => {
const { loginWithRedirect, logout, isAuthenticated, user } = useAuth0();
return (
<div>
<nav className="navbar navbar-expand-sm navbar-light bg-light">
<div className="container">
<a className="navbar-brand" href="#">
SoftwareNoteHub
</a>
<button
className="navbar-toggler d-lg-none"
type="button"
data-bs-toggle="collapse"
data-bs-target="#collapsibleNavId"
aria-controls="collapsibleNavId"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="collapsibleNavId">
<ul className="navbar-nav ms-auto mt-2 mt-lg-0">
{isAuthenticated && (
<li className="nav-item">
<Link
className="nav-link btn mt-2 "
aria-current="page"
to={"/home"}
>
Home
</Link>
</li>
)}
{isAuthenticated && (
<li className="nav-item mt-2 me-3">
<Link className="btn" aria-current="page" to={"/cart"}>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
fill="currentColor"
className="bi bi-cart"
viewBox="0 0 16 16"
>
<path d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
</svg>
<span className="ms-2">Cart</span>
</Link>
</li>
)}
{!isAuthenticated ? (
<li className="nav-item">
<button
className="nav-link active btn btn-outline-primary text-white"
aria-current="page"
onClick={() => loginWithRedirect()}
>
Login
</button>
</li>
) : (
<li className="nav-item">
<button
className="nav-link btn btn-outline-danger "
aria-current="page"
onClick={() => logout()}
>
<img
src={user.picture}
height={35}
width={35}
className="rounded-5 me-2"
/>
Logout
</button>
</li>
)}
</ul>
</div>
</div>
</nav>
</div>
);
}; |
use std::sync::Arc;
use std::time::SystemTime;
use alacritty_terminal::index::Side;
use alacritty_terminal::selection::{Selection, SelectionType};
use alacritty_terminal::term::search::Match;
use alacritty_terminal::term::RenderableContent;
use alacritty_terminal::{
grid::Dimensions,
term::{cell::Flags, test::TermSize},
};
use floem::context::{EventCx, PaintCx};
use floem::event::Event;
use floem::peniko::Color;
use floem::pointer::PointerInputEvent;
use floem::views::editor::core::register::Clipboard;
use floem::views::editor::text::SystemClipboard;
use floem::{
cosmic_text::{Attrs, AttrsList, FamilyOwned, TextLayout, Weight},
id::Id,
peniko::kurbo::{Point, Rect, Size},
reactive::{create_effect, ReadSignal, RwSignal},
view::{AnyWidget, View, ViewData, Widget},
EventPropagation, Renderer,
};
use lapce_core::mode::Mode;
use lapce_rpc::{proxy::ProxyRpcHandler, terminal::TermId};
use lsp_types::Position;
use parking_lot::RwLock;
use unicode_width::UnicodeWidthChar;
use super::{panel::TerminalPanelData, raw::RawTerminal};
use crate::command::InternalCommand;
use crate::editor::location::{EditorLocation, EditorPosition};
use crate::listener::Listener;
use crate::workspace::LapceWorkspace;
use crate::{
config::{color::LapceColor, LapceConfig},
debug::RunDebugProcess,
panel::kind::PanelKind,
window_tab::Focus,
};
/// Threshold used for double_click/triple_click.
const CLICK_THRESHOLD: u128 = 400;
enum TerminalViewState {
Config,
Focus(bool),
Raw(Arc<RwLock<RawTerminal>>),
}
struct TerminalLineContent<'a> {
y: f64,
bg: Vec<(usize, usize, Color)>,
underline: Vec<(usize, usize, Color, f64)>,
chars: Vec<(char, Attrs<'a>, f64, f64)>,
cursor: Option<(char, f64)>,
}
pub struct TerminalView {
data: ViewData,
term_id: TermId,
raw: Arc<RwLock<RawTerminal>>,
mode: ReadSignal<Mode>,
size: Size,
is_focused: bool,
config: ReadSignal<Arc<LapceConfig>>,
run_config: ReadSignal<Option<RunDebugProcess>>,
proxy: ProxyRpcHandler,
launch_error: RwSignal<Option<String>>,
internal_command: Listener<InternalCommand>,
workspace: Arc<LapceWorkspace>,
hyper_matches: Vec<Match>,
previous_mouse_action: MouseAction,
current_mouse_action: MouseAction,
}
#[allow(clippy::too_many_arguments)]
pub fn terminal_view(
term_id: TermId,
raw: ReadSignal<Arc<RwLock<RawTerminal>>>,
mode: ReadSignal<Mode>,
run_config: ReadSignal<Option<RunDebugProcess>>,
terminal_panel_data: TerminalPanelData,
launch_error: RwSignal<Option<String>>,
internal_command: Listener<InternalCommand>,
workspace: Arc<LapceWorkspace>,
) -> TerminalView {
let id = Id::next();
create_effect(move |_| {
let raw = raw.get();
id.update_state(TerminalViewState::Raw(raw));
});
create_effect(move |_| {
launch_error.track();
id.request_paint();
});
let config = terminal_panel_data.common.config;
create_effect(move |_| {
config.with(|_c| {});
id.update_state(TerminalViewState::Config);
});
let proxy = terminal_panel_data.common.proxy.clone();
create_effect(move |last| {
let focus = terminal_panel_data.common.focus.get();
let mut is_focused = false;
if let Focus::Panel(PanelKind::Terminal) = focus {
let tab = terminal_panel_data.active_tab(true);
if let Some(tab) = tab {
let terminal = tab.active_terminal(true);
is_focused = terminal.map(|t| t.term_id) == Some(term_id);
}
}
if last != Some(is_focused) {
id.update_state(TerminalViewState::Focus(is_focused));
}
is_focused
});
TerminalView {
data: ViewData::new(id),
term_id,
raw: raw.get_untracked(),
mode,
config,
proxy,
run_config,
size: Size::ZERO,
is_focused: false,
launch_error,
internal_command,
workspace,
hyper_matches: vec![],
previous_mouse_action: Default::default(),
current_mouse_action: Default::default(),
}
}
impl TerminalView {
fn char_size(&self) -> Size {
let config = self.config.get_untracked();
let font_family = config.terminal_font_family();
let font_size = config.terminal_font_size();
let family: Vec<FamilyOwned> =
FamilyOwned::parse_list(font_family).collect();
let attrs = Attrs::new().family(&family).font_size(font_size as f32);
let attrs_list = AttrsList::new(attrs);
let mut text_layout = TextLayout::new();
text_layout.set_text("W", attrs_list);
text_layout.size()
}
fn terminal_size(&self) -> (usize, usize) {
let config = self.config.get_untracked();
let line_height = config.terminal_line_height() as f64;
let char_width = self.char_size().width;
let width = (self.size.width / char_width).floor() as usize;
let height = (self.size.height / line_height).floor() as usize;
(width.max(1), height.max(1))
}
fn click(&self, pos: Point) -> Option<()> {
let raw_origin = self.raw.read();
let position = self.get_terminal_point(pos);
let hy = self.hyper_matches.iter().find(|x| x.contains(&position))?;
let hyperlink = raw_origin.term.bounds_to_string(*hy.start(), *hy.end());
let content: Vec<&str> = hyperlink.split(':').collect();
let (file, line_str, col_str) =
(content.first()?, content.get(1)?, content.get(2)?);
let (line, col) =
(line_str.parse::<u32>().ok()?, col_str.parse::<u32>().ok()?);
let parent_path = self.workspace.path.as_ref()?;
self.internal_command.send(InternalCommand::JumpToLocation {
location: EditorLocation {
path: parent_path.join(file),
position: Some(EditorPosition::Position(Position::new(line, col))),
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
},
});
None
}
fn update_mouse_action_by_down(&mut self, mouse: PointerInputEvent) {
let mut next_action = MouseAction::None;
match self.current_mouse_action {
MouseAction::None
| MouseAction::LeftDouble { .. }
| MouseAction::LeftSelect { .. }
| MouseAction::RightOnce { .. } => {
if mouse.button.is_primary() {
next_action = MouseAction::LeftDown { pos: mouse.pos };
} else if mouse.button.is_secondary() {
next_action = MouseAction::RightDown { pos: mouse.pos };
}
}
MouseAction::LeftOnce { pos, time } => {
let during_mills =
time.elapsed().map(|x| x.as_millis()).unwrap_or(u128::MAX);
match (
mouse.button.is_primary(),
mouse.pos == pos,
during_mills < CLICK_THRESHOLD,
) {
(true, true, true) => {
next_action = MouseAction::LeftOnceAndDown { pos, time };
}
(true, _, _) => {
next_action = MouseAction::LeftDown { pos: mouse.pos };
}
_ => {}
}
}
MouseAction::LeftOnceAndDown { .. }
| MouseAction::LeftDown { .. }
| MouseAction::RightDown { .. } => {}
}
self.current_mouse_action = next_action;
}
fn update_mouse_action_by_up(&mut self, mouse: PointerInputEvent) {
let mut next_action = MouseAction::None;
match self.current_mouse_action {
MouseAction::None => {}
MouseAction::LeftDown { pos } => {
match (mouse.button.is_primary(), mouse.pos == pos) {
(true, true) => {
next_action = MouseAction::LeftOnce {
pos,
time: SystemTime::now(),
}
}
(true, false) => {
next_action = MouseAction::LeftSelect {
start_pos: pos,
end_pos: mouse.pos,
};
}
_ => {}
}
}
MouseAction::LeftOnce { .. } => {}
MouseAction::LeftSelect { .. } => {}
MouseAction::LeftOnceAndDown { pos, time } => {
let during_mills =
time.elapsed().map(|x| x.as_millis()).unwrap_or(u128::MAX);
match (
mouse.button.is_primary(),
mouse.pos == pos,
during_mills < CLICK_THRESHOLD,
) {
(true, true, true) => {
next_action = MouseAction::LeftDouble { pos };
}
(true, true, false) => {
next_action = MouseAction::LeftOnce {
pos: mouse.pos,
time: SystemTime::now(),
};
}
(true, false, _) => {
next_action = MouseAction::LeftSelect {
start_pos: pos,
end_pos: mouse.pos,
};
}
_ => {}
}
}
MouseAction::LeftDouble { .. } => {}
MouseAction::RightDown { pos } => {
if mouse.button.is_secondary() && mouse.pos == pos {
next_action = MouseAction::RightOnce { pos };
}
}
MouseAction::RightOnce { .. } => {}
}
self.previous_mouse_action = self.current_mouse_action;
self.current_mouse_action = next_action;
}
fn get_terminal_point(&self, pos: Point) -> alacritty_terminal::index::Point {
let col = (pos.x / self.char_size().width) as usize;
let line_no =
pos.y as i32 / (self.config.get().terminal_line_height() as i32);
alacritty_terminal::index::Point::new(
alacritty_terminal::index::Line(line_no),
alacritty_terminal::index::Column(col),
)
}
fn paint_content(
&self,
cx: &mut PaintCx,
content: RenderableContent,
line_height: f64,
char_size: Size,
config: &LapceConfig,
) {
let term_bg = config.color(LapceColor::TERMINAL_BACKGROUND);
let term_fg = config.color(LapceColor::TERMINAL_FOREGROUND);
let font_size = config.terminal_font_size();
let font_family = config.terminal_font_family();
let family: Vec<FamilyOwned> =
FamilyOwned::parse_list(font_family).collect();
let attrs = Attrs::new().family(&family).font_size(font_size as f32);
let char_width = char_size.width;
let cursor_point = &content.cursor.point;
let mut line_content = TerminalLineContent {
y: 0.0,
bg: Vec::new(),
underline: Vec::new(),
chars: Vec::new(),
cursor: None,
};
for item in content.display_iter {
let point = item.point;
let cell = item.cell;
let inverse = cell.flags.contains(Flags::INVERSE);
let x = point.column.0 as f64 * char_width;
let y =
(point.line.0 as f64 + content.display_offset as f64) * line_height;
let char_y = y + (line_height - char_size.height) / 2.0;
let underline_y = (point.line.0 as f64 + content.display_offset as f64)
* line_height
+ line_height;
if y != line_content.y {
self.paint_line_content(
cx,
&line_content,
line_height,
char_width,
config,
);
line_content.y = y;
line_content.bg.clear();
line_content.underline.clear();
line_content.chars.clear();
line_content.cursor = None;
}
let mut bg = config.terminal_get_color(&cell.bg, content.colors);
let mut fg = config.terminal_get_color(&cell.fg, content.colors);
if cell.flags.contains(Flags::DIM)
|| cell.flags.contains(Flags::DIM_BOLD)
{
fg = fg.with_alpha_factor(0.66);
}
if inverse {
std::mem::swap(&mut fg, &mut bg);
}
if term_bg != bg {
let mut extend = false;
if let Some((_, end, color)) = line_content.bg.last_mut() {
if color == &bg && *end == point.column.0 {
*end += 1;
extend = true;
}
}
if !extend {
line_content
.bg
.push((point.column.0, point.column.0 + 1, bg));
}
}
if self.hyper_matches.iter().any(|x| x.contains(&point)) {
let mut extend = false;
if let Some((_, end, _, _)) = line_content.underline.last_mut() {
if *end == point.column.0 {
*end += 1;
extend = true;
}
}
if !extend {
line_content.underline.push((
point.column.0,
point.column.0 + 1,
term_fg,
underline_y,
));
}
}
if cursor_point == &point {
line_content.cursor = Some((cell.c, x));
}
let bold = cell.flags.contains(Flags::BOLD)
|| cell.flags.contains(Flags::DIM_BOLD);
if &point == cursor_point && self.is_focused {
fg = term_bg;
}
if cell.c != ' ' && cell.c != '\t' {
let mut attrs = attrs.color(fg);
if bold {
attrs = attrs.weight(Weight::BOLD);
}
line_content.chars.push((cell.c, attrs, x, char_y));
}
}
self.paint_line_content(cx, &line_content, line_height, char_width, config);
}
fn paint_line_content(
&self,
cx: &mut PaintCx,
line_content: &TerminalLineContent,
line_height: f64,
char_width: f64,
config: &LapceConfig,
) {
for (start, end, bg) in &line_content.bg {
let rect = Size::new(
char_width * (end.saturating_sub(*start) as f64),
line_height,
)
.to_rect()
.with_origin(Point::new(*start as f64 * char_width, line_content.y));
cx.fill(&rect, bg, 0.0);
}
for (start, end, fg, y) in &line_content.underline {
let rect =
Size::new(char_width * (end.saturating_sub(*start) as f64), 1.0)
.to_rect()
.with_origin(Point::new(*start as f64 * char_width, y - 1.0));
cx.fill(&rect, fg, 0.0);
}
if let Some((c, x)) = line_content.cursor {
let rect =
Size::new(char_width * c.width().unwrap_or(1) as f64, line_height)
.to_rect()
.with_origin(Point::new(x, line_content.y));
let mode = self.mode.get_untracked();
let cursor_color = if mode == Mode::Terminal {
if self.run_config.with_untracked(|run_config| {
run_config.as_ref().map(|r| r.stopped).unwrap_or(false)
}) {
config.color(LapceColor::LAPCE_ERROR)
} else {
config.color(LapceColor::TERMINAL_CURSOR)
}
} else {
config.color(LapceColor::EDITOR_CARET)
};
if self.is_focused {
cx.fill(&rect, cursor_color, 0.0);
} else {
cx.stroke(&rect, cursor_color, 1.0);
}
}
for (char, attr, x, y) in &line_content.chars {
let mut text_layout = TextLayout::new();
text_layout.set_text(&char.to_string(), AttrsList::new(*attr));
cx.draw_text(&text_layout, Point::new(*x, *y));
}
}
}
impl Drop for TerminalView {
fn drop(&mut self) {
self.proxy.terminal_close(self.term_id);
}
}
impl View for TerminalView {
fn view_data(&self) -> &ViewData {
&self.data
}
fn view_data_mut(&mut self) -> &mut ViewData {
&mut self.data
}
fn build(self) -> AnyWidget {
Box::new(self)
}
}
impl Widget for TerminalView {
fn view_data(&self) -> &ViewData {
&self.data
}
fn view_data_mut(&mut self) -> &mut ViewData {
&mut self.data
}
fn event(
&mut self,
_cx: &mut EventCx,
_id_path: Option<&[Id]>,
event: Event,
) -> EventPropagation {
match event {
Event::PointerDown(e) => {
self.update_mouse_action_by_down(e);
}
Event::PointerUp(e) => {
self.update_mouse_action_by_up(e);
let mut clear_selection = false;
match self.current_mouse_action {
MouseAction::LeftOnce { pos, .. } => {
clear_selection = true;
if self.click(pos).is_some() {
return EventPropagation::Stop;
}
}
MouseAction::LeftSelect { start_pos, end_pos } => {
let mut selection = Selection::new(
SelectionType::Simple,
self.get_terminal_point(start_pos),
Side::Left,
);
selection
.update(self.get_terminal_point(end_pos), Side::Right);
selection.include_all();
self.raw.write().term.selection = Some(selection);
_cx.app_state_mut().request_paint(self.data.id());
}
MouseAction::LeftDouble { pos } => {
let position = self.get_terminal_point(pos);
let mut raw = self.raw.write();
let start_point = raw.term.semantic_search_left(position);
let end_point = raw.term.semantic_search_right(position);
let mut selection = Selection::new(
SelectionType::Simple,
start_point,
Side::Left,
);
selection.update(end_point, Side::Right);
selection.include_all();
raw.term.selection = Some(selection);
_cx.app_state_mut().request_paint(self.data.id());
}
MouseAction::RightOnce { pos } => {
let position = self.get_terminal_point(pos);
let raw = self.raw.read();
if let Some(selection) = &raw
.term
.selection
.as_ref()
.and_then(|x| x.to_range(&raw.term))
{
if selection.contains(position) {
let mut clipboard = SystemClipboard::new();
let content = raw.term.bounds_to_string(
selection.start,
selection.end,
);
if !content.is_empty() {
clipboard.put_string(content);
}
}
clear_selection = true;
}
}
_ => {
clear_selection = true;
}
}
if clear_selection {
self.raw.write().term.selection = None;
_cx.app_state_mut().request_paint(self.data.id());
}
}
_ => {}
}
EventPropagation::Continue
}
fn update(
&mut self,
cx: &mut floem::context::UpdateCx,
state: Box<dyn std::any::Any>,
) {
if let Ok(state) = state.downcast() {
match *state {
TerminalViewState::Config => {}
TerminalViewState::Focus(is_focused) => {
self.is_focused = is_focused;
}
TerminalViewState::Raw(raw) => {
self.raw = raw;
}
}
cx.app_state_mut().request_paint(self.data.id());
}
}
fn layout(
&mut self,
cx: &mut floem::context::LayoutCx,
) -> floem::taffy::prelude::NodeId {
cx.layout_node(self.data.id(), false, |_cx| Vec::new())
}
fn compute_layout(
&mut self,
cx: &mut floem::context::ComputeLayoutCx,
) -> Option<Rect> {
let layout = cx.get_layout(self.data.id()).unwrap();
let size = layout.size;
let size = Size::new(size.width as f64, size.height as f64);
if size.is_empty() {
return None;
}
if size != self.size {
self.size = size;
let (width, height) = self.terminal_size();
let term_size = TermSize::new(width, height);
self.raw.write().term.resize(term_size);
self.proxy.terminal_resize(self.term_id, width, height);
}
None
}
fn paint(&mut self, cx: &mut floem::context::PaintCx) {
let config = self.config.get_untracked();
let mode = self.mode.get_untracked();
let line_height = config.terminal_line_height() as f64;
let font_family = config.terminal_font_family();
let font_size = config.terminal_font_size();
let char_size = self.char_size();
let char_width = char_size.width;
let family: Vec<FamilyOwned> =
FamilyOwned::parse_list(font_family).collect();
let attrs = Attrs::new().family(&family).font_size(font_size as f32);
if let Some(error) = self.launch_error.get() {
let mut text_layout = TextLayout::new();
text_layout.set_text(
&format!("Terminal failed to launch. Error: {error}"),
AttrsList::new(
attrs.color(config.color(LapceColor::EDITOR_FOREGROUND)),
),
);
cx.draw_text(
&text_layout,
Point::new(6.0, 0.0 + (line_height - char_size.height) / 2.0),
);
return;
}
let raw = self.raw.read();
let term = &raw.term;
let content = term.renderable_content();
// let mut search = RegexSearch::new("[\\w\\\\?]+\\.rs:\\d+:\\d+").unwrap();
// self.hyper_matches = visible_regex_match_iter(term, &mut search).collect();
if let Some(selection) = content.selection.as_ref() {
let start_line = selection.start.line.0 + content.display_offset as i32;
let start_line = if start_line < 0 {
0
} else {
start_line as usize
};
let start_col = selection.start.column.0;
let end_line = selection.end.line.0 + content.display_offset as i32;
let end_line = if end_line < 0 { 0 } else { end_line as usize };
let end_col = selection.end.column.0;
for line in start_line..end_line + 1 {
let left_col = if selection.is_block || line == start_line {
start_col
} else {
0
};
let right_col = if selection.is_block || line == end_line {
end_col + 1
} else {
term.last_column().0
};
let x0 = left_col as f64 * char_width;
let x1 = right_col as f64 * char_width;
let y0 = line as f64 * line_height;
let y1 = y0 + line_height;
cx.fill(
&Rect::new(x0, y0, x1, y1),
config.color(LapceColor::EDITOR_SELECTION),
0.0,
);
}
} else if mode != Mode::Terminal {
let y = (content.cursor.point.line.0 as f64
+ content.display_offset as f64)
* line_height;
cx.fill(
&Rect::new(0.0, y, self.size.width, y + line_height),
config.color(LapceColor::EDITOR_CURRENT_LINE),
0.0,
);
}
self.paint_content(cx, content, line_height, char_size, &config);
// if data.find.visual {
// if let Some(search_string) = data.find.search_string.as_ref() {
// if let Ok(dfas) = RegexSearch::new(®ex::escape(search_string)) {
// let mut start = alacritty_terminal::index::Point::new(
// alacritty_terminal::index::Line(
// -(content.display_offset as i32),
// ),
// alacritty_terminal::index::Column(0),
// );
// let end_line = (start.line + term.screen_lines())
// .min(term.bottommost_line());
// let mut max_lines = (end_line.0 - start.line.0) as usize;
// while let Some(m) = term.search_next(
// &dfas,
// start,
// Direction::Right,
// Side::Left,
// Some(max_lines),
// ) {
// let match_start = m.start();
// if match_start.line.0 < start.line.0
// || (match_start.line.0 == start.line.0
// && match_start.column.0 < start.column.0)
// {
// break;
// }
// let x = match_start.column.0 as f64 * char_width;
// let y = (match_start.line.0 as f64
// + content.display_offset as f64)
// * line_height;
// let rect = Rect::ZERO
// .with_origin(Point::new(x, y))
// .with_size(Size::new(
// (m.end().column.0 - m.start().column.0
// + term.grid()[*m.end()].c.width().unwrap_or(1))
// as f64
// * char_width,
// line_height,
// ));
// cx.stroke(
// &rect,
// config.get_color(LapceColor::TERMINAL_FOREGROUND),
// 1.0,
// );
// start = *m.end();
// if start.column.0 < term.last_column() {
// start.column.0 += 1;
// } else if start.line.0 < term.bottommost_line() {
// start.column.0 = 0;
// start.line.0 += 1;
// }
// max_lines = (end_line.0 - start.line.0) as usize;
// }
// }
// }
// }
}
}
#[derive(Debug, Default, Copy, Clone)]
enum MouseAction {
#[default]
None,
LeftDown {
pos: Point,
},
LeftOnce {
pos: Point,
time: SystemTime,
},
LeftSelect {
start_pos: Point,
end_pos: Point,
},
LeftOnceAndDown {
pos: Point,
time: SystemTime,
},
LeftDouble {
pos: Point,
},
RightDown {
pos: Point,
},
RightOnce {
pos: Point,
},
} |
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Authentication from "./Pages/Authentication/Authentication";
import Dashboard from "./Pages/Dashboard/Dashboard";
import Administration from "./Pages/Dashboard/sub-components/Administration";
import AdminList from "./Pages/Dashboard/sub-components/AdminList";
import Configuration from "./Pages/Dashboard/sub-components/Configuration";
import Monitoring from "./Pages/Dashboard/sub-components/Monitoring";
import RegisterAdmin from "./Pages/Dashboard/sub-components/RegisterAdmin";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import ThemeState from "./context/theme/ThemeState";
import UsersColumnState from "./context/users/UsersColumnState";
import Analytics from "./Pages/Dashboard/sub-components/Analytics";
import Summary from "./Pages/Dashboard/sub-components/Summary";
import Logs from "./Pages/Dashboard/sub-components/Logs";
import DataQueryState from "./context/dataQuery/DataQueryState";
function App() {
return (
<>
<UsersColumnState>
<ThemeState>
<DataQueryState>
<BrowserRouter>
<Routes>
<Route path="/" element={<Authentication />} />
<Route path="dashboard/*" element={<Dashboard />}>
<Route path="monitoring/*" element={<Monitoring />}>
<Route path="analytics/*" element={<Analytics />} />
<Route path="summary/*" element={<Summary />} />
<Route path="logs/*" element={<Logs />} />
</Route>
<Route path="configuration/*" element={<Configuration />} />
<Route path="administration/*" element={<Administration />}>
<Route path="adminList/*" element={<AdminList />} />
<Route path="register/*" element={<RegisterAdmin />} />
</Route>
</Route>
</Routes>
</BrowserRouter>
<ToastContainer autoClose={2000} className="p-4 md:p-0" />
</DataQueryState>
</ThemeState>
</UsersColumnState>
</>
);
}
export default App; |
title:: Event Stream
categories:: Streams-Patterns-Events
related:: Classes/Stream, Classes/Event
summary:: A Stream that returns Events when called
An event stream is a normal link::Classes/Stream:: that returns events when called. (see class link::Classes/Event::). Usually, an event stream requires an event to be passed in, often the default event is used:
code::
t = Pbind(\x, Pseq([1, 2, 3])).asStream; // Pbind, e.g. creates a stream
t.next(Event.default);
t.next(Event.default);
::
An event stream cannot be played directly with a clock, as it returns events and not time values. Therefore, an link::Classes/EventStreamPlayer:: is used, which replaces the event by according time value.
A link::Classes/Pevent:: can be used to wrap a stream in an event:
code::
t = Pevent(Pbind(\x, Pseq([1,2,3])), Event.default).asStream;
t.next;
t.next;
:: |
package com.lvchuan.export;
import com.alibaba.excel.write.handler.WriteHandler;
import com.lvchuan.common.page.PageRequest;
import java.util.LinkedHashMap;
import java.util.List;
/**
* @description: 动态导出服务接口
* @author: lvchuan
* @createTime: 2023-12-06 10:56
*/
public interface IDynamicExportHandler<T> {
/**
* 导出业务类型
* @return 业务类型
*/
ExportTemplateBizTypeEnum bizType();
/**
* 文件名称, 不加后缀
* @param param 传入的请求参数
* @return 返回文件名称
*/
default String fileName(T param) {
return null;
};
/**
* sheet 名称
* @param param 传入的请求参数
* @return 返回sheet 名称
*/
default String sheetName(T param) {
return null;
}
/**
* 头部class文件
*
* @param param 传入的请求参数
* @return 返回头设置
*/
default Class headClass(T param) {
return null;
}
/**
* 动态文件头
*
* @param param 传入的请求参数 <字段名称, 表头显示的名称>
* @return 文件头list
*/
default LinkedHashMap<String, String> headMap(T param) {
return null;
}
/**
* 自定义处理器列表,依次加载
*
* @param param 传入的请求参数
* @return 自定义处理器列表
*/
default List<WriteHandler> writeHandlerList(T param) {
return null;
}
/**
* 查询数据
*
* @param param 传入的请求参数
* @param pageRequest 分页信息
* @return 查询出来的业务数据
*/
List queryData(T param, PageRequest pageRequest);
} |
import {
isElemNode,
findNodes,
removeNode,
unwrapNode,
insertBeforeNode,
appendNodes,
} from '@/utils/dom';
const reMSOListClassName = /MsoListParagraph/;
const reMSOStylePrefix = /style=(.|\n)*mso-/;
const reMSOListStyle = /mso-list:(.*)/;
const reMSOTagName = /O:P/;
const reMSOListBullet = /^(n|u|l)/;
const MSO_CLASS_NAME_LIST_PARA = 'p.MsoListParagraph';
interface ListItemData {
id: number;
level: number;
prev: ListItemData | null;
parent: ListItemData | null;
children: ListItemData[];
unordered: boolean;
contents: string;
}
export function isFromMso(html: string) {
return reMSOStylePrefix.test(html);
}
function getListItemContents(para: HTMLElement) {
const removedNodes = [];
const walker = document.createTreeWalker(para, 1, null, false);
while (walker.nextNode()) {
const node = walker.currentNode;
if (isElemNode(node)) {
const { outerHTML, textContent } = node as HTMLElement;
const msoSpan = reMSOStylePrefix.test(outerHTML);
const bulletSpan = reMSOListStyle.test(outerHTML);
if (msoSpan && !bulletSpan && textContent) {
removedNodes.push([node, true]);
} else if (reMSOTagName.test(node.nodeName) || (msoSpan && !textContent) || bulletSpan) {
removedNodes.push([node, false]);
}
}
}
removedNodes.forEach(([node, isUnwrap]) => {
if (isUnwrap) {
unwrapNode(node as HTMLElement);
} else {
removeNode(node as HTMLElement);
}
});
return para.innerHTML.trim();
}
function createListItemDataFromParagraph(para: HTMLElement, index: number) {
const styleAttr = para.getAttribute('style');
if (styleAttr) {
const [, listItemInfo] = styleAttr.match(reMSOListStyle)!;
const [, levelStr] = listItemInfo.trim().split(' ');
const level = parseInt(levelStr.replace('level', ''), 10);
const unordered = reMSOListBullet.test(para.textContent || '');
return {
id: index,
level,
prev: null,
parent: null,
children: [],
unordered,
contents: getListItemContents(para),
};
}
return null;
}
function addListItemDetailData(data: ListItemData, prevData: ListItemData) {
if (prevData.level < data.level) {
prevData.children.push(data);
data.parent = prevData;
} else {
while (prevData) {
if (prevData.level === data.level) {
break;
}
prevData = prevData.parent!;
}
if (prevData) {
data.prev = prevData;
data.parent = prevData.parent;
if (data.parent) {
data.parent.children.push(data);
}
}
}
}
function createListData(paras: HTMLElement[]) {
const listData: ListItemData[] = [];
paras.forEach((para, index) => {
const prevListItemData = listData[index - 1];
const listItemData = createListItemDataFromParagraph(para, index);
if (listItemData) {
if (prevListItemData) {
addListItemDetailData(listItemData, prevListItemData);
}
listData.push(listItemData);
}
});
return listData;
}
function makeList(listData: ListItemData[]) {
const listTagName = listData[0].unordered ? 'ul' : 'ol';
const list = document.createElement(listTagName);
listData.forEach((data) => {
const { children, contents } = data;
const listItem = document.createElement('li');
listItem.innerHTML = contents;
list.appendChild(listItem);
if (children.length) {
list.appendChild(makeList(children));
}
});
return list;
}
function makeListFromParagraphs(paras: HTMLElement[]) {
const listData = createListData(paras);
const rootChildren = listData.filter(({ parent }) => !parent);
return makeList(rootChildren);
}
function isMsoListParagraphEnd(node: HTMLElement) {
while (node) {
if (isElemNode(node)) {
break;
}
node = node.nextSibling as HTMLElement;
}
return node ? !reMSOListClassName.test(node.className) : true;
}
export function convertMsoParagraphsToList(html: string) {
const container = document.createElement('div') as HTMLElement;
container.innerHTML = html;
let paras: HTMLElement[] = [];
const foundParas = findNodes(container, MSO_CLASS_NAME_LIST_PARA);
foundParas.forEach((para) => {
const msoListParaEnd = isMsoListParagraphEnd(para.nextSibling as HTMLElement);
paras.push(para as HTMLElement);
if (msoListParaEnd) {
const list = makeListFromParagraphs(paras);
const { nextSibling } = para;
if (nextSibling) {
insertBeforeNode(list, nextSibling);
} else {
appendNodes(container, list);
}
paras = [];
}
removeNode(para);
});
// without `<p></p>`, the list string was parsed as a paragraph node and added
const extraHTML = foundParas.length ? '<p></p>' : '';
return `${extraHTML}${container.innerHTML}`;
} |
module Day22 (day22) where
import Common
import PathFinding
import Control.Monad.State
import Data.HashMap.Strict qualified as M
import Text.Parsec qualified as P
day22 :: AOCSolution
day22 input = show <$> ([part1, part2] <*> pure (target, g))
where
(depth, target) = parseInput input
g = buildGraph depth target
parseInput :: String -> (Int, Point2d)
parseInput = parse' p id
where
p = do
d <- P.string "depth: " *> number
P.newline
x <- P.string "target: " *> number
y <- P.char ',' *> number
pure (d, (x, y))
modV :: Int -> Int
modV = (`mod` 20183)
part1 :: (Point2d, M.HashMap Point2d Int) -> Int
part1 ((x, y), g) = sum . M.elems . M.filterWithKey (\k _ -> fst k <= x && snd k <= y) $ g
part2 :: (Point2d, M.HashMap Point2d Int) -> Int
part2 (target, g) = fst $ last $ unsafeFindPathWith move (manhattanDistance target . fst) ((0, 0), 1) (target, 1)
where
move :: (Point2d, Int) -> [(Int, (Point2d, Int))]
move (p, e) = (7, (p, e')) : n
where
n = map ((1,) . (,e)) $ filter valid $ point2dNeighbours p
valid p' = (p' `M.member` g) && (e /= g M.! p')
e' = case g M.! p of
0 -> if e == 1 then 2 else 1
1 -> if e == 0 then 2 else 0
2 -> if e == 0 then 1 else 0
buildGraph :: Int -> Point2d -> M.HashMap Point2d Int
buildGraph depth target = M.map ((`mod` 3) . el) gi
where
lines = concat $ getLines target
el = modV . (+depth)
gi = M.insert target 0 $ execState (geologicIndex el lines) M.empty
getLines :: Point2d -> [[Point2d]]
getLines (mx, my) = map points [0..mx + my]
where
points n = [(i, n - i) | i <- [0..n]]
geologicIndex :: (Int -> Int) -> [Point2d] -> State (M.HashMap Point2d Int) ()
geologicIndex el [p] = modify (M.insert p 0)
geologicIndex el (p@(x, y):ps) = do
g <- get
let v | p == (0, 0) = 0
| x == 0 = modV (y * 48271)
| y == 0 = modV (x * 16807)
| otherwise = modV (el (g M.! (x-1, y)) * el (g M.! (x, y-1)))
modify (M.insert p v)
geologicIndex el ps
debug :: M.HashMap Point2d Int -> String
debug = point2dGridToString ' ' [[0, 0], [10, 10]]. M.map f
where
f 0 = '.'
f 1 = '='
f 2 = '|' |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sarang_app/src/app.dart';
import 'package:sarang_app/src/features/authentication/presentation/bloc/auth_bloc.dart';
import 'package:sarang_app/src/features/likes_you/presentation/bloc/explore_people/explore_people_bloc.dart';
import 'package:sarang_app/src/features/likes_you/presentation/bloc/people_loved/people_loved_bloc.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => AuthBloc(),
),
BlocProvider(
create: (context) => ExplorePeopleBloc(),
),
BlocProvider(
create: (context) => PeopleLovedBloc(),
)
],
child: const AppScreen(),
);
}
} |
package com.example.sensorsproject
import android.annotation.SuppressLint
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.Spinner
import android.widget.TextView
class MainActivity : AppCompatActivity() {
private lateinit var sensorEventListener: SensorEventListener
private lateinit var TempSensorEventListener: SensorEventListener
private lateinit var sensorManager: SensorManager
private var humiditySensor: Sensor? = null
private var temperatureSensor: Sensor? = null
private lateinit var breadPick: String
private val humList: List<Int> = arrayListOf(60, 80)
private var optimalTempL: Int = 0
private var optimalTempM: Int = 0
var tempVal: Double = 0.0
var humVal: Float = 0.0F
lateinit var resultText: TextView
lateinit var resultBox: TextView
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
resultText = findViewById(R.id.resultText)
resultBox = findViewById(R.id.textView2)
val spinner: Spinner = findViewById(R.id.typeSpinner)
sensorManager = getSystemService(SensorManager::class.java)
humiditySensor = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY) //set up manager to accept humidity
temperatureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) //set up manager to accept temperature
//Sensor Pipeline: Data Extraction and Preprocessing for Humidity
sensorEventListener = object : SensorEventListener { //event listener listens for when the sensor value changes
//Sensor Pipeline: preprocessing ->
//an event containing all data from the humidity sensor is created every time that the sensor changes
override fun onSensorChanged(event: SensorEvent?) {
//Sensor Pipeline: Data Classification, collecting the needed value from the sensor event, values[0]
humVal = event!!.values[0]
var messageH = "$humVal%" //refining the sensor data rep to show it is a percentage
findViewById<TextView>(R.id.hum_value).text = messageH
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
}
//Sensor Pipeline: Data Extraction and Preprocessing for Temperature
TempSensorEventListener = object : SensorEventListener { //event listener listens for when the sensor value changes
//Sensor Pipeline: preprocessing ->
//an event containing all data from the humidity sensor is created every time that the sensor changes
override fun onSensorChanged(event: SensorEvent?) {
//Sensor Pipeline: Data Classification, collecting the needed value from the sensor event, values[0]
tempVal = (event!!.values[0] * 1.8) + 32 // refining the sensor data to change it from Celsius to Fahrenheit
val intTemp = tempVal.toInt()
var messageT = "$intTemp Fahrenheit" //refining the sensor data rep to show it is fahrenheit
findViewById<TextView>(R.id.temp_value).text = messageT
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
}
ArrayAdapter.createFromResource(
this,
R.array.breads,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears.
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner.
spinner.adapter = adapter
}
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
parent?.run {
breadPick = getItemAtPosition(position).toString()
resultText.text = ""
resultBox.text = " Result: "
resultBox.setBackgroundColor(Color.parseColor("#82B1FF")) //light blue
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
/* while the sensor data is collected and displayed on the activity constantly,
it is only checked for a "result" when the test button is hit.
this process requires the current sensor data to once again be collected */
findViewById<Button>(R.id.testButton).setOnClickListener {
result(
handlePick(breadPick),
tempVal,
humVal
)
}
//implemented a "help" button to show the user the target ranges in case they are struggling to find a good spot
//the help button displays a pop up widnow with a chart of all target temperatures
findViewById<ImageButton>(R.id.helpButton).setOnClickListener {
// inflate the layout of the popup window
val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater
val popupView: View = inflater.inflate(R.layout.popup_window, null)
// create the popup window
val width = LinearLayout.LayoutParams.WRAP_CONTENT
val height = LinearLayout.LayoutParams.WRAP_CONTENT
val focusable = true // lets taps outside the popup also dismiss it
val popupWindow = PopupWindow(popupView, width, height, focusable)
// show the popup window
// which view you pass in doesn't matter, it is only used for the window tolken
popupWindow.showAtLocation(it, Gravity.CENTER, 0, 0)
// dismiss the popup window when touched
popupView.setOnTouchListener { v, event ->
popupWindow.dismiss()
true
}
}
}
//Sensor Pipeline: Data extraction set up is registered when resumed
override fun onResume() {
super.onResume()
sensorManager.registerListener(
sensorEventListener,
humiditySensor,
SensorManager.SENSOR_DELAY_NORMAL
)
sensorManager.registerListener(
TempSensorEventListener,
temperatureSensor,
SensorManager.SENSOR_DELAY_NORMAL
)
}
//Sensor Pipeline: Data extraction is unregistered when resumed
override fun onPause() {
super.onPause()
sensorManager.unregisterListener(sensorEventListener)
sensorManager.unregisterListener(TempSensorEventListener)
}
//Handle pick returns the optimal range for the currently selected bread type
fun handlePick(breadPick: String): List<Int> {
when (breadPick) {
"Sourdough" -> {
optimalTempL = 70
optimalTempM = 85
Log.d("Type", "Sourdough")
}
"Rye Dough" -> {
optimalTempL = 80
optimalTempM = 85
Log.d("Type", "Rye Dough")
}
"Sweet Dough / Croissant" -> {
optimalTempL = 75
optimalTempM = 80
Log.d("Type", "Sweet Dough / Croissant")
}
"Lean Dough" -> {
optimalTempL = 75
optimalTempM = 78
Log.d("Type", "Lean Dough")
}
"Pre-ferments" -> {
optimalTempL = 70
optimalTempM = 72
Log.d("Type", "Pre-ferments")
}
"Other" -> {
optimalTempL = 81
optimalTempM = 81
Log.d("Type", "Other")
}
}
return arrayListOf(optimalTempL, optimalTempM)
}
//result changes the result box on the app to show how the data lines up
//it compares the humidity and temperature collected data to the stored optimal range from handlepick
//both sensor data recordings are considered together in order to ensure that both are accounted for in the classification process
//the result box message and color changes according to the sensor conditions when the test button is hit
fun result(tempList: List<Int>, tempVal: Double, humVal: Float){
var humResult = 0
var tempResult = 0
if (breadPick == "Choose your bread type"){
resultText.text = "Please choose a bread type"
resultText.setTextColor(Color.GRAY)
return
}
if(humList[0]<humVal && humVal<humList[1]) humResult = 1
if(tempVal.toInt() in tempList[0]..tempList[1]) tempResult = 1 // in range
else if(tempVal.toInt() in tempList[0]-2..tempList[1]+2) tempResult = 2 //slightly outside range
if(humResult == 1 && tempResult == 1) {
findViewById<TextView>(R.id.textView2).text = " Result: \n Perfect "
findViewById<TextView>(R.id.textView2).setBackgroundColor(Color.parseColor("#CCFF90")) //green
}
if(humResult == 1 && tempResult == 2) {
findViewById<TextView>(R.id.textView2).text = " Result: \n Okay "
findViewById<TextView>(R.id.textView2).setBackgroundColor(Color.parseColor("#FFD180")) //orange
}
if(humResult == 0 && tempResult in 1..2){
findViewById<TextView>(R.id.textView2).text = "Result: \n Find a Better Humidity "
findViewById<TextView>(R.id.textView2).setBackgroundColor(Color.parseColor("#FF9E80")) //red
}
if(humResult == 1 && tempResult == 0){
findViewById<TextView>(R.id.textView2).text = "Result: \n Find a Better Temperature "
findViewById<TextView>(R.id.textView2).setBackgroundColor(Color.parseColor("#FF9E80")) //red
}
if(humResult == 0 && tempResult == 0){
findViewById<TextView>(R.id.textView2).text = "Result: \n Humidity and Temperature both not ideal "
findViewById<TextView>(R.id.textView2).setBackgroundColor(Color.parseColor("#FF9E80")) //red
}
}
}
//the light blue: #82B1FF"
//the red: #FF9E80
// the green: #CCFF90
//the orange: #FFD180 |
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mobx/mobx.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:url_launcher/url_launcher.dart';
part 'register_text_screen.g.dart';
class RegisterTextScreen extends StatelessWidget {
final TextRegisterStore store = TextRegisterStore();
RegisterTextScreen(List<String>? savedTexts) {
if (savedTexts != null) {
store.setTexts(savedTexts);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blueGrey.shade700,
),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.blueGrey.shade700,
Colors.grey,
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Observer(
builder: (_) => Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.elliptical(5, 70),
topRight: Radius.elliptical(5, 70),
bottomLeft: Radius.elliptical(5, 70),
bottomRight: Radius.elliptical(5, 70),
)
),
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.max,
children: _buildTextItems(context),
),
),
),
),
),
),
const SizedBox(height: 40),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Column(
children: [
TextField(
textAlign: TextAlign.center,
controller: TextEditingController(text: store.text),
onChanged: store.setText,
onEditingComplete: () => _saveText(context),
decoration: InputDecoration(
hintText: 'Digite seu texto',
hintStyle: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.black,
),
border: InputBorder.none,
),
onSubmitted: (value) {
if (value.isEmpty) {
Fluttertoast.showToast(
msg: 'Você precisa digitar algum texto!',
);
} else {
Fluttertoast.showToast(
msg: "Texto salvo!",
);
_saveText(context);
}
},
),
],
),
),
),
const SizedBox(height: 100),
GestureDetector(
onTap: openPrivacyPolicy,
child: const Text(
'Política de Privacidade',
style: TextStyle(
color: Colors.white,
fontSize: 16,
),
),
),
],
),
),
),
),
);
}
void openPrivacyPolicy() async {
const url = 'https://www.google.com.br';
Uri new_url = Uri.parse(url);
if (await canLaunchUrl(new_url)) {
await launchUrl(new_url);
} else {
Fluttertoast.showToast(msg: 'Não foi possível abrir a política de privacidade.');
}
}
List<Widget> _buildTextItems(BuildContext context) {
final List<Widget> textItems = [];
for (String text in store.texts) {
textItems.add(
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Column(
children: [
Row(
children: [
Expanded(
child: GestureDetector(
onTap: () => _editText(context, text),
child: Text(
_truncateText(text),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
),
IconButton(
icon: Icon(Icons.mode_edit),
color: Colors.black,
iconSize: 50,
onPressed: () => _editText(context, text),
),
IconButton(
icon: Icon(Icons.cancel_rounded),
color: Colors.red.shade600,
iconSize: 50,
onPressed: () =>
_showDeleteConfirmationDialog(context, text),
),
],
),
const Divider(color: Colors.black),
],
),
),
);
}
return textItems;
}
String _truncateText(String text) {
const int maxLength = 20;
return text.length <= maxLength
? text
: '${text.substring(0, maxLength)}...';
}
Future<void> _showDeleteConfirmationDialog(
BuildContext context, String text) async {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Confirmar exclusão'),
content: Text('Tem certeza de que deseja excluir o texto?'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Cancelar'),
),
TextButton(
onPressed: () {
store.removeText(text);
Navigator.of(context).pop();
},
child: Text('Excluir'),
),
],
);
},
);
}
Future<void> _editText(BuildContext context, String text) async {
TextEditingController editController = TextEditingController(text: text);
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Editar Texto'),
content: TextField(
controller: editController,
decoration: InputDecoration(
hintText: 'Digite seu texto',
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Cancelar'),
),
TextButton(
onPressed: () {
store.editText(text, editController.text);
Navigator.of(context).pop();
},
child: Text('Salvar'),
),
],
);
},
);
}
bool saving = false;
Future<void> _saveText(BuildContext context) async {
if (!saving && store.text != null && store.text!.isNotEmpty) {
saving = true;
store.addText(store.text!);
await store.saveTextsToSharedPreferences();
store.clearText();
saving = false;
}
}
}
class TextRegisterStore = _TextRegisterStore with _$TextRegisterStore;
abstract class _TextRegisterStore with Store {
@observable
String? text;
@observable
ObservableList<String> texts = ObservableList<String>();
@action
void setText(String value) {
text = value;
}
@action
void clearText() {
text = null;
}
@action
void addText(String text) {
if (text.isNotEmpty) {
texts.add(text);
}
}
@action
void removeText(String text) {
texts.remove(text);
saveTextsToSharedPreferences();
}
@action
void setTexts(List<String> texts) {
this.texts = ObservableList<String>.of(texts);
}
@action
void editText(String oldText, String newText) {
if (texts.contains(oldText)) {
final index = texts.indexOf(oldText);
texts[index] = newText;
saveTextsToSharedPreferences();
}
}
Future<void> saveTextsToSharedPreferences() async {
final prefs = await SharedPreferences.getInstance();
prefs.setStringList('savedTexts', texts);
}
Future<void> loadTextsFromSharedPreferences() async {
final prefs = await SharedPreferences.getInstance();
final savedTexts = prefs.getStringList('savedTexts');
if (savedTexts != null) {
setTexts(savedTexts);
}
}
} |
#ifndef _STR_StreamModule_H_ // -*- mode: c++ ; c-file-style: "hopper" -*-
/*
* Copyright 1991-2010 Eric M. Hopper <hopper@omnifarious.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* $Header$ */
// For log information, see ../ChangeLog
#include <cassert>
#include <cstddef>
#ifndef _STR_StrChunkPtr_H_
# include <StrMod/StrChunkPtr.h>
#endif
#define _STR_StreamModule_H_
namespace strmod {
namespace strmod {
/** \class StreamModule StreamModule.h StrMod/StreamModule.h
* An abstract base for objects that can be modules in the StreamModule
* framework.
*
* A StreamModule module can be thought of as a processing element in a stream
* of data. A StreamModule's 'sides' represent ports at which data can enter
* or leave the module.
*
* If you were to think of the UNIX utility 'grep' as a StreamModule, it's 0
* side would be stdin, and it's 1 side would be stdout. Depending on the
* implementation, it might also have a 2 side, where error messages are sent.
*
* Of course, grep's 'sides' are not bi-directional, they are uni-directional.
* As a rule, a StreamModule's data port (a Plug) is bi-directional. One way
* to encapsulate a UNIX program designed to run in a pipeline would be to
* make a module that has a 0 side (stdin) a 1 side, with it either passing
* data unchanged in the reverse direction, or refusing to pass data in the
* reverse direction at all.
*
* Another way would be to model it as a single sided StreamModule with it's
* input and output happening on the same plug. This would sort of violate
* the spirit of the StreamModule system though. There's currently only one
* module which operates this way, the EchoModule, which merely echoes all of
* its input to its output. */
class StreamModule
{
public:
class Plug;
friend class Plug;
/**
* The Strategy for what to do when a plug is disconnected from another
* plug.
*
* Probably best used as a Flyweight.
*
* Not called on module deletion, or if the module thinks it handles its
* plugs disconnecting and there's no room for a Strategy to get involved.
*/
class PlugDisconnectStrategy {
public:
/**
* Here so derived classes have a virtual destructor.
*/
virtual ~PlugDisconnectStrategy() = default;
/**
* Called by a module when one of its plugs has been disconnected.
*
* This is not called when a plug is disconnected because the module
* itself is being destructed.
*/
virtual void plugDisconnected(StreamModule *m, Plug *p) = 0;
};
//! Abstract class, doesn't do much.
StreamModule() : pdstrategy_(NULL) { }
//! Prudently virtual in an abstract base class.
virtual ~StreamModule() { pdstrategy_ = 0; }
//! Can a plug be created on the given side?
virtual bool canCreate(int side) const = 0;
/**
* Attempts to create a plug on the given side.
*
* When writing a derived class, your MakePlug function should \b ALWAYS
* call CanCreate first before calling i_MakePlug.
*
* Returns 0 (NULL) on failure. Only fails if CanCreate would return
* false.
*/
inline Plug *makePlug(int side);
//! Does the module own this plug?
virtual bool ownsPlug(const Plug *plug) const = 0;
/**
* Please delete this plug.
*
* Modules are supposed to own plugs, so you aren't supposed to delete them
* yourself.
*
* Returns false on failure. Failure could happen because module does not
* own the plug.
*/
virtual bool deletePlug(Plug *plug) = 0;
/**
* Get the current PlugDisconnectStrategy.
*
* Deleting the object you get this way is a BAD thing unless you set a new
* strategy before you do it.
*/
inline PlugDisconnectStrategy *getPDStrategy() const;
/**
* Set the current PlugDisconnectStrategy.
*
* The StreamModule does not assume responsibility for deleting the object
* you pass in. Of course, if you delete it while the StreamModule has it
* set, that will probably cause bad things to happen.
*
* Setting the strategy to NULL essentially turns it off. */
inline void setPDStrategy(PlugDisconnectStrategy *pds);
protected:
/**
* Called whenever a plug is disconnected.
*
* <b>This function isn't called when a plug is disconnected as a result of
* its destructor being called.</b>
*
* This is used to provide a hook to do what you think you should do when a
* plug is disconnected.
*
* It calls the pdstrategy_ by default, if there is one.
*/
inline virtual void plugDisconnected(Plug *plug);
/**
* Makes a plug on the given side.
*
* Guaranteed to never be called if canCreate would return false. Must
* NEVER return 0 (NULL).
*/
virtual Plug *i_MakePlug(int side) = 0;
//! Used to set the readable flag of a plug since their set method is
//! protected.
inline void setReadableFlagFor(Plug *p, bool val);
//! Used to set the writeable flag of a plug since their set method is
//! protected.
inline void setWriteableFlagFor(Plug *p, bool val);
private:
PlugDisconnectStrategy *pdstrategy_;
};
/** \class StreamModule::Plug StreamModule.h StrMod/StreamModule.h
* A point of connection between one StreamModule and another.
*/
class StreamModule::Plug
{
public:
friend class StreamModule;
//! A Plug has to have a parent.
inline Plug(StreamModule &parent);
//! Does some tricky things to avoid having the disconnect strategy called.
inline virtual ~Plug();
//! Can this plug be read from?
bool isReadable() const { return(flags_.canread_ && !flags_.isreading_); }
//! Can this plug be written to?
bool isWriteable() const { return(flags_.canwrite_ && !flags_.iswriting_); }
/**
* \brief Plug this plug into another. Can fail if already plugged in.
*/
bool plugInto(Plug &other);
//! Unplug this plug from any plugs it may be connected to.
inline void unPlug();
//! \brief Which plug (if any) is this plug plugged into? Returns NULL if
//! not plugged in.
inline Plug *pluggedInto() const;
//! Which module owns this plug?
StreamModule &getParent() const { return(parent_); }
//! Which 'side' is this plug on?
virtual int side() const = 0;
protected:
/**
* A struct just so raw bitfields don't have to be in the class.
*/
struct Flags {
bool isreading_ : 1; ///< re-entrancy control
bool iswriting_ : 1; ///< re-entrancy control
bool canread_ : 1; ///< Can the plug be read from?
bool canwrite_ : 1; ///< Can the plug be written to?
bool notifyonread_ : 1; ///< Does the plug need to be told if its partner can be read from?
bool notifyonwrite_ : 1; ///< Does the plug need to be told if its partner can be written to?
};
/**
* Set whether this plug is readable or not.
*
* Even if this is set, isReadable can return false because the plug is
* already being read from, and a plug can't be read by two things at once.
*/
inline void setReadable(bool val);
/**
* Set whether this plug is writeable or not.
*
* Even if this is set, isWriteable can return false because the plug is
* already being written to, and a plug can't be written to by two things
* at once.
*/
inline void setWriteable(bool val);
//! These are so derived classes have access to this flag.
void setIsReading(bool val) { flags_.isreading_ = val; }
//! These are so derived classes have access to this flag on other plugs.
static void setIsReading(Plug &othr, bool v) { othr.setIsReading(v); }
//! These are so derived classes have access to this flag.
void setIsWriting(bool val) { flags_.iswriting_ = val; }
//! These are so derived classes have access to this flag on other plugs.
static void setIsWriting(Plug &othr, bool v) { othr.setIsWriting(v); }
//! This is so derived classes can get read access to the flags of any plug.
inline static const Flags &getFlagsFrom(const Plug &p);
/**
* Tell a connected plug that this plug's readable state has changed.
*
* This checks the flags first and doesn't notify if the other plug doesn't
* request notification.
*/
inline void notifyOtherReadable() const;
/**
* Tell a connected plug that this plug's readable state has changed.
*
* This checks the flags first and doesn't notify if the other plug doesn't
* request notification.
*/
inline void notifyOtherWriteable() const;
/**
* If this plug needs to be notified of the other's readable state.
*
* The only plugs that should really need this are ones for modules where
* the readable or writeable state of certain plugs depends on the readable
* state of the plug that this plug is plugged into.
*/
virtual bool needsNotifyReadable() const { return(false); }
/**
* If this plug needs to be notified of the other's writeable state.
*
* The only plugs that should really need this are ones for modules where
* the readable or writeable state of certain plugs depends on the
* writeable state of the plug that this plug is plugged into.
*/
virtual bool needsNotifyWriteable() const { return(false); }
/**
* The 'other plug's readable state changed' notification function.
*
* Called when plug this plug is plugged into changes whether or not it is
* readable.
*/
virtual void otherIsReadable() { }
/**
* The 'other plug's writeable state changed' notification function.
*
* Called when plug this plug is plugged into changes whether or not it is
* writeable.
*/
virtual void otherIsWriteable() { }
/** @name Read and Write
* Actually read or write to a StreamModule::Plug.
*
* These functions have undefined behavior when the appropriate isReadable
* or isWriteable function returns false.
*
* Also, to avoid re-entrancy problems, the flag_.isreading_ or
* flag_.iswriting_ flag should be set before actually doing the read or
* write. This prevents the read or write from causing the function to be
* called again.
*
* This is of particular importance for modules like EchoModule. If you
* have two EchoModule objects with a buffering module of some sort between
* then, an infinitely recurisve loop could easily be formed if a read or
* write function were called without the appropriate re-entrancy control
* flag being set.
*
* As it is, you will get an infinite loop, but it will
* not be recursive, so the program will not crash. (You might have wanted
* the infinite loop for some reason.)
*/
//@{
/**
* \brief Read this this plug. Behavior is undefined if this plug not
* readable.
*
* When writing your own read function that calls this one, you are
* responsible for making sure the the plug is readable before calling this
* function.
*
* These functions do not set the isreading or iswriting
* flags. You'll need to write wrapper functions that do this. The
* pushLoop and pullLoop functions already set the isreading and iswriting
* flags.
*/
virtual const StrChunkPtr i_Read() = 0;
/**
* \brief Write to this plug. Behavior is undefined if this plug not
* writeable.
*
* When writing your own write function that calls this one, you are
* responsible for making sure the the plug is writeable before calling
* this function.
*
* These functions do not set the isreading or iswriting flags. You'll
* need to write wrapper functions that do this. The pushLoop and pullLoop
* functions already set the isreading and iswriting flags.
*/
virtual void i_Write(const StrChunkPtr &ptr) = 0;
//@}
//! This is so derived classes can call write on the connected plug.
void writeOther(const StrChunkPtr &ptr) const { other_->i_Write(ptr); }
//! This is so derived classes can call read on the connected plug.
const StrChunkPtr readOther() const { return(other_->i_Read()); }
/**
* Read as much as possible from this plug and write to the connected plug.
*/
void pushLoop();
/**
* Read as much as possible from the connected plug and write to this plug.
*/
void pullLoop();
private:
Flags flags_; ///< See struct Flags.
Plug *other_; ///< The plug I'm talking to (if any).
StreamModule &parent_; ///< What StreamModule I came from.
};
//-----------------------------inline functions--------------------------------
inline StreamModule::Plug *StreamModule::makePlug(int side)
{
if (canCreate(side)) {
Plug *plug = i_MakePlug(side);
assert(plug != 0);
return(plug);
} else {
return(0);
}
}
inline StreamModule::PlugDisconnectStrategy *StreamModule::getPDStrategy() const
{
return(pdstrategy_);
}
inline void StreamModule::setPDStrategy(PlugDisconnectStrategy *pds)
{
pdstrategy_ = pds;
}
inline void StreamModule::plugDisconnected(Plug *plug)
{
if (pdstrategy_ != NULL)
{
pdstrategy_->plugDisconnected(this, plug);
}
}
inline void StreamModule::setReadableFlagFor(Plug *p, bool val)
{
p->setReadable(val);
}
inline void StreamModule::setWriteableFlagFor(Plug *p, bool val)
{
p->setWriteable(val);
}
//---
inline StreamModule::Plug::Plug(StreamModule &parent)
: other_(NULL),
parent_(parent)
{
flags_.isreading_ = flags_.iswriting_ = flags_.canread_ = flags_.canwrite_
= flags_.notifyonread_ = flags_.notifyonwrite_ = false;
}
inline StreamModule::Plug::~Plug()
{
if (other_ != NULL)
{
Plug *temp = other_;
// This prevents the unPlug routine from gaining control. It will think
// this plug is already unplugged.
other_ = NULL;
flags_.notifyonread_ = flags_.notifyonwrite_ = false;
temp->unPlug();
// Note that parent->plugDisconnected() isn't called here. This is to
// avoid calling a partially destructed parent, and various similar
// kinds of nastiness.
}
}
inline void StreamModule::Plug::unPlug()
{
// Only need to unplug if we're plugged in.
if (other_ != NULL)
{
Plug *temp = other_;
// This prevents infinite recursion from happening when the other plug
// tells us to unplug. We'll think we're already unplugged.
other_ = NULL;
flags_.notifyonread_ = flags_.notifyonwrite_ = false;
temp->unPlug();
getParent().plugDisconnected(this);
}
}
inline StreamModule::Plug *StreamModule::Plug::pluggedInto() const
{
return(other_);
}
inline void StreamModule::Plug::setReadable(bool val)
{
bool oldflag = flags_.canread_;
flags_.canread_ = val;
if (isReadable() && pluggedInto() != NULL)
{
pushLoop();
}
if (flags_.canread_ != oldflag)
{
notifyOtherReadable();
}
}
inline void StreamModule::Plug::setWriteable(bool val)
{
bool oldflag = flags_.canwrite_;
flags_.canwrite_ = val;
if (isWriteable() && pluggedInto() != NULL)
{
pullLoop();
}
if (flags_.canwrite_ != oldflag)
{
notifyOtherWriteable();
}
}
inline const StreamModule::Plug::Flags &
StreamModule::Plug::getFlagsFrom(const Plug &p)
{
return(p.flags_);
}
inline void StreamModule::Plug::notifyOtherReadable() const
{
if (flags_.notifyonread_)
{
assert(other_ != NULL);
other_->otherIsReadable();
}
}
inline void StreamModule::Plug::notifyOtherWriteable() const
{
if (flags_.notifyonwrite_)
{
assert(other_ != NULL);
other_->otherIsWriteable();
}
}
} // namespace strmod
} // namespace strmod
#endif |
# [백준] 2565. 전깃줄 - Python
**[Gold V]**
https://www.acmicpc.net/problem/2565
## 풀이
전깃줄이 교차하는 경우를 생각해 보자.
A 전봇대에서 B 전봇대로의 모든 전깃줄을 시작부터 숫자가 작은 순서대로 하나하나 연결한다고 생각할 때,
도착하는 위치가 이미 존재하는 도착지들보다 더 작은 숫자라면, 전깃줄이 교차하게 된다.
따라서 그러한 전깃줄들을 제거하면 되는 문제이다.
이 과정에서, A 전봇대에서의 출발 위치를 기준으로 정렬하게 되면, 아래와 같다.
```python
[[1, 8], [2, 2], [3, 9], [4, 1], [6, 4], [7, 6], [9, 7], [10, 10]]
```
그리고 B 전봇대의 도착 위치만을 빼놓고 보면, 아래와 같다.
```python
[8, 2, 9, 1, 4, 6, 7, 10]
```
이 배열에서의 최장 증가 수열 (LIS)를 구해, 그 길이를 원래 길이에서 빼면, 제거할 전깃줄의 개수를 구할 수 있다.
따라서, 이 문제는 LIS로 풀 수 있다.
보통 LIS는 Time Complexity 문제 때문에, Binary Search로 해결하는 경우가 더 많지만,
이 문제의 경우 `n < 100` 이기 때문에, DP로 풀이할 수 있다.
그러나 이 글에서는 Binary Search로 풀이한다.
```python
import bisect
N = int(input())
lines = []
for _ in range(N):
lines.append(list(map(int, input().split())))
lines = sorted(lines, key=lambda x:x[0])
end = []
for s, e in lines:
end.append(e)
res = []
for e in end:
a = bisect.bisect_left(res, e)
if a == len(res):
res.append(e)
else:
res[a] = e
print(len(end)-len(res))
``` |
import {useEffect, useState} from "react";
import {UseSSEHookData} from './useSSE.types.ts'
const getStateChanges = (eventSource) => {
switch (eventSource.readyState){
case eventSource.CONNECTING:
return {
loading: true,
open: false
}
case eventSource.OPEN:
return {
loading: false,
open: true
}
case eventSource.CLOSED:
return {
loading: false,
open: false
}
}
}
export function useSSE<Type>(
url: string | null,
eventSourceFactory: (url: string)=>EventSource=(url: string) => {
return new EventSource(url)
}
): UseSSEHookData<Type>{
const [data, setData] = useState<Type | null>(null)
const [error, setError] = useState<string|null>(null)
const [eventSource, setEventSource] = useState<EventSource|null>(null);
const [isOpen, setIsOpen] = useState(false)
const [loading, setLoading] = useState(false)
const closeConnection = () =>{
if (eventSource){
eventSource.close()
setEventSource(null);
}
}
const stop = ()=>{
closeConnection()
}
const reset = () =>{
setData(null)
}
useEffect(() => {
if (eventSource && url === null){
closeConnection()
}
}, [url, eventSource]);
const handle_sse_event = (event: MessageEvent)=>{
const this_data = event.data
try {
const parsedData = JSON.parse(this_data) as Type
if (JSON.stringify(parsedData) !== JSON.stringify(data)){
setData(parsedData)
}
} catch (e) {
setError(e)
throw e
}
}
useEffect(() => {
if (eventSource){
const results = getStateChanges(eventSource)
if(results){
if (results.open != isOpen){
setIsOpen(results.open)
}
if (results.loading != loading){
setLoading(results.loading)
}
}
} else {
setLoading(false)
setIsOpen(false)
}
});
useEffect(()=>{
if (url){
if (eventSource === null){
setData(null)
const sse = eventSourceFactory(url)
sse.addEventListener('message', handle_sse_event)
sse.onerror = (event) =>{
setError(JSON.stringify(event))
}
setEventSource(sse);
}
}
return () =>{
if (eventSource) {
eventSource.close();
eventSource.onmessage = null
eventSource.removeEventListener('message', handle_sse_event)
setEventSource(null);
}
}
}, [url])
return {
data: data,
loading: loading,
error: error,
isOpen: isOpen,
stop: stop,
reset: reset
}
} |
import PropTypes from 'prop-types';
import { HiOutlineBookOpen } from 'react-icons/hi2';
import { FiDollarSign } from 'react-icons/fi';
const Course = ({ course, handleSelectedCourse }) => {
const { title, img, description, price, hours } = course;
return (
<>
<div className="bg-[#FFF] p-4 rounded-lg">
<figure className="">
<img src={img} alt="Shoes" className="w-full" />
</figure>
<div className="">
<h2 className="text-lg font-semibold pt-4">{title}</h2>
<p className='py-2 text-justify text-sm font-normal text-[#1C1B1B99]'>{description}</p>
<div className='flex justify-between'>
<div>
<p className='text-base text-[#1C1B1B99] font-medium'><FiDollarSign className='inline text-black text-2xl' /> Price : {price}</p>
</div>
<div>
<p className='text-base text-[#1C1B1B99] font-medium'><HiOutlineBookOpen className='inline text-black text-2xl' /> Credit : {hours}hr</p>
</div>
</div>
<div className="my-3">
<button onClick={() => handleSelectedCourse(course, course.hours, course.hours, course.price)} className="btn-primary text-white bg-[#2F80ED] w-full py-2 rounded-xl">Select</button>
</div>
</div>
</div>
</>
);
};
Course.propTypes = {
course: PropTypes.object.isRequired,
handleSelectedCourse: PropTypes.func
}
export default Course; |
#pragma once
#include <mainframe/utils/string.h>
#include <mainframe/ui/modifierkey.h>
#include <string>
#include <map>
#include <nlohmann/json.hpp>
#include <fmt/format.h>
namespace bt {
class KeyMapping {
public:
size_t key = 0;
mainframe::ui::ModifierKey modifier;
bool operator==(const KeyMapping& other);
bool operator!=(const KeyMapping& other);
};
class ConfigKeymapping {
public:
KeyMapping camMoveUp = {87, mainframe::ui::ModifierKey::none};
KeyMapping camMoveDown = {83, mainframe::ui::ModifierKey::none};
KeyMapping camMoveLeft = {65, mainframe::ui::ModifierKey::none};
KeyMapping camMoveRight = {68, mainframe::ui::ModifierKey::none};
};
class ConfigWorld {
public:
float scale = 200;
};
class ConfigCamera {
public:
float zoomMin = 0.2f;
float zoomMax = 5.0f;
float zoomSpeed = 0.92f;
float zoomScrollScale = 100.0f;
float moveSpeed = 25.0f;
};
class ConfigUI {
public:
float iconSheetSize = 128.0f;
float iconStarSize = 16.0f;
float iconStarRingSize = 26.0f;
float iconCarrierSize = 16.0f;
float iconCarrierRingSize = 26.0f;
float iconCarrierShadowScale = 1.3f;
};
class Config {
public:
ConfigUI ui;
ConfigWorld world;
ConfigCamera camera;
ConfigKeymapping mapping;
};
} |
/*
*
* Component: `TableBody`.
*
*/
import { memo, Fragment, useCallback } from "react";
import createLazyLoadedComponent from "@exsys-patient-insurance/react-lazy";
import {
TableRowRecordType,
ColorNamesType,
TableColumnProps,
TableSelectionProps,
TableSelectionKeysType,
TableExpandedRowRenderType,
TableActionColumnProps,
TableCellInputFunctionsType,
TableBodyRowClickEvents,
TableRowClassNameType,
TableRowCellClassNameType,
} from "@exsys-patient-insurance/types";
import SelectionView from "./SelectionView";
import ExpandIconCell from "./ExpandIconCell";
import BodyCellRenderer from "./BodyCellRenderer";
import MapCellChildren from "./MapCellChildren";
import {
StyledTableRowCell,
ExpandedRow,
ExpandedRowCell,
BodyRow,
} from "../styled";
import {
TableInternalSelectionChangeActionType,
InternalTableRowClickHandler,
} from "../index.interface";
interface TableBodyProps<T>
extends Omit<
TableSelectionProps<T>,
"disabledRowsSelection" | "onSelectionChanged"
>,
TableCellInputFunctionsType<T>,
TableActionColumnProps<T>,
Omit<TableBodyRowClickEvents<T>, "onSelectRow"> {
dataSource: T[];
rowKey: string;
columns: TableColumnProps<T>[];
disabledRowsSelection: TableSelectionKeysType;
handleRowSelectionChange: TableInternalSelectionChangeActionType;
showSelectionColumn?: boolean;
fontSize?: string;
expandedRowRender?: TableExpandedRowRenderType<T>;
rowsWithExpandCell: TableSelectionKeysType;
expandedKeys: TableSelectionKeysType;
setExpandedKeys: React.Dispatch<React.SetStateAction<TableSelectionKeysType>>;
showEditableInputs?: boolean;
selectedRowBackgroundColor?: ColorNamesType;
onRowClick: InternalTableRowClickHandler<T>;
clickedRowKey?: TableSelectionKeysType[0];
actionColumnWidth?: number;
rowClassName?: TableRowClassNameType<T>;
rowCellClassName?: TableRowCellClassNameType<T>;
}
const LazyLoadedActionColumnIcon = createLazyLoadedComponent(
() =>
import(
"./ActionColumnIcon" /* webpackChunkName: "table.actionColumnIcon" */
)
);
const TableBody = <T extends TableRowRecordType>({
dataSource,
rowKey,
showSelectionColumn,
selectionType,
columns,
disabledRowsSelection,
handleRowSelectionChange,
selectionKeys,
fontSize,
expandedRowRender,
rowsWithExpandCell,
expandedKeys,
setExpandedKeys,
onPressActionIcon,
actionIcon,
actionRowDisabled,
actionLabelId,
onInputChange,
recordInputsDisabled,
showEditableInputs,
selectedRowBackgroundColor,
onDoubleClick,
onRowClick,
clickedRowKey,
actionColumnWidth,
rowClassName,
rowCellClassName,
}: TableBodyProps<T>) => {
const columnsLength = columns?.length ?? 0;
const showActionColumn = !!onPressActionIcon;
const hasExpandRowRender = !!expandedRowRender;
const expandedRowColSpan = columnsLength + ~~showActionColumn;
const onRowDoubleClick = useCallback(
(currentRecord: T, recordIndex: number) => () => {
onDoubleClick?.(currentRecord, recordIndex);
},
[onDoubleClick]
);
return (
<tbody>
{dataSource.map((record, currentRecordIndex) => {
const currentRowKey = record[rowKey] as TableSelectionKeysType[0];
const onClickSelection = handleRowSelectionChange({
key: currentRowKey,
});
const showExpandCell = rowsWithExpandCell?.includes?.(
currentRowKey as never
);
const isRowChecked = selectionKeys?.includes?.(currentRowKey as never);
const rowExpanded = expandedKeys?.includes(currentRowKey as never);
const showExpandedRow =
hasExpandRowRender && showExpandCell && rowExpanded;
const selectionAndExpandColumnsSpan =
~~!!showSelectionColumn + ~~hasExpandRowRender;
return (
<Fragment key={currentRowKey}>
<BodyRow
// @ts-ignore ignore this for now.
selectedRowBackgroundColor={selectedRowBackgroundColor}
onClick={onRowClick(currentRowKey, record, currentRecordIndex)}
onDoubleClick={onRowDoubleClick(record, currentRecordIndex)}
selected={isRowChecked || clickedRowKey === currentRowKey}
className={rowClassName?.(record)}
>
{showSelectionColumn && (
<SelectionView
type={selectionType}
onCheck={onClickSelection}
fontSize={fontSize}
checked={isRowChecked}
disabled={disabledRowsSelection?.includes?.(
currentRowKey as never
)}
/>
)}
{hasExpandRowRender ? (
<ExpandIconCell
fontSize={fontSize}
currentRowKey={currentRowKey}
expanded={rowExpanded}
setExpandedKeys={setExpandedKeys}
showExpandIcon={showExpandCell}
/>
) : null}
{columns?.map((cellProps, currentColumnIndex) => {
const { dataIndex, align, children, titleDataIndex } =
cellProps;
const hasNestedColumns = !!children?.length;
const computedCellKey = `${dataIndex}-col-${currentColumnIndex}`;
const sharedProps = {
currentRecordIndex,
currentRecord: record,
fontSize,
showEditableInputs,
onInputChange,
recordInputsDisabled,
titleDataIndex,
rowCellClassName,
};
return (
<StyledTableRowCell key={computedCellKey} fontSize={fontSize}>
{!hasNestedColumns && (
<BodyCellRenderer<T>
{...sharedProps}
cellProps={cellProps}
/>
)}
{hasNestedColumns && (
<MapCellChildren<T>
nestedColumns={children as TableColumnProps<T>[]}
baseCellAlignment={align}
baseCellKey={computedCellKey}
baseCellProps={sharedProps}
isBodyCells
/>
)}
</StyledTableRowCell>
);
})}
<LazyLoadedActionColumnIcon
shouldMountChunk={showActionColumn}
onPressActionIcon={onPressActionIcon}
actionRowDisabled={actionRowDisabled}
actionLabelId={actionLabelId}
actionIcon={actionIcon}
actionColumnWidth={actionColumnWidth}
fontSize={fontSize}
currentRecord={record}
rowIndex={currentRecordIndex}
/>
</BodyRow>
{showExpandedRow && (
<ExpandedRow>
<StyledTableRowCell
colSpan={selectionAndExpandColumnsSpan}
fontSize={fontSize}
/>
<ExpandedRowCell
fontSize={fontSize}
colSpan={expandedRowColSpan}
>
{expandedRowRender?.(record, currentRecordIndex)}
</ExpandedRowCell>
</ExpandedRow>
)}
</Fragment>
);
})}
</tbody>
);
};
export default memo(TableBody) as typeof TableBody; |
import { newChain, addBlockToChain } from "../blockchain/blockchain";
import { blockToString } from "../blockchain/block";
import express from "express";
import cors from "cors"
import { createProxyMiddleware } from "http-proxy-middleware";
import { newP2PServer, P2PServerListen, P2PSyncChain } from "./p2pServer";
const HTTP_PORT = process.env.HTTP_PORT ? parseInt(process.env.HTTP_PORT) : 3001;
// we can run our app something like the following to run on a
// different port:
// HTTP_PORT=3002 P2P_PORT=5002 PEERS=ws://localhost:5001 npm run dev
// HTTP_PORT=3003 P2P_PORT=5003 PEERS=ws://localhost:5002,ws://localhost:5001 npm run dev
//create a new app
const app = express();
//using the blody parser middleware
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors())
// create a new blockchain instance
const blockchain = newChain();
const p2pServer = newP2PServer(blockchain)
P2PServerListen(p2pServer)
//EXPOSED APIs
//api to get the blocks
app.get("/blocks", (req, res) => {
res.json(p2pServer.blockchain.chain);
});
//api to add blocks
app.post("/mine", (req, res) => {
const block = addBlockToChain(p2pServer.blockchain, req.body.data);
console.log(`New block added: ${blockToString(block)}`);
P2PSyncChain(p2pServer)
res.redirect("/blocks");
});
// app server configurations
app.listen(HTTP_PORT, () => {
console.log(`listening on port ${HTTP_PORT}`);
}); |
import contextlib
from rest_framework.permissions import DjangoModelPermissions
from rest_framework.serializers import ModelSerializer, ValidationError
from rest_framework import serializers
from django.contrib.auth import get_user_model
from account.models import *
from home.models import *
User = get_user_model()
class TutorSerializer(ModelSerializer):
is_verified = serializers.BooleanField(read_only=True, default=False)
class Meta:
model = Tutor
fields = '__all__'
class SubjectSerializer(ModelSerializer):
class Meta:
model = Subject
fields = '__all__'
class CurriculumSerializer(ModelSerializer):
class Meta:
model = Curriculum
fields = '__all__'
class MessageSerializer(ModelSerializer):
class Meta:
model = UserMessage
fields = '__all__'
class TrialLessonSerializer(ModelSerializer):
class Meta:
model = TrialLesson
fields = '__all__'
class DegreeInformationSerializer(ModelSerializer):
class Meta:
model = DegreeInformation
fields = '__all__'
def convertTutorSerializedDataToResponseData(serialized_data):
tmpSubjects = []
for sub in serialized_data['subjects']:
with contextlib.suppress(Exception):
subInstance = Subject.objects.get(id=sub)
tmpSubjects.append(SubjectSerializer(subInstance).data)
serialized_data["subjects"] = tmpSubjects
tmpCurriculum = []
for curr in serialized_data['curriculum']:
with contextlib.suppress(Exception):
currInstance = Curriculum.objects.get(id=curr)
tmpCurriculum.append(CurriculumSerializer(currInstance).data)
serialized_data["curriculum"] = tmpCurriculum
tmpDegrees = []
for deg in serialized_data['degrees']:
with contextlib.suppress(Exception):
degInstance = DegreeInformation.objects.get(id=deg)
tmpDegrees.append(DegreeInformationSerializer(degInstance).data)
serialized_data["degrees"] = tmpDegrees
return serialized_data |
package br.com.brjdevs.miyuki.modules.db;
import br.com.brjdevs.miyuki.core.Module;
import br.com.brjdevs.miyuki.core.Module.*;
import br.com.brjdevs.miyuki.core.entities.ModuleResourceManager;
import br.com.brjdevs.miyuki.modules.cmds.PushCmd;
import br.com.brjdevs.miyuki.modules.cmds.manager.PermissionsModule;
import br.com.brjdevs.miyuki.modules.cmds.manager.entities.CommandEvent;
import br.com.brjdevs.miyuki.modules.cmds.manager.entities.Commands;
import br.com.brjdevs.miyuki.modules.cmds.manager.entities.ICommand;
import com.google.gson.JsonObject;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import org.apache.commons.codec.digest.DigestUtils;
import java.util.*;
import java.util.regex.Pattern;
import static br.com.brjdevs.miyuki.lib.AsyncUtils.asyncSleepThen;
import static br.com.brjdevs.miyuki.lib.CollectionUtils.iterate;
import static br.com.brjdevs.miyuki.lib.StringUtils.advancedSplitArgs;
import static br.com.brjdevs.miyuki.lib.StringUtils.notNullOrDefault;
import static br.com.brjdevs.miyuki.lib.data.DBUtils.decode;
import static br.com.brjdevs.miyuki.lib.data.DBUtils.encode;
import static br.com.brjdevs.miyuki.modules.db.DBModule.onDB;
import static com.rethinkdb.RethinkDB.r;
@Module(id = "i18n", order = 11)
public class I18nModule {
private static final Pattern compiledPattern = Pattern.compile("\\$\\([A-Za-z.]+?\\)");
@ResourceManager
private static ModuleResourceManager manager;
@Resource("main.json")
private static String i18nMain = "";
@JDAInstance
private static JDA jda = null;
private static List<String> syncedLocalizations = new ArrayList<>(), moderated = new ArrayList<>();
private static Map<String, Map<String, String>> locales = new HashMap<>();
private static Map<String, String> parents = new HashMap<>();
private static Map<String, Suggestion> suggestions = new HashMap<>();
public static void acceptSuggestion(String key) {
if (!suggestions.containsKey(key)) throw new IllegalStateException("Key does not exist");
suggestions.remove(key).accept();
}
public static void reject(String key) {
if (!suggestions.containsKey(key)) throw new IllegalStateException("Key does not exist");
suggestions.remove(key).reject();
}
@PreReady
private static void load() {
onDB(r.table("i18n")).run().cursorExpected().forEach(element -> {
JsonObject object = element.getAsJsonObject();
if (!object.has("id") || !object.has("value")) return;
String[] id = object.get("id").getAsString().split(":", 2);
if (id.length != 2) return;
setLocalTranslation(id[0], id[1], decode(object.get("value").getAsString()));
if (object.has("moderated")) setModerated(id[0], id[1], object.get("moderated").getAsBoolean());
});
}
@PostReady
private static void postReady() {
localizeDynamic("botname", jda.getSelfUser().getName());
localizeDynamic("mention", jda.getSelfUser().getAsMention());
}
@Command("i18n") //TODO Escrito nos Comentários
private static ICommand generateCommand() {
return Commands.buildTree(PermissionsModule.BOT_ADMIN)
.addCommand("suggest", Commands.buildSimple("i18n.suggest.usage")
.setAction(event -> {
String[] values = advancedSplitArgs(event.getArgs(), 3);
String unlocalized = values[0], locale = values[1], value = values[2];
if (unlocalized.isEmpty() || locale.isEmpty() || value.isEmpty()) {
event.awaitTyping(true).getAnswers().invalidargs();
return;
}
if (unlocalized.startsWith("!")) unlocalized = unlocalized.substring(1);
if (value.length() > 7 && value.startsWith("base64:")) value = decode(value.substring(7));
if (moderated.contains(unlocalized + ":" + locale)) {
//TODO Mensagem fofa
return;
}
//TODO Create I18n bans and check for ban
Suggestion suggestion = new Suggestion(unlocalized, locale, value, event.getAuthor());
String suggestMiniMd5 = DigestUtils.md5Hex(suggestion.toString().getBytes()).substring(0, 5);
suggestions.put(suggestMiniMd5, suggestion);
event.awaitTyping(true).getAnswers().bool(true).queue();
PushCmd.pushSimple(
"i18n",
"User " + event.getAuthor().getName() + "#" + event.getAuthor().getDiscriminator() +
" suggests the translation `" + unlocalized + "` in locale `" + locale + "` to:\n```\n" + value + "\n```\n" +
"To accept: `bot mod i18n accept " + suggestMiniMd5 + "`\n" +
"To reject: `bot mod i18n reject " + suggestMiniMd5 + "`"
);
})
.build()
)
.addCommand("localize", Commands.buildSimple()
.setAction(event -> {
String[] values = advancedSplitArgs(event.getArgs(), 3);
String unlocalized = values[0], locale = values[1], value = values[2];
if (unlocalized.isEmpty() || locale.isEmpty() || value.isEmpty()) {
event.awaitTyping(true).getAnswers().invalidargs();
return;
}
if (value.length() > 7 && value.startsWith("base64:")) value = decode(value.substring(7));
boolean moderated = unlocalized.startsWith("!");
if (moderated) unlocalized = unlocalized.substring(1);
pushTranslation(unlocalized, locale, value);
setModerated(unlocalized, locale, moderated);
event.awaitTyping(true).getAnswers().bool(true).queue();
})
.build()
)
.addCommand("suggestCommand", Commands.buildSimple()
// Args: <command> <locale> <[base64:]desc> <params> <info>
// Esse comando deverá funcionar igual ao suggest
// Mas com os argumentos do localizeCommand
.build()
)
.addCommand("localizeCommand", Commands.buildSimple()
// <command> <locale> <[base64:]desc> <[base64:]params> <[base64:]info>
// paramsMeta, noParams, noDesc <= localized(%s,locale)
// localize(genCmdUsage())
// return bool(true)
.setAction(event -> {
String[] values = advancedSplitArgs(event.getArgs(), 5);
String unlocalized = values[0], locale = values[1], desc = values[2], params = values[3], info = values[4];
if (unlocalized.isEmpty() || locale.isEmpty()) {
event.awaitTyping(true).getAnswers().invalidargs();
return;
}
if (desc.length() > 7 && desc.startsWith("base64:")) desc = decode(desc.substring(7));
if (params.length() > 7 && params.startsWith("base64:")) params = decode(params.substring(7));
if (info.length() > 7 && info.startsWith("base64:")) info = decode(info.substring(7));
boolean moderated = unlocalized.startsWith("!");
if (moderated) unlocalized = unlocalized.substring(1);
pushTranslation(
unlocalized, locale,
genCmdUsage(
desc, params, info
)
);
setModerated(unlocalized, locale, moderated);
event.awaitTyping(true).getAnswers().bool(true).queue();
})
.build()
)
.addCommand("remove", Commands.buildSimple()
// Args: <unlocalized> <locale|"all">
// Apaga a tradução
.build()
)
.addCommand("suggestRemove", Commands.buildSimple()
// Args: <unlocalized> <locale|"all">
// Esse comando deverá funcionar igual ao suggest
// Mas com os argumentos do remove
.build()
)
.addCommand("list", Commands.buildSimple()
// Args: [page]
// TODO-ADRIAN Gerar a lista
// TODO-STEVEN Sistema de Lista baseado em page
// Lista as traduções
.build()
)
.addCommand("about", Commands.buildSimple()
// NoArgs
// Explicar o sistema de traduções
.build()
)
.build();
}
private static String genCmdUsage(String desc, String params, String info) {
desc = (desc != null && !desc.isEmpty()) ? desc : "$(meta.noDesc)";
params = (params != null && !params.isEmpty()) ? params : "$(meta.noParams)";
info = (info != null && !info.isEmpty()) ? ("\n " + info.replace("\n", "\n ")) : "";
return desc + "\n" + "$(meta.params)" + ": " + params + info;
}
private static void localizeDynamic(String untranslated, String translated) {
setLocalTranslation("dynamic." + untranslated, "root", translated);
setModerated("dynamic." + untranslated, "root", true);
}
// public static String generateJsonDump() {
// System.out.println();
// JsonObject json = new JsonObject();
// JsonObject parentsJson = new JsonObject();
// JsonObject localizations = new JsonObject();
//
// parents.forEach(parentsJson::addProperty);
// locales.forEach((k, v) -> {
// JsonObject localization = new JsonObject();
// v.forEach(localization::addProperty);
// localizations.add(k, localization);
// });
//
// json.add("parents", parentsJson);
// json.add("localizations", localizations);
// return Pastee.post(json.toString());
// }
public static void pushTranslation(String unlocalized, String locale, String localized) {
String localeId = unlocalized + ":" + locale;
if (syncedLocalizations.contains(localeId)) {
onDB(r.table("i18n").get(localeId).update(arg -> r.hashMap("value", encode(localized)))).noReply();
} else {
onDB(r.table("i18n").insert(r.hashMap("id", localeId).with("value", encode(localized)).with("moderated", moderated.contains(localeId)))).noReply();
syncedLocalizations.add(localeId);
}
setLocalTranslation(unlocalized, locale, localized);
}
public static void setModerated(String unlocalized, String locale, boolean flag) {
String localeId = unlocalized + ":" + locale;
if (flag && !moderated.contains(localeId)) {
moderated.add(localeId);
} else if (!flag && moderated.contains(localeId)) {
moderated.remove(localeId);
}
if (syncedLocalizations.contains(localeId)) {
onDB(r.table("i18n").get(localeId).update(arg -> r.hashMap("moderated", flag))).noReply();
}
}
public static void setLocalTranslation(String unlocalized, String locale, String localized) {
if (!locales.containsKey(unlocalized)) locales.put(unlocalized, new HashMap<>());
locales.get(unlocalized).put(locale, localized);
}
public static String getLocale(CommandEvent event) {
return notNullOrDefault(UserModule.fromDiscord(event.getAuthor()).getLang(), event.getGuild().getLang());
}
public static void setParent(String locale, String parent) {
parents.put(locale, parent);
}
public static String parentOf(String locale) {
if (locale == null || locale.equals("root")) return null;
return parents.getOrDefault(locale, "root");
}
public static String getLocalized(String unlocalized, String locale) {
return dynamicTranslate(getBaseLocalized(unlocalized, locale), locale, null);
}
public static String dynamicTranslate(String string, String locale, Optional<Map<String, String>> dynamicMap) {
if (dynamicMap == null) dynamicMap = Optional.empty();
if (!string.contains("$(")) return string;
Set<String> skipIfIterated = new HashSet<>();
for (String key : iterate(compiledPattern.matcher(string))) {
if (skipIfIterated.contains(key)) continue;
String unlocalizedKey = key.substring(2, key.length() - 1);
if (dynamicMap.isPresent()) {
string = string.replace(key, Optional.ofNullable(dynamicMap.get().get(unlocalizedKey)).orElseGet(() -> getLocalized(unlocalizedKey, locale)));
} else {
string = string.replace(key, getLocalized(unlocalizedKey, locale));
}
if (!string.contains("$(")) break;
skipIfIterated.add(key);
}
return string;
}
public static String getLocalized(String unlocalized, CommandEvent event) {
return getLocalized(unlocalized, getLocale(event));
}
public static String getLocalized(String unlocalized, TextChannel channel) {
return getLocalized(unlocalized, GuildModule.fromDiscord(channel.getGuild()).getLang());
}
private static String getBaseLocalized(final String unlocalized, final String locale) {
String unlocalizing = unlocalized, localed = locale, localized = unlocalizing;
Map<String, String> currentLocales = locales.get(unlocalizing);
while (unlocalizing.equals(localized) && localed != null) {
localized = currentLocales != null ? currentLocales.getOrDefault(localed, unlocalizing) : unlocalizing;
if (unlocalizing.equals(localized)) localed = parentOf(localed);
else if (localized.length() > 1 && localized.startsWith("$$=") && localized.endsWith(";")) { //This won't change the parent
localized = localized.substring(3, localized.length() - 1); //Substring localized
if (unlocalizing.equals(localized)) {//unlocalized = localized -> LOOP
break;
} else {
unlocalizing = localized;
currentLocales = locales.get(unlocalizing);
}
}
}
if (unlocalizing.equals(localized) || localed == null) {
asyncSleepThen(1000, () -> PushCmd.pushSimple("i18n", channel -> "I18nModule Warn: Detected an untranslated String: " + unlocalized + ":" + locale)).run();
}
return localized;
}
private static class Suggestion {
private final String unlocalized;
private final String locale;
private final String value;
private final User author;
public Suggestion(String unlocalized, String locale, String value, User author) {
this.unlocalized = unlocalized;
this.locale = locale;
this.value = value;
this.author = author;
}
public void accept() {
pushTranslation(unlocalized, locale, value);
//TODO GIB XP (PROFILES)
suggestions.values().removeIf(this::equals);
}
public void reject() {
//TODO TAKE XP (PROFILES)
suggestions.values().removeIf(this::equals);
}
@Override
public String toString() {
return author.toString() + "(" + unlocalized + ":" + locale + "=" + value;
}
}
} |
import { useState } from "react";
import { Link, useLocation } from "react-router-dom";
import "./Navbar.style.scss";
import logo from "../../logo.png";
export const Navbar = () => {
const [menuVisible, setMenuVisible] = useState(false);
const location = useLocation();
const toggleMenu = () => {
setMenuVisible(!menuVisible);
};
// Function to calculate the number of hexagons needed to fill the viewport width
const calculateHexCount = () => {
const viewportWidth = window.innerWidth;
const hexWidth = 14; // Width of a hexagon
const margin = 0.5; // Adjust margin as needed
const availableWidth = viewportWidth - 2 * margin; // Subtract margins
return Math.floor(availableWidth / hexWidth);
};
// Function to generate a row of hexagons
const generateHexagonRow = () => {
const hexCount = calculateHexCount();
const hexagons = [];
for (let j = 0; j < hexCount; j++) {
hexagons.push(
<div className="hexagon" key={`hex-${j}`}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="#242424">
{/* Your hexagon SVG path here */}
<polygon points="50,5 95,25 95,75 50,95 5,75 5,25" />
</svg>
</div>
);
}
return hexagons;
};
const isActiveLink = (path: string) => {
return location.pathname === path;
};
return (
<nav className="hexagon-container">
<div id="hex-animation">
<div className="hexagon-row" id="first-row">
{generateHexagonRow()}
</div>
<div className="hexagon-row" id="second-row">
{generateHexagonRow()}
</div>
<div className="hexagon-row" id="third-row">
{generateHexagonRow()}
</div>
<div className="hexagon-row" id="fourth-row">
{generateHexagonRow()}
</div>
<div className="hexagon-row" id="fifth-row">
{generateHexagonRow()}
</div>
<div className="hexagon-row" id="sixth-row">
{generateHexagonRow()}
</div>
</div>
{window.innerWidth > 768 && (
<ul id="nav-ul" className={menuVisible ? "active" : ""}>
<img className="logo" src={logo} alt="logo" />
<li className={`nav-button ${isActiveLink("/") ? "active-link" : ""}`}>
<Link to="/">Home</Link>
</li>
<li className={`nav-button ${isActiveLink("/game") ? "active-link" : ""}`}>
<Link to="/game">Game</Link>
</li>
{/* TODO: @Mary - navbar-routing */}
{/* ------------------------------------------- */}
<li
className={`nav-button ${isActiveLink("/login-signup") ? "active-link" : ""}`}
>
<Link to="/login-signup">Login/Signup</Link>
</li>
<li className={`nav-button ${isActiveLink("/profile") ? "active-link" : ""}`}>
<Link to="/profile">Profile</Link>
</li>
{/* ------------------------------------------- */}
</ul>
)}
{window.innerWidth <= 768 && (
<>
<div
id="hamburger"
className={`menu-toggle nav-button ${menuVisible ? "active" : ""}`}
onClick={toggleMenu}
>
{/* Hamburger icon */}
<div className="bar"></div>
<div className="bar"></div>
<div className="bar"></div>
</div>{" "}
<div
id="modal-background"
className={menuVisible ? "active" : ""}
onClick={toggleMenu}
>
<ul id="nav-ul media-query" className={menuVisible ? "active" : ""}>
<li className={`nav-button ${isActiveLink("/") ? "active-link" : ""}`}>
<Link to="/">Home</Link>
</li>
<li
className={`nav-button ${isActiveLink("/feature") ? "active-link" : ""}`}
>
<Link to="/feature">Feature</Link>
</li>
<li
className={`nav-button ${isActiveLink("/feature2") ? "active-link" : ""}`}
>
<Link to="/feature2">Feature 2</Link>
</li>
<li
className={`nav-button ${isActiveLink("/example") ? "active-link" : ""}`}
>
<Link to="/example">Example</Link>
</li>
<li className={`nav-button ${isActiveLink("/game") ? "active-link" : ""}`}>
<Link to="/game">Game</Link>
</li>
{/* TODO- \/ conditional rendering after auth added \/ */}
{/* ------------------------------------------- */}
<li
className={`nav-button ${
isActiveLink("/login-signup") ? "active-link" : ""
}`}
>
<Link to="/login-signup">Login/Signup</Link>
</li>
<li
className={`nav-button ${isActiveLink("/profile") ? "active-link" : ""}`}
>
<Link to="/profile">Profile</Link>
</li>
{/* ------------------------------------------- */}
</ul>
</div>
</>
)}
</nav>
);
}; |
package com.sixint.dscatalog.services;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.any;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.sixint.dscatalog.dto.ProductDTO;
import com.sixint.dscatalog.entities.Category;
import com.sixint.dscatalog.entities.Product;
import com.sixint.dscatalog.repositories.CategoryRepository;
import com.sixint.dscatalog.repositories.ProductRepository;
import com.sixint.dscatalog.services.exceptions.DataBaseException;
import com.sixint.dscatalog.services.exceptions.ResourceNotFoundException;
import com.sixint.dscatalog.tests.Factory;
@ExtendWith(SpringExtension.class)
public class ProductServiceTests {
@InjectMocks
private ProductService service;
@Mock
private ProductRepository repository;
@Mock
private CategoryRepository categoryRepository;
private long existingId;
private long nonExistingId;
private long dependentId;
private PageImpl<Product> page;
private Product product;
private Category category;
private ProductDTO productDTO;
@BeforeEach
void setup() throws Exception {
existingId = 1L;
nonExistingId = 1000L;
dependentId = 4L;
product = Factory.createProduct();
category = Factory.createCategory();
productDTO = Factory.createProductDTO();
page = new PageImpl<>(List.of(product));
when(repository.findAll((Pageable)any())).thenReturn(page);
when(repository.find(any(), any(), any())).thenReturn(page);
when(repository.save(any())).thenReturn(product);
when(repository.getOne(existingId)).thenReturn(product);
when(repository.getOne(nonExistingId)).thenThrow(EntityNotFoundException.class);
when(categoryRepository.getOne(existingId)).thenReturn(category);
when(categoryRepository.getOne(nonExistingId)).thenThrow(EntityNotFoundException.class);
when(repository.findById(existingId)).thenReturn(Optional.of(product));
when(repository.findById(nonExistingId)).thenReturn(Optional.empty());
doNothing().when(repository).deleteById(existingId);
doThrow(EmptyResultDataAccessException.class).when(repository).deleteById(nonExistingId);
doThrow(DataIntegrityViolationException.class).when(repository).deleteById(dependentId);
}
@Test
public void deletShouldDoNothingWhenIdExists() {
Assertions.assertDoesNotThrow(() -> {
service.delete(existingId);
});
Mockito.verify(repository, Mockito.times(1)).deleteById(existingId);
}
@Test
public void deletShouldThrowResourceNotFoundExceptionWhenIdDoesntExists() {
Assertions.assertThrows(ResourceNotFoundException.class, () -> {
service.delete(nonExistingId);
});
Mockito.verify(repository, Mockito.times(1)).deleteById(nonExistingId);
}
@Test
public void deletShouldThrowDataBaseExceptionWhenDependentIdExists() {
Assertions.assertThrows(DataBaseException.class, () -> {
service.delete(dependentId);
});
Mockito.verify(repository, Mockito.times(1)).deleteById(dependentId);
}
@Test
public void findAllPageShouldReturnPAge() {
Pageable pageable = PageRequest.of(0, 10);
Page<ProductDTO> result = service.findAllPaged(0L, "", pageable);
Assertions.assertNotNull(result);
}
@Test
public void findByIdShouldReturnProductDTOWhenExistId() {
ProductDTO result = service.findById(existingId);
Assertions.assertNotNull(result);
Mockito.verify(repository, Mockito.times(1)).findById(existingId);
}
@Test
public void findByIdShouldThrowResourceNotFoundExceptionWhenIdDoesntExists() {
Assertions.assertThrows(ResourceNotFoundException.class, () -> {
service.findById(nonExistingId);
;
});
Mockito.verify(repository, Mockito.times(1)).findById(nonExistingId);
}
@Test
public void updateShouldReturnProductDTOWhenExistId() {
ProductDTO result = service.update(existingId, productDTO);
Assertions.assertNotNull(result);
}
@Test
public void updateShouldThrowResourceNotFoundExceptionWWhenIdDoesntExists() {
Assertions.assertThrows(ResourceNotFoundException.class, () -> {
service.update(nonExistingId, productDTO);
});
}
} |
const express = require('express')
const app = express()
const cors = require('cors')
var bodyParser = require('body-parser')
const path = require('path');
// database connection
require('./config/database');
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use(
cors(
{
origin: '*', // ! edit later
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
)
);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello World!')
})
const roomsRouter = require('./routes/rooms');
const staffRouter = require('./routes/staff');
const reservationsRouter = require('./routes/reservations');
app.use('/rooms', roomsRouter);
app.use('/staff', staffRouter);
app.use('/reservations', reservationsRouter);
const port = 9999;
app.listen(process.env.PORT || port, () => {
console.log(`app running on port ${port}`)
}) |
import time
import warnings
from functools import lru_cache
from typing import Optional, Dict, Union
import httpx
import requests
from random_user_agent.params import SoftwareName, OperatingSystem
from random_user_agent.user_agent import UserAgent
from requests.adapters import HTTPAdapter, Retry
DEFAULT_TIMEOUT = 10 # seconds
class TimeoutHTTPAdapter(HTTPAdapter):
"""
Custom HTTP adapter that sets a default timeout for requests.
Inherits from `HTTPAdapter`.
Usage:
- Create an instance of `TimeoutHTTPAdapter` and pass it to a `requests.Session` object's `mount` method.
Example:
```python
session = requests.Session()
adapter = TimeoutHTTPAdapter(timeout=10)
session.mount('http://', adapter)
session.mount('https://', adapter)
```
:param timeout: The default timeout value in seconds. (default: 10)
:type timeout: int
"""
def __init__(self, *args, **kwargs):
self.timeout = DEFAULT_TIMEOUT
if "timeout" in kwargs:
self.timeout = kwargs["timeout"]
del kwargs["timeout"]
super().__init__(*args, **kwargs)
def send(self, request, **kwargs):
"""
Sends a request with the provided timeout value.
:param request: The request to send.
:type request: PreparedRequest
:param kwargs: Additional keyword arguments.
:type kwargs: dict
:returns: The response from the request.
:rtype: Response
"""
timeout = kwargs.get("timeout")
if timeout is None:
kwargs["timeout"] = self.timeout
return super().send(request, **kwargs)
def get_requests_session(max_retries: int = 5, timeout: int = DEFAULT_TIMEOUT,
headers: Optional[Dict[str, str]] = None,
session: Optional[httpx.Client] = None, use_httpx: bool = False) \
-> Union[httpx.Client, requests.Session]:
if not session:
if use_httpx:
session = httpx.Client(http2=True, timeout=timeout, follow_redirects=True)
else:
session = requests.session()
if isinstance(session, requests.Session):
retries = Retry(
total=max_retries, backoff_factor=1,
status_forcelist=[408, 413, 429, 500, 501, 502, 503, 504, 505, 506, 507, 509, 510, 511],
allowed_methods=["HEAD", "GET", "POST", "PUT", "DELETE", "OPTIONS", "TRACE"],
)
adapter = TimeoutHTTPAdapter(max_retries=retries, timeout=timeout, pool_connections=32, pool_maxsize=32)
session.mount('http://', adapter)
session.mount('https://', adapter)
session.headers.update({
"User-Agent": get_random_ua(),
**dict(headers or {}),
})
return session
RETRY_ALLOWED_METHODS = ["HEAD", "GET", "POST", "PUT", "DELETE", "OPTIONS", "TRACE"]
RETRY_STATUS_FORCELIST = [413, 429, 500, 501, 502, 503, 504, 505, 506, 507, 509, 510, 511]
def _should_retry(response: httpx.Response) -> bool:
return response.request.method in RETRY_ALLOWED_METHODS and \
response.status_code in RETRY_STATUS_FORCELIST
def srequest(session: httpx.Client, method, url, *, max_retries: int = 5,
backoff_factor: float = 1.0, raise_for_status: bool = True, **kwargs) -> httpx.Response:
resp = None
for i in range(max_retries):
sleep_time = backoff_factor * (2 ** i)
try:
resp = session.request(method, url, **kwargs)
if raise_for_status:
resp.raise_for_status()
except (httpx.TooManyRedirects,):
raise
except (httpx.HTTPStatusError, requests.exceptions.HTTPError) as err:
if _should_retry(err.response):
warnings.warn(f'Requests {err.response.status_code} ({i + 1}/{max_retries}), '
f'sleep for {sleep_time!r}s ...')
time.sleep(sleep_time)
else:
raise
except (httpx.HTTPError, requests.exceptions.RequestException) as err:
warnings.warn(f'Requests error ({i + 1}/{max_retries}): {err!r}, '
f'sleep for {sleep_time!r}s ...')
time.sleep(sleep_time)
else:
break
assert resp is not None, f'Request failed for {max_retries} time(s) - {method} {url!r}.'
if raise_for_status:
resp.raise_for_status()
return resp
@lru_cache()
def _ua_pool():
software_names = [SoftwareName.CHROME.value, SoftwareName.FIREFOX.value, SoftwareName.EDGE.value]
operating_systems = [OperatingSystem.WINDOWS.value, OperatingSystem.MACOS.value]
user_agent_rotator = UserAgent(software_names=software_names, operating_systems=operating_systems, limit=1000)
return user_agent_rotator
def get_random_ua():
return _ua_pool().get_random_user_agent() |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 在js中,一个对象是不允许作为另一个对象的属性名的
// 比如在如下的例子中,编译器会自动把obj_0转化成字符串
let obj_0 = {
'hdcms': "haha"
}
let hd_0 = {
obj_0: 'houdunren'
}
console.log(hd_0)
// 如果还是需要将对象作为属性名可以加上中括号
// 其实还是把这个对象转成了字符串
let obj = {
"hdcms": "hahah"
}
let hd = {
[obj]: "我好困啊"
}
console.log(hd) // 无法显示obj,显示[object Object]
console.log(hd.obj) // 无法取到obj下的属性值,返回undefined
// 取到属性值的方法
console.log(hd[obj])
console.log(hd["[object Object]"])
console.log(hd[obj.toString()])
</script>
</body>
</html> |
<?php
/**
* The file that defines the core plugin class
*
* A class definition that includes attributes and functions used across both the
* public-facing side of the site and the admin area.
*
* @link https://www.welaunch.io
* @since 1.0.0
*
* @package WooCommerce_Catalog_Mode
* @subpackage WooCommerce_Catalog_Mode/includes
*/
/**
* The core plugin class.
*
* This is used to define internationalization, admin-specific hooks, and
* public-facing site hooks.
*
* Also maintains the unique identifier of this plugin as well as the current
* version of the plugin.
*
* @since 1.0.0
* @package WooCommerce_Catalog_Mode
* @subpackage WooCommerce_Catalog_Mode/includes
* @author Daniel Barenkamp <support@db-dzine.com>
*/
class WooCommerce_Catalog_Mode {
/**
* The loader that's responsible for maintaining and registering all hooks that power
* the plugin.
*
* @since 1.0.0
* @access protected
* @var WooCommerce_Catalog_Mode_Loader $loader Maintains and registers all hooks for the plugin.
*/
protected $loader;
/**
* The unique identifier of this plugin.
*
* @since 1.0.0
* @access protected
* @var string $plugin_name The string used to uniquely identify this plugin.
*/
protected $plugin_name;
/**
* The current version of the plugin.
*
* @since 1.0.0
* @access protected
* @var string $version The current version of the plugin.
*/
protected $version;
/**
* Define the core functionality of the plugin.
*
* Set the plugin name and the plugin version that can be used throughout the plugin.
* Load the dependencies, define the locale, and set the hooks for the admin area and
* the public-facing side of the site.
*
* @since 1.0.0
*/
public function __construct($version) {
$this->plugin_name = 'woocommerce-catalog-mode';
$this->version = $version;
$this->load_dependencies();
$this->set_locale();
$this->define_admin_hooks();
$this->define_public_hooks();
}
/**
* Load the required dependencies for this plugin.
*
* Include the following files that make up the plugin:
*
* - WooCommerce_Catalog_Mode_Loader. Orchestrates the hooks of the plugin.
* - WooCommerce_Catalog_Mode_i18n. Defines internationalization functionality.
* - WooCommerce_Catalog_Mode_Admin. Defines all hooks for the admin area.
* - WooCommerce_Catalog_Mode_Public. Defines all hooks for the public side of the site.
*
* Create an instance of the loader which will be used to register the hooks
* with WordPress.
*
* @since 1.0.0
* @access private
*/
private function load_dependencies() {
/**
* The class responsible for orchestrating the actions and filters of the
* core plugin.
*/
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-woocommerce-catalog-mode-loader.php';
/**
* The class responsible for defining internationalization functionality
* of the plugin.
*/
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-woocommerce-catalog-mode-i18n.php';
/**
* The class responsible for defining all actions that occur in the admin area.
*/
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-woocommerce-catalog-mode-admin.php';
/**
* The class responsible for defining all actions that occur in the public-facing
* side of the site.
*/
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'public/class-woocommerce-catalog-mode-public.php';
$this->loader = new WooCommerce_Catalog_Mode_Loader();
}
/**
* Define the locale for this plugin for internationalization.
*
* Uses the WooCommerce_Catalog_Mode_i18n class in order to set the domain and to register the hook
* with WordPress.
*
* @since 1.0.0
* @access private
*/
private function set_locale() {
$this->plugin_i18n = new WooCommerce_Catalog_Mode_i18n();
$this->loader->add_action( 'plugins_loaded', $this->plugin_i18n, 'load_plugin_textdomain' );
}
/**
* Register all of the hooks related to the admin area functionality
* of the plugin.
*
* @since 1.0.0
* @access private
*/
private function define_admin_hooks() {
$this->plugin_admin = new WooCommerce_Catalog_Mode_Admin( $this->get_plugin_name(), $this->get_version() );
$this->loader->add_action( 'plugins_loaded', $this->plugin_admin, 'load_redux' );
$this->loader->add_action( 'init', $this->plugin_admin, 'init', 1 );
}
/**
* Register all of the hooks related to the public-facing functionality
* of the plugin.
*
* @since 1.0.0
* @access private
*/
private function define_public_hooks() {
$this->plugin_public = new WooCommerce_Catalog_Mode_Public( $this->get_plugin_name(), $this->get_version() );
$this->loader->add_action( 'wp_enqueue_scripts', $this->plugin_public, 'enqueue_styles' );
$this->loader->add_action( 'wp_enqueue_scripts', $this->plugin_public, 'enqueue_scripts' );
$this->loader->add_action( 'wp_ajax_woocommerce_catalog_mode_clear_cart', $this->plugin_public, 'clear_cart' );
$this->loader->add_action( 'wp_ajax_nopriv_woocommerce_catalog_mode_clear_cart', $this->plugin_public, 'clear_cart' );
$this->loader->add_action( 'init', $this->plugin_public, 'init' );
}
/**
* Run the loader to execute all of the hooks with WordPress.
*
* @since 1.0.0
*/
public function run() {
$this->loader->run();
}
/**
* The name of the plugin used to uniquely identify it within the context of
* WordPress and to define internationalization functionality.
*
* @since 1.0.0
* @return string The name of the plugin.
*/
public function get_plugin_name() {
return $this->plugin_name;
}
/**
* The reference to the class that orchestrates the hooks with the plugin.
*
* @since 1.0.0
* @return WooCommerce_Catalog_Mode_Loader Orchestrates the hooks of the plugin.
*/
public function get_loader() {
return $this->loader;
}
/**
* Retrieve the version number of the plugin.
*
* @since 1.0.0
* @return string The version number of the plugin.
*/
public function get_version() {
return $this->version;
}
} |
<template>
<div id="setting" class="container">
<div class="navbar">
<Navbar :current-status="currentStatus" />
</div>
<div class="setting-account">
<div class="title">
<h1>帳戶設定</h1>
</div>
<!-- form block -->
<form class="setting-form" @submit.stop.prevent="formSubmit()">
<div class="form-label-group">
<label for="account">帳號</label>
<input
id="account"
v-model="account"
type="text"
class="form-control"
required
/>
</div>
<div class="form-label-group">
<label for="name">名稱</label>
<input
id="name"
v-model="name"
type="text"
class="form-control"
required
/>
</div>
<div class="form-label-group">
<label for="email">Email</label>
<input
id="email"
v-model="email"
type="text"
class="form-control"
required
/>
</div>
<div class="form-label-group">
<label for="password">密碼</label>
<input
id="password"
v-model="password"
type="text"
class="form-control"
required
/>
</div>
<div class="form-label-group">
<label for="password-check">密碼確認</label>
<input
id="password-check"
v-model="checkPassword"
type="text"
class="form-control"
required
/>
</div>
<div class="setting-block">
<button class="btn" type="submit" :disabled="isProcessing">
儲存
</button>
</div>
</form>
</div>
</div>
</template>
<script>
import Navbar from "../components/Navbar.vue";
import settingAPI from "./../apis/setting";
import { Toast } from "./../utils/helper";
import { Toast2 } from "./../utils/helper";
import { mapState } from "vuex";
export default {
name: "setting",
components: {
Navbar,
},
computed: {
...mapState(["currentUser", "isAuthenticated"]),
},
created() {
this.mapCurrentUser();
},
data() {
return {
account: "",
name: "",
email: "",
password: "",
checkPassword: "",
isProcessing: false,
currentStatus: {
isIndex: false,
isUser: false,
isSetting: true,
},
};
},
methods: {
async formSubmit() {
if (
!this.account.trim() ||
!this.name.trim() ||
!this.email.trim() ||
!this.password.trim() ||
!this.checkPassword.trim()
) {
return Toast2.fire({
message: "不得留白",
});
}
if (this.password.trim() !== this.checkPassword.trim()) {
return Toast2.fire({
message: "密碼錯誤",
});
}
if (this.email.trim().indexOf("@") === -1) {
return Toast2.fire({
message: "email沒有@",
});
}
try {
const formData = {
account: this.account ? this.account : this.currentUser.account,
name: this.name ? this.name : this.currentUser.name,
email: this.email ? this.email : this.currentUser.email,
password: this.password,
checkPassword: this.checkPassword,
};
this.isProcessing = true;
console.log(formData);
const { data } = await settingAPI.setUser({
userId: this.currentUser.id,
formData,
});
this.isProcessing = false;
if (data.status === "error") {
throw new Error(data.message);
}
Toast.fire({
title: "成功更新帳戶資料!",
});
} catch (error) {
this.isProcessing = false;
console.log("error", error);
Toast2.fire({
title: "無法設定帳戶資料,請稍後再試",
});
}
},
mapCurrentUser() {
const { account, name, email } = this.currentUser;
this.name = name;
this.account = account;
this.email = email;
},
},
};
</script>
<style lang="scss" scoped>
@import "./../styles/variables.scss";
#setting {
display: grid;
grid-template-columns: 210px auto;
column-gap: 30px;
}
.title {
border-bottom: 1px solid $borderColor;
height: 55px;
line-height: 55px;
}
h1 {
color: $mainColor;
font-size: 19px;
padding-left: 1rem;
}
.setting-account {
border-left: 1px solid $borderColor;
}
.setting-form {
padding: 1.875rem 25.3125rem 0 1rem;
margin-bottom: 40rem;
position: relative;
}
.form-label-group {
position: relative;
label {
position: absolute;
left: 0.625rem;
top: 0.313rem;
color: $secondaryTextColor;
font-size: 15px;
font-weight: 500;
line-height: 15px;
}
input {
width: 642px;
height: 52px;
border-radius: 4px;
background-color: $formBgColor;
padding: 1.25rem 0 0.25rem 0.625rem;
margin-bottom: 1.875rem;
color: $mainColor;
font-size: 19px;
font-weight: 500;
border: none;
border-bottom: 2px solid $secondaryTextColor;
&:focus,
&:hover {
border-bottom: 2px solid #50b5ff;
}
.invalid-message {
position: absolute;
top: 50px;
left: 2px;
font: {
weight: 500;
size: 15px;
}
color: #fc5a5a;
}
}
.invalid {
border-bottom: 2px solid #fc5a5a;
}
}
.setting-block {
width: 642px;
position: relative;
}
.btn {
position: absolute;
top: 0;
right: 0;
border-radius: 50px;
background-color: $orange;
font-size: 18px;
font-weight: 700;
color: $white;
margin-top: 0.625rem;
padding: 0.625rem 2.5rem;
border: none;
}
</style> |
import { Add, Send } from '@mui/icons-material';
import { Button, styled } from '@mui/material';
import React from 'react';
const ButtonDemo = () => {
const BlueButton = styled(Button)(({ theme }) => ({
backgroundColor: theme.palette.otherColor.main,
color: '#888',
margin: 5,
'&:hover': {
backgroundColor: 'lightblue',
},
'&:disabled:': {
backgroundColor: 'gray',
color: 'white',
},
}));
return (
<div>
<Button variant='text'>Text</Button>
<Button startIcon={<Add />} color='otherColor' variant='contained'>
Contained
</Button>
<Button endIcon={<Send />} variant='outlined'>
Outlined
</Button>
<Button
variant='contained'
sx={{
backgroundColor: 'skyblue',
color: '#888',
margin: 5,
'&:hover': {
backgroundColor: 'lightblue',
},
'&:disabled:': {
backgroundColor: 'gray',
color: 'white',
},
}}
>
Inner Style
</Button>
<BlueButton variant='contained'>Using styled</BlueButton>
</div>
);
};
export default ButtonDemo; |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BaseLayoutComponent } from './layouts/base-layout/base-layout.component';
import { AdminLayoutComponent } from './layouts/admin-layout/admin-layout.component';
import { ProductListComponent } from './pages/admin/product/product-list/product-list.component';
import { ProductAddComponent } from './pages/admin/product/product-add/product-add.component';
import { ProductEditComponent } from './pages/admin/product/product-edit/product-edit.component';
import { PageNotFoundComponent } from './pages/page-not-found/page-not-found.component';
import { ProductDetailComponent } from './pages/product-detail/product-detail.component';
const routes: Routes = [
{
path: '', component: BaseLayoutComponent, children: [
{
path: "product/:id", component: ProductDetailComponent
},
]
},
{
path: 'admin', component: AdminLayoutComponent, children: [
{
path: "product", component: ProductListComponent
},
{
path: "product/add", component: ProductAddComponent
},
{
path: "product/:id/edit", component: ProductEditComponent
},
]
},
{
path: '**', component: PageNotFoundComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { } |
package org.kalibro.core.abstractentity;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import org.junit.Before;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;
public class CollectionPrinterTest extends PrinterTestCase<Collection<?>> {
private Collection<Object> sample;
@Override
protected CollectionPrinter createPrinter() {
return new CollectionPrinter();
}
@Before
public void setUp() {
sample = new ArrayList<Object>();
sample.add(new ArrayList<String>());
sample.add(list("cat", "dog", "pig"));
}
@Test
public void shouldPrintCollections() {
assertTrue(printer.canPrint(new HashSet<CollectionPrinter>()));
assertTrue(printer.canPrint(new ArrayList<CollectionPrinterTest>()));
assertFalse(printer.canPrint(this));
assertFalse(printer.canPrint(printer));
}
@Test
public void shouldPrintAsYaml() throws Exception {
assertEquals(" [] # empty collection", print(new ArrayList<String>(), "empty collection"));
assertEquals(loadResource("collection.printer.test"), print(sample, "strange collection"));
}
@Test
public void shouldBeLoadableAsYaml() throws Exception {
assertEquals(sample, new Yaml().load(print(sample, "")));
}
} |
'''
Copyright (c)2022 - Soffos.ai - All rights reserved
Updated at: 2023-10-09
Purpose: Easily use Emotion Detection Service
-----------------------------------------------------
'''
from .service import SoffosAIService
from .input_config import InputConfig
from soffosai.common.constants import ServiceString
from typing import Union
class EmotionDetectionService(SoffosAIService):
'''
The Emotion Detection module can detect selected emotions within the provided
text. The original text is chunked to passages of a specified sentence length.
Smaller chunks yield better accuracy.
'''
def __init__(self, **kwargs) -> None:
service = ServiceString.EMOTION_DETECTION
super().__init__(service, **kwargs)
def __call__(self, user:str, text:str, sentence_split:int=None, sentence_overlap:bool=True, emotion_choices:list=['joy', 'trust', 'fear', 'surprise', 'sadness', 'disgust', 'anger', 'anticipation']) -> dict:
'''
Call the Emotion Detection Service
:param user: The ID of the user accessing the Soffos API.
Soffos assumes that the owner of the api is an application (app) and that app has users.
Soffos API will accept any string."
:param text: Text to detect emotions from.
:param sentence_split: The number of sentences of each chunk when splitting the input text.
:param sentence_overlap: Whether to overlap adjacent chunks by 1 sentence. For example, with
sentence_split=3 and sentence_overlap=true : [[s1, s2, s3], [s3, s4, s5],
[s5, s6, s7]]
:param emotion_choices: List of emotions to detect in the text. If the field is not provided in
the payload, or set as null or empty list, it will default to all emotion
choices. Currently supported emotions are listed above in the default
emotion values.
:return: spans: A list of spans resulting from the specified chunking parameters. Each
span contains the following fields: text: The text of the span.
detected_emotions: A list of the emotions detected for the specific span.
span_start: The starting character index of the span in the original input
text. span_end: The ending character index of the span in the original
input text.
:Examples
Detailed examples can be found at `Soffos Github Repository <https://github.com/Soffos-Inc/soffosai-python/tree/master/samples/services/emotion_detection.py>`_
'''
return super().__call__(user=user, text=text, sentence_split=sentence_split, sentence_overlap=sentence_overlap, emotion_choices=emotion_choices)
def set_input_configs(self, name:str, text:Union[str, InputConfig], sentence_split:Union[int, InputConfig], sentence_overlap:Union[bool, InputConfig], emotion_choices:Union[str, InputConfig]=['joy', 'trust', 'fear', 'surprise', 'sadness', 'disgust', 'anger', 'anticipation']):
super().set_input_configs(name=name, text=text, sentence_split=sentence_split, sentence_overlap=sentence_overlap, emotion_choices=emotion_choices)
@classmethod
def call(self, user:str, text:str, sentence_split:int=None, sentence_overlap:bool=True, emotion_choices:list=['joy', 'trust', 'fear', 'surprise', 'sadness', 'disgust', 'anger', 'anticipation']) -> dict:
'''
Call the Emotion Detection Service
:param user: The ID of the user accessing the Soffos API.
Soffos assumes that the owner of the api is an application (app) and that app has users.
Soffos API will accept any string."
:param text: Text to detect emotions from.
:param sentence_split: The number of sentences of each chunk when splitting the input text.
:param sentence_overlap: Whether to overlap adjacent chunks by 1 sentence. For example, with
sentence_split=3 and sentence_overlap=true : [[s1, s2, s3], [s3, s4, s5],
[s5, s6, s7]]
:param emotion_choices: List of emotions to detect in the text. If the field is not provided in
the payload, or set as null or empty list, it will default to all emotion
choices. Currently supported emotions are listed above in the default
emotion values.
:return: spans: A list of spans resulting from the specified chunking parameters. Each
span contains the following fields: text: The text of the span.
detected_emotions: A list of the emotions detected for the specific span.
span_start: The starting character index of the span in the original input
text. span_end: The ending character index of the span in the original
input text.
:Examples
Detailed examples can be found at `Soffos Github Repository <https://github.com/Soffos-Inc/soffosai-python/tree/master/samples/services/emotion_detection.py>`_
'''
return super().call(user=user, text=text, sentence_split=sentence_split, sentence_overlap=sentence_overlap, emotion_choices=emotion_choices) |
using System;
using System.Runtime.CompilerServices;
using ToolSmiths.InventorySystem.Data.Enums;
using UnityEngine;
[assembly: InternalsVisibleTo("Tests")]
namespace ToolSmiths.InventorySystem.Data
{
/// <summary>
/// StatModifier have a type to determine how they apply their modifier value.
/// </summary>
[Serializable]
public struct StatModifier : IComparable<StatModifier>, IEquatable<StatModifier>
{
/// <summary>The modifier's range.</summary>
[Tooltip("The modifier's range.")]
[field: SerializeField] public Vector2Int Range { get; private set; }
/// <summary>The modifier's value.</summary>
[Tooltip("The modifier's value.")]
[field: SerializeField] public float Value { get; private set; }
/// <summary>The modifyer type - defines how and in what order it is applied.</summary>
[Tooltip("The modifyer type - defines how and in what order it is applied.")]
[field: SerializeField] public StatModifierType Type { get; private set; }
public StatModifier(Vector2Int range, float value, StatModifierType type = StatModifierType.FlatAdd)
{
Range = range;
Value = Mathf.Clamp(value, range.x, range.y); // think about converting it to a (0 to 1) value and map it to the range
Type = type;
}
///// <summary>
///// Creates a StatModifier with random Type
///// </summary>
///// <param name="value"></param>
//public StatModifier(Vector2Int range, float value) // just for development -> REMOVE ME LATER
//{
// Range = range;
// Value = Mathf.Clamp(value, range.x, range.y);
//
// var randomType = UnityEngine.Random.Range(0, Enum.GetValues(typeof(StatModifierType)).Length);
// Type = randomType switch
// {
// 0 => StatModifierType.Override,
// 1 => StatModifierType.FlatAdd,
// 2 => StatModifierType.PercentAdd,
// 3 => StatModifierType.PercentMult,
//
// _ => StatModifierType.FlatAdd,
// };
//}
public int CompareTo(StatModifier other)
{
var typeComparison = Type.CompareTo(other.Type);
return typeComparison != 0 ? typeComparison : Value.CompareTo(other.Value);
}
///// <summary>The stat's duration in seconds: 0 = instant ; 60 = 1 minute;</summary>
//[Tooltip("The stat's duration in seconds.\n 0 = instant, 60 = 1 minute")]
//[field: SerializeField] public uint Duration {get; private set;}
public int SortByType(StatModifier other) => Type.CompareTo(other.Type);
public override readonly string ToString() => Type switch
{
/// wording => how to consistantly translate the modifier types
// additional, additive, bonus,
StatModifierType.Overwrite => $"={Value:- #.###;#.###}",
StatModifierType.FlatAdd => $"{Value:+ #.###;- #.###;#.###}",
StatModifierType.PercentAdd => $"{Value:+ #.###;- #.###;#.###}%",
StatModifierType.PercentMult => $"{Value:+ #.###;- #.###;#.###}*%",
_ => $"?? {Value:+ #.###;- #.###;#.###}",
};
public bool Equals(StatModifier other) => Value == other.Value && Type == other.Type;
}
} |
/**********************************************************
Add Google Fonts
**********************************************************/
@import url('https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700;900&family=Nunito:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,200&family=Poppins:wght@300;400;500;600;700;800&family=Ubuntu:wght@300;400;500;700&display=swap');
/**********************************************************
Reset Default Properties Start
**********************************************************/
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
::-webkit-scrollbar-track {
background-color: var(--active-dark-font-color);
border-radius: 2.5rem;
}
::-webkit-scrollbar-thumb {
background-color: var(--active-theme-color);
border-radius: 2.5rem;
}
html {
font-size: 62.5%;
/* Now 1rem = 1em = 10px */
overflow-x: hidden;
scroll-behavior: smooth;
}
body {
overflow-x: hidden;
}
/**********************************************************
Reset Default Properties End
**********************************************************/
/**********************************************************
Variables Start
**********************************************************/
:root {
/* Theme Colors */
--theme-1-color: #18FFFF;
--theme-2-color: #FF0000;
--theme-3-color: #05ff00;
--theme-4-color: #0500ff;
--theme-5-color: #ff5c00;
/* Active Theme */
--active-theme-color: var(--active-theme, var(--theme-3-color));
/* Light Mode */
--pure-white: #fff;
--l-primary-bg: #e1ebee78;
--l-secondary-bg: var(--pure-white);
--l-dark-font-color: #161617;
--l-light-font-color: #414144;
--l-one-mode-shadow: #00000014;
--l-two-mode-shadow: rgba(0, 0, 0, 0.064);
--l-border-color: rgba(128, 128, 128, 0.176);
/* Dark Mode */
--pure-black: #000;
--d-secondary-bg: #161617;
--d-primary-bg: var(--pure-black);
--d-white-font-color: #fff;
--d-light-font-color: #e1ebee78;
--d-one-mode-shadow: transparent;
--d-two-mode-shadow: var(--active-theme-color);
--d-border-color: #ada2a24d;
/* Theme Fonts */
--font-family-1: 'Nunito', sans-serif;
--font-family-2: 'Poppins', sans-serif;
/* Padding */
--pad-inline: 1.8rem;
--pad-block: 4.5rem
}
/**********************************************************
Variables End
**********************************************************/
/**********************************************************
Common Properties to Frequently Used Elements Start
**********************************************************/
body {
/* Following Properties Will be Inherited By All the Elements */
/* Active or Default Mode (Dark Mode) */
--active-pure-color: var(--pure-black);
--active-primary-bg: var(--d-primary-bg);
--active-secondary-bg: var(--d-secondary-bg);
--active-dark-font-color: var(--d-white-font-color);
--active-light-font-color: var(--d-light-font-color);
--active-one-mode-shadow: var(--d-one-mode-shadow);
--active-border-color: var(--d-border-color);
--active-two-mode-shadow: var(--d-two-mode-shadow);
}
a {
text-decoration: none;
display: inline-block;
font-family: var(--font-family-2);
transition: all .3s linear;
}
li {
list-style-type: none;
font-family: var(--font-family-2);
}
button {
border: none;
cursor: pointer;
font-size: 1.5rem;
font-weight: 500;
letter-spacing: 1px;
font-family: var(--font-family-2);
transition: all .3s linear;
background-color: transparent;
}
input,
textarea {
outline: none;
}
img {
max-width: 100%;
width: 100%;
display: inline-block;
-o-object-fit: cover;
object-fit: cover;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: var(--font-family-1);
line-height: 1.4;
text-transform: capitalize;
}
h1 {
letter-spacing: 1.2px;
word-spacing: 3px;
}
p {
font-family: var(--font-family-2);
line-height: 1.6;
}
/**********************************************************
Common Properties to Frequently Used Elements End
**********************************************************/
/***********************************************************************************************
Actual Document Styling Start
***********************************************************************************************/
/**********************************************************
Wrapper Start
**********************************************************/
.wrapper {
width: 100vw;
height: auto;
}
/**********************************************************
Aside Nav Start
**********************************************************/
.aside-nav {
width: 30rem;
height: 100vh;
background-color: var(--active-secondary-bg);
border-right: .2rem solid var(--active-border-color);
position: fixed;
top: 0;
left: 0;
}
.aside-nav nav {
width: 100%;
height: inherit;
overflow-x: hidden;
overflow-y: auto;
flex-wrap: nowrap;
position: relative;
gap: 10rem;
}
.aside-nav nav::-webkit-scrollbar {
width: .5rem;
}
/**********************************************************
Logo Start
**********************************************************/
.logo-box {
position: relative;
padding: 2rem;
gap: .5rem;
}
.logo-box::before,
.logo-box:after {
content: '';
position: absolute;
width: 4rem;
height: 4rem;
border-radius: .3rem;
}
.logo-box::before {
top: 0;
left: 0;
border-top: .4rem solid var(--active-theme-color);
border-left: .4rem solid var(--active-theme-color);
}
.logo-box::after {
bottom: 0;
right: 0;
border-bottom: .4rem solid var(--active-theme-color);
border-right: .4rem solid var(--active-theme-color);
}
.logo-box img {
width: 4rem;
}
.logo-box h2 {
color: var(--active-dark-font-color);
font-size: 2rem;
text-transform: uppercase;
font-weight: 900;
}
/**********************************************************
Aside Nav Links Start
**********************************************************/
.aside-nav-links {
gap: 1.3rem;
}
.aside-nav-links li a {
width: 14rem;
padding: 1.3rem 2rem;
font-size: 1.4rem;
letter-spacing: .3px;
font-weight: 600;
color: var(--active-dark-font-color);
border: 1px solid var(--active-border-color);
border-left: .5rem solid var(--active-dark-font-color);
background-color: var(--active-primary-bg);
position: relative;
z-index: 1;
}
.aside-nav-links li a::before {
content: "";
position: absolute;
top: 0;
left: 0;
height: 100%;
background-color: var(--active-theme-color);
width: 0;
transition: all .3s linear;
z-index: -1;
}
@media (hover:hover) {
.aside-nav-links li a:hover::before {
width: 100%;
}
.aside-nav-links li a.active-nav-link::before {
width: 100%;
}
}
.aside-nav-links li a i {
width: 2.4rem;
}
/**********************************************************
Aside Nav Links End
**********************************************************/
/**********************************************************
Aside Nav End
**********************************************************/
/**********************************************************
Pages Container Start
**********************************************************/
.pages-container {
background-color: var(--active-primary-bg);
position: fixed;
top: 0;
left: 30rem;
right: 0;
bottom: 0;
}
.pages-container .page {
width: 100%;
height: 100vh;
background-color: var(--active-primary-bg);
position: absolute;
top: 0;
left: 0;
transform: translateX(100%);
transition: all .4s linear;
overflow-x: hidden;
overflow-y: auto;
}
.pages-container .page.active-page {
transform: translateX(0);
}
.pages-container .page::-webkit-scrollbar {
width: .7rem;
}
/**********************************************************
Theme Change Box Start
**********************************************************/
.theme-change-box {
gap: var(--pad-inline);
position: fixed;
z-index: 100;
right: var(--pad-inline);
top: var(--pad-block);
}
.theme-change-icons {
gap: .6rem;
}
.theme-icon {
width: 4rem;
aspect-ratio: 1/1;
border-radius: 50%;
background-color: var(--active-pure-color);
color: var(--active-dark-font-color);
font-size: 1.8rem;
border: .1rem solid var(--active-border-color);
cursor: pointer;
}
.show-theme-colors-icon i {
-webkit-animation: animate-colors-show-icon 4s linear infinite;
animation: animate-colors-show-icon 4s linear infinite;
}
/* Keyframes to Animate Theme Colors Show Icon */
@-webkit-keyframes animate-colors-show-icon {
100% {
transform: rotate(-360deg);
}
}
@keyframes animate-colors-show-icon {
100% {
transform: rotate(-360deg);
}
}
.theme-colors-box {
max-width: 0;
overflow: hidden;
transition: all .6s linear;
}
.theme-colors-box>div {
border: .1rem solid var(--active-border-color);
border-radius: .8rem;
background-color: var(--active-primary-bg);
padding: 1rem;
width: 19rem;
}
.theme-colors-box h3 {
font-size: 1.4rem;
color: var(--active-dark-font-color);
margin-bottom: 1.4rem;
letter-spacing: .3px;
}
.theme-colors-box .colors {
gap: .6rem;
flex-wrap: nowrap;
}
.theme-colors-box .colors span {
width: 3rem;
aspect-ratio: 1/1;
border-radius: 50%;
border: .2rem solid var(--active-border-color);
cursor: pointer;
}
.theme-colors-box .colors span:nth-child(1) {
background-color: var(--theme-1-color);
}
.theme-colors-box .colors span:nth-child(2) {
background-color: var(--theme-2-color);
}
.theme-colors-box .colors span:nth-child(3) {
background-color: var(--theme-3-color);
}
.theme-colors-box .colors span:nth-child(4) {
background-color: var(--theme-4-color);
}
.theme-colors-box .colors span:nth-child(5) {
background-color: var(--theme-5-color);
}
/**********************************************************
Theme Change Box End
**********************************************************/
/**********************************************************
Home Page Start
**********************************************************/
/**********************************************************
Social Media Icons Start
**********************************************************/
.social-media-icons {
gap: 1rem;
}
.social-media-icons a {
width: 3rem;
aspect-ratio: 1/1;
border-radius: 50%;
display: grid;
place-items: center;
font-size: 1.4rem;
color: var(--active-pure-color);
background-color: var(--active-theme-color);
box-shadow: 0 0 1.5rem var(--active-two-mode-shadow);
transform: translateY(0);
}
@media (hover:hover) {
.social-media-icons a:hover {
transform: translateY(-.5rem);
}
}
/**********************************************************
Social Media Icons End
**********************************************************/
/**********************************************************
Hero Container Start
**********************************************************/
.hero-container {
min-height: calc(100vh - var(--pad-block) - 3.5rem);
}
/**********************************************************
Hero Left Start
**********************************************************/
.hero-left {
flex-basis: 50%;
max-width: 700px;
}
.hero-left h3 {
font-size: 2rem;
color: var(--active-theme-color);
letter-spacing: 1px;
}
.hero-left h1 {
font-size: 6rem;
color: var(--active-dark-font-color);
}
.hero-left h1 span {
text-shadow: 0 0 1rem var(--active-two-mode-shadow);
display: inline-block;
transform: none;
}
.hero-left h1 span.animate-aman-name {
-webkit-animation: animate-aman-name 3s ease-in-out 1;
animation: animate-aman-name 3s ease-in-out 1;
}
/* Keyframes to Animate Aman Name */
@-webkit-keyframes animate-aman-name {
0%,
30% {
transform: perspective(10px) rotate(-360deg) rotateX(80deg);
}
100% {
transform: perspective(0px) rotate(0deg) rotateX(0deg);
}
}
@keyframes animate-aman-name {
0%,
30% {
transform: perspective(10px) rotate(-360deg) rotateX(80deg);
}
100% {
transform: perspective(0px) rotate(0deg) rotateX(0deg);
}
}
.hero-left .animate-web-developer {
margin-block: 1rem;
width: 27.7rem;
letter-spacing: 1px;
text-transform: uppercase;
word-spacing: 3px;
font-size: 3rem;
color: transparent;
-webkit-text-stroke: 1px var(--active-theme-color);
-webkit-background-clip: text;
background-clip: text;
background-image: linear-gradient(var(--active-theme-color), var(--active-theme-color));
background-repeat: no-repeat;
background-size: 27rem;
background-position: -27rem;
position: relative;
-webkit-animation: animate-web-developer 10s linear infinite 1s;
animation: animate-web-developer 10s linear infinite 1s;
}
/* Keyframes to Animate Web Developer */
@-webkit-keyframes animate-web-developer {
0%,
50%,
100% {
background-position: -27rem;
text-shadow: 0 0 0 var(--active-pure-color);
}
40%,
45%,
80%,
85% {
background-position: 0rem;
text-shadow: 0 0 30px var(--active-theme-color);
}
}
@keyframes animate-web-developer {
0%,
50%,
100% {
background-position: -27rem;
text-shadow: 0 0 0 var(--active-pure-color);
}
40%,
45%,
80%,
85% {
background-position: 0rem;
text-shadow: 0 0 30px var(--active-theme-color);
}
}
.hero-left .animate-web-developer::before {
content: "";
position: absolute;
width: 0;
height: 100%;
border-right: 2px solid var(--active-theme-color);
left: 0;
top: 0;
-webkit-animation: animate-cursor 10s linear infinite 1s;
animation: animate-cursor 10s linear infinite 1s;
}
/* Keyframes to Animate Cursor On Web Developer */
@-webkit-keyframes animate-cursor {
0%,
50%,
100% {
width: 0;
}
40%,
45%,
80%,
85% {
width: 100%;
}
}
@keyframes animate-cursor {
0%,
50%,
100% {
width: 0;
}
40%,
45%,
80%,
85% {
width: 100%;
}
}
.hero-left p {
font-size: 1.4rem;
color: var(--active-light-font-color);
text-align: justify;
}
/**********************************************************
Hero Btns Start
**********************************************************/
.hero-btn-box {
margin-top: 2rem;
gap: 1.7rem;
}
/**********************************************************
Hero Left End
**********************************************************/
/**********************************************************
Hero Right Start
**********************************************************/
.hero-right {
flex-basis: 50%;
}
.hero-right .hero-img-box {
box-shadow: 0 0 7rem var(--active-two-mode-shadow);
background-color: var(--active-theme-color);
border-radius: 1.5rem;
}
.hero-right .hero-img {
width: 30rem;
}
/**********************************************************
Hero Right End
**********************************************************/
/**********************************************************
Hero Container End
**********************************************************/
/**********************************************************
Home Page End
**********************************************************/
/**********************************************************
About Page Start
**********************************************************/
/**********************************************************
About Intro Start
**********************************************************/
.about-intro-heading {
margin-bottom: 1rem;
}
.about-intro p {
color: var(--active-light-font-color);
font-size: 1.5rem;
margin-bottom: 1.8rem;
}
/**********************************************************
About Intro End
**********************************************************/
/**********************************************************
About Infos Start
**********************************************************/
.about-infos-boxes {
align-items: flex-start;
gap: 1.5rem;
}
.about-info {
border-left: .5rem solid var(--active-theme-color);
background-color: var(--active-secondary-bg);
padding: 1.5rem;
flex: 1 1 300px;
box-shadow: 0 0 10px var(--active-one-mode-shadow);
}
.about-info .about-info-header {
position: relative;
}
.about-info .about-info-header h3 {
color: var(--active-dark-font-color);
font-size: 1.8rem;
letter-spacing: .6px;
word-spacing: 2px;
}
.about-info .about-info-header .about-info-open-btn {
position: absolute;
font-size: 1.6rem;
color: var(--active-light-font-color);
top: 0;
right: 0;
cursor: pointer;
transition: all .2s linear;
}
@media (hover:hover) {
.about-info .about-info-header .about-info-open-btn:hover {
color: var(--active-dark-font-color);
}
}
.about-info .about-info-content {
max-height: 0;
overflow: hidden;
transition: all .3s linear;
}
.about-info .about-info-content ul {
padding-top: 1rem;
}
.about-info .about-info-content ul li {
padding-block: .5rem;
}
.about-info .about-info-content ul li span:first-child {
color: var(--active-dark-font-color);
font-size: 1.2rem;
font-weight: 600;
font-family: var(--font-family-2);
letter-spacing: .3px;
margin-right: .5rem;
}
.about-info .about-info-content ul li span:last-child {
font-size: 1.2rem;
font-weight: 400;
font-family: var(--font-family-2);
letter-spacing: .3px;
color: var(--active-light-font-color);
}
/**********************************************************
About Infos End
**********************************************************/
/**********************************************************
Academics Start
**********************************************************/
.academics-boxes {
padding-left: 20rem;
gap: 4rem;
}
.academics-box {
color: var(--active-light-font-color);
padding: 2rem;
background: var(--active-secondary-bg);
position: relative;
border-left: .5rem solid var(--active-theme-color);
box-shadow: 0 0 1rem var(--active-one-mode-shadow);
}
.academics-box::before {
content: "";
position: absolute;
width: 20rem;
height: .5rem;
background-color: var(--active-theme-color);
top: 50%;
transform: translateY(-50%);
left: -20rem;
}
.academics-box::after {
content: "1";
position: absolute;
width: 4rem;
height: 4rem;
border-radius: 50%;
background-color: var(--active-theme-color);
top: 50%;
transform: translateY(-50%);
left: -20rem;
display: grid;
place-content: center;
font-size: 2rem;
font-family: var(--font-family-2);
color: var(--active-pure-color);
font-weight: 600;
}
.academics-box:nth-child(1):after {
content: "1";
}
.academics-box:nth-child(2):after {
content: "2";
}
.academics-box:nth-child(3):after {
content: "3";
}
.academics-box .academics-year {
color: var(--active-theme-color);
font-size: 1.2rem;
font-family: var(--font-family-2);
font-weight: 600;
margin-bottom: .8rem;
}
.academics-box h3 {
color: var(--active-dark-font-color);
font-size: 1.8rem;
margin-bottom: .5rem;
letter-spacing: .4px;
word-spacing: 2px;
}
.academics-box p {
color: var(--active-light-font-color);
font-size: 1.4rem;
}
/**********************************************************
Academics End
**********************************************************/
/**********************************************************
About Page End
**********************************************************/
/**********************************************************
Projects Page Start
**********************************************************/
/**********************************************************
Project Search Bar Start
**********************************************************/
.project-search-bar {
position: absolute;
top: calc(var(--pad-block + 5rem));
right: calc(var(--pad-inline) + 1rem);
background-color: var(--active-theme-color);
box-shadow: 0 0 .5rem var(--active-two-mode-shadow);
padding: 1rem 1.2rem;
display: flex;
align-items: center;
border-radius: 3rem;
color: var(--pure-black);
cursor: pointer;
}
.project-search-bar input {
background-color: transparent;
font-size: 1.5rem;
border: none;
padding-inline: 0;
font-family: var(--font-family-2);
font-weight: 500;
letter-spacing: .3px;
width: 25rem;
transition: all .4s linear;
max-width: 0;
}
.project-search-bar input input::placeholder {
color: var(--active-secondary-bg);
}
.project-search-bar:hover>input {
max-width: 25rem;
padding-inline: 1rem;
}
.project-search-bar i {
font-size: 2rem;
}
/**********************************************************
Project Search Bar Start
**********************************************************/
.all-projects-container {
margin-top: 15rem;
}
.inner-projects-container .projects-category-heading {
display: flex;
align-items: center;
gap: 1rem;
font-size: 2rem;
color: var(--active-theme-color);
margin-bottom: 2.8rem;
text-transform: uppercase;
letter-spacing: .5px;
word-spacing: 3px;
}
.projects-category-heading i {
display: grid;
place-content: center;
width: 3rem;
aspect-ratio: 1;
border-radius: 50%;
background-color: var(--active-theme-color);
font-size: 1.6rem;
box-shadow: 0 0 3rem var(--active-two-mode-shadow);
color: var(--pure-white);
}
.projects-boxes-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 2.8rem;
}
.projects-boxes-container .project-box {
background-color: var(--active-secondary-bg);
padding: 2.8rem;
box-shadow: 0 0 1rem var(--active-one-mode-shadow);
}
.projects-boxes-container .project-box.hide-project {
display: none;
}
.project-box .project-thumbnail-box {
width: 100%;
aspect-ratio: 4/3;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
position: relative;
cursor: pointer;
overflow: hidden;
}
.project-box .project-thumbnail-box img {
height: 100%;
}
.project-box .project-thumbnail-box::after {
content: "Review Me";
position: absolute;
color: var(--active-secondary-bg);
font-size: 1.8rem;
font-family: var(--font-family-1);
letter-spacing: .3px;
text-transform: uppercase;
font-weight: 800;
word-spacing: 2px;
display: flex;
justify-content: center;
align-items: flex-end;
padding-bottom: 1rem;
left: 0;
top: 100%;
width: 100%;
height: 100%;
background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.151), var(--active-theme-color));
transition: all .3s ease-out;
}
.projects-boxes-container .project-box:hover>.project-thumbnail-box::after {
top: 0;
}
.project-box .project-title {
font-size: 1.8rem;
color: var(--active-dark-font-color);
margin-block: 1rem 2rem;
letter-spacing: .4px;
word-spacing: 2px;
}
.project-box .project-view-btns-group {
display: flex;
justify-content: space-between;
align-items: center;
}
.project-view-btns-group .project-view-btn {
font-size: 1.3rem;
font-weight: 600;
letter-spacing: .6px;
color: var(--active-theme-color);
text-transform: capitalize;
display: flex;
align-items: center;
gap: .5rem;
}
.project-view-btns-group .project-view-btn i {
font-size: 1.1rem;
}
.more-projects-btn {
margin-top: 2.8rem;
}
/**********************************************************
Projects Page End
**********************************************************/
/**********************************************************
Pages Container End
**********************************************************/
/***********************************************************************************************
Actual Document Styling End
***********************************************************************************************/ |
import pygame as pg
import sys
import random
def main():
clock = pg.time.Clock()
# 練習1:スクリーンと背景画像
pg.display.set_caption("逃げろ!こうかとん")
screen_sfc = pg.display.set_mode((1600, 900)) # Surface
screen_rct = screen_sfc.get_rect() # Rect
bgimg_sfc = pg.image.load("fig/pg_bg.jpg") # Surface
bgimg_rct = bgimg_sfc.get_rect() # Rect
screen_sfc.blit(bgimg_sfc, bgimg_rct)
# 練習3:こうかとん
kkimg_sfc = pg.image.load("fig/6.png") # Surface
kkimg_sfc = pg.transform.rotozoom(kkimg_sfc, 0, 2.0) # Surface
kkimg_rct = kkimg_sfc.get_rect() # Rect
kkimg_rct.center = 900, 400
# 練習5:爆弾
bmimg_sfc = pg.Surface((20, 20)) # Surface
bmimg_sfc.set_colorkey((0, 0, 0))
pg.draw.circle(bmimg_sfc, (255, 0, 0), (10, 10), 10)
bmimg_rct = bmimg_sfc.get_rect() # Rect
bmimg_rct.centerx = random.randint(0, screen_rct.width)
bmimg_rct.centery = random.randint(0, screen_rct.height)
vx, vy = +1, +1 # 練習6
while True:
screen_sfc.blit(bgimg_sfc, bgimg_rct)
# 練習2
for event in pg.event.get():
if event.type == pg.QUIT: return
# 練習4
key_states = pg.key.get_pressed() # 辞書
if key_states[pg.K_UP] == True: kkimg_rct.centery -= 1
if key_states[pg.K_DOWN] == True: kkimg_rct.centery += 1
if key_states[pg.K_LEFT] == True: kkimg_rct.centerx -= 1
if key_states[pg.K_RIGHT] == True: kkimg_rct.centerx += 1
# 練習7
if check_bound(kkimg_rct, screen_rct) != (1, 1): # 領域外だったら
if key_states[pg.K_UP] == True: kkimg_rct.centery += 1
if key_states[pg.K_DOWN] == True: kkimg_rct.centery -= 1
if key_states[pg.K_LEFT] == True: kkimg_rct.centerx += 1
if key_states[pg.K_RIGHT] == True: kkimg_rct.centerx -= 1
screen_sfc.blit(kkimg_sfc, kkimg_rct)
# 練習6
bmimg_rct.move_ip(vx, vy)
# 練習5
screen_sfc.blit(bmimg_sfc, bmimg_rct)
# 練習7
yoko, tate = check_bound(bmimg_rct, screen_rct)
vx *= yoko
vy *= tate
# 練習8
if kkimg_rct.colliderect(bmimg_rct): return
pg.display.update()
clock.tick(1000)
# 練習7
def check_bound(rct, scr_rct):
'''
[1] rct: こうかとん or 爆弾のRect
[2] scr_rct: スクリーンのRect
'''
yoko, tate = +1, +1 # 領域内
if rct.left < scr_rct.left or scr_rct.right < rct.right : yoko = -1 # 領域外
if rct.top < scr_rct.top or scr_rct.bottom < rct.bottom: tate = -1 # 領域外
return yoko, tate
if __name__ == "__main__":
pg.init()
main()
pg.quit()
sys.exit() |
#pragma once
namespace bsc
{
template <typename T>
struct vec4
{
union
{
struct { T x, y, z, w; };
struct { T r, g, b, a; };
struct { T p, q, s, t; };
T data[4];
};
vec4 ( void );
vec4 ( T v );
vec4 ( T x, T y, T z, T w );
vec4 ( const vec4<T> &other );
vec4 ( const vec2<T> &other, const T v );
vec4 ( const vec2<T> &other, const T v1, const T v2 );
vec4 ( const vec3<T> &other, const T v );
vec4 ( const T v, const vec3<T> &other );
vec4<T> & operator= ( const vec4<T> & v );
void operator+= ( const vec4<T> & other );
void operator+= ( const T constant );
void operator-= ( const vec4<T> & other );
void operator-= ( const T constant );
void operator*= ( const vec4<T> & other );
void operator*= ( const T constant );
void operator/= ( const vec4<T> & other );
void operator/= ( const T constant );
bool operator== ( const vec4<T> & other ) const;
bool operator!= ( const vec4<T> & other ) const;
T operator[] ( unsigned int i ) const;
T& operator[] ( unsigned int i );
const constexpr int size() const { return 4; }
};
template <typename T>
vec4<T> ::
vec4 ( void ) : x( (T)0 ), y( (T)0 ), z( (T)0 ), w( (T)0 )
{}
template <typename T>
vec4<T> ::
vec4 ( T v ) : x( v ), y( v ), z( v ), w( v )
{}
template <typename T>
vec4<T> ::
vec4 ( T x, T y, T z, T w ) : x( x ), y( y ), z( z ), w( w )
{}
template <typename T>
vec4<T> ::
vec4 ( const vec4<T> &other ) : x( other.x ), y( other.y ), z( other.z ), w( other.w )
{}
template <typename T>
vec4<T> ::
vec4( const vec2<T> &other, const T v ) : x( other.x ), y( other.y ), z( v ), w( v )
{}
template <typename T>
vec4<T> ::
vec4 ( const vec2<T> &other, const T v1, const T v2 ) : x( other.x ), y( other.y ), z( v1 ), w( v2 )
{}
template <typename T>
vec4<T> ::
vec4 ( const vec3<T> &other, const T v ) : x( other.x ),y( other.y ), z( other.z ), w( v ) {}
template <typename T>
vec4<T> ::
vec4 ( const T v, const vec3<T> &other ) : x( v ), y( other.x ), z( other.y ), w( other.z )
{}
template <typename T>
inline vec4<T> & vec4<T> ::
operator= ( const vec4<T> & v)
{
this->x = v.x;
this->y = v.y;
this->z = v.z;
this->w = v.w;
return *this;
}
template <typename T>
inline void vec4<T> ::
operator+= ( const vec4<T> & other )
{
this->x += other.x;
this->y += other.y;
this->z += other.z;
this->w += other.w;
}
template <typename T>
inline void vec4<T> ::
operator+= ( const T constant )
{
this->x += constant;
this->y += constant;
this->z += constant;
this->w += constant;
}
template <typename T>
inline vec4<T>
operator+ ( const vec4<T> & v1, const vec4<T> & v2 )
{
vec4<T> result( v1.x + v2.x,
v1.y + v2.y,
v1.z + v2.z,
v1.w + v2.w );
return result;
}
template <typename T>
inline vec4<T>
operator+ ( const vec4<T> & v, const T constant )
{
vec4<T> result( v.x + constant,
v.y + constant,
v.z + constant,
v.w + constant );
return result;
}
template <typename T>
inline vec4<T>
operator+ ( const T constant, const vec4<T> & v )
{
vec4<T> result( v.x + constant,
v.y + constant,
v.z + constant,
v.w + constant );
return result;
}
template <typename T>
inline void vec4<T> ::
operator-= ( const vec4<T> & other )
{
this->x -= other.x;
this->y -= other.y;
this->z -= other.z;
this->w -= other.w;
}
template <typename T>
inline void vec4<T> ::
operator-= ( const T constant )
{
this->x -= constant;
this->y -= constant;
this->z -= constant;
this->w -= constant;
}
template <typename T>
inline vec4<T>
operator- ( const vec4<T> & v1, const vec4<T> & v2 )
{
vec4<T> result( v1.x - v2.x,
v1.y - v2.y,
v1.z - v2.z,
v1.w - v2.w );
return result;
}
template <typename T>
inline vec4<T>
operator- ( const vec4<T> & v, const T constant )
{
vec4<T> result( v.x - constant,
v.y - constant,
v.z - constant,
v.w - constant );
return result;
}
template <typename T>
inline vec4<T>
operator- ( const T constant, const vec4<T> & v )
{
vec4<T> result( constant - v.x,
constant - v.y,
constant - v.z,
constant - v.w );
return result;
}
template <typename T>
inline vec4<T>
operator- ( const vec4<T> & v )
{
vec4<T> result( -v.x,
-v.y,
-v.z,
-v.w );
return result;
}
template <typename T>
inline void vec4<T> ::
operator*= ( const vec4<T> & other )
{
this->x *= other.x;
this->y *= other.y;
this->z *= other.z;
this->w *= other.w;
}
template <typename T>
inline void vec4<T> ::
operator*= ( const T constant )
{
this->x *= constant;
this->y *= constant;
this->z *= constant;
this->w *= constant;
}
template <typename T>
inline vec4<T>
operator* ( const vec4<T> & v1, const vec4<T> & v2 )
{
vec4<T> result( v1.x * v2.x,
v1.y * v2.y,
v1.z * v2.z,
v1.w * v2.w );
return result;
}
template <typename T>
inline vec4<T>
operator* ( const vec4<T> & v, const T constant )
{
vec4<T> result( v.x * constant,
v.y * constant,
v.z * constant,
v.w * constant );
return result;
}
template <typename T>
inline vec4<T>
operator* ( const T constant, const vec4<T> & v )
{
vec4<T> result( v.x * constant,
v.y * constant,
v.z * constant,
v.w * constant );
return result;
}
template <typename T>
inline void vec4<T> ::
operator/= ( const vec4<T> & other )
{
this->x /= other.x;
this->y /= other.y;
this->z /= other.z;
this->w /= other.w;
}
template <typename T>
inline void vec4<T> ::
operator/= ( const T constant )
{
T inv_constant = 1.0f / constant;
this->x *= inv_constant;
this->y *= inv_constant;
this->z *= inv_constant;
this->w *= inv_constant;
}
template <typename T>
inline vec4<T>
operator/ ( const vec4<T> & v1, const vec4<T> & v2 )
{
vec4<T> result( v1.x / v2.x,
v1.y / v2.y,
v1.z / v2.z,
v1.w / v2.w );
return result;
}
template <typename T>
inline vec4<T>
operator/ ( const vec4<T> & v, const T constant )
{
vec4<T> result( v.x / constant,
v.y / constant,
v.z / constant,
v.w / constant );
return result;
}
template <typename T>
inline vec4<T>
operator/ ( const T constant, const vec4<T> & v )
{
vec4<T> result( constant / v.x,
constant / v.y,
constant / v.z,
constant / v.w );
return result;
}
template <typename T>
inline T vec4<T> ::
operator[] ( unsigned int i ) const
{
return this->data[ i ];
}
template <typename T>
inline T& vec4<T> ::
operator[] ( unsigned int i )
{
return this->data[ i ];
}
template <typename T>
inline bool vec4<T> ::
operator== ( const vec4<T>& other ) const
{
if ( this->x == other.x &&
this->y == other.y &&
this->z == other.z &&
this->w == other.z )
{
return true;
}
else
{
return false;
}
}
template <typename T>
inline bool vec4<T> ::
operator!= ( const vec4<T>& other ) const
{
return !(*this == other);
}
} |
<template>
<div class="container2">
<div class="login-form" style="max-width: 500px;">
<ValidationObserver v-slot="{ invalid }">
<form @submit.prevent="registers">
<h1 style="margin-left:42px">ĐĂNG KÝ</h1>
<div class="input-box">
<b>Tên đăng nhập</b>
<ValidationProvider
v-slot="{ errors }"
rules="required|alpha-num"
name="Tên đăng nhập">
<input name="customerusername" v-model="dataSubmit.customername" type="text" placeholder="Nhập tên đăng nhập" >
<p class="muted text-danger">
{{ errors[0] }}
</p>
</ValidationProvider>
</div>
<div class="input-box">
<b style="margin-right:42px">Mật khẩu</b>
<ValidationProvider
v-slot="{ errors }"
rules="required|min:6"
name="Mật khẩu ">
<input name="customerpassword" v-model="dataSubmit.customerpassword" type="password" placeholder="Nhập mật khẩu">
<p class="muted text-danger">
{{ errors[0] }}
</p>
</ValidationProvider>
</div>
<div class="input-box">
<b style="margin-right:72px">Email</b>
<ValidationProvider
v-slot="{ errors }"
rules="required|email"
name="Email " >
<input name="customerEmail" v-model="dataSubmit.customeremail" type="text" placeholder="Nhập Email">
<p class="muted text-danger">
{{ errors[0] }}
</p>
</ValidationProvider>
</div>
<div class="input-box">
<b style="margin-right:14px">Số điện thoại</b>
<ValidationProvider
v-slot="{ errors }"
rules="required|max:10|min:9|num"
name="Số điện thoai " >
<input name="customernumber" v-model="dataSubmit.customernumber" type="text" placeholder="Nhập số điện thoại">
<p class="muted text-danger">
{{ errors[0] }}
</p>
</ValidationProvider>
</div>
<div class="btn-box">
<button class="btn-submit" :disabled="invalid" type="submit" >
Đăng ký
</button>
</div>
</form>
</ValidationObserver>
</div>
</div>
</template>
<script>
import { extend } from 'vee-validate';
import Apidata from '@/api/Apidata'
extend('alpha', {
validate(value) {
const nameformat = /^[A-Za-z ]+$/i
if(!nameformat.test(value)) {
return 'Chỉ cho phép kí tự chữ cái'
}
else return true
},
});
extend('alpha-num', {
validate(value) {
const usernameformat = /^[a-z0-9]+$/i
if(!usernameformat.test(value)) {
return 'Chỉ cho phép kí tự chữ cái và số'
}
else return true
},
});
extend('num', {
validate(value) {
const phone = /^[0-9]+$/
if(!phone.test(value)) {
return 'Chỉ cho phép kí tự số'
}
else return true
},
});
export default {
layout: 'default',
data(){
return{
dataSubmit:{
customername: '',
customeremail: '',
customernumber: '',
customerpassword: '',
}
}
},
methods:{
async registers() {
try {
await Apidata.register(this.$axios, this.dataSubmit)
alert("Bạn đã đăng kí thành công.")
this.$router.push(`/login`)
} catch (err) {
alert('Tài khoản hoặc Email đã tồn tại, vui lòng nhập lại!')
}
}
}
}
</script>
<style scoped>
.main{
background-color: #a7dfca;
min-height: 500px;
padding: 7.5px 15px;
}
.containerf{
margin-top: 50px;
margin-bottom: 50px;
}
.login-form{
width: 100%;
max-width: 400px;
margin: 20px auto;
background-color: #ffffff;
padding: 15px;
border: 2px solid #000000;
border-radius: 10px;
min-height: 550px;
}
h1{
color: #000000;
font-size: 20px;
margin-bottom: 30px;
text-align: center;
font-family: sans-serif;
font-size: 35px;
margin-left: 100px;
}
i, span {
display: block;
}
.input-box input{
padding: 6px 14px;
width: 100%;
border: 1px solid #cccccc;
outline: none;
}
.btn-box{
text-align: right;
margin-top: 30px;
}
.btn-box button {
padding: 7.5px 15px;
border-radius: 5px;
background-color: #002fc9;
color: #ffffff;
border: none;
outline: none;
}
.btn-submit:disabled {
background-color: #cccccc;
}
.container2 {
background-color: #a7dfca;
/* background: linear-gradient(120deg, #9b59b6, #3498db); */
padding-top: 1px;
padding-bottom: 1px;
}
</style> |
package com.example.greenwizard.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import com.example.greenwizard.data.LocationDatabase
import com.example.greenwizard.model.RecyclePoint
import com.example.greenwizard.repository.LocationRepository
import com.example.greenwizard.model.Report
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class LocationViewModel(application: Application) : AndroidViewModel(application) {
val readAllData: LiveData<List<Report>> // Change visibility to public
val readAllRecycleData: LiveData<List<RecyclePoint>> // Change visibility to public
private val repository: LocationRepository
init {
val locationDao = LocationDatabase.getDatabase(application).LocationDao()
repository = LocationRepository(locationDao)
readAllData = repository.readAllData
readAllRecycleData = repository.readAllRecycleData
}
//Illegal Dump Report
fun addReport(report: Report) {
viewModelScope.launch(Dispatchers.IO) {
repository.addReport(report)
}
}
fun updateReport(report: Report) {
viewModelScope.launch(Dispatchers.IO) {
repository.updateReport(report)
}
}
fun deleteReport(report: Report) {
viewModelScope.launch(Dispatchers.IO) {
repository.deleteReport(report)
}
}
//RecyclePoint
fun addRecycle(recyclePoint: RecyclePoint) {
viewModelScope.launch(Dispatchers.IO) {
repository.addRecycle(recyclePoint)
}
}
fun updateRecycle(recyclePoint: RecyclePoint) {
viewModelScope.launch(Dispatchers.IO) {
repository.updateRecycle(recyclePoint)
}
}
fun deleteRecycle(recyclePoint: RecyclePoint) {
viewModelScope.launch(Dispatchers.IO) {
repository.deleteRecycle(recyclePoint)
}
}
} |
import { useKeenSlider } from 'keen-slider/react';
import React, { useEffect, useState } from 'react';
import { Spinner } from 'react-activity';
import { Link, useParams, useSearchParams } from 'react-router-dom'
import AdCard from '../components/AdCard';
import { getAds } from './../api';
import { ArrowArcLeft, Check } from 'phosphor-react'
import { useWindowSize } from '../util/useWindowSize';
import { FilterInput } from '../components/FilterInput';
import * as Checkbox from '@radix-ui/react-checkbox'
import * as ToggleGroup from '@radix-ui/react-toggle-group';
import ToggleGroupItems from '../components/Form/ToggleGroupItems';
export type Ad = {
id: string,
name: string,
weekDays: string[],
useVoiceChannel: boolean,
yearsPlaying: number,
hourStart: string,
hourEnd: string,
createdAt: string
}
function Ads() {
const size = useWindowSize().width > 640
let { id } = useParams();
const [searchParams] = useSearchParams();
let title = searchParams.get("game");
let banner = searchParams.get("banner");
const [ads, setAds] = useState<Ad[]>([]);
const [fetchFlag, setFetchFlag] = useState(false);
const [filterInputYears, setFilterInputYears] = useState<string>("");
const [filterInputWeek, setFilterInputWeek] = useState<string[]>([]);
const [filterInputVoice, setFilterInputVoice] = useState<boolean>(false);
const [sliderRef, instanceRef] = useKeenSlider<HTMLDivElement>(
{
loop: false,
mode: "free-snap",
slides: {
origin: size ? "auto" : "center",
perView: 'auto',
spacing: 30
},
}, [])
useEffect(() => {
setTimeout(function () {
getAds(id as string).then(data => {
setAds(data)
setFetchFlag(true)
})
}, 1000)
document.title = "NLW eSports - " + title
}, [])
useEffect(() => {
setTimeout(function () {
instanceRef.current?.update
}, 500)
instanceRef.current?.update()
}, [filterInputYears, filterInputVoice, filterInputWeek])
return (
<div className='max-w-[88%] mx-auto flex flex-col sm:flex-row items-center m-20'>
<div>
<div className='flex self-stretch justify-center'>
<img src={banner as string} className="h-64 2xl:h-auto" />
</div>
<h1 className='text-3xl text-white font-semibold mt-10 text-center sm:text-left'>
<span>{title}</span>
<p className='text-lg'>Conecte-se e comece a jogar!</p>
</h1>
</div>
<div className='max-w-full sm:pl-20 w-[100%]'>
<div className='flex self-stretch justify-center sm:justify-start'>
<Link to={'/'} className='text-sm mt-3 sm:mt-0 sm:text-base py-2 px-3 sm:py-3 sm:px-4 bg-violet-500 hover:bg-violet-600 text-white rounded flex center items-center gap-3'>
<ArrowArcLeft size={24} />
{size ? "voltar" : ""}
</Link>
</div>
{ads.length == 0 ? (
!fetchFlag ?
<div className='mt-14 flex items-center self-stretch justify-center align-middle h-[276.66px]'>
<Spinner size={25} color={"white"} />
</div>
:
<div className='mt-14 flex items-start align-middle h-[276.66px]'>
<span className='text-white'>Esse jogo ainda não possui nenhum anúncio publicado.</span>
</div>
)
:
<div ref={sliderRef} className='keen-slider mt-8 self-stretch h-[276.66px]'>
{ads.filter(ad => {
if (ad.yearsPlaying >= parseInt(filterInputYears) || filterInputYears == "")
return ad
}).filter(ad => {
if (ad.useVoiceChannel || !filterInputVoice)
return ad
}).filter(ad => {
let aux = true
for(let x = 0; x < filterInputWeek.length; x++)
if (!ad.weekDays.toString().includes(filterInputWeek[x]))
aux = false
if (aux) return ad
}).map((ad) => {
return (
<AdCard key={ad.id} data={ad} />
)
})}
</div>}
<div className='flex flex-col w-full justify-center content-center sm:flex-row sm:justify-start mt-2 py-6'>
<div className='flex justify-center sm:mr-6'>
<div className='flex items-center'>
<FilterInput placeholder="Time playing" type="number" min="0" max="50" onChange={(event: React.ChangeEvent<HTMLInputElement>) => setFilterInputYears(event.target.value)} />
</div>
</div>
<div className='flex justify-center text-white mt-4 sm:mt-0 sm:mr-6'>
<ToggleGroup.Root
type="multiple"
className="grid grid-cols-4 gap-2 items-center"
value={filterInputWeek}
onValueChange={setFilterInputWeek}
>
<ToggleGroupItems weekDays={filterInputWeek} bg="bg-zinc-700" />
</ToggleGroup.Root>
</div>
<div className='flex justify-center mt-4 sm:mt-0'>
<label className="flex gap-2 text-sm items-center text-white">
<Checkbox.Root
onCheckedChange={() => setFilterInputVoice(!filterInputVoice)}
className="w-6 h-6 p-1 rounded bg-zinc-700"
>
<Checkbox.Indicator>
<Check className="w-4 h-4 text-emerald-400" />
</Checkbox.Indicator>
</Checkbox.Root>
Uses voice channel
</label>
</div>
</div>
</div>
</div>
);
}
export default Ads |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
import oci # noqa: F401
from oci.util import WAIT_RESOURCE_NOT_FOUND # noqa: F401
class TransferPackageClientCompositeOperations(object):
"""
This class provides a wrapper around :py:class:`~oci.dts.TransferPackageClient` and offers convenience methods
for operations that would otherwise need to be chained together. For example, instead of performing an action
on a resource (e.g. launching an instance, creating a load balancer) and then using a waiter to wait for the resource
to enter a given state, you can call a single method in this class to accomplish the same functionality
"""
def __init__(self, client, **kwargs):
"""
Creates a new TransferPackageClientCompositeOperations object
:param TransferPackageClient client:
The service client which will be wrapped by this object
"""
self.client = client
def create_transfer_package_and_wait_for_state(self, id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.dts.TransferPackageClient.create_transfer_package` and waits for the :py:class:`~oci.dts.models.TransferPackage` acted upon
to enter the given state(s).
:param str id: (required)
ID of the Transfer Job
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.dts.models.TransferPackage.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.dts.TransferPackageClient.create_transfer_package`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.create_transfer_package(id, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_transfer_package(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def update_transfer_package_and_wait_for_state(self, id, transfer_package_label, update_transfer_package_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.dts.TransferPackageClient.update_transfer_package` and waits for the :py:class:`~oci.dts.models.TransferPackage` acted upon
to enter the given state(s).
:param str id: (required)
ID of the Transfer Job
:param str transfer_package_label: (required)
Label of the Transfer Package
:param oci.dts.models.UpdateTransferPackageDetails update_transfer_package_details: (required)
fields to update
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.dts.models.TransferPackage.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.dts.TransferPackageClient.update_transfer_package`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.update_transfer_package(id, transfer_package_label, update_transfer_package_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_transfer_package(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e) |
import React, { useEffect, useState } from 'react'
import { Form, Input, message, Select } from 'antd'
import { ButtonDanger, ButtonPrimary } from '@components/button/ButtonCustom'
import FormCustom from '@components/form/FormCustom'
import ModalCustom from '@components/modal/ModalCustom'
import UploadImage from '@components/uploadImage/UploadImage'
import adminService from '@api/adminAPI'
function ModalUpdateMovie(props) {
const { visible, setVisible, initialValues, fetchMovieData } = props
const [url, setUrl] = useState()
const [form] = Form.useForm()
const handleCancel = () => {
form.resetFields()
setVisible(false)
}
const handleUpdateMovie = (values) => {
const newData = {
...values,
image: url,
releaseDate: (new Date(values.releaseDate).getTime()).toString(),
}
adminService.updateMovieBasic(newData, true)
.then((res) => {
if (res.data.updateMovieBasic) {
message.success('Update successfully')
fetchMovieData()
setVisible(false)
} else {
message.error('Update failed!')
}
})
}
useEffect(() => {
form.setFieldsValue(initialValues)
}, [form, initialValues])
return (
<ModalCustom
title={null}
footer={null}
visible={visible}
onCancel={handleCancel}
getContainer={false}
forceRender
>
<FormCustom
form={form}
initialValues={initialValues}
labelCol={{ span: 6 }}
wrapperCol={{ span: 18 }}
onFinish={handleUpdateMovie}
>
<h3 className='text-2xl text-center text-text-color-secondary'>Editing Basic Info</h3>
<Form.Item
label='Movie ID'
name='id'
>
<Input disabled className='text-right' />
</Form.Item>
<Form.Item
label='Title'
name='title'
>
<Input className='text-right' />
</Form.Item>
<Form.Item
label='Director'
name='director'
>
<Input className='text-right' />
</Form.Item>
<UploadImage label='image' name='image' url={initialValues?.image} setUrl={setUrl} />
<Form.Item
label='Release Date'
name='releaseDate'
>
<Input type='date' className='text-right' />
</Form.Item>
<Form.Item
label='Price'
name='price'
>
<Input className='text-right' />
</Form.Item>
<Form.Item
label='Status'
name='status'
>
<Select className='text-right' theme='dark'>
<Select.Option value='Released'>Released</Select.Option>
<Select.Option value='Upcoming'>Upcoming</Select.Option>
</Select>
</Form.Item>
<Form.Item
label='Description'
name='description'
>
<Input.TextArea autoSize={{ minRows: 4, maxRows: 7 }} />
</Form.Item>
<div className='w-full flex justify-center'>
<div className='w-full flex justify-center space-x-40'>
<ButtonDanger
type='button'
onClick={handleCancel}
>
Cancel
</ButtonDanger>
<ButtonPrimary
type='submit'
>
Update
</ButtonPrimary>
</div>
</div>
</FormCustom>
</ModalCustom>
)
}
export default ModalUpdateMovie |
package controller;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Scanner;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import entity.Task;
import impl.TaskDAOImpl;
import entity.TaskInfo;
public class ToDoListAppConsoleV2 {
private static EntityManagerFactory entityManagerFactory;
private static TaskDAOImpl taskDAO;
public static void main() {
entityManagerFactory = Persistence.createEntityManagerFactory("todolist");
taskDAO = new TaskDAOImpl(entityManagerFactory);
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("#### To Do List ####");
System.out.println("1. Ajouter une tâche à la liste");
System.out.println("2. Afficher toutes les tâches de la liste");
System.out.println("3. Marquer une tâche comme terminée");
System.out.println("4. Supprimer une tâche de la liste");
System.out.println("5. Modifier une tâche");
System.out.println("6. Modifier les informations d'une tâche");
System.out.println("7. Quitter l'application");
System.out.println("Choix : ");
choice = scanner.nextInt();
scanner.nextLine(); // Consomme la nouvelle ligne
switch (choice) {
case 1:
addTask(scanner);
break;
case 2:
displayTasks();
break;
case 3:
markTaskAsCompleted(scanner);
break;
case 4:
deleteTask(scanner);
break;
case 5:
updateTask(scanner);
break;
case 6:
updateTaskInfo(scanner);
break;
case 7:
System.out.println("Bye");
entityManagerFactory.close();
break;
default:
System.out.println("Choix invalide. Veuillez réessayer.");
}
} while (choice != 7);
}
private static void addTask(Scanner scanner) {
System.out.println("Entrer le titre de la tâche : ");
String title = scanner.nextLine();
System.out.println("Entrer la description de la tâche : ");
String description = scanner.nextLine();
System.out.println("Date limite de la tâche : (dd.MM.yyyy)");
String dueDateStr = scanner.nextLine();
LocalDate dueDate = LocalDate.parse(
dueDateStr,
DateTimeFormatter.ofPattern("dd.MM.yyyy")
);
System.out.println("Priorité de la tâche : ");
int priority = scanner.nextInt();
scanner.nextLine();
// Creation de la tache
Task task = new Task();
task.setTitle(title);
task.setCompleted(false);
//Creation de la taskinfo
TaskInfo taskInfo = new TaskInfo(description, dueDate, priority);
// Mise en relation
task.setTaskInfo(taskInfo);
taskInfo.setTask(task);
if (taskDAO.addTask(task)) {
System.out.println("Tâche ajoutée avec succès !");
} else {
System.out.println("Erreur");
}
}
private static void displayTasks() {
List<Task> tasks = taskDAO.getAllTasks();
if (tasks.isEmpty()) {
System.out.println("Aucune tâche trouvée.");
} else {
System.out.println("=== Liste des tâches ===");
for (Task task : tasks) {
System.out.println("###########");
System.out.println(
task.getId() +
". " +
task.getTitle() +
" (" +
(task.isCompleted() ? "Terminée" : "En cours") +
")"
);
System.out.println(task.getTaskInfo().toString());
System.out.println("###########");
}
}
}
private static void updateTask(Scanner scanner) {
System.out.println("Entrez l'ID de la tâche à modifier : ");
Long taskId = scanner.nextLong();
scanner.nextLine();
Task task = taskDAO.findTaskById(taskId);
if (task == null) {
System.out.println("Tâche non trouvée.");
return;
}
System.out.println("Entrez le nouveau titre de la tâche (actuel: " + task.getTitle() + ") :");
String title = scanner.nextLine();
task.setTitle(title);
if (taskDAO.updateTask(task)) {
System.out.println("Tâche mise à jour avec succès.");
} else {
System.out.println("Erreur lors de la mise à jour de la tâche.");
}
}
private static void updateTaskInfo(Scanner scanner) {
System.out.println("Entrez l'ID de la tâche dont vous voulez modifier les informations : ");
Long taskId = scanner.nextLong();
scanner.nextLine();
Task task = taskDAO.findTaskById(taskId);
if (task == null || task.getTaskInfo() == null) {
System.out.println("Tâche ou informations de tâche non trouvées.");
return;
}
TaskInfo taskInfo = task.getTaskInfo();
System.out.println("Entrez la nouvelle description (actuelle: " + taskInfo.getDescription() + ") :");
String description = scanner.nextLine();
taskInfo.setDescription(description);
System.out.println("Date limite de la tâche (actuelle: " + taskInfo.getDueDate() + ") : (dd.MM.yyyy)");
String dueDateStr = scanner.nextLine();
LocalDate dueDate = LocalDate.parse(dueDateStr, DateTimeFormatter.ofPattern("dd.MM.yyyy"));
taskInfo.setDueDate(dueDate);
System.out.println("Priorité de la tâche (actuelle: " + taskInfo.getPriority() + ") : ");
int priority = scanner.nextInt();
scanner.nextLine();
taskInfo.setPriority(priority);
if (taskDAO.updateTaskInfo(taskInfo)) {
System.out.println("Informations de la tâche mises à jour avec succès.");
} else {
System.out.println("Erreur lors de la mise à jour des informations de la tâche.");
}
}
private static void deleteTask(Scanner scanner) {
System.out.println("Entrez l'ID de la tâche à supprimer : ");
Long taskId = scanner.nextLong();
scanner.nextLine();
if (taskDAO.deleteTask(taskId)) {
System.out.println("Suppression OK");
} else {
System.out.println("Erreur");
}
}
private static void markTaskAsCompleted(Scanner scanner) {
System.out.println("Entrez l'ID de la tâche à supprimer : ");
Long taskId = scanner.nextLong();
scanner.nextLine();
if (taskDAO.markTaskAsCompleted(taskId)) {
System.out.println("Modification OK");
} else {
System.out.println("Erreur");
}
}
} |
/* eslint-disable no-unused-vars */
import React, { useContext } from 'react';
import { Button, Container, Form, Nav, Navbar } from 'react-bootstrap';
import logo from '../../assets/icons/calender_icon.png'
import { AuthContext } from '../../Providers/AuthProvider';
import { Link } from 'react-router-dom';
const Header = () => {
const { user, logOut,loading } = useContext(AuthContext)
console.log(user);
const handleLogOut = () => {
logOut()
.then(()=>{
console.log('successfully logout');
})
.catch(error=>{
console.log(error.message);
})
}
return (
<Navbar expand="lg">
<Container >
<Navbar.Brand href="#">
<img src={logo} alt="" />
</Navbar.Brand>
<Form className="ms-4">
<Form.Control
type="search"
placeholder="Search"
className="me-2"
aria-label="Search"
/>
</Form>
<Navbar.Toggle aria-controls="navbarScroll" />
<Navbar.Collapse id="navbarScroll">
<Nav
className="ms-auto my-2 my-lg-0 "
style={{ maxHeight: '100px' }}
navbarScroll
>
<Nav.Link href="#action1" className=''>News</Nav.Link>
<Nav.Link href="#action2" className=''>Destination</Nav.Link>
<Nav.Link href="#action2" className=''>Blog</Nav.Link>
<Nav.Link href="#action2" className=''>Contact</Nav.Link>
{
user ?
<>
<span className='p-2 text-warning'>WelCome, { user && user.displayName }</span>
<Button variant='warning' onClick={handleLogOut} >LogOut</Button>
</> :
<Link to='/login/login'><Button variant='warning' >Login</Button></Link>
}
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
);
};
export default Header; |
using Application.Commons;
using Application.IServices;
using DataAccess;
using Domain.Entities.Groups;
using Domain.Enums;
using Infrastructure.IRepositories.Groups;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Infrastructure.Repositories.Groups {
public class AccountInGroupRepository : GenericRepository<AccountInGroup>, IAccountInGroupRepository {
private readonly AppDBContext _dbContext;
public AccountInGroupRepository(IClaimService claimService):base(claimService) {
_dbContext = new AppDBContext();
}
public async Task<AccountInGroup?> GetAccountInGroupAsync(Guid accountId, Guid groupId) {
return await _dbContext.AccountInGroups.FirstOrDefaultAsync(x => x.AccountId == accountId && x.GroupId == groupId);
}
public async Task<Pagination<AccountInGroup>?> GetAccountListInGroupPaginationAsync(Guid groupId, int pageIndex, int pageSize) {
var list = _dbContext.AccountInGroups.Where(x => x.GroupId == groupId).Include(x => x.Account).OrderByDescending(x => x.CreationDate);
var itemCount = await list.CountAsync();
var accounts = await list.Skip(pageIndex * pageSize).Take(pageSize).ToListAsync();
var pagination = new Pagination<AccountInGroup> {
TotalItemsCount = itemCount,
PageSize = pageSize,
PageIndex = pageIndex,
Items = accounts
};
return pagination;
}
public async Task<Pagination<AccountInGroup>?> GetAccountListInGroupPaginationSearchAsync(Guid groupId, int pageIndex, int pageSize, string searchValue) {
var list = _dbContext.AccountInGroups.Where(x => x.GroupId == groupId).Include(x => x.Account)
.Where(x => x.Account.Username.Contains(searchValue) || x.Account.Email.Contains(searchValue))
.OrderByDescending(x => x.CreationDate);
var itemCount = await list.CountAsync();
var accounts = await list.Skip(pageIndex * pageSize).Take(pageSize).ToListAsync();
var pagination = new Pagination<AccountInGroup> {
TotalItemsCount = itemCount,
PageSize = pageSize,
PageIndex = pageIndex,
Items = accounts
};
return pagination;
}
public async Task<bool> AddAccountInGroupAsync(string username, Guid groupId) {
var account = _dbContext.Accounts.Where(x => x.Username == username).FirstOrDefault();
if (account == null) {
return false;
} else {
if (_dbContext.AccountInGroups.Where(x => x.GroupId == groupId && x.AccountId == account.Id).Any())
return false;
AccountInGroup accountInGroup = new AccountInGroup {
Role = Domain.Enums.RoleEnum.Member,
AccountId = account.Id,
GroupId = groupId
};
await _dbContext.AccountInGroups.AddAsync(accountInGroup);
await _dbContext.SaveChangesAsync();
return true;
}
}
public async Task RemoveAccountInGroupAsync(Guid accountId, Guid groupId) {
var account = _dbContext.AccountInGroups.Where(x => x.AccountId == accountId && x.GroupId == groupId).FirstOrDefault();
if (account != null) {
_dbContext.AccountInGroups.Remove(account);
await _dbContext.SaveChangesAsync();
}
}
public async Task ChangeRoleAccountInGroupAsync(Guid accountId, Guid groupId, RoleEnum role) {
var account = _dbContext.AccountInGroups.Where(x => x.AccountId == accountId && x.GroupId == groupId).FirstOrDefault();
if (account != null) {
account.Role = role;
_dbContext.AccountInGroups.Update(account);
await _dbContext.SaveChangesAsync();
}
}
}
} |
using BlazorTraining.WebApi.Features.Blog;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DbConnection"));
},
ServiceLifetime.Transient,
ServiceLifetime.Transient);
builder.Services.AddScoped<BlogDataAccess>();
builder.Services.AddScoped<BlogBusinessLogic>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run(); |
import Meta from '../components/Meta';
import EmptyBox from '../components/EmptyBox';
import { useState } from 'react';
function Watermark(){
const [imageurl, setImageurl] = useState(null);
const [loaded, setLoaded] = useState(false);
const metaDatas = {
title: "블록툴툴 워터마크",
description: "블록툴툴 워터마크",
canonical: "https://blogtooltool.github.io/watermark",
meta: {
charset: "utf-8",
name: {
keywords: "블록툴툴, 워터마크, 물방울, 물방울로고, 물방울로고생성기, 로고, 로고생성기, 로고만들기, 물방울로고만들기"
},
property: {
"og:type": "website",
"og:title": "블록툴툴 워터마크",
"og:description": "블록툴툴 워터마크",
"og:url": "https://blogtooltool.github.io/watermark",
"og:image": "https://blogtooltool.github.io/watermark/logo.png"
},
itemProp: {
name: "블록툴툴 워터마크",
description: "블록툴툴 워터마크",
image: "https://blogtooltool.github.io/watermark/logo.png"
},
"twitter:card": "summary_large_image",
"twitter:title": "블록툴툴 워터마크",
"twitter:description": "블록툴툴 워터마크",
"twitter:image": "https://blogtooltool.github.io/watermark/logo.png"
}
};
function ImageFileOpen() {
const file = document.createElement("input");
file.type = "file";
file.accept = "image/*";
file.onchange = function (event) {
const file = event.target.files[0];
setLoaded(false);
setImageurl(URL.createObjectURL(file));
}
file.click();
}
function ImageDragOver(event) {
event.preventDefault();
}
function ImageFileDrop(event) {
event.preventDefault();
if (event.dataTransfer.files.length === 0) {
return;
}
if (event.dataTransfer.files[0].type.indexOf("image") === -1) {
return;
}
const file = event.dataTransfer.files[0];
setLoaded(false);
setImageurl(URL.createObjectURL(file));
}
function Imageclick(event) {
ImageFileOpen();
}
return (
<>
<Meta data={metaDatas} />
<div>
<h1>Watermark</h1>
<p>Add watermark in image</p>
{imageurl == null?
<div><EmptyBox onClick={ImageFileOpen} onDragOver={ImageDragOver} onDrop={ImageFileDrop} /> </div> :
<div>
<img src={imageurl} alt="이미지" onClick={Imageclick} onDragOver={ImageDragOver} onDrop={ImageFileDrop} />
</div>
}
</div>
</>
)
}
export default Watermark; |
# Backend
Backend service for the game. Computes the bot player's next move in the game board. This is done by applying the minimax algorithm with alpha-beta pruning.
## Development
Run `cargo run` to start the server.
By default the server is bound to 0.0.0.0:8080 but during development one may want to modify these values e.g. due to security concerns. Following command shows how to start the server bound to a standard IPv4 loopback address
```bash
ADDR=127.0.0.1 PORT=8080 cargo run
```
In principle, it is easy to add new game boards. A board must have a same number of rows and columns (i.e., a k x k board) and that's about the only strict requirement. Place proper board size parameters in `src/conf.rs` and the new board is ready to be used. Of course, the drawback for larger boards is that the search space for bot player's moves increases exponentially.
Server implements an endpoint `/api/bot/next` that accepts POST requests with a JSON type payload and a URL query string `level=VALUE` with allowed values of *Easy* and *Normal*.
Following example shows a valid HTTP request with command line tool *curl* that is used to compute the first move of a normal level 3x3 3-in-a-row game for the bot player
```bash
curl "localhost:8080/api/bot/next?level=Normal" \
-H "content-type: application/json" \
-d '{"cells":[0, 0, 0, 0, 0, 0, 0, 0, 0],"p1_mark":1,"bot_mark":-1,"empty_mark":0}'
```
and the response for it could be for example
```bash
{"next":0,"next_is_valid":true,"game_over":false,"winner":0}
```
where *next* indicates the board index for the bot's next move. Here indices must be interpreted such that 0-2 represent the first row of the 3x3 board, 3-5 the second row and 6-8 the third and last row.
For more information on the payload requirements, please see the model definitions in `src/models.rs`.
## Production
Document `gcp/README.md` gives instructions for deploying to Google Cloud Run. |
<template>
<div class="c-chart__container">
<v-chart ref="chart" :option="chartOptions" />
</div>
</template>
<script>
import moment from "moment";
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { LineChart } from "echarts/charts";
import {
TitleComponent,
TooltipComponent,
GridComponent,
VisualMapComponent,
} from "echarts/components";
import VChart from "vue-echarts";
use([
CanvasRenderer,
LineChart,
TitleComponent,
TooltipComponent,
GridComponent,
VisualMapComponent,
]);
export default {
name: "PerformanceChartComponent",
props: {
chartData: Array
},
components: {
VChart,
},
data() {
return {
};
},
computed: {
initOptions() {
return {
width: "auto",
height: "300px",
};
},
chartOptions() {
return {
title: {
text: "Team Performance Index",
left: "center",
},
tooltip: {
trigger: 'axis',
transitionDuration: 0,
confine: false,
hideDelay: 0,
padding: [8, 15],
backgroundColor: '#16253F',
textStyle: {
color: 'white'
},
formatter: function(params) {
return `<strong style="display: block;text-align: center">${params[0].axisValue}</strong>
${params[0].marker} Team Perfromance Index: ${params[0].value}%
`
}
},
grid: {
left: "30px",
right: "12px",
bottom: "2px",
top: "6px",
containLabel: true,
},
xAxis: {
type: "category",
showGrid: false,
data: this.xAxisData,
axisLine: {
show: true,
},
axisTick: {
show: false,
},
axisLabel: {
fontSize: 11,
},
},
yAxis: {
axisLabel: { show: true },
axisTick: { show: true },
splitLine: { show: true },
},
series: [
{
data: this.yAxisData,
type: "line",
symbol: "circle",
symbolSize: 2,
cursor: "default",
lineStyle: {
width: 2,
},
},
],
visualMap: {
top: 50,
right: 10,
pieces: [
{
gt: 0,
lt: 50,
color: 'red'
},
{
gte: 50,
lte: 80,
color: 'yellow'
},
{
gt: 80,
color: 'green'
}
]
},
};
},
xAxisData() {
return this.chartData.map((item) => this.formatDate(item.date_ms));
},
yAxisData() {
return this.chartData.map((item) => +item.performance * 100);
},
},
methods: {
formatDate(dateInMs) {
return moment(dateInMs).format("DD MMM YYYY");
},
},
};
</script> |
import React from 'react';
import { Doughnut } from 'react-chartjs-2';
import { Chart, ArcElement } from 'chart.js';
import Labels from './Labels';
import { default as api } from '../store/apiSlice';
import { chartData, getTotal } from '../helper/helper';
Chart.register(ArcElement);
function Graph() {
const { data, isFetching, isSuccess, isError } = api.useGetLabelsQuery();
// console.log(data);
let graphData;
if (isFetching) {
graphData = <div>Fetching</div>
}
else if (isSuccess) {
// chartData(data);
// const d = getLabels(data, 'type');
graphData = <Doughnut {...chartData(data)} ></Doughnut>
}
else if (isError) {
graphData = <div>Error!!!</div>
}
return (
<div className="flex justify-content max-w-xs mx-auto">
<div className="item">
<div className="chart relative">
{/* chart */}
{graphData}
<h3 className="mb-4 font-bold text-3xl title">Total
<span className="block text-3xl text-emerald-400">₹{getTotal(data) ?? 0}</span>
</h3>
</div>
<div className="flex flex-col py-10 gap-4">
{/* Labels */}
<Labels></Labels>
</div>
</div>
</div>
)
}
export default Graph; |
import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import Swal from 'sweetalert2';
import { Booking, User } from '../interfaces/interfaces';
import { AdminService } from '../services/admin.service';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['../protected.component.css'],
providers:[AdminService]
})
export class AdminComponent implements OnInit {
// referencia al boton borrado
@ViewChild('botonBorrado') botonBorrado!: ElementRef;
// array de usuarios
arrUsuarios: User[] = [];
// array de reservas
arrReservas: Booking[] = [];
// formularios de busqueda: el de usuarios (email) y el de fecha (reservas) inicializados vacios
formEmail: FormGroup = new FormGroup({});
formFecha: FormGroup = new FormGroup({});
// inyección de servicios
constructor(private fb: FormBuilder, private router: Router, private adminService: AdminService) { }
// recogemos los valores de los formularios ahora en el ngOnInit para que recojan antes su valor, en cuanto cambie y no tengamos que recargar
// ciclos de vida (ngOnInit)
ngOnInit(): void {
// formulario de usuarios
this.formEmail = this.fb.group({
correo: ['', [Validators.required, Validators.email]]
});
// formulario de reservas
this.formFecha = this.fb.group({
fecha: ['', Validators.required]
});
}
// deleteUser() --> método para borrar al usuario seleccionado
deleteUser(id:number){
this.adminService.deleteUser(id)
.subscribe(resp=>{
if(resp === "OK"){
Swal.fire('Usuario borrado correctamente', '', 'success' );
this.router.navigateByUrl('/user');
}else{
Swal.fire('Algo salió mal', '', 'error' );
this.router.navigateByUrl('/admin');
}
})
}
// findUser --> para encontrar al usuario que hemos escrito su correoo
findUser(){
const correo = this.formEmail.get('correo')!.value;
this.adminService.findUser(correo).subscribe(usuarios => this.arrUsuarios=usuarios);
}
// findBooking() --> para encontrar las reservas por la fecha seleccionada
findBooking(){
const fecha = this.formFecha.get('fecha')!.value;
console.log(fecha)
this.adminService.findBooking(fecha).subscribe(reservas=>this.arrReservas=reservas);
}
// deleteBooking() --> método para borrar la reserva seleccionada
deleteBooking(id: number){
this.adminService.deleteBooking(id)
.subscribe(resp=>{
if(resp === "OK"){
Swal.fire('Reserva borrada correctamente', '', 'success' );
this.router.navigateByUrl('/user');
}else{
Swal.fire('Algo salió mal', '', 'error' );
this.router.navigateByUrl('/admin');
}
})
}
} |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('penduduk', function (Blueprint $table) {
$table->id('id_penduduk');
$table->string('NIK');
$table->string('NoKK');
$table->string('nama');
$table->string('TTL');
$table->string('Agama');
$table->enum('JenisKelamin', ['Pria', 'Wanita']);
$table->enum('rt',['1','2','3','4','5','6','7','8','9','10']);
$table->string('Alamat');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('penduduk');
}
}; |
# Tic Tac Toe 게임 만들기
## 1. App 컴퍼넌트 만들기
- 기본 구조 준비
## 2. Board, Square 컴퍼넌트 만들기
- components / Board.js
- components / Sqaure.js
### (1) 3 X 3 게임판 만들기
### (2) 간단한 스타일링
## 3. props를 통해서 컴퍼넌트간 데이터 전달하기
- 부모(Board)에서 전달한 숫자를 Square Component에 출력하기
## 4. 사용자와 상호 작용하는 컴퍼넌트 만들기
- Square Component를 클릭하면 "click" 로그를 출력
## 5. state 추가하기
- Square Component를 클릭한 것을 기억하게 만들어 'X' 표시를 채워넣는다.
## 6. 부모 컴퍼넌트에 state 보관하기
- Board.js에 state를 생성하여 자식들(Square)에게 props로 전달
## 7. 불변성에 대해서
- 자바스크립트에서 원시 타입은 불변성을 가지고, 참조타입은 그렇지 않다.
- 원시 타입 : Boolean, String, Number, null, undefinde, ..
- 참조 타입 : Object, Array
- 불변성은 왜 지켜야 하는가?
- 참조 타입에서 객체나 배열의 값이 변할 때, 원본 데이터가 변하기 때문에 이 원본 데이터를 참조하는 다른 객체에서 예상치 못한 오류 발생
- 리엑트에서는 화면을 업데이트할 때 불변성을 지켜서 값을 이전 값과 비교해서 변경된 사항을 확인한 후 업데이트를 하기 때문
- 불변성을 지키는 방법은?
- speread operator, map, filter, slice, reduce
- 원본데이터 변경 : splice, push
## 8. 함수형 컴퍼넌트로 변경
## 9. 순서를 만들어서 O를 추가하기
## 10. 승자 결정하기
- 승부를 결정하는 것을 계산하는 함수
- 승부가 났을 경우 더 이상 클릭 금지
## 11. 동작에 대한 기록 저장하기
- Board.js의 코드를 App.js로 이동
## 12. 과거의 이동을 표시하기 |
import React from 'react';
import { Button, Modal } from 'rsuite';
import { useModalState } from '../../../misc/custom-hooks';
import ProfileAvatar from '../../dashboard/ProfileAvatar';
const ProfileInfoBtnModal = ({profile, children, ...btnProps}) => {
const {isOpen, open, close} = useModalState()
const {name, avatar, createdAt} = profile
const shortName = profile.name.split(' ')[0]
const memberSince = new Date(createdAt).toLocaleDateString()
return (
<>
<Button onClick={open} {...btnProps}>
{shortName}
</Button>
<Modal open={isOpen} onClose={close}>
<Modal.Header>
<Modal.Title>{shortName} profile</Modal.Title>
</Modal.Header>
<Modal.Body className="text-center">
<ProfileAvatar
src={avatar}
name={name}
className="width-200 height-200 img-fullsize font-huge"/>
<h4 className="mt-2">{name}</h4>
<p>Member since {memberSince}</p>
</Modal.Body>
<Modal.Footer>
{children}
<Button block onClick={close}>
Close
</Button>
</Modal.Footer>
</Modal>
</>
)
};
export default ProfileInfoBtnModal; |
#!/usr/bin/python3
"""create an empty class called Square"""
class Square:
"""create a square.
size (no type/value verification)
atributes:
size: private instance.
"""
def __init__(self, size=0):
self.__size = size
def area(self):
return self.__size * self.__size
@property
def size(self):
return self.__size
@size.setter
def size(self, value):
if type(value) != int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value |
const asyncHandler = require("express-async-handler")
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const User = require("../models/userModel");
const registerUser = asyncHandler(async (req,res)=>{
const {username, email , password } = req.body;
if(!username || !email || !password){
res.status(400);
throw new Error("All fields are mandatory");
}
try {
const userAvailable = await User.findOne({ email:email });
if (userAvailable) {
res.status(400);
res.json({message:"User Already Exists"})
// throw new Error("User already registered");
}
const hashedPassword = await bcrypt.hash(password,10);
// console.log("hashedPassword", hashedPassword);
const user = await User.create({
username,
email,
password:hashedPassword,
});
console.log("Registerd User",user );
if(user){
res.status(201).json({_id:user.id, email:user.email});
}else{
res.status(400);
throw new Error("User data not Valid");
}
res.json({message:"Register the user"});
}
catch{
console.error(error);
res.status(500).json({ message: "Server error" });
}
});
const loginUser = asyncHandler(async (req,res)=>{
const {email, password}=req.body;
if(!email || !password){
res.json(400)
throw new Error("All field mandatory")
}
const user = await User.findOne({email});
if(user && (await bcrypt.compare(password,user.password))){
const accessToken=jwt.sign({
user:{
username:user.username,
email:user.email,
id:user.id
},
},process.env.ACCESS_TOKEN_SECRET,
{expiresIn:"1m"}
)
res.status(200).json({
accessToken:accessToken,
message:"Logged in successfully"
});
}
else{
res.status(401).json({
message:"some error in logging in "
})
}
res.json({message: "Login User"})
});
const currentUser = asyncHandler(async (req,res)=>{
res.json({message: "Current User"})
});
module.exports = {registerUser,loginUser,currentUser} |
import Proyecto from "../models/Proyecto.js"
import Tarea from "../models/Tarea.js"
const agregarTarea = async (req,res) => {
const proyecto = req.body.proyecto
const proyectoExiste = await Proyecto.findById(proyecto)
if(!proyectoExiste){
const error = new Error("El Proyecto no existe")
return res.status(404).json({msg: error.message})
}
if(proyectoExiste.creador.toString() !== req.usuario._id.toString()){
const error = new Error("No tienes Permisos")
return res.status(403).json({msg: error.message})
}
try {
const tareaAlmacenada = await Tarea.create(req.body)
proyectoExiste.tareas.push(tareaAlmacenada._id)
await proyectoExiste.save()
return res.json(tareaAlmacenada)
} catch (error) {
console.log(error)
}
}
const obtenerTarea = async (req,res) => {
const {id} = req.params
const tarea = await Tarea.findById(id).populate("proyecto")
if(!tarea){
const error = new Error("Tarea no encontrada")
return res.status(404).json({msg:error.message})
}
if(tarea.proyecto.creador.toString() !== req.usuario._id.toString()){
const error = new Error("No tienes permisos")
return res.status(401).json({msg:error.message})
}
return res.json(tarea)
}
const actualizarTarea = async (req,res) => {
const {id} = req.params
const tarea = await Tarea.findById(id).populate("proyecto")
if(!tarea){
const error = new Error("Tarea no encontrada")
return res.status(404).json({msg:error.message})
}
if(tarea.proyecto.creador.toString() !== req.usuario._id.toString()){
const error = new Error("No tienes permisos")
return res.status(403).json({msg:error.message})
}
try {
tarea.nombre = req.body.nombre || tarea.nombre
tarea.descripcion = req.body.descripcion || tarea.descripcion
tarea.estado = req.body.estado || tarea.estado
tarea.prioridad = req.body.prioridad || tarea.prioridad
tarea.fechaEntrega = req.body.fechaEntrega || tarea.fechaEntrega
const tareaActualizada = await tarea.save()
return res.json(tareaActualizada)
} catch (error) {
console.log(error)
}
}
const eliminarTarea = async (req,res) => {
const {id} = req.params
const tarea = await Tarea.findById(id).populate("proyecto")
if(!tarea){
const error = new Error("Tarea no encontrada")
return res.status(404).json({msg:error.message})
}
if(tarea.proyecto.creador.toString() !== req.usuario._id.toString()){
const error = new Error("No tienes permisos")
return res.status(403).json({msg:error.message})
}
try {
const proyecto = await Proyecto.findById(tarea.proyecto._id)
proyecto.tareas.pull(tarea._id)
await Promise.allSettled([await proyecto.save(),await tarea.deleteOne()])
return res.json({msg:"Tarea Eliminada"})
} catch (error) {
console.log(error)
}
}
const cambiarEstado = async (req,res) => {
const tarea = await Tarea.findById(req.params.id).populate("proyecto").populate("completado")
if(!tarea){
const error = new Error("Tarea no encontrada")
return res.status(404).json({msg:error.message})
}
if(tarea.proyecto.creador.toString() !== req.usuario._id.toString() && !tarea.proyecto.colaboradores.some(c => c._id.toString() === req.usuario._id.toString()) ){
const error = new Error("No tienes permisos")
return res.status(401).json({msg:error.message})
}
tarea.estado = !tarea.estado
tarea.completado = req.usuario._id
await tarea.save()
const tareaAlmacenada = await Tarea.findById(req.params.id).populate("proyecto").populate("completado")
res.json(tareaAlmacenada)
}
export{
agregarTarea,
obtenerTarea,
actualizarTarea,
eliminarTarea,
cambiarEstado
} |
<template>
<Layout v-bind="$attrs">
<template v-slot:banner>
<div
class="pt-6 text-center print:hidden"
:class="showReset ? 'pb-4' : 'pb-10'"
>
<p class="text-lg xl:text-xl font-bold">{{ searchTitle }}</p>
<ContentWrapper class="mt-3" size="medium">
<div role="search" class="flex items-center space-x-2">
<InputLocation
class="flex-1"
name="territorial_collectivity"
:placeholder="searchPlaceholder"
withoutMargin
:allowFreeSearch="allowFreeSearch"
v-model="inputLocation"
/>
<Button size="sm" type="button">Rechercher</Button>
</div>
<p
class="mt-1 text-right text-sm font-bold"
v-if="showReset"
>
<Link v-if="isNotOnDefaultFilter" @click="resetSearch">
<Icon icon="rotate-left" /> Revenir à mon
territoire</Link
>
<Link v-else @click="emptySearch">
{{ showNationalWording }}</Link
>
</p>
</ContentWrapper>
</div>
</template>
<slot />
</Layout>
</template>
<script setup>
import { defineProps, toRefs, computed, defineEmits } from "vue";
import { useUserStore } from "@/stores/user.store";
import Layout from "@/components/Layout/Layout.vue";
import {} from "@resorptionbidonvilles/ui";
import InputLocation from "@/components/InputLocation/InputLocation.vue";
import { Button, ContentWrapper, Icon, Link } from "@resorptionbidonvilles/ui";
const props = defineProps({
searchTitle: {
type: String,
required: true,
},
searchPlaceholder: {
type: String,
required: false,
},
allowFreeSearch: {
type: Boolean,
required: false,
default: true,
},
showNationalWording: {
type: String,
required: false,
default: "",
},
location: {
type: Object,
required: false,
default: () => undefined,
},
});
const {
searchTitle,
allowFreeSearch,
searchPlaceholder,
showNationalWording,
location,
} = toRefs(props);
const emit = defineEmits(["update:location"]);
const userStore = useUserStore();
const inputLocation = computed({
get() {
return location.value;
},
set(newValue) {
emit("update:location", newValue);
},
});
const showReset = computed(() => {
if (isNotOnDefaultFilter.value) {
return true;
}
return (
showNationalWording.value &&
userStore.user.organization.location.type !== "nation"
);
});
const isNotOnDefaultFilter = computed(() => {
return !userStore.isMyLocation(inputLocation.value);
});
function resetSearch() {
inputLocation.value = userStore.defaultLocationFilter;
}
function emptySearch() {
inputLocation.value = {
search: "",
data: null,
};
}
</script> |
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Responsive Bootstrap4 Shop Template, Created by Imran Hossain from https://imransdesign.com/">
<!-- title -->
<title>Shop</title>
<!-- favicon -->
<link rel="shortcut icon" type="image/png" href="{% static 'assets/img/favicon.png' %}">
<!-- google font -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Poppins:400,700&display=swap" rel="stylesheet">
<!-- fontawesome -->
<link rel="stylesheet" href="{% static 'assets/css/all.min.css' %}">
<!-- bootstrap -->
<link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}">
<!-- owl carousel -->
<link rel="stylesheet" href="{% static 'assets/css/owl.carousel.css' %}">
<!-- magnific popup -->
<link rel="stylesheet" href="{% static 'assets/css/magnific-popup.css' %}">
<!-- animate css -->
<link rel="stylesheet" href="{% static 'assets/css/animate.css' %}">
<!-- mean menu css -->
<link rel="stylesheet" href="{% static 'assets/css/meanmenu.min.css' %}">
<!-- main style -->
<link rel="stylesheet" href="{% static 'assets/css/main.css' %}">
<!-- responsive -->
<link rel="stylesheet" href="{% static 'assets/css/responsive.css' %}">
</head>
<body>
<!--PreLoader-->
<div class="loader">
<div class="loader-inner">
<div class="circle"></div>
</div>
</div>
<!--PreLoader Ends-->
<!-- header -->
<div class="top-header-area" id="sticker">
<div class="container">
<div class="row">
<div class="col-lg-12 col-sm-12 text-center">
<div class="main-menu-wrap">
<!-- logo -->
<div class="site-logo">
<a href="index.html">
<img src="{% static 'assets/img/logo.png' %}" alt="">
</a>
</div>
<!-- logo -->
<!-- menu start -->
<nav class="main-menu">
<ul>
<li class="current-list-item"><a href="{% url 'home_page' %}">Home</a>
<ul class="sub-menu">
<li><a href="index.html">Static Home</a></li>
<li><a href="index_2.html">Slider Home</a></li>
</ul>
</li>
<li><a href="{% url 'about_page' %}">About us</a></li>
<li><a href="">Pages</a>
<ul class="sub-menu">
<li><a href="404.html">404 page</a></li>
<li><a href="about.html">About</a></li>
<li><a href="cart.html">Cart</a></li>
<li><a href="checkout.html">Check Out</a></li>
<li><a href="contact.html">Contact</a></li>
<li><a href="news.html">News</a></li>
<li><a href="shop.html">Shop</a></li>
</ul>
</li>
<li><a href="news.html">News</a>
<ul class="sub-menu">
<li><a href="news.html">News</a></li>
<li><a href="single-news.html">Single News</a></li>
</ul>
</li>
<li><a href="{% url 'contact_page' %}">Contact</a></li>
{% if request.session.RegName %}
<li><a href="#">{{request.session.RegName}}</a></li>
<li><a href="{% url 'UserLogout' %}">Logout</a></li>
{% else %}
<li><a href="{% url 'login_page' %}">Login</a></li>
{% endif %}
<li><a href="shop.html">Categories</a>
<ul class="sub-menu">
{% for i in data %}
<li><a href="{% url 'product_page' cat_name=i.Name %}">{{i.Name}}</a></li>
<!-- <li><a href="checkout.html">Check Out</a></li>-->
<!-- <li><a href="single-product.html">Single Product</a></li>-->
<!-- <li><a href="cart.html">Cart</a></li>-->
{% endfor %}
</ul>
</li>
<li>
<div class="header-icons">
<a class="shopping-cart" href="cart.html"><i class="fas fa-shopping-cart"></i></a>
<a class="mobile-hide search-bar-icon" href="#"><i class="fas fa-search"></i></a>
</div>
</li>
</ul>
</nav>
<a class="mobile-show search-bar-icon" href="#"><i class="fas fa-search"></i></a>
<div class="mobile-menu"></div>
<!-- menu end -->
</div>
</div>
</div>
</div>
</div>
<!-- end header -->
<!-- search area -->
<div class="search-area">
<div class="container">
<div class="row">
<div class="col-lg-12">
<span class="close-btn"><i class="fas fa-window-close"></i></span>
<div class="search-bar">
<div class="search-bar-tablecell">
<h3>Search For:</h3>
<input type="text" placeholder="Keywords">
<button type="submit">Search <i class="fas fa-search"></i></button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- end search arewa -->
<!-- breadcrumb-section -->
<div class="breadcrumb-section breadcrumb-bg">
<div class="container">
<div class="row">
<div class="col-lg-8 offset-lg-2 text-center">
<div class="breadcrumb-text">
<p>Fresh and Organic</p>
<h1>Products</h1>
</div>
</div>
</div>
</div>
</div>
<!-- end breadcrumb section -->
<!-- products -->
<div class="product-section mt-150 mb-150">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="product-filters">
<ul>
<li class="active" data-filter="*">All</li>
<li data-filter=".strawberry">Strawberry</li>
<li data-filter=".berry">Berry</li>
<li data-filter=".lemon">Lemon</li>
</ul>
</div>
</div>
</div>
<div class="row product-lists">
{% for i in pro %}
<div class="col-lg-4 col-md-6 text-center strawberry">
<div class="single-product-item">
<div class="product-image">
<a href="single-product.html"><img src="{{i.Productimage.url}}" alt="" width="200px" height="200em"></a>
</div>
<h3>{{i.PrdctName}}</h3>
<p class="product-price"><span></span>{{i.Price}}</p>
<a href="{% url 'single_pro' dataid=i.id%}" class="cart-btn"><i class="fas fa-shopping-cart"></i>More Details</a>
</div>
</div>
{% endfor %}
<!-- <div class="col-lg-4 col-md-6 text-center berry">-->
<!-- <div class="single-product-item">-->
<!-- <div class="product-image">-->
<!-- <a href="single-product.html"><img src="{% static 'assets/img/products/product-img-2.jpg' %}" alt=""></a>-->
<!-- </div>-->
<!-- <h3>Berry</h3>-->
<!-- <p class="product-price"><span>Per Kg</span> 70$ </p>-->
<!-- <a href="cart.html" class="cart-btn"><i class="fas fa-shopping-cart"></i> Add to Cart</a>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="col-lg-4 col-md-6 text-center lemon">-->
<!-- <div class="single-product-item">-->
<!-- <div class="product-image">-->
<!-- <a href="single-product.html"><img src="{% static 'assets/img/products/product-img-3.jpg' %}" alt=""></a>-->
<!-- </div>-->
<!-- <h3>Lemon</h3>-->
<!-- <p class="product-price"><span>Per Kg</span> 35$ </p>-->
<!-- <a href="cart.html" class="cart-btn"><i class="fas fa-shopping-cart"></i> Add to Cart</a>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="col-lg-4 col-md-6 text-center">-->
<!-- <div class="single-product-item">-->
<!-- <div class="product-image">-->
<!-- <a href="single-product.html"><img src="{% static 'assets/img/products/product-img-4.jpg' %}" alt=""></a>-->
<!-- </div>-->
<!-- <h3>Avocado</h3>-->
<!-- <p class="product-price"><span>Per Kg</span> 50$ </p>-->
<!-- <a href="cart.html" class="cart-btn"><i class="fas fa-shopping-cart"></i> Add to Cart</a>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="col-lg-4 col-md-6 text-center">-->
<!-- <div class="single-product-item">-->
<!-- <div class="product-image">-->
<!-- <a href="single-product.html"><img src="{% static 'assets/img/products/product-img-5.jpg' %}" alt=""></a>-->
<!-- </div>-->
<!-- <h3>Green Apple</h3>-->
<!-- <p class="product-price"><span>Per Kg</span> 45$ </p>-->
<!-- <a href="cart.html" class="cart-btn"><i class="fas fa-shopping-cart"></i> Add to Cart</a>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="col-lg-4 col-md-6 text-center strawberry">-->
<!-- <div class="single-product-item">-->
<!-- <div class="product-image">-->
<!-- <a href="single-product.html"><img src="{% static 'assets/img/products/product-img-6.jpg' %}" alt=""></a>-->
<!-- </div>-->
<!-- <h3>Strawberry</h3>-->
<!-- <p class="product-price"><span>Per Kg</span> 80$ </p>-->
<!-- <a href="cart.html" class="cart-btn"><i class="fas fa-shopping-cart"></i> Add to Cart</a>-->
<!-- </div>-->
<!-- </div>-->
<!-- </div>-->
<div class="row">
<div class="col-lg-12 text-center">
<div class="pagination-wrap">
<ul>
<li><a href="#">Prev</a></li>
<li><a href="#">1</a></li>
<li><a class="active" href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">Next</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- end products -->
<!-- logo carousel -->
<div class="logo-carousel-section">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="logo-carousel-inner">
<div class="single-logo-item">
<img src="assets/img/company-logos/1.png" alt="">
</div>
<div class="single-logo-item">
<img src="assets/img/company-logos/2.png" alt="">
</div>
<div class="single-logo-item">
<img src="assets/img/company-logos/3.png" alt="">
</div>
<div class="single-logo-item">
<img src="assets/img/company-logos/4.png" alt="">
</div>
<div class="single-logo-item">
<img src="assets/img/company-logos/5.png" alt="">
</div>
</div>
</div>
</div>
</div>
</div>
<!-- end logo carousel -->
<!-- footer -->
<div class="footer-area">
<div class="container">
<div class="row">
<div class="col-lg-3 col-md-6">
<div class="footer-box about-widget">
<h2 class="widget-title">About us</h2>
<p>Ut enim ad minim veniam perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae.</p>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="footer-box get-in-touch">
<h2 class="widget-title">Get in Touch</h2>
<ul>
<li>34/8, East Hukupara, Gifirtok, Sadan.</li>
<li>support@fruitkha.com</li>
<li>+00 111 222 3333</li>
</ul>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="footer-box pages">
<h2 class="widget-title">Pages</h2>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="services.html">Shop</a></li>
<li><a href="news.html">News</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="footer-box subscribe">
<h2 class="widget-title">Subscribe</h2>
<p>Subscribe to our mailing list to get the latest updates.</p>
<form action="index.html">
<input type="email" placeholder="Email">
<button type="submit"><i class="fas fa-paper-plane"></i></button>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- end footer -->
<!-- copyright -->
<div class="copyright">
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-12">
<p>Copyrights © 2019 - <a href="https://imransdesign.com/">Imran Hossain</a>, All Rights Reserved.<br>
Distributed By - <a href="https://themewagon.com/">Themewagon</a>
</p>
</div>
<div class="col-lg-6 text-right col-md-12">
<div class="social-icons">
<ul>
<li><a href="#" target="_blank"><i class="fab fa-facebook-f"></i></a></li>
<li><a href="#" target="_blank"><i class="fab fa-twitter"></i></a></li>
<li><a href="#" target="_blank"><i class="fab fa-instagram"></i></a></li>
<li><a href="#" target="_blank"><i class="fab fa-linkedin"></i></a></li>
<li><a href="#" target="_blank"><i class="fab fa-dribbble"></i></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- end copyright -->
<!-- jquery -->
<script src="{% static 'assets/js/jquery-1.11.3.min.js' %}"></script>
<!-- bootstrap -->
<script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script>
<!-- count down -->
<script src="{% static 'assets/js/jquery.countdown.js' %}"></script>
<!-- isotope -->
<script src="{% static 'assets/js/jquery.isotope-3.0.6.min.js' %}"></script>
<!-- waypoints -->
<script src="{% static 'assets/js/waypoints.js' %}"></script>
<!-- owl carousel -->
<script src="{% static 'assets/js/owl.carousel.min.js' %}"></script>
<!-- magnific popup -->
<script src="{% static 'assets/js/jquery.magnific-popup.min.js' %}"></script>
<!-- mean menu -->
<script src="{% static 'assets/js/jquery.meanmenu.min.js' %}"></script>
<!-- sticker js -->
<script src="{% static 'assets/js/sticker.js' %}"></script>
<!-- main js -->
<script src="{% static 'assets/js/main.js' %}"></script>
</body>
</html> |
<template>
<div id="app">
<tool-bar />
<router-view></router-view>
<Spinner :loading="lodingStatus" />
</div>
</template>
<script>
import ToolBar from './components/ToolBar.vue';
import Spinner from './components/Spinner.vue'
import Bus from './utils/bus.js';
export default {
name: 'App',
data() {
return {
lodingStatus: false,
}
},
components: {
ToolBar,
Spinner
},
created() {
Bus.$on('start:spinner', this.startSpinner);
Bus.$on('end:spinner', this.endSpinner);
},
beforeDestroy() {
Bus.$off('start:spinner', this.startSpinner);
Bus.$off('end:spinner', this.endSpinner);
},
methods: {
startSpinner() {
this.lodingStatus = true;
},
endSpinner() {
this.lodingStatus = false;
}
}
}
</script>
<style>
body {
padding: 0;
margin: 0;
}
a {
color: #34495e;
text-decoration: none;
}
a:hover {
color: #42b883;
text-decoration: underline;
}
a.router-link-exact-active {
text-decoration: underline;
}
</style> |
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""An executor class for running model on TensorFlow 2.0."""
from __future__ import absolute_import
from __future__ import division
# from __future__ import google_type_annotations
from __future__ import print_function
from absl import logging
import tensorflow as tf
from official.vision.detection.executor import distributed_executor as executor
from official.vision.detection.utils.object_detection import visualization_utils
class DetectionDistributedExecutor(executor.DistributedExecutor):
"""Detection specific customer training loop executor.
Subclasses the DistributedExecutor and adds support for numpy based metrics.
"""
def __init__(self,
predict_post_process_fn=None,
trainable_variables_filter=None,
**kwargs):
super(DetectionDistributedExecutor, self).__init__(**kwargs)
if predict_post_process_fn:
assert callable(predict_post_process_fn)
if trainable_variables_filter:
assert callable(trainable_variables_filter)
self._predict_post_process_fn = predict_post_process_fn
self._trainable_variables_filter = trainable_variables_filter
self.eval_steps = tf.Variable(
0,
trainable=False,
dtype=tf.int32,
synchronization=tf.VariableSynchronization.ON_READ,
aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA,
shape=[])
def _create_replicated_step(self,
strategy,
model,
loss_fn,
optimizer,
metric=None):
trainable_variables = model.trainable_variables
if self._trainable_variables_filter:
trainable_variables = self._trainable_variables_filter(
trainable_variables)
logging.info('Filter trainable variables from %d to %d',
len(model.trainable_variables), len(trainable_variables))
update_state_fn = lambda labels, outputs: None
if isinstance(metric, tf.keras.metrics.Metric):
update_state_fn = metric.update_state
else:
logging.error('Detection: train metric is not an instance of '
'tf.keras.metrics.Metric.')
def _replicated_step(inputs):
"""Replicated training step."""
inputs, labels = inputs
with tf.GradientTape() as tape:
outputs = model(inputs, training=True)
all_losses = loss_fn(labels, outputs)
losses = {}
for k, v in all_losses.items():
losses[k] = tf.reduce_mean(v)
per_replica_loss = losses['total_loss'] / strategy.num_replicas_in_sync
update_state_fn(labels, outputs)
grads = tape.gradient(per_replica_loss, trainable_variables)
clipped_grads, _ = tf.clip_by_global_norm(grads, clip_norm=1.0)
optimizer.apply_gradients(zip(clipped_grads, trainable_variables))
return losses
return _replicated_step
def _create_test_step(self, strategy, model, metric):
"""Creates a distributed test step."""
@tf.function
def test_step(iterator, eval_steps):
"""Calculates evaluation metrics on distributed devices."""
def _test_step_fn(inputs, eval_steps):
"""Replicated accuracy calculation."""
inputs, labels = inputs
model_outputs = model(inputs, training=False)
if self._predict_post_process_fn:
labels, prediction_outputs = self._predict_post_process_fn(
labels, model_outputs)
num_remaining_visualizations = (
self._params.eval.num_images_to_visualize - eval_steps)
# If there are remaining number of visualizations that needs to be
# done, add next batch outputs for visualization.
#
# TODO(hongjunchoi): Once dynamic slicing is supported on TPU, only
# write correct slice of outputs to summary file.
if num_remaining_visualizations > 0:
visualization_utils.visualize_images_with_bounding_boxes(
inputs, prediction_outputs['detection_boxes'],
self.global_train_step, self.eval_summary_writer)
return labels, prediction_outputs
labels, outputs = strategy.run(
_test_step_fn, args=(
next(iterator),
eval_steps,
))
outputs = tf.nest.map_structure(strategy.experimental_local_results,
outputs)
labels = tf.nest.map_structure(strategy.experimental_local_results,
labels)
eval_steps.assign_add(self._params.eval.batch_size)
return labels, outputs
return test_step
def _run_evaluation(self, test_step, current_training_step, metric,
test_iterator):
"""Runs validation steps and aggregate metrics."""
self.eval_steps.assign(0)
if not test_iterator or not metric:
logging.warning(
'Both test_iterator (%s) and metrics (%s) must not be None.',
test_iterator, metric)
return None
logging.info('Running evaluation after step: %s.', current_training_step)
while True:
try:
labels, outputs = test_step(test_iterator, self.eval_steps)
if metric:
metric.update_state(labels, outputs)
except (StopIteration, tf.errors.OutOfRangeError):
break
metric_result = metric.result()
if isinstance(metric, tf.keras.metrics.Metric):
metric_result = tf.nest.map_structure(lambda x: x.numpy().astype(float),
metric_result)
logging.info('Step: [%d] Validation metric = %s', current_training_step,
metric_result)
return metric_result |
---
title: Web アプリケーションのレイアウトに flexbox を使用する
slug: Web/CSS/CSS_Flexible_Box_Layout/Using_flexbox_to_lay_out_web_applications
tags:
- Advanced
- CSS
- CSS Flexible Boxes
- Example
- Guide
- Web
translation_of: Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox
translation_of_original: Web/CSS/CSS_Flexible_Box_Layout/Using_flexbox_to_lay_out_web_applications
---
<div><section class="Quick_links" id="Quick_Links"><ol><li><strong><a href="/ja/docs/Web/CSS">CSS</a></strong></li><li><strong><a href="/ja/docs/Web/CSS/Reference">CSS リファレンス</a></strong></li><li><strong><a href="/ja/docs/Web/CSS/CSS_Flexible_Box_Layout">CSS Flexible Box Layout</a></strong></li><li class="toggle"><details open><summary>ガイド</summary><ol><li><a href="/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container">フレックスコンテナー内のアイテムの配置</a></li><li><a href="/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Backwards_Compatibility_of_Flexbox">フレックスボックスの後方互換性</a></li><li><a href="/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox">フレックスボックスの基本概念</a></li><li><a href="/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Controlling_Ratios_of_Flex_Items_Along_the_Main_Ax">主軸に沿ったフレックスアイテムの比率の制御</a></li><li><a href="/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Mixins">クロスブラウザのフレックスボックスのミックスイン</a></li><li><a href="/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Mastering_Wrapping_of_Flex_Items">フレックスアイテムの折り返しのマスター</a></li><li><a href="/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items">フレックスアイテムの並べ替え</a></li><li><a href="/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Relationship_of_Flexbox_to_Other_Layout_Methods">フレックスボックスと他のレイアウト方法の関係</a></li><li><a href="/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox">フレックスボックスの典型的な使用例</a></li></ol></details></li><li class="toggle"><details open><summary>プロパティ</summary><ol><li><a href="/ja/docs/Web/CSS/flex"><code>flex</code></a></li><li><a href="/ja/docs/Web/CSS/flex-basis"><code>flex-basis</code></a></li><li><a href="/ja/docs/Web/CSS/flex-direction"><code>flex-direction</code></a></li><li><a href="/ja/docs/Web/CSS/flex-flow"><code>flex-flow</code></a></li><li><a href="/ja/docs/Web/CSS/flex-grow"><code>flex-grow</code></a></li><li><a href="/ja/docs/Web/CSS/flex-shrink"><code>flex-shrink</code></a></li><li><a href="/ja/docs/Web/CSS/flex-wrap"><code>flex-wrap</code></a></li><li><a href="/ja/docs/Web/CSS/order"><code>order</code></a></li></ol></details></li></ol></section></div>
<p><a href="/ja/docs/Web/Guide/CSS/Flexible_boxes">flexbox</a> は、デスクトップからモバイルまで対応する Web アプリケーションのレイアウト設計で助けになります。浮動状態の <a href="/ja/docs/Web/HTML/Element/div" title="HTML の コンテンツ分割要素 (<div>) は、フローコンテンツの汎用コンテナーです。 CSS を用いてスタイル付けがされるまでは、コンテンツやレイアウトには影響を与えません。"><code><div></code></a> 要素、<a href="/ja/docs/Web/CSS/position#Absolute_positioning">絶対位置指定</a>、JavaScript による細工をなくして、数行の <a href="/ja/docs/Web/CSS">CSS</a> だけで水平方向または垂直方向のフローレイアウトを構築します。基本的な用途例を挙げます:</p>
<ul>
<li>ページの中央に要素を置きたい場合。</li>
<li>コンテナを垂直方向へ次々に並べて配置したい場合。</li>
<li>スクリーンサイズが小さいときに垂直方向へ並べ替えられる、ボタンや要素の列を作成したい場合。</li>
</ul>
<p>この記事では、接頭辞がない現行の標準仕様をサポートするブラウザで <em>flexbox</em> を使用する方法を扱います。古いブラウザ向けのベンダー接頭辞については、<a href="/ja/docs/Web/Guide/CSS/Flexible_boxes">CSS flexible box の使用に関する、より一般的なガイド</a>をご覧ください。</p>
<h2 id="Basics" name="Basics">基本</h2>
<p>任意の <a href="/ja/docs/Web/HTML/Element/div" title="HTML の コンテンツ分割要素 (<div>) は、フローコンテンツの汎用コンテナーです。 CSS を用いてスタイル付けがされるまでは、コンテンツやレイアウトには影響を与えません。"><code><div></code></a> 要素で <a href="/ja/docs/Web/CSS/display" title="CSS の display プロパティは、要素の表示種別を指定し、これは要素がボックスを生成する方法の二つの基本的な品質から成ります。 — 外部表示種別はボックスがフローレイアウトにどのように加わるのかを定義し、内部表示種別はボックスの子がどのように配置されるのかを定義します。"><code>display</code></a> プロパティに <code>flex</code> を、また <a href="/ja/docs/Web/CSS/flex-flow" title="CSS の flex-flow プロパティは、 flex-direction プロパティと flex-wrap プロパティの一括指定プロパティです。"><code>flex-flow</code></a> に <code>row</code> (要素を水平に並べたい場合) または <code>column</code> (要素を垂直に並べたい場合) を設定すると、内部の要素を flexbox のフローにすることができます。水平方向の flexbox を使用していて内容物を垂直方向に折り返したい場合は、値 <code>wrap</code> も指定します。</p>
<p>そして、flex フローの一部として組み込みたい要素に <a href="/ja/docs/Web/CSS/flex" title="CSS の flex プロパティは、フレックスアイテムをフレックスコンテナーの領域に収めるために、どのように伸長・収縮させるかを指定します。これは一括指定プロパティで、 flex-grow, flex-shrink, flex-basis を設定します。"><code>flex</code></a> プロパティを指定します。通常、以下の 3 種類の値のいずれかを使用するでしょう:</p>
<ul>
<li>ボタンなど、自身に割り当てられた幅を占有するだけの要素にしたい場合は、<code>flex: none</code> を使用します。この値は <code>0 0 auto</code> に展開されます。</li>
<li>要素のサイズを明示したい場合は、<code>flex: 0 0 <em>size</em></code> を使用します。例: <code>flex 0 0 60px</code></li>
<li>使用可能な領域を埋めるように拡張する要素にしたい、すなわちフロー内に同種の要素が複数ある場合は均等に領域を共有させたい場合は、<code>flex: auto</code> を使用します。この値は <code>1 1 auto</code> に展開されます。</li>
</ul>
<p>もちろん他にも使用できる値はありますが、それらは基本的な使用方法を超えるものでしょう。これらの値がどのように適用されるかを、いくつかの例で見ていきましょう。</p>
<h2 id="Centering_an_element_inside_a_page" name="Centering_an_element_inside_a_page">ページ内の中央に要素を配置する</h2>
<p>このような使い方でもっとも簡単な方法は、2 つの flexible box を入れ子にすることです。それぞれの flexbox 内に要素が 3 つあります。そのうち 2 つが詰め物になって、残る要素が中央に置かれます。</p>
<h3 id="CSS_Content" name="CSS_Content">CSS コンテンツ</h3>
<pre class="brush: css;">.vertical-box {
display: flex;
height: 400px;
width: 400px;
flex-flow: column;
}
.horizontal-box {
display: flex;
flex-flow: row;
}
.spacer {
flex: auto;
background-color: black;
}
.centered-element {
flex: none;
background-color: white;
}
</pre>
<h3 id="HTML_Content" name="HTML_Content">HTML コンテンツ</h3>
<pre class="brush: html;"><div class="vertical-box">
<div class="spacer"></div>
<div class="centered-element horizontal-box">
<div class="spacer"></div>
<div class="centered-element">Centered content</div>
<div class="spacer"></div>
</div>
<div class="spacer"></div>
</div>
</pre>
<h3 id="Result" name="Result">結果</h3>
<p><iframe src="https://mdn.mozillademos.org/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_flexbox_to_lay_out_web_applications$samples/Centering_an_element_inside_a_page?revision=980099" width="500" height="500" class="live-sample-frame sample-code-frame" frameborder="0" id="frame_Centering_an_element_inside_a_page"></iframe></p>
<h2 id="Flowing_a_set_of_containers_vertically" name="Flowing_a_set_of_containers_vertically">複数のコンテナを垂直方向に並べる</h2>
<p>ヘッダーセクション、コンテンツセクション、フッターセクションがあるレイアウトのページを思い浮かべてください。ヘッダーとフッターのサイズは固定しますが、コンテンツセクションは使用できる領域に応じてリサイズします。これはコンテンツセクションの <a href="/ja/docs/Web/CSS/flex" title="CSS の flex プロパティは、フレックスアイテムをフレックスコンテナーの領域に収めるために、どのように伸長・収縮させるかを指定します。これは一括指定プロパティで、 flex-grow, flex-shrink, flex-basis を設定します。"><code>flex</code></a> プロパティを <code>auto</code> に、またヘッダーおよびフッターの <a href="/ja/docs/Web/CSS/flex" title="CSS の flex プロパティは、フレックスアイテムをフレックスコンテナーの領域に収めるために、どのように伸長・収縮させるかを指定します。これは一括指定プロパティで、 flex-grow, flex-shrink, flex-basis を設定します。"><code>flex</code></a> プロパティを <code>none</code> にすることで実現できます。</p>
<h3 id="CSS_Content_2" name="CSS_Content_2">CSS コンテンツ</h3>
<pre class="brush: css;highlight:[8,14]">.vertical-box {
display: flex;
height: 400px;
width: 400px;
flex-flow: column;
}
.fixed-size {
flex: none;
height: 30px;
background-color: black;
text-align: center;
}
.flexible-size {
flex: auto;
background-color: white;
}
</pre>
<h3 id="HTML_Content_2" name="HTML_Content_2">HTML コンテンツ</h3>
<pre class="brush: html;"><div id="document" class="vertical-box">
<div class="fixed-size"><button id="increase-size">Increase container size</button></div>
<div id="flexible-content" class="flexible-size"></div>
<div class="fixed-size"><button id="decrease-size">Decrease container size</button></div>
</div>
</pre>
<h3 id="Javascript_Content" name="Javascript_Content">Javascript コンテンツ</h3>
<pre class="brush: js;">var height = 400;
document.getElementById('increase-size').onclick=function() {
height += 10;
if (height > 500) height = 500;
document.getElementById('document').style.height = (height + "px");
}
document.getElementById('decrease-size').onclick=function() {
height -= 10;
if (height < 300) height = 300;
document.getElementById('document').style.height = (height + "px");
}</pre>
<h3 id="Result_2" name="Result_2">結果</h3>
<p><iframe src="https://mdn.mozillademos.org/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_flexbox_to_lay_out_web_applications$samples/Flowing_a_set_of_containers_vertically?revision=980099" width="500" height="500" class="live-sample-frame sample-code-frame" frameborder="0" id="frame_Flowing_a_set_of_containers_vertically"></iframe></p>
<p>この例はヘッダーのボタンをクリックするとサイズが拡大、フッターのボタンをクリックするとサイズが縮小するようになっています。ヘッダーやフッターのサイズを一定にしたままで、どのようにしてコンテンツセクションを自動的に適切なサイズに変えているかを確認してください。</p>
<h2 id="Creating_a_collapsing_horizontal_container" name="Creating_a_collapsing_horizontal_container">折り返される水平方向のコンテナを作成する</h2>
<p>スクリーンサイズに余裕があれば水平方向に情報一式を並べますが、そうでない場合は水平方向のレイアウトを崩したい場合があるかもしれません。これは、flexbox を使用すればとても簡単です。<a href="/ja/docs/Web/CSS/flex-flow" title="CSS の flex-flow プロパティは、 flex-direction プロパティと flex-wrap プロパティの一括指定プロパティです。"><code>flex-flow</code></a> プロパティに値 <code>wrap</code> を追加すると実現できます。</p>
<h3 id="CSS_Content_3" name="CSS_Content_3">CSS コンテンツ</h3>
<pre class="brush: css;highlight:[4]">.horizontal-container {
display: flex;
width: 300px;
flex-flow: row wrap;
}
.fixed-size {
flex: none;
width: 100px;
background-color: black;
color: white;
text-align: center;
}
</pre>
<h3 id="HTML_Content_3" name="HTML_Content_3">HTML コンテンツ</h3>
<pre class="brush: html;"><div id="container" class="horizontal-container">
<div class="fixed-size">Element 1</div>
<div class="fixed-size">Element 2</div>
<div class="fixed-size">Element 3</div>
</div><button id="increase-size">Increase container size</button><button id="decrease-size">Decrease container size</button>
</pre>
<h3 id="Javascript_Content_2" name="Javascript_Content_2">Javascript コンテンツ</h3>
<pre class="brush: js;">var width = 300;
document.getElementById('increase-size').onclick=function() {
width += 100;
if (width > 300) width = 300;
document.getElementById('container').style.width = (width + "px");
}
document.getElementById('decrease-size').onclick=function() {
width -= 100;
if (width < 100) width = 100;
document.getElementById('container').style.width = (width + "px");
}
</pre>
<h3 id="Result_3" name="Result_3">結果</h3>
<p><iframe src="https://mdn.mozillademos.org/ja/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_flexbox_to_lay_out_web_applications$samples/Creating_a_collapsing_horizontal_container?revision=980099" width="500" height="200" class="live-sample-frame sample-code-frame" frameborder="0" id="frame_Creating_a_collapsing_horizontal_container"></iframe></p>
<h2 id="See_also" name="See_also">関連情報</h2>
<ul>
<li><a href="/ja/docs/Web/Guide/CSS/Flexible_boxes">CSS flexible box の利用</a></li>
</ul> |
const AppError = require('./../utils/appError');
const sendErrorDevelopment = (err, req, res) => {
if(req.originalUrl.startsWith('/api'))
{
return res.status(err.statusCode).json({
status: err.status,
statusCode: err.statusCode,
message: err.message,
error: err,
stack: err.stack
});
}
return res.status(err.statusCode).render('error', {
title: 'Error Occured',
msg: err.message
})
}
const sendErrorProduction = (err, req, res) => {
// if this error is operational : means user can see the error that he made not comming from us as a programmers
if(err.isOperational)
{
if(req.originalUrl.startsWith('/api'))
{
return res.status(err.statusCode).json({
status: err.status,
message: err.message
})
}
return res.status(err.statusCode).render('error', {
title: 'Error Occured',
msg: err.message
})
}
// other wise he should see that it was an error we need to fix weather it is from us as a programmers or we forgot to mark it as an operational error
// we then output the error to us to see it
console.error('Error Happened: ', err);
// we then send our response to user
if(req.originalUrl.startsWith('/api'))
return res.status(500).json({
status: 'error',
message: 'Something went very wrong!'
});
res.status(500).render('error', {
title: 'Error Occured',
msg: 'Please, try again later.'
})
}
function handleCastError(err){
const message = `Invalid ${err.path} = ${err.value}`;
return new AppError(message, 400);
}
function handleDuplicateFieldError(err){
const message = `dublicate ${Object.keys(err.keyValue)} : ${Object.values(err.keyValue)}, please use another value`;
return new AppError(message, 400)
}
function handleValidationErrorDB(err){
const keys = Object.keys(err.errors);
let message = err.errors[keys[0]];
keys.shift();
keys.forEach(data => message += `, ${err.errors[data].message}`);
return new AppError(message, 400);
}
function handleTokenSignatureError(){
return new AppError('Token signature error, please login again to have access.', 401);
}
function handleTokenExpiredError(){
return new AppError('Token Expired, please login again to have access.', 401);
}
const globalErrorHandler = (err, req, res, next) => {
err.status = err.status || 'error';
err.statusCode = err.statusCode || 500;
if(process.env.NODE_ENV === 'development')
sendErrorDevelopment(err, req, res);
else if(process.env.NODE_ENV === 'production')
{
let error = {...err};
error.message = err.message;
if(err.name === 'CastError') error = handleCastError(error);
if(err.code === 11000) error = handleDuplicateFieldError(error);
if(err.name === 'ValidationError') error = handleValidationErrorDB(error);
if(err.name === 'TokenExpiredError') error = handleTokenExpiredError();
if(err.name === 'JsonWebTokenError') error = handleTokenSignatureError();
sendErrorProduction(error, req, res);
}
}
module.exports = globalErrorHandler; |
package net.x3djsonld.data;
import org.web3d.x3d.jsail.Core.*;
import org.web3d.x3d.jsail.EnvironmentalEffects.*;
import org.web3d.x3d.jsail.fields.*;
import org.web3d.x3d.jsail.Geometry2D.*;
import org.web3d.x3d.jsail.Grouping.*;
import org.web3d.x3d.jsail.Lighting.*;
import org.web3d.x3d.jsail.Navigation.*;
import org.web3d.x3d.jsail.Networking.*;
import org.web3d.x3d.jsail.Scripting.*;
import org.web3d.x3d.jsail.Shape.*;
import org.web3d.x3d.jsail.Texturing.*;
// Javadoc metadata annotations follow, see below for X3DJSAIL Java source code.
/**
* <p> X3D utilizing ecmascript to develop quasi volumetric 3D clouds from png image textured billboard nodes. </p>
<p> Related links: <a href="../../../../Environment/Atmosphere/CloudsProcedural4.java">CloudsProcedural4.java</a> source, <a href="../../../../Environment/Atmosphere/CloudsProcedural4Index.html" target="_top">CloudsProcedural4 catalog page</a>, <a href="https://www.web3d.org/x3d/content/examples/X3dResources.html" target="_blank">X3D Resources</a>, <a href="https://www.web3d.org/x3d/content/examples/X3dSceneAuthoringHints.html" target="_blank">X3D Scene Authoring Hints</a>, and <a href="https://www.web3d.org/x3d/content/X3dTooltips.html" target="_blank">X3D Tooltips</a>. </p>
<table style="color:black; border:0px solid; border-spacing:10px 0px;">
<caption>Scene Meta Information</caption>
<tr style="background-color:silver; border-color:silver;">
<td style="text-align:center; padding:10px 0px;"><i>meta tags</i></td>
<td style="text-align:left; padding:10px 0px;"> Document Metadata </td>
</tr>
<tr>
<td style="text-align:right; vertical-align: text-top;"> <i> title </i> </td>
<td> <a href="../../../../Environment/Atmosphere/CloudsProcedural4.x3d">CloudsProcedural4.x3d</a> </td>
</tr>
<tr>
<td style="text-align:right; vertical-align: text-top;"> <i> description </i> </td>
<td> X3D utilizing ecmascript to develop quasi volumetric 3D clouds from png image textured billboard nodes. </td>
</tr>
<tr>
<td style="text-align:right; vertical-align: text-top;"> <i> creator </i> </td>
<td> Capt Darren W. Murphy </td>
</tr>
<tr>
<td style="text-align:right; vertical-align: text-top;"> <i> created </i> </td>
<td> 1 November 2007 </td>
</tr>
<tr>
<td style="text-align:right; vertical-align: text-top;"> <i> modified </i> </td>
<td> 14 January 2014 </td>
</tr>
<tr>
<td style="text-align:right; vertical-align: text-top;"> <i> identifier </i> </td>
<td> <a href="https://savage.nps.edu/Savage/Environment/Atmosphere/CloudsProcedural4.x3d" target="_blank">https://savage.nps.edu/Savage/Environment/Atmosphere/CloudsProcedural4.x3d</a> </td>
</tr>
<tr>
<td style="text-align:right; vertical-align: text-top;"> <i> generator </i> </td>
<td> X3D-Edit, <a href="https://www.web3d.org/x3d/content/README.X3D-Edit.html" target="_blank">https://www.web3d.org/x3d/content/README.X3D-Edit.html</a> </td>
</tr>
<tr>
<td style="text-align:right; vertical-align: text-top;"> <i> license </i> </td>
<td> <a href="../../../../Environment/Atmosphere/../../license.html">../../license.html</a> </td>
</tr>
<tr>
<td style="text-align:right; vertical-align: text-top;"> <i> TODO </i> </td>
<td> fix links </td>
</tr>
<tr style="background-color:silver; border-color:silver;">
<td style="text-align:center;" colspan="2"> </td>
</tr>
</table>
<p>
This program uses the
<a href="https://www.web3d.org/specifications/java/X3DJSAIL.html" target="_blank">X3D Java Scene Access Interface Library (X3DJSAIL)</a>.
It has been produced using the
<a href="https://www.web3d.org/x3d/stylesheets/X3dToJava.xslt" target="_blank">X3dToJava.xslt</a>
stylesheet
(<a href="https://sourceforge.net/p/x3d/code/HEAD/tree/www.web3d.org/x3d/stylesheets/X3dToJava.xslt" target="_blank">version&nbsp;control</a>)
is used to create Java source code from an original <code>.x3d</code> model.
</p>
* @author Capt Darren W. Murphy
*/
public class CloudsProcedural4
{
/** Default constructor to create this object. */
public CloudsProcedural4 ()
{
initialize();
}
/** Create and initialize the X3D model for this object. */
public final void initialize()
{
try { // catch-all
x3dModel = new X3D().setProfile(X3D.PROFILE_IMMERSIVE).setVersion(X3D.VERSION_3_2)
.setHead(new head()
.addMeta(new meta().setName(meta.NAME_TITLE ).setContent("CloudsProcedural4.x3d"))
.addMeta(new meta().setName(meta.NAME_DESCRIPTION).setContent("X3D utilizing ecmascript to develop quasi volumetric 3D clouds from png image textured billboard nodes."))
.addMeta(new meta().setName(meta.NAME_CREATOR ).setContent("Capt Darren W. Murphy"))
.addMeta(new meta().setName(meta.NAME_CREATED ).setContent("1 November 2007"))
.addMeta(new meta().setName(meta.NAME_MODIFIED ).setContent("14 January 2014"))
.addMeta(new meta().setName(meta.NAME_IDENTIFIER ).setContent("https://savage.nps.edu/Savage/Environment/Atmosphere/CloudsProcedural4.x3d"))
.addMeta(new meta().setName(meta.NAME_GENERATOR ).setContent("X3D-Edit, https://www.web3d.org/x3d/content/README.X3D-Edit.html"))
.addMeta(new meta().setName(meta.NAME_LICENSE ).setContent("../../license.html"))
.addMeta(new meta().setName(meta.NAME_TODO ).setContent("fix links")))
.setScene(new Scene()
.addComments(" A png image file for the cloud texture must be designated in the ecmascript node. ")
.addChild(new Viewpoint().setDescription("Main").setJump(false).setOrientation(0.0,1.0,0.0,1.57).setPosition(50000.0,1000.0,42000.0))
.addChild(new Viewpoint().setDescription("Light House Tower").setJump(false).setOrientation(0.0,1.0,0.0,1.3).setPosition(45000.0,1290.0,44000.0))
.addChild(new Viewpoint().setDescription("centerWest").setJump(false).setOrientation(0.0,1.0,0.0,2.5).setPosition(48000.0,1000.0,20000.0))
.addChild(new Background().setGroundColor(new MFColor(new double[] {0.0,0.0,1.0})).setSkyColor(new MFColor(new double[] {0.0,0.0,1.0})))
.addChild(new DirectionalLight().setAmbientIntensity(1).setDirection(-1.0,0.0,0.0).setGlobal(true))
.addChild(new Group("Terrain")
.addChild(new Transform().setScale(50.0,50.0,50.0).setTranslation(25000.0,0.0,25000.0)
.addChild(new Inline().setUrl(new String[] {"MontereyBayLargeMesh.x3d","https://savage.nps.edu/Savage/Environment/Atmosphere/MontereyBayLargeMesh.x3d","MontereyBayLargeMesh.wrl","https://savage.nps.edu/Savage/Environment/Atmosphere/MontereyBayLargeMesh.wrl"})))
.addChild(new Transform().setRotation(1.0,0.0,0.0,1.57).setTranslation(25000.0,0.0,25000.0)
.addChild(new Shape()
.setGeometry(new Rectangle2D().setSize(77000.0,55000.0))
.setAppearance(new Appearance()
.setTexture(new ImageTexture().setUrl(new String[] {"ocean.png","https://savage.nps.edu/Savage/Environment/Atmosphere/ocean.png"}))))))
.addChild(new Group("Placemarks")
.addChild(new Transform().setScale(50.0,50.0,50.0).setTranslation(45000.0,30.0,44000.0)
.addChild(new Inline().setUrl(new String[] {"Lighthouse.x3d","https://savage.nps.edu/Savage/Environment/Atmosphere/Lighthouse.x3d","Lighthouse.wrl","https://savage.nps.edu/Savage/Environment/Atmosphere/Lighthouse.wrl"}))))
.addChild(new Group("Clouds")
.addChild(new Transform("Cumulus"))
.addChild(new Transform("Cirrus"))
.addChild(new Transform("Fog"))
.addChild(new Script("PixelScript").setDirectOutput(true).setSourceCode("""
ecmascript:
Cirrus.children = [];
function cumulustranslation() // These values designate the boundary location of the cloud
{
X = 50000*Math.random(); // X horizontal range
Y = 1000 + 300*Math.random(); // Y vertical base + range
Z = 50000*Math.random(); // z horizontal range
randomt = new String(X+' '+Y+' '+Z);
return randomt;
}
function cumulusscale() // these values scale a cloud within a designated size
{
var maxscale = 1;
scale = Math.round(9+maxscale*Math.random());
X = 1.5*scale;
Y = scale;
Z = scale;
randomscale = new String(X+' '+Y+' '+Z);
return randomscale;
}
function cirrustranslation() // These values designate the boundary location of the cloud
{
X = 50000*Math.random(); // X horizontal range
Y = 8000 + 1000*Math.random(); // Y vertical base + range
Z = 50000*Math.random(); // z horizontal range
randomt = new String(X+' '+Y+' '+Z);
return randomt;
}
function cirrusscale() // these values scale a cloud within a designated size
{
var maxscale = 1;
scale = Math.round(9+maxscale*Math.random());
X = 1.5*scale;
Y = 2*Math.random();
Z = 1.5*scale;
randomscale = new String(X+' '+Y+' '+Z);
return randomscale;
}
function cumulussectiontranslation() // These random values place another portion of cumulus type cloud
{
randomtheta = 6.28319*Math.random();
randomphi = .7854*Math.random();
randomradius = 90 + 5*Math.random();//the first whole number should be close to the sectionradius
X = randomradius*Math.cos(randomtheta)*Math.sin(randomphi);
Z = randomradius*Math.sin(randomtheta)*Math.sin(randomphi);
Y = randomradius*Math.cos(randomphi);
randomt = new String(X+' '+Y+' '+Z);
return randomt;
}
function cirrussectiontranslation() // These random values place another portion of cirrus type cloud
{
randomtheta = 6.28319*Math.random();
randomphi = .7854*Math.random();
randomradius = 90 + 5*Math.random();//the first whole number should be close to the sectionradius
X = randomradius*Math.cos(randomtheta)*Math.sin(randomphi);
Z = randomradius*Math.sin(randomtheta)*Math.sin(randomphi);
Y = randomradius*Math.cos(randomphi);
randomt = new String(X+' '+Y+' '+Z);
return randomt;
}
function rotation() // This random value is for the billboard rotation not used in this script
{
radians = 6.28*Math.random();
randomr = new String('0 0 1 ' + radians );
return randomr;
}
function cumulus()
{
var maxi = 20; // number of clouds
var maxj = 5; // denotes how many portions affecting the size of the cloud
var maxk = 8; // number of billboards indicating cloud density
var sectionradius = 100; //radius of individual cloud sections
for (var i=0; i < maxi; i++)
{
CloudStringA = ' Transform { \n' +
' scale '+ cumulusscale() + ' \n' +
' translation '+ cumulustranslation() + ' \n' + // cloud placement
' children [ \n';
CloudStringB = new Array();
CloudStringF = new Array();
for (var j=0; j < maxj; j++)
{
radius = 0;
CloudStringB[j]= ' Transform { \n' +
' translation '+ cumulussectiontranslation() + ' \n' + // section placement
' children [ \n';
CloudStringC = new Array();
image = new String();
for (var k=1; k < maxk; k++) // maxk value denotes how many textured billboards make up the cloud
{
randomtheta = 6.28319*Math.random();
randomphi = 1.57079*Math.random();
radius = radius+(sectionradius/maxk); // radius incremental steps based on billow radius and max billboards
X = radius*Math.cos(randomtheta)*Math.sin(randomphi);
Z = radius*Math.sin(randomtheta)*Math.sin(randomphi);
Y = radius*Math.cos(randomphi);
if (Y <= 30) //cloud shading and lighting control
{
image = ' \"CloudTexture1_5.png\" \"https://savage.nps.edu/Savage/Environment/Spheretexture.png\" \n';
}
else
{
image = ' \"CloudTexture1_4.png\" \"https://savage.nps.edu/Savage/Environment/Spheretexture.png\" \n';
}
Billboardtranslation = new String(X+' '+Y+' '+Z);
CloudStringC[k] = ' Transform { \n' +
' translation '+ Billboardtranslation + ' \n' + // random billboard placement within radius designated above
' children [ \n' +
' Billboard { \n' +
' axisOfRotation 0 0 0 \n' + // 0 0 0 designates rotation on all axis
' children [ \n' +
' Transform { \n' +
' rotation 0 0 0 0 \n' + // a rotation of the individual billboards can be defined
' children [ \n' +
' Shape { \n' +
' appearance Appearance { \n' +
' material Material { \n' +
' } \n' +
' texture ImageTexture { \n' +
' url [ ' + image + ' ] \n' +
' } \n' +
' } \n' +
' geometry IndexedFaceSet { \n' + // define type of geometry to texture
' coordIndex [ 0, 1, 2, 3 ] \n' +
' solid FALSE \n' +
' coord Coordinate { \n' +
' point [ 50 50 0, \n' + // define size of the geometry. Here 100 meter 2D square.
' 50 -50 0, \n' +
' -50 -50 0, \n' +
' -50 50 0 ] \n' +
' } \n' +
' } \n' +
' } \n' +
' ] \n' +
' } \n' +
' ] \n' +
' } \n' +
' ] \n' +
' } \n';
}
CloudStringD = CloudStringC.join(' ');
CloudStringE = ' ] \n' +
' } \n';
CloudStringF[j] = CloudStringB[j] + CloudStringD +CloudStringE;
}
CloudStringG = CloudStringF.join(' ');
CloudStringH = ' ] \n' +
' } \n' +
'######################################################### \n';
CloudString = CloudStringA + CloudStringG + CloudStringH;
newNode = Browser.createVrmlFromString(CloudString);
Cumulus.children[i] = newNode[0];
}
}
function cirrus()
{
var maxi = 2; // number of clouds
var maxj = 5; // denotes how many portions affecting the size of the cloud
var maxk = 8; // number of billboards indicating cloud density
var sectionradius = 1000; //radius of individual cloud sections
for (var i=0; i < maxi; i++)
{
CloudStringA = ' Transform { \n' +
' scale '+ cirrusscale() + ' \n' +
' translation '+ cirrustranslation() + ' \n' + // cloud placement
' children [ \n';
CloudStringB = new Array();
CloudStringF = new Array();
for (var j=0; j < maxj; j++)
{
radius = 0;
CloudStringB[j]= ' Transform { \n' +
' translation '+ cirrussectiontranslation() + ' \n' + // section placement
' children [ \n';
CloudStringC = new Array();
for (var k=1; k < maxk; k++) // maxk value denotes how many textured billboards make up the cloud
{
randomtheta = 6.28319*Math.random();
randomphi = 1.57079*Math.random();
radius = radius+(sectionradius/maxk); // radius incremental steps based on section radius and max billboards
X = radius*Math.cos(randomtheta)*Math.sin(randomphi);
Z = radius*Math.sin(randomtheta)*Math.sin(randomphi);
Y = radius*Math.cos(randomphi);
Billboardtranslation = new String(X+' '+Y+' '+Z);
CloudStringC[k] = ' Transform { \n' +
' translation '+ Billboardtranslation + ' \n' + // random billboard placement within radius designated above
' children [ \n' +
' Billboard { \n' +
' axisOfRotation 0 0 0 \n' + // 0 0 0 designates rotation on all axis
' children [ \n' +
' Transform { \n' +
' rotation ' + rotation() + ' \n' +
' children [ \n' +
' Shape { \n' +
' appearance Appearance { \n' +
' material Material { \n' +
' } \n' +
' texture ImageTexture { \n' +
' url [\"cloudtexture3.png\" \"https://savage.nps.edu/Savage/Environment/cloudtexture1_4.png\" ] \n' +
' } \n' +
' } \n' +
' geometry IndexedFaceSet { \n' + // define type of geometry to texture
' coordIndex [ 0, 1, 2, 3 ] \n' +
' solid FALSE \n' +
' coord Coordinate { \n' +
' point [ 500 500 0, \n' + // define size of the geometry. Here 100 meter 2D square.
' 500 -500 0, \n' +
' -500 -500 0, \n' +
' -500 500 0 ] \n' +
' } \n' +
' } \n' +
' } \n' +
' ] \n' +
' } \n' +
' ] \n' +
' } \n' +
' ] \n' +
' } \n';
}
CloudStringD = CloudStringC.join(' ');
CloudStringE = ' ] \n' +
' } \n';
CloudStringF[j] = CloudStringB[j] + CloudStringD +CloudStringE;
}
CloudStringG = CloudStringF.join(' ');
CloudStringH = ' ] \n' +
' } \n' +
'######################################################### \n';
CloudString = CloudStringA + CloudStringG + CloudStringH;
newNode = Browser.createVrmlFromString(CloudString);
Cirrus.children[i] = newNode[0];
}
}
function initialize()
{
cumulus();
cirrus();
}
""")
.addField(new field().setName("Cumulus").setType(field.TYPE_SFNODE).setAccessType(field.ACCESSTYPE_INITIALIZEONLY)
.addChild(new Transform().setUSE("Cumulus")))
.addField(new field().setName("Cirrus").setType(field.TYPE_SFNODE).setAccessType(field.ACCESSTYPE_INITIALIZEONLY)
.addChild(new Transform().setUSE("Cirrus")))
.addField(new field().setName("Fog").setType(field.TYPE_SFNODE).setAccessType(field.ACCESSTYPE_INITIALIZEONLY)))
.addChild(new DirectionalLight().setAmbientIntensity(1).setColor(1.0,0.0,0.0).setDirection(-1.0,-1.0,0.0).setGlobal(true))));
}
catch (Exception ex)
{
System.err.println ("*** Further hints on X3DJSAIL errors and exceptions at");
System.err.println ("*** https://www.web3d.org/specifications/java/X3DJSAIL.html");
throw (ex);
}
}
// end of initialize() method
/** The initialized model object, created within initialize() method. */
private X3D x3dModel;
/**
* Provide a
* <a href="https://dzone.com/articles/java-copy-shallow-vs-deep-in-which-you-will-swim" target="_blank">shallow copy</a>
* of the X3D model.
* @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/Core/X3D.html">X3D</a>
* @return CloudsProcedural4 model
*/
public X3D getX3dModel()
{
return x3dModel;
}
/**
* Default main() method provided for test purposes, uses CommandLine to set global ConfigurationProperties for this object.
* @param args array of input parameters, provided as arguments
* @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/Core/X3D.html#handleArguments-java.lang.String:A-">X3D.handleArguments(args)</a>
* @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/Core/X3D.html#validationReport--">X3D.validationReport()</a>
* @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/CommandLine.html">CommandLine</a>
* @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/CommandLine.html#USAGE">CommandLine.USAGE</a>
* @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/ConfigurationProperties.html">ConfigurationProperties</a>
*/
public static void main(String args[])
{
X3D thisExampleX3dModel = new CloudsProcedural4().getX3dModel();
// System.out.println("X3D model construction complete.");
// next handle command line arguments
boolean hasArguments = (args != null) && (args.length > 0);
boolean validate = true; // default
boolean argumentsLoadNewModel = false;
String fileName = new String();
if (args != null)
{
for (String arg : args)
{
if (arg.toLowerCase().startsWith("-v") || arg.toLowerCase().contains("validate"))
{
validate = true; // making sure
}
if (arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_X3D) ||
arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_CLASSICVRML) ||
arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_X3DB) ||
arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_VRML97) ||
arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_EXI) ||
arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_GZIP) ||
arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_ZIP) ||
arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_HTML) ||
arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_XHTML))
{
argumentsLoadNewModel = true;
fileName = arg;
}
}
}
if (argumentsLoadNewModel)
System.out.println("WARNING: \"net.x3djsonld.data.CloudsProcedural4\" model invocation is attempting to load file \"" + fileName + "\" instead of simply validating itself... file loading ignored.");
else if (hasArguments) // if no arguments provided, this method produces usage warning
thisExampleX3dModel.handleArguments(args);
if (validate)
{
System.out.print("Java program \"net.x3djsonld.data.CloudsProcedural4\" self-validation test results: ");
String validationResults = thisExampleX3dModel.validationReport();
if (validationResults.length() > 10)
System.out.println();
System.out.println(validationResults);
}
}
} |
import { cbtPrint } from 'hy-algokit'
class Heap<T> {
data: T[] = []
// 交换
swap(x: number, y: number) {
let temp = this.data[x]
this.data[x] = this.data[y]
this.data[y] = temp
}
insert(ele: T) {
this.heapifyUp(ele)
}
// 上滤操作
heapifyUp(ele: T) {
this.data.push(ele)
let index = this.data.length - 1
while (index > 0) {
let parentIdx = Math.floor((index - 1) / 2)
const flag = this.data[index] > this.data[parentIdx]
if (!flag) break
// 如果插入的元素 > 父元素 需要进行上滤操作
this.swap(index, parentIdx)
index = parentIdx
}
}
// 提取
extract() {
// 1. 第一个值与最后一位交换位置
this.swap(0, this.data.length - 1)
// 2. 返回最后一个值
const top = this.data.pop()
// // 3.1 根节点与左右节点中最大的节点进行比获取较大的节点的索引
// // 3.2 如果较大的值,比我根的值大交换位置,否则break
let index = 0
// 3.3 有左子节点才需要进行比较
while (index * 2 + 1 < this.data.length) {
const leftNodeIndex = index * 2 + 1
const rightNodeIndex = leftNodeIndex + 1
let largeIndex = leftNodeIndex
if (this.data[rightNodeIndex] > this.data[leftNodeIndex]) {
largeIndex = rightNodeIndex
}
if (this.data[index] >= this.data[largeIndex]) break
this.swap(index, largeIndex)
index = largeIndex
}
return top
}
peek() {}
get size() {
return this.data.length
}
isEmpty() {
return !this.data.length
}
buildHeap() {}
}
const heap = new Heap<number>()
heap.insert(100)
heap.insert(19)
heap.insert(35)
heap.insert(17)
heap.insert(3)
heap.insert(25)
heap.insert(1)
heap.insert(2)
heap.insert(7)
heap.insert(-7)
heap.insert(10)
cbtPrint(heap.data)
while (!heap.isEmpty()) {
console.log(heap.extract())
}
export {} |
import "./globals.css";
import { Toaster } from "react-hot-toast";
import { Suspense } from "react";
import type { Metadata } from "next";
import { Nunito } from "next/font/google";
import Navbar from "@/components/custom/Navbar";
import Loading from "./loading";
const nunito = Nunito({
weight: ["300", "400", "600"],
subsets: ["latin"],
variable: "--font-nunito",
});
export const metadata: Metadata = {
title: "Anyone can learn DynamoDB",
description:
"This application aims to teach DynamoDB to anyone who is interested to this amazing database.",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={`${nunito.variable} px-8 font-nunito font-light`}>
<Navbar />
<Suspense fallback={<Loading />}>{children}</Suspense>
<Toaster position="top-right" />
</body>
</html>
);
} |
package road.core;
/**
*
* V2d represents a vector in a 2d space
*
*/
public record V2d(double x, double y) {
public static V2d makeV2d(final P2d from, final P2d to) {
return new V2d(to.x() - from.x(), to.y() - from.y());
}
public V2d sum(final V2d v){
return new V2d(this.x +v.x, this.y +v.y);
}
public double abs(){
return Math.sqrt(this.x * this.x + this.y * this.y);
}
public V2d getNormalized(){
final double module= Math.sqrt(this.x * this.x + this.y * this.y);
return new V2d(this.x /module, this.y /module);
}
public V2d mul(final double fact){
return new V2d(this.x *fact, this.y *fact);
}
public String toString(){
return "V2d("+ this.x +","+ this.y +")";
}
} |
// Copyright © 2023 Apple Inc.
#include <cassert>
#include <functional>
#include <limits>
#include "mlx/backend/common/reduce.h"
#include "mlx/primitives.h"
namespace mlx::core {
namespace {
template <typename U>
struct Limits {
static const U max;
static const U min;
};
#define instantiate_default_limit(type) \
template <> \
struct Limits<type> { \
static constexpr type max = std::numeric_limits<type>::max(); \
static constexpr type min = std::numeric_limits<type>::min(); \
};
instantiate_default_limit(uint8_t);
instantiate_default_limit(uint16_t);
instantiate_default_limit(uint32_t);
instantiate_default_limit(uint64_t);
instantiate_default_limit(int8_t);
instantiate_default_limit(int16_t);
instantiate_default_limit(int32_t);
instantiate_default_limit(int64_t);
#define instantiate_float_limit(type) \
template <> \
struct Limits<type> { \
static const type max; \
static const type min; \
};
instantiate_float_limit(float16_t);
instantiate_float_limit(bfloat16_t);
instantiate_float_limit(float);
instantiate_float_limit(complex64_t);
template <>
struct Limits<bool> {
static constexpr bool max = true;
static constexpr bool min = false;
};
const float Limits<float>::max = std::numeric_limits<float>::infinity();
const float Limits<float>::min = -std::numeric_limits<float>::infinity();
const bfloat16_t Limits<bfloat16_t>::max =
std::numeric_limits<float>::infinity();
const bfloat16_t Limits<bfloat16_t>::min =
-std::numeric_limits<float>::infinity();
const float16_t Limits<float16_t>::max = std::numeric_limits<float>::infinity();
const float16_t Limits<float16_t>::min =
-std::numeric_limits<float>::infinity();
const complex64_t Limits<complex64_t>::max =
std::numeric_limits<float>::infinity();
const complex64_t Limits<complex64_t>::min =
-std::numeric_limits<float>::infinity();
struct AndReduce {
template <typename T>
void operator()(bool* a, T b) {
(*a) &= (b != 0);
}
void operator()(bool* y, bool x) {
(*y) &= x;
}
};
struct OrReduce {
template <typename T>
void operator()(bool* a, T b) {
(*a) |= (b != 0);
}
void operator()(bool* y, bool x) {
(*y) |= x;
}
};
template <typename InT>
void reduce_dispatch_out(
const array& in,
array& out,
Reduce::ReduceType rtype,
const std::vector<int>& axes) {
switch (rtype) {
case Reduce::And: {
reduction_op<InT, bool>(in, out, axes, true, AndReduce());
break;
}
case Reduce::Or: {
reduction_op<InT, bool>(in, out, axes, false, OrReduce());
break;
}
case Reduce::Sum: {
auto op = [](auto y, auto x) { (*y) = (*y) + x; };
switch (out.dtype()) {
case bool_:
reduction_op<InT, bool>(in, out, axes, false, op);
break;
case uint8:
reduction_op<InT, uint8_t>(in, out, axes, 0, op);
break;
case uint16:
reduction_op<InT, uint16_t>(in, out, axes, 0, op);
break;
case uint32:
reduction_op<InT, uint32_t>(in, out, axes, 0, op);
break;
case uint64:
reduction_op<InT, uint64_t>(in, out, axes, 0, op);
break;
case int8:
reduction_op<InT, int8_t>(in, out, axes, 0, op);
break;
case int16:
reduction_op<InT, int16_t>(in, out, axes, 0, op);
break;
case int32:
reduction_op<InT, int32_t>(in, out, axes, 0, op);
break;
case int64:
reduction_op<InT, int64_t>(in, out, axes, 0, op);
break;
case float16:
reduction_op<InT, float16_t>(in, out, axes, 0.0f, op);
break;
case float32:
reduction_op<InT, float>(in, out, axes, 0.0f, op);
break;
case bfloat16:
reduction_op<InT, bfloat16_t>(in, out, axes, 0.0f, op);
break;
case complex64:
reduction_op<InT, complex64_t>(in, out, axes, complex64_t{0.0f}, op);
break;
}
} break;
case Reduce::Prod: {
auto op = [](auto y, auto x) { (*y) *= x; };
reduction_op<InT, InT>(in, out, axes, 1, op);
break;
}
case Reduce::Max: {
auto op = [](auto y, auto x) { (*y) = (*y > x) ? *y : x; };
auto init = Limits<InT>::min;
reduction_op<InT, InT>(in, out, axes, init, op);
break;
}
case Reduce::Min: {
auto op = [](auto y, auto x) { (*y) = (*y < x) ? *y : x; };
auto init = Limits<InT>::max;
reduction_op<InT, InT>(in, out, axes, init, op);
break;
}
}
}
} // namespace
void Reduce::eval(const std::vector<array>& inputs, array& out) {
assert(inputs.size() == 1);
auto& in = inputs[0];
switch (in.dtype()) {
case bool_:
reduce_dispatch_out<bool>(in, out, reduce_type_, axes_);
break;
case uint8:
reduce_dispatch_out<uint8_t>(in, out, reduce_type_, axes_);
break;
case uint16:
reduce_dispatch_out<uint16_t>(in, out, reduce_type_, axes_);
break;
case uint32:
reduce_dispatch_out<uint32_t>(in, out, reduce_type_, axes_);
break;
case uint64:
reduce_dispatch_out<uint64_t>(in, out, reduce_type_, axes_);
break;
case int8:
reduce_dispatch_out<uint8_t>(in, out, reduce_type_, axes_);
break;
case int16:
reduce_dispatch_out<uint16_t>(in, out, reduce_type_, axes_);
break;
case int32:
reduce_dispatch_out<int32_t>(in, out, reduce_type_, axes_);
break;
case int64:
reduce_dispatch_out<int64_t>(in, out, reduce_type_, axes_);
break;
case float16:
reduce_dispatch_out<float16_t>(in, out, reduce_type_, axes_);
break;
case float32:
reduce_dispatch_out<float>(in, out, reduce_type_, axes_);
break;
case bfloat16:
reduce_dispatch_out<bfloat16_t>(in, out, reduce_type_, axes_);
break;
case complex64:
reduce_dispatch_out<complex64_t>(in, out, reduce_type_, axes_);
break;
}
}
} // namespace mlx::core |
<script setup>
import { reactive } from 'vue';
import DeleteBtn from './DeleteBtn.vue';
const pokemon = reactive({
savedPokemon:[],
signedInEmail: localStorage.getItem('userEmail') || ''
})
let user = pokemon.signedInEmail
import { computed } from 'vue';
const filteredPokemon = computed(() => {
if (!user) return [];
return pokemon.savedPokemon.filter(pokemon => pokemon.email === user);
});
/*
This line creates a reactive computed property called filteredPokemon,
which filters the pokemon.savedPokemon array based on the current user's email,
returning an empty array if there's no user.
*/
const getAllPokemon = async () => {
try {
const res = await fetch("https://pokemon-chi-smoky.vercel.app/api/v1/pokemon/allPokemon", {
method: "GET",
headers: {
'Content-Type': 'application/json',
},
});
if (!res.ok) {
console.log(res)
throw new Error('Failed to add Pokemon');
}
const data = await res.json();
pokemon.savedPokemon.splice(0, pokemon.savedPokemon.length, ...data.findAllPokemon); /*
The line pokemon.savedPokemon.splice(0, pokemon.savedPokemon.length, ...data.findAllPokemon);
updates the pokemon.savedPokemon array with the most recent data fetched from the server by
clearing the array and replacing its contents with the new data.
*/
return data;
} catch (error) {
console.error('Error adding Pokemon:', error);
}
};
getAllPokemon()
</script>
<template>
<div>
<div class="pokemonContainer" v-if="user">
<div v-for="pokemon in filteredPokemon" :key="pokemon._id">
<img class="pokemonImg" :src="pokemon.url" :alt="pokemon.name" />
<p class="pokemonName">{{ pokemon.name }}</p>
<DeleteBtn :id="pokemon._id" :getAllPokemon="getAllPokemon"/>
</div>
</div>
<div v-else>
<p class="signInMsg">Please sign in to view your Pokedex</p>
</div>
</div>
</template>
<style lang="scss" scoped>
.pokemonContainer{
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
text-align: center;
gap: 100px;
margin-top: 100px;
img{
width: 120px;
}
p{
margin: 20px 0;
font-size: 1.25rem;
font-weight: bold;
}
}
.signInMsg{
color: #CC0000;
text-align: center;
font-size: 2rem;
margin-top: 50px;
}
</style> |
import React, { useState, useEffect } from 'react';
import {
Box, Flex, Text, IconButton, Stack, useColorModeValue,
Icon, Button, Menu, MenuButton, MenuList, MenuItem,
Avatar, Image
} from "@chakra-ui/react";
import {
FiHome, FiMenu, FiUser, FiBarChart2, FiBookOpen, FiInfo, FiLogOut, FiActivity
} from "react-icons/fi";
import { useAuth } from "@/context/AuthContext";
import { useRouter } from "next/router";
import NextLink from "next/link";
export default function HomeLayout({ children }) {
const [isClient, setIsClient] = useState(false);
const { isAuthenticated, loading, logout, user } = useAuth();
const [isSidebarOpen, setSidebarOpen] = useState(true);
const navBg = useColorModeValue("white", "gray.800");
const router = useRouter();
useEffect(() => {
if (!isAuthenticated && !loading) {
router.push("/");
}
setIsClient(true);
}, [isAuthenticated, loading, router]);
if (!isClient) {
return null;
}
const isUser = user && user.role === 'USER';
const isUserAdmin = user && user.role === 'ADMIN';
const isUserProfesor = user && user.role === 'PROFESOR';
const sidebarWidth = isSidebarOpen ? "300px" : "80px";
const SidebarContent = props => (
<Box
transition="0.3s ease"
bg={navBg}
borderRight="1px"
borderRightColor={useColorModeValue("gray.200", "gray.700")}
w={sidebarWidth}
pos="fixed"
h="full"
{...props}
>
<Flex
h="20"
alignItems="center"
justifyContent="space-between"
px="4"
>
<IconButton
onClick={() => setSidebarOpen(!isSidebarOpen)}
icon={<FiMenu />}
size="lg"
variant="ghost"
aria-label={isSidebarOpen ? "Collapse Menu" : "Expand Menu"}
/>
</Flex>
<Stack p="0">
<SidebarItem icon={FiHome} title="Inicio" href="/home" />
<SidebarItem icon={FiBookOpen} title="Cursos" href="/cursos" />
{ (isUserAdmin || isUserProfesor) && (
<SidebarItem icon={FiActivity} title="Monitoreo" href="/monitoreo" />
)}
<SidebarItem icon={FiBarChart2} title="Mis Estadísticas" href="/estadisticas" />
{isUserAdmin && (
<SidebarItem icon={FiUser} title="Usuarios" href="/usuarios" />
)}
<SidebarItem icon={FiInfo} title="Acerca de" href="/about" />
<Button leftIcon={<FiLogOut />} variant="ghost" justifyContent="start" onClick={() => logout()} display={isSidebarOpen ? "flex" : "none"}>
Cerrar Sesión
</Button>
</Stack>
</Box>
);
const SidebarItem = ({ icon, title, href }) => (
<NextLink href={href} passHref>
<Flex as="a" align="center" p="4" mx="4" borderRadius="lg" role="group" cursor="pointer" _hover={{ bg: 'cyan.400', color: 'white', }}>
<Icon as={icon} fontSize="20" />
<Text ml="4" display={isSidebarOpen ? "block" : "none"}>
{title}
</Text>
</Flex>
</NextLink>
);
const TopNav = () => {
return (
<Flex
align="center"
justify="space-between"
bg={useColorModeValue('purple.500', 'gray.800')}
borderBottomWidth="1px"
borderBottomColor={useColorModeValue('gray.200', 'gray.700')}
px={4}
h="20"
>
<Image
src="/img/GameTitle.png"
alt="El Fraccionista"
height="65%"
/>
<Menu>
<MenuButton as={Button} rounded={'full'} variant={'link'} cursor={'pointer'} minW={0}>
<Icon as={FiUser} w={10} h={10} color="white"/>
</MenuButton>
<MenuList>
<MenuItem as={NextLink} href="/profile">Perfil</MenuItem>
<MenuItem icon={<FiLogOut />} onClick={logout}>Cerrar Sesión</MenuItem>
</MenuList>
</Menu>
</Flex>
);
};
return (
<Box minH="100vh" bg={useColorModeValue('gray.100', 'gray.900')}>
<TopNav />
<SidebarContent onClose={() => setSidebarOpen(!isSidebarOpen)} />
<Box ml={sidebarWidth} transition="0.3s ease">
{children}
</Box>
</Box>
);
} |
import {
Body,
Controller,
Get,
Res,
Req,
HttpCode,
HttpStatus,
Post,
Request,
UnauthorizedException,
UseGuards,
Ip,
} from '@nestjs/common';
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@HttpCode(HttpStatus.OK)
@Post('login')
signIn(@Body() signInDto: Record<string, any>) {
if (!signInDto.username || !signInDto.password)
throw new UnauthorizedException();
this.authService.logUser(signInDto.username);
return this.authService.signIn(
signInDto.role,
signInDto.username,
signInDto.password,
);
}
@HttpCode(HttpStatus.OK)
@Post('google-login')
googleLogin(@Body() signInDto: Record<string, any>, @Ip() ip: string) {
if (!this.authService.isIntranetIp(ip)) {
throw new UnauthorizedException(`Invalid IP: ${ip}`);
}
if (signInDto.passkey !== process.env.CROSS_SECRET)
throw new UnauthorizedException();
this.authService.logUser(signInDto.username);
return this.authService.googleSignIn(signInDto.username);
}
@UseGuards(AuthGuard)
@Post('protected-login')
protectedLogin(@Request() req) {
if (req.user.role !== 'admin') throw new UnauthorizedException();
if (req.body.role === 'changeRole')
return this.authService.changeRole(req.body);
return this.authService.refreshToken(req.user);
}
@UseGuards(AuthGuard)
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
@UseGuards(AuthGuard)
@Post('login-log')
async loginLog(@Res() res, @Body() body, @Req() req) {
if (req.user.role !== 'admin')
return res.sendStatus(HttpStatus.UNAUTHORIZED);
const log = await this.authService.loginLog();
return res.status(HttpStatus.OK).send(log);
}
} |
---
date: '2006-09-14 00:40:00'
layout: post
slug: using-svnsync
status: publish
title: using svnsync
wordpress_id: '163'
---
[Garrett](http://asdf.blogs.com/) helped write svnsync as part of [Subversion 1.4](http://subversion.tigris.org/svn_1.4_releasenotes.html), but I wasn't able to find any documentation for it, other than passing --help.
svnsync is a one way replication system for Subversion. It allows you to create a read-only replica of a repository over any RA layer (including http, https, svn, svn+ssh).
First, lets setup the initial sync. We have two repositories, I will skip the details of [svnadmin create](http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html). For the remote access to the replica repository, I used [svnserve](http://svnbook.red-bean.com/nightly/en/svn.serverconfig.svnserve.html), and I [added a user with full write access](http://svnbook.red-bean.com/nightly/en/svn.serverconfig.svnserve.html#svn.serverconfig.svnserve.auth.users). The destination repository should be completely empty before starting.
So, to make this easier, I am going to put the repository URIs into enviroment variables:
$ export FROMREPO=svn://svn.example.com/
$ export TOREPO=svn://dest.example.com/
Because the svnsync is allowed to rewrite anything on the TOREPO, we need to [make sure the commit hooks](http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html#svn.reposadmin.create.hooks) are configured to allow our 'svnsync' user to do anything it wants.
On the server hosting TOREPO, I ran this:
$ echo "#!/bin/sh" > hooks/pre-revprop-change
$ chmod 755 hooks/pre-revprop-change
Now we are ready to setup the sync:
$ svnsync init ${TOREPO} ${FROMREPO}
This will prompt you for the username, password, and also sets several revision properties on the $TOREPO, for revision zero. It doesn't actually copy any of the data yet. To list the properties that it created, run:
$ svn proplist --revprop -r 0 ${TOREPO}
svn:sync-from-uuid
svn:sync-last-merged-rev
svn:date
svn:sync-from-url
$ svn propget svn:sync-from-url --revprop -r 0 ${TOREPO}
svn://svn.example.com/
So all the knowledge about what we are syncing from is stored at the destination repository. No state about this sync is stored in the source repository.
We are now ready to begin copying data:
$ svnsync --non-interactive sync ${TOREPO}
And if everything is setup correctly, you will start replicating data.
Except, I suck. And the first thing I did was hit control+c. I figured this is a cool replication system, so I just ran the `sync` command from above again, and got this:
$ svnsync --non-interactive sync ${TOREPO}
Failed to get lock on destination repos, currently held by 'svn.example.com:0e4e0d98-631d-0410-9a00-9320a90920b3'
Failed to get lock on destination repos, currently held by 'svn.example.com:0e4e0d98-631d-0410-9a00-9320a90920b3'
Failed to get lock on destination repos, currently held by 'svn.example.com:0e4e0d98-631d-0410-9a00-9320a90920b3'
Failed to get lock on destination repos, currently held by 'svn.example.com:0e4e0d98-631d-0410-9a00-9320a90920b3'
Failed to get lock on destination repos, currently held by 'svn.example.com:0e4e0d98-631d-0410-9a00-9320a90920b3'
Failed to get lock on destination repos, currently held by 'svn.example.com:0e4e0d98-631d-0410-9a00-9320a90920b3'
Failed to get lock on destination repos, currently held by 'svn.example.com:0e4e0d98-631d-0410-9a00-9320a90920b3'
Failed to get lock on destination repos, currently held by 'svn.example.com:0e4e0d98-631d-0410-9a00-9320a90920b3'
Failed to get lock on destination repos, currently held by 'svn.example.com:0e4e0d98-631d-0410-9a00-9320a90920b3'
Failed to get lock on destination repos, currently held by 'svn.example.com:0e4e0d98-631d-0410-9a00-9320a90920b3'
svnsync: Couldn't get lock on destination repos after 10 attempts
Oh snap. I guess its not so easy to restart after an aborted sync.
I started debugging, and found that svnsync kept its lock state in a special property in revision zero again.
So, To fix this, we can safely just delete this lock:
$ svn propdelete svn:sync-lock --revprop -r 0 ${TOREPO}
Now running `sync` again works! Hurrah!
After the sync finishes, we will want to keep the replica up to date.
I personally set a 'live' sync, but it is also possible to [use a crontab](http://www.freebsd.org/cgi/man.cgi?query=crontab&apropos=0&sektion=0&manpath=FreeBSD+6.1-RELEASE&format=html) or other scheduling method to invoke sync whenever you want.
To setup a live sync, on the FROMREPO server, I appended this to my hooks/post-commit file:
svnsync --non-interactive sync svn://dest.example.com/ &
You will want to make sure that the user-running subversion (and the hook script) has a cached copy of the authentication info for the destination repository.
Unfortunately, the post-commit hook won't catch everything, so we also need to added this to the `post-revprop-change` hook:
svnsync --non-interactive copy-revprops svn://dest.example.com/ ${REV} &
This will help propagate things [like editing svn:log messages](http://subversion.tigris.org/faq.html#change-log-msg).
And there you go, thats the path I took to mirror one of my repositories onto another machine. |
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:simple_moment/simple_moment.dart';
import './../../../models/_models/career_opening_model.dart';
import '../../../constants/index.dart';
import './../../../util/helper.dart';
// import './../../../util/faderoute.dart';
// import './../../../ui/screens/index.dart';
class CareerOpeningItem extends StatelessWidget {
final CareerOpening careerOpening;
final dateNow = Moment.now();
CareerOpeningItem(this.careerOpening);
@override
Widget build(BuildContext context) {
return InkWell(
// onTap: () => Navigator.push(
// context,
// FadeRoute(page: ComingSoonScreen()),
// ),
child: Card(
color: Colors.white,
margin: const EdgeInsets.only(left: 10),
child: new Container(
width: 300.0,
decoration: BoxDecoration(
border: Border.all(color: AppColors.grey08),
borderRadius: BorderRadius.all(Radius.circular(4))),
// height: double.infinity,
// padding: EdgeInsets.all(20),
child: Column(
children: [
Container(
width: double.infinity,
padding: EdgeInsets.only(top: 20, left: 20),
alignment: Alignment.topLeft,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
height: 32,
width: 32,
decoration: BoxDecoration(
color: AppColors.avatarRed,
borderRadius:
BorderRadius.all(const Radius.circular(4.0)),
),
child: Center(
child: Text(
Helper.getInitials(careerOpening.title),
style: TextStyle(color: AppColors.avatarText),
),
),
),
Container(
// alignment: Alignment.topLeft,
padding: EdgeInsets.only(left: 10),
width: 220,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
careerOpening.title,
maxLines: 2,
style: TextStyle(
color: AppColors.greys87,
fontSize: 12.0,
),
),
Padding(
padding: EdgeInsets.only(top: 5),
child: Text(
(dateNow.from(
DateTime.fromMillisecondsSinceEpoch(
careerOpening.timeStamp)))
.toString(),
style: TextStyle(
color: AppColors.greys60,
fontSize: 12.0,
),
),
)
])),
],
)),
Container(
alignment: Alignment.topLeft,
padding: EdgeInsets.all(20),
child: Text(
careerOpening.description,
maxLines: 3,
style: GoogleFonts.lato(
color: AppColors.greys87,
fontWeight: FontWeight.w700,
fontSize: 14,
height: 1.5,
),
),
),
],
),
),
));
}
} |
// src/app/shared/free-dragging.directive.ts
import { DOCUMENT } from "@angular/common";
import { Directive, ElementRef, Inject, OnDestroy, OnInit } from "@angular/core";
import { fromEvent, Subscription, takeUntil } from "rxjs";
@Directive({
selector: "[appFreeDragging]",
})
export class FreeDraggingDirective implements OnInit, OnDestroy {
private element!: HTMLElement;
private subscriptions: Subscription[] = [];
private wasDropped: boolean;
constructor(
private elementRef: ElementRef,
@Inject(DOCUMENT) private document: any
) {this.wasDropped = false;}
ngOnInit(): void {
this.element = this.elementRef.nativeElement as HTMLElement;
this.initDrag();
}
initDrag(): void {
if (!this.wasDropped) {
console.log("yellow1");
// 1
const dragStart$ = fromEvent<MouseEvent>(this.element, "mousedown");
const dragEnd$ = fromEvent<MouseEvent>(this.document, "mouseup");
const drag$ = fromEvent<MouseEvent>(this.document, "mousemove").pipe(
takeUntil(dragEnd$)
);
// 2
let initialX: number,
initialY: number,
currentX = 0,
currentY = 0;
let dragSub!: Subscription;
// 3
const dragStartSub = dragStart$.subscribe((event: MouseEvent) => {
initialX = event.clientX - currentX;
initialY = event.clientY - currentY;
this.element.classList.add('free-dragging');
// 4
dragSub = drag$.subscribe((event: MouseEvent) => {
event.preventDefault();
currentX = event.clientX - initialX;
currentY = event.clientY - initialY;
this.element.style.transform =
"translate3d(" + currentX + "px, " + currentY + "px, 0)";
});
});
// 5
const dragEndSub = dragEnd$.subscribe(() => {
initialX = currentX;
initialY = currentY;
this.element.classList.remove('free-dragging');
const elems = document.elementsFromPoint(currentX, currentY);
console.log(elems[elems.length - 1]);
console.log(elems);
console.log(document.elementFromPoint(currentX, currentY))
if (elems[elems.length - 1].getAttribute("class") == "square-multiplier") {
console.log("yellow");
elems[elems.length - 1].appendChild(this.element);
this.wasDropped = true;
}
if (dragSub) {
dragSub.unsubscribe();
}
});
// 6
this.subscriptions.push.apply(this.subscriptions, [
dragStartSub,
dragSub,
dragEndSub,
]);
}
}
ngOnDestroy(): void {
this.subscriptions.forEach((s) => s?.unsubscribe());
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace Oxide.Plugins
{
[Info("Scientist Names", "Ultra", "1.1.3")]
[Description("Gives real names to scientists, bandits, murderers and scarecrows (instead of numbers)")]
class ScientistNames : RustPlugin
{
#region Fields
Random rnd;
bool initialized = false;
int renameCount = 0;
List<string> surnameList = new List<string>();
List<string> currentActiveNames = new List<string>();
private string additionPermission = "scientistnames.addition";
#endregion
#region Oxide Hooks
void Init()
{
Unsubscribe(nameof(OnEntitySpawned));
}
void OnServerInitialized()
{
permission.RegisterPermission(additionPermission, this);
rnd = new Random();
renameCount = 0;
foreach (BaseNetworkable baseNetworkable in BaseNetworkable.serverEntities.Where(w => w is BasePlayer && (w is NPCPlayer || w is HTNPlayer || w is NPCMurderer)).Cast<BasePlayer>())
{
if (!baseNetworkable.ShortPrefabName.Contains("scientist") && !baseNetworkable.ShortPrefabName.Contains("bandit") && !baseNetworkable.ShortPrefabName.Contains("murderer") && !baseNetworkable.ShortPrefabName.Contains("scarecrow")) continue;
BasePlayer basePlayer = (BasePlayer)baseNetworkable;
string oldName = basePlayer.displayName;
RenameBasePlayer(basePlayer, GetAbbrevation(basePlayer));
if (oldName != basePlayer.displayName)
{
Log($"{oldName} renamed to {basePlayer.displayName}", console: true);
renameCount++;
}
}
Log($"{renameCount} scientists (bandits, murderers, scarecrows) renamed", console: true);
if (currentActiveNames.Count - renameCount > 0) Log($"{currentActiveNames.Count - renameCount} already named scientists (bandits, murderers, scarecrows) found", console: true);
Subscribe(nameof(OnEntitySpawned));
initialized = true;
}
void OnEntitySpawned(BaseEntity entity)
{
if (entity is BasePlayer && (entity is NPCPlayer || entity is HTNPlayer || entity is NPCMurderer))
{
BasePlayer basePlayer = (BasePlayer)entity;
string oldName = basePlayer.displayName;
RenameBasePlayer(basePlayer, GetAbbrevation(basePlayer));
if (oldName != basePlayer.displayName)
{
Log($"{oldName} renamed to {basePlayer.displayName}", console: true);
}
}
}
#endregion
#region Death Hook
void OnDeathNotice(Dictionary<string, object> data, string message)
{
if (!initialized) return;
object victim = data["VictimEntity"];
if (victim == null) return;
BasePlayer basePlayer = victim as BasePlayer;
if (basePlayer != null && currentActiveNames.Contains(basePlayer.displayName))
{
currentActiveNames.Remove(basePlayer.displayName);
}
}
#endregion
#region Commands
[ConsoleCommand("addname")]
void ConsoleCommand(ConsoleSystem.Arg arg)
{
BasePlayer player = arg.Connection.player as BasePlayer;
if (initialized && permission.UserHasPermission(player.UserIDString, additionPermission))
{
if (arg.Args.Length > 0)
{
string nameString = string.Join(" ", arg.Args, 0, arg.Args.Length);
foreach (string name in nameString.Split(','))
{
AddName(name);
}
SaveConfig();
}
}
}
[ChatCommand("addname")]
void WeedDealerCommand(BasePlayer player, string command, string[] args)
{
if (initialized && permission.UserHasPermission(player.UserIDString, additionPermission))
{
if (args.Length > 0)
{
string nameString = string.Join(" ", args, 0, args.Length);
foreach (string name in nameString.Split(','))
{
AddName(name);
}
SaveConfig();
}
}
else
{
SendReply(player, "You don't have the permissions to use this command");
}
}
void AddName(string name)
{
if (name == null) return;
if (!surnameList.Contains(name, StringComparer.OrdinalIgnoreCase))
{
surnameList.Add(name.Trim());
}
}
#endregion
#region Core
void RenameBasePlayer(BasePlayer basePlayer, string abbrevation)
{
for (int attempt = 0; attempt < 5; attempt++)
{
string newName = RenameBasePlayer(abbrevation);
if (!string.IsNullOrEmpty(newName))
{
basePlayer.displayName = newName;
return;
}
}
Log("Name generator failed. No unique name found", console: true, logType: LogType.ERROR);
if (!string.IsNullOrEmpty(basePlayer.displayName)) currentActiveNames.Add(basePlayer.displayName);
}
string RenameBasePlayer(string abbrevation)
{
if (surnameList.Count > 0)
{
string newName = (string.Format("{0} {1} {2}", abbrevation, GetFirstnameFirstLetter().ToUpper(), surnameList[rnd.Next(0, surnameList.Count)].Trim())).Trim().Replace(" ", " ");
if (!currentActiveNames.Contains(newName))
{
return newName;
}
}
return null;
}
string GetAbbrevation(BasePlayer basePlayer)
{
if (!configData.UseTitle) return string.Empty;
else if (basePlayer.ShortPrefabName.Contains("bandit")) return configData.BanditTitle;
else if (basePlayer.ShortPrefabName.Contains("scientist")) return configData.ScientistTitle;
else if (basePlayer.ShortPrefabName.Contains("murderer")) return configData.MurdererTitle;
else if (basePlayer.ShortPrefabName.Contains("scarecrow")) return configData.ScarecrowTitle;
else
{
Log($"Unknown ShortPrefabName: {basePlayer.ShortPrefabName}", console: true, logType: LogType.WARNING);
return string.Empty;
}
}
string GetFirstnameFirstLetter()
{
if (!configData.UseFirstNameFirstLetter) return string.Empty;
int num = rnd.Next(0, 26); // Zero to 25
char letter = (char)('a' + num);
return letter.ToString() + ".";
}
#endregion
#region Config
private ConfigData configData;
private class ConfigData
{
[JsonProperty(PropertyName = "UseTitle")]
public bool UseTitle;
[JsonProperty(PropertyName = "UseFirstNameFirstLetter")]
public bool UseFirstNameFirstLetter;
[JsonProperty(PropertyName = "ScientistTitle")]
public string ScientistTitle;
[JsonProperty(PropertyName = "BanditTitle")]
public string BanditTitle;
[JsonProperty(PropertyName = "MurdererTitle")]
public string MurdererTitle = "murderer";
[JsonProperty(PropertyName = "ScarecrowTitle")]
public string ScarecrowTitle = "scare";
[JsonProperty(PropertyName = "SurnameList")]
public string SurnameList;
[JsonProperty(PropertyName = "LogInFile")]
public bool LogInFile;
[JsonProperty(PropertyName = "LogInConsole")]
public bool LogInConsole;
}
protected override void LoadConfig()
{
try
{
base.LoadConfig();
configData = Config.ReadObject<ConfigData>();
if (configData == null)
{
LoadDefaultConfig();
}
}
catch
{
LoadDefaultConfig();
}
surnameList = configData.SurnameList.Split(',').Distinct().ToList();
SaveConfig();
}
protected override void LoadDefaultConfig()
{
configData = new ConfigData()
{
LogInConsole = false,
LogInFile = false,
UseTitle = true,
UseFirstNameFirstLetter = true,
ScientistTitle = "scientist",
BanditTitle = "bandit",
MurdererTitle = "murderer",
ScarecrowTitle = "scare",
SurnameList = "Smith, Johnson, Williams, Jones, Brown, Davis, Miller, Wilson, Moore, Taylor, Anderson, Thomas, Jackson, White, Harris, Martin, Thompson, Garcia, Martinez, Robinson, Clark, Rodriguez, Lewis, Lee, Walker, Hall, Allen, Young, Hernandez, King, Wright, Lopez, Hill, Scott, Green, Adams, Baker, Gonzalez, Nelson, Carter, Mitchell, Perez, Roberts, Turner, Phillips, Campbell, Parker, Evans, Edwards, Collins, Stewart, Sanchez, Morris, Rogers, Reed, Cook, Morgan, Bell, Murphy, Bailey, Rivera, Cooper, Richardson, Cox, Howard, Ward, Torres, Peterson, Gray, Ramirez, James, Watson, Brooks, Kelly, Sanders, Price, Bennett, Wood, Barnes, Ross, Henderson, Coleman, Jenkins, Perry, Powell, Long, Patterson, Hughes, Flores, Washington, Butler, Simmons, Foster, Gonzales, Bryant, Alexander, Russell, Griffin, Diaz, Hayes, Myers, Ford, Hamilton, Graham, Sullivan, Wallace, Woods, Cole, West, Jordan, Owens, Reynolds, Fisher, Ellis, Harrison, Gibson, McDonald, Cruz, Marshall, Ortiz, Gomez, Murray, Freeman, Wells, Webb, Simpson, Stevens, Tucker, Porter, Hunter, Hicks, Crawford, Henry, Boyd, Mason, Morales, Kennedy, Warren, Dixon, Ramos, Reyes, Burns, Gordon, Shaw, Holmes, Rice, Robertson, Hunt, Black, Daniels, Palmer, Mills, Nichols, Grant, Knight, Ferguson, Rose, Stone, Hawkins, Dunn, Perkins, Hudson, Spencer, Gardner, Stephens, Payne, Pierce, Berry, Matthews, Arnold, Wagner, Willis, Ray, Watkins, Olson, Carroll, Duncan, Snyder, Hart, Cunningham, Bradley, Lane, Andrews, Ruiz, Harper, Fox, Riley, Armstrong, Carpenter, Weaver, Greene, Lawrence, Elliott, Chavez, Sims, Austin, Peters, Kelley, Franklin, Lawson, Fields, Gutierrez, Ryan, Schmidt, Carr, Vasquez, Castillo, Wheeler, Chapman, Oliver, Montgomery, Richards, Williamson, Johnston, Banks, Meyer, Bishop, McCoy, Howell, Alvarez, Morrison, Hansen, Fernandez, Garza, Harvey, Little, Burton, Stanley, Nguyen, George, Jacobs, Reid, Kim, Fuller, Lynch, Dean, Gilbert, Garrett, Romero, Welch, Larson, Frazier, Burke, Hanson, Day, Mendoza, Moreno, Bowman, Medina, Fowler, Brewer, Hoffman, Carlson, Silva, Pearson, Holland, Douglas, Fleming, Jensen, Vargas, Byrd, Davidson, Hopkins, May, Terry, Herrera, Wade, Soto, Walters, Curtis, Neal, Caldwell, Lowe, Jennings, Barnett, Graves, Jimenez, Horton, Shelton, Barrett, Obrien, Castro, Sutton, Gregory, Mckinney, Lucas, Miles, Craig, Rodriquez, Chambers, Holt, Lambert, Fletcher, Watts, Bates, Hale, Rhodes, Pena, Beck, Newman, Haynes, McDaniel, Mendez, Bush, Vaughn, Parks, Dawson, Santiago, Norris, Hardy, Love, Steele, Curry, Powers, Schultz, Barker, Guzman, Page, Munoz, Ball, Keller, Chandler, Weber, Leonard, Walsh, Lyons, Ramsey, Wolfe, Schneider, Mullins, Benson, Sharp, Bowen, Daniel, Barber, Cummings, Hines, Baldwin, Griffith, Valdez, Hubbard, Salazar, Reeves, Warner, Stevenson, Burgess, Santos, Tate, Cross, Garner, Mann, Mack, Moss, Thornton, Dennis, McGee, Farmer, Delgado, Aguilar, Vega, Glover, Manning, Cohen, Harmon, Rodgers, Robbins, Newton, Todd, Blair, Higgins, Ingram, Reese, Cannon, Strickland, Townsend, Potter, Goodwin, Walton, Rowe, Hampton, Ortega, Patton, Swanson, Joseph, Francis, Goodman, Maldonado, Yates, Becker, Erickson, Hodges, Rios, Conner, Adkins, Webster, Norman, Malone, Hammond, Flowers, Cobb, Moody, Quinn, Blake, Maxwell, Pope, Floyd, Osborne, Paul, McCarthy, Guerrero, Lindsey, Estrada, Sandoval, Gibbs, Tyler, Gross, Fitzgerald, Stokes, Doyle, Sherman, Saunders, Wise, Colon, Gill, Alvarado, Greer, Padilla, Simon, Waters, Nunez, Ballard, Schwartz, McBride, Houston, Christensen, Klein, Pratt, Briggs, Parsons, McLaughlin, Zimmerman, French, Buchanan, Moran, Copeland, Roy, Pittman, Brady, McCormick, Holloway, Brock, Poole, Frank, Logan, Owen, Bass, Marsh, Drake, Wong, Jefferson, Park, Morton, Abbott, Sparks, Patrick, Norton, Huff, Clayton, Massey, Lloyd, Figueroa, Carson, Bowers, Roberson, Barton, Tran, Lamb, Harrington, Casey, Boone, Cortez, Clarke, Mathis, Singleton, Wilkins, Cain, Bryan, Underwood, Hogan, Mckenzie, Collier, Luna, Phelps, McGuire, Allison, Bridges, Wilkerson, Nash, Summers, Atkins"
};
}
protected override void SaveConfig()
{
configData.SurnameList = string.Join(",", surnameList.OrderBy(o => o).Where(w => w.Length > 0).Distinct().Select(s => s.Trim()));
Config.WriteObject(configData, true);
base.SaveConfig();
}
#endregion
#region Log
void Log(string message, bool console = false, LogType logType = LogType.INFO, string fileName = "")
{
if (string.IsNullOrEmpty(fileName)) fileName = this.Title;
if (configData.LogInFile)
{
LogToFile(fileName, $"[{DateTime.Now.ToString("hh:mm:ss")}] {logType} > {message}", this);
}
if (configData.LogInConsole)
{
Puts($"{message.Replace("\n", " ")}");
}
}
enum LogType
{
INFO = 0,
WARNING = 1,
ERROR = 2
}
#endregion
}
} |
---
sidebar_position: 2
title: SCOW管理员使用技巧
---
## 1. 系统报错:查看运行日志
:::tip
门户系统报错时,请查看portal-server(优先)和portal-web日志;管理系统报错时,请查看mis-server(优先)和mis-web日志。
:::
### 1.1 查看日志
各组件的实时日志是输出在`stdout`,可以通过`./cli compose logs -f `查看实时的日志输出:
```Bash
# 查看所有组件的日志
./cli compose logs -f
# 查看认证系统的日志
./cli compose logs -f auth
# 查看门户系统服务器端的日志
./cli compose logs -f portal-server
# 查看管理系统服务器端的日志
./cli compose logs -f mis-server
```
若开启了日志收集工具fluentd(默认开启),可以查看各组件的历史日志,历史日志的默认路径在`/var/log/fluentd/`,各组件的日志按组件名称分文件夹存储,每个组件的日志按照大小和日期分文件存储。
各组件日志:

mis-web日志:

### 1.2 设置日志级别
SCOW日志输出支持日志等级设置,可选等级包括`trace`, `debug`, `info`, `warn`, `error`,默认等级为`info`,通过修改`install.yamll`日志配置部分来实现:
```YAML
log:
# 可选trace, debug, info, warn, error, 默认info
level: "info"
```
## 2. 作业/交互式应用执行失败:查看输出文档
### 2.1 作业执行失败
作业执行完成时,在该作业的工作目录会生成两个标准输出文件:`job.{job_id}.out`和`job.{job_id}.err`。
当作业执行失败(状态为`FAILED`)时,可以通过查看`job.{job_id}.err` 文件内容分析错误的原因:所有作业列表->该作业行->进入目录:



### 2.2 交互式应用执行失败
交互式应用分为web和vnc两类。
查看交互式应用执行的节点:
- web类应用:工作目录下的`server_session_info.json`文件中的`HOST`
- vnc类应用:工作目录下的`VNC_SESSION_INFO`文件
查看交互式应用输出日志及报错:
- web类应用:工作目录下的`slurm-{job_id}.out`文件
- vnc类应用:工作目录下的`output`和`vnc.log`文件
*截图略。*
## 3. 用户操作审计:查看操作日志
SCOW支持可插拔的审计日志功能,配置审计日志的步骤如下:
- (1) 在install.yaml中添加
- ```YAML
# 可添加审计日志功能,并配置审计日志数据库密码
audit:
dbPassword: "must!chang3this"
```
- (2) 添加审计日志配置文件,在`./config`目录下添加`audit.yaml`
- ```YAML
# 审计系统数据库的信息。可以不修改
db:
host: audit-db
port: 3306
user: root
dbName: scow_audit
```
SCOW支持用户、账户、租户、平台级别操作日志查看:


## 4. 解决特定环境问题:模仿用户登录
为解决只在某个用户下出现的错误,管理员可以通过模仿该用户,以该用户的身份登录到SCOW重现问题。
- 内置认证系统:
在`config/auth.yml`文件添加如下内容:
```YAML
# 当登录用户的ID为fromUser1,实际上以toUser1登录
mockUsers:
fromUserId1: toUserId1
```
- IAAA认证系统:
在`config`目录下创建`pkuauth.yaml`文件,内容如下:
```YAML
mockUsers:
fromUserId1: toUserId1
```
修改改配置文件后无需重启认证系统,只需要退出再重新登录一下即可。
## 5. 其他
### 5.1 用户从账户中移除失败
在SCOW中可能会出现某个用户从账户中移除失败(slurm集群中该用户已与该账户取消关联)。该情况需要在SCOW数据库中处理:
```PowerShell
# 进入SCOW数据库
./cli db
use scow
# 通过用户名查找该用户的ID,注意user表中的user_id是指用户名,用户ID是表的id列
select * from user where user_id="{user}";
# 通过账户名查找该账户的ID
select * from account where account_name="{account}";
# 基于查找到的用户ID和账户ID,在用户账户关系表中。
# 注意user_account表中的user_id对应user表中的id,account_id对应account表中的id
select * from user_account where user_id={user.id} and account_id={account.id};
#确认无误之后删除该记录
delete from user_account where user_id={user.id} and account_id={account.id};
```
### 5.2 **将用户添加到某个账户失败**
在SCOW中可能会出现将一个用户添加到某个账户中失败的情况(slurm集群中已存在该用户与该账户的关联)。该情况需要在SCOW数据库中处理:
```PowerShell
# 进入SCOW数据库、查找用户ID和账户ID请参考5.1小节
./cli db
use scow
# 将用户与账户关系记录插入
insert into user_account(user_id,account_id,status,role,used_job_charge,job_charge_limit) values({user.id} , {account.id}, "UNBLOCKED", "USER", NULL, NULL);
``` |
import { getMonthName } from "../../$shared/utils";
import c from './MonthPicker.module.css';
import Text from "../Text/Text";
import { addMonths } from "date-fns";
interface Props {
month: number;
year: number;
onChange: (year: number, month: number) => void;
}
function MonthPicker(props: Props) {
const { month, year, onChange } = props;
const date = new Date(year, month - 1, 1)
const changeDate = (step: number) => {
const nextDate = addMonths(date, step)
onChange(nextDate.getFullYear(), nextDate.getMonth() + 1)
}
return (
<div className={c.MonthPicker} >
<Text size="md" bold color="primary">
{`${getMonthName(month)} ${year}`}
</Text>
<div className={c.caretContainer}>
<div className={c.caret} onClick={() => changeDate(-1)}> {"<"} </div>
<div className={c.caret} onClick={() => changeDate(1)}> {">"} </div>
</div>
</div>
);
}
export default MonthPicker; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.